// dash-credit-income.jsx — Credit & Income verification module

const FICO_MOCK = {
  score: 812,
  range: 'Exceptional',
  bureau: 'Experian',
  pulledAt: 'Apr 18, 2025',
  nextPull: 'Jul 18, 2025',
  factors: [
    { l: 'Payment history',         v: 'Excellent · 100%' },
    { l: 'Credit utilization',      v: '8% · Low' },
    { l: 'Length of history',       v: '14 yr 3 mo' },
    { l: 'Credit mix',              v: '6 accounts · Good' },
    { l: 'Recent inquiries',        v: '1 in last 12 mo' },
  ],
  tradelines: [
    { id: 'tl1', name: 'Chase Sapphire Reserve',   kind: 'Revolving', opened: '2019', balance: 2_142, limit: 30_000, status: 'Current', onTime: 72 },
    { id: 'tl2', name: 'Amex Platinum',             kind: 'Charge',    opened: '2021', balance: 8_430, limit: null,   status: 'Current', onTime: 48 },
    { id: 'tl3', name: 'Wells Fargo Mortgage',      kind: 'Mortgage',  opened: '2022', balance: 612_400, limit: 720_000, status: 'Current', onTime: 36 },
    { id: 'tl4', name: 'Tesla Financing',           kind: 'Auto',      opened: '2023', balance: 48_210, limit: 72_000, status: 'Current', onTime: 24 },
    { id: 'tl5', name: 'SoFi Personal Line',        kind: 'Revolving', opened: '2020', balance: 0,     limit: 25_000, status: 'Closed · User', onTime: 60 },
    { id: 'tl6', name: 'Capital One Venture X',     kind: 'Revolving', opened: '2018', balance: 412,   limit: 20_000, status: 'Current', onTime: 84 },
  ],
};

const INCOME_MOCK = {
  connected: [
    { id: 'payroll', name: 'Kairos Ventures',   kind: 'Payroll',  sub: 'W-2 · ADP',           amount: 28_750, cadence: 'monthly',  status: 'verified' },
    { id: 'chase',   name: 'Chase Checking',    kind: 'Bank',     sub: '•••• 4485 · Plaid',   amount: 8_400,  cadence: 'avg dep.', status: 'verified' },
    { id: 'wf',      name: 'Wells Fargo Savings', kind: 'Bank',   sub: '•••• 8821 · Plaid',   amount: 1_200,  cadence: 'interest', status: 'verified' },
    { id: 'schwab',  name: 'Schwab Brokerage',  kind: 'Investment', sub: '•••• 9042 · Plaid', amount: 3_650,  cadence: 'dividends',status: 'verified' },
  ],
  expenses: [
    { l: 'Mortgage · Wells Fargo',  v: 4_240 },
    { l: 'Auto · Tesla Financing',  v: 820 },
    { l: 'Insurance (home+auto)',   v: 612 },
    { l: 'Utilities · avg',         v: 385 },
    { l: 'Credit cards · minimums', v: 210 },
    { l: 'Subscriptions',           v: 184 },
  ],
};

const CI_ICON = (name, color = 'currentColor') => {
  const p = { width: 18, height: 18, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'payroll':    return <svg {...p}><rect x="2" y="6" width="20" height="12" rx="2"/><circle cx="12" cy="12" r="3"/><path d="M6 10v4M18 10v4"/></svg>;
    case 'bank':       return <svg {...p}><path d="M3 10l9-6 9 6M5 10v8M19 10v8M9 10v8M15 10v8M3 21h18"/></svg>;
    case 'investment': return <svg {...p}><path d="M3 17l6-6 4 4 8-8M14 7h7v7"/></svg>;
    case 'exchange':   return <svg {...p}><path d="M7 10h10M7 14h10"/><circle cx="12" cy="12" r="9"/></svg>;
    case 'check':      return <svg {...p}><path d="M20 6 9 17l-5-5"/></svg>;
    case 'plus':       return <svg {...p}><path d="M12 5v14M5 12h14"/></svg>;
    case 'flag':       return <svg {...p}><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><path d="M4 22V15"/></svg>;
    default: return null;
  }
};

// ═══ FICO gauge ═══════════════════════════════════════════════════════════
function FicoGauge({ score }) {
  // map 300-850 to a semicircle arc
  const pct = Math.max(0, Math.min(1, (score - 300) / 550));
  const angle = -90 + pct * 180; // deg
  const r = 70;
  const cx = 100, cy = 100;
  const endX = cx + r * Math.cos((angle) * Math.PI / 180);
  const endY = cy + r * Math.sin((angle) * Math.PI / 180);
  const startX = cx - r;
  const startY = cy;
  const largeArc = pct > 0.5 ? 1 : 0;
  const colorFor = (s) => s >= 800 ? '#10B981' : s >= 740 ? '#FF9F0A' : s >= 670 ? '#FBBF24' : s >= 580 ? '#F97316' : '#EF4444';
  const color = colorFor(score);

  return (
    <div style={{ position: 'relative', width: '100%', display: 'flex', justifyContent: 'center' }}>
      <svg width="200" height="120" viewBox="0 0 200 120">
        <defs>
          <linearGradient id="ficoGrad" x1="0" x2="1">
            <stop offset="0" stopColor="#EF4444"/>
            <stop offset="0.35" stopColor="#F97316"/>
            <stop offset="0.6" stopColor="#FBBF24"/>
            <stop offset="0.85" stopColor="#FF9F0A"/>
            <stop offset="1" stopColor="#10B981"/>
          </linearGradient>
        </defs>
        {/* background arc */}
        <path d={`M ${cx - r} ${cy} A ${r} ${r} 0 0 1 ${cx + r} ${cy}`} fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="10" strokeLinecap="round"/>
        {/* progress arc */}
        <path d={`M ${startX} ${startY} A ${r} ${r} 0 ${largeArc} 1 ${endX} ${endY}`} fill="none" stroke="url(#ficoGrad)" strokeWidth="10" strokeLinecap="round"/>
        {/* score dot */}
        <circle cx={endX} cy={endY} r="7" fill={color} stroke="#050507" strokeWidth="2"/>
      </svg>
      <div style={{ position: 'absolute', top: 36, textAlign: 'center' }}>
        <div style={{ fontFamily: DASH_DISPLAY, fontSize: 48, fontWeight: 700, color: '#fff', letterSpacing: '-0.04em', lineHeight: 1 }}>{score}</div>
        <div style={{ fontFamily: DASH_MONO, fontSize: 10, color, letterSpacing: '0.15em', marginTop: 4, fontWeight: 700 }}>EXCEPTIONAL</div>
      </div>
    </div>
  );
}

// ═══ Connect Plaid flow (simulated) ══════════════════════════════════════
function ConnectSheet({ onClose, onConnect }) {
  const [step, setStep] = React.useState('pick'); // pick → connecting → done
  const [picked, setPicked] = React.useState(null);

  const banks = [
    { id: 'chase', name: 'Chase', color: '#117ACA' },
    { id: 'wf',    name: 'Wells Fargo', color: '#CD1409' },
    { id: 'boa',   name: 'Bank of America', color: '#E31837' },
    { id: 'citi',  name: 'Citi', color: '#056DAE' },
    { id: 'schwab',name: 'Schwab', color: '#00A0DF' },
    { id: 'fidel', name: 'Fidelity', color: '#529022' },
    { id: 'cb',    name: 'Coinbase', color: '#0052FF' },
    { id: 'kraken',name: 'Kraken', color: '#5741D9' },
  ];

  React.useEffect(() => {
    if (step === 'connecting') {
      const t = setTimeout(() => setStep('done'), 1800);
      return () => clearTimeout(t);
    }
    if (step === 'done') {
      const t = setTimeout(() => { onConnect(picked); onClose(); }, 900);
      return () => clearTimeout(t);
    }
  }, [step]);

  return (
    <div onClick={step === 'pick' ? onClose : undefined} style={{
      position: 'absolute', inset: 0, zIndex: 70,
      background: 'rgba(0,0,0,0.8)', backdropFilter: 'blur(10px)',
      display: 'flex', alignItems: 'flex-end',
      animation: 'waOverlayIn 0.25s ease',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', background: '#0a0a0f',
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        border: '1px solid rgba(255,255,255,0.08)', borderBottom: 'none',
        padding: '14px 18px 28px',
        animation: 'waSheetIn 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 14px' }}/>

        {step === 'pick' && (
          <>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 22, fontWeight: 600, color: '#fff', letterSpacing: '-0.03em', marginBottom: 4 }}>Connect an account</div>
            <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.55)', marginBottom: 16 }}>256-bit encrypted · read-only · powered by Plaid</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {banks.map(b => (
                <button key={b.id} onClick={() => { setPicked(b); setStep('connecting'); }} style={{
                  padding: '14px 12px', borderRadius: 14, cursor: 'pointer',
                  background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)',
                  display: 'flex', alignItems: 'center', gap: 10, textAlign: 'left',
                }}>
                  <div style={{ width: 28, height: 28, borderRadius: 8, background: b.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: DASH_DISPLAY, fontWeight: 700, color: '#fff', fontSize: 11, flexShrink: 0 }}>{b.name[0]}</div>
                  <div style={{ fontSize: 12, fontWeight: 500, color: '#fff' }}>{b.name}</div>
                </button>
              ))}
            </div>
            <div style={{ fontFamily: DASH_MONO, fontSize: 9, color: 'rgba(245,245,247,0.4)', letterSpacing: '0.15em', textAlign: 'center', marginTop: 16 }}>
              WE NEVER STORE YOUR CREDENTIALS
            </div>
          </>
        )}

        {step === 'connecting' && (
          <div style={{ padding: '32px 16px', textAlign: 'center' }}>
            <div style={{ width: 64, height: 64, borderRadius: 18, background: picked.color, margin: '0 auto 18px', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: DASH_DISPLAY, fontWeight: 700, color: '#fff', fontSize: 26, animation: 'pulseGlow 1.2s ease-in-out infinite' }}>{picked.name[0]}</div>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 18, fontWeight: 600, color: '#fff', marginBottom: 4 }}>Connecting to {picked.name}…</div>
            <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.55)' }}>Pulling 24 months of transactions</div>
            <div style={{ width: '100%', height: 3, borderRadius: 2, background: 'rgba(255,255,255,0.08)', marginTop: 18, overflow: 'hidden' }}>
              <div style={{ width: '40%', height: '100%', background: DASH_GRADIENT, animation: 'ciProgress 1.6s ease-in-out infinite' }}/>
            </div>
          </div>
        )}

        {step === 'done' && (
          <div style={{ padding: '32px 16px', textAlign: 'center' }}>
            <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'rgba(16,185,129,0.15)', border: '2px solid #10B981', margin: '0 auto 18px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#10B981' }}>
              <svg width="32" height="32" 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_DISPLAY, fontSize: 18, fontWeight: 600, color: '#fff' }}>{picked.name} connected</div>
          </div>
        )}

        <style>{`
          @keyframes ciProgress { 0% { transform: translateX(-100%); } 100% { transform: translateX(350%); } }
          @keyframes pulseGlow { 0%,100% { box-shadow: 0 0 0 0 rgba(255,159,10,0.4); } 50% { box-shadow: 0 0 0 12px rgba(255,159,10,0); } }
        `}</style>
      </div>
    </div>
  );
}

// ═══ Dispute sheet ════════════════════════════════════════════════════════
function DisputeSheet({ tradeline, onClose }) {
  const [reason, setReason] = React.useState(null);
  const [note, setNote] = React.useState('');
  const [signed, setSigned] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);

  const reasons = [
    'Balance is wrong',
    'Account is not mine',
    'Already paid / closed',
    'Status reported wrong',
    'Outdated information',
    'Duplicate entry',
    'Other',
  ];

  if (submitted) {
    return (
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, zIndex: 80,
        background: 'rgba(0,0,0,0.85)', backdropFilter: 'blur(10px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <div onClick={e => e.stopPropagation()} style={{ padding: 28, textAlign: 'center', maxWidth: 300 }}>
          <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'rgba(16,185,129,0.15)', border: '2px solid #10B981', margin: '0 auto 18px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#10B981' }}>
            <svg width="32" height="32" 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_DISPLAY, fontSize: 20, fontWeight: 600, color: '#fff', marginBottom: 6 }}>Dispute filed</div>
          <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.6)', lineHeight: 1.5 }}>Case #DP-{Math.floor(Math.random() * 900000 + 100000)}. Expect a bureau response within 30 days. We'll notify you.</div>
          <button onClick={onClose} style={{ marginTop: 22, padding: '10px 28px', borderRadius: 100, background: '#FF9F0A', border: 'none', color: '#000', fontWeight: 600, fontSize: 13, cursor: 'pointer' }}>Done</button>
        </div>
      </div>
    );
  }

  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 80,
      background: 'rgba(0,0,0,0.8)', backdropFilter: 'blur(10px)',
      display: 'flex', alignItems: 'flex-end',
      animation: 'waOverlayIn 0.25s ease',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', height: '90%', overflowY: 'auto',
        background: '#0a0a0f',
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        border: '1px solid rgba(255,255,255,0.08)', borderBottom: 'none',
        padding: '14px 18px 28px',
        animation: 'waSheetIn 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 14px' }}/>

        <div style={{ fontFamily: DASH_DISPLAY, fontSize: 22, fontWeight: 600, color: '#fff', letterSpacing: '-0.03em', marginBottom: 4 }}>Dispute tradeline</div>
        <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.55)', marginBottom: 16 }}>{tradeline.name} · {tradeline.kind}</div>

        <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.45)', textTransform: 'uppercase', marginBottom: 8 }}>What's wrong?</div>
        <div style={{ display: 'grid', gap: 6, marginBottom: 18 }}>
          {reasons.map(r => (
            <button key={r} onClick={() => setReason(r)} style={{
              padding: '11px 14px', borderRadius: 12, cursor: 'pointer', textAlign: 'left',
              background: reason === r ? 'rgba(255,159,10,0.12)' : 'rgba(255,255,255,0.03)',
              border: reason === r ? '1px solid rgba(255,159,10,0.5)' : '1px solid rgba(255,255,255,0.08)',
              color: reason === r ? '#FF9F0A' : '#fff', fontSize: 13, fontWeight: 500,
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            }}>
              <span>{r}</span>
              {reason === r && <svg width="14" height="14" 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>}
            </button>
          ))}
        </div>

        <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.45)', textTransform: 'uppercase', marginBottom: 8 }}>Additional detail</div>
        <textarea value={note} onChange={e => setNote(e.target.value)} placeholder="Explain what's inaccurate or attach context…" style={{
          width: '100%', minHeight: 90, padding: 12, borderRadius: 12,
          background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)',
          color: '#fff', fontSize: 13, fontFamily: 'inherit', resize: 'vertical', boxSizing: 'border-box',
          marginBottom: 18,
        }}/>

        {/* Affidavit */}
        <div style={{ padding: 14, borderRadius: 14, background: 'rgba(255,159,10,0.06)', border: '1px solid rgba(255,159,10,0.25)', marginBottom: 14 }}>
          <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: '#FF9F0A', textTransform: 'uppercase', marginBottom: 8, fontWeight: 700 }}>Affidavit</div>
          <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.75)', lineHeight: 1.55, marginBottom: 12 }}>
            I, {USER_PROFILE.firstName} {USER_PROFILE.lastName}, declare under penalty of perjury that the above information is true and accurate to the best of my knowledge. I authorize BTC Now to file this dispute on my behalf with {FICO_MOCK.bureau}.
          </div>
          <button onClick={() => setSigned(!signed)} style={{
            width: '100%', padding: '12px 14px', borderRadius: 12, cursor: 'pointer',
            background: signed ? 'rgba(16,185,129,0.15)' : 'rgba(255,255,255,0.04)',
            border: signed ? '1px solid #10B981' : '1px dashed rgba(255,255,255,0.2)',
            color: signed ? '#10B981' : 'rgba(245,245,247,0.7)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            fontSize: 13, fontWeight: 500, fontStyle: signed ? 'italic' : 'normal',
            fontFamily: signed ? 'cursive, fantasy' : 'inherit',
          }}>
            {signed ? (
              <>
                <svg width="14" height="14" 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>
                Signed · {USER_PROFILE.firstName} {USER_PROFILE.lastName}
              </>
            ) : (
              <>
                <svg width="14" height="14" 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>
                Tap to sign
              </>
            )}
          </button>
        </div>

        <button disabled={!reason || !signed} onClick={() => setSubmitted(true)} style={{
          width: '100%', padding: '14px', borderRadius: 100, border: 'none', cursor: (!reason || !signed) ? 'not-allowed' : 'pointer',
          background: (!reason || !signed) ? 'rgba(255,255,255,0.08)' : DASH_GRADIENT,
          color: (!reason || !signed) ? 'rgba(245,245,247,0.4)' : '#000',
          fontSize: 14, fontWeight: 600, fontFamily: DASH_DISPLAY,
        }}>Submit dispute</button>
      </div>
    </div>
  );
}

// ═══ Main Credit & Income panel ══════════════════════════════════════════
function CreditIncomePanel({ tab, onBack }) {
  const [connectOpen, setConnectOpen] = React.useState(false);
  const [disputing, setDisputing] = React.useState(null);
  const [accounts, setAccounts] = React.useState(INCOME_MOCK.connected);

  const addAccount = (b) => {
    setAccounts(a => [...a, {
      id: b.id + Date.now(), name: b.name, kind: 'Bank', sub: `•••• ${Math.floor(Math.random()*9000+1000)} · Plaid`,
      amount: Math.floor(Math.random() * 5000 + 500), cadence: 'avg dep.', status: 'verified',
    }]);
  };

  const monthlyIncome = accounts.reduce((s, a) => s + a.amount, 0);
  const monthlyExpenses = INCOME_MOCK.expenses.reduce((s, e) => s + e.v, 0);
  const dti = monthlyExpenses / monthlyIncome;
  const dtiColor = dti < 0.36 ? '#10B981' : dti < 0.43 ? '#FBBF24' : '#EF4444';
  const dtiRating = dti < 0.36 ? 'Healthy' : dti < 0.43 ? 'Moderate' : 'High';

  return (
    <div>
      <button onClick={onBack} style={{
        display: 'flex', alignItems: 'center', gap: 6,
        background: 'transparent', border: 'none', color: '#FF9F0A',
        fontSize: 13, fontWeight: 500, cursor: 'pointer', padding: '4px 0', marginBottom: 12,
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
        Back
      </button>
      <div style={{ fontFamily: DASH_DISPLAY, fontSize: 24, fontWeight: 600, color: '#fff', letterSpacing: '-0.03em', marginBottom: 4 }}>Credit & Income</div>
      <div style={{ fontSize: 12, color: 'rgba(245,245,247,0.55)', marginBottom: 18 }}>One-time verification powers every loan, card limit, and offer — no reapplying.</div>

      {/* ═══ FICO BLOCK ═══════════════════════════════════════════════════ */}
      <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.45)', textTransform: 'uppercase', paddingLeft: 4, marginBottom: 8 }}>FICO Score</div>
      <DashCard style={{ padding: 18, marginBottom: 16 }}>
        <FicoGauge score={FICO_MOCK.score}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, fontFamily: DASH_MONO, color: 'rgba(245,245,247,0.5)', marginTop: -8, marginBottom: 14, padding: '0 20px' }}>
          <span>300</span><span>850</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, padding: '12px 0', borderTop: '1px solid rgba(255,255,255,0.05)' }}>
          <div>
            <div style={{ fontFamily: DASH_MONO, fontSize: 9, color: 'rgba(245,245,247,0.45)', letterSpacing: '0.15em', textTransform: 'uppercase', marginBottom: 3 }}>Bureau</div>
            <div style={{ fontSize: 13, fontWeight: 500, color: '#fff' }}>{FICO_MOCK.bureau}</div>
          </div>
          <div>
            <div style={{ fontFamily: DASH_MONO, fontSize: 9, color: 'rgba(245,245,247,0.45)', letterSpacing: '0.15em', textTransform: 'uppercase', marginBottom: 3 }}>Last pulled</div>
            <div style={{ fontSize: 13, fontWeight: 500, color: '#fff' }}>{FICO_MOCK.pulledAt}</div>
          </div>
        </div>
        <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.5)', lineHeight: 1.5, paddingTop: 8, borderTop: '1px solid rgba(255,255,255,0.05)' }}>
          We pulled your score once during onboarding. Next soft pull: <span style={{ color: '#FF9F0A', fontFamily: DASH_MONO }}>{FICO_MOCK.nextPull}</span>. No hard inquiries.
        </div>
      </DashCard>

      {/* Factors */}
      <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.45)', textTransform: 'uppercase', paddingLeft: 4, marginBottom: 8 }}>Factors</div>
      <DashCard style={{ padding: 0, overflow: 'hidden', marginBottom: 16 }}>
        {FICO_MOCK.factors.map((f, i) => (
          <div key={f.l} style={{ padding: '12px 14px', borderBottom: i === FICO_MOCK.factors.length-1 ? 'none' : '1px solid rgba(255,255,255,0.04)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 12, color: 'rgba(245,245,247,0.7)' }}>{f.l}</span>
            <span style={{ fontSize: 12, fontWeight: 500, color: '#fff', fontFamily: DASH_MONO }}>{f.v}</span>
          </div>
        ))}
      </DashCard>

      {/* Tradelines */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingLeft: 4, marginBottom: 8 }}>
        <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.45)', textTransform: 'uppercase' }}>Tradelines · {FICO_MOCK.tradelines.length}</div>
        <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.12em', color: 'rgba(245,245,247,0.4)' }}>Tap to dispute</div>
      </div>
      <DashCard style={{ padding: 0, overflow: 'hidden', marginBottom: 22 }}>
        {FICO_MOCK.tradelines.map((tl, i) => (
          <button key={tl.id} onClick={() => setDisputing(tl)} style={{
            width: '100%', padding: '14px', cursor: 'pointer', background: 'transparent', border: 'none', borderBottom: i === FICO_MOCK.tradelines.length-1 ? 'none' : '1px solid rgba(255,255,255,0.04)',
            display: 'block', textAlign: 'left',
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#fff', marginBottom: 2 }}>{tl.name}</div>
                <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.5)', fontFamily: DASH_MONO, letterSpacing: '0.04em' }}>{tl.kind.toUpperCase()} · OPENED {tl.opened} · {tl.onTime} ON-TIME</div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0, marginLeft: 10 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#fff', fontFamily: DASH_MONO }}>{fmtUsd(tl.balance, { decimals: 0 })}</div>
                {tl.limit && <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.45)', fontFamily: DASH_MONO, marginTop: 2 }}>of {fmtUsd(tl.limit, { decimals: 0 })}</div>}
              </div>
            </div>
            {tl.limit && (
              <div style={{ height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.05)', overflow: 'hidden', marginTop: 6 }}>
                <div style={{ width: `${(tl.balance / tl.limit) * 100}%`, height: '100%', background: tl.balance / tl.limit > 0.3 ? '#FBBF24' : '#10B981', transition: 'width 0.6s' }}/>
              </div>
            )}
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 8 }}>
              <span style={{ padding: '2px 7px', borderRadius: 100, background: tl.status === 'Current' ? 'rgba(16,185,129,0.12)' : 'rgba(255,255,255,0.06)', border: `1px solid ${tl.status === 'Current' ? 'rgba(16,185,129,0.3)' : 'rgba(255,255,255,0.1)'}`, color: tl.status === 'Current' ? '#10B981' : 'rgba(245,245,247,0.6)', fontFamily: DASH_MONO, fontSize: 8, fontWeight: 700, letterSpacing: '0.12em' }}>{tl.status.toUpperCase()}</span>
              <span style={{ fontFamily: DASH_MONO, fontSize: 9, color: 'rgba(245,245,247,0.4)', letterSpacing: '0.12em', marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 3 }}>
                {CI_ICON('flag', 'rgba(245,245,247,0.4)')}
                DISPUTE
              </span>
            </div>
          </button>
        ))}
      </DashCard>

      {/* ═══ INCOME BLOCK ═════════════════════════════════════════════════ */}
      <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.45)', textTransform: 'uppercase', paddingLeft: 4, marginBottom: 8 }}>Income Verification</div>

      {/* Summary card */}
      <DashCard style={{ padding: 18, marginBottom: 14, background: 'linear-gradient(135deg, rgba(59,130,246,0.1), rgba(16,185,129,0.06))', border: '1px solid rgba(59,130,246,0.2)' }}>
        <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.15em', color: 'rgba(245,245,247,0.6)', textTransform: 'uppercase', marginBottom: 4 }}>Verified monthly income</div>
        <div style={{ fontFamily: DASH_DISPLAY, fontSize: 36, fontWeight: 700, color: '#fff', letterSpacing: '-0.04em', lineHeight: 1 }}>{fmtUsd(monthlyIncome, { decimals: 0 })}</div>
        <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)', marginTop: 6 }}>Across {accounts.length} connected account{accounts.length !== 1 ? 's' : ''} · last 90 days</div>
      </DashCard>

      {/* Connected sources */}
      <DashCard style={{ padding: 0, overflow: 'hidden', marginBottom: 12 }}>
        {accounts.map((a, i) => {
          const iconName = a.kind === 'Payroll' ? 'payroll' : a.kind === 'Investment' ? 'investment' : a.kind === 'Exchange' ? 'exchange' : 'bank';
          return (
            <div key={a.id} style={{ padding: '12px 14px', borderBottom: i === accounts.length-1 ? 'none' : '1px solid rgba(255,255,255,0.04)', display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 32, height: 32, borderRadius: 10, background: 'rgba(59,130,246,0.12)', border: '1px solid rgba(59,130,246,0.3)', color: '#3B82F6', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{CI_ICON(iconName, '#3B82F6')}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500, color: '#fff' }}>{a.name}</div>
                <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.5)', fontFamily: DASH_MONO, letterSpacing: '0.04em', marginTop: 1 }}>{a.sub.toUpperCase()}</div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#fff', fontFamily: DASH_MONO }}>+{fmtUsd(a.amount, { decimals: 0 })}</div>
                <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.45)', fontFamily: DASH_MONO, marginTop: 1 }}>{a.cadence}</div>
              </div>
            </div>
          );
        })}
      </DashCard>

      {/* Missed income nudge + connect */}
      <button onClick={() => setConnectOpen(true)} style={{
        width: '100%', padding: '14px', borderRadius: 14, cursor: 'pointer',
        background: 'rgba(255,159,10,0.06)', border: '1px dashed rgba(255,159,10,0.4)',
        color: '#FF9F0A', fontSize: 13, fontWeight: 500,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, marginBottom: 22,
      }}>
        {CI_ICON('plus', '#FF9F0A')}
        Did we miss income? Connect another account
      </button>

      {/* Fixed Expenses */}
      <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.45)', textTransform: 'uppercase', paddingLeft: 4, marginBottom: 8 }}>Monthly Fixed Expenses</div>
      <DashCard style={{ padding: 0, overflow: 'hidden', marginBottom: 14 }}>
        {INCOME_MOCK.expenses.map((e, i) => (
          <div key={e.l} style={{ padding: '11px 14px', borderBottom: i === INCOME_MOCK.expenses.length-1 ? 'none' : '1px solid rgba(255,255,255,0.04)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 12, color: 'rgba(245,245,247,0.7)' }}>{e.l}</span>
            <span style={{ fontSize: 12, fontWeight: 500, color: '#fff', fontFamily: DASH_MONO }}>−{fmtUsd(e.v, { decimals: 0 })}</span>
          </div>
        ))}
        <div style={{ padding: '13px 14px', background: 'rgba(255,255,255,0.02)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ fontSize: 12, fontWeight: 600, color: '#fff' }}>Total fixed</span>
          <span style={{ fontSize: 14, fontWeight: 700, color: '#fff', fontFamily: DASH_MONO }}>{fmtUsd(monthlyExpenses, { decimals: 0 })}</span>
        </div>
      </DashCard>

      {/* DTI */}
      <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.45)', textTransform: 'uppercase', paddingLeft: 4, marginBottom: 8 }}>Debt-to-income ratio</div>
      <DashCard style={{ padding: 18, marginBottom: 22 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 12 }}>
          <div>
            <div style={{ fontFamily: DASH_DISPLAY, fontSize: 42, fontWeight: 700, color: dtiColor, letterSpacing: '-0.04em', lineHeight: 1 }}>{(dti * 100).toFixed(1)}%</div>
            <div style={{ fontFamily: DASH_MONO, fontSize: 10, color: dtiColor, letterSpacing: '0.15em', fontWeight: 700, marginTop: 4 }}>{dtiRating.toUpperCase()}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)' }}>{fmtUsd(monthlyExpenses, { decimals: 0 })} of {fmtUsd(monthlyIncome, { decimals: 0 })}</div>
            <div style={{ fontSize: 10, fontFamily: DASH_MONO, color: 'rgba(245,245,247,0.4)', marginTop: 2, letterSpacing: '0.04em' }}>fixed / gross</div>
          </div>
        </div>

        {/* DTI bar with thresholds */}
        <div style={{ position: 'relative', height: 10, borderRadius: 5, background: 'rgba(255,255,255,0.06)', overflow: 'visible', marginBottom: 20 }}>
          <div style={{ position: 'absolute', inset: 0, display: 'flex', borderRadius: 5, overflow: 'hidden' }}>
            <div style={{ width: `${Math.min(dti, 1) * 100}%`, background: dtiColor, transition: 'width 0.8s cubic-bezier(0.16,1,0.3,1)' }}/>
          </div>
          {/* threshold markers */}
          <div style={{ position: 'absolute', left: '36%', top: -2, width: 1, height: 14, background: 'rgba(255,255,255,0.3)' }}/>
          <div style={{ position: 'absolute', left: '43%', top: -2, width: 1, height: 14, background: 'rgba(255,255,255,0.3)' }}/>
          <div style={{ position: 'absolute', left: '36%', top: 16, fontSize: 8, fontFamily: DASH_MONO, color: 'rgba(245,245,247,0.45)', transform: 'translateX(-50%)', letterSpacing: '0.1em' }}>36%</div>
          <div style={{ position: 'absolute', left: '43%', top: 16, fontSize: 8, fontFamily: DASH_MONO, color: 'rgba(245,245,247,0.45)', transform: 'translateX(-50%)', letterSpacing: '0.1em' }}>43%</div>
        </div>

        <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)', lineHeight: 1.5, paddingTop: 10, borderTop: '1px solid rgba(255,255,255,0.05)' }}>
          Your DTI is <span style={{ color: dtiColor, fontWeight: 600 }}>{dtiRating.toLowerCase()}</span>. You qualify for every product on BTC Now — including the <span style={{ color: '#FF9F0A' }}>Sovereign tier</span> private credit line.
        </div>
      </DashCard>

      {/* Footer — re-run */}
      <div style={{ padding: 14, borderRadius: 14, background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.05)', textAlign: 'center' }}>
        <div style={{ fontSize: 11, color: 'rgba(245,245,247,0.55)', lineHeight: 1.5, marginBottom: 10 }}>
          All BTC Now products reuse this verification. No reapplying, no new hard pulls.
        </div>
        <button style={{
          padding: '8px 16px', borderRadius: 100, background: 'rgba(255,255,255,0.05)',
          border: '1px solid rgba(255,255,255,0.1)', color: 'rgba(245,245,247,0.75)',
          fontSize: 12, fontWeight: 500, cursor: 'pointer',
        }}>Refresh verification data</button>
      </div>

      {connectOpen && <ConnectSheet onClose={() => setConnectOpen(false)} onConnect={addAccount}/>}
      {disputing && <DisputeSheet tradeline={disputing} onClose={() => setDisputing(null)}/>}
    </div>
  );
}

Object.assign(window, { CreditIncomePanel });
