/**
 * Mementor TTS Error Recovery Script
 * 
 * This script provides error recovery and robust initialization for TTS players
 * even when there are JavaScript syntax errors or conflicts on the page.
 */
(function() {
    'use strict';
    
    // Global error handler to catch and log JS errors without breaking TTS functionality
    window.addEventListener('error', function(e) {
        // Only log TTS-related errors to avoid spam
        if (e.filename && (e.filename.includes('mementor-tts') || e.message.includes('mementor'))) {
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                console.error('[TTS Error Recovery] JavaScript Error:', {
                    message: e.message,
                    filename: e.filename,
                    line: e.lineno,
                    column: e.colno
                });
            }
        }
        
        // Don't prevent other error handlers from running
        return false;
    });
    
    // Track retry attempts to prevent infinite recursion
    let retryCount = 0;
    const MAX_RETRIES = 3;
    
    // Robust TTS player initialization with error recovery
    function initializeTTSWithRecovery() {
        try {
            // Only log if debug mode is enabled
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                console.log('[TTS Error Recovery] Starting robust TTS initialization... (attempt ' + (retryCount + 1) + ')');
            }
            
            // Wait for DOM to be ready
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', initializeTTSWithRecovery);
                return;
            }
            
            // Look for TTS players - use only the specific class to avoid duplicates
            const processedPlayers = new Set();
            const players = document.querySelectorAll('.mementor-tts-player');
            let playersFound = 0;
            
            if (players.length > 0) {
                // Only log in debug mode
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                    console.log('[TTS Error Recovery] Found', players.length, 'player(s)');
                }
                
                players.forEach(function(player, index) {
                    // Skip if already processed
                    if (!processedPlayers.has(player)) {
                        processedPlayers.add(player);
                        const playerId = player.id || 'player_' + index;
                        initializeSinglePlayer(player, playerId);
                        playersFound++;
                    }
                });
            }
            
            // If no players found, try to create one from shortcode content
            if (playersFound === 0) {
                // Only log in debug mode
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                    console.log('[TTS Error Recovery] No players found, checking for shortcode content...');
                }
                findAndCreatePlayersFromShortcodes();
            }
            
            // Only log in debug mode
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                console.log('[TTS Error Recovery] Initialization complete. Total players found:', playersFound);
            }
            
        } catch (error) {
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('[TTS Error Recovery] Critical error during initialization:', error); }
            
            // Only retry if we haven't exceeded the maximum retry count
            if (retryCount < MAX_RETRIES) {
                retryCount++;
                // Only log in debug mode
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                    console.log('[TTS Error Recovery] Retrying initialization after error... (attempt ' + (retryCount + 1) + ' of ' + (MAX_RETRIES + 1) + ')');
                }
                setTimeout(function() {
                    initializeTTSWithRecovery();
                }, 2000);
            } else {
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('[TTS Error Recovery] Maximum retry attempts reached. Stopping initialization to prevent infinite recursion.'); }
            }
        }
    }
    
    // Initialize a single TTS player with error handling
    function initializeSinglePlayer(playerElement, playerId) {
        try {
            // Skip if already initialized
            if (playerElement.getAttribute('data-initialized') === 'true') {
                return;
            }
            
            // Only log in debug mode
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                console.log('[TTS Error Recovery] Initializing player:', playerId);
            }
            
            // Check if player is visible
            const isVisible = playerElement.offsetParent !== null;
            const computedStyle = window.getComputedStyle(playerElement);
            
            // Only log status if there's an issue
            if (!isVisible || computedStyle.display === 'none') {
                // Only log in debug mode
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                    console.log('[TTS Error Recovery] Player', playerId, 'status:', {
                        visible: isVisible,
                        display: computedStyle.display,
                        visibility: computedStyle.visibility,
                        opacity: computedStyle.opacity,
                        hasAudio: !!playerElement.querySelector('audio')
                    });
                }
            }
            
            // If player is hidden, try to make it visible
            if (!isVisible || computedStyle.display === 'none') {
                // Only log in debug mode
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                    console.log('[TTS Error Recovery] Player', playerId, 'is hidden, attempting to show...');
                }
                
                // Remove common hiding styles
                playerElement.style.display = 'block';
                playerElement.style.visibility = 'visible';
                playerElement.style.opacity = '1';
                
                // Check if it's now visible
                const nowVisible = playerElement.offsetParent !== null;
                // Only log in debug mode
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                    console.log('[TTS Error Recovery] Player', playerId, 'visibility after fix:', nowVisible);
                }
            }
            
            // Look for audio element and initialize controls
            const audioElement = playerElement.querySelector('audio');
            if (audioElement) {
                initializeAudioControls(audioElement, playerId, playerElement);
            } else {
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.warn('[TTS Error Recovery] No audio element found in player:', playerId); }
            }
            
            // Info button initialization is now handled by mementor-tts-info-handler.js
            // initializeInfoButton(playerElement, playerId);
            
            // Mark as initialized
            playerElement.setAttribute('data-initialized', 'true');
            
        } catch (error) {
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('[TTS Error Recovery] Error initializing player', playerId, ':', error); }
        }
    }
    
    // Initialize info button
    function initializeInfoButton(playerElement, playerId) {
        try {
            var infoButton = playerElement.querySelector('.mementor-tts-info-button');
            if (infoButton && !infoButton.hasAttribute('data-tts-recovery-initialized')) {
                infoButton.setAttribute('data-tts-recovery-initialized', 'true');
                
                // Store the close handler reference so we can remove it later
                var currentCloseHandler = null;
                
                infoButton.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    // Find the popup
                    var popup = playerElement.querySelector('.mementor-tts-info-popup');
                    if (!popup) {
                        // Try parent container
                        var container = playerElement.closest('.mementor-tts-player-container');
                        if (container) {
                            popup = container.querySelector('.mementor-tts-info-popup');
                        }
                    }
                    
                    if (popup) {
                        // Toggle visibility
                        if (popup.style.display === 'none' || !popup.style.display) {
                            popup.style.display = 'block';
                            
                            // Remove any existing handler first
                            if (currentCloseHandler) {
                                document.removeEventListener('click', currentCloseHandler);
                            }
                            
                            // Create new close handler
                            currentCloseHandler = function(event) {
                                // Check if click is outside the popup and info button
                                if (!popup.contains(event.target) && !infoButton.contains(event.target)) {
                                    popup.style.display = 'none';
                                    document.removeEventListener('click', currentCloseHandler);
                                    currentCloseHandler = null;
                                    // Only log in debug mode
                                    if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                                        console.log('[TTS Error Recovery] Info popup closed (clicked outside)');
                                    }
                                }
                            };
                            
                            // Add click outside handler after a delay
                            setTimeout(function() {
                                document.addEventListener('click', currentCloseHandler);
                                
                                // Add close button handler
                                var closeButton = popup.querySelector('.mementor-tts-info-close');
                                if (closeButton && !closeButton.hasAttribute('data-tts-close-initialized')) {
                                    closeButton.setAttribute('data-tts-close-initialized', 'true');
                                    closeButton.addEventListener('click', function(e) {
                                        e.preventDefault();
                                        e.stopPropagation();
                                        popup.style.display = 'none';
                                        if (currentCloseHandler) {
                                            document.removeEventListener('click', currentCloseHandler);
                                            currentCloseHandler = null;
                                        }
                                        // Only log in debug mode
                                        if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                                            console.log('[TTS Error Recovery] Info popup closed (close button)');
                                        }
                                    });
                                }
                            }, 100);
                        } else {
                            popup.style.display = 'none';
                            // Clean up handler when closing
                            if (currentCloseHandler) {
                                document.removeEventListener('click', currentCloseHandler);
                                currentCloseHandler = null;
                            }
                        }
                        // Only log in debug mode
                        if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                            console.log('[TTS Error Recovery] Info popup toggled');
                        }
                    }
                });
                
                // Only log in debug mode
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                    console.log('[TTS Error Recovery] Info button initialized for:', playerId);
                }
            }
        } catch (error) {
            console.error('[TTS Error Recovery] Error initializing info button:', error);
        }
    }
    
    // Initialize audio controls with error handling
    function initializeAudioControls(audioElement, playerId, playerElement) {
        try {
            // Only log in debug mode
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                console.log('[TTS Error Recovery] Setting up audio controls for:', playerId);
            }
            
            // Find play button
            const playButton = audioElement.parentElement.querySelector('.mementor-tts-play-button, [class*="play-button"], button');
            
            if (playButton) {
                // Remove existing event listeners to avoid duplicates
                playButton.removeEventListener('click', handlePlayClick);
                
                // Add new event listener
                playButton.addEventListener('click', function(e) {
                    handlePlayClick(e, audioElement, playerId);
                });
                
                // Removed - too verbose
            } else {
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.warn('[TTS Error Recovery] No play button found for:', playerId); }
            }
            
            
            // Set up audio event listeners
            audioElement.addEventListener('loadstart', function() {
                // Only log in debug mode
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                    console.log('[TTS Error Recovery] Audio loading started for:', playerId);
                }
            });
            
            audioElement.addEventListener('error', function(e) {
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('[TTS Error Recovery] Audio error for', playerId, ':', e); }
            });
            
            audioElement.addEventListener('canplay', function() {
                // Only log in debug mode
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                    console.log('[TTS Error Recovery] Audio ready to play for:', playerId);
                }
            });
            
        } catch (error) {
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('[TTS Error Recovery] Error setting up audio controls:', error); }
        }
    }
    
    // Handle play button clicks
    function handlePlayClick(event, audioElement, playerId) {
        try {
            event.preventDefault();
            // Only log in debug mode
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                console.log('[TTS Error Recovery] Play button clicked for:', playerId);
            }
            
            if (audioElement.paused) {
                // Pause all other TTS players first
                const allAudio = document.querySelectorAll('audio[data-mementor-tts], .mementor-tts-player audio');
                allAudio.forEach(function(audio) {
                    if (audio !== audioElement && !audio.paused) {
                        audio.pause();
                    }
                });
                
                // Play this audio
                audioElement.play().then(function() {
                    // Removed - too verbose
                }).catch(function(error) {
                    if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('[TTS Error Recovery] Error playing audio for', playerId, ':', error); }
                });
            } else {
                audioElement.pause();
                // Removed - too verbose
            }
            
        } catch (error) {
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('[TTS Error Recovery] Error handling play click:', error); }
        }
    }
    
    // Look for shortcode content and create players
    function findAndCreatePlayersFromShortcodes() {
        try {
            const bodyContent = document.body.innerHTML;
            
            // Look for TTS shortcode patterns
            const shortcodePatterns = [
                /\[mementor_tts[^\]]*\]/gi,
                /\[tts[^\]]*\]/gi,
                /data-mementor-tts/gi
            ];
            
            let foundShortcodes = false;
            
            shortcodePatterns.forEach(function(pattern) {
                const matches = bodyContent.match(pattern);
                if (matches) {
                    // Only log in debug mode
                    if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                        console.log('[TTS Error Recovery] Found shortcode pattern:', pattern, 'matches:', matches.length);
                    }
                    foundShortcodes = true;
                }
            });
            
            if (foundShortcodes) {
                // Only log in debug mode
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                    console.log('[TTS Error Recovery] Shortcodes found but no players rendered. This may indicate a PHP rendering issue.');
                }
                
                // Try to trigger a re-render by dispatching a custom event
                const event = new CustomEvent('mementorTTSReinitialize', {
                    detail: { source: 'error-recovery' }
                });
                document.dispatchEvent(event);
            }
            
        } catch (error) {
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('[TTS Error Recovery] Error checking for shortcodes:', error); }
        }
    }
    
    // Monitor for dynamically added players
    function startPlayerMonitoring() {
        try {
            const observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.type === 'childList') {
                        mutation.addedNodes.forEach(function(node) {
                            if (node.nodeType === Node.ELEMENT_NODE) {
                                // Check if the added node is a TTS player
                                if (node.classList && (node.classList.contains('mementor-tts-player') || 
                                    node.querySelector && node.querySelector('.mementor-tts-player'))) {
                                    // Only log in debug mode
                                    if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                                        console.log('[TTS Error Recovery] New TTS player detected, initializing...');
                                    }
                                    setTimeout(function() {
                                        initializeTTSWithRecovery();
                                    }, 100);
                                }
                            }
                        });
                    }
                });
            });
            
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
            
            // Only log in debug mode
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                console.log('[TTS Error Recovery] Player monitoring started');
            }
            
        } catch (error) {
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('[TTS Error Recovery] Error starting player monitoring:', error); }
        }
    }
    
    // Initialize everything when the script loads
    // Only log in debug mode
    if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
        console.log('[TTS Error Recovery] Script loaded, starting initialization...');
    }
    
    // Start immediately if DOM is ready, otherwise wait
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            initializeTTSWithRecovery();
            startPlayerMonitoring();
        });
    } else {
        // DOM is already ready
        setTimeout(function() {
            initializeTTSWithRecovery();
            startPlayerMonitoring();
        }, 100);
    }
    
    // Also try after window load in case other scripts interfere
    window.addEventListener('load', function() {
        setTimeout(function() {
            // Only run if we haven't found any players yet
            var foundPlayers = document.querySelectorAll('.mementor-tts-player[data-initialized="true"]').length;
            if (foundPlayers === 0) {
                // Only log in debug mode
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) {
                    console.log('[TTS Error Recovery] Window loaded, no initialized players found, attempting initialization...');
                }
                initializeTTSWithRecovery();
            } else {
                // Removed - too verbose
            }
        }, 500);
    });
    
})();
