(function($) {
    // Check if mementorTTSAudio is available
    if (typeof window.mementorTTSAudio === 'undefined') {
        if (window.mementorTTSDebug) window.mementorTTSDebug.error('mementorTTSAudio object is not defined!');
        return;
    }

    // Track processing state
    window.processingPosts = window.processingPosts || {};

    // Function to handle generate/regenerate clicks
    function handleGenerateClick(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var button = $(this);
        var postId = button.data('post-id');
        
        // Prevent multiple clicks while processing
        if (window.processingPosts[postId]) {
            return;
        }

        // For regenerate, show confirmation
        if (button.hasClass('mementor-tts-regenerate')) {
            if (!confirm(window.mementorTTSAudio.regenerateConfirm || 'Are you sure you want to regenerate this audio file? This will replace the existing audio.')) {
                return;
            }
        }

        // Disable the button and show processing state
        button.addClass('mementor-tts-disabled');
        var originalHtml = button.html();
        var processingText = button.hasClass('mementor-tts-regenerate') 
                             ? (window.mementorTTSAudio.regeneratingText || 'Regenerating...') 
                             : (window.mementorTTSAudio.generatingText || 'Generating...');
        button.html('<span class="dashicons dashicons-update mementor-tts-spin"></span> ' + processingText);
        
        // Mark as processing
        window.processingPosts[postId] = true;
        
        $.ajax({
            url: window.mementorTTSAudio.ajaxUrl,
            type: 'POST',
            data: {
                action: 'mementor_tts_generate_audio',
                post_id: postId,
                nonce: window.mementorTTSAudio.nonce
                // Let server determine voice_id (including custom voice)
            },
            success: function(response) {
                
                if (response.success) {
                    // Instead of reloading the page, update the UI
                    var cell = button.closest('td.mementor_tts');
                    
                    // Create success notification - use modern modal if available
                    if (window.mementorTTSModalUtils && window.mementorTTSModalUtils.showAudioGeneratedSuccess) {
                        var creditsUsed = response.data && response.data.credits_used;
                        var remainingCredits = response.data && response.data.remaining_credits;
                        window.mementorTTSModalUtils.showAudioGeneratedSuccess(
                            '<p style="font-size: 14px;"><strong>Your audio has been generated successfully!</strong></p>' +
                            '<p style="font-size: 14px; margin-top: 10px;">Click the player icon to preview the audio.</p>',
                            creditsUsed,
                            remainingCredits
                        );
                    } else if (typeof window.mementorTTSShowNotification === 'function') {
                        window.mementorTTSShowNotification(window.mementorTTSAudio.successMessage || 'Audio generated successfully!', 'success');
                    } else {
                        // Fallback if notification function isn't available
                        $('<div class="notice notice-success is-dismissible"><p>' + 
                          (window.mementorTTSAudio.successMessage || 'Audio generated successfully!') + 
                          '</p></div>').insertAfter('.wp-header-end').delay(3000).fadeOut();
                    }
                    
                    // Replace the cell content with player and controls
                    updateTTSColumn(cell, postId, response.data.file_url);
                } else {
                    // Get the error message
                    var errorMessage = response.data ? (response.data.message || response.data) : (window.mementorTTSAudio.errorGeneric || 'Error generating audio');
                    
                    // Check if site is not connected
                    if (response.data && response.data.error === 'not_connected') {
                        if (typeof window.mementorTTSModalUtils !== 'undefined' &&
                            typeof window.mementorTTSModalUtils.showNotConnected === 'function') {
                            window.mementorTTSModalUtils.showNotConnected();
                        } else {
                            window.mementorTTSShowNotification(
                                'Site is not connected. Go to Settings to connect your site.',
                                'error',
                                0
                            );
                        }
                        button.html(originalHtml).removeClass('mementor-tts-disabled');
                        delete window.processingPosts[postId];
                        return;
                    }

                    // Check for voice_limit_reached in all possible locations
                    const responseStr = JSON.stringify(response);
                    const dataStr = response.data ? (typeof response.data === 'string' ? response.data : JSON.stringify(response.data)) : '';
                    
                    
                    // Create boolean flags for error detection
                    const isVoiceLimitError = 
                        (response.error_type === 'voice_limit_reached') ||
                        (response.data === 'voice_limit_reached') ||
                        responseStr.includes('voice_limit_reached') ||
                        dataStr.includes('voice_limit_reached') ||
                        (errorMessage && typeof errorMessage === 'string' && errorMessage.includes('voice_limit_reached')) ||
                        (response.data && response.data.detail && response.data.detail.status === 'voice_limit_reached');
                    
                    const isProPlanRequiredError = 
                        (response.error_type === 'pro_plan_required') ||
                        (response.data === 'pro_plan_required') ||
                        responseStr.includes('pro_plan_required') ||
                        dataStr.includes('pro_plan_required') ||
                        (errorMessage && typeof errorMessage === 'string' && errorMessage.includes('pro_plan_required')) ||
                        (response.data && response.data.detail && response.data.detail.status === 'free_users_not_allowed') ||
                        (errorMessage && typeof errorMessage === 'string' && errorMessage.includes('need to be on the creator tier'));
                    
                    
                    if (isProPlanRequiredError) {
                        // Use the shared utility function for PRO-plan required warnings
                        if (window.mementorTTSModalUtils && typeof window.mementorTTSModalUtils.showProPlanRequired === 'function') {
                            window.mementorTTSModalUtils.showProPlanRequired('<p><strong>This voice is available only with a PRO subscription.</strong></p><p>Visit the Voices page to pick a voice that matches your plan or </p>');
                        } else if (window.mementorTTSConfirmations && window.mementorTTSConfirmations.confirm) {
                            // Fall back to the old confirmation system if available
                            window.mementorTTSConfirmations.confirm(
                                '<p><strong>This voice is available only with a PRO subscription.</strong></p><p>Visit the Voices page to pick a voice that matches your plan or </p>',
                                {
                                    title: "Oops! PRO-plan needed",
                                    type: 'warning',
                                    confirmText: 'Go to Voices',
                                    cancelText: 'Close',
                                    confirmType: 'primary'
                                }
                            ).then(function(confirmed) {
                                if (confirmed) {
                                    // Redirect to Voices page
                                    window.location.href = 'admin.php?page=text-to-speech-tts-voices';
                                } else {
                                    // Reload the page when the modal is closed to reset UI state
                                    location.reload();
                                }
                            });
                        } else {
                            if (window.mementorTTSDebug) window.mementorTTSDebug.error('PRO-plan modal utility not available');
                            // Fallback to alert if no modal systems are available
                            alert("This feature requires a PRO plan subscription. Please upgrade to access premium voices and features.");
                            // Reload the page to reset UI state
                            setTimeout(function() {
                                location.reload();
                            }, 3000);
                        }
                        return;
                    } else if (isVoiceLimitError) {
                        // Use the shared utility function for voice limit dialogs
                        
                        // Use the shared utility function for voice limit warnings
                        if (window.mementorTTSModalUtils && typeof window.mementorTTSModalUtils.showVoiceLimitWarning === 'function') {
                            window.mementorTTSModalUtils.showVoiceLimitWarning('<strong>Open My Stats & Voices and delete one or more voices to free up space. Your selected voice will be added automatically once room is available.</strong><p><strong>Need more slots?</strong> Upgrade your subscription for unlimited custom voices.</p>');
                        } else {
                            if (window.mementorTTSDebug) window.mementorTTSDebug.error('Modal utility functions not available. Make sure mementor-tts-modal-utils.js is loaded before this script.');
                            // Fallback to alert if utilities are not available
                            alert("You've hit your limit of 3 custom voices. Please go to My Stats & Voices to manage your voices.");
                        }
                        return;
                    }
                    // Check if this is a quota_exceeded error
                    else if (errorMessage.indexOf('quota_exceeded') !== -1 || 
                        errorMessage.toLowerCase().includes('exceeds your api key') || 
                        errorMessage.toLowerCase().includes('quota')) {
                        
                        // Extract the main error message without quota_exceeded prefix
                        var cleanMessage = errorMessage.replace(/quota_exceeded:?\s*/i, '');
                        
                        // Create HTML for the notification with buttons and centered heading
                        var notificationHtml = 
                            '<div class="quota-error-wrapper">' +
                            '<h3>Quota Exceeded</h3>' +
                            '<p>' + cleanMessage + '</p>' +
                            '<div class="quota-action-buttons">' +
                            '<a href="https://elevenlabs.io/app/subscription" target="_blank" class="button button-primary">Upgrade Your ElevenLabs Plan</a>' +
                            '<a href="admin.php?page=text-to-speech-tts-upgrade" class="button button-secondary">Upgrade to PRO</a>' +
                            '</div>' +
                            '</div>';
                        
                        window.mementorTTSShowNotification(notificationHtml, 'error', 0); // 0 means don't auto-dismiss
                    } 
                    // Check if this is a credits exhausted error
                    else if (response.data && response.data.error === 'credits_exhausted') {
                        // Check if we're on playground.wordpress.net - show demo modal instead
                        if (window.location.hostname === 'playground.wordpress.net') {
                            if (typeof window.mementorTTSModalUtils !== 'undefined' && 
                                typeof window.mementorTTSModalUtils.showDemoNotAvailable === 'function') {
                                window.mementorTTSModalUtils.showDemoNotAvailable();
                            } else {
                                // Fallback notification for demo
                                var demoHtml = 
                                    '<div class="demo-not-available-wrapper">' +
                                    '<h3>Audio Generation Not Available in This Demo</h3>' +
                                    '<p>You\'re welcome to explore our plugin and try out all its features.</p>' +
                                    '<p>However, to generate audio and receive 10,000 free credits, you\'ll need to install the plugin on your own website — not on playground.wordpress.net.</p>' +
                                    '</div>';
                                window.mementorTTSShowNotification(demoHtml, 'info', 0);
                            }
                        } else {
                            // Handle credits exhausted error for regular sites
                            if (typeof window.mementorTTSModalUtils !== 'undefined' && 
                                typeof window.mementorTTSModalUtils.showCreditsExhausted === 'function') {
                                const creditsInfo = response.data.credits_info || {};
                                window.mementorTTSModalUtils.showCreditsExhausted(
                                    creditsInfo.remaining || 0,
                                    creditsInfo.required || 0,
                                    creditsInfo.limit || 5000
                                );
                            } else {
                                // Fallback notification when the modal util isn't loaded.
                                var creditsHtml =
                                    '<div class="credits-exhausted-wrapper">' +
                                    '<h3>Not enough credits</h3>' +
                                    '<p>You don\'t have enough credits for this request. Top up now or upgrade your plan to proceed.</p>' +
                                    '<p><a href="admin.php?page=text-to-speech-tts-account#top-ups" class="button button-primary">Top up credits</a> ' +
                                    '<a href="admin.php?page=text-to-speech-tts-account#upgrade" class="button button-secondary">Upgrade plan</a></p>' +
                                    '</div>';
                                window.mementorTTSShowNotification(creditsHtml, 'error', 0);
                            }
                        }
                    }
                    // Check if this is a No API key error or Unauthorized error
                    else if (errorMessage.indexOf('No API key') !== -1 || 
                             errorMessage.includes('Unauthorized') || 
                             errorMessage.includes('Invalid API key')) {
                        // First check if PRO is active with credits
                        if (window.mementorTTS && window.mementorTTS.pro_status && 
                            window.mementorTTS.pro_status.is_pro_active && 
                            window.mementorTTS.pro_status.has_pro_credits) {
                            
                            // If PRO is active with credits, retry the request with PRO flag
                            $.ajax({
                                url: window.mementorTTSAudio.ajaxUrl,
                                type: 'POST',
                                data: {
                                    action: 'mementor_tts_generate_audio',
                                    post_id: postId,
                                    nonce: window.mementorTTSAudio.nonce
                                },
                                success: function(proResponse) {
                                    if (proResponse.success) {
                                        var cell = button.closest('td.mementor_tts');
                                        // Use modern modal if available
                                        if (window.mementorTTSModalUtils && window.mementorTTSModalUtils.showAudioGeneratedSuccess) {
                                            window.mementorTTSModalUtils.showAudioGeneratedSuccess(
                                                '<p style="font-size: 14px;"><strong>Your audio has been generated successfully using PRO credits!</strong></p>' +
                                                '<p style="font-size: 14px; margin-top: 10px;">Click the player icon to preview the audio.</p>'
                                            );
                                        } else {
                                            window.mementorTTSShowNotification('Audio generated successfully using PRO credits!', 'success');
                                        }
                                        updateTTSColumn(cell, postId, proResponse.data.file_url);
                                    } else {
                                        // Log response for debugging
                                        
                                        // Check if this is a PRO-plan required error
                                        if ((proResponse.data.detail && proResponse.data.detail.status === 'free_users_not_allowed') ||
                                            (proResponse.data.status === 'free_users_not_allowed') ||
                                            (proResponse.data.error && proResponse.data.error === 'free_users_not_allowed') ||
                                            (proResponse.data.error_type === 'pro_plan_required') ||
                                            (proResponse.data === 'pro_plan_required') ||
                                            (typeof proResponse.data === 'string' && (proResponse.data.includes('free_users_not_allowed') || proResponse.data.includes('pro_plan_required')))) {
                                            // Show custom modal for PRO-plan required using our shared utility function
                                            if (window.mementorTTSModalUtils && typeof window.mementorTTSModalUtils.showProPlanRequired === 'function') {
                                                window.mementorTTSModalUtils.showProPlanRequired('<p><strong>This voice is available only with a PRO subscription.</strong></p><p>Visit the Voices page to pick a voice that matches your plan or </p>');
                                            } else if (window.mementorTTSConfirmations && window.mementorTTSConfirmations.confirm) {
                                                // Fall back to the old confirmation system if available
                                                window.mementorTTSConfirmations.confirm(
                                                    '<p><strong>This voice is available only with a PRO subscription.</strong></p><p>Visit the Voices page to pick a voice that matches your plan or </p>',
                                                    {
                                                        title: "Oops! PRO-plan needed",
                                                        type: 'warning',
                                                        confirmText: 'Go to Voices',
                                                        cancelText: 'Close',
                                                        confirmType: 'primary'
                                                    }
                                                ).then(function(confirmed) {
                                                    if (confirmed) {
                                                        // Redirect to Voices page
                                                        window.location.href = 'admin.php?page=text-to-speech-tts-voices';
                                                    } else {
                                                        // Reload the page when the modal is closed to reset UI state
                                                        location.reload();
                                                    }
                                                });
                                            } else {
                                                // Fall back to standard notification if no modal systems are available
                                                window.mementorTTSShowNotification('Error: <p><strong>This voice is available only with a PRO subscription.</strong></p> Visit the Voices page to pick a voice that matches your plan.', 'error');
                                                // Reload the page to reset UI state
                                                setTimeout(function() {
                                                    location.reload();
                                                }, 3000);
                                            }
                                        }
                                        // Check if this is a voice limit error
                                        else if ((proResponse.data.detail && proResponse.data.detail.status === 'voice_limit_reached') ||
                                            (proResponse.data.status === 'voice_limit_reached') ||
                                            (proResponse.data.error && proResponse.data.error === 'voice_limit_reached') ||
                                            (typeof proResponse.data === 'string' && proResponse.data.includes('voice_limit_reached'))) {
                                            // Show custom modal for voice limit reached using our shared utility function
                                            if (window.mementorTTSModalUtils && typeof window.mementorTTSModalUtils.showVoiceLimitWarning === 'function') {
                                                window.mementorTTSModalUtils.showVoiceLimitWarning('<strong>Open My Stats & Voices and delete one or more voices to free up space. Your selected voice will be added automatically once room is available.</strong><p><strong>Need more slots?</strong> Upgrade your subscription for unlimited custom voices.</p>');
                                            } else if (window.mementorTTSConfirmations && window.mementorTTSConfirmations.confirm) {
                                                // Fall back to the old confirmation system if available
                                                window.mementorTTSConfirmations.confirm(
                                                    '<strong>Open My Stats & Voices and delete one or more voices to free up space. Your selected voice will be added automatically once room is available.</strong><br><br><strong>Need more slots?</strong> Upgrade your subscription for unlimited custom voices.',
                                                    {
                                                        title: "You've hit your limit of 3 custom voice",
                                                        type: 'warning',
                                                        confirmText: 'Go to My Stats & Voices',
                                                        cancelText: 'Close',
                                                        confirmType: 'danger'
                                                    }
                                                ).then(function(confirmed) {
                                                    if (confirmed) {
                                                        // Redirect to My Stats & Voices page
                                                        window.location.href = 'admin.php?page=text-to-speech-tts-my-stats-voices';
                                                    } else {
                                                        // Reload the page when the modal is closed to reset UI state
                                                        location.reload();
                                                    }
                                                });
                                            } else {
                                                // Fall back to standard notification if no modal systems are available
                                                window.mementorTTSShowNotification('Error: ' + (proResponse.data.message || 'Voice limit reached. Please delete some voices or upgrade.'), 'error');
                                                // Reload the page to reset UI state
                                                setTimeout(function() {
                                                    location.reload();
                                                }, 3000);
                                            }
                                        } else {
                                            window.mementorTTSShowNotification('Error: ' + (proResponse.data.message || 'Unknown error'), 'error');
                                        }
                                    }
                                    // Reset the button state
                                    button.removeClass('mementor-tts-disabled');
                                    button.html(originalHtml);
                                    window.processingPosts[postId] = false;
                                },
                                error: function(xhr, status, error) {
                                    window.mementorTTSShowNotification('Error connecting to server', 'error');
                                    button.removeClass('mementor-tts-disabled');
                                    button.html(originalHtml);
                                    window.processingPosts[postId] = false;
                                }
                            });
                            return; // Don't show API key missing message
                        }
                        
                        // Check if modal utilities are available
                        if (typeof window.mementorTTSModalUtils !== 'undefined' && 
                            typeof window.mementorTTSModalUtils.showApiKeyError === 'function') {
                            // Determine if this is a "no API key" error
                            const hasNoApiKey = errorMessage.includes('needs_authorization') || 
                                              errorMessage.includes('Neither authorization header nor xi-api-key received') ||
                                              errorMessage.toLowerCase().includes('no api key') ||
                                              errorMessage.toLowerCase().includes('api key missing');
                            window.mementorTTSModalUtils.showApiKeyError(hasNoApiKey, errorMessage);
                        } else if (typeof window.mementorTTSShowNotification === 'function') {
                            // Fallback to notification if modal not available
                            var notificationHtml = 
                                '<div class="api-error-wrapper">' +
                                '<h3>API Key Required</h3>' +
                                '<p><strong>You need to connect an API key to generate audio.</strong></p>' +
                                '<p>Get started with two great options:</p>' +
                                '<ul style="text-align: left; margin: 15px 0;">' +
                                '<li><strong>Sign up for a free ElevenLabs account</strong> to unlock 10,000 free credits each month.</li>' +
                                '<li><strong>Upgrade to PRO for just $3.99/month</strong>, which includes 60,000 credits and all PRO features.</li>' +
                                '</ul>' +
                                '</div>' +
                                '<div class="quota-action-buttons">' +
                                '<a href="admin.php?page=text-to-speech-tts-settings" class="button button-primary" style="margin-right: 10px;">Get Free API Key</a>' +
                                '<a href="admin.php?page=text-to-speech-tts-upgrade" class="button button-secondary">Upgrade to PRO ($3.99/mo)</a>' +
                                '</div>';
                            
                            window.mementorTTSShowNotification(notificationHtml, 'error', 0); // 0 means don't auto-dismiss
                        } else {
                            // Final fallback to alert
                            alert('API Key Required: Please connect your ElevenLabs API key or upgrade to PRO to generate audio.');
                        }
                    }
                    // Default error handling
                    else {
                        // If notification function exists, use it
                        if (typeof window.mementorTTSShowNotification === 'function') {
                            window.mementorTTSShowNotification(errorMessage, 'error');
                        } else {
                            // Fallback to alert
                            alert(errorMessage);
                        }
                    }
                    
                    button.html(originalHtml).removeClass('mementor-tts-disabled');
                    delete window.processingPosts[postId];
                }
            },
            error: function(xhr, status, error) {
                // Enhanced debugging for voice limit errors
                
                // Use the shared utility function for voice limit warnings
                // Try to parse the response to check for voice limit error
                try {
                    let errorResponse;
                    try {
                        errorResponse = JSON.parse(xhr.responseText);
                    } catch(parseError) {
                        errorResponse = xhr.responseText;
                    }
                    
                    // Check for the voice_limit_reached string in various formats and locations
                    const responseStr = typeof errorResponse === 'string' ? errorResponse : JSON.stringify(errorResponse);
                    
                    // Create boolean flags for error detection
                    const isVoiceLimitError = (errorResponse && typeof errorResponse === 'object' && 
                         (// Check our new error_type property
                           (errorResponse.error_type === 'voice_limit_reached') ||
                           (errorResponse.detail && errorResponse.detail.status === 'voice_limit_reached') ||
                           (errorResponse.status === 'voice_limit_reached') ||
                           (errorResponse.error === 'voice_limit_reached') ||
                           (errorResponse.data && errorResponse.data === 'voice_limit_reached') ||
                           (errorResponse.data && errorResponse.data.error_type === 'voice_limit_reached') ||
                           (errorResponse.data && errorResponse.data.status === 'voice_limit_reached') ||
                           (errorResponse.data && errorResponse.data.message === 'voice_limit_reached') ||
                           (errorResponse.data && typeof errorResponse.data === 'string' && errorResponse.data === 'voice_limit_reached'))) ||
                        (typeof errorResponse === 'string' && errorResponse.includes('voice_limit_reached')) ||
                        (xhr.responseText && xhr.responseText.includes('voice_limit_reached'));
                    
                    // Check for PRO-plan required errors
                    const isProPlanRequiredError = (errorResponse && typeof errorResponse === 'object' && 
                         (// Check various error formats
                           (errorResponse.detail && errorResponse.detail.status === 'free_users_not_allowed') ||
                           (errorResponse.status === 'free_users_not_allowed') ||
                           (errorResponse.error === 'free_users_not_allowed') ||
                           (errorResponse.message && errorResponse.message.includes('need to be on the creator tier')) ||
                           (errorResponse.detail && errorResponse.detail.message && errorResponse.detail.message.includes('need to be on the creator tier')) ||
                           (errorResponse.data && errorResponse.data.status === 'free_users_not_allowed'))) ||
                        (typeof errorResponse === 'string' && (errorResponse.includes('free_users_not_allowed') || errorResponse.includes('need to be on the creator tier'))) ||
                        (xhr.responseText && (xhr.responseText.includes('free_users_not_allowed') || xhr.responseText.includes('need to be on the creator tier')));
                        
                        
                    if (isProPlanRequiredError) {
                        
                        // Use the shared utility function for PRO-plan required warnings
                        if (typeof window.mementorTTSModalUtils !== 'undefined' && typeof window.mementorTTSModalUtils.showProPlanRequired === 'function') {
                            window.mementorTTSModalUtils.showProPlanRequired('<p><strong>This voice is available only with a PRO subscription.</strong></p><p>Visit the Voices page to pick a voice that matches your plan or </p>');
                        } else if (window.mementorTTSConfirmations && window.mementorTTSConfirmations.confirm) {
                            // Fall back to the old confirmation system if available
                            window.mementorTTSConfirmations.confirm(
                                '<p><strong>This voice is available only with a PRO subscription.</strong></p><p>Visit the Voices page to pick a voice that matches your plan or </p>',
                                {
                                    title: "Oops! PRO-plan needed",
                                    type: 'warning',
                                    confirmText: 'Go to Voices',
                                    cancelText: 'Close',
                                    confirmType: 'primary'
                                }
                            ).then(function(confirmed) {
                                if (confirmed) {
                                    // Redirect to Voices page
                                    window.location.href = 'admin.php?page=text-to-speech-tts-voices';
                                } else {
                                    // Reload the page when the modal is closed to reset UI state
                                    location.reload();
                                }
                            });
                        } else {
                            if (window.mementorTTSDebug) window.mementorTTSDebug.error('PRO-plan modal utility not available');
                            // Fallback to alert if no modal systems are available
                            alert("This feature requires a PRO plan subscription. Please upgrade to access premium voices and features.");
                            // Reload the page to reset UI state
                            setTimeout(function() {
                                location.reload();
                            }, 3000);
                        }
                        
                        // Stop audio generation process
                        button.removeClass('mementor-tts-disabled');
                        button.html(originalHtml);
                        window.processingPosts[postId] = false;
                        return;
                    } else if (isVoiceLimitError) {
                        
                        // Use the shared utility function for voice limit warnings
                        if (typeof window.mementorTTSModalUtils !== 'undefined' && typeof window.mementorTTSModalUtils.showVoiceLimitWarning === 'function') {
                            window.mementorTTSModalUtils.showVoiceLimitWarning('<strong>Open My Stats & Voices and delete one or more voices to free up space. Your selected voice will be added automatically once room is available.</strong><p><strong>Need more slots?</strong> Upgrade your subscription for unlimited custom voices.</p>');
                        } else if (window.mementorTTSConfirmations && window.mementorTTSConfirmations.confirm) {
                            // Fall back to the old confirmation system if available
                            window.mementorTTSConfirmations.confirm(
                                '<strong>Open My Stats & Voices and delete one or more voices to free up space. Your selected voice will be added automatically once room is available.</strong><br><br><strong>Need more slots?</strong> Upgrade your subscription for unlimited custom voices.',
                                {
                                    title: "You've hit your limit of 3 custom voice",
                                    type: 'warning',
                                    confirmText: 'Go to My Stats & Voices',
                                    cancelText: 'Close',
                                    confirmType: 'danger'
                                }
                            ).then(function(confirmed) {
                                if (confirmed) {
                                    // Redirect to My Stats & Voices page
                                    window.location.href = 'admin.php?page=text-to-speech-tts-my-stats-voices';
                                } else {
                                    // Reload the page when the modal is closed to reset UI state
                                    location.reload();
                                }
                            });
                        } else {
                            if (window.mementorTTSDebug) window.mementorTTSDebug.error('Voice limit modal utility not available');
                            // Fallback to alert if no modal systems are available
                            alert("You've hit your limit of 3 custom voices. Please go to My Stats & Voices to delete some voices.");
                            // Reload the page to reset UI state
                            setTimeout(function() {
                                location.reload();
                            }, 3000);
                        }
                        
                        // Stop audio generation process
                        button.removeClass('mementor-tts-disabled');
                        button.html(originalHtml);
                        window.processingPosts[postId] = false;
                        return;
                    } else if (isProPlanRequiredError) {
                        
                        // Use the shared utility function for PRO-plan required warnings
                        if (typeof window.mementorTTSModalUtils !== 'undefined' && typeof window.mementorTTSModalUtils.showProPlanRequired === 'function') {
                            window.mementorTTSModalUtils.showProPlanRequired('<strong>This voice is available only with a PRO subscription.</strong><p>Visit the Voices page to pick a voice that matches your plan or upgrade your subscription to access premium voices.</p>');
                        } else if (window.mementorTTSConfirmations && window.mementorTTSConfirmations.confirm) {
                            // Fall back to the old confirmation system if available
                            window.mementorTTSConfirmations.confirm(
                                '<strong>This voice is available only with a PRO subscription.</strong><br><br>Visit the Voices page to pick a voice that matches your plan or upgrade your subscription to access premium voices.',
                                {
                                    title: "Oops! PRO-plan needed",
                                    type: 'warning',
                                    confirmText: 'Go to Voices',
                                    cancelText: 'Close',
                                    confirmType: 'primary'
                                }
                            ).then(function(confirmed) {
                                if (confirmed) {
                                    // Redirect to Voices page
                                    window.location.href = 'admin.php?page=text-to-speech-tts-voices';
                                } else {
                                    // Reload the page when the modal is closed to reset UI state
                                    location.reload();
                                }
                            });
                        } else {
                            if (window.mementorTTSDebug) window.mementorTTSDebug.error('PRO-plan modal utility not available');
                            // Fallback to alert if no modal systems are available
                            alert("This voice is available only with a PRO subscription. Please go to the Voices page to pick a voice that matches your plan.");
                            // Reload the page to reset UI state
                            setTimeout(function() {
                                location.reload();
                            }, 3000);
                        }
                        
                        // Stop audio generation process
                        button.removeClass('mementor-tts-disabled');
                        button.html(originalHtml);
                        window.processingPosts[postId] = false;
                        return;
                    } else {
                        alert((window.mementorTTSAudio.errorAjax || 'Error generating audio:') + ' ' + error);
                        button.html(originalHtml).removeClass('mementor-tts-disabled');
                        delete window.processingPosts[postId];
                    }
                } catch (e) {
                    // If parsing fails, continue with standard alert
                    alert((window.mementorTTSAudio.errorAjax || 'Error generating audio:') + ' ' + error);
                    button.html(originalHtml).removeClass('mementor-tts-disabled');
                    delete window.processingPosts[postId];
                }
            }
        });
    }
    
    /**
     * Update the TTS column with player and controls
     * 
     * @param {jQuery} cell - The table cell to update
     * @param {number} postId - The post ID
     * @param {string} audioUrl - The URL to the audio file
     */
    function updateTTSColumn(cell, postId, audioUrl) {
        if (!cell || !postId || !audioUrl) {
            if (window.mementorTTSDebug) window.mementorTTSDebug.error('Missing required parameters for updateTTSColumn');
            return;
        }
        
        // Create the play button and controls (match the same HTML structure as in render_tts_column)
        var icons = mementorTTSAudio || {};
        var columnHtml = '<div class="mementor-tts-column-controls">' +
            '<a href="#" class="mementor-tts-play-button" data-audio-url="' + audioUrl + '" data-tooltip="Play audio">' +
            '<img src="' + (icons.iconPlay || '') + '" alt="" width="18" height="18">' +
            '</a>' +
            '<a href="#" class="mementor-tts-generate-button mementor-tts-regenerate" data-post-id="' + postId + '" data-tooltip="Regenerate audio">' +
            '<img src="' + (icons.iconRedo || '') + '" alt="" width="18" height="18">' +
            '</a>' +
            '<a href="#" class="mementor-tts-delete-button" data-post-id="' + postId + '" data-tooltip="Delete audio">' +
            '<img src="' + (icons.iconDelete || '') + '" alt="" width="18" height="18">' +
            '</a>' +
            '</div>';
        
        // Update the cell
        cell.html(columnHtml);
        
        // Reset processing status
        delete window.processingPosts[postId];
    }

    // Function to handle delete clicks
    function handleDeleteClick(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var button = $(this);
        var postId = button.data('post-id');
        
        // Prevent multiple clicks while processing
        if (window.processingPosts[postId]) {
            return;
        }

        if (!confirm(window.mementorTTSAudio.deleteConfirm || 'Are you sure you want to delete this audio file? This action cannot be undone.')) {
            return;
        }

        // Disable the button and show processing state
        button.addClass('mementor-tts-disabled');
        var originalHtml = button.html();
        button.html('<span class="dashicons dashicons-update mementor-tts-spin"></span>');
        
        // Mark as processing
        window.processingPosts[postId] = true;
        
        $.ajax({
            url: window.mementorTTSAudio.ajaxUrl,
            type: 'POST',
            data: {
                action: 'mementor_tts_delete_audio',
                post_id: postId,
                nonce: window.mementorTTSAudio.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Instead of reloading, update the UI directly
                    var cell = button.closest('td.mementor_tts');
                    
                    // Create success notification
                    if (typeof window.mementorTTSShowNotification === 'function') {
                        window.mementorTTSShowNotification(window.mementorTTSAudio.deleteSuccessMessage || 'Audio deleted successfully!', 'success');
                    } else {
                        // Fallback if notification function isn't available
                        $('<div class="notice notice-success is-dismissible"><p>' + 
                          (window.mementorTTSAudio.deleteSuccessMessage || 'Audio deleted successfully!') + 
                          '</p></div>').insertAfter('.wp-header-end').delay(3000).fadeOut();
                    }
                    
                    // Replace with generate button
                    var generateHtml = '<div class="mementor-tts-column-controls">' +
                        '<a href="#" class="mementor-tts-generate-button" data-post-id="' + postId + '" title="Generate audio">' +
                        '<span class="dashicons dashicons-controls-play"></span> ' +
                        (window.mementorTTSAudio.generateText || 'Generate') +
                        '</a>' +
                        '</div>';
                    cell.html(generateHtml);
                    
                    // Reset processing state
                    delete window.processingPosts[postId];
                } else {
                    alert(response.data.message || window.mementorTTSAudio.errorGenericDelete || 'Error deleting audio');
                    button.html(originalHtml).removeClass('mementor-tts-disabled');
                    delete window.processingPosts[postId];
                }
            },
            error: function(xhr, status, error) {
                alert((window.mementorTTSAudio.errorAjaxDelete || 'Error deleting audio:') + ' ' + error);
                button.html(originalHtml).removeClass('mementor-tts-disabled');
                delete window.processingPosts[postId];
            }
        });
    }

    // Function to handle cancel processing clicks
    function handleCancelProcessingClick(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var button = $(this);
        var postId = button.data('post-id');
        
        // Prevent multiple clicks while processing
        if (window.processingPosts[postId]) {
            return;
        }

        // Disable the button and show processing state
        button.addClass('mementor-tts-disabled');
        var originalHtml = button.html();
        button.html('<span class="dashicons dashicons-update mementor-tts-spin"></span>');
        
        // Mark as processing
        window.processingPosts[postId] = true;
        
        $.ajax({
            url: window.mementorTTSAudio.ajaxUrl,
            type: 'POST',
            data: {
                action: 'mementor_tts_cancel_processing',
                post_id: postId,
                nonce: window.mementorTTSAudio.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Instead of reloading, update the UI directly
                    var cell = button.closest('td.mementor_tts');
                    
                    // Create success notification
                    if (typeof window.mementorTTSShowNotification === 'function') {
                        window.mementorTTSShowNotification('Processing canceled successfully!', 'success');
                    } else {
                        // Fallback if notification function isn't available
                        $('<div class="notice notice-success is-dismissible"><p>Processing canceled successfully!</p></div>')
                            .insertAfter('.wp-header-end').delay(3000).fadeOut();
                    }
                    
                    // Replace with generate button
                    var generateHtml = '<div class="mementor-tts-column-controls">' +
                        '<a href="#" class="mementor-tts-generate-button" data-post-id="' + postId + '" title="Generate audio">' +
                        '<span class="dashicons dashicons-controls-play"></span> ' +
                        (window.mementorTTSAudio.generateText || 'Generate') +
                        '</a>' +
                        '</div>';
                    cell.html(generateHtml);
                    
                    // Reset processing state
                    delete window.processingPosts[postId];
                } else {
                    alert(response.data.message || 'Error canceling audio processing');
                    button.html(originalHtml).removeClass('mementor-tts-disabled');
                    delete window.processingPosts[postId];
                }
            },
            error: function(xhr, status, error) {
                alert('Error canceling audio processing: ' + error);
                button.html(originalHtml).removeClass('mementor-tts-disabled');
                delete window.processingPosts[postId];
            }
        });
    }

    // Use event delegation for dynamically added elements
    $(document).ready(function() {
        // Remove any potential duplicates from previous (incorrect) initializations
        $(document).off('click.mementorTTS', '.mementor-tts-generate-button');
        $(document).off('click.mementorTTS', '.mementor-tts-delete-button');
        $(document).off('click.mementorTTS', '.mementor-tts-cancel-button');
        $(document).off('click.mementorTTS', '.mementor-tts-play-button');

        // Add namespaced event handlers
        $(document).on('click.mementorTTS', '.mementor-tts-generate-button', handleGenerateClick);
        $(document).on('click.mementorTTS', '.mementor-tts-delete-button', handleDeleteClick);
        $(document).on('click.mementorTTS', '.mementor-tts-cancel-button', handleCancelProcessingClick);

        // Inline audio playback handler
        var currentAudio = null;
        $(document).on('click.mementorTTS', '.mementor-tts-play-button', function(e) {
            e.preventDefault();
            var $btn = $(this);
            var audioUrl = $btn.data('audio-url');
            if (!audioUrl) return;

            // If already playing this URL, stop it
            if (currentAudio && currentAudio.src === audioUrl && !currentAudio.paused) {
                currentAudio.pause();
                currentAudio.currentTime = 0;
                $btn.removeClass('mementor-tts-playing');
                currentAudio = null;
                return;
            }

            // Stop any other playing audio
            if (currentAudio) {
                currentAudio.pause();
                currentAudio.currentTime = 0;
                $('.mementor-tts-play-button').removeClass('mementor-tts-playing');
            }

            currentAudio = new Audio(audioUrl);
            $btn.addClass('mementor-tts-playing');
            currentAudio.play();
            currentAudio.addEventListener('ended', function() {
                $btn.removeClass('mementor-tts-playing');
                currentAudio = null;
            });
        });

        // Modern tooltips for [data-tooltip] elements
        var $tooltip = $('<div class="mementor-tts-tooltip"></div>').appendTo('body');
        $(document).on('mouseenter', '[data-tooltip]', function() {
            var text = $(this).attr('data-tooltip');
            if (!text) return;
            var rect = this.getBoundingClientRect();
            $tooltip.text(text).addClass('mementor-tts-tooltip-visible');
            var tipW = $tooltip.outerWidth();
            $tooltip.css({
                top: rect.top - 32 + window.scrollY + 'px',
                left: rect.left + (rect.width / 2) - (tipW / 2) + 'px'
            });
        }).on('mouseleave', '[data-tooltip]', function() {
            $tooltip.removeClass('mementor-tts-tooltip-visible');
        });
    });

})(jQuery);
