/**
 * JavaScript for handling audio generation in the admin area
 *
 * @package    Mementor_TTS
 * @subpackage Mementor_TTS/admin/js
 */

(function($) {
    'use strict';

    // Initialize column event handlers on document ready
    $(document).ready(function() {
        // Use centralized debug utility
        if (window.mementorTTSDebug) {
            window.mementorTTSDebug.log('Initializing TTS column controls...');
        }
        initTTSColumnControls();
    });

    /**
     * Initialize TTS column controls
     */
    function initTTSColumnControls() {
        if (window.mementorTTSDebug) {
            window.mementorTTSDebug.log('Setting up event handlers...');
        }
        
        // Generate/regenerate button handler
        $(document).on('click', '.mementor-tts-generate-button', function(e) {
            e.preventDefault();
            e.stopPropagation();
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Generate/regenerate button clicked');
            }
            
            var button = $(this);
            var postId = button.data('post-id');
            var isRegenerate = button.hasClass('mementor-tts-regenerate');
            
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Post ID:', postId);
                window.mementorTTSDebug.log('Is regenerate:', isRegenerate);
                window.mementorTTSDebug.log('Button HTML:', button.html());
            }
            
            // Add confirmation for regenerate
            if (isRegenerate) {
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Showing regenerate confirmation...');
                }
                if (!confirm(mementorTTSAudio.regenerateConfirm)) {
                    if (window.mementorTTSDebug) {
                        window.mementorTTSDebug.log('Regenerate cancelled by user');
                    }
                    return;
                }
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Regenerate confirmed by user');
                }
            }
            
            // Change button text/state
            var originalHtml = button.html();
            button.html('<span class="dashicons dashicons-update mementor-tts-spin"></span> ' + 
                (isRegenerate ? mementorTTSAudio.recreating : mementorTTSAudio.creating));
            
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Making AJAX call...');
                window.mementorTTSDebug.log('AJAX URL:', mementorTTSAudio.ajaxUrl);
                window.mementorTTSDebug.log('Nonce:', mementorTTSAudio.nonce);
                window.mementorTTSDebug.log('Voice:', mementorTTSAudio.voice);
            }
            
            // Make the AJAX call
            $.ajax({
                url: mementorTTSAudio.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'mementor_tts_generate_audio',
                    post_id: postId,
                    nonce: mementorTTSAudio.nonce,
                    voice_id: mementorTTSAudio.voice
                },
                success: function(response) {
                    if (window.mementorTTSDebug) {
                        window.mementorTTSDebug.log('AJAX response:', response);
                    }
                    if (response.success) {
                        if (window.mementorTTSDebug) {
                            window.mementorTTSDebug.log('Success, reloading page...');
                        }
                        // Show success notification before reload
                        if (typeof window.mementorTTSShowNotification === 'function') {
                            window.mementorTTSShowNotification(mementorTTSAudio.success, 'success');
                        }
                        // Refresh the page to show updated controls
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    } else {
                        if (typeof response.data !== 'undefined' && typeof response.data.message !== 'undefined') {
                            if (typeof window.mementorTTSShowNotification === 'function') {
                                // Check if site is not connected
                                if (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);
                                    return;
                                }

                                // Check if this is a quota exceeded error
                                const errorMessage = response.data.message;
                                if (errorMessage.toLowerCase().includes('exceeds your api key') || 
                                    errorMessage.toLowerCase().includes('quota')) {
                                    
                                    // Create HTML for the notification with quota exceeded styling
                                    const quotaErrorHtml = 
                                        '<div class="quota-error-wrapper">' +
                                        '<h3>Quota Exceeded</h3>' +
                                        '<p>' + errorMessage + '</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>';
                                    
                                    // Show a specially formatted quota error notification
                                    window.mementorTTSShowNotification(quotaErrorHtml, 'error', 0); // 0 means don't auto-dismiss
                                } else if (response.data.error === 'credits_exhausted' || errorMessage.includes('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
                                            window.mementorTTSShowNotification(
                                                '<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>',
                                                '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.
                                            window.mementorTTSShowNotification(
                                                '<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>',
                                                'error',
                                                0
                                            );
                                        }
                                    }
                                } else if (errorMessage.toLowerCase().includes('api key missing') || 
                                         errorMessage.includes('Unauthorized') || 
                                         errorMessage.includes('Invalid API key')) {
                                    // 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.includes('api key missing');
                                        window.mementorTTSModalUtils.showApiKeyError(hasNoApiKey, errorMessage);
                                    } else {
                                        // Fallback to the old notification style
                                        let apiKeyErrorHtml = 
                                            '<div class="api-key-error-wrapper">' +
                                            '<h3>API Key Required</h3>' +
                                            '<p>' + errorMessage + '</p>';
                                        
                                        // Add debugging information if available
                                        if (response.data.debug_info) {
                                            const debugInfo = response.data.debug_info;
                                            
                                            apiKeyErrorHtml += '<div class="error-debug-info">' +
                                                '<h4>Troubleshooting Information</h4>';
                                                
                                            if (debugInfo.pro_available) {
                                                apiKeyErrorHtml += '<p>PRO version is installed. Please make sure your license is active and valid.</p>' +
                                                    '<a href="admin.php?page=text-to-speech-tts-upgrade" class="button button-primary">Check License Status</a>';
                                            } else {
                                                apiKeyErrorHtml += '<p>You need to add an ElevenLabs API key in the settings.</p>' +
                                                    '<a href="' + debugInfo.settings_url + '" class="button button-primary">Go to Settings</a>';
                                            }
                                            
                                            apiKeyErrorHtml += '</div>';
                                        } else {
                                            // No debug info available, provide generic help
                                            apiKeyErrorHtml += '<p>Please add your ElevenLabs API key in the plugin settings.</p>' +
                                                '<a href="admin.php?page=text-to-speech-tts-settings" class="button button-primary">Go to Settings</a>';
                                        }
                                        
                                        apiKeyErrorHtml += '</div>';
                                        
                                        // Show a specially formatted API key error notification
                                        window.mementorTTSShowNotification(apiKeyErrorHtml, 'error', 0); // 0 means don't auto-dismiss
                                    }
                                } else if (errorMessage.toLowerCase().includes('unknown api error')) {
                                    // Create HTML for detailed Unknown API error information
                                    let detailedErrorHtml = 
                                        '<div class="unknown-api-error-wrapper">' +
                                        '<h3>API Error Information</h3>' +
                                        '<p>' + errorMessage + '</p>';
                                    
                                    // Add debugging information if available
                                    if (response.data.debug_info) {
                                        detailedErrorHtml += '<div class="error-debug-info">' +
                                            '<h4>Detailed Information</h4>' +
                                            '<p>Status Code: ' + (response.data.debug_info.status_code || 'Unknown') + '</p>';
                                            
                                        if (response.data.debug_info.response_body) {
                                            detailedErrorHtml += '<p>Error Details: ' + response.data.debug_info.response_body + '</p>';
                                        }
                                        
                                        if (response.data.debug_info.status_code === 502) {
                                            detailedErrorHtml += '<p class="suggestion">This is a temporary server issue with ElevenLabs. Please try again in a few minutes.</p>';
                                        }
                                        
                                        detailedErrorHtml += '</div>';
                                    }
                                    
                                    detailedErrorHtml += '</div>';
                                    
                                    // Show a specially formatted detailed error notification
                                    window.mementorTTSShowNotification(detailedErrorHtml, 'error', 0); // 0 means don't auto-dismiss
                                } else {
                                    // General error notification for other errors
                                    window.mementorTTSShowNotification(errorMessage, 'error', 5000);
                                }
                            } else {
                                alert('Error generating audio: ' + response.data.message);
                            }
                        } else {
                            if (typeof window.mementorTTSShowNotification === 'function') {
                                window.mementorTTSShowNotification('Error generating audio', 'error', 5000);
                            } else {
                                alert('Error generating audio');
                            }
                        }
                    }
                    button.html(originalHtml);
                },
                error: function(xhr, status, error) {
                    if (window.mementorTTSDebug) {
                        window.mementorTTSDebug.error('AJAX error:', error);
                        window.mementorTTSDebug.error('Status:', status);
                        window.mementorTTSDebug.error('Response:', xhr.responseText);
                        
                        // Try to parse the response for more information
                        try {
                            const responseJson = JSON.parse(xhr.responseText);
                            window.mementorTTSDebug.error('Parsed error response:', responseJson);
                        } catch (e) {
                            window.mementorTTSDebug.error('Could not parse error response as JSON');
                        }
                    }
                    
                    // Try to extract more information from the XHR response
                    let errorMessage = mementorTTSAudio.error;
                    try {
                        const responseData = JSON.parse(xhr.responseText);
                        if (responseData && responseData.message) {
                            errorMessage = responseData.message;
                        } else if (responseData && responseData.error) {
                            errorMessage = responseData.error;
                        }
                    } catch (e) {
                        // Use default error message if we can't parse the response
                    }
                    
                    if (typeof window.mementorTTSShowNotification === 'function') {
                        window.mementorTTSShowNotification(errorMessage, 'error');
                    } else {
                        alert(errorMessage);
                    }
                    button.html(originalHtml);
                }
            });
        });
        
        // Delete button handler
        $(document).on('click', '.mementor-tts-delete-button', function(e) {
            e.preventDefault();
            e.stopPropagation();
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Delete button clicked');
            }
            
            var button = $(this);
            var postId = button.data('post-id');
            
            if (window.mementorTTSDebug) {
                window.mementorTTSDebug.log('Post ID:', postId);
                window.mementorTTSDebug.log('Button HTML:', button.html());
            }
            
            if (confirm(mementorTTSAudio.deleteConfirm)) {
                // Change button state
                var originalHtml = button.html();
                button.html('<span class="dashicons dashicons-update mementor-tts-spin"></span>');
                
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('Making delete AJAX call...');
                    window.mementorTTSDebug.log('AJAX URL:', mementorTTSAudio.ajaxUrl);
                    window.mementorTTSDebug.log('Nonce:', mementorTTSAudio.nonce);
                }
                
                // Make the AJAX call
                $.ajax({
                    url: mementorTTSAudio.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'mementor_tts_delete_audio',
                        post_id: postId,
                        nonce: mementorTTSAudio.nonce
                    },
                    success: function(response) {
                        if (window.mementorTTSDebug) {
                            window.mementorTTSDebug.log('Delete AJAX response:', response);
                        }
                        if (response.success) {
                            // Show success notification before reload
                            if (typeof window.mementorTTSShowNotification === 'function') {
                                window.mementorTTSShowNotification(mementorTTSAudio.success, 'success');
                            }
                            // Refresh the page to show updated controls
                            setTimeout(function() {
                                location.reload();
                            }, 1000);
                        } else {
                            if (typeof window.mementorTTSShowNotification === 'function') {
                                window.mementorTTSShowNotification(response.data.message || mementorTTSAudio.error, 'error');
                            }
                            button.html(originalHtml);
                        }
                    },
                    error: function(xhr, status, error) {
                        if (window.mementorTTSDebug) {
                            window.mementorTTSDebug.error('Delete AJAX error:', error);
                            window.mementorTTSDebug.error('Status:', status);
                            window.mementorTTSDebug.error('Response:', xhr.responseText);
                        }
                        if (typeof window.mementorTTSShowNotification === 'function') {
                            window.mementorTTSShowNotification(mementorTTSAudio.error, 'error');
                        }
                        button.html(originalHtml);
                    }
                });
            }
        });
        
        if (window.mementorTTSDebug) {
            window.mementorTTSDebug.log('Event handlers initialized');
        }
    }

})(jQuery);
