const F = window.DocsFoundations, C = window.DocsComponents;
const NAV = [
  ['Get started', [['overview', 'Overview', F.OverviewPage]]],
  ['Foundations', [['foundations/tokens', 'Design tokens', F.TokensPage], ['foundations/color', 'Color', F.ColorPage], ['foundations/typography', 'Typography', F.TypographyPage], ['foundations/spacing', 'Spacing & layout', F.SpacingPage], ['foundations/shape', 'Shape & elevation', F.ShapePage], ['foundations/motion', 'Motion', F.MotionPage], ['foundations/iconography', 'Iconography', F.IconsPage]]],
  ['Content', [['content/voice', 'Voice & tone', F.VoicePage]]],
  ['Components', [['components/button', 'Button', C.ButtonPage], ['components/badge', 'Badge', C.BadgePage], ['components/input', 'Input', C.InputPage], ['components/card', 'Card', C.CardPage], ['components/section-heading', 'Section heading', C.HeadingPage], ['components/accordion', 'Accordion', C.AccordionPage], ['components/header-footer', 'Header & footer', C.HeaderFooterPage]]],
  ['Patterns', [['patterns/address-entry', 'Address entry', C.AddressPatternPage]]],
];
const FLAT = NAV.flatMap(([g, items]) => items.map(i => ({ group: g, route: i[0], label: i[1], C: i[2] })));
const getRoute = () => { const r = location.hash.replace(/^#\/?/, ''); return FLAT.some(p => p.route === r) ? r : 'overview'; };

function Toc({ route, mainRef }) {
  const [items, setItems] = React.useState([]);
  React.useEffect(() => {
    const t = setTimeout(() => {
      const hs = [...(mainRef.current?.querySelectorAll('.doc-h2') || [])];
      hs.forEach((h, i) => { h.id = 'h-' + i; });
      setItems(hs.map((h, i) => ['h-' + i, h.textContent]));
    }, 50);
    return () => clearTimeout(t);
  }, [route]);
  if (!items.length) return <aside className="docs-toc"></aside>;
  const jump = (e, id) => { e.preventDefault(); const el = document.getElementById(id); const m = mainRef.current; if (el && m) m.scrollTo({ top: el.offsetTop - 24, behavior: 'smooth' }); };
  return <aside className="docs-toc"><h4>On this page</h4>{items.map(([id, t]) => <a key={id} href={'#' + id} onClick={e => jump(e, id)}>{t}</a>)}</aside>;
}

function DocsApp() {
  const [route, setRoute] = React.useState(getRoute());
  const [q, setQ] = React.useState('');
  const [open, setOpen] = React.useState(false);
  const mainRef = React.useRef(null);
  React.useEffect(() => {
    const on = () => { setRoute(getRoute()); setOpen(false); if (mainRef.current) mainRef.current.scrollTop = 0; };
    window.addEventListener('hashchange', on); return () => window.removeEventListener('hashchange', on);
  }, []);
  const idx = FLAT.findIndex(p => p.route === route);
  const page = FLAT[idx]; const prev = FLAT[idx - 1]; const next = FLAT[idx + 1];
  const Cmp = page.C;
  const ql = q.toLowerCase();
  return (
    <div className="docs">
      <header className="docs-top">
        <button className="docs-menu" onClick={() => setOpen(!open)} aria-label="Menu">{open ? 'Close' : 'Menu'}</button>
        <a className="docs-brand" href="#/overview"><b>7NOW</b><span>Design System</span></a>
        <nav className="docs-top__links">
          <a href="#/foundations/tokens">Foundations</a><a href="#/components/button">Components</a><a href="#/content/voice">Content</a><a href="../ui_kits/website/index.html">UI kit</a>
        </nav>
      </header>
      <div className="docs-body">
        <nav className={'docs-side' + (open ? ' is-open' : '')} aria-label="Documentation">
          <input className="docs-search" placeholder="Search docs" value={q} onChange={e => setQ(e.target.value)} />
          {NAV.map(([g, items]) => {
            const vis = items.filter(i => !ql || i[1].toLowerCase().includes(ql) || g.toLowerCase().includes(ql));
            if (!vis.length) return null;
            return <div className="docs-navgroup" key={g}><h4>{g}</h4>{vis.map(([r, l]) => <a key={r} href={'#/' + r} className={r === route ? 'is-active' : ''}>{l}</a>)}</div>;
          })}
        </nav>
        <main className="docs-main" ref={mainRef}>
          <div className="docs-content">
            <div style={{ minWidth: 0 }}>
              <Cmp key={route} />
              <div className="docs-pager">
                {prev && <a href={'#/' + prev.route}><small>Previous</small>{prev.label}</a>}
                {next && <a href={'#/' + next.route}><small>Next</small>{next.label}</a>}
              </div>
            </div>
            <Toc route={route} mainRef={mainRef} />
          </div>
        </main>
      </div>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<DocsApp />);
