// Nine scenes recreating the adviser portal happy path.
// Pixel-fidelity to the codebase brief; data scrubbed to Bennett synthetic family.

const { useState } = React;
const S = window.SEED;

// =====================================================================
// SCENE 1 — Adviser uploads source documents
// =====================================================================

function Scene1Upload() {
  const bp = useBreakpoint();
  const stack = bp !== 'desktop';
  const docs = S.documents;
  const totalMB = (docs.reduce((a, d) => a + d.sizeBytes, 0) / 1024 / 1024).toFixed(1);

  return (
    <AdviserShell activeNav="clients" pageHeader={{
      breadcrumb: ['Clients', S.client.clientName],
      title: S.client.clientName,
      description: 'Couple · existing client · annual review due',
      actions: [
        <Btn key="rev" variant="outline" icon="history" size="sm">View history</Btn>,
        <Btn key="edit" variant="outline" icon="edit" size="sm">Edit profile</Btn>,
      ],
    }}>
      <div style={{ display: 'grid', gridTemplateColumns: stack ? '1fr' : '1fr 1fr', gap: stack ? 14 : 20 }}>
        {/* Client snapshot */}
        <Card padding={0}>
          <div style={{ padding: '18px 20px', borderBottom: `1px solid ${EPG.line}` }}>
            <CardHeader eyebrow="// Client snapshot" title="Bennett, Daniel & Anna" description="Married · 2 dependants · joint review" style={{marginBottom:0}}/>
          </div>
          <div style={{ padding: '16px 20px' }}>
            <DefList rows={[
              ['Primary contact', 'Daniel Bennett'],
              ['Email',           'daniel@example.com.au'],
              ['Mobile',          '0412 345 678 (verified)'],
              ['Address',         '45 Beach Road, Brighton VIC 3186'],
              ['Adviser',         'Lachlan Brooks'],
              ['Last review',     '15 Sep 2025'],
              ['CRM linked',      'Practice CRM · client #BENN-0421'],
            ]}/>
            <div style={{ marginTop: 14, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              <Chip tone="primary" icon="check">Review due</Chip>
              <Chip tone="gold">Risk profile: Growth</Chip>
              <Chip tone="muted">2 child dependants</Chip>
            </div>
          </div>
        </Card>

        {/* Upload card */}
        <Card padding={0}>
          <div style={{ padding: '18px 20px', borderBottom: `1px solid ${EPG.line}` }}>
            <CardHeader
              eyebrow="// New extraction"
              title="Upload source documents"
              description="Up to 5 files, 20 MB total. PDF or DOCX."
              actions={<Chip tone="primary" icon="spark">AI extraction</Chip>}
              style={{marginBottom:0}}
            />
          </div>

          {/* Drag zone */}
          <div style={{
            margin: 16,
            border: `2px dashed ${EPG.line2}`,
            borderRadius: EPG.radius,
            padding: '20px 16px',
            background: EPG.page,
            textAlign: 'center',
          }}>
            <div style={{
              width: 40, height: 40, margin: '0 auto 8px',
              borderRadius: '50%', background: EPG.brandBg,
              display: 'flex', alignItems: 'center', justifyContent: 'center', color: EPG.brand,
            }}>
              <Icon d={ICONS.upload} size={20} stroke={EPG.brand}/>
            </div>
            <div style={{ fontSize: 13.5, fontWeight: 500, color: EPG.ink }}>Drop files here, or <span style={{ color: EPG.brand, textDecoration: 'underline' }}>browse</span></div>
            <div style={{ fontSize: 11.5, color: EPG.muted, marginTop: 4 }}>Or import from SharePoint &middot; {S.firm.afsl} tenancy</div>
          </div>

          {/* Files list */}
          <div style={{ padding: '0 20px 20px' }}>
            <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted, marginBottom: 8, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
              4 files queued · {totalMB} MB
            </div>
            <div style={{ border: `1px solid ${EPG.line}`, borderRadius: EPG.radius, overflow: 'hidden' }}>
              {docs.map((d, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '10px 14px',
                  borderBottom: i < docs.length - 1 ? `1px solid ${EPG.line}` : 'none',
                  background: EPG.card,
                }}>
                  <Icon d={ICONS.doc} size={15} stroke={EPG.muted}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, color: EPG.ink, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{d.name}</div>
                    <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted }}>
                      {(d.sizeBytes / 1024 / 1024).toFixed(1)} MB · {d.pages} pages
                    </div>
                  </div>
                  <Chip tone="success" icon="check">Ready</Chip>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 16 }}>
              <div style={{ fontSize: 11.5, color: EPG.muted, display: 'flex', alignItems: 'center', gap: 6 }}>
                <Icon d={ICONS.shieldDot} size={13} stroke={EPG.green}/>
                <span>Zero-retention · model pinned to <span style={{fontFamily:EPG.mono, color:EPG.ink2}}>claude-sonnet-4-6</span></span>
              </div>
              <Btn icon="spark">Run extraction</Btn>
            </div>
          </div>
        </Card>
      </div>

      {/* Footnote */}
      <div style={{ marginTop: 18, padding: 14, background: EPG.brandBg, border: `1px solid rgba(29,85,99,0.15)`, borderRadius: EPG.radius, display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <Icon d={ICONS.info} size={16} stroke={EPG.brand}/>
        <div style={{ fontSize: 12.5, color: EPG.ink2, lineHeight: 1.55 }}>
          <strong style={{ color: EPG.ink }}>What happens next.</strong> Files are virus-scanned by Defender for Storage, then sent in one batched call to Claude. Extraction takes 8–15 seconds. You'll review every value before anything reaches the client.
        </div>
      </div>
    </AdviserShell>
  );
}

function DefList({ rows }) {
  const bp = useBreakpoint();
  return (
    <div style={{ display: 'grid', gridTemplateColumns: bp === 'mobile' ? '1fr' : '120px 1fr', rowGap: bp === 'mobile' ? 4 : 8, columnGap: 12, fontSize: 12.5 }}>
      {rows.map(([k, v], i) => (
        <React.Fragment key={i}>
          <div style={{ color: EPG.muted, fontFamily: EPG.mono, fontSize: 11, marginTop: bp === 'mobile' && i > 0 ? 8 : 0 }}>{k}</div>
          <div style={{ color: EPG.ink2 }}>{v}</div>
        </React.Fragment>
      ))}
    </div>
  );
}

// =====================================================================
// SCENE 2 — Claude extracting (polling state)
// =====================================================================

function Scene2Extracting() {
  const bp = useBreakpoint();
  const stack = bp !== 'desktop';
  const stage = 'extracting'; // queued, reading, extracting, building, done
  const stages = [
    { id: 'queued',     label: 'Queued',              done: true,  pct: 10 },
    { id: 'reading',    label: 'Reading documents',   done: true,  pct: 30 },
    { id: 'extracting', label: 'Extracting details',  done: false, pct: 65, active: true },
    { id: 'building',   label: 'Building form data',  done: false, pct: 90 },
  ];
  const activePct = 65;

  return (
    <AdviserShell activeNav="clients" pageHeader={{
      breadcrumb: ['Clients', S.client.clientName],
      title: S.client.clientName,
      description: 'Couple · existing client · annual review due',
    }}>
      <div style={{ display: 'grid', gridTemplateColumns: stack ? '1fr' : '1fr 1fr', gap: stack ? 14 : 20 }}>
        {/* Files being read */}
        <Card padding={0}>
          <div style={{ padding: '18px 20px', borderBottom: `1px solid ${EPG.line}` }}>
            <CardHeader eyebrow="// Source documents" title="Reading 4 documents" description="Sent in one batched call · processed together so values can be reconciled across documents." style={{marginBottom:0}}/>
          </div>
          <div style={{ padding: 20 }}>
            {S.documents.map((d, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 0' }}>
                <Icon d={ICONS.doc} size={14} stroke={EPG.muted}/>
                <div style={{ flex: 1, fontSize: 12.5, color: EPG.ink2 }}>{d.name}</div>
                <span style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted }}>{d.pages}p · {(d.sizeBytes/1024/1024).toFixed(1)}MB</span>
              </div>
            ))}
          </div>
        </Card>

        {/* Extraction progress */}
        <Card padding={24}>
          <div style={{ marginBottom: 18 }}>
            <Chip tone="primary" icon="spark">Extracting</Chip>
          </div>
          <div style={{ fontFamily: EPG.serif, fontSize: 22, fontWeight: 600, color: EPG.ink, marginBottom: 4 }}>
            Extracting details…
          </div>
          <div style={{ fontSize: 13, color: EPG.muted, marginBottom: 22 }}>
            Reading prose and turning it into structured fields. The model returns JSON conforming to the fact-find schema.
          </div>

          {/* Progress bar */}
          <div style={{ height: 8, background: EPG.line, borderRadius: 99, overflow: 'hidden', marginBottom: 18 }}>
            <div style={{
              height: '100%', width: `${activePct}%`,
              background: `linear-gradient(90deg, ${EPG.brand}, ${EPG.brand2})`,
              borderRadius: 99,
              transition: 'width 1s ease',
            }}/>
          </div>

          {/* Stage list */}
          <div>
            {stages.map((s, i) => (
              <div key={s.id} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 0',
                borderTop: i > 0 ? `1px solid ${EPG.line}` : 'none',
                opacity: s.done || s.active ? 1 : 0.4,
              }}>
                <div style={{
                  width: 18, height: 18, borderRadius: '50%', flexShrink: 0,
                  background: s.done ? EPG.green : s.active ? EPG.brand : 'transparent',
                  border: `1.5px solid ${s.done ? EPG.green : s.active ? EPG.brand : EPG.line2}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  animation: s.active ? 'epgPulse 1.4s infinite' : 'none',
                }}>
                  {s.done && <Icon d={ICONS.check} size={11} stroke="#fff"/>}
                </div>
                <div style={{ flex: 1, fontSize: 13, color: s.done ? EPG.ink2 : s.active ? EPG.ink : EPG.muted, fontWeight: s.active ? 600 : 500 }}>{s.label}</div>
                <span style={{ fontFamily: EPG.mono, fontSize: 11, color: EPG.muted }}>{s.pct}%</span>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 22, paddingTop: 16, borderTop: `1px solid ${EPG.line}`, fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
            <span>model: <span style={{ color: EPG.ink2 }}>claude-sonnet-4-6</span></span>
            <span>tool: <span style={{ color: EPG.ink2 }}>extract_client</span></span>
            <span>est. cost: <span style={{ color: EPG.ink2 }}>~$0.08</span></span>
          </div>
        </Card>
      </div>

      <style>{`
        @keyframes epgPulse { 0%,100% { box-shadow: 0 0 0 0 rgba(29,85,99,0.4); } 50% { box-shadow: 0 0 0 6px rgba(29,85,99,0); } }
      `}</style>
    </AdviserShell>
  );
}

// =====================================================================
// SCENE 3 — Extraction review (HERO — most detailed scene)
// =====================================================================

function Scene3Review() {
  const bp = useBreakpoint();
  const stack = bp !== 'desktop';
  const [editingIncome, setEditingIncome] = useState(true);
  const [incomeValue, setIncomeValue] = useState('215000');

  return (
    <AdviserShell activeNav="clients" pageHeader={{
      breadcrumb: ['Clients', S.client.clientName],
      title: 'Review extraction',
      description: 'Extracted from 4 documents · 110 fields · check the red and amber dots first.',
      actions: stack ? [
        <Btn key="cnf" size="sm" icon="check">Confirm</Btn>,
      ] : [
        <Btn key="rej" variant="outline" size="sm" icon="x">Reject extraction</Btn>,
        <Btn key="cnf" size="sm" icon="check">Confirm extraction</Btn>,
      ],
    }}>
      <div style={{ display: 'grid', gridTemplateColumns: stack ? '1fr' : '1fr 320px', gap: stack ? 14 : 20, alignItems: 'flex-start' }}>
        {/* LEFT — extraction sections */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>

          {/* Personal section (collapsed-ish, expanded by default) */}
          <Card padding={0}>
            <SectionAccordion title="01 — Personal" subtitle="Client 1 · Client 2" defaultOpen={true}>
              <FieldRow label="Title — Daniel" value="Mr" confidence="high"/>
              <FieldRow label="Full name — Daniel" value="Daniel Bennett" confidence="high"/>
              <FieldRow label="Date of birth — Daniel" value="15 March 1988" confidence="high"/>
              <FieldRow label="Occupation — Daniel" value="Business Owner · Bennett Holdings Pty Ltd" confidence="medium"/>
              <FieldRow label="Full name — Anna" value="Anna Bennett" confidence="high"/>
              <FieldRow label="Date of birth — Anna" value="22 July 1990" confidence="high"/>
              <FieldRow label="Occupation — Anna" value="Marketing Manager · Northbeam Health" confidence="high"/>
            </SectionAccordion>
          </Card>

          {/* Contact section */}
          <Card padding={0}>
            <SectionAccordion title="02 — Contact" subtitle="Mobile · email · address · dependants" defaultOpen={false}>
              <div style={{ padding: 10, color: EPG.muted, fontSize: 12 }}>Collapsed for brevity.</div>
            </SectionAccordion>
          </Card>

          {/* Income & cashflow — the section with the LOW dot */}
          <Card padding={0} style={{ borderColor: 'rgba(176,120,35,0.4)', boxShadow: '0 0 0 3px rgba(176,120,35,0.05)' }}>
            <SectionAccordion title="04 — Income & cashflow" subtitle="2 income rows · expenses · gov benefits" defaultOpen={true} warningCount={1}>
              {/* LOW-CONFIDENCE row in edit mode */}
              <div style={{
                margin: '6px 4px',
                border: `1px solid ${EPG.amber}66`,
                background: EPG.amberBg,
                borderRadius: EPG.radius,
                padding: 12,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ fontSize: 12.5, fontWeight: 500, color: EPG.ink }}>Salary income — Daniel</span>
                    <ConfidenceDot confidence="low" withBadge/>
                  </div>
                  <span style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted }}>
                    <Icon d={ICONS.link} size={11}/> Bennett_SoA_2025.pdf · p3
                  </span>
                </div>
                {editingIncome ? (
                  <div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{ position: 'relative', flex: 1 }}>
                        <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: EPG.muted, fontSize: 13 }}>$</span>
                        <input
                          value={incomeValue}
                          onChange={e => setIncomeValue(e.target.value)}
                          style={{
                            width: '100%', height: 36,
                            padding: '0 12px 0 24px',
                            border: `1.5px solid ${EPG.brand}`,
                            borderRadius: EPG.radius,
                            background: '#fff',
                            fontFamily: EPG.sans, fontSize: 14, color: EPG.ink,
                            outline: 'none',
                            boxShadow: '0 0 0 3px rgba(29,85,99,0.12)',
                          }}
                        />
                      </div>
                      <Btn size="sm" onClick={() => setEditingIncome(false)} icon="check">Save</Btn>
                      <Btn size="sm" variant="ghost" onClick={() => { setIncomeValue('195000'); setEditingIncome(false); }} icon="x">Cancel</Btn>
                    </div>
                    <div style={{ marginTop: 8, padding: 8, background: '#fff', borderRadius: 6, fontSize: 11.5, color: EPG.muted, fontStyle: 'italic', borderLeft: `2px solid ${EPG.amber}` }}>
                      <strong style={{ color: EPG.amber, fontStyle: 'normal' }}>Why low?</strong>&nbsp; "Found on the 2025 SoA but contradicted by 2026 PAYG summary — chose the lower value."
                    </div>
                  </div>
                ) : (
                  <button style={{ background: '#fff', border: `1px solid ${EPG.line2}`, borderRadius: EPG.radius, padding: '8px 12px', textAlign: 'left', width: '100%', fontFamily: EPG.sans, fontSize: 13, color: EPG.ink, cursor: 'pointer' }}>
                    {aud(parseFloat(incomeValue))}
                  </button>
                )}
              </div>

              <FieldRow label="Salary frequency — Daniel" value="Annual" confidence="high"/>
              <FieldRow label="Salary income — Anna" value={aud(125000)} confidence="high" source="Bennett_PAYG_2026.pdf · p1"/>
              <FieldRow label="Salary frequency — Anna" value="Annual" confidence="high"/>
              <FieldRow label="Government benefits" value="Family Tax Benefit A — $5,840 p.a." confidence="medium" source="Bennett_SoA_2025.pdf · p4"/>
              <FieldRow label="Essential expenses (annual)" value={aud(78400)} confidence="medium"/>
              <FieldRow label="Lifestyle expenses (annual)" value={aud(32100)} confidence="medium"/>
            </SectionAccordion>
          </Card>

          {/* Assets — collapsed */}
          <Card padding={0}>
            <SectionAccordion title="05 — Assets" subtitle="Properties · accounts · investments" defaultOpen={false} subFields={['1 property', '2 accounts', '1 investment']}/>
          </Card>
          {/* Debts — collapsed */}
          <Card padding={0}>
            <SectionAccordion title="06 — Debts" subtitle="Home loan · credit card" defaultOpen={false} subFields={['2 debts', 'HECS 0']}/>
          </Card>
          {/* Super — collapsed */}
          <Card padding={0}>
            <SectionAccordion title="07 — Superannuation" subtitle="2 funds · binding nominations in place" defaultOpen={false}/>
          </Card>
          {/* Insurance — collapsed */}
          <Card padding={0}>
            <SectionAccordion title="08 — Insurance" subtitle="5 policies in super" defaultOpen={false}/>
          </Card>
        </div>

        {/* RIGHT — sidebar (sticky on desktop, inline below content on mobile/tablet) */}
        <div style={{ position: stack ? 'static' : 'sticky', top: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card padding={18}>
            <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>
              // Confidence overview
            </div>
            <ConfidenceBar high={87} medium={18} low={5}/>
            <div style={{ marginTop: 14, paddingTop: 14, borderTop: `1px solid ${EPG.line}`, fontSize: 12, color: EPG.muted, lineHeight: 1.55 }}>
              <strong style={{ color: EPG.ink }}>5 low-confidence fields</strong> to check first — they cluster in section 4 (income).
            </div>
          </Card>

          <Card padding={18}>
            <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>
              // Source documents
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {S.documents.map((d, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: EPG.ink2 }}>
                  <Icon d={ICONS.doc} size={12} stroke={EPG.muted}/>
                  <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.name}</span>
                  <span style={{ fontFamily: EPG.mono, fontSize: 10, color: EPG.muted }}>p{d.pages}</span>
                </div>
              ))}
            </div>
          </Card>

          <Card padding={18}>
            <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>
              // Extraction metadata
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontSize: 12 }}>
              <div><div style={{color:EPG.muted, fontFamily:EPG.mono, fontSize:10}}>MODEL</div><div style={{color:EPG.ink2}}>sonnet-4-6</div></div>
              <div><div style={{color:EPG.muted, fontFamily:EPG.mono, fontSize:10}}>LATENCY</div><div style={{color:EPG.ink2}}>11.4 s</div></div>
              <div><div style={{color:EPG.muted, fontFamily:EPG.mono, fontSize:10}}>TOKENS</div><div style={{color:EPG.ink2}}>21,319</div></div>
              <div><div style={{color:EPG.muted, fontFamily:EPG.mono, fontSize:10}}>COST</div><div style={{color:EPG.ink2}}>$0.08</div></div>
            </div>
          </Card>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <Btn icon="check" size="lg">Confirm extraction</Btn>
            <Btn variant="outline" icon="x" size="lg">Reject extraction</Btn>
          </div>
        </div>
      </div>
    </AdviserShell>
  );
}

function SectionAccordion({ title, subtitle, defaultOpen, warningCount, subFields, children }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div>
      <button onClick={() => setOpen(!open)} style={{
        width: '100%', display: 'flex', alignItems: 'center', gap: 12,
        padding: '14px 18px',
        background: 'transparent', border: 'none', cursor: 'pointer',
        textAlign: 'left',
      }}>
        <Icon d={open ? ICONS.chevD : ICONS.chevR} size={14} stroke={EPG.muted}/>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ fontFamily: EPG.serif, fontSize: 15, fontWeight: 600, color: EPG.ink }}>{title}</span>
            {warningCount && <Chip tone="warning">{warningCount} low</Chip>}
          </div>
          <div style={{ fontSize: 11.5, color: EPG.muted, marginTop: 2 }}>{subtitle}</div>
        </div>
        {subFields && (
          <div style={{ display: 'flex', gap: 6 }}>
            {subFields.map((sf, i) => <Chip key={i} tone="muted">{sf}</Chip>)}
          </div>
        )}
      </button>
      {open && (
        <div style={{ padding: '4px 14px 14px', borderTop: `1px solid ${EPG.line}` }}>
          {children}
        </div>
      )}
    </div>
  );
}

function FieldRow({ label, value, confidence, source }) {
  const isLow = confidence === 'low';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '8px 12px',
      margin: '4px 0',
      border: `1px solid ${isLow ? EPG.amber + '66' : EPG.line}`,
      background: isLow ? EPG.amberBg : EPG.card,
      borderRadius: EPG.radius,
    }}>
      <ConfidenceDot confidence={confidence}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, color: EPG.muted }}>{label}</div>
        <div style={{ fontSize: 13, color: EPG.ink, marginTop: 1 }}>{value}</div>
      </div>
      {source && (
        <span style={{ fontFamily: EPG.mono, fontSize: 10, color: EPG.muted, display: 'flex', alignItems: 'center', gap: 4 }}>
          <Icon d={ICONS.link} size={10}/> {source}
        </span>
      )}
    </div>
  );
}

// =====================================================================
// SCENE 4 — Adviser confirms; send-link dialog opens
// =====================================================================

function Scene4Confirm() {
  const bp = useBreakpoint();
  const stack = bp !== 'desktop';
  const isMobile = bp === 'mobile';
  return (
    <AdviserShell activeNav="clients" pageHeader={{
      breadcrumb: ['Clients', S.client.clientName],
      title: S.client.clientName,
      description: 'Couple · existing client · annual review due',
    }}>
      <div style={{ position: 'relative' }}>
        {/* Toast banner */}
        <div style={{
          marginBottom: 18, padding: '12px 16px',
          background: EPG.greenBg, border: `1px solid rgba(47,122,74,0.3)`,
          borderRadius: EPG.radius, color: EPG.green,
          display: 'flex', alignItems: 'center', gap: 10,
          fontSize: 13, fontWeight: 500,
        }}>
          <Icon d={ICONS.check} size={16} stroke={EPG.green}/>
          Extraction confirmed. Draft submission <span style={{fontFamily:EPG.mono, color:EPG.ink2}}>sub-2104</span> created.
          <span style={{ marginLeft: 'auto', fontFamily: EPG.mono, fontSize: 11, color: EPG.muted }}>
            audit · 3 fields changed · just now
          </span>
        </div>

        {/* Dimmed page behind */}
        <div style={{ filter: 'blur(0.4px)', opacity: 0.55, pointerEvents: 'none' }}>
          <div style={{ display: 'grid', gridTemplateColumns: stack ? '1fr' : '1fr 1fr', gap: stack ? 14 : 20 }}>
            <Card padding={20}>
              <div style={{ fontFamily: EPG.serif, fontSize: 16, fontWeight: 600, color: EPG.ink, marginBottom: 12 }}>Client snapshot</div>
              <DefList rows={[
                ['Primary', 'Daniel Bennett'],
                ['Status',  'Submission draft created'],
                ['Last extraction', 'Just now · confirmed'],
              ]}/>
            </Card>
            <Card padding={20}>
              <div style={{ fontFamily: EPG.serif, fontSize: 16, fontWeight: 600, color: EPG.ink, marginBottom: 12 }}>Upload new documents</div>
              <div style={{ height: 80, background: EPG.page, border: `1px dashed ${EPG.line2}`, borderRadius: EPG.radius }}/>
            </Card>
          </div>
        </div>

        {/* Modal — Send link */}
        <div style={{
          position: 'absolute',
          top: isMobile ? 30 : 60,
          left: isMobile ? 8 : '50%',
          right: isMobile ? 8 : 'auto',
          transform: isMobile ? 'none' : 'translateX(-50%)',
          width: isMobile ? 'auto' : 520,
          maxWidth: 'calc(100vw - 16px)',
          background: EPG.card,
          border: `1px solid ${EPG.line}`,
          borderRadius: EPG.radiusLg,
          boxShadow: '0 25px 80px rgba(28,45,48,0.18)',
          padding: isMobile ? 18 : 24,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 4 }}>
            <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.brand2, letterSpacing: '0.12em', textTransform: 'uppercase' }}>// Send for client confirmation</div>
            <Icon d={ICONS.x} size={16} stroke={EPG.muted}/>
          </div>
          <h2 style={{ margin: '6px 0 4px', fontFamily: EPG.serif, fontSize: 20, fontWeight: 600, color: EPG.ink, letterSpacing:'-0.01em' }}>Send review link to Daniel Bennett</h2>
          <p style={{ margin: '0 0 18px', fontSize: 13, color: EPG.muted }}>
            They'll get a magic link by email and a 6-digit SMS code to verify. No password, no app.
          </p>

          <div style={{ marginBottom: 14 }}>
            <Label>Email</Label>
            <ReadOnlyField icon="info" value="daniel@example.com.au"/>
          </div>

          <div style={{ marginBottom: 14 }}>
            <Label>Mobile (for OTP)</Label>
            <ReadOnlyField icon="info" value="+61 412 345 678"/>
          </div>

          <div style={{ marginBottom: 18 }}>
            <Label>Link preview</Label>
            <div style={{ padding: '10px 12px', background: EPG.page, border: `1px solid ${EPG.line}`, borderRadius: EPG.radius, fontFamily: EPG.mono, fontSize: 11.5, color: EPG.ink2, wordBreak: 'break-all' }}>
              dashboard.advisory.example/form/<span style={{ color: EPG.brand }}>9f3b7c2a1d8e</span>
            </div>
          </div>

          <div style={{
            padding: '10px 12px', borderRadius: EPG.radius,
            background: EPG.amberBg, border: `1px solid rgba(176,120,35,0.25)`,
            fontSize: 11.5, color: EPG.amber, marginBottom: 18,
            display: 'flex', gap: 8, alignItems: 'flex-start',
          }}>
            <Icon d={ICONS.warn} size={13} stroke={EPG.amber}/>
            <span><strong>State change.</strong> Submission moves <span style={{fontFamily:EPG.mono}}>draft → sent</span>. An <span style={{fontFamily:EPG.mono}}>email_sent</span> audit row will be written.</span>
          </div>

          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
            <Btn variant="outline">Cancel</Btn>
            <Btn icon="send">Send link & SMS code</Btn>
          </div>
        </div>
      </div>
    </AdviserShell>
  );
}

function Label({ children }) {
  return <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted, letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 6 }}>{children}</div>;
}
function ReadOnlyField({ value, icon }) {
  return (
    <div style={{ padding: '8px 12px', background: EPG.page, border: `1px solid ${EPG.line}`, borderRadius: EPG.radius, fontSize: 13, color: EPG.ink2, display: 'flex', alignItems: 'center', gap: 8 }}>
      {icon && <Icon d={ICONS[icon]} size={13} stroke={EPG.muted}/>}
      {value}
    </div>
  );
}

// =====================================================================
// SCENE 5 — Client OTP entry
// =====================================================================

function Scene5OTP() {
  const [code, setCode] = useState('428193');
  const [trust, setTrust] = useState(true);

  return (
    <ClientMagicShell>
      <h1 style={{ margin: 0, fontFamily: EPG.serif, fontSize: 24, fontWeight: 600, color: EPG.ink, textAlign: 'center', letterSpacing: '-0.01em' }}>
        Enter your verification code
      </h1>
      <p style={{ margin: '10px 0 24px', fontSize: 13.5, color: EPG.muted, textAlign: 'center', lineHeight: 1.5 }}>
        We sent a 6-digit code to <span style={{ fontFamily: EPG.mono, color: EPG.ink }}>+61 4** *** *678</span>. It expires in 10 minutes.
      </p>

      <input
        value={code}
        onChange={e => setCode(e.target.value)}
        maxLength={6}
        inputMode="numeric"
        autoComplete="one-time-code"
        style={{
          width: '100%', height: 56,
          padding: '0 14px',
          textAlign: 'center',
          border: `1.5px solid ${EPG.brand}`,
          borderRadius: EPG.radius,
          fontFamily: EPG.mono, fontSize: 28, fontWeight: 500, color: EPG.ink,
          letterSpacing: '0.4em',
          background: EPG.card,
          outline: 'none',
          boxShadow: '0 0 0 4px rgba(29,85,99,0.12)',
        }}
      />

      <label style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 18, fontSize: 12.5, color: EPG.ink2, cursor: 'pointer' }}>
        <input
          type="checkbox"
          checked={trust}
          onChange={e => setTrust(e.target.checked)}
          style={{ width: 14, height: 14, accentColor: EPG.brand }}
        />
        Trust this device for 30 days
      </label>

      <Btn size="lg" style={{ width: '100%', justifyContent: 'center', height: 44, marginTop: 22 }}>Verify and continue</Btn>

      <div style={{ marginTop: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11.5, color: EPG.muted }}>
        <button style={{ background: 'none', border: 'none', color: EPG.muted, cursor: 'pointer', fontFamily: EPG.sans, fontSize: 11.5, padding: 0 }}>
          Resend code in <span style={{ color: EPG.ink2 }}>45s</span>
        </button>
        <span style={{ fontFamily: EPG.mono }}>2 of 5 attempts</span>
      </div>

      <div style={{ marginTop: 28, paddingTop: 18, borderTop: `1px solid ${EPG.line}`, fontSize: 11, color: EPG.muted, textAlign: 'center', lineHeight: 1.5 }}>
        Sent on behalf of <strong style={{ color: EPG.ink2 }}>{S.firm.name}</strong> · {S.firm.afsl}<br/>
        If you didn't expect this, ignore the email. Your link expires in 7 days.
      </div>
    </ClientMagicShell>
  );
}

// =====================================================================
// SCENE 6 — Client form (pre-filled, edits one value)
// =====================================================================

function Scene6Form() {
  const bp = useBreakpoint();
  const isMobile = bp === 'mobile';
  return (
    <ClientFormShell title="Confirm your details" saveStatus="All changes saved · 12:04 PM" progress={42}>
      {/* Section stepper */}
      <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 8, fontSize: 12, color: EPG.muted, marginBottom: isMobile ? 16 : 22 }}>
        <span style={{ fontFamily: EPG.mono }}>04 of 10</span>
        <span>·</span>
        <span style={{ color: EPG.ink }}>Income & cashflow</span>
        <span style={{ marginLeft: 'auto' }}>
          <Chip tone="primary">3 fields updated</Chip>
        </span>
      </div>

      <Card padding={isMobile ? 18 : 28}>
        <h2 style={{ margin: '0 0 4px', fontFamily: EPG.serif, fontSize: isMobile ? 18 : 22, fontWeight: 600, color: EPG.ink }}>Income & cashflow</h2>
        <p style={{ margin: '0 0 24px', fontSize: 13.5, color: EPG.muted }}>
          We've filled in what we already know from your documents. Please check each field and update anything that's changed.
        </p>

        {/* Daniel's income — prefilled, unchanged after adviser correction */}
        <FormField
          label="Daniel — salary income (annual)"
          value={aud(215000)}
          state="prefilled-unchanged"
          hint="From your 2026 PAYG summary"
        />

        {/* Anna's income — prefilled, unchanged */}
        <FormField
          label="Anna — salary income (annual)"
          value={aud(125000)}
          state="prefilled-unchanged"
        />

        {/* Gov benefits — MODIFIED by client (was $5,840 → now $0) */}
        <FormField
          label="Government benefits (annual)"
          value={aud(0)}
          state="prefilled-modified"
          hint='Changed from $5,840 — "we stopped claiming FTB-A in March"'
        />

        {/* New goal — BLANK FILLED */}
        <FormField
          label="Add an additional goal (optional)"
          value="Investigate investment property purchase in next 12 months"
          state="blank-filled"
          hint="New information"
        />

        {/* Essential expenses — unchanged */}
        <FormField
          label="Essential expenses (annual)"
          value={aud(78400)}
          state="prefilled-unchanged"
        />

        {/* Lifestyle expenses — unchanged */}
        <FormField
          label="Lifestyle expenses (annual)"
          value={aud(32100)}
          state="prefilled-unchanged"
        />

        <div style={{ marginTop: 24, padding: 14, background: EPG.brandBg, border: `1px solid rgba(29,85,99,0.15)`, borderRadius: EPG.radius, fontSize: 12.5, color: EPG.ink2, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <Icon d={ICONS.info} size={14} stroke={EPG.brand}/>
          <span><strong style={{color:EPG.ink}}>Surplus this year:</strong> {aud(215000 + 125000 - 0 - 78400 - 32100)} before tax, super and debt repayments.</span>
        </div>
      </Card>

      {/* Navigation */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 10, marginTop: 18 }}>
        <Btn variant="outline" icon="chevL">Assets</Btn>
        {!isMobile && <div style={{ fontSize: 12, color: EPG.muted }}>Next: <span style={{color:EPG.ink2}}>Debts</span></div>}
        <Btn icon="chevR" style={{ flexDirection: 'row-reverse' }}>Continue</Btn>
      </div>
    </ClientFormShell>
  );
}

function FormField({ label, value, state, hint }) {
  const s = {
    'prefilled-unchanged': { bg: '#fff',           bd: EPG.line,                  tone: null },
    'prefilled-modified':  { bg: EPG.amberBg,      bd: EPG.amber + '66',          tone: 'warning', toneLabel: 'Modified' },
    'blank-filled':        { bg: EPG.greenBg,      bd: 'rgba(47,122,74,0.35)',    tone: 'success', toneLabel: 'New' },
  }[state];
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
        <label style={{ fontSize: 12.5, fontWeight: 500, color: EPG.ink }}>{label}</label>
        {s.tone && <Chip tone={s.tone}>{s.toneLabel}</Chip>}
      </div>
      <div style={{
        padding: '10px 14px',
        background: s.bg,
        border: `1px solid ${s.bd}`,
        borderRadius: EPG.radius,
        fontSize: 14, color: EPG.ink,
      }}>{value}</div>
      {hint && <div style={{ fontSize: 11.5, color: EPG.muted, marginTop: 4, fontStyle: 'italic' }}>{hint}</div>}
    </div>
  );
}

// =====================================================================
// SCENE 7 — Adviser cockpit (money audit + agenda)
// =====================================================================

function Scene7Cockpit() {
  const bp = useBreakpoint();
  const stack = bp !== 'desktop';
  const isMobile = bp === 'mobile';
  const money = {
    income: 340000,
    essential: 78400,
    lifestyle: 32100,
    surplus: 229500,
    assets: 1985500,
    liabilities: 722400,
    super_balance: 283000,
    investable: 70000,
  };

  return (
    <AdviserShell activeNav="clients" pageHeader={{
      breadcrumb: ['Clients', S.client.clientName, 'Fact find'],
      title: 'Bennett review — fact find',
      description: 'Recall count: 0 · Pinned view model not yet created',
      actions: [
        <Btn key="rev" variant="outline" size="sm" icon="history">Revert overrides</Btn>,
        <Btn key="send" size="sm" icon="send">Send for signature</Btn>,
      ],
    }}>
      <div style={{ display: 'grid', gridTemplateColumns: stack ? '1fr' : '1fr 320px', gap: stack ? 14 : 20, alignItems: 'flex-start' }}>
        {/* MAIN COLUMN */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

          {/* Money audit */}
          <Card padding={0}>
            <div style={{ padding: '16px 20px', borderBottom: `1px solid ${EPG.line}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
              <CardHeader eyebrow="// Money fields audit" title="Position summary" description="Client-supplied values vs adviser corrections (sparse JSONB)" style={{marginBottom:0}}/>
              <Chip tone="success" icon="check">Reviewed</Chip>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)' }}>
              <Stat label="Gross income" value={money.income} green/>
              <Stat label="Essential exp." value={money.essential}/>
              <Stat label="Lifestyle exp." value={money.lifestyle}/>
              <Stat label="Surplus" value={money.surplus} green prominent/>
              <Stat label="Total assets" value={money.assets}/>
              <Stat label="Total liabilities" value={money.liabilities} red/>
              <Stat label="Super balance" value={money.super_balance}/>
              <Stat label="Investable surplus" value={money.investable} prominent/>
            </div>
          </Card>

          {/* Agenda section */}
          <Card padding={0}>
            <div style={{ padding: '16px 20px', borderBottom: `1px solid ${EPG.line}` }}>
              <CardHeader eyebrow="// Agenda ledger · 12 sections" title="Meeting agenda" description="27 of 42 items ticked · ledger written to audit log on each tick" style={{marginBottom:0}}/>
            </div>

            <AgendaSection
              num="03"
              title="Goals, objectives & timeframes"
              items={[
                { id: 's03_objectives_review', label: 'Reviewed previous objectives', checked: true },
                { id: 's03_timeframes',        label: 'Confirmed timeframes (short / medium / long)', checked: true },
                { id: 's03_year_ahead',        label: 'Discussed major year-ahead changes', checked: true },
                { id: 's03_helping_others',    label: 'Helping other family members?', checked: false },
              ]}
            />

            <AgendaSection
              num="04"
              title="Cashflow position"
              items={[
                { id: 's04_cashflow_summary', label: 'Walked through cashflow summary', checked: true },
                { id: 's04_savings_pattern',  label: 'Reviewed savings pattern', checked: true },
              ]}
            />

            <AgendaSection
              num="09"
              title="Insurance assessment"
              collapsed={true}
              tickedCount="6 of 7 ticked"
            />

            <AgendaSection
              num="12"
              title="Disclosures, costs & risks"
              collapsed={true}
              tickedCount="4 of 6 ticked"
            />
          </Card>
        </div>

        {/* RIGHT — scope + warnings + send (sticky on desktop only) */}
        <div style={{ position: stack ? 'static' : 'sticky', top: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card padding={18}>
            <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>
              // Scope of advice
            </div>
            {[
              { l: 'Cash flow management', c: true },
              { l: 'Debt management',      c: true },
              { l: 'Risk management',      c: false },
              { l: 'Investment (incl. super)', c: true },
              { l: 'Social security / Aged care', c: false },
              { l: 'Estate planning',      c: false },
              { l: 'SMSF',                 c: false },
            ].map((it, i) => (
              <CheckRow key={i} label={it.l} checked={it.c}/>
            ))}
          </Card>

          <Card padding={18}>
            <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 12 }}>
              // General warnings
            </div>
            <div style={{ fontSize: 11.5, color: EPG.muted, lineHeight: 1.55, marginBottom: 10 }}>
              All six warnings must be acknowledged before the fact-find can be sent for signature.
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 4 }}>
              {[1,2,3,4,5,6].map(i => (
                <div key={i} style={{
                  height: 22, borderRadius: 4,
                  background: i <= 5 ? EPG.greenBg : EPG.page,
                  border: `1px solid ${i <= 5 ? 'rgba(47,122,74,0.3)' : EPG.line}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontFamily: EPG.mono,
                  color: i <= 5 ? EPG.green : EPG.muted,
                }}>{i <= 5 ? '✓' : i}</div>
              ))}
            </div>
            <div style={{ marginTop: 10, fontSize: 11, color: EPG.amber, fontStyle: 'italic' }}>
              1 warning still to acknowledge.
            </div>
          </Card>

          <Card padding={18} style={{ background: EPG.brandInk, color: '#fff', border: 'none' }}>
            <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: 'rgba(255,255,255,0.6)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 8 }}>
              // Pin & send
            </div>
            <div style={{ fontFamily: EPG.serif, fontSize: 16, marginBottom: 6 }}>Send for e-signature</div>
            <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.65)', lineHeight: 1.5, marginBottom: 14 }}>
              Confirming snapshots a <span style={{fontFamily:EPG.mono}}>pinned_view_model</span>. Later override edits won't change what gets signed.
            </div>
            <Btn icon="send" style={{ background: '#fff', color: EPG.brandInk, borderColor: '#fff', width: '100%', justifyContent: 'center' }}>
              Confirm & send to Bennett
            </Btn>
          </Card>
        </div>
      </div>
    </AdviserShell>
  );
}

function Stat({ label, value, green, red, prominent }) {
  const color = green ? EPG.green : red ? EPG.red : EPG.ink;
  return (
    <div style={{
      padding: 18,
      borderRight: `1px solid ${EPG.line}`,
      borderBottom: `1px solid ${EPG.line}`,
      background: prominent ? EPG.brandBg : EPG.card,
    }}>
      <div style={{ fontFamily: EPG.mono, fontSize: 10, color: EPG.muted, letterSpacing: '0.08em', textTransform: 'uppercase' }}>{label}</div>
      <div style={{
        marginTop: 4,
        fontFamily: EPG.serif, fontSize: prominent ? 22 : 18, fontWeight: 600,
        color: prominent ? EPG.brand : color,
        letterSpacing: '-0.01em',
      }}>{aud(value)}</div>
    </div>
  );
}

function AgendaSection({ num, title, items, collapsed, tickedCount }) {
  const tickedNum = items ? items.filter(i => i.checked).length : null;
  return (
    <div style={{ borderBottom: `1px solid ${EPG.line}` }}>
      <div style={{ padding: '12px 20px', display: 'flex', alignItems: 'center', gap: 10, background: collapsed ? EPG.page : '#fff' }}>
        <Icon d={collapsed ? ICONS.chevR : ICONS.chevD} size={13} stroke={EPG.muted}/>
        <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.brand2, letterSpacing: '0.06em' }}>s{num}</div>
        <div style={{ flex: 1, fontFamily: EPG.serif, fontSize: 14, fontWeight: 600, color: EPG.ink }}>{title}</div>
        <Chip tone="muted">{items ? `${tickedNum} of ${items.length} ticked` : tickedCount}</Chip>
      </div>
      {!collapsed && items && (
        <div style={{ padding: '6px 20px 14px' }}>
          {items.map(item => (
            <CheckRow key={item.id} label={item.label} checked={item.checked} small id={item.id}/>
          ))}
        </div>
      )}
    </div>
  );
}

function CheckRow({ label, checked, small, id }) {
  return (
    <label style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: small ? '6px 0' : '5px 0',
      cursor: 'pointer',
    }}>
      <span style={{
        width: 16, height: 16, borderRadius: 4, flexShrink: 0,
        background: checked ? EPG.brand : '#fff',
        border: `1.5px solid ${checked ? EPG.brand : EPG.line2}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {checked && <Icon d={ICONS.check} size={11} stroke="#fff"/>}
      </span>
      <span style={{ flex: 1, fontSize: small ? 12.5 : 12.5, color: checked ? EPG.ink : EPG.ink2 }}>{label}</span>
      {id && <span style={{ fontFamily: EPG.mono, fontSize: 9.5, color: EPG.soft }}>{id}</span>}
    </label>
  );
}

// =====================================================================
// SCENE 8 — E-signature (signer flow on PDF)
// =====================================================================

function Scene8Signature() {
  const bp = useBreakpoint();
  const isMobile = bp === 'mobile';
  const isTablet = bp === 'tablet';
  const stack = bp !== 'desktop';
  return (
    <div style={{ minHeight: '100%', background: EPG.page, fontFamily: EPG.sans, color: EPG.ink, display: 'flex', flexDirection: 'column' }}>
      {/* Top strip */}
      <header style={{
        height: isMobile ? 52 : 60, flexShrink: 0,
        background: EPG.card, borderBottom: `1px solid ${EPG.line}`,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: `0 ${isMobile ? 14 : 24}px`,
        gap: 10,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 10 : 20, minWidth: 0 }}>
          <EpgLogo size={isMobile ? 22 : 26}/>
          {!isMobile && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: EPG.muted }}>
              <Chip tone="primary" icon="shieldDot">Daniel Bennett</Chip>
              <span>signing on behalf of Bennett review</span>
            </div>
          )}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 6 : 14, flexShrink: 0 }}>
          {!isMobile && <Btn variant="ghost" size="sm" icon="download">Download bundle</Btn>}
          <Btn variant="outline" size="sm" icon="x">{isMobile ? '' : 'Decline'}</Btn>
        </div>
      </header>

      {/* Doc tabs */}
      <div style={{ background: EPG.card, borderBottom: `1px solid ${EPG.line}`, padding: `8px ${isMobile ? 12 : 24}px`, display: 'flex', gap: 4, overflowX: 'auto' }}>
        {[
          { l: 'Fact Find',         active: true,  pages: '1–5'  },
          { l: 'Statement of Advice', active: false, pages: '6–18' },
          { l: 'Fee Disclosure',    active: false, pages: '19'   },
          { l: 'Payment Authority', active: false, pages: '20'   },
        ].map((t, i) => (
          <div key={i} style={{
            padding: '6px 12px',
            borderRadius: EPG.radiusSm,
            background: t.active ? EPG.brandBg : 'transparent',
            color: t.active ? EPG.brand : EPG.muted,
            fontSize: 12, fontWeight: t.active ? 600 : 500,
            cursor: 'pointer',
            display: 'flex', gap: 6, alignItems: 'center',
          }}>
            <span>{t.l}</span>
            <span style={{ fontFamily: EPG.mono, fontSize: 10, opacity: 0.7 }}>p{t.pages}</span>
          </div>
        ))}
      </div>

      {/* Main viewer area */}
      <div style={{ flex: 1, display: 'flex', flexDirection: stack ? 'column' : 'row', gap: 0, overflow: 'hidden' }}>
        {/* Page thumbs — desktop only */}
        {!stack && (
          <div style={{ width: 88, background: EPG.card, borderRight: `1px solid ${EPG.line}`, padding: '14px 10px', overflowY: 'auto', flexShrink: 0 }}>
            {[1,2,3,4,5].map(p => (
              <div key={p} style={{
                marginBottom: 8,
                border: `1.5px solid ${p === 3 ? EPG.brand : EPG.line}`,
                background: '#fff',
                borderRadius: 4,
                height: 84, padding: 6,
                position: 'relative',
                cursor: 'pointer',
                boxShadow: p === 3 ? '0 0 0 3px rgba(29,85,99,0.15)' : 'none',
              }}>
                <div style={{ height: 4, width: '60%', background: EPG.line, borderRadius: 1, marginBottom: 4 }}/>
                <div style={{ height: 3, width: '90%', background: EPG.line, borderRadius: 1, marginBottom: 3 }}/>
                <div style={{ height: 3, width: '85%', background: EPG.line, borderRadius: 1, marginBottom: 3 }}/>
                <div style={{ height: 3, width: '88%', background: EPG.line, borderRadius: 1, marginBottom: 8 }}/>
                {p === 3 && (
                  <div style={{ position: 'absolute', bottom: 12, left: 8, right: 8, height: 14, background: EPG.green + '40', borderRadius: 2, border: `1px solid ${EPG.green}` }}/>
                )}
                <div style={{ position: 'absolute', bottom: 4, left: 6, fontFamily: EPG.mono, fontSize: 9, color: EPG.muted }}>p{p}</div>
              </div>
            ))}
          </div>
        )}

        {/* PDF canvas */}
        <div style={{ flex: stack ? 'none' : 1, padding: isMobile ? '16px 12px' : '24px 32px', overflow: 'auto', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 24 }}>
          {/* PDF page */}
          <div style={{
            width: '100%', maxWidth: 600,
            background: '#fff',
            border: `1px solid ${EPG.line}`,
            boxShadow: '0 4px 24px rgba(28,45,48,0.08)',
            padding: isMobile ? '20px 18px' : '40px 50px',
            position: 'relative',
            minHeight: isMobile ? 480 : 700,
          }}>
            {/* Faux PDF content */}
            <div style={{ fontFamily: EPG.serif, fontSize: 18, fontWeight: 600, color: EPG.ink, marginBottom: 6 }}>Bennett Family — Fact Find Confirmation</div>
            <div style={{ fontFamily: EPG.sans, fontSize: 10, color: EPG.muted, marginBottom: 24 }}>Financial Advisory Firm · AFSL ##### · 21 May 2026</div>

            <FakePdfPara/>
            <FakePdfPara short/>
            <FakePdfPara/>

            <div style={{ fontFamily: EPG.serif, fontSize: 13, fontWeight: 600, color: EPG.ink, margin: '18px 0 8px' }}>Acknowledgement</div>
            <FakePdfPara/>
            <FakePdfPara short/>

            {/* Signature field — FILLED */}
            <div style={{ marginTop: 36, display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 140px', gap: isMobile ? 14 : 24, alignItems: 'flex-end' }}>
              <div>
                <div style={{ height: 56, borderBottom: `1.5px solid ${EPG.ink}`, position: 'relative', display: 'flex', alignItems: 'flex-end', paddingBottom: 4 }}>
                  <span style={{ fontFamily: '"Dancing Script", "Brush Script MT", cursive', fontSize: 28, color: EPG.brandInk, transform: 'rotate(-2deg)', display: 'inline-block' }}>
                    Daniel Bennett
                  </span>
                  <Chip tone="success" icon="check" style={{ position: 'absolute', top: -8, right: -8 }}>Signed</Chip>
                </div>
                <div style={{ fontSize: 10, color: EPG.muted, marginTop: 4 }}>Signer: Daniel Bennett</div>
              </div>
              <div>
                <div style={{ height: 56, borderBottom: `1.5px solid ${EPG.ink}`, fontSize: 11, color: EPG.ink2, display: 'flex', alignItems: 'flex-end', paddingBottom: 6, fontFamily: EPG.mono }}>21/05/2026</div>
                <div style={{ fontSize: 10, color: EPG.muted, marginTop: 4 }}>Date</div>
              </div>
            </div>

            {/* Signature field — UNFILLED for Anna, highlighted */}
            <div style={{ marginTop: 30, display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 140px', gap: isMobile ? 14 : 24, alignItems: 'flex-end' }}>
              <div>
                <button style={{
                  height: 56, width: '100%',
                  background: EPG.amberBg,
                  border: `1.5px dashed ${EPG.amber}`,
                  borderRadius: 4,
                  color: EPG.amber,
                  fontSize: 13, fontWeight: 600,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                  cursor: 'pointer',
                  animation: 'sigPulse 2.4s infinite',
                }}>
                  <Icon d={ICONS.pen} size={14}/> Sign here
                </button>
                <div style={{ fontSize: 10, color: EPG.muted, marginTop: 4 }}>Signer: Anna Bennett</div>
              </div>
              <div>
                <div style={{ height: 56, borderBottom: `1.5px solid ${EPG.ink}`, fontSize: 11, color: EPG.muted, display: 'flex', alignItems: 'flex-end', paddingBottom: 6, fontFamily: EPG.mono }}>—</div>
                <div style={{ fontSize: 10, color: EPG.muted, marginTop: 4 }}>Date</div>
              </div>
            </div>
          </div>
        </div>

        {/* Signer side panel — sidebar on desktop, full-width below PDF on stacked layouts */}
        <div style={{
          width: stack ? 'auto' : 260,
          background: EPG.card,
          borderLeft: stack ? 'none' : `1px solid ${EPG.line}`,
          borderTop: stack ? `1px solid ${EPG.line}` : 'none',
          padding: isMobile ? 16 : 20,
          display: 'flex', flexDirection: 'column', gap: 16,
          flexShrink: 0,
        }}>
          <div>
            <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 10 }}>// Signers</div>
            <SignerRow name="Daniel Bennett" email="daniel@example.com.au" status="signed" color={EPG.brand}/>
            <SignerRow name="Anna Bennett"   email="anna@example.com.au"   status="awaiting" color={EPG.amber}/>
          </div>
          <div>
            <div style={{ fontFamily: EPG.mono, fontSize: 10.5, color: EPG.muted, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 10 }}>// Progress</div>
            <div style={{ fontSize: 13, color: EPG.ink, marginBottom: 4 }}>9 of 14 fields complete</div>
            <div style={{ height: 6, background: EPG.line, borderRadius: 99, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: '64%', background: EPG.green, borderRadius: 99 }}/>
            </div>
          </div>
          <div style={{ flex: 1 }}/>
          <Btn size="lg" style={{ width: '100%', justifyContent: 'center' }}>Submit signed bundle</Btn>
          <div style={{ fontFamily: EPG.mono, fontSize: 10, color: EPG.muted, textAlign: 'center', lineHeight: 1.5 }}>
            ETA s10 compliant.<br/>Audit page is appended on submit.
          </div>
        </div>
      </div>

      <style>{`
        @keyframes sigPulse {
          0%,100% { box-shadow: 0 0 0 0 rgba(176,120,35,0.5); }
          50% { box-shadow: 0 0 0 6px rgba(176,120,35,0); }
        }
      `}</style>
    </div>
  );
}

function FakePdfPara({ short }) {
  const lines = short ? 2 : 4;
  const widths = ['96%','92%','98%','78%'];
  return (
    <div style={{ marginBottom: 10 }}>
      {Array.from({ length: lines }).map((_, i) => (
        <div key={i} style={{ height: 6, background: '#eaeef0', borderRadius: 1, marginBottom: 6, width: widths[i % widths.length] }}/>
      ))}
    </div>
  );
}

function SignerRow({ name, email, status, color }) {
  const isDone = status === 'signed';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '8px 10px',
      marginBottom: 6,
      borderRadius: EPG.radius,
      background: isDone ? EPG.greenBg : EPG.amberBg,
      border: `1px solid ${isDone ? 'rgba(47,122,74,0.25)' : 'rgba(176,120,35,0.25)'}`,
    }}>
      <div style={{ width: 8, height: 8, borderRadius: '50%', background: isDone ? EPG.green : EPG.amber }}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, fontWeight: 500, color: EPG.ink }}>{name}</div>
        <div style={{ fontSize: 10.5, color: EPG.muted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{email}</div>
      </div>
      <span style={{ fontFamily: EPG.mono, fontSize: 9.5, color: isDone ? EPG.green : EPG.amber, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{isDone ? '✓ signed' : 'awaiting'}</span>
    </div>
  );
}

// =====================================================================
// SCENE 9 — Audit log (demo ending)
// =====================================================================

function Scene9Audit() {
  const bp = useBreakpoint();
  const isMobile = bp === 'mobile';
  const isTablet = bp === 'tablet';
  const filterCols = isMobile ? 'repeat(2, 1fr)' : isTablet ? 'repeat(3, 1fr)' : 'repeat(5, 1fr) auto';
  return (
    <AdviserShell activeNav="audit" pageHeader={{
      breadcrumb: ['Admin', 'Audit log'],
      title: 'Audit log',
      count: 12,
      description: 'Immutable record of every state transition. Filter by entity, actor, action, date.',
      actions: [
        <Btn key="csv" variant="outline" size="sm" icon="download">Export CSV</Btn>,
      ],
    }}>
      {/* Filters */}
      <Card padding={isMobile ? 12 : 16} style={{ marginBottom: 16 }}>
        <div style={{ display: 'grid', gridTemplateColumns: filterCols, gap: isMobile ? 10 : 12, alignItems: 'end' }}>
          <FilterField label="Action" value="*"/>
          <FilterField label="Actor type" value="any"/>
          <FilterField label="Entity" value={isMobile ? 'client/Bennett' : 'client/aaaaaaaa-bbbb-…'} highlight/>
          <FilterField label="From" value="14 May 2026"/>
          <FilterField label="To" value="21 May 2026"/>
          <div style={{ gridColumn: isMobile || isTablet ? '1 / -1' : 'auto' }}>
            <Btn size="sm" icon="filter" style={isMobile || isTablet ? { width: '100%', justifyContent: 'center' } : {}}>Apply</Btn>
          </div>
        </div>
        <div style={{ marginTop: 10, fontFamily: EPG.mono, fontSize: 11, color: EPG.muted }}>
          Filter: <span style={{ color: EPG.brand }}>entity_id = client/Bennett</span> · 12 results · last 7 days
        </div>
      </Card>

      {/* Audit table */}
      <Card padding={0}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead>
              <tr style={{ background: EPG.page, borderBottom: `1px solid ${EPG.line}` }}>
                <Th width="200px">Timestamp</Th>
                <Th width="220px">Actor</Th>
                <Th width="220px">Action</Th>
                <Th width="220px">Entity</Th>
                <Th width="130px">IP</Th>
                <Th>Metadata</Th>
              </tr>
            </thead>
            <tbody>
              {S.auditChain.map((row, i) => {
                const isLast = i === S.auditChain.length - 1;
                return (
                  <tr key={row.id} style={{
                    borderBottom: `1px solid ${EPG.line}`,
                    background: isLast ? EPG.greenBg : 'transparent',
                  }}>
                    <Td>
                      <div style={{ fontFamily: EPG.mono, fontSize: 11, color: EPG.ink2 }}>{formatAest(row.timestamp)}</div>
                      <div style={{ fontSize: 10, color: EPG.muted, marginTop: 2 }}>{relTime(row.offsetDays)}</div>
                    </Td>
                    <Td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <ActorAvatar type={row.actorType} name={row.actorName}/>
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontSize: 12, color: EPG.ink, fontWeight: 500 }}>{row.actorName}</div>
                          <ActorChip type={row.actorType}/>
                        </div>
                      </div>
                    </Td>
                    <Td>
                      <span style={{
                        fontFamily: EPG.mono, fontSize: 11,
                        background: EPG.page, padding: '2px 8px', borderRadius: 4,
                        color: EPG.ink2,
                        border: `1px solid ${EPG.line}`,
                      }}>{row.action}</span>
                    </Td>
                    <Td>
                      <div style={{ fontFamily: EPG.mono, fontSize: 11, color: EPG.brand, textDecoration: 'underline', textDecorationStyle: 'dotted' }}>{row.entity}</div>
                    </Td>
                    <Td>
                      <div style={{ fontFamily: EPG.mono, fontSize: 11, color: EPG.ink2 }}>{row.ip}</div>
                    </Td>
                    <Td>
                      <details>
                        <summary style={{ cursor: 'pointer', color: EPG.muted, fontFamily: EPG.mono, fontSize: 11 }}>{Object.keys(row.meta).length} keys</summary>
                        <pre style={{ margin: '6px 0 0', padding: 8, background: EPG.page, borderRadius: 4, fontFamily: EPG.mono, fontSize: 10.5, color: EPG.ink2, overflow: 'auto' }}>
{JSON.stringify(row.meta, null, 2)}
                        </pre>
                      </details>
                    </Td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 18px', borderTop: `1px solid ${EPG.line}`, fontSize: 11.5, color: EPG.muted }}>
          <span>Page 1 of 1 · 12 total · 50 per page</span>
          <div style={{ display: 'flex', gap: 6 }}>
            <Btn variant="outline" size="sm" disabled icon="chevL">Prev</Btn>
            <Btn variant="outline" size="sm" disabled>Next</Btn>
          </div>
        </div>
      </Card>

      <div style={{ marginTop: 18, padding: 14, background: EPG.brandBg, border: `1px solid rgba(29,85,99,0.2)`, borderRadius: EPG.radius, display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <Icon d={ICONS.shieldDot} size={16} stroke={EPG.brand}/>
        <div style={{ fontSize: 12.5, color: EPG.ink2, lineHeight: 1.55 }}>
          <strong style={{ color: EPG.ink }}>One vertical thread.</strong> Filter to a client and you see the entire story from extraction through signature, in order, on one page. A compliance review is a date range and a filter, not a forensic exercise.
        </div>
      </div>
    </AdviserShell>
  );
}

function FilterField({ label, value, highlight }) {
  return (
    <div>
      <div style={{ fontFamily: EPG.mono, fontSize: 10, color: EPG.muted, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>{label}</div>
      <div style={{
        height: 30, padding: '0 10px',
        border: `1px solid ${highlight ? EPG.brand : EPG.line}`,
        background: highlight ? EPG.brandBg : EPG.card,
        borderRadius: EPG.radius,
        fontFamily: EPG.mono, fontSize: 11.5,
        color: highlight ? EPG.brand : EPG.ink2,
        display: 'flex', alignItems: 'center',
        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
      }}>{value}</div>
    </div>
  );
}

function Th({ children, width }) {
  return (
    <th style={{
      textAlign: 'left',
      padding: '12px 16px',
      fontFamily: EPG.mono, fontSize: 10.5, fontWeight: 500,
      color: EPG.muted, letterSpacing: '0.1em', textTransform: 'uppercase',
      width,
    }}>{children}</th>
  );
}
function Td({ children }) {
  return <td style={{ padding: '12px 16px', verticalAlign: 'top' }}>{children}</td>;
}
function ActorAvatar({ type, name }) {
  const initials = name.split(' ').map(p => p[0]).join('').slice(0,2);
  const bg = type === 'adviser' ? EPG.brand : type === 'client' ? EPG.gold : EPG.muted;
  return (
    <div style={{
      width: 28, height: 28, borderRadius: '50%',
      background: bg, color: '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 10, fontWeight: 600,
      flexShrink: 0,
    }}>{initials}</div>
  );
}
function ActorChip({ type }) {
  return <Chip tone={type === 'adviser' ? 'primary' : type === 'client' ? 'gold' : 'muted'}>{type}</Chip>;
}
function relTime(days) {
  if (days === 0) return 'just now';
  if (days === 1) return 'yesterday';
  return `${days}d ago`;
}

// =====================================================================
// EXPORT
// =====================================================================
Object.assign(window, {
  Scene1Upload, Scene2Extracting, Scene3Review, Scene4Confirm,
  Scene5OTP, Scene6Form, Scene7Cockpit, Scene8Signature, Scene9Audit,
});
