/* ============================================================================
   BetPrince Sportsbook — Withdraw Screen
   Tabs: Bank Transfer (7 Nigerian banks) · Crypto
   Confirmation modal with validation.
   Depends on sb-atoms.jsx + sb-info-screens.jsx (InfoHeader).
   ============================================================================ */

const _NL = 'https://nigerialogos.com/logos/';
const NIGERIAN_BANKS = [
  { k: 'access',   name: 'Access Bank',   color: '#F37021', short: 'AB', logo: _NL + 'access_bank/access_bank.svg' },
  { k: 'gtb',      name: 'GTBank',        color: '#E04E14', short: 'GT', logo: _NL + 'guaranty_trust_bank/guaranty_trust_bank.svg' },
  { k: 'firstbank',name: 'First Bank',    color: '#002D62', short: 'FB', logo: _NL + 'first_bank/first_bank.svg' },
  { k: 'uba',      name: 'UBA',           color: '#E30613', short: 'UB', logo: _NL + 'united_bank_for_africa/united_bank_for_africa.svg' },
  { k: 'zenith',   name: 'Zenith Bank',   color: '#E30613', short: 'ZB', logo: _NL + 'zenith_bank/zenith_bank.svg' },
  { k: 'fidelity', name: 'Fidelity Bank', color: '#00205B', short: 'FD', logo: _NL + 'fidelity_bank/fidelity_bank.svg' },
  { k: 'opay',     name: 'OPay',          color: '#1DCE59', short: 'OP', logo: 'banks/opay.png' },
  { k: 'moniepoint', name: 'Moniepoint', color: '#0055FF', short: 'MP', logo: _NL + 'moniepoint/moniepoint.svg' },
  { k: 'kuda',     name: 'Kuda',          color: '#40196D', short: 'KD', logo: _NL + 'kuda_bank/kuda_bank.svg' },
  { k: 'paga',     name: 'Paga',          color: '#0B2559', short: 'PG', logo: _NL + 'paga/paga.svg' },
];

const CRYPTO_WITHDRAW = [
  { k: 'usdt', name: 'USDT (TRC-20)', symbol: 'USDT', color: '#26A17B' },
  { k: 'btc',  name: 'Bitcoin',       symbol: 'BTC',  color: '#F7931A' },
  { k: 'trx',  name: 'Tron',          symbol: 'TRX',  color: '#EF0027' },
];

/* mock account name resolver */
const MOCK_NAMES = [
  'ADEYEMI O****', 'CHUKWU E****', 'IBRAHIM M****', 'OKONKWO C****',
  'BALOGUN A****', 'EMEKA J****',  'ABIODUN T****',
];

function BankLogo({ bank, size = 32 }) {
  const [failed, setFailed] = useState(false);
  if (bank.logo && !failed) {
    return (
      <span style={{ width: size, height: size, borderRadius: 8, overflow: 'hidden',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        background: '#fff' }}>
        <img src={bank.logo} alt={bank.name} style={{ width: '100%', height: '100%', objectFit: 'contain' }}
          onError={() => setFailed(true)} />
      </span>
    );
  }
  return (
    <span style={{ width: size, height: size, borderRadius: 8, background: bank.color,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: size * 0.34,
      color: '#fff', letterSpacing: '-0.02em' }}>
      {bank.short}
    </span>
  );
}

function WithdrawScreen({ balance, onBack, theme, onUpdateBalance }) {
  const [tab, setTab] = useState('bank');
  const [selectedBank, setSelectedBank] = useState(null);
  const [bankOpen, setBankOpen] = useState(false);
  const [acctNum, setAcctNum] = useState('');
  const [acctName, setAcctName] = useState('');
  const [amount, setAmount] = useState('');
  const [showConfirm, setShowConfirm] = useState(false);
  const [error, setError] = useState(null);
  const [processing, setProcessing] = useState(false);
  const [success, setSuccess] = useState(null);
  const [showHint, setShowHint] = useState(false);

  /* crypto state */
  const [cryptoCoin, setCryptoCoin] = useState('usdt');
  const [cryptoOpen, setCryptoOpen] = useState(false);
  const [walletAddr, setWalletAddr] = useState('');
  const selectedCrypto = CRYPTO_WITHDRAW.find(c => c.k === cryptoCoin);

  const MIN_WITHDRAW = 100000;
  const withdrawableBalance = balance; // in real app this could differ

  const QUICK_AMOUNTS = [100000, 200000, 300000, 400000, 500000];

  const formatInput = (val) => {
    const digits = val.replace(/[^0-9]/g, '').slice(0, 7); // cap at 9,999,999
    if (!digits) return '';
    return Number(digits).toLocaleString('en-NG');
  };

  const numAmount = parseInt(amount.replace(/,/g, ''), 10) || 0;

  /* mock: "resolve" account name after 10 digits entered */
  useEffect(() => {
    if (acctNum.length === 10 && selectedBank) {
      const idx = Math.abs([...acctNum].reduce((a, c) => a + c.charCodeAt(0), 0)) % MOCK_NAMES.length;
      setAcctName(MOCK_NAMES[idx]);
    } else {
      setAcctName('');
    }
  }, [acctNum, selectedBank]);

  const canProceed = tab === 'bank'
    ? (selectedBank && acctNum.length === 10 && numAmount > 0)
    : (walletAddr.length >= 20 && numAmount > 0);

  const handleWithdraw = () => {
    setError(null);
    setShowConfirm(true);
  };

  const handleConfirm = () => {
    /* validation happens on confirm click */
    if (numAmount > balance) {
      setError('insufficient');
      return;
    }
    if (numAmount < MIN_WITHDRAW) {
      setError('minimum');
      return;
    }
    setError(null);
    setShowConfirm(false);
    setProcessing(true);
    setTimeout(() => {
      setProcessing(false);
      setSuccess(numAmount);
      if (onUpdateBalance) onUpdateBalance(-numAmount);
    }, 2000);
  };

  const handleDone = () => {
    setSuccess(null);
    setAmount('');
    setAcctNum('');
    setAcctName('');
    setSelectedBank(null);
    setWalletAddr('');
    onBack && onBack();
  };

  const maskAcct = (num) => {
    if (num.length < 4) return num;
    return '****' + num.slice(-4);
  };

  /* ---- Success ---- */
  if (success) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center',
        justifyContent: 'center', padding: '60px 30px', textAlign: 'center', minHeight: '70vh' }}>
        <div style={{ width: 80, height: 80, borderRadius: 999, background: 'var(--green)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 24,
          boxShadow: '0 12px 32px rgba(22,163,74,0.3)' }}>
          <Icon name="check" size={40} color="#fff" />
        </div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22,
          color: 'var(--ink)', marginBottom: 8 }}>Withdrawal Submitted!</div>
        <div style={{ fontFamily: 'var(--font-text)', fontSize: 14, color: 'var(--ink-2)',
          marginBottom: 6, lineHeight: 1.5 }}>
          Your withdrawal is being processed.
        </div>
        <div style={{ fontFamily: 'var(--font-text)', fontSize: 13, color: 'var(--ink-3)',
          marginBottom: 20 }}>
          Estimated arrival: 5–30 minutes
        </div>
        <div className="sb-num" style={{ fontWeight: 700, fontSize: 36, color: 'var(--green)',
          letterSpacing: '-0.02em', marginBottom: 32 }}>
          -{fmtNGN(success)}
        </div>
        <GoldBtn full onClick={handleDone}>Done</GoldBtn>
      </div>
    );
  }

  /* ---- Processing ---- */
  if (processing) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center',
        justifyContent: 'center', padding: '80px 30px', textAlign: 'center', minHeight: '70vh' }}>
        <div className="deposit-spinner" style={{ width: 56, height: 56, border: '4px solid var(--line-2)',
          borderTopColor: 'var(--green)', borderRadius: 999, marginBottom: 24 }} />
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18,
          color: 'var(--ink)', marginBottom: 6 }}>Processing Withdrawal…</div>
        <div style={{ fontFamily: 'var(--font-text)', fontSize: 14, color: 'var(--ink-3)' }}>
          Please wait while we process your request.
        </div>
      </div>
    );
  }

  const tabs = [
    { k: 'bank', label: 'Bank Transfer' },
    { k: 'crypto', label: 'Crypto' },
  ];

  return (
    <div>
      <InfoHeader title="Withdraw" onBack={onBack} />

      {/* Balance rows — compact, no card */}
      <div style={{ margin: '14px 14px 2px', padding: '0 4px', position: 'relative' }}>
        {/* Balance row */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '10px 0', borderBottom: '1px solid var(--line)' }}>
          <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 13,
            color: 'var(--ink-3)' }}>Balance (NGN)</span>
          <span className="sb-num" style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)',
            letterSpacing: '-0.01em' }}>
            {Number(balance).toLocaleString('en-NG', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          </span>
        </div>
        {/* Withdrawable row */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '10px 0' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 13,
              color: 'var(--ink-3)' }}>Withdrawable Balance (NGN)</span>
            <button onClick={() => setShowHint(!showHint)}
              style={{ width: 17, height: 17, borderRadius: 999, border: '1.5px solid var(--green)',
                background: 'transparent', cursor: 'pointer', padding: 0,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 9, color: 'var(--green)' }}>?</button>
          </span>
          <span className="sb-num" style={{ fontWeight: 700, fontSize: 15, color: 'var(--green)',
            letterSpacing: '-0.01em' }}>
            {Number(withdrawableBalance).toLocaleString('en-NG', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          </span>
        </div>

        {/* Hint tooltip */}
        {showHint && (
          <div style={{ position: 'absolute', left: 0, right: 0, top: '100%', zIndex: 30,
            marginTop: 4, padding: '12px 14px', background: 'var(--card)', borderRadius: 12,
            border: '1px solid var(--line)', boxShadow: 'var(--shadow-pop)' }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
              <Icon name="info" size={15} color="var(--green)" style={{ flexShrink: 0, marginTop: 1 }} />
              <div style={{ fontFamily: 'var(--font-text)', fontSize: 12.5, color: 'var(--ink-2)',
                lineHeight: 1.55 }}>
                This is the balance you can withdraw. Deposited funds must be staked at least 1× before they become withdrawable. Winnings from bets are instantly withdrawable.
              </div>
            </div>
            <button onClick={() => setShowHint(false)}
              style={{ marginTop: 8, width: '100%', padding: '8px', borderRadius: 8,
                background: 'var(--card-2)', border: '1px solid var(--line)', cursor: 'pointer',
                fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12, color: 'var(--ink-3)' }}>
              Got it
            </button>
          </div>
        )}
      </div>

      {/* Method tabs */}
      <div style={{ display: 'flex', gap: 0, margin: '14px 14px 0', background: 'var(--card-2)',
        borderRadius: 14, padding: 4, border: '1px solid var(--line)' }}>
        {tabs.map(t => {
          const isActive = tab === t.k;
          return (
            <button key={t.k + '-' + isActive} onClick={() => setTab(t.k)} style={{
              flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              padding: '11px 6px', borderRadius: 11, border: 'none', cursor: 'pointer',
              fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12.5,
              background: isActive ? 'var(--green)' : 'transparent',
              color: isActive ? '#fff' : 'var(--ink-3)',
              boxShadow: isActive ? '0 4px 12px rgba(22,163,74,0.25)' : 'none',
            }}>
              <span style={{ whiteSpace: 'nowrap' }}>{t.label}</span>
            </button>
          );
        })}
      </div>

      <div style={{ padding: '0 14px 24px' }}>

        {/* ============ BANK TRANSFER ============ */}
        {tab === 'bank' && (
          <div>
            <div style={{ fontFamily: 'var(--font-text)', fontSize: 13, color: 'var(--ink-3)',
              margin: '18px 0 14px' }}>
              Select your bank and enter your account details.
            </div>

            {/* Bank selector */}
            <div style={{ marginBottom: 14, position: 'relative' }}>
              <label style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12.5,
                color: 'var(--ink-2)', display: 'block', marginBottom: 6 }}>Bank</label>
              <button onClick={() => setBankOpen(!bankOpen)}
                style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                  padding: '11px 14px', borderRadius: 12, cursor: 'pointer',
                  background: 'var(--card)',
                  border: '1.5px solid ' + (bankOpen ? 'var(--green)' : 'var(--line-2)'),
                  transition: 'border-color 180ms',
                }}>
                {selectedBank ? (
                  <>
                    <BankLogo bank={selectedBank} size={26} />
                    <div style={{ flex: 1, textAlign: 'left' }}>
                      <div style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14,
                        color: 'var(--ink)' }}>{selectedBank.name}</div>
                    </div>
                  </>
                ) : (
                  <div style={{ flex: 1, textAlign: 'left' }}>
                    <div style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 14,
                      color: 'var(--ink-3)' }}>Select a bank</div>
                  </div>
                )}
                <span style={{ color: 'var(--ink-3)', transition: 'transform 180ms',
                  transform: bankOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                  display: 'inline-flex' }}>
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m6 9 6 6 6-6"></path></svg>
                </span>
              </button>

              {bankOpen && (
                <div style={{ position: 'absolute', left: 0, right: 0, top: '100%', zIndex: 20,
                  marginTop: 6, background: 'var(--card)', borderRadius: 14,
                  border: '1px solid var(--line)', boxShadow: 'var(--shadow-pop)',
                  overflow: 'hidden', maxHeight: 320, overflowY: 'auto' }}>
                  {NIGERIAN_BANKS.map(b => (
                    <button key={b.k} onClick={() => { setSelectedBank(b); setBankOpen(false); }}
                      style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12,
                        padding: '13px 16px', border: 'none', cursor: 'pointer',
                        borderBottom: '1px solid var(--line)',
                        background: selectedBank && selectedBank.k === b.k ? 'rgba(22,163,74,0.08)' : 'transparent',
                        transition: 'background 120ms',
                      }}>
                      <BankLogo bank={b} size={30} />
                      <div style={{ flex: 1, textAlign: 'left' }}>
                        <div style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14.5,
                          color: 'var(--ink)' }}>{b.name}</div>
                      </div>
                      {selectedBank && selectedBank.k === b.k && (
                        <span style={{ width: 22, height: 22, borderRadius: 999, background: 'var(--green)',
                          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          <Icon name="check" size={14} color="#fff" />
                        </span>
                      )}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Account number */}
            <div style={{ marginBottom: 14 }}>
              <label style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12.5,
                color: 'var(--ink-2)', display: 'block', marginBottom: 6 }}>Account Number</label>
              <input type="text" inputMode="numeric" placeholder="Enter 10-digit account number"
                maxLength={10}
                value={acctNum}
                onChange={(e) => setAcctNum(e.target.value.replace(/[^0-9]/g, '').slice(0, 10))}
                style={{ width: '100%', padding: '11px 14px',
                  fontFamily: 'var(--font-num)', fontWeight: 600, fontSize: 14,
                  color: 'var(--ink)', background: 'var(--card)',
                  border: '1.5px solid var(--line-2)', borderRadius: 12, outline: 'none',
                  boxSizing: 'border-box', caretColor: 'var(--green)',
                  letterSpacing: '0.06em',
                }}
                onFocus={(e) => { e.target.style.borderColor = 'var(--green)'; }}
                onBlur={(e) => { e.target.style.borderColor = 'var(--line-2)'; }}
              />
            </div>

            {/* Amount input */}
            <div style={{ marginBottom: 12 }}>
              <label style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12.5,
                color: 'var(--ink-2)', display: 'block', marginBottom: 6 }}>Amount (NGN)</label>
              <div style={{ position: 'relative' }}>
                <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)',
                  fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 15, color: 'var(--ink-3)' }}>₦</span>
                <input type="text" inputMode="numeric" placeholder="0"
                  value={amount}
                  onChange={(e) => setAmount(formatInput(e.target.value))}
                  style={{ width: '100%', padding: '11px 14px 11px 32px',
                    fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 17,
                    color: 'var(--ink)', background: 'var(--card)',
                    border: '1.5px solid var(--line-2)', borderRadius: 12, outline: 'none',
                    boxSizing: 'border-box', caretColor: 'var(--green)',
                  }}
                  onFocus={(e) => { e.target.style.borderColor = 'var(--green)'; }}
                  onBlur={(e) => { e.target.style.borderColor = 'var(--line-2)'; }}
                />
                <span style={{ position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)',
                  fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 11, color: 'var(--ink-3)' }}>
                  min. ₦{MIN_WITHDRAW.toLocaleString('en-NG')}
                </span>
              </div>
            </div>

            {/* Quick amounts */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6, marginBottom: 16 }}>
              {QUICK_AMOUNTS.map(v => {
                const isActive = numAmount === v;
                return (
                  <button key={v + '-' + isActive} onClick={() => setAmount(v.toLocaleString('en-NG'))}
                    style={{ padding: '9px 6px', borderRadius: 9, cursor: 'pointer',
                      fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 12.5,
                      background: isActive ? 'var(--green)' : 'var(--card)',
                      color: isActive ? '#fff' : 'var(--ink)',
                      border: '1px solid ' + (isActive ? 'var(--green)' : 'var(--line-2)'),
                      boxShadow: isActive ? '0 4px 12px rgba(22,163,74,0.25)' : 'none',
                    }}>
                    ₦{v.toLocaleString('en-NG')}
                  </button>
                );
              })}
            </div>

            {/* Withdraw CTA */}
            <button onClick={handleWithdraw} disabled={!canProceed}
              style={{ width: '100%', padding: '14px', border: 'none', borderRadius: 12,
                cursor: canProceed ? 'pointer' : 'default',
                fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 16,
                background: canProceed ? 'var(--green)' : 'var(--line-2)',
                color: canProceed ? '#fff' : 'var(--ink-3)',
                transition: 'box-shadow 180ms',
                boxShadow: canProceed ? '0 8px 24px rgba(22,163,74,0.3)' : 'none',
              }}>
              Withdraw
            </button>

            {/* Info */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16,
              marginTop: 20, padding: '14px 0', borderTop: '1px solid var(--line)' }}>
              {[
                { icon: 'lock', label: 'Secure' },
                { icon: 'clock', label: '5–30 min' },
              ].map((s, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                  <Icon name={s.icon} size={13} color="var(--ink-3)" />
                  <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 11.5,
                    color: 'var(--ink-3)' }}>{s.label}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* ============ CRYPTO ============ */}
        {tab === 'crypto' && (
          <div>
            <div style={{ fontFamily: 'var(--font-text)', fontSize: 13, color: 'var(--ink-3)',
              margin: '18px 0 14px' }}>
              Select a cryptocurrency and enter your wallet address.
            </div>

            {/* Crypto dropdown */}
            <div style={{ marginBottom: 14, position: 'relative' }}>
              <label style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12.5,
                color: 'var(--ink-2)', display: 'block', marginBottom: 6 }}>Cryptocurrency</label>
              <button onClick={() => setCryptoOpen(!cryptoOpen)}
                style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                  padding: '11px 14px', borderRadius: 12, cursor: 'pointer',
                  background: 'var(--card)',
                  border: '1.5px solid ' + (cryptoOpen ? 'var(--green)' : 'var(--line-2)'),
                  transition: 'border-color 180ms',
                }}>
                <span style={{ width: 26, height: 26, borderRadius: 999, background: selectedCrypto.color,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 9, color: '#fff' }}>
                  {selectedCrypto.symbol.slice(0, 2)}
                </span>
                <div style={{ flex: 1, textAlign: 'left' }}>
                  <div style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14,
                    color: 'var(--ink)' }}>{selectedCrypto.name}</div>
                  <div style={{ fontFamily: 'var(--font-text)', fontSize: 12, color: 'var(--ink-3)',
                    marginTop: 1 }}>{selectedCrypto.symbol}</div>
                </div>
                <span style={{ color: 'var(--ink-3)', transition: 'transform 180ms',
                  transform: cryptoOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                  display: 'inline-flex' }}>
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m6 9 6 6 6-6"></path></svg>
                </span>
              </button>

              {cryptoOpen && (
                <div style={{ position: 'absolute', left: 0, right: 0, top: '100%', zIndex: 20,
                  marginTop: 6, background: 'var(--card)', borderRadius: 14,
                  border: '1px solid var(--line)', boxShadow: 'var(--shadow-pop)',
                  overflow: 'hidden' }}>
                  {CRYPTO_WITHDRAW.map(c => (
                    <button key={c.k} onClick={() => { setCryptoCoin(c.k); setCryptoOpen(false); }}
                      style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12,
                        padding: '13px 16px', border: 'none', cursor: 'pointer',
                        borderBottom: '1px solid var(--line)',
                        background: cryptoCoin === c.k ? 'rgba(22,163,74,0.08)' : 'transparent',
                        transition: 'background 120ms',
                      }}>
                      <span style={{ width: 30, height: 30, borderRadius: 999, background: c.color,
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                        fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 10, color: '#fff' }}>
                        {c.symbol.slice(0, 2)}
                      </span>
                      <div style={{ flex: 1, textAlign: 'left' }}>
                        <div style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14.5,
                          color: 'var(--ink)' }}>{c.name}</div>
                        <div style={{ fontFamily: 'var(--font-text)', fontSize: 12, color: 'var(--ink-3)',
                          marginTop: 1 }}>{c.symbol}</div>
                      </div>
                      {cryptoCoin === c.k && (
                        <span style={{ width: 22, height: 22, borderRadius: 999, background: 'var(--green)',
                          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          <Icon name="check" size={14} color="#fff" />
                        </span>
                      )}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Wallet address */}
            <div style={{ marginBottom: 14 }}>
              <label style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12.5,
                color: 'var(--ink-2)', display: 'block', marginBottom: 6 }}>Wallet Address</label>
              <input type="text" placeholder="Paste your wallet address"
                value={walletAddr}
                onChange={(e) => setWalletAddr(e.target.value)}
                style={{ width: '100%', padding: '11px 14px',
                  fontFamily: 'var(--font-num)', fontWeight: 600, fontSize: 13,
                  color: 'var(--ink)', background: 'var(--card)',
                  border: '1.5px solid var(--line-2)', borderRadius: 12, outline: 'none',
                  boxSizing: 'border-box', caretColor: 'var(--green)',
                }}
                onFocus={(e) => { e.target.style.borderColor = 'var(--green)'; }}
                onBlur={(e) => { e.target.style.borderColor = 'var(--line-2)'; }}
              />
            </div>

            {/* Amount */}
            <div style={{ marginBottom: 12 }}>
              <label style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 12.5,
                color: 'var(--ink-2)', display: 'block', marginBottom: 6 }}>Amount (NGN)</label>
              <div style={{ position: 'relative' }}>
                <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)',
                  fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 15, color: 'var(--ink-3)' }}>₦</span>
                <input type="text" inputMode="numeric" placeholder="0"
                  value={amount}
                  onChange={(e) => setAmount(formatInput(e.target.value))}
                  style={{ width: '100%', padding: '11px 14px 11px 32px',
                    fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 17,
                    color: 'var(--ink)', background: 'var(--card)',
                    border: '1.5px solid var(--line-2)', borderRadius: 12, outline: 'none',
                    boxSizing: 'border-box', caretColor: 'var(--green)',
                  }}
                  onFocus={(e) => { e.target.style.borderColor = 'var(--green)'; }}
                  onBlur={(e) => { e.target.style.borderColor = 'var(--line-2)'; }}
                />
                <span style={{ position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)',
                  fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 11, color: 'var(--ink-3)' }}>
                  min. ₦{MIN_WITHDRAW.toLocaleString('en-NG')}
                </span>
              </div>
            </div>

            {/* Quick amounts */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6, marginBottom: 16 }}>
              {QUICK_AMOUNTS.map(v => {
                const isActive = numAmount === v;
                return (
                  <button key={v + '-' + isActive} onClick={() => setAmount(v.toLocaleString('en-NG'))}
                    style={{ padding: '9px 6px', borderRadius: 9, cursor: 'pointer',
                      fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 12.5,
                      background: isActive ? 'var(--green)' : 'var(--card)',
                      color: isActive ? '#fff' : 'var(--ink)',
                      border: '1px solid ' + (isActive ? 'var(--green)' : 'var(--line-2)'),
                      boxShadow: isActive ? '0 4px 12px rgba(22,163,74,0.25)' : 'none',
                    }}>
                    ₦{v.toLocaleString('en-NG')}
                  </button>
                );
              })}
            </div>

            <button onClick={handleWithdraw} disabled={!canProceed}
              style={{ width: '100%', padding: '14px', border: 'none', borderRadius: 12,
                cursor: canProceed ? 'pointer' : 'default',
                fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 16,
                background: canProceed ? 'var(--green)' : 'var(--line-2)',
                color: canProceed ? '#fff' : 'var(--ink-3)',
                transition: 'box-shadow 180ms',
                boxShadow: canProceed ? '0 8px 24px rgba(22,163,74,0.3)' : 'none',
              }}>
              Withdraw
            </button>

            <div style={{ marginTop: 18, padding: '14px', background: 'var(--card-2)',
              borderRadius: 12, border: '1px solid var(--line)' }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                <Icon name="info" size={16} color="var(--ink-3)" style={{ flexShrink: 0, marginTop: 2 }} />
                <div style={{ fontFamily: 'var(--font-text)', fontSize: 12.5, color: 'var(--ink-3)',
                  lineHeight: 1.5 }}>
                  Double-check your wallet address. Crypto withdrawals are irreversible
                  once confirmed on the network.
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* ============ CONFIRMATION MODAL (portaled to .phone) ============ */}
      {showConfirm && ReactDOM.createPortal(
        <>
          {/* scrim */}
          <div onClick={() => { setShowConfirm(false); setError(null); }}
            style={{ position: 'absolute', inset: 0, zIndex: 200, background: 'var(--scrim)' }} />
          {/* sheet */}
          <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 210,
            background: 'var(--card)', borderRadius: '24px 24px 0 0', boxShadow: 'var(--shadow-pop)',
            animation: 'confirmSlideUp 300ms cubic-bezier(0.22,1,0.36,1)',
          }}>
            <style>{`
              @keyframes confirmSlideUp {
                from { transform: translateY(100%); }
                to { transform: translateY(0); }
              }
              @keyframes confirmShake {
                0%, 100% { transform: translateX(0); }
                20%, 60% { transform: translateX(-6px); }
                40%, 80% { transform: translateX(6px); }
              }
            `}</style>

            {/* Header */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '20px 20px 16px' }}>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20,
                color: 'var(--ink)' }}>Confirm Withdrawal</span>
              <button onClick={() => { setShowConfirm(false); setError(null); }}
                style={{ background: 'transparent', border: 'none', cursor: 'pointer',
                  color: 'var(--ink-3)', padding: 4 }}>
                <Icon name="x" size={24} />
              </button>
            </div>

            {/* Details card */}
            <div style={{ margin: '0 16px 16px', background: 'var(--card-2)', borderRadius: 14,
              border: '1px solid var(--line)', padding: '14px 16px' }}>
              {/* Remaining */}
              <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0',
                borderBottom: '1px solid var(--line)' }}>
                <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 14,
                  color: 'var(--ink-3)' }}>Remaining Amount (NGN)</span>
                <span className="sb-num" style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)' }}>
                  {Math.max(0, balance - numAmount).toLocaleString('en-NG', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                </span>
              </div>
              {/* Withdraw to */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                padding: '8px 0', borderBottom: '1px solid var(--line)' }}>
                <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 14,
                  color: 'var(--ink-3)' }}>Withdraw To</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14,
                    color: 'var(--ink)' }}>
                    {tab === 'bank' && selectedBank ? selectedBank.name : selectedCrypto.name}
                  </span>
                  {tab === 'bank' && selectedBank && <BankLogo bank={selectedBank} size={24} />}
                </span>
              </div>
              {/* Account number / wallet */}
              <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0' }}>
                <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 14,
                  color: 'var(--ink-3)' }}>
                  {tab === 'bank' ? 'Account Number' : 'Wallet'}
                </span>
                <span className="sb-num" style={{ fontWeight: 700, fontSize: 14, color: 'var(--ink)' }}>
                  {tab === 'bank' ? maskAcct(acctNum) : (walletAddr.slice(0, 6) + '…' + walletAddr.slice(-4))}
                </span>
              </div>
            </div>

            {/* Amount card */}
            <div style={{ margin: '0 16px 16px', background: 'var(--card-2)', borderRadius: 14,
              border: '1px solid var(--line)', padding: '16px',
              display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17,
                  color: 'var(--ink)' }}>Withdrawal Amount</div>
                <div style={{ fontFamily: 'var(--font-text)', fontSize: 13, color: 'var(--ink-3)',
                  marginTop: 2 }}>(NGN)</div>
              </div>
              <span className="sb-num" style={{ fontWeight: 700, fontSize: 28, color: 'var(--ink)',
                letterSpacing: '-0.02em' }}>
                {Number(numAmount).toLocaleString('en-NG', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
              </span>
            </div>

            {/* Error messages */}
            {error && (
              <div style={{ margin: '0 16px 12px', padding: '12px 16px', borderRadius: 12,
                background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.25)',
                display: 'flex', alignItems: 'center', gap: 10,
                animation: 'confirmShake 400ms ease' }}>
                <Icon name="alert-circle" size={18} color="var(--live)" />
                <span style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 14,
                  color: 'var(--live)' }}>
                  {error === 'insufficient'
                    ? 'Insufficient balance for this withdrawal.'
                    : `Minimum withdrawal is ₦${MIN_WITHDRAW.toLocaleString('en-NG')}.`
                  }
                </span>
              </div>
            )}

            {/* Buttons */}
            <div style={{ display: 'flex', gap: 12, padding: '4px 16px 28px' }}>
              <button onClick={() => { setShowConfirm(false); setError(null); }}
                style={{ flex: 1, padding: '15px', borderRadius: 14, cursor: 'pointer',
                  fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 16,
                  background: 'transparent',
                  color: 'var(--green)', border: '2px solid var(--green)',
                }}>
                Cancel
              </button>
              <button onClick={handleConfirm}
                style={{ flex: 1, padding: '15px', borderRadius: 14, cursor: 'pointer',
                  fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 16,
                  background: 'var(--green)', color: '#fff', border: '2px solid var(--green)',
                  boxShadow: '0 6px 20px rgba(22,163,74,0.3)',
                }}>
                Confirm
              </button>
            </div>
          </div>
        </>,
        document.querySelector('.phone')
      )}
    </div>
  );
}

Object.assign(window, { WithdrawScreen });
