// CredNX Underwrite — app shell, sidebar, upload flow, sessions, processing.
// Re-themed to Editorial Forest tokens. ALL fetch() calls, sessionStorage
// usage and API endpoint paths are preserved verbatim.

// document_type → icon key in I{...}
const DOC_TYPE_ICON = {
  bank_statement: 'bank', credit_bureau: 'creditCard', invoice: 'receipt',
  id_document: 'fileText', tax_return: 'fileText', medical_report: 'fileText',
  medical_prescription: 'fileText', disbursement_report: 'fileText',
};

// Fallback used when the /api/v1/documents endpoint is unreachable
const FALLBACK_DOC_MASTER = [
  {id:'DOC_001', name:'Bank Statement', icon:'bank', desc:'PDF statements, any bank'},
  {id:'DOC_008', name:'Credit Bureau', icon:'creditCard', desc:'CIBIL / Experian reports'},
  {id:'DOC_002', name:'Invoice', icon:'receipt', desc:'Supplier & buyer invoices'},
];

function useDocMaster() {
  const [docs, setDocs] = React.useState(FALLBACK_DOC_MASTER);
  const [loading, setLoading] = React.useState(true);
  React.useEffect(() => {
    const authKey = sessionStorage.getItem('crednx_auth_key');
    const headers = authKey ? { 'X-Auth-Key': authKey } : {};
    fetch('/api/v1/documents', { headers })
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then(data => {
        const list = data?.result?.json?.documents;
        if (Array.isArray(list) && list.length > 0) {
          setDocs(list.map(d => ({
            id: d.document_id,
            name: d.document_name,
            icon: DOC_TYPE_ICON[d.document_type] || 'fileText',
            desc: d.description,
          })));
        }
      })
      .catch(() => {/* keep fallback */})
      .finally(() => setLoading(false));
  }, []);
  return { docs, loading };
}

const MOCK_BORROWERS = [
  {id:'BRW-2847', name:'PT Sinar Mas Agro', sessions:4},
  {id:'BRW-2931', name:'Budi Santoso', sessions:2},
  {id:'BRW-3012', name:'CV Karya Jaya', sessions:1},
  {id:'BRW-3104', name:'Rahmat Hidayat', sessions:7},
];

// ——— Sidebar wordmark — uses the brand SVG. The wrapper is data-theme="dark" ———
// because the sidebar uses a dark deep-forest panel regardless of theme.
const SidebarWordmark = () => <BrandLogo height={22} variant="full"/>;

function Sidebar({page, setPage, user, org, sessionCount}) {
  const [collapsed, setCollapsed] = React.useState(() => {
    try { return localStorage.getItem('crednx_sidebar_collapsed') === '1'; } catch { return false; }
  });
  const toggleCollapsed = () => setCollapsed(c => {
    const next = !c;
    try { localStorage.setItem('crednx_sidebar_collapsed', next ? '1' : '0'); } catch {}
    return next;
  });

  const W = collapsed ? 72 : 240;
  const sessionBadge = sessionCount == null ? null : String(sessionCount);
  const items = [
    {id:'home', label:'Home', icon:<I.home/>, badge:null},
    {id:'underwrite', label:'Underwrite', icon:<I.upload/>, badge:null},
    {id:'sessions', label:'Sessions', icon:<I.layers/>, badge:sessionBadge},
    {id:'borrowers', label:'Borrowers', icon:<I.users/>, badge:null},
    {id:'insights', label:'Insights', icon:<I.chart/>, badge:null},
    {divider:true},
    {id:'settings', label:'Settings', icon:<I.settings/>, badge:null},
    ...(user.role==='Admin' ? [{id:'team', label:'Team', icon:<I.users/>, badge:null}] : []),
  ];
  return (
    <div style={{
      width: W,
      background:'hsl(var(--surface))', borderRight:'1px solid hsl(var(--border))',
      display:'flex', flexDirection:'column', flexShrink:0, color:'hsl(var(--fg))',
      transition:'width 280ms cubic-bezier(0.22, 1, 0.36, 1)', overflow:'hidden',
    }}>
      <div style={{height:72, padding: collapsed ? 0 : '0 20px', borderBottom:'1px solid hsl(var(--border))', display:'flex', alignItems:'center', justifyContent: collapsed ? 'center' : 'flex-start', flexShrink:0}}>
        {collapsed ? <BrandLogo height={28} variant="mark"/> : <BrandLogo height={22} variant="full"/>}
      </div>
      <div style={{padding:'12px 12px 8px'}}>
        {collapsed ? (
          <div title={`${org.name} · ${org.plan}`} style={{
            width:48, height:48, margin:'0 auto', borderRadius:12,
            background:'hsl(var(--accent-soft))', display:'flex', alignItems:'center', justifyContent:'center',
            color:'hsl(var(--primary))', border:'1px solid hsl(var(--accent) / 0.25)'
          }}>
            <I.building/>
          </div>
        ) : (
          <div style={{display:'flex', alignItems:'center', gap:10, padding:'10px 10px', background:'hsl(var(--accent-soft))', borderRadius:12, border:'1px solid hsl(var(--accent) / 0.25)'}}>
            <div style={{width:30, height:30, borderRadius:8, background:'hsl(var(--primary))', display:'flex', alignItems:'center', justifyContent:'center', color:'hsl(var(--primary-fg))', flexShrink:0}}><I.building/></div>
            <div style={{flex:1, minWidth:0}}>
              <div style={{fontSize:13, fontWeight:600, color:'hsl(var(--fg))', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{org.name}</div>
              <div style={{fontSize:11, color:'hsl(var(--fg-muted))'}}>{org.plan}</div>
            </div>
            <I.chevronDown style={{color:'hsl(var(--fg-subtle))', flexShrink:0}}/>
          </div>
        )}
      </div>
      <nav style={{padding:'4px 8px', flex:1}}>
        {!collapsed
          ? <div style={{fontSize:11, letterSpacing:'0.06em', textTransform:'uppercase', color:'hsl(var(--fg-subtle))', padding:'12px 10px 6px', fontWeight:600}}>Workspace</div>
          : <div style={{height:18}}/>}
        {items.map((item, idx)=>{
          if (item.divider) {
            return <div key={`div-${idx}`} style={{ height:1, background:'hsl(var(--border))', margin: collapsed ? '10px 14px' : '10px 12px' }}/>;
          }
          const active = page===item.id;
          return (
            <button key={item.id} onClick={()=>setPage(item.id)}
              title={collapsed ? item.label : undefined}
              style={{
                width:'100%', display:'flex', alignItems:'center',
                justifyContent: collapsed ? 'center' : 'flex-start',
                gap:10, padding: collapsed ? '12px 0' : '10px 12px',
                borderRadius:12, border:'none', cursor:'pointer', fontFamily:'inherit', fontSize:14, fontWeight:500,
                color: active ? 'hsl(var(--primary))' : 'hsl(var(--fg))',
                background: active ? 'hsl(var(--accent-soft))' : 'transparent',
                marginBottom:2, transition:'background 120ms, color 120ms',
                position:'relative',
              }}
              onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'hsl(var(--surface-2))'; }}
              onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
              {active && (
                <span style={{
                  position:'absolute',
                  left: collapsed ? 0 : -8,
                  top: collapsed ? 8 : 6, bottom: collapsed ? 8 : 6,
                  width:3, borderRadius:2, background:'hsl(var(--accent))',
                }}/>
              )}
              <span style={{color: active ? 'hsl(var(--primary))' : 'hsl(var(--fg-muted))', display:'flex', position:'relative', flexShrink:0}}>
                {item.icon}
                {collapsed && item.badge && (
                  <span style={{position:'absolute', top:-5, right:-7, minWidth:14, height:14, padding:'0 3px', borderRadius:7, background:'hsl(var(--accent))', color:'hsl(var(--accent-fg))', fontSize:9, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', lineHeight:1}}>{item.badge}</span>
                )}
              </span>
              {!collapsed && <span style={{flex:1, textAlign:'left', overflow:'hidden', whiteSpace:'nowrap', textOverflow:'ellipsis'}}>{item.label}</span>}
              {!collapsed && item.badge && <Badge tone={active?'brand':'neutral'} size="sm">{item.badge}</Badge>}
            </button>
          );
        })}
      </nav>
      {!collapsed && (
        <div style={{padding:12}}>
          <Card padding={14} style={{background:'var(--gradient-deep)', border:'none', color:'hsl(var(--surface-deep-fg))', borderRadius:14}}>
            <div style={{fontSize:12, fontWeight:600, marginBottom:4, color:'hsl(var(--surface-deep-fg))'}}>API credits</div>
            <div style={{fontSize:18, fontWeight:700, letterSpacing:'-0.02em', color:'hsl(var(--surface-deep-fg))'}}>1,248 <span style={{fontSize:11, opacity:0.7, fontWeight:500}}>/ 2,000</span></div>
            <div style={{height:5, background:'hsl(var(--surface-deep-fg) / 0.18)', borderRadius:3, marginTop:8, overflow:'hidden'}}>
              <div style={{height:'100%', width:'62%', background:'hsl(var(--accent))', borderRadius:3}}/>
            </div>
          </Card>
        </div>
      )}
      <button
        onClick={toggleCollapsed}
        title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
        aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
        style={{
          height:44, width:'100%',
          display:'flex', alignItems:'center', justifyContent: collapsed ? 'center' : 'flex-start',
          gap:8, padding: collapsed ? 0 : '0 20px',
          border:'none', borderTop:'1px solid hsl(var(--border))',
          background:'transparent', color:'hsl(var(--fg-muted))', cursor:'pointer',
          fontFamily:'inherit', fontSize:12, fontWeight:500, flexShrink:0, transition:'background 150ms, color 150ms',
        }}
        onMouseEnter={e => { e.currentTarget.style.background = 'hsl(var(--surface-2))'; e.currentTarget.style.color = 'hsl(var(--fg))'; }}
        onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'hsl(var(--fg-muted))'; }}>
        <I.chevronRight style={{transform: collapsed ? 'rotate(0deg)' : 'rotate(180deg)', transition:'transform 240ms'}}/>
        {!collapsed && <span>Collapse</span>}
      </button>
    </div>
  );
}

function TopBar({user, onLogout, title, subtitle, actions}) {
  const [menu, setMenu] = React.useState(false);
  return (
    <div style={{height:72, background:'hsl(var(--surface))', borderBottom:'1px solid hsl(var(--border))', display:'flex', alignItems:'center', padding:'0 32px', gap:16, flexShrink:0}}>
      <div style={{flex:1, minWidth:0}}>
        <div style={{fontFamily:'var(--font-serif)', fontSize:24, fontWeight:400, letterSpacing:'-0.025em', color:'hsl(var(--fg))', lineHeight:1.1}}>{title}</div>
        {subtitle && <div style={{fontSize:13, color:'hsl(var(--fg-muted))', marginTop:2}}>{subtitle}</div>}
      </div>
      {actions}
      <ThemeToggle/>
      <div style={{display:'flex', alignItems:'center', height:40, padding:'0 14px 0 6px', borderRadius:999, border:'1px solid hsl(var(--border))', gap:10, cursor:'pointer', background:'hsl(var(--surface))', transition:'background 150ms'}}
        onMouseEnter={e=>e.currentTarget.style.background='hsl(var(--surface-2))'}
        onMouseLeave={e=>e.currentTarget.style.background='hsl(var(--surface))'}
        onClick={()=>setMenu(!menu)}>
        <Avatar name={user.name} size={28}/>
        <div style={{fontSize:13}}>
          <div style={{fontWeight:600, color:'hsl(var(--fg))'}}>{user.name}</div>
        </div>
        <I.chevronDown style={{color:'hsl(var(--fg-subtle))'}}/>
      </div>
      {menu && <UserMenu user={user} onClose={()=>setMenu(false)} onLogout={onLogout}/>}
    </div>
  );
}

function UserMenu({user, onClose, onLogout}) {
  return (
    <>
      <div onClick={onClose} style={{position:'fixed', inset:0, zIndex:30}}/>
      <div className="cx-fadein" style={{position:'absolute', top:64, right:24, width:280, background:'hsl(var(--surface))', border:'1px solid hsl(var(--border))', borderRadius:14, boxShadow:'var(--shadow-lg)', padding:8, zIndex:40, color:'hsl(var(--fg))'}}>
        <div style={{padding:12, borderBottom:'1px solid hsl(var(--border))', marginBottom:6}}>
          <div style={{display:'flex', alignItems:'center', gap:10}}>
            <Avatar name={user.name} size={36}/>
            <div style={{minWidth:0}}>
              <div style={{fontSize:14, fontWeight:600, color:'hsl(var(--fg))'}}>{user.name}</div>
              <div style={{fontSize:12, color:'hsl(var(--fg-muted))', overflow:'hidden', textOverflow:'ellipsis'}}>{user.email}</div>
            </div>
          </div>
          <div style={{marginTop:10}}><Badge tone="brand" size="sm">{user.role}</Badge></div>
        </div>
        {[
          {label:'Account settings', icon:<I.settings/>},
          {label:'API keys', icon:<I.lock/>},
          {label:'Help & docs', icon:<I.help/>},
        ].map(it=>
          <button key={it.label} style={{width:'100%', display:'flex', alignItems:'center', gap:10, padding:'10px 12px', borderRadius:10, border:'none', background:'transparent', cursor:'pointer', fontSize:13, color:'hsl(var(--fg))', fontFamily:'inherit'}}
            onMouseEnter={e=>e.currentTarget.style.background='hsl(var(--surface-2))'}
            onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
            <span style={{color:'hsl(var(--fg-muted))', display:'flex'}}>{it.icon}</span>{it.label}
          </button>
        )}
        <div style={{height:1, background:'hsl(var(--border))', margin:'6px 0'}}/>
        <button onClick={onLogout} style={{width:'100%', display:'flex', alignItems:'center', gap:10, padding:'10px 12px', borderRadius:10, border:'none', background:'transparent', cursor:'pointer', fontSize:13, color:'hsl(var(--danger))', fontFamily:'inherit', fontWeight:500}}
          onMouseEnter={e=>e.currentTarget.style.background='hsl(var(--danger-bg))'}
          onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
          <I.logout/>Log out
        </button>
      </div>
    </>
  );
}

// ——— Underwrite / Upload ———

function DocTypeSelect({value, onChange, docMaster = FALLBACK_DOC_MASTER}) {
  const selected = docMaster.find(d=>d.id===value);
  return (
    <div style={{position:'relative'}}>
      <div style={{display:'flex', alignItems:'center', gap:10, padding:'0 14px', height:52, border:'1.5px solid hsl(var(--primary))', borderRadius:14, background:'hsl(var(--accent-soft))', cursor:'pointer', position:'relative'}}>
        {selected && (
          <div style={{width:36, height:36, borderRadius:10, background:'hsl(var(--primary))', color:'hsl(var(--primary-fg))', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
            {I[selected.icon]()}
          </div>
        )}
        <div style={{flex:1}}>
          <div style={{fontSize:14, fontWeight:600, color:'hsl(var(--fg))'}}>{selected ? selected.name : 'Select document type'}</div>
          {selected && <div style={{fontSize:12, color:'hsl(var(--fg-muted))'}}>{selected.desc}</div>}
        </div>
        <I.chevronDown style={{color:'hsl(var(--fg-muted))', flexShrink:0}}/>
        <select value={value} onChange={e=>onChange(e.target.value)}
          style={{position:'absolute', inset:0, opacity:0, cursor:'pointer', width:'100%', height:'100%'}}>
          {docMaster.map(d=>(
            <option key={d.id} value={d.id}>{d.name} — {d.desc}</option>
          ))}
        </select>
      </div>
    </div>
  );
}

function UnderwriteA({onSubmit, docMaster = FALLBACK_DOC_MASTER, borrowers: propBorrowers}) {
  const [docType, setDocType] = React.useState('DOC_001');
  const [borrowerId, setBorrowerId] = React.useState('');
  const [borrowerNew, setBorrowerNew] = React.useState('');
  const [ddOpen, setDd] = React.useState(false);
  const [files, setFiles] = React.useState([]);
  const [drag, setDrag] = React.useState(false);
  const fileInputRef = React.useRef(null);
  const selectedDoc = docMaster.find(d => d.id === docType);

  const allBorrowers = (propBorrowers && propBorrowers.length > 0)
    ? propBorrowers.map(b => ({ id: b.customer_id, sub: `${b.total_sessions ?? 0} sessions` }))
    : MOCK_BORROWERS.map(b => ({ id: b.id, sub: b.name }));

  function addFiles(rawFiles) {
    const list = Array.from(rawFiles).filter(f => f.name.toLowerCase().endsWith('.pdf'));
    setFiles(prev => {
      const existing = new Set(prev.map(f => f.name));
      return [...prev, ...list.filter(f => !existing.has(f.name))];
    });
  }

  function fmtSize(bytes) {
    if (bytes < 1048576) return (bytes / 1024).toFixed(0) + ' KB';
    return (bytes / 1048576).toFixed(1) + ' MB';
  }

  const activeBorrower = borrowerId || borrowerNew;
  const stepNumStyle = {width:26, height:26, borderRadius:13, background:'hsl(var(--primary))', color:'hsl(var(--primary-fg))', fontSize:12, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center'};

  return (
    <div style={{padding:'28px 32px', maxWidth:1100, margin:'0 auto', width:'100%', boxSizing:'border-box'}}>
      <input ref={fileInputRef} type="file" accept=".pdf" multiple style={{display:'none'}}
        onChange={e => { addFiles(e.target.files); e.target.value = ''; }}/>
      <div style={{display:'grid', gridTemplateColumns:'1fr 340px', gap:24, alignItems:'start'}}>
        <div style={{display:'flex', flexDirection:'column', gap:20}}>
          <Card>
            <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:4}}>
              <div style={stepNumStyle}>1</div>
              <div style={{fontSize:16, fontWeight:600, color:'hsl(var(--fg))'}}>Document type</div>
            </div>
            <div style={{fontSize:13, color:'hsl(var(--fg-muted))', marginLeft:36, marginBottom:14}}>Select the type of document to analyse. Each session processes one document type.</div>
            <DocTypeSelect value={docType} onChange={setDocType} docMaster={docMaster}/>
          </Card>

          <Card>
            <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:4}}>
              <div style={stepNumStyle}>2</div>
              <div style={{fontSize:16, fontWeight:600, color:'hsl(var(--fg))'}}>Borrower Reference ID</div>
            </div>
            <div style={{fontSize:13, color:'hsl(var(--fg-muted))', marginLeft:36, marginBottom:14}}>Files with the same reference ID are grouped into one borrower's session history.</div>
            <div style={{position:'relative'}}>
              <button onClick={() => setDd(!ddOpen)}
                style={{width:'100%', display:'flex', alignItems:'center', gap:10, padding:'0 14px', height:48, border:'1px solid hsl(var(--border))', borderRadius:12, background:'hsl(var(--surface))', cursor:'pointer', fontFamily:'inherit', textAlign:'left'}}>
                <I.users style={{color:'hsl(var(--fg-subtle))'}}/>
                {borrowerId ? (
                  <span style={{fontSize:14, fontWeight:500, color:'hsl(var(--fg))'}}>{borrowerId}</span>
                ) : borrowerNew ? (
                  <><Badge tone="success" size="sm">New</Badge><span style={{fontSize:14, color:'hsl(var(--fg))', marginLeft:6}}>{borrowerNew}</span></>
                ) : (
                  <span style={{fontSize:14, color:'hsl(var(--fg-subtle))', flex:1}}>Select or create a borrower reference</span>
                )}
                <I.chevronDown style={{color:'hsl(var(--fg-subtle))', marginLeft:'auto'}}/>
              </button>
              {ddOpen && (
                <div className="cx-fadein" style={{position:'absolute', top:'calc(100% + 4px)', left:0, right:0, background:'hsl(var(--surface))', border:'1px solid hsl(var(--border))', borderRadius:12, boxShadow:'var(--shadow-lg)', zIndex:20, overflow:'hidden'}}>
                  <div style={{maxHeight:240, overflow:'auto'}}>
                    {allBorrowers.map(b => (
                      <button key={b.id} onClick={() => { setBorrowerId(b.id); setBorrowerNew(''); setDd(false); }}
                        style={{width:'100%', display:'flex', alignItems:'center', gap:10, padding:'10px 12px', border:'none', background:'transparent', cursor:'pointer', fontFamily:'inherit', textAlign:'left'}}
                        onMouseEnter={e => e.currentTarget.style.background = 'hsl(var(--surface-2))'}
                        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                        <Avatar name={b.id} size={28}/>
                        <div style={{flex:1, minWidth:0}}>
                          <div style={{fontSize:13, fontWeight:600, color:'hsl(var(--fg))'}}>{b.id}</div>
                          <div style={{fontSize:12, color:'hsl(var(--fg-muted))'}}>{b.sub}</div>
                        </div>
                      </button>
                    ))}
                  </div>
                  <div style={{borderTop:'1px solid hsl(var(--border))', padding:10, background:'hsl(var(--surface-2))'}}>
                    <div style={{fontSize:11, color:'hsl(var(--fg-muted))', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:6, fontWeight:600}}>New borrower ID</div>
                    <div style={{display:'flex', gap:8}}>
                      <input placeholder="e.g. ACME-001" value={borrowerNew} onChange={e => setBorrowerNew(e.target.value)}
                        style={{flex:1, height:34, padding:'0 10px', border:'1px solid hsl(var(--border))', borderRadius:10, fontSize:13, fontFamily:'inherit', outline:'none', color:'hsl(var(--fg))', background:'hsl(var(--surface))'}}/>
                      <Button size="sm" onClick={() => { if (borrowerNew) { setBorrowerId(''); setDd(false); } }} icon={<I.plus/>}>Use</Button>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </Card>

          <Card>
            <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:4}}>
              <div style={stepNumStyle}>3</div>
              <div style={{fontSize:16, fontWeight:600, color:'hsl(var(--fg))'}}>Upload documents</div>
            </div>
            <div style={{fontSize:13, color:'hsl(var(--fg-muted))', marginLeft:36, marginBottom:14}}>Accepts PDF files, up to 50 MB each.</div>
            <div
              onClick={() => fileInputRef.current?.click()}
              onDragOver={e => { e.preventDefault(); setDrag(true); }}
              onDragLeave={() => setDrag(false)}
              onDrop={e => { e.preventDefault(); setDrag(false); addFiles(e.dataTransfer.files); }}
              style={{border:`2px dashed ${drag ? 'hsl(var(--primary))' : 'hsl(var(--border-strong))'}`, borderRadius:16, padding:'36px 20px', textAlign:'center', background: drag ? 'hsl(var(--accent-soft))' : 'hsl(var(--bg-soft))', transition:'all 200ms', cursor:'pointer'}}>
              <div style={{width:56, height:56, borderRadius:16, background:'hsl(var(--surface))', border:'1px solid hsl(var(--border))', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 14px', color:'hsl(var(--primary))'}}><I.upload/></div>
              <div style={{fontFamily:'var(--font-serif)', fontSize:20, fontWeight:400, color:'hsl(var(--fg))', marginBottom:4, letterSpacing:'-0.02em'}}>Drop files <span style={{fontStyle:'italic'}}>here</span></div>
              <div style={{fontSize:13, color:'hsl(var(--fg-muted))', marginBottom:14}}>or <a href="#" className="cx-link" onClick={e => { e.stopPropagation(); e.preventDefault(); fileInputRef.current?.click(); }}>browse from your computer</a></div>
              <div style={{fontSize:11, color:'hsl(var(--fg-subtle))'}}>PDF only · 50 MB max · All files encrypted in transit</div>
            </div>
            {files.length > 0 && (
              <div style={{marginTop:14, display:'flex', flexDirection:'column', gap:8}}>
                {files.map((f, i) => (
                  <div key={i} style={{display:'flex', alignItems:'center', gap:10, padding:'10px 12px', border:'1px solid hsl(var(--border))', borderRadius:12, background:'hsl(var(--surface))'}}>
                    <div style={{width:36, height:36, borderRadius:10, background:'hsl(var(--danger-bg))', color:'hsl(var(--danger))', display:'flex', alignItems:'center', justifyContent:'center'}}><I.fileText/></div>
                    <div style={{flex:1, minWidth:0}}>
                      <div style={{fontSize:13, fontWeight:600, color:'hsl(var(--fg))', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{f.name}</div>
                      <div style={{fontSize:12, color:'hsl(var(--fg-muted))', display:'flex', gap:8, alignItems:'center'}}>
                        <span>{fmtSize(f.size)}</span>
                        <span>•</span>
                        <Badge tone="brand" size="sm">{selectedDoc?.name}</Badge>
                      </div>
                    </div>
                    <button onClick={() => setFiles(files.filter((_, j) => j !== i))}
                      style={{width:32, height:32, borderRadius:10, border:'none', background:'transparent', cursor:'pointer', color:'hsl(var(--fg-subtle))', display:'flex', alignItems:'center', justifyContent:'center'}}
                      onMouseEnter={e => { e.currentTarget.style.background = 'hsl(var(--danger-bg))'; e.currentTarget.style.color = 'hsl(var(--danger))'; }}
                      onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'hsl(var(--fg-subtle))'; }}><I.trash/></button>
                  </div>
                ))}
              </div>
            )}
          </Card>
        </div>

        <div style={{position:'sticky', top:20}}>
          <Card>
            <div style={{fontSize:14, fontWeight:600, color:'hsl(var(--fg))', marginBottom:14, letterSpacing:'-0.01em'}}>Session summary</div>
            <div style={{display:'flex', flexDirection:'column', gap:12, fontSize:13}}>
              <div style={{display:'flex', justifyContent:'space-between'}}>
                <span style={{color:'hsl(var(--fg-muted))'}}>Document type</span>
                <span style={{color:'hsl(var(--fg))', fontWeight:500}}>{selectedDoc?.name || '—'}</span>
              </div>
              <div style={{display:'flex', justifyContent:'space-between'}}>
                <span style={{color:'hsl(var(--fg-muted))'}}>Files</span>
                <span style={{color:'hsl(var(--fg))', fontWeight:500}}>{files.length}</span>
              </div>
              <div style={{display:'flex', justifyContent:'space-between'}}>
                <span style={{color:'hsl(var(--fg-muted))'}}>Borrower</span>
                <span style={{color:'hsl(var(--fg))', fontWeight:500}}>{activeBorrower || '—'}</span>
              </div>
              <div style={{height:1, background:'hsl(var(--border))', margin:'4px 0'}}/>
              <div style={{display:'flex', justifyContent:'space-between'}}>
                <span style={{color:'hsl(var(--fg-muted))'}}>Estimated credits</span>
                <span style={{color:'hsl(var(--fg))', fontWeight:600}}>{files.length * 2}</span>
              </div>
              <div style={{display:'flex', justifyContent:'space-between'}}>
                <span style={{color:'hsl(var(--fg-muted))'}}>Estimated time</span>
                <span style={{color:'hsl(var(--fg))', fontWeight:500}}>~{Math.max(1, files.length)} min</span>
              </div>
            </div>
            <Button variant="primary" full size="lg" style={{marginTop:18}}
              onClick={() => onSubmit({ docType, borrowerId: activeBorrower, files })}
              disabled={files.length === 0 || !activeBorrower} iconRight={<I.arrowRight/>}>Start analysis</Button>
            <div style={{fontSize:11, color:'hsl(var(--fg-subtle))', textAlign:'center', marginTop:10}}>Files are processed asynchronously. You'll be notified on completion.</div>
          </Card>
        </div>
      </div>
    </div>
  );
}

function UnderwriteB({onSubmit, docMaster = FALLBACK_DOC_MASTER}) {
  const [step, setStep] = React.useState(1);
  const [docType, setDocType] = React.useState('DOC_001');
  const [selectedBorrower, setSelectedBorrower] = React.useState(0);

  return (
    <div style={{padding:'28px 32px', maxWidth:780, margin:'0 auto', width:'100%', boxSizing:'border-box'}}>
      <div style={{display:'flex', alignItems:'center', gap:0, marginBottom:24, background:'hsl(var(--surface))', border:'1px solid hsl(var(--border))', borderRadius:16, padding:4}}>
        {[{n:1,l:'Document type'},{n:2,l:'Borrower'},{n:3,l:'Upload'}].map((s)=>(
          <div key={s.n} style={{flex:1, display:'flex', alignItems:'center', gap:8, padding:'10px 14px', borderRadius:12, background:step===s.n?'hsl(var(--accent-soft))':'transparent', cursor:'pointer', transition:'background 150ms'}} onClick={()=>setStep(s.n)}>
            <div style={{width:22, height:22, borderRadius:11, background:step>=s.n?'hsl(var(--primary))':'hsl(var(--border))', color:step>=s.n?'hsl(var(--primary-fg))':'hsl(var(--fg-subtle))', fontSize:11, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center'}}>
              {step>s.n ? <I.check/> : s.n}
            </div>
            <div style={{fontSize:13, fontWeight:step===s.n?600:500, color:step===s.n?'hsl(var(--primary))':step>s.n?'hsl(var(--fg))':'hsl(var(--fg-subtle))'}}>{s.l}</div>
          </div>
        ))}
      </div>
      <Card padding={28}>
        {step===1 && <div className="cx-fadein" key="w1">
          <div style={{fontFamily:'var(--font-serif)', fontSize:24, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.02em', marginBottom:6}}>What type of document?</div>
          <div style={{fontSize:13, color:'hsl(var(--fg-muted))', marginBottom:18}}>Select one document type. Each session processes one type.</div>
          <div style={{display:'flex', flexDirection:'column', gap:10}}>
            {docMaster.map((d)=>{
              const on = docType===d.id;
              return (
                <button key={d.id} onClick={()=>setDocType(d.id)}
                  style={{display:'flex', alignItems:'center', gap:14, padding:16, border:on?'1.5px solid hsl(var(--primary))':'1px solid hsl(var(--border))', background:on?'hsl(var(--accent-soft))':'hsl(var(--surface))', borderRadius:14, cursor:'pointer', fontFamily:'inherit', textAlign:'left', transition:'border-color 120ms, background 120ms'}}>
                  <div style={{width:42, height:42, borderRadius:12, background:on?'hsl(var(--primary))':'hsl(var(--accent-soft))', color:on?'hsl(var(--primary-fg))':'hsl(var(--primary))', display:'flex', alignItems:'center', justifyContent:'center'}}>{I[d.icon]()}</div>
                  <div style={{flex:1}}>
                    <div style={{fontSize:14, fontWeight:600, color:'hsl(var(--fg))'}}>{d.name}</div>
                    <div style={{fontSize:12, color:'hsl(var(--fg-muted))'}}>{d.desc}</div>
                  </div>
                  <div style={{width:22, height:22, borderRadius:11, border:on?'none':'1.5px solid hsl(var(--border-strong))', background:on?'hsl(var(--primary))':'transparent', color:'hsl(var(--primary-fg))', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>{on && <I.check/>}</div>
                </button>
              );
            })}
          </div>
          <div style={{display:'flex', justifyContent:'flex-end', marginTop:22}}>
            <Button variant="primary" onClick={()=>setStep(2)} iconRight={<I.arrowRight/>}>Next</Button>
          </div>
        </div>}
        {step===2 && <div className="cx-fadein" key="w2">
          <div style={{fontFamily:'var(--font-serif)', fontSize:24, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.02em', marginBottom:6}}>Who is this for?</div>
          <div style={{fontSize:13, color:'hsl(var(--fg-muted))', marginBottom:18}}>Link this session to a borrower.</div>
          <div style={{display:'flex', flexDirection:'column', gap:8, marginBottom:16}}>
            {MOCK_BORROWERS.slice(0,3).map((b,i)=>(
              <div key={b.id} className="cx-row" onClick={()=>setSelectedBorrower(i)}
                style={{display:'flex', alignItems:'center', gap:12, padding:'12px 14px', border:selectedBorrower===i?'1.5px solid hsl(var(--primary))':'1px solid hsl(var(--border))', borderRadius:14, background:selectedBorrower===i?'hsl(var(--accent-soft))':'hsl(var(--surface))', cursor:'pointer', transition:'border-color 120ms, background 120ms'}}>
                <Avatar name={b.name} size={32}/>
                <div style={{flex:1}}>
                  <div style={{fontSize:13, fontWeight:600, color:'hsl(var(--fg))'}}>{b.id}</div>
                  <div style={{fontSize:12, color:'hsl(var(--fg-muted))'}}>{b.name} · {b.sessions} sessions</div>
                </div>
                {selectedBorrower===i && <I.checkCircle style={{color:'hsl(var(--primary))'}}/>}
              </div>
            ))}
          </div>
          <button style={{width:'100%', padding:14, border:'1.5px dashed hsl(var(--border-strong))', borderRadius:14, background:'transparent', color:'hsl(var(--primary))', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit', display:'flex', alignItems:'center', justifyContent:'center', gap:6}}><I.plus/>Create new borrower</button>
          <div style={{display:'flex', justifyContent:'space-between', marginTop:22}}>
            <Button variant="secondary" onClick={()=>setStep(1)} icon={<I.arrowLeft/>}>Back</Button>
            <Button variant="primary" onClick={()=>setStep(3)} iconRight={<I.arrowRight/>}>Next</Button>
          </div>
        </div>}
        {step===3 && <div className="cx-fadein" key="w3">
          <div style={{fontFamily:'var(--font-serif)', fontSize:24, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.02em', marginBottom:6}}>Upload your files</div>
          <div style={{fontSize:13, color:'hsl(var(--fg-muted))', marginBottom:18}}>PDF only, up to 50 MB each.</div>
          <div style={{border:'2px dashed hsl(var(--border-strong))', borderRadius:16, padding:'48px 20px', textAlign:'center', background:'hsl(var(--bg-soft))'}}>
            <div style={{width:60, height:60, borderRadius:16, background:'hsl(var(--surface))', border:'1px solid hsl(var(--border))', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 14px', color:'hsl(var(--primary))'}}><I.upload/></div>
            <div style={{fontFamily:'var(--font-serif)', fontSize:20, fontWeight:400, color:'hsl(var(--fg))', marginBottom:4}}>Drag and drop here</div>
            <div style={{fontSize:13, color:'hsl(var(--fg-muted))'}}>or <a className="cx-link" href="#">browse</a></div>
          </div>
          <div style={{marginTop:14, padding:'12px 14px', background:'hsl(var(--accent-soft))', border:'1px solid hsl(var(--accent) / 0.3)', borderRadius:12, display:'flex', alignItems:'center', gap:10, fontSize:13, color:'hsl(var(--primary))'}}>
            <I.fileText/>2 files ready · bca_statement_jan.pdf, bni_statement_feb.pdf
          </div>
          <div style={{display:'flex', justifyContent:'space-between', marginTop:22}}>
            <Button variant="secondary" onClick={()=>setStep(2)} icon={<I.arrowLeft/>}>Back</Button>
            <Button variant="primary" onClick={onSubmit} iconRight={<I.arrowRight/>}>Start analysis</Button>
          </div>
        </div>}
      </Card>
    </div>
  );
}

// ——— Sessions list (kept for design canvas; production uses BorrowersPage) ———

const SESSIONS = [
  {id:'sess_8a436c61', borrower:'BRW-2847', borrowerName:'PT Sinar Mas Agro', docs:3, type:'Bank Statement', created:'2 min ago', status:'processing', progress:64},
  {id:'sess_6b8382c3', borrower:'BRW-2931', borrowerName:'Budi Santoso', docs:2, type:'Credit Bureau', created:'18 min ago', status:'completed', progress:100},
  {id:'sess_be067ef3', borrower:'BRW-2847', borrowerName:'PT Sinar Mas Agro', docs:1, type:'Invoice', created:'1 hour ago', status:'completed', progress:100},
  {id:'sess_d76c0cea', borrower:'BRW-3012', borrowerName:'CV Karya Jaya', docs:4, type:'Bank Statement', created:'3 hours ago', status:'completed', progress:100},
  {id:'sess_d7e3a616', borrower:'BRW-3104', borrowerName:'Rahmat Hidayat', docs:2, type:'Bank Statement', created:'Yesterday', status:'failed', progress:0},
  {id:'sess_2728e0cd', borrower:'BRW-2931', borrowerName:'Budi Santoso', docs:1, type:'Credit Bureau', created:'2 days ago', status:'completed', progress:100},
];

function SessionsList({populated, onOpen, sessions: propSessions}) {
  const sessions = propSessions || SESSIONS;
  const [search, setSearch] = React.useState('');
  const [expanded, setExpanded] = React.useState(sessions.length > 0 ? [sessions[0].borrower] : []);
  const toggle = (id) => setExpanded(prev => prev.includes(id) ? prev.filter(x=>x!==id) : [...prev, id]);

  if (propSessions === undefined) {
    return (
      <div style={{padding:40, display:'flex', alignItems:'center', justifyContent:'center', minHeight:360, gap:12, color:'hsl(var(--fg-muted))', fontSize:14}}>
        <Spinner size={18}/> Loading sessions…
      </div>
    );
  }
  if (!populated) {
    return (
      <div style={{padding:40, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', minHeight:480}}>
        <div style={{width:80, height:80, borderRadius:24, background:'hsl(var(--accent-soft))', display:'flex', alignItems:'center', justifyContent:'center', color:'hsl(var(--primary))', marginBottom:18, border:'1px solid hsl(var(--accent) / 0.25)'}}><I.layers/></div>
        <div style={{fontFamily:'var(--font-serif)', fontSize:28, fontWeight:400, color:'hsl(var(--fg))', marginBottom:6, letterSpacing:'-0.02em'}}>No sessions <span style={{fontStyle:'italic'}}>yet</span></div>
        <div style={{fontSize:14, color:'hsl(var(--fg-muted))', marginBottom:20, textAlign:'center', maxWidth:380}}>Create your first underwriting session to analyse borrower documents.</div>
        <Button variant="primary" icon={<I.upload/>}>New Session</Button>
      </div>
    );
  }

  const byBorrower = {};
  sessions.forEach(s => {
    if (!byBorrower[s.borrower]) byBorrower[s.borrower] = {borrower:s.borrower, name:s.borrowerName||s.borrower, sessions:[]};
    byBorrower[s.borrower].sessions.push(s);
  });
  const groups = Object.values(byBorrower);
  const visible = search
    ? groups.filter(g => g.borrower.toLowerCase().includes(search.toLowerCase()) || g.name.toLowerCase().includes(search.toLowerCase()))
    : groups;

  return (
    <div style={{padding:'24px 32px'}}>
      <Card padding={0}>
        <div style={{display:'flex', alignItems:'center', gap:12, padding:'14px 18px', borderBottom:'1px solid hsl(var(--border))'}}>
          <div style={{display:'flex', alignItems:'center', gap:8, height:36, padding:'0 12px', borderRadius:10, border:'1px solid hsl(var(--border))', flex:1, maxWidth:320, background:'hsl(var(--surface))'}}>
            <I.search style={{color:'hsl(var(--fg-subtle))'}}/>
            <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search by borrower ID or name" style={{flex:1, border:'none', outline:'none', fontSize:13, fontFamily:'inherit', color:'hsl(var(--fg))', background:'transparent'}}/>
          </div>
          <div style={{flex:1}}/>
          <Badge tone="neutral">{groups.length} borrower{groups.length!==1?'s':''} · {sessions.length} session{sessions.length!==1?'s':''}</Badge>
        </div>
        <div>
          {visible.map((g,gi)=>{
            const open = expanded.includes(g.borrower);
            const completed = g.sessions.filter(s=>s.status==='completed').length;
            const processing = g.sessions.filter(s=>s.status==='processing').length;
            return (
              <div key={g.borrower} style={{borderTop:gi===0?'none':'1px solid hsl(var(--border))'}}>
                <button onClick={()=>toggle(g.borrower)} className="cx-row" style={{width:'100%', display:'flex', alignItems:'center', gap:14, padding:'14px 18px', border:'none', background:'transparent', cursor:'pointer', fontFamily:'inherit', textAlign:'left'}}>
                  <I.chevronRight style={{color:'hsl(var(--fg-muted))', transform:open?'rotate(90deg)':'rotate(0)', transition:'transform 180ms'}}/>
                  <Avatar name={g.name} size={36}/>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{display:'flex', alignItems:'center', gap:10}}>
                      <div style={{fontSize:14, fontWeight:600, color:'hsl(var(--fg))'}}>{g.borrower}</div>
                      {g.name !== g.borrower && <div style={{fontSize:13, color:'hsl(var(--fg-muted))'}}>{g.name}</div>}
                    </div>
                    <div style={{fontSize:12, color:'hsl(var(--fg-muted))', marginTop:2}}>{g.sessions.length} session{g.sessions.length>1?'s':''}</div>
                  </div>
                  {processing>0 && <Badge tone="brand" size="sm"><Spinner size={10}/>{processing} processing</Badge>}
                  <Badge tone="success" size="sm"><I.check/>{completed} completed</Badge>
                </button>
                {open && (
                  <div className="cx-fadein" style={{background:'hsl(var(--surface-2))', borderTop:'1px solid hsl(var(--border))'}}>
                    <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
                      <thead>
                        <tr style={{fontSize:10, color:'hsl(var(--fg-subtle))', textTransform:'uppercase', letterSpacing:'0.06em'}}>
                          <th style={{textAlign:'left', padding:'10px 18px 8px 64px', fontWeight:600}}>Session ID</th>
                          <th style={{textAlign:'left', padding:'10px 8px 8px', fontWeight:600}}>Type</th>
                          <th style={{textAlign:'left', padding:'10px 8px 8px', fontWeight:600}}>Docs</th>
                          <th style={{textAlign:'left', padding:'10px 8px 8px', fontWeight:600}}>Created</th>
                          <th style={{textAlign:'left', padding:'10px 8px 8px', fontWeight:600}}>Status</th>
                          <th style={{padding:'10px 18px 8px'}}></th>
                        </tr>
                      </thead>
                      <tbody>
                        {g.sessions.map(s=>(
                          <tr key={s.id} className="cx-row" style={{borderTop:'1px solid hsl(var(--border))', cursor:'pointer'}} onClick={()=>onOpen(s)}>
                            <td style={{padding:'10px 18px 10px 64px', fontFamily:'var(--font-mono)', fontSize:12, color:'hsl(var(--fg))', fontWeight:500}}>{s.id}</td>
                            <td style={{padding:'10px 8px', color:'hsl(var(--fg))'}}>{s.type}</td>
                            <td style={{padding:'10px 8px', color:'hsl(var(--fg))'}}>{s.docs}</td>
                            <td style={{padding:'10px 8px', color:'hsl(var(--fg-muted))'}}>{s.created}</td>
                            <td style={{padding:'10px 8px'}}>
                              {s.status==='processing' && <Badge tone="brand" size="sm"><Spinner size={10}/>Processing</Badge>}
                              {s.status==='completed' && <Badge tone="success" size="sm"><I.check/>Completed</Badge>}
                              {s.status==='failed' && <Badge tone="danger" size="sm"><I.alert/>Failed</Badge>}
                            </td>
                            <td style={{padding:'10px 18px', textAlign:'right'}}><I.chevronRight style={{color:'hsl(var(--fg-subtle))'}}/></td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </Card>
    </div>
  );
}

function ProcessingScreen({onDone}) {
  const [progress, setProgress] = React.useState(0);
  const [stage, setStage] = React.useState(0);
  const stages = ['Uploading files','Extracting data','Standardising schema','Categorising transactions','Generating CAM analysis'];
  React.useEffect(()=>{
    const t = setInterval(()=>{
      setProgress(p=>{
        const n = Math.min(100, p + 8);
        setStage(Math.floor(n/20));
        if (n>=100) clearInterval(t);
        return n;
      });
    }, 400);
    return ()=>clearInterval(t);
  },[]);
  return (
    <div style={{padding:'40px 32px', maxWidth:720, margin:'0 auto'}}>
      <Card padding={32}>
        <div style={{display:'flex', alignItems:'center', gap:14, marginBottom:22}}>
          <div style={{width:56, height:56, borderRadius:16, background:progress>=100?'hsl(var(--success-bg))':'hsl(var(--accent-soft))', display:'flex', alignItems:'center', justifyContent:'center', color:progress>=100?'hsl(var(--success-fg))':'hsl(var(--primary))', position:'relative', transition:'background 300ms, color 300ms', border:`1px solid ${progress>=100?'hsl(var(--success) / 0.3)':'hsl(var(--accent) / 0.3)'}`}}>
            {progress>=100 ? <I.checkCircle/> : <Spinner size={22}/>}
          </div>
          <div style={{flex:1}}>
            <div style={{fontFamily:'var(--font-serif)', fontSize:22, fontWeight:400, color:'hsl(var(--fg))', letterSpacing:'-0.02em'}}>{progress>=100 ? 'Analysis complete' : 'Analysing documents'}</div>
            <div style={{fontSize:13, color:'hsl(var(--fg-muted))'}}>Session <code>sess_8a436c61</code> · 3 files</div>
          </div>
          {progress>=100 ? <Badge tone="success"><I.check/> Completed</Badge> : <Badge tone="brand">{progress}%</Badge>}
        </div>
        <div style={{height:8, background:'hsl(var(--surface-2))', borderRadius:4, overflow:'hidden', marginBottom:24, position:'relative'}}>
          <div style={{height:'100%', width:`${progress}%`, background:'var(--gradient-lime)', borderRadius:4, transition:'width 400ms'}}/>
        </div>
        <div style={{display:'flex', flexDirection:'column', gap:10}}>
          {stages.map((s,i)=>(
            <div key={s} style={{display:'flex', alignItems:'center', gap:12, padding:'12px 14px', border:'1px solid hsl(var(--border))', borderRadius:12, background:i<stage?'hsl(var(--surface-2))':i===stage?'hsl(var(--accent-soft))':'hsl(var(--surface))', transition:'background 300ms'}}>
              <div style={{width:26, height:26, borderRadius:13, background:i<stage?'hsl(var(--success))':i===stage?'hsl(var(--primary))':'hsl(var(--border))', color:i<stage||i===stage?'hsl(var(--primary-fg))':'hsl(var(--fg-subtle))', display:'flex', alignItems:'center', justifyContent:'center'}}>
                {i<stage ? <I.check/> : i===stage ? <Spinner size={12} color="hsl(var(--primary-fg))"/> : <span style={{fontSize:11, fontWeight:700}}>{i+1}</span>}
              </div>
              <div style={{flex:1, fontSize:14, fontWeight:i===stage?600:500, color:i<=stage?'hsl(var(--fg))':'hsl(var(--fg-subtle))'}}>{s}</div>
              {i<stage && <span style={{fontSize:11, color:'hsl(var(--success-fg))', fontWeight:500}}>Done</span>}
              {i===stage && <span style={{fontSize:11, color:'hsl(var(--primary))', fontWeight:500, animation:'cx-pulse 1.6s ease-in-out infinite'}}>In progress</span>}
            </div>
          ))}
        </div>
        {progress>=100 && (
          <div className="cx-fadein" style={{marginTop:22, padding:18, background:'hsl(var(--success-bg))', border:'1px solid hsl(var(--success) / 0.3)', borderRadius:14, display:'flex', alignItems:'center', gap:14}}>
            <div style={{width:42, height:42, borderRadius:21, background:'hsl(var(--success))', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center'}}><I.check/></div>
            <div style={{flex:1}}>
              <div style={{fontSize:14, fontWeight:600, color:'hsl(var(--success-fg))'}}>Analysis complete</div>
              <div style={{fontSize:12, color:'hsl(var(--success-fg))', opacity:0.85}}>Report ready for review or download.</div>
            </div>
            <Button variant="primary" size="sm" onClick={onDone} iconRight={<I.arrowRight/>}>View report</Button>
          </div>
        )}
      </Card>
    </div>
  );
}

Object.assign(window, { Sidebar, TopBar, UserMenu, UnderwriteA, UnderwriteB, SessionsList, ProcessingScreen, FALLBACK_DOC_MASTER, useDocMaster, SESSIONS, MOCK_BORROWERS });
