// Wallet — deposit (crypto), withdraw, transfer, history
const CRYPTOS = [
  { id: 'BTC', name: 'Bitcoin', net: 'Bitcoin', addr: 'bc1q9h6mlk2x4pvgaq8jp7n3dy5fwxrt0c8mev2lrh', fee: '0.0002 BTC', conf: '2 confs (~20 min)', icon: 'bitcoin' },
  { id: 'ETH', name: 'Ethereum', net: 'ERC-20', addr: '0x4b2cE9aA38B7d5F2c5b09A8e9D1a4F8a7C3b5d2E', fee: '0.0015 ETH', conf: '12 confs (~3 min)', icon: 'ethereum' },
  { id: 'USDT', name: 'Tether', net: 'TRC-20', addr: 'TYHj4N9ZpDqK8RvX2eMfA7sBbCcDdEeFf3', fee: '1 USDT', conf: '20 confs (~1 min)', icon: 'tether' },
];

function Deposit() {
  const { go, accounts, toast, desktop } = useApp();
  const live = accounts.filter(a => a.type === 'live');
  const [step, setStep] = useState(1);
  const [crypto, setCrypto] = useState(CRYPTOS[2]);
  const [accId, setAccId] = useState(live[0]?.id);
  const [amount, setAmount] = useState('');
  const [copied, setCopied] = useState(false);
  const acc = live.find(a => a.id === accId) || live[0];

  const copy = () => {
    setCopied(true);
    toast('Address copied');
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className={desktop ? "desktop-screen-inner" : "screen page-enter"}>
      {!desktop && <><StatusBar /><AppBar title="Deposit" onBack={() => step === 1 ? go('dashboard') : setStep(step - 1)} /></>}
      <div style={{ padding: '0 20px 30px' }}>
        <div className="row" style={{ gap: 6, marginBottom: 22 }}>
          {[1,2,3].map(s => (
            <div key={s} style={{ flex: 1, height: 4, borderRadius: 2, background: s <= step ? 'var(--green)' : 'var(--line)' }}/>
          ))}
        </div>

        {step === 1 && (
          <>
            <h2 style={{ fontSize: 22, margin: '0 0 4px' }}>Choose currency</h2>
            <p style={{ color: 'var(--text-dim)', fontSize: 13, margin: '0 0 18px' }}>Crypto only. Funds credited after network confirmation.</p>
            <div className="stack" style={{ gap: 10 }}>
              {CRYPTOS.map(c => (
                <button key={c.id} onClick={() => setCrypto(c)} style={{
                  display: 'flex', alignItems: 'center', gap: 14,
                  padding: 14, borderRadius: 16,
                  border: '1px solid ' + (crypto.id === c.id ? 'var(--green)' : 'var(--line)'),
                  background: crypto.id === c.id ? 'color-mix(in oklab, var(--green) 6%, var(--card))' : 'var(--card)',
                  color: 'var(--text)', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left'
                }}>
                  <div style={{ width: 40, height: 40, borderRadius: '50%', overflow: 'hidden' }}>
                    {I[c.icon]()}
                  </div>
                  <div className="col" style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, fontWeight: 600 }}>{c.name} <span style={{ color: 'var(--text-dim)', fontWeight: 400, fontSize: 13 }}>· {c.id}</span></div>
                    <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>{c.net} · {c.conf}</div>
                  </div>
                  <I.chevR size={16} />
                </button>
              ))}
            </div>
            <button className="btn btn-primary" onClick={() => setStep(2)} style={{ marginTop: 20 }}>Continue</button>
          </>
        )}

        {step === 2 && (
          <>
            <h2 style={{ fontSize: 22, margin: '0 0 4px' }}>Deposit to</h2>
            <p style={{ color: 'var(--text-dim)', fontSize: 13, margin: '0 0 18px' }}>Select trading account &amp; amount.</p>
            <div className="input-label">Trading account</div>
            <div className="stack" style={{ gap: 8, marginBottom: 18 }}>
              {live.map(a => (
                <Row key={a.id} active={accId === a.id} onClick={() => setAccId(a.id)}
                  title={'#' + a.number + ' · ' + a.platform}
                  desc={'Balance $' + a.balance.toFixed(2) + ' · ' + a.kind} />
              ))}
            </div>
            <div className="input-label">Amount in USD</div>
            <div className="input-group">
              <span className="input-prefix mono">$</span>
              <input className="input input-with-prefix mono" type="number" placeholder="0.00" value={amount} onChange={e => setAmount(e.target.value)} style={{ fontSize: 22, fontWeight: 600 }}/>
            </div>
            <div className="row" style={{ gap: 8, marginTop: 10 }}>
              {[100, 500, 1000, 5000].map(v => (
                <button key={v} onClick={() => setAmount(String(v))} className="mono" style={{
                  flex: 1, padding: '8px', borderRadius: 10, fontSize: 12, fontWeight: 600,
                  background: 'var(--card)', color: 'var(--text-dim)', border: '1px solid var(--line)', cursor: 'pointer', fontFamily: 'inherit'
                }}>${v}</button>
              ))}
            </div>
            <div className="card" style={{ marginTop: 16, padding: 14, fontSize: 12, color: 'var(--text-dim)' }}>
              <div className="between"><span>You'll send (est.)</span><span className="mono" style={{ color: 'var(--text)' }}>~{amount ? (parseFloat(amount) / (crypto.id === 'BTC' ? 68900 : crypto.id === 'ETH' ? 3420 : 1)).toFixed(crypto.id === 'USDT' ? 2 : 6) : '0'} {crypto.id}</span></div>
              <div className="between" style={{ marginTop: 6 }}><span>Network fee</span><span className="mono" style={{ color: 'var(--text)' }}>{crypto.fee}</span></div>
              <div className="between" style={{ marginTop: 6 }}><span>You'll receive</span><span className="mono" style={{ color: 'var(--green)' }}>${amount || '0.00'}</span></div>
            </div>
            <button className="btn btn-primary" disabled={!amount || parseFloat(amount) <= 0} onClick={() => setStep(3)} style={{ marginTop: 20 }}>Generate address</button>
          </>
        )}

        {step === 3 && (
          <>
            <h2 style={{ fontSize: 22, margin: '0 0 4px' }}>Send {crypto.id} to address</h2>
            <p style={{ color: 'var(--text-dim)', fontSize: 13, margin: '0 0 18px' }}>Use the {crypto.net} network only. Other networks will lose funds.</p>
            <div className="card" style={{ padding: 18, textAlign: 'center' }}>
              <FakeQR seed={crypto.addr} />
              <div className="addr-box" style={{ marginTop: 14, textAlign: 'left' }}>
                <strong>{crypto.addr}</strong>
              </div>
              <button className="btn btn-secondary btn-sm" onClick={copy} style={{ marginTop: 10 }}>
                {copied ? <><I.check size={16}/> Copied</> : <><I.copy size={16}/> Copy address</>}
              </button>
            </div>
            <div className="card" style={{ marginTop: 12, padding: 0 }}>
              <Detail k="Amount" v={'$' + (amount || '0.00')} />
              <Detail k="Network" v={crypto.net} />
              <Detail k="Min. confirmations" v={crypto.conf} />
              <Detail k="Crediting account" v={'#' + acc.number} last />
            </div>
            <div className="row" style={{ gap: 6, marginTop: 14, padding: 12, background: 'color-mix(in oklab, var(--amber) 10%, transparent)', borderRadius: 12, fontSize: 12, color: 'var(--text-dim)' }}>
              <I.info size={16} /> <span>Send only {crypto.id} via {crypto.net}. Sending other tokens or networks may result in permanent loss.</span>
            </div>
            <button className="btn btn-primary" onClick={() => { toast('We\'ll notify when received'); go('dashboard'); }} style={{ marginTop: 20 }}>I've sent the payment</button>
          </>
        )}
      </div>
    </div>
  );
}

function FakeQR({ seed = '' }) {
  // Deterministic pseudo-QR pattern
  const cells = useMemo(() => {
    let h = 0;
    for (const c of seed) h = (h * 31 + c.charCodeAt(0)) >>> 0;
    const arr = [];
    for (let i = 0; i < 21 * 21; i++) {
      h = (h * 1664525 + 1013904223) >>> 0;
      arr.push((h & 1) === 1);
    }
    // Finder patterns at 3 corners
    const inFinder = (x, y) => {
      const f = (cx, cy) => x >= cx && x < cx+7 && y >= cy && y < cy+7;
      return f(0,0) || f(14,0) || f(0,14);
    };
    return { arr, inFinder };
  }, [seed]);
  return (
    <div className="qr">
      {Array.from({ length: 21 * 21 }).map((_, i) => {
        const x = i % 21, y = Math.floor(i / 21);
        if (cells.inFinder(x, y)) {
          // Draw 7x7 finder
          const fx = x < 7 ? x : (x >= 14 ? x - 14 : 0);
          const fy = y < 7 ? y : (y >= 14 ? y - 14 : 0);
          const onBorder = fx === 0 || fx === 6 || fy === 0 || fy === 6;
          const onCenter = fx >= 2 && fx <= 4 && fy >= 2 && fy <= 4;
          return <div key={i} className={onBorder || onCenter ? '' : 'empty'} />;
        }
        return <div key={i} className={cells.arr[i] ? '' : 'empty'} />;
      })}
    </div>
  );
}

function Withdraw() {
  const { go, accounts, toast, desktop } = useApp();
  const live = accounts.filter(a => a.type === 'live');
  const [crypto, setCrypto] = useState(CRYPTOS[2]);
  const [accId, setAccId] = useState(live[0]?.id);
  const [amount, setAmount] = useState('');
  const [addr, setAddr] = useState('');
  const acc = live.find(a => a.id === accId) || live[0];

  const max = acc.balance;
  const valid = amount && parseFloat(amount) > 0 && parseFloat(amount) <= max && addr.length > 20;

  const submit = () => {
    toast('Withdrawal requested');
    go('history');
  };

  return (
    <div className={desktop ? "desktop-screen-inner" : "screen page-enter"}>
      {!desktop && <><StatusBar /><AppBar title="Withdraw" onBack={() => go('dashboard')} /></>}
      <div style={{ padding: '0 20px 30px' }}>
        <div className="input-label">From account</div>
        <div className="stack" style={{ gap: 8, marginBottom: 18 }}>
          {live.map(a => (
            <Row key={a.id} active={accId === a.id} onClick={() => setAccId(a.id)}
              title={'#' + a.number + ' · ' + a.platform}
              desc={'Available $' + a.balance.toFixed(2)} />
          ))}
        </div>

        <div className="input-label">Currency</div>
        <div className="row" style={{ gap: 8, marginBottom: 18 }}>
          {CRYPTOS.map(c => (
            <button key={c.id} onClick={() => setCrypto(c)} style={{
              flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              padding: '10px', borderRadius: 12, fontWeight: 600, fontSize: 13,
              background: crypto.id === c.id ? 'color-mix(in oklab, var(--green) 8%, var(--card))' : 'var(--card)',
              color: 'var(--text)', border: '1px solid ' + (crypto.id === c.id ? 'var(--green)' : 'var(--line)'),
              cursor: 'pointer', fontFamily: 'inherit'
            }}>
              <div style={{ width: 20, height: 20, borderRadius: '50%', overflow: 'hidden' }}>{I[c.icon]()}</div>
              {c.id}
            </button>
          ))}
        </div>

        <div className="input-label">Amount</div>
        <div className="input-group">
          <span className="input-prefix mono">$</span>
          <input className="input input-with-prefix mono" type="number" placeholder="0.00" value={amount} onChange={e => setAmount(e.target.value)} style={{ fontSize: 22, fontWeight: 600 }}/>
          <button onClick={() => setAmount(String(max))} className="mono" style={{
            position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)',
            background: 'var(--card-2)', border: '1px solid var(--line)', borderRadius: 8,
            padding: '4px 10px', fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', cursor: 'pointer'
          }}>MAX</button>
        </div>
        <div className="between" style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 6 }}>
          <span>Available</span>
          <span className="mono">${max.toFixed(2)}</span>
        </div>

        <div className="input-label" style={{ marginTop: 18 }}>{crypto.id} address ({crypto.net})</div>
        <input className="input mono" style={{ fontSize: 13 }} placeholder={'Paste your ' + crypto.id + ' address'} value={addr} onChange={e => setAddr(e.target.value)} />

        <div className="card" style={{ marginTop: 18, padding: 14, fontSize: 12, color: 'var(--text-dim)' }}>
          <div className="between" style={{ gap: 12 }}><span style={{ whiteSpace: 'nowrap' }}>Network fee</span><span className="mono" style={{ color: 'var(--text)', whiteSpace: 'nowrap' }}>{crypto.fee}</span></div>
          <div className="between" style={{ marginTop: 6, gap: 12 }}><span style={{ whiteSpace: 'nowrap' }}>You'll receive (est.)</span><span className="mono" style={{ color: 'var(--green)', whiteSpace: 'nowrap' }}>~{amount ? (parseFloat(amount) / (crypto.id === 'BTC' ? 68900 : crypto.id === 'ETH' ? 3420 : 1)).toFixed(crypto.id === 'USDT' ? 2 : 6) : '0'} {crypto.id}</span></div>
          <div className="between" style={{ marginTop: 6, gap: 12 }}><span style={{ whiteSpace: 'nowrap' }}>Processing time</span><span style={{ color: 'var(--text)', whiteSpace: 'nowrap' }}>Up to 1 hour</span></div>
        </div>

        <button className="btn btn-primary" disabled={!valid} onClick={submit} style={{ marginTop: 20 }}>Request withdrawal</button>
      </div>
    </div>
  );
}

function Transfer() {
  const { go, accounts, toast, desktop } = useApp();
  const [from, setFrom] = useState(accounts[0]?.id);
  const [to, setTo] = useState(accounts[1]?.id);
  const [amount, setAmount] = useState('');
  const fromAcc = accounts.find(a => a.id === from);
  const toAcc = accounts.find(a => a.id === to);
  const valid = from !== to && amount && parseFloat(amount) > 0 && parseFloat(amount) <= (fromAcc?.balance || 0);

  const swap = () => { setFrom(to); setTo(from); };

  const submit = () => {
    toast('Transferred $' + amount);
    go('dashboard');
  };

  return (
    <div className={desktop ? "desktop-screen-inner" : "screen page-enter"}>
      {!desktop && <><StatusBar /><AppBar title="Transfer" onBack={() => go('dashboard')} /></>}
      <div style={{ padding: '0 20px 30px' }}>
        <p style={{ color: 'var(--text-dim)', fontSize: 13, margin: '0 0 18px' }}>Move funds instantly between your trading accounts. No fee.</p>

        <AccountPicker label="From" value={from} onChange={setFrom} accounts={accounts} />
        <div style={{ display: 'flex', justifyContent: 'center', margin: '8px 0' }}>
          <button onClick={swap} style={{
            width: 40, height: 40, borderRadius: 12,
            background: 'var(--card)', border: '1px solid var(--line)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'var(--text)'
          }}>
            <I.swap />
          </button>
        </div>
        <AccountPicker label="To" value={to} onChange={setTo} accounts={accounts.filter(a => a.id !== from)} />

        <div className="input-label" style={{ marginTop: 22 }}>Amount</div>
        <div className="input-group">
          <span className="input-prefix mono">$</span>
          <input className="input input-with-prefix mono" type="number" placeholder="0.00" value={amount} onChange={e => setAmount(e.target.value)} style={{ fontSize: 22, fontWeight: 600 }}/>
        </div>
        <div className="between" style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 6 }}>
          <span>Available in source</span>
          <span className="mono">${fromAcc?.balance.toFixed(2)}</span>
        </div>

        <button className="btn btn-primary" disabled={!valid} onClick={submit} style={{ marginTop: 24 }}>Transfer</button>
      </div>
    </div>
  );
}

function AccountPicker({ label, value, onChange, accounts }) {
  const [open, setOpen] = useState(false);
  const acc = accounts.find(a => a.id === value);
  return (
    <div>
      <div className="input-label">{label}</div>
      <button className="card row between" onClick={() => setOpen(o => !o)} style={{ width: '100%', cursor: 'pointer', color: 'var(--text)', textAlign: 'left' }}>
        <div className="col">
          <div className="row" style={{ gap: 8 }}>
            <span className={'pill ' + (acc?.type === 'demo' ? 'pill-demo' : 'pill-green')}>{acc?.type === 'demo' ? 'Demo' : 'Live'}</span>
            <span className="mono" style={{ fontSize: 13 }}>#{acc?.number}</span>
          </div>
          <div className="mono" style={{ fontSize: 18, fontWeight: 600, marginTop: 4 }}>${acc?.balance.toFixed(2)}</div>
        </div>
        <I.chevD />
      </button>
      {open && (
        <div className="card" style={{ marginTop: 4, padding: 6 }}>
          {accounts.map(a => (
            <div key={a.id} onClick={() => { onChange(a.id); setOpen(false); }} className="row between" style={{
              padding: 10, borderRadius: 10, cursor: 'pointer',
              background: a.id === value ? 'var(--card-2)' : 'transparent'
            }}>
              <div className="row" style={{ gap: 8 }}>
                <span className={'pill ' + (a.type === 'demo' ? 'pill-demo' : 'pill-green')}>{a.type === 'demo' ? 'Demo' : 'Live'}</span>
                <span className="mono" style={{ fontSize: 13 }}>#{a.number}</span>
              </div>
              <span className="mono" style={{ fontSize: 13, color: 'var(--text-dim)' }}>${a.balance.toFixed(2)}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function History() {
  const { go, txns } = useApp();
  const [filter, setFilter] = useState('all');
  const filters = [['all','All'],['deposit','Deposits'],['withdraw','Withdrawals'],['transfer','Transfers']];
  const list = filter === 'all' ? txns : txns.filter(t => t.type === filter);

  // Group by date
  const groups = {};
  list.forEach(t => { (groups[t.date] = groups[t.date] || []).push(t); });

  return (
    <div className="screen with-tabs page-enter">
      <StatusBar />
      <AppBar title="History" large right={<button className="icon-btn"><I.filter size={18}/></button>} />
      <div style={{ padding: '0 20px 30px' }}>
        <div style={{ display: 'flex', gap: 8, overflowX: 'auto', margin: '0 -20px 16px', padding: '0 20px', scrollbarWidth: 'none' }}>
          {filters.map(([id, l]) => (
            <button key={id} onClick={() => setFilter(id)} style={{
              padding: '8px 14px', borderRadius: 999, fontSize: 13, fontWeight: 500,
              background: filter === id ? 'var(--green)' : 'var(--card)',
              color: filter === id ? '#0A0B0D' : 'var(--text-dim)',
              border: '1px solid ' + (filter === id ? 'var(--green)' : 'var(--line)'),
              cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap'
            }}>{l}</button>
          ))}
        </div>
        {Object.entries(groups).map(([date, items]) => (
          <div key={date} style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em', margin: '4px 4px 8px' }}>{date}</div>
            <div className="card" style={{ padding: 4 }}>
              {items.map((t, i) => <TxRow key={t.id} tx={t} last={i === items.length - 1} />)}
            </div>
          </div>
        ))}
        {list.length === 0 && (
          <div style={{ textAlign: 'center', padding: '60px 20px', color: 'var(--text-dim)' }}>
            <div style={{ fontSize: 14 }}>No transactions yet</div>
          </div>
        )}
      </div>
      <TabBar />
    </div>
  );
}

window.Deposit = Deposit;
window.Withdraw = Withdraw;
window.Transfer = Transfer;
window.History = History;
