/* ===================================================================
   mtc. HTML system — formats/document/document.js
   Document behaviour: section scroll-spy + mobile contents menu.
   (Mermaid rendering is shared via core/mermaid.js.)
   =================================================================== */
(() => {
  /* ---- print / save-as-PDF button (screen only; hidden in @media print) ---- */
  const printBtn = document.createElement('button');
  printBtn.className = 'print-btn';
  printBtn.type = 'button';
  printBtn.setAttribute('aria-label', 'Print or save as PDF');
  printBtn.innerHTML =
    '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M6 9V2h12v7"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="13" width="12" height="9" rx="1"/></svg><span>PDF</span>';
  printBtn.addEventListener('click', () => window.print());
  document.body.appendChild(printBtn);

  const sidebar = document.querySelector('.doc-sidebar');
  const nav = sidebar && sidebar.querySelector('.doc-nav');
  if (!sidebar || !nav) return;

  /* ---- mobile contents toggle (hamburger) ---- */
  const toggle = document.createElement('button');
  toggle.className = 's-toggle';
  toggle.setAttribute('aria-label', 'Toggle contents');
  toggle.innerHTML =
    '<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M3 6h18M3 12h18M3 18h18"/></svg>';
  const logo = sidebar.querySelector('.s-logo');
  (logo || sidebar.firstChild).insertAdjacentElement('afterend', toggle);
  toggle.addEventListener('click', () => sidebar.classList.toggle('open'));

  /* ---- nav overflow affordances: a "more" chevron at the bottom edge of the
          list (fade masks are handled in CSS via the .more-above/.more-below
          classes toggled below) so it's obvious when more links exist than fit ---- */
  const moreCue = document.createElement('div');
  moreCue.className = 'doc-nav-more';
  moreCue.setAttribute('aria-hidden', 'true');
  moreCue.innerHTML =
    '<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M5 8.5l7 7 7-7"/></svg>';
  nav.insertAdjacentElement('afterend', moreCue);

  function updateNavHints() {
    const moreBelow = nav.scrollTop + nav.clientHeight < nav.scrollHeight - 1;
    const moreAbove = nav.scrollTop > 1;
    nav.classList.toggle('more-below', moreBelow);
    nav.classList.toggle('more-above', moreAbove);
    /* park the chevron just inside the bottom edge of the nav's visible area
       (the sidebar is its positioning context) */
    if (moreBelow) moreCue.style.top = (nav.offsetTop + nav.clientHeight - 30) + 'px';
  }
  nav.addEventListener('scroll', updateNavHints, { passive: true });
  window.addEventListener('resize', updateNavHints);

  /* ---- keep the active link visible inside the nav (scroll the rail, not the
          page) when scroll-spy moves it past the fold ---- */
  function revealInNav(a) {
    const navBox = nav.getBoundingClientRect();
    const aBox = a.getBoundingClientRect();
    if (aBox.top < navBox.top) {
      nav.scrollTo({ top: nav.scrollTop - (navBox.top - aBox.top) - 16, behavior: 'smooth' });
    } else if (aBox.bottom > navBox.bottom) {
      nav.scrollTo({ top: nav.scrollTop + (aBox.bottom - navBox.bottom) + 16, behavior: 'smooth' });
    }
  }

  /* ---- section nav: close on click + scroll-spy ---- */
  const links = Array.from(nav.querySelectorAll('a'));
  const byId = new Map(links.map(a => [a.getAttribute('href').slice(1), a]));
  links.forEach(a => a.addEventListener('click', () => sidebar.classList.remove('open')));

  const obs = new IntersectionObserver((entries) => {
    entries.forEach(e => {
      if (e.isIntersecting) {
        links.forEach(l => l.classList.remove('active'));
        const a = byId.get(e.target.id);
        if (a) { a.classList.add('active'); revealInNav(a); }
      }
    });
  }, { rootMargin: '-30% 0px -60% 0px', threshold: 0 });
  document.querySelectorAll('.doc-cover[id], .doc-section[id]').forEach(s => obs.observe(s));

  updateNavHints();
})();
