/**
 * VMPFence Login Security Settings JavaScript
 * Handles Settings tab functionality
 * Phase 1: Show Last Login Column & Delete on Deactivation
 * Phase 2: User Statistics & NTP Toggle
 * Phase 3: 2FA Core Settings (Roles, Grace Period, Remember Device)
 *
 * @package VMPFence
 * @since 2.1.0
 */

(function($) {
    'use strict';

    // Store original settings for change detection
    let originalSettings = {};
    let hasUnsavedChanges = false;
    let isProgrammaticChange = false; // Flag to prevent handlers during programmatic updates
    let isSaving = false; // Flag to prevent concurrent save operations
    let isInitialized = false; // Flag to prevent duplicate initialization
    
    // AJAX URL and nonce - global within module scope
    let ajaxUrl = '';
    let nonce = '';

    /**
     * Initialize settings tab
     */
    function init() {
        // Only initialize if we're on the settings tab (check if it's the active tab)
        if (!$('#settings').hasClass('active')) {
            return;
        }

        // Load settings only once
        if (!isInitialized) {
            loadSettings();
            loadUserStats(); // Phase 2: Load user statistics
            setupUnsavedChangesWarning();
            isInitialized = true;
        }

        // Always attach event handlers (with .off() first to prevent duplicates)
        attachEventHandlers();
    }

    /**
     * Load current settings from server
     */
    function loadSettings() {
        ajaxUrl = $('#vmpfence-ajax-url').val();
        nonce = $('#vmpfence-settings-nonce').val();

        // Validate required fields
        if (!ajaxUrl || !nonce) {
            console.error('Missing AJAX URL or nonce for loading settings');
            if (typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showError('Unable to load settings. Please refresh the page.', 5000);
            } else {
                alert('Unable to load settings. Please refresh the page.');
            }
            return;
        }

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'vmpfence_load_login_settings',
                nonce: nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    applySettings(response.data);
                    originalSettings = $.extend(true, {}, response.data);
                    hasUnsavedChanges = false;
                } else if (response.success && !response.data) {
                    // Success but no data returned - this shouldn't happen
                    console.error('Settings loaded but no data returned');
                    if (typeof VMPFenceNotifications !== 'undefined') {
                        VMPFenceNotifications.showWarning('Settings data is missing. Using defaults.', 5000);
                    }
                } else {
                    // Response indicated failure
                    console.error('Failed to load settings:', response);
                    if (typeof VMPFenceNotifications !== 'undefined') {
                        VMPFenceNotifications.showError('Failed to load settings: ' + (response.data && response.data.message ? response.data.message : 'Unknown error'), 5000);
                    } else {
                        alert('Failed to load settings. Please refresh the page.');
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('Failed to load settings:', error);
                if (typeof VMPFenceNotifications !== 'undefined') {
                    VMPFenceNotifications.showError('Failed to load settings. Please refresh the page.', 5000);
                } else {
                    alert('Failed to load settings. Please refresh the page.');
                }
            }
        });
    }

    /**
     * Apply settings to form controls
     */
    function applySettings(settings) {
        // Validate settings parameter
        if (!settings || typeof settings !== 'object') {
            console.error('Invalid settings object passed to applySettings');
            return;
        }

        // Set flag to prevent change handlers from firing
        isProgrammaticChange = true;

        // Show Last Login Column (default: true)
        // Handle boolean, integer, and string values from database (false/0/'0' = unchecked)
        $('#vmpfence-show-last-login-column').prop('checked', settings.show_last_login_column !== false && settings.show_last_login_column !== 0 && settings.show_last_login_column !== '0');

        // Delete on Deactivation (default: false)
        // Handle boolean, integer, and string values from database (true/1/'1' = checked)
        $('#vmpfence-delete-on-deactivate').prop('checked', settings.delete_on_deactivate === true || settings.delete_on_deactivate === 1 || settings.delete_on_deactivate === '1');

        // Phase 2: NTP enabled state (default: true)
        const ntpEnabled = settings.ntp_enabled !== false && settings.ntp_enabled !== 0 && settings.ntp_enabled !== '0';
        $('#vmpfence-ntp-toggle-btn').text(ntpEnabled ? 'DISABLE' : 'ENABLE');
        $('#ntp-status-text').text('NTP is currently ' + (ntpEnabled ? 'enabled' : 'disabled') + '.');

        // Phase 3: 2FA Role Settings (default: administrator=optional, others=disabled)
        const roles = ['administrator', 'editor', 'author', 'contributor', 'subscriber'];
        const defaultRoleSettings = {
            administrator: 'optional',
            editor: 'disabled',
            author: 'disabled',
            contributor: 'disabled',
            subscriber: 'disabled'
        };
        
        roles.forEach(function(role) {
            const roleValue = settings['2fa_role_' + role] || defaultRoleSettings[role];
            $('#vmpfence-2fa-role-' + role).val(roleValue);
        });

        // Phase 3: Grace Period (default: 10 days)
        const gracePeriod = settings['2fa_grace_period'] !== undefined ? parseInt(settings['2fa_grace_period']) : 10;
        $('#vmpfence-2fa-grace-period').val(gracePeriod);

        // Phase 3: Remember Device (default: false)
        $('#vmpfence-2fa-remember-device').prop('checked', settings['2fa_remember_device'] === true || settings['2fa_remember_device'] === 1 || settings['2fa_remember_device'] === '1');

        // Phase 4: XML-RPC 2FA Required (default: false)
        const xmlrpc2faRequired = settings['xmlrpc_2fa_required'] === true || settings['xmlrpc_2fa_required'] === 1 || settings['xmlrpc_2fa_required'] === '1';
        if (xmlrpc2faRequired) {
            $('#vmpfence-xmlrpc-2fa-btn-skipped').removeClass('active');
            $('#vmpfence-xmlrpc-2fa-btn-required').addClass('active');
        } else {
            $('#vmpfence-xmlrpc-2fa-btn-skipped').addClass('active');
            $('#vmpfence-xmlrpc-2fa-btn-required').removeClass('active');
        }

        // Phase 4: Disable XML-RPC Auth (default: false)
        $('#vmpfence-disable-xmlrpc-auth').prop('checked', settings['disable_xmlrpc_auth'] === true || settings['disable_xmlrpc_auth'] === 1 || settings['disable_xmlrpc_auth'] === '1');

        // Phase 5: WooCommerce integration (default: false)
        $('#vmpfence-woocommerce-integration').prop('checked', settings['woocommerce_integration'] === true || settings['woocommerce_integration'] === 1 || settings['woocommerce_integration'] === '1');

        // Phase 5: 2FA Shortcode (default: false)
        $('#vmpfence-2fa-shortcode').prop('checked', settings['2fa_shortcode_enabled'] === true || settings['2fa_shortcode_enabled'] === 1 || settings['2fa_shortcode_enabled'] === '1');

        // Phase 6: reCAPTCHA Enabled (default: false)
        $('#vmpfence-recaptcha-enabled').prop('checked', settings['recaptcha_enabled'] === true || settings['recaptcha_enabled'] === 1 || settings['recaptcha_enabled'] === '1');

        // Phase 6: reCAPTCHA Site Key (default: empty string)
        $('#vmpfence-recaptcha-site-key').val(settings['recaptcha_site_key'] || '');

        // Phase 6: reCAPTCHA Secret Key (default: empty string)
        $('#vmpfence-recaptcha-secret-key').val(settings['recaptcha_secret_key'] || '');

        // Phase 6: reCAPTCHA Threshold (default: 0.5)
        const recaptchaThreshold = settings['recaptcha_threshold'] !== undefined ? parseFloat(settings['recaptcha_threshold']) : 0.5;
        $('#vmpfence-recaptcha-threshold').val(recaptchaThreshold.toFixed(1));

        // PHASE 7: IP Allowlist
        const ipAllowlist = settings['ip_allowlist'] !== undefined ? settings['ip_allowlist'] : '';
        $('#vmpfence-ip-allowlist').val(ipAllowlist);

        // Reset flag after changes are applied
        isProgrammaticChange = false;
    }

    /**
     * Collect current form values
     */
    function collectFormValues() {
        const values = {
            show_last_login_column: $('#vmpfence-show-last-login-column').is(':checked'),
            delete_on_deactivate: $('#vmpfence-delete-on-deactivate').is(':checked'),
            ntp_enabled: $('#vmpfence-ntp-toggle-btn').text().trim() === 'DISABLE'
        };

        // Phase 3: Collect 2FA role settings
        const roles = ['administrator', 'editor', 'author', 'contributor', 'subscriber'];
        roles.forEach(function(role) {
            values['2fa_role_' + role] = $('#vmpfence-2fa-role-' + role).val();
        });

        // Phase 3: Grace Period (handle empty, zero, or invalid values)
        const gracePeriodInput = $('#vmpfence-2fa-grace-period').val();
        const gracePeriodValue = gracePeriodInput === '' ? 10 : parseInt(gracePeriodInput);
        values['2fa_grace_period'] = isNaN(gracePeriodValue) ? 10 : gracePeriodValue;

        // Phase 3: Remember Device
        values['2fa_remember_device'] = $('#vmpfence-2fa-remember-device').is(':checked');

        // Phase 4: XML-RPC settings
        values['xmlrpc_2fa_required'] = $('#vmpfence-xmlrpc-2fa-btn-required').hasClass('active');
        values['disable_xmlrpc_auth'] = $('#vmpfence-disable-xmlrpc-auth').is(':checked');

        // Phase 5: WooCommerce and Shortcode settings
        values['woocommerce_integration'] = $('#vmpfence-woocommerce-integration').is(':checked');
        values['2fa_shortcode_enabled'] = $('#vmpfence-2fa-shortcode').is(':checked');

        // Phase 6: reCAPTCHA settings
        values['recaptcha_enabled'] = $('#vmpfence-recaptcha-enabled').is(':checked');
        values['recaptcha_site_key'] = $('#vmpfence-recaptcha-site-key').val().trim();
        values['recaptcha_secret_key'] = $('#vmpfence-recaptcha-secret-key').val().trim();
        values['recaptcha_threshold'] = parseFloat($('#vmpfence-recaptcha-threshold').val());

        // PHASE 7: IP Allowlist
        values['ip_allowlist'] = $('#vmpfence-ip-allowlist').val();

        return values;
    }

    /**
     * Check if settings have changed
     */
    function settingsChanged() {
        const currentSettings = collectFormValues();
        return JSON.stringify(currentSettings) !== JSON.stringify(originalSettings);
    }

    /**
     * Attach event handlers (remove first to prevent duplicates)
     */
    function attachEventHandlers() {
        // Save button click (remove any existing handler first)
        $('#vmpfence-save-settings').off('click').on('click', function(e) {
            e.preventDefault();
            saveSettings();
        });

        // Cancel button click
        $('#vmpfence-cancel-settings').off('click').on('click', function(e) {
            e.preventDefault();
            cancelChanges();
        });

        // Track changes on form controls
        $('#vmpfence-show-last-login-column, #vmpfence-delete-on-deactivate').off('change').on('change', function() {
            // Only track user-initiated changes, not programmatic ones
            if (!isProgrammaticChange) {
                hasUnsavedChanges = settingsChanged();
            }
        });

        // Phase 3: Track changes on 2FA role dropdowns
        $('#vmpfence-2fa-role-administrator, #vmpfence-2fa-role-editor, #vmpfence-2fa-role-author, #vmpfence-2fa-role-contributor, #vmpfence-2fa-role-subscriber').off('change').on('change', function() {
            if (!isProgrammaticChange) {
                hasUnsavedChanges = settingsChanged();
            }
        });

        // Phase 3: Track changes on grace period input
        $('#vmpfence-2fa-grace-period').off('input').on('input', function() {
            if (!isProgrammaticChange) {
                hasUnsavedChanges = settingsChanged();
            }
        });

        // Phase 3: Track changes on remember device checkbox
        $('#vmpfence-2fa-remember-device').off('change').on('change', function() {
            if (!isProgrammaticChange) {
                hasUnsavedChanges = settingsChanged();
            }
        });

        // Phase 4: XML-RPC 2FA toggle buttons
        $('#vmpfence-xmlrpc-2fa-btn-skipped, #vmpfence-xmlrpc-2fa-btn-required').off('click').on('click', function() {
            if (isProgrammaticChange) return;
            
            const $clickedBtn = $(this);
            const isSkipped = $clickedBtn.attr('id') === 'vmpfence-xmlrpc-2fa-btn-skipped';
            
            // Update visual state
            $('#vmpfence-xmlrpc-2fa-btn-skipped, #vmpfence-xmlrpc-2fa-btn-required').removeClass('active');
            $clickedBtn.addClass('active');
            
            // Mark form dirty
            hasUnsavedChanges = settingsChanged();
            
            // Show warning if switching to REQUIRED
            if (!isSkipped && typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showWarning(
                    'Warning: Requiring 2FA for XML-RPC may break mobile app access and other integrations!',
                    5000
                );
            }
        });

        // Phase 4: Disable XML-RPC checkbox
        $('#vmpfence-disable-xmlrpc-auth').off('change').on('change', function() {
            if (isProgrammaticChange) return;
            
            hasUnsavedChanges = settingsChanged();
            
            if ($(this).is(':checked') && typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showWarning(
                    'Warning: Disabling XML-RPC authentication will prevent mobile apps and other services from accessing your site!',
                    5000
                );
            }
        });

        // Phase 2: NTP toggle button
        $('#vmpfence-ntp-toggle-btn').off('click').on('click', function(e) {
            e.preventDefault();
            handleNTPToggle();
        });

        // Phase 5: WooCommerce integration checkbox
        $('#vmpfence-woocommerce-integration').off('change').on('change', function() {
            if (isProgrammaticChange) return;
            
            hasUnsavedChanges = settingsChanged();
            
            // Show warning if enabling and WooCommerce not detected
            if ($(this).is(':checked')) {
                // Check if WooCommerce is active (we'll validate on save)
                if (typeof VMPFenceNotifications !== 'undefined') {
                    VMPFenceNotifications.showInfo(
                        'Remember to click "Save Changes" to apply this setting.',
                        3000
                    );
                }
            }
        });

        // Phase 5: 2FA shortcode checkbox
        $('#vmpfence-2fa-shortcode').off('change').on('change', function() {
            if (isProgrammaticChange) return;
            
            hasUnsavedChanges = settingsChanged();
            
            if ($(this).is(':checked') && typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showInfo(
                    'Use [vmpfence_2fa] shortcode in any page after saving.',
                    3000
                );
            }
        });

        // Phase 6: reCAPTCHA enabled checkbox
        $('#vmpfence-recaptcha-enabled').off('change').on('change', function() {
            if (isProgrammaticChange) return;
            
            hasUnsavedChanges = settingsChanged();
            
            if ($(this).is(':checked') && typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showInfo(
                    'Remember to configure Site Key and Secret below.',
                    3000
                );
            }
        });

        // Phase 6: reCAPTCHA Site Key input
        $('#vmpfence-recaptcha-site-key').off('input').on('input', function() {
            if (isProgrammaticChange) return;
            
            hasUnsavedChanges = settingsChanged();
        });

        // Phase 6: reCAPTCHA Secret Key input
        $('#vmpfence-recaptcha-secret-key').off('input').on('input', function() {
            if (isProgrammaticChange) return;
            
            hasUnsavedChanges = settingsChanged();
        });

        // Phase 6: reCAPTCHA Threshold dropdown
        $('#vmpfence-recaptcha-threshold').off('change').on('change', function() {
            if (isProgrammaticChange) return;
            
            hasUnsavedChanges = settingsChanged();
            
            const threshold = parseFloat($(this).val());
            if (threshold < 0.3 && typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showWarning(
                    'Low threshold values may block legitimate users.',
                    3000
                );
            } else if (threshold > 0.7 && typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showWarning(
                    'High threshold values may allow bots through.',
                    3000
                );
            }
        });

        // PHASE 7: IP Allowlist textarea change detection
        $('#vmpfence-ip-allowlist').off('input.loginSettings').on('input.loginSettings', function() {
            if (isProgrammaticChange) return;
            hasUnsavedChanges = settingsChanged();
            // Clear status when user types
            $('#vmpfence-ip-allowlist-status').text('').removeClass('success-text error-text');
        });

        // PHASE 7: Validate & Apply button for IP allowlist
        $('#vmpfence-validate-ip-allowlist').off('click').on('click', function() {
            const ipAllowlist = $('#vmpfence-ip-allowlist').val();
            const $button = $(this);
            const $status = $('#vmpfence-ip-allowlist-status');
            const originalText = $button.text();
            
            // Show validating state
            $button.prop('disabled', true).text('Validating...');
            $status.text('').removeClass('success-text error-text');
            
            // Timeout fallback in case AJAX hangs
            const timeoutId = setTimeout(function() {
                $button.prop('disabled', false).text(originalText);
                $status.text('✗ Validation timeout').addClass('error-text');
            }, 10000); // 10 second timeout
            
            // Perform validation
            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: {
                    action: 'vmpfence_validate_ip_allowlist',
                    nonce: nonce,
                    ip_allowlist: ipAllowlist
                },
                timeout: 10000, // 10 second Ajax timeout
                success: function(response) {
                    clearTimeout(timeoutId);
                    $button.prop('disabled', false).text(originalText);
                    
                    if (response.success) {
                        $status.text('✓ Valid - Changes will be saved when you click SAVE at the top')
                               .removeClass('error-text')
                               .addClass('success-text');
                        
                        if (typeof VMPFenceNotifications !== 'undefined') {
                            VMPFenceNotifications.showSuccess('IP allowlist validated successfully. Click SAVE to commit changes.', 4000);
                        }
                        
                        // Mark as having unsaved changes
                        hasUnsavedChanges = true;
                    } else {
                        $status.text('✗ Invalid format')
                               .removeClass('success-text')
                               .addClass('error-text');
                        
                        const errorMsg = response.data && response.data.message ? response.data.message : 'Validation failed';
                        if (typeof VMPFenceNotifications !== 'undefined') {
                            VMPFenceNotifications.showError(errorMsg, 6000);
                        } else {
                            alert('Validation Error: ' + errorMsg);
                        }
                    }
                },
                error: function(xhr, status, error) {
                    clearTimeout(timeoutId);
                    $button.prop('disabled', false).text(originalText);
                    $status.text('✗ Validation error')
                           .removeClass('success-text')
                           .addClass('error-text');
                    
                    console.error('VMPFence validation AJAX error:', status, error, xhr);
                    
                    if (typeof VMPFenceNotifications !== 'undefined') {
                        VMPFenceNotifications.showError('Validation Error: ' + error, 5000);
                    } else {
                        alert('Validation Error: ' + error);
                    }
                },
                complete: function() {
                    // Always re-enable button in complete handler as fallback
                    $button.prop('disabled', false).text(originalText);
                }
            });
        });

        // Special confirmation for Delete on Deactivation
        $('#vmpfence-delete-on-deactivate').off('change.deleteWarning').on('change.deleteWarning', function() {
            // Only show warning for user-initiated checks, not programmatic ones
            if (!isProgrammaticChange && $(this).is(':checked')) {
                showDeleteOnDeactivationWarning($(this));
            }
        });
    }

    /**
     * Show warning when enabling Delete on Deactivation
     */
    function showDeleteOnDeactivationWarning($checkbox) {
        if (typeof VMPFenceNotifications !== 'undefined') {
            VMPFenceNotifications.showConfirmModal({
                title: 'Enable Data Deletion?',
                message: '⚠️ WARNING: All Login Security data will be PERMANENTLY DELETED if you deactivate the plugin. This includes:\n\n• Login Security settings\n• 2FA configurations\n• User login history\n• All related data\n\nThis action cannot be undone. Are you sure?',
                confirmText: 'Enable',
                cancelText: 'Cancel',
                type: 'danger',
                showIcon: true
            }).then(function(confirmed) {
                if (!confirmed) {
                    // User cancelled, uncheck the box (set flag to prevent handlers)
                    isProgrammaticChange = true;
                    $checkbox.prop('checked', false);
                    isProgrammaticChange = false;
                    // Recalculate unsaved changes
                    hasUnsavedChanges = settingsChanged();
                }
            });
        } else {
            // Fallback to native confirm
            if (!confirm('⚠️ WARNING: All Login Security data will be PERMANENTLY DELETED if you deactivate the plugin. This includes:\n\n• Login Security settings\n• 2FA configurations\n• User login history\n• All related data\n\nThis action cannot be undone. Are you sure?')) {
                // User cancelled, uncheck the box (set flag to prevent handlers)
                isProgrammaticChange = true;
                $checkbox.prop('checked', false);
                isProgrammaticChange = false;
                // Recalculate unsaved changes
                hasUnsavedChanges = settingsChanged();
            }
        }
    }

    /**
     * Save settings to server
     */
    function saveSettings() {
        // Prevent concurrent save operations
        if (isSaving) {
            console.warn('Save already in progress');
            return;
        }

        // Validate required fields (use module-scoped variables)
        if (!ajaxUrl || !nonce) {
            console.error('Missing AJAX URL or nonce for saving settings');
            if (typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showError('Unable to save settings. Please refresh the page.', 5000);
            } else {
                alert('Unable to save settings. Please refresh the page.');
            }
            return;
        }

        const settings = collectFormValues();

        // Validate settings
        const validation = validateSettings(settings);
        if (!validation.valid) {
            if (typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showError(validation.message, 5000);
            } else {
                alert('Validation Error: ' + validation.message);
            }
            return;
        }

        // Show loading state
        const $saveButton = $('#vmpfence-save-settings');
        const originalText = $saveButton.text();
        $saveButton.prop('disabled', true).text('Saving...');
        isSaving = true;

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'vmpfence_save_login_settings',
                nonce: nonce,
                settings: JSON.stringify(settings)
            },
            success: function(response) {
                if (response.success) {
                    // Check if Last Login column setting changed BEFORE updating originalSettings
                    const lastLoginChanged = settings.show_last_login_column !== originalSettings.show_last_login_column;
                    const lastLoginEnabled = settings.show_last_login_column;
                    
                    // Update original settings
                    originalSettings = $.extend(true, {}, settings);
                    hasUnsavedChanges = false;

                    if (typeof VMPFenceNotifications !== 'undefined') {
                        // Show success message
                        VMPFenceNotifications.showSuccess('Login Security settings saved successfully!', 3000);

                        // Show info about Last Login column if changed
                        if (lastLoginChanged) {
                            setTimeout(function() {
                                if (lastLoginEnabled) {
                                    VMPFenceNotifications.showInfo('Last Login column enabled. Visit the Users page to see it. If not visible, refresh WordPress admin.', 6000);
                                } else {
                                    VMPFenceNotifications.showInfo('Last Login column disabled. If still visible on Users page, refresh your WordPress admin (Ctrl+Shift+R).', 6000);
                                }
                            }, 500);
                        } else if (lastLoginEnabled) {
                            setTimeout(function() {
                                VMPFenceNotifications.showInfo('Visit the Users page to see the Last Login column.', 4000);
                            }, 500);
                        }
                    } else {
                        alert('Settings saved successfully!');
                    }
                } else {
                    if (typeof VMPFenceNotifications !== 'undefined') {
                        VMPFenceNotifications.showError(
                            response.data && response.data.message 
                                ? response.data.message 
                                : 'Failed to save settings. Please try again.',
                            5000
                        );
                    } else {
                        alert('Error: ' + (response.data && response.data.message ? response.data.message : 'Failed to save settings. Please try again.'));
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('Save settings error:', error);
                if (typeof VMPFenceNotifications !== 'undefined') {
                    VMPFenceNotifications.showError('An error occurred while saving settings. Please try again.', 5000);
                } else {
                    alert('An error occurred while saving settings. Please try again.');
                }
            },
            complete: function() {
                // Restore button state
                $saveButton.prop('disabled', false).text(originalText);
                isSaving = false;
            }
        });
    }

    /**
     * Validate settings before save
     */
    function validateSettings(settings) {
        // Phase 3: Validate grace period (0-365 days)
        const gracePeriod = parseInt(settings['2fa_grace_period']);
        if (isNaN(gracePeriod) || gracePeriod < 0 || gracePeriod > 365) {
            return {
                valid: false,
                message: 'Grace period must be between 0 and 365 days.'
            };
        }

        // Phase 3: Validate role settings (must be disabled, optional, or required)
        const roles = ['administrator', 'editor', 'author', 'contributor', 'subscriber'];
        const validValues = ['disabled', 'optional', 'required'];
        
        for (let i = 0; i < roles.length; i++) {
            const role = roles[i];
            const roleValue = settings['2fa_role_' + role];
            if (!validValues.includes(roleValue)) {
                return {
                    valid: false,
                    message: 'Invalid 2FA setting for role: ' + role
                };
            }
        }

        // Phase 6: Validate reCAPTCHA keys if enabled
        if (settings['recaptcha_enabled']) {
            const siteKey = settings['recaptcha_site_key'];
            const secretKey = settings['recaptcha_secret_key'];
            
            if (!siteKey || siteKey.length < 40) {
                return {
                    valid: false,
                    message: 'reCAPTCHA Site Key must be at least 40 characters.'
                };
            }
            
            if (!secretKey || secretKey.length < 40) {
                return {
                    valid: false,
                    message: 'reCAPTCHA Secret Key must be at least 40 characters.'
                };
            }
            
            // Validate alphanumeric format
            if (!/^[A-Za-z0-9_-]+$/.test(siteKey)) {
                return {
                    valid: false,
                    message: 'reCAPTCHA Site Key contains invalid characters.'
                };
            }
            
            if (!/^[A-Za-z0-9_-]+$/.test(secretKey)) {
                return {
                    valid: false,
                    message: 'reCAPTCHA Secret Key contains invalid characters.'
                };
            }
        }

        // Phase 6: Validate threshold (0.0-1.0)
        const threshold = parseFloat(settings['recaptcha_threshold']);
        if (isNaN(threshold) || threshold < 0.0 || threshold > 1.0) {
            return {
                valid: false,
                message: 'reCAPTCHA threshold must be between 0.0 and 1.0.'
            };
        }

        return {
            valid: true,
            message: ''
        };
    }

    /**
     * Cancel changes and restore original values
     */
    function cancelChanges() {
        if (!hasUnsavedChanges) {
            if (typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showInfo('No changes to discard.', 2000);
            } else {
                alert('No changes to discard.');
            }
            return;
        }

        if (typeof VMPFenceNotifications !== 'undefined') {
            VMPFenceNotifications.showConfirmModal({
                title: 'Discard Changes?',
                message: 'Are you sure you want to discard your unsaved changes?',
                confirmText: 'Discard',
                cancelText: 'Keep Editing',
                type: 'warning',
                showIcon: true
            }).then(function(confirmed) {
                if (confirmed) {
                    // Restore original values
                    applySettings(originalSettings);
                    hasUnsavedChanges = false;
                    VMPFenceNotifications.showInfo('Changes discarded.', 2000);
                }
            });
        } else {
            // Fallback to native confirm
            if (confirm('Are you sure you want to discard your unsaved changes?')) {
                applySettings(originalSettings);
                hasUnsavedChanges = false;
                alert('Changes discarded.');
            }
        }
    }

    /**
     * Setup unsaved changes warning
     */
    function setupUnsavedChangesWarning() {
        // Warn user if they try to leave with unsaved changes
        $(window).on('beforeunload', function(e) {
            if (hasUnsavedChanges) {
                const message = 'You have unsaved changes. Are you sure you want to leave?';
                e.returnValue = message;
                return message;
            }
        });

        // Note: hasUnsavedChanges is set to false AFTER successful save
        // This prevents the race condition where user clicks save then immediately navigates away
    }

    /**
     * Load user statistics by role with 2FA status (Phase 2)
     */
    function loadUserStats() {
        const ajaxUrl = $('#vmpfence-ajax-url').val();
        const nonce = $('#vmpfence-settings-nonce').val();

        if (!ajaxUrl || !nonce) {
            console.error('Missing AJAX URL or nonce for loading user stats');
            return;
        }

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'vmpfence_get_user_stats',
                nonce: nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    updateUserStatsTable(response.data);
                } else {
                    // Show error message in table
                    $('#user-stats-tbody').html(
                        '<tr><td colspan="4" style="text-align: center; color: #dc3232;">Unable to load user statistics. Please refresh the page.</td></tr>'
                    );
                }
            },
            error: function(xhr, status, error) {
                console.error('Failed to load user stats:', error);
                // Show error message in table
                $('#user-stats-tbody').html(
                    '<tr><td colspan="4" style="text-align: center; color: #dc3232;">Unable to load user statistics. Please refresh the page.</td></tr>'
                );
            }
        });
    }

    /**
     * Update user stats table with data from server (Phase 2)
     */
    function updateUserStatsTable(data) {
        const $tbody = $('#user-stats-tbody');
        $tbody.empty();
        
        let totalUsers = 0, totalActive = 0, totalInactive = 0;
        
        // Add row for each role (using jQuery DOM creation to prevent XSS)
        $.each(data.roles, function(role, roleData) {
            totalUsers += roleData.total;
            totalActive += roleData.twofa_active;
            totalInactive += roleData.twofa_inactive;
            
            $tbody.append(
                $('<tr>').append(
                    $('<td>').text(roleData.name),
                    $('<td>').text(roleData.total),
                    $('<td>').text(roleData.twofa_active),
                    $('<td>').text(roleData.twofa_inactive)
                )
            );
        });
        
        // Add totals row (using jQuery DOM creation to prevent XSS)
        $tbody.append(
            $('<tr>').css('font-weight', 'bold').append(
                $('<td>').text('Total'),
                $('<td>').text(totalUsers),
                $('<td>').text(totalActive),
                $('<td>').text(totalInactive)
            )
        );
    }

    /**
     * Handle NTP toggle button click (Phase 2)
     */
    function handleNTPToggle() {
        const $btn = $('#vmpfence-ntp-toggle-btn');
        const currentlyEnabled = $btn.text().trim() === 'DISABLE';
        const newState = !currentlyEnabled;
        
        // Disable button during save
        $btn.prop('disabled', true);
        
        const ajaxUrl = $('#vmpfence-ajax-url').val();
        const nonce = $('#vmpfence-settings-nonce').val();
        
        // IMPORTANT: Only save NTP setting to avoid accidentally saving other modified settings
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'vmpfence_save_login_settings',
                nonce: nonce,
                settings: JSON.stringify({
                    ntp_enabled: newState
                })
            },
            success: function(response) {
                if (response.success) {
                    // Update button text and status
                    $btn.text(newState ? 'DISABLE' : 'ENABLE');
                    $('#ntp-status-text').text(
                        'NTP is currently ' + (newState ? 'enabled' : 'disabled') + '.'
                    );
                    
                    // Update original settings to reflect change
                    originalSettings.ntp_enabled = newState;
                    
                    // Show success toast
                    if (typeof VMPFenceNotifications !== 'undefined') {
                        VMPFenceNotifications.showSuccess(
                            'NTP ' + (newState ? 'enabled' : 'disabled') + ' successfully', 
                            3000
                        );
                    }
                } else {
                    // Show error toast
                    if (typeof VMPFenceNotifications !== 'undefined') {
                        VMPFenceNotifications.showError(
                            'Failed to update NTP setting: ' + (response.data && response.data.message ? response.data.message : 'Unknown error'),
                            5000
                        );
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('Failed to save NTP setting:', error);
                // Show error toast
                if (typeof VMPFenceNotifications !== 'undefined') {
                    VMPFenceNotifications.showError('Network error while saving NTP setting', 5000);
                }
            },
            complete: function() {
                // Re-enable button
                $btn.prop('disabled', false);
            }
        });
    }

    // Phase 5 handlers removed - these checkboxes now use bulk save like all other settings

    // Initialize when document is ready
    $(document).ready(function() {
        init();
        
        // Re-initialize when Settings tab is clicked (fixes save button after tab switch)
        $(document).on('click', '.vmpfence-tabs-nav button[data-tab="settings"]', function() {
            // Small delay to ensure tab is active
            setTimeout(function() {
                if ($('#settings').hasClass('active')) {
                    init();
                }
            }, 50);
        });
    });

})(jQuery);
