/**
 * Fullscreen popup system for Aladin
 * Handles popups that need to be visible in fullscreen mode
 */

window.aladinFullscreenPopups = {
    resolveElement: function(elementId, scopeRootId) {
        if (!elementId) {
            return null;
        }

        if (scopeRootId) {
            const scopeRoot = document.getElementById(scopeRootId);
            if (scopeRoot) {
                const scopedMatch = scopeRoot.querySelector(`#${elementId}`);
                if (scopedMatch) {
                    return scopedMatch;
                }
            }
        }

        return document.getElementById(elementId);
    },

    resolveTargetContainer: function(options = {}) {
        if (this.isInFullscreen()) {
            return document.getElementById('aladin-fullscreen-popup-container')
                || document.fullscreenElement
                || document.querySelector('.am-aladin-pseudo-fullscreen')
                || document.body;
        }

        if (options.containerId) {
            return this.resolveElement(options.containerId, options.scopeRootId);
        }

        return null;
    },
    
    /**
     * Initialize the fullscreen popup system
     * @param {string} aladinDivId - ID of the Aladin div
     */
    init: function(aladinDivId) {
        this.aladinDivId = aladinDivId;
        this.setupEventListeners();
    },

    /**
     * Setup event listeners for fullscreen changes
     */
    setupEventListeners: function() {
        const self = this;
        
        // Listen for fullscreen changes
        document.addEventListener('fullscreenchange', () => self.onFullscreenChange());
        document.addEventListener('webkitfullscreenchange', () => self.onFullscreenChange());
        document.addEventListener('mozfullscreenchange', () => self.onFullscreenChange());
        document.addEventListener('MSFullscreenChange', () => self.onFullscreenChange());
    },

    /**
     * Handle fullscreen state changes
     */
    onFullscreenChange: function() {
        if (this.isInFullscreen()) {
            this.createFullscreenPopupContainer();
        } else {
            this.removeFullscreenContainer();
        }
    },

    /**
     * Check if currently in fullscreen mode
     * @returns {boolean}
     */
    isInFullscreen: function() {
        return !!(document.fullscreenElement || 
                 document.webkitFullscreenElement || 
                 document.mozFullScreenElement || 
                 document.msFullscreenElement ||
                 document.querySelector('.am-aladin-pseudo-fullscreen'));
    },

    /**
     * Get the appropriate container for popups
     * @returns {HTMLElement}
     */
    getPopupContainer: function() {
        if (this.isInFullscreen()) {
            return document.getElementById('aladin-fullscreen-popup-container') || 
                   document.fullscreenElement || 
                   document.querySelector('.am-aladin-pseudo-fullscreen') ||
                   document.body;
        }
        return document.body;
    },

    /**
     * Remember where a Blazor popup belongs so it can be restored after fullscreen.
     * @param {HTMLElement} popup
     */
    rememberPopupOrigin: function(popup) {
        if (!popup || !popup.parentElement) {
            return;
        }

        if (popup.dataset.aladinOriginalParentId) {
            return;
        }

        if (popup.parentElement.id) {
            popup.dataset.aladinOriginalParentId = popup.parentElement.id;
        }
    },

    /**
     * Restore a popup to its original Blazor host when possible.
     * @param {HTMLElement} popup
     */
    restorePopupToOriginalParent: function(popup) {
        if (!popup) {
            return;
        }

        const originalParentId = popup.dataset.aladinOriginalParentId;
        const originalParent = originalParentId ? document.getElementById(originalParentId) : null;

        if (originalParent) {
            originalParent.appendChild(popup);
            return;
        }

        document.body.appendChild(popup);
    },

    /**
     * Create the fullscreen popup container
     */
    createFullscreenPopupContainer: function() {
        const aladinDiv = document.getElementById(this.aladinDivId);
        if (!aladinDiv) return;

        // Remove existing container if any
        this.removeFullscreenContainer();

        // Create popup container
        const popupContainer = document.createElement('div');
        popupContainer.id = 'aladin-fullscreen-popup-container';
        popupContainer.style.cssText = `
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        `;

        aladinDiv.appendChild(popupContainer);
            },

    /**
     * Remove fullscreen popup container when exiting fullscreen
     */
    removeFullscreenContainer: function() {
        const container = document.getElementById('aladin-fullscreen-popup-container');
        if (container) {
            // Before removing container, restore any popups to their original Blazor host
            const popups = container.querySelectorAll('[id$="-popup-container"], [id*="popup"]');
            popups.forEach(popup => {
                this.restorePopupToOriginalParent(popup);
                // Reset positioning for normal mode
                popup.style.position = '';
                popup.style.bottom = '';
                popup.style.left = '';
                popup.style.zIndex = '';
            });
            
            container.remove();
                    }
    },

    /**
     * Show a popup in the appropriate container
     * @param {string} htmlContent - HTML content for the popup
     * @param {Object} options - Popup options
     */
    showPopup: function(htmlContent, options = {}) {
        const container = this.getPopupContainer();
                
        if (this.isInFullscreen()) {
            // Show in fullscreen container
            const fsContainer = document.getElementById('aladin-fullscreen-popup-container');
                        if (fsContainer) {
                fsContainer.innerHTML = htmlContent;
                fsContainer.style.pointerEvents = 'auto';
                            } else {
                console.error('Fullscreen popup container not found!');
            }
        } else {
            // For non-fullscreen, you can still use this system or fall back to Blazor components
            // This creates a temporary overlay for consistency
                        this.createTemporaryOverlay(htmlContent);
        }
    },

    /**
     * Hide the current popup
     */
    hidePopup: function() {
        if (this.isInFullscreen()) {
            const container = document.getElementById('aladin-fullscreen-popup-container');
            if (container) {
                container.innerHTML = '';
                container.style.pointerEvents = 'none';
            }
        } else {
            // Remove temporary overlay
            const overlay = document.getElementById('aladin-temp-popup-overlay');
            if (overlay) {
                overlay.remove();
            }
        }
    },

    /**
     * Create temporary overlay for non-fullscreen mode (optional)
     * @param {string} htmlContent 
     */
    createTemporaryOverlay: function(htmlContent) {
        // Remove existing overlay
        const existing = document.getElementById('aladin-temp-popup-overlay');
        if (existing) existing.remove();

        const overlay = document.createElement('div');
        overlay.id = 'aladin-temp-popup-overlay';
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 10000;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        `;
        overlay.innerHTML = htmlContent;
        document.body.appendChild(overlay);
    },

    /**
     * Create a standard popup HTML structure
     * @param {string} title - Popup title
     * @param {string} content - Popup content
     * @param {Array} buttons - Array of button objects {text, onclick, style}
     * @returns {string} HTML string
     */
    createPopupHtml: function(title, content, buttons = []) {
        const buttonHtml = buttons.map(btn => 
            `<button onclick="${btn.onclick}" style="${btn.style || this.getDefaultButtonStyle(btn.type)}">${btn.text}</button>`
        ).join('');

        return `
            <div style="${this.getPopupContainerStyle()}">
                <div style="${this.getPopupStyle()}">
                    <h3 style="${this.getPopupTitleStyle()}">${title}</h3>
                    <div style="${this.getPopupContentStyle()}">
                        ${content}
                    </div>
                    <div style="${this.getPopupButtonsStyle()}">
                        ${buttonHtml}
                    </div>
                </div>
            </div>
        `;
    },

    /**
     * Get default popup container style
     */
    getPopupContainerStyle: function() {
        return `
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(0, 0, 0, 0.7);
            backdrop-filter: blur(2px);
        `;
    },

    /**
     * Get default popup style
     */
    getPopupStyle: function() {
        return `
            background: #1a1a1a;
            color: white;
            padding: 24px;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
            border: 1px solid #333;
            min-width: 300px;
            max-width: 500px;
            max-height: 80vh;
            overflow-y: auto;
        `;
    },

    /**
     * Get popup title style
     */
    getPopupTitleStyle: function() {
        return `
            margin: 0 0 16px 0;
            font-size: 18px;
            font-weight: 600;
            color: #fff;
        `;
    },

    /**
     * Get popup content style
     */
    getPopupContentStyle: function() {
        return `
            margin-bottom: 20px;
            line-height: 1.5;
        `;
    },

    /**
     * Get popup buttons container style
     */
    getPopupButtonsStyle: function() {
        return `
            display: flex;
            gap: 12px;
            justify-content: flex-end;
        `;
    },

    /**
     * Get default button style
     * @param {string} type - Button type: 'primary', 'secondary', 'danger'
     */
    getDefaultButtonStyle: function(type = 'secondary') {
        const baseStyle = `
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s ease;
        `;

        const typeStyles = {
            primary: 'background: #007bff; color: white;',
            secondary: 'background: #6c757d; color: white;',
            danger: 'background: #dc3545; color: white;'
        };

        return baseStyle + (typeStyles[type] || typeStyles.secondary);
    },

    /**
     * Move a Blazor popup to the appropriate container based on fullscreen state
     * @param {string} popupId - ID of the popup element
     * @param {Object} options - Options for positioning and focus
     */
    moveBlazorPopupToContainer: function(popupId, options = {}) {
        const attemptMove = (attempts = 0) => {
            const popup = this.resolveElement(popupId, options.scopeRootId);
            if (!popup && attempts < 10) {
                                setTimeout(() => attemptMove(attempts + 1), 100);
                return;
            }
            
            if (!popup) {
                console.warn(`Popup with ID ${popupId} not found after 10 attempts`);
                return;
            }

            const targetContainer = this.resolveTargetContainer(options);

            if (targetContainer) {
                if (popup.parentElement !== targetContainer) {
                    this.rememberPopupOrigin(popup);
                    targetContainer.appendChild(popup);
                }

                if (this.isInFullscreen()) {
                    // Apply fullscreen positioning
                    popup.style.position = 'absolute';
                    popup.style.bottom = options.bottom || '80px';
                    popup.style.left = options.left || '20px';
                    popup.style.zIndex = options.zIndex || '1000';
                } else {
                    popup.style.position = '';
                    popup.style.top = '';
                    popup.style.right = '';
                    popup.style.bottom = '';
                    popup.style.left = '';
                    popup.style.zIndex = '';
                }

                if (this.isInFullscreen() && targetContainer.id === 'aladin-fullscreen-popup-container') {
                    // Add click protection to fullscreen container
                    const protectInputFocus = (e) => {
                        const inputs = popup.querySelectorAll('input, textarea, select');
                        const clickedInput = Array.from(inputs).find(input => 
                            input === e.target || input.contains(e.target) || e.target.contains(input)
                        );
                        
                        if (clickedInput) {
                                                        e.stopPropagation();
                            e.stopImmediatePropagation();
                            setTimeout(() => {
                                clickedInput.focus();
                                if (clickedInput.select) clickedInput.select();
                            }, 10);
                        }
                    };
                    
                    // Add protection with capture phase
                    targetContainer.addEventListener('click', protectInputFocus, true);
                    
                    // Remove protection when popup is removed
                    const observer = new MutationObserver((mutations) => {
                        mutations.forEach((mutation) => {
                            if (mutation.type === 'childList') {
                                const removed = Array.from(mutation.removedNodes);
                                if (removed.includes(popup)) {
                                    targetContainer.removeEventListener('click', protectInputFocus, true);
                                    observer.disconnect();
                                }
                            }
                        });
                    });
                    observer.observe(targetContainer, { childList: true });
                }
                    
                // Wait for DOM to settle before focusing
                setTimeout(() => {
                    this.focusPopupInput(popup, options.focusSelector);
                }, 200);
            } else {
                if (popup.parentElement && popup.parentElement.id === 'aladin-fullscreen-popup-container') {
                    this.restorePopupToOriginalParent(popup);
                } else if (popup.parentElement === document.body && popup.dataset.aladinOriginalParentId) {
                    this.restorePopupToOriginalParent(popup);
                }

                // Handle focus for normal mode with delay
                setTimeout(() => {
                    this.focusPopupInput(popup, options.focusSelector);
                }, 200);
            }
        };
        
        // Start the attempt process
        setTimeout(() => attemptMove(), options.delay || 100);
    },

    /**
     * Move a Blazor popup back to its original container
     * @param {string} popupId - ID of the popup element
     */
    moveBlazorPopupBack: function(popupId, options = {}) {
        const popup = this.resolveElement(popupId, options.scopeRootId);
        if (popup && popup.dataset.aladinOriginalParentId && popup.parentElement && popup.parentElement.id !== popup.dataset.aladinOriginalParentId) {
            this.restorePopupToOriginalParent(popup);
        }
    },

    /**
     * Focus input in popup with optional selector
     * @param {HTMLElement} popup - Popup element
     * @param {string} focusSelector - CSS selector for input to focus
     */
    focusPopupInput: function(popup, focusSelector) {
        if (!popup) return;
        
        const selector = focusSelector || 'input[type="number"], input[type="text"], textarea, select, .e-input-group input, .e-numerictextbox input';
        
        // Debug: log all inputs found in popup
        const allInputs = popup.querySelectorAll('input, textarea, select');
                allInputs.forEach((inp, i) => {
                    });
        
        // Try multiple times to ensure focus works after DOM manipulation
        const attemptFocus = (attempts = 0) => {
            const input = popup.querySelector(selector);
            
            if (input && attempts < 5) {
                try {
                    // For Syncfusion components, also try to find the actual input element
                    const actualInput = input.tagName === 'INPUT' ? input : input.querySelector('input');
                    const targetInput = actualInput || input;
                    
                                        
                    targetInput.focus();
                    if (targetInput.select && typeof targetInput.select === 'function') {
                        targetInput.select();
                    }
                    
                    
                    // Add comprehensive click and focus handlers
                    const clickHandler = (e) => {
                        // Don't interfere with close buttons or other buttons
                        if (e.target.closest('button') || e.target.closest('.e-btn')) {
                                                        return;
                        }
                        
                                                e.stopPropagation();
                        e.stopImmediatePropagation();
                        e.preventDefault();
                        
                        // Focus with a slight delay to override any competing handlers
                        setTimeout(() => {
                            targetInput.focus();
                            if (targetInput.select) targetInput.select();
                                                    }, 10);
                    };
                    
                    
                    const focusHandler = (e) => {
                                                e.stopPropagation();
                    };
                    
                    // Remove existing listeners to avoid duplicates
                    targetInput.removeEventListener('click', clickHandler);
                    targetInput.removeEventListener('focus', focusHandler);
                    
                    // Add event listeners with capture to run before other handlers
                    targetInput.addEventListener('click', clickHandler, true);
                    targetInput.addEventListener('focus', focusHandler, true);
                    

                    // Check if focus was successful
                    setTimeout(() => {
                        if (document.activeElement !== targetInput) {
                                                        attemptFocus(attempts + 1);
                        } else {
                                                    }
                    }, 50);
                } catch (e) {
                    console.warn('Focus attempt failed:', e);
                    setTimeout(() => attemptFocus(attempts + 1), 100);
                }
            } else if (!input) {
                console.warn('Input element not found with selector:', selector);
                            }
        };
        
        // Start focus attempts after a short delay
        setTimeout(() => attemptFocus(), 15);
    }
};

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    // Auto-initialize if aladin div exists
    const aladinDiv = document.querySelector('[id*="aladin"]');
    if (aladinDiv) {
        window.aladinFullscreenPopups.init(aladinDiv.id);
    }
});

// Export for manual initialization
window.initAladinFullscreenPopups = function(aladinDivId) {
    window.aladinFullscreenPopups.init(aladinDivId);
};

// Convenience functions
window.showAladinPopup = function(htmlContent, options) {
    window.aladinFullscreenPopups.showPopup(htmlContent, options);
};

window.hideAladinPopup = function() {
    window.aladinFullscreenPopups.hidePopup();
};

window.createAladinPopup = function(title, content, buttons) {
    return window.aladinFullscreenPopups.createPopupHtml(title, content, buttons);
};

window.isAladinInFullscreen = function() {
    return window.aladinFullscreenPopups.isInFullscreen();
};

// Convenience functions for Blazor popup management
window.moveBlazorPopupToContainer = function(popupId, options) {
    window.aladinFullscreenPopups.moveBlazorPopupToContainer(popupId, options);
};

window.moveBlazorPopupBack = function(popupId, options) {
    window.aladinFullscreenPopups.moveBlazorPopupBack(popupId, options);
};
