document.addEventListener("DOMContentLoaded", function () {
    setTheme();
    initEventButtons();
    showBody();
    updateCount();
});

let sCol = -1;
let sDir = 1;

function changeScope(scope) {
    if (scope === 'all') {
        window.location.href = baseurl + "/tools/wcag.php?all=1";
    } else {
        window.location.href = baseurl + "/tools/wcag.php";
    }
}

function updateCount() {
    const all = document.querySelectorAll('#tb tr:not(.empty)').length;
    const vis = document.querySelectorAll('#tb tr:not(.empty):not([style*="display: none"])').length;
    const rc = document.getElementById('rc');
    if (rc) {
        rc.textContent = vis === all ? all + ' domains' : vis + ' / ' + all;
    }
}

function applyFilters() {
    const sEl = document.getElementById('srch');
    const stEl = document.getElementById('fSt');
    const lvEl = document.getElementById('fLv');

    const s = sEl ? sEl.value.toLowerCase() : '';
    const st = stEl ? stEl.value.toLowerCase() : '';
    const lv = lvEl ? lvEl.value.toLowerCase() : '';

    document.querySelectorAll('#tb tr:not(.empty)').forEach(tr => {
        const ok = (!s || (tr.dataset.domain || '').toLowerCase().includes(s))
            && (!st || (tr.dataset.status || '').toLowerCase() === st)
            && (!lv || (tr.dataset.level || '').toLowerCase() === lv);

        tr.style.display = ok ? '' : 'none';
    });

    updateCount();
}

function sortBy(col, key) {
    if (sCol === col) {
        sDir *= -1;
    } else {
        sCol = col;
        sDir = 1;
    }

    const tb = document.getElementById('tb');
    if (!tb) return;

    const rows = [...tb.querySelectorAll('tr:not(.empty)')];

    rows.sort((a, b) => {
        const av = a.dataset[key] || '';
        const bv = b.dataset[key] || '';
        const an = parseFloat(av);
        const bn = parseFloat(bv);

        if (!isNaN(an) && !isNaN(bn)) {
            return (an - bn) * sDir;
        }

        return av.localeCompare(bv) * sDir;
    });

    document.querySelectorAll('.sa').forEach((el, i) => {
        el.textContent = i === col ? (sDir === 1 ? ' ▲' : ' ▼') : '';
    });

    rows.forEach(r => tb.appendChild(r));
}

function doExport(fmt) {
    const all = new URLSearchParams(window.location.search).get('all');
    window.location.href = baseurl + "/tools/wcag.php?action=export_" + fmt + (all === '1' ? '&all=1' : '');
}

function esc(s) {
    return String(s)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

function openPopup(domain) {
    const titleEl = document.getElementById('popTitle');
    const bodyEl = document.getElementById('popBody');
    const overlayEl = document.getElementById('ov');

    if (!titleEl || !bodyEl || !overlayEl) {
        return;
    }

    titleEl.textContent = domain;
    bodyEl.innerHTML = '<p class="loading">Loading…</p>';
    overlayEl.style.display = 'block';

    fetch(baseurl + '/tools/wcag.php?action=get_violations&domain=' + encodeURIComponent(domain))
        .then(r => {
            if (!r.ok) {
                throw new Error('HTTP ' + r.status);
            }
            return r.json();
        })
        .then(data => {
            if (isSessionError(data)) {
                closePopup();
                showSessionExpired();
                return;
            }
            renderPopup(data);
        })
        .catch(e => {
            bodyEl.innerHTML = '<p class="pop-err">Error: ' + esc(e.message) + '</p>';
        });
}

function closePopup(e) {
    const overlayEl = document.getElementById('ov');
    if (!overlayEl) {
        return;
    }

    if (!e || e.target === overlayEl) {
        overlayEl.style.display = 'none';
    }
}

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

function renderPopup(d) {
    const body = document.getElementById('popBody');
    if (!body) {
        return;
    }

    if (!d || d.error) {
        body.innerHTML = '<p class="pop-err">' + esc((d && d.error) || 'Unknown error') + '</p>';
        return;
    }

    const c = d.issueCounts || {};
    const v = d.violations || [];
    const inc = d.incomplete || [];

    let h = `<div class="pop-stats">
        <span>Status: <b>${esc(d.status || '—')}</b></span>
        <span>Level: <b>${esc(d.wcagLevel || '—')}</b></span>
        <span>Critical: <b>${c.critical || 0}</b></span>
        <span>Serious: <b>${c.serious || 0}</b></span>
        <span>Moderate: <b>${c.moderate || 0}</b></span>
        <span>Minor: <b>${c.minor || 0}</b></span>
        <span>Passes: <b>${d.passes || 0}</b></span>
        <span>Scanned: <b>${esc(d.scannedAt || '—')}</b></span>
    </div>`;

    if (d.finalUrl) {
        h += `<p class="pop-url">URL: <a href="${esc(d.finalUrl)}" target="_blank" rel="noopener">${esc(d.finalUrl)}</a></p>`;
    }

    if (d.error) {
        h += `<div class="pop-err">${esc(d.error)}</div>`;
    }

    h += `<div class="tabs">
        <div class="tab on" onclick="switchTab(this,'pv')">Violations (${v.length})</div>
        <div class="tab" onclick="switchTab(this,'pi')">Incomplete (${inc.length})</div>
    </div>
    <div class="panel on" id="pv">${v.length ? vList(v) : '<p class="none">No violations found.</p>'}</div>
    <div class="panel" id="pi">${inc.length ? vList(inc) : '<p class="none">No incomplete items.</p>'}</div>`;

    body.innerHTML = h;
}

function vList(list) {
    return list.map(v => {
        const tags = (v.tags || []).filter(t => /^wcag/.test(t)).join(' · ');
        const nodes = (v.nodes || []).slice(0, 5).map(n =>
            `<div class="vc-node">${esc(n.html || '')}<small>${esc(n.message || '')}</small></div>`
        ).join('');

        const badgeClass = {
            critical: 'bf',
            serious: 'bw',
            moderate: 'be',
            minor: 'bn'
        }[v.impact] || 'bn';

        return `<div class="vc">
            <div class="vc-hd">
                <span class="badge ${badgeClass}">${esc(v.impact || '')}</span>
                <strong>${esc(v.id || '')}</strong>
                <span class="vc-tags">${esc(tags)}</span>
                ${v.helpUrl ? `<a class="vc-help" href="${esc(v.helpUrl)}" target="_blank" rel="noopener" onclick="event.stopPropagation()">Help ↗</a>` : ''}
            </div>
            <div class="vc-body">${esc(v.description || '')}
                ${nodes ? '<div class="vc-nodes">' + nodes + '</div>' : ''}
            </div>
        </div>`;
    }).join('');
}

function switchTab(el, id) {
    document.querySelectorAll('.tab').forEach(t => t.classList.remove('on'));
    document.querySelectorAll('.panel').forEach(p => p.classList.remove('on'));

    el.classList.add('on');

    const panel = document.getElementById(id);
    if (panel) {
        panel.classList.add('on');
    }
}

function resetScan(btn, sid) {
    fetch(baseurl + '/tools/wcag.php?action=reset_scan&sid=' + sid)
        .then(r => r.json())
        .then(data => {
            if (isSessionError(data)) {
                showSessionExpired();
                return;
            }

            if (data.ok) {
                const row = btn.closest('tr');
                if (row) {
                    row.dataset.scanned = '';

                    const cells = row.querySelectorAll('td');
                    if (cells[7]) {
                        cells[7].textContent = '—';
                    }
                }
            } else {
                alert('Reset failed: ' + (data.error || 'unknown error'));
            }
        })
        .catch(e => {
            alert('Reset failed: ' + e.message);
        });
}

function isSessionError(data) {
    return data && (data.error === 'session_expired' || data.error === 'auth_required');
}

function showSessionExpired() {
    let el = document.getElementById('session-expired-msg');

    if (!el) {
        el = document.createElement('div');
        el.id = 'session-expired-msg';
        el.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:9999;display:flex;align-items:center;justify-content:center';
        el.innerHTML =
            '<div style="background:#fff;border-radius:10px;padding:32px 40px;text-align:center;max-width:380px;box-shadow:0 8px 40px rgba(0,0,0,.25)">' +
            '<div style="font-size:2em;margin-bottom:12px">&#x1F512;</div>' +
            '<h2 style="font-size:1.1em;margin-bottom:10px;color:#1e2235">Session Expired</h2>' +
            '<p style="color:#6b7280;font-size:0.92em;margin-bottom:20px">Your WMD session has ended. Please log in again to continue.</p>' +
            '<a href="' + baseurl + '/?logout&return=tools/wcag" style="display:inline-block;background:#1e2235;color:#fff;padding:9px 24px;border-radius:6px;text-decoration:none;font-size:0.9em">Log In Again</a>' +
            '</div>';
        document.body.appendChild(el);
    }

    el.style.display = 'flex';
}
