// dash-wallet.jsx — detail view for BTC or USD wallet
// Shows balance hero, quick actions, and a transaction history specific
// to the wallet type (send, receive, convert, card, round-ups, etc.)

const BTC_TX_HISTORY = [
  { id: 'b1', kind: 'receive',  amt: +0.2431,  from: 'Kraken · withdrawal',  when: 'Today · 2:14pm',     note: 'DCA buy settled' },
  { id: 'b2', kind: 'roundup',  amt: +0.00042, from: 'Round-ups · Nobu',     when: 'Today · 8:14pm',     note: '412 sats' },
  { id: 'b3', kind: 'convert',  amt: -0.1500,  from: 'Convert → USD',        when: 'Yesterday',          note: 'Paid down card' },
  { id: 'b4', kind: 'cashback', amt: +0.00124, from: 'Card cashback',        when: 'Apr 21',             note: 'Velocity Black · 18,400 sats' },
  { id: 'b5', kind: 'send',     amt: -0.3200,  from: 'bc1q…k4zp',            when: 'Apr 20',             note: 'To cold storage' },
  { id: 'b6', kind: 'receive',  amt: +1.2000,  from: 'Loan disbursement',    when: 'Apr 18',             note: 'Collateral returned' },
  { id: 'b7', kind: 'roundup',  amt: +0.00032, from: 'Round-ups · Equinox',  when: 'Apr 18',             note: '325 sats' },
  { id: 'b8', kind: 'receive',  amt: +0.5000,  from: 'Coinbase · transfer',  when: 'Apr 15',             note: 'External' },
];

const USD_TX_HISTORY = [
  { id: 'u1', kind: 'deposit',  amt: +42_000.00, from: 'Payroll · Kairos Ventures', when: 'Today · 9:00am', note: 'Direct deposit' },
  { id: 'u2', kind: 'card',     amt: -412.80,    from: 'Card · Nobu Malibu',        when: 'Today · 8:14pm', note: 'Dining' },
  { id: 'u3', kind: 'card',     amt: -2_399.00,  from: 'Card · Apple Store',        when: 'Yesterday',      note: 'Tech' },
  { id: 'u4', kind: 'convert',  amt: +10_261.86, from: 'Convert from BTC',          when: 'Yesterday',      note: '0.15 BTC swapped' },
  { id: 'u5', kind: 'send',     amt: -8_400.00,  from: 'Wire · Title & Escrow Co.', when: 'Apr 21',         note: 'Earnest money' },
  { id: 'u6', kind: 'card',     amt: -18_400.00, from: 'Card · Velocity Black',     when: 'Apr 21',         note: 'Yacht charter' },
  { id: 'u7', kind: 'receive',  amt: +5_000.00,  from: 'Zelle · Amara Okafor',      when: 'Apr 20',         note: 'Split · Miami' },
  { id: 'u8', kind: 'deposit',  amt: +42_000.00, from: 'Payroll · Kairos Ventures', when: 'Apr 15',         note: 'Direct deposit' },
];

function walletTheme(kind) {
  if (kind === 'btc') {
    return {
      name: 'Bitcoin',
      sub: 'BTC · On-chain + custodial',
      heroBg: DASH_GRADIENT,
      accent: '#FF9F0A',
      symbol: '₿',
      shadow: '0 20px 60px rgba(255,159,10,0.35)',
    };
  }
  return {
    name: 'US Dollar',
    sub: 'USD · FDIC-insured · yielding 4.8%',
    heroBg: 'linear-gradient(135deg, #10B981 0%, #059669 100%)',
    accent: '#10B981',
    symbol: '$',
    shadow: '0 20px 60px rgba(16,185,129,0.3)',
  };
}

const TX_KIND_META = {
  receive:  { label: 'Received',   color: '#10B981', icon: (c) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 7L7 17M7 17h9M7 17V8"/></svg> },
  send:     { label: 'Sent',       color: '#F5F5F7', icon: (c) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17L17 7M17 7H8M17 7v9"/></svg> },
  convert:  { label: 'Converted',  color: '#A78BFA', icon: (c) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 10h14M17 6l4 4-4 4M17 14H3M7 18l-4-4 4-4"/></svg> },
  deposit:  { label: 'Deposit',    color: '#10B981', icon: (c) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v14M6 13l6 6 6-6M4 21h16"/></svg> },
  card:     { label: 'Card',       color: '#F59E0B', icon: (c) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="6" width="18" height="12" rx="2"/><path d="M3 10h18"/></svg> },
  roundup:  { label: 'Round-up',   color: '#FF9F0A', icon: (c) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17l5-5 5 5"/><path d="M7 11l5-5 5 5"/></svg> },
  cashback: { label: 'Cashback',   color: '#FF9F0A', icon: (c) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v10M9 10h5a2 2 0 010 4H9"/></svg> },
};

function WalletActionPill({ icon, label, onClick, primary }) {
  const icons = {
    send:    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17L17 7M17 7H8M17 7v9"/></svg>,
    receive: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 7L7 17M7 17h9M7 17V8"/></svg>,
    convert: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 10h14M17 6l4 4-4 4M17 14H3M7 18l-4-4 4-4"/></svg>,
    buy:     <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v10M9 12h6"/></svg>,
  };
  return (
    <button onClick={onClick} style={{
      background: primary ? 'rgba(255,255,255,0.16)' : 'rgba(255,255,255,0.08)',
      border: '1px solid rgba(255,255,255,0.14)',
      color: '#fff',
      borderRadius: 100, padding: '9px 14px',
      display: 'flex', alignItems: 'center', gap: 6,
      fontSize: 12, fontWeight: 600, cursor: 'pointer', flexShrink: 0,
      backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
    }}>
      {icons[icon]}<span>{label}</span>
    </button>
  );
}

function WalletTxRow({ tx, kind, isLast, btcPrice }) {
  const meta = TX_KIND_META[tx.kind] || TX_KIND_META.receive;
  const isNeg = tx.amt < 0;
  const primaryAmt = kind === 'btc'
    ? `${isNeg ? '-' : '+'}${Math.abs(tx.amt).toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 8 })} BTC`
    : fmtUsd(tx.amt, { decimals: 2 });
  const secondary = kind === 'btc'
    ? `≈ ${fmtUsd(Math.abs(tx.amt) * btcPrice, { decimals: 0 })}`
    : meta.label;

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 14px',
      borderBottom: isLast ? 'none' : '1px solid rgba(255,255,255,0.04)',
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10,
        background: `${meta.color}15`, border: `1px solid ${meta.color}35`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>{meta.icon(meta.color)}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500, color: '#fff', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tx.from}</div>
        <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.45)', marginTop: 1, display: 'flex', alignItems: 'center', gap: 6 }}>
          <span>{tx.when}</span>
          <span style={{ opacity: 0.5 }}>·</span>
          <span style={{ color: 'rgba(245,245,247,0.55)' }}>{tx.note}</span>
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: isNeg ? '#fff' : '#10B981', fontFamily: DASH_MONO }}>{primaryAmt}</div>
        <div style={{ fontSize: 10, color: 'rgba(245,245,247,0.45)', marginTop: 1, fontFamily: DASH_MONO }}>{secondary}</div>
      </div>
    </div>
  );
}

function WalletDetail({ kind, btcPrice, onBack }) {
  const theme = walletTheme(kind);
  const balance = kind === 'btc' ? MOCK.btc : MOCK.cashUsd;
  const usdValue = kind === 'btc' ? MOCK.btc * btcPrice : MOCK.cashUsd;
  const history  = kind === 'btc' ? BTC_TX_HISTORY : USD_TX_HISTORY;
  const [filter, setFilter] = React.useState('all');
  const [action, setAction] = React.useState(null); // 'send' | 'receive' | 'convert' | 'buy'

  const filterOptions = kind === 'btc'
    ? [{v:'all',l:'All'},{v:'receive',l:'In'},{v:'send',l:'Out'},{v:'convert',l:'Convert'},{v:'roundup',l:'Round-ups'}]
    : [{v:'all',l:'All'},{v:'deposit',l:'Deposits'},{v:'card',l:'Card'},{v:'send',l:'Sent'},{v:'receive',l:'Received'},{v:'convert',l:'Convert'}];

  const shown = filter === 'all' ? history : history.filter(t => t.kind === filter);
  const inflow  = history.filter(t => t.amt > 0).reduce((s, t) => s + t.amt, 0);
  const outflow = history.filter(t => t.amt < 0).reduce((s, t) => s + Math.abs(t.amt), 0);

  return (
    <DashScreen modals={action && <WalletActionSheet action={action} kind={kind} btcPrice={btcPrice} onClose={() => setAction(null)} />}>
      {/* custom header with back */}
      <div style={{
        position: 'absolute', top: 52, left: 0, right: 0, zIndex: 10,
        padding: '8px 16px 12px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: 'linear-gradient(180deg, rgba(5,5,7,0.98) 0%, rgba(5,5,7,0.85) 70%, transparent 100%)',
        backdropFilter: 'blur(12px)',
      }}>
        <button onClick={onBack} style={{
          width: 34, height: 34, 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="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>
        </button>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.2em', color: 'rgba(245,245,247,0.5)', textTransform: 'uppercase' }}>Wallet</div>
          <div style={{ fontFamily: DASH_DISPLAY, fontSize: 16, fontWeight: 600, color: '#fff' }}>{theme.name}</div>
        </div>
        <div style={{ width: 34 }}/>
      </div>

      <div style={{ padding: '0 20px 16px' }}>
        {/* HERO */}
        <div style={{
          background: theme.heroBg, borderRadius: 24, padding: 22,
          boxShadow: theme.shadow,
          position: 'relative', overflow: 'hidden', marginBottom: 14,
        }}>
          <div style={{ fontFamily: DASH_MONO, fontSize: 10, letterSpacing: '0.22em', color: '#000', opacity: 0.6, fontWeight: 700, textTransform: 'uppercase' }}>
            {kind === 'btc' ? 'BTC Balance' : 'USD Balance'}
          </div>
          <div style={{ fontFamily: DASH_DISPLAY, fontSize: 42, fontWeight: 700, color: '#000', letterSpacing: '-0.04em', lineHeight: 1, marginTop: 12 }}>
            {kind === 'btc' ? fmtBtc(balance) : fmtUsd(balance, { decimals: 2 })}
          </div>
          {kind === 'btc' ? (
            <div style={{ fontFamily: DASH_MONO, fontSize: 13, color: '#000', opacity: 0.7, marginTop: 6, fontWeight: 600 }}>
              ≈ <AnimatedNumber value={usdValue} format={v => fmtUsd(v, { decimals: 0 })} /> · @ {fmtUsd(btcPrice, { decimals: 0 })}
            </div>
          ) : (
            <div style={{ fontFamily: DASH_MONO, fontSize: 11, color: '#000', opacity: 0.7, marginTop: 6, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#000', opacity: 0.6 }}/>
              Yielding 4.8% APY · paid daily
            </div>
          )}

          <div style={{ display: 'flex', gap: 8, marginTop: 20, flexWrap: 'wrap' }}>
            <WalletActionPill icon="send"    label="Send"    onClick={() => setAction('send')} primary />
            <WalletActionPill icon="receive" label="Receive" onClick={() => setAction('receive')} />
            <WalletActionPill icon="convert" label={kind === 'btc' ? 'Convert to USD' : 'Convert to BTC'} onClick={() => setAction('convert')} />
            {kind === 'btc' && <WalletActionPill icon="buy" label="Buy" onClick={() => setAction('buy')} />}
          </div>

          <div style={{ position: 'absolute', right: -10, bottom: -30, fontFamily: DASH_DISPLAY, fontSize: 160, fontWeight: 800, color: 'rgba(0,0,0,0.07)', lineHeight: 1, pointerEvents: 'none' }}>{theme.symbol}</div>
        </div>

        {/* 30-day summary */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
          <DashCard style={{ padding: 14 }}>
            <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.18em', color: 'rgba(245,245,247,0.5)', textTransform: 'uppercase', marginBottom: 6 }}>30-day in</div>
            <div style={{ fontFamily: DASH_MONO, fontSize: 16, fontWeight: 700, color: '#10B981' }}>
              {kind === 'btc' ? `+${inflow.toFixed(4)} BTC` : `+${fmtUsd(inflow, { decimals: 0 })}`}
            </div>
          </DashCard>
          <DashCard style={{ padding: 14 }}>
            <div style={{ fontFamily: DASH_MONO, fontSize: 9, letterSpacing: '0.18em', color: 'rgba(245,245,247,0.5)', textTransform: 'uppercase', marginBottom: 6 }}>30-day out</div>
            <div style={{ fontFamily: DASH_MONO, fontSize: 16, fontWeight: 700, color: '#fff' }}>
              {kind === 'btc' ? `-${outflow.toFixed(4)} BTC` : `-${fmtUsd(outflow, { decimals: 0 })}`}
            </div>
          </DashCard>
        </div>

        {/* FILTER CHIPS */}
        <div style={{ display: 'flex', gap: 6, overflowX: 'auto', marginBottom: 10, paddingBottom: 2, marginLeft: -4, paddingLeft: 4 }}>
          {filterOptions.map(opt => (
            <button key={opt.v} onClick={() => setFilter(opt.v)} style={{
              padding: '7px 12px', borderRadius: 100, whiteSpace: 'nowrap',
              background: filter === opt.v ? `${theme.accent}20` : 'rgba(255,255,255,0.04)',
              border: `1px solid ${filter === opt.v ? `${theme.accent}50` : 'rgba(255,255,255,0.08)'}`,
              color: filter === opt.v ? theme.accent : 'rgba(245,245,247,0.7)',
              fontSize: 11, fontWeight: 600, cursor: 'pointer',
              transition: 'all 0.2s',
            }}>{opt.l}</button>
          ))}
        </div>

        {/* TRANSACTIONS */}
        <DashCard style={{ padding: 0, overflow: 'hidden' }}>
          {shown.length === 0 ? (
            <div style={{ padding: '40px 16px', textAlign: 'center', fontSize: 12, color: 'rgba(245,245,247,0.45)' }}>No transactions in this filter.</div>
          ) : shown.map((tx, i) => (
            <WalletTxRow key={tx.id} tx={tx} kind={kind} isLast={i === shown.length - 1} btcPrice={btcPrice}/>
          ))}
        </DashCard>
      </div>
    </DashScreen>
  );
}

Object.assign(window, { WalletDetail });