/*
  Theme toggle (A6). The no-flash init in ThemeScript already set data-theme before
  paint; this only wires the button, persists the choice, and keeps the aria-label
  describing the *next* action. Fail-silent if the button is absent.
*/
const html = document.documentElement;
const btn = document.getElementById('theme-toggle');

function labelFor(theme: string): string {
  if (!btn) return '';
  return theme === 'dark'
    ? (btn.dataset.toLight ?? '')
    : (btn.dataset.toDark ?? '');
}

if (btn) {
  btn.setAttribute('aria-label', labelFor(html.dataset.theme ?? 'dark'));
  btn.addEventListener('click', () => {
    const next = html.dataset.theme === 'light' ? 'dark' : 'light';
    html.dataset.theme = next;
    try {
      localStorage.setItem('theme', next);
    } catch {
      /* private mode — ignore */
    }
    btn.setAttribute('aria-label', labelFor(next));
  });
}
