/**
 * FormShield Email Settings JavaScript
 * 
 * Handles all email settings functionality including:
 * - Saving email settings
 * - Sending test emails
 * - Form validation
 * - User feedback
 * 
 * @since 1.0.3-beta
 */
jQuery(document).ready(function($) {
    const DEBUG = false;
    
    const FormShieldEmailSettings = {
        init: function() {
            this.setupEventListeners();
        },
        
        setupEventListeners: function() {
            // Save email settings
            $('.save-email-settings').on('click', (e) => {
                e.preventDefault();
                this.saveEmailSettings();
            });
            
            // Test email functionality
            $('.test-email').on('click', (e) => {
                e.preventDefault();
                this.testEmail();
            });
            
            // Real-time validation
            $('#admin-email').on('blur', (e) => {
                this.validateEmail($(e.target).val());
            });
            
            // Periodic reports toggle
            $('#periodic_reports').on('change', (e) => {
                this.toggleReportFrequency($(e.target).is(':checked'));
            });
        },
        
        saveEmailSettings: function() {
            const button = $('.save-email-settings');
            const originalText = button.text();
            
            // Disable button and show loading
            button.prop('disabled', true).text('Saving...');
            
            // Collect form data
            const formData = {
                admin_email: $('#admin-email').val(),
                notification_frequency: $('#notification-frequency').val(),
                email_attacks: $('#email-attacks').is(':checked'),
                email_forms: $('#email-forms').is(':checked'),
                periodic_reports: $('#periodic_reports').is(':checked'),
                report_frequency: $('#report_frequency').val(),
                nonce: formshieldData.nonce
            };
            
            
            // Send AJAX request
            $.ajax({
                url: formshieldData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'formshield_save_email_settings',
                    ...formData
                },
                success: (response) => {
                    if (response.success) {
                        this.showSuccess('Email settings saved successfully!');
                    } else {
                        this.showError('Failed to save settings: ' + response.data);
                        if (DEBUG) console.error('FormShield: Save failed:', response.data);
                    }
                },
                error: (xhr, status, error) => {
                    this.showError('Error saving settings: ' + error);
                    if (DEBUG) console.error('FormShield: AJAX error:', error);
                },
                complete: () => {
                    // Re-enable button
                    button.prop('disabled', false).text(originalText);
                }
            });
        },
        
        testEmail: function() {
            const button = $('.test-email');
            const originalText = button.text();
            const email = $('#admin-email').val();
            
            if (!this.validateEmail(email)) {
                this.showError('Please enter a valid email address first');
                return;
            }
            
            // Disable button and show loading
            button.prop('disabled', true).text('Sending...');
            
            
            // Send AJAX request
            $.ajax({
                url: formshieldData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'formsh_test_email',
                    admin_email: email,
                    nonce: formshieldData.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showSuccess('Test email sent successfully! Check your inbox.');
                    } else {
                        this.showError('Failed to send test email: ' + response.data);
                        if (DEBUG) console.error('FormShield: Test email failed:', response.data);
                    }
                },
                error: (xhr, status, error) => {
                    this.showError('Error sending test email: ' + error);
                    if (DEBUG) console.error('FormShield: Test email error:', error);
                },
                complete: () => {
                    // Re-enable button
                    button.prop('disabled', false).text(originalText);
                }
            });
        },
        
        validateEmail: function(email) {
            const emailField = $('#admin-email');
            const emailRow = emailField.closest('.form-row');
            
            // Remove existing validation classes
            emailRow.removeClass('valid invalid');
            emailRow.find('.validation-message').remove();
            
            if (!email) {
                return false;
            }
            
            // Basic email validation
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            const isValid = emailRegex.test(email);
            
            if (isValid) {
                emailRow.addClass('valid');
                emailRow.append('<span class="validation-message valid">✅ Valid email address</span>');
                return true;
            } else {
                emailRow.addClass('invalid');
                emailRow.append('<span class="validation-message invalid">❌ Invalid email address</span>');
                return false;
            }
        },
        
        showSuccess: function(message) {
            this.showMessage(message, 'success');
        },
        
        showError: function(message) {
            this.showMessage(message, 'error');
        },
        
        showMessage: function(message, type) {
            // Remove existing messages
            $('.formshield-message').remove();
            
            // Create message element
            const messageElement = $('<div>', {
                class: `formshield-message ${type}`,
                text: message
            });
            
            // Add to page
            $('.email-settings').prepend(messageElement);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                messageElement.fadeOut('slow', function() {
                    $(this).remove();
                });
            }, 5000);
        },
        
        toggleReportFrequency: function(enabled) {
            const reportFrequencyGroup = $('#report_frequency_group');
            
            if (enabled) {
                reportFrequencyGroup.slideDown('fast');
            } else {
                reportFrequencyGroup.slideUp('fast');
            }
        }
    };
    
    // Initialize email settings
    FormShieldEmailSettings.init();
});
