(() => {
  'use strict';
  document.documentElement.classList.replace('no-js', 'js');
  const toggle = document.querySelector('.nav-toggle');
  const nav = document.getElementById('site-nav');
  const close = () => { toggle?.setAttribute('aria-expanded', 'false'); nav?.classList.remove('open'); };
  toggle?.addEventListener('click', () => {
    const open = toggle.getAttribute('aria-expanded') !== 'true';
    toggle.setAttribute('aria-expanded', String(open)); nav?.classList.toggle('open', open);
  });
  nav?.addEventListener('click', event => { if (event.target.closest('a')) close(); });
  document.addEventListener('keydown', event => {
    if (event.key === 'Escape' && nav?.classList.contains('open')) { close(); toggle?.focus(); }
  });
  document.addEventListener('click', event => {
    if (nav?.classList.contains('open') && !nav.contains(event.target) && !toggle.contains(event.target)) close();
  });
  matchMedia('(min-width: 761px)').addEventListener('change', event => { if (event.matches) close(); });
  const cases = {
    block: { verdict:'BLOCK', base:7, candidate:10, total:20, gains:6, regressions:3, ties:11, note:'The score improved. Three regressions still block promotion.' },
    pass: { verdict:'PASS', base:6, candidate:13, total:16, gains:7, regressions:0, ties:9, note:'Seven gains, no regressions. This separate local comparison earned promotion.' },
    hold: { verdict:'HOLD', base:7, candidate:7, total:20, gains:0, regressions:0, ties:20, note:'Identical paired outcomes. There is no evidence of improvement.' }
  };
  document.getElementById('demo-case')?.addEventListener('change', event => {
    const data = cases[event.target.value]; if (!data) return;
    for (const [id, value] of [['demo-gains',`+${data.gains}`],['demo-regressions',data.regressions],['demo-ties',data.ties],['demo-explanation',data.note]]) document.getElementById(id).textContent = value;
    const verdict = document.getElementById('demo-verdict');
    verdict.textContent = data.verdict;
    verdict.className = 'status' + (data.verdict === 'BLOCK' ? ' status-red' : data.verdict === 'PASS' ? ' status-green' : '');
    document.getElementById('demo-baseline').innerHTML = `${data.base}<span>/${data.total}</span>`;
    document.getElementById('demo-candidate').innerHTML = `${data.candidate}<span>/${data.total}</span>`;
  });
  document.querySelectorAll('[data-filter]').forEach(button => button.addEventListener('click', () => {
    const filter = button.dataset.filter;
    document.querySelectorAll('[data-filter]').forEach(item => item.setAttribute('aria-pressed', String(item === button)));
    let count = 0;
    document.querySelectorAll('[data-category]').forEach(row => { row.hidden = filter !== 'all' && row.dataset.category !== filter; if (!row.hidden) count++; });
    document.getElementById('filter-count').textContent = `${count} ${count === 1 ? 'tool' : 'tools'}`;
  }));
})();
