/**
 * jQuery wait wrapper for Text to Speech
 * Ensures jQuery is loaded before initializing
 */
(function() {
    'use strict';
    
    var attempts = 0;
    var maxAttempts = 50;
    
    function waitForJQuery() {
        if (typeof jQuery !== 'undefined') {
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.log('[TTS] jQuery loaded, initializing info button handlers...'); }
            initializeInfoButtons();
        } else if (attempts < maxAttempts) {
            attempts++;
            setTimeout(waitForJQuery, 100);
        } else {
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('[TTS] jQuery not loaded after ' + maxAttempts + ' attempts'); }
        }
    }
    
    function initializeInfoButtons() {
        var $ = jQuery;
        
        // Set up info button click handlers
        function setupInfoButton(button) {
            // Skip if already initialized by error recovery script
            if (button.hasAttribute('data-tts-recovery-initialized')) {
                return;
            }
            
            // Remove any existing handlers first
            $(button).off('click.tts');
            
            // Add our handler
            $(button).on('click.tts', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.log('[TTS] Info button clicked'); }
                
                // Find the popup - it should be a sibling
                var popup = $(this).siblings('.mementor-tts-info-popup');
                
                if (popup.length === 0) {
                    // Try to find it in the parent container
                    popup = $(this).closest('.mementor-tts-controls').find('.mementor-tts-info-popup');
                }
                
                if (popup.length === 0) {
                    // Last resort - find any popup on the page
                    popup = $('.mementor-tts-info-popup').first();
                }
                
                if (popup.length > 0) {
                    // Check current visibility
                    var isCurrentlyVisible = popup.is(':visible');
                    
                    if (!isCurrentlyVisible) {
                        // Show the popup
                        popup.show();
                        
                        // Clean up any existing handlers first
                        $(document).off('click.tts-popup');
                        popup.find('.mementor-tts-info-close').off('click.tts-close');
                        
                        // Add handlers after a delay
                        setTimeout(function() {
                            // Click outside handler
                            $(document).on('click.tts-popup', function(event) {
                                // Check if click is outside the popup and info button
                                if (!popup.is(event.target) && popup.has(event.target).length === 0 &&
                                    !$(event.target).closest('.mementor-tts-info-button').length) {
                                    popup.hide();
                                    $(document).off('click.tts-popup');
                                    if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.log('[TTS] Popup closed (clicked outside)'); }
                                }
                            });
                            
                            // Close button handler
                            popup.find('.mementor-tts-info-close').on('click.tts-close', function(e) {
                                e.preventDefault();
                                e.stopPropagation();
                                popup.hide();
                                $(document).off('click.tts-popup');
                                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.log('[TTS] Popup closed (close button)'); }
                            });
                        }, 100);
                        
                        if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.log('[TTS] Popup opened'); }
                    } else {
                        // Hide the popup
                        popup.hide();
                        $(document).off('click.tts-popup');
                        if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.log('[TTS] Popup closed'); }
                    }
                } else {
                    if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('[TTS] Info popup not found'); }
                }
                
                return false;
            });
        }
            
        // Initialize all info buttons
        $('.mementor-tts-info-button').each(function() {
            setupInfoButton(this);
        });
        
        if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.log('[TTS] Info button handlers initialized for', $('.mementor-tts-info-button').length, 'buttons'); }
        
        // Watch for dynamically added players
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) { // Element node
                        var buttons = $(node).find('.mementor-tts-info-button');
                        buttons.each(function() {
                            setupInfoButton(this);
                        });
                    }
                });
            });
        });
        
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
        
        // Also run when DOM is ready in case we're called early
        $(document).ready(function() {
            $('.mementor-tts-info-button').each(function() {
                setupInfoButton(this);
            });
        });
    }
    
    // Start waiting for jQuery
    waitForJQuery();
})();