// Wealth screen — segmented Assets / Liabilities

function AssetsScreen({ theme, accent, onAddAsset }) {
  const [view, setView] = React.useState('assets'); // 'assets' | 'liabilities'

  return (
    <Screen theme={theme}>
      <ScreenHeader
        title="Wealth"
        subtitle={view === 'assets' ? 'Across every account' : 'Debts and obligations'}
        theme={theme} accent={accent}
        action={
          <button
            onClick={() => view === 'liabilities'
              ? window.dispatchEvent(new CustomEvent('himma-add-liability'))
              : window.dispatchEvent(new CustomEvent('himma-add-asset'))}
            style={{
              background:'transparent', border:`0.5px solid ${theme.line2}`, borderRadius: 999,
              padding: '7px 12px', color: theme.text, fontSize: 12, fontFamily: FONTS.ui,
              cursor:'pointer', display:'flex', alignItems:'center', gap: 5, whiteSpace: 'nowrap',
            }}>
            <Ico.plus size={12}/> {view === 'liabilities' ? 'Liability' : 'Asset'}
          </button>
        }
      />

      <div style={{ padding: '0 16px 14px' }}>
        <WealthSegmented value={view} onChange={setView} theme={theme} accent={accent}/>
      </div>

      {view === 'assets' ? (
        <AssetsBody theme={theme} accent={accent}/>
      ) : (
        <LiabilitiesBody theme={theme} accent={accent}/>
      )}

      <div style={{ height: 10 }}/>
    </Screen>
  );
}

function WealthSegmented({ value, onChange, theme, accent }) {
  const opts = [
    { key: 'assets',      label: 'Assets',      total: ASSETS_TOTAL },
    { key: 'liabilities', label: 'Liabilities', total: LIABILITIES_TOTAL },
  ];
  return (
    <div style={{
      display: 'flex',
      background: theme.surface2,
      border: `0.5px solid ${theme.line}`,
      borderRadius: 14, padding: 3,
    }}>
      {opts.map(o => {
        const active = value === o.key;
        return (
          <button key={o.key} onClick={() => onChange(o.key)} style={{
            flex: 1, background: active ? theme.surface : 'transparent',
            border: 'none', borderRadius: 11,
            padding: '8px 12px', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
            boxShadow: active ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
            transition: 'background 140ms',
          }}>
            <span style={{
              fontFamily: FONTS.ui, fontSize: 12.5, fontWeight: 600,
              color: active ? theme.text : theme.textDim,
            }}>{o.label}</span>
            <span style={{
              fontFamily: FONTS.mono, fontSize: 10, fontVariantNumeric: 'tabular-nums',
              color: active ? theme.textDim : theme.textMute,
            }}>{o.key === 'liabilities' ? '−' : ''}<Dh/> {fmtAED(o.total, {compact: true})}</span>
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// ASSETS BODY (existing structure, unchanged except mortgage source)
// ─────────────────────────────────────────────────────────────
function AssetsBody({ theme, accent }) {
  const [open, setOpen] = React.useState({ banking: true, brokerages: true, crypto: false, realestate: false, other: false });
  const total = ASSETS_TOTAL;
  const toggle = (k) => setOpen(o => ({ ...o, [k]: !o[k] }));

  const banksUAE = BANK_ACCOUNTS.filter(b => b.region === 'UAE');
  const banksIntl = BANK_ACCOUNTS.filter(b => b.region === 'International');
  const bankTotal = BANK_ACCOUNTS.reduce((s,b)=>s+b.balance,0);
  const brokTotal = BROKERAGES.reduce((s,b)=>s+b.portfolio,0);
  const cryptoTotal = CRYPTO.reduce((s,c)=>s+c.value,0);
  const reTotal = REAL_ESTATE.reduce((s,r)=>s+r.value,0);
  const otherTotal = OTHER_ASSETS.reduce((s,o)=>s+o.value,0);

  return (
    <>
      {/* Total + allocation bar */}
      <div style={{ padding: '0 16px 16px' }}>
        <Card theme={theme} style={{ padding: 18 }}>
          <div style={{ display: 'flex', justifyContent:'space-between', alignItems:'flex-end' }}>
            <div>
              <SectionLabel theme={theme}>Total assets</SectionLabel>
              <BigNumber value={total} theme={theme} accent={accent} size={30}/>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute, textTransform:'uppercase', letterSpacing: 1 }}>30d</div>
              <Delta pct={((ASSETS_TOTAL - ASSETS_LAST_MONTH)/ASSETS_LAST_MONTH)*100} value={ASSETS_TOTAL - ASSETS_LAST_MONTH} theme={theme}/>
            </div>
          </div>
          <div style={{ marginTop: 14 }}>
            <StackedBar segments={ASSET_BREAKDOWN} height={5} theme={theme}/>
            <div style={{ display:'flex', justifyContent:'space-between', marginTop: 10, fontFamily: FONTS.mono, fontSize: 9.5, color: theme.textMute }}>
              {ASSET_BREAKDOWN.map(s => (
                <div key={s.key} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                  <div style={{ width: 5, height: 5, borderRadius: 1, background: s.color }}/>
                  <span>{(s.value/total*100).toFixed(0)}%</span>
                </div>
              ))}
            </div>
          </div>
        </Card>
      </div>

      <Section
        title="Banking" total={bankTotal} count={BANK_ACCOUNTS.length}
        color="#D4B27A" icon="building" parentTotal={total}
        open={open.banking} onToggle={() => toggle('banking')} theme={theme} accent={accent}>
        <SubHeader label="UAE" theme={theme}/>
        {banksUAE.map(b => <BankRow key={b.id} b={b} theme={theme} accent={accent}/>)}
        <SubHeader label="International" theme={theme}/>
        {banksIntl.map(b => <BankRow key={b.id} b={b} theme={theme} accent={accent}/>)}
      </Section>

      <Section
        title="Brokerages" total={brokTotal} count={BROKERAGES.length}
        color="#E8D4A8" icon="chart" parentTotal={total}
        open={open.brokerages} onToggle={() => toggle('brokerages')} theme={theme} accent={accent}>
        {BROKERAGES.map(b => (
          <Row key={b.id} theme={theme}
            left={<InstLogo name={b.name} theme={theme} accent={accent}/>}
            title={b.name}
            subtitle={`${b.holdings} holdings`}
            rightTop={<span style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}><Dh/> {fmtAED(b.portfolio)}</span>}
            rightBottom={<Delta value={b.pnlDay} pct={b.pnlPct} theme={theme} size={11}/>}
          />
        ))}
      </Section>

      <Section
        title="Crypto" total={cryptoTotal} count={CRYPTO.length}
        color="#9BB08A" icon="coin" parentTotal={total}
        open={open.crypto} onToggle={() => toggle('crypto')} theme={theme} accent={accent}>
        {CRYPTO.map(c => (
          <Row key={c.id} theme={theme}
            left={<CoinBadge symbol={c.symbol} theme={theme}/>}
            title={c.name}
            subtitle={<>{c.qty} {c.symbol} · <Dh/> {fmtAED(c.price)}</>}
            rightTop={<span style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}><Dh/> {fmtAED(c.value)}</span>}
            rightBottom={c.pnl24 === 0 ? <span style={{ fontFamily: FONTS.mono, fontSize: 11, color: theme.textMute }}>—</span> : <Delta pct={c.pnl24} value={c.pnl24} theme={theme} size={11}/>}
          />
        ))}
      </Section>

      <Section
        title="Real Estate" total={reTotal} count={REAL_ESTATE.length}
        color="#7389A8" icon="building" parentTotal={total}
        open={open.realestate} onToggle={() => toggle('realestate')} theme={theme} accent={accent}>
        {REAL_ESTATE.map(r => {
          const { equity, mortgage } = getPropertyEquity(r);
          return (
            <div key={r.id} style={{ padding: '14px 18px', borderBottom: `0.5px solid ${theme.line}` }}>
              <div style={{ display: 'flex', justifyContent:'space-between', alignItems:'flex-start', gap: 12 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, color: theme.text, fontWeight: 500 }}>{r.name}</div>
                  <div style={{ fontSize: 11, color: theme.textMute, fontFamily: FONTS.mono, marginTop: 2 }}>{r.location}</div>
                </div>
                <div style={{ textAlign:'right' }}>
                  <div style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}><Dh/> {fmtAED(r.value, {compact:true})}</div>
                  <div style={{ fontSize: 10.5, fontFamily: FONTS.mono, color: theme.textDim }}>Market value</div>
                </div>
              </div>
              <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, fontFamily: FONTS.mono, fontSize: 10.5 }}>
                <Stat label="Purchased" value={`${fmtAED(r.purchase,{compact:true})}`} theme={theme}/>
                <Stat label="Equity" value={`${fmtAED(equity,{compact:true})}`} theme={theme} accent={accent}/>
                <Stat label="Mortgage" value={`${fmtAED(mortgage,{compact:true})}`} theme={theme}/>
              </div>
              <div style={{ marginTop: 10, height: 4, borderRadius: 2, background: theme.surface2, overflow: 'hidden' }}>
                <div style={{ height: '100%', width: `${equity / r.value * 100}%`, background: accent }}/>
              </div>
              <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute, marginTop: 5 }}>
                {(equity / r.value * 100).toFixed(0)}% equity built · mortgage tracked under Liabilities
              </div>
            </div>
          );
        })}
      </Section>

      <Section
        title="Other Valuables" total={otherTotal} count={OTHER_ASSETS.length}
        color="#C97B63" icon="gem" parentTotal={total}
        open={open.other} onToggle={() => toggle('other')} theme={theme} accent={accent}>
        {OTHER_ASSETS.map(o => (
          <Row key={o.id} theme={theme}
            left={(() => {
              const iconName = o.category === 'Vehicle' ? 'car' : o.category === 'Jewellery' ? 'gem' : 'briefcase';
              const IcC = Ico[iconName];
              return (
                <div style={{ width: 36, height: 36, borderRadius: 10, background: theme.surface2, display:'flex', alignItems:'center', justifyContent:'center', color: accent, border:`0.5px solid ${theme.line}` }}>
                  <IcC size={16}/>
                </div>
              );
            })()}
            title={o.name}
            subtitle={`${o.category} · updated ${o.updated}`}
            rightTop={<span style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}><Dh/> {fmtAED(o.value)}</span>}
            rightBottom={<span style={{ fontFamily: FONTS.mono, fontSize: 11, color: theme.textMute }}>Manual</span>}
          />
        ))}
      </Section>
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// LIABILITIES BODY
// ─────────────────────────────────────────────────────────────
function LiabilitiesBody({ theme, accent }) {
  const [open, setOpen] = React.useState({ loans: true, credit_cards: true, mortgages: false });
  const toggle = (k) => setOpen(o => ({ ...o, [k]: !o[k] }));

  const total = LIABILITIES_TOTAL;
  const loansTotal = LIABILITIES.loans.reduce((s,l)=>s+l.balance, 0);
  const ccTotal    = LIABILITIES.credit_cards.reduce((s,c)=>s+c.balance, 0);
  const mortTotal  = LIABILITIES.mortgages.reduce((s,m)=>s+m.balance, 0);

  // Weighted-average APR + monthly debt service.
  // Credit cards expose `minPayment`; loans/mortgages expose `monthlyPayment`.
  const flatItems = [
    ...LIABILITIES.loans, ...LIABILITIES.credit_cards, ...LIABILITIES.mortgages,
  ];
  const weightedAPR = flatItems.reduce((s,i)=>s + i.balance * i.apr, 0) / total;
  const monthlyService = flatItems.reduce((s,i)=>s + (i.monthlyPayment ?? i.minPayment ?? 0), 0);

  // Group loans by kind for sub-headers
  const loansByKind = LIABILITIES.loans.reduce((acc, l) => {
    (acc[l.kind] = acc[l.kind] || []).push(l);
    return acc;
  }, {});

  return (
    <>
      {/* Total liabilities card */}
      <div style={{ padding: '0 16px 12px' }}>
        <Card theme={theme} style={{ padding: 18 }}>
          <div style={{ display: 'flex', justifyContent:'space-between', alignItems:'flex-end' }}>
            <div>
              <SectionLabel theme={theme}>Total owed</SectionLabel>
              <BigNumber value={total} theme={theme} accent={theme.negative} size={30}/>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute, textTransform:'uppercase', letterSpacing: 1 }}>30d</div>
              <DebtDelta value={LIABILITIES_MOM} theme={theme}/>
            </div>
          </div>
          <div style={{ marginTop: 14 }}>
            <StackedBar segments={LIABILITY_BREAKDOWN} height={5} theme={theme}/>
            <div style={{ display:'flex', justifyContent:'space-between', marginTop: 10, fontFamily: FONTS.mono, fontSize: 9.5, color: theme.textMute }}>
              {LIABILITY_BREAKDOWN.map(s => (
                <div key={s.key} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                  <div style={{ width: 5, height: 5, borderRadius: 1, background: s.color }}/>
                  <span>{(s.value/total*100).toFixed(0)}%</span>
                </div>
              ))}
            </div>
          </div>
        </Card>
      </div>

      {/* Cost-of-debt card */}
      <div style={{ padding: '0 16px 16px' }}>
        <Card theme={theme} style={{ padding: 14, display: 'flex', gap: 0 }}>
          <CostStat
            label="Avg APR"
            value={`${weightedAPR.toFixed(1)}%`}
            sub="weighted by balance"
            theme={theme}
          />
          <div style={{ width: 0.5, background: theme.line, margin: '2px 0' }}/>
          <CostStat
            label="Monthly debt service"
            value={<><Dh/> {fmtAED(monthlyService)}</>}
            sub={`${(monthlyService/24800*100).toFixed(0)}% of salary`}
            theme={theme}
          />
        </Card>
      </div>

      {/* Loans (with sub-headers per kind) */}
      <Section
        title="Loans" total={loansTotal} count={LIABILITIES.loans.length}
        color="#C77A00" icon="wallet" parentTotal={total}
        open={open.loans} onToggle={() => toggle('loans')} theme={theme} accent={accent}>
        {Object.keys(loansByKind).map(kind => (
          <React.Fragment key={kind}>
            <SubHeader label={LOAN_KIND_LABELS[kind] || kind} theme={theme}/>
            {loansByKind[kind].map(l => (
              <Row key={l.id} theme={theme}
                left={<InstLogo name={l.lender} theme={theme} accent={accent}/>}
                title={l.lender}
                subtitle={`${l.apr.toFixed(1)}% APR · payoff ${l.payoffDate}`}
                rightTop={<span style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}><Dh/> {fmtAED(l.balance)}</span>}
                rightBottom={<span style={{ fontFamily: FONTS.mono, fontSize: 11, color: theme.textMute }}><Dh/> {fmtAED(l.monthlyPayment)}/mo</span>}
              />
            ))}
          </React.Fragment>
        ))}
      </Section>

      {/* Credit cards */}
      <Section
        title="Credit Cards" total={ccTotal} count={LIABILITIES.credit_cards.length}
        color="#D23B2E" icon="wallet" parentTotal={total}
        open={open.credit_cards} onToggle={() => toggle('credit_cards')} theme={theme} accent={accent}>
        {LIABILITIES.credit_cards.map(c => {
          const utilPct = (c.balance / c.limit) * 100;
          return (
            <div key={c.id} style={{ padding: '12px 16px', borderBottom: `0.5px solid ${theme.line}` }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <InstLogo name={c.issuer} theme={theme} accent={accent}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, color: theme.text, fontWeight: 500 }}>{c.issuer}</div>
                  <div style={{ fontSize: 11, color: theme.textMute, fontFamily: FONTS.mono, marginTop: 2 }}>
                    {c.last} · {c.apr.toFixed(0)}% APR
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}><Dh/> {fmtAED(c.balance)}</div>
                  <div style={{ fontFamily: FONTS.mono, fontSize: 10.5, color: theme.textMute, marginTop: 2 }}>
                    of <Dh/> {fmtAED(c.limit, {compact: true})}
                  </div>
                </div>
              </div>
              <div style={{ marginTop: 10, height: 3, borderRadius: 2, background: theme.surface2, overflow: 'hidden' }}>
                <div style={{
                  height: '100%', width: `${Math.min(100, utilPct)}%`,
                  background: utilPct > 30 ? theme.warning : theme.positive,
                }}/>
              </div>
              <div style={{ fontFamily: FONTS.mono, fontSize: 9.5, color: theme.textMute, marginTop: 4 }}>
                {utilPct.toFixed(0)}% utilization · min <Dh/> {c.minPayment} on {c.statementDate}
              </div>
            </div>
          );
        })}
      </Section>

      {/* Mortgages — link back to Real Estate */}
      <Section
        title="Mortgages" total={mortTotal} count={LIABILITIES.mortgages.length}
        color="#7389A8" icon="building" parentTotal={total}
        open={open.mortgages} onToggle={() => toggle('mortgages')} theme={theme} accent={accent}>
        {LIABILITIES.mortgages.map(m => {
          const property = REAL_ESTATE.find(r => r.id === m.propertyId);
          const paid = m.originalAmount - m.balance;
          const paidPct = (paid / m.originalAmount) * 100;
          return (
            <div key={m.id} style={{ padding: '14px 18px', borderBottom: `0.5px solid ${theme.line}` }}>
              <div style={{ display: 'flex', justifyContent:'space-between', alignItems:'flex-start', gap: 12 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, color: theme.text, fontWeight: 500 }}>{m.lender}</div>
                  <div style={{ fontSize: 11, color: theme.textMute, fontFamily: FONTS.mono, marginTop: 2 }}>
                    {property ? property.name : 'Property'} · {m.term}
                  </div>
                </div>
                <div style={{ textAlign:'right' }}>
                  <div style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}><Dh/> {fmtAED(m.balance, {compact:true})}</div>
                  <div style={{ fontSize: 10.5, fontFamily: FONTS.mono, color: theme.textDim }}>{m.apr.toFixed(2)}% APR</div>
                </div>
              </div>
              <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, fontFamily: FONTS.mono, fontSize: 10.5 }}>
                <Stat label="Original" value={`${fmtAED(m.originalAmount,{compact:true})}`} theme={theme}/>
                <Stat label="Paid down" value={`${fmtAED(paid,{compact:true})}`} theme={theme} accent={theme.positive}/>
                <Stat label="Monthly" value={`${fmtAED(m.monthlyPayment)}`} theme={theme}/>
              </div>
              <div style={{ marginTop: 10, height: 4, borderRadius: 2, background: theme.surface2, overflow: 'hidden' }}>
                <div style={{ height: '100%', width: `${paidPct}%`, background: theme.positive }}/>
              </div>
              <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute, marginTop: 5 }}>
                {paidPct.toFixed(0)}% paid down · since {m.originationDate}
              </div>
            </div>
          );
        })}
      </Section>
    </>
  );
}

// Delta variant for debt: down = good (green), up = bad (red).
function DebtDelta({ value, theme }) {
  const paidDown = value < 0;
  const color = paidDown ? theme.positive : theme.negative;
  const arrow = paidDown ? '↓' : '↑';
  return (
    <span style={{ color, fontFamily: FONTS.mono, fontSize: 13, fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>
      {arrow} <Dh/> {fmtAED(Math.abs(value))}
    </span>
  );
}

function CostStat({ label, value, sub, theme }) {
  return (
    <div style={{ flex: 1, padding: '4px 12px' }}>
      <div style={{ fontFamily: FONTS.mono, fontSize: 9.5, color: theme.textMute, textTransform: 'uppercase', letterSpacing: 1 }}>{label}</div>
      <div style={{ fontFamily: FONTS.display, fontSize: 20, color: theme.text, marginTop: 4, letterSpacing: -0.4, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
      <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.textDim, marginTop: 3 }}>{sub}</div>
    </div>
  );
}

function Section({ title, total, count, color, icon, open, onToggle, theme, accent, children, parentTotal }) {
  const Icon = Ico[icon];
  const denom = parentTotal || NET_WORTH;
  return (
    <div style={{ padding: '0 16px 12px' }}>
      <button onClick={onToggle} style={{
        width: '100%', background: theme.surface,
        border: `0.5px solid ${theme.line}`,
        borderRadius: open ? '18px 18px 0 0' : 18,
        padding: '14px 16px',
        display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
        color: theme.text, textAlign: 'left',
      }}>
        <div style={{ width: 8, height: 8, borderRadius: 2, background: color }}/>
        <div style={{ flex: 1, display: 'flex', flexDirection:'column', gap: 2 }}>
          <div style={{ fontFamily: FONTS.ui, fontSize: 14, fontWeight: 500 }}>{title}</div>
          <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute, letterSpacing: 0.3 }}>{count} {count===1?'item':'items'}</div>
        </div>
            <div style={{ textAlign: 'right', flexShrink: 0, marginLeft: 12 }}>
              <div style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text, whiteSpace:'nowrap' }}><Dh/> {fmtAED(total, {compact: total>10000})}</div>
              <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute, marginTop: 2 }}>{(total/denom*100).toFixed(1)}%</div>
            </div>
        <div style={{ marginLeft: 8, color: theme.textDim, transform: open ? 'rotate(90deg)' : '', transition: 'transform 160ms' }}>
          <Ico.chevR size={14}/>
        </div>
      </button>
      {open && (
        <div style={{
          background: theme.surface, borderLeft: `0.5px solid ${theme.line}`, borderRight: `0.5px solid ${theme.line}`, borderBottom: `0.5px solid ${theme.line}`,
          borderRadius: '0 0 18px 18px', overflow: 'hidden',
        }}>
          {children}
        </div>
      )}
    </div>
  );
}

function SubHeader({ label, theme }) {
  return (
    <div style={{ padding: '10px 18px 4px', fontFamily: FONTS.mono, fontSize: 9.5, letterSpacing: 1.2, textTransform: 'uppercase', color: theme.textMute, borderTop: `0.5px solid ${theme.line}` }}>{label}</div>
  );
}

function BankRow({ b, theme, accent }) {
  return (
    <Row theme={theme}
      left={<InstLogo name={b.bank} theme={theme} accent={accent}/>}
      title={`${b.bank}`}
      subtitle={`${b.type} · ${b.last}`}
      rightTop={<span style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}><Dh/> {fmtAED(b.balance)}</span>}
      rightBottom={<span style={{ fontFamily: FONTS.mono, fontSize: 10.5, color: theme.textMute }}>{b.synced}</span>}
    />
  );
}

function Row({ left, title, subtitle, rightTop, rightBottom, theme }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 16px',
      borderBottom: `0.5px solid ${theme.line}`,
    }}>
      {left}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, color: theme.text, fontWeight: 500, overflow: 'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{title}</div>
        <div style={{ fontSize: 11, color: theme.textMute, fontFamily: FONTS.mono, marginTop: 2, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{subtitle}</div>
      </div>
      <div style={{ textAlign: 'right', display:'flex', flexDirection:'column', alignItems:'flex-end', gap: 3, flexShrink: 0, minWidth: 90 }}>
        <div style={{ whiteSpace: 'nowrap' }}>{rightTop}</div>
        <div style={{ whiteSpace: 'nowrap' }}>{rightBottom}</div>
      </div>
    </div>
  );
}

function InstLogo({ name, theme, accent }) {
  const short = name.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase();
  return (
    <div style={{
      width: 36, height: 36, borderRadius: 10,
      background: theme.surface2,
      border: `0.5px solid ${theme.line}`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: FONTS.display, fontSize: 13, color: theme.text, fontWeight: 500,
      letterSpacing: -0.3, flexShrink: 0,
    }}>{short}</div>
  );
}

function CoinBadge({ symbol, theme }) {
  const colors = { BTC:'#F7931A', ETH:'#627EEA', SOL:'#9945FF', USDC:'#2775CA' };
  return (
    <div style={{
      width: 36, height: 36, borderRadius: 18,
      background: colors[symbol] + '25',
      border: `0.5px solid ${colors[symbol] + '55'}`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: FONTS.mono, fontSize: 10, color: colors[symbol], fontWeight: 600,
      flexShrink: 0, letterSpacing: 0.2,
    }}>{symbol}</div>
  );
}

function Stat({ label, value, theme, accent }) {
  return (
    <div>
      <div style={{ fontSize: 9.5, color: theme.textMute, textTransform: 'uppercase', letterSpacing: 1 }}>{label}</div>
      <div style={{ fontSize: 12, color: accent || theme.text, marginTop: 2, fontVariantNumeric: 'tabular-nums' }}><Dh/> {value}</div>
    </div>
  );
}

Object.assign(window, { AssetsScreen });
