jQuery(document).ready(function($) {
    // Add body class for advanced page
    $('body').addClass('advanced-page-active');
    
    // AJAX form submission
    $('#mementor-tts-advanced-settings-form').on('submit', function(e) {
        // Only use AJAX if JavaScript is enabled
        if (mementorTTS.ajaxurl) {
            e.preventDefault();
            
            // Show loading state
            var $submitButton = $(this).find('button[type="submit"]');
            var originalButtonText = $submitButton.html();
            $submitButton.html('<span class="dashicons dashicons-update mementor-tts-spinning"></span> ' + mementorTTS.strings.saving);
            $submitButton.prop('disabled', true);
            
            // Collect all form data
            var formData = new FormData(this);
            formData.append('action', 'mementor_tts_save_advanced_settings');
            formData.append('nonce', mementorTTS.advancedNonce);
            
            // Send AJAX request
            $.ajax({
                url: mementorTTS.ajaxurl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        // Show success message
                        var $notice = $('<div class="notice notice-success is-dismissible"><p>' + mementorTTS.strings.settingsSaved + '</p></div>');
                        $('.mementor-tts-section-header').after($notice);
                        
                        // Restore button state
                        $submitButton.html('<span class="dashicons dashicons-yes"></span> ' + mementorTTS.strings.saved);
                        
                        // Remove notice after 3 seconds
                        setTimeout(function() {
                            $notice.fadeOut(function() {
                                $(this).remove();
                            });
                            $submitButton.html(originalButtonText);
                            $submitButton.prop('disabled', false);
                        }, 3000);
                    } else {
                        // Show error message
                        var errorMessage = response.data || mementorTTS.strings.errorSaving;
                        var $notice = $('<div class="notice notice-error is-dismissible"><p>' + errorMessage + '</p></div>');
                        $('.mementor-tts-section-header').after($notice);
                        
                        // Restore button state
                        $submitButton.html(originalButtonText);
                        $submitButton.prop('disabled', false);
                    }
                },
                error: function() {
                    // Show error message
                    var $notice = $('<div class="notice notice-error is-dismissible"><p>' + mementorTTS.strings.errorSavingTryAgain + '</p></div>');
                    $('.mementor-tts-section-header').after($notice);
                    
                    // Restore button state
                    $submitButton.html(originalButtonText);
                    $submitButton.prop('disabled', false);
                }
            });
        }
    });
    
    // Import settings button click handler
    $('#mementor_tts_import_settings').on('click', function() {
        $('#mementor_tts_import_file').trigger('click');
    });
    
    // Handle file selection for import
    $('#mementor_tts_import_file').on('change', function(e) {
        var file = e.target.files[0];
        if (!file) {
            return;
        }
        
        var reader = new FileReader();
        reader.onload = function(e) {
            try {
                var settings = JSON.parse(e.target.result);
                
                // Send settings to server
                $.ajax({
                    url: mementorTTS.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'mementor_tts_import_settings',
                        settings: settings,
                        nonce: mementorTTS.importNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            alert(mementorTTS.strings.importSuccess);
                            location.reload();
                        } else {
                            alert(mementorTTS.strings.importError + ' ' + response.data);
                        }
                    },
                    error: function() {
                        alert(mementorTTS.strings.importErrorTryAgain);
                    }
                });
            } catch (e) {
                alert(mementorTTS.strings.invalidSettingsFile);
            }
        };
        reader.readAsText(file);
    });
    
    // Export settings button click handler
    $('#mementor_tts_export_settings').on('click', function() {
        $.ajax({
            url: mementorTTS.ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_export_settings',
                nonce: mementorTTS.exportNonce
            },
            success: function(response) {
                if (response.success) {
                    // Create and download file
                    var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(response.data));
                    var downloadAnchorNode = document.createElement('a');
                    downloadAnchorNode.setAttribute("href", dataStr);
                    downloadAnchorNode.setAttribute("download", "mementor-tts-settings-" + new Date().toISOString().slice(0,10) + ".json");
                    document.body.appendChild(downloadAnchorNode);
                    downloadAnchorNode.click();
                    downloadAnchorNode.remove();
                } else {
                    alert(mementorTTS.strings.exportError + ' ' + response.data);
                }
            },
            error: function() {
                alert(mementorTTS.strings.exportErrorTryAgain);
            }
        });
    });
    
    // Clear cache button click handler
    $('#mementor_tts_clear_cache').on('click', function() {
        if (confirm(mementorTTS.strings.confirmClearCache)) {
            // Add AJAX call to clear cache
            $(this).html('<span class="dashicons dashicons-update mementor-tts-spinning"></span> ' + mementorTTS.strings.clearing);
            
            $.ajax({
                url: mementorTTS.ajaxurl,
                type: 'POST',
                data: {
                    action: 'mementor_tts_clear_cache',
                    nonce: mementorTTS.clearCacheNonce
                },
                success: function(response) {
                    if (response.success) {
                        $('#mementor_tts_clear_cache').html('<span class="dashicons dashicons-yes"></span> ' + mementorTTS.strings.cacheCleared);
                    } else {
                        $('#mementor_tts_clear_cache').html('<span class="dashicons dashicons-warning"></span> ' + mementorTTS.strings.error);
                        alert(mementorTTS.strings.clearCacheError + ' ' + response.data);
                    }
                    setTimeout(function() {
                        $('#mementor_tts_clear_cache').html('<span class="dashicons dashicons-trash"></span> ' + mementorTTS.strings.clearCache);
                    }, 2000);
                },
                error: function() {
                    $('#mementor_tts_clear_cache').html('<span class="dashicons dashicons-warning"></span> ' + mementorTTS.strings.error);
                    alert(mementorTTS.strings.clearCacheErrorTryAgain);
                    setTimeout(function() {
                        $('#mementor_tts_clear_cache').html('<span class="dashicons dashicons-trash"></span> ' + mementorTTS.strings.clearCache);
                    }, 2000);
                }
            });
        }
    });
}); 