/**
 * JavaScript for the Text to Speech Generator admin page
 *
 * Handles tab switching, character counting, AJAX requests for audio generation,
 * voice metadata fetching, and clipboard copy functionality
 *
 * @package    Mementor_TTS
 * @subpackage Mementor_TTS/admin/js
 */

// EMERGENCY STOP FUNCTION - can be called from browser console if audio gets stuck
window.emergencyStopTTSAudio = function() {
    try {
        // Stop current history audio
        if (window.currentHistoryAudio) {
            window.currentHistoryAudio.pause();
            window.currentHistoryAudio.currentTime = 0;
            window.currentHistoryAudio.src = '';
            window.currentHistoryAudio.load();
            delete window.currentHistoryAudio;
            window.currentHistoryAudio = null;
        }
        
        // Find and stop ALL audio elements on page
        var allAudio = document.querySelectorAll('audio');
        for (var i = 0; i < allAudio.length; i++) {
            try {
                allAudio[i].pause();
                allAudio[i].currentTime = 0;
                allAudio[i].src = '';
                allAudio[i].load();
            } catch(e) {
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Error stopping audio element:', e);
            }
        }
        
        // Reset all history play buttons
        jQuery('.mementor-tts-history-btn-play').each(function() {
            jQuery(this).html('<span class="dashicons dashicons-controls-play"></span> Play');
            jQuery(this).prop('disabled', false);
        });
        
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('EMERGENCY STOP: All audio stopped, buttons reset');
    } catch (e) {
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Emergency stop error:', e);
    }
};

jQuery(document).ready(function($) {
    // Initialize jQuery UI components
    if ($.ui && $.ui.dialog) {
        // Set default dialog options
        $.ui.dialog.prototype._allowInteraction = function(event) {
            return true;
        };
    } else {
        if (window.mementorTTSDebug) window.mementorTTSDebug.error('jQuery UI Dialog not available');
    }
    
    // Variables for audio playback
    var audio = new Audio();
    var audioSrc = null;
    
    // Define the default audio source using the localized plugin URL
    var defaultAudioSrc = (typeof mementorTtsGenerator !== 'undefined' && mementorTtsGenerator.pluginUrl ? mementorTtsGenerator.pluginUrl : '/wp-content/plugins/text-to-speech-tts/') + 'admin/audio/v3-intro.mp3';
    if (window.mementorTTSDebug) window.mementorTTSDebug.log('Default audio source:', defaultAudioSrc);
    
    var currentlyPlaying = false;
    var audioGenerated = false;
    var textArea = $('#mementor-tts-text');
    var currentCharsElement = $('#mementor-tts-current-chars');
    
    
    // Initialize button states
    $('#mementor-tts-download-btn').prop('disabled', true);
    
    // Add custom CSS for the green button state
    $('<style>\n.mementor-tts-generate-btn { background-color: #009b51 !important; border-color: #008043 !important; }\n</style>').appendTo('head');
    
    // Helper function to update the play button text consistently
    function updatePlayButtonText(state) {
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Updating button text to:', state);
        var buttonIcon = $('#mementor-tts-play-btn .dashicons');
        var buttonText = $('#mementor-tts-play-btn .button-text');
        var playButton = $('#mementor-tts-play-btn');
        
        // First remove all state-specific classes
        playButton.removeClass('mementor-tts-generate-btn');
        
        switch(state) {
            case 'generate':
                buttonIcon.removeClass('dashicons-controls-pause dashicons-update dashicons-update-loading').addClass('dashicons-controls-play');
                buttonText.text('Generate Audio');
                playButton.addClass('mementor-tts-generate-btn');
                break;
            case 'play':
                buttonIcon.removeClass('dashicons-controls-pause dashicons-update dashicons-update-loading').addClass('dashicons-controls-play');
                buttonText.text('Play Demo');
                break;
            case 'play_generated':
                buttonIcon.removeClass('dashicons-controls-pause dashicons-update dashicons-update-loading').addClass('dashicons-controls-play');
                buttonText.text('Play Generated Audio');
                break;
            case 'pause':
                buttonIcon.removeClass('dashicons-controls-play dashicons-update dashicons-update-loading').addClass('dashicons-controls-pause');
                buttonText.text('Pause');
                break;
            case 'generating':
                buttonIcon.removeClass('dashicons-controls-play dashicons-controls-pause').addClass('dashicons-update dashicons-update-loading');
                buttonText.text('Generating...');
                break;
            default:
                if (window.mementorTTSDebug) window.mementorTTSDebug.error('Unknown button state:', state);
        }
    }
    
    // Function to show message
    function showMessage(message, type) {
        const messageElem = $('<div class="mementor-tts-message ' + type + '">' + message + '</div>');
        $('#mementor-tts-messages').append(messageElem);

        // Also show errors inline in the generator area for visibility
        if (type === 'error') {
            var inlineError = $('#mementor-tts-inline-error');
            if (inlineError.length) {
                inlineError.text(message).show();
                setTimeout(function() {
                    inlineError.fadeOut(300);
                }, 5000);
            }
        }

        // Auto-hide after 8 seconds
        setTimeout(function() {
            messageElem.css('animation', 'fadeOutRight 0.3s ease-out');
            setTimeout(function() {
                messageElem.remove();
            }, 300);
        }, 8000);
    }
    
    
    // Textarea input event for character counting and button text toggling
    $('#mementor-tts-text').on('input', function() {
        const textarea = $(this);
        const text = textarea.val();
        const maxLength = textarea.attr('maxlength');
        const currentLength = text.length;
        const defaultText = textarea.attr('data-default-text');
        
        // Update counter
        $('#mementor-tts-current-chars').text(currentLength);
        
        // Update play button text based on content matching default text
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Textarea changed. Current text matches default:', text === defaultText);
        if (text !== defaultText) {
            updatePlayButtonText('generate');
        } else {
            updatePlayButtonText('play');
        }
    });
    
    // Trigger input event on load to initialize play button text
    textArea.trigger('input');

    // Tab switching with audio state management
    $('.mementor-tts-tab').on('click', function() {
        const tabId = $(this).data('tab');
        
        // Update active tab
        $('.mementor-tts-tab').removeClass('active');
        $(this).addClass('active');
        
        // Show corresponding tab content
        $('.mementor-tts-tab-content').hide();
        $('#' + tabId).show();
        
        // Special handling for text input tab
        if (tabId === 'text-input') {
            // When switching to the text input tab, check if text matches default
            // and update the play button text accordingly
            const textarea = $('#mementor-tts-text');
            const currentText = textarea.val();
            const defaultText = textarea.attr('data-default-text');
            
            if (currentText !== defaultText) {
                updatePlayButtonText('generate');
            } else {
                updatePlayButtonText('play');
            }
        }
    });
    
    // Play/Pause button functionality
    $('#mementor-tts-play-btn').on('click', function() {
        const button = $(this);
        
        if (window.mementorTTSDebug) {
            window.mementorTTSDebug.log('Play button clicked');
            window.mementorTTSDebug.log('Button text:', button.find('.button-text').text());
            window.mementorTTSDebug.log('audioGenerated:', audioGenerated);
            window.mementorTTSDebug.log('audioSrc:', audioSrc);
            window.mementorTTSDebug.log('currentlyPlaying:', currentlyPlaying);
        }
        
        if (button.hasClass('loading')) return; // Prevent multiple clicks while loading
        
        const textarea = $('#mementor-tts-text');
        const text = textarea.val();
        if (text.trim() === '') return; // Don't process empty text
        
        // Check if need to generate new audio or play existing
        const defaultText = textArea.attr('data-default-text');
        // Only regenerate if text has changed AND we're not just resuming a paused audio
        const needsGenerate = (text !== defaultText) && !(audio.src && audioGenerated);
        
        // If audio is currently playing, pause it
        if (currentlyPlaying) {
            audio.pause();
            currentlyPlaying = false;
            
            // Always use correct text for button after pause
            if (audioGenerated) {
                updatePlayButtonText('play_generated');
            } else {
                const currentText = $('#mementor-tts-text').val();
                const defaultText = $('#mementor-tts-text').attr('data-default-text');
                
                if (currentText !== defaultText) {
                    updatePlayButtonText('generate');
                } else {
                    updatePlayButtonText('play');
                }
            }
            
            if (window.mementorTTSDebug) window.mementorTTSDebug.log('Pausing audio at position:', audio.currentTime);
            return;
        }
        
        if (textArea.val() === defaultText && !audioGenerated) {
            if (window.mementorTTSDebug) window.mementorTTSDebug.log('Playing default audio:', defaultAudioSrc);
            
            // Set audio source and prepare for playback
            audio.src = defaultAudioSrc;
            audioSrc = defaultAudioSrc;
            
            currentlyPlaying = true;
            updatePlayButtonText('pause');
            $('#mementor-tts-download-btn').prop('disabled', false);
            
// Play the audio
            audio.play().then(function() {
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Audio playback started');
            }).catch(function(error) {
                if (window.mementorTTSDebug) window.mementorTTSDebug.error('Error playing default audio:', error);
                alert('Error playing default audio. Please check the console for details.');
                
                // Reset UI state on error
                currentlyPlaying = false;
                updatePlayButtonText('play');
            });

            return;
        }

        // Generate new audio if text is changed
        if (!audioGenerated) {
            // Clear any previous inline error
            $('#mementor-tts-inline-error').hide().empty();

            // Disable play button during generation
            $(this).prop('disabled', true);
            updatePlayButtonText('generating');

            // Check if intro/outro checkboxes exist and get their values FIRST
            // (before generating element UID so we can include them in the filename)
            var includeIntroCheckbox = $('#mementor-tts-include-intro');
            var includeOutroCheckbox = $('#mementor-tts-include-outro');
            var includeIntro = includeIntroCheckbox.length ? (includeIntroCheckbox.is(':checked') ? '1' : '0') : '1';
            var includeOutro = includeOutroCheckbox.length ? (includeOutroCheckbox.is(':checked') ? '1' : '0') : '1';

            // Generate a unique element ID for shortcode text
            // Use shorter timestamp (last 6 digits) and random string (5 chars)
            // Include intro/outro state to create unique files for different configurations
            const timestamp = Date.now().toString().slice(-6);
            const randomStr = Math.random().toString(36).substr(2, 5);
            var elementUid = 'shortcode_' + timestamp + '_' + randomStr;

            // Add suffixes based on intro/outro inclusion to create unique filenames
            if (includeIntro === '0' || includeOutro === '0') {
                if (includeIntro === '0' && includeOutro === '0') {
                    elementUid += '_noio'; // no intro, no outro
                } else if (includeIntro === '0') {
                    elementUid += '_noi'; // no intro
                } else if (includeOutro === '0') {
                    elementUid += '_noo'; // no outro
                }
            }

            // Get voice ID from hidden field first, then fall back to JavaScript objects
            const voiceId = $('#mementor-tts-voice-id').val() ||
                           (typeof mementorTtsGenerator !== 'undefined' && mementorTtsGenerator.currentVoiceId) ||
                           (typeof mementorTTS !== 'undefined' && mementorTTS.voice_id) ||
                           '';

            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Voice ID from hidden field:', $('#mementor-tts-voice-id').val());
                window.mementorTTSDebug.log('Voice ID being used:', voiceId);
                window.mementorTTSDebug.log('Text being sent:', text);
                window.mementorTTSDebug.log('Element UID:', elementUid);
            }

            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Include intro checkbox exists:', includeIntroCheckbox.length > 0);
                window.mementorTTSDebug.log('Include intro checked:', includeIntro);
                window.mementorTTSDebug.log('Include outro checkbox exists:', includeOutroCheckbox.length > 0);
                window.mementorTTSDebug.log('Include outro checked:', includeOutro);
            }

            // Prepare data object for debugging
            const ajaxData = {
                action: 'mementor_tts_generate_shortcode_audio',
                text: text,
                element_uid: elementUid,
                voice_id: voiceId,
                nonce: (typeof mementorTtsGenerator !== 'undefined' && mementorTtsGenerator.nonce) || '',
                include_intro: includeIntro,
                include_outro: includeOutro
            };

            if (window.mementorTTSDebug) window.mementorTTSDebug.log('Full AJAX data being sent:', ajaxData);
            
            // Make AJAX call to generate audio
            $.ajax({
                url: (typeof mementorTtsGenerator !== 'undefined' && mementorTtsGenerator.ajaxUrl) || ajaxurl || '/wp-admin/admin-ajax.php',
                type: 'POST',
                data: ajaxData,
                success: function(response) {
                    if (window.mementorTTSDebug) {
                        window.mementorTTSDebug.log('Audio generation response:', response);
                        window.mementorTTSDebug.log('Response type:', typeof response);
                        window.mementorTTSDebug.log('Response success:', response.success);
                        window.mementorTTSDebug.log('Response data:', response.data);
                    }
                    
                    if (response.success && response.data && (response.data.audio_url || response.data.file_url)) {
                        // Handle both audio_url and file_url for compatibility
                        const generatedAudioUrl = response.data.audio_url || response.data.file_url;
                        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Audio generated successfully at:', generatedAudioUrl);
                        
                        // Enable buttons after successful generation
                        $('#mementor-tts-play-btn').prop('disabled', false);
                        updatePlayButtonText('play_generated');
                        $('#mementor-tts-download-btn').prop('disabled', false);

                        // Set flag that audio has been generated
                        audioGenerated = true;
                        
                        // Set the audio source from the response
                        audioSrc = generatedAudioUrl;
                        audio.src = audioSrc;
                        
                        // Show success modal if available, otherwise use legacy message
                        if (window.mementorTTSModalUtils && window.mementorTTSModalUtils.showAudioGeneratedSuccess) {
                            // Extract credits info if available
                            var creditsUsed = response.data.credits_used;
                            var remainingCredits = response.data.remaining_credits;
                            window.mementorTTSModalUtils.showAudioGeneratedSuccess(null, creditsUsed, remainingCredits);
                        } else {
                            showMessage('Audio generated successfully!', 'success');
                        }
                        
                        // Update the shortcode display using the function
                        updateShortcodeDisplay();
                        
                        // Add to history
                        var currentShortcode = $('#mementor-tts-shortcode-realtime').text();
                        var currentVoiceName = $('#mementor-tts-voice-name').text();
                        HistoryManager.addToHistory(text, currentShortcode, voiceId, currentVoiceName, generatedAudioUrl, elementUid);

                        // Automatically trigger play after generation
                        setTimeout(function() {
                            if (window.mementorTTSDebug) {
                                window.mementorTTSDebug.log('Auto-triggering play button click');
                                window.mementorTTSDebug.log('audioGenerated:', audioGenerated);
                                window.mementorTTSDebug.log('audioSrc:', audioSrc);
                                window.mementorTTSDebug.log('Button text:', $('#mementor-tts-play-btn .button-text').text());
                            }
                            $('#mementor-tts-play-btn').trigger('click');
                        }, 500); // Small delay to ensure audio is loaded
                    } else {
                        // Handle error - check for voice_limit_reached
                        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Error in success handler:', response);
                        
                        const isVoiceLimitError = 
                            (response.data && response.data.error_type === 'voice_limit_reached') ||
                            (response.data && response.data.data === 'voice_limit_reached') ||
                            (response.data && response.data.message === 'voice_limit_reached');
                        
                        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Is voice limit error in success handler?', isVoiceLimitError);
                        
                        if (isVoiceLimitError) {
                            // Show the voice limit modal
                            if (window.mementorTTSDebug) window.mementorTTSDebug.log('Showing voice limit modal from success handler');
                            if (window.mementorTTSModalUtils && window.mementorTTSModalUtils.showVoiceLimitWarning) {
                                window.mementorTTSModalUtils.showVoiceLimitWarning(
                                    'You have reached your voice creation limit. Open My Stats & Voices and delete one or more voices to free up space.'
                                );
                            } else {
                                // Fallback if modal utils aren't loaded
                                showMessage('Voice limit reached. Please go to My Stats & Voices to manage your voices.', 'error');
                            }
                        } else {
                            var errorMessage = (response.data && response.data.message) || 'Failed to generate audio';
                            // Make error codes human-readable
                            if (errorMessage.indexOf('pro_plan_required') !== -1) {
                                errorMessage = 'This voice requires a paid ElevenLabs subscription. Please select a different voice, or upgrade your ElevenLabs API key.';
                            } else if (errorMessage.indexOf('quota_exceeded') !== -1) {
                                errorMessage = 'PRO credits are temporarily exhausted. Please try again later or contact support.';
                            }
                            showMessage(errorMessage, 'error');
                        }
                        
                        // Re-enable button and reset state
                        $('#mementor-tts-play-btn').prop('disabled', false);
                        updatePlayButtonText('generate');
                        audioGenerated = false;
                    }
                },
                error: function(xhr, status, error) {
                    if (window.mementorTTSDebug) {
                        window.mementorTTSDebug.error('AJAX error:', error);
                        window.mementorTTSDebug.error('Response:', xhr.responseText);
                        window.mementorTTSDebug.error('Status:', xhr.status);
                        window.mementorTTSDebug.error('Full XHR object:', xhr);
                    }
                    
                    // Try to parse the error response
                    let errorResponse;
                    try {
                        errorResponse = JSON.parse(xhr.responseText);
                        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Parsed error response:', errorResponse);
                    } catch(parseError) {
                        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Not valid JSON, using raw text');
                        errorResponse = xhr.responseText;
                    }
                    
                    // Check for voice_limit_reached in various formats - similar to admin-columns.js
                    const responseStr = typeof errorResponse === 'string' ? errorResponse : JSON.stringify(errorResponse);
                    if (window.mementorTTSDebug) window.mementorTTSDebug.log('Looking for voice_limit_reached in:', responseStr);
                    
                    const isVoiceLimitError = 
                        (errorResponse && typeof errorResponse === 'object' && 
                         ((errorResponse.error_type === 'voice_limit_reached') ||
                          (errorResponse.detail && errorResponse.detail.status === 'voice_limit_reached') ||
                          (errorResponse.status === 'voice_limit_reached') ||
                          (errorResponse.error === 'voice_limit_reached') ||
                          (errorResponse.data && errorResponse.data === 'voice_limit_reached') ||
                          (errorResponse.data && errorResponse.data.error_type === 'voice_limit_reached') ||
                          (errorResponse.data && errorResponse.data.status === 'voice_limit_reached') ||
                          (errorResponse.data && errorResponse.data.message === 'voice_limit_reached') ||
                          (errorResponse.data && typeof errorResponse.data === 'string' && errorResponse.data === 'voice_limit_reached') ||
                          (errorResponse.message === 'voice_limit_reached'))) ||
                        (typeof errorResponse === 'string' && errorResponse.includes('voice_limit_reached')) ||
                        (xhr.responseText && xhr.responseText.includes('voice_limit_reached'));
                    
                    if (window.mementorTTSDebug) window.mementorTTSDebug.log('Is voice limit error?', isVoiceLimitError);
                    
                    if (isVoiceLimitError) {
                        // Show the voice limit modal
                        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Showing voice limit modal');
                        if (window.mementorTTSModalUtils && window.mementorTTSModalUtils.showVoiceLimitWarning) {
                            window.mementorTTSModalUtils.showVoiceLimitWarning(
                                'You have reached your voice creation limit. Open My Stats & Voices and delete one or more voices to free up space.'
                            );
                        } else {
                            // Fallback if modal utils aren't loaded
                            showMessage('Voice limit reached. Please go to My Stats & Voices to manage your voices.', 'error');
                        }
                    } else {
                        // Extract error message from various possible locations
                        let errorMsg = 'Error generating audio';
                        if (errorResponse && typeof errorResponse === 'object') {
                            if (errorResponse.message) {
                                errorMsg = errorResponse.message;
                            } else if (errorResponse.data && errorResponse.data.message) {
                                errorMsg = errorResponse.data.message;
                            } else if (errorResponse.data && typeof errorResponse.data === 'string') {
                                errorMsg = errorResponse.data;
                            }
                        } else if (typeof errorResponse === 'string') {
                            errorMsg = errorResponse;
                        }
                        
                        showMessage(errorMsg, 'error');
                    }
                    
                    // Re-enable button and reset state
                    $('#mementor-tts-play-btn').prop('disabled', false);
                    updatePlayButtonText('generate');
                    audioGenerated = false;
                }
            });
            return;
        }

        // If audio was generated and button says "Play Generated Audio", play it
        if (audioGenerated && audioSrc && !currentlyPlaying) {
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Playing generated audio');
                window.mementorTTSDebug.log('audioSrc:', audioSrc);
            }
            
            audio.src = audioSrc;
            audio.currentTime = 0;
            
            audio.play().then(function() {
                currentlyPlaying = true;
                updatePlayButtonText('pause');
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Generated audio playback started');
            }).catch(function(error) {
                if (window.mementorTTSDebug) window.mementorTTSDebug.error('Error playing generated audio:', error);
                showMessage('Error playing audio. Please try again.', 'error');
                currentlyPlaying = false;
                updatePlayButtonText('play_generated');
            });
            
            return;
        }

        // Start playing audio
        if (audioSrc) {
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Playing audio with audioSrc:', audioSrc);
                window.mementorTTSDebug.log('Current audio.src:', audio.src);
                window.mementorTTSDebug.log('audioGenerated flag:', audioGenerated);
            }
            
            // Check if audio is currently paused and has a position to resume from
            if (audio.src && audio.paused && audio.currentTime > 0 && !audio.ended) {
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Resuming from position:', audio.currentTime);
                // Resume from current position without changing the source
                try {
                    // Don't reset the currentTime if we're resuming from pause
                    // Only reset if the audio has ended or hasn't started
                    if (audio.ended || audio.currentTime === 0) {
                        audio.currentTime = 0;
                    }
                    audio.play()
                        .then(() => {
                            // Success, update UI
                            currentlyPlaying = true;
                            updatePlayButtonText('pause');
                            if (window.mementorTTSDebug) {
                                window.mementorTTSDebug.log('Playing audio from source: ' + audioSrc);
                                window.mementorTTSDebug.log('Current playback position: ' + audio.currentTime);
                            }
                            
})
                        .catch((error) => {
                            // Error playing audio
                            currentlyPlaying = false;
                            updatePlayButtonText('play_generated');
                            if (window.mementorTTSDebug) window.mementorTTSDebug.error('Error playing audio:', error);
                        });
                } catch (e) {
                    if (window.mementorTTSDebug) window.mementorTTSDebug.error('Error playing audio:', e);
                    currentlyPlaying = false;
                    updatePlayButtonText('play_generated');
                }
            } else {
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Starting audio from beginning');
                // Set source and start from beginning only if needed
                audio.src = audioSrc;
                audio.currentTime = 0;
                
audio.play()
                    .then(function() {
                        currentlyPlaying = true;
                        updatePlayButtonText('pause');
                        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Audio playback started');
                    })
                    .catch(function(error) {
                        if (window.mementorTTSDebug) window.mementorTTSDebug.error('Error playing audio:', error);
                        showMessage('Error playing audio: ' + error.message, 'error');
                        
                        // Reset UI state on error
                        currentlyPlaying = false;
                        updatePlayButtonText('play_generated');
                    });
            }
            
            if (window.mementorTTSDebug) window.mementorTTSDebug.log('Playing audio:', audioSrc);
        } else {
            if (window.mementorTTSDebug) window.mementorTTSDebug.error('No audio source available');
            showMessage('No audio source available', 'error');
        }
    });
    
    // Add event listener to handle audio ending
    audio.addEventListener('ended', function() {
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Audio playback ended');
        currentlyPlaying = false;
        
        // Update button text based on whether it was generated audio or default
        if (audioGenerated) {
            updatePlayButtonText('play_generated');
        } else {
            updatePlayButtonText('play');
        }
    });
    
    // Reset button functionality
    $('#mementor-tts-reset-btn').on('click', function() {
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Reset button clicked');
        
        // Stop audio if playing
        if (audio && !audio.paused) {
            audio.pause();
            audio.currentTime = 0;
            currentlyPlaying = false;
        }
        // Reset textarea to default
        const defaultText = textArea.attr('data-default-text');
        textArea.val(defaultText);
        
        // Update character count
        $('#mementor-tts-current-chars').text(defaultText.length);
        
        // Reset audio generation state
        audioGenerated = false;
        audioSrc = null;
        
        // Reset button to Play Demo state
        updatePlayButtonText('play');
        
        // Disable download button
        $('#mementor-tts-download-btn').prop('disabled', true);
        
        // Reset speed slider if it exists
        if ($('#mementor-tts-speed-adjust').length) {
            $('#mementor-tts-speed-adjust').val(1.0);
            $('#mementor-tts-speed-value').text('1.0x');
        }
        
        // Reset all customizer checkboxes
        $('.mementor-tts-customizer-option input[type="checkbox"]').prop('checked', false);
        
        // Update shortcode display to default
        updateShortcodeDisplay();
        
        // Show success message
        showMessage('Reset complete!', 'success');
    });
    
    // Download button functionality 
    $('#mementor-tts-download-btn').on('click', function() {
        if (!audioSrc || $(this).prop('disabled')) return; // No audio to download or button disabled

        if (audioGenerated) {
            // Use the actual filename from the audio URL
            var dlFilename = audioSrc.split('/').pop() || 'text-to-speech-generated.mp3';

            // Proxy through WP AJAX to avoid CORS issues with CloudFront/S3
            var proxyUrl = mementorTtsGenerator.ajaxUrl
                + '?action=mementor_tts_proxy_download'
                + '&nonce=' + encodeURIComponent(mementorTtsGenerator.nonce)
                + '&url=' + encodeURIComponent(audioSrc)
                + '&filename=' + encodeURIComponent(dlFilename);

            var downloadLink = document.createElement('a');
            downloadLink.href = proxyUrl;
            downloadLink.download = dlFilename;
            downloadLink.style.display = 'none';
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);

            showMessage('Download started!', 'success');
        } else {
            // For default demo audio, simple download
            var downloadLink = document.createElement('a');
            downloadLink.href = audioSrc;
            downloadLink.download = 'text-to-speech-demo.mp3';
            downloadLink.style.display = 'none';
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
            
            showMessage('Download started!', 'success');
        }
    });
    
    // Copy shortcode button functionality
    $('#mementor-tts-copy-shortcode-btn').on('click', function() {
        // First update the shortcode display
        updateShortcodeDisplay();
        
        // Get the current shortcode text
        const shortcodeText = $('#mementor-tts-shortcode-realtime').text();
        
        // Create a temporary textarea to copy the shortcode
        const tempTextarea = document.createElement('textarea');
        tempTextarea.value = shortcodeText;
        document.body.appendChild(tempTextarea);
        tempTextarea.select();
        document.execCommand('copy');
        document.body.removeChild(tempTextarea);
        
        // Update both displays
        $('#mementor-tts-shortcode-text').text(shortcodeText);
        $('#mementor-tts-shortcode-display').show();
        
        // Add to history when copying shortcode
        var currentText = $('#mementor-tts-text').val();
        var currentVoiceName = $('#mementor-tts-voice-name').text();
        var currentVoiceId = $('#mementor-tts-voice-id').val();
        // Note: audioUrl may not be available when just copying shortcode without generating
        HistoryManager.addToHistory(currentText, shortcodeText, currentVoiceId, currentVoiceName, audioSrc, null);

        showMessage('Shortcode copied to clipboard!', 'success');
    });
    
    // Helper function to insert text at cursor position
    function insertAtCursor(field, text) {
        // Save current scroll position
        const scrollPos = field.scrollTop;
        
        if (field.selectionStart || field.selectionStart === 0) {
            const startPos = field.selectionStart;
            const endPos = field.selectionEnd;
            
            // Get selected text
            const selectedText = field.value.substring(startPos, endPos);
            
            // Insert the text - if there's a selection, wrap it with SSML tags
            if (selectedText && text.includes('{selection}')) {
                // Replace {selection} placeholder with the selected text
                const newText = text.replace('{selection}', selectedText);
                field.value = field.value.substring(0, startPos) + newText + field.value.substring(endPos, field.value.length);
                field.selectionStart = startPos + newText.length;
                field.selectionEnd = field.selectionStart;
            } else {
                // Just insert the text at cursor position
                field.value = field.value.substring(0, startPos) + text + field.value.substring(endPos, field.value.length);
                field.selectionStart = startPos + text.length;
                field.selectionEnd = startPos + text.length;
            }
            
            // Trigger input event to update character count
            $(field).trigger('input');
        } else {
            // Fallback for older browsers
            field.value += text;
        }
        
        // Restore scroll position
        field.scrollTop = scrollPos;
        
        // Focus the field
        field.focus();
    }
    
    // SSML toolbar button clicks
    $('.mementor-tts-ssml-btn').on('click', function(e) {
        e.preventDefault();
        
        // Check if button is disabled (PRO feature)
        if ($(this).hasClass('mementor-tts-pro-feature')) {
            return; // Let the tooltip handler manage this
        }
        
        const ssmlType = $(this).data('ssml');
        const textarea = document.getElementById('mementor-tts-text');
        
        switch(ssmlType) {
            case 'break':
                // Add pause/break - insert default 0.65s break
                insertAtCursor(textarea, '<break time="0.65s" />');
                break;
                
            case 'prosody':
                // Insert prosody tag with default values
                insertAtCursor(textarea, '<prosody rate="medium" pitch="medium" volume="medium">{selection}</prosody>');
                break;
                
            case 'say-as':
                // Insert say-as tag with default value
                insertAtCursor(textarea, '<say-as interpret-as="cardinal">123</say-as>');
                break;
                
            case 'emotional':
            case 'sound-effects':
            case 'unique-special':
                // Show tooltip popup with SSML examples
                var tooltipMap = {
                    'emotional': 'emotional-expressions-tooltip',
                    'sound-effects': 'sound-effects-tooltip',
                    'unique-special': 'unique-special-tooltip'
                };
                var tooltipId = tooltipMap[ssmlType];
                var tooltipContent = $('#' + tooltipId);
                if (tooltipContent.length) {
                    // Remove any existing tooltip popup
                    $('.mementor-tts-ssml-popup').remove();
                    var popup = $('<div class="mementor-tts-ssml-popup"></div>');
                    popup.html(tooltipContent.html());
                    popup.append('<button type="button" class="mementor-tts-ssml-popup-close">&times;</button>');
                    $(this).closest('.tts-ssml-btn-wrap').append(popup);
                    popup.show();
                    // Close on click outside or close button
                    popup.find('.mementor-tts-ssml-popup-close').on('click', function() { popup.remove(); });
                    $(document).one('click', function(ev) {
                        if (!$(ev.target).closest('.mementor-tts-ssml-popup, .mementor-tts-ssml-btn').length) {
                            popup.remove();
                        }
                    });
                }
                break;
                
            default:
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Unknown SSML type:', ssmlType);
        }
    });
    
    // Initialize - set character count and disable buttons
    (function() {
        const textarea = $('#mementor-tts-text');
        const text = textarea.val();
        $('#mementor-tts-current-chars').text(text.length);
        
        $('#mementor-tts-download-btn').prop('disabled', true);
        // Initialize play button text based on content
        if (text !== textarea.attr('data-default-text')) {
            updatePlayButtonText('generate');
        }
        
        // Make sure text tab is active on page load
        $('.mementor-tts-tab[data-tab="text-input"]').trigger('click');
    })();
    
    // Handle any audio loading errors
    audio.addEventListener('error', function() {
        if (window.mementorTTSDebug) window.mementorTTSDebug.error('Audio error occurred');
        currentlyPlaying = false;
        
        // Reset UI state on error
        if (audioGenerated) {
            updatePlayButtonText('play_generated');
        } else {
            updatePlayButtonText('play');
        }
        
        showMessage('Error loading audio file', 'error');
    });
    
    // Initialize PRO feature tooltips
    initializeProFeatureTooltips();
    
    // Click to copy shortcode from real-time display
    $(document).on('click', '#mementor-tts-shortcode-realtime', function() {
        const shortcodeText = $(this).text();
        
        // Create a temporary textarea to copy the shortcode
        const tempTextarea = document.createElement('textarea');
        tempTextarea.value = shortcodeText;
        document.body.appendChild(tempTextarea);
        tempTextarea.select();
        document.execCommand('copy');
        document.body.removeChild(tempTextarea);
        
        // Show feedback
        showMessage('Shortcode copied to clipboard!', 'success');
        
        // Visual feedback
        $(this).css('background-color', '#d4edda');
        setTimeout(() => {
            $(this).css('background-color', '#fff');
        }, 300);
    });
    
    // Function to update shortcode based on selected options
    function updateShortcodeDisplay() {
        let shortcode = '[mementor-tts';
        
        // Check if audio has been generated
        if (audioGenerated && audioSrc) {
            // Extract just the filename from the full URL
            const filename = audioSrc.split('/').pop();
            shortcode += ' audio="' + filename + '"';
        }
        
        // Add selected customizer options
        $('.mementor-tts-customizer-option input[type="checkbox"]:checked').each(function() {
            const param = $(this).data('param');
            const value = $(this).data('value');
            shortcode += ' ' + param + '="' + value + '"';
        });
        
        shortcode += ']';
        
        // Update the display
        $('#mementor-tts-shortcode-realtime').text(shortcode);
        
        // Also update the hidden field and old display if visible
        $('#mementor-tts-shortcode').val(shortcode);
        if ($('#mementor-tts-shortcode-display').is(':visible')) {
            $('#mementor-tts-shortcode-text').text(shortcode);
        }
    }
    
    // Handle checkbox changes
    $('.mementor-tts-customizer-option input[type="checkbox"]').on('change', function() {
        updateShortcodeDisplay();
    });
    
    // Handle label clicks (for better UX)
    $('.mementor-tts-customizer-option').on('click', function(e) {
        // Prevent event bubbling
        e.stopPropagation();
        
        // If the click wasn't on the checkbox itself, toggle it
        if (!$(e.target).is('input[type="checkbox"]')) {
            e.preventDefault();
            const checkbox = $(this).find('input[type="checkbox"]');
            checkbox.prop('checked', !checkbox.prop('checked'));
            checkbox.trigger('change');
        }
    });
    
    // Prevent checkbox clicks from bubbling up
    $('.mementor-tts-customizer-option input[type="checkbox"]').on('click', function(e) {
        e.stopPropagation();
    });

    // History Manager Object
    var HistoryManager = {
        maxItems: 5,
        storageKey: 'mementor_tts_generator_history',

        // Resolve audio URL: prefer full URL, fall back to baseUrl + filename
        resolveAudioUrl: function(item) {
            // Full URL stored (CloudFront/S3/external) — use directly
            if (item.audioUrl && item.audioUrl.indexOf('http') === 0) {
                return item.audioUrl;
            }
            // Filename stored — reconstruct from local base
            var baseUrl = (typeof mementorTtsGenerator !== 'undefined' && mementorTtsGenerator.audioBaseUrl) || '';
            if (item.audioFilename && baseUrl) {
                return baseUrl + item.audioFilename;
            }
            return item.audioUrl || null;
        },

        // Get history from localStorage
        getHistory: function() {
            try {
                var history = localStorage.getItem(this.storageKey);
                return history ? JSON.parse(history) : [];
            } catch (e) {
                if (window.mementorTTSDebug) window.mementorTTSDebug.error('Error reading history from localStorage:', e);
                return [];
            }
        },

        // Save history to localStorage
        saveHistory: function(history) {
            try {
                localStorage.setItem(this.storageKey, JSON.stringify(history));
            } catch (e) {
                if (window.mementorTTSDebug) window.mementorTTSDebug.error('Error saving history to localStorage:', e);
            }
        },

        // Extract filename from a full audio URL
        extractFilename: function(url) {
            if (!url) return null;
            var parts = url.split('/text-to-speech-tts/');
            return parts.length > 1 ? parts[parts.length - 1] : url.split('/').pop();
        },

        // Add new item to history
        addToHistory: function(text, shortcode, voiceId, voiceName, audioUrl, elementUid) {
            var history = this.getHistory();
            var newItem = {
                id: Date.now().toString(),
                text: text.substring(0, 200), // Limit text length for storage
                shortcode: shortcode,
                voiceId: voiceId,
                voiceName: voiceName,
                audioFilename: this.extractFilename(audioUrl),
                audioUrl: audioUrl || null, // Keep for backwards compat
                elementUid: elementUid || null,
                timestamp: Date.now(),
                date: new Date().toLocaleDateString() + ' ' + new Date().toLocaleTimeString()
            };

            // Add to beginning of array
            history.unshift(newItem);

            // Keep only last maxItems
            if (history.length > this.maxItems) {
                history = history.slice(0, this.maxItems);
            }

            this.saveHistory(history);
            this.renderHistory();
        },
        
        // Restore state from history item
        restoreFromHistory: function(item) {
            // Set the textarea text
            $('#mementor-tts-text').val(item.text);
            
            // Parse shortcode to restore checkboxes
            this.parseShortcodeAndSetOptions(item.shortcode);
            
            // Update character count
            $('#mementor-tts-current-chars').text(item.text.length);
            
            // Update shortcode display
            updateShortcodeDisplay();
            
            showMessage('Settings restored from history!', 'success');
        },
        
        // Parse shortcode and set checkbox options
        parseShortcodeAndSetOptions: function(shortcode) {
            // Reset all checkboxes first
            $('.mementor-tts-customizer-option input[type="checkbox"]').prop('checked', false);
            
            // Parse shortcode attributes
            var attributes = shortcode.match(/(\w+)="([^"]*)"/g);
            if (attributes) {
                attributes.forEach(function(attr) {
                    var match = attr.match(/(\w+)="([^"]*)"/);
                    if (match) {
                        var param = match[1];
                        var value = match[2];
                        
                        // Find corresponding checkbox
                        var checkbox = $('input[data-param="' + param + '"]');
                        if (checkbox.length) {
                            checkbox.prop('checked', true);
                        }
                    }
                });
            }
        },
        
        // Copy shortcode to clipboard
        copyShortcode: function(shortcode) {
            var tempTextarea = document.createElement('textarea');
            tempTextarea.value = shortcode;
            document.body.appendChild(tempTextarea);
            tempTextarea.select();
            document.execCommand('copy');
            document.body.removeChild(tempTextarea);

            showMessage('Shortcode copied to clipboard!', 'success');
        },

        // Download audio from history item
        downloadHistoryAudio: function(item) {
            var audioUrl = this.resolveAudioUrl(item);
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Download button clicked for history item:', item);
                window.mementorTTSDebug.log('Audio URL:', audioUrl);
            }

            if (!audioUrl) {
                if (window.mementorTTSDebug) window.mementorTTSDebug.warn('No audio URL in history item:', item);
                showMessage('Audio file not found. Try refreshing recent generations.', 'error');
                return;
            }

            // Generate a filename based on the timestamp or element UID
            var filename = 'tts-audio-' + item.timestamp + '.mp3';
            if (item.elementUid) {
                filename = item.elementUid + '.mp3';
            }

            // Check if URL is from S3 or external source
            var isExternalUrl = audioUrl.indexOf('http') === 0 &&
                               (audioUrl.indexOf(window.location.hostname) === -1);

            if (isExternalUrl) {
                // Proxy through WP AJAX to avoid CORS issues
                var proxyUrl = mementorTtsGenerator.ajaxUrl
                    + '?action=mementor_tts_proxy_download'
                    + '&nonce=' + encodeURIComponent(mementorTtsGenerator.nonce)
                    + '&url=' + encodeURIComponent(audioUrl)
                    + '&filename=' + encodeURIComponent(filename);

                var link = document.createElement('a');
                link.href = proxyUrl;
                link.download = filename;
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                showMessage('Download started!', 'success');
            } else {
                // For local files, use direct download
                var link = document.createElement('a');
                link.href = audioUrl;
                link.download = filename;
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                showMessage('Download started!', 'success');
            }
        },

        // Delete item from history
        deleteFromHistory: function(itemId) {
            var history = this.getHistory();
            history = history.filter(function(item) {
                return item.id !== itemId;
            });
            this.saveHistory(history);
            this.stopAllHistoryAudio();
            this.renderHistory();
        },

        // Global function to stop all audio completely
        stopAllHistoryAudio: function() {
            // Stop and destroy any existing audio
            if (window.currentHistoryAudio) {
                try {
                    window.currentHistoryAudio.pause();
                    window.currentHistoryAudio.currentTime = 0;
                    window.currentHistoryAudio.src = '';
                    window.currentHistoryAudio.load(); // Reset the audio element
                } catch (e) {
                    if (window.mementorTTSDebug) window.mementorTTSDebug.log('Error stopping audio:', e);
                }
                window.currentHistoryAudio = null;
            }
            
            // Reset ALL buttons
            $('.mementor-tts-history-btn-play').each(function() {
                $(this).html('<span class="dashicons dashicons-controls-play"></span> Play');
                $(this).prop('disabled', false);
                $(this).removeData('playing paused audio-filename');
            });
        },
        
        // ULTRA SIMPLE - No event listeners to prevent loops
        playHistoryAudio: function(item, $button) {
            var self = this;

            var audioUrl = this.resolveAudioUrl(item);
            if (!audioUrl) {
                showMessage('No audio file found for this item', 'info');
                return;
            }
            
            // If already playing, just stop
            if (window.currentHistoryAudio && !window.currentHistoryAudio.paused) {
                self.stopAllHistoryAudio();
                return;
            }
            
            // Stop everything first
            self.stopAllHistoryAudio();
            
            // Create audio element
            try {
                var audio = new Audio(audioUrl);
                window.currentHistoryAudio = audio;
                
                // Set volume
                audio.volume = 1.0;
                
                // Update button to pause state immediately
                $button.html('<span class="dashicons dashicons-controls-pause"></span> Pause');
                
                // Simple play with timeout fallback
                var playPromise = audio.play();
                
                if (playPromise !== undefined) {
                    playPromise.then(function() {
                        // Playing started successfully
                        if (window.mementorTTSDebug) window.mementorTTSDebug.log('History audio started successfully');
                    }).catch(function(error) {
                        if (window.mementorTTSDebug) window.mementorTTSDebug.error('Play failed:', error);
                        self.stopAllHistoryAudio();
                        showMessage('Could not play audio', 'error');
                    });
                }
                
                // Set up ended handler only
                audio.onended = function() {
                    self.stopAllHistoryAudio();
                };
                
                // Set up error handler only
                audio.onerror = function() {
                    self.stopAllHistoryAudio();
                    showMessage('Audio file not found. Try refreshing recent generations.', 'error');
                };
                
            } catch (error) {
                if (window.mementorTTSDebug) window.mementorTTSDebug.error('Audio creation failed:', error);
                self.stopAllHistoryAudio();
                showMessage('Could not create audio player', 'error');
            }
        },
        
        // Render history list
        renderHistory: function() {
            var history = this.getHistory();
            var $historyList = $('#mementor-tts-history-list');
            var $historyEmpty = $('#mementor-tts-history-empty');
            var $historyCount = $('#mementor-tts-history-count');
            
            // Update count
            $historyCount.text('(' + history.length + ')');
            
            if (history.length === 0) {
                $historyList.hide();
                $historyEmpty.show();
                return;
            }
            
            $historyEmpty.hide();
            $historyList.show().empty();
            
            var self = this;
            history.forEach(function(item) {
                var $item = $('<div class="mementor-tts-history-item"></div>');
                
                var $header = $('<div class="mementor-tts-history-item-header"></div>');
                var $info = $('<div class="mementor-tts-history-item-info"></div>');
                var $actions = $('<div class="mementor-tts-history-actions"></div>');
                
                // Date and text info
                $info.append('<div class="mementor-tts-history-date">' + item.date + '</div>');
                $info.append('<div class="mementor-tts-history-text">' + item.text + '</div>');
                if (item.voiceName) {
                    $info.append('<div class="mementor-tts-history-voice">Voice: ' + item.voiceName + '</div>');
                }
                
                // Action buttons
                var $playBtn = $('<button class="mementor-tts-history-btn mementor-tts-history-btn-play" title="Play audio if available"><span class="dashicons dashicons-controls-play"></span> Play</button>');
                var $restoreBtn = $('<button class="mementor-tts-history-btn mementor-tts-history-btn-restore" title="Restore this configuration"><span class="dashicons dashicons-update"></span> Restore</button>');
                var $copyBtn = $('<button class="mementor-tts-history-btn mementor-tts-history-btn-copy" title="Copy shortcode"><span class="dashicons dashicons-clipboard"></span> Copy</button>');
                var $downloadBtn = $('<button class="mementor-tts-history-btn mementor-tts-history-btn-download" title="Download audio file"><span class="dashicons dashicons-download"></span> Download</button>');
                var $deleteBtn = $('<button class="mementor-tts-history-btn mementor-tts-history-btn-delete" title="Remove from history"><span class="dashicons dashicons-trash"></span> Delete</button>');

                // Store the item data on the button for later use
                $playBtn.data('audio-item', item);

                // Disable play and download buttons if no audio URL
                if (!self.resolveAudioUrl(item)) {
                    $playBtn.prop('disabled', true).css('opacity', '0.5');
                    $downloadBtn.prop('disabled', true).css('opacity', '0.5');
                }

                // Event handlers (using off to prevent duplicate handlers)
                $playBtn.off('click.playAudio').on('click.playAudio', function() {
                    self.playHistoryAudio(item, $playBtn);
                });

                $restoreBtn.on('click', function() {
                    self.restoreFromHistory(item);
                });

                $copyBtn.on('click', function() {
                    self.copyShortcode(item.shortcode);
                });

                $downloadBtn.on('click', function() {
                    self.downloadHistoryAudio(item);
                });

                $deleteBtn.on('click', function() {
                    self.deleteFromHistory(item.id);
                });

                $actions.append($playBtn).append($restoreBtn).append($copyBtn).append($downloadBtn).append($deleteBtn);
                
                // Shortcode display
                var $shortcode = $('<div class="mementor-tts-history-shortcode">' + item.shortcode + '</div>');
                
                $header.append($info).append($actions);
                $item.append($header).append($shortcode);
                
                $historyList.append($item);
            });
        },
        
        // Initialize history
        init: function() {
            this.renderHistory();
            
            // Handle history section toggle
            $('#mementor-tts-history-toggle').on('click', function() {
                var $content = $('#mementor-tts-history-content');
                var $header = $(this);
                
                if ($content.is(':visible')) {
                    $content.slideUp();
                    $header.removeClass('expanded');
                } else {
                    $content.slideDown();
                    $header.addClass('expanded');
                }
            });
        }
    };
    
    // Initialize History Manager
    HistoryManager.init();

    // Add event handlers for intro/outro checkboxes to provide feedback
    $('#mementor-tts-include-intro').on('change', function() {
        var isChecked = $(this).is(':checked');

        // Visual feedback
        if (isChecked) {
            $(this).closest('.mementor-tts-toolbar-checkbox').css('background', '#e8f5e9');
            setTimeout(function() {
                $('#mementor-tts-include-intro').closest('.mementor-tts-toolbar-checkbox').css('background', '');
            }, 300);
        } else {
            $(this).closest('.mementor-tts-toolbar-checkbox').css('background', '#ffebee');
            setTimeout(function() {
                $('#mementor-tts-include-intro').closest('.mementor-tts-toolbar-checkbox').css('background', '');
            }, 300);
        }
    });

    $('#mementor-tts-include-outro').on('change', function() {
        var isChecked = $(this).is(':checked');

        // Visual feedback
        if (isChecked) {
            $(this).closest('.mementor-tts-toolbar-checkbox').css('background', '#e8f5e9');
            setTimeout(function() {
                $('#mementor-tts-include-outro').closest('.mementor-tts-toolbar-checkbox').css('background', '');
            }, 300);
        } else {
            $(this).closest('.mementor-tts-toolbar-checkbox').css('background', '#ffebee');
            setTimeout(function() {
                $('#mementor-tts-include-outro').closest('.mementor-tts-toolbar-checkbox').css('background', '');
            }, 300);
        }
    });

});


// Function to initialize PRO feature tooltips
function initializeProFeatureTooltips() {
    if (window.mementorTTSDebug) window.mementorTTSDebug.log('Initializing PRO feature tooltips');
    
    // Only initialize tooltips that haven't been initialized yet
    jQuery('.mementor-tts-pro-feature').each(function() {
        const button = jQuery(this);
        const tooltipId = button.data('tooltip-id');
        
        // Skip if already initialized and still in DOM
        if (button.data('tooltipInitialized') === true) {
            const existingTooltip = button.data('tooltipElement');
            if (existingTooltip && existingTooltip.parent().length > 0) {
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Tooltip already initialized and in DOM for:', tooltipId);
                return; // Skip to next button
            }
        }
        
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Processing button with tooltip ID:', tooltipId);
            
        // Find the tooltip content
        const tooltip = jQuery('#' + tooltipId);
            
        if (tooltip.length) {
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Found tooltip content for ID:', tooltipId);
                window.mementorTTSDebug.log('Tooltip content:', tooltip.html());
            }
                
            // IMPORTANT: Remove the title attribute to prevent default browser tooltip
            if (button.attr('title')) {
                // Store the original title in a data attribute in case we need it later
                button.data('original-title', button.attr('title'));
                button.removeAttr('title');
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Removed title attribute from button');
            }
                
            // Determine which audio file to use based on tooltip ID
            let audioFile = '';
            const pluginUrl = (typeof mementorTtsGenerator !== 'undefined' && mementorTtsGenerator.pluginUrl) || 
                             (typeof mementorTTS !== 'undefined' && mementorTTS.plugin_url) || 
                             '/wp-content/plugins/text-to-speech-tts/';
            
            if (tooltipId === 'emotional-expressions-tooltip') {
                audioFile = pluginUrl + 'admin/audio/tooltip-emotions.mp3';
            } else if (tooltipId === 'sound-effects-tooltip') {
                audioFile = pluginUrl + 'admin/audio/tooltip-effects.mp3';
            } else if (tooltipId === 'unique-special-tooltip') {
                audioFile = pluginUrl + 'admin/audio/tooltip-elevator.mp3';
            }
            
            // Create tooltip element
            const tooltipElement = jQuery('<div class="mementor-tts-tooltip"></div>');
            
            // Get the HTML content from the hidden tooltip
            const tooltipHtml = tooltip.html();
            
            // Remove any existing footer from the HTML
            const cleanedHtml = tooltipHtml.replace(/<div class="mementor-tts-tooltip-footer">[\s\S]*?<\/div>/gi, '');
            
            // Set the cleaned HTML
            tooltipElement.html(cleanedHtml);
            
            // Always add our audio player footer
            tooltipElement.append('<div class="mementor-tts-tooltip-footer">' +
                    '<audio class="tooltip-audio" style="display: none;">' +
                    '<source src="' + audioFile + '" type="audio/mpeg">' +
                    '</audio>' +
                    '<button type="button" class="button button-secondary mementor-tts-tooltip-play-btn">' +
                    '<span class="dashicons dashicons-controls-play"></span> Play Example' +
                    '</button>' +
                    '</div>');
            
            tooltipElement.appendTo('body')
                .css({
                    'position': 'absolute',
                    'z-index': 10000,
                    'display': 'none',
                    'visibility': 'visible',
                    'opacity': 0
                })
                .hide();
            
            // Add click handler for the play button
            tooltipElement.find('.mementor-tts-tooltip-play-btn').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                const playBtn = jQuery(this);
                const audio = tooltipElement.find('.tooltip-audio')[0];
                const icon = playBtn.find('.dashicons');
                
                if (audio.paused) {
                    // Stop any other playing tooltip audios
                    jQuery('.tooltip-audio').each(function() {
                        if (!this.paused && this !== audio) {
                            this.pause();
                            this.currentTime = 0;
                            jQuery(this).siblings('.mementor-tts-tooltip-play-btn')
                                .find('.dashicons')
                                .removeClass('dashicons-controls-pause')
                                .addClass('dashicons-controls-play');
                        }
                    });
                    
                    // Play this audio
                    audio.play();
                    icon.removeClass('dashicons-controls-play').addClass('dashicons-controls-pause');
                    playBtn.html('<span class="dashicons dashicons-controls-pause"></span> Pause');
                } else {
                    // Pause this audio
                    audio.pause();
                    icon.removeClass('dashicons-controls-pause').addClass('dashicons-controls-play');
                    playBtn.html('<span class="dashicons dashicons-controls-play"></span> Play Example');
                }
            });
            
            // Handle audio ended event
            tooltipElement.find('.tooltip-audio').on('ended', function() {
                const playBtn = tooltipElement.find('.mementor-tts-tooltip-play-btn');
                playBtn.html('<span class="dashicons dashicons-controls-play"></span> Play Example');
            });
                
            // Remove any existing event handlers to avoid duplicates
            button.off('mouseenter mouseleave click');
                
            // Store reference to tooltip in button's data for easy access
            button.data('tooltipElement', tooltipElement);
                
            // Add a timeout reference for delayed hiding
            let hideTimeout = null;
            
            // Store hideTimeout in button data so it persists
            button.data('hideTimeout', null);
            
            // Function to clear any existing hide timeout
            const clearHideTimeout = function() {
                if (hideTimeout) {
                    clearTimeout(hideTimeout);
                    hideTimeout = null;
                }
            };
            
            // Use direct event binding instead of hover() method for better compatibility with disabled buttons
            button.on('mouseenter', function(e) {
                e.stopPropagation();
                clearHideTimeout(); // Clear any pending hide
                const tooltipElem = jQuery(this).data('tooltipElement');
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Mouse enter detected on button with tooltip ID:', tooltipId);
                }
                if (tooltipElem) {
                    // Reposition tooltip in case page has changed
                    const btnOffset = jQuery(this).offset();
                    const btnWidth = jQuery(this).outerWidth();
                    const btnHeight = jQuery(this).outerHeight();
                    const tipWidth = tooltipElem.outerWidth() || 300;
                        
                    tooltipElem.css({
                        'top': (btnOffset.top + btnHeight + 5) + 'px',
                        'left': (btnOffset.left + (btnWidth - tipWidth) / 2) + 'px',
                        'opacity': 1,
                        'visibility': 'visible',
                        'display': 'block'
                    }).fadeIn(200);
                }
            });
                
            button.on('mouseleave', function(e) {
                e.stopPropagation();
                const tooltipElem = jQuery(this).data('tooltipElement');
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Mouse leave detected on button with tooltip ID:', tooltipId);
                }
                if (tooltipElem) {
                    // Add a delay before hiding to allow mouse to move to tooltip
                    hideTimeout = setTimeout(function() {
                        // Only hide if mouse is not over the tooltip
                        if (!tooltipElem.is(':hover')) {
                            tooltipElem.fadeOut(100);
                        }
                    }, 300); // 300ms delay to allow moving to tooltip
                }
            });
            
            // Add hover handlers to the tooltip itself
            tooltipElement.on('mouseenter', function(e) {
                e.stopPropagation();
                clearHideTimeout(); // Cancel hiding when hovering over tooltip
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Mouse entered tooltip');
                }
            });
            
            tooltipElement.on('mouseleave', function(e) {
                e.stopPropagation();
                const self = jQuery(this);
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Mouse left tooltip');
                }
                // Hide the tooltip when mouse leaves it
                hideTimeout = setTimeout(function() {
                    // Check if mouse is back on the button
                    if (!button.is(':hover')) {
                        self.fadeOut(100);
                    }
                }, 300); // 300ms delay to allow moving back to button
            });
                
            button.on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const tooltipElem = jQuery(this).data('tooltipElement');
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Click detected on button with tooltip ID:', tooltipId);
                }
                if (tooltipElem) {
                    tooltipElem.fadeToggle(100);
                }
            });
                
            // Force the tooltip to be visible for a moment to ensure it's properly initialized
            tooltipElement.show();
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Tooltip temporarily shown for initialization');
            }
            setTimeout(function() {
                tooltipElement.hide();
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Tooltip hidden after initialization');
                }
            }, 100);
            
            // Mark as initialized
            button.data('tooltipInitialized', true);
        }
    });
}