/**
 * Mementor Text to Speech - Frontend JavaScript
 *
 * Handles the audio player functionality on the frontend.
 */
(function(factory) {
    if (typeof jQuery !== 'undefined') {
        factory(jQuery);
    } else {
        // jQuery not yet available (may be delayed by cache plugin) — wait for it
        var maxAttempts = 50; // 5 seconds max
        var attempts = 0;
        var waitForjQuery = setInterval(function() {
            attempts++;
            if (typeof jQuery !== 'undefined') {
                clearInterval(waitForjQuery);
                factory(jQuery);
            } else if (attempts >= maxAttempts) {
                clearInterval(waitForjQuery);
                if (window.mementorTTSDebugEnabled) {
                    console.warn('Mementor TTS: jQuery not available after waiting. Player may not function correctly.');
                }
            }
        }, 100);
    }
})(function($) {
    'use strict';

    // We now rely on the centralized debug logic in mementor-tts-debug-settings.js
    // The global mementorTTSDebugEnabled variable should already be set
    // The global mementorTTSDebug function should already be defined
    
    // Create a safe wrapper for debug logging
    var safeDebug = function() {
        if (typeof window.mementorTTSDebug === 'function') {
            window.mementorTTSDebug.apply(window, arguments);
        }
    };
    
    // Statistics tracking stub functions
    // These will be overridden by the statistics script if it's loaded
    window.mementorTTSTrackEvent = window.mementorTTSTrackEvent || function() {};
    window.mementorTTSSetupTracking = window.mementorTTSSetupTracking || function() {};
    
    // Get post ID from player element
    function getPostIdFromPlayer(playerElement) {
        // Try different methods to get post ID
        const $player = $(playerElement);
        
        safeDebug('Getting post ID from player:', playerElement);
        
        // Check data-post-id attribute
        let postId = $player.data('post-id');
        safeDebug('Player data-post-id:', postId);
        if (postId) return postId;
        
        // Check parent container
        const $container = $player.closest('[data-post-id]');
        safeDebug('Found container with data-post-id:', $container.length > 0);
        if ($container.length) {
            postId = $container.data('post-id');
            safeDebug('Container data-post-id:', postId);
            if (postId) return postId;
        }
        
        // Try to get from mementorTTS global object
        if (typeof mementorTTS !== 'undefined' && mementorTTS.postId) {
            safeDebug('Using mementorTTS.postId:', mementorTTS.postId);
            return mementorTTS.postId;
        }
        
        // Try to get from mementorTTSStats global object
        if (typeof mementorTTSStats !== 'undefined' && mementorTTSStats.postId) {
            safeDebug('Using mementorTTSStats.postId:', mementorTTSStats.postId);
            return mementorTTSStats.postId;
        }
        
        // Try to get from body class (single post pages)
        const bodyClasses = document.body.className;
        const match = bodyClasses.match(/postid-(\d+)/);
        if (match) {
            safeDebug('Found post ID in body class:', match[1]);
            return match[1];
        }
        
        safeDebug('No post ID found');
        return null;
    }
    

    // Initialize all players when the document is ready
    $(document).ready(function() {
        // Log debug status if not already logged
        if (window.mementorTTSDebugEnabled && typeof window.debugStatusLogged === 'undefined') {
            window.debugStatusLogged = true;
        }

        // Lazy load: defer initialization until player scrolls into view
        if (typeof mementorTTSPlayer !== 'undefined' && mementorTTSPlayer.lazyLoad && 'IntersectionObserver' in window) {
            safeDebug('Lazy load enabled — deferring player init');
            var containers = document.querySelectorAll('.mementor-tts-player-container');
            if (containers.length) {
                var observer = new IntersectionObserver(function(entries, obs) {
                    entries.forEach(function(entry) {
                        if (entry.isIntersecting) {
                            obs.unobserve(entry.target);
                            safeDebug('Lazy init player in view');
                            initializePlayers();
                            initializeShortcodePlayers();
                            // Disconnect after first trigger since all players init together
                            obs.disconnect();
                        }
                    });
                }, { rootMargin: '200px' });
                containers.forEach(function(c) { observer.observe(c); });
                return; // Skip immediate init below
            }
        }

        // Initialize players
        initializePlayers();

        // Also initialize shortcode players that might be dynamically added
        initializeShortcodePlayers();
        
        // Additional check for any SHORTCODE players that might have been missed
        setTimeout(function() {
            $('.mementor-tts-player-container[data-player-type="shortcode"] .mementor-tts-player').each(function() {
                const player = $(this);
                // Check if this player has been initialized
                if (!player.data('initialized')) {
                    safeDebug('Found uninitialized shortcode player, initializing now');
                    if (player.data('audio-url')) {
                        // Pre-generated audio
                        let audio = player.find('audio');
                        if (!audio.length) {
                            audio = $('<audio preload="metadata"></audio>');
                            player.prepend(audio);
                        }
                        if (player.data('audio-url') && !audio.attr('src')) {
                            audio.attr('src', player.data('audio-url'));
                        }
                        initializePlayer(player[0]);
                    }
                    player.data('initialized', true);
                }
            });
        }, 100);
        
        // Fix all play buttons on the page
        setTimeout(function() {
            safeDebug('Automatically fixing all play buttons');
            
            // Ensure dashicons are loaded again after a delay
            if (typeof window.ensureDashiconsLoaded === 'function') {
                window.ensureDashiconsLoaded();
            }
            
            if (typeof window.fixPlayButtons === 'function') {
                window.fixPlayButtons();
            }
            
            // Fix HTML5 audio players
            if (typeof window.fixHTML5Players === 'function') {
                window.fixHTML5Players();
            }
            
            // Make sure all player controls are properly initialized
            fixPlayerControls();
        }, 500);
    });

    // Add debug function to window for troubleshooting
    window.debugMementorTTS = function() {
        safeDebug('=== Mementor TTS Debug ===');
        
        // Find all audio elements
        const audioElements = document.querySelectorAll('audio');
        safeDebug(`Found ${audioElements.length} audio elements:`);
        
        audioElements.forEach(function(audio, index) {
            safeDebug(`Audio #${index + 1}:`, {
                element: audio,
                hasSource: !!audio.src,
                src: audio.src,
                paused: audio.paused,
                duration: audio.duration,
                readyState: audio.readyState,
                networkState: audio.networkState,
                error: audio.error
            });
            
            // Check source elements
            const sources = audio.querySelectorAll('source');
            safeDebug(`  Sources: ${sources.length}`);
            sources.forEach(function(source, i) {
                safeDebug(`  Source #${i + 1}:`, {
                    element: source,
                    src: source.src,
                    type: source.type
                });
            });
            
            // Find parent player
            const player = $(audio).closest('.mementor-tts-player');
            if (player.length) {
                safeDebug(`  Player:`, {
                    element: player[0],
                    hasPlayButton: player.find('.mementor-tts-play-button').length > 0,
                    hasControls: player.find('.mementor-tts-custom-controls, .mementor-tts-controls').length > 0
                });
            } else {
                safeDebug(`  No parent player found`);
            }
        });
        
        // Try to play the first audio element
        if (audioElements.length > 0) {
            safeDebug('Attempting to play the first audio element...');
            try {
                const firstAudio = audioElements[0];
                firstAudio.load();
                
                setTimeout(function() {
                    const playPromise = firstAudio.play();
                    if (playPromise !== undefined) {
                        playPromise.then(function() {
                            safeDebug('Audio playing successfully via debug function');
                        }).catch(function(error) {
                            if (window.mementorTTSDebugEnabled) console.error('Error playing audio via debug function:', error);
                        });
                    }
                }, 100);
            } catch (error) {
                if (window.mementorTTSDebugEnabled) console.error('Error in debug play attempt:', error);
            }
        }
        
        safeDebug('=== End Debug ===');
    };

    // Global helper function to play all audio elements
    window.playAllAudio = function() {
        safeDebug('Playing all audio elements');
        try {
            const audioElements = document.querySelectorAll('audio');
            safeDebug('Found', audioElements.length, 'audio elements');
            
            audioElements.forEach(function(audio, index) {
                safeDebug('Processing audio element', index);
                
                // Initialize the _isPlaying property and add debug listeners only once
                if (typeof audio._isPlaying === 'undefined') {
                    audio._isPlaying = false;
                    
                    // Check if debug listeners are already set up
                    if (!audio._debugListenersSetup) {
                        audio._debugListenersSetup = true;
                        
                        // Add event listeners to track play/pause state
                        audio.addEventListener('play', function() {
                            safeDebug('Audio play event triggered');
                            audio._isPlaying = true;
                            
                            // Update all play buttons associated with this audio to show pause icon
                            $(audio).closest('.mementor-tts-player').find('.mementor-tts-play-button .dashicons')
                                .removeClass('dashicons-controls-play mementor-dashicons-controls-play')
                                .addClass('dashicons-controls-pause mementor-dashicons-controls-pause');
                        });
                        
                        audio.addEventListener('pause', function() {
                            safeDebug('Audio pause event triggered');
                            audio._isPlaying = false;
                            
                            // Update all play buttons associated with this audio to show play icon
                            $(audio).closest('.mementor-tts-player').find('.mementor-tts-play-button .dashicons')
                                .removeClass('dashicons-controls-pause')
                                .addClass('dashicons-controls-play');
                        });
                        
                        audio.addEventListener('ended', function() {
                            safeDebug('Audio ended event triggered');
                            audio._isPlaying = false;
                            audio.currentTime = 0; // Reset to beginning only when ended
                            
                            // Update all play buttons associated with this audio to show play icon
                            $(audio).closest('.mementor-tts-player').find('.mementor-tts-play-button .dashicons')
                                .removeClass('dashicons-controls-pause')
                                .addClass('dashicons-controls-play');
                        });
                    }
                }
                
                // Make sure the audio has a source
                try {
                    if (!audio.src) {
                        const sourceElement = safeQuerySelector(audio, 'source');
                        if (sourceElement && sourceElement.src) {
                            safeDebug('Setting audio source from source element:', sourceElement.src);
                            audio.src = sourceElement.src;
                        } else {
                            // Try jQuery as a fallback
                            const $source = $(audio).find('source');
                            if ($source.length && $source.attr('src')) {
                                safeDebug('Setting audio source from jQuery source element:', $source.attr('src'));
                                audio.src = $source.attr('src');
                            } else {
                                if (window.mementorTTSDebugEnabled) console.error('No source found for audio element', index);
                                return;
                            }
                        }
                    }
                    
                    // Play the audio if it's not already playing
                    if (!audio._isPlaying) {
                        safeDebug('Playing audio element', index, 'from position:', audio.currentTime);
                        audio.play().catch(function(error) {
                            if (window.mementorTTSDebugEnabled) console.error('Error playing audio:', error);

                            // Try to reload and play again if there was an error
                            try {
                                safeDebug('Attempting to reload and play again');
                                audio.load();
                                setTimeout(function() {
                                    audio.play().catch(function(retryError) {
                                        if (window.mementorTTSDebugEnabled) console.error('Error playing audio after retry:', retryError);
                                    });
                                }, 100);
                            } catch (retryError) {
                                if (window.mementorTTSDebugEnabled) console.error('Error during retry:', retryError);
                            }
                        });
                    } else {
                        safeDebug('Audio element', index, 'is already playing');
                    }
                } catch (error) {
                    if (window.mementorTTSDebugEnabled) console.error('Error processing audio element', index, ':', error);
                }
            });
            
            return true;
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error playing all audio:', error);
            return false;
        }
    };

    // Global helper function to fix volume buttons
    window.fixVolumeButtons = function() {
        safeDebug('Fixing all volume buttons');
        try {
            const volumeButtons = document.querySelectorAll('.mementor-tts-volume-button');
            safeDebug('Found', volumeButtons.length, 'volume buttons');
            
            volumeButtons.forEach(function(button, index) {
                safeDebug('Processing volume button', index);
                
                // Find the audio element
                const player = button.closest('.mementor-tts-player');
                if (!player) return;
                
                const audio = player.querySelector('audio');
                if (!audio) return;
                
                // Remove existing handlers and re-setup
                const $button = $(button);
                $button.off('click.volume');
                $(audio).off('volumechange.mementor');
                
                // Re-setup the volume control
                setupVolumeControl(button, audio);
                
                safeDebug('Fixed volume button', index);
            });
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error fixing volume buttons:', error);
        }
    };
    
    // Global helper function to fix all play buttons
    window.fixPlayButtons = function() {
        safeDebug('Fixing all play buttons');
        try {
            const playButtons = document.querySelectorAll('.mementor-tts-play-button');
            safeDebug('Found', playButtons.length, 'play buttons');
            
            playButtons.forEach(function(button, index) {
                safeDebug('Processing play button', index);
                
                // Find the audio element using DOM traversal
                const player = button.closest('.mementor-tts-player');
                if (!player) return;
                
                const audio = player.querySelector('audio');
                if (!audio) return;
                
                // Initialize the _isPlaying property and add debug listeners only once
                if (typeof audio._isPlaying === 'undefined') {
                    audio._isPlaying = false;
                    
                    // Check if debug listeners are already set up
                    if (!audio._debugListenersSetup) {
                        audio._debugListenersSetup = true;
                        
                        // Add event listeners to track play/pause state
                        audio.addEventListener('play', function() {
                            safeDebug('Audio play event triggered');
                            audio._isPlaying = true;
                            
                            // Update button to show pause icon
                            const icon = button.querySelector('.dashicons');
                            if (icon) {
                                icon.classList.remove('dashicons-controls-play', 'mementor-dashicons-controls-play');
                                icon.classList.add('dashicons-controls-pause', 'mementor-dashicons-controls-pause');
                            }
                        });
                        
                        audio.addEventListener('pause', function() {
                            safeDebug('Audio pause event triggered');
                            audio._isPlaying = false;
                            
                            // Update button to show play icon
                            const icon = button.querySelector('.dashicons');
                            if (icon) {
                                icon.classList.remove('dashicons-controls-pause', 'mementor-dashicons-controls-pause');
                                icon.classList.add('dashicons-controls-play', 'mementor-dashicons-controls-play');
                            }
                        });
                        
                        audio.addEventListener('ended', function() {
                            safeDebug('Audio ended event triggered');
                            audio._isPlaying = false;
                            audio.currentTime = 0; // Reset to beginning
                            
                            // Update button to show play icon
                            const icon = button.querySelector('.dashicons');
                            if (icon) {
                                icon.classList.remove('dashicons-controls-pause', 'mementor-dashicons-controls-pause');
                                icon.classList.add('dashicons-controls-play', 'mementor-dashicons-controls-play');
                            }
                        });
                    }
                }
                
                // Add click handler to button if it doesn't have one
                if (!button._hasClickHandler) {
                    button._hasClickHandler = true;
                    
                    button.addEventListener('click', function() {
                        safeDebug('Play button clicked, current state:', audio._isPlaying ? 'playing' : 'paused');
                        
                        if (!audio._isPlaying) {
                            safeDebug('Playing from current position:', audio.currentTime);
                            audio.play().catch(function(error) {
                                if (window.mementorTTSDebugEnabled) console.error('Error playing audio:', error);

                                // Try to reload and play again if there was an error
                                try {
                                    safeDebug('Attempting to reload and play again');
                                    audio.load();
                                    setTimeout(function() {
                                        audio.play().catch(function(retryError) {
                                            if (window.mementorTTSDebugEnabled) console.error('Error playing audio after retry:', retryError);
                                        });
                                    }, 100);
                                } catch (retryError) {
                                    if (window.mementorTTSDebugEnabled) console.error('Error during retry:', retryError);
                                }
                            });
                        } else {
                            safeDebug('Pausing at current position:', audio.currentTime);
                            audio.pause();
                        }
                    });
                }
                
                safeDebug('Fixed play button', index);
            });
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error fixing play buttons:', error);
        }
    };

    // Global helper function to fix HTML5 audio players
    window.fixHTML5Players = function() {
        safeDebug('Fixing HTML5 audio players');
        try {
            const audioElements = document.querySelectorAll('audio:not(.mementor-tts-player audio)');
            safeDebug('Found', audioElements.length, 'audio elements');
            
            audioElements.forEach(function(audio, index) {
                safeDebug('Processing audio element', index);
                
                // Initialize the _isPlaying property and add debug listeners only once
                if (typeof audio._isPlaying === 'undefined') {
                    audio._isPlaying = false;
                    
                    // Check if debug listeners are already set up
                    if (!audio._debugListenersSetup) {
                        audio._debugListenersSetup = true;
                        
                        // Add event listeners to track play/pause state
                        audio.addEventListener('play', function() {
                            safeDebug('Audio play event triggered');
                            audio._isPlaying = true;
                            
                            // Find and update related play buttons if any
                            if (audio._playButton) {
                                const icon = audio._playButton.querySelector('.dashicons');
                                if (icon) {
                                    icon.classList.remove('dashicons-controls-play', 'mementor-dashicons-controls-play');
                                    icon.classList.add('dashicons-controls-pause', 'mementor-dashicons-controls-pause');
                                }
                            }
                        });
                        
                        audio.addEventListener('pause', function() {
                            safeDebug('Audio pause event triggered');
                            audio._isPlaying = false;
                            
                            // Find and update related play buttons if any
                            if (audio._playButton) {
                                const icon = audio._playButton.querySelector('.dashicons');
                                if (icon) {
                                    icon.classList.remove('dashicons-controls-pause');
                                    icon.classList.add('dashicons-controls-play');
                                }
                            }
                        });
                        
                        audio.addEventListener('ended', function() {
                            safeDebug('Audio ended event triggered');
                            audio._isPlaying = false;
                            audio.currentTime = 0; // Reset to beginning
                            
                            // Find and update related play buttons if any
                            if (audio._playButton) {
                                const icon = audio._playButton.querySelector('.dashicons');
                                if (icon) {
                                    icon.classList.remove('dashicons-controls-pause');
                                    icon.classList.add('dashicons-controls-play');
                                }
                            }
                        });
                    }
                }
                
                // Look for associated play button
                const playButton = document.querySelector('[data-audio-id="' + audio.id + '"]');
                if (playButton) {
                    safeDebug('Found play button for audio element', index);
                    
                    // Store reference to the play button on the audio element
                    audio._playButton = playButton;
                    
                    // Add click handler to button if it doesn't have one
                    if (!playButton._hasClickHandler) {
                        playButton._hasClickHandler = true;
                        
                        playButton.addEventListener('click', function(e) {
                            e.preventDefault();
                            
                            safeDebug('Play button clicked, current state:', audio._isPlaying ? 'playing' : 'paused');
                            
                            if (!audio._isPlaying) {
                                safeDebug('Playing from current position:', audio.currentTime);
                                audio.play();
                            } else {
                                safeDebug('Pausing at current position:', audio.currentTime);
                                audio.pause();
                            }
                        });
                    }
                } else {
                    safeDebug('No play button found for audio element', index);
                }
            });
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error fixing HTML5 players:', error);
        }
    };

    // Add a polyfill for querySelector on audio elements
    function safeQuerySelector(element, selector) {
        try {
            // Check if querySelector exists and is a function
            if (element && element.querySelector && typeof element.querySelector === 'function') {
                return element.querySelector(selector);
            } else {
                // Fallback to jQuery
                return $(element).find(selector)[0] || null;
            }
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error in safeQuerySelector:', error);
            // Fallback to jQuery
            return $(element).find(selector)[0] || null;
        }
    }

    // Add a function to ensure dashicons are loaded
    window.ensureDashiconsLoaded = function() {
        safeDebug('Checking if dashicons are loaded');
        try {
            // Check if dashicons are loaded
            const dashiconsLoaded = document.querySelector('[href*="dashicons.min.css"]') !== null;
            safeDebug('Dashicons loaded:', dashiconsLoaded);
            
            if (!dashiconsLoaded) {
                safeDebug('Dashicons not loaded, adding them manually');
                
                // Create a link element for the dashicons
                const link = document.createElement('link');
                link.rel = 'stylesheet';
                link.id = 'mementor-tts-dashicons-css';
                link.href = typeof mementorTTSData !== 'undefined' && mementorTTSData.dashicons_url 
                    ? mementorTTSData.dashicons_url 
                    : '/wp-includes/css/dashicons.min.css';
                link.type = 'text/css';
                link.media = 'all';
                
                // Add to head
                document.head.appendChild(link);
                
                // Wait for it to load
                link.onload = function() {
                    safeDebug('Dashicons added manually');
                };
            }
            
            // Check if dashicons are visible
            const dashicons = document.querySelectorAll('.dashicons');
            safeDebug('Found', dashicons.length, 'dashicons');
            
            // Check if any dashicons have display: none
            dashicons.forEach(function(icon, index) {
                const style = window.getComputedStyle(icon);
                safeDebug('Dashicon', index, 'display:', style.display);
                
                if (style.display === 'none') {
                    safeDebug('Dashicon', index, 'is hidden, making it visible');
                    icon.style.display = 'inline-block';
                }
            });
            
            // Check if custom controls are visible
            const customControls = document.querySelectorAll('.mementor-tts-custom-controls');
            safeDebug('Found', customControls.length, 'custom controls');
            
            // Check if any custom controls have display: none
            customControls.forEach(function(control, index) {
                const style = window.getComputedStyle(control);
                safeDebug('Custom control', index, 'display:', style.display);
                
                if (style.display === 'none') {
                    safeDebug('Custom control', index, 'is hidden, making it visible');
                    control.style.display = 'flex';
                }
            });
            
            return true;
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error setting up dashicons:', error);
            return false;
        }
    };

    /**
     * Initialize shortcode players that have data-text attribute
     */
    function initializeShortcodePlayers() {
        // Also handle SHORTCODE players with pre-generated audio (data-audio-url)
        $('.mementor-tts-player-container[data-player-type="shortcode"] .mementor-tts-player[data-audio-url]').each(function() {
            const player = $(this);
            const preExistingAudioUrl = player.data('audio-url');
            
            safeDebug('Found player with pre-generated audio:', preExistingAudioUrl);
            
            // Check if player already has an audio element
            let audio = player.find('audio');
            if (audio.length === 0) {
                // Create audio element
                audio = $('<audio preload="metadata"></audio>');
                player.prepend(audio);
            }
            
            // Set the audio source
            if (preExistingAudioUrl && !audio.attr('src')) {
                audio.attr('src', preExistingAudioUrl);
            }
            
            // Initialize player controls
            initializePlayer(player[0]);
        });
        
        // Handle SHORTCODE players with text that need generation
        $('.mementor-tts-player-container[data-player-type="shortcode"] .mementor-tts-player[data-text]:not([data-audio-url])').each(function() {
            const player = $(this);
            const text = player.data('text');
            const elementUid = player.data('element-uid');
            const preExistingAudioUrl = player.data('audio-url');
            
            if (!text) return;
            
            // Check if player already has an audio element
            if (player.find('audio').length > 0) return;
            
            // Create audio element
            const audio = $('<audio preload="metadata"></audio>');
            player.prepend(audio);
            
            // Check if player already has controls (either custom or dynamically added)
            if (player.find('.mementor-tts-controls, .mementor-tts-custom-controls').length === 0) {
                const controls = $(`
                    <div class="mementor-tts-controls">
                        <button class="mementor-tts-play-button" aria-label="Play">
                            <span class="dashicons dashicons-controls-play mementor-dashicons mementor-dashicons-controls-play"></span>
                        </button>
                        <div class="mementor-tts-progress-container">
                            <div class="mementor-tts-progress-bar"></div>
                        </div>
                        <div class="mementor-tts-time-display">0:00</div>
                        <div class="mementor-tts-duration-display">0:00</div>
                        <button class="mementor-tts-volume-button" aria-label="Volume">
                            <span class="dashicons dashicons-controls-volumeon mementor-dashicons mementor-dashicons-controls-volumeon"></span>
                        </button>
                        <button class="mementor-tts-speed-button" aria-label="Playback Speed">1.0x</button>
                    </div>
                `);
                player.append(controls);
            }
            
            // Create message container for errors if it doesn't exist
            if (player.find('.mementor-tts-message-container').length === 0) {
                const messageContainer = $('<div class="mementor-tts-message-container"></div>');
                player.append(messageContainer);
            }
            
            // If we already have an audio URL, use it directly
            if (preExistingAudioUrl) {
                audio.attr('src', preExistingAudioUrl);
                initializePlayer(player[0]);
                return;
            }
            
            // Set up AJAX request to generate audio from text
            const playButton = player.find('.mementor-tts-play-button');
            
            if (playButton.length) {
                playButton.on('click', function(e) {
                    // If audio source is already set, use normal play functionality
                    if (audio.attr('src')) return;
                    
                    e.preventDefault();
                    e.stopPropagation();
                    
                    // Clear any error states
                    // Get the text with preserved line breaks
                    const textToSpeak = text;
                    
                    // Make AJAX request to generate audio
                    $.ajax({
                        url: mementorTTS.ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'mementor_tts_generate_shortcode_audio',
                            nonce: mementorTTS.nonce,
                            text: textToSpeak,
                            voice_id: player.data('voice-id') || '',
                            element_uid: elementUid || ''
                        },
                        success: function(response) {
                            if (response.success && response.data.file_url) {
                                // Set audio source and play
                                audio.attr('src', response.data.file_url);
                                
                                // Save the URL to the player's data attribute for future use
                                player.attr('data-audio-url', response.data.file_url);
                                
                                // Initialize player controls now that we have audio
                                initializePlayer(player[0]);
                                
                                // Remove loading state
                                playButton.removeClass('mementor-tts-loading mementor-tts-generating');
                                player.removeClass('is-generating');
                                playButton.find('.dashicons').removeClass('dashicons-update mementor-dashicons-update mementor-tts-spin').addClass('dashicons-controls-play mementor-dashicons-controls-play');
                                
                                // Trigger click again to play
                                playButton.trigger('click');
                            } else {
                                // Show error message in the UI
                                let errorMessage = response.data || 'Audio generation failed.';
                                player.addClass('has-error');
                                player.find('.mementor-tts-message-container').text(errorMessage).show();
                                playButton.removeClass('mementor-tts-loading');
                                playButton.find('.dashicons').removeClass('mementor-tts-spin dashicons-media-audio').addClass('dashicons-controls-play mementor-dashicons-controls-play');
                                
                                if (memtts_public_vars.debug) {
                                    console.error('TTS Error:', errorMessage);
                                }
                            }
                        },
                        error: function (xhr, status, error) {
                            // Parse error response
                            let errorMessage = 'An error occurred during audio generation.';
                            try {
                                let response = JSON.parse(xhr.responseText);
                                if (response && response.data) {
                                    errorMessage = response.data;
                                }
                            } catch (e) {
                                if (error) errorMessage = error;
                            }
                            
                            // Show error message in the UI
                            player.addClass('has-error');
                            player.find('.mementor-tts-message-container').text(errorMessage).show();
                            playButton.removeClass('mementor-tts-loading');
                            playButton.find('.dashicons').removeClass('mementor-tts-spin dashicons-media-audio').addClass('dashicons-controls-play');
                            
                            if (memtts_public_vars.debug) {
                                console.error('TTS Error:', errorMessage, xhr);
                            }
                        }
                    });
                });
            }
            
            // Add event listener for audio errors
            const audioElement = player.find('audio')[0];
            if (audioElement) {
                audioElement.addEventListener('error', function(e) {
                    let errorMessage = 'Audio playback error. Please try again.';
                    player.addClass('has-error');
                    player.find('.mementor-tts-message-container').text(errorMessage).show();
                    playButton.removeClass('mementor-tts-loading');
                    playButton.find('.dashicons').removeClass('mementor-tts-spin dashicons-media-audio').addClass('dashicons-controls-play');
                    
                    if (memtts_public_vars.debug) {
                        console.error('Audio element error:', e);
                    }
                });
            }
        });
    }

    /**
     * Initialize a single player element
     * 
     * @param {HTMLElement} playerElement - The player element to initialize
     */
    function initializePlayer(playerElement) {
        if (!playerElement) {
            if (window.mementorTTSDebugEnabled) console.error('Invalid player element');
            return;
        }
        
        safeDebug('Initializing player element:', playerElement);
        
        try {
            // Find the audio element
            const audioElement = safeQuerySelector(playerElement, 'audio');
            if (!audioElement) {
                if (window.mementorTTSDebugEnabled) console.error('No audio element found in player');
                return;
            }
            
            // Find the play button
            const playButton = safeQuerySelector(playerElement, '.mementor-tts-play-button');
            if (!playButton) {
                if (window.mementorTTSDebugEnabled) console.error('No play button found in player');
                return;
            }
            
            // Set up play button
            setupPlayButton(playButton, audioElement);
            
            // Set up progress bar if it exists
            const progressContainer = safeQuerySelector(playerElement, '.mementor-tts-progress-container');
            if (progressContainer) {
                safeDebug('Setting up progress bar');
                safeDebug('[TTS Init] Progress container found:', progressContainer);
                safeDebug('[TTS Init] Progress container children:', progressContainer.children);
                // Make sure we pass the DOM element, not a jQuery object
                setupProgressBar(progressContainer, audioElement);
            } else {
                safeDebug('[TTS Init] No progress container found in player');
            }
            
            // Set up time display if they exist
            const timeDisplay = safeQuerySelector(playerElement, '.mementor-tts-time-display');
            const durationDisplay = safeQuerySelector(playerElement, '.mementor-tts-duration-display');
            if (timeDisplay && durationDisplay) {
                safeDebug('Setting up time display');
                // Make sure we pass the DOM elements, not jQuery objects
                setupTimeDisplay(timeDisplay, durationDisplay, audioElement);
            }
            
            // Set up volume button if it exists
            const volumeButton = safeQuerySelector(playerElement, '.mementor-tts-volume-button');
            if (volumeButton) {
                safeDebug('Found volume button in player, setting up control');
                setupVolumeControl(volumeButton, audioElement);
            } else {
                safeDebug('No volume button found in player');
            }
            
            // Set up speed control if it exists
            const speedButton = safeQuerySelector(playerElement, '.mementor-tts-speed-button');
            if (speedButton) {
                setupSpeedControl(speedButton, audioElement);
            }
            
            // Set up download button if it exists
            const downloadButton = safeQuerySelector(playerElement, '.mementor-tts-download-button');
            if (downloadButton) {
                setupDownloadButton(downloadButton, audioElement);
            }
            
            // Fix info button
            const infoButton = playerElement.querySelector('.mementor-tts-info-button');
            if (infoButton) {
                $(infoButton).off('click').on('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    // Find or create the info popup
                    let infoPopup = document.querySelector('.mementor-tts-info-popup');
                    
                    // Create popup if it doesn't exist
                    if (!infoPopup) {
                        infoPopup = document.createElement('div');
                        infoPopup.className = 'mementor-tts-info-popup';
                        
                        const infoText = document.createElement('p');
                        infoText.innerHTML = 'Generated with Mementor\'s <a href="https://mementor.no/en/wordpress-plugins/text-to-speech/" target="_blank" rel="noopener"><strong>Text to Speech for WordPress plugin</strong></a>, using <a href="https://try.elevenlabs.io/mementor" target="_blank" rel="noopener"><strong>ElevenLabs</strong></a> technology.';
                        infoPopup.appendChild(infoText);
                        
                        // Append to body
                        document.body.appendChild(infoPopup);
                    }
                    
                    // Toggle visibility
                    const isVisible = infoPopup.classList.contains('tooltip-visible');
                    
                    // If currently visible, just hide it
                    if (isVisible) {
                        infoPopup.classList.remove('tooltip-visible');
                        return;
                    }
                    
                    // Remove all position classes
                    infoPopup.classList.remove('position-top-left', 'position-top-center', 'position-top-right');
                    
                    // Clear any inline styles that might be present
                    infoPopup.style.left = '';
                    infoPopup.style.top = '';
                    infoPopup.style.right = '';
                    infoPopup.style.bottom = '';
                    
                    // Get button position
                    const buttonRect = this.getBoundingClientRect();
                    
                    // Append to body
                    if (!infoPopup.parentElement || infoPopup.parentElement !== document.body) {
                        document.body.appendChild(infoPopup);
                    }
                    
                    // Position using CSS variables for precise positioning
                    infoPopup.style.setProperty('--button-x', `${buttonRect.left}px`);
                    infoPopup.style.setProperty('--button-y', `${buttonRect.top}px`);
                    infoPopup.style.setProperty('--button-width', `${buttonRect.width}px`);
                    infoPopup.style.setProperty('--button-right', `${buttonRect.right}px`);
                    
                    // Position the popup using classes
                    if (buttonRect.left < 150) {
                        // Button is near left edge
                        infoPopup.classList.add('position-top-left');
                    } else if (buttonRect.right > window.innerWidth - 150) {
                        // Button is near right edge
                        infoPopup.classList.add('position-top-right');
                    } else {
                        // Button is in the center area
                        infoPopup.classList.add('position-top-center');
                    }
                    
                    // Make visible
                    infoPopup.classList.add('tooltip-visible');
                    
                    // Close popup when clicking elsewhere
                    const handleOutsideClick = function(event) {
                        if (!infoPopup.contains(event.target) && event.target !== e.target) {
                            infoPopup.classList.remove('tooltip-visible');
                            document.removeEventListener('click', handleOutsideClick);
                        }
                    };
                    
                    // Set timeout to allow the current click to complete
                    setTimeout(() => {
                        document.addEventListener('click', handleOutsideClick);
                    }, 10);
                });
            }
            
            // Track player initialization (if statistics are enabled)
            const postId = getPostIdFromPlayer(playerElement);
            safeDebug('Player initialization - Post ID:', postId);
            
            if (postId) {
                safeDebug('Calling mementorTTSTrackEvent for player_init');
                mementorTTSTrackEvent(postId, 'player_init');
                
                // Set up event tracking for this audio element
                safeDebug('Calling mementorTTSSetupTracking');
                mementorTTSSetupTracking(audioElement, postId);
            } else {
                safeDebug('No post ID found for player, statistics tracking skipped');
            }
            
            safeDebug('Player initialized successfully');
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error initializing player:', error);
        }
    }

    /**
     * Initialize all audio players on the page
     */
    function initializePlayers() {
        safeDebug('Initializing all audio players');
        
        // First, try to find our custom players (exclude shortcode players as they're handled separately)
        const customPlayers = $('.mementor-tts-player:not([data-text])').filter(function() {
            // Only initialize if it's part of an auto-inserted player or doesn't have a player type
            const container = $(this).closest('.mementor-tts-player-container');
            const playerType = container.attr('data-player-type');
            return !playerType || playerType === 'auto-inserted';
        });
        safeDebug(`Found ${customPlayers.length} custom players`);
        
        customPlayers.each(function() {
            // Check if already initialized to avoid double initialization
            if (!$(this).data('player-initialized')) {
                initializePlayer(this);
                $(this).data('player-initialized', true);
            }
        });
        
        // Also look for any standalone audio elements that might be using native controls
        const standaloneAudio = $('audio').not('.mementor-tts-player audio');
        safeDebug(`Found ${standaloneAudio.length} standalone audio elements`);
        
        standaloneAudio.each(function() {
            const audio = this;
            
            // Add direct event listeners to the audio element
            try {
                // Make sure the audio has a source
                if (!audio.src && $(audio).find('source').length > 0) {
                    const sourceElement = $(audio).find('source')[0];
                    if (sourceElement && sourceElement.src) {
                        audio.src = sourceElement.src;
                        safeDebug('Set standalone audio source:', audio.src);
                    }
                }
                
                // Force a load of the audio to ensure it's ready
                if (audio.src) {
                    safeDebug('Loading standalone audio source:', audio.src);
                    audio.load();
                    
                    // Add play/pause event listeners
                    $(audio).on('play', function() {
                        safeDebug('Standalone audio playing');
                    });
                    
                    $(audio).on('pause', function() {
                        safeDebug('Standalone audio paused');
                    });
                    
                    $(audio).on('ended', function() {
                        safeDebug('Standalone audio ended');
                    });
                    
                    // Add direct click handler to the play button if it's a native player
                    const playButton = $(audio).siblings('button.plyr__control--overlaid, button.plyr__play, button[data-plyr="play"]');
                    if (playButton.length) {
                        playButton.on('click', function() {
                            safeDebug('Native play button clicked');
                            if (audio.paused) {
                                audio.play().catch(function(error) {
                                    if (window.mementorTTSDebugEnabled) console.error('Error playing standalone audio:', error);
                                });
                            } else {
                                audio.pause();
                            }
                        });
                    }
                }
            } catch (error) {
                if (window.mementorTTSDebugEnabled) console.error('Error setting up standalone audio:', error);
            }
        });
        
        // Add a global click handler for any play buttons
        $(document).on('click', '.mementor-tts-play-button, .plyr__control--overlaid, .plyr__play, [data-plyr="play"]', function(e) {
            safeDebug('Global play button clicked');
            const button = $(this);
            const player = button.closest('.mementor-tts-player, .plyr');
            
            // *** Add check for shortcode player ***
            if (player.closest('.mementor-tts-player-container[data-player-type="shortcode"]').length > 0) {
                safeDebug('Global handler ignoring click on shortcode player.');
                return; // Do nothing, let the specific shortcode handler manage it
            }
            // *********************************************
            
            const audio = player.find('audio')[0] || player.siblings('audio')[0] || player.get(0);
            
            if (audio) {
                try {
                    if (audio.paused) {
                        safeDebug('Playing audio via global handler');
                        audio.play().catch(function(error) {
                            if (window.mementorTTSDebugEnabled) console.error('Error playing audio via global handler:', error);
                        });
                    } else {
                        safeDebug('Pausing audio via global handler');
                        audio.pause();
                    }
                } catch (error) {
                    if (window.mementorTTSDebugEnabled) console.error('Error in global play button handler:', error);
                }
            }
        });
    }

    /**
     * Set up progress bar functionality
     * 
     * @param {HTMLElement} progressContainer - The progress container element
     * @param {HTMLElement} audio - The audio element
     */
    function setupProgressBar(progressContainer, audio) {
        if (!progressContainer || !audio) {
            if (window.mementorTTSDebugEnabled) console.error('Missing progress container or audio for progress bar setup');
            return;
        }
        
        try {
            // Find the progress bar element inside the container
            let progressBar = progressContainer.querySelector('.mementor-tts-progress-bar');
            
            // If not found directly, it might be in custom controls structure
            if (!progressBar) {
                const customControls = progressContainer.closest('.mementor-tts-custom-controls');
                if (customControls) {
                    progressBar = customControls.querySelector('.mementor-tts-progress-bar');
                }
            }
            
            if (!progressBar) {
                safeDebug('Progress bar element not found within container');
                return;
            }
            
            // Debug: log initial setup
            safeDebug('Setting up progress bar. Initial width:', progressBar.style.width);
            
            // Ensure the container has proper dimensions
            if (progressContainer.offsetHeight === 0) {
                progressContainer.style.height = '4px';
                progressContainer.style.position = 'relative';
            }
            
            // Ensure initial width is set and bar is visible with !important
            progressBar.setAttribute('style', 'width: 0% !important; position: absolute !important; left: 0 !important; top: 0 !important; height: 100% !important; transition: width 0.1s ease !important;');
            
            // Update progress bar on timeupdate
            const updateProgress = function() {
                if (!isNaN(audio.duration) && audio.duration > 0) {
                    const percent = (audio.currentTime / audio.duration) * 100;
                    
                    // Use setAttribute to ensure the style is applied with highest priority
                    progressBar.setAttribute('style', `width: ${percent}% !important; position: absolute !important; left: 0 !important; top: 0 !important; height: 100% !important; transition: width 0.1s ease !important;`);
                    
                    // Force a repaint to ensure the change is visible
                    progressBar.offsetHeight;
                }
            };
            
            // Remove any existing listeners
            $(audio).off('timeupdate.progressUpdate');
            audio.removeEventListener('timeupdate', updateProgress);
            
            // Add both jQuery and native listeners for compatibility
            $(audio).on('timeupdate.progressUpdate', updateProgress);
            audio.addEventListener('timeupdate', updateProgress);
            
            // Also update on play event to ensure immediate feedback
            $(audio).on('play.progressUpdate', updateProgress);
            
            // Handle click on progress bar container for seeking
            $(progressContainer).off('click.progressSeek').on('click.progressSeek', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                // Calculate the click position relative to the container width
                const containerRect = progressContainer.getBoundingClientRect();
                const clickPosition = e.clientX - containerRect.left;
                const containerWidth = containerRect.width;
                
                // Calculate the percentage of the container that was clicked
                const percentage = clickPosition / containerWidth;
                
                // Set the audio's current time based on the percentage
                if (!isNaN(audio.duration) && audio.duration > 0) {
                    audio.currentTime = percentage * audio.duration;
                    
                    // Update progress bar immediately for better visual feedback
                    progressBar.style.width = (percentage * 100) + '%';
                    
                    // Play audio if it was paused (optional feature)
                    if (audio.paused) {
                        audio.play().catch(function(error) {
                            if (window.mementorTTSDebugEnabled) console.error('Error playing audio after seek:', error);
                        });
                    }
                }
            });
            
            // Handle mouse move over progress bar for better user experience (optional)
            let isMouseDown = false;
            
            $(progressContainer).off('mousedown.progressDrag').on('mousedown.progressDrag', function(e) {
                isMouseDown = true;
                e.preventDefault(); // Prevent text selection
            });
            
            $(document).off('mouseup.progressDrag').on('mouseup.progressDrag', function() {
                isMouseDown = false;
            });
            
            $(progressContainer).off('mousemove.progressHover').on('mousemove.progressHover', function(e) {
                if (isMouseDown) {
                    // Same seeking logic as click, but triggered on drag
                    const containerRect = progressContainer.getBoundingClientRect();
                    const mousePosition = e.clientX - containerRect.left;
                    const containerWidth = containerRect.width;
                    const percentage = Math.max(0, Math.min(1, mousePosition / containerWidth));
                    
                    if (!isNaN(audio.duration) && audio.duration > 0) {
                        audio.currentTime = percentage * audio.duration;
                        progressBar.style.width = (percentage * 100) + '%';
                    }
                }
            });
            
            // Make sure initial progress is correct
            if (!isNaN(audio.duration) && audio.duration > 0 && audio.currentTime > 0) {
                const percent = (audio.currentTime / audio.duration) * 100;
                progressBar.style.width = percent + '%';
            } else {
                progressBar.style.width = '0%';
            }
            
            safeDebug('Progress bar setup complete');
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error setting up progress bar:', error);
        }
    }

    /**
     * Set up time display functionality
     * 
     * @param {HTMLElement} timeEl - The time display element
     * @param {HTMLElement} durationEl - The duration display element
     * @param {HTMLElement} audio - The audio element
     */
    function setupTimeDisplay(timeEl, durationEl, audio) {
        if (!timeEl || !durationEl || !audio) {
            if (window.mementorTTSDebugEnabled) console.error('Missing elements for time display setup');
            return;
        }
        
        try {
            // Set initial time display
            timeEl.textContent = '0:00';
            
            // Set duration display if available
            if (!isNaN(audio.duration) && audio.duration > 0) {
                durationEl.textContent = formatTime(audio.duration);
            } else {
                // Add loadedmetadata event to get duration once it's available
                $(audio).one('loadedmetadata', function() {
                    if (!isNaN(audio.duration) && audio.duration > 0) {
                        durationEl.textContent = formatTime(audio.duration);
                    }
                });
                
                // Fallback: check duration periodically in case loadedmetadata doesn't fire
                let durationCheckAttempts = 0;
                const maxAttempts = 10;
                
                const checkDuration = function() {
                    if (durationCheckAttempts >= maxAttempts) return;
                    
                    if (!isNaN(audio.duration) && audio.duration > 0) {
                        durationEl.textContent = formatTime(audio.duration);
                    } else {
                        durationCheckAttempts++;
                        setTimeout(checkDuration, 500);
                    }
                };
                
                setTimeout(checkDuration, 500);
            }
            
            // Update current time display during playback
            $(audio).off('timeupdate.timeDisplay').on('timeupdate.timeDisplay', function() {
                if (!isNaN(audio.currentTime)) {
                    timeEl.textContent = formatTime(audio.currentTime);
                }
            });
            
            // Update time display when seeking
            $(audio).off('seeking.timeDisplay seeking.timeDisplay').on('seeking.timeDisplay seeked.timeDisplay', function() {
                if (!isNaN(audio.currentTime)) {
                    timeEl.textContent = formatTime(audio.currentTime);
                }
            });
            
            safeDebug('Time display setup complete');
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error setting up time display:', error);
        }
    }

    /**
     * Set up volume button functionality
     */
    function setupVolumeControl(button, audio) {
        if (!button || !audio) {
            if (window.mementorTTSDebugEnabled) console.error('Missing button or audio for volume control');
            return;
        }
        
        try {
            // Ensure we're working with jQuery objects
            const $button = $(button);
            
            safeDebug('Setting up volume control, initial state:', {
                muted: audio.muted,
                volume: audio.volume
            });
            
            // Update initial icon state based on audio state
            if (audio.muted || audio.volume === 0) {
                $button.find('.dashicons')
                    .removeClass('dashicons-controls-volumeon mementor-dashicons-controls-volumeon')
                    .addClass('dashicons-controls-volumeoff mementor-dashicons-controls-volumeoff');
            } else {
                $button.find('.dashicons')
                    .removeClass('dashicons-controls-volumeoff mementor-dashicons-controls-volumeoff')
                    .addClass('dashicons-controls-volumeon mementor-dashicons-controls-volumeon');
            }
            
            // Add click handler - use off() then on() to avoid duplicates
            $button.off('click').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                safeDebug('Volume button clicked - current state:', audio.muted, audio.volume);
                
                if (audio.muted || audio.volume === 0) {
                    audio.muted = false;
                    audio.volume = 1.0;
                    $button.find('.dashicons')
                        .removeClass('dashicons-controls-volumeoff mementor-dashicons-controls-volumeoff')
                        .addClass('dashicons-controls-volumeon mementor-dashicons-controls-volumeon');
                } else {
                    audio.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 from other sources
            $(audio).on('volumechange', function() {
                if (audio.muted || audio.volume === 0) {
                    $button.find('.dashicons')
                        .removeClass('dashicons-controls-volumeon mementor-dashicons-controls-volumeon')
                        .addClass('dashicons-controls-volumeoff mementor-dashicons-controls-volumeoff');
                } else {
                    $button.find('.dashicons')
                        .removeClass('dashicons-controls-volumeoff mementor-dashicons-controls-volumeoff')
                        .addClass('dashicons-controls-volumeon mementor-dashicons-controls-volumeon');
                }
            });
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error setting up volume control:', error);
        }
    }

    /**
     * Set up speed button functionality
     */
    function setupSpeedControl(button, audio) {
        if (!button || !audio) {
            if (window.mementorTTSDebugEnabled) console.error('Missing button or audio for speed control');
            return;
        }

        try {
            // Ensure we're working with jQuery objects
            const $button = $(button);
            
            // Define speed options
            const speeds = [0.75, 1.0, 1.25, 1.5, 2.0];
            let currentSpeedIndex = 1; // Default 1.0x
            
            // Set initial text
            $button.text('1.0x');
            
            // Add click handler
            $button.off('click').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                try {
                    currentSpeedIndex = (currentSpeedIndex + 1) % speeds.length;
                    const newSpeed = speeds[currentSpeedIndex];
                    
                    audio.playbackRate = newSpeed;
                    $button.text(newSpeed + 'x');
                    safeDebug('Speed changed to:', newSpeed);
                } catch (error) {
                    if (window.mementorTTSDebugEnabled) console.error('Error handling speed button click:', error);
                }
                
                return false;
            });
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error setting up speed control:', error);
        }
    }

    /**
     * Set up download button functionality
     */
    function setupDownloadButton(button, audio) {
        if (!button || !audio) {
            if (window.mementorTTSDebugEnabled) console.error('Missing button or audio for download button');
            return;
        }

        try {
            // Ensure we're working with jQuery objects
            const $button = $(button);
            
            // Add click handler
            $button.off('click').on('click', function(e) {
                // Don't prevent default if it's an anchor with download attribute
                if (!$button.is('a[download]')) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    try {
                        const audioSrc = audio.src || ($(audio).find('source').attr('src'));
                        if (audioSrc) {
                            safeDebug('Downloading audio from:', audioSrc);
                            const a = document.createElement('a');
                            a.href = audioSrc;
                            a.download = 'audio-' + new Date().getTime() + '.mp3';
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a);
                        } else {
                            if (window.mementorTTSDebugEnabled) console.error('No audio source found for download');
                        }
                    } catch (error) {
                        if (window.mementorTTSDebugEnabled) console.error('Error handling download button click:', error);
                    }
                    
                    return false;
                }
            });
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error setting up download button:', error);
        }
    }

    /**
     * Format time in seconds to MM:SS format
     */
    function formatTime(seconds) {
        try {
            if (isNaN(seconds) || seconds === null || seconds === undefined) {
            return '0:00';
        }

        seconds = Math.floor(seconds);
        const minutes = Math.floor(seconds / 60);
        seconds = seconds % 60;

        return minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error formatting time:', error);
            return '0:00';
        }
    }

    /**
     * Sets up the play button for an audio element
     * 
     * @param {HTMLElement} button - The play button element
     * @param {HTMLElement} audio - The audio element
     */
    function setupPlayButton(button, audio) {
        if (!button || !audio) {
            if (window.mementorTTSDebugEnabled) console.error('Invalid button or audio element');
            return;
        }
        
        safeDebug('Setting up play button for audio element');
        
        // Initialize the _isPlaying property and add debug listeners only once
        if (typeof audio._isPlaying === 'undefined') {
            audio._isPlaying = false;
            
            // Check if debug listeners are already set up
            if (!audio._debugListenersSetup) {
                audio._debugListenersSetup = true;
                
                // Add event listeners to track play/pause state
                audio.addEventListener('play', function() {
                    safeDebug('Audio play event triggered');
                    audio._isPlaying = true;
                    
                    // Update all play buttons associated with this audio to show pause icon
                    $(audio).closest('.mementor-tts-player').find('.mementor-tts-play-button .dashicons')
                        .removeClass('dashicons-controls-play mementor-dashicons-controls-play')
                        .addClass('dashicons-controls-pause mementor-dashicons-controls-pause');
                });
                
                audio.addEventListener('pause', function() {
                    safeDebug('Audio pause event triggered');
                    audio._isPlaying = false;
                    
                    // Update all play buttons associated with this audio to show play icon
                    $(audio).closest('.mementor-tts-player').find('.mementor-tts-play-button .dashicons')
                        .removeClass('dashicons-controls-pause mementor-dashicons-controls-pause')
                        .addClass('dashicons-controls-play mementor-dashicons-controls-play');
                });
                
                audio.addEventListener('ended', function() {
                    safeDebug('Audio ended event triggered');
                    audio._isPlaying = false;
                    audio.currentTime = 0; // Reset to beginning only when ended
                    
                    // Update all play buttons associated with this audio to show play icon
                    $(audio).closest('.mementor-tts-player').find('.mementor-tts-play-button .dashicons')
                        .removeClass('dashicons-controls-pause mementor-dashicons-controls-pause')
                        .addClass('dashicons-controls-play mementor-dashicons-controls-play');
                });
            }
        }
        
        // Make sure the audio has a source
        try {
            if (!audio.src) {
                const sourceElement = safeQuerySelector(audio, 'source');
                if (sourceElement && sourceElement.src) {
                    safeDebug('Setting audio source from source element:', sourceElement.src);
                    audio.src = sourceElement.src;
                } else {
                    // Try jQuery as a fallback
                    const $source = $(audio).find('source');
                    if ($source.length && $source.attr('src')) {
                        safeDebug('Setting audio source from jQuery source element:', $source.attr('src'));
                        audio.src = $source.attr('src');
                    } else {
                        if (window.mementorTTSDebugEnabled) console.error('No source found for audio element');
                        return;
                    }
                }
            }
        } catch (error) {
            if (window.mementorTTSDebugEnabled) console.error('Error setting audio source:', error);
        }
        
        // Remove any existing click handlers to avoid duplicates
        $(button).off('click');
        
        // Add click handler
        $(button).on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            safeDebug('Play button clicked, current state:', audio._isPlaying ? 'playing' : 'paused');
            
            if (!audio._isPlaying) {
                // If paused, play from current position
                safeDebug('Playing from current position:', audio.currentTime);
                audio.play().catch(function(error) {
                    if (window.mementorTTSDebugEnabled) console.error('Error playing audio:', error);

                    // Try to reload and play again if there was an error
                    try {
                        safeDebug('Attempting to reload and play again');
                        audio.load();
                        setTimeout(function() {
                            audio.play().catch(function(retryError) {
                                if (window.mementorTTSDebugEnabled) console.error('Error playing audio after retry:', retryError);
                            });
                        }, 100);
                    } catch (retryError) {
                        if (window.mementorTTSDebugEnabled) console.error('Error during retry:', retryError);
                    }
                });
            } else {
                // If playing, pause at current position
                safeDebug('Pausing at current position:', audio.currentTime);
                audio.pause();
            }
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        // Initialize all players
        document.querySelectorAll('.mementor-tts-preview-player').forEach(function(playerContainer) {
            // Get label settings from mementorTTSData
            var showLabel = window.mementorTTSData ? window.mementorTTSData.showLabel : '0';
            var labelPosition = window.mementorTTSData ? window.mementorTTSData.labelPosition : 'left';
            var labelText = window.mementorTTSData ? window.mementorTTSData.labelText : 'Listen to this article:';
            var label = playerContainer.querySelector('.mementor-tts-player-label');
            
            // Create label if it doesn't exist and should be shown
            if (showLabel === '1' && !label) {
                label = document.createElement('div');
                label.className = 'mementor-tts-player-label text-' + labelPosition;
                label.textContent = labelText;
                playerContainer.insertBefore(label, playerContainer.firstChild);
            }
            
            // Update existing label
            if (label) {
                // Update label visibility
                label.style.display = showLabel === '1' ? 'block' : 'none';
                
                // Update label position class
                label.className = 'mementor-tts-player-label text-' + labelPosition;
                
                // Update label text
                label.textContent = labelText;
            }
            
            // Initialize player controls
            initializePlayer(playerContainer);
        });
    });

    // Add a global debug function to help troubleshoot player control issues
    window.debugMementorTTSControls = function() {
        safeDebug('=== Mementor TTS Controls Debug ===');
        
        // Find all players on the page
        const players = document.querySelectorAll('.mementor-tts-player');
        safeDebug(`Found ${players.length} players to debug`);
        
        players.forEach(function(player, index) {
            safeDebug(`Player #${index + 1}:`);
            
            // Check for audio element
            const audio = player.querySelector('audio');
            if (!audio) {
                if (window.mementorTTSDebugEnabled) console.error(`Player #${index + 1} has no audio element!`);
                return;
            }
            
            safeDebug(`Audio element:`, {
                src: audio.src || (audio.querySelector('source') ? audio.querySelector('source').src : 'No source'),
                duration: audio.duration,
                paused: audio.paused,
                muted: audio.muted,
                volume: audio.volume,
                playbackRate: audio.playbackRate
            });
            
            // Check for controls
            const controls = player.querySelector('.mementor-tts-custom-controls');
            if (!controls) {
                if (window.mementorTTSDebugEnabled) console.error(`Player #${index + 1} has no controls element!`);
                return;
            }
            
            // Check for buttons
            const volumeButton = controls.querySelector('.mementor-tts-volume-button');
            const speedButton = controls.querySelector('.mementor-tts-speed-button');
            const downloadButton = controls.querySelector('.mementor-tts-download-button');
            
            safeDebug(`Control buttons:`, {
                volumeButton: !!volumeButton,
                speedButton: !!speedButton,
                downloadButton: !!downloadButton
            });
            
            // Try to fix volume button
            if (volumeButton) {
                safeDebug(`Fixing volume button for player #${index + 1}`);
                $(volumeButton).off('click').on('click', function(e) {
                    e.preventDefault();
                    safeDebug(`Volume button clicked - muted: ${audio.muted}, volume: ${audio.volume}`);
                    
                    if (audio.muted || audio.volume === 0) {
                        audio.muted = false;
                        audio.volume = 1.0;
                        safeDebug(`Unmuted - muted: ${audio.muted}, volume: ${audio.volume}`);
                        $(volumeButton).find('.dashicons')
                            .removeClass('dashicons-controls-volumeoff')
                            .addClass('dashicons-controls-volumeon');
                    } else {
                        audio.muted = true;
                        safeDebug(`Muted - muted: ${audio.muted}, volume: ${audio.volume}`);
                        $(volumeButton).find('.dashicons')
                            .removeClass('dashicons-controls-volumeon')
                            .addClass('dashicons-controls-volumeoff');
                    }
                });
            }
            
            // Try to fix speed button
            if (speedButton) {
                safeDebug(`Fixing speed button for player #${index + 1}`);
                
                // Define speeds
                const speeds = [0.75, 1.0, 1.25, 1.5, 2.0];
                let currentSpeedIndex = 1; // Default 1.0x
                
                $(speedButton).off('click').on('click', function(e) {
                    e.preventDefault();
                    safeDebug(`Speed button clicked - current speed: ${audio.playbackRate}`);
                    
                    currentSpeedIndex = (currentSpeedIndex + 1) % speeds.length;
                    const newSpeed = speeds[currentSpeedIndex];
                    
                    audio.playbackRate = newSpeed;
                    $(speedButton).text(newSpeed + 'x');
                    safeDebug(`Speed changed to: ${newSpeed}`);
                });
            }
            
            // Try to fix download button
            if (downloadButton) {
                safeDebug(`Fixing download button for player #${index + 1}`);
                $(downloadButton).off('click').on('click', function(e) {
                    e.preventDefault();
                    safeDebug(`Download button clicked`);
                    
                    const audioSrc = audio.src || ($(audio).find('source').attr('src'));
                    if (audioSrc) {
                        safeDebug(`Downloading audio from: ${audioSrc}`);
                        const a = document.createElement('a');
                        a.href = audioSrc;
                        a.download = 'audio-' + new Date().getTime() + '.mp3';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    } else {
                        if (window.mementorTTSDebugEnabled) console.error(`No audio source found for download`);
                    }
                });
            }
        });
        
        // Add a global click handler for specific button types
        $(document).off('click.safeDebug').on('click.safeDebug', '.mementor-tts-volume-button, .mementor-tts-speed-button, .mementor-tts-download-button', function(e) {
            const buttonType = this.className.match(/mementor-tts-(volume|speed|download)-button/)[0];
            safeDebug(`Global handler detected click on: ${buttonType}`);
        });
        
        safeDebug('=== Manual debug controls added! ===');
        
        return 'Debug controls initialized successfully. Try clicking the volume, speed, or download buttons.';
    };

    /**
     * Fix controls for all players on the page
     * This ensures that volume, speed, and download buttons work properly
     */
    function fixPlayerControls() {
        safeDebug('Fixing player controls for all players');
        
        // Find all players on the page
        const players = document.querySelectorAll('.mementor-tts-player');
        
        players.forEach(function(player, index) {
            const audio = player.querySelector('audio');
            if (!audio) return;
            
            // Fix volume button - just re-setup the control properly
            const volumeButton = player.querySelector('.mementor-tts-volume-button');
            if (volumeButton) {
                // Remove all existing handlers first
                $(volumeButton).off('click');
                $(audio).off('volumechange');
                
                // Re-setup using the main function
                setupVolumeControl(volumeButton, audio);
            }
            
            // Fix speed button
            const speedButton = player.querySelector('.mementor-tts-speed-button');
            if (speedButton) {
                const speeds = [0.75, 1.0, 1.25, 1.5, 2.0];
                let currentSpeedIndex = 1; // Default 1.0x
                
                $(speedButton).off('click').on('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    currentSpeedIndex = (currentSpeedIndex + 1) % speeds.length;
                    const newSpeed = speeds[currentSpeedIndex];
                    
                    audio.playbackRate = newSpeed;
                    $(speedButton).text(newSpeed + 'x');
                    safeDebug('Speed changed to:', newSpeed);
                });
            }
            
            // Fix download button - use the built-in download attribute
            const downloadButton = player.querySelector('.mementor-tts-download-button');
            if (downloadButton && !downloadButton.hasAttribute('download')) {
                const audioSrc = audio.src || (audio.querySelector('source') ? audio.querySelector('source').src : '');
                if (audioSrc) {
                    downloadButton.href = audioSrc;
                    downloadButton.setAttribute('download', 'audio-' + Date.now() + '.mp3');
                }
            }
            
            // Fix info button
            const infoButton = player.querySelector('.mementor-tts-info-button');
            if (infoButton) {
                $(infoButton).off('click').on('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    // Find or create the info popup
                    let infoPopup = document.querySelector('.mementor-tts-info-popup');
                    
                    // Create popup if it doesn't exist
                    if (!infoPopup) {
                        infoPopup = document.createElement('div');
                        infoPopup.className = 'mementor-tts-info-popup';
                        
                        const infoText = document.createElement('p');
                        infoText.innerHTML = 'Generated with Mementor\'s <a href="https://mementor.no/en/wordpress-plugins/text-to-speech/" target="_blank" rel="noopener"><strong>Text to Speech for WordPress plugin</strong></a>, using <a href="https://try.elevenlabs.io/mementor" target="_blank" rel="noopener"><strong>ElevenLabs</strong></a> technology.';
                        infoPopup.appendChild(infoText);
                        
                        // Append to body
                        document.body.appendChild(infoPopup);
                    }
                    
                    // Toggle visibility
                    const isVisible = infoPopup.classList.contains('tooltip-visible');
                    
                    // If currently visible, just hide it
                    if (isVisible) {
                        infoPopup.classList.remove('tooltip-visible');
                        return;
                    }
                    
                    // Remove all position classes
                    infoPopup.classList.remove('position-top-left', 'position-top-center', 'position-top-right');
                    
                    // Clear any inline styles that might be present
                    infoPopup.style.left = '';
                    infoPopup.style.top = '';
                    infoPopup.style.right = '';
                    infoPopup.style.bottom = '';
                    
                    // Get button position
                    const buttonRect = this.getBoundingClientRect();
                    
                    // Append to body
                    if (!infoPopup.parentElement || infoPopup.parentElement !== document.body) {
                        document.body.appendChild(infoPopup);
                    }
                    
                    // Position using CSS variables for precise positioning
                    infoPopup.style.setProperty('--button-x', `${buttonRect.left}px`);
                    infoPopup.style.setProperty('--button-y', `${buttonRect.top}px`);
                    infoPopup.style.setProperty('--button-width', `${buttonRect.width}px`);
                    infoPopup.style.setProperty('--button-right', `${buttonRect.right}px`);
                    
                    // Position the popup using classes
                    if (buttonRect.left < 150) {
                        // Button is near left edge
                        infoPopup.classList.add('position-top-left');
                    } else if (buttonRect.right > window.innerWidth - 150) {
                        // Button is near right edge
                        infoPopup.classList.add('position-top-right');
                    } else {
                        // Button is in the center area
                        infoPopup.classList.add('position-top-center');
                    }
                    
                    // Make visible
                    infoPopup.classList.add('tooltip-visible');
                    
                    // Close popup when clicking elsewhere
                    const handleOutsideClick = function(event) {
                        if (!infoPopup.contains(event.target) && event.target !== e.target) {
                            infoPopup.classList.remove('tooltip-visible');
                            document.removeEventListener('click', handleOutsideClick);
                        }
                    };
                    
                    // Set timeout to allow the current click to complete
                    setTimeout(() => {
                        document.addEventListener('click', handleOutsideClick);
                    }, 10);
                });
            }
            
            // Fix progress bar
            const progressContainer = player.querySelector('.mementor-tts-progress-container');
            if (progressContainer) {
                safeDebug('Fixing progress bar for player');
                // Find the progress bar element
                const progressBar = progressContainer.querySelector('.mementor-tts-progress-bar');
                if (progressBar) {
                    // Ensure current progress is displayed correctly
                    const updateProgress = function() {
                        if (!isNaN(audio.duration) && audio.duration > 0) {
                            const percent = (audio.currentTime / audio.duration) * 100;
                            progressBar.style.width = percent + '%';
                        } else {
                            progressBar.style.width = '0%';
                        }
                    };
                    
                    // Update progress on timeupdate
                    $(audio).off('timeupdate.fixedProgress').on('timeupdate.fixedProgress', updateProgress);
                    
                    // Handle click on progress bar for seeking
                    $(progressContainer).off('click.fixedSeek').on('click.fixedSeek', function(e) {
                        e.preventDefault();
                        
                        const containerRect = progressContainer.getBoundingClientRect();
                        const clickPosition = e.clientX - containerRect.left;
                        const containerWidth = containerRect.width;
                        const percentage = clickPosition / containerWidth;
                        
                        if (!isNaN(audio.duration) && audio.duration > 0) {
                            audio.currentTime = percentage * audio.duration;
                            progressBar.style.width = (percentage * 100) + '%';
                        }
                    });
                    
                    // Handle drag on progress bar
                    let isMouseDown = false;
                    
                    $(progressContainer).off('mousedown.fixedDrag').on('mousedown.fixedDrag', function(e) {
                        isMouseDown = true;
                        e.preventDefault();
                    });
                    
                    $(document).off('mouseup.fixedDrag').on('mouseup.fixedDrag', function() {
                        isMouseDown = false;
                    });
                    
                    $(progressContainer).off('mousemove.fixedDrag').on('mousemove.fixedDrag', function(e) {
                        if (isMouseDown) {
                            const containerRect = progressContainer.getBoundingClientRect();
                            const mousePosition = e.clientX - containerRect.left;
                            const containerWidth = containerRect.width;
                            const percentage = Math.max(0, Math.min(1, mousePosition / containerWidth));
                            
                            if (!isNaN(audio.duration) && audio.duration > 0) {
                                audio.currentTime = percentage * audio.duration;
                                progressBar.style.width = (percentage * 100) + '%';
                            }
                        }
                    });
                    
                    // Run update once
                    updateProgress();
                }
            }

            // Fix time display
            const timeDisplay = player.querySelector('.mementor-tts-time-display');
            const durationDisplay = player.querySelector('.mementor-tts-duration-display');
            
            if (timeDisplay && durationDisplay) {
                safeDebug('Fixing time display for player');
                
                // Set initial time display
                timeDisplay.textContent = formatTime(audio.currentTime || 0);
                
                // Set duration display if available
                if (!isNaN(audio.duration) && audio.duration > 0) {
                    durationDisplay.textContent = formatTime(audio.duration);
                } else {
                    // Listen for duration to become available
                    $(audio).one('loadedmetadata', function() {
                        if (!isNaN(audio.duration) && audio.duration > 0) {
                            durationDisplay.textContent = formatTime(audio.duration);
                        }
                    });
                }
                
                // Update time display during playback
                $(audio).off('timeupdate.fixedTimeDisplay').on('timeupdate.fixedTimeDisplay', function() {
                    timeDisplay.textContent = formatTime(audio.currentTime);
                });
                
                // Update time display when seeking
                $(audio).off('seeking.fixedTimeDisplay seeked.fixedTimeDisplay').on('seeking.fixedTimeDisplay seeked.fixedTimeDisplay', function() {
                    timeDisplay.textContent = formatTime(audio.currentTime);
                });
                
                // Reset time display when playback ends
                $(audio).off('ended.fixedTimeDisplay').on('ended.fixedTimeDisplay', function() {
                    timeDisplay.textContent = '0:00';
                });
            }
        });
    }

});
