// dash-home.jsx — Home tab: split wallets + dynamic credit limit + activity

function HomeTab({ btcPrice, onNavigate, onOpenWallet, onOpenSettings }) {
  const btcValueUsd = MOCK.btc * btcPrice;
  const netWorth = MOCK.cashUsd + btcValueUsd;

  // Dynamic credit limit — income line always on; pledges expand it based on aggressiveness
  const [pledges, setPledges] = React.useState({
    btc: 0.32,              // ₿ pledged
    usd: 18_000,            // $ pledged
    investments: 50_000,    // $ pledged (stocks/ETFs)
  });
  const [aggr, setAggr] = React.useState(40); // 10–75% — drives ceiling & APR
  const [limitOpen, setLimitOpen] = React.useState(false);

  const incomeLimit  = MOCK.fromIncome;
  const pledgedValue = pledges.btc * btcPrice + pledges.usd + pledges.investments;
  const hasPledges   = pledgedValue > 0;
  const pledgeLimit  = pledgedValue * (aggr / 100);
  // Income line contributes fully at aggressiveness; at 10% you use ~13% of income, at 75% you use ~100%
  const incomeShare  = aggr / 75;
  const incomeContribution = incomeLimit * incomeShare;
  const creditLimit  = incomeContribution + pledgeLimit;
  const usedCredit   = 24_871.44;
  const availCredit  = creditLimit - usedCredit;

  return (
    <DashScreen>
      <DashHeader
        subtitle={`Welcome back, ${MOCK.firstName}`}
        title="Overview"
        right={
          <button onClick={onOpenSettings} style={{
            width: 40, height: 40, borderRadius: '50%',
            background: DASH_GRADIENT,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: DASH_DISPLAY, fontWeight: 700, fontSize: 16, color: '#000',
            boxShadow: '0 0 16px rgba(255,159,10,0.4)',
            border: 'none', cursor: 'pointer', padding: 0,
          }}>{MOCK.firstName[0]}{MOCK.lastName[0]}</button>
        }
      />

      <div style={{ padding: '0 20px 16px' }}>
        {/* NET WORTH + BTC PRICE ticker */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <div>
            <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.45)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 2, fontFamily: DASH_MONO }}>Net worth</div>
            <AnimatedNumber value={netWorth} format={v => fmtUsd(v)} style={{ fontFamily: DASH_DISPLAY, fontSize: 30, fontWeight: 600, color: '#fff', letterSpacing: '-0.035em' }} />
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.45)', letterSpacing: '0.15em', textTransform: 'uppercase', marginBottom: 2, fontFamily: DASH_MONO }}>BTC · LIVE</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'flex-end' }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#10B981', boxShadow: '0 0 6px #10B981', animation: 'livePulse 1.5s ease-in-out infinite' }}/>
              <AnimatedNumber value={btcPrice} format={v => fmtUsd(v, { decimals: 0 })} duration={800} style={{ fontFamily: DASH_MONO, fontSize: 14, fontWeight: 600, color: '#FF9F0A' }}/>
            </div>
          </div>
        </div>

        {/* SPLIT WALLETS */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
          {/* BTC wallet */}
          <div onClick={() => onOpenWallet && onOpenWallet('btc')} style={{
            background: DASH_GRADIENT, borderRadius: 20, padding: 16,
            boxShadow: '0 12px 40px rgba(255,159,10,0.3)',
            position: 'relative', overflow: 'hidden', minHeight: 140,
            cursor: 'pointer', transition: 'transform 0.2s',
          }}
          onMouseDown={e => e.currentTarget.style.transform = 'scale(0.98)'}
          onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}>
            <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: '#000', opacity: 0.6, textTransform: 'uppercase', fontWeight: 700 }}>BTC Wallet</div>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 26, fontWeight: 700, color: '#000', letterSpacing: '-0.03em', marginTop: 28, lineHeight: 1 }}>{fmtBtc(MOCK.btc)}</div>
            <div style={{ fontFamily: DASH_MONO, fontSize: 11, color: '#000', opacity: 0.65, marginTop: 4, fontWeight: 600 }}>
              ≈ <AnimatedNumber value={btcValueUsd} format={v => fmtUsd(v, { decimals: 0 })} />
            </div>
            <div style={{ position: 'absolute', right: -12, bottom: -18, fontFamily: DASH_DISPLAY, fontSize: 110, fontWeight: 800, color: 'rgba(0,0,0,0.08)', lineHeight: 1 }}>₿</div>
            <div style={{ position: 'absolute', top: 12, right: 12, width: 20, height: 20, borderRadius: '50%', background: 'rgba(0,0,0,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#000" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l6 6-6 6"/></svg>
            </div>
          </div>
          {/* USD wallet */}
          <div onClick={() => onOpenWallet && onOpenWallet('usd')} style={{
            background: 'linear-gradient(135deg, #10B981 0%, #059669 100%)',
            borderRadius: 20, padding: 16,
            boxShadow: '0 12px 40px rgba(16,185,129,0.25)',
            position: 'relative', overflow: 'hidden', minHeight: 140,
            cursor: 'pointer', transition: 'transform 0.2s',
          }}
          onMouseDown={e => e.currentTarget.style.transform = 'scale(0.98)'}
          onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}>
            <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: '#000', opacity: 0.6, textTransform: 'uppercase', fontWeight: 700 }}>USD Wallet</div>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 26, fontWeight: 700, color: '#000', letterSpacing: '-0.03em', marginTop: 28, lineHeight: 1 }}>{fmtUsd(MOCK.cashUsd, { decimals: 0 })}</div>
            <div style={{ fontFamily: DASH_MONO, fontSize: 10, color: '#000', opacity: 0.65, marginTop: 4, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>
              <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#000', opacity: 0.5 }}/>
              Over-roll armed
            </div>
            <div style={{ position: 'absolute', right: -4, bottom: -10, fontFamily: DASH_DISPLAY, fontSize: 80, fontWeight: 800, color: 'rgba(0,0,0,0.08)', lineHeight: 1 }}>$</div>
            <div style={{ position: 'absolute', top: 12, right: 12, width: 20, height: 20, borderRadius: '50%', background: 'rgba(0,0,0,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#000" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l6 6-6 6"/></svg>
            </div>
          </div>
        </div>

        {/* DYNAMIC CREDIT LIMIT — the hero secondary card */}
        <DashCard glow onClick={() => setLimitOpen(true)} style={{ marginBottom: 14, padding: 18, cursor: 'pointer' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
            <div>
              <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: '#FF9F0A', textTransform: 'uppercase', marginBottom: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
                Dynamic Credit Limit
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.7 }}><circle cx="12" cy="12" r="9"/><path d="M12 16v-4M12 8h.01"/></svg>
              </div>
              <AnimatedNumber value={creditLimit} format={v => fmtUsd(v, { decimals: 0 })} duration={800} style={{ fontFamily: DASH_DISPLAY, fontSize: 34, fontWeight: 600, letterSpacing: '-0.035em', color: '#fff', display: 'block', lineHeight: 1 }}/>
              <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.55)', marginTop: 6 }}>
                <AnimatedNumber value={availCredit} format={v => fmtUsd(v, { decimals: 0 })} style={{ color: '#10B981', fontWeight: 600 }}/> available · {fmtUsd(usedCredit, { decimals: 0 })} used
              </div>
            </div>
            <div style={{ padding: '4px 8px', borderRadius: 100, background: 'rgba(255,159,10,0.12)', border: '1px solid rgba(255,159,10,0.3)', fontSize: 9, fontWeight: 700, letterSpacing: '0.15em', color: '#FF9F0A', fontFamily: DASH_MONO, textTransform: 'uppercase' }}>{tierForLtv(aggr).apr.toFixed(2)}% APR</div>
          </div>

          {/* Stacked bar — income vs pledges */}
          <div style={{ height: 8, borderRadius: 4, background: 'rgba(255,255,255,0.05)', display: 'flex', overflow: 'hidden', marginBottom: 10 }}>
            <div style={{ flex: incomeContribution, background: '#3B82F6' }}/>
            <div style={{ flex: pledgeLimit,        background: DASH_GRADIENT, transition: 'flex 0.6s cubic-bezier(0.16,1,0.3,1)' }}/>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6, fontSize: 10 }}>
            <LimitLegend color="#3B82F6" label="Income"  value={incomeContribution} />
            <LimitLegend color="#FF9F0A" label="Pledges" value={pledgeLimit} animated />
            <LimitLegend color="#A78BFA" label={`${aggr}% aggr.`} value={creditLimit} />
          </div>
        </DashCard>

        {/* QUICK ACTIONS — removed; Send/Receive/Swap/Buy live in BTC Wallet and USD Wallet tabs */}

        {/* ROUND-UP BANNER */}
        <DashCard style={{ marginBottom: 14, padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 40, height: 40, borderRadius: 12, background: 'rgba(255,159,10,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#FF9F0A" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17l5-5 5 5"/><path d="M7 11l5-5 5 5"/></svg>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 500, color: '#fff', marginBottom: 1 }}>Round-ups → Bitcoin</div>
            <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)' }}>This month: <span style={{ color: '#FF9F0A', fontWeight: 600 }}>142,384 sats</span> earned</div>
          </div>
          <button onClick={() => onNavigate('card')} style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', padding: '6px 12px', borderRadius: 100, fontSize: 11, fontWeight: 500, cursor: 'pointer' }}>Tune</button>
        </DashCard>

        {/* RECENT ACTIVITY — unified across card, USD, BTC */}
        <div style={{ marginBottom: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingLeft: 4 }}>
          <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.45)', textTransform: 'uppercase' }}>Recent activity · all accounts</div>
          <button onClick={() => onNavigate('card')} style={{ background: 'transparent', border: 'none', color: '#FF9F0A', fontSize: 11, fontWeight: 500, cursor: 'pointer', padding: 0 }}>See all</button>
        </div>
        <DashCard style={{ padding: 0, overflow: 'hidden' }}>
          {UNIFIED_ACTIVITY.slice(0, 6).map((tx, i, a) => (
            <UnifiedTxRow key={tx.id} tx={tx} btcPrice={btcPrice} isLast={i === a.slice(0, 6).length - 1} />
          ))}
        </DashCard>
      </div>

      <style>{`
        @keyframes livePulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }
      `}</style>

      {limitOpen && (
        <DynamicLimitModal
          pledges={pledges}
          setPledges={setPledges}
          aggr={aggr}
          setAggr={setAggr}
          btcPrice={btcPrice}
          incomeLimit={incomeLimit}
          incomeContribution={incomeContribution}
          pledgeLimit={pledgeLimit}
          creditLimit={creditLimit}
          hasPledges={hasPledges}
          onClose={() => setLimitOpen(false)}
        />
      )}
    </DashScreen>
  );
}

function LimitLegend({ color, label, value, animated }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 2 }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: color }}/>
        <span style={{ fontSize: 10, color: 'rgba(245,245,247,0.5)', letterSpacing: '0.04em' }}>{label}</span>
      </div>
      {animated
        ? <AnimatedNumber value={value} format={v => fmtUsd(v, { decimals: 0 })} style={{ fontFamily: DASH_MONO, fontSize: 12, fontWeight: 600, color: '#fff' }}/>
        : <div style={{ fontFamily: DASH_MONO, fontSize: 12, fontWeight: 600, color: '#fff' }}>{fmtUsd(value, { decimals: 0 })}</div>}
    </div>
  );
}

function QuickAction({ icon, label, onClick }) {
  const icons = {
    send:    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17L17 7M17 7H8M17 7v9"/></svg>,
    receive: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 7L7 17M7 17h9M7 17V8"/></svg>,
    swap:    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 10h14M17 6l4 4-4 4M17 14H3M7 18l-4-4 4-4"/></svg>,
    buy:     <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v10M9 10h4.5a2 2 0 010 4H9m0-4v4m6-4v4"/></svg>,
  };
  return (
    <button onClick={onClick} style={{
      background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)',
      borderRadius: 16, padding: '12px 4px',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
      color: '#fff', cursor: 'pointer', transition: 'all 0.2s',
    }}>
      <div style={{ color: '#FF9F0A' }}>{icons[icon]}</div>
      <span style={{ fontSize: 11, fontWeight: 500 }}>{label}</span>
    </button>
  );
}

function TxRow({ tx, isLast }) {
  const catColors = {
    Dining: '#FF9F0A', Fuel: '#3B82F6', Tech: '#A78BFA',
    Travel: '#10B981', Groceries: '#EC4899', Fitness: '#F59E0B',
  };
  const color = catColors[tx.cat] || '#FF9F0A';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 14px',
      borderBottom: isLast ? 'none' : '1px solid rgba(255,255,255,0.04)',
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10,
        background: `${color}20`, border: `1px solid ${color}40`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 10, fontWeight: 700, color, fontFamily: DASH_MONO,
        flexShrink: 0,
      }}>{tx.cat.slice(0, 3).toUpperCase()}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500, color: '#fff', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tx.merchant}</div>
        <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.45)', marginTop: 1 }}>{tx.when}</div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: '#fff', fontFamily: DASH_MONO }}>{fmtUsd(tx.amt, { decimals: 2 })}</div>
        <div style={{ fontSize: 9, color: '#FF9F0A', marginTop: 1, fontFamily: DASH_MONO, fontWeight: 600 }}>+{tx.sats} sats</div>
      </div>
    </div>
  );
}

// ═══ UNIFIED ACTIVITY — merged from card / USD / BTC wallets ════════════
// Order matters: higher _order = more recent (shown first)
const UNIFIED_ACTIVITY = [
  // Today
  { id: 'ua1', src: 'card', title: 'Nobu · Malibu',          sub: 'Dining · Velocity Black',    amt: -412.80,    kind: 'usd', sats: +412,  when: 'Today · 8:14pm',   _order: 100 },
  { id: 'ua2', src: 'btc',  title: 'Round-ups · Nobu',       sub: 'Auto-stacked 412 sats',      amt: +0.00000412,kind: 'btc',              when: 'Today · 8:14pm',   _order: 99 },
  { id: 'ua3', src: 'btc',  title: 'DCA buy settled',        sub: 'Kraken · withdrawal',        amt: +0.2431,    kind: 'btc',              when: 'Today · 2:14pm',   _order: 98 },
  { id: 'ua4', src: 'card', title: 'Shell',                  sub: 'Fuel · Velocity Black',      amt: -84.20,     kind: 'usd', sats: +84,   when: 'Today · 11:02am',  _order: 97 },
  { id: 'ua5', src: 'usd',  title: 'Payroll · Kairos',       sub: 'Direct deposit',             amt: +42_000.00, kind: 'usd',              when: 'Today · 9:00am',   _order: 96 },
  // Yesterday
  { id: 'ua6', src: 'card', title: 'Apple Store',            sub: 'Tech · Velocity Black',      amt: -2_399.00,  kind: 'usd', sats: +2399, when: 'Yesterday · 4:42pm', _order: 90 },
  { id: 'ua7', src: 'usd',  title: 'Convert from BTC',       sub: '0.15 BTC → USD',             amt: +10_261.86, kind: 'usd',              when: 'Yesterday · 2:18pm', _order: 89 },
  { id: 'ua8', src: 'btc',  title: 'Convert → USD',          sub: 'Paid down card',             amt: -0.1500,    kind: 'btc',              when: 'Yesterday · 2:18pm', _order: 88 },
  // Earlier
  { id: 'ua9',  src: 'usd',  title: 'Wire · Title & Escrow', sub: 'Earnest money',              amt: -8_400.00,  kind: 'usd',              when: 'Apr 21',            _order: 80 },
  { id: 'ua10', src: 'card', title: 'Velocity Black · Yacht',sub: 'Travel',                     amt: -18_400.00, kind: 'usd', sats: +18400,when: 'Apr 21',            _order: 79 },
  { id: 'ua11', src: 'btc',  title: 'Card cashback',         sub: 'Velocity Black · 18,400 sats', amt: +0.00124, kind: 'btc',              when: 'Apr 21',            _order: 78 },
].sort((a, b) => b._order - a._order);

function SrcBadge({ src }) {
  const map = {
    card: { label: 'CARD', bg: 'rgba(167,139,250,0.12)', br: 'rgba(167,139,250,0.35)', fg: '#A78BFA',
            icon: <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="6" width="20" height="13" rx="2"/><path d="M2 11h20"/></svg> },
    btc:  { label: 'BTC',  bg: 'rgba(255,159,10,0.15)',  br: 'rgba(255,159,10,0.4)',   fg: '#FF9F0A',
            icon: <span style={{ fontWeight: 700, fontSize: 13, lineHeight: 1 }}>₿</span> },
    usd:  { label: 'USD',  bg: 'rgba(16,185,129,0.12)',  br: 'rgba(16,185,129,0.35)',  fg: '#10B981',
            icon: <span style={{ fontWeight: 700, fontSize: 12, lineHeight: 1 }}>$</span> },
  };
  const m = map[src];
  return (
    <div style={{
      width: 36, height: 36, borderRadius: 10,
      background: m.bg, border: `1px solid ${m.br}`, color: m.fg,
      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
    }}>{m.icon}</div>
  );
}

function UnifiedTxRow({ tx, btcPrice, isLast }) {
  const fg = tx.amt >= 0 ? '#10B981' : '#fff';
  const main = tx.kind === 'btc'
    ? (tx.amt >= 0 ? '+' : '') + fmtBtc(tx.amt)
    : fmtUsd(tx.amt, { decimals: 2 });
  const usdEq = tx.kind === 'btc' ? fmtUsd(tx.amt * btcPrice, { decimals: 2 }) : null;

  const srcTag = { card: 'Card', btc: 'BTC wallet', usd: 'USD wallet' }[tx.src];

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 14px',
      borderBottom: isLast ? 'none' : '1px solid rgba(255,255,255,0.04)',
    }}>
      <SrcBadge src={tx.src}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500, color: '#fff', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tx.title}</div>
        <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.45)', marginTop: 1, display: 'flex', alignItems: 'center', gap: 5 }}>
          <span style={{ fontFamily: DASH_MONO, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(245,245,247,0.55)' }}>{srcTag}</span>
          <span style={{ width: 2, height: 2, borderRadius: '50%', background: 'rgba(245,245,247,0.3)' }}/>
          <span>{tx.when}</span>
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: fg, fontFamily: DASH_MONO }}>{main}</div>
        {tx.sats != null && <div style={{ fontSize: 9, color: '#FF9F0A', marginTop: 1, fontFamily: DASH_MONO, fontWeight: 600 }}>+{tx.sats.toLocaleString()} sats</div>}
        {usdEq && <div style={{ fontSize: 9, color: 'rgba(245,245,247,0.45)', marginTop: 1, fontFamily: DASH_MONO }}>≈ {usdEq}</div>}
      </div>
    </div>
  );
}

Object.assign(window, { HomeTab, TxRow, UNIFIED_ACTIVITY, UnifiedTxRow });

// ═══ DYNAMIC CREDIT LIMIT MODAL ═══════════════════════════════════════════
// APR tiers based on max LTV ratio
const LTV_TIERS = [
  { min: 10, max: 25, apr: 14.99, label: 'Deep cushion' },
  { min: 26, max: 40, apr: 17.99, label: 'Conservative' },
  { min: 41, max: 55, apr: 21.99, label: 'Moderate' },
  { min: 56, max: 70, apr: 25.99, label: 'Aggressive' },
  { min: 71, max: 75, apr: 29.99, label: 'Maximum' },
];
function tierForLtv(ltv) {
  return LTV_TIERS.find(t => ltv >= t.min && ltv <= t.max) || LTV_TIERS[0];
}

function DynamicLimitModal({ pledges, setPledges, aggr, setAggr, btcPrice, incomeLimit, incomeContribution, pledgeLimit, creditLimit, hasPledges, onClose }) {
  const btcValue = pledges.btc * btcPrice;
  const tier = tierForLtv(aggr);
  const btcContrib = btcValue * (aggr / 100);
  const usdContrib = pledges.usd * (aggr / 100);
  const invContrib = pledges.investments * (aggr / 100);

  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 55,
      background: 'rgba(0,0,0,0.78)', backdropFilter: 'blur(10px)',
      display: 'flex', alignItems: 'flex-end',
      animation: 'loanOverlayIn 0.25s ease',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', height: '94%', overflowY: 'auto',
        background: '#0a0a0f',
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        border: '1px solid rgba(255,255,255,0.08)', borderBottom: 'none',
        animation: 'loanSheetIn 0.35s cubic-bezier(0.16, 1, 0.3, 1)',
      }}>
        {/* Header */}
        <div style={{ position: 'sticky', top: 0, background: 'linear-gradient(#0a0a0f, #0a0a0f 80%, rgba(10,10,15,0))', padding: '14px 20px 12px', zIndex: 5 }}>
          <div style={{ width: 36, height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.15)', margin: '0 auto 14px' }}/>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: '#FF9F0A', textTransform: 'uppercase', fontWeight: 700, marginBottom: 6 }}>Dynamic credit limit</div>
              <div style={{ fontFamily: DASH_DISPLAY, fontSize: 26, fontWeight: 600, color: '#fff', letterSpacing: '-0.03em' }}>What you pledge, you can spend</div>
            </div>
            <button onClick={onClose} style={{ width: 32, height: 32, borderRadius: '50%', background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
            </button>
          </div>
        </div>

        <div style={{ padding: '0 20px 28px' }}>
          {/* Explanation */}
          <div style={{ padding: 14, borderRadius: 12, background: 'rgba(255,159,10,0.06)', border: '1px solid rgba(255,159,10,0.2)', marginBottom: 16 }}>
            <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.8)', lineHeight: 1.55 }}>
              Your limit = <b style={{ color: '#3B82F6' }}>income line</b> + what you <b style={{ color: '#fff' }}>pledge</b>. One <b style={{ color: '#FF9F0A' }}>aggressiveness</b> dial controls how much of each we extend — and your APR. Pledges stay in your wallets and keep earning.
            </div>
          </div>

          {/* Total */}
          <div style={{
            padding: 18, borderRadius: 16,
            background: 'linear-gradient(135deg, rgba(255,159,10,0.12), rgba(255,69,58,0.03))',
            border: '1px solid rgba(255,159,10,0.3)',
            marginBottom: 18,
          }}>
            <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.2em', color: '#FF9F0A', textTransform: 'uppercase', fontWeight: 700, marginBottom: 6 }}>Your credit limit</div>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 38, fontWeight: 700, color: '#fff', letterSpacing: '-0.035em', lineHeight: 1 }}>{fmtUsd(creditLimit, { decimals: 0 })}</div>
            <div style={{ fontFamily: DASH_MONO, fontSize: 11, color: 'rgba(245,245,247,0.55)', marginTop: 6 }}>Updates live as your pledges change</div>
          </div>

          {/* Aggressiveness slider + APR — the single control */}
          <div style={{ padding: 16, borderRadius: 14, background: 'linear-gradient(135deg, rgba(255,159,10,0.08), rgba(255,69,58,0.02))', border: '1px solid rgba(255,159,10,0.25)', marginBottom: 16 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.2em', color: '#FF9F0A', textTransform: 'uppercase', fontWeight: 700, marginBottom: 4 }}>Aggressiveness</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#fff' }}>{tier.label}</div>
                <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.55)', marginTop: 2 }}>Controls income utilization, pledge LTV, and APR — all at once</div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0, marginLeft: 12 }}>
                <div style={{ fontFamily: DASH_DISPLAY, fontSize: 28, fontWeight: 700, color: '#FF9F0A', lineHeight: 1, letterSpacing: '-0.03em' }}>{aggr}<span style={{ fontSize: 16, color: 'rgba(255,159,10,0.6)' }}>%</span></div>
              </div>
            </div>

            <input
              type="range" min="10" max="75" step="5"
              value={aggr} onChange={e => setAggr(Number(e.target.value))}
              style={{ width: '100%', accentColor: '#FF9F0A' }}
            />
            <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: DASH_MONO, fontSize: 9, color: 'rgba(245,245,247,0.4)', marginTop: 2, marginBottom: 14 }}>
              <span>Conservative</span><span>Maximum</span>
            </div>

            {/* APR callout */}
            <div style={{
              padding: 12, borderRadius: 10,
              background: 'rgba(0,0,0,0.35)',
              border: '1px solid rgba(255,159,10,0.3)',
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <div>
                <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.18em', color: '#FF9F0A', textTransform: 'uppercase', fontWeight: 700, marginBottom: 3 }}>Purchase APR</div>
                <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.6)' }}>Variable · applied to revolved balance only</div>
              </div>
              <div style={{ fontFamily: DASH_DISPLAY, fontSize: 26, fontWeight: 700, color: '#fff', letterSpacing: '-0.03em' }}>{tier.apr.toFixed(2)}%</div>
            </div>
          </div>

          {/* Income line */}
          <LimitSection
            color="#3B82F6"
            title="Income line"
            subtitle="FICO + verified income"
            rightTag={`${Math.round((aggr / 75) * 100)}% in use`}
            locked
          >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 2px' }}>
              <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)' }}>Max {fmtUsd(incomeLimit, { decimals: 0 })} · contributing now</div>
              <div style={{ fontFamily: DASH_MONO, fontSize: 14, color: '#3B82F6', fontWeight: 700 }}>+{fmtUsd(incomeContribution, { decimals: 0 })}</div>
            </div>
          </LimitSection>

          {/* Bitcoin pledge */}
          <LimitSection
            color="#FF9F0A"
            title="Pledge Bitcoin"
            subtitle={`Holdings: ${MOCK.btc.toFixed(4)} ₿`}
            amount={pledges.btc}
            hasPledge={pledges.btc > 0}
          >
            <PledgeInput
              color="#FF9F0A"
              prefix="₿"
              value={pledges.btc}
              max={MOCK.btc}
              step={0.001}
              decimals={4}
              onChange={v => setPledges(p => ({ ...p, btc: v }))}
              sub={`≈ ${fmtUsd(btcValue, { decimals: 0 })} · contributes +${fmtUsd(btcContrib, { decimals: 0 })} at ${aggr}%`}
            />
          </LimitSection>

          {/* USD pledge */}
          <LimitSection
            color="#10B981"
            title="Pledge USD"
            subtitle={`Balance: ${fmtUsd(MOCK.cashUsd, { decimals: 0 })}`}
            amount={pledges.usd}
            hasPledge={pledges.usd > 0}
          >
            <PledgeInput
              color="#10B981"
              prefix="$"
              value={pledges.usd}
              max={MOCK.cashUsd}
              step={100}
              decimals={0}
              onChange={v => setPledges(p => ({ ...p, usd: v }))}
              sub={`Contributes +${fmtUsd(usdContrib, { decimals: 0 })} at ${aggr}%`}
            />
          </LimitSection>

          {/* Investments pledge */}
          <LimitSection
            color="#A78BFA"
            title="Pledge investments"
            subtitle="Linked brokerage · stocks, ETFs, bonds"
            amount={pledges.investments}
            hasPledge={pledges.investments > 0}
          >
            <PledgeInput
              color="#A78BFA"
              prefix="$"
              value={pledges.investments}
              max={180_000}
              step={1000}
              decimals={0}
              onChange={v => setPledges(p => ({ ...p, investments: v }))}
              sub={`Contributes +${fmtUsd(invContrib, { decimals: 0 })} at ${aggr}%`}
            />
          </LimitSection>

          {/* Fine print */}
          <div style={{ padding: 14, borderRadius: 12, background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.05)', marginBottom: 16 }}>
            <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.55)', textTransform: 'uppercase', fontWeight: 700, marginBottom: 8 }}>How pledges work</div>
            <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.7)', lineHeight: 1.55 }}>
              Pledged assets stay in <b style={{ color: '#fff' }}>your</b> wallets. You can still see them and they keep earning. If you miss your minimum payment and the card is canceled for default, we settle the outstanding balance from your pledges — in the order you choose. Otherwise, they're yours, untouched, forever.
            </div>
          </div>

          <button onClick={onClose} style={{
            width: '100%', padding: 15, borderRadius: 100,
            background: DASH_GRADIENT, border: 'none', color: '#000',
            fontSize: 14, fontWeight: 600, fontFamily: DASH_DISPLAY, cursor: 'pointer',
            boxShadow: '0 0 24px rgba(255,159,10,0.35)',
          }}>Save pledges</button>
        </div>
      </div>
    </div>
  );
}

function LimitSection({ color, title, subtitle, rightTag, amount, hasPledge, locked, children }) {
  return (
    <div style={{ padding: 14, borderRadius: 14, background: 'rgba(255,255,255,0.03)', border: `1px solid ${hasPledge ? color + '30' : 'rgba(255,255,255,0.06)'}`, marginBottom: 12 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: children ? 12 : 0 }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: `${color}18`, border: `1px solid ${color}40`, color, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          {locked ? (
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
          ) : (
            <div style={{ width: 10, height: 10, borderRadius: '50%', background: hasPledge ? color : 'transparent', border: `2px solid ${color}`, boxShadow: hasPledge ? `0 0 8px ${color}80` : 'none' }}/>
          )}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: '#fff' }}>{title}</div>
          <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)', marginTop: 1 }}>{subtitle}</div>
        </div>
        {rightTag && <div style={{ padding: '3px 8px', borderRadius: 100, background: `${color}15`, border: `1px solid ${color}40`, color, fontSize: 9, fontWeight: 700, fontFamily: DASH_MONO, letterSpacing: '0.12em', textTransform: 'uppercase', flexShrink: 0 }}>{rightTag}</div>}
      </div>
      {children}
    </div>
  );
}

function PledgeInput({ color, prefix, value, max, step, decimals, onChange, sub }) {
  const pct = Math.min(100, (value / max) * 100);
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginBottom: 8 }}>
        <span style={{ fontFamily: DASH_DISPLAY, fontSize: 22, fontWeight: 700, color: 'rgba(245,245,247,0.55)' }}>{prefix}</span>
        <input
          type="text"
          inputMode="decimal"
          value={value.toFixed(decimals)}
          onChange={e => {
            const n = Number(e.target.value.replace(/[^0-9.]/g, ''));
            if (!isNaN(n)) onChange(Math.max(0, Math.min(max, n)));
          }}
          style={{
            flex: 1, background: 'transparent', border: 'none', outline: 'none',
            fontFamily: DASH_DISPLAY, fontSize: 22, fontWeight: 700,
            color: '#fff', letterSpacing: '-0.02em', width: '100%', padding: 0,
          }}
        />
        <div style={{ display: 'flex', gap: 4 }}>
          {[0, 0.5, 1].map(p => (
            <button key={p} onClick={() => onChange(+(max * p).toFixed(decimals))} style={{
              padding: '4px 8px', borderRadius: 6,
              background: Math.abs(value - max * p) < step / 2 ? `${color}25` : 'rgba(255,255,255,0.04)',
              border: `1px solid ${Math.abs(value - max * p) < step / 2 ? `${color}50` : 'rgba(255,255,255,0.08)'}`,
              color: Math.abs(value - max * p) < step / 2 ? color : 'rgba(245,245,247,0.65)',
              fontSize: 9, fontWeight: 700, fontFamily: DASH_MONO, cursor: 'pointer',
            }}>{p === 0 ? '0' : p === 0.5 ? '½' : 'Max'}</button>
          ))}
        </div>
      </div>
      <input
        type="range" min="0" max={max} step={step}
        value={value} onChange={e => onChange(Number(e.target.value))}
        style={{ width: '100%', accentColor: color, margin: 0 }}
      />
      <div style={{ fontFamily: DASH_MONO, fontSize: 10, color: pct > 0 ? color : 'rgba(245,245,247,0.45)', marginTop: 6, fontWeight: 600 }}>{sub}</div>
    </div>
  );
}
