/* Tab switching — enige bron van waarheid voor zichtbaarheid (geen hidden attr) */
(function () {
  var DEFAULT = 'overview';

  function show(tab) {
    if (!tab) tab = DEFAULT;
    document.querySelectorAll('.doc-hub [data-tab-panel]').forEach(function (el) {
      var on = el.getAttribute('data-tab-panel') === tab;
      el.classList.toggle('tab-active', on);
    });
    document.querySelectorAll('#doc-nav .doc-nav-btn[data-tab]').forEach(function (btn) {
      btn.classList.toggle('active', btn.getAttribute('data-tab') === tab);
    });
  }

  function onClick(ev) {
    var btn = ev.target.closest('.doc-nav-btn[data-tab]');
    if (!btn) return;
    ev.preventDefault();
    ev.stopPropagation();
    var tab = btn.getAttribute('data-tab');
    show(tab);
    var hub = document.querySelector('.doc-hub');
    if (hub && window.Alpine) {
      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', e);
      }
    }
  }

  function bind() {
    var nav = document.getElementById('doc-nav');
    if (!nav || nav.dataset.bound) return;
    nav.dataset.bound = '1';
    nav.addEventListener('click', onClick, true);
    show(DEFAULT);
  }

  window.DocTabs = { show: show };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', bind);
  } else {
    bind();
  }
  document.addEventListener('alpine:initialized', function () {
    show(window.__docActiveTab || DEFAULT);
  });
})();
