/* Docs — reader shell: grouped left nav, article, right scroll-spy ToC,
 * breadcrumb, prev/next. Exports window.Docs. Content lives in docsContent.jsx. */
const DS_D = window.EquestrianismDesignSystem_6b57f9;

function scrollToId(id, smooth) {
  const el = document.getElementById(id);
  if (!el) return false;
  const y = el.getBoundingClientRect().top + window.scrollY - 84;
  window.scrollTo({ top: y, behavior: smooth ? 'smooth' : 'auto' });
  return true;
}

function scrollToIdWhenReady(id, tries) {
  tries = tries == null ? 40 : tries;
  if (scrollToId(id, false)) return;
  if (tries <= 0) return;
  setTimeout(() => scrollToIdWhenReady(id, tries - 1), 25);
}

function Docs({ target, onOpenSearch }) {
  const DOCS = window.EQ_DOCS, ORDER = window.EQ_DOC_ORDER;
  const [page, setPage] = React.useState(
    target && DOCS[target.pageId] ? target.pageId : 'quick-start');
  const [activeSec, setActiveSec] = React.useState(null);
  const bodyRef = React.useRef(null);
  const pendingSec = React.useRef(null);
  const { CodeBlock, Callout, Badge, Tag, Button } = DS_D;
  const doc = DOCS[page];

  // React to an external target (from search / nav)
  React.useEffect(() => {
    if (!(target && DOCS[target.pageId])) return;
    if (target.pageId === page) {
      if (target.sectionId) scrollToId(target.sectionId, true);
      else window.scrollTo({ top: 0 });
    } else {
      pendingSec.current = target.sectionId || '__top__';
      setPage(target.pageId);
    }
  }, [target]);

  // After the new page's DOM commits, honour any pending scroll target
  React.useLayoutEffect(() => {
    if (pendingSec.current == null) return;
    const sec = pendingSec.current; pendingSec.current = null;
    if (sec === '__top__') window.scrollTo({ top: 0 });
    else scrollToId(sec, false);
  }, [page]);

  // Scroll-spy over the current page's h2 sections
  React.useEffect(() => {
    const ids = doc.toc.map(t => t.id);
    const els = ids.map(id => document.getElementById(id)).filter(Boolean);
    if (!els.length) return;
    const obs = new IntersectionObserver((entries) => {
      const vis = entries.filter(e => e.isIntersecting)
        .sort((a,b) => a.boundingClientRect.top - b.boundingClientRect.top);
      if (vis[0]) setActiveSec(vis[0].target.id);
    }, { rootMargin: '-80px 0px -66% 0px', threshold: 0 });
    els.forEach(el => obs.observe(el));
    setActiveSec(ids[0]);
    return () => obs.disconnect();
  }, [page]);

  const groups = {};
  ORDER.forEach(id => { const g = DOCS[id].group; (groups[g] = groups[g] || []).push(id); });

  const idx = ORDER.indexOf(page);
  const prev = idx > 0 ? ORDER[idx-1] : null;
  const next = idx < ORDER.length-1 ? ORDER[idx+1] : null;

  const goto = (pid) => { setPage(pid); window.scrollTo({ top: 0 }); };

  return (
    <main className="wrap">
      <div className="docs">
        {/* left: page nav */}
        <nav className="docnav">
          <div className="searchtrigger" onClick={onOpenSearch} role="button" tabIndex={0}>
            <window.EqIcon name="search" size={15} />
            <span>Search docs</span>
            <span className="searchtrigger__kbd">⌘K</span>
          </div>
          {Object.entries(groups).map(([g, ids]) => (
            <div key={g}>
              <div className="docnav__grp">{g}</div>
              {ids.map(id => (
                <button key={id} className={`docnav__item ${id===page?'docnav__item--active':''}`}
                  onClick={() => goto(id)}>{DOCS[id].title}</button>
              ))}
            </div>
          ))}
        </nav>

        {/* middle: article */}
        <article className="doc__body" ref={bodyRef}>
          <div className="breadcrumb">
            <b>{doc.group}</b><span className="sep">/</span><span>{doc.title}</span>
          </div>
          <h1>{doc.title}</h1>
          <p className="doc__lead">{doc.lead}</p>
          {doc.render({ CodeBlock, Callout, Badge, Tag })}

          <div className="prevnext">
            {prev
              ? <button className="prevnext__btn" onClick={() => goto(prev)}>
                  <span className="prevnext__k">← Previous</span>
                  <span className="prevnext__t">{DOCS[prev].title}</span>
                </button>
              : <span></span>}
            {next
              ? <button className="prevnext__btn prevnext__btn--next" onClick={() => goto(next)}>
                  <span className="prevnext__k">Next →</span>
                  <span className="prevnext__t">{DOCS[next].title}</span>
                </button>
              : <span></span>}
          </div>
        </article>

        {/* right: on this page */}
        <aside className="doc-toc">
          <div className="doc-toc__h">On this page</div>
          {doc.toc.map(t => (
            <button key={t.id} className={`doc-toc__item ${t.id===activeSec?'doc-toc__item--active':''}`}
              onClick={() => scrollToId(t.id, true)}>{t.label}</button>
          ))}
        </aside>
      </div>
    </main>
  );
}
window.Docs = Docs;
