jQuery(document).ready(function($) {
    // Ensure variables are available
    const mementorTTS = window.mementorTTS || {};

    const mementorTTSGetAjaxUrl = () => {
        return mementorTTS.ajaxurl;
    };

    // Function to get current page slug
    const getCurrentPage = () => {
        const urlParams = new URLSearchParams(window.location.search);
        const page = urlParams.get('page');
        const tab = urlParams.get('tab');
        return tab || (page ? page.replace('text-to-speech-tts-', '') : 'settings');
    };
    
    // Remove third-party admin notices on TTS pages
    if (window.location.search.includes('text-to-speech-tts')) {
        // Function to remove notices
        const removeThirdPartyNotices = () => {
            // Select all notices that are not ours
            const notices = document.querySelectorAll(
                '.notice:not(.mementor-tts-notice), ' +
                '.error:not(.mementor-tts-notice), ' +
                '.updated:not(.mementor-tts-notice), ' +
                '.update-nag:not(.mementor-tts-notice), ' +
                '.notice-error:not(.mementor-tts-notice), ' +
                '.notice-warning:not(.mementor-tts-notice), ' +
                '.notice-success:not(.mementor-tts-notice), ' +
                '.notice-info:not(.mementor-tts-notice), ' +
                '[class*="notice"]:not(.mementor-tts-notice):not(.mementor-tts-welcome-card):not(.mementor-tts-settings-card):not(.mementor-tts-api-settings-card), ' +
                '[id*="message"]:not(.mementor-tts-notice):not(textarea):not(input), ' +
                '#elm-sw-setup-wizard-notice, ' +
                '.elm-notice, ' +
                '.fs-notice, ' +
                '[class*="admin-notice"]:not(.mementor-tts-notice), ' +
                '[class*="admin_notice"]:not(.mementor-tts-notice)'
            );
            
            // Remove each notice
            notices.forEach(notice => {
                // Don't remove our own cards/containers
                if (!notice.classList.contains('mementor-tts-welcome-card') &&
                    !notice.classList.contains('mementor-tts-settings-card') &&
                    !notice.classList.contains('mementor-tts-api-settings-card') &&
                    !notice.classList.contains('mementor-tts-notice')) {
                    notice.remove();
                }
            });
        };
        
        // Remove notices immediately
        removeThirdPartyNotices();
        
        // Also remove notices that are added later
        const observer = new MutationObserver(() => {
            removeThirdPartyNotices();
        });
        
        // Start observing
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
        
        // Clean up notices periodically in case some slip through
        setInterval(removeThirdPartyNotices, 1000);
    }
 
    // Confirmation dialog system
    window.mementorTTSConfirmations = {
        // Store the original confirm method
        originalConfirm: window.confirm,
        
        // Show a confirmation dialog
        confirm: function(message, options = {}) {
            return new Promise((resolve) => {
                const defaults = {
                    title: 'Confirm Action',
                    message: message,
                    confirmText: 'OK',
                    cancelText: 'Cancel',
                    type: 'info', // info, warning, error, success
                    icon: 'dashicons-info',
                    confirmType: 'primary', // primary, secondary, danger
                    cancelType: 'secondary'
                };
                
                const settings = $.extend({}, defaults, options);
                
                // Set icon based on type if not explicitly provided
                if (!options.icon) {
                    switch (settings.type) {
                        case 'warning':
                            settings.icon = 'dashicons-warning';
                            break;
                        case 'error':
                            settings.icon = 'dashicons-dismiss';
                            break;
                        case 'success':
                            settings.icon = 'dashicons-yes-alt';
                            break;
                        default:
                            settings.icon = 'dashicons-info';
                    }
                }
                
                // Remove any existing modals
                $('.mementor-tts-confirm-modal-overlay').remove();
                
                // Create modal structure
                const modal = $(
                    '<div class="mementor-tts-confirm-modal-overlay">' +
                        '<div class="mementor-tts-confirm-modal">' +
                            '<div class="mementor-tts-confirm-modal-header ' + settings.type + '">' +
                                '<span class="dashicons ' + settings.icon + '"></span>' +
                                '<h3 class="mementor-tts-confirm-modal-title">' + settings.title + '</h3>' +
                            '</div>' +
                            '<div class="mementor-tts-confirm-modal-content">' +
                                '<p>' + settings.message + '</p>' +
                            '</div>' +
                            '<div class="mementor-tts-confirm-modal-actions">' +
                                '<button class="mementor-tts-confirm-modal-btn mementor-tts-confirm-modal-btn-' + settings.cancelType + ' mementor-tts-confirm-cancel">' + settings.cancelText + '</button>' +
                                '<button class="mementor-tts-confirm-modal-btn mementor-tts-confirm-modal-btn-' + settings.confirmType + ' mementor-tts-confirm-ok">' + settings.confirmText + '</button>' +
                            '</div>' +
                        '</div>' +
                    '</div>'
                );
                
                // Add modal to body
                $('body').append(modal);
                
                // Show modal with animation
                setTimeout(() => {
                    modal.addClass('active');
                }, 10);
                
                // Handle confirm button click
                modal.find('.mementor-tts-confirm-ok').on('click', function() {
                    modal.removeClass('active');
                    setTimeout(() => {
                        modal.remove();
                    }, 300);
                    resolve(true);
                });
                
                // Handle cancel button click
                modal.find('.mementor-tts-confirm-cancel').on('click', function() {
                    modal.removeClass('active');
                    setTimeout(() => {
                        modal.remove();
                    }, 300);
                    resolve(false);
                });
                
                // Handle click outside modal to cancel
                modal.on('click', function(e) {
                    if ($(e.target).hasClass('mementor-tts-confirm-modal-overlay')) {
                        modal.removeClass('active');
                        setTimeout(() => {
                            modal.remove();
                        }, 300);
                        resolve(false);
                    }
                });
                
                // Handle ESC key to cancel
                $(document).on('keydown.mementorTTSModal', function(e) {
                    if (e.key === 'Escape') {
                        modal.removeClass('active');
                        setTimeout(() => {
                            modal.remove();
                        }, 300);
                        resolve(false);
                        $(document).off('keydown.mementorTTSModal');
                    }
                });
            });
        }
    };

    // Initialize event handlers for confirmation dialogs
    function initializeConfirmationHandlers() {
        // Handle confirmation for links with data-confirm attribute
        $(document).on('click', 'a[data-confirm]', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const link = $(this);
            const message = link.data('confirm');
            const title = link.data('confirm-title') || 'Confirm Action';
            const type = link.data('confirm-type') || 'warning';
            
            mementorTTSConfirmations.confirm(message, {
                title: title,
                type: type,
                confirmText: link.data('confirm-text') || 'OK',
                cancelText: link.data('cancel-text') || 'Cancel',
                confirmType: link.data('confirm-button-type') || 'primary'
            }).then(function(confirmed) {
                if (confirmed) {
                    window.location.href = link.attr('href');
                }
            });
            
            return false;
        });
        
        // Handle confirmation for forms with data-confirm attribute
        $(document).on('submit', 'form[data-confirm]', function(e) {
            e.preventDefault();
            
            const form = $(this);
            const message = form.data('confirm');
            const title = form.data('confirm-title') || 'Confirm Action';
            const type = form.data('confirm-type') || 'warning';
            
            mementorTTSConfirmations.confirm(message, {
                title: title,
                type: type,
                confirmText: form.data('confirm-text') || 'OK',
                cancelText: form.data('cancel-text') || 'Cancel',
                confirmType: form.data('confirm-button-type') || 'primary'
            }).then(function(confirmed) {
                if (confirmed) {
                    form.off('submit').submit();
                }
            });
            
            return false;
        });
        
        // Handle confirmation for buttons with data-confirm attribute
        $(document).on('click', 'button[data-confirm], input[type="button"][data-confirm], input[type="submit"][data-confirm]', function(e) {
            e.preventDefault();
            
            const button = $(this);
            const message = button.data('confirm');
            const title = button.data('confirm-title') || 'Confirm Action';
            const type = button.data('confirm-type') || 'warning';
            
            mementorTTSConfirmations.confirm(message, {
                title: title,
                type: type,
                confirmText: button.data('confirm-text') || 'OK',
                cancelText: button.data('cancel-text') || 'Cancel',
                confirmType: button.data('confirm-button-type') || 'primary'
            }).then(function(confirmed) {
                if (confirmed && button.is('input[type="submit"]')) {
                    button.closest('form').submit();
                } else if (confirmed) {
                    button.trigger('confirmed.mementorTTS');
                }
            });
        });
        
        // Handle Reset API Key button
        $(document).on('click', '.mementor-tts-reset-api-key', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const link = $(this);
            const apiKeyRow = link.closest('tr');
            const apiKeyInput = $('#mementor_tts_api_key');
            const apiStatus = $('.mementor-tts-api-status');
            
            // Store original button text for restoration if needed
            const originalButtonHtml = link.html();
            
            mementorTTSConfirmations.confirm(
                '<strong>Are you sure you want to reset your API settings?</strong><br><br>This will remove your API key and reset all related settings. This action cannot be undone.',
                {
                    title: 'Reset API Settings',
                    type: 'warning',
                    confirmText: 'Yes, Reset the API Key',
                    cancelText: 'Cancel',
                    confirmType: 'danger'
                }
            ).then(function(confirmed) {
                if (confirmed) {
                    // Show loading state
                    link.addClass('disabled').html('<span class="dashicons dashicons-update-alt"></span> Resetting...');
                    
                    // Make AJAX request to reset API settings
                    const ajaxUrl = mementorTTSGetAjaxUrl();
                    const ajaxData = {
                        action: 'mementor_tts_reset_api_settings',
                        nonce: mementorTTS.nonce
                    };
                    
                    $.ajax({
                        url: ajaxUrl,
                        type: 'POST',
                        data: ajaxData,
                        success: function(response) {
                            if (response.success) {
                                // Clear the API key input
                                apiKeyInput.val('');
                                
                                // Update API status
                                apiStatus.removeClass('connected').addClass('not-connected').text('Not Connected');
                                
                                // Add success animation to the row
                                apiKeyRow.addClass('mementor-tts-reset-success');
                                setTimeout(function() {
                                    apiKeyRow.removeClass('mementor-tts-reset-success');
                                }, 1500);
                                
                                // Show success notification with more details
                                mementorTTSShowNotification(
                                    '<strong>API settings reset successfully!</strong><br>Your API key has been removed and all related settings have been reset to their default values.',
                                    'success',
                                    5000
                                );
                                
                                // Reload the page after a short delay
                                setTimeout(function() {
                                    window.location.reload();
                                }, 2000);
                            } else {
                                // Show error notification
                                mementorTTSShowNotification(
                                    '<strong>Error:</strong> ' + (response.data.message || 'An error occurred while resetting API settings.'),
                                    'error',
                                    5000
                                );
                                
                                // Reset button state
                                link.removeClass('disabled').html(originalButtonHtml);
                            }
                        },
                        error: function(xhr, status, error) {
                            // Show error notification with details
                            mementorTTSShowNotification(
                                '<strong>Error:</strong> An error occurred while resetting API settings. Please try again later.',
                                'error',
                                5000
                            );
                            
                            // Reset button state
                            link.removeClass('disabled').html(originalButtonHtml);
                        }
                    });
                }
            });
            
            return false;
        });
    }

    // Initialize player preview functionality
    function initializePlayerPreview() {
        // Initialize sticky preview behavior
        const stickyPreview = $('.mementor-tts-sticky-preview');
        if (!stickyPreview.length) return;

        // Remove any existing spacer elements that might be left over
        $('.mementor-tts-preview-spacer').remove();

        const adminBar = $('#wpadminbar');
        const adminBarHeight = adminBar.length ? adminBar.height() : 32;
        
        // Store the initial position of the preview element
        let previewInitialPosition = 0;
        let previewInitialTop = 0;
        let windowScrollTop = 0;
        
        // Function to calculate and store the initial position of the preview
        function calculateInitialPosition() {
            // Get the element's position relative to the document
            previewInitialPosition = stickyPreview.offset().top;
            // Get the initial top position
            previewInitialTop = parseInt(stickyPreview.css('top'), 10) || 0;
            // Get current scroll position
            windowScrollTop = $(window).scrollTop();
            
            return previewInitialPosition;
        }
        
        // Calculate the initial position
        calculateInitialPosition();
        
        // Function to check if the preview should be sticky
        function updateStickyState() {
            // Current scroll position
            const scrollTop = $(window).scrollTop();
            
            // The threshold is the initial position minus the admin bar height
            const threshold = previewInitialPosition - adminBarHeight;
            
            // If we're scrolled past the threshold, make it sticky
            if (scrollTop > threshold) {
                if (!stickyPreview.hasClass('is-sticky')) {
                    stickyPreview.addClass('is-sticky');
                }
            } else {
                // Otherwise, ensure it's not sticky
                if (stickyPreview.hasClass('is-sticky')) {
                    stickyPreview.removeClass('is-sticky');
                }
            }
        }
        
        // Attach scroll event with throttling
        let isScrolling = false;
        let lastScrollTop = 0;
        $(window).on('scroll', function() {
            if (!isScrolling) {
                window.requestAnimationFrame(function() {
                    const currentScrollTop = $(window).scrollTop();
                    
                    // Special handling for scrolling back to top
                    const isScrollingUp = currentScrollTop < lastScrollTop;
                    const isNearTop = currentScrollTop < adminBarHeight;
                    
                    // Force recalculation when scrolling up and near the top
                    if (isScrollingUp && isNearTop) {
                        calculateInitialPosition();
                    }
                    
                    updateStickyState();
                    lastScrollTop = currentScrollTop;
                    isScrolling = false;
                });
                isScrolling = true;
            }
        });
        
        // Handle resize events with debouncing
        let resizeTimeout;
        $(window).on('resize', function() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function() {
                // Remove sticky class temporarily for accurate position calculation
                stickyPreview.removeClass('is-sticky');
                
                // Recalculate after a small delay to let the layout stabilize
                setTimeout(function() {
                    // Recalculate positions on resize
                    calculateInitialPosition();
                    // Then update the sticky state
                    updateStickyState();
                }, 50);
            }, 150);
        });
        
        // Also handle orientation changes on mobile
        $(window).on('orientationchange', function() {
            // Remove sticky class temporarily for accurate position calculation
            stickyPreview.removeClass('is-sticky');
            
            // Recalculate after orientation change is complete
            setTimeout(function() {
                calculateInitialPosition();
                updateStickyState();
            }, 300);
        });
        
        // Update after images and other resources load
        $(window).on('load', function() {
            calculateInitialPosition();
            updateStickyState();
        });
        
        // Initial check
        updateStickyState();
        
        // Also check after a short delay to account for any layout shifts
        setTimeout(function() {
            calculateInitialPosition();
            updateStickyState();
        }, 300);
        
        // Initialize using MementorAudioPlayer class
        const playerContainer = document.querySelector('.mementor-tts-preview-player');
        if (playerContainer) {
            new MementorAudioPlayer(playerContainer);
        }

        // Update player preview when settings change
        $('#player-settings-form input[type="text"], #player-settings-form select').on('change input', function() {
            const $this = $(this);
            const id = $this.attr('id');
            
            // Handle width settings immediately
            if (id === 'mementor_tts_player_width') {
                const widthSetting = $this.val();
                const previewPlayer = $('.mementor-tts-preview-player');
                const player = previewPlayer.find('.mementor-tts-player');
                
                // Remove existing width classes
                player.removeClass('mementor-tts-width-500 mementor-tts-width-custom mementor-tts-width-full');
                
                // Add appropriate width class
                switch(widthSetting) {
                    case 'content_width':
                        player.addClass('mementor-tts-width-500');
                        break;
                    case 'custom_width':
                        player.addClass('mementor-tts-width-custom');
                        break;
                    default:
                        player.addClass('mementor-tts-width-full');
                }
                
                // Update data attribute
                previewPlayer.attr('data-width', widthSetting);
            }
            
            // Handle custom width input immediately
            if (id === 'mementor_tts_custom_width') {
                const customWidth = $this.val();
                const previewPlayer = $('.mementor-tts-preview-player');
                previewPlayer.css('--mementor-tts-custom-width', customWidth + 'px');
            }
            
            updatePlayerPreview();
        });

        // Update player preview when checkboxes change
        $('#player-settings-form input[type="checkbox"]').on('change', function() {
            const $this = $(this);
            const id = $this.attr('id');
            const isChecked = $this.is(':checked');
            const previewPlayer = $('.mementor-tts-preview-player');

            // Handle specific controls immediately
            switch(id) {
                case 'mementor_tts_show_time':
                    previewPlayer.find('.mementor-tts-player .mementor-tts-time-display, .mementor-tts-player .mementor-tts-duration-display').css('display', isChecked ? '' : 'none');
                    break;
                case 'mementor_tts_show_volume':
                    previewPlayer.find('.mementor-tts-player .mementor-tts-volume-button').css('display', isChecked ? '' : 'none');
                    break;
                case 'mementor_tts_speed_control':
                    previewPlayer.find('.mementor-tts-player .mementor-tts-speed-button').css('display', isChecked ? '' : 'none');
                    break;
                case 'mementor_tts_show_download':
                    previewPlayer.find('.mementor-tts-player .mementor-tts-download-button').css('display', isChecked ? '' : 'none');
                    break;
                case 'mementor_tts_show_info':
                    previewPlayer.find('.mementor-tts-player .mementor-tts-info-button').css('display', isChecked ? '' : 'none');
                    // Also hide the info popup if info button is hidden
                    if (!isChecked) {
                        previewPlayer.find('.mementor-tts-info-popup').hide();
                    }
                    break;
                case 'mementor_tts_show_play_bg':
                    const customControls = previewPlayer.find('.mementor-tts-player .mementor-tts-custom-controls');
                    const playButton = previewPlayer.find('.mementor-tts-player .mementor-tts-play-button');
                    if (isChecked) {
                        customControls.attr('data-show-play-bg', 'true');
                        playButton.removeClass('no-background');
                    } else {
                        customControls.attr('data-show-play-bg', 'false');
                        playButton.addClass('no-background');
                    }
                    break;
            }

            // Still call updatePlayerPreview for any other updates needed
            updatePlayerPreview();
        });

        // Update player preview when color inputs change
        $('#player-settings-form input[type="color"]').on('input change', function() {
            // When color picker changes, update the associated text input
            const $this = $(this);
            const textInput = $this.siblings('.mementor-tts-color-text');
            if (textInput.length) {
                textInput.val($this.val().toUpperCase());
            }
            updatePlayerPreview();
        });

        // Handle manual hex color input
        $('.mementor-tts-color-text').on('keyup paste input change', function() {
            // When text input changes, update the associated color picker
            const $this = $(this);
            let colorValue = $this.val();
            
            // Ensure the color value starts with #
            if (!colorValue.startsWith('#')) {
                colorValue = '#' + colorValue;
            }
            
            // Update even if incomplete to show live preview
            const colorPicker = $this.siblings('input[type="color"]');
            if (colorPicker.length) {
                colorPicker.val(colorValue);
            }
            
            // Always update preview for immediate feedback
            updatePlayerPreview();
        });

        // Update player preview when number inputs change
        $('#player-settings-form input[type="number"]').on('input change', function() {
            updatePlayerPreview();
        });
        
        // Handle reset button click using event delegation (restored AJAX version, though onclick is used now)
        $(document).on('click', '#reset-player-settings', function(e) {
            // If onclick is present, it will likely handle this first.
            // This code remains as a fallback or reference.
            if ($(this).attr('onclick')) {
                return; // Let the onclick handler run
            }
            
            e.preventDefault();
            
            if (!confirm(mementorTTS.i18n.resetConfirm || 'Are you sure you want to reset all player settings to default values?')) {
                return;
            }

            const $button = $(this);
            $button.prop('disabled', true).text('Resetting...');

            $.ajax({
                url: mementorTTS.ajaxurl,
                type: 'POST',
                data: {
                    action: 'mementor_tts_reset_player_settings',
                    nonce: $('#mementor_tts_nonce').val() // Assumes mementor_tts_nonce exists
                },
                success: function(response) {
                    if (response.success) {
                        // Show success message
                        showNotification(mementorTTS.i18n.resetSuccess || 'Player settings reset successfully.', 'success');
                        
                        // Reload the page to show updated values
                        window.location.reload();
                    } else {
                        showNotification((response.data && response.data.message) || mementorTTS.i18n.resetError || 'Failed to reset player settings.', 'error');
                    }
                },
                error: function() {
                    showNotification(mementorTTS.i18n.resetError || 'Failed to reset player settings.', 'error');
                },
                complete: function() {
                    $button.prop('disabled', false).text('Reset');
                }
            });
        });
        
        function resetFormFields() {
            // Reset player position and width
            $('#mementor_tts_player_position').val('after_title');
            $('#mementor_tts_player_width').val('full_width');
            
            // Reset label settings
            $('#mementor_tts_show_player_label').prop('checked', true);
            $('#mementor_tts_player_label').val('Listen to this article:');
            $('#mementor_tts_player_label_position').val('left');
            $('#mementor_tts_player_label_margin').val('10');
            $('#mementor_tts_player_label_size').val('14');
            $('#mementor_tts_player_label_weight').val('400');
            $('#mementor_tts_player_label_color').val('#1d2327');
            
            // Reset controls
            $('#mementor_tts_show_time').prop('checked', true);
            $('#mementor_tts_speed_control').prop('checked', false);
            $('#mementor_tts_show_volume').prop('checked', true);
            $('#mementor_tts_show_download').prop('checked', false);
            $('#mementor_tts_show_info').prop('checked', false);
            $('#mementor_tts_show_play_bg').prop('checked', true);
            
            // Reset colors
            $('#mementor_tts_player_bg_color').val('#f6f7fb');
            $('#mementor_tts_player_border_color').val('#dcdcde');
            $('#mementor_tts_player_text_color').val('#000000');
            $('#mementor_tts_player_accent_color').val('#007cba');
            $('#mementor_tts_play_button_bg').val('#ffffff');
            $('#mementor_tts_timer_color').val('#50575e');
            $('#mementor_tts_progress_bar_default').val('#e0e0e0');
            $('#mementor_tts_progress_bar_playing').val('#2271b1');
            
            // Reset fonts and padding
            $('#mementor_tts_play_icon_size').val('24');
            $('#mementor_tts_font_size').val('14');
            $('#mementor_tts_player_padding').val('12');
            
            // Reset max width settings
            $('#mementor_tts_player_max_width').val('100');
            $('#mementor_tts_player_max_width_unit').val('%');
            $('#mementor_tts_player_alignment').val('left');
            
            // Reset margin settings
            $('#mementor_tts_player_margin_top').val('0');
            $('#mementor_tts_player_margin_bottom').val('0');
            
            // Trigger change event on all inputs to update any dependent UI
            $('#player-settings-form input, #player-settings-form select').trigger('change');
        }

        function showNotification(message, type) {
            const $notice = $('<div class="notice notice-' + type + ' is-dismissible"><p></p></div>');
            $notice.find('p').text(message);
            $('.wrap h2').first().after($notice);
            
            // Auto dismiss after 3 seconds
            setTimeout(function() {
                $notice.fadeOut(function() {
                    $(this).remove();
                });
            }, 3000);
        }
        
        // Show/hide custom colors based on theme selection
        $('#mementor_tts_player_theme').on('change', function() {
            if ($(this).val() === 'custom') {
                $('#mementor_tts_custom_colors').show();
            } else {
                $('#mementor_tts_custom_colors').hide();
            }
        });
        
        // Initialize player preview
        updatePlayerPreview();

        // Handle max width and unit changes
        $('#mementor_tts_player_max_width, #mementor_tts_player_max_width_unit').on('input change', function() {
            const maxWidth = $('#mementor_tts_player_max_width').val();
            const unit = $('#mementor_tts_player_max_width_unit').val();
            const maxWidthValue = maxWidth + unit;
            
            // Update the CSS variable
            document.documentElement.style.setProperty('--mementor-tts-max-width', maxWidthValue);
            
            // Update the preview player directly
            const previewPlayer = $('.mementor-tts-preview-player');
            const playerContainer = previewPlayer.find('.mementor-tts-player-container');
            
            // Apply max-width to both the preview player and its container
            previewPlayer.css('max-width', maxWidthValue);
            playerContainer.css('max-width', maxWidthValue);
            
            // Force refresh of player width classes
            handlePlayerWidth();
        });

        // Handle alignment changes
        $('#mementor_tts_player_alignment').on('change', function() {
            const alignment = $(this).val();
            const previewPlayer = $('.mementor-tts-preview-player');
            
            // Update data attribute
            previewPlayer.attr('data-alignment', alignment);
            
            // Update margins based on alignment
            if (alignment === 'left') {
                previewPlayer.css({
                    'margin-left': '0 !important',
                    'margin-right': 'auto !important'
                });
            } else if (alignment === 'center') {
                previewPlayer.css({
                    'margin-left': 'auto !important',
                    'margin-right': 'auto !important'
                });
            } else if (alignment === 'right') {
                previewPlayer.css({
                    'margin-right': '0 !important',
                    'margin-left': 'auto !important'
                });
            }
        });

        // Initialize alignment on page load
        $(document).ready(function() {
            const initialAlignment = $('#mementor_tts_player_alignment').val();
            $('#mementor_tts_player_alignment').trigger('change');
        });

        // Initialize max width on page load
        const maxWidth = $('#mementor_tts_player_max_width').val();
        const unit = $('#mementor_tts_player_max_width_unit').val();
        $('.mementor-tts-preview-player').css('max-width', maxWidth + unit);
    }

    // Initialize page-specific functionality
    function initializePageFunctionality() {
        // Initialize confirmation handlers
        initializeConfirmationHandlers();
        
        const currentPage = getCurrentPage();
        
        // Add body class based on current page
        if (currentPage) {
            $('body').addClass('mementor-tts-' + currentPage + '-page');
        }
        
        // Initialize sticky sidebar if it exists
        if ($('.mementor-tts-sidebar').length) {
            initStickySidebar();
            enhanceSidebarUpgradeSection();
        }
        
        // Lock sections if no API key is found (except on settings page)
        lockSectionsIfNoApiKey();
        
        // Check if API key is connected
        if (mementorTTSIsApiKeyConnected()) {
            // If on voices page, initialize voice functionality
            if (currentPage === 'voices') {
                mementorTTSInitializeVoiceFunctionality();
                mementorTTSInitializeVoiceFilters();
            }
            
            // If on player page, initialize player preview
            if (currentPage === 'player') {
                initializePlayerPreview();
            }
            
            // If on statistics page, initialize statistics
            if (currentPage === 'statistics') {
                initializeStatistics();
            }
        } else {
            // Show API key notification if needed
            mementorTTSShowApiKeyNotification();
        }
    }

    // Add a debounce function
    function mementorTTSDebounce(func, wait) {
        let timeout;
        return function() {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                func.apply(context, args);
            }, wait);
        };
    }

    // Replace the document ready function to prevent double initialization
    $(document).ready(function() {
        // Use a single initialization flag
        if (window.mementorTTSInitialized) {
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('TTS Plugin: Already initialized, skipping');
            }
            return;
        }
        window.mementorTTSInitialized = true;

        // Only log initialization if debug mode is enabled
        if (window.mementorTTS && window.mementorTTS.isDebug) {
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('TTS Plugin: Initializing admin JS');
            }
        }
        
        // Initialize the base functionality
        initializeConfirmationHandlers();
        
        // Setup tab navigation
        $('.mementor-tts-nav-tab-wrapper a').on('click', function(e) {
            e.preventDefault();
            const tab = $(this).attr('href').replace('#', '');
            navigateToTab(tab);
        });
        
        // Configure tabs based on URL
        if (window.location.hash) {
            const tab = window.location.hash.replace('#', '');
            navigateToTab(tab);
        }
        
        // Create a debounced version of the load voices function
        const debouncedLoadVoices = mementorTTSDebounce(mementorTTSLoadVoices, 300);
        
        // Initialize the voice list on first load
        if ($('#mementor-tts-voice-list').length) {
            debouncedLoadVoices();
        }
        
        // Listen for model changes
        $('#mementor_tts_model').on('change', debouncedLoadVoices);
        
        // Listen for language changes
        $('#mementor_tts_language').on('change', debouncedLoadVoices);
        
        // Handle API key validation
        $('#mementor-tts-verify-api-key').on('click', function(e) {
            e.preventDefault();
            validateAPIKey();
        });
        
        // Handle the reset API key button
        $(document).on('confirmed.mementorTTS', '.mementor-tts-reset-api-key', function() {
            resetAPIKey();
        });
        
        // Handle sample text generation
        $('.mementor-tts-action-listen').on('click', function(e) {
            e.preventDefault();
            const voiceId = $(this).data('voice-id');
            const sampleText = $(this).closest('tr').find('.mementor-tts-voice-sample-text').val();
            generateSampleAudio(voiceId, sampleText);
        });
        
        // Handle sample text keypress
        $('.mementor-tts-voice-sample-text').on('keypress', function(e) {
            if (e.which === 13) {
                e.preventDefault();
                const voiceId = $(this).closest('tr').find('.mementor-tts-action-listen').data('voice-id');
                generateSampleAudio(voiceId, $(this).val());
            }
        });
        
// Handle voice selection
$(document).on('click', '.mementor-tts-voice-use-button', function(e) {
    // Check if this is a PRO voice and user doesn't have PRO
    const button = $(this);
    const voiceRow = button.closest('.tts-voice-item, tr');

    // Get the voice name from the row for better logging
    const voiceName = button.data('voice-name');

    // The primary indicator is now the data-pro attribute which is set based on available_for_tiers
    // But we'll still check multiple indicators as a fallback
    // 1. Check if the button has data-pro=true (primary indicator set from available_for_tiers)
    // 2. Check if the row has the pro-voice class (also set from available_for_tiers)
    // 3. Check if the voice name contains specific PRO indicators (fallback)
    const hasProData = button.data('pro') === true;
    const hasProClass = voiceRow.hasClass('pro-voice');
    const hasProName = voiceName && (
        voiceName.includes('Professional') || 
        voiceName.includes('Podcast') ||
        voiceName.includes('Audiobooks')
    );
    
    // If any of these indicators are true, consider it a PRO voice
    const isProVoice = hasProData || hasProClass || hasProName;
    
    if (window.mementorTTSDebug) {
        window.mementorTTSDebug.log('TTS Plugin: Button clicked for voice:', voiceName);
    }
    if (window.mementorTTSDebug) {
        window.mementorTTSDebug.log('TTS Plugin: PRO detection - class:', hasProClass, 'data:', hasProData, 'name:', hasProName, 'final:', isProVoice);
    }
    
    // Check if user has PRO
    let hasPro = false;
    if (typeof mementorTTS !== 'undefined') {
        if (mementorTTS.pro_status && mementorTTS.pro_status.is_pro) {
            hasPro = true;
        } else if (mementorTTS.isPro) {
            hasPro = true;
        }
    }
    
    // If this is a PRO voice and user doesn't have PRO, prevent selection
    if (isProVoice && !hasPro) {
        e.preventDefault();
        e.stopPropagation();
        mementorTTSShowNotification('This is a PRO voice. Please upgrade to PRO to use this voice.', 'error');
        return false;
    }
    
    // Continue with voice selection
    const voiceId = button.data('voice-id');
    // voiceName already defined above
    const language = $('#mementor_tts_language').val(); // Get the currently selected language
    
    // Find the voice in the filteredVoices array to get its free_users_allowed property
    let free_users_allowed = true; // Default to true for safety
    free_users_allowed = !isProVoice; // If it's a PRO voice, free_users_allowed is false
    
    if (window.mementorTTSDebug) {
        window.mementorTTSDebug.log(`TTS Plugin: Voice selection - isProVoice: ${isProVoice}, free_users_allowed: ${free_users_allowed}, row has pro-voice class: ${voiceRow.hasClass('pro-voice')}`);
    }
    
    if (window.mementorTTSDebug) {
        window.mementorTTSDebug.log(`TTS Plugin: Selecting voice ${voiceName} (${voiceId}), free_users_allowed: ${free_users_allowed}`);
    }
    
    // Remove selected class and text from all buttons
    $('.mementor-tts-voice-use-button').removeClass('selected').text('Use Voice');
    $('.tts-voice-item').removeClass('is-selected');

    // Add selected class and update text for clicked button
    button.addClass('selected').text('Selected');
    button.closest('.tts-voice-item').addClass('is-selected');
    
    // Update hidden input fields
    $('#mementor_tts_voice').val(voiceId);
    $('#mementor_tts_voice_name').val(voiceName);
    
    // Save selected voice via AJAX
    $.ajax({
        url: mementorTTSGetAjaxUrl(),
        type: 'POST',
        data: {
            action: 'mementor_tts_save_voice',
            voice_id: voiceId,
            voice_name: voiceName,
            language: language, // Add language to the saved data
            free_users_allowed: free_users_allowed, // Add free_users_allowed flag
            nonce: $('#mementor_tts_nonce').val()
        },
        success: function(response) {
            if (response.success) {
                mementorTTSShowNotification('Voice "' + voiceName + '" set as default.', 'success');
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('TTS Plugin: Voice saved with language: ' + language);
                }
            } else {
                // Show the error message from the server
                var errorMessage = 'Failed to set default voice.';
                if (response.data && response.data.message) {
                    errorMessage = response.data.message;
                }
                mementorTTSShowNotification(errorMessage, 'error');
                
                // Revert button state on error
                button.removeClass('selected').text('Use Voice');
                
                // If the server provided a fallback voice, update the UI to reflect it
                if (response.data && response.data.voice_id && response.data.voice_name) {
                    if (window.mementorTTSDebug) {
                        window.mementorTTSDebug.log('TTS Plugin: Server rejected PRO voice, using fallback voice:', response.data.voice_name);
                    }
                    
                    // Update hidden input fields with the fallback voice
                    $('#mementor_tts_voice').val(response.data.voice_id);
                    $('#mementor_tts_voice_name').val(response.data.voice_name);
                    
                    // Find the button for the fallback voice and mark it as selected
                    $('.mementor-tts-voice-use-button').each(function() {
                        var $btn = $(this);
                        if ($btn.data('voice-id') === response.data.voice_id) {
                            $btn.addClass('selected').text('Selected');
                        }
                    });
                }
            }
        },
        error: function() {
            mementorTTSShowNotification('An error occurred while setting the default voice.', 'error');
            // Revert button state on error
            button.removeClass('selected').text('Use Voice');
        }
    });
});
        
        // Setup color pickers
        if ($('.mementor-tts-color-picker').length && $.fn.wpColorPicker) {
            $('.mementor-tts-color-picker').wpColorPicker();
        }
        
        // Setup audio player toggle
        $('.mementor-tts-audio-toggle').on('click', function(e) {
            e.preventDefault();
            $(this).closest('.mementor-tts-audio-container').toggleClass('collapsed');
        });
    });

    // Function to lock all mementor-tts-section elements if no API key is found
    function lockSectionsIfNoApiKey() {
        const currentPage = getCurrentPage();
        
        // Skip on settings page
        if (currentPage === 'settings') {
            return;
        }
        
        // If API key is not connected
        if (!mementorTTSIsApiKeyConnected()) {
            // Add API notice only once at the top of the page
            const $firstSection = $('.mementor-tts-section').first();
            
            // Only add the notice if it doesn't already exist
            if ($('.mementor-tts-pro-notice').length === 0) {
                // Create API notice
                const $notice = $('<div class="mementor-tts-pro-notice"><p>' + 
                    'Please add your Elevenlabs API key in the <a href="admin.php?page=text-to-speech-tts-settings">Settings page</a> ' + 
                    'before starting to use the plugin. You will not be able to use the plugin without an API key.' + 
                    '</p></div>');
                
                // Insert notice before the first section
                $firstSection.before($notice);
            }
            
            // Apply disabled styling to all section content
            $('.mementor-tts-section-content').each(function() {
                const $content = $(this);
                if (!$content.hasClass('mementor-tts-settings-content')) {
                    $content.addClass('mementor-tts-settings-content');
                }
            });
            
            // Also apply to any other content sections that might have different class names
            $('.mementor-tts-section').each(function() {
                const $section = $(this);
                // Skip the section header
                $section.children().not('.mementor-tts-section-header').each(function() {
                    const $element = $(this);
                    if (!$element.hasClass('mementor-tts-settings-content') && !$element.hasClass('mementor-tts-pro-notice')) {
                        $element.addClass('mementor-tts-settings-content');
                    }
                });
            });
            
            // Specifically target the blocks container which might not be caught by the above selectors
            $('.mementor-tts-blocks-container').each(function() {
                const $container = $(this);
                if (!$container.hasClass('mementor-tts-settings-content')) {
                    $container.addClass('mementor-tts-settings-content');
                }
            });
            
            // Target individual blocks as well
            $('.mementor-tts-block').each(function() {
                const $block = $(this);
                if (!$block.hasClass('mementor-tts-settings-content')) {
                    $block.addClass('mementor-tts-settings-content');
                }
            });
            
            // Apply to any form elements to ensure they can't be interacted with
            $('form:not(.mementor-tts-settings-page form)').each(function() {
                const $form = $(this);
                if (!$form.hasClass('mementor-tts-settings-content')) {
                    $form.addClass('mementor-tts-settings-content');
                }
            });
        }
    }

    // Check if API key is connected
    function mementorTTSIsApiKeyConnected() {
        // Check if the global variable exists and is true
        if (typeof mementorTTSApiKeyConnected !== 'undefined' && mementorTTSApiKeyConnected === true) {
            return true;
        }
        
        // First check if the API key status element exists and has the connected class
        if ($('#mementor-tts-api-key-status').length && $('#mementor-tts-api-key-status').hasClass('connected')) {
            return true;
        }
        
        // Alternative check: if there are no locked tabs, then the API key is connected
        // or the user is using the PRO version
        return $('.mementor-tts-nav-item.locked').length === 0;
    }

    // Show API key notification
    function mementorTTSShowApiKeyNotification() {
        // Function disabled - no slide-in notifications
        return;
    }

    // Initialize sticky sidebar
    function initStickySidebar() {
        // Using CSS position: sticky instead of JavaScript positioning
        const sidebar = $('.mementor-tts-sidebar');
        if (sidebar.length) {
            // Ensure the sidebar has the correct width but don't change position
            const updateSidebarWidth = function() {
                // Only update width, not position
                const parentWidth = sidebar.parent().width();
                const sidebarWidth = sidebar.width();
                const sidebarPercentage = (sidebarWidth / parentWidth) * 100;
                
                // Make sure position is not overridden
                sidebar.css({
                    'width': sidebarPercentage + '%',
                    'position': 'sticky' // Ensure sticky position is maintained
                });
            };
            
            // Update width on window resize
            $(window).on('resize', updateSidebarWidth);
            
            // Initial width update
            updateSidebarWidth();
        }
    }

    // Initialize voice functionality
    function mementorTTSInitializeVoiceFunctionality() {
        // Check if nonce is available
        if (!$('#mementor_tts_nonce').length) {
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.error('TTS Plugin: Nonce field not found');
            }
            mementorTTSShowNotification('Error: Security token not found. Please refresh the page.', 'error');
            return;
        }

        // Initialize voice filters
        mementorTTSInitializeVoiceFilters();

        // Handle model and language changes
        $('#mementor_tts_model, #mementor_tts_language').on('change', function() {
            // If this is a language change and not English, ensure we're using a compatible model
            if ($(this).attr('id') === 'mementor_tts_language' && $(this).val() !== 'en') {
                const currentModel = $('#mementor_tts_model').val();
                
                // If using the monolingual model, switch to Flash model for non-English languages
                if (currentModel === 'eleven_monolingual_v1') {
                    if (window.mementorTTSDebug) {
                        window.mementorTTSDebug.log('TTS Plugin: Switching to eleven_flash_v2_5 model for non-English language: ' + $(this).val());
                    }
                    $('#mementor_tts_model').val('eleven_flash_v2_5');
                }
            }
            
            mementorTTSLoadVoices();
        });
        
        // Voice selection is handled by the global handler above (line ~915)
        
        // Handle voice cache clearing
        $('#clear-voice-cache').on('click', function() {
            $(this).find('.dashicons').addClass('spin');
            
            // Explicitly clear all voice-related localStorage cache
            for (let key in localStorage) {
                if (key.startsWith('mementor_tts_voices_')) {
                    localStorage.removeItem(key);
                }
            }

            $.ajax({
                url: mementorTTSGetAjaxUrl(),
                type: 'POST',
                data: {
                    action: 'mementor_tts_clear_voice_cache',
                    nonce: $('#mementor_tts_nonce').val()
                },
                success: function(response) {
                    if (response.success) {
                        // Reload voices after clearing cache
                        mementorTTSLoadVoices();
                    } else {
                        mementorTTSShowNotification('Failed to clear voice cache.', 'error');
                    }
                    $('#clear-voice-cache').find('.dashicons').removeClass('spin');
                },
                error: function() {
                    mementorTTSShowNotification('An error occurred while clearing the voice cache.', 'error');
                    $('#clear-voice-cache').find('.dashicons').removeClass('spin');
                }
            });
        });

        // Load voices from the server
        mementorTTSLoadVoices();
    }

    // Initialize voice filters
    function mementorTTSInitializeVoiceFilters() {
        // Voice search
        $('#voice-search').on('input', function() {
            filterVoices();
        });
        
        // Filter dropdowns
        $('#mementor-tts-filter-gender, #mementor-tts-filter-age, #mementor-tts-filter-accent, #mementor-tts-filter-use-case').on('change', function() {
            filterVoices();
        });
        
        // Filter voices based on language
        function filterVoices() {
            const searchTerm = $('#voice-search').val().toLowerCase();
            const selectedGender = $('#mementor-tts-filter-gender').val();
            const selectedAge = $('#mementor-tts-filter-age').val();
            const selectedAccent = $('#mementor-tts-filter-accent').val();
            const selectedUseCase = $('#mementor-tts-filter-use-case').val();
            
            $('.mementor-tts-voice-table tbody tr').each(function() {
                const row = $(this);
                const voiceName = row.find('.mementor-tts-voice-name-header h4').text().toLowerCase();
                const voiceDetails = row.find('.mementor-tts-voice-details').text().toLowerCase();
                const gender = row.find('.mementor-tts-gender-badge').data('gender');
                const age = row.find('.mementor-tts-age-badge').data('age');
                const accent = row.find('.mementor-tts-voice-details .accent').text();
                const useCase = row.find('.mementor-tts-voice-details .use-case').text();
                
                const matchesSearch = searchTerm === '' || 
                                     voiceName.includes(searchTerm) || 
                                     voiceDetails.includes(searchTerm);
                
                const matchesGender = selectedGender === '' || gender === selectedGender;
                const matchesAge = selectedAge === '' || age === selectedAge;
                const matchesAccent = selectedAccent === '' || accent === selectedAccent;
                const matchesUseCase = selectedUseCase === '' || useCase === selectedUseCase;
                
                if (matchesSearch && matchesGender && matchesAge && matchesAccent && matchesUseCase) {
                    row.show();
                } else {
                    row.hide();
                }
            });
            
            // Show message if no voices match
            if ($('.mementor-tts-voice-table tbody tr:visible').length === 0) {
                if ($('.no-voices-message').length === 0) {
                    $('.mementor-tts-voice-table').after('<p class="no-voices-message">No voices match your filters. Please adjust your criteria.</p>');
                }
            } else {
                $('.no-voices-message').remove();
            }
        }
    }

    // Initialize voice preview
    function initVoicePreview() {
        $('.mementor-tts-voice-play-button').on('click', function() {
            const button = $(this);
            const voiceId = button.data('voice-id');
            const audioContainer = button.closest('.mementor-tts-voice-preview-container').find('.mementor-tts-voice-audio');
            const previewUrl = button.data('preview-url');
            
            // If audio is already loaded, toggle play/pause
            if (audioContainer.find('audio').length) {
                const audio = audioContainer.find('audio')[0];
                
                if (audio.paused) {
                    // Pause all other audio elements
                    $('audio').each(function() {
                        if (this !== audio) {
                            this.pause();
                            $(this).closest('.mementor-tts-voice-preview-container').find('.mementor-tts-voice-play-button').removeClass('playing')
                                .find('.dashicons').removeClass('dashicons-controls-pause').addClass('dashicons-controls-play');
                        }
                    });
                    
                    audio.play();
                    button.addClass('playing')
                        .find('.dashicons').removeClass('dashicons-controls-play').addClass('dashicons-controls-pause');
                } else {
                    audio.pause();
                    button.removeClass('playing')
                        .find('.dashicons').removeClass('dashicons-controls-pause').addClass('dashicons-controls-play');
                }
                
                return;
            }
            
            // Show loading indicator
            button.addClass('loading');
            button.prop('disabled', true);
            
            // Create audio element with preview URL
            const audioElement = $('<audio controls preload="auto"><source src="' + previewUrl + '" type="audio/mpeg">Your browser does not support the audio element.</audio>');
            audioContainer.html(audioElement);
            
            // Play audio
            const audio = audioElement[0];
            
            // Pause all other audio elements
            $('audio').each(function() {
                if (this !== audio) {
                    this.pause();
                    $(this).closest('.mementor-tts-voice-preview-container').find('.mementor-tts-voice-play-button').removeClass('playing')
                        .find('.dashicons').removeClass('dashicons-controls-pause').addClass('dashicons-controls-play');
                }
            });
            
            audio.play();
            button.addClass('playing')
                .find('.dashicons').removeClass('dashicons-controls-play').addClass('dashicons-controls-pause');
            
            // Handle audio end
            audio.addEventListener('ended', function() {
                button.removeClass('playing')
                    .find('.dashicons').removeClass('dashicons-controls-pause').addClass('dashicons-controls-play');
            });
            
            // Handle audio play/pause
            audio.addEventListener('play', function() {
                button.addClass('playing')
                    .find('.dashicons').removeClass('dashicons-controls-play').addClass('dashicons-controls-pause');
            });
            
            audio.addEventListener('pause', function() {
                button.removeClass('playing')
                    .find('.dashicons').removeClass('dashicons-controls-pause').addClass('dashicons-controls-play');
            });
            
            // Remove loading state
            button.removeClass('loading');
            button.prop('disabled', false);
        });
    }

    // Function to get consistent avatar based on voice ID
    function getVoiceAvatar(voiceId, gender) {
        // Define arrays with only existing avatar files
        const femaleAvatars = [
            'Female_2_1.svg', 'Female2_2.svg', 'Female2_3.svg', 'Female2_5.svg',
            'Female2_11.svg', 'Female2_12.svg', 'Female2_13.svg', 'Female2_14.svg', 'Female2_15.svg',
            'Female2_21.svg', 'Female2_22.svg', 'Female2_23.svg', 'Female2_24.svg', 'Female2_25.svg',
            'Female2_31.svg', 'Female2_32.svg', 'Female2_33.svg', 'Female2_34.svg', 'Female2_35.svg',
            'Female2_41.svg', 'Female2_42.svg', 'Female2_43.svg', 'Female2_44.svg', 'Female2_45.svg',
            'Female2_46.svg'
        ];
        
        const maleAvatars = [
            'Male2_6.svg', 'Male2_7.svg', 'Male2_8.svg', 'Male2_9.svg', 'Male2_10.svg',
            'Male2_16.svg', 'Male2_17.svg', 'Male2_18.svg', 'Male2_19.svg', 'MAle2_20.svg',
            'Male2_26.svg', 'Male2_27.svg', 'Male2_28.svg', 'Male2_29.svg', 'Male2_30.svg',
            'Male2_36.svg', 'Male2_37.svg', 'Male2_38.svg', 'Male2_39.svg', 'Male2_40.svg',
            'Male2_47.svg', 'Male2_48.svg', 'Male2_49.svg', 'Male2_50.svg'
        ];
        
        const nonBinaryAvatars = ['NONB2_4.svg'];
        
        let avatars;
        switch(gender?.toLowerCase()) {
            case 'female':
                avatars = femaleAvatars;
                break;
            case 'male':
                avatars = maleAvatars;
                break;
            case 'non-binary':
            case 'nonbinary':
                avatars = nonBinaryAvatars;
                break;
            default:
                avatars = [...femaleAvatars, ...maleAvatars, ...nonBinaryAvatars];
        }

        // Create a hash from the voice ID to get a consistent index
        let hash = 0;
        for (let i = 0; i < voiceId.length; i++) {
            hash = ((hash << 5) - hash) + voiceId.charCodeAt(i);
            hash = hash & hash; // Convert to 32-bit integer
        }
        
        // Use the hash to get a consistent index for this voice ID
        const index = Math.abs(hash) % avatars.length;
        return mementorTTS.pluginUrl + 'admin/images/avatar/' + avatars[index];
    }

    // Load voices from the server
    function mementorTTSLoadVoices() {
        const voiceList = $('#mementor-tts-voice-list');
        const modelId = $('#mementor_tts_model').val();
        const language = $('#mementor_tts_language').val();
        
        // Check if PRO status is available and determine if user has PRO
        let hasPro = false;
        if (typeof isPro !== 'undefined') {
            // Check if global isPro variable exists (from settings.php or voices.php)
            hasPro = isPro;
        } else if (typeof mementorTTS !== 'undefined') {
            // Check if mementorTTS object exists and has the pro_status property
            if (mementorTTS.pro_status && mementorTTS.pro_status.is_pro) {
                hasPro = true;
            } else if (mementorTTS.isPro) {
                hasPro = true;
            }
        }
        
        // Log PRO status for debugging
        if (window.mementorTTS && window.mementorTTS.isDebug) {
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('TTS Plugin: PRO status detected as:', hasPro);
            }
        }
        
        // No longer block any languages - we now allow 1 voice per language for free users
        // The voice restriction is handled when displaying individual voices
        
        if (window.mementorTTS && window.mementorTTS.isDebug) {
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('TTS Plugin: Loading voices with model_id =', modelId, 'language =', language);
            }
        }

        // Show loading state
        voiceList.html('<div class="tts-voice-loading"><span class="dashicons dashicons-update-alt spinning"></span> Loading voices...</div>');

        // Store a request identifier to prevent duplicate calls
        window.mementorTTSLastRequestId = modelId + '_' + language;

        fetchVoicesFromServer(modelId, language, voiceList);
    }

    // Helper function to fetch voices from server
    function fetchVoicesFromServer(modelId, language, voiceList) {
        $.ajax({
            url: mementorTTSGetAjaxUrl(),
            type: 'POST',
            data: {
                action: 'mementor_tts_get_voices',
                model_id: modelId,
                language: language,
                nonce: mementorTTS.nonce
            },
            success: function(response) {
                // Verify this is not a stale response from a previous request
                if (window.mementorTTSLastRequestId !== modelId + '_' + language) {
                    return;
                }
                
                if (response.success && response.data && Array.isArray(response.data.voices)) {
                    processVoicesResponse(response);
                } else {
                    voiceList.html('<tr><td colspan="5" class="mementor-tts-error">Failed to load voices. The response was invalid.</td></tr>');
                }
            },
            error: function(xhr, status, error) {
                voiceList.html('<tr><td colspan="5" class="mementor-tts-error">Failed to load voices. Please try again.</td></tr>');
                
                // Add detailed error logging
                if (window.mementorTTS && window.mementorTTS.isDebug) {
                    if (window.mementorTTSDebug) {
                        window.mementorTTSDebug.error('TTS Plugin: Failed to load voices for language:', language);
                        window.mementorTTSDebug.error('TTS Plugin: Error details:', { xhr, status, error });
                        if (xhr.responseText) {
                            try {
                                const errorResponse = JSON.parse(xhr.responseText);
                                window.mementorTTSDebug.error('TTS Plugin: Server error response:', errorResponse);
                            } catch (e) {
                                window.mementorTTSDebug.error('TTS Plugin: Raw error response:', xhr.responseText);
                            }
                        }
                    }
                }
            }
        });
    }

    // Process voices response (moved from success callback for reuse)
    function processVoicesResponse(response) {
        const voiceList = $('#mementor-tts-voice-list');
        const voices = response.data.voices;
        
        // Update voice count badge if available
        if (response.data.voice_count !== undefined && response.data.voice_limit !== undefined) {
            const voiceCount = response.data.voice_count;
            const voiceLimit = response.data.voice_limit;
            const percentage = Math.round((voiceCount / voiceLimit) * 100);
            
            // Update the badge text
            const badgeText = `${voiceCount} of ${voiceLimit} (${percentage}%)`;
            $('#mementor-tts-voice-count').text(badgeText);
            
            // Add color coding based on usage percentage
            if (percentage >= 90) {
                $('#mementor-tts-voice-count').removeClass('count-normal count-warning').addClass('count-critical');
            } else if (percentage >= 70) {
                $('#mementor-tts-voice-count').removeClass('count-normal count-critical').addClass('count-warning');
            } else {
                $('#mementor-tts-voice-count').removeClass('count-warning count-critical').addClass('count-normal');
            }
        }
        
        const selectedLanguage = $('#mementor_tts_language').val();
        if (window.mementorTTS && window.mementorTTS.isDebug) {
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('TTS Plugin: Processing', voices.length, 'voices');
                window.mementorTTSDebug.log('TTS Plugin: Selected language =', selectedLanguage);
            }
        }

        // Debug the response specifically for Norwegian
        if (selectedLanguage === 'no') {
            if (window.mementorTTS && window.mementorTTS.isDebug) {
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('TTS Plugin: Norwegian response received', response);
                    window.mementorTTSDebug.log('TTS Plugin: Response voices count', response.data?.voices?.length);
                    
                    // Log each voice and its language code
                    if (response.data && response.data.voices) {
                        window.mementorTTSDebug.log('TTS Plugin: Norwegian voices details:');
                        response.data.voices.forEach(voice => {
                            const langCode = voice.labels?.language || voice.language || 'unknown';
                            window.mementorTTSDebug.log(`Voice: ${voice.name}, Language: ${langCode}`);
                        });
                    }
                }
            }
        }
        
        // Log available language codes for debugging
        const languages = new Set();
        voices.forEach(voice => {
            const lang = voice.labels?.language || voice.language || 'unknown';
            languages.add(lang);
        });
        if (window.mementorTTS && window.mementorTTS.isDebug) {
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('TTS Plugin: Available languages in API response:', Array.from(languages).sort());
            }
        }
        
        // Extra debug logging for Norwegian
        if (selectedLanguage === 'no') {
            if (window.mementorTTS && window.mementorTTS.isDebug) {
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('TTS Plugin: Searching for Norwegian voices...');
                    const norwegianVoices = voices.filter(voice => {
                        const voiceLanguage = voice.labels?.language || voice.language || '';
                        window.mementorTTSDebug.log(`Voice ${voice.name} has language: "${voiceLanguage}"`);
                        return voiceLanguage === 'no';
                    });
                    window.mementorTTSDebug.log('TTS Plugin: Found', norwegianVoices.length, 'Norwegian voices with exact "no" code');
                    
                    // Also check for other Norwegian-like codes
                    const otherNorwegianVoices = voices.filter(voice => {
                        const voiceLanguage = voice.labels?.language || voice.language || '';
                        return voiceLanguage === 'nb' || 
                               voiceLanguage === 'nn' || 
                               voiceLanguage.startsWith('no-') || 
                               voiceLanguage.startsWith('nb-') ||
                               voiceLanguage.startsWith('nn-') ||
                               voiceLanguage.includes('norw');
                    });
                    window.mementorTTSDebug.log('TTS Plugin: Found', otherNorwegianVoices.length, 'other Norwegian-like voices that we\'re not showing');
                    if (otherNorwegianVoices.length > 0) {
                        otherNorwegianVoices.forEach(voice => {
                            const lang = voice.labels?.language || voice.language || 'unknown';
                            window.mementorTTSDebug.log(`- Norwegian-like voice: ${voice.name}, language code: "${lang}"`);
                        });
                    }
                }
            }
        }
        
        // Check if a PRO language is selected and show notice for free users
        let hasPro = false;
        if (typeof isPro !== 'undefined') {
            // Check if global isPro variable exists (from settings.php or voices.php)
            hasPro = isPro;
        } else if (typeof mementorTTS !== 'undefined') {
            // Check if mementorTTS object exists and has the pro_status property
            if (mementorTTS.pro_status && mementorTTS.pro_status.is_pro) {
                hasPro = true;
            } else if (mementorTTS.isPro) {
                hasPro = true;
            }
        }
        
        // Log PRO status for debugging
        if (window.mementorTTS && window.mementorTTS.isDebug) {
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('TTS Plugin: processVoicesResponse - PRO status detected as:', hasPro);
            }
        }
        
        // Hide PRO notice - we now allow 1 voice per language for free users
        $('#mementor-tts-pro-language-notice').hide();
        
        // Filter voices by selected language - only show voices that match the selected language
        let filteredVoices = voices;
        if (selectedLanguage) {
            if (window.mementorTTS && window.mementorTTS.isDebug) {
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('TTS Plugin: Filtering voices by primary language:', selectedLanguage);
                }
            }
            
            filteredVoices = voices.filter(voice => {
                // Get the voice language
                const voiceLanguage = voice.labels?.language || voice.language || '';
                
                // Handle English specially - show all English variants (en-US, en-GB, etc.) when 'en' is selected
                if (selectedLanguage === 'en' && (voiceLanguage === 'en' || voiceLanguage.startsWith('en-'))) {
                    return true;
                }
                
                // Handle Norwegian specially - show 'no', 'nb', 'nn' and voices with Norwegian in the name
                if (selectedLanguage === 'no') {
                    const voiceName = (voice.name || '').toLowerCase();
                    const voiceAccent = (voice.labels?.accent || '').toLowerCase();
                    const voiceDescription = (voice.labels?.description || '').toLowerCase();

                    // Check if language code matches Norwegian variants
                    const hasNorwegianLanguageCode = voiceLanguage === 'no' ||
                                                     voiceLanguage === 'nb' ||
                                                     voiceLanguage === 'nn' ||
                                                     voiceLanguage.startsWith('no-') ||
                                                     voiceLanguage.startsWith('nb-') ||
                                                     voiceLanguage.startsWith('nn-');

                    // Check if voice name, accent or description contains Norwegian indicators
                    const hasNorwegianIndicator = voiceName.includes('norw') ||
                                                 voiceName.includes('norge') ||
                                                 voiceAccent.includes('oslo') ||
                                                 voiceAccent.includes('bergen') ||
                                                 voiceDescription.includes('norw');

                    if (hasNorwegianLanguageCode || hasNorwegianIndicator) {
                        if (window.mementorTTS && window.mementorTTS.isDebug) {
                            if (window.mementorTTSDebug) {
                                window.mementorTTSDebug.log('TTS Plugin: Matched Norwegian voice:', voice.name, voice.id, 'with language code:', voiceLanguage);
                            }
                        }
                        return true;
                    }
                }
                
                // For all other languages, use exact match
                return voiceLanguage === selectedLanguage;
            });
            
            if (window.mementorTTS && window.mementorTTS.isDebug) {
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('TTS Plugin: Filtered to', filteredVoices.length, 'voices with language', selectedLanguage);
                }
            }
        }
        
        // Create a map to track how many voices per language are marked as free
        const freeVoiceCountByLanguage = {};
        
        // First pass: Count all voices by language
        const voicesByLanguage = {};
        filteredVoices.forEach(voice => {
            const voiceLang = voice.labels?.language || voice.language || 'unknown';
            if (!voicesByLanguage[voiceLang]) {
                voicesByLanguage[voiceLang] = [];
            }
            voicesByLanguage[voiceLang].push(voice);
        });
        
        // Determine which voices are free based on new rules:
        // - First 5 English voices are free
        // - First 1 voice per other language is free
        filteredVoices.forEach(voice => {
            const voiceLangCode = voice.labels?.language || voice.language || 'unknown';
            
            // Initialize counter for this language if not exists
            if (!freeVoiceCountByLanguage[voiceLangCode]) {
                freeVoiceCountByLanguage[voiceLangCode] = 0;
            }
            
            // Apply our new rules (ignore API's free_users_allowed for our custom logic)
            const isEnglish = voiceLangCode === 'en' || voiceLangCode.startsWith('en-');
            
            if (isEnglish) {
                // Only allow up to 5 English voices for free users
                if (freeVoiceCountByLanguage[voiceLangCode] < 5) {
                    voice.free_users_allowed = true;
                    freeVoiceCountByLanguage[voiceLangCode]++;
                } else {
                    voice.free_users_allowed = false;
                }
            } else {
                // For non-English languages, only allow 1 free voice
                if (freeVoiceCountByLanguage[voiceLangCode] < 1) {
                    voice.free_users_allowed = true;
                    freeVoiceCountByLanguage[voiceLangCode]++;
                } else {
                    voice.free_users_allowed = false;
                }
            }
            
            if (window.mementorTTS && window.mementorTTS.isDebug) {
                if (window.mementorTTSDebug) {
                    const debugVoiceLanguage = voice.labels?.language || voice.language || '';
                    window.mementorTTSDebug.log(`TTS Plugin: Voice ${voice.name} (${debugVoiceLanguage}) is ${voice.free_users_allowed ? 'FREE' : 'PRO'}, sharing:`, voice.sharing);
                }
            }
        });
        
        // Collect unique values for filter dropdowns
        const genders = new Set();
        const ages = new Set();
        const accents = new Set();
        const useCases = new Set();
        
        // Extract unique values from filtered voices
        filteredVoices.forEach(voice => {
            if (voice.labels?.gender) genders.add(voice.labels.gender);
            if (voice.labels?.age) ages.add(voice.labels.age);
            if (voice.labels?.accent) accents.add(voice.labels.accent);
            if (voice.labels?.use_case) useCases.add(voice.labels.use_case);
        });
        
        // Populate filter dropdowns
        populateFilterDropdown('#mementor-tts-filter-gender', Array.from(genders).sort());
        populateFilterDropdown('#mementor-tts-filter-age', Array.from(ages).sort());
        populateFilterDropdown('#mementor-tts-filter-accent', Array.from(accents).sort());
        populateFilterDropdown('#mementor-tts-filter-use-case', Array.from(useCases).sort());
        
        // Sort voices: selected voice first, then free voices (for free users), then descriptions, then alphabetically
        filteredVoices.sort((a, b) => {
            // Selected voice always comes first
            if (a.voice_id === $('#mementor_tts_voice').val()) return -1;
            if (b.voice_id === $('#mementor_tts_voice').val()) return 1;
            
            // For free users, show free voices at the top
            if (!hasPro) {
                if (a.free_users_allowed && !b.free_users_allowed) return -1;
                if (!a.free_users_allowed && b.free_users_allowed) return 1;
            }
            
            // Then sort by whether they have a description
            if (a.description && !b.description) return -1;
            if (!a.description && b.description) return 1;
            
            // Finally sort by name
            return a.name.localeCompare(b.name);
        });
        
        // Keep custom voice row if present, remove everything else
        voiceList.find('.tts-voice-loading, .tts-voice-load-more').remove();
        voiceList.find('.tts-voice-item:not([style])').remove();

        // Get the currently saved voice ID
        const savedVoiceId = $('#mementor_tts_voice').val();
        const VOICES_PER_PAGE = 30;

        function buildVoiceItem(voice) {
            const isSelected = voice.voice_id === savedVoiceId;
            const isProVoice = !voice.free_users_allowed;
            const disableForFreeUser = !hasPro && isProVoice;
            const gender = (voice.labels?.gender || '').toLowerCase().replace(' ', '-');
            const age = (voice.labels?.age || '').toLowerCase().replace(' ', '-');
            const desc = voice.description ? ' — ' + voice.description : '';

            let tags = '';
            if (voice.labels?.language) tags += '<span class="tts-tag">' + voice.labels.language + '</span>';
            if (voice.labels?.accent) tags += '<span class="tts-tag">' + voice.labels.accent + '</span>';
            if (voice.labels?.use_case) tags += '<span class="tts-tag">' + voice.labels.use_case + '</span>';

            let actionBtn;
            if (disableForFreeUser) {
                actionBtn = '<a class="tts-use-voice-btn pro-upgrade-button" href="admin.php?page=text-to-speech-tts-account#upgrade" data-voice-id="' + voice.voice_id + '" data-voice-name="' + voice.name + '">' +
                    '<span class="dashicons dashicons-lock"></span> Upgrade to use</a>';
            } else {
                actionBtn = '<button type="button" class="tts-use-voice-btn mementor-tts-voice-use-button' + (isSelected ? ' selected' : '') + '" data-voice-id="' + voice.voice_id + '" data-voice-name="' + voice.name + '" data-pro="' + isProVoice + '">' +
                    (isSelected ? 'Selected' : 'Use Voice') + '</button>';
            }

            return $(
                '<div class="tts-voice-item' + (isSelected ? ' is-selected' : '') + (isProVoice ? ' pro-voice' : '') + '" data-gender="' + (voice.labels?.gender || '') + '" data-age="' + (voice.labels?.age || '') + '">' +
                    '<div class="tts-voice-avatar-wrap">' +
                        '<img class="tts-voice-avatar" src="' + getVoiceAvatar(voice.voice_id, voice.labels?.gender) + '" alt="' + voice.name + '">' +
                        (isProVoice ? '<span class="tts-voice-pro-badge">PRO</span>' : '') +
                    '</div>' +
                    '<div class="tts-voice-info">' +
                        '<div class="tts-voice-name" data-tooltip="' + voice.name + (voice.description ? ' — ' + voice.description : '') + '">' + voice.name + desc + '</div>' +
                        '<div class="tts-voice-meta">' +
                            tags +
                            '<span class="tts-voice-id">' + voice.voice_id +
                                ' <button type="button" class="tts-copy-btn" data-id="' + voice.voice_id + '">Copy ID</button>' +
                            '</span>' +
                        '</div>' +
                    '</div>' +
                    '<div class="tts-voice-badges">' +
                        (gender ? '<span class="tts-gender-badge ' + gender + '">' + (voice.labels?.gender || '') + '</span>' : '') +
                        (age ? '<span class="tts-age-badge ' + age + '">' + (voice.labels?.age || '') + '</span>' : '') +
                    '</div>' +
                    '<div class="tts-voice-actions">' +
                        '<div class="mementor-tts-voice-preview-container">' +
                            '<button type="button" class="tts-play-btn mementor-tts-voice-play-button" data-voice-id="' + voice.voice_id + '" data-preview-url="' + voice.preview_url + '">' +
                                '<span class="dashicons dashicons-controls-play"></span>' +
                            '</button>' +
                            '<div class="mementor-tts-voice-audio"></div>' +
                        '</div>' +
                        actionBtn +
                    '</div>' +
                '</div>'
            );
        }

        // Render first batch
        let rendered = 0;
        const total = filteredVoices.length;
        const batch = filteredVoices.slice(0, VOICES_PER_PAGE);
        batch.forEach(voice => { voiceList.append(buildVoiceItem(voice)); });
        rendered = batch.length;

        // Add "Load more" button if there are more voices
        function addLoadMore() {
            voiceList.find('.tts-voice-load-more').remove();
            const remaining = total - rendered;
            if (remaining > 0) {
                const loadMoreBtn = $('<div class="tts-voice-load-more"><button type="button" class="tts-btn">Show ' + Math.min(remaining, VOICES_PER_PAGE) + ' more voices (' + remaining + ' remaining)</button></div>');
                voiceList.append(loadMoreBtn);
                loadMoreBtn.find('button').on('click', function() {
                    loadMoreBtn.remove();
                    const nextBatch = filteredVoices.slice(rendered, rendered + VOICES_PER_PAGE);
                    nextBatch.forEach(voice => { voiceList.append(buildVoiceItem(voice)); });
                    rendered += nextBatch.length;
                    initVoicePreview();
                    addLoadMore();
                });
            }
        }
        addLoadMore();

        // Initialize voice preview functionality
        initVoicePreview();
    }

    // Helper function to populate filter dropdowns
    function populateFilterDropdown(selector, options) {
        const dropdown = $(selector);
        const currentValue = dropdown.val(); // Save current selection
        
        // Keep the first option (All X) and remove other options
        dropdown.find('option:not(:first)').remove();
        
        // Add new options
        options.forEach(option => {
            dropdown.append(`<option value="${option}">${option}</option>`);
        });
        
        // Restore previous selection if it still exists
        if (currentValue && options.includes(currentValue)) {
            dropdown.val(currentValue);
        }
    }

    // Initialize statistics
    function initializeStatistics() {
        // Refresh statistics button
        $('#refresh-elevenlabs-stats').on('click', function() {
            const button = $(this);
            button.find('.dashicons').addClass('spin');
            button.prop('disabled', true);
            
            $.ajax({
                url: mementorTTSGetAjaxUrl(),
                type: 'POST',
                data: {
                    action: 'mementor_tts_refresh_stats',
                    nonce: $('#mementor_tts_nonce').val()
                },
                success: function(response) {
                    if (response.success) {
                        mementorTTSShowNotification('Statistics refreshed successfully.', 'success');
                        setTimeout(function() {
                            window.location.reload();
                        }, 1500);
                    } else {
                        mementorTTSShowNotification('Failed to refresh statistics: ' + response.data.message, 'error');
                        button.find('.dashicons').removeClass('spin');
                        button.prop('disabled', false);
                    }
                },
                error: function() {
                    mementorTTSShowNotification('An error occurred while refreshing statistics.', 'error');
                    button.find('.dashicons').removeClass('spin');
                    button.prop('disabled', false);
                }
            });
        });
    }

    // Update player preview
    function updatePlayerPreview() {
        const previewPlayer = $('.mementor-tts-preview-player');
        const player = previewPlayer.find('.mementor-tts-player');
        const customControls = player.find('.mementor-tts-custom-controls');
        
        // Update label
        const showLabel = $('#mementor_tts_show_player_label').is(':checked');
        const labelText = $('#mementor_tts_player_label').val();
        const labelPosition = $('#mementor_tts_player_label_position').val();
        const labelMargin = $('#mementor_tts_player_label_margin').val();
        const labelSize = $('#mementor_tts_player_label_size').val();
        const labelWeight = $('#mementor_tts_player_label_weight').val();
        const labelColor = $('#mementor_tts_player_label_color').val();
        const playButtonText = $('#mementor_tts_player_play_button_text_color').val();
        
        let playerLabel = previewPlayer.find('.mementor-tts-player-label');
        if (showLabel) {
            if (!playerLabel.length) {
                playerLabel = $('<div class="mementor-tts-player-label"></div>').insertBefore(player);
            }
            playerLabel.text(labelText)
                      .removeClass('text-left text-center text-right')
                      .addClass('text-' + labelPosition)
                      .css({
                          'margin-bottom': labelMargin + 'px',
                          'font-size': labelSize + 'px',
                          'font-weight': labelWeight,
                          'color': labelColor
                      })
                      .show();
        } else {
            playerLabel.hide();
        }

        // Update player width
        const playerWidth = $('#mementor_tts_player_width').val();
        const customWidth = $('#mementor_tts_custom_width').val();
        
        // Remove existing width classes
        player.removeClass('mementor-tts-width-500 mementor-tts-width-custom mementor-tts-width-full');
        
        // Add appropriate width class
        switch(playerWidth) {
            case 'content_width':
                player.addClass('mementor-tts-width-500');
                break;
            case 'custom_width':
                player.addClass('mementor-tts-width-custom');
                break;
            default:
                player.addClass('mementor-tts-width-full');
        }
        
        // Update data attribute
        previewPlayer.attr('data-width', playerWidth);

        // Update controls visibility
        const showTime = $('#mementor_tts_show_time').is(':checked');
        const showSpeed = $('#mementor_tts_speed_control').is(':checked');
        const showVolume = $('#mementor_tts_show_volume').is(':checked');
        const showDownload = $('#mementor_tts_show_download').is(':checked');
        const showInfo = $('#mementor_tts_show_info').is(':checked');
        const showPlayBg = $('#mementor_tts_show_play_bg').is(':checked');

        previewPlayer.find('.mementor-tts-player .mementor-tts-time-display, .mementor-tts-player .mementor-tts-duration-display').css('display', showTime ? '' : 'none');
        previewPlayer.find('.mementor-tts-player .mementor-tts-speed-button').css('display', showSpeed ? '' : 'none');
        previewPlayer.find('.mementor-tts-player .mementor-tts-volume-button').css('display', showVolume ? '' : 'none');
        previewPlayer.find('.mementor-tts-player .mementor-tts-download-button').css('display', showDownload ? '' : 'none');
        previewPlayer.find('.mementor-tts-player .mementor-tts-info-button').css('display', showInfo ? '' : 'none');
        
        // Also hide the info popup if info button is hidden
        if (!showInfo) {
            previewPlayer.find('.mementor-tts-info-popup').hide();
        }

        // Update play button background
        if (showPlayBg) {
            customControls.attr('data-show-play-bg', 'true');
            previewPlayer.find('.mementor-tts-player .mementor-tts-play-button').removeClass('no-background');
        } else {
            customControls.attr('data-show-play-bg', 'false');
            previewPlayer.find('.mementor-tts-player .mementor-tts-play-button').addClass('no-background');
        }

        // Update colors and styles
        const bgColor = $('#mementor_tts_player_bg_color').val();
        const borderColor = $('#mementor_tts_player_border_color').val();
        const textColor = $('#mementor_tts_player_text_color').val();
        const accentColor = $('#mementor_tts_player_accent_color').val();
        const playButtonBg = $('#mementor_tts_play_button_bg').val();
        const timerColor = $('#mementor_tts_timer_color').val();
        const progressDefault = $('#mementor_tts_progress_bar_default').val();
        const progressPlaying = $('#mementor_tts_progress_bar_playing').val();
        
        // Update sizes
        const playIconSize = $('#mementor_tts_play_icon_size').val();
        const fontSize = $('#mementor_tts_font_size').val();
        const padding = $('#mementor_tts_player_padding').val();
        const borderRadius = $('#mementor_tts_player_border_radius').val();
        const fontFamily = $('#mementor_tts_player_font_family').val();
        const shadowOption = $('#mementor_tts_player_shadow').val();
        const playerAlign = $('#mementor_tts_player_alignment').val(); // none, left, center, right
        const marginTop = $('#mementor_tts_player_margin_top').val();
        const marginBottom = $('#mementor_tts_player_margin_bottom').val();
        const maxWidth = $('#mementor_tts_player_max_width').val();
        const widthUnit = $('#mementor_tts_player_width_unit').val();

        // Get the preview player wrapper element
        const previewWrapper = $('.mementor-tts-preview-player-wrapper').get(0); // Get the DOM element

        if (previewWrapper) {
             // --- Update CSS Variables --- 
            previewWrapper.style.setProperty('--preview-player-bg-color', bgColor);
            previewWrapper.style.setProperty('--preview-player-text-color', textColor);
            // Add console log for debugging accent color
            if (window.mementorTTS && window.mementorTTS.isDebug) {
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Updating --preview-player-accent-color to:', accentColor);
                }
            }
            previewWrapper.style.setProperty('--preview-player-accent-color', accentColor);
            previewWrapper.style.setProperty('--mementor-tts-accent-color', accentColor);
            previewWrapper.style.setProperty('--preview-player-border-radius', borderRadius + 'px');
            previewWrapper.style.setProperty('--preview-player-padding', padding + 'px');
            previewWrapper.style.setProperty('--preview-player-max-width', maxWidth + widthUnit);
            previewWrapper.style.setProperty('--preview-player-width', playerWidth === 'custom_width' ? customWidth + 'px' : (playerWidth === 'content_width' ? '500px' : '100%'));
            previewWrapper.style.setProperty('--preview-player-font-family', fontFamily);
            previewWrapper.style.setProperty('--preview-player-font-size', fontSize + 'px');
            previewWrapper.style.setProperty('--preview-player-label-display', showLabel ? 'block' : 'none');
            previewWrapper.style.setProperty('--preview-player-label-color', labelColor);
            previewWrapper.style.setProperty('--preview-player-label-weight', labelWeight);
            previewWrapper.style.setProperty('--preview-player-play-button-bg', playButtonBg);
            previewWrapper.style.setProperty('--preview-player-play-button-text', playButtonText); // Need option for this
            previewWrapper.style.setProperty('--preview-player-progress-bg', progressDefault);
            previewWrapper.style.setProperty('--preview-player-progress-fg', progressPlaying);
            previewWrapper.style.setProperty('--preview-player-time-color', timerColor);
            previewWrapper.style.setProperty('--preview-player-border-color', borderColor);
            
            // Also set the standard CSS variables used by the player
            previewWrapper.style.setProperty('--mementor-tts-bg-color', bgColor);
            previewWrapper.style.setProperty('--mementor-tts-border-color', borderColor);
            previewWrapper.style.setProperty('--mementor-tts-play-button-bg', playButtonBg);
            previewWrapper.style.setProperty('--mementor-tts-timer-color', timerColor);
            previewWrapper.style.setProperty('--mementor-tts-progress-default', progressDefault);
            previewWrapper.style.setProperty('--mementor-tts-progress-playing', progressPlaying);
            previewWrapper.style.setProperty('--mementor-tts-play-icon-size', playIconSize + 'px');
            previewWrapper.style.setProperty('--mementor-tts-font-size', fontSize + 'px');
            previewWrapper.style.setProperty('--mementor-tts-player-padding', padding + 'px');

            // Sync sticky footer preview with same variables
            var stickyPreview = document.getElementById('tts-sticky-preview');
            if (stickyPreview) {
                stickyPreview.style.setProperty('--mementor-tts-bg-color', bgColor);
                stickyPreview.style.setProperty('--mementor-tts-border-color', borderColor);
                stickyPreview.style.setProperty('--mementor-tts-accent-color', accentColor);
                stickyPreview.style.setProperty('--mementor-tts-text-color', textColor);
                stickyPreview.style.setProperty('--mementor-tts-play-button-bg', playButtonBg);
                stickyPreview.style.setProperty('--mementor-tts-timer-color', timerColor);
                stickyPreview.style.setProperty('--mementor-tts-progress-default', progressDefault);
                stickyPreview.style.setProperty('--mementor-tts-progress-playing', progressPlaying);
                stickyPreview.style.setProperty('--mementor-tts-player-padding', padding + 'px');
                var opacityEl = document.getElementById('mementor_tts_player_opacity');
                if (opacityEl) {
                    var opVal = parseFloat(opacityEl.value);
                    var hex = bgColor || '#f6f7fb';
                    if (opVal < 1 && hex.length === 7) {
                        var r = parseInt(hex.slice(1,3),16), g = parseInt(hex.slice(3,5),16), b = parseInt(hex.slice(5,7),16);
                        stickyPreview.style.setProperty('--mementor-tts-sticky-bg', 'rgba('+r+','+g+','+b+','+opVal+')');
                    } else {
                        stickyPreview.style.setProperty('--mementor-tts-sticky-bg', hex);
                    }
                }
            }

            // Sync progress type to previews
            var progressTypeSelect = document.getElementById('mementor_tts_progress_type');
            if (progressTypeSelect) {
                progressTypeSelect.addEventListener('change', function() {
                    var isWaveform = progressTypeSelect.value === 'waveform_progress';

                    // Update sticky preview
                    if (stickyPreview) {
                        var stickyPC = stickyPreview.querySelector('.mementor-tts-sticky-progress-container');
                        if (stickyPC) {
                            if (isWaveform) {
                                stickyPC.classList.add('mementor-tts-waveform');
                                stickyPC.setAttribute('data-progress-type', 'waveform_progress');
                                stickyPC.setAttribute('data-post-id', '0');
                                while (stickyPC.firstChild) stickyPC.removeChild(stickyPC.firstChild);
                                if (window.MementorTTSWaveform) window.MementorTTSWaveform.init(stickyPC);
                            } else {
                                stickyPC.classList.remove('mementor-tts-waveform');
                                stickyPC.removeAttribute('data-progress-type');
                                stickyPC.removeAttribute('data-post-id');
                                while (stickyPC.firstChild) stickyPC.removeChild(stickyPC.firstChild);
                                var bar = document.createElement('div');
                                bar.className = 'mementor-tts-sticky-progress-bar';
                                bar.style.width = '35%';
                                stickyPC.appendChild(bar);
                            }
                        }
                    }

                    // Update inline preview
                    var inlinePC = document.querySelector('#tts-inline-preview .mementor-tts-progress-container');
                    if (inlinePC) {
                        if (isWaveform) {
                            inlinePC.classList.add('mementor-tts-waveform');
                            inlinePC.setAttribute('data-progress-type', 'waveform_progress');
                            inlinePC.setAttribute('data-post-id', '0');
                            while (inlinePC.firstChild) inlinePC.removeChild(inlinePC.firstChild);
                            if (window.MementorTTSWaveform) window.MementorTTSWaveform.init(inlinePC);
                        } else {
                            inlinePC.classList.remove('mementor-tts-waveform');
                            inlinePC.removeAttribute('data-progress-type');
                            inlinePC.removeAttribute('data-post-id');
                            while (inlinePC.firstChild) inlinePC.removeChild(inlinePC.firstChild);
                            var linearBar = document.createElement('div');
                            linearBar.className = 'mementor-tts-progress-bar';
                            inlinePC.appendChild(linearBar);
                        }
                    }
                });
            }

            // Calculate margin based on alignment
            let marginValue = '0 auto';
            if (playerAlign === 'left') {
                marginValue = marginTop + 'px auto ' + marginBottom + 'px 0';
            } else if (playerAlign === 'center') {
                marginValue = marginTop + 'px auto ' + marginBottom + 'px auto';
            } else { // right or none
                marginValue = marginTop + 'px 0 ' + marginBottom + 'px auto';
            }
            previewWrapper.style.setProperty('--preview-player-margin', marginValue);

            // Calculate shadow
            let shadowValue = 'none';
            if (shadowOption === 'small') shadowValue = '0 2px 5px rgba(0,0,0,0.1)';
            if (shadowOption === 'medium') shadowValue = '0 5px 15px rgba(0,0,0,0.15)';
            if (shadowOption === 'large') shadowValue = '0 10px 25px rgba(0,0,0,0.2)';
            previewWrapper.style.setProperty('--preview-player-shadow', shadowValue);
            // Set the icon size variable
            previewWrapper.style.setProperty('--preview-player-play-icon-size', playIconSize + 'px');
            
            // --- Update specific element styles not covered by variables (or needing direct control) --- 
            // Example: Toggle play button background class based on setting (if needed beyond CSS variable)
            const playButton = previewPlayer.find('.mementor-tts-play-button');
            if (showPlayBg) {
                playButton.removeClass('no-background');
                customControls.attr('data-show-play-bg', 'true'); 
            } else {
                playButton.addClass('no-background');
                customControls.attr('data-show-play-bg', 'false');
            }
            // Update play icon size directly if needed (though variable should handle it)
            playButton.find('.dashicons').css('font-size', playIconSize + 'px'); 
        }
        
        // Remove the old style tag injection
        // let styleElement = $('#mementor-tts-preview-styles');
        // if (styleElement.length) {
        //     styleElement.remove(); 
        // }
    }

    // Initialize API key verification
    $('#mementor-tts-verify-api-key').on('click', function() {
        const apiKey = $('#mementor_tts_api_key').val();
        const statusElement = $('#mementor-tts-api-key-status');
        
        if (!apiKey) {
            mementorTTSShowNotification('Please enter an API key first.', 'error');
            return;
        }
        
        $(this).prop('disabled', true).text('Verifying...');
        statusElement.removeClass('connected').text('Checking...');
        
        $.ajax({
            url: mementorTTSGetAjaxUrl(),
            type: 'POST',
            data: {
                action: 'mementor_tts_verify_api_key',
                api_key: apiKey,
                nonce: $('#mementor_tts_nonce').val()
            },
            success: function(response) {
                if (response.success) {
                    statusElement.addClass('connected').text('Connected');
                    
                    // Use the html_message (preferred) or message from the PHP response
                    let notificationMessage = response.data.html_message || response.data.message || 'Success!'; 
                    mementorTTSShowNotification(notificationMessage, 'success');
                    
                    // If we have voices, update the default voice dropdown
                    if (response.data && response.data.voices) {
                        const defaultVoiceSelect = $('#mementor_tts_default_voice');
                        defaultVoiceSelect.empty();
                        defaultVoiceSelect.append('<option value="">Select a voice</option>');
                        
                        $.each(response.data.voices, function(index, voice) {
                            defaultVoiceSelect.append('<option value="' + voice.voice_id + '">' + voice.name + '</option>');
                        });
                    }
                } else {
                    statusElement.removeClass('connected').text('Failed to connect');
                    mementorTTSShowNotification(response.data.message || 'Failed to verify API key. Please check your key and try again.', 'error');
                }
            },
            error: function(xhr, status, error) {
                statusElement.removeClass('connected').text('Connection error');
                mementorTTSShowNotification('An error occurred while verifying the API key. Please try again.', 'error');
                
                // Add detailed error logging
                if (window.mementorTTS && window.mementorTTS.isDebug) {
                    if (window.mementorTTSDebug) {
                        window.mementorTTSDebug.error('TTS Plugin: Failed to verify API key for language:', language);
                        window.mementorTTSDebug.error('TTS Plugin: Error details:', { xhr, status, error });
                        if (xhr.responseText) {
                            try {
                                const errorResponse = JSON.parse(xhr.responseText);
                                window.mementorTTSDebug.error('TTS Plugin: Server error response:', errorResponse);
                            } catch (e) {
                                window.mementorTTSDebug.error('TTS Plugin: Raw error response:', xhr.responseText);
                            }
                        }
                    }
                }
            },
            complete: function() {
                $('#mementor-tts-verify-api-key').prop('disabled', false).text('Verify API Key');
            }
        });
    });

    // Enhance the sidebar upgrade section
    function enhanceSidebarUpgradeSection() {
        // Check if we're on the settings page
        if (!$('body').hasClass('mementor-tts-settings-page')) {
            return;
        }
        
        // Check if the user has PRO version by looking for PRO-specific elements
        const hasPro = $('.mementor-tts-resources-list').length > 0;
        
        if (hasPro) {
            // For PRO users, enhance the PRO sidebar sections
            enhanceProSidebar();
        } else {
            // For free users, enhance the upgrade section
            enhanceFreeSidebar();
        }
    }
    
    // Enhance the sidebar for free users
    function enhanceFreeSidebar() {
        // Find the upgrade section in the sidebar
        const upgradeSection = $('.mementor-tts-sidebar .mementor-tts-section, .mementor-tts-sidebar .mementor-tts-pro-cta, .mementor-tts-sidebar .mementor-tts-license-cta');
        
        if (upgradeSection.length) {
            // Convert to license-cta if it's not already
            if (!upgradeSection.hasClass('mementor-tts-license-cta')) {
                upgradeSection.addClass('mementor-tts-license-cta');
            }
            
            // Add highlight badge
            if (!upgradeSection.find('.highlight-badge').length) {
                upgradeSection.append('<span class="highlight-badge">30% OFF</span>');
            }
            
            // Add H2 heading if it doesn't exist
            if (!upgradeSection.find('h2').length && !upgradeSection.find('.mementor-tts-section-header h2').length) {
                // If there's an h3, replace it with h2
                if (upgradeSection.find('h3').length) {
                    const h3Text = upgradeSection.find('h3').text();
                    upgradeSection.find('h3').replaceWith('<h2>' + h3Text + '</h2>');
                } else {
                    // Add a new h2 at the beginning
                    upgradeSection.prepend('<h2>Special Release Deal</h2>');
                }
            }
            
            // If the section has a header, move the content out
            if (upgradeSection.find('.mementor-tts-section-header').length && upgradeSection.find('.mementor-tts-section-content').length) {
                const header = upgradeSection.find('.mementor-tts-section-header');
                const content = upgradeSection.find('.mementor-tts-section-content');
                
                // Move the h2 out of the header
                const h2 = header.find('h2').clone();
                upgradeSection.prepend(h2);
                
                // Move the content elements directly into the section
                content.children().appendTo(upgradeSection);
                
                // Remove the original header and content containers
                header.remove();
                content.remove();
            }
            
            // Restructure the content into a single column with a feature list
            const paragraphs = upgradeSection.find('p.mementor-tts-pro-cta-text');
            
            // Keep only the first paragraph and create a feature list from the others
            if (paragraphs.length > 1) {
                // Keep the first paragraph
                const firstParagraph = paragraphs.first();
                
                // Create a feature list
                const featureList = $('<ul class="feature-list"></ul>');
                
                // Extract features from other paragraphs
                const features = [
                    'Crystal-clear 196kbps audio quality',
                    '32 languages supported',
                    'Advanced analytics and insights',
                    'SEO features for better discoverability',
                    'Live support when you need it',
                    '30,000 FREE credits every month',
                    'Automatic & bulk audio generation +++'
                ];
                
                // Add features to the list
                features.forEach(function(feature) {
                    featureList.append('<li>' + feature + '</li>');
                });
                
                // Remove all paragraphs except the first one
                paragraphs.not(firstParagraph).remove();
                
                // Add the feature list after the first paragraph
                firstParagraph.after(featureList);
                
                // Create a wrapper div for the feature list to help with centering
                featureList.wrap('<div style="text-align: center; width: 100%;"></div>');
                
                // Enhance the button text
                const button = upgradeSection.find('.button-primary, .mementor-tts-upgrade-button, .mementor-tts-pro-button');
                if (button.length) {
                    // Create a button wrapper
                    button.wrap('<div class="button-wrapper"></div>');
                    
                    // Add the expiration text
                    button.after('<span class="expiration-text">Offer Expires 31. March 2025</span>');
                    
                    button.text('GET PRO TODAY!');
                    
                    // Add a subtle icon to the button
                    button.prepend('<span class="dashicons dashicons-star-filled" style="margin-right: 8px;"></span>');
                    
                    // Add the discount paragraph after the button wrapper
                    const discountParagraph = $('<p style="margin-bottom:0px;font-weight: bold;">Use discount code: <strong>LAUNCHTTS</strong></p>');
                    button.parent('.button-wrapper').after(discountParagraph);
                }
            }
        }
    }

    // Enhance the sidebar for PRO users
    function enhanceProSidebar() {
        // Find the PRO sidebar sections
        const proSections = $('.mementor-tts-sidebar .mementor-tts-sidebar-box');
        
        if (proSections.length) {
            // Add icons to the resource list items if not already present
            const resourceList = $('.mementor-tts-resources-list');
            if (resourceList.length) {
                // Make sure the list items have proper styling
                resourceList.find('li').css({
                    'margin-bottom': '10px',
                    'padding-left': '5px'
                });
                
                // Style the links
                resourceList.find('a').css({
                    'text-decoration': 'none',
                    'color': '#2271b1',
                    'font-weight': '500'
                });
                
                // Style the icons
                resourceList.find('.dashicons').css({
                    'margin-right': '8px',
                    'color': '#2271b1',
                    'vertical-align': 'middle'
                });
            }
            
            // Enhance the progress bar
            const progressBar = $('.mementor-tts-progress-bar');
            if (progressBar.length) {
                // Add a subtle animation
                progressBar.css({
                    'transition': 'width 1.5s ease-in-out',
                    'background': 'linear-gradient(to right, #2271b1, #72aee6)'
                });
                
                // Animate the progress bar
                setTimeout(function() {
                    progressBar.css('width', progressBar.css('width'));
                }, 300);
            }
            
            // Style the button
            const button = $('.mementor-tts-sidebar-box .button');
            if (button.length) {
                button.css({
                    'display': 'inline-block',
                    'margin-top': '10px',
                    'text-align': 'center',
                    'width': 'auto'
                });
            }
        }
    }

    $(document).ready(function() {
        // Backfill href on any upgrade button that's missing one — points to the SaaS billing page.
        $('.mementor-tts-upgrade-button:not([href])').attr('href', 'admin.php?page=text-to-speech-tts-account#upgrade');
    });

    // Convert existing WordPress admin notices to our notification style
    function convertExistingNotices() {
        // Only convert notices on TTS plugin pages
        var currentUrl = window.location.href;
        var isTTSPage = currentUrl.indexOf('page=text-to-speech-tts') !== -1;
        
        if (!isTTSPage) {
            return; // Don't process notices on non-TTS pages
        }
        
        // Handle success notices
        $('.notice-success').not('.mementor-tts-pro-license-notice').each(function() {
            var message = $(this).find('p').text();
            if (message) {
                // Show our custom notification
                mementorTTSShowNotification(message, 'success');
                // Remove the original notice to prevent layout shifts
                $(this).remove();
            }
        });
        
        // Also handle error notices
        $('.notice-error').not('.mementor-tts-pro-license-notice').each(function() {
            var message = $(this).find('p').text();
            if (message) {
                mementorTTSShowNotification(message, 'error');
                $(this).remove();
            }
        });
        
        // And warning notices - exclude PRO license notices
        $('.notice-warning').not('.mementor-tts-pro-license-notice').each(function() {
            var message = $(this).find('p').text();
            if (message) {
                mementorTTSShowNotification(message, 'warning');
                $(this).remove();
            }
        });
    }
    
    // Run once on page load
    convertExistingNotices();
    
    // Also expose the notification function globally so it can be used from other scripts
    window.mementorTTSShowNotification = mementorTTSShowNotification;
    
    // Also check for notices after AJAX requests
    $(document).ajaxComplete(function() {
        // Only convert notices on TTS plugin pages
        var currentUrl = window.location.href;
        var isTTSPage = currentUrl.indexOf('page=text-to-speech-tts') !== -1;
        
        if (isTTSPage) {
            setTimeout(convertExistingNotices, 100);
        }
    });

    // Check for URL parameter indicating settings were saved
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('settings-updated') === 'true') {
        // Show settings saved notification
        mementorTTSShowNotification(mementorTTS.settingsUpdated || 'Settings saved successfully.', 'success');
    }

    // Handle max width and unit changes
    $('#mementor_tts_player_max_width, #mementor_tts_player_max_width_unit').on('input change', function() {
        const maxWidth = $('#mementor_tts_player_max_width').val();
        const unit = $('#mementor_tts_player_max_width_unit').val();
        const maxWidthValue = maxWidth + unit;
        
        // Update the CSS variable
        document.documentElement.style.setProperty('--mementor-tts-max-width', maxWidthValue);
        
        // Update the preview player directly
        const previewPlayer = $('.mementor-tts-preview-player');
        const playerContainer = previewPlayer.find('.mementor-tts-player-container');
        
        // Apply max-width to both the preview player and its container
        previewPlayer.css('max-width', maxWidthValue);
        playerContainer.css('max-width', maxWidthValue);
        
        // Force refresh of player width classes
        handlePlayerWidth();
    });

    // Handle alignment changes
    $('#mementor_tts_player_alignment').on('change', function() {
        const alignment = $(this).val();
        const previewPlayer = $('.mementor-tts-preview-player');
        
        // Update data attribute
        previewPlayer.attr('data-alignment', alignment);
        
        // Update margins based on alignment
        if (alignment === 'left') {
            previewPlayer.css({
                'margin-left': '0 !important',
                'margin-right': 'auto !important'
            });
        } else if (alignment === 'center') {
            previewPlayer.css({
                'margin-left': 'auto !important',
                'margin-right': 'auto !important'
            });
        } else if (alignment === 'right') {
            previewPlayer.css({
                'margin-right': '0 !important',
                'margin-left': 'auto !important'
            });
        }
    });

    // Initialize alignment on page load
    $(document).ready(function() {
        const initialAlignment = $('#mementor_tts_player_alignment').val();
        $('#mementor_tts_player_alignment').trigger('change');
    });

    // Function to initialize common admin functionality
    function mementorTTSInitializeCommonAdmin() {
        if (window.mementorTTS && window.mementorTTS.isDebug) {
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Initializing Mementor TTS Common Admin...');
            }
        }
        initializeConfirmationHandlers();
        initializePageFunctionality(); // Calls specific page initializers
        initStickySidebar();
        enhanceSidebarUpgradeSection();
        convertExistingNotices();
        // Add calls to any other general init functions here
    }

    // Initialize everything when the document is ready
    mementorTTSInitializeCommonAdmin();

    // Handle Toggle API Key button
    $(document).on('click', '#toggle-api-key', function() {
        const apiKeyInput = $('#mementor_tts_api_key');
        const button = $(this);
        const icon = button.find('.dashicons');
        const buttonTextSpan = button.find('.button-text');
        
        // Use a data attribute to track state reliably
        const currentState = button.data('state') || 'hidden'; 
        
        // Get initial text only if not already stored
        let initialText = button.data('initial-text');
        if (!initialText) {
            initialText = buttonTextSpan.text();
            button.data('initial-text', initialText);
        }
        
        if (currentState === 'hidden') {
            // --- Show the API key ---
            if (window.mementorTTS && window.mementorTTS.isDebug) {
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Current state is hidden. Attempting to show...');
                }
            }
            // Add loading state
            button.prop('disabled', true);
            buttonTextSpan.text('Loading...'); // Use variable
            icon.removeClass('dashicons-visibility').addClass('dashicons-update-alt spin');

            // Make AJAX call to get decrypted key
            $.ajax({
                url: mementorTTSGetAjaxUrl(),
                type: 'POST',
                data: {
                    action: 'mementor_tts_get_decrypted_key',
                    nonce: mementorTTS.nonce // Ensure mementorTTS object with nonce is available
                },
                success: function(response) {
                    if (response.success && response.data.decrypted_key) {
                        apiKeyInput.val(response.data.decrypted_key); 
                        apiKeyInput.prop('type', 'text');
                        icon.removeClass('dashicons-update-alt spin').addClass('dashicons-hidden');
                        buttonTextSpan.text('Hide API Key'); 
                        button.attr('title', 'Hide API Key');
                        button.data('state', 'shown'); // Set state to shown
                        if (window.mementorTTS && window.mementorTTS.isDebug) {
                            if (window.mementorTTSDebug) {
                                window.mementorTTSDebug.log('Successfully shown. State set to shown.');
                            }
                        }
                    } else {
                        mementorTTSShowNotification(response.data.message || 'Could not retrieve API key.', 'error');
                        icon.removeClass('dashicons-update-alt spin').addClass('dashicons-visibility');
                        buttonTextSpan.text(initialText); 
                        button.data('state', 'hidden'); // Ensure state is hidden on error
                    }
                },
                error: function(xhr, status, error) {
                    mementorTTSShowNotification('An error occurred while retrieving the API key.', 'error');
                    icon.removeClass('dashicons-update-alt spin').addClass('dashicons-visibility');
                    buttonTextSpan.text(initialText); 
                    button.data('state', 'hidden'); // Ensure state is hidden on error
                    
                    // Add detailed error logging
                    if (window.mementorTTS && window.mementorTTS.isDebug) {
                        if (window.mementorTTSDebug) {
                            window.mementorTTSDebug.error('TTS Plugin: Failed to retrieve API key');
                            window.mementorTTSDebug.error('TTS Plugin: Error details:', { xhr, status, error });
                            if (xhr.responseText) {
                                try {
                                    const errorResponse = JSON.parse(xhr.responseText);
                                    window.mementorTTSDebug.error('TTS Plugin: Server error response:', errorResponse);
                                } catch (e) {
                                    window.mementorTTSDebug.error('TTS Plugin: Raw error response:', xhr.responseText);
                                }
                            }
                        }
                    }
                },
                complete: function() {
                    // Re-enable button
                     button.prop('disabled', false);
                }
            });

        } else { // currentState === 'shown'
            // --- Hide the API key ---
            if (window.mementorTTS && window.mementorTTS.isDebug) {
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Current state is shown. Hiding...');
                }
            }
            apiKeyInput.prop('type', 'password'); 
            icon.removeClass('dashicons-hidden').addClass('dashicons-visibility');
            buttonTextSpan.text(initialText); 
            button.attr('title', 'Show API Key');
            button.data('state', 'hidden'); // Set state to hidden
            if (window.mementorTTS && window.mementorTTS.isDebug) {
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Successfully hidden. State set to hidden.');
                }
            }
        }
    });
    // === Special License Key Activation/Deactivation (License Page) ===
    $('#mementor-tts-activate-special-license').on('click', function(e) {
        e.preventDefault();
        var licenseKey = $('#mementor-tts-special-license-key').val().trim();
        var $btn = $(this);
        var $msg = $('#mementor-tts-special-license-message');

        if (!licenseKey) {
            $msg.html('<span style="color: #d63638;">Please enter a license key.</span>');
            return;
        }

        $btn.prop('disabled', true).html('<span class="dashicons dashicons-update-alt" style="animation: rotation 2s infinite linear; margin-right: 5px;"></span>Validating...');
        $msg.html('');

        $.ajax({
            url: mementorTTS.ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_activate_special_license',
                license_key: licenseKey,
                nonce: mementorTTS.nonce
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    $msg.html('<span style="color: #d63638;"></span>').find('span').text(response.data && response.data.message ? response.data.message : 'Invalid key.');
                }
            },
            error: function() {
                $msg.html('<span style="color: #d63638;">Connection error. Please try again.</span>');
            },
            complete: function() {
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-yes" style="margin-top: 4px; margin-right: 4px;"></span>Activate');
            }
        });
    });

    $('#mementor-tts-deactivate-special-license').on('click', function(e) {
        e.preventDefault();
        if (!confirm('Are you sure you want to deactivate your extra credits license?')) {
            return;
        }

        var $btn = $(this);
        $btn.prop('disabled', true);

        $.ajax({
            url: mementorTTS.ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_deactivate_special_license',
                nonce: mementorTTS.nonce
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                }
            },
            error: function() {
                alert('Connection error. Please try again.');
            },
            complete: function() {
                $btn.prop('disabled', false);
            }
        });
    });

}); // End jQuery document ready