jQuery(document).ready(function($) {
    
    // Flag to prevent re-initialization
    if (window.mementorTtsShortcodeInitialized) {
        return;
    }
    window.mementorTtsShortcodeInitialized = true;

    // Ensure we have a valid object for AJAX operations - fallback to mementorTTSPlayer or create a new one
    if (typeof mementorTtsShortcode === 'undefined') {
        
        // Try to use mementorTTSPlayer or create a default object
        if (typeof mementorTTSPlayer !== 'undefined') {
            window.mementorTtsShortcode = mementorTTSPlayer;
        } else {
            window.mementorTtsShortcode = {
                ajaxurl: (window.ajaxurl || (typeof wp !== 'undefined' ? wp.ajax.settings.url : '/wp-admin/admin-ajax.php')),
                nonce: '',
                debug: '1'  // Enable debug mode by default when using fallback
            };
        }
    }

    /* Output current AJAX settings for debugging
        url: mementorTtsShortcode.ajaxurl,
        nonce: mementorTtsShortcode.nonce
    }); */

    // Helper function for logging
    function log(...args) {
        if (mementorTtsShortcode && mementorTtsShortcode.debug === '1') {
        }
    }

    // Debug function to log text content for all players
    /* function debugTTSPlayers() {
        $('.mementor-tts-player').each(function(index) {
            const player = $(this);
            const text = player.data('text');
            const uid = player.data('element-uid');
            if (text && text.length > 0) {
            } else {
            }
        });
    } */

    // Run debug on page load
    // debugTTSPlayers();

    // Initialize TTS shortcode players
    function initTtsShortcodes() {
        
        // Debug: Check what shortcode containers we can find
        const shortcodeContainers = $('.mementor-tts-player-container[data-player-type="shortcode"]');
        
        /* Debug: Check for any mementor-tts-player elements
        const allPlayers = $('.mementor-tts-player');
        allPlayers.each(function(i) {
                'data-audio-url': $(this).attr('data-audio-url'),
                'data-status': $(this).attr('data-status'),
                'parent-data-player-type': $(this).closest('.mementor-tts-player-container').attr('data-player-type')
            });
        }); */
        
        // First handle SHORTCODE players with pre-generated audio (data-status="ready" or data-audio-url)
        $('.mementor-tts-player-container[data-player-type="shortcode"] .mementor-tts-player[data-status="ready"], .mementor-tts-player-container[data-player-type="shortcode"] .mementor-tts-player[data-audio-url]').each(function() {
            const player = $(this);
            
            // Skip if already initialized
            if (player.data('shortcode-initialized')) {
                return;
            }
            
            const audioUrl = player.data('audio-url');
            
            
            if (audioUrl) {
                // Ensure audio element exists
                let audio = player.find('audio');
                if (!audio.length) {
                    audio = $('<audio>', {
                        preload: 'metadata',
                        src: audioUrl
                    });
                    audio.appendTo(player);
                } else if (!audio.attr('src')) {
                    audio.attr('src', audioUrl);
                }
                
                // Initialize the audio player
                initializeAudioPlayer(player, audio);
                
                // Handle autoplay if enabled
                if (player.attr('data-autoplay') === 'true') {
                    audio[0].play().catch(function(error) {
                    });
                }
                
                // Handle loop if enabled
                if (player.attr('data-loop') === 'true') {
                    audio[0].loop = true;
                }
                
                // Ensure play button has correct icon and handlers
                const playButton = player.find('.mementor-tts-play-button');
                if (playButton.length) {
                    playButton.find('.dashicons')
                        .removeClass('dashicons-update mementor-dashicons-update')
                        .addClass('dashicons-controls-play mementor-dashicons-controls-play');
                    
                    // Add click handler for play/pause
                    playButton.off('click.playPause').on('click.playPause', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        if (audio.length && audio[0].src) {
                            togglePlayPause(player, audio[0]);
                        }
                    });
                }
                
                // Also set up the volume and other controls
                setupPlayerControls(player, audio);
                
                // Mark as initialized
                player.data('shortcode-initialized', true);
            }
        });
        
        // Then handle pending SHORTCODE players that need generation
        $('.mementor-tts-player-container[data-player-type="shortcode"] .mementor-tts-player[data-status="pending"][data-text]').each(function() {
            const player = $(this);
            const playerContainer = player.closest('.mementor-tts-player-container');
            const elementUid = player.data('element-uid');
            const text = player.data('text');

            /* elementUid: elementUid,
                hasText: !!text,
                textLength: text ? text.length : 0
            }); */
            
            // Ensure audio element exists
            if (!player.find('audio').length) {
                const audio = $('<audio>', {
                    preload: 'metadata'
                });
                audio.appendTo(player).hide();
            }
            
            // Update the button to show "generate" icon (this part seems redundant now as PHP handles it, but keep for safety)
            player.find('.mementor-tts-play-button .dashicons')
                .removeClass('dashicons-controls-play mementor-dashicons-controls-play')
                .addClass('dashicons-update mementor-dashicons-update');
            player.find('.mementor-tts-play-button')
                .attr('title', 'Generate audio')
                .addClass('mementor-tts-generate-button'); // Ensure class for delegation
            player.addClass('mementor-tts-needs-generation');
        });

        // *** Use Event Delegation for Play Button Clicks on Pending SHORTCODE Players ***
        $(document).on('click', '.mementor-tts-player-container[data-player-type="shortcode"] .mementor-tts-player[data-status="pending"] .mementor-tts-play-button', function(e) {
            e.preventDefault(); 
            e.stopPropagation(); 
            
            const button = $(this);
            const player = button.closest('.mementor-tts-player');
            const text = player.data('text');
            const elementUid = player.data('element-uid');

            // Double-check status and text just in case
            if (player.data('status') !== 'pending' || !text) {
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.warn('Delegated click handler fired on non-pending player or player without text.'); }
                return; 
            }


            // Show generating state on the clicked button
            button.find('.dashicons')
                .removeClass('dashicons-controls-play dashicons-update mementor-dashicons-controls-play mementor-dashicons-update')
                .addClass('dashicons-update mementor-dashicons-update mementor-tts-rotating');
            
            // Add generating state to the container
            player.closest('.mementor-tts-player-container').addClass('mementor-tts-generating');
            
            // Generate the audio
            generateAudio(player); 
        });

        // Note: Non-pending players are now handled at the beginning of this function

        // Setup non-generation controls for SHORTCODE players only
        $('.mementor-tts-player-container[data-player-type="shortcode"] .mementor-tts-player').each(function() {
            const player = $(this);
            const audio = player.find('audio');
            
            // Skip pending players - they're handled by delegation
            if (player.data('status') === 'pending') {
                return;
            }
            
            // For ready players, ensure audio element exists and set up all controls
            if (audio.length && audio[0].src) {
                // Initialize if not already done
                if (!player.data('controls-initialized')) {
                    initializeAudioPlayer(player, audio);
                    setupPlayerControls(player, audio);
                    player.data('controls-initialized', true);
                }
            }

            // Progress bar click
            player.find('.mementor-tts-progress-container').on('click', function(e) {
                if (!audio.length || !audio[0].src) return;
                const progressContainer = $(this);
                const position = (e.pageX - progressContainer.offset().left) / progressContainer.width();
                audio[0].currentTime = position * audio[0].duration;
                updateProgressBar(player, audio[0]);
            });

            // Volume button
            player.find('.mementor-tts-volume-button').off('click.volume').on('click.volume', function(e) {
                e.preventDefault();
                e.stopPropagation();
                if (!audio.length || !audio[0].src) return;
                const audioElement = audio[0];
                const button = $(this);
                
                if (audioElement.muted || audioElement.volume === 0) {
                    audioElement.muted = false;
                    audioElement.volume = 1.0;
                    button.find('.dashicons')
                        .removeClass('dashicons-controls-volumeoff mementor-dashicons-controls-volumeoff')
                        .addClass('dashicons-controls-volumeon mementor-dashicons-controls-volumeon');
                } else {
                    audioElement.muted = true;
                    button.find('.dashicons')
                        .removeClass('dashicons-controls-volumeon mementor-dashicons-controls-volumeon')
                        .addClass('dashicons-controls-volumeoff mementor-dashicons-controls-volumeoff');
                }
            });
            
            // Listen for volume changes to update the icon
            audio.on('volumechange', function() {
                const volumeButton = player.find('.mementor-tts-volume-button');
                if (audio[0].muted || audio[0].volume === 0) {
                    volumeButton.find('.dashicons')
                        .removeClass('dashicons-controls-volumeon mementor-dashicons-controls-volumeon')
                        .addClass('dashicons-controls-volumeoff mementor-dashicons-controls-volumeoff');
                } else {
                    volumeButton.find('.dashicons')
                        .removeClass('dashicons-controls-volumeoff mementor-dashicons-controls-volumeoff')
                        .addClass('dashicons-controls-volumeon mementor-dashicons-controls-volumeon');
                }
            });

            // Speed button
            player.find('.mementor-tts-speed-button').on('click', function() {
                if (!audio.length || !audio[0].src) return;
                const audioElement = audio[0];
                const speeds = [0.75, 1.0, 1.25, 1.5, 2.0];
                let currentIndex = speeds.indexOf(audioElement.playbackRate);
                if (currentIndex === -1) currentIndex = 1;
                const nextIndex = (currentIndex + 1) % speeds.length;
                audioElement.playbackRate = speeds[nextIndex];
                $(this).text(speeds[nextIndex] + 'x');
            });
        });
    }
    
    // Function to initialize audio player
    function initializeAudioPlayer(player, audio) {
        const audioElement = audio[0];
        
        // Set up event listeners for the audio element
        audio.on('loadedmetadata', function() {
            updateDuration(player, audioElement);
            player.data('status', 'ready');
            player.closest('.mementor-tts-player-container').addClass('mementor-tts-audio-ready');
        });
        
        audio.on('timeupdate', function() {
            updateProgressBar(player, audioElement);
            updateCurrentTime(player, audioElement);
        });
        
        audio.on('play', function() {
            player.find('.mementor-tts-play-button .dashicons')
                .removeClass('dashicons-controls-play mementor-dashicons-controls-play')
                .addClass('dashicons-controls-pause mementor-dashicons-controls-pause');
        });
        
        audio.on('pause', function() {
            player.find('.mementor-tts-play-button .dashicons')
                .removeClass('dashicons-controls-pause mementor-dashicons-controls-pause')
                .addClass('dashicons-controls-play mementor-dashicons-controls-play');
        });
        
        audio.on('ended', function() {
            player.find('.mementor-tts-play-button .dashicons')
                .removeClass('dashicons-controls-pause mementor-dashicons-controls-pause')
                .addClass('dashicons-controls-play mementor-dashicons-controls-play');
        });
        
        // Set initial duration if already loaded
        if (audioElement.readyState > 0) {
            updateDuration(player, audioElement);
        }
    }
    
    // Function to toggle play/pause
    function togglePlayPause(player, audio) {
        if (audio.paused) {
            // Pause all other players first
            $('audio').not(audio).each(function() {
                this.pause();
            });
            
            // Play this audio
            audio.play().catch(function(error) {
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('Error playing audio:', error); }
            });
        } else {
            audio.pause();
        }
    }
    
    // Function to play audio
    function playAudio(player) {
        log('Playing audio for player:', player.data('element-uid'));
        const audio = player.find('audio')[0];
        
        if (audio && audio.src) {
            // Pause all other players first
            $('audio').not(audio).each(function() {
                this.pause();
                $(this).closest('.mementor-tts-player').find('.mementor-tts-play-button .dashicons')
                    .removeClass('dashicons-controls-pause')
                    .addClass('dashicons-controls-play');
            });
            
            // Play this audio
            audio.play().catch(function(error) {
                log('Error playing audio:', error);
            });
            
            // Update UI
            player.find('.mementor-tts-play-button .dashicons')
                .removeClass('dashicons-controls-play dashicons-update mementor-dashicons-controls-play mementor-dashicons-update mementor-tts-rotating')
                .addClass('dashicons-controls-pause mementor-dashicons-controls-pause');
        } else {
            log('Cannot play audio - no audio element or source found');
        }
    }
    
    // Function to generate audio via AJAX
    function generateAudio(player) {
        const playerContainer = player.closest('.mementor-tts-player-container');
        const text = player.data('text');
        const voiceID = player.data('voice-id');
        const elementUid = player.data('element-uid');

        /* textLength: text ? text.length : 0,
            voiceID: voiceID,
            elementUid: elementUid,
            ajaxNonce: mementorTtsShortcode.nonce, // Check nonce
            ajaxUrl: mementorTtsShortcode.ajaxurl  // Check URL
        }); */
        
        if (!text || text.length === 0) {
            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('No text available for generating audio!'); }
            alert('No text found to generate audio. Please try again or contact the site administrator.');
            return;
        }
        
        // Set status to generating
        player.data('status', 'generating');
        player.attr('data-status', 'generating');
        
        // Update UI to show generating state
        player.find('.mementor-tts-play-button .dashicons')
            .removeClass('dashicons-controls-play')
            .addClass('dashicons-update mementor-tts-rotating');
        playerContainer.addClass('mementor-tts-generating');
        
        // Set a timeout for the request (60 seconds)
        let requestTimeout = setTimeout(function() {
            resetGeneratingUI(player);
            alert('Audio generation timed out. Please try again or contact the site administrator.');
        }, 60000);
        
        // Prepare AJAX data
        const ajaxData = {
            action: 'mementor_tts_generate_shortcode_audio',
            nonce: mementorTtsShortcode.nonce,
            element_uid: elementUid,
            text: text,
            voice_id: voiceID
        };
        
        
        $.ajax({
            url: mementorTtsShortcode.ajaxurl,
            type: 'POST',
            data: ajaxData,
            timeout: 60000, // 60 second timeout
            success: function(response) {
                clearTimeout(requestTimeout);
                
                if (response.success) {
                    
                    // Get the audio URL from the response data
                    let audioUrl;
                    if (response.data.audio_url) {
                        audioUrl = response.data.audio_url;
                    } else if (response.data.file_url) {
                        audioUrl = response.data.file_url;
                    }
                    
                    
                    if (!audioUrl) {
                        if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('No audio URL in response'); }
                        resetGeneratingUI(player);
                        alert('Error: No audio URL received from server');
                        return;
                    }
                    
                    // Set the audio source
                    const audioElement = player.find('audio')[0];
                    audioElement.src = audioUrl;
                    
                    // Add error handler for audio loading failures
                    $(audioElement).on('error', function() {
                        if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('Error loading audio file'); }
                        resetGeneratingUI(player);
                        alert('Error loading the generated audio. Please try again.');
                    });
                    
                    // Try to load and play the audio
                    audioElement.load();
                    
                    // Update UI
                    player.data('status', 'ready');
                    player.attr('data-status', 'ready');
                    player.find('.mementor-tts-play-button .dashicons')
                        .removeClass('dashicons-update mementor-tts-rotating mementor-dashicons-update')
                        .addClass('dashicons-controls-play mementor-dashicons-controls-play');
                    playerContainer.removeClass('mementor-tts-generating');
                    
                    // Handle loop if enabled
                    if (player.attr('data-loop') === 'true') {
                        audioElement.loop = true;
                    }
                    
                    // Play the audio if autoplay is enabled or if just generated
                    if (player.attr('data-autoplay') === 'true') {
                        log('Autoplay is enabled, playing audio'); // Use log helper
                        playAudio(player);
                    } else {
                        // Automatically play the newly generated audio
                        log('Playing newly generated audio'); // Use log helper
                        playAudio(player);
                    }
                } else {
                    if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('Error generating audio:', response.data ? response.data.message : 'Unknown error'); }
                    resetGeneratingUI(player);
                    alert('Error generating audio: ' + (response.data ? response.data.message : 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                clearTimeout(requestTimeout);
                if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('AJAX Error:', status, error); console.error('Response text:', xhr.responseText); }
                resetGeneratingUI(player);
                
                // Provide more specific error messages based on HTTP status
                if (status === 'timeout') {
                    alert('Request timed out. The server may be busy or the text might be too long.');
                } else if (xhr.status === 0) {
                    alert('Could not connect to the server. Please check your internet connection and try again.');
                } else if (xhr.status === 401 || xhr.status === 403) {
                    alert('Unauthorized access. Please refresh the page and try again.');
                } else if (xhr.status >= 500) {
                    alert('Server error. Please try again later or contact the site administrator.');
                } else {
                    alert('Error generating audio. Please try again.');
                }
            }
        });
    }
    
    // Helper function to reset UI after failed generation
    function resetGeneratingUI(player) {
        const playerContainer = player.closest('.mementor-tts-player-container');
        
        // Reset button state
        player.find('.mementor-tts-play-button .dashicons')
            .removeClass('dashicons-update mementor-tts-rotating mementor-dashicons-update')
            .addClass('dashicons-controls-play mementor-dashicons-controls-play');
            
        // Reset container classes
        playerContainer.removeClass('mementor-tts-generating');
        
        // Reset player status but keep it in 'needs generation' state
        player.data('status', 'needs-generation');
        player.attr('data-status', 'needs-generation');
    }
    
    // Function to update progress bar
    function updateProgressBar(player, audio) {
        const progress = (audio.currentTime / audio.duration) * 100;
        player.find('.mementor-tts-progress-bar').css('width', progress + '%');
    }
    
    // Function to update current time display
    function updateCurrentTime(player, audio) {
        player.find('.mementor-tts-time-display').text(formatTime(audio.currentTime));
    }
    
    // Function to update duration display
    function updateDuration(player, audio) {
        player.find('.mementor-tts-duration-display').text(formatTime(audio.duration));
    }
    
    // Function to format time in MM:SS
    function formatTime(seconds) {
        if (isNaN(seconds)) return '0:00';
        
        const mins = Math.floor(seconds / 60);
        const secs = Math.floor(seconds % 60);
        return mins + ':' + (secs < 10 ? '0' : '') + secs;
    }
    
    // Function to set up all player controls
    function setupPlayerControls(player, audio) {
        if (!player || !audio || !audio.length) return;
        
        const audioElement = audio[0];
        
        // Volume control is already set up in the main setup
        // Just ensure the icon state is correct
        const volumeButton = player.find('.mementor-tts-volume-button');
        if (volumeButton.length) {
            // Set initial state
            if (audioElement.muted || audioElement.volume === 0) {
                volumeButton.find('.dashicons')
                    .removeClass('dashicons-controls-volumeon mementor-dashicons-controls-volumeon')
                    .addClass('dashicons-controls-volumeoff mementor-dashicons-controls-volumeoff');
            } else {
                volumeButton.find('.dashicons')
                    .removeClass('dashicons-controls-volumeoff mementor-dashicons-controls-volumeoff')
                    .addClass('dashicons-controls-volumeon mementor-dashicons-controls-volumeon');
            }
        }
    }
    
    // Initialize players
    initTtsShortcodes();
    
    // Re-initialize shortcode players if DOM changes (e.g., when auto-inserted player is added)
    const observer = new MutationObserver(function(mutations) {
        let shouldReinitialize = false;
        
        mutations.forEach(function(mutation) {
            // Check if auto-inserted player was added
            if (mutation.addedNodes.length > 0) {
                $(mutation.addedNodes).each(function() {
                    if ($(this).hasClass('mementor-tts-player-container') && 
                        $(this).attr('data-player-type') === 'auto-inserted') {
                        shouldReinitialize = true;
                    }
                });
            }
        });
        
        if (shouldReinitialize) {
            setTimeout(function() {
                initTtsShortcodes();
            }, 100);
        }
    });
    
    // Start observing
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});
