/**
 * VMPFence Firewall Options JavaScript
 * Handles ALL firewall options: Basic, Advanced, Brute Force, Rate Limiting, Allowlisted URLs
 * @since 2.0.0 -- Unified firewall options management
 * @since 2.2.1 -- Added Restore Defaults functionality
 * @since 2.2.4 -- Updated protection level buttons to use WAF optimizer modal system
 * @since 2.2.5 -- Filter by logic updated, IPs and URLs now support comma or newline separation
 */

jQuery(document).ready(function($) {
    'use strict';

    /**
     * Convert comma-separated string to newline-separated for textarea display
     */
    function commasToNewlines(str) {
        if (!str) return '';
        return str.split(/[,\s]+/).map(function(s) { return s.trim(); }).filter(Boolean).join('\n');
    }

    /**
     * VMPFence Firewall Options Object - Unified approach
     */
    window.VMPFenceFirewallOptions = {
        
        // Store initial state for cancel functionality
        initialFirewallState: {},
        
        /**
         * Initialize firewall options functionality
         */
        init: function() {
            // Only initialize if we're on the firewall options page
            if (!$('#vmpfence_firewall_options_nonce').length) {
                return;
            }

            this.initEventHandlers();
            this.loadAllSettings();
        },

        /**
         * Initialize event handlers
         */
        initEventHandlers: function() {
            var self = this;
            
            // Handle checkbox toggle switches  
            $('.vmpfence-toggle-btn').not('.vmpfence-btn-group .vmpfence-toggle-btn').on('click', function(e) {
                self.handleCheckboxToggle.call(this, e);
            });
            
            // Handle button group toggles (ON/OFF buttons)
            $('.vmpfence-btn-group .vmpfence-toggle-btn').on('click', function(e) {
                self.handleButtonGroupToggle.call(this, e);
            });
            
            // Handle unified save button - saves ALL firewall options
            $('.vmpfence-btn-save').off('click').on('click', function(e) {
                self.saveAllSettings(e);
            });
            
            // Handle restore defaults button
            $('.vmpfence-btn-restore').off('click').on('click', function(e) {
                self.restoreDefaults(e);
            });
            
            // Handle cancel changes button
            $('.vmpfence-btn-cancel').off('click').on('click', function(e) {
                self.cancelChanges(e);
            });
            
            // Initialize throttle behavior visibility
            self.initThrottleBehaviorVisibility();
            
            // Initialize param type select display
            self.initParamTypeSelect();
            
            // Handle protection level buttons
            // Note: These handlers are now managed by waf-optimization.js
            // The new WAF optimization modal system handles these buttons
            // $('#optimize-firewall').on('click', function(e) {
            //     e.preventDefault();
            //     self.enableExtendedProtection();
            // });
            
            // $('#remove-extended-protection').on('click', function(e) {
            //     e.preventDefault();
            //     self.disableExtendedProtection();
            // });
        },

        /**
         * Save ALL firewall settings using unified save method
         * Handles: Basic Firewall, Advanced, Brute Force, Rate Limiting, Allowlisted URLs
         */
        saveAllSettings: function(e) {
            if (e) {
                e.preventDefault();
            }
            
            var self = this;
            var $saveButton = $('.vmpfence-btn-save');
            var originalText = $saveButton.text();
            
            // Clear previous field errors
            self.clearFieldError($('#whitelisted_ips_bypass'));
            self.clearFieldError($('#ignored_ips_waf'));
            
            // Validate IP address fields
            var whitelistedIPs = $('#whitelisted_ips_bypass').val();
            var ignoredIPs = $('#ignored_ips_waf').val();
            
            var whitelistValidation = self.validateIPAddresses(whitelistedIPs);
            var ignoredValidation = self.validateIPAddresses(ignoredIPs);
            
            if (!whitelistValidation.valid) {
                self.showFieldError($('#whitelisted_ips_bypass'), whitelistValidation.errors);
                return;
            }
            
            if (!ignoredValidation.valid) {
                self.showFieldError($('#ignored_ips_waf'), ignoredValidation.errors);
                return;
            }
            
            // Show loading state
            $saveButton.prop('disabled', true).text('Saving All Options...');
            
            // Collect ALL firewall form data in one object
            var allFormData = {
                action: 'vmpfence_save_firewall_options',
                nonce: $('#vmpfence_firewall_options_nonce').val(),
                
                // === BASIC FIREWALL OPTIONS ===
                waf_enabled: $('#waf_enabled').val(),
                auto_update_rules: $('#auto_update_rules').length ? $('#auto_update_rules').is(':checked') : true,
                block_suspicious_requests: $('#block_suspicious_requests').length ? $('#block_suspicious_requests').is(':checked') : true,
                realtime_ip_blocklist_enabled: $('#realtime_ip_blocklist_enabled').val() == '1',
                
                // === BRUTE FORCE OPTIONS ===
                // Boolean settings (button toggle)
                brute_force_enabled: $('#brute_force_enabled').val() == '1',
                
                // Boolean settings (checkboxes)
                lock_invalid_usernames: $('#lock_invalid_usernames').is(':checked'),
                prevent_leaked_passwords_enabled: $('#prevent_leaked_passwords_enabled').is(':checked'),
                enforce_strong_passwords: $('#enforce_strong_passwords').is(':checked'),
                dont_reveal_users: $('#dont_reveal_users').is(':checked'),
                prevent_admin_username: $('#prevent_admin_username').is(':checked'),
                prevent_username_discovery: $('#prevent_username_discovery').is(':checked'),
                disable_app_passwords: $('#disable_app_passwords').is(':checked'),
                block_post_requests: $('#block_post_requests').is(':checked'),
                check_password_strength: $('#check_password_strength').is(':checked'),
                participate_security_network: $('#participate_security_network').is(':checked'),
                
                // Integer settings
                max_login_attempts: $('#max_login_failures').val(),
                max_forgot_password_attempts: $('#max_forgot_password').val(),
                count_failures_window: $('#count_failures_window').val(),
                lockout_duration: $('#lockout_duration').val(),
                permanent_ban_threshold: $('#permanent_ban_threshold').val() || 10,
                
                // String settings
                prevent_leaked_passwords_scope: $('#prevent_leaked_passwords_scope').val(),
                strong_passwords_scope: $('#strong_passwords_scope').val(),
                custom_block_text: $('#custom_block_text').val(),
                
                // Array settings (blocked usernames)
                blocked_usernames: $('#blocked_usernames').val(),
                
                // === RATE LIMITING OPTIONS ===
                // Rate limiting toggle (button group)
                rate_limiting_enabled: $('#rate_limiting_enabled').val() == '1',
                
                // All rate limiting settings from the guide
                google_crawler_treatment: $('#google_crawler_treatment').val(),
                global_rate_limit: $('#global_rate_limit').val(),
                global_rate_action: $('#global_rate_action').val(),
                crawler_rate_limit: $('#crawler_rate_limit').val(),
                crawler_rate_action: $('#crawler_rate_action').val(),
                crawler_404_limit: $('#crawler_404_limit').val(),
                crawler_404_action: $('#crawler_404_action').val(),
                human_rate_limit: $('#human_rate_limit').val(),
                human_rate_action: $('#human_rate_action').val(),
                human_404_limit: $('#human_404_limit').val(),
                human_404_action: $('#human_404_action').val(),
                rate_block_duration: $('#rate_block_duration').val(),
                throttle_behavior: $('#throttle_behavior').val(),
                throttle_delay_duration: $('#throttle_delay_duration').val(),
                allowlisted_404_urls: $('#allowlisted_404_urls').val(),
                
                // === ADVANCED FIREWALL OPTIONS ===
                delay_ip_blocking: $('#delay_ip_blocking').is(':checked'),
                whitelisted_ips_bypass: $('#whitelisted_ips_bypass').val(),
                whitelisted_services: self.collectWhitelistedServices(),
                blocked_urls: $('#blocked_urls').val(),
                ignored_ips_waf: $('#ignored_ips_waf').val(),
                
                // === WAF CATEGORY TOGGLES ===
                category_toggles: window.categoryChanges || {}
            };
            
            // Send unified AJAX request
            $.post(ajaxurl, allFormData, function(response) {
                $saveButton.prop('disabled', false).text(originalText);
                
                if (response.success) {
                    // console.log('[VMPFence] Save successful. Total saved:', response.data.total_saved, 'Failed:', response.data.total_failed);
                    if (response.data.failed_settings && response.data.failed_settings.length > 0) {
                        console.error('[VMPFence] Failed to save settings:', response.data.failed_settings);
                    }
                    
                    // Check if async IP blocklist sync was scheduled
                    if (response.data.async_sync_scheduled) {
                        VMPFenceNotifications.showInfo(
                            'Real-Time IP Blocklist enabled. Syncing blocked IPs in background...',
                            5000,
                            'Background Sync'
                        );
                    }
                    
                    // Check if category toggles were saved - if so, reload page to show updated counts
                    var hasCategoryChanges = window.categoryChanges && Object.keys(window.categoryChanges).length > 0;
                    
                    if (hasCategoryChanges) {
                        VMPFenceNotifications.showSuccess('Firewall options saved successfully. Reloading to show updated rules...', 3000);
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    } else {
                        // Update initial state after successful save
                        self.captureInitialFirewallState();
                        VMPFenceNotifications.showSuccess(response.data.message || 'All firewall options saved successfully', 3000);
                    }
                } else {
                    VMPFenceNotifications.showError(response.data || 'Failed to save firewall options', 5000);
                }
            }).fail(function(xhr, status, error) {
                $saveButton.prop('disabled', false).text(originalText);
                VMPFenceNotifications.showError('Network error occurred while saving firewall options: ' + error, 6000);
            });
        },

        /**
         * Load ALL firewall settings using unified load method
         * Loads: Basic Firewall, Advanced, Brute Force, Rate Limiting, Allowlisted URLs
         */
        loadAllSettings: function() {
            // Load settings from server
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_load_firewall_options',
                    nonce: $('#vmpfence_firewall_options_nonce').val()
                },
                success: function(response) {
                    if (response.success && response.data.settings) {
                        var settings = response.data.settings;
                        
                        // === POPULATE WAF STATUS ===
                        if ($('#waf_enabled').length) {
                            var wafValue = settings.waf_enabled ? '1' : '0';
                            $('#waf_enabled').val(wafValue);
                        }
                        
                        if ($('#auto_update_rules').length) {
                            $('#auto_update_rules').prop('checked', !!settings.auto_update_rules);
                        } else {
                        }
                        if ($('#block_suspicious_requests').length) {
                            $('#block_suspicious_requests').prop('checked', !!settings.block_suspicious_requests);
                        }
                        
                        // Real-Time IP Blocklist
                        if ($('#realtime_ip_blocklist_enabled').length) {
                            var realtimeValue = settings.realtime_ip_blocklist_enabled ? '1' : '0';
                            $('#realtime_ip_blocklist_enabled').val(realtimeValue);
                            
                            // Update button group visual state
                            var $btnGroup = $('#realtime_ip_blocklist_enabled').closest('.vmpfence-btn-group');
                            $btnGroup.find('.vmpfence-toggle-btn').removeClass('vmpfence-toggle-btn-active');
                            if (realtimeValue === '1') {
                                $btnGroup.find('[data-value="on"]').addClass('vmpfence-toggle-btn-active');
                            } else {
                                $btnGroup.find('[data-value="off"]').addClass('vmpfence-toggle-btn-active');
                            }
                        }
                        
                        // === POPULATE BRUTE FORCE ===
                        if ($('#brute_force_enabled').length) {
                            $('#brute_force_enabled').val(settings.brute_force_enabled ? '1' : '0');
                        }
                        
                        // Boolean checkboxes
                        const bruteForceCheckboxes = [
                            'lock_invalid_usernames', 'prevent_leaked_passwords_enabled', 'enforce_strong_passwords',
                            'dont_reveal_users', 'prevent_admin_username', 'prevent_username_discovery', 
                            'disable_app_passwords', 'block_post_requests', 'check_password_strength', 'participate_security_network'
                        ];
                        bruteForceCheckboxes.forEach(function(fieldName) {
                            if ($('#' + fieldName).length) {
                                $('#' + fieldName).prop('checked', !!settings[fieldName]);
                            }
                        });
                        
                        // Integer fields
                        if ($('#max_login_failures').length) {
                            $('#max_login_failures').val(settings.max_login_attempts);
                        }
                        if ($('#max_forgot_password').length) {
                            $('#max_forgot_password').val(settings.max_forgot_password_attempts);
                        }
                        if ($('#count_failures_window').length) {
                            $('#count_failures_window').val(settings.count_failures_window);
                        }
                        if ($('#lockout_duration').length) {
                            $('#lockout_duration').val(settings.lockout_duration);
                        }
                        if ($('#permanent_ban_threshold').length) {
                            $('#permanent_ban_threshold').val(settings.permanent_ban_threshold);
                        }
                        
                        // String fields
                        if ($('#prevent_leaked_passwords_scope').length) {
                            $('#prevent_leaked_passwords_scope').val(settings.prevent_leaked_passwords_scope);
                        }
                        if ($('#strong_passwords_scope').length) {
                            $('#strong_passwords_scope').val(settings.strong_passwords_scope);
                        }
                        if ($('#custom_block_text').length) {
                            $('#custom_block_text').val(settings.custom_block_text || '');
                        }
                        if ($('#blocked_usernames').length) {
                            var blockedUsernamesText = Array.isArray(settings.blocked_usernames) ? settings.blocked_usernames.join('\n') : '';
                            $('#blocked_usernames').val(blockedUsernamesText);
                        } else {
                        }
                        
                        // === POPULATE RATE LIMITING ===
                        if ($('#rate_limiting_enabled').length) {
                            $('#rate_limiting_enabled').val(settings.rate_limiting_enabled ? '1' : '0');
                        } else {
                        }
                        
                        // Rate limiting dropdowns
                        const rateLimitingFields = [
                            'google_crawler_treatment', 'global_rate_limit', 'global_rate_action',
                            'crawler_rate_limit', 'crawler_rate_action', 'crawler_404_limit', 'crawler_404_action',
                            'human_rate_limit', 'human_rate_action', 'human_404_limit', 'human_404_action', 'rate_block_duration', 'throttle_behavior', 'throttle_delay_duration'
                        ];
                        rateLimitingFields.forEach(function(fieldName) {
                            if ($('#' + fieldName).length) {
                                var value = settings[fieldName];
                                if (fieldName === 'google_crawler_treatment' && !value) value = 'verified_google';
                                if ((fieldName.includes('rate_limit') || fieldName.includes('rate_action')) && !value) value = fieldName.includes('action') ? 'throttle' : 'unlimited';
                                if (fieldName === 'rate_block_duration' && !value) value = 5;
                                if (fieldName === 'throttle_behavior' && !value) value = 'show_503';
                                if (fieldName === 'throttle_delay_duration' && !value) value = 5;
                                
                                $('#' + fieldName).val(value);
                            } else {
                            }
                        });
                        
                        // After loading values, trigger visibility check for throttle options
                        // This ensures proper show/hide state on page load
                        setTimeout(function() {
                            window.VMPFenceFirewallOptions.checkThrottleOptionsVisibility();
                        }, 200);
                        
                        // Allowlisted 404 URLs textarea
                        if ($('#allowlisted_404_urls').length) {
                            var allowlistedUrls = Array.isArray(settings.allowlisted_404_urls) ? 
                                settings.allowlisted_404_urls.join('\n') : 
                                '/favicon.ico\n/apple-touch-icon*.png\n/*@2x.png\n/browserconfig.xml';
                            $('#allowlisted_404_urls').val(allowlistedUrls);
                        } else {
                        }
                        
                        // === POPULATE ADVANCED FIREWALL OPTIONS ===
                        // Delay IP Blocking checkbox
                        if ($('#delay_ip_blocking').length) {
                            $('#delay_ip_blocking').prop('checked', !!settings.delay_ip_blocking);
                        }
                        
                        // Allowlisted IPs textarea
                        if ($('#whitelisted_ips_bypass').length) {
                            $('#whitelisted_ips_bypass').val(commasToNewlines(settings.whitelisted_ips_bypass));
                        }
                        
                        // Allowlisted Services checkboxes
                        if (settings.whitelisted_services) {
                            var services = {};
                            if (typeof settings.whitelisted_services === 'string') {
                                try {
                                    services = JSON.parse(settings.whitelisted_services);
                                } catch (e) {
                                    services = {};
                                }
                            } else if (typeof settings.whitelisted_services === 'object') {
                                services = settings.whitelisted_services;
                            }
                            
                            // Update each service checkbox
                            $('#service_sucuri').prop('checked', !!services.sucuri);
                            $('#service_facebook').prop('checked', !!services.facebook);
                            $('#service_uptime').prop('checked', !!services.uptime);
                            $('#service_statuscake').prop('checked', !!services.statuscake);
                            $('#service_managewp').prop('checked', !!services.managewp);
                            $('#service_seznam').prop('checked', !!services.seznam);
                            $('#service_google').prop('checked', !!services.google);
                        }
                        
                        // Blocked URLs textarea
                        if ($('#blocked_urls').length) {
                            $('#blocked_urls').val(commasToNewlines(settings.blocked_urls));
                        }
                        
                        // Ignored IPs for WAF Alerting textarea
                        if ($('#ignored_ips_waf').length) {
                            $('#ignored_ips_waf').val(commasToNewlines(settings.ignored_ips_waf));
                        }
                        
                        // Update button group states for toggles
                        $('.vmpfence-btn-group .vmpfence-toggle-btn').each(function() {
                            var $button = $(this);
                            var value = $button.data('value');
                            var $hiddenInput = $button.closest('.vmpfence-option-right').find('input[type="hidden"]');
                            
                            if ($hiddenInput.length) {
                                var inputId = $hiddenInput.attr('id');
                                var settingValue = settings[inputId];
                                var isActive = (value === 'on' && settingValue) || (value === 'off' && !settingValue);
                                
                                if (isActive) {
                                    $button.addClass('vmpfence-toggle-btn-active');
                                } else {
                                    $button.removeClass('vmpfence-toggle-btn-active');
                                }
                                
                                // Update the hidden input value
                                $hiddenInput.val(settingValue ? '1' : '0');
                            }
                        });
                        
                        
                    } else {
                    }
                },
                error: function(xhr, status, error) {
                }
            });
        },

        /**
         * Handle button group toggle switches (ON/OFF buttons)
         */
        handleButtonGroupToggle: function(e) {
            e.preventDefault();
            var $btn = $(this);
            var $group = $btn.closest('.vmpfence-btn-group');
            var value = $btn.data('value');
            
            // Remove active class from all buttons in group
            $group.find('.vmpfence-toggle-btn').removeClass('vmpfence-toggle-btn-active');
            
            // Add active class to clicked button
            $btn.addClass('vmpfence-toggle-btn-active');
            
            // Update hidden input if it exists (check both inside btn-group and in parent .vmpfence-option-right)
            var $hiddenInput = $group.find('input[type="hidden"]');
            if (!$hiddenInput.length) {
                $hiddenInput = $group.closest('.vmpfence-option-right').find('input[type="hidden"]');
            }
            if ($hiddenInput.length) {
                $hiddenInput.val(value === 'on' ? '1' : '0');
            }
        },

        /**
         * Handle checkbox toggle switches
         */
        handleCheckboxToggle: function(e) {
            e.preventDefault();
            var $toggle = $(this);
            var $input = $toggle.find('input[type="checkbox"]');
            
            // Toggle the checkbox state
            $input.prop('checked', !$input.prop('checked'));
            
            // Update toggle appearance
            if ($input.prop('checked')) {
                $toggle.addClass('active');
            } else {
                $toggle.removeClass('active');
            }
            
            // Trigger change event
            $input.trigger('change');
        },

        /**
         * Restore defaults for all firewall settings
         */
        restoreDefaults: function(e) {
            if (e) {
                e.preventDefault();
            }
            
            var self = this;
            
            VMPFenceNotifications.showConfirmModal({
                title: 'Restore Defaults',
                message: 'Are you sure you want to restore default firewall settings? This will overwrite ALL your current firewall configuration.',
                confirmText: 'Yes, Restore',
                cancelText: 'Cancel',
                type: 'danger'
            }).then(function(confirmed) {
                if (!confirmed) return;
                
                var $restoreButton = $('.vmpfence-btn-restore');
                var originalText = $restoreButton.text();
                
                // Show loading state
                $restoreButton.prop('disabled', true).text('⟳ Restoring...');
                
                // Show loading notification
                var loadingToast = VMPFenceNotifications.showInfo('Loading default firewall settings...', 0, 'Please Wait');
                
                // Call backend to get default values
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'vmpfence_restore_firewall_defaults',
                        nonce: $('#vmpfence_firewall_options_nonce').val()
                    },
                    success: function(response) {
                        VMPFenceNotifications.removeToast(loadingToast);
                        
                        if (response.success && response.data.defaults) {
                            var defaults = response.data.defaults;
                            
                            // Populate all form fields with default values
                            self.populateFormWithDefaults(defaults);
                            
                            // Show saving notification
                            var savingToast = VMPFenceNotifications.showInfo('Saving default settings...', 0, 'Please Wait');
                            
                            // Save the defaults to database
                            self.performSave(function(saveSuccess) {
                                VMPFenceNotifications.removeToast(savingToast);
                                
                                if (saveSuccess) {
                                    VMPFenceNotifications.showSuccess(
                                        'Default firewall settings restored! Page will reload in 2 seconds...',
                                        2000,
                                        'Defaults Restored'
                                    );
                                    
                                    // Reload page after 2 seconds to show updated WAF rules and cleared allowlist
                                    setTimeout(function() {
                                        window.location.reload();
                                    }, 2000);
                                } else {
                                    VMPFenceNotifications.showWarning(
                                        'Defaults loaded but save may have failed. Please verify your settings.',
                                        5000,
                                        'Partial Success'
                                    );
                                    $restoreButton.prop('disabled', false).text(originalText);
                                }
                            });
                        } else {
                            VMPFenceNotifications.showError(
                                response.data || 'Failed to load default settings',
                                5000,
                                'Restore Failed'
                            );
                            $restoreButton.prop('disabled', false).text(originalText);
                        }
                    },
                    error: function(xhr, status, error) {
                        VMPFenceNotifications.removeToast(loadingToast);
                        VMPFenceNotifications.showError(
                            'Network error: ' + (error || 'Connection failed'),
                            6000,
                            'Request Failed'
                        );
                        $restoreButton.prop('disabled', false).text(originalText);
                    }
                });
            }.bind(this));
        },
        
        /**
         * Populate form fields with default values
         */
        populateFormWithDefaults: function(defaults) {
            // WAF toggles
            if (typeof defaults.waf_enabled !== 'undefined') {
                $('#waf_enabled').val(defaults.waf_enabled ? '1' : '0');
                var $wafBtnGroup = $('#waf_enabled').closest('.vmpfence-btn-group');
                $wafBtnGroup.find('.vmpfence-toggle-btn').removeClass('vmpfence-toggle-btn-active');
                if (defaults.waf_enabled) {
                    $wafBtnGroup.find('[data-value="on"]').addClass('vmpfence-toggle-btn-active');
                } else {
                    $wafBtnGroup.find('[data-value="off"]').addClass('vmpfence-toggle-btn-active');
                }
            }
            
            // WAF checkboxes
            if (typeof defaults.auto_update_rules !== 'undefined' && $('#auto_update_rules').length) {
                $('#auto_update_rules').prop('checked', !!defaults.auto_update_rules);
            }
            if (typeof defaults.block_suspicious_requests !== 'undefined' && $('#block_suspicious_requests').length) {
                $('#block_suspicious_requests').prop('checked', !!defaults.block_suspicious_requests);
            }
            
            // Real-time IP blocklist
            if (typeof defaults.realtime_ip_blocklist_enabled !== 'undefined') {
                $('#realtime_ip_blocklist_enabled').val(defaults.realtime_ip_blocklist_enabled ? '1' : '0');
                var $realtimeBtnGroup = $('#realtime_ip_blocklist_enabled').closest('.vmpfence-btn-group');
                $realtimeBtnGroup.find('.vmpfence-toggle-btn').removeClass('vmpfence-toggle-btn-active');
                if (defaults.realtime_ip_blocklist_enabled) {
                    $realtimeBtnGroup.find('[data-value="on"]').addClass('vmpfence-toggle-btn-active');
                } else {
                    $realtimeBtnGroup.find('[data-value="off"]').addClass('vmpfence-toggle-btn-active');
                }
            }
            
            // Brute force enabled
            if (typeof defaults.brute_force_enabled !== 'undefined') {
                $('#brute_force_enabled').val(defaults.brute_force_enabled ? '1' : '0');
                var $bruteForceBtnGroup = $('#brute_force_enabled').closest('.vmpfence-btn-group');
                $bruteForceBtnGroup.find('.vmpfence-toggle-btn').removeClass('vmpfence-toggle-btn-active');
                if (defaults.brute_force_enabled) {
                    $bruteForceBtnGroup.find('[data-value="on"]').addClass('vmpfence-toggle-btn-active');
                } else {
                    $bruteForceBtnGroup.find('[data-value="off"]').addClass('vmpfence-toggle-btn-active');
                }
            }
            
            // Brute force checkboxes
            var bruteForceCheckboxes = [
                'lock_invalid_usernames', 'prevent_leaked_passwords_enabled', 'enforce_strong_passwords',
                'dont_reveal_users', 'prevent_admin_username', 'prevent_username_discovery',
                'disable_app_passwords', 'block_post_requests', 'check_password_strength', 'participate_security_network'
            ];
            bruteForceCheckboxes.forEach(function(field) {
                if (typeof defaults[field] !== 'undefined') {
                    $('#' + field).prop('checked', !!defaults[field]);
                }
            });
            
            // Brute force numeric fields
            if (defaults.max_login_attempts) $('#max_login_failures').val(defaults.max_login_attempts);
            if (defaults.max_forgot_password_attempts) $('#max_forgot_password').val(defaults.max_forgot_password_attempts);
            if (defaults.count_failures_window) $('#count_failures_window').val(defaults.count_failures_window);
            if (defaults.lockout_duration) $('#lockout_duration').val(defaults.lockout_duration);
            if (defaults.permanent_ban_threshold) $('#permanent_ban_threshold').val(defaults.permanent_ban_threshold);
            
            // Brute force string fields
            if (defaults.prevent_leaked_passwords_scope) $('#prevent_leaked_passwords_scope').val(defaults.prevent_leaked_passwords_scope);
            if (defaults.strong_passwords_scope) $('#strong_passwords_scope').val(defaults.strong_passwords_scope);
            $('#custom_block_text').val(defaults.custom_block_text || '');
            
            // Blocked usernames
            var blockedUsernamesText = Array.isArray(defaults.blocked_usernames) ? defaults.blocked_usernames.join('\n') : '';
            $('#blocked_usernames').val(blockedUsernamesText);
            
            // Rate limiting enabled
            if (typeof defaults.rate_limiting_enabled !== 'undefined') {
                $('#rate_limiting_enabled').val(defaults.rate_limiting_enabled ? '1' : '0');
                var $rateLimitingBtnGroup = $('#rate_limiting_enabled').closest('.vmpfence-btn-group');
                $rateLimitingBtnGroup.find('.vmpfence-toggle-btn').removeClass('vmpfence-toggle-btn-active');
                if (defaults.rate_limiting_enabled) {
                    $rateLimitingBtnGroup.find('[data-value="on"]').addClass('vmpfence-toggle-btn-active');
                } else {
                    $rateLimitingBtnGroup.find('[data-value="off"]').addClass('vmpfence-toggle-btn-active');
                }
            }
            
            // Rate limiting dropdowns
            if (defaults.google_crawler_treatment) $('#google_crawler_treatment').val(defaults.google_crawler_treatment);
            if (defaults.global_rate_limit) $('#global_rate_limit').val(defaults.global_rate_limit);
            if (defaults.global_rate_action) $('#global_rate_action').val(defaults.global_rate_action);
            if (defaults.crawler_rate_limit) $('#crawler_rate_limit').val(defaults.crawler_rate_limit);
            if (defaults.crawler_rate_action) $('#crawler_rate_action').val(defaults.crawler_rate_action);
            if (defaults.crawler_404_limit) $('#crawler_404_limit').val(defaults.crawler_404_limit);
            if (defaults.crawler_404_action) $('#crawler_404_action').val(defaults.crawler_404_action);
            if (defaults.human_rate_limit) $('#human_rate_limit').val(defaults.human_rate_limit);
            if (defaults.human_rate_action) $('#human_rate_action').val(defaults.human_rate_action);
            if (defaults.human_404_limit) $('#human_404_limit').val(defaults.human_404_limit);
            if (defaults.human_404_action) $('#human_404_action').val(defaults.human_404_action);
            if (defaults.rate_block_duration) $('#rate_block_duration').val(defaults.rate_block_duration);
            if (defaults.throttle_behavior) $('#throttle_behavior').val(defaults.throttle_behavior);
            if (defaults.throttle_delay_duration) $('#throttle_delay_duration').val(defaults.throttle_delay_duration);
            
            // Allowlisted 404 URLs
            var allowlisted404Text = Array.isArray(defaults.allowlisted_404_urls) ? defaults.allowlisted_404_urls.join('\n') : '';
            $('#allowlisted_404_urls').val(allowlisted404Text);
            
            // Advanced firewall options
            if (typeof defaults.delay_ip_blocking !== 'undefined') {
                $('#delay_ip_blocking').prop('checked', !!defaults.delay_ip_blocking);
            }
            $('#whitelisted_ips_bypass').val(commasToNewlines(defaults.whitelisted_ips_bypass));
            $('#blocked_urls').val(commasToNewlines(defaults.blocked_urls));
            $('#ignored_ips_waf').val(commasToNewlines(defaults.ignored_ips_waf));
            
            // Whitelisted services
            if (defaults.whitelisted_services) {
                var services = {};
                try {
                    services = JSON.parse(defaults.whitelisted_services);
                } catch (e) {
                    services = {};
                }
                $('#service_sucuri').prop('checked', !!services.sucuri);
                $('#service_facebook').prop('checked', !!services.facebook);
                $('#service_uptime').prop('checked', !!services.uptime);
                $('#service_statuscake').prop('checked', !!services.statuscake);
                $('#service_managewp').prop('checked', !!services.managewp);
                $('#service_seznam').prop('checked', !!services.seznam);
                $('#service_google').prop('checked', !!services.google);
            }
        },
        
        /**
         * Perform save operation (extracted for reuse)
         */
        performSave: function(callback) {
            var self = this;
            
            // Validate IP address fields before saving
            var whitelistedIPs = $('#whitelisted_ips_bypass').val();
            var ignoredIPs = $('#ignored_ips_waf').val();
            
            var whitelistValidation = self.validateIPAddresses(whitelistedIPs);
            var ignoredValidation = self.validateIPAddresses(ignoredIPs);
            
            if (!whitelistValidation.valid) {
                if (callback) callback(false);
                return;
            }
            
            if (!ignoredValidation.valid) {
                if (callback) callback(false);
                return;
            }
            
            // Collect ALL firewall form data (same as saveAllSettings)
            var allFormData = {
                action: 'vmpfence_save_firewall_options',
                nonce: $('#vmpfence_firewall_options_nonce').val(),
                
                // === BASIC FIREWALL OPTIONS ===
                waf_enabled: $('#waf_enabled').val(),
                auto_update_rules: $('#auto_update_rules').length ? $('#auto_update_rules').is(':checked') : true,
                block_suspicious_requests: $('#block_suspicious_requests').length ? $('#block_suspicious_requests').is(':checked') : true,
                realtime_ip_blocklist_enabled: $('#realtime_ip_blocklist_enabled').val() == '1',
                
                // === BRUTE FORCE OPTIONS ===
                brute_force_enabled: $('#brute_force_enabled').val() == '1',
                lock_invalid_usernames: $('#lock_invalid_usernames').is(':checked'),
                prevent_leaked_passwords_enabled: $('#prevent_leaked_passwords_enabled').is(':checked'),
                enforce_strong_passwords: $('#enforce_strong_passwords').is(':checked'),
                dont_reveal_users: $('#dont_reveal_users').is(':checked'),
                prevent_admin_username: $('#prevent_admin_username').is(':checked'),
                prevent_username_discovery: $('#prevent_username_discovery').is(':checked'),
                disable_app_passwords: $('#disable_app_passwords').is(':checked'),
                block_post_requests: $('#block_post_requests').is(':checked'),
                check_password_strength: $('#check_password_strength').is(':checked'),
                participate_security_network: $('#participate_security_network').is(':checked'),
                max_login_attempts: $('#max_login_failures').val(),
                max_forgot_password_attempts: $('#max_forgot_password').val(),
                count_failures_window: $('#count_failures_window').val(),
                lockout_duration: $('#lockout_duration').val(),
                permanent_ban_threshold: $('#permanent_ban_threshold').val() || 10,
                prevent_leaked_passwords_scope: $('#prevent_leaked_passwords_scope').val(),
                strong_passwords_scope: $('#strong_passwords_scope').val(),
                custom_block_text: $('#custom_block_text').val(),
                blocked_usernames: $('#blocked_usernames').val(),
                
                // === RATE LIMITING OPTIONS ===
                rate_limiting_enabled: $('#rate_limiting_enabled').val() == '1',
                google_crawler_treatment: $('#google_crawler_treatment').val(),
                global_rate_limit: $('#global_rate_limit').val(),
                global_rate_action: $('#global_rate_action').val(),
                crawler_rate_limit: $('#crawler_rate_limit').val(),
                crawler_rate_action: $('#crawler_rate_action').val(),
                crawler_404_limit: $('#crawler_404_limit').val(),
                crawler_404_action: $('#crawler_404_action').val(),
                human_rate_limit: $('#human_rate_limit').val(),
                human_rate_action: $('#human_rate_action').val(),
                human_404_limit: $('#human_404_limit').val(),
                human_404_action: $('#human_404_action').val(),
                rate_block_duration: $('#rate_block_duration').val(),
                throttle_behavior: $('#throttle_behavior').val(),
                throttle_delay_duration: $('#throttle_delay_duration').val(),
                allowlisted_404_urls: $('#allowlisted_404_urls').val(),
                
                // === ADVANCED FIREWALL OPTIONS ===
                delay_ip_blocking: $('#delay_ip_blocking').is(':checked'),
                whitelisted_ips_bypass: $('#whitelisted_ips_bypass').val(),
                whitelisted_services: self.collectWhitelistedServices(),
                blocked_urls: $('#blocked_urls').val(),
                ignored_ips_waf: $('#ignored_ips_waf').val(),
                
                // === WAF CATEGORY TOGGLES ===
                category_toggles: window.categoryChanges || {}
            };
            
            $.post(ajaxurl, allFormData, function(response) {
                if (callback) callback(response.success);
            }).fail(function() {
                if (callback) callback(false);
            });
        },

        /**
         * Cancel all changes and reload from database
         */
        cancelChanges: function(e) {
            if (e) {
                e.preventDefault();
            }
            
            this.loadAllSettings(); // Reload all settings from database
            VMPFenceNotifications.showInfo('Changes cancelled - reloaded from database', 3000);
        },

        /**
         * Capture initial state for cancel functionality
         */
        captureInitialFirewallState: function() {
            // Implementation would capture all form states
        },

        /**
         * Initialize throttle behavior visibility based on action selections
         */
        initThrottleBehaviorVisibility: function() {
            var self = this;
            
            // Add change event listeners to all rate limit action dropdowns
            $('#global_rate_action, #crawler_rate_action, #crawler_404_action, #human_rate_action, #human_404_action').on('change', function() {
                self.checkThrottleOptionsVisibility();
            });
            
            // Add change event listener to throttle behavior dropdown
            $('#throttle_behavior').on('change', function() {
                self.checkThrottleDelayVisibility();
            });
        },

        /**
         * Check and update visibility of throttle options
         * Separated into a callable method for reuse
         */
        checkThrottleOptionsVisibility: function() {
            var hasThrottle = false;
            
            // Check all 5 rate limit action dropdowns
            var actionSelectors = [
                '#global_rate_action',
                '#crawler_rate_action',
                '#crawler_404_action',
                '#human_rate_action',
                '#human_404_action'
            ];
            
            actionSelectors.forEach(function(selector) {
                if ($(selector).val() === 'throttle') {
                    hasThrottle = true;
                }
            });
            
            // Show/hide throttle behavior option
            if (hasThrottle) {
                $('#throttle_behavior_option').show();
                // Check if slow_down is selected to show delay duration
                this.checkThrottleDelayVisibility();
            } else {
                $('#throttle_behavior_option').hide();
                $('#throttle_delay_option').hide();
            }
        },

        /**
         * Check and update visibility of throttle delay duration option
         */
        checkThrottleDelayVisibility: function() {
            var throttleBehavior = $('#throttle_behavior').val();
            
            if (throttleBehavior === 'slow_down') {
                $('#throttle_delay_option').show();
            } else {
                $('#throttle_delay_option').hide();
            }
        },

        /**
         * Initialize param type select with Select2
         * Shows "Param Type: " prefix in closed state, but not in dropdown options
         */
        initParamTypeSelect: function() {
            var $select = $('#allowlist_param_type');
            
            if (!$select.length) {
                return;
            }
            
            // Check if Select2 is available
            if (typeof $.fn.select2 === 'undefined') {
                console.warn('Select2 library not loaded');
                return;
            }
            
            // Initialize Select2 with custom template
            $select.select2({
                templateSelection: function(data) {
                    // Show "Param Type: " prefix in closed/selected state
                    if (data.id) {
                        return 'Param Type: ' + data.text;
                    }
                    return data.text;
                },
                minimumResultsForSearch: -1, // Hide search box
                width: '180px'
            });
        },

        /**
         * Collect whitelisted services into JSON object
         */
        collectWhitelistedServices: function() {
            var services = {
                sucuri: $('#service_sucuri').is(':checked'),
                facebook: $('#service_facebook').is(':checked'),
                uptime: $('#service_uptime').is(':checked'),
                statuscake: $('#service_statuscake').is(':checked'),
                managewp: $('#service_managewp').is(':checked'),
                seznam: $('#service_seznam').is(':checked'),
                google: $('#service_google').is(':checked')
            };
            return JSON.stringify(services);
        },

        /**
         * Validate IP address formats
         * Supports: single IP, CIDR, bracket ranges, dash ranges
         */
        validateIPAddresses: function(input) {
            if (!input || input.trim() === '') {
                return { valid: true, errors: [] };
            }

            var errors = [];
            var lines = input.split(/[\r\n,]+/);
            
            lines.forEach(function(line, index) {
                line = line.trim();
                if (line === '') return;
                
                var lineNum = index + 1;
                var isValid = false;
                
                // Check single IPv4 (e.g., 192.168.1.1)
                if (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(line)) {
                    var parts = line.split('.');
                    isValid = parts.every(function(part) {
                        var num = parseInt(part);
                        return num >= 0 && num <= 255;
                    });
                }
                // Check single IPv6 (e.g., 2001:db8::1 or fe80::1 or ::1)
                // Simplified IPv6 validation that handles compressed notation
                else if (/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/.test(line)) {
                    isValid = true;
                }
                // Check IPv4 CIDR notation (e.g., 192.168.1.0/24)
                else if (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2}$/.test(line)) {
                    var ipPart = line.split('/')[0];
                    var cidrPart = parseInt(line.split('/')[1]);
                    var parts = ipPart.split('.');
                    var ipValid = parts.every(function(part) {
                        var num = parseInt(part);
                        return num >= 0 && num <= 255;
                    });
                    isValid = ipValid && cidrPart >= 0 && cidrPart <= 32;
                }
                // Check IPv6 CIDR notation (e.g., 2001:db8::/32 or fe80::/10)
                // Use same comprehensive regex as single IPv6 but with CIDR suffix
                else if (/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/\d{1,3}$/.test(line)) {
                    var cidrPart = parseInt(line.split('/')[1]);
                    isValid = cidrPart >= 0 && cidrPart <= 128;
                }
                // Check IPv4 bracket range (e.g., 192.168.1.[1-100])
                else if (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\[\d{1,3}-\d{1,3}\]$/.test(line)) {
                    var match = line.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.\[(\d{1,3})-(\d{1,3})\]$/);
                    if (match) {
                        var parts = [match[1], match[2], match[3]];
                        var start = parseInt(match[4]);
                        var end = parseInt(match[5]);
                        var partsValid = parts.every(function(part) {
                            var num = parseInt(part);
                            return num >= 0 && num <= 255;
                        });
                        isValid = partsValid && start >= 0 && start <= 255 && end >= 0 && end <= 255 && start <= end;
                    }
                }
                // Check IPv4 dash range (e.g., 192.168.1.1-192.168.1.100)
                else if (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}-\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(line)) {
                    var ips = line.split('-');
                    isValid = ips.every(function(ip) {
                        var parts = ip.split('.');
                        return parts.every(function(part) {
                            var num = parseInt(part);
                            return num >= 0 && num <= 255;
                        });
                    });
                }
                
                if (!isValid) {
                    errors.push('Line ' + lineNum + ': Invalid IP format "' + line + '"');
                }
            });
            
            return {
                valid: errors.length === 0,
                errors: errors
            };
        },

        /**
         * Show admin notice
         */
        showNotice: function(type, message) {
            // Create notice element
            var $notice = $('<div class="vmpfence-notice vmpfence-notice-' + type + '">' + message + '</div>');
            
            // Remove existing notices
            $('.vmpfence-notice').remove();
            
            // Add new notice
            $('.vmpfence-options-header').after($notice);
            
            // Auto remove after 5 seconds
            setTimeout(function() {
                $notice.fadeOut();
            }, 5000);
        },

        /**
         * Show inline field error
         */
        showFieldError: function($field, errors) {
            // Remove existing error for this field
            $field.removeClass('vmpfence-field-error');
            $field.next('.vmpfence-field-error-message').remove();
            
            if (errors.length === 0) return;
            
            // Add error styling to field
            $field.addClass('vmpfence-field-error');
            
            // Create error message
            var errorHtml = '<div class="vmpfence-field-error-message" style="' +
                'background: #dc3232; ' +
                'color: white; ' +
                'padding: 8px 12px; ' +
                'margin-top: 8px; ' +
                'border-radius: 3px; ' +
                'font-size: 13px; ' +
                'line-height: 1.5;">' +
                '<strong>Validation Error:</strong><br>' +
                errors.join('<br>') +
                '</div>';
            
            // Insert error message after field
            $field.after(errorHtml);
            
            // Scroll to error
            $('html, body').animate({
                scrollTop: $field.offset().top - 100
            }, 500);
        },

        /**
         * Clear field error
         */
        clearFieldError: function($field) {
            $field.removeClass('vmpfence-field-error');
            $field.next('.vmpfence-field-error-message').remove();
        },

        /**
         * Show allowlist notice
         */
        showAllowlistNotice: function(type, message) {
            // Create notice element
            var bgColor = (type === 'success') ? '#46b450' : '#db5454';
            var $notice = $('<div class="vmpfence-notice vmpfence-notice-' + type + '" style="background-color: ' + bgColor + '; padding: 10px; border-radius: 3px; margin-top: 10px; width: 180px; color: white !important;">' + message + '</div>');
            
            // Remove only notices inside allowlist area
            $('.vmpfence-allowlist-row').next('.vmpfence-notice').remove();
            
            // Insert under the allowlist inputs
            $('.vmpfence-allowlist-row').after($notice);
            
            // Auto remove after 5 seconds
            setTimeout(function() {
                $notice.fadeOut();
            }, 5000);
        },

        /**
         * Show duplicate entry modal popup
         */
        showDuplicateModal: function(message) {
            // Remove existing modal if any
            $('#vmpfence-duplicate-modal').remove();
            
            // Create modal HTML
            var modalHtml = '<div id="vmpfence-duplicate-modal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 999999; display: flex; align-items: center; justify-content: center;">' +
                '<div style="background: white; padding: 30px; border-radius: 5px; max-width: 500px; box-shadow: 0 4px 20px rgba(0,0,0,0.3);">' +
                '<h2 style="margin: 0 0 15px 0; font-size: 18px; font-weight: 600; color: #333;">Allowlist Entry Exists</h2>' +
                '<p style="margin: 0 0 20px 0; font-size: 14px; color: #555; line-height: 1.5;">' + message + '</p>' +
                '<button type="button" class="button button-primary" style="background: #0085ba; border-color: #0073aa; padding: 8px 20px; font-size: 14px; cursor: pointer;">CLOSE</button>' +
                '</div>' +
                '</div>';
            
            // Append to body
            $('body').append(modalHtml);
            
            // Close on button click
            $('#vmpfence-duplicate-modal button').on('click', function() {
                $('#vmpfence-duplicate-modal').fadeOut(200, function() {
                    $(this).remove();
                });
            });
            
            // Close on background click
            $('#vmpfence-duplicate-modal').on('click', function(e) {
                if (e.target.id === 'vmpfence-duplicate-modal') {
                    $(this).fadeOut(200, function() {
                        $(this).remove();
                    });
                }
            });
        },

        /**
         * Load allowlist table data via AJAX
         */
        loadAllowlistTable: function() {
            var self = this;
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_allowlist_data',
                    nonce: $('#vmpfence_allowlist_nonce').val()
                },
                success: function(response) {
                    if (response.success) {
                        self.populateAllowlistTable(response.data.data);
                    }
                },
                error: function() {
                    console.error('Failed to load allowlist data');
                }
            });
        },

        /**
         * Format parameter name for display based on type
         */
        formatParamDisplay: function(paramName, paramType) {
            var prefix = '';
            switch(paramType) {
                case 'POST Body':
                    prefix = 'request.body';
                    break;
                case 'Query String':
                    prefix = 'request.queryString';
                    break;
                case 'Cookie':
                    prefix = 'request.cookie';
                    break;
                case 'File Name':
                    prefix = 'request.fileNames';
                    break;
                case 'Header':
                    prefix = 'request.headers';
                    break;
                default:
                    prefix = 'request.body';
            }
            return prefix + '[' + paramName + ']';
        },

        /**
         * Populate allowlist table with data
         */
        populateAllowlistTable: function(data) {
            var self = this;
            var $tbody = $('.vmpfence-allowlist-table tbody');
            $tbody.empty();
            
            if (!data || data.length === 0) {
                $tbody.append('<tr><td colspan="8" style="text-align: center; padding: 20px; color: #666;">No allowlisted parameters yet.</td></tr>');
                return;
            }
            
            $.each(data, function(index, entry) {
                var timestamp = new Date(entry.metadata.timestamp * 1000);
                var formattedDate = timestamp.toLocaleString();
                var disabled = entry.metadata.disabled ? '' : 'checked';
                var paramType = entry.metadata.param_type || 'POST Body';
                var displayParam = self.formatParamDisplay(entry.param_key, paramType);
                
                var row = '<tr data-path="' + entry.path + '" data-param="' + entry.param_key + '" data-rule="' + entry.rule_id + '">' +
                    '<td><input type="checkbox" class="vmpfence-row-select"></td>' +
                    '<td><input type="checkbox" ' + disabled + ' class="vmpfence-enabled-toggle"></td>' +
                    '<td>' + entry.path + '</td>' +
                    '<td>' + displayParam + '</td>' +
                    '<td>' + formattedDate + '</td>' +
                    '<td>' + entry.metadata.source + '</td>' +
                    '<td>' + (entry.metadata.user || '-') + '</td>' +
                    '<td>' + (entry.metadata.ip || '-') + '</td>' +
                    '</tr>';
                
                $tbody.append(row);
            });
        },

        /**
         * Add allowlist entry
         */
        addAllowlistEntry: function() {
            const self = this;
            
            var $urlField = $('#allowlist_url');
            var $paramNameField = $('#allowlist_param_name');
            var $paramTypeField = $('#allowlist_param_type');
            
            var path = $urlField.val().trim();
            var paramType = $paramTypeField.val();
            var paramName = $paramNameField.val().trim();
            if (!path || !paramName) {
                self.showAllowlistNotice('error', 'Please fill in all required fields');
                return;
            }
            
            // Store only param name
            // Type is for UI display only, not stored in composite key
            var nonce = $('#vmpfence_allowlist_nonce').val();
            
            var ajaxData = {
                action: 'vmpfence_add_param_allowlist',
                nonce: nonce,
                path: path,
                param_key: paramName,
                param_type: paramType,
                rule_id: 'all' // Default to bypass all rules
            };
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: ajaxData,
                success: function(response) {
                    if (response.success) {
                        self.showAllowlistNotice('success', response.data.message);
                        self.populateAllowlistTable(response.data.data);
                        // Clear form
                        $('#allowlist_url').val('');
                        $('#allowlist_param_name').val('');
                    } else {
                        // Check if it's a duplicate entry error
                        if (response.data && response.data.duplicate) {
                            self.showDuplicateModal(response.data.message);
                        } else {
                            self.showAllowlistNotice('error', response.data.message || 'Failed to add entry');
                        }
                    }
                },
                error: function(xhr, status, error) {
                    self.showAllowlistNotice('error', 'Failed to add allowlist entry: ' + error);
                }
            });
        },

        /**
         * Delete selected allowlist entries
         */
        deleteAllowlistEntry: function() {
            var self = this;
            var $selected = $('.vmpfence-row-select:checked');
            
            if ($selected.length === 0) {
                VMPFenceNotifications.showError('Please select entries to delete', 3000);
                return;
            }
            
            // Collect all entries to delete
            var entries = [];
            $selected.each(function() {
                var $row = $(this).closest('tr');
                entries.push({
                    path: $row.data('path'),
                    param: $row.data('param'),
                    rule: $row.data('rule')
                });
            });
            
            // Process deletions sequentially to avoid race conditions
            var deleteNext = function(index) {
                if (index >= entries.length) {
                    VMPFenceNotifications.showSuccess('Selected entries deleted', 3000);
                    self.loadAllowlistTable();
                    return;
                }
                
                var entry = entries[index];
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'vmpfence_remove_param_allowlist',
                        nonce: $('#vmpfence_allowlist_nonce').val(),
                        path: entry.path,
                        param_key: entry.param,
                        rule_id: entry.rule
                    },
                    success: function(response) {
                        // Continue to next entry
                        deleteNext(index + 1);
                    },
                    error: function(xhr, status, error) {
                        // Continue anyway
                        deleteNext(index + 1);
                    }
                });
            };
            
            // Start sequential deletion
            deleteNext(0);
        },

        /**
         * Toggle allowlist entry enabled/disabled
         */
        toggleAllowlistEntry: function($checkbox) {
            var self = this;
            var $row = $checkbox.closest('tr');
            var path = $row.data('path');
            var param = $row.data('param');
            var rule = $row.data('rule');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_toggle_param_allowlist',
                    nonce: $('#vmpfence_allowlist_nonce').val(),
                    path: path,
                    param_key: param,
                    rule_id: rule
                },
                success: function(response) {
                    if (response.success) {
                        VMPFenceNotifications.showSuccess(response.data.message, 3000);
                    } else {
                        // Revert checkbox state
                        $checkbox.prop('checked', !$checkbox.prop('checked'));
                        VMPFenceNotifications.showError(response.data.message, 4000);
                    }
                },
                error: function() {
                    // Revert checkbox state
                    $checkbox.prop('checked', !$checkbox.prop('checked'));
                    VMPFenceNotifications.showError('Failed to toggle entry', 4000);
                }
            });
        },

        /**
         * Enable selected allowlist entries
         */
        enableAllowlistEntries: function() {
            var self = this;
            var $selected = $('.vmpfence-row-select:checked');
            
            if ($selected.length === 0) {
                VMPFenceNotifications.showError('Please select entries to enable', 3000);
                return;
            }
            
            // Collect all entries to enable
            var entries = [];
            $selected.each(function() {
                var $row = $(this).closest('tr');
                var $enableCheckbox = $row.find('.vmpfence-enabled-toggle');
                
                // Only toggle if currently disabled
                if (!$enableCheckbox.prop('checked')) {
                    entries.push({
                        path: $row.data('path'),
                        param: $row.data('param'),
                        rule: $row.data('rule'),
                        checkbox: $enableCheckbox
                    });
                } else {
                    // Already enabled, just ensure checkbox is checked
                    $enableCheckbox.prop('checked', true);
                }
            });
            
            if (entries.length === 0) {
                VMPFenceNotifications.showInfo('All selected entries are already enabled', 3000);
                return;
            }
            
            // Process sequentially to avoid race conditions
            var enableNext = function(index) {
                if (index >= entries.length) {
                    VMPFenceNotifications.showSuccess('Selected entries enabled', 3000);
                    return;
                }
                
                var entry = entries[index];
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'vmpfence_toggle_param_allowlist',
                        nonce: $('#vmpfence_allowlist_nonce').val(),
                        path: entry.path,
                        param_key: entry.param,
                        rule_id: entry.rule
                    },
                    success: function() {
                        entry.checkbox.prop('checked', true);
                        enableNext(index + 1);
                    },
                    error: function() {
                        // Continue anyway
                        enableNext(index + 1);
                    }
                });
            };
            
            enableNext(0);
        },

        /**
         * Disable selected allowlist entries
         */
        disableAllowlistEntries: function() {
            var self = this;
            var $selected = $('.vmpfence-row-select:checked');
            
            if ($selected.length === 0) {
                VMPFenceNotifications.showError('Please select entries to disable', 3000);
                return;
            }
            
            // Collect all entries to disable
            var entries = [];
            $selected.each(function() {
                var $row = $(this).closest('tr');
                var $enableCheckbox = $row.find('.vmpfence-enabled-toggle');
                
                // Only toggle if currently enabled
                if ($enableCheckbox.prop('checked')) {
                    entries.push({
                        path: $row.data('path'),
                        param: $row.data('param'),
                        rule: $row.data('rule'),
                        checkbox: $enableCheckbox
                    });
                } else {
                    // Already disabled, just ensure checkbox is unchecked
                    $enableCheckbox.prop('checked', false);
                }
            });
            
            if (entries.length === 0) {
                VMPFenceNotifications.showInfo('All selected entries are already disabled', 3000);
                return;
            }
            
            // Process sequentially to avoid race conditions
            var disableNext = function(index) {
                if (index >= entries.length) {
                    VMPFenceNotifications.showSuccess('Selected entries disabled', 3000);
                    return;
                }
                
                var entry = entries[index];
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'vmpfence_toggle_param_allowlist',
                        nonce: $('#vmpfence_allowlist_nonce').val(),
                        path: entry.path,
                        param_key: entry.param,
                        rule_id: entry.rule
                    },
                    success: function() {
                        entry.checkbox.prop('checked', false);
                        disableNext(index + 1);
                    },
                    error: function() {
                        // Continue anyway
                        disableNext(index + 1);
                    }
                });
            };
            
            disableNext(0);
        },
        
        /**
         * Enable Extended Protection
         */
        enableExtendedProtection: function() {
            var self = this;
            var $button = $('#optimize-firewall');
            
            // Show confirmation modal or fallback to browser confirm
            if (typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showConfirmModal({
                    title: 'Enable Extended Protection',
                    message: 'This will process all PHP requests through the firewall before WordPress loads.\n\nAre you sure you want to enable extended protection?',
                    confirmText: 'Enable',
                    cancelText: 'Cancel',
                    type: 'warning'
                }).then(function(confirmed) {
                    if (!confirmed) {
                        return; // User cancelled
                    }
                    
                    // User confirmed - proceed with enabling
                    $button
                        .prop('disabled', true)
                        .text('ENABLING...');
                    
                    $.ajax({
                        url: vmpfence_firewall_ajax.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'vmpfence_enable_extended_protection',
                            nonce: vmpfence_firewall_ajax.protection_level_nonce
                        },
                        success: function(response) {
                            if (response.success) {
                                VMPFenceNotifications.showSuccess(
                                    'Extended protection enabled successfully! Page will reload...',
                                    3000
                                );
                                
                                setTimeout(function() {
                                    location.reload();
                                }, 1500);
                            } else {
                                VMPFenceNotifications.showError(
                                    'Error: ' + (response.data || 'Failed to enable extended protection'),
                                    5000
                                );
                                $button
                                    .prop('disabled', false)
                                    .text('OPTIMIZE THE VMP FIREWALL');
                            }
                        },
                        error: function(xhr, status, error) {
                            VMPFenceNotifications.showError(
                                'AJAX Error: ' + error,
                                5000
                            );
                            $button
                                .prop('disabled', false)
                                .text('OPTIMIZE THE VMP FIREWALL');
                        }
                    });
                });
            } else {
                // Fallback to browser confirm if toast system unavailable
                if (!confirm('Enable Extended Protection?\n\nThis will process all PHP requests through the firewall before WordPress loads.\n\nAre you sure you want to enable extended protection?')) {
                    return; // User cancelled
                }
                
                // User confirmed - proceed with enabling
                $button
                    .prop('disabled', true)
                    .text('ENABLING...');
                
                $.ajax({
                    url: vmpfence_firewall_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'vmpfence_enable_extended_protection',
                        nonce: vmpfence_firewall_ajax.protection_level_nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            alert('Extended protection enabled successfully! Page will reload...');
                            setTimeout(function() {
                                location.reload();
                            }, 500);
                        } else {
                            alert('Error: ' + (response.data || 'Failed to enable extended protection'));
                            $button
                                .prop('disabled', false)
                                .text('OPTIMIZE THE VMP FIREWALL');
                        }
                    },
                    error: function(xhr, status, error) {
                        alert('AJAX Error: ' + error);
                        $button
                            .prop('disabled', false)
                            .text('OPTIMIZE THE VMP FIREWALL');
                    }
                });
            }
        },
        
        /**
         * Disable Extended Protection
         */
        disableExtendedProtection: function() {
            var self = this;
            var $button = $('#remove-extended-protection');
            
            // Show confirmation modal or fallback to browser confirm
            if (typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showConfirmModal({
                    title: 'Remove Extended Protection',
                    message: 'The firewall will load as a regular WordPress plugin.\n\nAre you sure you want to remove extended protection?',
                    confirmText: 'Remove',
                    cancelText: 'Cancel',
                    type: 'danger'
                }).then(function(confirmed) {
                    if (!confirmed) {
                        return; // User cancelled
                    }
                    
                    // User confirmed - proceed with removal
                    $button
                        .prop('disabled', true)
                        .text('REMOVING...');
                    
                    $.ajax({
                        url: vmpfence_firewall_ajax.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'vmpfence_disable_extended_protection',
                            nonce: vmpfence_firewall_ajax.protection_level_nonce
                        },
                        success: function(response) {
                            if (response.success) {
                                VMPFenceNotifications.showSuccess(
                                    'Extended protection removed successfully! Page will reload...',
                                    3000
                                );
                                
                                setTimeout(function() {
                                    location.reload();
                                }, 1500);
                            } else {
                                VMPFenceNotifications.showError(
                                    'Error: ' + (response.data || 'Failed to remove extended protection'),
                                    5000
                                );
                                $button
                                    .prop('disabled', false)
                                    .text('REMOVE EXTENDED PROTECTION');
                            }
                        },
                        error: function(xhr, status, error) {
                            VMPFenceNotifications.showError(
                                'AJAX Error: ' + error,
                                5000
                            );
                            $button
                                .prop('disabled', false)
                                .text('REMOVE EXTENDED PROTECTION');
                        }
                    });
                });
            } else {
                // Fallback to browser confirm if toast system unavailable
                if (!confirm('Remove Extended Protection?\n\nThe firewall will load as a regular WordPress plugin.\n\nAre you sure you want to remove extended protection?')) {
                    return; // User cancelled
                }
                
                // User confirmed - proceed with removal
                $button
                    .prop('disabled', true)
                    .text('REMOVING...');
                
                $.ajax({
                    url: vmpfence_firewall_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'vmpfence_disable_extended_protection',
                        nonce: vmpfence_firewall_ajax.protection_level_nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            alert('Extended protection removed successfully! Page will reload...');
                            setTimeout(function() {
                                location.reload();
                            }, 500);
                        } else {
                            alert('Error: ' + (response.data || 'Failed to remove extended protection'));
                            $button
                                .prop('disabled', false)
                                .text('REMOVE EXTENDED PROTECTION');
                        }
                    },
                    error: function(xhr, status, error) {
                        alert('AJAX Error: ' + error);
                        $button
                            .prop('disabled', false)
                            .text('REMOVE EXTENDED PROTECTION');
                    }
                });
            }
        }
    };

    // Initialize when DOM is ready
    if (typeof VMPFenceFirewallOptions !== 'undefined') {
        VMPFenceFirewallOptions.init();
        
        // Initialize allowlist functionality
        if ($('.vmpfence-allowlist-table').length) {
            VMPFenceFirewallOptions.loadAllowlistTable();
            
            // Add button click
            $('.vmpfence-btn-add').on('click', function() {
                VMPFenceFirewallOptions.addAllowlistEntry();
            });
            
            // Delete button click
            $('.vmpfence-btn-delete').on('click', function() {
                VMPFenceFirewallOptions.deleteAllowlistEntry();
            });
            
            // Enable button click
            $('.vmpfence-btn-enable').on('click', function() {
                VMPFenceFirewallOptions.enableAllowlistEntries();
            });
            
            // Disable button click
            $('.vmpfence-btn-disable').on('click', function() {
                VMPFenceFirewallOptions.disableAllowlistEntries();
            });
            
            // Toggle enabled/disabled
            $(document).on('change', '.vmpfence-enabled-toggle', function() {
                VMPFenceFirewallOptions.toggleAllowlistEntry($(this));
            });
            
            // Select all checkbox
            $('.vmpfence-select-all').on('change', function() {
                $('.vmpfence-row-select').prop('checked', $(this).prop('checked'));
            });

            // Filter select "Filter By:" prefix logic
            (function() {
                var $sel = $('.vmpfence-filter-select');
                if (!$sel.length) return;
                function addPrefix() {
                    var $opt = $sel.find('option:selected');
                    if ($opt.text().indexOf('Filter By: ') !== 0) {
                        $opt.text('Filter By: ' + $opt.text());
                    }
                }
                function removePrefix() {
                    $sel.find('option').each(function() {
                        $(this).text($(this).text().replace('Filter By: ', ''));
                    });
                }
                $sel.on('focus mousedown', removePrefix);
                $sel.on('change blur', function() { removePrefix(); addPrefix(); });
                addPrefix(); // init
            })();
        }
    }
});
