/* Accessible tabs (WAI-ARIA): click + Arrow-key roving tabindex. First panel
   is visible without JS (authors mark only non-first panels hidden). */
(function () {
  function initTabs(root) {
    const tabs = Array.from(root.querySelectorAll(".tab"));
    const panels = Array.from(root.querySelectorAll(".tabpanel"));
    if (!tabs.length) return;
    function select(i) {
      tabs.forEach((t, k) => {
        const on = k === i;
        t.setAttribute("aria-selected", on);
        t.tabIndex = on ? 0 : -1;
        if (panels[k]) panels[k].hidden = !on;
      });
    }
    tabs.forEach((t, i) => {
      t.addEventListener("click", () => select(i));
      t.addEventListener("keydown", (e) => {
        let j = null;
        if (e.key === "ArrowRight") j = (i + 1) % tabs.length;
        if (e.key === "ArrowLeft") j = (i - 1 + tabs.length) % tabs.length;
        if (j !== null) { e.preventDefault(); tabs[j].focus(); select(j); }
      });
    });
    select(0);
  }
  function build() {
    document.querySelectorAll(".tabs").forEach((t) => {
      if (!t.dataset.bound) { t.dataset.bound = "1"; initTabs(t); }
    });
  }
  document.addEventListener("DOMContentLoaded", build);
  document.addEventListener("partials:loaded", build);
})();
