// Result dashboards (Bank Statement, Credit Bureau, Invoice), Admin, Logout, Borrowers.
// Re-themed to Editorial Forest tokens. Data shape and props are unchanged.

// ——— Tiny chart primitives — colors default to theme tokens ———
const Bars = ({data, w=240, h=60, color='hsl(var(--primary))', neg='hsl(var(--danger))'}) => {
  const max = Math.max(...data.map(d=>Math.abs(d)));
  const bw = w / data.length;
  return (
    <svg width={w} height={h} style={{display:'block'}}>
      {data.map((d,i)=>{
        const bh = (Math.abs(d)/max)*(h-4);
        return <rect key={i} x={i*bw+1} y={d>=0 ? (h-bh)/1 : (h/2)} width={bw-2} height={bh} fill={d>=0?color:neg} rx={2}/>;
      })}
    </svg>
  );
};

const Line = ({data, w=240, h=60, color='hsl(var(--primary))', fill='hsl(var(--accent-soft))'}) => {
  const max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((d,i)=>[i*(w/(data.length-1)), h-2 - ((d-min)/(max-min||1))*(h-4)]);
  const dstr = 'M'+pts.map(p=>p.join(',')).join(' L');
  const area = dstr+` L${w},${h} L0,${h} Z`;
  return (
    <svg width={w} height={h} style={{display:'block'}}>
      <path d={area} fill={fill}/>
      <path d={dstr} stroke={color} strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
};

const Donut = ({value, size=80, stroke=10, color='hsl(var(--primary))', track='hsl(var(--surface-2))', label}) => {
  const r = (size-stroke)/2, c = 2*Math.PI*r;
  return (
    <div style={{position:'relative', width:size, height:size}}>
      <svg width={size} height={size} style={{transform:'rotate(-90deg)'}}>
        <circle cx={size/2} cy={size/2} r={r} stroke={track} strokeWidth={stroke} fill="none"/>
        <circle cx={size/2} cy={size/2} r={r} stroke={color} strokeWidth={stroke} fill="none" strokeDasharray={c} strokeDashoffset={c*(1-value/100)} strokeLinecap="round"/>
      </svg>
      <div style={{position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', flexDirection:'column'}}>
        <div style={{fontSize:size*0.22, fontWeight:700, color:'hsl(var(--fg))', letterSpacing:'-0.02em'}}>{value}</div>
        {label && <div style={{fontSize:10, color:'hsl(var(--fg-muted))'}}>{label}</div>}
      </div>
    </div>
  );
};

// ——— Result Dashboard: Bank Statement ———
function BankStatementReport({onBack, currency, report}) {
  const [tab, setTab] = React.useState('overview');
  const tabs = ['overview','transactions','daily balance','counterparties','cam analysis'];
  const cur = currency || { code: 'IDR', symbol: 'Rp', locale: 'id-ID' };

  const transactions = React.useMemo(() => {
    if (!report) return null;
    return report?.transactions || [];
  }, [report]);

  const sessionId = report?.session_id || '';
  const customerId = report?.customer_id || '';

  return (
    <CurrencyCtx.Provider value={cur}>
    <div style={{display:'flex', flexDirection:'column', height:'100%', background:'hsl(var(--bg))'}}>
      <div style={{padding:'20px 32px 0', borderBottom:'1px solid hsl(var(--border))', background:'hsl(var(--surface))'}}>
        <div style={{display:'flex', alignItems:'center', gap:10, fontSize:13, color:'hsl(var(--fg-muted))', marginBottom:10}}>
          <a href="#" className="cx-link" onClick={e=>{e.preventDefault(); onBack && onBack()}}>Sessions</a>
          <I.chevronRight/>
          <span style={{color:'hsl(var(--fg))', fontFamily:'var(--font-mono)', fontSize:12}}>{sessionId}</span>
        </div>
        <div style={{display:'flex', alignItems:'flex-end', gap:20, marginBottom:16}}>
          <div style={{flex:1}}>
            <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:6}}>
              <div style={{fontFamily:'var(--font-serif)', fontSize:30, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.025em'}}>Bank Statement <span style={{fontStyle:'italic'}}>Analysis</span></div>
              <Badge tone="success"><I.check/>Completed</Badge>
            </div>
            <div style={{fontSize:13, color:'hsl(var(--fg-muted))'}}>Borrower <b style={{color:'hsl(var(--fg))'}}>{customerId}</b> · {transactions ? transactions.length + ' transactions' : 'Loading…'}</div>
          </div>
          <Button variant="secondary" icon={<I.download/>} size="sm">Export JSON</Button>
        </div>
        <div style={{display:'flex', gap:4}}>
          {tabs.map(t=>(
            <button key={t} onClick={()=>setTab(t)} style={{padding:'10px 14px', border:'none', background:'transparent', cursor:'pointer', fontFamily:'inherit', fontSize:13, fontWeight:500, color: tab===t ? 'hsl(var(--primary))' : 'hsl(var(--fg-muted))', borderBottom: tab===t ? '2px solid hsl(var(--accent))' : '2px solid transparent', textTransform:'capitalize', marginBottom:-1, transition:'color 150ms'}}>
              {t}
            </button>
          ))}
        </div>
      </div>
      <div style={{flex:1, overflow:'auto', padding:'22px 32px'}}>
        {tab==='overview' && <OverviewPane/>}
        {tab==='transactions' && <TransactionsPane transactions={transactions}/>}
        {tab==='daily balance' && <DailyBalancePane/>}
        {tab==='counterparties' && <CounterpartiesPane/>}
        {tab==='cam analysis' && <CamPane/>}
      </div>
    </div>
    </CurrencyCtx.Provider>
  );
}

function KPI({label, value, delta, tone='brand', spark}) {
  const toneC = {
    brand:'hsl(var(--primary))',
    success:'hsl(var(--success))',
    warning:'hsl(var(--warning))',
    danger:'hsl(var(--danger))',
  }[tone];
  const fillC = {
    brand:'hsl(var(--accent-soft))',
    success:'hsl(var(--success-bg))',
    warning:'hsl(var(--warning-bg))',
    danger:'hsl(var(--danger-bg))',
  }[tone];
  return (
    <Card padding={18}>
      <div style={{fontSize:12, color:'hsl(var(--fg-muted))', marginBottom:6, fontWeight:500}}>{label}</div>
      <div style={{display:'flex', alignItems:'baseline', gap:8, marginBottom:10}}>
        <div style={{fontFamily:'var(--font-serif)', fontSize:30, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.025em'}}>{value}</div>
        {delta && <div style={{fontSize:12, color: delta.startsWith('+') ? 'hsl(var(--success-fg))' : 'hsl(var(--danger))', fontWeight:600}}>{delta}</div>}
      </div>
      {spark && <Line data={spark} w={220} h={36} color={toneC} fill={fillC}/>}
    </Card>
  );
}

function OverviewPane() {
  return (
    <div style={{display:'flex', flexDirection:'column', gap:18}}>
      <div style={{display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14}}>
        <KPI label="Total Credits" value="Rp 4.2B" delta="+12%" tone="success" spark={[2.1,2.6,2.4,3.1,3.5,3.2,3.9,4.2]}/>
        <KPI label="Total Debits" value="Rp 3.8B" delta="+8%" tone="brand" spark={[2.0,2.3,2.5,2.9,3.1,3.0,3.6,3.8]}/>
        <KPI label="Avg Daily Balance" value="Rp 842M" delta="+4%" tone="brand" spark={[620,680,710,740,780,820,840,842]}/>
        <KPI label="Bounced Cheques" value="2" delta="−1" tone="success" spark={[3,2,4,2,3,2,1,2]}/>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'1.5fr 1fr', gap:14}}>
        <Card>
          <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:14}}>
            <div style={{fontSize:15, fontWeight:600, color:'hsl(var(--fg))'}}>Daily balance trend</div>
            <div style={{display:'flex', gap:6}}>
              {['30d','90d','All'].map((t,i)=><button key={t} style={{padding:'4px 10px', fontSize:11, fontFamily:'inherit', border:'1px solid hsl(var(--border))', borderRadius:8, background: i===1 ? 'hsl(var(--accent-soft))' : 'hsl(var(--surface))', color: i===1 ? 'hsl(var(--primary))' : 'hsl(var(--fg-muted))', cursor:'pointer', fontWeight:500}}>{t}</button>)}
            </div>
          </div>
          <Line data={[620,680,650,710,720,780,740,820,800,840,810,860,830,842,870,840,880,870,910,880,930,900,950,920,940,960,930,970]} w={560} h={180}/>
          <div style={{display:'flex', justifyContent:'space-between', fontSize:11, color:'hsl(var(--fg-subtle))', marginTop:8}}>
            <span>Jan 1</span><span>Feb 1</span><span>Mar 1</span><span>Apr 21</span>
          </div>
        </Card>
        <Card>
          <div style={{fontSize:15, fontWeight:600, color:'hsl(var(--fg))', marginBottom:14}}>Transaction mix</div>
          <div style={{display:'flex', alignItems:'center', gap:18}}>
            <Donut value={68} size={120} stroke={14} label="Credits"/>
            <div style={{flex:1, fontSize:12, display:'flex', flexDirection:'column', gap:10}}>
              {[['Payments in','hsl(var(--primary))',42],['Refunds','hsl(var(--accent))',18],['Transfers','hsl(var(--gold))',22],['Other','hsl(var(--border-strong))',18]].map(([l,c,v])=>
                <div key={l} style={{display:'flex', alignItems:'center', gap:8}}>
                  <div style={{width:10, height:10, borderRadius:3, background:c}}/>
                  <div style={{flex:1, color:'hsl(var(--fg))'}}>{l}</div>
                  <div style={{color:'hsl(var(--fg))', fontWeight:600}}>{v}%</div>
                </div>
              )}
            </div>
          </div>
        </Card>
      </div>
      <Card>
        <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:12}}>
          <div style={{fontSize:15, fontWeight:600, color:'hsl(var(--fg))'}}>Key flags</div>
          <Badge tone="warning">3 flags</Badge>
        </div>
        <div style={{display:'flex', flexDirection:'column', gap:8}}>
          {[
            {tone:'warning', title:'Round-number deposits detected', desc:'4 credits of exactly Rp 100M within 3 days (Feb 8–11). Manual review recommended.'},
            {tone:'success', title:'Stable salary inflow', desc:'Monthly credit ~Rp 48M from PT SINAR MAS AGRO, 4 consecutive months.'},
            {tone:'danger',  title:'2 cheque bounces', desc:'Rp 12.5M on Mar 3 (insufficient funds), Rp 8.2M on Feb 17 (stop payment).'},
          ].map((f,i)=>{
            const bg     = `hsl(var(--${f.tone}-bg))`;
            const border = `hsl(var(--${f.tone}) / 0.3)`;
            const fg     = `hsl(var(--${f.tone}-fg))`;
            return (
              <div key={i} style={{display:'flex', gap:12, padding:'12px 14px', background:bg, border:`1px solid ${border}`, borderRadius:12}}>
                <div style={{color:fg, display:'flex', alignItems:'center'}}>{f.tone==='success'?<I.check/>:<I.alert/>}</div>
                <div style={{flex:1}}>
                  <div style={{fontSize:13, fontWeight:600, color:'hsl(var(--fg))', marginBottom:2}}>{f.title}</div>
                  <div style={{fontSize:12, color:'hsl(var(--fg-muted))'}}>{f.desc}</div>
                </div>
              </div>
            );
          })}
        </div>
      </Card>
    </div>
  );
}

function TransactionsPane({ transactions }) {
  const cur = useCurrency();
  const [search, setSearch] = React.useState('');
  const [catFilter, setCatFilter] = React.useState('All');

  const categories = React.useMemo(() => {
    if (!transactions?.length) return [];
    return ['All', ...Array.from(new Set(transactions.map(t => t.category || 'Uncategorized'))).sort()];
  }, [transactions]);

  const filtered = React.useMemo(() => {
    if (!transactions) return [];
    return transactions.filter(t => {
      const matchSearch = !search || (t.description || '').toLowerCase().includes(search.toLowerCase());
      const matchCat = catFilter === 'All' || (t.category || 'Uncategorized') === catFilter;
      return matchSearch && matchCat;
    });
  }, [transactions, search, catFilter]);

  if (transactions === null) return (
    <div style={{display:'flex', alignItems:'center', justifyContent:'center', height:200, gap:12, color:'hsl(var(--fg-muted))'}}>
      <Spinner/><span style={{fontSize:14}}>Loading transactions…</span>
    </div>
  );

  return (
    <Card padding={0}>
      <div style={{padding:'14px 18px', borderBottom:'1px solid hsl(var(--border))', display:'flex', alignItems:'center', gap:10, flexWrap:'wrap'}}>
        <div style={{display:'flex', alignItems:'center', gap:8, height:36, padding:'0 12px', borderRadius:10, border:'1px solid hsl(var(--border))', flex:'1 1 220px', maxWidth:320, background:'hsl(var(--surface))'}}>
          <I.search style={{color:'hsl(var(--fg-subtle))', flexShrink:0}}/>
          <input
            value={search}
            onChange={e => setSearch(e.target.value)}
            placeholder="Search transactions"
            style={{flex:1, border:'none', outline:'none', fontSize:13, fontFamily:'inherit', color:'hsl(var(--fg))', background:'transparent'}}
          />
        </div>
        <select
          value={catFilter}
          onChange={e => setCatFilter(e.target.value)}
          style={{height:36, padding:'0 10px', borderRadius:10, border:'1px solid hsl(var(--border))', fontSize:13, fontFamily:'inherit', color:'hsl(var(--fg))', background:'hsl(var(--surface))', cursor:'pointer'}}
        >
          {categories.map(c => <option key={c}>{c}</option>)}
        </select>
        <div style={{flex:1}}/>
        <Badge tone="brand">{filtered.length} transactions</Badge>
      </div>
      {filtered.length === 0 ? (
        <div style={{padding:'48px 18px', textAlign:'center', color:'hsl(var(--fg-subtle))', fontSize:13}}>No transactions match your filter</div>
      ) : (
        <div style={{overflowX:'auto'}}>
          <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
            <thead>
              <tr style={{background:'hsl(var(--surface-2))', fontSize:11, color:'hsl(var(--fg-muted))', textTransform:'uppercase', letterSpacing:'0.05em'}}>
                <th style={{textAlign:'left', padding:'10px 18px', fontWeight:600}}>Date</th>
                <th style={{textAlign:'left', padding:'10px 8px', fontWeight:600}}>Description</th>
                <th style={{textAlign:'left', padding:'10px 8px', fontWeight:600}}>Category</th>
                <th style={{textAlign:'right', padding:'10px 8px', fontWeight:600}}>Amount</th>
                <th style={{textAlign:'right', padding:'10px 18px', fontWeight:600}}>Balance</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((t, i) => {
                const isCredit = (t.type || '').toLowerCase() === 'credit';
                const amt = parseFloat(t.amount) || 0;
                const bal = parseFloat(t.balance);
                const cat = t.category || 'Uncategorized';
                return (
                  <tr key={i} className="cx-row" style={{borderTop:'1px solid hsl(var(--border))'}}>
                    <td style={{padding:'10px 18px', color:'hsl(var(--fg-muted))', fontFamily:'var(--font-mono)', fontSize:12, whiteSpace:'nowrap'}}>{t.date || '—'}</td>
                    <td style={{padding:'10px 8px', color:'hsl(var(--fg))', fontWeight:500, maxWidth:300, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{t.description || '—'}</td>
                    <td style={{padding:'10px 8px'}}><Badge tone={isCredit ? 'success' : 'neutral'} size="sm">{cat}</Badge></td>
                    <td style={{padding:'10px 8px', textAlign:'right', fontVariantNumeric:'tabular-nums', fontWeight:600, color: isCredit ? 'hsl(var(--success-fg))' : 'hsl(var(--danger))', whiteSpace:'nowrap'}}>
                      {isCredit ? '+' : '-'}{fmtAmt(amt, cur)}
                    </td>
                    <td style={{padding:'10px 18px', textAlign:'right', fontVariantNumeric:'tabular-nums', color:'hsl(var(--fg-muted))', whiteSpace:'nowrap'}}>
                      {isNaN(bal) ? '—' : fmtAmt(bal, cur)}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </Card>
  );
}

function DailyBalancePane() {
  const data = Array.from({length:90}, (_,i)=>600+Math.sin(i/8)*80+i*3+Math.random()*40);
  return (
    <div style={{display:'flex', flexDirection:'column', gap:14}}>
      <Card>
        <div style={{fontSize:15, fontWeight:600, color:'hsl(var(--fg))', marginBottom:14}}>Daily closing balance — 90 days</div>
        <Line data={data} w={960} h={260}/>
      </Card>
      <div style={{display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:14}}>
        <KPI label="Min Balance" value="Rp 124M" tone="warning" spark={data.slice(0,20)}/>
        <KPI label="Max Balance" value="Rp 1.24B" tone="success" spark={data.slice(-20)}/>
        <KPI label="Avg Balance" value="Rp 842M" tone="brand" spark={data.slice(30,50)}/>
      </div>
    </div>
  );
}

function CounterpartiesPane() {
  const rows = [
    {name:'PT BUMI RESOURCES', type:'Business', txns:24, total:'Rp 1.2B', direction:'in'},
    {name:'CV KARYA JAYA', type:'Vendor', txns:18, total:'Rp 485M', direction:'out'},
    {name:'PT SINAR MAS AGRO', type:'Employer', txns:4, total:'Rp 192M', direction:'in'},
    {name:'BCA CREDIT CARD', type:'Card', txns:12, total:'Rp 294M', direction:'out'},
    {name:'BNI HOME LOAN', type:'EMI', txns:4, total:'Rp 73M', direction:'out'},
  ];
  return (
    <Card padding={0}>
      <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
        <thead>
          <tr style={{background:'hsl(var(--surface-2))', fontSize:11, color:'hsl(var(--fg-muted))', textTransform:'uppercase'}}>
            <th style={{textAlign:'left', padding:'10px 18px', fontWeight:600}}>Counterparty</th>
            <th style={{textAlign:'left', padding:'10px 8px', fontWeight:600}}>Type</th>
            <th style={{textAlign:'right', padding:'10px 8px', fontWeight:600}}>Transactions</th>
            <th style={{textAlign:'right', padding:'10px 18px', fontWeight:600}}>Volume</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r,i)=>(
            <tr key={i} className="cx-row" style={{borderTop:'1px solid hsl(var(--border))'}}>
              <td style={{padding:'12px 18px'}}>
                <div style={{display:'flex', alignItems:'center', gap:10}}>
                  <Avatar name={r.name} size={30} color={r.direction==='in' ? 'hsl(var(--success))' : 'hsl(var(--primary))'}/>
                  <div style={{fontWeight:600, color:'hsl(var(--fg))'}}>{r.name}</div>
                </div>
              </td>
              <td style={{padding:'12px 8px'}}><Badge tone="neutral" size="sm">{r.type}</Badge></td>
              <td style={{padding:'12px 8px', textAlign:'right', fontVariantNumeric:'tabular-nums', color:'hsl(var(--fg))'}}>{r.txns}</td>
              <td style={{padding:'12px 18px', textAlign:'right', fontWeight:600, color: r.direction==='in' ? 'hsl(var(--success-fg))' : 'hsl(var(--fg))', fontVariantNumeric:'tabular-nums'}}>{r.direction==='in'?'+':'−'}{r.total}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

function CamPane() {
  return (
    <div style={{display:'grid', gridTemplateColumns:'1fr 320px', gap:14}}>
      <Card padding={28} style={{maxHeight:'calc(100vh - 240px)', overflow:'auto'}}>
        <div style={{fontFamily:'var(--font-serif)', fontSize:30, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.025em', marginBottom:6}}>Credit Appraisal <span style={{fontStyle:'italic'}}>Memo</span></div>
        <div style={{fontSize:13, color:'hsl(var(--fg-muted))', marginBottom:18}}>Generated Apr 21, 2026 · Model v2.1</div>
        <div style={{padding:18, background:'hsl(var(--accent-soft))', border:'1px solid hsl(var(--accent) / 0.3)', borderRadius:14, marginBottom:20}}>
          <div style={{fontSize:13, fontWeight:600, color:'hsl(var(--primary))', marginBottom:6, textTransform:'uppercase', letterSpacing:'0.05em'}}>Executive Summary</div>
          <div style={{fontSize:13, color:'hsl(var(--fg))', lineHeight:1.6}}>Borrower demonstrates a consistent inflow pattern with an average daily balance of Rp 842M over 90 days. Stable business income from PT BUMI RESOURCES accounts for 48% of credits. Two cheque returns in the period warrant a soft enquiry. Overall cashflow profile is supportive of the proposed facility.</div>
        </div>
        {[
          {h:'Cashflow Analysis', b:'Net cashflow positive in 11 of 12 months. Inflow concentration from 3 counterparties (72%) is within acceptable limits for SME lending. No material seasonality observed.'},
          {h:'Obligation Servicing', b:'Existing EMI commitments total Rp 73M/month (BNI Home Loan) with 100% on-time servicing. Credit card utilisation averaged 34% with full-payment behaviour.'},
          {h:'Red Flags', b:'Four round-number deposits of Rp 100M detected between Feb 8–11; review recommended. Two cheque returns in the period (Rp 20.7M total). No adverse bureau record identified.'},
          {h:'Recommendation', b:'APPROVE with a facility size up to Rp 5.2B, 24-month tenor, at a contracted rate of 11.5% p.a. Condition: quarterly bank statement refresh.'},
        ].map((s,i)=>(
          <div key={i} style={{marginBottom:18}}>
            <div style={{fontSize:15, fontWeight:600, color:'hsl(var(--fg))', marginBottom:6}}>{s.h}</div>
            <div style={{fontSize:13, color:'hsl(var(--fg))', lineHeight:1.7}}>{s.b}</div>
          </div>
        ))}
      </Card>
      <div style={{display:'flex', flexDirection:'column', gap:14, position:'sticky', top:0, alignSelf:'start'}}>
        <Card>
          <div style={{fontSize:13, fontWeight:600, color:'hsl(var(--fg))', marginBottom:10}}>Credit score</div>
          <div style={{display:'flex', alignItems:'center', gap:14}}>
            <Donut value={742} size={90} stroke={10} color="hsl(var(--success))"/>
            <div>
              <Badge tone="success">Good</Badge>
              <div style={{fontSize:11, color:'hsl(var(--fg-muted))', marginTop:6}}>Top 28% in segment</div>
            </div>
          </div>
        </Card>
        <Card>
          <div style={{fontSize:13, fontWeight:600, color:'hsl(var(--fg))', marginBottom:10}}>Ratios</div>
          <div style={{display:'flex', flexDirection:'column', gap:10, fontSize:12}}>
            {[['DSCR','1.86','success'],['Debt/Income','0.24','success'],['Cash buffer','3.2 mo','brand'],['Inflow stability','Low Var','success']].map(([l,v,t])=>
              <div key={l} style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                <span style={{color:'hsl(var(--fg-muted))'}}>{l}</span>
                <Badge tone={t} size="sm">{v}</Badge>
              </div>
            )}
          </div>
        </Card>
        <Button variant="primary" full size="lg" icon={<I.checkCircle/>}>Approve & issue term sheet</Button>
        <Button variant="secondary" full>Return for more info</Button>
      </div>
    </div>
  );
}

// ——— Credit Bureau ———
function CreditBureauReport({onBack}) {
  return (
    <div style={{display:'flex', flexDirection:'column', height:'100%', background:'hsl(var(--bg))'}}>
      <div style={{padding:'20px 32px 18px', borderBottom:'1px solid hsl(var(--border))', background:'hsl(var(--surface))'}}>
        <div style={{display:'flex', alignItems:'center', gap:10, fontSize:13, color:'hsl(var(--fg-muted))', marginBottom:10}}>
          <a href="#" className="cx-link" onClick={e=>{e.preventDefault(); onBack && onBack()}}>Sessions</a>
          <I.chevronRight/><span style={{color:'hsl(var(--fg))', fontFamily:'var(--font-mono)', fontSize:12}}>sess_6b8382c3</span>
        </div>
        <div style={{display:'flex', alignItems:'flex-end', gap:20}}>
          <div style={{flex:1}}>
            <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:4}}>
              <div style={{fontFamily:'var(--font-serif)', fontSize:30, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.025em'}}>Credit Bureau <span style={{fontStyle:'italic'}}>Report</span></div>
              <Badge tone="success"><I.check/>Completed</Badge>
            </div>
            <div style={{fontSize:13, color:'hsl(var(--fg-muted))'}}>Borrower <b style={{color:'hsl(var(--fg))'}}>BRW-2931</b> · Budi Santoso · CIBIL + Experian</div>
          </div>
          <Button variant="secondary" icon={<I.download/>} size="sm">Download PDF</Button>
        </div>
      </div>
      <div style={{flex:1, overflow:'auto', padding:'22px 32px'}}>
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:14, marginBottom:14}}>
          <Card>
            <div style={{display:'flex', alignItems:'center', gap:16}}>
              <Donut value={782} size={100} stroke={12} color="hsl(var(--success))"/>
              <div>
                <div style={{fontSize:12, color:'hsl(var(--fg-muted))'}}>CIBIL Score</div>
                <div style={{fontFamily:'var(--font-serif)', fontSize:36, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.025em', lineHeight:1}}>782</div>
                <Badge tone="success" size="sm" style={{marginTop:6}}>Excellent</Badge>
              </div>
            </div>
          </Card>
          <Card>
            <div style={{display:'flex', alignItems:'center', gap:16}}>
              <Donut value={76} size={100} stroke={12} label="Util"/>
              <div>
                <div style={{fontSize:12, color:'hsl(var(--fg-muted))'}}>Credit Utilisation</div>
                <div style={{fontFamily:'var(--font-serif)', fontSize:36, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.025em', lineHeight:1}}>24%</div>
                <Badge tone="success" size="sm" style={{marginTop:6}}>Healthy</Badge>
              </div>
            </div>
          </Card>
          <Card>
            <div style={{fontSize:12, color:'hsl(var(--fg-muted))', marginBottom:4}}>Active accounts</div>
            <div style={{fontFamily:'var(--font-serif)', fontSize:36, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.025em', marginBottom:8, lineHeight:1}}>6</div>
            <div style={{display:'flex', gap:6}}>
              <Badge tone="brand" size="sm">3 CC</Badge>
              <Badge tone="neutral" size="sm">2 Loans</Badge>
              <Badge tone="neutral" size="sm">1 Home</Badge>
            </div>
          </Card>
        </div>
        <Card>
          <div style={{fontSize:15, fontWeight:600, color:'hsl(var(--fg))', marginBottom:14}}>Payment history — 24 months</div>
          <div style={{display:'grid', gridTemplateColumns:'repeat(24,1fr)', gap:3}}>
            {Array.from({length:24}).map((_,i)=>{
              const v = i===7?'30':i===15?'30':'OK';
              return <div key={i} style={{height:32, borderRadius:6, background: v==='OK' ? 'hsl(var(--success))' : 'hsl(var(--warning))', display:'flex', alignItems:'center', justifyContent:'center', fontSize:9, color:'#fff', fontWeight:600}}>{v==='OK'?'':v}</div>;
            })}
          </div>
          <div style={{display:'flex', gap:14, marginTop:10, fontSize:11, color:'hsl(var(--fg-muted))'}}>
            <span>Apr 2024</span><span style={{flex:1, textAlign:'center'}}>Apr 2025</span><span>Apr 2026</span>
          </div>
        </Card>
      </div>
    </div>
  );
}

// ——— Invoice ———
function InvoiceReport({onBack}) {
  return (
    <div style={{display:'flex', flexDirection:'column', height:'100%', background:'hsl(var(--bg))'}}>
      <div style={{padding:'20px 32px 18px', borderBottom:'1px solid hsl(var(--border))', background:'hsl(var(--surface))'}}>
        <div style={{display:'flex', alignItems:'center', gap:10, fontSize:13, color:'hsl(var(--fg-muted))', marginBottom:10}}>
          <a href="#" className="cx-link" onClick={e=>{e.preventDefault(); onBack && onBack()}}>Sessions</a>
          <I.chevronRight/><span style={{color:'hsl(var(--fg))', fontFamily:'var(--font-mono)', fontSize:12}}>sess_be067ef3</span>
        </div>
        <div style={{display:'flex', alignItems:'flex-end', gap:20}}>
          <div style={{flex:1}}>
            <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:4}}>
              <div style={{fontFamily:'var(--font-serif)', fontSize:30, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.025em'}}>Invoice <span style={{fontStyle:'italic'}}>Analysis</span></div>
              <Badge tone="success"><I.check/>Completed</Badge>
            </div>
            <div style={{fontSize:13, color:'hsl(var(--fg-muted))'}}>Invoice <b style={{color:'hsl(var(--fg))'}}>#INV-2024-8842</b> · PT Sinar Mas Agro</div>
          </div>
          <Button variant="secondary" icon={<I.download/>} size="sm">Export</Button>
        </div>
      </div>
      <div style={{flex:1, overflow:'auto', padding:'22px 32px'}}>
        <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap:14}}>
          <Card>
            <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:18, paddingBottom:16, borderBottom:'1px solid hsl(var(--border))'}}>
              <div>
                <div style={{fontSize:11, color:'hsl(var(--fg-muted))', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:4, fontWeight:600}}>Invoice</div>
                <div style={{fontFamily:'var(--font-serif)', fontSize:28, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.025em'}}>INV-2024-8842</div>
              </div>
              <div style={{textAlign:'right'}}>
                <div style={{fontSize:11, color:'hsl(var(--fg-muted))', textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:600}}>Total</div>
                <div style={{fontFamily:'var(--font-serif)', fontSize:30, fontWeight:400, color:'hsl(var(--primary))', letterSpacing:'-0.025em'}}>Rp 284,500,000</div>
              </div>
            </div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:24, marginBottom:18}}>
              <div>
                <div style={{fontSize:11, color:'hsl(var(--fg-muted))', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:8, fontWeight:600}}>Supplier</div>
                <div style={{fontSize:14, fontWeight:600, color:'hsl(var(--fg))'}}>PT Karya Manufaktur Indonesia</div>
                <div style={{fontSize:12, color:'hsl(var(--fg-muted))', lineHeight:1.6, marginTop:4}}>Jl. Sudirman Kav. 52, Jakarta 12190<br/>NPWP: 01.234.567.8-901.000</div>
              </div>
              <div>
                <div style={{fontSize:11, color:'hsl(var(--fg-muted))', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:8, fontWeight:600}}>Buyer</div>
                <div style={{fontSize:14, fontWeight:600, color:'hsl(var(--fg))'}}>PT Sinar Mas Agro</div>
                <div style={{fontSize:12, color:'hsl(var(--fg-muted))', lineHeight:1.6, marginTop:4}}>Jl. Thamrin No. 51, Jakarta 10350<br/>NPWP: 02.345.678.9-012.000</div>
              </div>
            </div>
            <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
              <thead>
                <tr style={{fontSize:11, color:'hsl(var(--fg-muted))', textTransform:'uppercase', letterSpacing:'0.05em', borderBottom:'1px solid hsl(var(--border))'}}>
                  <th style={{textAlign:'left', padding:'10px 0', fontWeight:600}}>Item</th>
                  <th style={{textAlign:'right', padding:'10px 8px', fontWeight:600}}>Qty</th>
                  <th style={{textAlign:'right', padding:'10px 8px', fontWeight:600}}>Rate</th>
                  <th style={{textAlign:'right', padding:'10px 0', fontWeight:600}}>Amount</th>
                </tr>
              </thead>
              <tbody>
                {[['Palm oil refinery equipment — Module A',2,'85,000,000','170,000,000'],['Installation & commissioning',1,'42,500,000','42,500,000'],['Training (on-site, 5 days)',1,'18,000,000','18,000,000'],['Spare parts kit',3,'18,000,000','54,000,000']].map((r,i)=>(
                  <tr key={i} style={{borderBottom:'1px solid hsl(var(--border))'}}>
                    <td style={{padding:'10px 0', color:'hsl(var(--fg))'}}>{r[0]}</td>
                    <td style={{padding:'10px 8px', textAlign:'right', color:'hsl(var(--fg-muted))'}}>{r[1]}</td>
                    <td style={{padding:'10px 8px', textAlign:'right', color:'hsl(var(--fg-muted))', fontVariantNumeric:'tabular-nums'}}>Rp {r[2]}</td>
                    <td style={{padding:'10px 0', textAlign:'right', fontWeight:600, color:'hsl(var(--fg))', fontVariantNumeric:'tabular-nums'}}>Rp {r[3]}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
          <div style={{display:'flex', flexDirection:'column', gap:14}}>
            <Card>
              <div style={{fontSize:13, fontWeight:600, color:'hsl(var(--fg))', marginBottom:10}}>Extraction confidence</div>
              <div style={{display:'flex', alignItems:'center', gap:14}}>
                <Donut value={98} size={80} stroke={10} color="hsl(var(--success))"/>
                <div style={{fontSize:12, color:'hsl(var(--fg-muted))', lineHeight:1.6}}>All fields extracted. Manual review recommended for <b style={{color:'hsl(var(--fg))'}}>2</b> line items.</div>
              </div>
            </Card>
            <Card>
              <div style={{fontSize:13, fontWeight:600, color:'hsl(var(--fg))', marginBottom:10}}>Cross-checks</div>
              <div style={{display:'flex', flexDirection:'column', gap:8, fontSize:12}}>
                {[['NPWP format','pass'],['GST calculation','pass'],['Sum of line items','pass'],['Duplicate invoice','warn']].map(([l,s])=>
                  <div key={l} style={{display:'flex', alignItems:'center', gap:8}}>
                    <div style={{width:22, height:22, borderRadius:11, background: s==='pass' ? 'hsl(var(--success))' : 'hsl(var(--warning))', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center'}}>{s==='pass'?<I.check/>:<I.alert/>}</div>
                    <span style={{flex:1, color:'hsl(var(--fg))'}}>{l}</span>
                    <span style={{color:'hsl(var(--fg-muted))', textTransform:'capitalize'}}>{s}</span>
                  </div>
                )}
              </div>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}

// ——— Admin / Team ———
function AdminTeam() {
  const members = [
    {name:'Fina Lestari', email:'fina.lestari@bankx.id', role:'Admin', last:'Active now'},
    {name:'Aditya Rahman', email:'aditya.rahman@bankx.id', role:'Analyst', last:'12 min ago'},
    {name:'Siti Nuraini', email:'siti.n@bankx.id', role:'Analyst', last:'2 hours ago'},
    {name:'Rendra Pratama', email:'rendra.p@bankx.id', role:'Viewer', last:'Yesterday'},
    {name:'Dewi Kusuma', email:'dewi.k@bankx.id', role:'Analyst', last:'3 days ago'},
  ];
  return (
    <div style={{padding:'24px 32px'}}>
      <div style={{display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:14, marginBottom:18}}>
        <Card><div style={{fontSize:12, color:'hsl(var(--fg-muted))', marginBottom:4}}>Members</div><div style={{fontFamily:'var(--font-serif)', fontSize:34, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.025em'}}>5 / 15</div></Card>
        <Card><div style={{fontSize:12, color:'hsl(var(--fg-muted))', marginBottom:4}}>Active today</div><div style={{fontFamily:'var(--font-serif)', fontSize:34, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.025em'}}>3</div></Card>
        <Card><div style={{fontSize:12, color:'hsl(var(--fg-muted))', marginBottom:4}}>Plan</div><div style={{fontSize:18, fontWeight:700, color:'hsl(var(--fg))', marginTop:4}}>Growth</div><Badge tone="brand" size="sm" style={{marginTop:4}}>Pro-rated billing</Badge></Card>
      </div>
      <Card padding={0}>
        <div style={{padding:'14px 18px', borderBottom:'1px solid hsl(var(--border))', display:'flex', alignItems:'center', gap:10}}>
          <div style={{fontSize:15, fontWeight:600, color:'hsl(var(--fg))', flex:1}}>Team members</div>
          <Button variant="primary" size="sm" icon={<I.plus/>}>Invite</Button>
        </div>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
          <thead>
            <tr style={{background:'hsl(var(--surface-2))', fontSize:11, color:'hsl(var(--fg-muted))', textTransform:'uppercase'}}>
              <th style={{textAlign:'left', padding:'10px 18px', fontWeight:600}}>Name</th>
              <th style={{textAlign:'left', padding:'10px 8px', fontWeight:600}}>Role</th>
              <th style={{textAlign:'left', padding:'10px 8px', fontWeight:600}}>Last active</th>
              <th style={{padding:'10px 18px'}}></th>
            </tr>
          </thead>
          <tbody>
            {members.map((m,i)=>(
              <tr key={i} className="cx-row" style={{borderTop:'1px solid hsl(var(--border))'}}>
                <td style={{padding:'12px 18px'}}>
                  <div style={{display:'flex', alignItems:'center', gap:10}}>
                    <Avatar name={m.name} size={32}/>
                    <div>
                      <div style={{fontWeight:600, color:'hsl(var(--fg))'}}>{m.name}</div>
                      <div style={{fontSize:12, color:'hsl(var(--fg-muted))'}}>{m.email}</div>
                    </div>
                  </div>
                </td>
                <td style={{padding:'12px 8px'}}><Badge tone={m.role==='Admin'?'brand':m.role==='Viewer'?'neutral':'success'} size="sm">{m.role}</Badge></td>
                <td style={{padding:'12px 8px', color:'hsl(var(--fg-muted))'}}>{m.last}</td>
                <td style={{padding:'12px 18px', textAlign:'right'}}><button style={{width:30, height:30, border:'none', background:'transparent', borderRadius:8, cursor:'pointer', color:'hsl(var(--fg-subtle))', display:'inline-flex', alignItems:'center', justifyContent:'center'}}><I.moreH/></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ——— Borrowers ———
function BorrowersList({ borrowers }) {
  const list = borrowers || [];
  if (borrowers === undefined) return (
    <div style={{padding:'24px 32px', display:'flex', alignItems:'center', gap:10, color:'hsl(var(--fg-muted))', fontSize:14}}>
      <Spinner size={18}/> Loading borrowers…
    </div>
  );
  if (list.length === 0) return (
    <div style={{padding:'24px 32px', color:'hsl(var(--fg-muted))', fontSize:14}}>No borrowers yet.</div>
  );
  return (
    <div style={{padding:'24px 32px'}}>
      <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(240px,1fr))', gap:14}}>
        {list.map((b) => (
          <Card key={b.customer_id} style={{cursor:'pointer'}} className="cx-hover-lift">
            <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:14}}>
              <Avatar name={b.customer_id} size={40}/>
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontSize:14, fontWeight:600, color:'hsl(var(--fg))'}}>{b.customer_id}</div>
              </div>
            </div>
            <div style={{display:'flex', gap:8, flexWrap:'wrap'}}>
              <Badge tone="neutral" size="sm">{b.total_sessions ?? 0} sessions</Badge>
              {(b.completed_sessions ?? 0) > 0 && <Badge tone="success" size="sm">{b.completed_sessions} completed</Badge>}
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

// ——— Logout confirmation ———
function LogoutConfirm({onCancel, onConfirm}) {
  return (
    <div style={{position:'absolute', inset:0, background:'hsl(var(--surface-deep) / 0.6)', backdropFilter:'blur(6px)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:50}} className="cx-fadein">
      <Card style={{maxWidth:420, margin:20, boxShadow:'var(--shadow-xl)'}}>
        <div style={{display:'flex', gap:14, alignItems:'flex-start', marginBottom:18}}>
          <div style={{width:46, height:46, borderRadius:14, background:'hsl(var(--danger-bg))', color:'hsl(var(--danger))', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, border:'1px solid hsl(var(--danger) / 0.3)'}}><I.logout/></div>
          <div>
            <div style={{fontFamily:'var(--font-serif)', fontSize:22, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.02em', marginBottom:4}}>Log out of <span style={{fontStyle:'italic'}}>CredNX?</span></div>
            <div style={{fontSize:13, color:'hsl(var(--fg-muted))'}}>You'll need to sign in again to access your sessions. Any in-progress uploads will continue in the background.</div>
          </div>
        </div>
        <div style={{display:'flex', gap:10, justifyContent:'flex-end'}}>
          <Button variant="secondary" onClick={onCancel}>Cancel</Button>
          <Button variant="danger" onClick={onConfirm} icon={<I.logout/>}>Log out</Button>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { Bars, Line, Donut, KPI, BankStatementReport, CreditBureauReport, InvoiceReport, AdminTeam, BorrowersList, LogoutConfirm });
