(function () {
    if (window.OpsGateStableUI) {
        return;
    }

    var transientWorkspaceQueryKeys = [
        'opsgate_notice',
        'opsgate_notice_detail',
        'opsgate_validation_notice',
        'opsgate_validation_notice_detail',
        'opsgate_alerts_notice',
        'opsgate_alerts_error',
        'opsgate_alert_destinations_notice',
        'opsgate_alert_destinations_error',
        'opsgate_settings_saved',
        'opsgate_settings_error',
        'opsgate_pairing_error',
        'opsgate_pairing_open',
        'opsgate_export_error',
        'opsgate_export_started',
        'opsgate_link_notice',
        'opsgate_link_notice_detail',
        'opsgate_agency_notice',
        'opsgate_license_error'
    ];
    var workspaceLoading = false;
    var workspacePromise = null;
    var pendingWorkspaceRequest = null;
    var triageTimer = null;
    var reportsTimer = null;
    var inlineStatusTimers = {};
    var selectedRunStorageKey = 'opsgate:selected-source-job';

    function normalizeUrl(rawUrl) {
        try {
            var baseUrl = new URL(window.location.href);
            var url = new URL(rawUrl || window.location.href, baseUrl);
            var path = String(url.pathname || '');
            var isWorkspace = url.searchParams.get('page') === 'opsgate';
            var isWpAdminEndpoint = /\/wp-admin\/(?:admin|admin-ajax|admin-post)\.php$/i.test(path);
            if (!isWorkspace && !isWpAdminEndpoint) {
                return url.toString();
            }
            if (url.origin === window.location.origin) {
                return url.toString();
            }
            return new URL(path + url.search + url.hash, window.location.origin).toString();
        } catch (error) {
            return rawUrl || window.location.href;
        }
    }

    function scrubUrl(rawUrl) {
        try {
            var nextUrl = new URL(normalizeUrl(rawUrl || window.location.href), window.location.origin);
            transientWorkspaceQueryKeys.forEach(function (key) {
                nextUrl.searchParams.delete(key);
            });
            return nextUrl.toString();
        } catch (error) {
            return rawUrl || window.location.href;
        }
    }

    function currentWorkspace() {
        return document.querySelector('.wrap.opsgate-admin');
    }

    function normalizeAnchorId(rawValue) {
        var value = String(rawValue || '');
        if (!value) {
            return '';
        }
        if (value.indexOf('#') !== -1) {
            value = value.split('#').pop();
        }
        return value.replace(/^#/, '').trim();
    }

    function readSelectedRunId() {
        try {
            return String(window.sessionStorage.getItem(selectedRunStorageKey) || '').trim();
        } catch (error) {
            return '';
        }
    }

    function writeSelectedRunId(jobId) {
        var value = String(jobId || '').trim();
        if (!value) {
            return;
        }
        try {
            window.sessionStorage.setItem(selectedRunStorageKey, value);
        } catch (error) {
            // Keep the UI usable even if session storage is unavailable.
        }
    }

    function syncSelectedRunId(root) {
        root = root || document;
        var reportsPanel = root.querySelector('#opsgate-reports-live-panel');
        if (reportsPanel) {
            writeSelectedRunId(
                attr(reportsPanel, 'data-opsgate-current-source-job-id')
                || attr(reportsPanel, 'data-opsgate-rendered-source-job-id')
            );
        }

        var triagePanel = root.querySelector('#opsgate-triage-live-panel');
        if (triagePanel) {
            writeSelectedRunId(
                attr(triagePanel, 'data-opsgate-current-job-id')
                || attr(triagePanel, 'data-opsgate-rendered-run-id')
            );
        }
    }

    function updateWorkspaceHash(anchorId, replace) {
        var normalizedAnchorId = normalizeAnchorId(anchorId);
        if (!normalizedAnchorId || !window.history) {
            return;
        }
        var historyMethod = replace && typeof window.history.replaceState === 'function'
            ? 'replaceState'
            : (typeof window.history.pushState === 'function' ? 'pushState' : '');
        if (!historyMethod) {
            return;
        }
        try {
            var nextUrl = new URL(window.location.href);
            if (nextUrl.hash === '#' + normalizedAnchorId) {
                return;
            }
            nextUrl.hash = normalizedAnchorId;
            window.history[historyMethod]({}, '', nextUrl.toString());
        } catch (error) {
            // Preserve the current URL if parsing fails.
        }
    }

    function applySelectedRunBindings(root) {
        root = root || document;
        var selectedRunId = readSelectedRunId();
        if (!selectedRunId) {
            return;
        }

        Array.prototype.slice.call(root.querySelectorAll('a[href]')).forEach(function (link) {
            if (!isInternalWorkspaceUrl(link.href)) {
                return;
            }
            try {
                var url = new URL(normalizeUrl(link.href), window.location.origin);
                if (url.searchParams.get('tab') !== 'reports') {
                    return;
                }
                if (url.searchParams.get('view_export_job_id')) {
                    return;
                }
                url.searchParams.set('source_job_id', selectedRunId);
                link.href = url.toString();
            } catch (error) {
                // Leave individual links unchanged if URL parsing fails.
            }
        });
    }

    function syncReportsUrlState(panel) {
        if (!panel || !window.history || typeof window.history.replaceState !== 'function') {
            return;
        }
        var selectedRunId = attr(panel, 'data-opsgate-current-source-job-id') || attr(panel, 'data-opsgate-rendered-source-job-id');
        if (!selectedRunId) {
            return;
        }
        try {
            var nextUrl = new URL(window.location.href);
            if (nextUrl.searchParams.get('page') !== 'opsgate' || nextUrl.searchParams.get('tab') !== 'reports') {
                return;
            }
            if (nextUrl.searchParams.get('source_job_id') === selectedRunId) {
                return;
            }
            nextUrl.searchParams.set('source_job_id', selectedRunId);
            window.history.replaceState({}, '', nextUrl.toString());
        } catch (error) {
            // Preserve the current URL if parsing fails.
        }
    }

    function runWorkspaceScripts(root) {
        root = root || currentWorkspace();
        if (!root) {
            return;
        }
        Array.prototype.slice.call(root.querySelectorAll('script')).forEach(function (originalScript) {
            if (!originalScript.parentNode) {
                return;
            }
            var replacement = document.createElement('script');
            Array.prototype.slice.call(originalScript.attributes || []).forEach(function (attribute) {
                replacement.setAttribute(attribute.name, attribute.value);
            });
            if (originalScript.src) {
                replacement.src = originalScript.src;
            } else {
                replacement.text = originalScript.textContent || '';
            }
            originalScript.parentNode.replaceChild(replacement, originalScript);
        });
    }

    function currentScrollY() {
        return window.scrollY || window.pageYOffset || 0;
    }

    function ensureWorkspaceStatusBox() {
        var wrap = currentWorkspace();
        if (!wrap) {
            return null;
        }
        var existing = document.getElementById('opsgate-workspace-status');
        if (existing) {
            return existing;
        }
        var box = document.createElement('div');
        box.id = 'opsgate-workspace-status';
        box.className = 'opsgate-alert-inline-status';
        box.setAttribute('data-opsgate-transient-status', '1');
        box.setAttribute('role', 'status');
        box.setAttribute('aria-live', 'polite');
        var copy = document.createElement('p');
        box.appendChild(copy);
        wrap.insertBefore(box, wrap.firstChild);
        return box;
    }

    function clearInlineStatus(id) {
        var box = document.getElementById(id);
        if (!box) {
            return;
        }
        if (inlineStatusTimers[id]) {
            window.clearTimeout(inlineStatusTimers[id]);
            delete inlineStatusTimers[id];
        }
        box.className = 'opsgate-alert-inline-status';
        var text = box.querySelector('p');
        if (text) {
            text.textContent = '';
        }
    }

    function showInlineStatus(id, message, kind) {
        var box = document.getElementById(id);
        if (!box) {
            if (id === 'opsgate-workspace-status') {
                box = ensureWorkspaceStatusBox();
            }
            if (!box) {
                return;
            }
        }
        if (inlineStatusTimers[id]) {
            window.clearTimeout(inlineStatusTimers[id]);
            delete inlineStatusTimers[id];
        }
        box.className = 'opsgate-alert-inline-status is-visible ' + (kind === 'error' ? 'is-error' : 'is-success');
        var text = box.querySelector('p');
        if (text) {
            text.textContent = String(message || '');
        }
        inlineStatusTimers[id] = window.setTimeout(function () {
            clearInlineStatus(id);
        }, 5200);
    }

    function clearTransientStatuses(root) {
        root = root || document;
        Array.prototype.slice.call(root.querySelectorAll('[data-opsgate-transient-status="1"]')).forEach(function (box) {
            box.classList.remove('is-visible');
        });
    }

    function initTransientStatuses(root) {
        root = root || document;
        if (window.history && window.history.replaceState) {
            var cleanedUrl = scrubUrl(window.location.href);
            if (cleanedUrl !== window.location.href) {
                window.history.replaceState({}, '', cleanedUrl);
            }
        }
        Array.prototype.slice.call(root.querySelectorAll('[data-opsgate-transient-status="1"]')).forEach(function (box, index) {
            if (box.getAttribute('data-opsgate-live-transient-init') === '1') {
                return;
            }
            box.setAttribute('data-opsgate-live-transient-init', '1');
            window.setTimeout(function () {
                box.classList.remove('is-visible');
            }, 5200 + (index * 120));
        });
    }

    function parseStates(panel) {
        if (!panel) {
            return [];
        }
        return String(panel.getAttribute('data-opsgate-live-states') || '')
            .split(',')
            .map(function (value) {
                return value.trim().toUpperCase();
            })
            .filter(Boolean);
    }

    function hasNonTerminalState(states) {
        if (!states.length) {
            return false;
        }
        return states.some(function (state) {
            return ['COMPLETED', 'FAILED'].indexOf(state) === -1;
        });
    }

    function attr(node, name) {
        if (!node) {
            return '';
        }
        return String(node.getAttribute(name) || '').trim();
    }

    function shouldPollTriage(panel) {
        var states = parseStates(panel);
        if (hasNonTerminalState(states)) {
            return true;
        }
        var currentJobId = attr(panel, 'data-opsgate-current-job-id');
        var renderedRunId = attr(panel, 'data-opsgate-rendered-run-id');
        if (currentJobId && currentJobId !== renderedRunId) {
            return true;
        }
        var currentExportJobId = attr(panel, 'data-opsgate-current-export-job-id');
        var currentExportSourceJobId = attr(panel, 'data-opsgate-current-export-source-job-id');
        var renderedExportJobId = attr(panel, 'data-opsgate-rendered-export-job-id');
        if (currentExportJobId && currentExportSourceJobId && currentJobId && currentExportSourceJobId === currentJobId && currentExportJobId !== renderedExportJobId) {
            return true;
        }
        return false;
    }

    function shouldPollReports(panel) {
        var states = parseStates(panel);
        if (hasNonTerminalState(states)) {
            return true;
        }
        var currentSourceJobId = attr(panel, 'data-opsgate-current-source-job-id');
        var renderedSourceJobId = attr(panel, 'data-opsgate-rendered-source-job-id');
        if (currentSourceJobId && currentSourceJobId !== renderedSourceJobId) {
            return true;
        }
        var currentExportJobId = attr(panel, 'data-opsgate-current-export-job-id');
        var renderedExportJobId = attr(panel, 'data-opsgate-rendered-export-job-id');
        if (currentExportJobId && currentExportJobId !== renderedExportJobId) {
            return true;
        }
        return false;
    }

    function setRunButtonsBusy(panel, isBusy, label) {
        var root = panel && panel.closest ? panel.closest('.wrap.opsgate-admin') : document;
        if (!root) {
            return;
        }
        Array.prototype.slice.call(root.querySelectorAll('[data-opsgate-run-button]')).forEach(function (button) {
            var idleLabel = button.getAttribute('data-opsgate-run-idle-label') || 'Run Security Scan';
            var busyLabel = button.getAttribute('data-opsgate-run-busy-label') || 'Run in progress';
            button.disabled = !!isBusy;
            button.textContent = isBusy ? (label || busyLabel) : idleLabel;
        });
    }

    function setRuntimeNote(panel, message, tone) {
        if (!panel) {
            return;
        }
        var note = panel.querySelector('[data-opsgate-triage-runtime-note]');
        if (!note) {
            return;
        }
        note.hidden = !message;
        note.textContent = String(message || '');
        ['info', 'success', 'warn', 'error'].forEach(function (value) {
            note.classList.remove('is-' + value);
        });
        if (tone) {
            note.classList.add('is-' + tone);
        }
    }

    function updateTriagePanel(panel, payload) {
        if (!panel || !payload) {
            return;
        }
        var states = Array.isArray(payload.live_states) ? payload.live_states : [];
        panel.setAttribute('data-opsgate-live-states', states.join(','));
        if (Object.prototype.hasOwnProperty.call(payload, 'job_id')) {
            panel.setAttribute('data-opsgate-current-job-id', String(payload.job_id || ''));
            writeSelectedRunId(payload.job_id || '');
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'export_job_id')) {
            panel.setAttribute('data-opsgate-current-export-job-id', String(payload.export_job_id || ''));
        }
        if (Object.prototype.hasOwnProperty.call(payload, 'export_source_job_id')) {
            panel.setAttribute('data-opsgate-current-export-source-job-id', String(payload.export_source_job_id || ''));
        }
        var commandCopy = panel.querySelector('[data-opsgate-triage-command-status-copy]');
        var title = panel.querySelector('[data-opsgate-triage-progress-title]');
        var copy = panel.querySelector('[data-opsgate-triage-progress-copy]');
        var fill = panel.querySelector('[data-opsgate-triage-progress-fill]');
        var meter = panel.querySelector('[data-opsgate-triage-progress-meter]');
        var phase = panel.querySelector('[data-opsgate-triage-progress-phase]');
        var elapsed = panel.querySelector('[data-opsgate-triage-progress-elapsed]');
        var evidence = panel.querySelector('[data-opsgate-triage-progress-evidence]');
        var asideTitle = panel.querySelector('[data-opsgate-triage-aside-title]');
        var asideCopy = panel.querySelector('[data-opsgate-triage-aside-copy]');
        if (commandCopy) {
            commandCopy.textContent = String(payload.progress_copy || '');
        }
        if (title) {
            title.textContent = String(payload.progress_title || 'Latest run status');
        }
        if (copy) {
            copy.textContent = String(payload.progress_copy || '');
        }
        if (fill) {
            fill.style.width = String(payload.progress_percent || 0) + '%';
        }
        if (meter) {
            meter.setAttribute('aria-valuenow', String(payload.progress_percent || 0));
            meter.setAttribute('aria-label', String(payload.progress_meter_label || 'Run progress'));
        }
        if (phase) {
            phase.textContent = String(payload.progress_phase_label || 'Waiting');
        }
        if (elapsed) {
            elapsed.textContent = String(payload.elapsed_label || '');
        }
        if (evidence) {
            evidence.textContent = String(payload.evidence_label || '');
        }
        if (asideTitle) {
            asideTitle.textContent = String(payload.progress_phase_label || 'Waiting');
        }
        if (asideCopy) {
            asideCopy.textContent = String(payload.progress_phase_copy || '');
        }
        if (Array.isArray(payload.phase_items)) {
            payload.phase_items.forEach(function (item) {
                var phaseCard = panel.querySelector('[data-opsgate-triage-phase-key="' + String(item.key || '') + '"]');
                if (!phaseCard) {
                    return;
                }
                ['pending', 'current', 'complete', 'failed', 'blocked'].forEach(function (state) {
                    phaseCard.classList.remove('is-' + state);
                });
                phaseCard.classList.add('is-' + String(item.state || 'pending'));
                var phaseStatus = phaseCard.querySelector('[data-opsgate-triage-phase-status]');
                if (phaseStatus) {
                    phaseStatus.textContent = String(item.state_label || 'Waiting');
                }
            });
        }
        setRunButtonsBusy(panel, shouldPollTriage(panel), 'Run in progress');
    }

    function replaceWorkspaceFromHtml(html, requestUrl, options) {
        var parser = new DOMParser();
        var doc = parser.parseFromString(html, 'text/html');
        var next = doc.querySelector('.wrap.opsgate-admin');
        var current = currentWorkspace();
        if (!next || !current) {
            throw new Error('Could not load the latest OpsGate workspace.');
        }
        current.outerHTML = next.outerHTML;
        var finalUrl = options && options.keepTransientQuery ? (requestUrl || window.location.href) : scrubUrl(requestUrl || window.location.href);
        if (!options || !options.skipHistory) {
            if (options && options.replace && window.history && window.history.replaceState) {
                window.history.replaceState({}, '', finalUrl);
            } else if (window.history && window.history.pushState) {
                window.history.pushState({}, '', finalUrl);
            }
        }
        runWorkspaceScripts(currentWorkspace());
        if (window.OpsGateWorkspace && typeof window.OpsGateWorkspace.initializeWorkspace === 'function') {
            window.OpsGateWorkspace.initializeWorkspace(currentWorkspace() || document);
        }
        initTransientStatuses(document);
        syncSelectedRunId(document);
        applySelectedRunBindings(document);
        syncReportsUrlState(document.getElementById('opsgate-reports-live-panel'));
        bindAlertToggleFallback(document);
        initScoreGauge();
        initHelpPanels();
        scheduleTriagePolling(500);
        scheduleReportsPolling(500);
        if (options && options.anchor) {
            var anchorId = normalizeAnchorId(options.anchor);
            if (anchorId) {
                updateWorkspaceHash(anchorId, true);
                window.requestAnimationFrame(function () {
                    var target = document.getElementById(anchorId);
                    if (target && typeof target.scrollIntoView === 'function') {
                        target.scrollIntoView({ block: 'start', behavior: 'smooth' });
                    }
                });
            }
        }
        if (options && options.preserveScroll) {
            var scrollY = options.scrollY || 0;
            window.requestAnimationFrame(function () {
                window.scrollTo(0, scrollY);
            });
        }
    }

    function loadWorkspace(url, options) {
        options = options || {};
        var normalizedUrl = normalizeUrl(url);
        if (workspaceLoading) {
            pendingWorkspaceRequest = {
                url: normalizedUrl,
                options: options
            };
            return workspacePromise || Promise.resolve();
        }
        workspaceLoading = true;
        var scrollY = options.preserveScroll ? currentScrollY() : 0;
        workspacePromise = fetch(normalizedUrl, {
            credentials: 'same-origin',
            cache: 'no-store'
        }).then(function (response) {
            if (!response.ok) {
                throw new Error('Could not load the latest OpsGate workspace.');
            }
            return response.text();
        }).then(function (html) {
            replaceWorkspaceFromHtml(html, normalizedUrl, {
                replace: !!options.replace,
                skipHistory: !!options.skipHistory,
                preserveScroll: !!options.preserveScroll,
                scrollY: scrollY,
                keepTransientQuery: !!options.keepTransientQuery,
                anchor: options.anchor || ''
            });
        }).catch(function (error) {
            showInlineStatus('opsgate-workspace-status', error && error.message ? error.message : 'Could not update this OpsGate view in place.', 'error');
            throw error;
        }).finally(function () {
            workspaceLoading = false;
            var nextRequest = pendingWorkspaceRequest;
            pendingWorkspaceRequest = null;
            workspacePromise = null;
            if (nextRequest) {
                loadWorkspace(nextRequest.url, nextRequest.options);
            }
        });
        return workspacePromise;
    }

    function refreshPanel(panelId) {
        var panel = document.getElementById(panelId);
        if (!panel) {
            return Promise.resolve(null);
        }
        var refreshUrl = normalizeUrl(panel.getAttribute('data-opsgate-refresh-url') || window.location.href);
        return fetch(refreshUrl, {
            credentials: 'same-origin',
            cache: 'no-store'
        }).then(function (response) {
            if (!response.ok) {
                throw new Error('Could not refresh this OpsGate panel.');
            }
            return response.text();
        }).then(function (html) {
            var parser = new DOMParser();
            var doc = parser.parseFromString(html, 'text/html');
            var next = doc.getElementById(panelId);
            var current = document.getElementById(panelId);
            if (!next || !current) {
                throw new Error('Could not refresh this OpsGate panel.');
            }
            var helpEl = current.querySelector('.opsgate-p5-help-panel');
            var helpPanelOpen = !!(helpEl && helpEl.hasAttribute('open'));
            var openRefIndexes = [];
            if (helpEl) {
                var refDetails = Array.prototype.slice.call(helpEl.querySelectorAll('.opsgate-triage-reference-details'));
                refDetails.forEach(function (d, i) { if (d.hasAttribute('open')) { openRefIndexes.push(i); } });
            }
            current.outerHTML = next.outerHTML;
            initTransientStatuses(document);
            if (window.OpsGateWorkspace && typeof window.OpsGateWorkspace.initializeWorkspace === 'function') {
                window.OpsGateWorkspace.initializeWorkspace(document);
            }
            var refreshedPanel = document.getElementById(panelId);
            if (refreshedPanel) {
                var newHelp = refreshedPanel.querySelector('.opsgate-p5-help-panel');
                if (newHelp && helpPanelOpen) { newHelp.setAttribute('open', ''); }
                if (newHelp && openRefIndexes.length) {
                    var newRefDetails = Array.prototype.slice.call(newHelp.querySelectorAll('.opsgate-triage-reference-details'));
                    openRefIndexes.forEach(function (i) { if (newRefDetails[i]) { newRefDetails[i].setAttribute('open', ''); } });
                }
            }
            syncSelectedRunId(document);
            applySelectedRunBindings(document);
            if (panelId === 'opsgate-reports-live-panel') {
                syncReportsUrlState(refreshedPanel);
            }
            bindAlertToggleFallback(document);
            initActivityFilterTabVisibility(document);
            return refreshedPanel;
        });
    }

    function stopTriagePolling() {
        if (triageTimer) {
            window.clearTimeout(triageTimer);
            triageTimer = null;
        }
    }

    function stopReportsPolling() {
        if (reportsTimer) {
            window.clearTimeout(reportsTimer);
            reportsTimer = null;
        }
    }

    function isLegacyAlertNode(node) {
        return !!(node && node.closest && node.closest('.opsgate-alerts-legacy-block'));
    }

    function alertToggleFormsForRule(ruleId, root) {
        var normalizedRuleId = String(ruleId || '').trim();
        var scopeRoot = root || document;
        if (!normalizedRuleId || !scopeRoot || !scopeRoot.querySelectorAll) {
            return [];
        }
        return Array.prototype.slice.call(scopeRoot.querySelectorAll('.opsgate-alert-switch-form[data-rule-id]')).filter(function (candidate) {
            return !isLegacyAlertNode(candidate) && (candidate.getAttribute('data-rule-id') || '') === normalizedRuleId;
        });
    }

    function syncAlertToggleRow(form, isEnabled) {
        if (!form) {
            return;
        }
        var button = form.querySelector('[data-opsgate-alert-toggle-button]');
        var label = form.querySelector('[data-opsgate-alert-toggle-label]');
        var row = form.closest('tr');
        form.setAttribute('data-current-enabled', isEnabled ? '1' : '0');
        form.setAttribute('data-next-enabled', isEnabled ? '0' : '1');
        if (button) {
            button.setAttribute('aria-checked', isEnabled ? 'true' : 'false');
            button.setAttribute('aria-label', isEnabled ? 'Disable alert' : 'Enable alert');
        }
        if (label) {
            label.textContent = isEnabled ? 'ON' : 'OFF';
        }
        if (row) {
            row.classList.toggle('is-enabled', isEnabled);
        }
    }

    function syncVisibleAlertRuleState(ruleId, isEnabled, root) {
        alertToggleFormsForRule(ruleId, root).forEach(function (form) {
            syncAlertToggleRow(form, isEnabled);
        });
    }

    function setVisibleAlertRuleBusyState(ruleId, isBusy, root) {
        alertToggleFormsForRule(ruleId, root).forEach(function (form) {
            var button = form.querySelector('[data-opsgate-alert-toggle-button]');
            form.classList.toggle('is-busy', !!isBusy);
            if (isBusy) {
                form.setAttribute('data-opsgate-toggle-busy', '1');
            } else {
                form.removeAttribute('data-opsgate-toggle-busy');
            }
            if (button) {
                button.classList.toggle('is-busy', !!isBusy);
                button.disabled = !!isBusy;
            }
        });
    }

    function bindAlertToggleFallback(root) {
        root = root || document;
        var panel = root.querySelector ? root.querySelector('#opsgate-alerts-live-panel') : null;
        if (!panel) {
            return;
        }

        Array.prototype.slice.call(panel.querySelectorAll('.opsgate-alert-switch-form[data-rule-id]')).forEach(function (form) {
            if (isLegacyAlertNode(form)) {
                return;
            }
            var button = form.querySelector('[data-opsgate-alert-toggle-button]');
            if (!button) {
                return;
            }
            if (button.getAttribute('data-opsgate-alert-control-init') === '1') {
                return;
            }
            if (button.getAttribute('data-opsgate-alert-fallback-init') === '1') {
                return;
            }

            var submitToggle = function () {
                if (form.getAttribute('data-opsgate-toggle-busy') === '1' || button.disabled) {
                    return;
                }
                var ruleId = String(form.getAttribute('data-rule-id') || '').trim();
                var nonce = String(form.getAttribute('data-ajax-nonce') || '');
                var ajaxUrl = normalizeUrl(form.getAttribute('data-ajax-url') || panel.getAttribute('data-opsgate-ajax-url') || '');
                var nextEnabled = form.getAttribute('data-current-enabled') !== '1';
                if (!ruleId || !nonce || !ajaxUrl) {
                    showInlineStatus('opsgate-alerts-rules-status', 'Could not update the alert setting.', 'error');
                    return;
                }

                var previousEnabled = form.getAttribute('data-current-enabled') === '1';
                var params = new URLSearchParams();
                params.set('action', 'opsgate_notification_rule_toggle');
                params.set('nonce', nonce);
                params.set('rule_id', ruleId);
                params.set('enabled', nextEnabled ? '1' : '0');

                syncVisibleAlertRuleState(ruleId, nextEnabled);
                setVisibleAlertRuleBusyState(ruleId, true);

                fetch(ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    body: params.toString()
                }).then(function (response) {
                    return response.json();
                }).then(function (payload) {
                    if (!payload || !payload.success || !payload.data) {
                        throw new Error(payload && payload.data && payload.data.message ? payload.data.message : 'Could not update the alert setting.');
                    }
                    var isEnabled = !!payload.data.is_enabled;
                    syncVisibleAlertRuleState(ruleId, isEnabled);
                    showInlineStatus('opsgate-alerts-rules-status', payload.data.message || 'Alert setting updated.', 'success');
                    return refreshPanel('opsgate-alerts-live-panel');
                }).catch(function (error) {
                    syncVisibleAlertRuleState(ruleId, previousEnabled);
                    showInlineStatus('opsgate-alerts-rules-status', error && error.message ? error.message : 'Could not update the alert setting.', 'error');
                }).finally(function () {
                    setVisibleAlertRuleBusyState(ruleId, false);
                });
            };

            button.setAttribute('role', 'switch');
            button.setAttribute('tabindex', '0');
            button.setAttribute('aria-checked', form.getAttribute('data-current-enabled') === '1' ? 'true' : 'false');
            button.setAttribute('data-opsgate-alert-fallback-init', '1');
            button.addEventListener('click', function (event) {
                event.preventDefault();
                event.stopPropagation();
                submitToggle();
            });
            button.addEventListener('keydown', function (event) {
                if (event.key !== ' ' && event.key !== 'Enter') {
                    return;
                }
                event.preventDefault();
                event.stopPropagation();
                submitToggle();
            });
        });
    }

    function scheduleTriagePolling(delay) {
        stopTriagePolling();
        var panel = document.getElementById('opsgate-triage-live-panel');
        if (!panel || !shouldPollTriage(panel)) {
            return;
        }
        triageTimer = window.setTimeout(function () {
            refreshPanel('opsgate-triage-live-panel').then(function (nextPanel) {
                if (nextPanel && shouldPollTriage(nextPanel)) {
                    scheduleTriagePolling(1500);
                } else if (nextPanel && attr(nextPanel, 'data-opsgate-reload-workspace-on-settle') === '1') {
                    loadWorkspace(window.location.href, { replace: true, skipHistory: true, preserveScroll: true }).catch(function () {
                        clearTransientStatuses(document);
                    });
                } else {
                    clearTransientStatuses(document);
                }
            }).catch(function () {
                scheduleTriagePolling(2200);
            });
        }, delay || 1500);
    }

    function scheduleReportsPolling(delay) {
        stopReportsPolling();
        var panel = document.getElementById('opsgate-reports-live-panel');
        if (!panel || !shouldPollReports(panel)) {
            return;
        }
        reportsTimer = window.setTimeout(function () {
            refreshPanel('opsgate-reports-live-panel').then(function (nextPanel) {
                if (nextPanel && shouldPollReports(nextPanel)) {
                    scheduleReportsPolling(1500);
                } else {
                    clearTransientStatuses(document);
                }
            }).catch(function () {
                scheduleReportsPolling(2200);
            });
        }, delay || 1500);
    }

    function isInternalWorkspaceUrl(href) {
        try {
            var raw = new URL(href, window.location.origin);
            if (raw.origin !== window.location.origin) {
                return false;
            }
            var url = new URL(normalizeUrl(href), window.location.origin);
            return url.origin === window.location.origin && url.searchParams.get('page') === 'opsgate';
        } catch (error) {
            return false;
        }
    }

    function startTriageRun(form) {
        var panel = document.getElementById('opsgate-triage-live-panel');
        if (!panel) {
            return;
        }
        var actionUrl = normalizeUrl(form.getAttribute('data-opsgate-triage-run-url') || panel.getAttribute('data-opsgate-run-url') || '');
        var nonceField = form.querySelector('input[name="_wpnonce"]');
        var nonce = nonceField ? String(nonceField.value || '') : '';
        if (!actionUrl || !nonce) {
            showInlineStatus('opsgate-workspace-status', 'Could not start Portfolio Triage from this page.', 'error');
            return;
        }
        var submitter = form.querySelector('button[type="submit"], input[type="submit"]');
        var originalLabel = submitter ? (submitter.textContent || submitter.value || '') : '';
        if (submitter) {
            submitter.disabled = true;
            if (submitter.tagName === 'BUTTON') {
                submitter.textContent = 'Starting run…';
            } else {
                submitter.value = 'Starting run…';
            }
        }
        setRuntimeNote(panel, 'Starting security scan…', 'info');
        setRunButtonsBusy(panel, true, 'Starting run…');
        var body = new URLSearchParams();
        body.set('action', 'opsgate_run_portfolio_triage_live');
        body.set('nonce', nonce);
        fetch(actionUrl, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: body.toString()
        }).then(function (response) {
            return response.json();
        }).then(function (payload) {
            if (!payload || !payload.success || !payload.data) {
                throw new Error(payload && payload.data && payload.data.message ? payload.data.message : 'Could not start security scan.');
            }
            updateTriagePanel(panel, payload.data);
            setRuntimeNote(panel, payload.data.message || 'Security scan started. Live run state is updating in place.', 'success');
            stopTriagePolling();
            scheduleTriagePolling(350);
        }).catch(function (error) {
            setRuntimeNote(panel, error && error.message ? error.message : 'Could not start security scan.', 'error');
            setRunButtonsBusy(panel, false);
        }).finally(function () {
            if (!submitter) {
                return;
            }
            submitter.disabled = false;
            if (submitter.tagName === 'BUTTON') {
                submitter.textContent = originalLabel || submitter.getAttribute('data-opsgate-run-idle-label') || 'Run Security Scan';
            } else {
                submitter.value = originalLabel || 'Run Security Scan';
            }
        });
    }

    function startReportExport(form) {
        var panel = document.getElementById('opsgate-reports-live-panel');
        if (!panel) {
            return;
        }
        var actionInput = form.querySelector('input[name="action"]');
        var sourceInput = form.querySelector('input[name="source_job_id"]');
        if (!actionInput || !sourceInput) {
            return;
        }
        var exportType = '';
        if (actionInput.value === 'opsgate_export_report_pdf') {
            exportType = 'pdf';
        } else if (actionInput.value === 'opsgate_export_report_html') {
            exportType = 'html';
        } else if (actionInput.value === 'opsgate_export_report_xlsx') {
            exportType = 'xlsx';
        } else if (actionInput.value === 'opsgate_export_triage_csv') {
            exportType = 'csv';
        }
        if (!exportType) {
            return;
        }
        var ajaxUrl = normalizeUrl(panel.getAttribute('data-opsgate-ajax-url') || '');
        var nonce = String(panel.getAttribute('data-opsgate-export-nonce') || '');
        var submitter = form.querySelector('button[type="submit"], input[type="submit"]');
        var originalLabel = submitter ? (submitter.textContent || submitter.value || '') : '';
        if (submitter) {
            submitter.disabled = true;
            if (submitter.tagName === 'BUTTON') {
                submitter.textContent = 'Generating…';
            } else {
                submitter.value = 'Generating…';
            }
        }
        var params = new URLSearchParams();
        params.set('action', 'opsgate_export_start');
        params.set('nonce', nonce);
        params.set('export_type', exportType);
        params.set('source_job_id', String(sourceInput.value || ''));
        fetch(ajaxUrl, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: params.toString()
        }).then(function (response) {
            return response.json();
        }).then(function (payload) {
            if (!payload || !payload.success || !payload.data) {
                throw new Error(payload && payload.data && payload.data.message ? payload.data.message : 'Could not start the packaged output.');
            }
            showInlineStatus('opsgate-reports-status-box', payload.data.message || 'Packaged output started.', 'success');
            panel.setAttribute('data-opsgate-live-states', 'RUNNING');
            if (payload.data.source_job_id) {
                panel.setAttribute('data-opsgate-current-source-job-id', String(payload.data.source_job_id));
                writeSelectedRunId(payload.data.source_job_id);
            }
            if (Object.prototype.hasOwnProperty.call(payload.data, 'export_job_id')) {
                panel.setAttribute('data-opsgate-current-export-job-id', String(payload.data.export_job_id || ''));
            }
            syncReportsUrlState(panel);
            stopReportsPolling();
            scheduleReportsPolling(350);
        }).catch(function (error) {
            showInlineStatus('opsgate-reports-status-box', error && error.message ? error.message : 'Could not start the packaged output.', 'error');
        }).finally(function () {
            if (!submitter) {
                return;
            }
            submitter.disabled = false;
            if (submitter.tagName === 'BUTTON') {
                submitter.textContent = originalLabel || 'Generate';
            } else {
                submitter.value = originalLabel || 'Generate';
            }
        });
    }

    function handleWorkspaceLinkClick(event) {
        var link = event.target.closest('a[href]');
        if (!link || link.hasAttribute('data-opsgate-no-ajax')) {
            return;
        }
        if (link.hasAttribute('data-og-sub-target')) {
            return;
        }
        if (!link.closest('.wrap.opsgate-admin')) {
            return;
        }
        if (!isInternalWorkspaceUrl(link.href)) {
            return;
        }
        var linkUrl = new URL(normalizeUrl(link.href), window.location.origin);
        var anchorId = normalizeAnchorId(linkUrl.hash || '');
        var currentUrl = new URL(normalizeUrl(window.location.href), window.location.origin);
        var sameBase = linkUrl.pathname === currentUrl.pathname
            && linkUrl.searchParams.get('page') === currentUrl.searchParams.get('page')
            && linkUrl.searchParams.get('tab') === currentUrl.searchParams.get('tab');
        event.preventDefault();
        event.stopImmediatePropagation();
        if (anchorId && sameBase) {
            var target = document.getElementById(anchorId);
            if (target && typeof target.scrollIntoView === 'function') {
                updateWorkspaceHash(anchorId, false);
                target.scrollIntoView({ block: 'start', behavior: 'smooth' });
            }
            return;
        }
        loadWorkspace(link.href, { preserveScroll: false, anchor: anchorId });
    }

    function handleWorkspaceSubmit(event) {
        var form = event.target;
        if (!form || form.tagName !== 'FORM' || !form.closest('.wrap.opsgate-admin')) {
            return;
        }
        var actionInput = form.querySelector('input[name="action"]');
        var actionName = actionInput ? String(actionInput.value || '') : '';
        if (form.matches('[data-opsgate-triage-run-form]')) {
            event.preventDefault();
            event.stopImmediatePropagation();
            startTriageRun(form);
            return;
        }
        if (form.matches('[data-opsgate-export-form]')) {
            event.preventDefault();
            event.stopImmediatePropagation();
            startReportExport(form);
            return;
        }
        if (!form.action || form.action.indexOf('admin-post.php') === -1) {
            return;
        }
        if (!actionName || actionName.indexOf('opsgate_notification_') === 0 || actionName.indexOf('opsgate_download_') === 0) {
            return;
        }
        if (form.getAttribute('enctype') && String(form.getAttribute('enctype')).toLowerCase().indexOf('multipart/form-data') !== -1) {
            return;
        }
        event.preventDefault();
        event.stopImmediatePropagation();
        var submitter = event.submitter || form.querySelector('button[type="submit"], input[type="submit"]');
        var originalLabel = submitter ? (submitter.textContent || submitter.value || '') : '';
        if (submitter) {
            submitter.disabled = true;
            if (submitter.tagName === 'BUTTON') {
                submitter.textContent = 'Saving…';
            } else {
                submitter.value = 'Saving…';
            }
        }
        var body = new URLSearchParams(new FormData(form));
        fetch(normalizeUrl(form.action), {
            method: 'POST',
            credentials: 'same-origin',
            body: body
        }).then(function (response) {
            if (!response.ok) {
                throw new Error('Could not save this OpsGate change in place.');
            }
            return response.text().then(function (html) {
                return {
                    html: html,
                    url: response.url || window.location.href
                };
            });
        }).then(function (payload) {
            replaceWorkspaceFromHtml(payload.html, payload.url || window.location.href, {
                replace: true,
                preserveScroll: true,
                scrollY: currentScrollY(),
                keepTransientQuery: true
            });
        }).catch(function (error) {
            showInlineStatus('opsgate-workspace-status', error && error.message ? error.message : 'Could not save this OpsGate change in place.', 'error');
        }).finally(function () {
            if (!submitter) {
                return;
            }
            submitter.disabled = false;
            if (submitter.tagName === 'BUTTON') {
                submitter.textContent = originalLabel || 'Save';
            } else {
                submitter.value = originalLabel || 'Save';
            }
        });
    }

    function initReportsViewer() {
        if (document.body.getAttribute('data-opsgate-viewer-init') === '1') {
            return;
        }
        document.body.setAttribute('data-opsgate-viewer-init', '1');
        document.addEventListener('click', function (event) {
            var modal = document.getElementById('opsgate-reports-viewer-modal');
            var frame = document.getElementById('opsgate-reports-viewer-frame');
            var title = document.getElementById('opsgate-reports-viewer-title');
            if (!modal || !frame || !title) {
                return;
            }
            var trigger = event.target.closest('.opsgate-reports-viewer-trigger');
            if (trigger) {
                event.preventDefault();
                title.textContent = (trigger.getAttribute('data-viewer-kind') || 'Report Preview');
                frame.setAttribute('src', trigger.getAttribute('data-viewer-url') || 'about:blank');
                modal.removeAttribute('hidden');
                return;
            }
            if (event.target.closest('[data-opsgate-viewer-close]')) {
                event.preventDefault();
                modal.setAttribute('hidden', 'hidden');
                frame.setAttribute('src', 'about:blank');
            }
        }, true);

        document.addEventListener('keydown', function (event) {
            var modal = document.getElementById('opsgate-reports-viewer-modal');
            var frame = document.getElementById('opsgate-reports-viewer-frame');
            if (!modal || !frame) {
                return;
            }
            if (event.key === 'Escape' && !modal.hasAttribute('hidden')) {
                modal.setAttribute('hidden', 'hidden');
                frame.setAttribute('src', 'about:blank');
            }
        });
    }

    function initRemotePairingModal() {
        if (document.body.getAttribute('data-opsgate-pairing-init') === '1') {
            return;
        }
        document.body.setAttribute('data-opsgate-pairing-init', '1');
        document.addEventListener('click', function (event) {
            var modal = document.getElementById('opsgate-remote-pairing-modal');
            if (!modal) {
                return;
            }
            if (event.target.closest('[data-opsgate-pairing-open]')) {
                event.preventDefault();
                modal.removeAttribute('hidden');
                var pairingInput = document.getElementById('opsgate_remote_pairing_code');
                if (pairingInput) {
                    window.setTimeout(function () {
                        pairingInput.focus();
                    }, 30);
                }
                return;
            }
            if (event.target.closest('[data-opsgate-pairing-close]')) {
                event.preventDefault();
                modal.setAttribute('hidden', 'hidden');
            }
        }, true);

        document.addEventListener('keydown', function (event) {
            var modal = document.getElementById('opsgate-remote-pairing-modal');
            if (!modal) {
                return;
            }
            if (event.key === 'Escape' && !modal.hasAttribute('hidden')) {
                modal.setAttribute('hidden', 'hidden');
            }
        });

        document.addEventListener('submit', function (event) {
            var form = event.target.closest('[data-opsgate-pairing-submit-form]');
            if (!form) { return; }
            var btn = form.querySelector('[data-opsgate-pairing-submit-btn]');
            if (!btn) { return; }
            var busyLabel = btn.getAttribute('data-opsgate-busy-label') || 'Connecting…';
            btn.disabled = true;
            btn.textContent = busyLabel;
        }, true);
    }

    function initAlertsRefreshDelegate() {
        if (document.body.getAttribute('data-opsgate-alerts-refresh-init') === '1') { return; }
        document.body.setAttribute('data-opsgate-alerts-refresh-init', '1');
        document.addEventListener('click', function (event) {
            var btn = event.target && event.target.closest && event.target.closest('[data-opsgate-refresh-panel]');
            if (!btn) { return; }
            var panelId = btn.getAttribute('data-opsgate-refresh-panel') || '';
            if (!panelId) { return; }
            event.preventDefault();
            event.stopImmediatePropagation();
            var origText = btn.textContent || '';
            btn.disabled = true;
            btn.textContent = 'Refreshing…';
            refreshPanel(panelId).then(function () {
                showInlineStatus('opsgate-workspace-status', 'Alert center refreshed.', 'success');
            }).catch(function () {
                showInlineStatus('opsgate-workspace-status', 'Could not refresh the alert center.', 'error');
            }).finally(function () {
                btn.disabled = false;
                btn.textContent = origText || 'Refresh alert center';
            });
        }, true);
    }

    function initCreateDestinationDelegate() {
        if (document.body.getAttribute('data-opsgate-create-dest-init') === '1') { return; }
        document.body.setAttribute('data-opsgate-create-dest-init', '1');
        document.addEventListener('click', function (event) {
            var el = event.target;
            if (!el || !el.closest) { return; }
            var isSubmitBtn = el.matches && (el.matches('button[type="submit"]') || el.matches('input[type="submit"]'));
            if (!isSubmitBtn) { return; }
            var form = el.closest('[data-opsgate-destination-form="create"]');
            if (!form) { return; }
            var btn = el;
            if (btn.disabled) { return; }
            if (btn.getAttribute('data-og-busy') === '1') { return; }
            event.preventDefault();
            event.stopImmediatePropagation();
            var panel = document.getElementById('opsgate-alerts-live-panel');
            var ajaxUrl = normalizeUrl((panel && panel.getAttribute('data-opsgate-ajax-url')) || (window._ogAjaxUrl || ''));
            if (!ajaxUrl) {
                ajaxUrl = normalizeUrl('/wp-admin/admin-ajax.php');
            }
            var nonceField = form.querySelector('input[name="_wpnonce"]');
            var nonceValue = nonceField ? (nonceField.value || '') : '';
            var familyField = form.querySelector('select[name="destination_family"], input[name="destination_family"]');
            var family = familyField ? String(familyField.value || '').trim() : 'email';
            var formData = new FormData(form);
            var params = new URLSearchParams();
            formData.forEach(function(val, key) {
                params.append(key, val);
            });
            params.set('action', 'opsgate_notification_destination_mutation');
            params.set('mutation_action', 'opsgate_notification_destination_create');
            params.set('nonce', nonceValue);
            params.set('destination_family', family);
            var origLabel = btn.tagName === 'BUTTON' ? (btn.textContent || 'Create destination') : (btn.value || 'Create destination');
            btn.setAttribute('data-og-busy', '1');
            btn.disabled = true;
            if (btn.tagName === 'BUTTON') { btn.textContent = 'Saving…'; }
            else { btn.value = 'Saving…'; }
            fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                body: params.toString()
            }).then(function (r) {
                if (!r.ok) { throw new Error('Server error ' + r.status); }
                return r.json();
            }).then(function (payload) {
                if (!payload || !payload.success) {
                    throw new Error((payload && payload.data && payload.data.message) ? payload.data.message : 'Could not create the alert destination.');
                }
                return refreshPanel('opsgate-alerts-live-panel').then(function () {
                    showInlineStatus('opsgate-workspace-status', (payload.data && payload.data.message) ? payload.data.message : 'Alert destination created.', 'success');
                });
            }).catch(function (err) {
                showInlineStatus('opsgate-workspace-status', (err && err.message) ? err.message : 'Could not create the alert destination.', 'error');
                btn.removeAttribute('data-og-busy');
                btn.disabled = false;
                if (btn.tagName === 'BUTTON') { btn.textContent = origLabel; }
                else { btn.value = origLabel; }
            });
        }, true);
        document.addEventListener('submit', function (event) {
            var form = event.target && event.target.closest && event.target.closest('[data-opsgate-destination-form="create"]');
            if (!form) { return; }
            event.preventDefault();
            event.stopImmediatePropagation();
        }, true);
    }

    function initCreateRuleDelegate() {
        if (document.body.getAttribute('data-opsgate-create-rule-init') === '1') { return; }
        document.body.setAttribute('data-opsgate-create-rule-init', '1');
        document.addEventListener('submit', function (event) {
            var form = event.target && event.target.closest && event.target.closest('[data-opsgate-rule-form="create"]');
            if (!form) { return; }
            event.preventDefault();
            event.stopImmediatePropagation();
            var panel = document.getElementById('opsgate-alerts-live-panel');
            var ajaxUrl = normalizeUrl((panel && panel.getAttribute('data-opsgate-ajax-url')) || '/wp-admin/admin-ajax.php');
            var nonceField = form.querySelector('input[name="_wpnonce"]');
            var nonceValue = nonceField ? (nonceField.value || '') : '';
            var submitter = event.submitter || form.querySelector('button[type="submit"],input[type="submit"]');
            var origLabel = submitter ? (submitter.tagName === 'BUTTON' ? submitter.textContent : submitter.value) : '';
            if (submitter) {
                submitter.disabled = true;
                if (submitter.tagName === 'BUTTON') { submitter.textContent = 'Saving…'; }
                else { submitter.value = 'Saving…'; }
            }
            var params = new URLSearchParams(new FormData(form));
            params.set('action', 'opsgate_notification_rule_create');
            params.set('nonce', nonceValue);
            fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                body: params.toString()
            }).then(function (r) {
                if (!r.ok) { throw new Error('Server error ' + r.status); }
                return r.json();
            }).then(function (payload) {
                if (!payload || !payload.success) {
                    throw new Error((payload && payload.data && payload.data.message) ? payload.data.message : 'Could not create the alert rule.');
                }
                return refreshPanel('opsgate-alerts-live-panel').then(function () {
                    showInlineStatus('opsgate-workspace-status', (payload.data && payload.data.message) ? payload.data.message : 'Alert rule created.', 'success');
                });
            }).catch(function (err) {
                showInlineStatus('opsgate-workspace-status', (err && err.message) ? err.message : 'Could not create the alert rule.', 'error');
                if (submitter) {
                    submitter.disabled = false;
                    if (submitter.tagName === 'BUTTON') { submitter.textContent = origLabel; }
                    else { submitter.value = origLabel; }
                }
            });
        }, true);
    }

    function initAlertsSubNav() {
        // Delegated to document — survives DOM replacement on AJAX navigation.
        if (document.body.getAttribute('data-opsgate-alerts-subnav-init') === '1') { return; }
        document.body.setAttribute('data-opsgate-alerts-subnav-init', '1');
        document.addEventListener('click', function (e) {
            var link = e.target && e.target.closest && e.target.closest('[data-og-sub-target]');
            if (!link) { return; }
            var nav = link.closest('#opsgate-alerts-subnav');
            if (!nav) { return; }
            e.preventDefault();
            var target = (link.getAttribute('data-og-sub-target') || '').replace('alerts-', '');
            var panels = document.querySelectorAll('.opsgate-sub-panel');
            var items = nav.querySelectorAll('.opsgate-sub-nav-item');
            panels.forEach(function (p) { p.classList.remove('is-active'); });
            items.forEach(function (i) { i.classList.remove('is-active'); i.setAttribute('aria-selected', 'false'); });
            var panel = document.getElementById('opsgate-alerts-sub-' + target);
            var item = nav.querySelector('[data-og-sub-target="alerts-' + target + '"]');
            if (panel) { panel.classList.add('is-active'); }
            if (item) { item.classList.add('is-active'); item.setAttribute('aria-selected', 'true'); }
        });
    }

    function initAlertsOverviewActions() {
        // Delegated handler for Overview card action buttons that target sub-panels.
        // Uses data-og-overview-action="history|rules|destinations|overview" — same switch
        // logic as initAlertsSubNav but triggered from outside #opsgate-alerts-subnav.
        if (document.body.getAttribute('data-opsgate-overview-actions-init') === '1') { return; }
        document.body.setAttribute('data-opsgate-overview-actions-init', '1');
        document.addEventListener('click', function (e) {
            var btn = e.target && e.target.closest && e.target.closest('[data-og-overview-action]');
            if (!btn) { return; }
            var target = btn.getAttribute('data-og-overview-action') || '';
            if (!target) { return; }
            e.preventDefault();
            var nav = document.getElementById('opsgate-alerts-subnav');
            var panels = document.querySelectorAll('.opsgate-sub-panel');
            var items = nav ? nav.querySelectorAll('.opsgate-sub-nav-item') : [];
            panels.forEach(function (p) { p.classList.remove('is-active'); });
            items.forEach(function (i) { i.classList.remove('is-active'); i.setAttribute('aria-selected', 'false'); });
            var panel = document.getElementById('opsgate-alerts-sub-' + target);
            var item = nav ? nav.querySelector('[data-og-sub-target="alerts-' + target + '"]') : null;
            if (panel) { panel.classList.add('is-active'); }
            if (item) { item.classList.add('is-active'); item.setAttribute('aria-selected', 'true'); }
        });
    }

    function initActivityFilterTabVisibility(root) {
        root = root || document;
        var bar = root.getElementById('opsgate-activity-filter-bar');
        if (!bar) { return; }
        var feed = root.getElementById('opsgate-activity-feed-list');
        if (!feed) { return; }
        var presentFamilies = {};
        feed.querySelectorAll('[data-og-family]').forEach(function (item) {
            var f = item.getAttribute('data-og-family');
            if (f) { presentFamilies[f] = true; }
        });
        bar.querySelectorAll('.opsgate-filter-btn[data-og-filter]').forEach(function (btn) {
            var filter = btn.getAttribute('data-og-filter');
            if (filter === 'all') { return; }
            btn.style.display = presentFamilies[filter] ? '' : 'none';
        });
    }

    function initActivityFilterBar() {
        // Delegated to document — survives DOM replacement on AJAX navigation.
        if (document.body.getAttribute('data-opsgate-activity-filter-init') === '1') { return; }
        document.body.setAttribute('data-opsgate-activity-filter-init', '1');
        document.addEventListener('click', function (e) {
            var btn = e.target && e.target.closest && e.target.closest('[data-og-filter]');
            if (!btn) { return; }
            var bar = btn.closest('#opsgate-activity-filter-bar');
            if (!bar) { return; }
            var feed = document.getElementById('opsgate-activity-feed-list');
            if (!feed) { return; }
            var emptyState = document.getElementById('opsgate-activity-filter-empty');
            bar.querySelectorAll('.opsgate-filter-btn').forEach(function (b) { b.classList.remove('is-active'); });
            btn.classList.add('is-active');
            var filter = btn.getAttribute('data-og-filter');
            var visibleCount = 0;
            feed.querySelectorAll('.opsgate-activity-item').forEach(function (item) {
                if (filter === 'all' || item.getAttribute('data-og-family') === filter) {
                    item.style.display = '';
                    visibleCount++;
                } else {
                    item.style.display = 'none';
                }
            });
            feed.querySelectorAll('.opsgate-activity-day-group').forEach(function (group) {
                var hasVisible = group.querySelector('.opsgate-activity-item:not([style*="display: none"]):not([style*="display:none"])');
                group.style.display = hasVisible ? '' : 'none';
            });
            if (emptyState) {
                emptyState.style.display = visibleCount === 0 ? '' : 'none';
            }
        });
    }

    var triageFilterToneMap = {
        needs_action: ['warn', 'bad', 'blocked'],
        vulnerabilities: ['bad'],
        updates: ['warn'],
        uptime: ['warn', 'bad'],
        configuration: ['warn', 'bad'],
        logs: ['info'],
        passed: ['good', 'foundation']
    };

    function initTriageFilterStrip() {
        // Delegated to document — survives DOM replacement on AJAX navigation.
        if (document.body.getAttribute('data-opsgate-triage-filter-init') === '1') { return; }
        document.body.setAttribute('data-opsgate-triage-filter-init', '1');
        document.addEventListener('click', function (e) {
            var btn = e.target && e.target.closest && e.target.closest('[data-og-triage-filter]');
            if (!btn) { return; }
            var strip = btn.closest('#opsgate-triage-filter-strip');
            if (!strip) { return; }
            strip.querySelectorAll('.opsgate-triage-filter-btn').forEach(function (b) { b.classList.remove('is-active'); });
            btn.classList.add('is-active');
            var filter = btn.getAttribute('data-og-triage-filter');
            var allowedTones = triageFilterToneMap[filter] || null;
            var emptyState = document.getElementById('opsgate-triage-filter-empty');
            var visibleCount = 0;
            document.querySelectorAll('.opsgate-triage-dimension-row').forEach(function (row) {
                if (!allowedTones) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    var tone = row.getAttribute('data-og-triage-tone') || '';
                    var visible = allowedTones.indexOf(tone) !== -1;
                    row.style.display = visible ? '' : 'none';
                    if (visible) { visibleCount++; }
                }
            });
            if (emptyState) {
                emptyState.style.display = visibleCount === 0 ? '' : 'none';
            }
        });
    }

    function initSettingsZoneB() {
        var toggle = document.querySelector('.opsgate-settings-zone-b-toggle');
        if (!toggle) { return; }
        var bodyId = toggle.getAttribute('aria-controls');
        var body = bodyId ? document.getElementById(bodyId) : null;
        if (!body) { return; }
        toggle.addEventListener('click', function () {
            var isOpen = body.classList.contains('is-open');
            toggle.setAttribute('aria-expanded', String(!isOpen));
            toggle.classList.toggle('is-open', !isOpen);
            body.classList.toggle('is-open', !isOpen);
        });
    }

    // Phase 5: Animate SVG score gauge arcs on load
    function initScoreGauge() {
        var arcs = document.querySelectorAll('.opsgate-p5-gauge-arc');
        arcs.forEach(function (arc) {
            var target = parseFloat(arc.getAttribute('stroke-dashoffset') || '0');
            var circumference = parseFloat(arc.getAttribute('stroke-dasharray') || '351.86');
            arc.style.strokeDashoffset = String(circumference);
            arc.style.transition = 'stroke-dashoffset 0.9s cubic-bezier(0.4, 0, 0.2, 1)';
            requestAnimationFrame(function () {
                requestAnimationFrame(function () {
                    arc.style.strokeDashoffset = String(target);
                });
            });
        });
    }

    // Phase 5: Ensure all help panels start collapsed
    function initHelpPanels() {
        var panels = document.querySelectorAll('.opsgate-p5-help-panel');
        panels.forEach(function (panel) {
            panel.removeAttribute('open');
        });
    }

    function initAutoPairing() {
        // Auto-submit the complete-pairing form when central redirected back with the token pre-filled.
        var pairForm = document.querySelector('[data-opsgate-auto-pair-form="1"]');
        if (pairForm) {
            var btn = pairForm.querySelector('[data-opsgate-pairing-submit-btn]');
            if (btn) {
                btn.disabled = true;
                btn.textContent = btn.getAttribute('data-opsgate-busy-label') || 'Connecting…';
            }
            window.setTimeout(function () { pairForm.submit(); }, 400);
            return;
        }
        // Auto-submit the create-pairing-session form when arriving from a remote handoff
        // and the site is already resolved (central already has a site_id).
        var createForm = document.querySelector('[data-opsgate-auto-create-pairing="1"]');
        if (createForm) {
            var createBtn = createForm.querySelector('button[type="submit"]');
            if (createBtn) {
                createBtn.disabled = true;
                createBtn.textContent = 'Generating code…';
            }
            window.setTimeout(function () { createForm.submit(); }, 300);
        }
    }

    function boot() {
        document.documentElement.setAttribute('data-opsgate-stable-js', '1');
        initTransientStatuses(document);
        syncSelectedRunId(document);
        applySelectedRunBindings(document);
        syncReportsUrlState(document.getElementById('opsgate-reports-live-panel'));
        bindAlertToggleFallback(document);
        scheduleTriagePolling(700);
        scheduleReportsPolling(700);
        initReportsViewer();
        initRemotePairingModal();
        initAutoPairing();
        initAlertsRefreshDelegate();
        initCreateDestinationDelegate();
        initCreateRuleDelegate();
        initAlertsSubNav();
        initAlertsOverviewActions();
        initActivityFilterBar();
        initActivityFilterTabVisibility(document);
        initTriageFilterStrip();
        initSettingsZoneB();
        initReportsFilterBar();
        initSendToClientBtn();
        initScoreGauge();
        initHelpPanels();
        document.addEventListener('click', handleWorkspaceLinkClick, true);
        document.addEventListener('submit', handleWorkspaceSubmit, true);
        window.addEventListener('popstate', function () {
            if (!isInternalWorkspaceUrl(window.location.href)) {
                return;
            }
            loadWorkspace(window.location.href, { replace: true, skipHistory: true, preserveScroll: false });
        });
    }

    function applyReportsFilter(activeFilter, grid) {
        var emptyMsg = document.getElementById('opsgate-reports-filter-empty');
        var cards = grid.querySelectorAll('.opsgate-reports-output-card');
        var visibleCount = 0;
        cards.forEach(function (card) {
            var format = (card.getAttribute('data-og-report-format') || '').toLowerCase();
            var state  = (card.getAttribute('data-og-report-state') || '').toLowerCase();
            var show = false;
            if (activeFilter === 'all') {
                show = true;
            } else if (activeFilter === 'ready') {
                show = state === 'ready';
            } else if (activeFilter === 'pending') {
                show = state === 'processing' || state === 'pending' || state === 'not generated';
            } else if (activeFilter === 'failed') {
                show = state === 'failed';
            } else if (activeFilter === 'pdf') {
                show = format === 'pdf';
            } else if (activeFilter === 'html') {
                show = format === 'html';
            } else if (activeFilter === 'csv') {
                show = format === 'csv';
            } else if (activeFilter === 'xlsx') {
                show = format === 'xlsx';
            }
            card.style.display = show ? '' : 'none';
            if (show) { visibleCount++; }
        });
        if (emptyMsg) {
            emptyMsg.style.display = visibleCount === 0 ? '' : 'none';
        }
    }

    function initReportsFilterBar() {
        // Delegated to document — survives DOM replacement on AJAX navigation.
        if (document.body.getAttribute('data-opsgate-reports-filter-init') === '1') { return; }
        document.body.setAttribute('data-opsgate-reports-filter-init', '1');
        document.addEventListener('click', function (e) {
            var btn = e.target && e.target.closest && e.target.closest('.opsgate-reports-filter-btn');
            if (!btn) { return; }
            var bar = btn.closest('#opsgate-reports-filter-bar');
            if (!bar) { return; }
            var grid = document.getElementById('opsgate-reports-output-grid');
            if (!grid) { return; }
            bar.querySelectorAll('.opsgate-reports-filter-btn').forEach(function (b) { b.classList.remove('is-active'); });
            btn.classList.add('is-active');
            applyReportsFilter(btn.getAttribute('data-og-report-filter') || 'all', grid);
        });
    }

    function initSendToClientBtn() {
        var activeBtn = null;

        function openModal(btn) {
            var modal = document.getElementById('opsgate-deliver-modal');
            if (!modal) return;
            activeBtn = btn;
            modal.hidden = false;
            var emailInput = document.getElementById('opsgate-deliver-email');
            var statusEl = document.getElementById('opsgate-deliver-status');
            if (emailInput) { emailInput.value = ''; emailInput.focus(); }
            if (statusEl) { statusEl.textContent = ''; statusEl.className = 'opsgate-deliver-modal-status'; }
            var submitBtn = document.getElementById('opsgate-deliver-submit');
            if (submitBtn) { submitBtn.disabled = false; submitBtn.textContent = 'Send report'; }
        }

        function closeModal() {
            var modal = document.getElementById('opsgate-deliver-modal');
            if (modal) { modal.hidden = true; }
            activeBtn = null;
        }

        function showStatus(msg, tone) {
            var statusEl = document.getElementById('opsgate-deliver-status');
            if (!statusEl) return;
            statusEl.textContent = msg;
            statusEl.className = 'opsgate-deliver-modal-status opsgate-deliver-modal-status-' + (tone || 'info');
        }

        document.addEventListener('click', function (e) {
            var btn = e.target && e.target.closest && e.target.closest('.opsgate-send-to-client-btn');
            if (btn) { e.preventDefault(); openModal(btn); return; }

            if (e.target && e.target.id === 'opsgate-deliver-cancel') { closeModal(); return; }

            if (e.target && e.target.id === 'opsgate-deliver-submit') {
                if (!activeBtn) { closeModal(); return; }
                var emailInput = document.getElementById('opsgate-deliver-email');
                var email = emailInput ? emailInput.value.trim() : '';
                if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
                    showStatus('Enter a valid email address.', 'error');
                    return;
                }
                var siteId   = activeBtn.getAttribute('data-delivery-site-id') || '';
                var jobId    = activeBtn.getAttribute('data-delivery-job-id') || '';
                var nonce    = activeBtn.getAttribute('data-delivery-nonce') || '';
                var ajaxUrl  = activeBtn.getAttribute('data-delivery-ajax-url') || (window.ajaxurl || '');
                if (!siteId || !jobId || !ajaxUrl) {
                    showStatus('Delivery context is missing. Reload the page and try again.', 'error');
                    return;
                }
                var submitBtn = document.getElementById('opsgate-deliver-submit');
                if (submitBtn) { submitBtn.disabled = true; submitBtn.textContent = 'Sending…'; }
                showStatus('Sending…', 'info');

                var body = new URLSearchParams();
                body.append('action', 'opsgate_report_deliver');
                body.append('nonce', nonce);
                body.append('site_id', siteId);
                body.append('job_id', jobId);
                body.append('recipient_email', email);

                fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body })
                    .then(function (r) { return r.json(); })
                    .then(function (data) {
                        if (submitBtn) { submitBtn.disabled = false; submitBtn.textContent = 'Send report'; }
                        if (data && data.success) {
                            showStatus((data.data && data.data.message) || 'Report queued for delivery.', 'ok');
                            setTimeout(closeModal, 2400);
                        } else {
                            var msg = (data && data.data && data.data.message) || 'Delivery could not be queued. Try again.';
                            showStatus(msg, 'error');
                        }
                    })
                    .catch(function () {
                        if (submitBtn) { submitBtn.disabled = false; submitBtn.textContent = 'Send report'; }
                        showStatus('Connection error. Check your network and try again.', 'error');
                    });
            }
        });

        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') { closeModal(); }
        });
    }

    window.OpsGateStableUI = {
        loadWorkspace: loadWorkspace,
        refreshTriagePanel: function () {
            return refreshPanel('opsgate-triage-live-panel');
        },
        refreshReportsPanel: function () {
            return refreshPanel('opsgate-reports-live-panel');
        },
        refreshAlertsPanel: function () {
            return refreshPanel('opsgate-alerts-live-panel');
        }
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', boot, { once: true });
    } else {
        boot();
    }
}());
