// ============================================================
// DEMIURGE — LEGAL DOCUMENT RENDERER
// Renders window.LEGAL_DOCS[window.__DOC__] with sticky ToC, working
// anchors, scrollspy, print styles, and document metadata.
// Depends on: site.js, site-chrome.jsx, legal-data.jsx.
// ============================================================

const Block = ({ block }) => {
  if (typeof block === 'string') return <p>{block}</p>;
  if (Array.isArray(block)) {
    const [kind, a, b] = block;
    if (kind === 'h3') return <h3>{a}</h3>;
    if (kind === 'list') return <ul>{a.map((it, i) => <li key={i}>{it}</li>)}</ul>;
    if (kind === 'olist') return <ol>{a.map((it, i) => <li key={i}>{it}</li>)}</ol>;
    if (kind === 'note') return <div className={`note ${b || ''}`}>{a}</div>;
  }
  return null;
};

const LegalDoc = ({ doc }) => {
  const [active, setActive] = React.useState(doc.sections[0] && doc.sections[0].id);

  React.useEffect(() => {
    const ids = doc.sections.map(s => s.id);
    const onScroll = () => {
      let current = ids[0];
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.getBoundingClientRect().top <= 120) current = id;
      }
      setActive(current);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [doc]);

  return (
    <React.Fragment>
      <a href="#doc-body" className="lp-skip">Skip to content</a>
      <div className="lp-starfield" aria-hidden="true"></div>
      <div className="lp-vignette" aria-hidden="true"></div>
      <SiteNav/>
      <main className="page-wrap">
        <section className="page-hero">
          <div className="lp">
            <a href="/legal" className="page-back">← Legal</a>
            <div className="lp-eyebrow">/ Legal · {doc.title}</div>
            <h1 className="page-h1">{doc.title}</h1>
            <p className="page-lede">{doc.description}</p>
            <div className="legal-meta">
              <span>Version <b>{doc.version}</b></span>
              <span>Effective <b>{doc.effectiveDate}</b></span>
              <span>Last updated <b>{doc.lastUpdated}</b></span>
              <span><button type="button" onClick={() => window.print()} style={{background:'none',border:'none',padding:0,color:'#8388a8',font:'inherit',cursor:'pointer',textDecoration:'underline'}}>Print / save PDF</button></span>
            </div>
          </div>
        </section>

        <section className="page-body" id="doc-body">
          <div className="lp">
            <div className="legal-grid">
              <nav className="legal-toc" aria-label="On this page">
                <div className="toc-h">On this page</div>
                {doc.sections.map(s => (
                  <a key={s.id} href={`#${s.id}`} className={active === s.id ? 'active' : ''}>{s.heading}</a>
                ))}
              </nav>
              <div className="prose">
                {doc.intro ? <p style={{fontSize: 16, color: '#c8ccdd'}}>{doc.intro}</p> : null}
                {doc.sections.map(s => (
                  <section key={s.id} id={s.id} aria-labelledby={`h-${s.id}`}>
                    <h2 id={`h-${s.id}`}>{s.heading}</h2>
                    {s.body.map((b, i) => <Block key={i} block={b}/>)}
                  </section>
                ))}
                <hr/>
                <p style={{fontFamily: 'Geist Mono', fontSize: 12, color: '#4a4f6b'}}>
                  {(window.SITE && window.SITE.legalName) || 'Demiurge Systems Ltd'} · {(window.SITE && window.SITE.registration) || 'Registered in England · 17109558'} · Document version {doc.version}.
                </p>
              </div>
            </div>
          </div>
        </section>
      </main>
      <SiteFooter/>
    </React.Fragment>
  );
};

(function mount() {
  const key = (typeof window !== 'undefined' && window.__DOC__) || 'privacy';
  const doc = (window.LEGAL_DOCS || {})[key];
  const root = document.getElementById('root');
  if (!doc) {
    root.innerHTML = '<p style="color:#f5f1e6;padding:120px 24px;text-align:center">Document not found.</p>';
    return;
  }
  document.title = `${doc.title} · Demiurge Systems`;
  ReactDOM.createRoot(root).render(<LegalDoc doc={doc}/>);
})();
