jQuery(document).ready(function ($) {
    const FEED_REFRESH_INTERVAL_MS = 5000;
    const LOG_PAGE_SIZE = 30;
    const $firewallRoot = $('#vulntitan-firewall-page');
    if (!$firewallRoot.length) {
        return;
    }

    const $firewallOverview = $('#vulntitan-firewall-overview');
    const $firewallFeedback = $('#vulntitan-firewall-feedback');
    const $firewallLogsList = $('#vulntitan-firewall-logs-list');
    const $firewallLogsEmpty = $('#vulntitan-firewall-logs-empty');
    const $firewallLogDetail = $('#vulntitan-firewall-log-detail');
    const $firewallLoadMore = $('#vulntitan-firewall-load-more');
    const $firewallFeedMeta = $('#vulntitan-firewall-feed-meta');
    const $firewallFeedStatus = $('#vulntitan-firewall-feed-status');
    const $firewallFeedToggle = $('#vulntitan-firewall-feed-toggle');
    const $firewallFeedSearch = $('#vulntitan-firewall-feed-search');
    const $firewallFeedSummary = $('#vulntitan-firewall-feed-summary');
    const $firewallFeedFilters = $firewallRoot.find('[data-firewall-feed-filter]');
    const $firewallEnabled = $('#vulntitan-firewall-enabled');
    const $firewallLoginProtection = $('#vulntitan-firewall-login-protection');
    const $firewallCustomLoginSlug = $('#vulntitan-firewall-custom-login-slug');
    const $firewallCustomLoginUrl = $('#vulntitan-firewall-custom-login-url');
    const $firewallTwoFactorEnabled = $('#vulntitan-firewall-two-factor-enabled');
    const $firewallTwoFactorRoles = $('#vulntitan-firewall-two-factor-roles');
    const $firewallTrustedDeviceDays = $('#vulntitan-firewall-trusted-device-days');
    const $firewallCaptchaProvider = $('#vulntitan-firewall-captcha-provider');
    const $firewallCaptchaSiteKey = $('#vulntitan-firewall-captcha-site-key');
    const $firewallCaptchaSecretKey = $('#vulntitan-firewall-captcha-secret-key');
    const $firewallCaptchaLoginEnabled = $('#vulntitan-firewall-captcha-login-enabled');
    const $firewallCaptchaRegisterEnabled = $('#vulntitan-firewall-captcha-register-enabled');
    const $firewallCaptchaWooCommerceLoginEnabled = $('#vulntitan-firewall-captcha-woocommerce-login-enabled');
    const $firewallCaptchaWooCommerceRegisterEnabled = $('#vulntitan-firewall-captcha-woocommerce-register-enabled');
    const $firewallCaptchaLostPasswordEnabled = $('#vulntitan-firewall-captcha-lostpassword-enabled');
    const $firewallCaptchaCommentEnabled = $('#vulntitan-firewall-captcha-comment-enabled');
    const $firewallXmlrpcPolicy = $('#vulntitan-firewall-xmlrpc-policy');
    const $firewallXmlrpcAllowlist = $('#vulntitan-firewall-xmlrpc-allowlist');
    const $firewallXmlrpcRateLimitAttempts = $('#vulntitan-firewall-xmlrpc-rate-limit-attempts');
    const $firewallXmlrpcRateLimitWindowMinutes = $('#vulntitan-firewall-xmlrpc-rate-limit-window-minutes');
    const $firewallWeakPasswordBlockingEnabled = $('#vulntitan-firewall-weak-password-blocking-enabled');
    const $firewallWafSqliEnabled = $('#vulntitan-firewall-waf-sqli-enabled');
    const $firewallWafCommandEnabled = $('#vulntitan-firewall-waf-command-enabled');
    const $firewallWafWhitelistPaths = $('#vulntitan-firewall-waf-whitelist-paths');
    const $firewallLearningEnabled = $('#vulntitan-firewall-learning-enabled');
    const $firewallLearningThreshold = $('#vulntitan-firewall-learning-threshold');
    const $firewallLearningWindow = $('#vulntitan-firewall-learning-window');
    const $firewallLearningRefresh = $('#vulntitan-firewall-learning-refresh');
    const $firewallLearningList = $('#vulntitan-firewall-learning-list');
    const $firewallLearningEmpty = $('#vulntitan-firewall-learning-empty');
    const $firewallTrustCloudflare = $('#vulntitan-firewall-trust-cloudflare');
    const $firewallTrustedProxies = $('#vulntitan-firewall-trusted-proxies');
    const $firewallProxyAlert = $('#vulntitan-firewall-proxy-alert');
    const $firewallProxyMissing = $('#vulntitan-firewall-proxy-missing');
    const $firewallMaxAttempts = $('#vulntitan-firewall-max-attempts');
    const $firewallLockoutMinutes = $('#vulntitan-firewall-lockout-minutes');
    const $firewallCommentShieldEnabled = $('#vulntitan-firewall-comment-shield-enabled');
    const $firewallFormShieldEnabled = $('#vulntitan-firewall-form-shield-enabled');
    const $firewallFormProviderCf7Enabled = $('#vulntitan-firewall-form-provider-cf7-enabled');
    const $firewallFormProviderFluentFormsEnabled = $('#vulntitan-firewall-form-provider-fluentforms-enabled');
    const $firewallCommentSuspiciousAction = $('#vulntitan-firewall-comment-suspicious-action');
    const $firewallSubmissionMinSubmitSeconds = $('#vulntitan-firewall-submission-min-submit-seconds');
    const $firewallSubmissionMaxLinks = $('#vulntitan-firewall-submission-max-links');
    const $firewallSubmissionRateLimitAttempts = $('#vulntitan-firewall-submission-rate-limit-attempts');
    const $firewallSubmissionRateLimitWindowMinutes = $('#vulntitan-firewall-submission-rate-limit-window-minutes');
    const $firewallLogRetention = $('#vulntitan-firewall-log-retention');
    const $firewallLockoutAllowlist = $('#vulntitan-firewall-lockout-allowlist');
    const $firewallWeeklySummaryEmailEnabled = $('#vulntitan-firewall-weekly-summary-email-enabled');
    const $firewallWeeklySummaryEmailRecipient = $('#vulntitan-firewall-weekly-summary-email-recipient');
    const $firewallApprovalsList = $('#vulntitan-firewall-approvals-list');
    const $firewallApprovalsEmpty = $('#vulntitan-firewall-approvals-empty');
    const $firewallApprovalsCount = $('#vulntitan-firewall-approvals-count');
    const $firewallSaveSettings = $('#vulntitan-firewall-save-settings');
    const $firewallRefresh = $('#vulntitan-firewall-refresh');
    const $firewallClearLogs = $('#vulntitan-firewall-clear-logs');
    const $firewallPruneLogs = $('#vulntitan-firewall-prune-logs');
    const $firewallTabs = $firewallRoot.find('[data-firewall-tab]');
    const $firewallTabPanels = $firewallRoot.find('[data-firewall-tab-panel]');
    const i18n = (window.VulnTitan && window.VulnTitan.i18n) ? window.VulnTitan.i18n : {};
    const state = {
        hardBusy: false,
        requestInFlight: false,
        feedPaused: false,
        activeFilter: 'all',
        searchTerm: '',
        allLogs: [],
        approvals: [],
        learningSuggestions: [],
        learningLoaded: false,
        learningLoading: false,
        selectedLogId: '',
        visibleLogLimit: LOG_PAGE_SIZE,
        lastUpdatedAt: null,
        lastRefreshFailed: false,
        refreshTimerId: null,
        proxyStatus: {}
    };
    let latestMuLoaderStatus = null;
    let feedbackTimer = null;
    let feedbackHideTimer = null;

    function isInstalledProviderControl($control) {
        return String($control.data('providerInstalled') || '1') === '1';
    }

    function escapeHtml(value) {
        return String(value == null ? '' : value).replace(/[&<>"']/g, function (match) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            }[match];
        });
    }

    function clearFeedbackTimers() {
        if (feedbackTimer) {
            window.clearTimeout(feedbackTimer);
            feedbackTimer = null;
        }

        if (feedbackHideTimer) {
            window.clearTimeout(feedbackHideTimer);
            feedbackHideTimer = null;
        }
    }

    function dismissFeedback() {
        clearFeedbackTimers();

        $firewallFeedback.removeClass('is-visible');
        feedbackHideTimer = window.setTimeout(function () {
            $firewallFeedback.hide().empty();
            feedbackHideTimer = null;
        }, 180);
    }

    function getFeedbackConfig(type) {
        switch (type) {
            case 'success':
                return {
                    label: i18n.firewall_toast_success || 'Saved',
                    duration: 3200
                };
            case 'warning':
                return {
                    label: i18n.firewall_toast_warning || 'Review',
                    duration: 5200
                };
            case 'error':
                return {
                    label: i18n.firewall_toast_error || 'Error',
                    duration: 6200
                };
            default:
                return {
                    label: i18n.firewall_toast_info || 'Working',
                    duration: 0
                };
        }
    }

    function setFeedback(type, message) {
        if (!message) {
            dismissFeedback();
            return;
        }

        const normalizedType = (type === 'success' || type === 'error' || type === 'warning') ? type : 'info';
        const config = getFeedbackConfig(normalizedType);
        const liveMode = normalizedType === 'error' ? 'assertive' : 'polite';

        clearFeedbackTimers();

        $firewallFeedback
            .html(`
                <div class="vulntitan-firewall-toast is-${normalizedType}" role="status" aria-live="${liveMode}">
                    <span class="vulntitan-firewall-toast-badge">${escapeHtml(config.label)}</span>
                    <div class="vulntitan-firewall-toast-message">${escapeHtml(message)}</div>
                    <button type="button" class="vulntitan-firewall-toast-close" data-firewall-toast-close aria-label="${escapeHtml(i18n.firewall_toast_close || 'Dismiss notification')}">x</button>
                </div>
            `)
            .show();

        window.requestAnimationFrame(function () {
            $firewallFeedback.addClass('is-visible');
        });

        if (config.duration > 0) {
            feedbackTimer = window.setTimeout(function () {
                dismissFeedback();
            }, config.duration);
        }
    }

    function isFormBlockedRow(row) {
        if (!row) {
            return false;
        }

        const eventType = String(row.event_type || '').toLowerCase();
        const source = String(row.event_source || '').toLowerCase();

        return eventType === 'request_blocked' && (
            source === 'contact_form_7' ||
            source === 'fluent_forms'
        );
    }

    function isWafBlockedRow(row) {
        if (!row) {
            return false;
        }

        const eventType = String(row.event_type || '').toLowerCase();

        return eventType === 'request_blocked' && !isFormBlockedRow(row);
    }

    function getEventLabel(logOrEventType) {
        if (typeof logOrEventType === 'object' && isFormBlockedRow(logOrEventType)) {
            return i18n.firewall_event_form_blocked || 'Form blocked';
        }

        const eventType = typeof logOrEventType === 'object'
            ? String(logOrEventType.event_type || '').toLowerCase()
            : String(logOrEventType || '').toLowerCase();

        switch (eventType) {
            case 'login_failed':
                return i18n.firewall_event_login_failed || 'Login failed';
            case 'login_blocked':
                return i18n.firewall_event_login_blocked || 'Login blocked';
            case 'login_lockout':
                return i18n.firewall_event_login_lockout || 'IP lockout';
            case 'login_recovered':
                return i18n.firewall_event_login_recovered || 'Login recovered';
            case 'request_blocked':
                return i18n.firewall_event_request_blocked || 'Request blocked';
            case 'comment_spam_blocked':
                return i18n.firewall_event_comment_spam_blocked || 'Comment spam blocked';
            case 'comment_spam_held':
                return i18n.firewall_event_comment_spam_held || 'Comment held for review';
            case 'comment_pending_review':
                return i18n.firewall_event_comment_pending_review || 'Comment entered pending review';
            case 'comment_rate_limited':
                return i18n.firewall_event_comment_rate_limited || 'Comment rate limited';
            default:
                return i18n.firewall_event_unknown || 'Unknown event';
        }
    }

    function getEventBadgeClass(eventType) {
        switch (String(eventType || '').toLowerCase()) {
            case 'request_blocked':
            case 'login_blocked':
            case 'login_lockout':
            case 'comment_spam_blocked':
            case 'comment_rate_limited':
                return 'is-danger';
            case 'comment_spam_held':
            case 'comment_pending_review':
            case 'login_failed':
                return 'is-warning';
            case 'login_recovered':
                return 'is-success';
            default:
                return 'is-info';
        }
    }

    function isTruthy(value) {
        return value === true || value === 1 || value === '1';
    }

    function buildRequestLine(row) {
        const method = String(row.request_method || '').trim();
        const target = String(row.request_uri || row.request_path || '/').trim() || '/';
        return `${method} ${target}`.trim();
    }

    function formatLocalTime(date) {
        if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
            return '';
        }

        try {
            return date.toLocaleTimeString([], {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        } catch (error) {
            return date.toTimeString().slice(0, 8);
        }
    }

    function isEmptyStructuredValue(value) {
        if (value == null || value === '') {
            return true;
        }

        if (Array.isArray(value)) {
            return value.length === 0;
        }

        if (typeof value === 'object') {
            return Object.keys(value).length === 0;
        }

        return false;
    }

    function formatValue(value, emptyFallback) {
        if (value == null || value === '') {
            return emptyFallback || (i18n.firewall_feed_none || 'n/a');
        }

        if (typeof value === 'boolean') {
            return value ? (i18n.firewall_feed_yes || 'Yes') : (i18n.firewall_feed_no || 'No');
        }

        if (Array.isArray(value)) {
            return value.length ? value.join(', ') : (emptyFallback || (i18n.firewall_feed_none || 'n/a'));
        }

        if (typeof value === 'object') {
            try {
                return JSON.stringify(value);
            } catch (error) {
                return emptyFallback || (i18n.firewall_feed_none || 'n/a');
            }
        }

        return String(value);
    }

    function formatFlag(value) {
        return isTruthy(value) ? (i18n.firewall_feed_yes || 'Yes') : (i18n.firewall_feed_no || 'No');
    }

    function updateFeedChrome() {
        let statusClass = 'is-live';
        let statusLabel = i18n.firewall_feed_live || 'Live';
        let metaText = i18n.firewall_feed_meta_live || 'Auto-refresh every 5 seconds';

        if (state.feedPaused) {
            statusClass = 'is-paused';
            statusLabel = i18n.firewall_feed_paused || 'Paused';
            metaText = i18n.firewall_feed_meta_paused || 'Live updates are paused';
        } else if (state.requestInFlight) {
            statusClass = 'is-updating';
            statusLabel = i18n.firewall_feed_updating || 'Updating';
        } else if (state.lastRefreshFailed) {
            statusClass = 'is-warning';
            metaText = i18n.firewall_feed_meta_failed || 'Refresh failed. Showing last successful snapshot.';
        } else if (state.lastUpdatedAt instanceof Date) {
            metaText = `${i18n.firewall_feed_updated_prefix || 'Updated'} ${formatLocalTime(state.lastUpdatedAt)} · ${i18n.firewall_feed_meta_live || 'Auto-refresh every 5 seconds'}`;
        }

        $firewallFeedStatus
            .removeClass('is-live is-paused is-updating is-warning')
            .addClass(statusClass)
            .text(statusLabel);

        $firewallFeedMeta.text(metaText);
        $firewallFeedToggle.text(state.feedPaused ? (i18n.firewall_feed_resume || 'Resume') : (i18n.firewall_feed_pause || 'Pause'));
    }

    function renderOverview(summary, muLoader) {
        const data = summary || {};
        const mu = muLoader || {};
        const muInstalled = !!mu.installed;
        const muStatusLabel = muInstalled
            ? (i18n.firewall_mu_active || 'MU loader active')
            : (i18n.firewall_mu_inactive || 'MU loader inactive');
        const runtimePathHtml = mu.path
            ? `<code class="vulntitan-firewall-runtime-path">${escapeHtml(mu.path)}</code>`
            : '';
        const runtimeErrorHtml = mu.error
            ? `<div class="vulntitan-firewall-runtime-error">${escapeHtml(mu.error)}</div>`
            : '';

        $firewallOverview.html(`
            <div class="vulntitan-firewall-overview-grid">
                <article class="vulntitan-firewall-stat-card is-info">
                    <span class="vulntitan-firewall-stat-label">${escapeHtml(i18n.firewall_overview_total || 'Events (24h)')}</span>
                    <strong class="vulntitan-firewall-stat-value">${Number(data.total || 0)}</strong>
                </article>
                <article class="vulntitan-firewall-stat-card is-danger">
                    <span class="vulntitan-firewall-stat-label">${escapeHtml(i18n.firewall_overview_blocked || 'Blocked (24h)')}</span>
                    <strong class="vulntitan-firewall-stat-value">${Number(data.blocked || 0)}</strong>
                </article>
                <article class="vulntitan-firewall-stat-card is-accent">
                    <span class="vulntitan-firewall-stat-label">${escapeHtml(i18n.firewall_overview_forms_blocked || 'Forms Blocked (24h)')}</span>
                    <strong class="vulntitan-firewall-stat-value">${Number(data.forms_blocked || 0)}</strong>
                </article>
                <article class="vulntitan-firewall-stat-card is-warning">
                    <span class="vulntitan-firewall-stat-label">${escapeHtml(i18n.firewall_overview_login_failed || 'Login Failed (24h)')}</span>
                    <strong class="vulntitan-firewall-stat-value">${Number(data.login_failed || 0)}</strong>
                </article>
                <article class="vulntitan-firewall-stat-card is-accent">
                    <span class="vulntitan-firewall-stat-label">${escapeHtml(i18n.firewall_overview_lockouts || 'Lockouts (24h)')}</span>
                    <strong class="vulntitan-firewall-stat-value">${Number(data.lockouts || 0)}</strong>
                </article>
                <article class="vulntitan-firewall-stat-card is-danger">
                    <span class="vulntitan-firewall-stat-label">${escapeHtml(i18n.firewall_overview_spam_blocked || 'Spam Blocked (24h)')}</span>
                    <strong class="vulntitan-firewall-stat-value">${Number(data.spam_blocked || 0)}</strong>
                </article>
                <article class="vulntitan-firewall-stat-card is-warning">
                    <span class="vulntitan-firewall-stat-label">${escapeHtml(i18n.firewall_overview_spam_held || 'Spam Held (24h)')}</span>
                    <strong class="vulntitan-firewall-stat-value">${Number(data.spam_held || 0)}</strong>
                </article>
            </div>
            <div class="vulntitan-firewall-runtime ${muInstalled ? 'is-active' : 'is-inactive'}">
                <span class="vulntitan-firewall-runtime-dot" aria-hidden="true"></span>
                <span class="vulntitan-firewall-runtime-label">${escapeHtml(muStatusLabel)}</span>
                ${runtimePathHtml}
            </div>
            ${runtimeErrorHtml}
        `);
    }

    function renderLoginAccess(loginAccess) {
        const data = loginAccess || {};
        const customUrl = String(data.url || '').trim();

        if (!customUrl) {
            $firewallCustomLoginUrl.text(
                i18n.firewall_custom_login_disabled || 'Custom login URL is disabled. Leave the slug blank to keep the default WordPress login endpoints.'
            );
            return;
        }

        $firewallCustomLoginUrl.text(customUrl);
    }

    function getLocationTabId() {
        const hash = window.location.hash ? String(window.location.hash).replace('#', '') : '';
        const normalized = hash.replace(/^tab-/, '').trim();
        if (!normalized) {
            return '';
        }

        return $firewallTabs.filter(`[data-firewall-tab="${normalized}"]`).length ? normalized : '';
    }

    function updateTabHash(tabId) {
        const normalizedTab = String(tabId || '').trim();
        if (!normalizedTab) {
            return;
        }

        const newHash = `#${normalizedTab}`;
        if (window.location.hash === newHash) {
            return;
        }

        if (window.history && window.history.replaceState) {
            window.history.replaceState(null, document.title, newHash);
        } else {
            window.location.hash = normalizedTab;
        }
    }

    function activateTab(tabId) {
        const normalizedTab = String(tabId || '').trim();
        if (!normalizedTab) {
            return;
        }

        $firewallTabs.each(function () {
            const $tab = $(this);
            const isActive = String($tab.data('firewallTab')) === normalizedTab;

            $tab
                .toggleClass('is-active', isActive)
                .attr('aria-selected', isActive ? 'true' : 'false')
                .attr('tabindex', isActive ? '0' : '-1');
        });

        $firewallTabPanels.each(function () {
            const $panel = $(this);
            const isActive = String($panel.data('firewallTabPanel')) === normalizedTab;

            $panel
                .toggleClass('is-active', isActive)
                .prop('hidden', !isActive);
        });

        if (normalizedTab === 'waf') {
            maybeLoadLearningSuggestions(false);
        }
    }

    function refreshIdentityControlState() {
        const isTwoFactorEnabled = $firewallTwoFactorEnabled.is(':checked');
        const captchaProvider = String($firewallCaptchaProvider.val() || 'none');
        const hasCaptchaProvider = captchaProvider !== 'none';
        const isXmlrpcRateLimit = String($firewallXmlrpcPolicy.val() || 'allow') === 'rate_limit';

        $firewallTwoFactorRoles.prop('disabled', state.hardBusy || !isTwoFactorEnabled);
        $firewallTrustedDeviceDays.prop('disabled', state.hardBusy || !isTwoFactorEnabled);
        $firewallCaptchaSiteKey.prop('disabled', state.hardBusy || !hasCaptchaProvider);
        $firewallCaptchaSecretKey.prop('disabled', state.hardBusy || !hasCaptchaProvider);
        $firewallCaptchaLoginEnabled.prop('disabled', state.hardBusy || !hasCaptchaProvider);
        $firewallCaptchaRegisterEnabled.prop('disabled', state.hardBusy || !hasCaptchaProvider);
        $firewallCaptchaWooCommerceLoginEnabled.prop('disabled', state.hardBusy || !hasCaptchaProvider || !isInstalledProviderControl($firewallCaptchaWooCommerceLoginEnabled));
        $firewallCaptchaWooCommerceRegisterEnabled.prop('disabled', state.hardBusy || !hasCaptchaProvider || !isInstalledProviderControl($firewallCaptchaWooCommerceRegisterEnabled));
        $firewallCaptchaLostPasswordEnabled.prop('disabled', state.hardBusy || !hasCaptchaProvider);
        $firewallCaptchaCommentEnabled.prop('disabled', state.hardBusy || !hasCaptchaProvider);
        $firewallXmlrpcRateLimitAttempts.prop('disabled', state.hardBusy || !isXmlrpcRateLimit);
        $firewallXmlrpcRateLimitWindowMinutes.prop('disabled', state.hardBusy || !isXmlrpcRateLimit);
    }

    function updateProxyWarnings() {
        const hasForwarded = !!(state.proxyStatus && state.proxyStatus.has_forwarded_headers);
        const hasTrustedConfig = $firewallTrustCloudflare.is(':checked')
            || String($firewallTrustedProxies.val() || '').trim() !== '';

        if ($firewallProxyAlert.length) {
            $firewallProxyAlert.toggle(hasForwarded && !hasTrustedConfig);
        }

        if ($firewallProxyMissing.length) {
            $firewallProxyMissing.toggle(!hasForwarded && hasTrustedConfig);
        }
    }

    function applySettings(settings) {
        const data = settings || {};

        $firewallEnabled.prop('checked', !!Number(data.enabled || 0));
        $firewallLoginProtection.prop('checked', !!Number(data.login_protection_enabled || 0));
        $firewallCustomLoginSlug.val(String(data.custom_login_slug || ''));
        $firewallTwoFactorEnabled.prop('checked', !!Number(data.two_factor_enabled || 0));
        $firewallTwoFactorRoles.val(Array.isArray(data.two_factor_roles) ? data.two_factor_roles : []);
        $firewallTrustedDeviceDays.val(Number(data.trusted_device_days || 30));
        $firewallCaptchaProvider.val(String(data.captcha_provider || 'none'));
        $firewallCaptchaSiteKey.val(String(data.captcha_site_key || ''));
        $firewallCaptchaSecretKey.val(String(data.captcha_secret_key || ''));
        $firewallCaptchaLoginEnabled.prop('checked', !!Number(data.captcha_login_enabled || 0));
        $firewallCaptchaRegisterEnabled.prop('checked', !!Number(data.captcha_register_enabled || 0));
        $firewallCaptchaWooCommerceLoginEnabled.prop('checked', !!Number(data.captcha_woocommerce_login_enabled || 0));
        $firewallCaptchaWooCommerceRegisterEnabled.prop('checked', !!Number(data.captcha_woocommerce_register_enabled || 0));
        $firewallCaptchaLostPasswordEnabled.prop('checked', !!Number(data.captcha_lostpassword_enabled || 0));
        $firewallCaptchaCommentEnabled.prop('checked', !!Number(data.captcha_comment_enabled || 0));
        $firewallXmlrpcPolicy.val(String(data.xmlrpc_policy || 'allow'));
        $firewallXmlrpcAllowlist.val(
            Array.isArray(data.xmlrpc_allowlist_ips) ? data.xmlrpc_allowlist_ips.join('\n') : ''
        );
        $firewallXmlrpcRateLimitAttempts.val(Number(data.xmlrpc_rate_limit_attempts || 20));
        $firewallXmlrpcRateLimitWindowMinutes.val(Number(data.xmlrpc_rate_limit_window_minutes || 10));
        $firewallWeakPasswordBlockingEnabled.prop('checked', !!Number(data.weak_password_blocking_enabled || 0));
        $firewallWafSqliEnabled.prop('checked', !!Number(data.waf_sqli_enabled || 0));
        $firewallWafCommandEnabled.prop('checked', !!Number(data.waf_command_injection_enabled || 0));
        $firewallWafWhitelistPaths.val(
            Array.isArray(data.waf_whitelist_paths) ? data.waf_whitelist_paths.join('\n') : ''
        );
        $firewallLearningEnabled.prop('checked', !!Number(data.learning_mode_enabled || 0));
        $firewallLearningThreshold.val(Number(data.learning_suggestion_threshold || 3));
        $firewallLearningWindow.val(Number(data.learning_suggestion_window_days || 7));
        $firewallTrustCloudflare.prop('checked', !!Number(data.trust_cloudflare || 0));
        $firewallTrustedProxies.val(
            Array.isArray(data.trusted_proxies) ? data.trusted_proxies.join('\n') : ''
        );
        $firewallMaxAttempts.val(Number(data.max_attempts || 5));
        $firewallLockoutMinutes.val(Number(data.lockout_minutes || 15));
        $firewallCommentShieldEnabled.prop('checked', !!Number(data.comment_shield_enabled || 0));
        $firewallFormShieldEnabled.prop('checked', !!Number(data.form_shield_enabled || 0));
        $firewallFormProviderCf7Enabled.prop('checked', !!Number(data.form_provider_cf7_enabled || data.cf7_shield_enabled || 0));
        $firewallFormProviderFluentFormsEnabled.prop('checked', !!Number(data.form_provider_fluentforms_enabled || 0));
        $firewallCommentSuspiciousAction.val(String(data.comment_suspicious_action || 'hold'));
        $firewallSubmissionMinSubmitSeconds.val(Number(data.submission_min_submit_seconds || data.comment_min_submit_seconds || 3));
        $firewallSubmissionMaxLinks.val(Number(data.submission_max_links || data.comment_max_links || 2));
        $firewallSubmissionRateLimitAttempts.val(Number(data.submission_rate_limit_attempts || data.comment_rate_limit_attempts || 3));
        $firewallSubmissionRateLimitWindowMinutes.val(Number(data.submission_rate_limit_window_minutes || data.comment_rate_limit_window_minutes || 10));
        $firewallLogRetention.val(Number(data.log_retention_days || 30));
        $firewallLockoutAllowlist.val(
            Array.isArray(data.lockout_allowlist_ips) ? data.lockout_allowlist_ips.join('\n') : ''
        );
        $firewallWeeklySummaryEmailEnabled.prop('checked', !!Number(data.weekly_summary_email_enabled || 0));
        $firewallWeeklySummaryEmailRecipient.val(String(data.weekly_summary_email_recipient || ''));
        refreshIdentityControlState();
        updateProxyWarnings();
    }

    function matchesFeedFilter(row) {
        const eventType = String(row.event_type || '').toLowerCase();

        switch (state.activeFilter) {
            case 'blocked':
                return isTruthy(row.blocked) || eventType === 'request_blocked' || eventType === 'login_blocked' || eventType === 'login_lockout';
            case 'forms':
                return isFormBlockedRow(row);
            case 'login':
                return eventType.indexOf('login_') === 0;
            case 'spam':
                return eventType.indexOf('comment_') === 0;
            case 'waf':
                return isWafBlockedRow(row);
            default:
                return true;
        }
    }

    function matchesFeedSearch(row) {
        if (!state.searchTerm) {
            return true;
        }

        const haystack = [
            row.ip_address,
            row.username,
            row.request_uri,
            row.request_path,
            row.request_host,
            row.reason,
            row.rule_id,
            row.rule_group,
            row.matched_pattern
        ].join(' ').toLowerCase();

        return haystack.indexOf(state.searchTerm) !== -1;
    }

    function getVisibleLogs() {
        return state.allLogs.filter(function (row) {
            return matchesFeedFilter(row) && matchesFeedSearch(row);
        });
    }

    function resetVisibleLogLimit() {
        state.visibleLogLimit = LOG_PAGE_SIZE;
    }

    function buildFeedSummary(visibleCount, totalCount) {
        if (!totalCount) {
            return '';
        }

        return `${i18n.firewall_feed_showing_prefix || 'Showing'} ${visibleCount} ${i18n.firewall_feed_of || 'of'} ${totalCount} ${i18n.firewall_feed_events || 'events'}`;
    }

    function buildDetailSection(title, contentHtml) {
        if (!contentHtml) {
            return '';
        }

        return `
            <section class="vulntitan-firewall-detail-section">
                <h4 class="vulntitan-firewall-detail-section-title">${escapeHtml(title)}</h4>
                ${contentHtml}
            </section>
        `;
    }

    function buildKeyValueGrid(items) {
        const rows = items.filter(function (item) {
            return item && item.value != null && item.value !== '';
        });

        if (!rows.length) {
            return '';
        }

        return `
            <dl class="vulntitan-firewall-detail-grid">
                ${rows.map(function (item) {
                    return `
                        <div class="vulntitan-firewall-detail-cell">
                            <dt>${escapeHtml(item.label)}</dt>
                            <dd>${escapeHtml(item.value)}</dd>
                        </div>
                    `;
                }).join('')}
            </dl>
        `;
    }

    function buildStructuredBlock(value) {
        if (isEmptyStructuredValue(value)) {
            return '';
        }

        let serialized = '';

        try {
            serialized = JSON.stringify(value, null, 2);
        } catch (error) {
            serialized = String(value);
        }

        if (!serialized) {
            return '';
        }

        return `<pre class="vulntitan-firewall-detail-pre">${escapeHtml(serialized)}</pre>`;
    }

    function isLockoutEventType(eventType) {
        const normalized = String(eventType || '');
        return normalized === 'login_lockout' || normalized === 'login_blocked';
    }

    function buildLockoutActions(log) {
        if (!log || !isLockoutEventType(log.event_type)) {
            return '';
        }

        const ipAddress = String(log.ip_address || '').trim();
        if (!ipAddress) {
            return '';
        }

        return `
            <div class="vulntitan-firewall-detail-actions">
                <button type="button" class="vulntitan-fw-btn vulntitan-fw-btn-danger" data-firewall-unblock-ip="${escapeHtml(ipAddress)}">
                    ${escapeHtml(i18n.firewall_lockout_unblock || 'Unblock IP')}
                </button>
                <button type="button" class="vulntitan-fw-btn vulntitan-fw-btn-secondary" data-firewall-allowlist-ip="${escapeHtml(ipAddress)}">
                    ${escapeHtml(i18n.firewall_lockout_allowlist || 'Add to allowlist')}
                </button>
            </div>
        `;
    }

    function renderLogDetail(log) {
        if (!log) {
            $firewallLogDetail.prop('hidden', true).empty();
            return;
        }

        const detailHtml = `
            <div class="vulntitan-firewall-detail-card">
                <div class="vulntitan-firewall-detail-head">
                    <div class="vulntitan-firewall-detail-head-copy">
                        <span class="vulntitan-firewall-log-badge ${escapeHtml(getEventBadgeClass(log.event_type || ''))}">
                            ${escapeHtml(getEventLabel(log))}
                        </span>
                        <time class="vulntitan-firewall-log-time">${escapeHtml(log.created_at_local || log.created_at || '')}</time>
                    </div>
                    <button type="button" class="vulntitan-firewall-detail-close" data-firewall-detail-close>
                        ${escapeHtml(i18n.firewall_feed_close_details || 'Close details')}
                    </button>
                </div>
                <div class="vulntitan-firewall-detail-request">${escapeHtml(buildRequestLine(log))}</div>
                ${buildDetailSection(
                    i18n.firewall_feed_request || 'Request',
                    buildKeyValueGrid([
                        { label: 'Host', value: formatValue(log.request_host, '') },
                        { label: 'Path', value: formatValue(log.request_path, '') },
                        { label: 'Scheme', value: formatValue(log.request_scheme, '') },
                        { label: 'Request ID', value: formatValue(log.request_id, '') },
                        { label: 'Response', value: Number(log.response_code || 0) > 0 ? String(log.response_code) : '' },
                        { label: 'Referer', value: formatValue(log.referer, '') },
                        { label: 'User-Agent', value: formatValue(log.user_agent, '') }
                    ])
                )}
                ${buildDetailSection(
                    i18n.firewall_feed_actor || 'Actor',
                    buildKeyValueGrid([
                        { label: 'IP', value: formatValue(log.ip_address, '') },
                        { label: 'Forwarded For', value: formatValue(log.forwarded_for, '') },
                        { label: 'Country', value: formatValue(log.country_code, '') },
                        { label: 'User', value: formatValue(log.username, '') },
                        { label: 'User ID', value: Number(log.user_id || 0) > 0 ? String(log.user_id) : '' },
                        { label: 'Session', value: formatValue(log.session_id, '') },
                        { label: 'Source', value: formatValue(log.event_source, '') }
                    ])
                )}
                ${buildDetailSection(
                    i18n.firewall_feed_detection || 'Detection',
                    buildKeyValueGrid([
                        { label: 'Action', value: formatValue(log.event_action, '') },
                        { label: 'Severity', value: Number(log.severity || 0) > 0 ? String(log.severity) : '' },
                        { label: 'Rule ID', value: formatValue(log.rule_id, '') },
                        { label: 'Rule Group', value: formatValue(log.rule_group, '') },
                        { label: 'Pattern', value: formatValue(log.matched_pattern, '') },
                        { label: 'Blocked', value: formatFlag(log.blocked) }
                    ])
                )}
                ${buildDetailSection(
                    i18n.firewall_feed_flags || 'Flags',
                    buildKeyValueGrid([
                        { label: 'Authenticated', value: formatFlag(log.is_authenticated) },
                        { label: 'AJAX', value: formatFlag(log.is_ajax) },
                        { label: 'REST', value: formatFlag(log.is_rest) },
                        { label: 'XML-RPC', value: formatFlag(log.is_xmlrpc) },
                        { label: 'WP Login', value: formatFlag(log.is_wp_login) }
                    ])
                )}
                ${buildDetailSection(
                    i18n.firewall_feed_reason || 'Reason',
                    log.reason ? `<div class="vulntitan-firewall-detail-copy">${escapeHtml(log.reason)}</div>` : ''
                )}
                ${buildLockoutActions(log)}
                ${buildDetailSection(i18n.firewall_feed_details || 'Details', buildStructuredBlock(log.details))}
                ${buildDetailSection(i18n.firewall_feed_context || 'Context', buildStructuredBlock(log.context))}
            </div>
        `;

        $firewallLogDetail.html(detailHtml).prop('hidden', false);
    }

    function renderFeed() {
        const filteredLogs = getVisibleLogs();
        const totalLogs = state.allLogs.length;
        const filteredTotal = filteredLogs.length;
        const visibleLimit = Math.max(state.visibleLogLimit || LOG_PAGE_SIZE, LOG_PAGE_SIZE);
        const visibleLogs = filteredLogs.slice(0, visibleLimit);
        const selectedVisible = visibleLogs.some(function (row) {
            return String(row.id || '') === state.selectedLogId;
        });

        if (!selectedVisible) {
            state.selectedLogId = '';
        }

        $firewallFeedFilters.each(function () {
            const $button = $(this);
            const isActive = String($button.data('firewallFeedFilter')) === state.activeFilter;
            $button.toggleClass('is-active', isActive).attr('aria-pressed', isActive ? 'true' : 'false');
        });

        $firewallFeedSummary.text(buildFeedSummary(visibleLogs.length, filteredTotal));

        if (!visibleLogs.length) {
            $firewallLogsList.empty();
            renderLogDetail(null);
            $firewallLogsEmpty
                .text(totalLogs ? (i18n.firewall_no_filtered_logs || 'No events match the current filters.') : (i18n.firewall_no_logs || 'No firewall events recorded yet.'))
                .show();
            $firewallLoadMore.hide();
            return;
        }

        $firewallLogsEmpty.hide();
        $firewallLogsList.html(visibleLogs.map(function (row) {
            const eventType = String(row.event_type || '');
            const eventClass = getEventBadgeClass(eventType);
            const eventLabel = getEventLabel(row);
            const createdAt = row.created_at_local || row.created_at || '';
            const ipAddress = row.ip_address || '-';
            const username = row.username || '';
            const requestLine = buildRequestLine(row);
            const reason = row.reason || '';
            const source = row.event_source || '';
            const ruleId = row.rule_id || '';
            const isSelected = String(row.id || '') === state.selectedLogId;

            return `
                <button type="button" class="vulntitan-firewall-log-item ${isSelected ? 'is-selected' : ''}" data-firewall-log-id="${escapeHtml(String(row.id || ''))}">
                    <div class="vulntitan-firewall-log-head">
                        <span class="vulntitan-firewall-log-badge ${eventClass}">
                            ${escapeHtml(eventLabel)}
                        </span>
                        <time class="vulntitan-firewall-log-time">${escapeHtml(createdAt)}</time>
                    </div>
                    <div class="vulntitan-firewall-log-request">${escapeHtml(requestLine || '/')}</div>
                    <div class="vulntitan-firewall-log-meta">
                        <span class="vulntitan-firewall-log-meta-item">IP: ${escapeHtml(ipAddress)}</span>
                        ${username ? `<span class="vulntitan-firewall-log-meta-item">User: ${escapeHtml(username)}</span>` : ''}
                        ${source ? `<span class="vulntitan-firewall-log-meta-item">Source: ${escapeHtml(source)}</span>` : ''}
                        ${ruleId ? `<span class="vulntitan-firewall-log-meta-item">Rule: ${escapeHtml(ruleId)}</span>` : ''}
                    </div>
                    ${reason ? `<div class="vulntitan-firewall-log-reason">${escapeHtml(reason)}</div>` : ''}
                </button>
            `;
        }).join(''));

        if (state.selectedLogId) {
            const selectedLog = visibleLogs.find(function (row) {
                return String(row.id || '') === state.selectedLogId;
            }) || null;
            renderLogDetail(selectedLog);
        } else {
            renderLogDetail(null);
        }

        const canLoadMore = filteredTotal > visibleLogs.length;
        if ($firewallLoadMore.length) {
            $firewallLoadMore.toggle(canLoadMore);
            $firewallLoadMore.find('[data-firewall-load-more]').text(i18n.firewall_feed_load_more || 'Load more');
        }
    }

    function applyPayload(payload, options) {
        const data = payload || {};
        const config = $.extend({
            syncSettings: true
        }, options || {});

        latestMuLoaderStatus = data.mu_loader || latestMuLoaderStatus;
        state.allLogs = Array.isArray(data.logs) ? data.logs : [];
        state.approvals = Array.isArray(data.approvals) ? data.approvals : [];
        state.proxyStatus = data.proxy_status || state.proxyStatus || {};
        state.lastUpdatedAt = new Date();
        state.lastRefreshFailed = false;

        if (config.syncSettings) {
            applySettings(data.settings || {});
            renderLoginAccess(data.login_access || {});
            renderLearningSuggestions();
        }

        renderOverview(data.summary || {}, latestMuLoaderStatus || {});
        renderFeed();
        renderApprovals();
        updateFeedChrome();
        updateProxyWarnings();
    }

    function setBusyState(isBusy) {
        state.hardBusy = !!isBusy;

        $firewallRoot.toggleClass('is-busy', !!isBusy);
        $firewallSaveSettings.prop('disabled', !!isBusy);
        $firewallRefresh.prop('disabled', !!isBusy);
        $firewallClearLogs.prop('disabled', !!isBusy);
        $firewallPruneLogs.prop('disabled', !!isBusy);
        $firewallFeedToggle.prop('disabled', !!isBusy);
        $firewallFeedSearch.prop('disabled', !!isBusy);
        $firewallFeedFilters.prop('disabled', !!isBusy);
        $firewallLoadMore.find('[data-firewall-load-more]').prop('disabled', !!isBusy);
        $firewallTabs.prop('disabled', !!isBusy);
        $firewallEnabled.prop('disabled', !!isBusy);
        $firewallLoginProtection.prop('disabled', !!isBusy);
        $firewallCustomLoginSlug.prop('disabled', !!isBusy);
        $firewallTwoFactorEnabled.prop('disabled', !!isBusy);
        $firewallCaptchaProvider.prop('disabled', !!isBusy);
        $firewallXmlrpcPolicy.prop('disabled', !!isBusy);
        $firewallXmlrpcAllowlist.prop('disabled', !!isBusy);
        $firewallWeakPasswordBlockingEnabled.prop('disabled', !!isBusy);
        $firewallWafSqliEnabled.prop('disabled', !!isBusy);
        $firewallWafCommandEnabled.prop('disabled', !!isBusy);
        $firewallWafWhitelistPaths.prop('disabled', !!isBusy);
        $firewallLearningEnabled.prop('disabled', !!isBusy);
        $firewallLearningThreshold.prop('disabled', !!isBusy);
        $firewallLearningWindow.prop('disabled', !!isBusy);
        $firewallLearningRefresh.prop('disabled', !!isBusy);
        $firewallTrustCloudflare.prop('disabled', !!isBusy);
        $firewallTrustedProxies.prop('disabled', !!isBusy);
        $firewallMaxAttempts.prop('disabled', !!isBusy);
        $firewallLockoutMinutes.prop('disabled', !!isBusy);
        $firewallCommentShieldEnabled.prop('disabled', !!isBusy);
        $firewallFormShieldEnabled.prop('disabled', !!isBusy);
        $firewallFormProviderCf7Enabled.prop('disabled', !!isBusy || !isInstalledProviderControl($firewallFormProviderCf7Enabled));
        $firewallFormProviderFluentFormsEnabled.prop('disabled', !!isBusy || !isInstalledProviderControl($firewallFormProviderFluentFormsEnabled));
        $firewallCommentSuspiciousAction.prop('disabled', !!isBusy);
        $firewallSubmissionMinSubmitSeconds.prop('disabled', !!isBusy);
        $firewallSubmissionMaxLinks.prop('disabled', !!isBusy);
        $firewallSubmissionRateLimitAttempts.prop('disabled', !!isBusy);
        $firewallSubmissionRateLimitWindowMinutes.prop('disabled', !!isBusy);
        $firewallLogRetention.prop('disabled', !!isBusy);
        $firewallLockoutAllowlist.prop('disabled', !!isBusy);
        $firewallWeeklySummaryEmailEnabled.prop('disabled', !!isBusy);
        $firewallWeeklySummaryEmailRecipient.prop('disabled', !!isBusy);
        refreshIdentityControlState();
    }

    function loadFirewallData(options) {
        const config = $.extend({
            showLoadingNotice: false,
            hardBusy: false,
            silentError: false,
            clearFeedbackOnSuccess: false,
            syncSettings: false
        }, options || {});

        if (state.requestInFlight) {
            return;
        }

        if (config.hardBusy) {
            setBusyState(true);
        }

        state.requestInFlight = true;
        updateFeedChrome();

        if (config.showLoadingNotice) {
            setFeedback('info', i18n.firewall_refreshing || 'Refreshing firewall data...');
        }

        $.post(VulnTitan.ajaxUrl, {
            action: 'vulntitan_firewall_get_data',
            nonce: VulnTitan.nonce
        }, function (response) {
            if (!response || !response.success) {
                state.lastRefreshFailed = true;
                updateFeedChrome();

                if (!config.silentError) {
                    const message = (response && response.data && response.data.message)
                        ? response.data.message
                        : (i18n.firewall_load_failed || 'Failed to load firewall data.');
                    setFeedback('error', message);
                }
                return;
            }

            applyPayload(response.data || {}, {
                syncSettings: config.syncSettings
            });

            if (config.clearFeedbackOnSuccess) {
                setFeedback('', '');
            }
        }).fail(function () {
            state.lastRefreshFailed = true;
            updateFeedChrome();

            if (!config.silentError) {
                setFeedback('error', i18n.firewall_load_failed || 'Failed to load firewall data.');
            }
        }).always(function () {
            state.requestInFlight = false;
            updateFeedChrome();

            if (config.hardBusy) {
                setBusyState(false);
            }
        });
    }

    function renderApprovals() {
        if (!$firewallApprovalsList.length) {
            return;
        }

        const approvals = Array.isArray(state.approvals) ? state.approvals : [];
        const count = approvals.length;

        if ($firewallApprovalsCount.length) {
            $firewallApprovalsCount
                .text(count ? String(count) : '')
                .toggleClass('is-visible', count > 0);
        }

        if (!count) {
            $firewallApprovalsList.empty();
            $firewallApprovalsEmpty.show();
            return;
        }

        $firewallApprovalsEmpty.hide();
        $firewallApprovalsList.html(approvals.map(renderApprovalItem).join(''));
    }

    function renderApprovalItem(row) {
        const logId = String(row.id || '');
        const createdAt = row.created_at_local || row.created_at || '';
        const requestLine = buildRequestLine(row);
        const ruleGroup = row.rule_group || '';
        const ruleId = row.rule_id || '';
        const reason = row.reason || '';
        const username = row.username || '';
        const action = row.approval_action || '';
        const restRoute = row.approval_rest_route || '';
        const pattern = row.approval_pattern || '';
        const actionLabel = action
            ? `${i18n.firewall_approval_action || 'Action'}: ${action}`
            : (restRoute ? `${i18n.firewall_approval_route || 'Route'}: ${restRoute}` : '');
        const canApprove = !!pattern;
        const patternHtml = pattern
            ? `<div class="vulntitan-firewall-approval-pattern"><span>${escapeHtml(i18n.firewall_approval_pattern || 'Whitelist pattern')}:</span> <code>${escapeHtml(pattern)}</code></div>`
            : `<div class="vulntitan-firewall-approval-pattern is-empty">${escapeHtml(i18n.firewall_approval_no_pattern || 'No safe auto-approval pattern available.')}</div>`;

        return `
            <div class="vulntitan-firewall-log-item vulntitan-firewall-approval-card">
                <div class="vulntitan-firewall-log-head">
                    <span class="vulntitan-firewall-log-badge is-danger">
                        ${escapeHtml(i18n.firewall_event_request_blocked || 'Request blocked')}
                    </span>
                    <time class="vulntitan-firewall-log-time">${escapeHtml(createdAt)}</time>
                </div>
                <div class="vulntitan-firewall-log-request">${escapeHtml(requestLine || '/')}</div>
                <div class="vulntitan-firewall-log-meta">
                    ${ruleGroup ? `<span class="vulntitan-firewall-log-meta-item">Group: ${escapeHtml(ruleGroup)}</span>` : ''}
                    ${ruleId ? `<span class="vulntitan-firewall-log-meta-item">Rule: ${escapeHtml(ruleId)}</span>` : ''}
                    ${actionLabel ? `<span class="vulntitan-firewall-log-meta-item">${escapeHtml(actionLabel)}</span>` : ''}
                    ${username ? `<span class="vulntitan-firewall-log-meta-item">User: ${escapeHtml(username)}</span>` : ''}
                </div>
                ${reason ? `<div class="vulntitan-firewall-log-reason">${escapeHtml(reason)}</div>` : ''}
                ${patternHtml}
                <div class="vulntitan-firewall-approval-actions">
                    <button type="button" class="vulntitan-fw-btn vulntitan-fw-btn-primary" data-firewall-approval-allow="${escapeHtml(logId)}" ${canApprove ? '' : 'disabled'}>
                        ${escapeHtml(i18n.firewall_approval_allow || 'Approve')}
                    </button>
                    <button type="button" class="vulntitan-fw-btn vulntitan-fw-btn-secondary" data-firewall-approval-dismiss="${escapeHtml(logId)}">
                        ${escapeHtml(i18n.firewall_approval_dismiss || 'Dismiss')}
                    </button>
                </div>
            </div>
        `;
    }

    function renderLearningSuggestions() {
        if (!$firewallLearningList.length) {
            return;
        }

        const enabled = $firewallLearningEnabled.is(':checked');
        const suggestions = Array.isArray(state.learningSuggestions) ? state.learningSuggestions : [];

        if (!enabled) {
            $firewallLearningList.empty();
            $firewallLearningEmpty
                .text(i18n.firewall_learning_disabled || 'Learning suggestions are disabled.')
                .show();
            return;
        }

        if (!suggestions.length) {
            $firewallLearningList.empty();
            $firewallLearningEmpty
                .text(i18n.firewall_learning_empty || 'No learning suggestions yet.')
                .show();
            return;
        }

        $firewallLearningEmpty.hide();
        $firewallLearningList.html(suggestions.map(renderLearningItem).join(''));
    }

    function renderLearningItem(item) {
        const pattern = String(item.pattern || '');
        const lastSeen = item.last_seen_local || item.last_seen || '';
        const count = Number(item.count || 0);
        const ruleGroup = item.rule_group || '';
        const ruleId = item.rule_id || '';
        const action = item.approval_action || '';
        const restRoute = item.approval_rest_route || '';
        const actionLabel = action
            ? `${i18n.firewall_approval_action || 'Action'}: ${action}`
            : (restRoute ? `${i18n.firewall_approval_route || 'Route'}: ${restRoute}` : '');

        return `
            <div class="vulntitan-firewall-log-item vulntitan-firewall-approval-card">
                <div class="vulntitan-firewall-log-head">
                    <span class="vulntitan-firewall-log-badge is-warning">
                        ${escapeHtml(i18n.firewall_learning_suggestion || 'Learning suggestion')}
                    </span>
                    <time class="vulntitan-firewall-log-time">${escapeHtml(lastSeen)}</time>
                </div>
                <div class="vulntitan-firewall-log-request">${escapeHtml(pattern || '/')}</div>
                <div class="vulntitan-firewall-log-meta">
                    <span class="vulntitan-firewall-log-meta-item">${escapeHtml(i18n.firewall_learning_hits || 'Hits')}: ${count}</span>
                    ${ruleGroup ? `<span class="vulntitan-firewall-log-meta-item">Group: ${escapeHtml(ruleGroup)}</span>` : ''}
                    ${ruleId ? `<span class="vulntitan-firewall-log-meta-item">Rule: ${escapeHtml(ruleId)}</span>` : ''}
                    ${actionLabel ? `<span class="vulntitan-firewall-log-meta-item">${escapeHtml(actionLabel)}</span>` : ''}
                </div>
                <div class="vulntitan-firewall-approval-pattern">
                    <span>${escapeHtml(i18n.firewall_approval_pattern || 'Whitelist pattern')}:</span>
                    <code>${escapeHtml(pattern)}</code>
                </div>
                <div class="vulntitan-firewall-approval-actions">
                    <button type="button" class="vulntitan-fw-btn vulntitan-fw-btn-primary" data-firewall-learning-allow="${escapeHtml(pattern)}">
                        ${escapeHtml(i18n.firewall_learning_allow || 'Allow')}
                    </button>
                    <button type="button" class="vulntitan-fw-btn vulntitan-fw-btn-secondary" data-firewall-learning-dismiss="${escapeHtml(pattern)}">
                        ${escapeHtml(i18n.firewall_learning_dismiss || 'Dismiss')}
                    </button>
                </div>
            </div>
        `;
    }

    function loadLearningSuggestions(options) {
        if (!$firewallLearningList.length) {
            return;
        }

        const config = $.extend({
            silent: false,
            force: false
        }, options || {});

        if (!$firewallLearningEnabled.is(':checked')) {
            state.learningSuggestions = [];
            renderLearningSuggestions();
            return;
        }

        if (state.learningLoading) {
            return;
        }

        if (state.learningLoaded && !config.force) {
            renderLearningSuggestions();
            return;
        }

        state.learningLoading = true;

        if (!config.silent) {
            setFeedback('info', i18n.firewall_learning_loading || 'Loading learning suggestions...');
        }

        $.post(VulnTitan.ajaxUrl, {
            action: 'vulntitan_firewall_get_learning',
            nonce: VulnTitan.nonce
        }, function (response) {
            if (!response || !response.success) {
                const message = (response && response.data && response.data.message)
                    ? response.data.message
                    : (i18n.firewall_learning_failed || 'Failed to load learning suggestions.');
                if (!config.silent) {
                    setFeedback('error', message);
                }
                return;
            }

            const payload = response.data || {};
            state.learningSuggestions = Array.isArray(payload.suggestions) ? payload.suggestions : [];
            state.learningLoaded = true;
            renderLearningSuggestions();

            if (!config.silent) {
                setFeedback('success', i18n.firewall_learning_updated || 'Learning suggestions updated.');
            }
        }).fail(function () {
            if (!config.silent) {
                setFeedback('error', i18n.firewall_learning_failed || 'Failed to load learning suggestions.');
            }
        }).always(function () {
            state.learningLoading = false;
        });
    }

    function maybeLoadLearningSuggestions(force) {
        if (force) {
            loadLearningSuggestions({ force: true, silent: true });
            return;
        }

        if (!state.learningLoaded) {
            loadLearningSuggestions({ silent: true });
        } else {
            renderLearningSuggestions();
        }
    }

    function saveSettings() {
        if (state.requestInFlight) {
            return;
        }

        const selectedTwoFactorRoles = $firewallTwoFactorRoles.val();
        setBusyState(true);
        state.requestInFlight = true;
        updateFeedChrome();
        setFeedback('info', i18n.firewall_saving || 'Saving firewall settings...');

        $.post(VulnTitan.ajaxUrl, {
            action: 'vulntitan_firewall_save_settings',
            nonce: VulnTitan.nonce,
            enabled: $firewallEnabled.is(':checked') ? 1 : 0,
            login_protection_enabled: $firewallLoginProtection.is(':checked') ? 1 : 0,
            custom_login_slug: String($firewallCustomLoginSlug.val() || ''),
            two_factor_enabled: $firewallTwoFactorEnabled.is(':checked') ? 1 : 0,
            two_factor_roles: Array.isArray(selectedTwoFactorRoles) ? selectedTwoFactorRoles : [],
            trusted_device_days: Number($firewallTrustedDeviceDays.val() || 30),
            captcha_provider: String($firewallCaptchaProvider.val() || 'none'),
            captcha_site_key: String($firewallCaptchaSiteKey.val() || ''),
            captcha_secret_key: String($firewallCaptchaSecretKey.val() || ''),
            captcha_login_enabled: $firewallCaptchaLoginEnabled.is(':checked') ? 1 : 0,
            captcha_register_enabled: $firewallCaptchaRegisterEnabled.is(':checked') ? 1 : 0,
            captcha_woocommerce_login_enabled: $firewallCaptchaWooCommerceLoginEnabled.is(':checked') ? 1 : 0,
            captcha_woocommerce_register_enabled: $firewallCaptchaWooCommerceRegisterEnabled.is(':checked') ? 1 : 0,
            captcha_lostpassword_enabled: $firewallCaptchaLostPasswordEnabled.is(':checked') ? 1 : 0,
            captcha_comment_enabled: $firewallCaptchaCommentEnabled.is(':checked') ? 1 : 0,
            xmlrpc_policy: String($firewallXmlrpcPolicy.val() || 'allow'),
            xmlrpc_allowlist_ips: String($firewallXmlrpcAllowlist.val() || ''),
            xmlrpc_rate_limit_attempts: Number($firewallXmlrpcRateLimitAttempts.val() || 20),
            xmlrpc_rate_limit_window_minutes: Number($firewallXmlrpcRateLimitWindowMinutes.val() || 10),
            weak_password_blocking_enabled: $firewallWeakPasswordBlockingEnabled.is(':checked') ? 1 : 0,
            waf_sqli_enabled: $firewallWafSqliEnabled.is(':checked') ? 1 : 0,
            waf_command_injection_enabled: $firewallWafCommandEnabled.is(':checked') ? 1 : 0,
            waf_whitelist_paths: String($firewallWafWhitelistPaths.val() || ''),
            learning_mode_enabled: $firewallLearningEnabled.is(':checked') ? 1 : 0,
            learning_suggestion_threshold: Number($firewallLearningThreshold.val() || 3),
            learning_suggestion_window_days: Number($firewallLearningWindow.val() || 7),
            trust_cloudflare: $firewallTrustCloudflare.is(':checked') ? 1 : 0,
            trusted_proxies: String($firewallTrustedProxies.val() || ''),
            max_attempts: Number($firewallMaxAttempts.val() || 5),
            lockout_minutes: Number($firewallLockoutMinutes.val() || 15),
            comment_shield_enabled: $firewallCommentShieldEnabled.is(':checked') ? 1 : 0,
            form_shield_enabled: $firewallFormShieldEnabled.is(':checked') ? 1 : 0,
            form_provider_cf7_enabled: $firewallFormProviderCf7Enabled.is(':checked') ? 1 : 0,
            form_provider_fluentforms_enabled: $firewallFormProviderFluentFormsEnabled.is(':checked') ? 1 : 0,
            comment_suspicious_action: String($firewallCommentSuspiciousAction.val() || 'hold'),
            submission_min_submit_seconds: Number($firewallSubmissionMinSubmitSeconds.val() || 3),
            submission_max_links: Number($firewallSubmissionMaxLinks.val() || 2),
            submission_rate_limit_attempts: Number($firewallSubmissionRateLimitAttempts.val() || 3),
            submission_rate_limit_window_minutes: Number($firewallSubmissionRateLimitWindowMinutes.val() || 10),
            log_retention_days: Number($firewallLogRetention.val() || 30),
            lockout_allowlist_ips: String($firewallLockoutAllowlist.val() || ''),
            weekly_summary_email_enabled: $firewallWeeklySummaryEmailEnabled.is(':checked') ? 1 : 0,
            weekly_summary_email_recipient: String($firewallWeeklySummaryEmailRecipient.val() || '')
        }, function (response) {
            if (!response || !response.success) {
                const message = (response && response.data && response.data.message)
                    ? response.data.message
                    : (i18n.firewall_save_failed || 'Failed to save firewall settings.');
                setFeedback('error', message);
                return;
            }

            const payload = response.data || {};
            applyPayload(payload, {
                syncSettings: true
            });

            const activeTab = String($firewallTabs.filter('.is-active').data('firewallTab') || '');
            if (activeTab === 'waf' && $firewallLearningEnabled.is(':checked')) {
                state.learningLoaded = false;
                loadLearningSuggestions({
                    silent: true,
                    force: true
                });
            }

            const muInstall = payload.mu_loader_install || {};
            if (payload.notice) {
                setFeedback('warning', payload.notice);
                return;
            }

            if (muInstall.success === false && muInstall.error) {
                setFeedback('warning', muInstall.error);
                return;
            }

            setFeedback('success', i18n.firewall_settings_saved || 'Firewall settings saved.');
        }).fail(function () {
            setFeedback('error', i18n.firewall_save_failed || 'Failed to save firewall settings.');
        }).always(function () {
            state.requestInFlight = false;
            updateFeedChrome();
            setBusyState(false);
        });
    }

    function applyLogCleanupPayload(payload) {
        state.selectedLogId = '';
        state.allLogs = Array.isArray(payload.logs) ? payload.logs : [];
        state.approvals = Array.isArray(payload.approvals) ? payload.approvals : [];
        state.lastUpdatedAt = new Date();
        state.lastRefreshFailed = false;

        renderOverview(payload.summary || {}, latestMuLoaderStatus || {});
        renderFeed();
        renderApprovals();
        updateFeedChrome();
    }

    function pruneLogs() {
        if (state.requestInFlight) {
            return;
        }

        const confirmMessage = i18n.firewall_confirm_prune || 'Delete firewall logs older than the current retention period?';
        if (!window.confirm(confirmMessage)) {
            return;
        }

        setBusyState(true);
        state.requestInFlight = true;
        updateFeedChrome();
        setFeedback('info', i18n.firewall_pruning || 'Deleting expired firewall logs...');

        $.post(VulnTitan.ajaxUrl, {
            action: 'vulntitan_firewall_prune_logs',
            nonce: VulnTitan.nonce,
            retention_days: Number($firewallLogRetention.val() || 30)
        }, function (response) {
            if (!response || !response.success) {
                const message = (response && response.data && response.data.message)
                    ? response.data.message
                    : (i18n.firewall_prune_failed || 'Failed to delete expired firewall logs.');
                setFeedback('error', message);
                return;
            }

            applyLogCleanupPayload(response.data || {});
            setFeedback('success', i18n.firewall_logs_pruned || 'Expired firewall logs deleted.');
        }).fail(function () {
            setFeedback('error', i18n.firewall_prune_failed || 'Failed to delete expired firewall logs.');
        }).always(function () {
            state.requestInFlight = false;
            updateFeedChrome();
            setBusyState(false);
        });
    }

    function clearLogs() {
        if (state.requestInFlight) {
            return;
        }

        const confirmMessage = i18n.firewall_confirm_clear || 'Permanently delete all firewall logs?';
        if (!window.confirm(confirmMessage)) {
            return;
        }

        setBusyState(true);
        state.requestInFlight = true;
        updateFeedChrome();
        setFeedback('info', i18n.firewall_clearing || 'Clearing firewall logs...');

        $.post(VulnTitan.ajaxUrl, {
            action: 'vulntitan_firewall_clear_logs',
            nonce: VulnTitan.nonce
        }, function (response) {
            if (!response || !response.success) {
                const message = (response && response.data && response.data.message)
                    ? response.data.message
                    : (i18n.firewall_clear_failed || 'Failed to clear firewall logs.');
                setFeedback('error', message);
                return;
            }

            applyLogCleanupPayload(response.data || {});
            setFeedback('success', i18n.firewall_logs_cleared || 'Firewall logs cleared.');
        }).fail(function () {
            setFeedback('error', i18n.firewall_clear_failed || 'Failed to clear firewall logs.');
        }).always(function () {
            state.requestInFlight = false;
            updateFeedChrome();
            setBusyState(false);
        });
    }

    function sendLockoutAction(action, ipAddress, $button, confirmMessage, successMessage) {
        const ip = String(ipAddress || '').trim();
        if (!ip) {
            setFeedback('error', i18n.firewall_ip_invalid || 'Invalid IP address.');
            return;
        }

        if (confirmMessage && !window.confirm(confirmMessage)) {
            return;
        }

        if ($button && $button.length) {
            $button.prop('disabled', true);
        }

        setFeedback('info', i18n.firewall_action_in_progress || 'Working...');

        $.post(VulnTitan.ajaxUrl, {
            action: action,
            nonce: VulnTitan.nonce,
            ip: ip
        }, function (response) {
            if (!response || !response.success) {
                const message = (response && response.data && response.data.message)
                    ? response.data.message
                    : (i18n.firewall_action_failed || 'Action failed.');
                setFeedback('error', message);
                return;
            }

            setFeedback('success', successMessage);
        }).fail(function () {
            setFeedback('error', i18n.firewall_action_failed || 'Action failed.');
        }).always(function () {
            if ($button && $button.length) {
                $button.prop('disabled', false);
            }
        });
    }

    function sendApprovalAction(action, logId, $button, confirmMessage, successMessage) {
        const id = parseInt(logId, 10);
        if (!Number.isInteger(id) || id <= 0) {
            setFeedback('error', i18n.firewall_approval_invalid || 'Invalid approval request.');
            return;
        }

        if (confirmMessage && !window.confirm(confirmMessage)) {
            return;
        }

        if ($button && $button.length) {
            $button.prop('disabled', true);
        }

        setFeedback('info', i18n.firewall_action_in_progress || 'Working...');

        $.post(VulnTitan.ajaxUrl, {
            action: action,
            nonce: VulnTitan.nonce,
            log_id: id
        }, function (response) {
            if (!response || !response.success) {
                const message = (response && response.data && response.data.message)
                    ? response.data.message
                    : (i18n.firewall_action_failed || 'Action failed.');
                setFeedback('error', message);
                return;
            }

            const payload = response.data || {};
            if (payload.settings) {
                applySettings(payload.settings);
            }

            if (Array.isArray(payload.approvals)) {
                state.approvals = payload.approvals;
                renderApprovals();
            }

            setFeedback('success', successMessage);
        }).fail(function () {
            setFeedback('error', i18n.firewall_action_failed || 'Action failed.');
        }).always(function () {
            if ($button && $button.length) {
                $button.prop('disabled', false);
            }
        });
    }

    function sendLearningAction(action, pattern, $button, confirmMessage, successMessage) {
        const cleanPattern = String(pattern || '').trim();
        if (!cleanPattern) {
            setFeedback('error', i18n.firewall_approval_invalid || 'Invalid learning suggestion.');
            return;
        }

        if (confirmMessage && !window.confirm(confirmMessage)) {
            return;
        }

        if ($button && $button.length) {
            $button.prop('disabled', true);
        }

        setFeedback('info', i18n.firewall_action_in_progress || 'Working...');

        $.post(VulnTitan.ajaxUrl, {
            action: action,
            nonce: VulnTitan.nonce,
            pattern: cleanPattern
        }, function (response) {
            if (!response || !response.success) {
                const message = (response && response.data && response.data.message)
                    ? response.data.message
                    : (i18n.firewall_action_failed || 'Action failed.');
                setFeedback('error', message);
                return;
            }

            const payload = response.data || {};
            if (payload.settings) {
                applySettings(payload.settings);
            }

            if (Array.isArray(payload.suggestions)) {
                state.learningSuggestions = payload.suggestions;
                state.learningLoaded = true;
                renderLearningSuggestions();
            }

            setFeedback('success', successMessage);
        }).fail(function () {
            setFeedback('error', i18n.firewall_action_failed || 'Action failed.');
        }).always(function () {
            if ($button && $button.length) {
                $button.prop('disabled', false);
            }
        });
    }

    function handleFeedToggle() {
        state.feedPaused = !state.feedPaused;
        updateFeedChrome();

        if (!state.feedPaused && !state.requestInFlight) {
            loadFirewallData({
                silentError: true
            });
        }
    }

    function startRefreshTimer() {
        if (state.refreshTimerId) {
            window.clearInterval(state.refreshTimerId);
        }

        state.refreshTimerId = window.setInterval(function () {
            if (state.feedPaused || state.hardBusy || state.requestInFlight || document.hidden) {
                return;
            }

            loadFirewallData({
                silentError: true
            });
        }, FEED_REFRESH_INTERVAL_MS);
    }

    $firewallRefresh.off('click').on('click', function () {
        loadFirewallData({
            showLoadingNotice: true,
            hardBusy: true,
            clearFeedbackOnSuccess: true,
            syncSettings: true
        });
    });

    $firewallSaveSettings.off('click').on('click', function () {
        saveSettings();
    });

    $firewallClearLogs.off('click').on('click', function () {
        clearLogs();
    });

    $firewallPruneLogs.off('click').on('click', function () {
        pruneLogs();
    });

    $firewallFeedToggle.off('click').on('click', function () {
        handleFeedToggle();
    });

    $firewallFeedFilters.off('click').on('click', function () {
        state.activeFilter = String($(this).data('firewallFeedFilter') || 'all');
        resetVisibleLogLimit();
        renderFeed();
    });

    $firewallFeedSearch.off('input').on('input', function () {
        state.searchTerm = String($(this).val() || '').trim().toLowerCase();
        resetVisibleLogLimit();
        renderFeed();
    });

    $firewallLogsList.off('click', '[data-firewall-log-id]').on('click', '[data-firewall-log-id]', function () {
        const selectedId = String($(this).data('firewallLogId') || '');

        state.selectedLogId = state.selectedLogId === selectedId ? '' : selectedId;
        renderFeed();
    });

    $firewallLogDetail.off('click', '[data-firewall-detail-close]').on('click', '[data-firewall-detail-close]', function () {
        state.selectedLogId = '';
        renderFeed();
    });

    $firewallLogDetail.off('click', '[data-firewall-unblock-ip]').on('click', '[data-firewall-unblock-ip]', function () {
        const $button = $(this);
        const ipAddress = String($button.data('firewallUnblockIp') || '');
        sendLockoutAction(
            'vulntitan_firewall_unblock_ip',
            ipAddress,
            $button,
            i18n.firewall_confirm_unblock || 'Unblock this IP?',
            i18n.firewall_unblock_success || 'IP unblocked.'
        );
    });

    $firewallLogDetail.off('click', '[data-firewall-allowlist-ip]').on('click', '[data-firewall-allowlist-ip]', function () {
        const $button = $(this);
        const ipAddress = String($button.data('firewallAllowlistIp') || '');
        sendLockoutAction(
            'vulntitan_firewall_allowlist_ip',
            ipAddress,
            $button,
            i18n.firewall_confirm_allowlist || 'Add this IP to the lockout allowlist?',
            i18n.firewall_allowlist_success || 'IP added to lockout allowlist.'
        );
    });

    $firewallApprovalsList.off('click', '[data-firewall-approval-allow]').on('click', '[data-firewall-approval-allow]', function () {
        const $button = $(this);
        const logId = String($button.data('firewallApprovalAllow') || '');
        sendApprovalAction(
            'vulntitan_firewall_approve_request',
            logId,
            $button,
            i18n.firewall_approval_confirm || 'Approve this request and whitelist its pattern?',
            i18n.firewall_approval_success || 'Whitelist updated.'
        );
    });

    $firewallApprovalsList.off('click', '[data-firewall-approval-dismiss]').on('click', '[data-firewall-approval-dismiss]', function () {
        const $button = $(this);
        const logId = String($button.data('firewallApprovalDismiss') || '');
        sendApprovalAction(
            'vulntitan_firewall_dismiss_approval',
            logId,
            $button,
            i18n.firewall_approval_confirm_dismiss || 'Dismiss this approval request?',
            i18n.firewall_approval_dismissed || 'Approval dismissed.'
        );
    });

    $firewallLearningRefresh.off('click').on('click', function () {
        loadLearningSuggestions({
            silent: false,
            force: true
        });
    });

    $firewallLearningEnabled.off('change').on('change', function () {
        if ($firewallLearningEnabled.is(':checked')) {
            state.learningLoaded = false;
            loadLearningSuggestions({
                silent: true,
                force: true
            });
            return;
        }

        state.learningLoaded = false;
        state.learningSuggestions = [];
        renderLearningSuggestions();
    });

    $firewallLearningList.off('click', '[data-firewall-learning-allow]').on('click', '[data-firewall-learning-allow]', function () {
        const $button = $(this);
        const pattern = String($button.data('firewallLearningAllow') || '');
        sendLearningAction(
            'vulntitan_firewall_apply_learning',
            pattern,
            $button,
            i18n.firewall_learning_confirm_allow || 'Allow this suggested pattern and add it to the WAF whitelist?',
            i18n.firewall_approval_success || 'Whitelist updated.'
        );
    });

    $firewallLearningList.off('click', '[data-firewall-learning-dismiss]').on('click', '[data-firewall-learning-dismiss]', function () {
        const $button = $(this);
        const pattern = String($button.data('firewallLearningDismiss') || '');
        sendLearningAction(
            'vulntitan_firewall_dismiss_learning',
            pattern,
            $button,
            i18n.firewall_learning_confirm_dismiss || 'Dismiss this learning suggestion?',
            i18n.firewall_learning_dismissed || 'Learning suggestion dismissed.'
        );
    });

    $firewallLoadMore.off('click', '[data-firewall-load-more]').on('click', '[data-firewall-load-more]', function () {
        state.visibleLogLimit += LOG_PAGE_SIZE;
        renderFeed();
    });

    $firewallFeedback.off('click', '[data-firewall-toast-close]').on('click', '[data-firewall-toast-close]', function () {
        dismissFeedback();
    });

    $firewallTabs.off('click').on('click', function () {
        const tabId = $(this).data('firewallTab');
        activateTab(tabId);
        updateTabHash(tabId);
    });

    $firewallTwoFactorEnabled.off('change').on('change', function () {
        refreshIdentityControlState();
    });

    $firewallCaptchaProvider.off('change').on('change', function () {
        refreshIdentityControlState();
    });

    $firewallXmlrpcPolicy.off('change').on('change', function () {
        refreshIdentityControlState();
    });

    $firewallTrustCloudflare.off('change').on('change', function () {
        updateProxyWarnings();
    });

    $firewallTrustedProxies.off('input').on('input', function () {
        updateProxyWarnings();
    });

    $firewallTabs.off('keydown').on('keydown', function (event) {
        const keys = ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'];
        if (keys.indexOf(event.key) === -1) {
            return;
        }

        event.preventDefault();

        const currentIndex = $firewallTabs.index(this);
        if (currentIndex < 0) {
            return;
        }

        let nextIndex = currentIndex;

        if (event.key === 'Home') {
            nextIndex = 0;
        } else if (event.key === 'End') {
            nextIndex = $firewallTabs.length - 1;
        } else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
            nextIndex = currentIndex === 0 ? $firewallTabs.length - 1 : currentIndex - 1;
        } else if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
            nextIndex = currentIndex === $firewallTabs.length - 1 ? 0 : currentIndex + 1;
        }

        const $nextTab = $firewallTabs.eq(nextIndex);
        const nextTabId = $nextTab.data('firewallTab');
        activateTab(nextTabId);
        updateTabHash(nextTabId);
        $nextTab.trigger('focus');
    });

    $(document).on('visibilitychange', function () {
        if (!document.hidden && !state.feedPaused && !state.requestInFlight && !state.hardBusy) {
            loadFirewallData({
                silentError: true
            });
        }
    });

    activateTab(
        getLocationTabId()
        || $firewallTabs.filter('.is-active').first().data('firewallTab')
        || $firewallTabs.first().data('firewallTab')
    );
    updateFeedChrome();
    startRefreshTimer();
    loadFirewallData({
        silentError: false,
        syncSettings: true
    });
});
