/* ============================================================
   legal.jsx — Shared renderer for the five TLI legal pages.
   Depends on: legal-content.jsx (window.LEGAL_DOCS / LEGAL_INDEX),
   page.jsx (window.Header), footer.jsx (window.Footer).
   Usage (per page):  <LegalPage slug="privacy" />
   ============================================================ */

function LegalStyles() {
  return (
    <style>{`
      .lg-hero {
        position: relative;
        padding: calc(var(--header-h, 75px) + clamp(40px, 7vw, 92px)) 0 clamp(36px, 5vw, 64px);
        border-bottom: 1px solid var(--border);
        background:
          radial-gradient(120% 140% at 88% -10%, rgba(235,207,0,0.10), rgba(235,207,0,0) 55%),
          var(--bg);
        overflow: hidden;
      }
      .lg-breadcrumb {
        display: flex; align-items: center; gap: 10px;
        font-size: 12px; letter-spacing: 0.16em; text-transform: uppercase;
        color: var(--fg-faded); font-weight: 600; margin-bottom: 28px;
      }
      .lg-breadcrumb a { color: var(--fg-faded); transition: color 150ms var(--ease-out); }
      .lg-breadcrumb a:hover { color: var(--accent); }
      .lg-breadcrumb .here { color: var(--fg-dim); }

      .lg-eyebrow {
        font-family: var(--font-text);
        font-weight: 600; font-size: 11px;
        letter-spacing: 0.28em; text-transform: uppercase;
        color: var(--accent);
        display: inline-flex; align-items: center; gap: 10px;
        margin-bottom: 18px;
      }
      .lg-eyebrow::before {
        content: ""; width: 22px; height: 2px; background: var(--accent); display: inline-block;
      }
      .lg-title {
        font-family: var(--font-display);
        font-weight: 500;
        font-size: clamp(40px, 6vw, 68px);
        line-height: 1.04; letter-spacing: -0.01em;
        color: var(--fg); margin: 0 0 22px;
      }
      .lg-intro {
        font-family: var(--font-display);
        font-weight: 400;
        font-size: clamp(17px, 1.9vw, 21px);
        line-height: 1.6; color: var(--fg-dim);
        max-width: 64ch; margin: 0;
      }
      .lg-dates {
        display: flex; flex-wrap: wrap; gap: 8px 28px;
        margin-top: 30px;
        font-family: var(--font-mono);
        font-size: 12px; letter-spacing: 0.04em;
        color: var(--fg-faded);
        font-variant-numeric: tabular-nums;
      }
      .lg-dates b { color: var(--fg-dim); font-weight: 500; }

      /* ---- Body layout: sticky TOC + content ---- */
      .lg-body { padding: clamp(48px, 6vw, 80px) 0 clamp(56px, 7vw, 96px); }
      .lg-grid {
        display: grid;
        grid-template-columns: 248px minmax(0, 1fr);
        gap: clamp(40px, 6vw, 84px);
        align-items: start;
      }
      .lg-toc {
        position: sticky; top: calc(var(--header-h, 75px) + 24px);
        align-self: start;
      }
      .lg-toc-label {
        font-size: 10.5px; letter-spacing: 0.24em; text-transform: uppercase;
        color: var(--fg-faded); font-weight: 700; margin-bottom: 16px;
        display: flex; align-items: center; gap: 8px;
      }
      .lg-toc-label::before { content: ""; width: 2px; height: 11px; background: var(--accent); }
      .lg-toc ol { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
      .lg-toc a {
        display: block; padding: 6px 12px;
        font-size: 13px; line-height: 1.4;
        color: var(--fg-faded);
        border-left: 2px solid transparent;
        transition: color 150ms var(--ease-out), border-color 150ms var(--ease-out);
      }
      .lg-toc a:hover { color: var(--fg); }
      .lg-toc a.active { color: var(--accent); border-left-color: var(--accent); }

      /* ---- Content typography ---- */
      .lg-content { max-width: 72ch; }
      .lg-content section { scroll-margin-top: calc(var(--header-h, 75px) + 20px); }
      .lg-content section + section { margin-top: 40px; }
      .lg-h2 {
        font-family: var(--font-display);
        font-weight: 500; font-size: clamp(22px, 2.6vw, 28px);
        line-height: 1.2; color: var(--fg);
        margin: 0 0 16px; padding-top: 4px;
      }
      .lg-h3 {
        font-family: var(--font-text);
        font-weight: 700; font-size: 14px;
        letter-spacing: 0.04em;
        color: var(--accent);
        margin: 24px 0 10px; text-transform: none;
      }
      .lg-content p {
        font-family: var(--font-text);
        font-size: 16px; line-height: 1.72;
        color: var(--fg-dim); margin: 0 0 16px;
      }
      .lg-content ul {
        list-style: none; margin: 4px 0 18px; padding: 0;
        display: flex; flex-direction: column; gap: 11px;
      }
      .lg-content ul li {
        position: relative; padding-left: 22px;
        font-family: var(--font-text);
        font-size: 16px; line-height: 1.66; color: var(--fg-dim);
      }
      .lg-content ul li::before {
        content: ""; position: absolute; left: 2px; top: 11px;
        width: 6px; height: 6px; background: var(--accent);
        transform: rotate(45deg);
      }

      /* ---- Table ---- */
      .lg-table-wrap { margin: 6px 0 22px; overflow-x: auto; border: 1px solid var(--border); border-radius: 6px; }
      .lg-table { width: 100%; border-collapse: collapse; min-width: 520px; }
      .lg-table th {
        text-align: left; vertical-align: top;
        font-family: var(--font-text); font-weight: 700;
        font-size: 10.5px; letter-spacing: 0.14em; text-transform: uppercase;
        color: var(--fg-dim);
        padding: 13px 18px; background: rgba(255,250,238,0.035);
        border-bottom: 1px solid var(--border-strong);
      }
      .lg-table td {
        font-family: var(--font-text); font-size: 14px; line-height: 1.5;
        color: var(--fg-dim); padding: 14px 18px;
        border-bottom: 1px solid var(--border);
        vertical-align: top;
      }
      .lg-table tr:last-child td { border-bottom: none; }
      .lg-table td:first-child { color: var(--fg); font-weight: 500; }

      /* ---- Callout ---- */
      .lg-callout {
        position: relative;
        border: 1px solid var(--border-gold-soft);
        background: rgba(235,207,0,0.05);
        border-radius: 8px;
        padding: 22px 26px;
        margin: 0 0 30px;
      }
      .lg-callout::before {
        content: ""; position: absolute; left: 0; top: 14px; bottom: 14px;
        width: 3px; background: var(--accent); border-radius: 2px;
      }
      .lg-callout-title {
        font-family: var(--font-display); font-weight: 600;
        font-size: 18px; color: var(--fg); margin: 0 0 8px;
      }
      .lg-callout p { font-size: 15px; line-height: 1.62; color: var(--fg-dim); margin: 0; }

      /* ---- Related docs ---- */
      .lg-related { margin-top: clamp(48px, 6vw, 72px); padding-top: 36px; border-top: 1px solid var(--border); }
      .lg-related-label {
        font-size: 10.5px; letter-spacing: 0.24em; text-transform: uppercase;
        color: var(--fg-faded); font-weight: 700; margin-bottom: 18px;
      }
      .lg-related-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 12px; }
      .lg-related-card {
        display: flex; align-items: center; justify-content: space-between; gap: 12px;
        border: 1px solid var(--border); border-radius: 6px;
        padding: 16px 18px; color: var(--fg);
        transition: border-color 160ms var(--ease-out), background 160ms var(--ease-out), transform 160ms var(--ease-out);
      }
      .lg-related-card:hover { border-color: var(--border-gold-soft); background: rgba(235,207,0,0.04); transform: translateY(-2px); }
      .lg-related-card span { font-family: var(--font-text); font-weight: 600; font-size: 14px; }
      .lg-related-card .arr { color: var(--accent); font-size: 15px; }

      @media (max-width: 880px) {
        .lg-grid { grid-template-columns: 1fr; gap: 32px; }
        .lg-toc {
          position: static;
          border: 1px solid var(--border); border-radius: 8px;
          padding: 18px 16px; background: rgba(255,250,238,0.02);
        }
        .lg-toc ol { display: grid; grid-template-columns: 1fr 1fr; gap: 0; }
        .lg-content { max-width: none; }
      }
      @media (max-width: 520px) {
        .lg-toc ol { grid-template-columns: 1fr; }
      }
    `}</style>
  );
}

function LegalTOC({ sections, activeId }) {
  return (
    <nav className="lg-toc" aria-label="On this page">
      <div className="lg-toc-label">On this page</div>
      <ol>
        {sections.map((s) => (
          <li key={s.id}>
            <a href={"#" + s.id}
              className={activeId === s.id ? "active" : ""}
              onClick={(e) => {
                e.preventDefault();
                const el = document.getElementById(s.id);
                if (el) {
                  const top = el.getBoundingClientRect().top + window.scrollY - ((window.innerHeight ? 0 : 0) + 96);
                  window.scrollTo({ top, behavior: "smooth" });
                  history.replaceState(null, "", "#" + s.id);
                }
              }}>
              {s.title}
            </a>
          </li>
        ))}
      </ol>
    </nav>
  );
}

function LegalBlock({ block }) {
  const [kind, a, b] = block;
  if (kind === "h3") return <h3 className="lg-h3">{a}</h3>;
  if (kind === "p") return <p>{a}</p>;
  if (kind === "ul") {
    return (
      <ul>
        {a.map((li, i) => <li key={i}>{li}</li>)}
      </ul>
    );
  }
  if (kind === "table") {
    return (
      <div className="lg-table-wrap">
        <table className="lg-table">
          <thead>
            <tr>{a.headers.map((h, i) => <th key={i}>{h}</th>)}</tr>
          </thead>
          <tbody>
            {a.rows.map((row, ri) => (
              <tr key={ri}>{row.map((cell, ci) => <td key={ci}>{cell}</td>)}</tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
  if (kind === "callout") {
    return (
      <div className="lg-callout">
        {a ? <div className="lg-callout-title">{a}</div> : null}
        <p>{b}</p>
      </div>
    );
  }
  return null;
}

function LegalPage({ slug }) {
  const { useState, useEffect, useMemo } = React;
  const doc = window.LEGAL_DOCS[slug];

  // Build sections: each "h2" starts a new section; following blocks until
  // the next "h2" belong to it. Leading non-h2 blocks (e.g. the Risk callout)
  // render in an unlabelled intro section.
  const { sections, tocSections } = useMemo(() => {
    const secs = [];
    let cur = null;
    let leadId = 0;
    doc.blocks.forEach((blk) => {
      if (blk[0] === "h2") {
        cur = { id: "s-" + (secs.length + 1), title: blk[1], blocks: [] };
        secs.push(cur);
      } else {
        if (!cur) {
          cur = { id: "lead-" + (leadId++), title: null, blocks: [] };
          secs.push(cur);
        }
        cur.blocks.push(blk);
      }
    });
    return { sections: secs, tocSections: secs.filter((s) => s.title) };
  }, [slug]);

  const [activeId, setActiveId] = useState(tocSections[0] ? tocSections[0].id : null);

  useEffect(() => {
    const ids = tocSections.map((s) => s.id);
    const onScroll = () => {
      const offset = (parseInt(getComputedStyle(document.documentElement).getPropertyValue("--header-h")) || 75) + 60;
      let current = ids[0];
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.getBoundingClientRect().top <= offset) current = id;
      }
      setActiveId(current);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [slug]);

  const related = window.LEGAL_INDEX.filter((d) => d.slug !== slug);

  return (
    <div id="top">
      <LegalStyles />
      <window.Header />

      <section className="lg-hero" data-screen-label={doc.title}>
        <div className="container">
          <div className="lg-breadcrumb">
            <a href="/">Home</a>
            <span aria-hidden="true">·</span>
            <span className="here">{doc.label}</span>
          </div>
          <div className="lg-eyebrow">{doc.eyebrow}</div>
          <h1 className="lg-title">{doc.title}</h1>
          <p className="lg-intro">{doc.intro}</p>
          <div className="lg-dates">
            <span>Effective date: <b>{doc.effective}</b></span>
            <span>Last updated: <b>{doc.updated}</b></span>
          </div>
        </div>
      </section>

      <div className="lg-body">
        <div className="container">
          <div className="lg-grid">
            <LegalTOC sections={tocSections} activeId={activeId} />

            <div className="lg-content">
              {sections.map((sec) => (
                <section key={sec.id} id={sec.id}>
                  {sec.title ? <h2 className="lg-h2">{sec.title}</h2> : null}
                  {sec.blocks.map((blk, i) => <LegalBlock key={i} block={blk} />)}
                </section>
              ))}

              <div className="lg-related">
                <div className="lg-related-label">Related documents</div>
                <div className="lg-related-grid">
                  {related.map((d) => (
                    <a key={d.slug} className="lg-related-card" href={d.file}>
                      <span>{d.label}</span>
                      <span className="arr" aria-hidden="true">→</span>
                    </a>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <window.Footer />
    </div>
  );
}

window.LegalPage = LegalPage;
