/* Platform (pods + BI + signals), Connectors, Batch — sections 7-10 */

const Platform = () => (
  <section id="platform">
    <div className="container">
      <div className="section-head">
        <span className="eyebrow"><span className="dot"/> The platform</span>
        <h2>Everything, <span className="italic-serif hl-accent">organized</span>. Everything, <span className="italic-serif hl-accent">visible</span>.</h2>
        <p>
          Manage all your firm's data across knowledge pods. Query across many at once. Get live
          dashboards, real-time signals, and standing queries — all cited back to the source, all on
          private AI.
        </p>
      </div>

      {/* Row 1 — Pods & multi-pod querying */}
      <div className="feature-row">
        <div className="feature-copy">
          <div className="step">01 · Knowledge pods</div>
          <h3>Pods for every client, project, or domain.</h3>
          <p className="lede">Each pod holds one team's documents with its own AI, its own access controls, and its own audit trail. Managers can query across many pods at once — surfacing patterns and risks no single team would have caught.</p>
          <ul>
            <li>Unlimited pods — client, project, or department</li>
            <li>Admin / Editor / Viewer permissions per pod</li>
            <li>Cross-pod queries with per-viewer redaction</li>
            <li>Every answer cited back to source clauses</li>
          </ul>
        </div>
        <div className="widget">
          <div className="widget-head">
            <span>hub.yourcompany.com / pods</span>
            <span className="pill live">Live</span>
          </div>
          <div className="widget-body" style={{display:'flex', flexDirection:'column', gap:14}}>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10}}>
              {[
                { name: 'Client: Acme Co.', docs: '412 docs', color: 'var(--accent)' },
                { name: 'Finance & Audit', docs: '1,204 docs', color: '#2A2925' },
                { name: 'Legal Templates', docs: '287 docs', color: '#6B6862' },
                { name: 'Tax Advisory', docs: '156 docs', color: '#b06614' },
              ].map(p => (
                <div key={p.name} style={{border:'1px solid var(--line)', borderRadius:10, padding:'12px 14px', background:'var(--bg)'}}>
                  <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:6}}>
                    <div style={{width:10, height:10, borderRadius:3, background:p.color}}/>
                    <span style={{fontSize:13, fontWeight:500}}>{p.name}</span>
                  </div>
                  <div style={{fontFamily:'var(--font-mono)', fontSize:11, color:'var(--muted)'}}>{p.docs}</div>
                </div>
              ))}
            </div>
            <div style={{padding:'12px 14px', borderRadius:10, background:'var(--accent-tint)', border:'1px solid var(--accent-soft)', fontSize:13, color:'var(--accent-ink)'}}>
              <div style={{fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'0.14em', textTransform:'uppercase', marginBottom:4}}>Cross-pod query</div>
              Compare Acme &amp; Borealis revenue Q1–Q3 · 4 pods
            </div>
          </div>
        </div>
      </div>

      {/* Row 2 — Dashboards — animated docs → table → chart */}
      <div className="feature-row reverse">
        <div className="feature-copy">
          <div className="step">02 · Automated BI</div>
          <h3>From a pile of documents to a live chart — automatically.</h3>
          <p className="lede">Traditional BI can't touch contracts, PDFs, decks, and emails — where 80% of your intelligence lives. dFusion extracts, structures and visualizes it on the fly. Prompt it. Chart it. Decide.</p>
          <ul>
            <li>Unstructured docs → structured tables → live charts</li>
            <li>Drag pods onto a canvas — every widget cited to source</li>
            <li>Per-viewer permissions — one dashboard, many views</li>
            <li>No data modeling, no ETL, no analyst in the loop</li>
          </ul>
        </div>
        <BIAnimation />
      </div>

      {/* Row 3 — Signals */}
      <div className="feature-row">
        <div className="feature-copy">
          <div className="step">03 · Signals</div>
          <h3>Set a condition. Get alerted the moment it's true.</h3>
          <p className="lede">Signals watch your data in real time. The moment a document hits a pod, the AI processes it — and if your condition is met, you're notified instantly. No polling, no analyst.</p>
          <ul>
            <li>"Alert me whenever a supplier's price rises above 10%"</li>
            <li>"Alert me whenever a regulation cited in our contracts changes"</li>
            <li>"Alert me whenever inventory drops below reorder point"</li>
            <li>"Alert me whenever a client is mentioned in any pod"</li>
          </ul>
        </div>
        <div className="widget">
          <div className="widget-head">
            <span>hub.yourcompany.com / signals</span>
            <span className="pill live">Live feed</span>
          </div>
          <div className="widget-body" style={{padding:'8px 20px'}}>
            <div className="signal">
              <div className="signal-dot"/>
              <div className="signal-body">
                <div className="signal-title">Supplier price delta — Vendor D up 22% YoY</div>
                <div className="signal-meta">Procurement · Vendor_D_Contract_2026.pdf · 2m ago</div>
              </div>
            </div>
            <div className="signal">
              <div className="signal-dot g"/>
              <div className="signal-body">
                <div className="signal-title">Regulation change — GDPR Art. 28 updated</div>
                <div className="signal-meta">Compliance · EU_Update_2026.pdf · 18m ago</div>
              </div>
            </div>
            <div className="signal">
              <div className="signal-dot"/>
              <div className="signal-body">
                <div className="signal-title">Client A mentioned in 3 new clauses</div>
                <div className="signal-meta">Legal Templates · Vendor_Amend_Oct26.pdf · 1h ago</div>
              </div>
            </div>
            <div className="signal">
              <div className="signal-dot g"/>
              <div className="signal-body">
                <div className="signal-title">NDA expiry — Vendor D · 12 days</div>
                <div className="signal-meta">Legal Templates · no renewal clause found · 3h ago</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Row 4 — Automations */}
      <div className="feature-row reverse">
        <div className="feature-copy">
          <div className="step">04 · Automations</div>
          <h3>Standing orders. Reports on cadence. Zero handoffs.</h3>
          <p className="lede">Turn any query into a scheduled task. Run it hourly, daily, or every time a document lands. The AI cross-references, drafts, files — and delivers to the right stakeholder without anyone asking.</p>
          <ul>
            <li>Any query → hourly / daily / on-upload cadence</li>
            <li>Multi-step workflows: extract → reconcile → draft → file</li>
            <li>Results delivered as reports, dashboards, or alerts</li>
            <li>Full audit log of every run</li>
          </ul>
        </div>
        <div className="widget">
          <div className="widget-head">
            <span>Scheduled queries</span>
            <span>+ New query</span>
          </div>
          <div className="widget-body">
            {[
              { q: 'Weekly revenue summary', p: 'Finance · 5 pods', c: 'Daily', s: 'Ran 6h ago' },
              { q: 'Legal agreement expirations', p: 'Legal Templates', c: 'Daily', s: 'Ran 6h ago' },
              { q: 'Supplier price delta scan', p: 'Procurement', c: 'Hourly', s: 'Running…' },
              { q: 'Client A activity digest', p: 'Client: Acme', c: 'On upload', s: 'Live' },
              { q: 'Compliance gap report', p: 'Compliance · Legal', c: 'Weekly', s: 'Ran 2d ago' },
            ].map((r, i) => (
              <div key={i} className="dash-row" style={{flexDirection:'column', alignItems:'stretch', gap:4, padding:'12px 0'}}>
                <div style={{display:'flex', justifyContent:'space-between'}}>
                  <span style={{fontWeight:500}}>{r.q}</span>
                  <span style={{fontFamily:'var(--font-mono)', fontSize:11, color:r.s==='Running…'||r.s==='Live'?'var(--accent-ink)':'var(--muted)'}}>{r.s}</span>
                </div>
                <div style={{fontFamily:'var(--font-mono)', fontSize:11, color:'var(--muted)', display:'flex', gap:8}}>
                  <span>{r.p}</span>·<span>{r.c}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  </section>
);

const BIAnimation = () => {
  const [stage, setStage] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setStage(s => (s + 1) % 3), 2600);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="widget bi-anim">
      <div className="widget-head">
        <span>Prompt · "Track supplier price changes YoY across our contracts"</span>
        <span className="pill live">Live</span>
      </div>
      <div className="bi-stages">
        <div className={`bi-stage-label ${stage===0?'on':''}`}>Documents</div>
        <div className={`bi-stage-arrow ${stage>=1?'on':''}`}>→</div>
        <div className={`bi-stage-label ${stage===1?'on':''}`}>Structured table</div>
        <div className={`bi-stage-arrow ${stage>=2?'on':''}`}>→</div>
        <div className={`bi-stage-label ${stage===2?'on':''}`}>Live chart</div>
      </div>
      <div className="bi-view">
        {/* Stage 0: Documents */}
        <div className={`bi-slide ${stage===0?'on':''}`}>
          <div className="doc-stack">
            {['Vendor_A_MSA_2025.pdf','Vendor_B_MSA_2025.pdf','Vendor_C_Amend.pdf','Vendor_D_Contract.pdf','Vendor_E_SoW.pdf','Vendor_F_Renewal.pdf'].map((d, i) => (
              <div key={d} className="doc" style={{animationDelay:`${i*80}ms`}}>
                <div className="doc-icon">PDF</div>
                <div className="doc-info">
                  <div className="doc-name">{d}</div>
                  <div className="doc-sub">Procurement pod · scanning…</div>
                </div>
                <div className="doc-check">✓</div>
              </div>
            ))}
          </div>
        </div>
        {/* Stage 1: Table */}
        <div className={`bi-slide ${stage===1?'on':''}`}>
          <div className="bi-table">
            <div className="tr th">
              <div>Vendor</div><div>2024 price</div><div>2025 price</div><div>Δ YoY</div><div>Source</div>
            </div>
            {[
              ['Vendor A','$412,000','$481,000','+16.7%','MSA_2025.pdf'],
              ['Vendor B','$95,200','$99,500','+4.5%','MSA_2025.pdf'],
              ['Vendor C','$220,000','$268,400','+22.0%','Amend.pdf'],
              ['Vendor D','$88,700','$91,300','+2.9%','Contract.pdf'],
              ['Vendor E','$54,300','$52,700','-2.9%','SoW.pdf'],
            ].map((r, i) => (
              <div key={i} className="tr" style={{animationDelay:`${i*70}ms`}}>
                <div>{r[0]}</div>
                <div className="mono">{r[1]}</div>
                <div className="mono">{r[2]}</div>
                <div className={`mono ${r[3].startsWith('-')?'neg':'pos'}`}>{r[3]}</div>
                <div className="mono muted">{r[4]}</div>
              </div>
            ))}
          </div>
        </div>
        {/* Stage 2: Chart */}
        <div className={`bi-slide ${stage===2?'on':''}`}>
          <div className="bi-chart-wrap">
            <div className="bi-chart-title">
              <div>YoY price change by supplier</div>
              <span className="cite">5 contracts · cited</span>
            </div>
            <div className="bi-chart">
              {[
                {v:'Vendor C', p:22, d:'+22.0%'},
                {v:'Vendor A', p:17, d:'+16.7%'},
                {v:'Vendor B', p:5, d:'+4.5%'},
                {v:'Vendor D', p:3, d:'+2.9%'},
                {v:'Vendor E', p:-3, d:'-2.9%'},
              ].map((b, i) => (
                <div key={b.v} className="bi-row" style={{animationDelay:`${i*90}ms`}}>
                  <div className="bi-lbl">{b.v}</div>
                  <div className="bi-bar-track">
                    <div className={`bi-bar ${b.p<0?'neg':''}`} style={{width:`${Math.abs(b.p)*4}%`}}/>
                  </div>
                  <div className={`bi-val ${b.p<0?'neg':'pos'}`}>{b.d}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const CONNECTORS = [
  { n: 'SharePoint', s: 'MCP · live', logo: 'LogoSharePoint' },
  { n: 'Google Drive', s: 'MCP · live', logo: 'LogoGoogleDrive' },
  { n: 'Microsoft Teams', s: 'API · live', logo: 'LogoTeams' },
  { n: 'OneDrive', s: 'MCP · live', logo: 'LogoOneDrive' },
  { n: 'HubSpot', s: 'API · live', logo: 'LogoHubSpot' },
  { n: 'Salesforce', s: 'API · live', logo: 'LogoSalesforce' },
  { n: 'Notion', s: 'API · live', logo: 'LogoNotion' },
  { n: 'Confluence', s: 'API · live', logo: 'LogoConfluence' },
  { n: 'Jira', s: 'API · live', logo: 'LogoJira' },
  { n: 'Box', s: 'MCP · live', logo: 'LogoBox' },
  { n: 'Email & Calendar', s: 'IMAP · CalDAV', logo: 'LogoEmail' },
  { n: 'Any REST · MCP', s: 'Build in minutes', logo: 'LogoMCP' },
];

const Connectors = () => (
  <section id="connectors" style={{paddingTop:60}}>
    <div className="container">
      <div className="section-head">
        <span className="eyebrow"><span className="dot"/> Connectors</span>
        <h2>Plugged into <span className="italic-serif hl-accent">everything</span> you already use.</h2>
        <p>Via MCP and native APIs. Dashboards, signals, and answers draw live from where your data actually lives. No exports. No stale snapshots. Anything with an endpoint can be a source.</p>
      </div>
      <div className="connectors-grid">
        {CONNECTORS.map(c => {
          const Logo = window[c.logo];
          return (
            <div key={c.n} className="connector-tile">
              <div className="connector-logo"><Logo/></div>
              <div className="name">{c.n}</div>
              <div className="stat">{c.s}</div>
            </div>
          );
        })}
      </div>
    </div>
  </section>
);

const Batch = () => (
  <section>
    <div className="container">
      <div className="section-head">
        <span className="eyebrow"><span className="dot"/> Smart AI OCR · batch processing</span>
        <h2>Drop the messy pile. Get a <span className="italic-serif hl-accent">live knowledge pod</span>.</h2>
        <p>
          Faded scans. Crooked photocopies. Handwritten notes in the margin. Multi-column layouts, foreign languages, coffee stains. Smart AI OCR recognizes what each document actually is, extracts the fields that matter, and lands the whole batch as a structured, cited knowledge pod your firm can query immediately. No manual tagging. No spreadsheet reconciliation. No analyst in the loop.
        </p>
      </div>

      <BatchOCR />

      <div className="batch-recap">
        <div className="batch-recap-item">
          <div className="brc-icon">◆</div>
          <div>
            <div className="brc-title">AI recognizes what each doc <em>is</em></div>
            <div className="brc-sub">Invoice, contract, receipt, ID, spec sheet — routed to the right OCR + extraction pipeline automatically.</div>
          </div>
        </div>
        <div className="batch-recap-item">
          <div className="brc-icon">◈</div>
          <div>
            <div className="brc-title">Context-aware OCR</div>
            <div className="brc-sub">Handles scans, handwriting, multi-column layouts, tables, and 40+ languages — with the right model for each.</div>
          </div>
        </div>
        <div className="batch-recap-item">
          <div className="brc-icon">▣</div>
          <div>
            <div className="brc-title">Lands as a knowledge pod</div>
            <div className="brc-sub">Structured rows, cited to source. Instantly queryable across the firm — with permissions, signals, and dashboards on top.</div>
          </div>
        </div>
      </div>
    </div>
  </section>
);

// ── Messy source doc renderers ───────────────────────────────────────
// Each doc simulates a real-world artifact: skew, tears, coffee, faint
// scanner lines, handwritten annotations, mixed layouts, stamps.

const ScannedGermanInvoice = () => (
  <div className="scan scan-german" style={{transform: 'rotate(-1.4deg)'}}>
    <div className="scan-stain" style={{top: '58%', right: '8%'}}/>
    <div className="scan-fold"/>
    <div className="scan-noise"/>
    <div className="scan-header">
      <div className="scan-letterhead">
        <div className="scan-logo-mark">A</div>
        <div>
          <div className="scan-company">ACME GmbH</div>
          <div className="scan-tagline">Berliner Str. 47 · 10115 Berlin · DE</div>
        </div>
      </div>
      <div className="scan-stamp" style={{transform:'rotate(-8deg)'}}>
        <div>BEZAHLT</div>
        <div className="scan-stamp-date">14.09.26</div>
      </div>
    </div>

    <div className="scan-doctitle">RECHNUNG · Nr. ACM-4192</div>

    <div className="scan-meta">
      <div>Rechnungsdatum: <b>14.09.2026</b></div>
      <div>Fällig: <b>30 Tage netto</b></div>
      <div>USt-IdNr.: <b>DE 812 340 991</b></div>
    </div>

    <div className="scan-block scan-faded">
      <div className="scan-line">Beratungsleistungen Q3/2026</div>
      <div className="scan-line-thin"/>
      <div className="scan-line-thin short"/>
    </div>

    <table className="scan-table">
      <tbody>
        <tr><td>Pos. 01</td><td>Steuerberatung Konzern</td><td className="r">€ 22,400.00</td></tr>
        <tr><td>Pos. 02</td><td>Audit-Vorbereitung</td><td className="r">€ 18,890.00</td></tr>
        <tr><td>Pos. 03</td><td>Compliance-Review</td><td className="r">€ 7,000.00</td></tr>
      </tbody>
    </table>

    <div className="scan-totals">
      <div className="scan-tot-row"><span>Nettosumme</span><span>€ 48,290.00</span></div>
      <div className="scan-tot-row"><span>MwSt. 19%</span><span>€ 9,175.10</span></div>
      <div className="scan-tot-row bold"><span>Gesamtbetrag</span><span>€ 57,465.10</span></div>
    </div>

    <div className="scan-handwritten" style={{top:'62%', left:'6%', transform:'rotate(-3deg)'}}>
      OK — bezahlt 15/9 ✓
    </div>
  </div>
);

const ScannedFrenchReceipt = () => (
  <div className="scan scan-french" style={{transform:'rotate(1.8deg)'}}>
    <div className="scan-tear" style={{top:0}}/>
    <div className="scan-stain small" style={{top:'8%', left:'12%'}}/>
    <div className="scan-noise"/>

    <div className="scan-header narrow">
      <div style={{fontFamily:'ui-serif, Georgia', fontSize:14, fontWeight:700, letterSpacing:'0.02em'}}>Vendor D SARL</div>
      <div style={{fontSize:9, color:'#888'}}>12 Rue de la Paix · 75002 Paris</div>
      <div style={{fontSize:9, color:'#888'}}>TVA FR 88 123 456 789</div>
    </div>

    <div className="scan-divider dashed"/>

    <div className="scan-receipt">
      <div className="rr">FACTURE N°</div>
      <div className="rv bold">VND-D-881</div>
      <div className="rr">Date</div>
      <div className="rv">30/08/2026</div>
      <div className="rr">Client</div>
      <div className="rv">Acme Advisory</div>
    </div>

    <div className="scan-divider"/>

    <div className="scan-lineitems">
      <div className="li"><span>Prestation conseil · août</span><span>€ 8,200.00</span></div>
      <div className="li"><span>Frais de déplacement</span><span>€ 1,450.00</span></div>
      <div className="li"><span>Documentation</span><span>€ 750.00</span></div>
      <div className="li faded"><span>Remise fidélité 5%</span><span>-€ 520.00</span></div>
      <div className="li"><span>Divers</span><span>€ 2,520.00</span></div>
    </div>

    <div className="scan-divider dashed"/>

    <div className="scan-totals compact">
      <div className="scan-tot-row"><span>Montant HT</span><span>€ 12,400.00</span></div>
      <div className="scan-tot-row"><span>TVA 20%</span><span>€ 2,480.00</span></div>
      <div className="scan-tot-row bold big"><span>TOTAL TTC</span><span>€ 14,880.00</span></div>
    </div>

    <div className="scan-handwritten" style={{top:'82%', right:'8%', transform:'rotate(4deg)', color:'#1E3A8A'}}>
      cf. MSA §4.2
    </div>
    <div className="scan-scribble" style={{bottom:'6%', left:'8%'}}/>
  </div>
);

const ScannedContract = () => (
  <div className="scan scan-contract" style={{transform:'rotate(-0.7deg)'}}>
    <div className="scan-noise"/>
    <div className="scan-stain" style={{top:'12%', right:'15%', opacity:0.4}}/>
    <div className="scan-punch" style={{top:'22%'}}/>
    <div className="scan-punch" style={{top:'50%'}}/>
    <div className="scan-punch" style={{top:'78%'}}/>

    <div className="scan-contract-title">MASTER SERVICE<br/>AGREEMENT</div>
    <div className="scan-contract-sub">between Borealis Ltd. and Acme Advisory · effective 1 April 2026</div>

    <div className="scan-divider double"/>

    <div className="scan-contract-body">
      <div className="scan-cclause">
        <span className="scan-num">1.</span>
        <span><b>TERM.</b> This Agreement shall commence on the Effective Date and continue for an initial period of <u>twenty-four (24) months</u>, unless earlier terminated in accordance with Section 8.</span>
      </div>
      <div className="scan-cclause">
        <span className="scan-num">2.</span>
        <span><b>RENEWAL.</b> Upon expiration, this Agreement shall automatically renew for successive twelve (12) month periods unless either party provides written notice of non-renewal at least <u>sixty (60) days</u> prior.</span>
      </div>
      <div className="scan-cclause faded">
        <span className="scan-num">3.</span>
        <span><b>GOVERNING LAW.</b> This Agreement shall be governed by and construed in accordance with the laws of the <u>State of New York</u>, without regard to conflict of law principles.</span>
      </div>
      <div className="scan-cclause">
        <span className="scan-num">4.</span>
        <span><b>FEES.</b> Client shall pay Provider the fees set forth in Schedule A, payable net-thirty from invoice date.</span>
      </div>
    </div>

    <div className="scan-signature-row">
      <div className="scan-sig">
        <div className="scan-sig-line">
          <svg width="120" height="26" viewBox="0 0 120 26"><path d="M4 20 Q 14 4, 24 14 T 44 12 Q 60 4, 72 18 T 100 10 Q 112 6, 116 14" stroke="#1E3A8A" strokeWidth="1.5" fill="none"/></svg>
        </div>
        <div className="scan-sig-label">J. Chen · CEO, Borealis</div>
      </div>
      <div className="scan-sig">
        <div className="scan-sig-line">
          <svg width="130" height="26" viewBox="0 0 130 26"><path d="M6 18 Q 20 2, 34 16 Q 48 6, 62 20 Q 76 8, 92 16 Q 108 4, 122 14" stroke="#1E3A8A" strokeWidth="1.5" fill="none"/></svg>
        </div>
        <div className="scan-sig-label">M. Kaur · Partner, Acme</div>
      </div>
    </div>

    <div className="scan-handwritten" style={{top:'6%', right:'6%', transform:'rotate(-6deg)', fontSize:11}}>
      renewal → Feb ‛28
    </div>
  </div>
);

const OCR_DOCS = [
  {
    name: 'scan_ACM_invoice_09_14.pdf',
    kind: 'Invoice',
    lang: 'DE · scanned',
    Render: ScannedGermanInvoice,
    extract: {
      doc_type: 'invoice',
      supplier: 'Acme GmbH',
      invoice_no: 'ACM-4192',
      date: '2026-09-14',
      due_date: '2026-10-14',
      vat_id: 'DE 812 340 991',
      subtotal_eur: 48290.00,
      tax_eur: 9175.10,
      total_eur: 57465.10,
      status: 'paid',
    }
  },
  {
    name: 'facture_VND_D_scan_881.pdf',
    kind: 'Invoice',
    lang: 'FR · photo',
    Render: ScannedFrenchReceipt,
    extract: {
      doc_type: 'invoice',
      supplier: 'Vendor D SARL',
      invoice_no: 'VND-D-881',
      date: '2026-08-30',
      subtotal_eur: 12400.00,
      tax_eur: 2480.00,
      total_eur: 14880.00,
      note: 'ref MSA §4.2',
    }
  },
  {
    name: 'MSA_Borealis_signed_scan.pdf',
    kind: 'Contract',
    lang: 'EN · signed',
    Render: ScannedContract,
    extract: {
      doc_type: 'msa',
      counterparty: 'Borealis Ltd.',
      effective_date: '2026-04-01',
      term_months: 24,
      auto_renew: true,
      notice_days: 60,
      governing_law: 'NY',
      renewal_reminder: '2028-02-01',
    }
  },
];

const BatchOCR = () => {
  const [idx, setIdx] = React.useState(0);
  const [phase, setPhase] = React.useState(0); // 0 scan, 1 extract, 2 land
  const [landed, setLanded] = React.useState([]);

  React.useEffect(() => {
    const timers = [];
    // scan → extract → land, then advance
    timers.push(setTimeout(() => setPhase(1), 1400));
    timers.push(setTimeout(() => setPhase(2), 2600));
    timers.push(setTimeout(() => {
      setLanded(prev => {
        const doc = OCR_DOCS[idx];
        const next = [...prev, { ...doc.extract, __name: doc.name, __kind: doc.kind }];
        return next.slice(-6);
      });
    }, 3300));
    timers.push(setTimeout(() => {
      setPhase(0);
      setIdx(i => (i + 1) % OCR_DOCS.length);
    }, 4200));
    return () => timers.forEach(clearTimeout);
  }, [idx]);

  const doc = OCR_DOCS[idx];
  const extractEntries = Object.entries(doc.extract);
  const Render = doc.Render;

  return (
    <div className="ocr-viz">
      {/* LEFT — the messy source doc being scanned */}
      <div className="ocr-panel">
        <div className="ocr-panel-head">
          <span className="ocr-panel-title">1 · Messy source</span>
          <span className="pill">{doc.kind} · {doc.lang}</span>
        </div>
        <div className="ocr-doc">
          <div className="ocr-doc-name">{doc.name}</div>
          <div className="ocr-doc-scan messy" key={idx}>
            {phase === 0 && <div className="ocr-scanline"/>}
            <div className="ocr-scan-stage">
              <Render/>
            </div>
          </div>
          <div className="ocr-doc-foot">
            <span className="ocr-badge"><span className="ocr-badge-dot"/> Smart AI OCR</span>
            <span className="mono" style={{fontSize:11, color:'var(--muted)'}}>→ {doc.kind.toLowerCase()} pipeline</span>
          </div>
        </div>
      </div>

      {/* MIDDLE — extracted JSON */}
      <div className="ocr-panel">
        <div className="ocr-panel-head">
          <span className="ocr-panel-title">2 · Structured extract</span>
          <span className={`pill ${phase >= 1 ? 'live' : ''}`}>{phase >= 1 ? 'Extracting' : 'Waiting'}</span>
        </div>
        <div className="ocr-json">
          <div className="ocr-json-line">{'{'}</div>
          {extractEntries.map(([k, v], i) => (
            <div key={k} className={`ocr-json-line ${phase >= 1 ? 'on' : ''}`} style={{animationDelay:`${i*70}ms`}}>
              &nbsp;&nbsp;<span className="jk">"{k}"</span>: <span className="jv">{typeof v === 'string' ? `"${v}"` : String(v)}</span>{i < extractEntries.length-1 ? ',' : ''}
            </div>
          ))}
          <div className="ocr-json-line">{'}'}</div>
        </div>
        <div className="ocr-json-foot">
          <span className="cite">confidence 0.97</span>
          <span className="cite">source cited</span>
        </div>
      </div>

      {/* RIGHT — knowledge pod */}
      <div className="ocr-panel">
        <div className="ocr-panel-head">
          <span className="ocr-panel-title">3 · Live knowledge pod</span>
          <span className="pill live">Firm-wide</span>
        </div>
        <div className="ocr-pod">
          <div className="ocr-pod-title">
            <span className="ocr-pod-swatch"/>
            <div>
              <div className="ocr-pod-name">Q3 Vendor Invoices</div>
              <div className="ocr-pod-meta">{landed.length} of {OCR_DOCS.length} indexed · queryable now</div>
            </div>
          </div>
          <div className="ocr-pod-rows">
            {landed.slice().reverse().map((row, i) => (
              <div key={row.__name + i} className="ocr-pod-row" style={{animation: i===0 ? 'podRowIn .5s ease both' : 'none'}}>
                <div className="oprr-name">
                  <span className="mono" style={{fontSize:10, color:'var(--accent-ink)'}}>{row.__kind.toUpperCase()}</span>
                  <span>{row.__name}</span>
                </div>
                <div className="oprr-fields">
                  {Object.entries(row).filter(([k]) => !k.startsWith('__')).slice(0, 3).map(([k, v]) => (
                    <span key={k} className="oprr-field"><span className="oprr-k">{k}</span><span className="oprr-v">{String(v)}</span></span>
                  ))}
                </div>
              </div>
            ))}
            {landed.length === 0 && (
              <div className="ocr-pod-empty">Waiting for first extract…</div>
            )}
          </div>
          <div className="ocr-pod-foot">
            <span className="mono">▸</span>
            <span>"Total Q3 spend by supplier, EUR"</span>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Platform, Connectors, Batch, BatchOCR });
