/* ============================================================================
   BetPrince Sportsbook — Deposit Screen
   Tabs: Bank Transfer (Paystack) · Crypto · MTN Token
   Depends on sb-atoms.jsx. Exports to window.
   ============================================================================ */

function DepositScreen({ balance, onBack, theme, onUpdateBalance }) {
  const [tab, setTab] = useState('bank');
  const [amount, setAmount] = useState('');
  const [cryptoCoin, setCryptoCoin] = useState('usdt');
  const [mtnPhone, setMtnPhone] = useState('');
  const [mtnToken, setMtnToken] = useState('');
  const [processing, setProcessing] = useState(false);
  const [success, setSuccess] = useState(null);
  const [cryptoOpen, setCryptoOpen] = useState(false);

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

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

  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 handleDeposit = () => {
    if (!isValid) return;
    setProcessing(true);
    setTimeout(() => {
      setProcessing(false);
      onUpdateBalance && onUpdateBalance(numAmount);
      setSuccess(numAmount);
    }, 1800);
  };

  const handleSuccessDone = () => {
    setSuccess(null);
    setAmount('');
    onBack && onBack();
  };

  /* ---- Success overlay ---- */
  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 }}>Deposit Successful!</div>
        <div style={{ fontFamily: 'var(--font-text)', fontSize: 14, color: 'var(--ink-2)',
          marginBottom: 20, lineHeight: 1.5 }}>
          Your wallet has been credited.
        </div>
        <div className="sb-num" style={{ fontWeight: 700, fontSize: 36, color: 'var(--green)',
          letterSpacing: '-0.02em', marginBottom: 32 }}>
          +{fmtNGN(success)}
        </div>
        <GoldBtn full onClick={handleSuccessDone}>Done</GoldBtn>
      </div>
    );
  }

  /* ---- Processing overlay ---- */
  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(--blue)', borderRadius: 999, marginBottom: 24 }} />
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18,
          color: 'var(--ink)', marginBottom: 6 }}>Processing…</div>
        <div style={{ fontFamily: 'var(--font-text)', fontSize: 14, color: 'var(--ink-3)' }}>
          Please wait while we process your payment.
        </div>
      </div>
    );
  }

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

  const CRYPTO_OPTIONS = [
    { k: 'usdt', name: 'USDT (TRC-20)', symbol: 'USDT', color: '#26A17B',
      logo: 'https://cdn.crypto-logo.com/logos/tether-usdt/64x64/transparent.png' },
    { k: 'btc', name: 'Bitcoin', symbol: 'BTC', color: '#F7931A',
      logo: 'https://cdn.crypto-logo.com/logos/bitcoin-btc/64x64/transparent.png' },
    { k: 'trx', name: 'Tron', symbol: 'TRX', color: '#EF0027',
      logo: 'https://cdn.crypto-logo.com/logos/tron-trx/64x64/transparent.png' },
  ];
  const selectedCrypto = CRYPTO_OPTIONS.find(c => c.k === cryptoCoin);

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

      {/* Balance card */}
      <div style={{ margin: '14px 14px 6px', background: 'var(--card)', borderRadius: 16,
        border: '1px solid var(--line)', boxShadow: 'var(--shadow-card)', padding: '16px 18px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontFamily: 'var(--font-text)', fontWeight: 800, fontSize: 10.5,
            letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 4 }}>
            Current Balance
          </div>
          <div className="sb-num" style={{ fontWeight: 700, fontSize: 22, color: 'var(--ink)',
            letterSpacing: '-0.02em' }}>{fmtNGN(balance)}</div>
        </div>
        <div style={{ width: 44, height: 44, borderRadius: 14, background: 'var(--blue-tint)',
          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="wallet" size={22} color="var(--blue)" />
        </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(--blue)' : 'transparent',
            color: isActive ? '#fff' : 'var(--ink-3)',
            boxShadow: isActive ? '0 4px 12px rgba(37,54,216,0.25)' : 'none',
          }}>
            <span style={{ whiteSpace: 'nowrap' }}>{t.label}</span>
          </button>
          );
        })}
      </div>

      {/* Tab content */}
      <div style={{ padding: '0 14px 24px' }}>
        {/* ============ BANK TRANSFER ============ */}
        {tab === 'bank' && (
          <div>
            {/* Paystack branding */}
            <div style={{ margin: '18px 0 6px', display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 16px',
                background: 'var(--card)', borderRadius: 12, border: '1px solid var(--line)' }}>
                <img src={theme === 'dark' ? 'paystack-white.svg' : 'paystack-black.svg'} alt="Paystack"
                  style={{ height: 18, width: 'auto' }} />
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                <Icon name="shield-check" size={14} color="var(--green)" />
                <span style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 12,
                  color: 'var(--green)' }}>Secured</span>
              </div>
            </div>

            <div style={{ fontFamily: 'var(--font-text)', fontSize: 13, color: 'var(--ink-3)',
              marginBottom: 18 }}>
              Instant deposit via Paystack.
            </div>

            {/* Amount input */}
            <div style={{ marginBottom: 14 }}>
              <label style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 13,
                color: 'var(--ink-2)', display: 'block', marginBottom: 8 }}>Amount (NGN)</label>
              <div style={{ position: 'relative' }}>
                <span style={{ position: 'absolute', left: 16, top: '50%', transform: 'translateY(-50%)',
                  fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 18, 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: '16px 16px 16px 38px',
                    fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 22,
                    color: 'var(--ink)', background: 'var(--card)',
                    border: '2px solid ' + (amount && !isValid ? 'var(--live)' : 'var(--line-2)'),
                    borderRadius: 14, outline: 'none', boxSizing: 'border-box',
                    transition: 'border-color 180ms',
                    caretColor: 'var(--blue)',
                  }}
                  onFocus={(e) => { e.target.style.borderColor = 'var(--blue)'; }}
                  onBlur={(e) => { e.target.style.borderColor = amount && !isValid ? 'var(--live)' : 'var(--line-2)'; }}
                />
                <span style={{ position: 'absolute', right: 16, top: '50%', transform: 'translateY(-50%)',
                  fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 12, color: 'var(--ink-3)' }}>
                  min. ₦{MIN_DEPOSIT.toLocaleString('en-NG')}
                </span>
              </div>
              {amount && !isValid && (
                <div style={{ fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 12,
                  color: 'var(--live)', marginTop: 6, display: 'flex', alignItems: 'center', gap: 5 }}>
                  <Icon name="alert-circle" size={13} /> Minimum deposit is ₦{MIN_DEPOSIT.toLocaleString('en-NG')}
                </div>
              )}
            </div>

            {/* Quick amount chips */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 20 }}>
              {QUICK_AMOUNTS.map(v => {
                const isActive = numAmount === v;
                const has2x = v >= 100000;
                return (
                <button key={v + '-' + isActive} onClick={() => setAmount(v.toLocaleString('en-NG'))}
                  style={{ padding: has2x ? '10px 8px 12px' : '12px 8px', borderRadius: 11, cursor: 'pointer',
                    fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 14,
                    position: 'relative', overflow: 'hidden',
                    background: isActive ? 'var(--blue)' : 'var(--card)',
                    color: isActive ? '#fff' : 'var(--ink)',
                    border: '1px solid ' + (isActive ? 'var(--blue)' : 'var(--line-2)'),
                    boxShadow: isActive ? '0 4px 12px rgba(37,54,216,0.25)' : 'none',
                  }}>
                  {has2x && (
                    <span style={{ display: 'block', fontFamily: 'var(--font-text)', fontWeight: 800,
                      fontSize: 9.5, letterSpacing: '0.04em', marginBottom: 3,
                      color: isActive ? 'var(--gold)' : 'var(--gold-strong)' }}>2× BONUS</span>
                  )}
                  ₦{v.toLocaleString('en-NG')}
                </button>
                );
              })}
            </div>

            {/* CTA */}
            <button onClick={handleDeposit} disabled={!isValid}
              style={{ width: '100%', padding: '16px', border: 'none', borderRadius: 14,
                cursor: isValid ? 'pointer' : 'default',
                fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 16,
                background: isValid ? 'var(--blue)' : 'var(--line-2)',
                color: isValid ? '#fff' : 'var(--ink-3)',
                transition: 'box-shadow 180ms',
                boxShadow: isValid ? '0 8px 24px rgba(37,54,216,0.3)' : 'none',
              }}>
              Top Up Now
            </button>

            {/* Trust signals */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16,
              marginTop: 20, padding: '14px 0', borderTop: '1px solid var(--line)' }}>
              {[
                { icon: 'lock', label: 'Encrypted' },
                { icon: 'zap', label: 'Instant' },
              ].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 the amount to generate a deposit address.
            </div>

            {/* Crypto dropdown */}
            <div style={{ marginBottom: 18, position: 'relative' }}>
              <label style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 13,
                color: 'var(--ink-2)', display: 'block', marginBottom: 8 }}>Cryptocurrency</label>
              <button onClick={() => setCryptoOpen(!cryptoOpen)}
                style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12,
                  padding: '12px 16px', borderRadius: 14, cursor: 'pointer',
                  background: 'var(--card)',
                  border: '2px solid ' + (cryptoOpen ? 'var(--blue)' : 'var(--line-2)'),
                  transition: 'border-color 180ms',
                }}>
                <img src={selectedCrypto.logo} alt={selectedCrypto.symbol}
                  style={{ width: 32, height: 32, borderRadius: 999 }} />
                <div style={{ flex: 1, textAlign: 'left' }}>
                  <div style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 15,
                    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>

              {/* Dropdown menu */}
              {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_OPTIONS.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 ? 'var(--blue-tint)' : 'transparent',
                        transition: 'background 120ms',
                      }}>
                      <img src={c.logo} alt={c.symbol}
                        style={{ width: 30, height: 30, borderRadius: 999 }} />
                      <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(--blue)',
                          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          <Icon name="check" size={14} color="#fff" />
                        </span>
                      )}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Amount input (same as bank) */}
            <div style={{ marginBottom: 14 }}>
              <label style={{ fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 13,
                color: 'var(--ink-2)', display: 'block', marginBottom: 8 }}>Amount (NGN)</label>
              <div style={{ position: 'relative' }}>
                <span style={{ position: 'absolute', left: 16, top: '50%', transform: 'translateY(-50%)',
                  fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 18, 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: '16px 16px 16px 38px',
                    fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 22,
                    color: 'var(--ink)', background: 'var(--card)',
                    border: '2px solid var(--line-2)', borderRadius: 14, outline: 'none',
                    boxSizing: 'border-box', caretColor: 'var(--blue)',
                  }}
                  onFocus={(e) => { e.target.style.borderColor = 'var(--blue)'; }}
                  onBlur={(e) => { e.target.style.borderColor = 'var(--line-2)'; }}
                />
                <span style={{ position: 'absolute', right: 16, top: '50%', transform: 'translateY(-50%)',
                  fontFamily: 'var(--font-text)', fontWeight: 600, fontSize: 12, color: 'var(--ink-3)' }}>
                  min. ₦{MIN_DEPOSIT.toLocaleString('en-NG')}
                </span>
              </div>
            </div>

            {/* Quick amounts */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 20 }}>
              {QUICK_AMOUNTS.map(v => {
                const isActive = numAmount === v;
                const has2x = v >= 100000;
                return (
                <button key={v + '-' + isActive} onClick={() => setAmount(v.toLocaleString('en-NG'))}
                  style={{ padding: has2x ? '10px 8px 12px' : '12px 8px', borderRadius: 11, cursor: 'pointer',
                    fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 14,
                    position: 'relative', overflow: 'hidden',
                    background: isActive ? 'var(--blue)' : 'var(--card)',
                    color: isActive ? '#fff' : 'var(--ink)',
                    border: '1px solid ' + (isActive ? 'var(--blue)' : 'var(--line-2)'),
                    boxShadow: isActive ? '0 4px 12px rgba(37,54,216,0.25)' : 'none',
                  }}>
                  {has2x && (
                    <span style={{ display: 'block', fontFamily: 'var(--font-text)', fontWeight: 800,
                      fontSize: 9.5, letterSpacing: '0.04em', marginBottom: 3,
                      color: isActive ? 'var(--gold)' : 'var(--gold-strong)' }}>2× BONUS</span>
                  )}
                  ₦{v.toLocaleString('en-NG')}
                </button>
                );
              })}
            </div>

            <button onClick={handleDeposit} disabled={!isValid}
              style={{ width: '100%', padding: '16px', border: 'none', borderRadius: 14,
                cursor: isValid ? 'pointer' : 'default',
                fontFamily: 'var(--font-text)', fontWeight: 700, fontSize: 16,
                background: isValid ? 'var(--blue)' : 'var(--line-2)',
                color: isValid ? '#fff' : 'var(--ink-3)',
                transition: 'box-shadow 180ms',
                boxShadow: isValid ? '0 8px 24px rgba(37,54,216,0.3)' : 'none',
              }}>
              Generate Address
            </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 }}>
                  Send only the exact amount to the generated address. Crypto deposits
                  are confirmed after 1 network confirmation.
                </div>
              </div>
            </div>
          </div>
        )}


      </div>
    </div>
  );
}

Object.assign(window, { DepositScreen });
