/* Legal pages — Terms of Use / Privacy Notice / Cookie Notice rendered in-app,
   Kestrel-themed, from the verbatim text in legal_content.jsx (window.LEGAL_DOCS).
   These REPLACE the old footer links that downloaded the .docx: same legal text,
   styled to match the site. Route: { page:'legal', doc:'terms'|'privacy'|'cookie' }. */

const LEGAL_CSS = `
.legal-wrap{max-width:1080px;margin:0 auto;}
.legal-switch{display:inline-flex;gap:4px;padding:4px;border:1px solid var(--line);border-radius:999px;background:var(--canvas-2);flex-wrap:wrap;}
.legal-switch button{appearance:none;border:none;cursor:pointer;background:transparent;font-family:var(--mono);font-size:12.5px;letter-spacing:.01em;color:var(--ink-3);padding:8px 16px;border-radius:999px;transition:background .2s var(--ease-quiet),color .2s var(--ease-quiet);}
.legal-switch button:hover{color:var(--ink);}
.legal-switch button[aria-current="true"]{background:var(--ink);color:var(--canvas);}
.legal-layout{display:grid;grid-template-columns:240px 1fr;gap:48px;margin-top:44px;align-items:start;}
.legal-toc{position:sticky;top:96px;}
.legal-toc-label{font-family:var(--mono);font-size:10px;font-weight:600;letter-spacing:.14em;text-transform:uppercase;color:var(--moss-deep);margin-bottom:14px;}
.legal-toc a{display:block;font-size:12.5px;line-height:1.45;color:var(--ink-3);text-decoration:none;padding:5px 0 5px 12px;border-left:2px solid var(--line);transition:color .15s,border-color .15s;}
.legal-toc a:hover{color:var(--moss-deep);border-left-color:var(--moss);}
.legal-body{max-width:680px;min-width:0;}
.legal-body h2{font-size:21px;font-weight:600;letter-spacing:-0.01em;color:var(--ink);margin:42px 0 14px;scroll-margin-top:90px;display:flex;gap:10px;align-items:baseline;}
.legal-body h2:first-child{margin-top:0;}
.legal-body h2 .legal-tick{color:var(--moss);font-size:13px;flex:0 0 auto;}
.legal-body h3{font-size:15px;font-weight:600;color:var(--ink);margin:26px 0 8px;}
.legal-body p{font-size:15px;line-height:1.72;color:var(--ink-2);margin:0 0 14px;}
.legal-body p.b{font-weight:600;color:var(--ink);}
.legal-body ul{margin:0 0 16px;padding:0;list-style:none;display:flex;flex-direction:column;gap:9px;}
.legal-body li{position:relative;font-size:14.5px;line-height:1.65;color:var(--ink-2);padding-left:20px;}
.legal-body li::before{content:"";position:absolute;left:2px;top:9px;width:6px;height:6px;border-radius:50%;background:var(--moss);}
.legal-meta-row{display:flex;flex-wrap:wrap;gap:8px 18px;margin-top:16px;}
.legal-meta{font-family:var(--mono);font-size:12px;color:var(--ink-3);}
.legal-foot{margin-top:64px;padding-top:24px;border-top:1px solid var(--line);display:flex;justify-content:space-between;gap:16px;flex-wrap:wrap;align-items:center;}
@media (max-width:860px){
  .legal-layout{grid-template-columns:1fr;gap:0;}
  .legal-toc{position:static;margin-bottom:32px;}
  .legal-toc-inner{display:flex;flex-wrap:wrap;gap:6px;}
  .legal-toc a{border-left:none;padding:6px 10px;background:var(--canvas-2);border-radius:8px;}
}
.legal-banner{display:inline-block;margin-top:18px;font-family:var(--mono);font-size:12px;letter-spacing:.02em;color:var(--ink-2);background:var(--canvas-2);border:1px solid var(--line);border-radius:999px;padding:7px 14px;}
.legal-actions{display:flex;gap:10px;margin-top:16px;flex-wrap:wrap;}
.legal-act-btn{display:inline-flex;align-items:center;gap:6px;font-family:var(--mono);font-size:12.5px;color:var(--ink);background:var(--canvas);border:1px solid var(--line);border-radius:999px;padding:8px 16px;cursor:pointer;text-decoration:none;}
.legal-act-btn:hover{border-color:var(--ink);}
@media print{
  header, footer, .legal-switch, .legal-toc, .legal-actions{display:none !important;}
  .legal-layout{grid-template-columns:1fr;gap:0;}
  .legal-body{max-width:none;}
  .legal-banner{border:none;padding:0;background:none;}
}
`;

/* Render the flat block list, batching consecutive list items into one <ul>. */
const renderLegalBlocks = (blocks) => {
  const out = [];
  let bucket = null;
  const flush = () => { if (bucket) { out.push(<ul key={`ul${out.length}`}>{bucket}</ul>); bucket = null; } };
  blocks.forEach((b, i) => {
    if (b.t === 'li') { (bucket = bucket || []).push(<li key={i}>{b.x}</li>); return; }
    flush();
    if (b.t === 'h2') out.push(<h2 key={i} id={b.id}><span className="legal-tick" aria-hidden="true">▸</span><span>{b.x}</span></h2>);
    else if (b.t === 'h3') out.push(<h3 key={i}>{b.x}</h3>);
    else if (b.t === 'meta') out.push(<p key={i} className="legal-meta" style={{ margin: '0 0 10px' }}>{b.x}</p>);
    else out.push(<p key={i} className={b.b ? 'b' : undefined}>{b.x}</p>);
  });
  flush();
  return out;
};

const LEGAL_DOCX_FILES = {
  terms: 'legal/Terms_of_Use_2026-06-15.docx',
  privacy: 'legal/Privacy_Notice_2026-06-15.docx',
  cookie: 'legal/Cookie_Notice_2026-06-15.docx',
};

const LegalPage = ({ docKey, setRoute }) => {
  const docs = window.LEGAL_DOCS || {};
  const order = (window.LEGAL_ORDER && window.LEGAL_ORDER.length ? window.LEGAL_ORDER : Object.keys(docs));
  const key = docs[docKey] ? docKey : order[0];
  const doc = docs[key];

  React.useEffect(() => { window.scrollTo({ top: 0, behavior: 'instant' }); }, [key]);
  if (!doc) return null;

  const metas = doc.blocks.filter((b) => b.t === 'meta');
  // Body = everything except the leading H1 (shown in the hero) and meta (shown as chips).
  let secN = 0;
  const body = doc.blocks
    .filter((b, i) => i !== 0 && b.t !== 'meta')
    .map((b) => (b.t === 'h2' ? { ...b, id: `legal-sec-${secN++}` } : b));
  const toc = body.filter((b) => b.t === 'h2');

  const jump = (e, id) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ block: 'start' });
  };

  return (
    <section className="section first">
      <style>{LEGAL_CSS}</style>
      <div className="site-wrap">
        <div className="legal-wrap">
          {/* Block wrapper forces the back button onto its own line — both it and
              .mono-eyebrow are inline-flex, so without this they collide on one line. */}
          <div style={{ marginBottom: 26 }}>
            <button onClick={() => setRoute({ page: 'home' })}
              style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, fontSize: 13, color: 'var(--ink-3)', fontFamily: 'var(--font-sans)' }}>
              <Icon name="arrow-left" size={12} /> Overview
            </button>
          </div>

          <div className="mono-eyebrow" style={{ marginBottom: 18 }}>Legal</div>
          <h1 className="spade-h" style={{ fontSize: 'clamp(30px, 5vw, 46px)' }}>{doc.title}</h1>
          {metas.length > 0 && (
            <div className="legal-meta-row">
              {metas.map((m, i) => <span key={i} className="legal-meta">{m.x}</span>)}
            </div>
          )}

          {/* Last Updated banner */}
          <div className="legal-banner">Last Updated: 15 June 2026</div>

          {/* Print + Download DOCX */}
          <div className="legal-actions">
            <button type="button" className="legal-act-btn" onClick={() => window.print()}>Print</button>
            {LEGAL_DOCX_FILES[key] && (
              <a className="legal-act-btn" href={LEGAL_DOCX_FILES[key]} download>Download DOCX</a>
            )}
          </div>

          {/* Document switcher */}
          <div style={{ marginTop: 26 }}>
            <div className="legal-switch" role="tablist" aria-label="Legal documents">
              {order.map((k) => (
                <button key={k} role="tab" aria-current={k === key} onClick={() => setRoute({ page: 'legal', doc: k })}>
                  {docs[k].label}
                </button>
              ))}
            </div>
          </div>

          <div className="legal-layout">
            <aside className="legal-toc" aria-label="On this page">
              <div className="legal-toc-label">On this page</div>
              <nav className="legal-toc-inner">
                {toc.map((s) => (
                  <a key={s.id} href={`#${s.id}`} onClick={(e) => jump(e, s.id)}>{s.x}</a>
                ))}
              </nav>
            </aside>

            <div className="legal-body">
              {renderLegalBlocks(body)}

              <div className="legal-foot">
                <span style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--ink-3)' }}>
                  Questions? <a href="#" onClick={(e) => { e.preventDefault(); setRoute({ page: 'contact' }); }} style={{ color: 'var(--moss-deep)' }}>Contact us</a>
                </span>
                <button onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
                  style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: 'transparent', border: '1px solid var(--line)', borderRadius: 999, padding: '7px 14px', cursor: 'pointer', fontFamily: 'var(--mono)', fontSize: 11.5, color: 'var(--ink-3)' }}>
                  Back to top <Icon name="arrow-left" size={11} style={{ transform: 'rotate(90deg)' }} />
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};
window.LegalPage = LegalPage;
