/* LEGAL PAGES — Terms of Service (/terms) and Privacy Policy (/privacy-policy).
   Text-heavy long-form reading pages. Shares the site header/footer (rendered by App),
   uses the same type tokens, and constrains line length for comfortable reading.
   Replace the body copy below with the finalised legal text when ready. */

/* ---- shared reading-page chrome ---- */
function LegalLayout({ eyebrow, title, effectiveDate, lastUpdated, intro, children }) {
  const { isMobile } = useBreakpoint();
  return (
    <div data-screen-label={'Legal · ' + title}>
      <section style={{ background: 'var(--paper)', padding: `clamp(24px, 4vw, 40px) var(--pad-x) clamp(64px, 9vw, 112px)` }}>
        <div style={{ maxWidth: 'var(--container-sm)', margin: '0 auto' }}>
          <Breadcrumbs trail={[{ l: 'Legal' }, { l: title }]} />

          <header style={{ marginTop: 28, paddingBottom: 'clamp(28px, 4vw, 44px)', borderBottom: '1px solid var(--bone)' }}>
            <Eyebrow>{eyebrow}</Eyebrow>
            <h1 style={{
              fontFamily: 'var(--font-display)', fontWeight: 300,
              fontSize: 'clamp(40px, 6vw, 76px)', lineHeight: 1.0, letterSpacing: '-0.04em',
              color: 'var(--ink)', margin: '18px 0 0',
            }}>{title}</h1>
            <div style={{
              marginTop: 20, display: 'flex', flexWrap: 'wrap', gap: '6px 24px',
              fontFamily: 'var(--font-mono)', fontSize: 12,
              letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--slate)',
            }}>
              {effectiveDate && <span>Effective date · {effectiveDate}</span>}
              {lastUpdated && <span>Last updated · {lastUpdated}</span>}
            </div>
            {intro &&
            <p style={{
              marginTop: 24, fontSize: 'clamp(16px, 1.5vw, 18px)', lineHeight: 1.7,
              color: 'var(--graphite)', maxWidth: '68ch',
            }}>{intro}</p>
            }
          </header>

          <div style={{ marginTop: 'clamp(32px, 5vw, 56px)' }}>
            {children}
          </div>
        </div>
      </section>
    </div>);

}

/* A numbered section with a scannable heading. `id` lets it be linked to directly. */
function LegalSection({ num, title, id, children }) {
  return (
    <section id={id} style={{ marginBottom: 'clamp(36px, 5vw, 52px)', scrollMarginTop: 112 }}>
      <h2 style={{
        fontFamily: 'var(--font-display)', fontWeight: 400,
        fontSize: 'clamp(22px, 2.6vw, 30px)', lineHeight: 1.2, letterSpacing: '-0.02em',
        color: 'var(--ink)', margin: '0 0 16px',
        display: 'flex', gap: 14, alignItems: 'baseline',
      }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: '0.62em', color: 'var(--slate)', fontWeight: 400 }}>{num}</span>
        <span>{title}</span>
      </h2>
      <div className="legal-prose" style={{ color: 'var(--graphite)' }}>
        {children}
      </div>
    </section>);

}

/* Shared prose styling for paragraphs / lists inside legal sections. */
const LEGAL_PROSE_CSS = `
.legal-prose p, .legal-prose li {
  font-size: clamp(15px, 1.4vw, 17px);
  line-height: 1.75;
  max-width: 68ch;
}
.legal-prose p { margin: 0 0 16px; }
.legal-prose p:last-child, .legal-prose ul:last-child { margin-bottom: 0; }
.legal-prose ul { margin: 0 0 16px; padding-left: 22px; }
.legal-prose li { margin-bottom: 8px; }
.legal-prose strong { color: var(--ink); font-weight: 600; }
.legal-prose a { color: var(--ink); text-decoration: underline; text-underline-offset: 2px; }
.legal-prose h3 {
  font-family: var(--font-sans); font-weight: 600;
  font-size: clamp(15px, 1.4vw, 17px); color: var(--charcoal);
  margin: 22px 0 8px;
}
.legal-table-wrap { margin: 0 0 20px; overflow-x: auto; -webkit-overflow-scrolling: touch; border: 1px solid var(--bone); border-radius: 8px; }
.legal-table { border-collapse: collapse; width: 100%; min-width: 520px; font-size: clamp(13px, 1.2vw, 15px); }
.legal-table th, .legal-table td { text-align: left; vertical-align: top; padding: 12px 16px; border-bottom: 1px solid var(--bone); line-height: 1.55; }
.legal-table thead th { background: var(--bone); color: var(--ink); font-family: var(--font-sans); font-weight: 600; letter-spacing: 0; position: sticky; top: 0; }
.legal-table tbody tr:last-child td { border-bottom: none; }
.legal-table td:first-child { color: var(--ink); font-weight: 500; }
.legal-table strong { color: var(--ink); font-weight: 600; }
.legal-table a { color: var(--ink); text-decoration: underline; text-underline-offset: 2px; }
`;

/* ---------- lightweight markdown rendering for legal copy ---------- */

// Turn email addresses, "Privacy Policy" and "Data Processing Agreement" mentions
// in a plain string into links. Privacy Policy -> #/privacy-policy (same hash route
// as the footer "Privacy" link); Data Processing Agreement -> #/data-processing-agreement
// (an unlisted page only reachable via these in-text links).
function linkifyEmails(text, kp) {
  const out = [];
  const re = /([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})|(Privacy Policy)|(Data Processing Agreement)/g;
  let last = 0, m, i = 0;
  while ((m = re.exec(text))) {
    if (m.index > last) out.push(text.slice(last, m.index));
    if (m[1]) {
      out.push(<a key={kp + '-e' + (i++)} href={'mailto:' + m[1]}>{m[1]}</a>);
    } else if (m[2]) {
      out.push(<Link key={kp + '-p' + (i++)} to="/privacy-policy">{m[2]}</Link>);
    } else {
      out.push(<Link key={kp + '-d' + (i++)} to="/data-processing-agreement">{m[3]}</Link>);
    }
    last = m.index + m[0].length;
  }
  if (last < text.length) out.push(text.slice(last));
  return out;
}

// Render inline markdown: **bold** and *italic* segments (with email/route linkification).
function renderInline(text, kp) {
  const parts = text.split(/(\*\*[\s\S]+?\*\*)/g);
  const nodes = [];
  parts.forEach((p, i) => {
    if (!p) return;
    if (/^\*\*[\s\S]+\*\*$/.test(p)) {
      nodes.push(<strong key={kp + '-s' + i}>{renderEmphasis(p.slice(2, -2), kp + '-s' + i)}</strong>);
    } else {
      nodes.push(<React.Fragment key={kp + '-f' + i}>{renderEmphasis(p, kp + '-f' + i)}</React.Fragment>);
    }
  });
  return nodes;
}

// Within a (possibly bold) run: handle *italic* then linkify the remaining text.
function renderEmphasis(text, kp) {
  const parts = text.split(/(\*[^*]+\*)/g);
  const nodes = [];
  parts.forEach((p, i) => {
    if (!p) return;
    if (/^\*[^*]+\*$/.test(p)) {
      nodes.push(<em key={kp + '-i' + i}>{linkifyEmails(p.slice(1, -1), kp + '-i' + i)}</em>);
    } else {
      nodes.push(<React.Fragment key={kp + '-t' + i}>{linkifyEmails(p, kp + '-t' + i)}</React.Fragment>);
    }
  });
  return nodes;
}

// Detect a GitHub-style pipe table block (header row, a --- separator row, then rows).
function isTableBlock(block) {
  const lines = block.split('\n').map((l) => l.trim());
  return lines.length >= 2 && /\|/.test(lines[0]) && /^\|?[\s:|-]*-[\s:|-]*\|?$/.test(lines[1]);
}

function splitRow(line) {
  let l = line.trim();
  if (l.startsWith('|')) l = l.slice(1);
  if (l.endsWith('|')) l = l.slice(0, -1);
  return l.split('|').map((c) => c.trim());
}

function renderTable(block, key) {
  const lines = block.split('\n').map((l) => l.trim()).filter(Boolean);
  const headers = splitRow(lines[0]);
  const rows = lines.slice(2).map(splitRow);
  return (
    <div className="legal-table-wrap" key={key}>
      <table className="legal-table">
        <thead>
          <tr>{headers.map((h, i) => <th key={i}>{renderInline(h, key + '-h' + i)}</th>)}</tr>
        </thead>
        <tbody>
          {rows.map((r, ri) =>
          <tr key={ri}>{r.map((c, ci) => <td key={ci}>{renderInline(c, key + '-r' + ri + 'c' + ci)}</td>)}</tr>
          )}
        </tbody>
      </table>
    </div>);

}

// One paragraph block; lines that begin "(a)" / "(iv)" are indented as sub-points,
// lines that begin "- " or "* " render as hanging bullets, and pipe-table blocks
// render as responsive tables.
function renderLegalBlock(block, key) {
  if (isTableBlock(block)) return renderTable(block, key);
  if (/^[-*]\s+/.test(block)) {
    return (
      <p key={key} style={{ paddingLeft: '1.5em', textIndent: '-0.9em' }}>
        <span aria-hidden="true">•&nbsp;&nbsp;</span>{renderInline(block.replace(/^[-*]\s+/, ''), key)}
      </p>);

  }
  const isSub = /^\([0-9a-z]+\)\s/i.test(block);
  return (
    <p key={key} style={isSub ? { paddingLeft: '1.6em' } : undefined}>
      {renderInline(block, key)}
    </p>);

}

// Parse the Terms markdown into { effectiveDate, lastUpdated, preambleBlocks, sections }.
function parseLegalMarkdown(md) {
  const blocksFrom = (t) => t.split(/\n\s*\n/).map((b) => b.trim()).filter(Boolean);
  const idx = md.indexOf('## ');
  const pre = idx >= 0 ? md.slice(0, idx) : md;
  const rest = idx >= 0 ? md.slice(idx) : '';

  const effectiveDate = ((pre.match(/Effective date:\s*(.+)/) || [])[1] || '').trim();
  const lastUpdated = ((pre.match(/Last updated:\s*(.+)/) || [])[1] || '').trim();
  const preambleBlocks = blocksFrom(pre).filter(
    (b) => !/^Effective date:/i.test(b) && !/^Last updated:/i.test(b));


  const sections = [];
  rest.split(/\n(?=## )/).forEach((chunk) => {
    const c = chunk.trim();
    if (!c.startsWith('## ')) return;
    const nl = c.indexOf('\n');
    const heading = (nl === -1 ? c : c.slice(0, nl)).replace(/^##\s+/, '').trim();
    const body = nl === -1 ? '' : c.slice(nl + 1);
    const hm = heading.match(/^([0-9]+[A-Z]?)\.\s*(.*)$/);
    const title = hm ? hm[2] : heading;
    sections.push({
      num: hm ? hm[1] : '',
      title,
      id: /cookie/i.test(title) ? 'cookies' : undefined,
      blocks: blocksFrom(body),
    });
  });

  return { effectiveDate, lastUpdated, preambleBlocks, sections };
}

/* ============================ TERMS OF SERVICE ============================ */
function TermsPage() {
  React.useEffect(() => {
    document.title = 'Terms of Service — ViZO Studio';
    return () => { document.title = 'ViZO Studio — Studio-quality fashion images.'; };
  }, []);

  const { effectiveDate, lastUpdated, preambleBlocks, sections } =
    React.useMemo(() => parseLegalMarkdown(window.TERMS_MD || ''), []);

  return (
    <React.Fragment>
      <style>{LEGAL_PROSE_CSS}</style>
      <LegalLayout
        eyebrow="Legal"
        title="Terms of Service"
        effectiveDate={effectiveDate}
        lastUpdated={lastUpdated}>

        {preambleBlocks.length > 0 &&
        <div className="legal-prose" style={{
          color: 'var(--graphite)',
          marginBottom: 'clamp(32px, 5vw, 52px)',
          paddingBottom: 'clamp(28px, 4vw, 40px)',
          borderBottom: '1px solid var(--bone)',
        }}>
            {preambleBlocks.map((b, i) => renderLegalBlock(b, 'pre' + i))}
          </div>
        }

        {sections.map((s, i) =>
        <LegalSection key={i} num={s.num} title={s.title}>
            {s.blocks.map((b, j) => renderLegalBlock(b, i + '-' + j))}
          </LegalSection>
        )}

      </LegalLayout>
    </React.Fragment>);

}

/* ============================ PRIVACY POLICY ============================ */
function PrivacyPolicyPage() {
  React.useEffect(() => {
    document.title = 'Privacy Policy — ViZO Studio';
    return () => { document.title = 'ViZO Studio — Studio-quality fashion images.'; };
  }, []);

  const { effectiveDate, lastUpdated, preambleBlocks, sections } =
    React.useMemo(() => parseLegalMarkdown(window.PRIVACY_MD || ''), []);

  return (
    <React.Fragment>
      <style>{LEGAL_PROSE_CSS}</style>
      <LegalLayout
        eyebrow="Legal"
        title="Privacy Policy"
        effectiveDate={effectiveDate}
        lastUpdated={lastUpdated}>

        {preambleBlocks.length > 0 &&
        <div className="legal-prose" style={{
          color: 'var(--graphite)',
          marginBottom: 'clamp(32px, 5vw, 52px)',
          paddingBottom: 'clamp(28px, 4vw, 40px)',
          borderBottom: '1px solid var(--bone)',
        }}>
            {preambleBlocks.map((b, i) => renderLegalBlock(b, 'pre' + i))}
          </div>
        }

        {sections.map((s, i) =>
        <LegalSection key={i} num={s.num} title={s.title} id={s.id}>
            {s.blocks.map((b, j) => renderLegalBlock(b, i + '-' + j))}
          </LegalSection>
        )}

      </LegalLayout>
    </React.Fragment>);

}

/* ===================== DATA PROCESSING AGREEMENT (unlisted) =====================
   Reachable only via in-text links from the Terms and Privacy pages, or by direct URL.
   Deliberately NOT added to the footer, nav, or any menu. */
function DataProcessingPage() {
  React.useEffect(() => {
    document.title = 'Data Processing Agreement — ViZO Studio';
    return () => { document.title = 'ViZO Studio — Studio-quality fashion images.'; };
  }, []);

  const { effectiveDate, lastUpdated, preambleBlocks, sections } =
    React.useMemo(() => parseLegalMarkdown(window.DPA_MD || ''), []);

  return (
    <React.Fragment>
      <style>{LEGAL_PROSE_CSS}</style>
      <LegalLayout
        eyebrow="Legal"
        title="Data Processing Agreement"
        effectiveDate={effectiveDate}
        lastUpdated={lastUpdated}>

        {preambleBlocks.length > 0 &&
        <div className="legal-prose" style={{
          color: 'var(--graphite)',
          marginBottom: 'clamp(32px, 5vw, 52px)',
          paddingBottom: 'clamp(28px, 4vw, 40px)',
          borderBottom: '1px solid var(--bone)',
        }}>
            {preambleBlocks.map((b, i) => renderLegalBlock(b, 'pre' + i))}
          </div>
        }

        {sections.map((s, i) =>
        <LegalSection key={i} num={s.num} title={s.title} id={s.id}>
            {s.blocks.map((b, j) => renderLegalBlock(b, i + '-' + j))}
          </LegalSection>
        )}

      </LegalLayout>
    </React.Fragment>);

}

Object.assign(window, { TermsPage, PrivacyPolicyPage, DataProcessingPage });
