(function () {
    'use strict';

    var scanBtn   = document.getElementById('wa-scan-btn');
    var fixAllBtn = document.getElementById('wa-fix-all-btn');
    var cfg       = window.WEBABILITY_SCANNER || {};

    if (!cfg.ajax) return;

    // ── Scan ──
    if (scanBtn) {
        scanBtn.addEventListener('click', function (e) {
            e.preventDefault();
            scanSite();
        });
    }

    // ── Fix All ──
    if (fixAllBtn) {
        fixAllBtn.addEventListener('click', function (e) {
            e.preventDefault();
            applyAllFixes();
        });
    }

    // ── Delegated click handler ──
    document.addEventListener('click', function (e) {
        var catBtn = e.target.closest('.wa-category-btn');
        if (catBtn) {
            e.preventDefault();
            toggleCategory(catBtn);
            return;
        }

        var fixBtn = e.target.closest('.wa-fix-btn');
        if (fixBtn) {
            e.preventDefault();
            applySingleFix(fixBtn);
            return;
        }

        var viewBtn = e.target.closest('.wa-btn-view-scan');
        if (viewBtn && !viewBtn.disabled) {
            e.preventDefault();
            setActiveScan(viewBtn.getAttribute('data-url-key'));
            return;
        }

        var rescanBtn = e.target.closest('.wa-btn-rescan-url');
        if (rescanBtn) {
            e.preventDefault();
            var url = rescanBtn.getAttribute('data-url');
            var urlInput = document.getElementById('wa-scan-url') || document.getElementById('wa-scan-url-stored');
            if (urlInput) urlInput.value = url;
            scanSite();
            return;
        }

        var deleteBtn = e.target.closest('.wa-btn-delete-scan');
        if (deleteBtn) {
            e.preventDefault();
            deleteScan(deleteBtn.getAttribute('data-url-key'));
            return;
        }
    });

    function toggleCategory(btn) {
        var cat = btn.getAttribute('data-category');
        var panel = document.getElementById('wa-panel-' + cat);
        if (!panel) return;

        var isOpen = panel.classList.contains('wa-panel-open');

        // Close all panels
        var allPanels = document.querySelectorAll('.wa-issue-panel');
        var allBtns   = document.querySelectorAll('.wa-category-btn');
        for (var i = 0; i < allPanels.length; i++) {
            allPanels[i].classList.remove('wa-panel-open');
        }
        for (var j = 0; j < allBtns.length; j++) {
            allBtns[j].classList.remove('wa-category-open');
            allBtns[j].setAttribute('aria-expanded', 'false');
        }

        // Toggle this one
        if (!isOpen) {
            panel.classList.add('wa-panel-open');
            btn.classList.add('wa-category-open');
            btn.setAttribute('aria-expanded', 'true');
        }
    }

    function scanSite() {
        var urlInput = document.getElementById('wa-scan-url') || document.getElementById('wa-scan-url-stored');
        var url = urlInput ? urlInput.value : '';
        if (!url) return;

        var progress = document.getElementById('wa-scan-progress');
        var status   = document.getElementById('wa-scan-status');

        if (scanBtn) {
            scanBtn.disabled = true;
            scanBtn.textContent = 'Scanning\u2026';
        }
        if (progress) progress.style.display = 'block';
        if (status) status.textContent = 'Analyzing ' + url + ' \u2014 this may take up to 60 seconds\u2026';
        animateProgress();

        var fd = new FormData();
        fd.append('action', 'webability_acwg_scan');
        fd.append('nonce', cfg.nonce);
        fd.append('scan_url', url);

        fetch(cfg.ajax, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function (r) { return r.json(); })
            .then(function (j) {
                stopProgress();
                if (j.success) {
                    showToast('Scan complete \u2014 ' + j.data.meta.total_issues + ' issues found', 'success');
                    setTimeout(function () { window.location.reload(); }, 800);
                } else {
                    resetScanBtn();
                    showToast('Scan failed: ' + (j.data && j.data.msg ? j.data.msg : 'Unknown error'), 'error');
                }
            })
            .catch(function () {
                stopProgress();
                resetScanBtn();
                showToast('Network error during scan', 'error');
            });
    }

    function resetScanBtn() {
        if (!scanBtn) return;
        scanBtn.disabled = false;
        scanBtn.textContent = scanBtn.classList.contains('wa-btn-rescan') ? 'Re-scan' : 'Scan Now';
    }

    function animateProgress() {
        var fill = document.querySelector('.wa-progress-fill');
        if (!fill) return;
        fill.style.width = '0%';
        var w = 0;
        var interval = setInterval(function () {
            if (w >= 90) { clearInterval(interval); return; }
            w += Math.random() * 6;
            fill.style.width = Math.min(w, 90) + '%';
        }, 600);
        fill._interval = interval;
    }

    function stopProgress() {
        var fill = document.querySelector('.wa-progress-fill');
        if (fill && fill._interval) clearInterval(fill._interval);
        if (fill) fill.style.width = '100%';
        var progress = document.getElementById('wa-scan-progress');
        if (progress) {
            setTimeout(function () { progress.style.display = 'none'; }, 600);
        }
    }

    function setButtonLoading(btn, loadingText) {
        btn.disabled = true;
        btn.textContent = '';
        var spinner = document.createElement('span');
        spinner.className = 'wa-spinner';
        btn.appendChild(spinner);
        btn.appendChild(document.createTextNode(loadingText));
    }

    function createBadge(text) {
        var badge = document.createElement('span');
        badge.className = 'wa-badge-done';
        badge.textContent = '\u2713 ' + text;
        return badge;
    }

    function applySingleFix(btn) {
        var index = parseInt(btn.getAttribute('data-index'), 10);
        setButtonLoading(btn, 'Fixing\u2026');

        var fd = new FormData();
        fd.append('action', 'webability_acwg_apply_fix');
        fd.append('nonce', cfg.nonce);
        fd.append('fix_index', index);

        fetch(cfg.ajax, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function (r) { return r.json(); })
            .then(function (j) {
                if (j.success) {
                    var row = document.getElementById('wa-fix-row-' + index);
                    if (row) row.classList.add('wa-issue-fixed');
                    var badge = createBadge('Fixed');
                    btn.parentNode.replaceChild(badge, btn);
                    updateStats();
                    showToast(j.data.msg || 'Fix applied', 'success');
                } else {
                    btn.disabled = false;
                    btn.textContent = 'Apply Fix';
                    showToast('Fix failed: ' + (j.data && j.data.msg ? j.data.msg : 'Unknown error'), 'error');
                }
            })
            .catch(function () {
                btn.disabled = false;
                btn.textContent = 'Apply Fix';
                showToast('Network error', 'error');
            });
    }

    function applyAllFixes() {
        if (!fixAllBtn) return;
        setButtonLoading(fixAllBtn, 'Fixing all\u2026');

        var fd = new FormData();
        fd.append('action', 'webability_acwg_apply_all');
        fd.append('nonce', cfg.nonce);

        fetch(cfg.ajax, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function (r) { return r.json(); })
            .then(function (j) {
                if (j.success) {
                    var msg = j.data.applied + ' fixed';
                    if (j.data.failed > 0) msg += ', ' + j.data.failed + ' failed';
                    showToast(msg, j.data.failed > 0 ? 'error' : 'success');
                    setTimeout(function () { window.location.reload(); }, 1000);
                } else {
                    fixAllBtn.disabled = false;
                    fixAllBtn.textContent = 'Fix All';
                    showToast('Batch fix failed', 'error');
                }
            })
            .catch(function () {
                fixAllBtn.disabled = false;
                fixAllBtn.textContent = 'Fix All';
                showToast('Network error', 'error');
            });
    }

    // ── Set active scan (load URL detail) ──
    function setActiveScan(urlKey) {
        var fd = new FormData();
        fd.append('action', 'webability_acwg_set_active_scan');
        fd.append('nonce', cfg.nonce);
        fd.append('url_key', urlKey);

        fetch(cfg.ajax, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function (r) { return r.json(); })
            .then(function (j) {
                if (j.success) {
                    window.location.reload();
                } else {
                    showToast('Failed to load scan: ' + (j.data && j.data.msg ? j.data.msg : 'Unknown error'), 'error');
                }
            })
            .catch(function () {
                showToast('Network error', 'error');
            });
    }

    // ── Delete a scan ──
    function deleteScan(urlKey) {
        var fd = new FormData();
        fd.append('action', 'webability_acwg_delete_scan');
        fd.append('nonce', cfg.nonce);
        fd.append('url_key', urlKey);

        fetch(cfg.ajax, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function (r) { return r.json(); })
            .then(function (j) {
                if (j.success) {
                    var row = document.querySelector('tr[data-url-key="' + urlKey + '"]');
                    if (row) row.remove();
                    showToast('Scan removed', 'success');
                    // Update count
                    var remaining = document.querySelectorAll('.wa-scan-row-item');
                    var subtitle = document.querySelector('.wa-scans-subtitle');
                    if (subtitle) subtitle.textContent = remaining.length + ' pages scanned';
                    if (remaining.length === 0) {
                        setTimeout(function () { window.location.reload(); }, 500);
                    }
                } else {
                    showToast('Failed to remove scan', 'error');
                }
            })
            .catch(function () {
                showToast('Network error', 'error');
            });
    }

    // ── Update stats after a single fix ──
    function updateStats() {
        var fixedEls   = document.querySelectorAll('.wa-issue-fixed');
        var totalItems = document.querySelectorAll('.wa-issue-item');
        var fixed      = fixedEls.length;
        var total      = totalItems.length;
        var open       = total - fixed;
        var pct        = total > 0 ? Math.round((fixed / total) * 100) : 0;

        // Update stat tiles
        var tiles = document.querySelectorAll('.wa-stat-tile');
        for (var t = 0; t < tiles.length; t++) {
            var tile = tiles[t];
            if (tile.classList.contains('wa-stat-tile--fixed')) {
                var val = tile.querySelector('.wa-stat-tile-value');
                var sub = tile.querySelector('.wa-stat-tile-sub');
                if (val) val.textContent = fixed;
                if (sub) sub.textContent = pct + '% complete';
            }
            if (tile.classList.contains('wa-stat-tile--open')) {
                var val2 = tile.querySelector('.wa-stat-tile-value');
                var sub2 = tile.querySelector('.wa-stat-tile-sub');
                if (val2) val2.textContent = open;
                if (open === 0) {
                    tile.classList.add('wa-stat-tile--clear');
                    if (sub2) sub2.textContent = 'All clear';
                }
            }
        }

        // Update category counts
        var wrappers = document.querySelectorAll('.wa-category-wrapper');
        for (var i = 0; i < wrappers.length; i++) {
            var panel = wrappers[i].querySelector('.wa-issue-panel');
            var catBtn = wrappers[i].querySelector('.wa-category-btn');
            if (!panel || !catBtn) continue;

            var items = panel.querySelectorAll('.wa-issue-item');
            var fixedItems = panel.querySelectorAll('.wa-issue-fixed');
            var openCount = items.length - fixedItems.length;

            var countEl = catBtn.querySelector('.wa-category-count');

            if (openCount === 0) {
                catBtn.classList.add('wa-category-resolved');
                if (countEl) {
                    var check = document.createElement('span');
                    check.className = 'wa-category-check';
                    check.setAttribute('aria-label', 'All resolved');
                    check.textContent = '\u2713';
                    countEl.parentNode.replaceChild(check, countEl);
                }
            } else if (countEl) {
                countEl.textContent = openCount;
            }
        }

        // Hide fix-all if no more auto-fixable
        var remainingAuto = document.querySelectorAll('.wa-fix-btn:not(:disabled)');
        if (fixAllBtn && remainingAuto.length === 0) {
            fixAllBtn.style.display = 'none';
        }
    }

    // ── Toast notification ──
    function showToast(msg, type) {
        var toast = document.getElementById('wa-toast');
        if (!toast) return;
        toast.textContent = msg;
        toast.className = 'wa-toast wa-toast-' + (type || 'success');
        // Force reflow
        toast.offsetHeight;
        toast.classList.add('wa-toast-visible');
        setTimeout(function () {
            toast.classList.remove('wa-toast-visible');
        }, 3500);
    }
})();
