/*
  Theme toggle (A6). The no-flash init in ThemeScript already set data-theme before
  paint; this wires every toggle (header + mobile nav), persists the choice, and keeps
  each aria-label describing the *next* action. Fail-silent if none are present.
*/
const html = document.documentElement;
const toggles = document.querySelectorAll<HTMLElement>('[data-theme-toggle]');

function label(el: HTMLElement, theme: string): string {
  return theme === 'dark' ? (el.dataset.toLight ?? '') : (el.dataset.toDark ?? '');
}
function syncLabels(theme: string): void {
  toggles.forEach((el) => el.setAttribute('aria-label', label(el, theme)));
}

syncLabels(html.dataset.theme ?? 'dark');
toggles.forEach((el) =>
  el.addEventListener('click', () => {
    const next = html.dataset.theme === 'light' ? 'dark' : 'light';
    html.dataset.theme = next;
    try {
      localStorage.setItem('theme', next);
    } catch {
      /* private mode — ignore */
    }
    syncLabels(next);
  }),
);
