/**
 * Tabs: keyboard (Arrow Left/Right) and ARIA. Requires structure with
 * role="tablist", role="tab", role="tabpanel".
 *
 * Markup: add data-tabs to the .tabs container. Ensure [role="tablist"] contains
 * [role="tab"] buttons and sibling [role="tabpanel"] elements.
 *
 * Initialization: automatic. All .tabs[data-tabs] are wired on load (or on
 * DOMContentLoaded if the script runs before DOM ready).
 *
 * Programmatic API: Tabs.show(container, index) to switch to a tab by index.
 */
(function () {
  function getTabsPanels(tabsEl) {
    const list = tabsEl.querySelector('[role="tablist"]');
    const tabs = list ? list.querySelectorAll('[role="tab"]') : [];
    const panels = tabsEl.querySelectorAll('[role="tabpanel"]');
    return { tabs, panels };
  }

  function setTabIndex(tabsEl, index, focusTab = true) {
    const { tabs, panels } = getTabsPanels(tabsEl);
    if (!tabs.length || !panels.length || index < 0 || index >= tabs.length) return;
    tabs.forEach((t, i) => {
      const selected = i === index;
      t.setAttribute('aria-selected', selected);
      t.setAttribute('tabindex', selected ? 0 : -1);
    });
    panels.forEach((p, i) => {
      p.hidden = i !== index;
    });
    if (focusTab) tabs[index].focus();
  }

  function init() {
    document.querySelectorAll('.tabs[data-tabs]').forEach((tabsEl) => {
      const { tabs, panels } = getTabsPanels(tabsEl);
      if (!tabs.length || !panels.length) return;

      tabs.forEach((tab, index) => {
        tab.addEventListener('click', () => setTabIndex(tabsEl, index));
        tab.addEventListener('keydown', (e) => {
          if (e.key === 'ArrowLeft' && index > 0) {
            e.preventDefault();
            setTabIndex(tabsEl, index - 1);
          } else if (e.key === 'ArrowRight' && index < tabs.length - 1) {
            e.preventDefault();
            setTabIndex(tabsEl, index + 1);
          }
        });
      });

      const current = tabsEl.querySelector('[role="tab"][aria-selected="true"]');
      const startIndex = current ? Array.prototype.indexOf.call(tabs, current) : 0;
      setTabIndex(tabsEl, startIndex, false);
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

  window.Tabs = {
    /**
     * Switch to tab by index (0-based). container: .tabs element or selector.
     */
    show(container, index) {
      const el = typeof container === 'string' ? document.querySelector(container) : container;
      if (el?.classList.contains('tabs')) setTabIndex(el, index);
    }
  };
})();
