// dash-loans.jsx — Loans tab: product catalogue + apply flow

const LOAN_PRODUCTS = [
  {
    id: 'auto',
    title: 'Auto Loan',
    tagline: 'Apply for a car loan',
    apr: 'from 5.9%',
    term: '36–72 mo',
    max: '$250,000',
    accent: '#EF4444',
    glyph: (
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 17h14M7 17v-4l2-5h6l2 5v4M5 21v-4M19 21v-4"/><circle cx="8" cy="17" r="2"/><circle cx="16" cy="17" r="2"/></svg>
    ),
    fields: [
      { id: 'amount', label: 'Loan amount', type: 'number', placeholder: '45,000' },
      { id: 'vehicle', label: 'Vehicle', type: 'text', placeholder: '2025 Porsche Taycan' },
      { id: 'term', label: 'Term', type: 'select', options: ['36 months', '48 months', '60 months', '72 months'] },
    ],
  },
  {
    id: 'home',
    title: 'Home Loan',
    tagline: 'Get a home loan',
    apr: 'from 6.4%',
    term: '15–30 yr',
    max: '$3,000,000',
    accent: '#10B981',
    glyph: (
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 11l9-7 9 7v9a2 2 0 01-2 2h-4v-7h-6v7H5a2 2 0 01-2-2z"/></svg>
    ),
    fields: [
      { id: 'amount', label: 'Home price', type: 'number', placeholder: '1,850,000' },
      { id: 'down', label: 'Down payment', type: 'number', placeholder: '370,000' },
      { id: 'address', label: 'Property address', type: 'text', placeholder: '1410 Ocean Ave, Santa Monica' },
      { id: 'term', label: 'Term', type: 'select', options: ['15 years · fixed', '20 years · fixed', '30 years · fixed', '7/1 ARM'] },
    ],
  },
  {
    id: 'personal',
    title: 'Personal Loan',
    tagline: 'Borrow money today',
    apr: 'from 7.9%',
    term: '12–60 mo',
    max: '$100,000',
    accent: '#A78BFA',
    glyph: (
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="7" width="18" height="12" rx="2"/><path d="M3 11h18"/><circle cx="12" cy="15" r="1.5"/></svg>
    ),
    fields: [
      { id: 'amount', label: 'Amount', type: 'number', placeholder: '25,000' },
      { id: 'purpose', label: 'Purpose', type: 'select', options: ['Debt consolidation', 'Home improvement', 'Medical', 'Wedding', 'Other'] },
      { id: 'term', label: 'Term', type: 'select', options: ['12 months', '24 months', '36 months', '48 months', '60 months'] },
    ],
  },
  {
    id: 'car-equity',
    title: 'Car Equity',
    tagline: 'Get money against your car',
    apr: 'from 8.4%',
    term: '12–48 mo',
    max: '$80,000',
    accent: '#F59E0B',
    glyph: (
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 17h14M7 17v-4l2-5h6l2 5v4"/><circle cx="8" cy="17" r="2"/><circle cx="16" cy="17" r="2"/><path d="M12 3v4M10 5h4"/></svg>
    ),
    fields: [
      { id: 'vehicle', label: 'Your vehicle', type: 'text', placeholder: '2023 Range Rover Sport' },
      { id: 'vin', label: 'VIN', type: 'text', placeholder: 'SAL***********' },
      { id: 'amount', label: 'Cash-out amount', type: 'number', placeholder: '32,000' },
    ],
  },
  {
    id: 'heloc',
    title: 'HELOC',
    tagline: 'Get money against your house',
    apr: 'from 7.2%',
    term: '10 yr draw',
    max: '$750,000',
    accent: '#3B82F6',
    glyph: (
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 11l9-7 9 7v9a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><path d="M9 21v-6h6v6"/><circle cx="12" cy="12" r="1.5"/></svg>
    ),
    fields: [
      { id: 'address', label: 'Property', type: 'text', placeholder: '1410 Ocean Ave, Santa Monica' },
      { id: 'value', label: 'Est. home value', type: 'number', placeholder: '2,400,000' },
      { id: 'mortgage', label: 'Mortgage balance', type: 'number', placeholder: '1,100,000' },
      { id: 'amount', label: 'Line requested', type: 'number', placeholder: '400,000' },
    ],
  },
  {
    id: 'btc-installment',
    title: 'Bitcoin on Installment',
    tagline: 'Buy BTC now. Pay over time.',
    apr: 'Lock price today',
    term: '3–24 mo',
    max: '$500,000',
    accent: '#FF9F0A',
    featured: true,
    installment: true,
    glyph: (
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9.5 7v10M9 10h5.5a2 2 0 010 4H9m0-4v4m6-4v4"/><path d="M4 20l16-16" opacity="0.35"/></svg>
    ),
  },
  {
    id: 'btc',
    title: 'Bitcoin-backed Loan',
    tagline: 'Borrow against your Bitcoin',
    apr: 'from 5.4%',
    term: 'Up to 50% LTV',
    max: '50% LTV',
    accent: '#FF9F0A',
    featured: true,
    glyph: (
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9.5 7v10M9 10h5.5a2 2 0 010 4H9m0-4v4m6-4v4"/></svg>
    ),
    fields: [
      { id: 'amount', label: 'Borrow amount', type: 'slider-btc' },
      { id: 'term', label: 'Term', type: 'select', options: ['6 months', '12 months', '24 months', '36 months'] },
      { id: 'disburse', label: 'Disburse to', type: 'select', options: ['USD Wallet (instant)', 'External bank account', 'Wire transfer'] },
    ],
  },
];

function LoanCard({ product, onClick }) {
  if (product.installment) {
    return (
      <button onClick={onClick} style={{
        gridColumn: '1 / -1',
        textAlign: 'left',
        background: 'linear-gradient(135deg, rgba(255,159,10,0.16) 0%, rgba(255,69,58,0.08) 100%)',
        border: '1px solid rgba(255,159,10,0.4)',
        borderRadius: 18, padding: 16,
        boxShadow: '0 0 40px rgba(255,159,10,0.2), inset 0 1px 0 rgba(255,255,255,0.08)',
        cursor: 'pointer', transition: 'transform 0.15s',
        display: 'flex', alignItems: 'center', gap: 14,
        position: 'relative', overflow: 'hidden',
      }}
      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={{
          width: 52, height: 52, borderRadius: 14,
          background: 'rgba(255,159,10,0.2)', border: '1px solid rgba(255,159,10,0.5)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#FF9F0A', flexShrink: 0,
        }}>{product.glyph}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 16, fontWeight: 600, color: '#fff', letterSpacing: '-0.01em' }}>{product.title}</div>
            <div style={{
              padding: '2px 7px', borderRadius: 100,
              background: 'rgba(255,159,10,0.2)', border: '1px solid rgba(255,159,10,0.4)',
              fontFamily: DASH_MONO, fontSize: 8, letterSpacing: '0.18em',
              color: '#FF9F0A', fontWeight: 700,
            }}>SIGNATURE</div>
          </div>
          <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.7)', lineHeight: 1.3, marginBottom: 6 }}>{product.tagline}</div>
          <div style={{ display: 'flex', gap: 10, fontSize: 10, fontFamily: DASH_MONO, color: 'rgba(245,245,247,0.6)' }}>
            <span><span style={{ color: '#FF9F0A', fontWeight: 700 }}>{product.apr}</span></span>
            <span>· {product.term}</span>
            <span>· up to {product.max}</span>
          </div>
        </div>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="rgba(245,245,247,0.5)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><path d="M9 6l6 6-6 6"/></svg>
      </button>
    );
  }
  const featured = product.featured;
  return (
    <button onClick={onClick} style={{
      textAlign: 'left',
      background: featured
        ? 'linear-gradient(135deg, rgba(255,159,10,0.12) 0%, rgba(255,69,58,0.06) 100%)'
        : 'linear-gradient(180deg, rgba(20,20,26,0.7) 0%, rgba(10,10,14,0.85) 100%)',
      border: featured ? '1px solid rgba(255,159,10,0.35)' : '1px solid rgba(255,255,255,0.06)',
      borderRadius: 18, padding: 14,
      boxShadow: featured ? '0 0 30px rgba(255,159,10,0.15), inset 0 1px 0 rgba(255,255,255,0.06)' : 'inset 0 1px 0 rgba(255,255,255,0.04)',
      cursor: 'pointer', transition: 'transform 0.15s, box-shadow 0.2s',
      display: 'flex', flexDirection: 'column', gap: 10,
      minHeight: 150,
      position: 'relative', overflow: 'hidden',
    }}
    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={{
        width: 44, height: 44, borderRadius: 12,
        background: `${product.accent}18`, border: `1px solid ${product.accent}40`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: product.accent,
      }}>{product.glyph}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: DASH_DISPLAY, fontSize: 15, fontWeight: 600, color: '#fff', letterSpacing: '-0.01em' }}>{product.title}</div>
        <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)', marginTop: 2, lineHeight: 1.3 }}>{product.tagline}</div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 8, borderTop: '1px solid rgba(255,255,255,0.05)' }}>
        <span style={{ fontFamily: DASH_MONO, fontSize: 10, fontWeight: 600, color: product.accent, letterSpacing: '0.04em' }}>{product.apr}</span>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="rgba(245,245,247,0.4)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l6 6-6 6"/></svg>
      </div>
      {featured && (
        <div style={{
          position: 'absolute', top: 10, right: 10,
          padding: '3px 8px', borderRadius: 100,
          background: 'rgba(255,159,10,0.15)', border: '1px solid rgba(255,159,10,0.35)',
          fontFamily: DASH_MONO, fontSize: 8, letterSpacing: '0.18em',
          color: '#FF9F0A', fontWeight: 700, textTransform: 'uppercase',
        }}>BTC</div>
      )}
    </button>
  );
}

function InstallmentHero({ product, btcPrice, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', textAlign: 'left', cursor: 'pointer',
      background: 'radial-gradient(ellipse at top right, rgba(255,159,10,0.22) 0%, rgba(255,69,58,0.08) 40%, rgba(10,10,14,0.6) 100%)',
      border: '1px solid rgba(255,159,10,0.4)',
      borderRadius: 20, padding: 20, marginBottom: 16,
      boxShadow: '0 0 50px rgba(255,159,10,0.2), inset 0 1px 0 rgba(255,255,255,0.08)',
      position: 'relative', overflow: 'hidden', transition: 'transform 0.15s',
    }}
    onMouseDown={e => e.currentTarget.style.transform = 'scale(0.99)'}
    onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
    onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}>
      <div style={{ position: 'absolute', right: -30, top: -20, fontSize: 200, fontFamily: DASH_DISPLAY, fontWeight: 800, color: 'rgba(255,159,10,0.06)', lineHeight: 1, pointerEvents: 'none' }}>₿</div>

      <div style={{ position: 'relative', zIndex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 10 }}>
          <div style={{ padding: '3px 8px', borderRadius: 100, background: 'rgba(255,159,10,0.2)', border: '1px solid rgba(255,159,10,0.45)', fontFamily: DASH_MONO, fontSize: 8, letterSpacing: '0.2em', color: '#FF9F0A', fontWeight: 700 }}>SIGNATURE PRODUCT</div>
        </div>
        <div style={{ fontFamily: DASH_DISPLAY, fontSize: 26, fontWeight: 700, color: '#fff', letterSpacing: '-0.03em', lineHeight: 1.1, marginBottom: 6, maxWidth: '85%' }}>
          Bitcoin on Installment.
        </div>
        <div style={{ fontSize: 13, color: 'rgba(245,245,247,0.75)', lineHeight: 1.5, marginBottom: 14, maxWidth: '88%' }}>
          Lock in today's price. Pay monthly. Your Bitcoin is held in segregated, bankruptcy-remote custody until your plan is paid off.
        </div>

        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 14 }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.15em', color: 'rgba(245,245,247,0.5)', textTransform: 'uppercase', marginBottom: 4 }}>Locked price today</div>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 32, fontWeight: 700, color: '#FF9F0A', letterSpacing: '-0.02em', lineHeight: 1 }}>{fmtUsd(btcPrice, { decimals: 0 })}</div>
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', borderRadius: 100, background: 'rgba(0,0,0,0.4)', border: '1px solid rgba(255,255,255,0.12)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'rgba(255,159,10,0.2)', border: '1px solid rgba(255,159,10,0.5)', color: '#FF9F0A', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9.5 7v10M9 10h5.5a2 2 0 010 4H9m0-4v4m6-4v4"/></svg>
            </div>
            <span style={{ fontFamily: DASH_DISPLAY, fontSize: 14, fontWeight: 600, color: '#fff' }}>Start an installment plan</span>
          </div>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#FF9F0A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l6 6-6 6"/></svg>
        </div>
      </div>
    </button>
  );
}

const LOAN_GROUPS = [
  { id: 'btc',      label: 'Bitcoin-backed',    ids: ['btc'] },
  { id: 'property', label: 'Home & real estate', ids: ['home', 'heloc'] },
  { id: 'auto',     label: 'Auto',               ids: ['auto', 'car-equity'] },
  { id: 'personal', label: 'Personal',           ids: ['personal'] },
];

function LoansTab({ btcPrice }) {
  const [applying, setApplying] = React.useState(null);
  const [managing, setManaging] = React.useState(false);
  const [activeLoans, setActiveLoans] = React.useState(INITIAL_ACTIVE_LOANS);

  const installment = LOAN_PRODUCTS.find(p => p.installment);
  const otherProducts = LOAN_PRODUCTS.filter(p => !p.installment);

  const totalBalance = activeLoans.reduce((s, l) => s + l.balance, 0);
  const nextDate = activeLoans[0]?.nextDate || '—';

  const addInstallmentPlan = (plan) => {
    setActiveLoans(prev => [plan, ...prev]);
  };

  return (
    <DashScreen modals={<>
      {applying && applying.installment && <InstallmentFlow product={applying} btcPrice={btcPrice} onClose={() => setApplying(null)} onCreate={addInstallmentPlan} onOpenManage={() => { setApplying(null); setManaging(true); }} />}
      {applying && !applying.installment && <LoanApplyModal product={applying} btcPrice={btcPrice} onClose={() => setApplying(null)} />}
      {managing && <ManageLoansModal btcPrice={btcPrice} loans={activeLoans} onClose={() => setManaging(false)} />}
    </>}>
      <DashHeader subtitle="Loans" title="Borrow with BTC Now" />

      <div style={{ padding: '0 20px 16px' }}>
        {/* Hero: Bitcoin Installment */}
        {installment && <InstallmentHero product={installment} btcPrice={btcPrice} onClick={() => setApplying(installment)} />}

        {/* Active loans — compact strip */}
        <button onClick={() => setManaging(true)} style={{
          width: '100%', textAlign: 'left', cursor: 'pointer',
          padding: '12px 14px', marginBottom: 18, borderRadius: 14,
          background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(255,159,10,0.12)', border: '1px solid rgba(255,159,10,0.3)', color: '#FF9F0A', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18M7 15h2"/></svg>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.18em', color: 'rgba(245,245,247,0.5)', textTransform: 'uppercase', marginBottom: 2 }}>Your active loans</div>
            <div style={{ fontSize: 14, fontWeight: 600, color: '#fff' }}>{fmtUsd(totalBalance, { decimals: 0 })} · {activeLoans.length} {activeLoans.length === 1 ? 'loan' : 'loans'}</div>
          </div>
          <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)', fontFamily: DASH_MONO, textAlign: 'right', flexShrink: 0 }}>
            Manage
            <div style={{ fontSize: 9, marginTop: 2, color: 'rgba(245,245,247,0.4)' }}>Next {nextDate.split(',')[0]}</div>
          </div>
        </button>

        {/* Grouped catalogue */}
        {LOAN_GROUPS.map(g => {
          const products = otherProducts.filter(p => g.ids.includes(p.id));
          if (products.length === 0) return null;
          return (
            <div key={g.id} style={{ marginBottom: 16 }}>
              <div style={{ marginBottom: 8, paddingLeft: 4, fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.5)', textTransform: 'uppercase' }}>{g.label}</div>
              <div style={{ borderRadius: 14, background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.05)', overflow: 'hidden' }}>
                {products.map((p, i) => (
                  <button key={p.id} onClick={() => setApplying(p)} style={{
                    width: '100%', padding: '14px', cursor: 'pointer', textAlign: 'left',
                    background: 'transparent', border: 'none',
                    borderBottom: i === products.length - 1 ? 'none' : '1px solid rgba(255,255,255,0.05)',
                    display: 'flex', alignItems: 'center', gap: 12,
                  }}>
                    <div style={{ width: 40, height: 40, borderRadius: 10, background: `${p.accent}18`, border: `1px solid ${p.accent}40`, color: p.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      {React.cloneElement(p.glyph, { width: 22, height: 22 })}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: '#fff' }}>{p.title}</div>
                      <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)', marginTop: 2 }}>{p.tagline}</div>
                    </div>
                    <div style={{ textAlign: 'right', flexShrink: 0 }}>
                      <div style={{ fontSize: 12, fontWeight: 600, color: p.accent, fontFamily: DASH_MONO }}>{p.apr}</div>
                      <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.5)', fontFamily: DASH_MONO, marginTop: 1 }}>{p.term}</div>
                    </div>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="rgba(245,245,247,0.35)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><path d="M9 6l6 6-6 6"/></svg>
                  </button>
                ))}
              </div>
            </div>
          );
        })}

        <div style={{ textAlign: 'center', fontFamily: DASH_MONO, fontSize: 9, color: 'rgba(245,245,247,0.3)', letterSpacing: '0.15em', marginTop: 18, textTransform: 'uppercase' }}>
          All rates shown are soft-pull estimates
        </div>
      </div>

    </DashScreen>
  );
}

// ═══ MANAGE LOANS MODAL ═══════════════════════════════════════════════════
const INITIAL_ACTIVE_LOANS = [
  {
    id: 'home-1',
    title: 'Home Loan',
    subtitle: '30-yr fixed · 1410 Ocean Ave',
    accent: '#10B981',
    glyph: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 11l9-7 9 7v9a2 2 0 01-2 2h-4v-7h-6v7H5a2 2 0 01-2-2z"/></svg>
    ),
    balance: 218_400, original: 220_000, apr: 6.4,
    monthly: 1_377, nextDate: 'May 1, 2026',
    paidOff: 0.7, termLabel: '357 of 360 payments remaining',
    transactions: [
      { d: 'Apr 1', a: 1377, status: 'Paid' },
      { d: 'Mar 1', a: 1377, status: 'Paid' },
      { d: 'Feb 1', a: 1377, status: 'Paid' },
    ],
  },
  {
    id: 'btc-1',
    title: 'Bitcoin-backed Loan',
    subtitle: '12 mo · 0.9 BTC collateral',
    accent: '#FF9F0A',
    glyph: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9.5 7v10M9 10h5.5a2 2 0 010 4H9m0-4v4m6-4v4"/></svg>
    ),
    balance: 61_600, original: 62_000, apr: 5.4,
    monthly: 279, nextDate: 'May 1, 2026',
    paidOff: 5, termLabel: '11 of 12 payments remaining',
    ltv: 32.4, liquidation: 47_820,
    transactions: [
      { d: 'Apr 1', a: 279, status: 'Paid' },
      { d: 'Mar 15', a: 400, status: 'Extra principal' },
      { d: 'Mar 1', a: 279, status: 'Paid' },
    ],
  },
];

function ManageLoansModal({ btcPrice, loans, onClose }) {
  const [active, setActive] = React.useState(null); // loan id or null
  const currentLoan = loans.find(l => l.id === active);

  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 45,
      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%', maxHeight: '92%', overflowY: 'auto',
        background: '#0a0a0f',
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        border: '1px solid rgba(255,255,255,0.08)', borderBottom: 'none',
        padding: '14px 20px 28px',
        animation: 'loanSheetIn 0.35s cubic-bezier(0.16, 1, 0.3, 1)',
      }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.15)', margin: '0 auto 16px' }}/>

        {!active ? (
          <>
            <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: '#FF9F0A', textTransform: 'uppercase', fontWeight: 700, marginBottom: 6 }}>Active Loans</div>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 26, fontWeight: 600, color: '#fff', letterSpacing: '-0.03em', marginBottom: 4 }}>Manage your loans</div>
            <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.55)', marginBottom: 18 }}>Tap a loan to view details, make a payment, or pay off early.</div>

            {loans.map(l => (
              <button key={l.id} onClick={() => setActive(l.id)} style={{
                width: '100%', padding: 14, borderRadius: 16, marginBottom: 10,
                background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)',
                cursor: 'pointer', textAlign: 'left',
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{ width: 40, height: 40, borderRadius: 10, background: `${l.accent}18`, border: `1px solid ${l.accent}40`, color: l.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{l.glyph}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: '#fff' }}>{l.title}</div>
                    {l.kind === 'installment' && <div style={{ padding: '1px 5px', borderRadius: 4, background: 'rgba(255,159,10,0.15)', border: '1px solid rgba(255,159,10,0.3)', fontFamily: DASH_MONO, fontSize: 7, letterSpacing: '0.1em', color: '#FF9F0A', fontWeight: 700 }}>NEW</div>}
                  </div>
                  <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{l.subtitle}</div>
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#fff', fontFamily: DASH_MONO }}>{fmtUsd(l.balance, { decimals: 0 })}</div>
                  <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.5)', fontFamily: DASH_MONO, marginTop: 1 }}>{l.kind === 'installment' ? `${l.btcAmount.toFixed(4)} ₿` : `${l.apr}% APR`}</div>
                </div>
              </button>
            ))}

            <div style={{ marginTop: 6, padding: 14, borderRadius: 14, background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.05)' }}>
              <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.65)', lineHeight: 1.5 }}>
                Total monthly payment <span style={{ color: '#fff', fontFamily: DASH_MONO, fontWeight: 700 }}>{fmtUsd(loans.reduce((s, l) => s + l.monthly, 0), { decimals: 0 })}</span> auto-debits from your USD wallet on the 1st.
              </div>
            </div>
          </>
        ) : currentLoan?.kind === 'installment' ? (
          <InstallmentDetail loan={currentLoan} onBack={() => setActive(null)} />
        ) : (
          <LoanDetail loan={currentLoan} onBack={() => setActive(null)} />
        )}
      </div>
    </div>
  );
}

function LoanDetail({ loan, onBack }) {
  const [action, setAction] = React.useState(null); // 'pay' | 'payoff' | null
  const [payAmount, setPayAmount] = React.useState(loan.monthly);
  const [success, setSuccess] = React.useState(null);

  if (success) {
    return (
      <div style={{ textAlign: 'center', padding: '28px 0 10px' }}>
        <div style={{
          width: 72, height: 72, borderRadius: '50%',
          background: 'rgba(16,185,129,0.15)', border: '2px solid rgba(16,185,129,0.5)',
          margin: '0 auto 16px', display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 0 32px rgba(16,185,129,0.35)',
          animation: 'readyPop 0.5s cubic-bezier(0.16, 1, 0.3, 1)',
        }}>
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#10B981" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
        </div>
        <div style={{ fontFamily: DASH_DISPLAY, fontSize: 24, fontWeight: 600, color: '#fff', letterSpacing: '-0.03em', marginBottom: 6 }}>{success.title}</div>
        <div style={{ fontSize: 13, color: 'rgba(245,245,247,0.55)', maxWidth: 280, margin: '0 auto 22px' }}>{success.sub}</div>
        <button onClick={onBack} style={{
          width: '100%', padding: 16, borderRadius: 100,
          background: DASH_GRADIENT, border: 'none', color: '#000',
          fontSize: 14, fontWeight: 600, cursor: 'pointer',
        }}>Done</button>
      </div>
    );
  }

  return (
    <div>
      <button onClick={onBack} style={{
        display: 'flex', alignItems: 'center', gap: 6, padding: 0,
        background: 'transparent', border: 'none', color: 'rgba(245,245,247,0.65)',
        fontSize: 12, cursor: 'pointer', marginBottom: 12,
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
        All loans
      </button>

      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
        <div style={{ width: 44, height: 44, borderRadius: 12, background: `${loan.accent}18`, border: `1px solid ${loan.accent}40`, color: loan.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{loan.glyph}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: DASH_DISPLAY, fontSize: 19, fontWeight: 600, color: '#fff', letterSpacing: '-0.02em' }}>{loan.title}</div>
          <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)' }}>{loan.subtitle}</div>
        </div>
      </div>

      {/* Balance + progress */}
      <div style={{ padding: 16, borderRadius: 14, background: `linear-gradient(135deg, ${loan.accent}12, rgba(255,255,255,0.02))`, border: `1px solid ${loan.accent}30`, marginBottom: 14 }}>
        <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: loan.accent, textTransform: 'uppercase', marginBottom: 4 }}>Remaining balance</div>
        <div style={{ fontFamily: DASH_DISPLAY, fontSize: 32, fontWeight: 700, color: '#fff', letterSpacing: '-0.03em', lineHeight: 1 }}>{fmtUsd(loan.balance, { decimals: 0 })}</div>
        <div style={{ height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.06)', marginTop: 14, overflow: 'hidden' }}>
          <div style={{ height: '100%', width: `${loan.paidOff}%`, background: loan.accent, borderRadius: 2 }}/>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 10, color: 'rgba(245,245,247,0.55)', fontFamily: DASH_MONO }}>
          <span>{loan.paidOff}% paid off</span>
          <span>of {fmtUsd(loan.original, { decimals: 0 })}</span>
        </div>
      </div>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14 }}>
        {[
          { l: 'Next payment', v: fmtUsd(loan.monthly, { decimals: 0 }) },
          { l: 'Due', v: loan.nextDate },
          { l: 'APR', v: `${loan.apr}%` },
          { l: 'Status', v: loan.termLabel.split(' of ')[0] + ' left', small: true },
          ...(loan.ltv ? [{ l: 'LTV', v: `${loan.ltv}%`, c: '#10B981' }] : []),
          ...(loan.liquidation ? [{ l: 'Liq. price', v: fmtUsd(loan.liquidation, { decimals: 0 }), c: '#EF4444' }] : []),
        ].map((f, i) => (
          <div key={i} style={{ padding: '10px 12px', borderRadius: 10, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
            <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.15em', color: 'rgba(245,245,247,0.5)', textTransform: 'uppercase', marginBottom: 3 }}>{f.l}</div>
            <div style={{ fontSize: f.small ? 11 : 13, fontWeight: 600, color: f.c || '#fff', fontFamily: DASH_MONO }}>{f.v}</div>
          </div>
        ))}
      </div>

      {/* Actions */}
      {!action && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14 }}>
          <button onClick={() => setAction('pay')} style={{
            padding: 14, borderRadius: 100, background: DASH_GRADIENT, border: 'none', color: '#000',
            fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: DASH_DISPLAY,
          }}>Make a payment</button>
          <button onClick={() => setAction('payoff')} style={{
            padding: 14, borderRadius: 100,
            background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.12)',
            color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer',
          }}>Pay off early</button>
        </div>
      )}

      {action === 'pay' && (
        <div style={{ padding: 14, borderRadius: 14, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)', marginBottom: 14 }}>
          <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.55)', textTransform: 'uppercase', marginBottom: 8 }}>Payment amount</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <span style={{ fontSize: 20, color: 'rgba(245,245,247,0.4)', fontFamily: DASH_MONO }}>$</span>
            <input type="number" value={payAmount} onChange={e => setPayAmount(Number(e.target.value))} style={{ flex: 1, padding: '12px 14px', borderRadius: 10, background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', color: '#fff', fontSize: 18, fontFamily: DASH_MONO, fontWeight: 600, boxSizing: 'border-box', outline: 'none' }}/>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6, marginBottom: 12 }}>
            {[{ l: 'Minimum', v: loan.monthly }, { l: 'x2', v: loan.monthly * 2 }, { l: 'x3', v: loan.monthly * 3 }].map(q => (
              <button key={q.l} onClick={() => setPayAmount(q.v)} style={{ padding: 9, borderRadius: 100, background: payAmount === q.v ? 'rgba(255,159,10,0.15)' : 'rgba(255,255,255,0.04)', border: payAmount === q.v ? '1px solid rgba(255,159,10,0.5)' : '1px solid rgba(255,255,255,0.08)', color: payAmount === q.v ? '#FF9F0A' : 'rgba(245,245,247,0.7)', fontSize: 10, fontWeight: 600, fontFamily: DASH_MONO, cursor: 'pointer' }}>{q.l} · {fmtUsd(q.v, { decimals: 0 })}</button>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={() => setAction(null)} style={{ flex: 1, padding: 13, borderRadius: 100, background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Cancel</button>
            <button onClick={() => setSuccess({ title: 'Payment sent', sub: `${fmtUsd(payAmount, { decimals: 0 })} applied to your ${loan.title.toLowerCase()}. New balance ${fmtUsd(loan.balance - payAmount, { decimals: 0 })}.` })} style={{ flex: 2, padding: 13, borderRadius: 100, background: DASH_GRADIENT, border: 'none', color: '#000', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Pay {fmtUsd(payAmount, { decimals: 0 })}</button>
          </div>
        </div>
      )}

      {action === 'payoff' && (
        <div style={{ padding: 14, borderRadius: 14, background: 'rgba(239,68,68,0.06)', border: '1px solid rgba(239,68,68,0.25)', marginBottom: 14 }}>
          <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: '#EF4444', textTransform: 'uppercase', marginBottom: 6 }}>Full Payoff</div>
          <div style={{ fontSize: 13, color: 'rgba(245,245,247,0.75)', lineHeight: 1.5, marginBottom: 12 }}>
            Close this loan today with a single payment. {loan.id === 'btc-1' ? 'Your BTC collateral will be released to your wallet immediately.' : 'No early-payoff penalty.'}
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 12px', borderRadius: 10, background: 'rgba(255,255,255,0.04)', marginBottom: 12 }}>
            <span style={{ fontSize: 12, color: 'rgba(245,245,247,0.6)' }}>Payoff amount</span>
            <span style={{ fontSize: 15, fontWeight: 700, color: '#fff', fontFamily: DASH_MONO }}>{fmtUsd(loan.balance, { decimals: 0 })}</span>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={() => setAction(null)} style={{ flex: 1, padding: 13, borderRadius: 100, background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Cancel</button>
            <button onClick={() => setSuccess({ title: 'Loan paid off', sub: loan.id === 'btc-1' ? `${loan.title} closed. 0.9 BTC released back to your wallet.` : `${loan.title} closed in full. You're debt-free on this loan.` })} style={{ flex: 2, padding: 13, borderRadius: 100, background: 'linear-gradient(135deg, #EF4444, #F59E0B)', border: 'none', color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Pay off in full</button>
          </div>
        </div>
      )}

      {/* Transactions */}
      <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.45)', textTransform: 'uppercase', paddingLeft: 4, marginBottom: 8 }}>Recent activity</div>
      <div style={{ borderRadius: 14, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)', overflow: 'hidden', marginBottom: 14 }}>
        {loan.transactions.map((t, i) => (
          <div key={i} style={{ padding: '11px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: i === loan.transactions.length - 1 ? 'none' : '1px solid rgba(255,255,255,0.04)' }}>
            <div>
              <div style={{ fontSize: 12, color: '#fff', fontWeight: 500 }}>{t.status}</div>
              <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.5)', fontFamily: DASH_MONO, marginTop: 2 }}>{t.d}</div>
            </div>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#fff', fontFamily: DASH_MONO }}>{fmtUsd(t.a, { decimals: 0 })}</div>
          </div>
        ))}
      </div>

      <div style={{ textAlign: 'center', fontSize: 10, color: 'rgba(245,245,247,0.35)', fontFamily: DASH_MONO, letterSpacing: '0.1em' }}>
        Auto-debit from USD wallet · 1st of each month
      </div>
    </div>
  );
}

// ═══ APPLY MODAL ══════════════════════════════════════════════════════════
function LoanApplyModal({ product, btcPrice, onClose }) {
  const [stage, setStage] = React.useState('form'); // 'form' | 'review' | 'approved'
  const [vals, setVals] = React.useState({});
  const [btcBorrow, setBtcBorrow] = React.useState(120_000);
  const btcCollateral = MOCK.btc * btcPrice;
  const maxBtcLoan = btcCollateral * 0.5;
  const currentLtv = (btcBorrow / btcCollateral) * 100;
  const liquidation = btcPrice * (btcBorrow / (btcCollateral * 0.85));

  const setVal = (k, v) => setVals(x => ({ ...x, [k]: v }));

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 40,
      background: 'rgba(0,0,0,0.75)', backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'flex-end',
      animation: 'loanOverlayIn 0.25s ease',
    }}>
      <div style={{
        width: '100%', maxHeight: '92%', overflowY: 'auto',
        background: '#0a0a0f',
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        border: '1px solid rgba(255,255,255,0.08)', borderBottom: 'none',
        padding: '14px 20px 28px',
        animation: 'loanSheetIn 0.35s cubic-bezier(0.16, 1, 0.3, 1)',
      }}>
        {/* handle */}
        <div style={{ width: 36, height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.15)', margin: '0 auto 16px' }}/>

        {/* header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12,
            background: `${product.accent}18`, border: `1px solid ${product.accent}40`,
            color: product.accent,
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>{product.glyph}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 19, fontWeight: 600, color: '#fff', letterSpacing: '-0.02em' }}>{product.title}</div>
            <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)' }}>{product.apr} · {product.term} · up to {product.max}</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',
          }}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
          </button>
        </div>

        {stage === 'form' && (
          <div>
            {/* What we know about you */}
            <div style={{
              padding: 14, borderRadius: 14, marginBottom: 16,
              background: 'rgba(16,185,129,0.05)', border: '1px solid rgba(16,185,129,0.2)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <div style={{ width: 22, height: 22, borderRadius: '50%', background: 'rgba(16,185,129,0.2)', border: '1px solid #10B981', color: '#10B981', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
                </div>
                <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.18em', color: '#10B981', fontWeight: 700, textTransform: 'uppercase' }}>What we already know</div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 10 }}>
                {[
                  { l: 'FICO', v: '812' },
                  { l: 'Income', v: '$41,000/mo' },
                  { l: 'DTI', v: '15.1%' },
                  { l: 'ID', v: 'Verified' },
                ].map(x => (
                  <div key={x.l} style={{ padding: '8px 10px', borderRadius: 10, background: 'rgba(255,255,255,0.03)' }}>
                    <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.15em', color: 'rgba(245,245,247,0.5)', textTransform: 'uppercase', marginBottom: 2 }}>{x.l}</div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: '#fff', fontFamily: DASH_MONO }}>{x.v}</div>
                  </div>
                ))}
              </div>
              <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.65)', lineHeight: 1.5, marginBottom: 10 }}>
                We're reusing your verification — no hard pull, no re-uploads. Want to update anything before applying?
              </div>
              <button onClick={() => { onClose(); setTimeout(() => window.dispatchEvent(new CustomEvent('__openCreditIncome')), 250); }} style={{
                width: '100%', padding: '10px', borderRadius: 100,
                background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)',
                color: '#fff', fontSize: 12, fontWeight: 500, cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              }}>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 20h9M16.5 3.5a2.12 2.12 0 013 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
                Review or update my info
              </button>
            </div>
            {product.fields.map(field => (
              <div key={field.id} style={{ marginBottom: 12 }}>
                <label style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.18em', color: 'rgba(245,245,247,0.5)', textTransform: 'uppercase', marginBottom: 6, display: 'block' }}>
                  {field.label}
                </label>
                {field.type === 'select' ? (
                  <select value={vals[field.id] || field.options[0]} onChange={e => setVal(field.id, e.target.value)} style={{
                    width: '100%', padding: '14px', borderRadius: 12,
                    background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)',
                    color: '#fff', fontSize: 14, fontFamily: 'Inter, sans-serif', outline: 'none',
                    appearance: 'none', WebkitAppearance: 'none',
                    backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23888' stroke-width='2.5'><path d='M6 9l6 6 6-6'/></svg>")`,
                    backgroundRepeat: 'no-repeat', backgroundPosition: 'right 14px center', backgroundSize: '12px',
                  }}>
                    {field.options.map(o => <option key={o} value={o} style={{ background: '#0a0a0f', color: '#fff' }}>{o}</option>)}
                  </select>
                ) : field.type === 'slider-btc' ? (
                  <div style={{ padding: '14px 16px', borderRadius: 12, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
                      <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)' }}>Borrow amount</div>
                      <div style={{ fontFamily: DASH_MONO, fontSize: 16, fontWeight: 700, color: '#FF9F0A' }}>{fmtUsd(btcBorrow, { decimals: 0 })}</div>
                    </div>
                    <input type="range" min="10000" max={maxBtcLoan} step="1000" value={btcBorrow} onChange={e => setBtcBorrow(+e.target.value)} style={{ width: '100%', accentColor: '#FF9F0A' }}/>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10, fontSize: 10, color: 'rgba(245,245,247,0.5)', fontFamily: DASH_MONO }}>
                      <div>LTV <span style={{ color: currentLtv > 40 ? '#F59E0B' : '#10B981', fontWeight: 700 }}>{currentLtv.toFixed(1)}%</span></div>
                      <div>Liq. <span style={{ color: '#EF4444', fontWeight: 700 }}>{fmtUsd(liquidation, { decimals: 0 })}</span></div>
                      <div>Collateral <span style={{ color: '#fff', fontWeight: 700 }}>{MOCK.btc.toFixed(3)} BTC</span></div>
                    </div>
                  </div>
                ) : (
                  <input
                    type={field.type === 'number' ? 'text' : field.type}
                    inputMode={field.type === 'number' ? 'decimal' : 'text'}
                    placeholder={field.placeholder}
                    value={vals[field.id] || ''}
                    onChange={e => setVal(field.id, e.target.value)}
                    style={{
                      width: '100%', padding: '14px', borderRadius: 12,
                      background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)',
                      color: '#fff', fontSize: 14, outline: 'none', boxSizing: 'border-box',
                      fontFamily: 'Inter, sans-serif',
                    }}
                  />
                )}
              </div>
            ))}
            <div style={{ marginTop: 18 }}>
              <button onClick={() => setStage('review')} style={{
                width: '100%', padding: 16, borderRadius: 100,
                background: DASH_GRADIENT, border: 'none', color: '#000',
                fontSize: 14, fontWeight: 600, cursor: 'pointer',
                boxShadow: '0 0 24px rgba(255,159,10,0.35)',
              }}>Review offer →</button>
              <div style={{ textAlign: 'center', fontSize: 10, color: 'rgba(245,245,247,0.4)', marginTop: 10, fontFamily: DASH_MONO, letterSpacing: '0.08em' }}>
                SOFT PULL · WON'T AFFECT YOUR SCORE
              </div>
            </div>
          </div>
        )}

        {stage === 'review' && (
          <div>
            <div style={{ padding: 16, borderRadius: 14, background: 'rgba(16,185,129,0.08)', border: '1px solid rgba(16,185,129,0.25)', marginBottom: 14 }}>
              <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: '#10B981', textTransform: 'uppercase', marginBottom: 6 }}>Pre-qualified</div>
              <div style={{ fontFamily: DASH_DISPLAY, fontSize: 28, fontWeight: 600, color: '#fff', letterSpacing: '-0.03em', lineHeight: 1 }}>{product.apr}</div>
              <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.65)', marginTop: 4 }}>Estimated payment · auto-debit from USD wallet</div>
            </div>
            <ReviewRow label="Product" value={product.title}/>
            {product.id === 'btc' ? (
              <>
                <ReviewRow label="Amount" value={fmtUsd(btcBorrow, { decimals: 0 })}/>
                <ReviewRow label="Collateral" value={`${MOCK.btc.toFixed(4)} BTC`}/>
                <ReviewRow label="LTV" value={`${currentLtv.toFixed(1)}%`}/>
                <ReviewRow label="Liquidation" value={fmtUsd(liquidation, { decimals: 0 })} isLast/>
              </>
            ) : product.fields.map(f => (
              <ReviewRow key={f.id} label={f.label} value={vals[f.id] || (f.type === 'select' ? f.options[0] : '—')}/>
            ))}
            <div style={{ marginTop: 18, display: 'flex', gap: 10 }}>
              <button onClick={() => setStage('form')} style={{
                flex: 1, padding: 16, borderRadius: 100,
                background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.1)',
                color: '#fff', fontSize: 14, fontWeight: 600, cursor: 'pointer',
              }}>Edit</button>
              <button onClick={() => setStage('approved')} style={{
                flex: 2, padding: 16, borderRadius: 100,
                background: DASH_GRADIENT, border: 'none', color: '#000',
                fontSize: 14, fontWeight: 600, cursor: 'pointer',
                boxShadow: '0 0 24px rgba(255,159,10,0.35)',
              }}>Accept offer</button>
            </div>
          </div>
        )}

        {stage === 'approved' && (
          <div style={{ textAlign: 'center', padding: '20px 0 10px' }}>
            <div style={{
              width: 72, height: 72, borderRadius: '50%',
              background: 'rgba(16,185,129,0.15)', border: '2px solid rgba(16,185,129,0.5)',
              margin: '0 auto 16px',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 0 32px rgba(16,185,129,0.35)',
              animation: 'readyPop 0.5s cubic-bezier(0.16, 1, 0.3, 1)',
            }}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#10B981" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
            </div>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 24, fontWeight: 600, color: '#fff', letterSpacing: '-0.03em', marginBottom: 6 }}>You're approved.</div>
            <div style={{ fontSize: 13, color: 'rgba(245,245,247,0.55)', maxWidth: 280, margin: '0 auto 22px' }}>
              Funds will land in your USD wallet {product.id === 'btc' ? 'instantly' : 'within 1 business day'}.
            </div>
            <button onClick={onClose} style={{
              width: '100%', padding: 16, borderRadius: 100,
              background: DASH_GRADIENT, border: 'none', color: '#000',
              fontSize: 14, fontWeight: 600, cursor: 'pointer',
              boxShadow: '0 0 24px rgba(255,159,10,0.35)',
            }}>Done</button>
          </div>
        )}
      </div>

      <style>{`
        @keyframes loanOverlayIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes loanSheetIn { from { transform: translateY(100%); } to { transform: translateY(0); } }
      `}</style>
    </div>
  );
}

// ═══ INSTALLMENT DETAIL (for an active installment plan) ══════════════════
// ═══ FUNDING SOURCE PICKER ════════════════════════════════════════════════
const FUNDING_SOURCES = [
  { id: 'usd',    label: 'USD Wallet',      sub: 'Balance $4,283.19',        c: '#10B981',
    icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 6v12M9 9h4a2 2 0 010 4H9m0 0h5a2 2 0 010 4H9"/></svg> },
  { id: 'btc',    label: 'BTC Wallet',      sub: '0.4821 ₿ · auto-convert',    c: '#FF9F0A',
    icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9.5 7v10M9 10h5.5a2 2 0 010 4H9m0-4v4m6-4v4"/></svg> },
  { id: 'chase',  label: 'Chase ···4821',   sub: 'Checking · ACH 1–2 days',    c: '#3B82F6',
    icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="7" width="18" height="13" rx="1.5"/><path d="M3 11h18M7 16h3"/></svg> },
  { id: 'amex',   label: 'Amex ···1007',    sub: 'Platinum · instant',         c: '#A78BFA',
    icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/></svg> },
  { id: 'new',    label: 'Add new account', sub: 'Link a bank via Plaid',      c: 'rgba(245,245,247,0.55)', isNew: true,
    icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M5 12h14"/></svg> },
];

function FundingSourcePicker({ current, onSelect, onClose }) {
  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%', maxHeight: '80%', overflowY: 'auto',
        background: '#0a0a0f',
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        border: '1px solid rgba(255,255,255,0.08)', borderBottom: 'none',
        padding: '14px 20px 24px',
        animation: 'loanSheetIn 0.35s cubic-bezier(0.16, 1, 0.3, 1)',
      }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.15)', margin: '0 auto 16px' }}/>
        <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: '#FF9F0A', textTransform: 'uppercase', fontWeight: 700, marginBottom: 6 }}>Auto-pay source</div>
        <div style={{ fontFamily: DASH_DISPLAY, fontSize: 22, fontWeight: 600, color: '#fff', letterSpacing: '-0.03em', marginBottom: 4 }}>Change funding source</div>
        <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.55)', marginBottom: 16 }}>Your monthly payment will auto-debit from this account on the 1st.</div>

        <div style={{ borderRadius: 14, background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.06)', overflow: 'hidden' }}>
          {FUNDING_SOURCES.map((s, i, a) => {
            const isActive = s.label === current;
            return (
              <button key={s.id} onClick={() => onSelect(s.isNew ? 'New bank account' : s.label)} style={{
                width: '100%', padding: 14, background: 'transparent', border: 'none',
                borderBottom: i === a.length - 1 ? 'none' : '1px solid rgba(255,255,255,0.04)',
                display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer', textAlign: 'left',
              }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: `${s.c}18`, border: `1px solid ${s.c}40`, color: s.c, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{s.icon}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#fff' }}>{s.label}</div>
                  <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)', marginTop: 1 }}>{s.sub}</div>
                </div>
                {isActive ? (
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#10B981" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><path d="M20 6 9 17l-5-5"/></svg>
                ) : (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="rgba(245,245,247,0.35)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><path d="M9 6l6 6-6 6"/></svg>
                )}
              </button>
            );
          })}
        </div>

        <button onClick={onClose} style={{
          width: '100%', padding: 14, borderRadius: 100, marginTop: 14,
          background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.1)',
          color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer',
        }}>Cancel</button>
      </div>
    </div>
  );
}

function InstallmentDetail({ loan, onBack }) {
  const [copied, setCopied] = React.useState(false);
  const [payAmount, setPayAmount] = React.useState(loan.monthly);
  const [success, setSuccess] = React.useState(null);
  const [fundingSource, setFundingSource] = React.useState(loan.fundingSource);
  const [changingSource, setChangingSource] = React.useState(false);

  const copyAddr = () => {
    try {
      navigator.clipboard?.writeText(loan.walletAddress);
    } catch (e) { /* ignore — not allowed in some embeds */ }
    setCopied(true);
    setTimeout(() => setCopied(false), 1400);
  };

  if (success) {
    return (
      <div style={{ textAlign: 'center', padding: '28px 0 10px' }}>
        <div style={{
          width: 72, height: 72, borderRadius: '50%',
          background: 'rgba(16,185,129,0.15)', border: '2px solid rgba(16,185,129,0.5)',
          margin: '0 auto 16px', display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 0 32px rgba(16,185,129,0.35)',
          animation: 'readyPop 0.5s cubic-bezier(0.16, 1, 0.3, 1)',
        }}>
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#10B981" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
        </div>
        <div style={{ fontFamily: DASH_DISPLAY, fontSize: 24, fontWeight: 600, color: '#fff', letterSpacing: '-0.03em', marginBottom: 6 }}>{success.title}</div>
        <div style={{ fontSize: 13, color: 'rgba(245,245,247,0.55)', maxWidth: 280, margin: '0 auto 22px' }}>{success.sub}</div>
        <button onClick={onBack} style={{
          width: '100%', padding: 16, borderRadius: 100,
          background: DASH_GRADIENT, border: 'none', color: '#000',
          fontSize: 14, fontWeight: 600, cursor: 'pointer',
        }}>Done</button>
      </div>
    );
  }

  return (
    <div>
      <button onClick={onBack} style={{
        display: 'flex', alignItems: 'center', gap: 6, padding: 0,
        background: 'transparent', border: 'none', color: 'rgba(245,245,247,0.65)',
        fontSize: 12, cursor: 'pointer', marginBottom: 12,
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
        All loans
      </button>

      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
        <div style={{ width: 44, height: 44, borderRadius: 12, background: `${loan.accent}18`, border: `1px solid ${loan.accent}40`, color: loan.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{loan.glyph}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 19, fontWeight: 600, color: '#fff', letterSpacing: '-0.02em' }}>{loan.title}</div>
            <div style={{ padding: '2px 6px', borderRadius: 4, background: 'rgba(255,159,10,0.15)', border: '1px solid rgba(255,159,10,0.3)', fontFamily: DASH_MONO, fontSize: 8, letterSpacing: '0.1em', color: '#FF9F0A', fontWeight: 700 }}>ACTIVE</div>
          </div>
          <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)', fontFamily: DASH_MONO, marginTop: 2 }}>Plan #{loan.planId}</div>
        </div>
      </div>

      {/* Hero: BTC amount locked at price + wallet address */}
      <div style={{
        padding: 18, borderRadius: 18,
        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: 12,
      }}>
        <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: '#FF9F0A', textTransform: 'uppercase', fontWeight: 700, marginBottom: 8 }}>Total Bitcoin Purchased</div>
        <div style={{ fontFamily: DASH_DISPLAY, fontSize: 34, fontWeight: 700, color: '#fff', letterSpacing: '-0.03em', lineHeight: 1 }}>
          {loan.btcAmount.toFixed(6)} <span style={{ fontSize: 22, color: '#FF9F0A' }}>₿</span>
        </div>
        <div style={{ fontFamily: DASH_MONO, fontSize: 11, color: 'rgba(245,245,247,0.55)', marginTop: 6 }}>Locked at {fmtUsd(loan.lockedPrice, { decimals: 0 })} · {fmtUsd(loan.btcAmount * loan.lockedPrice, { decimals: 0 })} total</div>

        {/* Progress */}
        <div style={{ marginTop: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'rgba(245,245,247,0.55)', fontFamily: DASH_MONO, marginBottom: 6 }}>
            <span>{loan.paidOff.toFixed(0)}% paid</span>
            <span>{loan.btcAmount.toFixed(6)} ₿ in custody</span>
          </div>
          <div style={{ height: 6, borderRadius: 3, background: 'rgba(255,255,255,0.06)', overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${loan.paidOff}%`, background: '#FF9F0A', borderRadius: 3 }}/>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 10, color: 'rgba(245,245,247,0.45)', fontFamily: DASH_MONO }}>
            <span>{loan.paidOff}% paid</span>
            <span>{loan.termLabel}</span>
          </div>
        </div>

        {/* Wallet address — compact */}
        <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid rgba(255,159,10,0.18)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
            <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.18em', color: 'rgba(245,245,247,0.55)', textTransform: 'uppercase', fontWeight: 700 }}>Wallet address</div>
            <div style={{ fontFamily: DASH_MONO, fontSize: 8, color: '#10B981', letterSpacing: '0.1em', display: 'flex', alignItems: 'center', gap: 4 }}>
              <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#10B981' }}/>SEGREGATED
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ fontFamily: DASH_MONO, fontSize: 10.5, color: 'rgba(245,245,247,0.85)', wordBreak: 'break-all', flex: 1, lineHeight: 1.3 }}>
              {loan.walletAddress}
            </div>
            <button onClick={copyAddr} style={{ padding: '5px 9px', borderRadius: 6, background: copied ? 'rgba(16,185,129,0.15)' : 'rgba(255,255,255,0.06)', border: `1px solid ${copied ? 'rgba(16,185,129,0.4)' : 'rgba(255,255,255,0.1)'}`, color: copied ? '#10B981' : 'rgba(245,245,247,0.75)', fontSize: 9, fontWeight: 700, fontFamily: DASH_MONO, letterSpacing: '0.1em', cursor: 'pointer', flexShrink: 0 }}>{copied ? 'COPIED' : 'COPY'}</button>
          </div>
        </div>
      </div>

      {/* Open Amount + Next Payment */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 12 }}>
        <div style={{ padding: 12, borderRadius: 12, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
          <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.55)', marginBottom: 3 }}>Open Amount</div>
          <div style={{ fontFamily: DASH_DISPLAY, fontSize: 18, fontWeight: 600, color: '#fff', letterSpacing: '-0.02em' }}>{fmtUsd(loan.openAmount, { decimals: 0 })}</div>
          <div style={{ fontFamily: DASH_MONO, fontSize: 9, color: 'rgba(245,245,247,0.4)', marginTop: 2 }}>of {fmtUsd(loan.original, { decimals: 0 })}</div>
        </div>
        <div style={{ padding: 12, borderRadius: 12, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
          <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.55)', marginBottom: 3 }}>Next Payment</div>
          <div style={{ fontFamily: DASH_DISPLAY, fontSize: 18, fontWeight: 600, color: '#fff', letterSpacing: '-0.02em' }}>{fmtUsd(loan.monthly, { decimals: 0 })}</div>
          <div style={{ fontFamily: DASH_MONO, fontSize: 9, color: '#FF9F0A', marginTop: 2 }}>{loan.nextDate}</div>
        </div>
      </div>

      {/* Funding source */}
      <div style={{ padding: 12, borderRadius: 12, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)', marginBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.55)', marginBottom: 2 }}>Auto-pay source</div>
          <div style={{ fontSize: 13, color: '#fff', fontWeight: 600 }}>{fundingSource}</div>
        </div>
        <button onClick={() => setChangingSource(true)} style={{ padding: '6px 12px', borderRadius: 100, background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)', color: 'rgba(245,245,247,0.75)', fontSize: 11, fontWeight: 600, cursor: 'pointer' }}>Change</button>
      </div>

      {changingSource && (
        <FundingSourcePicker
          current={fundingSource}
          onSelect={(src) => { setFundingSource(src); setChangingSource(false); }}
          onClose={() => setChangingSource(false)}
        />
      )}

      {/* Pay amount input */}
      <div style={{ padding: 14, borderRadius: 14, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)', marginBottom: 10 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
          <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.18em', color: 'rgba(245,245,247,0.55)', textTransform: 'uppercase', fontWeight: 700 }}>Make a payment</div>
          <div style={{ display: 'flex', gap: 4 }}>
            {[
              { lbl: 'Minimum', val: loan.monthly },
              { lbl: '2×', val: loan.monthly * 2 },
              { lbl: 'Full', val: loan.openAmount },
            ].map(p => (
              <button key={p.lbl} onClick={() => setPayAmount(p.val)} style={{
                padding: '4px 8px', borderRadius: 6,
                background: payAmount === p.val ? 'rgba(255,159,10,0.18)' : 'rgba(255,255,255,0.04)',
                border: `1px solid ${payAmount === p.val ? 'rgba(255,159,10,0.4)' : 'rgba(255,255,255,0.08)'}`,
                color: payAmount === p.val ? '#FF9F0A' : 'rgba(245,245,247,0.7)',
                fontSize: 9, fontWeight: 600, fontFamily: DASH_MONO, letterSpacing: '0.05em', cursor: 'pointer',
              }}>{p.lbl}</button>
            ))}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
          <span style={{ fontFamily: DASH_DISPLAY, fontSize: 26, fontWeight: 700, color: 'rgba(245,245,247,0.55)' }}>$</span>
          <input
            type="text"
            inputMode="decimal"
            value={payAmount.toFixed(2)}
            onChange={e => {
              const cleaned = e.target.value.replace(/[^0-9.]/g, '');
              const n = Number(cleaned);
              if (!isNaN(n)) setPayAmount(Math.max(0, Math.min(loan.openAmount, n)));
            }}
            style={{
              flex: 1,
              background: 'transparent', border: 'none', outline: 'none',
              fontFamily: DASH_DISPLAY, fontSize: 26, fontWeight: 700,
              color: '#fff', letterSpacing: '-0.02em',
              width: '100%', padding: 0,
            }}
          />
        </div>
        <div style={{ fontFamily: DASH_MONO, fontSize: 10, color: 'rgba(245,245,247,0.45)', marginTop: 4 }}>
          Min {fmtUsd(loan.monthly, { decimals: 2 })} · BTC releases in full once paid off
        </div>
      </div>

      {/* Pay button */}
      <button
        disabled={payAmount < loan.monthly || payAmount > loan.openAmount}
        onClick={() => {
          setSuccess({
            title: payAmount >= loan.openAmount ? 'Plan paid off · BTC released' : 'Payment sent',
            sub: payAmount >= loan.openAmount
              ? `${fmtUsd(payAmount, { decimals: 2 })} paid · ${loan.btcAmount.toFixed(6)} ₿ released to your wallet. Plan #${loan.planId} is complete.`
              : `${fmtUsd(payAmount, { decimals: 2 })} paid · ${fmtUsd(loan.openAmount - payAmount, { decimals: 2 })} remaining. BTC releases once your plan is paid in full.`,
          });
        }}
        style={{
          width: '100%', padding: 14, borderRadius: 100,
          background: payAmount < loan.monthly || payAmount > loan.openAmount ? 'rgba(255,255,255,0.06)' : DASH_GRADIENT,
          border: 'none',
          color: payAmount < loan.monthly || payAmount > loan.openAmount ? 'rgba(245,245,247,0.35)' : '#000',
          fontSize: 14, fontWeight: 600, fontFamily: DASH_DISPLAY, cursor: payAmount < loan.monthly || payAmount > loan.openAmount ? 'not-allowed' : 'pointer',
          marginBottom: 14,
          boxShadow: payAmount < loan.monthly || payAmount > loan.openAmount ? 'none' : '0 0 20px rgba(255,159,10,0.3)',
        }}
      >
        {payAmount < loan.monthly ? `Minimum ${fmtUsd(loan.monthly, { decimals: 2 })}` : `Pay ${fmtUsd(payAmount, { decimals: 2 })} now`}
      </button>

      {/* Recent payments */}
      <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.5)', textTransform: 'uppercase', fontWeight: 700, marginBottom: 8, paddingLeft: 4 }}>Payment history</div>
      <div style={{ borderRadius: 12, background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.05)', overflow: 'hidden' }}>
        {loan.transactions.map((t, i) => (
          <div key={i} style={{ padding: '10px 12px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: i === loan.transactions.length - 1 ? 'none' : '1px solid rgba(255,255,255,0.04)' }}>
            <div>
              <div style={{ fontSize: 12, color: '#fff', fontWeight: 500 }}>{t.status}</div>
              <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.5)', fontFamily: DASH_MONO, marginTop: 1 }}>{t.d}</div>
            </div>
            <div style={{ fontSize: 12, fontWeight: 600, color: '#fff', fontFamily: DASH_MONO }}>{fmtUsd(t.a, { decimals: 0 })}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ═══ INSTALLMENT FLOW ═════════════════════════════════════════════════════
function InstallmentFlow({ product, btcPrice, onClose, onCreate, onOpenManage }) {
  const [step, setStep] = React.useState(0); // 0 calculate · 1 funding · 2 review · 3 first-payment · 4 done
  const [createdPlan, setCreatedPlan] = React.useState(null); // snapshot at creation time
  // btcnow.com model: user inputs BTC amount OR monthly payment amount, plus term (years).
  // APR is fixed 15% (10-18% range marketed).
  const APR = 0.15;
  const [inputMode, setInputMode] = React.useState('btc'); // 'btc' | 'payment'
  const [payDisplay, setPayDisplay] = React.useState('usd'); // 'usd' | 'btc'
  const [btc, setBtc] = React.useState(0.1); // user-chosen BTC amount
  const [months, setMonths] = React.useState(120); // term in months (10yr default)
  const [targetPayment, setTargetPayment] = React.useState(500); // USD/mo if inputMode === 'payment'
  const [funding, setFunding] = React.useState('usd');

  // amortized monthly payment = P * r / (1 - (1+r)^-n)
  const amort = (P, aprAnnual, n) => {
    const r = aprAnnual / 12;
    if (r === 0) return P / n;
    return P * r / (1 - Math.pow(1 + r, -n));
  };
  // inverse: principal from monthly payment
  const principalFromPayment = (pmt, aprAnnual, n) => {
    const r = aprAnnual / 12;
    if (r === 0) return pmt * n;
    return pmt * (1 - Math.pow(1 + r, -n)) / r;
  };

  // Derived numbers — depend on input mode
  const principal = inputMode === 'btc'
    ? btc * btcPrice
    : principalFromPayment(targetPayment, APR, months);
  const btcAmount = inputMode === 'btc' ? btc : principal / btcPrice;
  const monthly = inputMode === 'btc' ? amort(principal, APR, months) : targetPayment;
  const usd = principal;
  const totalPaid = monthly * months;

  const today = new Date();
  const schedule = Array.from({ length: months }, (_, i) => {
    const d = new Date(today.getFullYear(), today.getMonth() + i + 1, 1);
    return { idx: i + 1, date: d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }), btc: btcAmount / months };
  });

  const stepLabels = ['Calculate plan', 'Funding', 'Review', 'First payment'];

  const termYears = [1, 2, 3, 5, 7, 10];

  return (
    <div onClick={step === 0 ? onClose : undefined} style={{
      position: 'absolute', inset: 0, zIndex: 50,
      background: 'rgba(0,0,0,0.8)', 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',
        padding: '14px 20px 28px',
        animation: 'loanSheetIn 0.35s cubic-bezier(0.16, 1, 0.3, 1)',
      }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.15)', margin: '0 auto 16px' }}/>

        {/* Progress */}
        <div style={{ display: 'flex', gap: 4, marginBottom: 16 }}>
          {stepLabels.map((_, i) => (
            <div key={i} style={{ flex: 1, height: 3, borderRadius: 2, background: i <= step ? '#FF9F0A' : 'rgba(255,255,255,0.08)', transition: 'background 0.3s' }}/>
          ))}
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(255,159,10,0.18)', border: '1px solid rgba(255,159,10,0.4)', color: '#FF9F0A', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9.5 7v10M9 10h5.5a2 2 0 010 4H9m0-4v4m6-4v4"/></svg>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.2em', color: '#FF9F0A', textTransform: 'uppercase', fontWeight: 700 }}>Bitcoin on Installment · Step {step + 1} of 4</div>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 20, fontWeight: 600, color: '#fff', letterSpacing: '-0.02em' }}>{stepLabels[step]}</div>
          </div>
        </div>

        {step === 0 && (
          <>
            <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.6)', marginBottom: 16, lineHeight: 1.5 }}>
              Type in either field — the other updates automatically. Price locks at <span style={{ color: '#FF9F0A', fontFamily: DASH_MONO, fontWeight: 700 }}>{fmtUsd(btcPrice, { decimals: 0 })}</span>/BTC.
            </div>

            {/* YOU BUY — editable BTC amount */}
            <div style={{
              padding: 16, borderRadius: 16, marginBottom: 10,
              background: inputMode === 'btc' ? 'linear-gradient(135deg, rgba(255,159,10,0.15), rgba(255,69,58,0.04))' : 'rgba(255,255,255,0.03)',
              border: inputMode === 'btc' ? '1px solid rgba(255,159,10,0.4)' : '1px solid rgba(255,255,255,0.08)',
              transition: 'background 0.2s, border-color 0.2s',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: inputMode === 'btc' ? '#FF9F0A' : 'rgba(245,245,247,0.55)', textTransform: 'uppercase', fontWeight: 700 }}>You buy</div>
                <div style={{ fontFamily: DASH_MONO, fontSize: 10, color: 'rgba(245,245,247,0.55)', display: 'flex', alignItems: 'center', gap: 5 }}>
                  <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#10B981' }}/>Current Spot Price: {fmtUsd(btcPrice, { decimals: 0 })}
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <input
                  type="text"
                  inputMode="decimal"
                  value={inputMode === 'btc' ? btc : btcAmount.toFixed(6)}
                  onFocus={() => setInputMode('btc')}
                  onChange={e => {
                    const v = e.target.value.replace(/[^0-9.]/g, '');
                    setInputMode('btc');
                    setBtc(v === '' ? 0 : Number(v));
                  }}
                  style={{
                    flex: 1, minWidth: 0,
                    background: 'transparent', border: 'none', outline: 'none',
                    fontFamily: DASH_DISPLAY, fontSize: 36, fontWeight: 700, color: '#fff',
                    letterSpacing: '-0.04em', lineHeight: 1, padding: 0,
                  }}
                />
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 14px', borderRadius: 100, background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)', fontFamily: DASH_MONO, fontSize: 13, fontWeight: 700, color: '#fff', flexShrink: 0 }}>
                  <span style={{ color: '#FF9F0A', fontSize: 15 }}>₿</span>BTC
                </div>
              </div>

            </div>

            {/* TERM — inline dropdown between the two panels */}
            <div style={{ display: 'flex', justifyContent: 'center', margin: '-6px 0 -6px', position: 'relative', zIndex: 2 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 14px', borderRadius: 100, background: '#0a0a0f', border: '1px solid rgba(255,255,255,0.1)', boxShadow: '0 4px 12px rgba(0,0,0,0.4)' }}>
                <div style={{ fontFamily: DASH_MONO, fontSize: 10, color: 'rgba(245,245,247,0.6)', letterSpacing: '0.15em', textTransform: 'uppercase', fontWeight: 700 }}>Term</div>
                <div style={{ position: 'relative' }}>
                  <select
                    value={months}
                    onChange={e => setMonths(Number(e.target.value))}
                    style={{
                      appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none',
                      background: 'rgba(255,159,10,0.12)',
                      border: '1px solid rgba(255,159,10,0.4)',
                      color: '#FF9F0A',
                      fontFamily: DASH_MONO, fontSize: 12, fontWeight: 700,
                      padding: '6px 28px 6px 12px', borderRadius: 100, cursor: 'pointer',
                      outline: 'none',
                    }}
                  >
                    {termYears.map(y => (
                      <option key={y} value={y * 12} style={{ background: '#0a0a0f', color: '#fff' }}>{y} {y === 1 ? 'year' : 'years'}</option>
                    ))}
                  </select>
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#FF9F0A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }}><path d="M6 9l6 6 6-6"/></svg>
                </div>
              </div>
            </div>

            {/* MONTHLY PAYMENT — editable USD */}
            <div style={{
              padding: 16, borderRadius: 16, marginTop: 10, marginBottom: 20,
              background: inputMode === 'payment' ? 'linear-gradient(135deg, rgba(255,159,10,0.15), rgba(255,69,58,0.04))' : 'rgba(255,255,255,0.03)',
              border: inputMode === 'payment' ? '1px solid rgba(255,159,10,0.4)' : '1px solid rgba(255,255,255,0.08)',
              transition: 'background 0.2s, border-color 0.2s',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: inputMode === 'payment' ? '#FF9F0A' : 'rgba(245,245,247,0.55)', textTransform: 'uppercase', fontWeight: 700 }}>Monthly payment</div>
                <div style={{ fontFamily: DASH_MONO, fontSize: 10, color: 'rgba(245,245,247,0.55)' }}>BTC Now Installment Price: {fmtUsd(totalPaid, { decimals: 0 })}</div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <input
                  type="text"
                  inputMode="decimal"
                  value={inputMode === 'payment' ? targetPayment : monthly.toFixed(2)}
                  onFocus={() => setInputMode('payment')}
                  onChange={e => {
                    const v = e.target.value.replace(/[^0-9.]/g, '');
                    setInputMode('payment');
                    setTargetPayment(v === '' ? 0 : Number(v));
                  }}
                  style={{
                    flex: 1, minWidth: 0,
                    background: 'transparent', border: 'none', outline: 'none',
                    fontFamily: DASH_DISPLAY, fontSize: 36, fontWeight: 700, color: '#fff',
                    letterSpacing: '-0.04em', lineHeight: 1, padding: 0,
                  }}
                />
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 14px', borderRadius: 100, background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)', fontFamily: DASH_MONO, fontSize: 13, fontWeight: 700, color: '#fff', flexShrink: 0 }}>
                  <span style={{ color: '#10B981', fontSize: 15 }}>$</span>USD
                </div>
              </div>
            </div>

            <button onClick={() => setStep(1)} style={{ width: '100%', padding: 15, borderRadius: 100, background: DASH_GRADIENT, border: 'none', color: '#000', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: DASH_DISPLAY, boxShadow: '0 0 24px rgba(255,159,10,0.35)' }}>Create plan</button>
            <div style={{ textAlign: 'center', fontFamily: DASH_MONO, fontSize: 9, color: 'rgba(245,245,247,0.4)', letterSpacing: '0.15em', marginTop: 12, textTransform: 'uppercase' }}>Subject to approval · Soft pull only</div>
          </>
        )}

        {step === 1 && (
          <>
            <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.6)', marginBottom: 16 }}>Where should we auto-debit {fmtUsd(monthly, { decimals: 0 })} each month?</div>
            <div style={{ display: 'grid', gap: 8, marginBottom: 18 }}>
              {[
                { id: 'usd', l: 'USD Wallet', s: 'Balance: $128,420 · no fee', icon: '$' },
                { id: 'bank', l: 'Chase ···4821', s: 'Linked checking · no fee', icon: '🏦' },
                { id: 'addbank', l: 'Add bank account', s: 'Link via Plaid · instant verification', icon: '+' },
              ].map(o => (
                <button key={o.id} onClick={() => setFunding(o.id)} style={{
                  padding: 14, borderRadius: 14, textAlign: 'left', cursor: 'pointer',
                  background: funding === o.id ? 'rgba(255,159,10,0.12)' : 'rgba(255,255,255,0.03)',
                  border: funding === o.id ? '1px solid rgba(255,159,10,0.5)' : '1px solid rgba(255,255,255,0.08)',
                  display: 'flex', alignItems: 'center', gap: 12,
                }}>
                  <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(255,255,255,0.06)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, color: '#fff', flexShrink: 0 }}>{o.icon}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: '#fff' }}>{o.l}</div>
                    <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)', marginTop: 2 }}>{o.s}</div>
                  </div>
                  {funding === o.id && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#FF9F0A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>}
                </button>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => setStep(0)} style={{ flex: 1, padding: 14, borderRadius: 100, background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Back</button>
              <button onClick={() => setStep(2)} style={{ flex: 2, padding: 14, borderRadius: 100, background: DASH_GRADIENT, border: 'none', color: '#000', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: DASH_DISPLAY }}>Review plan</button>
            </div>
          </>
        )}

        {step === 2 && (
          <>
            <div style={{ padding: 16, borderRadius: 14, background: 'linear-gradient(135deg, rgba(255,159,10,0.15), rgba(255,69,58,0.05))', border: '1px solid rgba(255,159,10,0.35)', marginBottom: 14 }}>
              <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: '#FF9F0A', textTransform: 'uppercase', marginBottom: 6 }}>Price locked</div>
              <div style={{ fontFamily: DASH_DISPLAY, fontSize: 30, fontWeight: 700, color: '#fff', letterSpacing: '-0.03em', lineHeight: 1 }}>{btcAmount.toFixed(6)} BTC</div>
              <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.7)', marginTop: 4 }}>@ {fmtUsd(btcPrice, { decimals: 0 })} per BTC · today's rate</div>
            </div>

            <ReviewRow label="Current spot price" value={fmtUsd(btcPrice, { decimals: 0 })}/>
            <ReviewRow label="Term" value={`${months / 12} ${months === 12 ? 'year' : 'years'} · ${months} payments`}/>
            <ReviewRow label="Monthly payment" value={fmtUsd(monthly, { decimals: 0 })}/>
            <ReviewRow label="BTC Now Price" value={fmtUsd(totalPaid, { decimals: 0 })}/>
            <ReviewRow label="Funding" value={funding === 'usd' ? 'USD Wallet' : funding === 'bank' ? 'Chase ···4821' : 'New bank account'}/>
            <ReviewRow label="First payment" value="Today" isLast/>

            <div style={{ marginTop: 14, padding: 12, borderRadius: 12, background: 'rgba(16,185,129,0.06)', border: '1px solid rgba(16,185,129,0.2)', display: 'flex', gap: 10 }}>
              <div style={{ width: 20, height: 20, borderRadius: '50%', background: 'rgba(16,185,129,0.2)', color: '#10B981', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 }}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
              </div>
              <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.75)', lineHeight: 1.5 }}>
                Your {btcAmount.toFixed(6)} BTC is held in a segregated custody account in a fully bankruptcy-remote structure until all payments have been made. Your BTC is released to your wallet once the plan is paid off.
              </div>
            </div>

            <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
              <button onClick={() => setStep(1)} style={{ flex: 1, padding: 14, borderRadius: 100, background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Edit</button>
              <button onClick={() => setStep(3)} style={{ flex: 2, padding: 14, borderRadius: 100, background: DASH_GRADIENT, border: 'none', color: '#000', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: DASH_DISPLAY, boxShadow: '0 0 24px rgba(255,159,10,0.35)' }}>Lock price & continue</button>
            </div>
          </>
        )}

        {step === 3 && (
          <>
            <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.6)', marginBottom: 14 }}>Make your first payment to activate your plan. We'll auto-debit the rest on the 1st of each month.</div>
            <div style={{ padding: 18, borderRadius: 16, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)', marginBottom: 14, textAlign: 'center' }}>
              <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.55)', textTransform: 'uppercase', marginBottom: 8 }}>Payment 1 of {months}</div>
              <div style={{ fontFamily: DASH_DISPLAY, fontSize: 44, fontWeight: 700, color: '#fff', letterSpacing: '-0.04em', lineHeight: 1 }}>{fmtUsd(monthly, { decimals: 0 })}</div>
              <div style={{ fontFamily: DASH_MONO, fontSize: 11, color: '#FF9F0A', marginTop: 8 }}>BTC releases in full once all {months} payments are made</div>
            </div>

            {/* Mini schedule */}
            <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.45)', textTransform: 'uppercase', paddingLeft: 4, marginBottom: 8 }}>Upcoming payments</div>
            <div style={{ borderRadius: 14, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)', overflow: 'hidden', marginBottom: 14, maxHeight: 180, overflowY: 'auto' }}>
              {schedule.slice(0, 4).map((s, i) => (
                <div key={i} style={{ padding: '10px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: i === 3 ? 'none' : '1px solid rgba(255,255,255,0.04)' }}>
                  <div>
                    <div style={{ fontSize: 12, color: '#fff', fontWeight: 500 }}>Payment {s.idx}</div>
                    <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.5)', fontFamily: DASH_MONO, marginTop: 1 }}>{s.date}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: '#fff', fontFamily: DASH_MONO }}>{fmtUsd(monthly, { decimals: 0 })}</div>
                    <div style={{ fontSize: 9, color: '#FF9F0A', fontFamily: DASH_MONO, marginTop: 1 }}>+{s.btc.toFixed(6)} ₿</div>
                  </div>
                </div>
              ))}
              {months > 4 && <div style={{ padding: '8px 14px', fontSize: 10, color: 'rgba(245,245,247,0.45)', fontFamily: DASH_MONO, textAlign: 'center' }}>+ {months - 4} more payments</div>}
            </div>

            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => setStep(2)} style={{ flex: 1, padding: 14, borderRadius: 100, background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Back</button>
              <button onClick={() => {
                // Create the installment loan and add it to the active loans list
                const walletAddr = 'bc1q' + Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 8);
                const planId = 'IN-' + String(Date.now()).slice(-6);
                const plan = {
                  id: 'install-' + Date.now(),
                  kind: 'installment',
                  planId,
                  title: 'Bitcoin on Installment',
                  subtitle: `${months / 12}yr · ${btcAmount.toFixed(4)} ₿ · locked at ${fmtUsd(btcPrice, { decimals: 0 })}`,
                  accent: '#FF9F0A',
                  glyph: (
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9.5 7v10M9 10h5.5a2 2 0 010 4H9m0-4v4m6-4v4"/></svg>
                  ),
                  balance: totalPaid - monthly,
                  original: totalPaid,
                  openAmount: totalPaid - monthly,
                  btcAmount,
                  lockedPrice: btcPrice,
                  walletAddress: walletAddr,
                  monthly,
                  nextDate: schedule[1]?.date || schedule[0].date,
                  paidOff: Math.round((1 / months) * 100 * 10) / 10,
                  termLabel: `${months - 1} of ${months} payments remaining`,
                  fundingSource: funding === 'usd' ? 'USD Wallet' : funding === 'bank' ? 'Chase ···4821' : 'New bank account',
                  transactions: [
                    { d: new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' }), a: monthly, status: 'First payment' },
                  ],
                };
                setCreatedPlan(plan);
                onCreate && onCreate(plan);
                setStep(4);
              }} style={{ flex: 2, padding: 14, borderRadius: 100, background: DASH_GRADIENT, border: 'none', color: '#000', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: DASH_DISPLAY, boxShadow: '0 0 24px rgba(255,159,10,0.35)' }}>Pay {fmtUsd(monthly, { decimals: 0 })} now</button>
            </div>
            <div style={{ textAlign: 'center', fontSize: 10, color: 'rgba(245,245,247,0.4)', marginTop: 10, fontFamily: DASH_MONO, letterSpacing: '0.08em' }}>SECURED BY BTC COLLATERAL · NO HARD CREDIT PULL</div>
          </>
        )}

        {step === 4 && (
          <div style={{ padding: '4px 0 10px' }}>
            {/* Success header */}
            <div style={{ textAlign: 'center', marginBottom: 18 }}>
              <div style={{
                width: 64, height: 64, borderRadius: '50%',
                background: 'rgba(16,185,129,0.15)', border: '2px solid rgba(16,185,129,0.5)',
                margin: '0 auto 14px', display: 'flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: '0 0 40px rgba(16,185,129,0.3)',
                animation: 'readyPop 0.5s cubic-bezier(0.16, 1, 0.3, 1)',
              }}>
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#10B981" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
              </div>
              <div style={{ fontFamily: DASH_DISPLAY, fontSize: 22, fontWeight: 600, color: '#fff', letterSpacing: '-0.02em', marginBottom: 4 }}>Plan created</div>
              <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.55)' }}>BTC locked at {fmtUsd(createdPlan?.lockedPrice ?? btcPrice, { decimals: 0 })} · Plan #{createdPlan?.planId ?? 'IN------'}</div>
            </div>

            {/* Plan overview card */}
            <div style={{
              padding: 18, borderRadius: 18,
              background: 'linear-gradient(135deg, rgba(255,159,10,0.1), rgba(255,69,58,0.02))',
              border: '1px solid rgba(255,159,10,0.3)',
              marginBottom: 14,
            }}>
              <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.2em', color: '#FF9F0A', textTransform: 'uppercase', fontWeight: 700, marginBottom: 10 }}>Installment plan overview</div>

              {/* Bitcoin Amount — hero */}
              <div style={{ marginBottom: 16 }}>
                <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.6)', marginBottom: 4 }}>Bitcoin Amount</div>
                <div style={{ fontFamily: DASH_DISPLAY, fontSize: 32, fontWeight: 700, color: '#fff', letterSpacing: '-0.03em', lineHeight: 1 }}>
                  {(createdPlan?.btcAmount ?? btcAmount).toFixed(6)} <span style={{ fontSize: 20, color: '#FF9F0A' }}>₿</span>
                </div>
                <div style={{ fontFamily: DASH_MONO, fontSize: 11, color: 'rgba(245,245,247,0.5)', marginTop: 4 }}>≈ {fmtUsd((createdPlan?.btcAmount ?? btcAmount) * (createdPlan?.lockedPrice ?? btcPrice), { decimals: 0 })} locked at {fmtUsd(createdPlan?.lockedPrice ?? btcPrice, { decimals: 0 })}</div>
              </div>

              <div style={{ height: 1, background: 'rgba(255,255,255,0.08)', marginBottom: 14 }}/>

              {/* Open Amount + Next Payment — 2-up */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 14 }}>
                <div>
                  <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.55)', marginBottom: 3 }}>Open Amount</div>
                  <div style={{ fontFamily: DASH_DISPLAY, fontSize: 18, fontWeight: 600, color: '#fff', letterSpacing: '-0.02em' }}>{fmtUsd(createdPlan?.openAmount ?? (totalPaid - monthly), { decimals: 0 })}</div>
                  <div style={{ fontFamily: DASH_MONO, fontSize: 9, color: 'rgba(245,245,247,0.4)', marginTop: 2 }}>of {fmtUsd(createdPlan?.original ?? totalPaid, { decimals: 0 })} total</div>
                </div>
                <div>
                  <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.55)', marginBottom: 3 }}>Next Payment Due</div>
                  <div style={{ fontFamily: DASH_DISPLAY, fontSize: 18, fontWeight: 600, color: '#fff', letterSpacing: '-0.02em' }}>{fmtUsd(createdPlan?.monthly ?? monthly, { decimals: 0 })}</div>
                  <div style={{ fontFamily: DASH_MONO, fontSize: 9, color: '#FF9F0A', marginTop: 2 }}>{createdPlan?.nextDate ?? schedule[0].date}</div>
                </div>
              </div>

              {/* Wallet address */}
              <div style={{ padding: 12, borderRadius: 12, background: 'rgba(0,0,0,0.3)', border: '1px solid rgba(255,255,255,0.06)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                  <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.55)' }}>Bitcoin Wallet Address</div>
                  <div style={{ fontFamily: DASH_MONO, fontSize: 8, color: '#10B981', letterSpacing: '0.1em', display: 'flex', alignItems: 'center', gap: 4 }}>
                    <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#10B981' }}/>SEGREGATED CUSTODY
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ fontFamily: DASH_MONO, fontSize: 11, color: '#fff', wordBreak: 'break-all', flex: 1, lineHeight: 1.3 }}>
                    {createdPlan?.walletAddress ?? 'bc1q7x9v2m4k8n3p5r6t1y2u3i4o5p6a7s8d9f0g1h'}
                  </div>
                  <button style={{ padding: '5px 9px', borderRadius: 6, background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)', color: 'rgba(245,245,247,0.7)', fontSize: 9, fontWeight: 600, fontFamily: DASH_MONO, cursor: 'pointer', flexShrink: 0 }}>COPY</button>
                </div>
              </div>
            </div>

            {/* Payment schedule preview */}
            <div style={{ padding: 14, borderRadius: 14, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)', marginBottom: 18 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.5)', textTransform: 'uppercase', fontWeight: 700 }}>Upcoming payments</div>
                <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.45)', fontFamily: DASH_MONO }}>1 of {months} paid</div>
              </div>
              {schedule.slice(0, 3).map((s, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 0', borderBottom: i < 2 ? '1px solid rgba(255,255,255,0.04)' : 'none' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ width: 5, height: 5, borderRadius: '50%', background: i === 0 ? '#FF9F0A' : 'rgba(255,255,255,0.2)' }}/>
                    <span style={{ fontSize: 11, color: 'rgba(245,245,247,0.75)', fontFamily: DASH_MONO }}>{s.date}</span>
                  </div>
                  <span style={{ fontSize: 11, color: '#fff', fontFamily: DASH_MONO, fontWeight: 600 }}>{fmtUsd(monthly, { decimals: 0 })}</span>
                </div>
              ))}
              {months > 3 && <div style={{ textAlign: 'center', fontSize: 10, color: 'rgba(245,245,247,0.4)', fontFamily: DASH_MONO, marginTop: 8 }}>+ {months - 3} more scheduled</div>}
            </div>

            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={onClose} style={{
                flex: 1, padding: 15, borderRadius: 100,
                background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.1)',
                color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer',
              }}>Done</button>
              <button onClick={() => onOpenManage && onOpenManage()} style={{
                flex: 2, padding: 15, borderRadius: 100,
                background: DASH_GRADIENT, border: 'none', color: '#000',
                fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: DASH_DISPLAY,
                boxShadow: '0 0 24px rgba(255,159,10,0.35)',
              }}>View plan</button>
            </div>
          </div>
        )}

        <style>{`input[type=range]::-webkit-slider-thumb { background: #FF9F0A; }`}</style>
      </div>
    </div>
  );
}

function ReviewRow({ label, value, isLast }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: '12px 0',
      borderBottom: isLast ? 'none' : '1px solid rgba(255,255,255,0.05)',
    }}>
      <span style={{ fontSize: 12, color: 'rgba(245,245,247,0.55)' }}>{label}</span>
      <span style={{ fontSize: 13, fontWeight: 600, color: '#fff', fontFamily: DASH_MONO, textAlign: 'right', maxWidth: '60%' }}>{value}</span>
    </div>
  );
}

Object.assign(window, { LoansTab });
