/**
 * BotFend Anti-Bot Firewall Settings Page JavaScript
 * Handles collapsible sections, range sliders, AJAX actions, and form management
 *
 * @since 4.6.0
 * @version 5.0.3 - Fixed unsaved indicator for all tabs, improved error handling
 */

(function($) {
    'use strict';

    /**
     * Initialize all settings page functionality
     */
    function initBotFendSettings() {
        initRangeSliders();
        initCollapsibleSections();
        initFormManagement();
        initFileGuardActions();
        initTORActions();
        initRecaptchaActions();
        initExportImportActions();
        initSystemActions();
        initResetActions();
        initSortableLists();
        initMasterToggles();
        initAdaptiveMode();
        
        // Component Actions
        initBehavioralActions();
        initAdvanced404Actions();
    }

    // ============================================
    // TOAST NOTIFICATION SYSTEM
    // ============================================
    function showToast(message, type) {
        var $toast = $('#botfend-settings-toast');
        
        if (!$toast.length) {
            $toast = $('<div id="botfend-settings-toast" class="botfend-toast"></div>').appendTo('body');
        }
        
        $toast.removeClass('success error warning').addClass(type);
        $toast.html('<span class="dashicons"></span><span class="toast-message">' + message + '</span>');
        $toast.addClass('show');
        
        setTimeout(function() {
            $toast.removeClass('show');
        }, 3000);
    }

    /**
     * Range Sliders with Live Updates
     */
    function initRangeSliders() {
        $('input[type="range"]').each(function() {
            var $slider = $(this);
            var $output = null;
            var sliderId = $slider.attr('id');
            
            if (sliderId) {
                $output = $('#' + sliderId + '_val');
                
                if (!$output || !$output.length) {
                    var baseId = sliderId.replace('_range', '');
                    $output = $('#' + baseId + '_val');
                }
                
                if (!$output || !$output.length) {
                    $output = $('#' + sliderId.replace('_range', '') + '_val');
                }
            }
            
            if (!$output || !$output.length) {
                var $wrapper = $slider.closest('.botfend-range-wrapper');
                if ($wrapper.length) {
                    $output = $wrapper.find('output');
                }
            }
            
            if (!$output || !$output.length) {
                $output = $slider.next('output');
            }
            
            if ($output && $output.length) {
                var initialValue = $slider.val();
                var suffix = '';
                
                if (sliderId) {
                    if (sliderId.indexOf('abuseipdb_confidence') !== -1 || sliderId.indexOf('challenge_prob') !== -1) {
                        suffix = '%';
                    } else if (sliderId.indexOf('penalty_multiplier') !== -1) {
                        suffix = 'x';
                    } else if ($slider.attr('data-suffix')) {
                        suffix = $slider.attr('data-suffix');
                    }
                }
                
                $output.text(initialValue + suffix);
                
                $slider.on('input', function() {
                    var value = $(this).val();
                    var currentSuffix = suffix;
                    
                    if (!currentSuffix) {
                        var currentId = $(this).attr('id');
                        if (currentId && currentId.indexOf('abuseipdb_confidence') !== -1) {
                            currentSuffix = '%';
                        } else if (currentId && currentId.indexOf('penalty_multiplier') !== -1) {
                            currentSuffix = 'x';
                        }
                    }
                    
                    $output.text(value + currentSuffix);
                });
            }
        });
        
        $(document).on('input', 'input[type="range"]', function() {
            var $slider = $(this);
            var sliderId = $slider.attr('id');
            var $output = null;
            
            if (sliderId) {
                $output = $('#' + sliderId + '_val');
                if (!$output || !$output.length) {
                    var baseId = sliderId.replace('_range', '');
                    $output = $('#' + baseId + '_val');
                }
            }
            
            if (!$output || !$output.length) {
                var $wrapper = $slider.closest('.botfend-range-wrapper');
                if ($wrapper.length) {
                    $output = $wrapper.find('output');
                }
            }
            
            if ($output && $output.length) {
                var value = $slider.val();
                var suffix = '';
                
                if (sliderId) {
                    if (sliderId.indexOf('abuseipdb_confidence') !== -1) suffix = '%';
                    else if (sliderId.indexOf('penalty_multiplier') !== -1) suffix = 'x';
                }
                
                $output.text(value + suffix);
            }
        });
    }

    /**
     * Collapsible Sections Functionality
     */
    function initCollapsibleSections() {
        $('.botfend-section-header').on('click', function(e) {
            if ($(e.target).hasClass('dashicons-info') || $(e.target).hasClass('botfend-info-icon')) {
                e.stopPropagation();
                return;
            }
            
            var $header = $(this);
            var $content = $header.next('.botfend-section-content');
            var $icon = $header.find('.toggle-icon');
            
            if ($content.is(':visible')) {
                $content.slideUp(300);
                $icon.removeClass('dashicons-arrow-down').addClass('dashicons-arrow-up');
                var sectionId = $header.data('section');
                if (sectionId) {
                    localStorage.setItem('botfend_section_' + sectionId, 'closed');
                }
            } else {
                $content.slideDown(300);
                $icon.removeClass('dashicons-arrow-up').addClass('dashicons-arrow-down');
                var sectionId = $header.data('section');
                if (sectionId) {
                    localStorage.setItem('botfend_section_' + sectionId, 'open');
                }
            }
        });
        
        $('.botfend-section-header').each(function() {
            var sectionId = $(this).data('section');
            if (sectionId) {
                var savedState = localStorage.getItem('botfend_section_' + sectionId);
                var $content = $(this).next('.botfend-section-content');
                var $icon = $(this).find('.toggle-icon');
                
                if (savedState === 'closed') {
                    $content.hide();
                    $icon.removeClass('dashicons-arrow-down').addClass('dashicons-arrow-up');
                } else {
                    $content.show();
                    $icon.removeClass('dashicons-arrow-up').addClass('dashicons-arrow-down');
                }
            }
        });
    }

    /**
     * Form Management - Unsaved Changes Detection & AJAX Saving
     * FIXED: Properly handles unsaved indicator for all tabs
     */
    function initFormManagement() {
        var originalFormData = {};
        var forms = $('.botfend-settings-form');
        
        // Initialize original form data and ensure each form has required elements
        forms.each(function() {
            var $form = $(this);
            var tabId = $form.data('tab');
            originalFormData[tabId] = $form.serialize();
            $form.data('dirty', false);
            
            // Ensure the submit button has the correct ID
            var $submitBtn = $('#botfend-submit-' + tabId);
            if (!$submitBtn.length) {
                // Fallback: find submit button within the form
                $submitBtn = $form.find('input[type="submit"]');
                if ($submitBtn.length) {
                    $submitBtn.attr('id', 'botfend-submit-' + tabId);
                }
            }
            
            // Ensure unsaved indicator exists in the tab content
            var $tabContent = $form.closest('.botfend-tab-content');
            var $indicator = $tabContent.find('.botfend-unsaved-indicator');
            
            if (!$indicator.length) {
                // Create indicator if missing
                $indicator = $('<span class="botfend-unsaved-indicator" style="display: none; color: #856404; background: #fff3cd; padding: 5px 12px; border-radius: 3px; font-size: 13px;">' +
                    '<span class="dashicons dashicons-warning" style="font-size: 16px; width: 16px; height: 16px; vertical-align: middle;"></span>' +
                    botfendSettings.unsavedText + '</span>');
                $tabContent.find('.submit-container').prepend($indicator);
            }
        });
        
        function checkFormChanges($form) {
            var tabId = $form.data('tab');
            var currentData = $form.serialize();
            var $submitBtn = $('#botfend-submit-' + tabId);
            var $indicator = $form.closest('.botfend-tab-content').find('.botfend-unsaved-indicator');
            
            // Skip if elements don't exist (shouldn't happen after initialization)
            if (!$submitBtn.length || !$indicator.length) {
                return;
            }
            
            if (originalFormData[tabId] !== currentData) {
                if (!$form.data('dirty')) {
                    $form.data('dirty', true);
                    $submitBtn.prop('disabled', false);
                    $indicator.fadeIn(200);
                }
            } else {
                if ($form.data('dirty')) {
                    $form.data('dirty', false);
                    $submitBtn.prop('disabled', true);
                    $indicator.fadeOut(200);
                }
            }
        }
        
        // Track changes on all form inputs
        forms.on('input change', 'input, select, textarea', function() {
            var $form = $(this).closest('.botfend-settings-form');
            checkFormChanges($form);
        });
        
        forms.on('change', 'input[type="checkbox"]', function() {
            var $form = $(this).closest('.botfend-settings-form');
            setTimeout(function() { checkFormChanges($form); }, 10);
        });
        
        // Tab switching with unsaved changes protection
        $('#botfend-tabs .nav-tab').on('click', function(e) {
            e.preventDefault();
            var $currentTabContent = $('.botfend-tab-content.active');
            var $currentForm = $currentTabContent.find('.botfend-settings-form');
            var tabId = $(this).data('tab');
            
            if ($currentForm.length && $currentForm.data('dirty')) {
                if (!confirm(botfendSettings.confirmTabSwitch)) {
                    return false;
                }
                $currentForm.data('dirty', false);
            }
            
            $('#botfend-tabs .nav-tab').removeClass('nav-tab-active');
            $(this).addClass('nav-tab-active');
            $('.botfend-tab-content').hide();
            $('#botfend-tab-' + tabId).show();
            
            setTimeout(function() {
                initRangeSliders();
            }, 100);
            
            var newUrl = window.location.pathname + '?page=botfend-settings&tab=' + tabId;
            window.history.pushState({tab: tabId}, '', newUrl);
        });
        
        // Browser back/forward
        window.addEventListener('popstate', function(event) {
            if (event.state && event.state.tab) {
                var tabId = event.state.tab;
                var $currentTabContent = $('.botfend-tab-content.active');
                var $currentForm = $currentTabContent.find('.botfend-settings-form');
                
                if ($currentForm.length && $currentForm.data('dirty')) {
                    if (!confirm(botfendSettings.confirmTabSwitch)) {
                        history.go(1);
                        return;
                    }
                }
                $('#botfend-tabs .nav-tab').removeClass('nav-tab-active');
                $('#botfend-tabs .nav-tab[data-tab="' + tabId + '"]').addClass('nav-tab-active');
                $('.botfend-tab-content').hide();
                $('#botfend-tab-' + tabId).show();
                
                setTimeout(function() { initRangeSliders(); }, 100);
            }
        });
        
        // Before unload warning
        $(window).on('beforeunload', function() {
            var dirtyForms = forms.filter(function() { return $(this).data('dirty'); });
            if (dirtyForms.length > 0) {
                return botfendSettings.confirmLeave;
            }
        });
        
        // AJAX Form Submission
        forms.on('submit', function(e) {
            e.preventDefault();
            
            var $form = $(this);
            var tab = $form.data('tab');
            var $submitBtn = $('#botfend-submit-' + tab);
            var originalText = $submitBtn.val();
            
            $submitBtn.val(botfendSettings.savingText).prop('disabled', true);
            
            // Temporarily enable disabled inputs to ensure they serialize properly
            var $disabledInputs = $form.find(':disabled');
            $disabledInputs.prop('disabled', false);
            var formData = $form.serialize();
            $disabledInputs.prop('disabled', true);
            
            $.ajax({
                url: $form.attr('action'),
                type: 'POST',
                data: formData,
                success: function(response) {
                    originalFormData[tab] = formData;
                    $form.data('dirty', false);
                    $form.closest('.botfend-tab-content').find('.botfend-unsaved-indicator').fadeOut(200);
                    showToast(botfendSettings.saveSuccess, 'success');
                    $('.settings-error').remove();
                },
                error: function() {
                    showToast(botfendSettings.saveError, 'error');
                },
                complete: function() {
                    $submitBtn.val(originalText);
                }
            });
            return false;
        });
        
        // Initial check for each form
        forms.each(function() { checkFormChanges($(this)); });
    }

    /**
     * File Guard Actions
     */
    function initFileGuardActions() {
        function showFileGuardNotice(message, type, targetElement) {
            var noticeClass = type === 'success' ? 'notice-success' : (type === 'warning' ? 'notice-warning' : 'notice-error');
            var icon = type === 'success' ? 'yes' : (type === 'warning' ? 'warning' : 'info');
            var noticeHtml = '<div class="notice ' + noticeClass + ' is-dismissible" style="margin-top: 20px;"><p><span class="dashicons dashicons-' + icon + '"></span> ' + message + '</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss</span></button></div>';
            $(targetElement).after(noticeHtml);
            
            if (type === 'success') {
                setTimeout(function() {
                    $('.notice-' + noticeClass).fadeOut(function() { $(this).remove(); });
                }, 5000);
            }
        }
        
        $('.botfend-protect-uploads-btn').on('click', function() {
            var $btn = $(this);
            var originalText = $btn.html();
            var nonce = $btn.data('nonce');
            
            $btn.html('<span class="dashicons dashicons-update spin"></span> ' + botfendSettings.applyingText).prop('disabled', true);
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'botfend_protect_uploads',
                    nonce: nonce
                },
                success: function(response) {
                    if (response.success) {
                        showFileGuardNotice(response.data.message, 'success', '.botfend-collapsible-section:last');
                        setTimeout(function() { location.reload(); }, 1500);
                    } else {
                        showFileGuardNotice(response.data.message || botfendSettings.protectFailed, 'error', '.botfend-collapsible-section:last');
                    }
                },
                error: function(xhr) {
                    var message = botfendSettings.protectError;
                    if (xhr.status === 429) message = botfendSettings.rateLimit;
                    else if (xhr.status === 403) message = botfendSettings.permissionDenied;
                    showFileGuardNotice(message, 'error', '.botfend-collapsible-section:last');
                },
                complete: function() {
                    $btn.html(originalText).prop('disabled', false);
                }
            });
        });
        
        $('.botfend-check-permissions-btn').on('click', function() {
            var $btn = $(this);
            var originalText = $btn.html();
            var nonce = $btn.data('nonce');
            
            $btn.html('<span class="dashicons dashicons-update spin"></span> ' + botfendSettings.checkingText).prop('disabled', true);
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'botfend_check_permissions',
                    nonce: nonce
                },
                success: function(response) {
                    if (response.success) {
                        var issues = response.data.issues || [];
                        var message = response.data.message;
                        
                        if (issues.length > 0) {
                            var warningHtml = '<div class="notice notice-warning is-dismissible" style="margin-top: 20px;"><p><span class="dashicons dashicons-warning"></span> ' + message + '</p>';
                            warningHtml += '<ul style="margin: 10px 0 0 20px;">';
                            issues.forEach(function(issue) {
                                warningHtml += '<li><code>' + issue.file + '</code>: ' + issue.reason + 
                                             (issue.fixed ? ' <span style="color:#46b450;">✓ Fixed</span>' : '') + '</li>';
                            });
                            warningHtml += '</ul><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss</span></button></div>';
                            $('.botfend-collapsible-section:last').after(warningHtml);
                            
                            if (issues.some(function(i) { return i.fixed; })) {
                                setTimeout(function() { location.reload(); }, 3000);
                            }
                        } else {
                            showFileGuardNotice(message, 'success', '.botfend-collapsible-section:last');
                        }
                    } else {
                        showFileGuardNotice(response.data.message || botfendSettings.checkFailed, 'error', '.botfend-collapsible-section:last');
                    }
                },
                error: function() {
                    showFileGuardNotice(botfendSettings.checkError, 'error', '.botfend-collapsible-section:last');
                },
                complete: function() {
                    $btn.html(originalText).prop('disabled', false);
                }
            });
        });

        $(document).on('click', '.botfend-view-permission-details', function(e) {
            e.preventDefault();
            var $btn = $(this);
            var $alertBox = $btn.closest('.botfend-permission-alert');
            var $container = $alertBox.find('.botfend-permission-details-container');
            var $loading = $container.find('.botfend-permission-loading');
            var $list = $container.find('.botfend-permission-file-list');
            var nonce = $btn.data('nonce');

            if ($list.children().length > 0) {
                $container.slideToggle('fast');
                return;
            }

            $container.slideDown('fast');
            $loading.show();
            $btn.prop('disabled', true);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'botfend_check_permissions',
                    nonce: nonce
                },
                success: function(response) {
                    $loading.hide();
                    $btn.prop('disabled', false);
                    $list.empty();
                    
                    if (response.success) {
                        if (response.data.issues && response.data.issues.length > 0) {
                            $.each(response.data.issues, function(index, issue) {
                                var fixedBadge = issue.fixed ? ' <span class="botfend-badge-fixed">✓ Fixed</span>' : '';
                                
                                var permsHtml = '';
                                if (issue.current_permission && issue.expected_permission) {
                                    permsHtml = '<div class="botfend-file-perms">' +
                                                '<span class="botfend-perm-current">Current: ' + issue.current_permission + '</span>' +
                                                '<span class="dashicons dashicons-arrow-right-alt2 botfend-perm-arrow"></span>' +
                                                '<span class="botfend-perm-required">Required: ' + issue.expected_permission + '</span>' +
                                                '</div>';
                                }
                                
                                $list.append(
                                    '<li>' +
                                        '<code class="botfend-file-path">' + issue.file + '</code>' +
                                        permsHtml +
                                        '<div class="botfend-file-meta">' +
                                            '<span class="botfend-file-reason">' + issue.reason + '</span>' + 
                                            fixedBadge +
                                        '</div>' +
                                    '</li>'
                                );
                            });
                        } else {
                            $list.append('<li style="color:#46b450; font-weight: 600;"><span class="dashicons dashicons-yes-alt"></span> ' + botfendSettings.noIssuesFound + '</li>');
                            setTimeout(function(){ location.reload(); }, 1500);
                        }
                    } else {
                        $list.append('<li style="color:#dc3232;"><span class="dashicons dashicons-warning"></span> ' + (response.data.message || botfendSettings.serverError) + '</li>');
                    }
                },
                error: function(xhr) {
                    $loading.hide();
                    $btn.prop('disabled', false);
                    $list.html('<li style="color:#dc3232;"><span class="dashicons dashicons-warning"></span> ' + botfendSettings.fetchError + ' Status: ' + xhr.status + '</li>');
                }
            });
        });
    }

    /**
     * TOR Actions
     */
    function initTORActions() {
        $('#botfend_manual_tor_update').on('click', function(e) {
            e.preventDefault();
            var $button = $(this);
            var $status = $('#botfend_tor_update_status');
            
            $button.prop('disabled', true).text(botfendSettings.updatingText || 'Updating...');
            $status.html('<span style="color: #ffb900;">' + (botfendSettings.updatingTor || 'Downloading TOR list...') + '</span>');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'botfend_tor_update',
                    nonce: botfendSettings.torUpdateNonce
                },
                success: function(response) {
                    if (response.success) {
                        $status.html('<span style="color: #46b450;">✓ ' + response.data.message + '</span>');
                        var updateTime = response.data.timestamp || response.data.last_updated;
                        if (updateTime) {
                            $('#botfend_tor_last_updated').text(updateTime);
                        }
                    } else {
                        $status.html('<span style="color: #dc3232;">✗ ' + (response.data.message || 'Update failed') + '</span>');
                    }
                },
                error: function() {
                    $status.html('<span style="color: #dc3232;">' + (botfendSettings.updateFailed || 'Update failed.') + '</span>');
                },
                complete: function() {
                    $button.prop('disabled', false).text(botfendSettings.manualUpdateText || 'Manual Update Now');
                    setTimeout(function() {
                        $status.fadeOut(1000, function() { $(this).empty().show(); });
                    }, 5000);
                }
            });
        });

        $('#botfend_clear_tor_cache').on('click', function(e) {
            e.preventDefault();
            var $btn = $(this);
            var $status = $('#botfend_tor_update_status');
            
            $btn.prop('disabled', true);
            $status.html('<span style="color: #007cba;">Clearing TOR cache...</span>');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'botfend_reset_tor_cache',
                    nonce: botfendSettings.torCacheNonce
                },
                success: function(response) {
                    if (response.success) {
                        $status.html('<span style="color: #46b450;">✓ ' + response.data.message + '</span>');
                    } else {
                        $status.html('<span style="color: #dc3232;">✗ ' + (response.data.message || 'Failed to clear cache') + '</span>');
                    }
                    setTimeout(function() { $status.empty(); }, 5000);
                },
                error: function() {
                    $status.html('<span style="color: #dc3232;">Server communication error.</span>');
                    setTimeout(function() { $status.empty(); }, 5000);
                },
                complete: function() {
                    $btn.prop('disabled', false);
                }
            });
        });
        
        $('#botfend_reset_tor_stats').on('click', function(e) {
            e.preventDefault();
            if (confirm(botfendSettings.resetTorConfirm)) {
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'botfend_reset_tor_stats',
                        nonce: botfendSettings.torStatsNonce
                    },
                    success: function(response) {
                        if (response.success) location.reload();
                        else alert(response.data.message);
                    }
                });
            }
        });
    }

    /**
     * reCAPTCHA Actions
     */
    function initRecaptchaActions() {
        var $versionSelect = $('#recaptcha-version-select');
        var $v3Settings = $('#recaptcha-v3-settings');
        var $v2Settings = $('#recaptcha-v2-settings');
        
        function toggleRecaptchaSettings() {
            if ($versionSelect.val() === 'v3') {
                $v3Settings.show(); $v2Settings.hide();
            } else {
                $v3Settings.hide(); $v2Settings.show();
            }
        }
        
        if ($versionSelect.length) {
            $versionSelect.on('change', toggleRecaptchaSettings);
            toggleRecaptchaSettings();
        }
        
        $('#botfend-test-recaptcha').on('click', function() {
            var $btn = $(this);
            var $result = $('#botfend-recaptcha-test-result');
            var version = $versionSelect.val();
            
            $btn.prop('disabled', true).text(botfendSettings.testingText);
            $result.html('').removeClass('notice notice-success notice-error');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'botfend_test_recaptcha',
                    nonce: botfendSettings.recaptchaNonce,
                    version: version
                },
                success: function(response) {
                    if (response.success) {
                        $result.html('<span style="color: #46b450;">✓ ' + response.data.message + '</span>');
                    } else {
                        $result.html('<span style="color: #dc3232;">✗ ' + response.data.message + '</span>');
                    }
                },
                error: function() {
                    $result.html('<span style="color: #dc3232;">' + botfendSettings.connectionFailed + '</span>');
                },
                complete: function() {
                    $btn.prop('disabled', false).text(botfendSettings.testRecaptchaText);
                }
            });
        });
    }

    /**
     * Export/Import Actions
     */
    function initExportImportActions() {
        $('#botfend-show-import').on('click', function() {
            $(this).hide();
            $('#botfend-import-form').slideDown();
        });
        
        $('#botfend-cancel-import').on('click', function() {
            $('#botfend-import-form').slideUp(function() {
                $('#botfend-show-import').show();
            });
        });
        
        $('#botfend_export_whitelist').on('click', function() {
            var content = $('#botfend_whitelist_ips').val();
            if (!content.trim()) { alert(botfendSettings.whitelistEmpty); return; }
            var blob = new Blob([content], {type: 'text/plain'});
            var link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = 'botfend-whitelist-' + new Date().toISOString().slice(0,19) + '.txt';
            link.click();
            URL.revokeObjectURL(link.href);
        });
        
        $('#botfend_export_blocklist').on('click', function() {
            var content = $('#botfend_permanent_blocklist').val();
            if (!content.trim()) { alert(botfendSettings.blocklistEmpty); return; }
            var blob = new Blob([content], {type: 'text/plain'});
            var link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = 'botfend-blocklist-' + new Date().toISOString().slice(0,19) + '.txt';
            link.click();
            URL.revokeObjectURL(link.href);
        });
        
        $('#botfend_clear_whitelist').on('click', function() {
            if (confirm(botfendSettings.clearWhitelistConfirm)) {
                $('#botfend_whitelist_ips').val('').trigger('change');
                showToast(botfendSettings.whitelistCleared, 'success');
            }
        });
        
        $('#botfend_clear_blocklist').on('click', function() {
            if (confirm(botfendSettings.clearBlocklistConfirm)) {
                $('#botfend_permanent_blocklist').val('').trigger('change');
                showToast(botfendSettings.blocklistCleared, 'success');
            }
        });
    }

    /**
     * Behavioral Analyzer Actions
     */
    function initBehavioralActions() {
        $('.botfend-clear-behavior-btn').on('click', function(e) {
            e.preventDefault();
            var $btn = $(this);
            var $status = $btn.siblings('.botfend-behavior-clear-status');
            var nonce = $btn.data('nonce');
            var originalText = $btn.html();

            if (!confirm(botfendSettings.confirmClearBehavior)) {
                return;
            }

            $btn.prop('disabled', true).html('<span class="dashicons dashicons-update spin" style="vertical-align: middle; margin-top: -3px;"></span> ' + botfendSettings.clearingText);
            $status.hide();

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'botfend_clear_behavior_analysis',
                    nonce: nonce
                },
                success: function(response) {
                    if (response.success) {
                        $status.css('color', '#46b450').text('✓ ' + response.data.message).fadeIn();
                    } else {
                        $status.css('color', '#dc3232').text('✗ ' + response.data.message).fadeIn();
                    }
                },
                error: function() {
                    $status.css('color', '#dc3232').text('✗ ' + botfendSettings.serverError).fadeIn();
                },
                complete: function() {
                    $btn.prop('disabled', false).html(originalText);
                    setTimeout(function() { $status.fadeOut(); }, 4000);
                }
            });
        });
    }

    /**
     * Advanced 404 Actions
     */
    function initAdvanced404Actions() {
        $('.botfend-clear-404-history-btn').on('click', function(e) {
            e.preventDefault();
            var $btn = $(this);
            var $status = $btn.siblings('.botfend-404-clear-status');
            var nonce = $btn.data('nonce');
            var originalText = $btn.html();

            if (!confirm(botfendSettings.confirmClear404)) {
                return;
            }

            $btn.prop('disabled', true).html('<span class="dashicons dashicons-update spin" style="vertical-align: middle; margin-top: -3px;"></span> ' + botfendSettings.clearingText);
            $status.hide();

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'botfend_clear_404_history',
                    nonce: nonce
                },
                success: function(response) {
                    if (response.success) {
                        $status.css('color', '#46b450').text('✓ ' + response.data.message).fadeIn();
                    } else {
                        $status.css('color', '#dc3232').text('✗ ' + response.data.message).fadeIn();
                    }
                },
                error: function() {
                    $status.css('color', '#dc3232').text('✗ ' + botfendSettings.serverError).fadeIn();
                },
                complete: function() {
                    $btn.prop('disabled', false).html(originalText);
                    setTimeout(function() { $status.fadeOut(); }, 4000);
                }
            });
        });
    }

    /**
     * System Actions
     */
    function initSystemActions() {
        $('#botfend-clear-cache').on('click', function() {
            var $btn = $(this);
            var originalText = $btn.html();
            
            if (!confirm(botfendSettings.clearCacheConfirm)) return;
            
            $btn.html('<span class="dashicons dashicons-update spin"></span> ' + botfendSettings.clearingText).prop('disabled', true);
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'botfend_clear_all_caches',
                    nonce: botfendSettings.clearCacheNonce
                },
                success: function(response) {
                    if (response.success) {
                        showToast(response.data.message, 'success');
                    } else {
                        showToast(response.data.message || botfendSettings.clearFailed, 'error');
                    }
                },
                error: function() {
                    showToast(botfendSettings.clearError, 'error');
                },
                complete: function() {
                    $btn.html(originalText).prop('disabled', false);
                }
            });
        });
        
        function toggleTrustedProxies() {
            var mode = $('#ip-validation-mode').val();
            if (mode === 'balanced') $('#trusted-proxies-row').show();
            else $('#trusted-proxies-row').hide();
        }
        
        $('#ip-validation-mode').on('change', toggleTrustedProxies);
        toggleTrustedProxies();
        
        $('#add-cloudflare-ips').on('click', function() {
            var cloudflareIps = [
                '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22',
                '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20',
                '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13',
                '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22', '2400:cb00::/32',
                '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32',
                '2a06:98c0::/29', '2c0f:f248::/32'
            ];
            var textarea = $('#trusted-proxies-textarea');
            var current = textarea.val().split('\n').map(function(line) { return line.trim(); }).filter(Boolean);
            var combined = [...new Set([...current, ...cloudflareIps])];
            textarea.val(combined.join('\n')).trigger('change');
        });
        
        $('#clear-proxy-ips').on('click', function() {
            if (confirm(botfendSettings.clearProxiesConfirm)) {
                $('#trusted-proxies-textarea').val('').trigger('change');
            }
        });
    }

    /**
     * Sortable Lists
     */
    function initSortableLists() {
        if ($.fn.sortable && $('#ip-headers-list').length) {
            $('#ip-headers-list').sortable({
                placeholder: 'botfend-sortable-item botfend-sortable-placeholder',
                tolerance: 'pointer',
                update: function() {
                    $('#ip-headers-list .botfend-sortable-item').each(function(index) {
                        $(this).find('input').val($(this).find('code').text().trim());
                    });
                }
            });
        }
    }

    /**
     * Master Toggles
     */
    function initMasterToggles() {
        function toggleSection($element, isEnabled) {
            var $parentSection = $element.closest('.botfend-collapsible-section');
            var $targets = $parentSection.find('tr:not(:first-child)');
            
            if (!isEnabled) {
                $targets.css({'opacity': '0.5', 'pointer-events': 'none'});
            } else {
                $targets.css({'opacity': '1', 'pointer-events': 'auto'});
            }
        }

        $('#botfend_protect_uploads').on('change', function() {
            toggleSection($(this), $(this).is(':checked'));
        });
        if ($('#botfend_protect_uploads').length) {
            toggleSection($('#botfend_protect_uploads'), $('#botfend_protect_uploads').is(':checked'));
        }
        
        $('#botfend_enabled').on('change', function() {
            toggleSection($(this), $(this).is(':checked'));
        });
        if ($('#botfend_enabled').length) {
            toggleSection($('#botfend_enabled'), $('#botfend_enabled').is(':checked'));
        }
        
        $('#botfend_enable_detection').on('change', function() {
            var isEnabled = $(this).is(':checked');
            var $otherSections = $('.botfend-collapsible-section').not($(this).closest('.botfend-collapsible-section'));
            var $siblingRows = $(this).closest('tr').siblings('tr');
            
            if (!isEnabled) {
                $otherSections.css({'opacity': '0.5', 'pointer-events': 'none'});
                $siblingRows.css({'opacity': '0.5', 'pointer-events': 'none'});
            } else {
                $otherSections.css({'opacity': '1', 'pointer-events': 'auto'});
                $siblingRows.css({'opacity': '1', 'pointer-events': 'auto'});
            }
        });
        if ($('#botfend_enable_detection').length) {
            $('#botfend_enable_detection').trigger('change');
        }
    }

    /**
     * Adaptive Mode
     */
    function initAdaptiveMode() {
        var $adaptiveToggle = $('#botfend_enable_adaptive');
        var $modeSelect = $('#botfend_adaptive_mode');
        var $modeContainer = $('#botfend-mode-container');

        function toggleModeLock() {
            if ($adaptiveToggle.is(':checked')) {
                $modeSelect.css({'pointer-events': 'none', 'background-color': '#f0f0f1', 'color': '#8c8f94'});
                $modeContainer.css('opacity', '0.7');
                
                if ($('#botfend-ai-badge').length === 0) {
                    $modeSelect.after('<span id="botfend-ai-badge" style="display:inline-block; margin-left:10px; padding:3px 10px; background:#e5f0fa; color:#2271b1; border-radius:12px; font-size:11px; font-weight:500;"><span class="dashicons dashicons-lock" style="font-size:12px; width:12px; height:12px; line-height:1; margin-right:4px;"></span>Managed by Autopilot</span>');
                } else {
                    $('#botfend-ai-badge').show();
                }
            } else {
                $modeSelect.css({'pointer-events': 'auto', 'background-color': '#fff', 'color': '#2c3338'});
                $modeContainer.css('opacity', '1');
                $('#botfend-ai-badge').hide();
            }
        }

        if ($adaptiveToggle.length) {
            toggleModeLock();
            $adaptiveToggle.on('change', toggleModeLock);
        }
    }

    /**
     * Reset Actions
     */
    function initResetActions() {
        var $resetSelect = $('#botfend_reset_action_select');
        var $executeBtn = $('#botfend_execute_action_btn');
        
        function toggleExecuteButton() {
            if ($resetSelect.val() === '') {
                $executeBtn.prop('disabled', true);
            } else {
                $executeBtn.prop('disabled', false);
                if ($resetSelect.val() === 'reset_settings') {
                    $executeBtn.removeClass('button-secondary').addClass('button-primary').css('background', '#dc3232').css('border-color', '#dc3232');
                } else {
                    $executeBtn.addClass('button-secondary').removeClass('button-primary').css('background', '').css('border-color', '');
                }
            }
        }
        
        if ($resetSelect.length) {
            $resetSelect.on('change', toggleExecuteButton);
            toggleExecuteButton();
        }
    }

    /**
     * Add CSS styles
     */
    function addStyles() {
        if (!$('#botfend-sortable-style').length) {
            $('head').append('<style id="botfend-sortable-style">' +
                '.botfend-sortable-list{background:#f8f9fa;padding:10px;border-radius:4px;border:1px solid #ddd;}' +
                '.botfend-sortable-item{background:#fff;border:1px solid #ddd;border-radius:3px;padding:8px 12px;margin-bottom:5px;cursor:move;display:flex;align-items:center;gap:10px;}' +
                '.botfend-sortable-item:last-child{margin-bottom:0;}' +
                '.botfend-sortable-item .dashicons-menu{color:#999;cursor:grab;}' +
                '.botfend-sortable-placeholder{background:#f0f0f1;border:2px dashed #999;height:40px;margin-bottom:5px;border-radius:3px;}' +
                '</style>');
        }
        
        if (!$('#botfend-spin-style').length) {
            $('head').append('<style id="botfend-spin-style">' +
                '@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}' +
                '.spin{animation:spin 1s linear infinite;}' +
                '</style>');
        }
        
        if (!$('#botfend-toast-style').length) {
            $('head').append('<style id="botfend-toast-style">' +
                '.botfend-toast{position:fixed;bottom:24px;right:24px;padding:12px 20px;border-radius:8px;color:#fff;font-size:14px;font-weight:500;display:flex;align-items:center;gap:10px;box-shadow:0 4px 12px rgba(0,0,0,0.15);transform:translateX(400px);transition:transform 0.3s ease;z-index:10000}' +
                '.botfend-toast.show{transform:translateX(0)}' +
                '.botfend-toast.success{background:#46b450}' +
                '.botfend-toast.error{background:#dc3232}' +
                '.botfend-toast.warning{background:#ffb900}' +
                '.botfend-toast .dashicons{font-size:18px;width:18px;height:18px}' +
                '.botfend-toast.success .dashicons:before{content:"\\f147"}' +
                '.botfend-toast.error .dashicons:before{content:"\\f158"}' +
                '.botfend-toast.warning .dashicons:before{content:"\\f534"}' +
                '</style>');
        }
    }

    // Initialize when document is ready
    $(document).ready(function() {
        addStyles();
        initBotFendSettings();
    });

})(jQuery);