/**
 * Simple info button handler for Text to Speech
 * This replaces the complex multi-handler approach with a single, clean implementation
 */
(function() {
    'use strict';
    
    // Global state to track popup
    var activePopup = null;
    var outsideClickHandler = null;
    
    function closePopup() {
        if (activePopup) {
            activePopup.style.display = 'none';
            activePopup = null;
        }
        
        if (outsideClickHandler) {
            document.removeEventListener('click', outsideClickHandler);
            outsideClickHandler = null;
        }
        
        // Only log in debug mode
        if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
            console.log('[TTS Info] Popup closed');
        }
    }
    
    function positionPopup(popup, button) {
        if (!button) return;

        // Reset any prior positioning state.
        popup.classList.remove('position-top-left', 'position-top-center', 'position-top-right');
        popup.style.left = '';
        popup.style.top = '';
        popup.style.right = '';
        popup.style.bottom = '';

        // Move the popup to <body> so it escapes overflow/clipping on its
        // original container (critical for the sticky footer, which is
        // position:fixed and would otherwise crop the popup).
        if (popup.parentElement !== document.body) {
            document.body.appendChild(popup);
        }

        var rect = button.getBoundingClientRect();
        popup.style.setProperty('--button-x', rect.left + 'px');
        popup.style.setProperty('--button-y', rect.top + 'px');
        popup.style.setProperty('--button-width', rect.width + 'px');
        popup.style.setProperty('--button-right', rect.right + 'px');

        if (rect.left < 150) {
            popup.classList.add('position-top-left');
        } else if (rect.right > window.innerWidth - 150) {
            popup.classList.add('position-top-right');
        } else {
            popup.classList.add('position-top-center');
        }
    }

    function openPopup(popup, button) {
        // Close any existing popup first
        closePopup();

        positionPopup(popup, button);

        // Show the new popup
        popup.style.display = 'block';
        activePopup = popup;

        // Set up outside click handler with a delay
        setTimeout(function() {
            outsideClickHandler = function(event) {
                // Check if click is on the popup or any info button
                if (!popup.contains(event.target) &&
                    !event.target.classList.contains('mementor-tts-info-button') &&
                    !event.target.closest('.mementor-tts-info-button')) {
                    closePopup();
                }
            };
            document.addEventListener('click', outsideClickHandler);
        }, 100);
        
        // Only log in debug mode
        if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
            console.log('[TTS Info] Popup opened');
        }
    }
    
    function initializeInfoButton(button) {
        // Skip if already initialized
        if (button.hasAttribute('data-tts-info-initialized')) {
            return;
        }
        button.setAttribute('data-tts-info-initialized', 'true');
        
        button.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            // Find the popup — check inline player container first, then the
            // sticky footer (info button lives there in sticky mode), then
            // fall back to any popup in the document.
            var popup = null;
            var container = button.closest('.mementor-tts-player-container')
                || button.closest('.mementor-tts-sticky-footer');
            if (container) {
                popup = container.querySelector('.mementor-tts-info-popup');
            }
            if (!popup) {
                popup = document.querySelector('.mementor-tts-info-popup');
            }
            
            if (!popup) {
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('[TTS Info] Popup not found'); }
                return;
            }
            
            // Toggle popup
            if (popup === activePopup && popup.style.display !== 'none') {
                closePopup();
            } else {
                openPopup(popup, button);
            }
        });
        
        // Removed - too verbose
    }
    
    function initializeCloseButton(button) {
        if (button.hasAttribute('data-tts-close-initialized')) {
            return;
        }
        button.setAttribute('data-tts-close-initialized', 'true');
        
        button.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            closePopup();
        });
    }
    
    function initialize() {
        // Initialize all info buttons
        document.querySelectorAll('.mementor-tts-info-button').forEach(initializeInfoButton);
        
        // Initialize all close buttons
        document.querySelectorAll('.mementor-tts-info-close').forEach(initializeCloseButton);
        
        // Watch for new players
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) {
                        if (node.classList && node.classList.contains('mementor-tts-info-button')) {
                            initializeInfoButton(node);
                        } else if (node.querySelector) {
                            node.querySelectorAll('.mementor-tts-info-button').forEach(initializeInfoButton);
                            node.querySelectorAll('.mementor-tts-info-close').forEach(initializeCloseButton);
                        }
                    }
                });
            });
        });
        
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }
    
    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initialize);
    } else {
        initialize();
    }
    
    // Also initialize on window load as backup
    window.addEventListener('load', function() {
        setTimeout(initialize, 100);
    });
})();