jQuery(document).ready(function($) {
    // Use the standardized debug utility
    
    // No longer hide WordPress notices - we want them to show
    // $('.notice, .updated, #message, .notice-success').hide();
    
    // Remove the MutationObserver that hides WordPress notices
    // const observeTarget = document.querySelector('body');
    // if (observeTarget) {
    //     const observer = new MutationObserver(function(mutations) {
    //         mutations.forEach(function(mutation) {
    //             if (mutation.addedNodes && mutation.addedNodes.length > 0) {
    //                 for (let i = 0; i < mutation.addedNodes.length; i++) {
    //                     const node = mutation.addedNodes[i];
    //                     if (node.classList && 
    //                         (node.classList.contains('notice') || 
    //                          node.classList.contains('updated') || 
    //                          node.id === 'message' ||
    //                          node.classList.contains('notice-success'))) {
    //                         $(node).hide();
    //                     }
    //                 }
    //             }
    //         });
    //     });
    //     
    //     observer.observe(observeTarget, { childList: true, subtree: true });
    // }
    
    // Add body class for styling
    $('body').addClass('mementor-tts-settings-page');
    
    // Add audio element to the page with a path from the localized data
    if ($('#mementor-tts-success-audio').length === 0) {
        const pluginUrl = mementorTTS.pluginUrl;
        $('body').append('<audio id="mementor-tts-success-audio" preload="auto"><source src="' + pluginUrl + 'admin/audio/api-success.mp3" type="audio/mpeg"></audio>');
    }
    
    // Custom notification function
    function showCustomNotification(message, type = 'success', duration = 0, playSound = false) {
        // Remove any existing notifications
        $('.mementor-tts-notification').remove();
        
        // Also remove WordPress default notifications that might appear
        $('.notice, .updated, #message').remove();
        
        // Create notification element
        const notification = $('<div class="mementor-tts-notification ' + type + '"></div>');
        
        // Add message content - support HTML
        notification.html('<div class="mementor-tts-notification-content"></div>').find('.mementor-tts-notification-content').text(message);
        
        // Add close button
        const closeButton = $('<span class="mementor-tts-notification-close dashicons dashicons-no-alt"></span>');
        notification.append(closeButton);
        
        // Add to body
        $('body').append(notification);
        
        // Show notification with animation
        setTimeout(function() {
            notification.addClass('show');
            
            // Try to play success sound if requested, but don't rely on autoplay
            if (playSound && type === 'success') {
                // We'll rely on the manual play button instead of autoplay
                // since many browsers block autoplay
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Audio ready to play via button click');
            }
        }, 10);
        
        // Handle close button click
        closeButton.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation(); // Prevent event bubbling
            notification.removeClass('show');
            setTimeout(function() {
                notification.remove();
            }, 300);
        });
        
        // Hide notification after duration (only if duration > 0)
        if (duration > 0) {
            setTimeout(function() {
                notification.removeClass('show');
                setTimeout(function() {
                    notification.remove();
                }, 300);
            }, duration);
        }
    }
    
    // Toggle API key visibility
    $('#toggle-api-key').on('click', function() {
        var apiKeyInput = $('#mementor_tts_api_key');
        var type = apiKeyInput.attr('type');
        
        if (type === 'password') {
            // Fetch the actual API key via AJAX when toggling to show it
            $.ajax({
                url: mementorTTS.ajaxurl,
                type: 'POST',
                data: {
                    action: 'mementor_tts_get_api_key',
                    nonce: mementorTTS.nonce
                },
                success: function(response) {
                    if (response.success && response.data) {
                        // Set the key in the field
                        apiKeyInput.val(response.data.key);
                        // Change input type to text to make it visible
                        apiKeyInput.attr('type', 'text');
                        // Update button icon
                        $('#toggle-api-key').find('.dashicons').removeClass('dashicons-visibility').addClass('dashicons-hidden');
                    } else {
                        // Show error message if available
                        var errorMsg = (response.data && response.data.message) ? response.data.message : 'Failed to decrypt API key';
                        apiKeyInput.val(errorMsg);
                        apiKeyInput.attr('type', 'text');
                        // Update button icon
                        $('#toggle-api-key').find('.dashicons').removeClass('dashicons-visibility').addClass('dashicons-hidden');
                        if (isDebug) {
                            if (window.mementorTTSDebug) window.mementorTTSDebug.error('Could not get API key:', errorMsg);
                        }
                    }
                },
                error: function(xhr, status, error) {
                    // Show error in field
                    var errorMsg = 'Failed to decrypt API key';
                    if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                        errorMsg = xhr.responseJSON.data.message;
                    }
                    apiKeyInput.val(errorMsg);
                    apiKeyInput.attr('type', 'text');
                    // Update button icon
                    $('#toggle-api-key').find('.dashicons').removeClass('dashicons-visibility').addClass('dashicons-hidden');
                    if (isDebug) {
                        if (window.mementorTTSDebug) window.mementorTTSDebug.error('AJAX Error:', error);
                    }
                }
            });
        } else {
            // When hiding, clear the field and reset placeholder
            apiKeyInput.val('').attr('type', 'password')
                .attr('placeholder', '••••••••••••••••••••••••••••••••••••••••');
            $(this).find('.dashicons').removeClass('dashicons-hidden').addClass('dashicons-visibility');
        }
    });
    
    // Verify API key
    $('#validate-api-key').on('click', function(e) {
        e.preventDefault();
        
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Validate API key button clicked');
        var apiKey = $('#mementor_tts_api_key').val().trim();
        var statusElement = $('.mementor-tts-api-status');
        var nonce = $('#mementor_tts_nonce').val();
        
        // Debug logs
        if (window.mementorTTSDebug) {
            window.mementorTTSDebug.log('API Key length:', apiKey.length);
            window.mementorTTSDebug.log('Nonce:', nonce);
        }
        
        if (!apiKey) {
            showCustomNotification(
                '<strong>⚠️ API Key Required</strong><br>Please enter an API key before validating.',
                'error',
                5000 // Show for 5 seconds
            );
            return;
        }
        
        // Disable button and show processing state
        $(this).prop('disabled', true).html('<span class="dashicons dashicons-update-alt" style="animation: rotation 2s infinite linear; margin-right: 5px;"></span>Validating...');
        statusElement.removeClass('connected').text('Validating...');
        
        // Make the AJAX request
        $.ajax({
            url: mementorTTS.ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_validate_api_key',
                api_key: apiKey,
                nonce: nonce
            },
            success: function(response) {
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('AJAX Success Response:', response);
                
                if (response.success) {
                    // Clear the API key field for security
                    $('#mementor_tts_api_key').val('').attr('placeholder', '••••••••••••••••••••••••••••••••••••••••');
                    
                    // Update status indicator
                    statusElement.addClass('connected').text('Connected');
                    
                    // Just reload the page to see WordPress default notification
                    location.reload();
                    
                    // No custom notification - let WordPress handle it
                } else {
                    // Update status indicator
                    statusElement.removeClass('connected').text('Not Connected');
                    
                    // Get error message from response
                    var errorMsg = typeof response.data === 'string' ? response.data : 'Unknown error. Please check your API key and try again.';
                    
                    // Show error notification
                    showCustomNotification(
                        '<strong>❌ API Key Verification Failed</strong><br>' + errorMsg,
                        'error',
                        0 // Stay open until closed
                    );
                }
            },
            error: function(xhr, status, error) {
                if (window.mementorTTSDebug) {
                    window.mementorTTSDebug.log('AJAX Error:', error);
                    window.mementorTTSDebug.log('Status:', status);
                    window.mementorTTSDebug.log('Response:', xhr.responseText);
                }
                
                // Update status indicator
                statusElement.removeClass('connected').text('Not Connected');
                
                // Show error notification
                showCustomNotification(
                    '<strong>❌ Connection Error</strong><br>' +
                    'There was a problem connecting to the server. Please try again later.',
                    'error',
                    0 // Stay open until closed
                );
            },
            complete: function() {
                // Re-enable the button
                $('#validate-api-key').prop('disabled', false).html(
                    '<span class="dashicons dashicons-yes-alt" style="margin-right: 5px;"></span>' +
                    'Save & Validate API Key'
                );
            }
        });
    });

});