/* Documenten tabs — CSS radio primary, JS syncs Alpine */
(function () {
  var DEFAULT = 'overview';

  function radioId(tab) {
    return 'doctab-' + tab;
  }

  function getActiveTab() {
    var checked = document.querySelector('.doc-tab-input:checked');
    return (checked && checked.value) || window.__docActiveTab || DEFAULT;
  }

  function show(tab) {
    if (!tab) tab = DEFAULT;
    var radio = document.getElementById(radioId(tab));
    if (radio) radio.checked = true;
    document.querySelectorAll('#doc-tab-stage [data-tab-panel]').forEach(function (el) {
      el.classList.toggle('tab-active', el.getAttribute('data-tab-panel') === tab);
    });
    window.__docActiveTab = tab;
  }

  function syncAlpine(tab) {
    var hub = document.querySelector('.doc-hub');
    if (!hub || !window.Alpine) return;
    try {
      var d = Alpine.$data(hub);
      if (!d) return;
      if (d.activeTab !== tab) d.activeTab = tab;
      if (typeof d.onTabShown === 'function') d.onTabShown(tab);
    } catch (e) {
      console.warn('doc-tabs alpine', e);
    }
  }

  function onTabChange() {
    var tab = getActiveTab();
    window.__docActiveTab = tab;
    document.querySelectorAll('#doc-tab-stage [data-tab-panel]').forEach(function (el) {
      el.classList.toggle('tab-active', el.getAttribute('data-tab-panel') === tab);
    });
    syncAlpine(tab);
  }

  function bind() {
    document.querySelectorAll('.doc-tab-input').forEach(function (radio) {
      if (radio.dataset.bound) return;
      radio.dataset.bound = '1';
      radio.addEventListener('change', onTabChange);
    });
  }

  window.DocTabs = { show: show, getActive: getActiveTab };

  bind();
  document.addEventListener('DOMContentLoaded', function () {
    bind();
    show(window.__docActiveTab || getActiveTab());
  });
  document.addEventListener('alpine:initialized', function () {
    bind();
    show(window.__docActiveTab || getActiveTab());
    syncAlpine(getActiveTab());
  });
})();
