/**
 * CoinRush Wallet Modals V2 - Ultra Premium
 * Psychology-driven UX with gamification elements
 * Includes Cryptocurrency Payment Options (Demo Mode)
 */

const { useState, useEffect, useRef, useCallback, useMemo } = React;

// ============================================
// UTILITIES
// ============================================
const formatBalance = (cents) => ((cents || 0) / 100).toLocaleString('en-US', { 
  minimumFractionDigits: 2, 
  maximumFractionDigits: 2 
});

const formatCurrency = (value) => {
  const num = parseFloat(value) || 0;
  return num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

// Bonus tiers for gamification
const BONUS_TIERS = [
  { min: 0, max: 50, bonus: 0, label: 'No bonus' },
  { min: 50, max: 100, bonus: 2, label: '+2% Bonus' },
  { min: 100, max: 250, bonus: 5, label: '+5% Bonus' },
  { min: 250, max: 500, bonus: 8, label: '+8% Bonus' },
  { min: 500, max: Infinity, bonus: 10, label: '+10% Bonus' },
];

const getBonusTier = (amount) => {
  return BONUS_TIERS.find(t => amount >= t.min && amount < t.max) || BONUS_TIERS[0];
};

const getNextTier = (amount) => {
  const currentIndex = BONUS_TIERS.findIndex(t => amount >= t.min && amount < t.max);
  return BONUS_TIERS[currentIndex + 1] || null;
};

// ============================================
// PAYMENT METHODS CONFIGURATION
// ============================================
const PAYMENT_METHODS = {
  crypto: [
    { 
      id: 'btc', 
      name: 'Bitcoin', 
      symbol: 'BTC', 
      color: '#F7931A', 
      network: 'Bitcoin Network',
      minDeposit: 0.0001,
      confirmations: 3,
      estimatedTime: '10-60 min',
      address: '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
      popular: true
    },
    { 
      id: 'eth', 
      name: 'Ethereum', 
      symbol: 'ETH', 
      color: '#627EEA', 
      network: 'ERC-20',
      minDeposit: 0.001,
      confirmations: 12,
      estimatedTime: '2-5 min',
      address: '0x742d35Cc6634C0532925a3b844Bc9e7595f8EdE8',
      popular: true
    },
    { 
      id: 'usdt', 
      name: 'Tether', 
      symbol: 'USDT', 
      color: '#26A17B', 
      network: 'TRC-20',
      networks: ['ERC-20', 'TRC-20', 'BEP-20'],
      minDeposit: 10,
      confirmations: 1,
      estimatedTime: '1-5 min',
      address: 'TN8sL5FFvJGT3c8PN7V6PPLZ5WVfYqZU3e',
      popular: true
    },
    { 
      id: 'usdc', 
      name: 'USD Coin', 
      symbol: 'USDC', 
      color: '#2775CA', 
      network: 'ERC-20',
      networks: ['ERC-20', 'Solana', 'Polygon'],
      minDeposit: 10,
      confirmations: 12,
      estimatedTime: '2-5 min',
      address: '0x742d35Cc6634C0532925a3b844Bc9e7595f8EdE8'
    },
    { 
      id: 'ltc', 
      name: 'Litecoin', 
      symbol: 'LTC', 
      color: '#BFBBBB', 
      network: 'Litecoin',
      minDeposit: 0.01,
      confirmations: 6,
      estimatedTime: '5-30 min',
      address: 'LcHK6vhPSr8E8KcexNokiEwQi6hh8Zc8XV'
    },
    { 
      id: 'sol', 
      name: 'Solana', 
      symbol: 'SOL', 
      color: '#9945FF', 
      network: 'Solana',
      minDeposit: 0.1,
      confirmations: 1,
      estimatedTime: '< 1 min',
      address: '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU'
    },
    { 
      id: 'doge', 
      name: 'Dogecoin', 
      symbol: 'DOGE', 
      color: '#C2A633', 
      network: 'Dogecoin',
      minDeposit: 50,
      confirmations: 6,
      estimatedTime: '10-30 min',
      address: 'DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L'
    },
    { 
      id: 'bnb', 
      name: 'BNB', 
      symbol: 'BNB', 
      color: '#F3BA2F', 
      network: 'BEP-20',
      minDeposit: 0.01,
      confirmations: 15,
      estimatedTime: '2-5 min',
      address: '0x742d35Cc6634C0532925a3b844Bc9e7595f8EdE8'
    }
  ],
  fiat: [
    { id: 'card', name: 'Credit/Debit Card', icon: 'card', fee: '2.5%', instant: true },
    { id: 'bank', name: 'Bank Transfer', icon: 'bank', fee: 'Free', instant: false }
  ]
};

// ============================================
// ICONS - Refined SVGs
// ============================================
const CloseIcon = () => (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
    <line x1="18" y1="6" x2="6" y2="18"></line>
    <line x1="6" y1="6" x2="18" y2="18"></line>
  </svg>
);

const CheckIcon = () => (
  <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
    <polyline points="20 6 9 17 4 12"></polyline>
  </svg>
);

const ShieldCheckIcon = () => (
  <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
    <polyline points="9 12 11 14 15 10"></polyline>
  </svg>
);

const LockIcon = () => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
    <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
  </svg>
);

const ArrowDownIcon = () => (
  <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 5v14"/>
    <path d="M19 12l-7 7-7-7"/>
  </svg>
);

const ArrowUpIcon = () => (
  <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 19V5"/>
    <path d="M5 12l7-7 7 7"/>
  </svg>
);

const WalletIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/>
    <path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/>
    <path d="M18 12a2 2 0 0 0 0 4h4v-4h-4z"/>
  </svg>
);

const SparklesIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3z"/>
    <path d="M5 19l.5 1.5L7 21l-1.5.5L5 23l-.5-1.5L3 21l1.5-.5L5 19z"/>
    <path d="M19 5l.5 1.5L21 7l-1.5.5L19 9l-.5-1.5L17 7l1.5-.5L19 5z"/>
  </svg>
);

const InfoIcon = () => (
  <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="10"></circle>
    <line x1="12" y1="16" x2="12" y2="12"></line>
    <line x1="12" y1="8" x2="12.01" y2="8"></line>
  </svg>
);

const SpinnerIcon = ({ size = 24 }) => (
  <svg className="wallet-spinner" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
    <circle cx="12" cy="12" r="10" strokeOpacity="0.15"/>
    <path d="M12 2a10 10 0 0 1 10 10"/>
  </svg>
);

const GiftIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <polyline points="20 12 20 22 4 22 4 12"></polyline>
    <rect x="2" y="7" width="20" height="5"></rect>
    <line x1="12" y1="22" x2="12" y2="7"></line>
    <path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"></path>
    <path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"></path>
  </svg>
);

// Cryptocurrency Icons
const BitcoinIcon = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
    <circle cx="16" cy="16" r="16" fill="#F7931A"/>
    <path d="M22.5 14.2c.3-2-1.2-3.1-3.3-3.8l.7-2.7-1.6-.4-.7 2.6c-.4-.1-.8-.2-1.3-.3l.7-2.7-1.6-.4-.7 2.7c-.3-.1-.7-.2-1-.2v0l-2.2-.6-.4 1.7s1.2.3 1.2.3c.7.2.8.6.8 1l-.8 3.2c0 0 .1 0 .2.1h-.2l-1.1 4.5c-.1.2-.3.5-.8.4 0 0-1.2-.3-1.2-.3l-.8 1.9 2.1.5c.4.1.8.2 1.2.3l-.7 2.8 1.6.4.7-2.7c.4.1.9.2 1.3.3l-.7 2.7 1.6.4.7-2.8c2.9.5 5.1.3 6-2.3.7-2.1 0-3.3-1.5-4.1 1.1-.3 1.9-1 2.1-2.5zm-3.8 5.3c-.5 2.1-4 1-5.1.7l.9-3.7c1.1.3 4.8.8 4.2 3zm.5-5.4c-.5 1.9-3.4.9-4.3.7l.8-3.3c1 .2 4 .7 3.5 2.6z" fill="white"/>
  </svg>
);

const EthereumIcon = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
    <circle cx="16" cy="16" r="16" fill="#627EEA"/>
    <path d="M16 4v8.9l7.5 3.3L16 4z" fill="white" fillOpacity="0.6"/>
    <path d="M16 4l-7.5 12.2 7.5-3.3V4z" fill="white"/>
    <path d="M16 21.9v6.1l7.5-10.4L16 21.9z" fill="white" fillOpacity="0.6"/>
    <path d="M16 28v-6.1l-7.5-4.3L16 28z" fill="white"/>
    <path d="M16 20.4l7.5-4.2-7.5-3.3v7.5z" fill="white" fillOpacity="0.2"/>
    <path d="M8.5 16.2l7.5 4.2v-7.5l-7.5 3.3z" fill="white" fillOpacity="0.6"/>
  </svg>
);

const TetherIcon = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
    <circle cx="16" cy="16" r="16" fill="#26A17B"/>
    <path d="M17.9 17.9v0c-.1 0-.6 0-1.9 0s-1.6 0-1.9 0v0c-3.8-.2-6.6-.9-6.6-1.7 0-.8 2.8-1.5 6.6-1.7v2.8c.3 0 .8.1 1.9.1s1.7 0 1.9-.1v-2.8c3.8.2 6.6.9 6.6 1.7 0 .8-2.8 1.5-6.6 1.7zm0-3.7v-2.5h5.3V8H8.9v3.7h5.3v2.5c-4.3.2-7.5 1.1-7.5 2.2 0 1.1 3.2 2 7.5 2.2v7.9h3.7v-7.9c4.2-.2 7.4-1.1 7.4-2.2 0-1.1-3.2-2-7.4-2.2z" fill="white"/>
  </svg>
);

const UsdcIcon = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
    <circle cx="16" cy="16" r="16" fill="#2775CA"/>
    <path d="M20.5 18.5c0-2-1.2-2.7-3.7-3-.8-.2-2-.3-2.2-1-.2-.5.1-1.1.8-1.2.9-.2 1.8.1 2.6.5l.5-1.5c-.8-.4-1.6-.6-2.4-.6v-1.5h-1.5v1.5c-1.9.3-3 1.6-2.7 3.3.3 1.6 1.4 2.2 3.2 2.5 1.3.3 2.6.4 2.5 1.4-.1.7-.9 1-1.9.9-.9 0-2-.4-2.7-.9l-.6 1.6c.8.5 1.9.8 2.8.9v1.6h1.5v-1.6c2-.3 3.2-1.4 2.8-3.4z" fill="white"/>
    <path d="M13 24.5c-4.4-1.4-6.8-6.2-5.4-10.6 1.4-4.4 6.2-6.8 10.6-5.4" stroke="white" strokeWidth="1.5" strokeLinecap="round"/>
    <path d="M19 7.5c4.4 1.4 6.8 6.2 5.4 10.6-1.4 4.4-6.2 6.8-10.6 5.4" stroke="white" strokeWidth="1.5" strokeLinecap="round"/>
  </svg>
);

const LitecoinIcon = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
    <circle cx="16" cy="16" r="16" fill="#345D9D"/>
    <path d="M16 6l-4.5 13h3.3l-.9 2.7-2.5.8-.6 2h12.7l.8-2.5h-7.2l.9-2.7 2.5-.8.6-2h-3.3L16 6z" fill="white"/>
  </svg>
);

const SolanaIcon = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
    <circle cx="16" cy="16" r="16" fill="#000"/>
    <defs>
      <linearGradient id="solGrad" x1="0%" y1="0%" x2="100%" y2="100%">
        <stop offset="0%" stopColor="#00FFA3"/>
        <stop offset="100%" stopColor="#DC1FFF"/>
      </linearGradient>
    </defs>
    <path d="M9.5 19.5l2.2-2.2c.1-.1.3-.2.5-.2h11.2c.3 0 .5.4.3.6l-2.2 2.2c-.1.1-.3.2-.5.2H9.8c-.3 0-.5-.4-.3-.6z" fill="url(#solGrad)"/>
    <path d="M9.5 10.5l2.2 2.2c.1.1.3.2.5.2h11.2c.3 0 .5-.4.3-.6l-2.2-2.2c-.1-.1-.3-.2-.5-.2H9.8c-.3 0-.5.4-.3.6z" fill="url(#solGrad)"/>
    <path d="M21.5 14.5l-2.2 2.2c-.1.1-.3.2-.5.2H7.6c-.3 0-.5-.4-.3-.6l2.2-2.2c.1-.1.3-.2.5-.2h11.2c.3 0 .5.4.3.6z" fill="url(#solGrad)"/>
  </svg>
);

const DogeIcon = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
    <circle cx="16" cy="16" r="16" fill="#C2A633"/>
    <path d="M13 8h5c4.4 0 8 3.6 8 8s-3.6 8-8 8h-5V8zm3 3v10h2c2.8 0 5-2.2 5-5s-2.2-5-5-5h-2z" fill="white"/>
    <path d="M11 14h8v3h-8z" fill="white"/>
  </svg>
);

const BnbIcon = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
    <circle cx="16" cy="16" r="16" fill="#F3BA2F"/>
    <path d="M16 7l2.5 2.5-4.8 4.8-2.5-2.5L16 7zm6.3 6.3l2.5 2.5-9.3 9.2-2.5-2.5 9.3-9.2zm-9.1 0l2.5 2.5-2.5 2.5-2.5-2.5 2.5-2.5zm-6.2 0l2.5 2.5-2.5 2.5-2.5-2.5 2.5-2.5z" fill="white"/>
  </svg>
);

const CardIcon = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect>
    <line x1="1" y1="10" x2="23" y2="10"></line>
  </svg>
);

const BankIcon = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M3 21h18"/>
    <path d="M3 10h18"/>
    <path d="M5 6l7-3 7 3"/>
    <path d="M4 10v11"/>
    <path d="M20 10v11"/>
    <path d="M8 10v11"/>
    <path d="M12 10v11"/>
    <path d="M16 10v11"/>
  </svg>
);

const CopyIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
  </svg>
);

const QrCodeIcon = ({ size = 20 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect x="3" y="3" width="7" height="7"></rect>
    <rect x="14" y="3" width="7" height="7"></rect>
    <rect x="3" y="14" width="7" height="7"></rect>
    <rect x="14" y="14" width="4" height="4"></rect>
    <line x1="21" y1="14" x2="21" y2="21"></line>
    <line x1="14" y1="21" x2="21" y2="21"></line>
  </svg>
);

// Additional icons for premium UI (replacing emojis)
const ShieldIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
  </svg>
);

const ZapIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon>
  </svg>
);

const TrendingUpIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <polyline points="23 6 13.5 15.5 8.5 10.5 1 18"></polyline>
    <polyline points="17 6 23 6 23 12"></polyline>
  </svg>
);

const AlertTriangleIcon = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path>
    <line x1="12" y1="9" x2="12" y2="13"></line>
    <line x1="12" y1="17" x2="12.01" y2="17"></line>
  </svg>
);

const StarIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" strokeWidth="1">
    <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
  </svg>
);

const CelebrationIcon = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M5.8 11.3 2 22l10.7-3.79"></path>
    <path d="M4 3h.01"></path>
    <path d="M22 8h.01"></path>
    <path d="M15 2h.01"></path>
    <path d="M22 20h.01"></path>
    <path d="m22 2-2.24.75a2.9 2.9 0 0 0-1.96 3.12v0c.1.86-.57 1.63-1.45 1.63h-.38c-.86 0-1.6.6-1.76 1.44L14 10"></path>
    <path d="m22 13-.82-.33c-.86-.34-1.82.2-1.98 1.11v0c-.11.7-.72 1.22-1.43 1.22H17"></path>
    <path d="m11 2 .33.82c.34.86-.2 1.82-1.11 1.98v0C9.52 4.9 9 5.52 9 6.23V7"></path>
    <path d="M11 13c1.93 1.93 2.83 4.17 2 5-.83.83-3.07-.07-5-2-1.93-1.93-2.83-4.17-2-5 .83-.83 3.07.07 5 2Z"></path>
  </svg>
);

const CoinsIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="8" cy="8" r="6"></circle>
    <path d="M18.09 10.37A6 6 0 1 1 10.34 18"></path>
    <path d="M7 6h1v4"></path>
    <path d="m16.71 13.88.7.71-2.82 2.82"></path>
  </svg>
);

const ClockIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="10"></circle>
    <polyline points="12 6 12 12 16 14"></polyline>
  </svg>
);

// Get crypto icon component
const getCryptoIcon = (id, size = 24) => {
  const icons = {
    btc: BitcoinIcon,
    eth: EthereumIcon,
    usdt: TetherIcon,
    usdc: UsdcIcon,
    ltc: LitecoinIcon,
    sol: SolanaIcon,
    doge: DogeIcon,
    bnb: BnbIcon
  };
  const IconComponent = icons[id];
  return IconComponent ? <IconComponent size={size} /> : null;
};

// ============================================
// 2FA SETUP COMPONENT
// ============================================
function TwoFactorSetup({ onSetupComplete, onCancel }) {
  const [step, setStep] = useState('loading');
  const [setupData, setSetupData] = useState(null);
  const [confirmCode, setConfirmCode] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const inputRefs = useRef([]);

  useEffect(() => {
    initSetup();
  }, []);

  useEffect(() => {
    if (step === 'setup' && inputRefs.current[0]) {
      inputRefs.current[0].focus();
    }
  }, [step]);

  const initSetup = async () => {
    try {
      const res = await fetch('/api/2fa/setup', { method: 'POST', credentials: 'include' });
      if (!res.ok) throw new Error('Failed to initialize 2FA');
      const data = await res.json();
      setSetupData(data);
      setStep('setup');
    } catch (err) {
      setError(err.message);
      setStep('error');
    }
  };

  const handleConfirm = async () => {
    if (confirmCode.length !== 6) {
      setError('Enter all 6 digits');
      return;
    }
    setIsLoading(true);
    setError('');
    try {
      const res = await fetch('/api/2fa/confirm', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ code: confirmCode })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.detail || 'Invalid code. Please try again.');
      setStep('success');
      setTimeout(() => onSetupComplete(), 1500);
    } catch (err) {
      setError(err.message || 'Invalid code. Please try again.');
      setConfirmCode('');
      inputRefs.current[0]?.focus();
    } finally {
      setIsLoading(false);
    }
  };

  const handleCodeInput = (index, value) => {
    if (!/^\d*$/.test(value)) return;
    const newCode = confirmCode.split('');
    newCode[index] = value;
    const updatedCode = newCode.join('').slice(0, 6);
    setConfirmCode(updatedCode);
    setError('');
    if (value && index < 5) inputRefs.current[index + 1]?.focus();
    if (updatedCode.length === 6) setTimeout(() => handleConfirm(), 100);
  };

  const handleKeyDown = (index, e) => {
    if (e.key === 'Backspace' && !confirmCode[index] && index > 0) {
      inputRefs.current[index - 1]?.focus();
    }
  };

  const handlePaste = (e) => {
    e.preventDefault();
    const pasted = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, 6);
    setConfirmCode(pasted);
    if (pasted.length === 6) setTimeout(() => handleConfirm(), 100);
  };

  if (step === 'loading') {
    return (
      <div className="wallet-modal-state">
        <div className="state-icon processing"><SpinnerIcon size={48} /></div>
        <h3>Setting Up Security</h3>
        <p>Generating your secure key...</p>
      </div>
    );
  }

  if (step === 'error') {
    return (
      <div className="wallet-modal-state">
        <div className="state-icon error">✕</div>
        <h3>Setup Failed</h3>
        <p>{error}</p>
        <button className="action-btn primary" onClick={onCancel}>Go Back</button>
      </div>
    );
  }

  if (step === 'success') {
    return (
      <div className="wallet-modal-state">
        <div className="state-icon success"><CheckIcon /></div>
        <h3>2FA Enabled!</h3>
        <p>Your account is now protected</p>
      </div>
    );
  }

  return (
    <div className="twofa-setup">
      <div className="twofa-header">
        <div className="twofa-icon shield"><ShieldCheckIcon /></div>
        <h2>Enable 2FA Protection</h2>
        <p>Add an extra layer of security</p>
      </div>

      <div className="setup-steps">
        <div className="setup-step">
          <span className="step-number">1</span>
          <div className="step-content">
            <h4>Get Google Authenticator</h4>
            <p>Download from App Store or Play Store</p>
          </div>
        </div>
        <div className="setup-step">
          <span className="step-number">2</span>
          <div className="step-content">
            <h4>Scan QR Code</h4>
            <p>Tap + in the app, then scan below</p>
          </div>
        </div>
      </div>

      <div className="qr-container">
        {setupData?.qr_code_data_url ? (
          <img src={setupData.qr_code_data_url} alt="QR Code" className="qr-image" />
        ) : (
          <div className="qr-loading"><SpinnerIcon size={32} /></div>
        )}
      </div>

      <details className="manual-key">
        <summary>Can't scan? Enter manually</summary>
        <code className="secret-key">{setupData?.secret}</code>
      </details>

      <div className="setup-step" style={{ marginBottom: '16px' }}>
        <span className="step-number">3</span>
        <div className="step-content">
          <h4>Enter 6-Digit Code</h4>
          <p>From your authenticator app</p>
        </div>
      </div>

      <div className="code-input-section">
        <div className="code-input-group" onPaste={handlePaste}>
          {[0, 1, 2, 3, 4, 5].map(i => (
            <input
              key={i}
              ref={el => inputRefs.current[i] = el}
              type="text"
              inputMode="numeric"
              maxLength={1}
              value={confirmCode[i] || ''}
              onChange={e => handleCodeInput(i, e.target.value)}
              onKeyDown={e => handleKeyDown(i, e)}
              className={`code-input ${confirmCode.length === 6 ? 'success' : (error ? 'error' : '')}`}
              disabled={isLoading}
            />
          ))}
        </div>
        {error && confirmCode.length < 6 && <p className="error-message" style={{ marginTop: '12px' }}>{error}</p>}
      </div>

      <div className="wallet-modal-actions">
        <button className="action-btn secondary" onClick={onCancel} disabled={isLoading}>Cancel</button>
        <button 
          className={`action-btn primary ${confirmCode.length === 6 ? 'pulse-ready' : ''}`} 
          onClick={handleConfirm} 
          disabled={isLoading || confirmCode.length !== 6}
        >
          {isLoading ? <SpinnerIcon size={20} /> : 'Enable 2FA'}
        </button>
      </div>
    </div>
  );
}

// ============================================
// 2FA VERIFY COMPONENT
// ============================================
function TwoFactorVerify({ onVerify, onCancel, isLoading, amount, type = 'withdraw' }) {
  const [code, setCode] = useState('');
  const [error, setError] = useState('');
  const inputRefs = useRef([]);

  useEffect(() => {
    inputRefs.current[0]?.focus();
  }, []);

  const handleCodeInput = (index, value) => {
    if (!/^\d*$/.test(value)) return;
    const newCode = code.split('');
    newCode[index] = value;
    const updatedCode = newCode.join('').slice(0, 6);
    setCode(updatedCode);
    setError('');
    if (value && index < 5) inputRefs.current[index + 1]?.focus();
    if (updatedCode.length === 6) handleSubmit(updatedCode);
  };

  const handleKeyDown = (index, e) => {
    if (e.key === 'Backspace' && !code[index] && index > 0) {
      inputRefs.current[index - 1]?.focus();
    }
  };

  const handlePaste = (e) => {
    e.preventDefault();
    const pasted = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, 6);
    setCode(pasted);
    if (pasted.length === 6) handleSubmit(pasted);
  };

  const handleSubmit = async (codeValue = code) => {
    if (codeValue.length !== 6) return;
    try {
      await onVerify(codeValue);
    } catch (err) {
      setError(err.message || 'Invalid code');
      setCode('');
      inputRefs.current[0]?.focus();
    }
  };

  return (
    <div className="twofa-verify">
      <div className="twofa-header">
        <div className="twofa-icon lock"><LockIcon style={{ width: 28, height: 28 }} /></div>
        <h2>Verify {type === 'deposit' ? 'Deposit' : 'Withdrawal'}</h2>
        <p className="verify-amount">
          {type === 'deposit' ? 'Depositing' : 'Withdrawing'} <strong>${formatBalance(amount)}</strong>
        </p>
      </div>

      <div className="code-input-section">
        <p>Enter your 6-digit authenticator code</p>
        <div className="code-input-group" onPaste={handlePaste}>
          {[0, 1, 2, 3, 4, 5].map(i => (
            <input
              key={i}
              ref={el => inputRefs.current[i] = el}
              type="text"
              inputMode="numeric"
              maxLength={1}
              value={code[i] || ''}
              onChange={e => handleCodeInput(i, e.target.value)}
              onKeyDown={e => handleKeyDown(i, e)}
              className={`code-input ${error ? 'error' : ''}`}
              disabled={isLoading}
            />
          ))}
        </div>
        {error && <p className="error-message" style={{ marginTop: '12px' }}>{error}</p>}
      </div>

      <div className="wallet-modal-actions">
        <button className="action-btn secondary" onClick={onCancel} disabled={isLoading}>Cancel</button>
        <button 
          className={`action-btn primary ${type}`} 
          onClick={() => handleSubmit()} 
          disabled={isLoading || code.length !== 6}
        >
          {isLoading ? <SpinnerIcon size={20} /> : 'Confirm'}
        </button>
      </div>
    </div>
  );
}

// ============================================
// CRYPTO DEPOSIT VIEW COMPONENT
// ============================================
function CryptoDepositView({ crypto, onBack, amount }) {
  const [copied, setCopied] = useState(false);
  const [selectedNetwork, setSelectedNetwork] = useState(crypto.network);

  const handleCopyAddress = () => {
    navigator.clipboard.writeText(crypto.address);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  // Generate simple QR code placeholder (in production, use a real QR library)
  const generateQRPlaceholder = () => {
    return (
      <div className="crypto-qr-code">
        <div className="qr-placeholder">
          <QrCodeIcon size={32} />
          <span>QR Code</span>
        </div>
        <div className="qr-label">Scan with your wallet</div>
      </div>
    );
  };

  return (
    <div className="crypto-deposit-view">
      <button className="crypto-back-btn" onClick={onBack}>
        ← Back to payment methods
      </button>

      <div className="crypto-deposit-header">
        <div className="crypto-icon-large">
          {getCryptoIcon(crypto.id, 48)}
        </div>
        <h3>Deposit {crypto.name}</h3>
        <p className="crypto-subtitle">Send {crypto.symbol} to the address below</p>
      </div>

      {crypto.networks && (
        <div className="network-selector">
          <label>Select Network</label>
          <div className="network-options">
            {crypto.networks.map(net => (
              <button
                key={net}
                className={`network-option ${selectedNetwork === net ? 'selected' : ''}`}
                onClick={() => setSelectedNetwork(net)}
              >
                {net}
              </button>
            ))}
          </div>
          <p className="network-warning">
            <AlertTriangleIcon size={13} /> Sending assets via wrong network may result in loss of funds
          </p>
        </div>
      )}

      {generateQRPlaceholder()}

      <div className="crypto-address-section">
        <label>Deposit Address ({selectedNetwork})</label>
        <div className="crypto-address-box">
          <code className="crypto-address">{crypto.address}</code>
          <button 
            className={`copy-btn ${copied ? 'copied' : ''}`}
            onClick={handleCopyAddress}
          >
            {copied ? '✓ Copied' : <><CopyIcon /> Copy</>}
          </button>
        </div>
      </div>

      <div className="crypto-info-grid">
        <div className="crypto-info-item">
          <span className="info-label">Minimum Deposit</span>
          <span className="info-value">{crypto.minDeposit} {crypto.symbol}</span>
        </div>
        <div className="crypto-info-item">
          <span className="info-label">Confirmations</span>
          <span className="info-value">{crypto.confirmations} blocks</span>
        </div>
        <div className="crypto-info-item">
          <span className="info-label">Estimated Time</span>
          <span className="info-value">{crypto.estimatedTime}</span>
        </div>
        <div className="crypto-info-item">
          <span className="info-label">Network Fee</span>
          <span className="info-value">Paid by you</span>
        </div>
      </div>

      <div className="demo-notice">
        <div className="demo-badge">DEMO MODE</div>
        <p>This is a demonstration. No real cryptocurrency transactions are processed.</p>
      </div>
    </div>
  );
}

// ============================================
// DEPOSIT MODAL
// ============================================
function DepositModal({ isOpen, onClose, userBalance, onBalanceUpdate }) {
  const [step, setStep] = useState('form');
  const [paymentType, setPaymentType] = useState('crypto'); // 'crypto' or 'fiat'
  const [selectedCrypto, setSelectedCrypto] = useState(null);
  const [pendingCrypto, setPendingCrypto] = useState(null); // Track crypto selection during 2FA flow
  const [amount, setAmount] = useState('');
  const [twoFaStatus, setTwoFaStatus] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [newBalance, setNewBalance] = useState(0);
  const modalRef = useRef(null);
  const inputRef = useRef(null);

  const QUICK_AMOUNTS = [10, 25, 50, 100, 250, 500];
  const amountNum = parseFloat(amount || 0);
  const amountInCents = amountNum * 100;
  const minDeposit = 100;
  const isValidAmount = amountInCents >= minDeposit;
  const requires2FA = amountInCents >= 5000;
  
  // Bonus tier calculation
  const currentTier = getBonusTier(amountNum);
  const nextTier = getNextTier(amountNum);
  const bonusAmount = (amountNum * currentTier.bonus / 100).toFixed(2);
  const totalWithBonus = (amountNum + parseFloat(bonusAmount)).toFixed(2);

  useEffect(() => {
    if (isOpen) {
      check2FAStatus();
      document.body.style.overflow = 'hidden';
      setTimeout(() => inputRef.current?.focus(), 100);
    } else {
      document.body.style.overflow = '';
      setStep('form');
      setPaymentType('crypto');
      setSelectedCrypto(null);
      setPendingCrypto(null);
      setAmount('');
      setError('');
    }
    return () => { document.body.style.overflow = ''; };
  }, [isOpen]);

  const check2FAStatus = async () => {
    try {
      const res = await fetch('/api/2fa/status', { credentials: 'include' });
      if (res.ok) setTwoFaStatus(await res.json());
    } catch (err) { console.error('2FA check failed:', err); }
  };

  const handleBackdropClick = (e) => {
    if (e.target === modalRef.current) onClose();
  };

  const handleSelectCrypto = (crypto) => {
    if (!isValidAmount) {
      setError('Please enter a valid deposit amount first (minimum $1.00)');
      return;
    }
    
    // For crypto deposits >= $50, require 2FA first
    if (requires2FA) {
      setPendingCrypto(crypto);
      if (!twoFaStatus?.enabled) {
        setStep('2fa-setup');
        return;
      }
      setStep('2fa-verify');
      return;
    }
    
    setSelectedCrypto(crypto);
    setStep('crypto-deposit');
  };

  const handleDeposit = () => {
    if (!isValidAmount) {
      setError('Minimum deposit is $1.00');
      return;
    }
    if (requires2FA) {
      if (!twoFaStatus?.enabled) {
        setStep('2fa-setup');
        return;
      }
      setStep('2fa-verify');
      return;
    }
    processDeposit();
  };

  const processDeposit = async (twoFaCode = null) => {
    setStep('processing');
    setIsLoading(true);
    try {
      const res = await fetch('/api/wallet/deposit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ amount: amountInCents, two_factor_code: twoFaCode })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.detail || 'Deposit failed');
      setNewBalance(data.new_balance);
      setStep('success');
      // Update balance with floating animation (positive delta)
      if (window.updateCoinRushBalance) {
        window.updateCoinRushBalance(data.new_balance, amountInCents);
      }
      if (typeof window.refreshUserBalance === 'function') window.refreshUserBalance();
    } catch (err) {
      setError(err.message);
      setStep('error');
    } finally {
      setIsLoading(false);
    }
  };

  if (!isOpen) return null;

  // Handle 2FA verification - for crypto, proceed to crypto-deposit; for fiat, process deposit
  const handleTwoFaVerified = (twoFaCode) => {
    if (pendingCrypto) {
      // Crypto deposit - after 2FA, show the crypto deposit view
      setSelectedCrypto(pendingCrypto);
      setPendingCrypto(null);
      setStep('crypto-deposit');
    } else {
      // Fiat deposit - process immediately
      processDeposit(twoFaCode);
    }
  };

  const renderContent = () => {
    switch (step) {
      case 'crypto-deposit':
        return (
          <>
            <button className="modal-close-btn" onClick={onClose} aria-label="Close"><CloseIcon /></button>
            <div className="wallet-modal-scroll">
              <CryptoDepositView 
                crypto={selectedCrypto} 
                onBack={() => { setSelectedCrypto(null); setStep('form'); }}
                amount={amountNum}
              />
            </div>
          </>
        );

      case '2fa-setup':
        return <TwoFactorSetup onSetupComplete={() => { check2FAStatus(); setStep('2fa-verify'); }} onCancel={() => { setPendingCrypto(null); setStep('form'); }} />;
      
      case '2fa-verify':
        return <TwoFactorVerify amount={amountInCents} onVerify={handleTwoFaVerified} onCancel={() => { setPendingCrypto(null); setStep('form'); }} isLoading={isLoading} type="deposit" />;
      
      case 'processing':
        return (
          <div className="wallet-modal-state">
            <div className="state-icon processing"><SpinnerIcon size={48} /></div>
            <h3>Processing Deposit</h3>
            <p>Adding funds to your account...</p>
          </div>
        );
      
      case 'success':
        return (
          <div className="wallet-modal-state">
            <div className="state-icon-container">
              <div className="state-icon success"><CheckIcon /></div>
            </div>
            <h3>Deposit Complete!</h3>
            <p className="success-amount">+${formatCurrency(amount)}</p>
            {currentTier.bonus > 0 && (
              <p className="bonus-celebration">
                <CelebrationIcon size={16} /> +${bonusAmount} bonus added!
              </p>
            )}
            <p>New balance: <strong>${formatBalance(newBalance)}</strong></p>
            <button className="action-btn primary deposit" onClick={onClose}>Continue Playing</button>
          </div>
        );
      
      case 'error':
        return (
          <div className="wallet-modal-state">
            <div className="state-icon error">✕</div>
            <h3>Deposit Failed</h3>
            <p>{error}</p>
            <button className="action-btn primary" onClick={() => setStep('form')}>Try Again</button>
          </div>
        );
      
      default:
        return (
          <>
            <button className="modal-close-btn" onClick={onClose} aria-label="Close"><CloseIcon /></button>
            
            <div className="wallet-modal-scroll">
              <div className="wallet-modal-header">
                <div className="header-icon-container">
                  <div className="header-icon deposit"><ArrowDownIcon /></div>
                </div>
                <h2>Add Funds</h2>
                <div className="balance-display">
                  <WalletIcon />
                  <span>Balance:</span>
                  <span className="balance-amount">${formatBalance(userBalance)}</span>
                </div>
              </div>

              <div className="wallet-modal-body">
                {/* Payment Method Tabs */}
                <div className="payment-method-tabs">
                  <button 
                    className={`payment-tab ${paymentType === 'crypto' ? 'active' : ''}`}
                    onClick={() => setPaymentType('crypto')}
                  >
                    <BitcoinIcon size={18} />
                    <span>Cryptocurrency</span>
                    <span className="tab-badge popular">Popular</span>
                  </button>
                  <button 
                    className={`payment-tab ${paymentType === 'fiat' ? 'active' : ''}`}
                    onClick={() => setPaymentType('fiat')}
                  >
                    <CardIcon size={18} />
                    <span>Card / Bank</span>
                  </button>
                </div>

                {/* Crypto Payment Options */}
                {paymentType === 'crypto' && (
                  <div className="crypto-section">
                    {/* Inline Amount Input */}
                    <div className="inline-amount-section">
                      <div className="inline-amount-row">
                        <span className="inline-amount-label">Amount</span>
                        <div className="inline-amount-input-wrap">
                          <span className="dollar-prefix">$</span>
                          <input
                            type="number"
                            className="inline-amount-input"
                            placeholder="0.00"
                            value={amount}
                            onChange={(e) => { setAmount(e.target.value); setError(''); }}
                            min="1"
                            step="1"
                          />
                        </div>
                      </div>
                      <div className="inline-quick-amounts">
                        {QUICK_AMOUNTS.map(val => (
                          <button
                            key={val}
                            className={`inline-quick-chip ${amountNum === val ? 'active' : ''}`}
                            onClick={() => setAmount(String(val))}
                          >
                            ${val}
                          </button>
                        ))}
                      </div>
                      {error && <div className="inline-amount-error"><AlertTriangleIcon size={12} /> {error}</div>}
                    </div>
                    
                    <div className="crypto-grid">
                      {PAYMENT_METHODS.crypto.map(crypto => (
                        <button
                          key={crypto.id}
                          className={`crypto-option ${crypto.popular ? 'popular' : ''} ${!isValidAmount ? 'disabled' : ''}`}
                          onClick={() => handleSelectCrypto(crypto)}
                          disabled={!isValidAmount}
                          title={!isValidAmount ? 'Enter amount first' : `Deposit with ${crypto.name}`}
                        >
                          <div className="crypto-option-icon">
                            {getCryptoIcon(crypto.id, 32)}
                          </div>
                          <div className="crypto-option-info">
                            <span className="crypto-name">{crypto.name}</span>
                            <span className="crypto-network">{crypto.network}</span>
                          </div>
                          {crypto.popular && <span className="crypto-popular-badge"><ZapIcon size={12} /></span>}
                        </button>
                      ))}
                    </div>
                    
                    <div className="crypto-benefits">
                      <div className="benefit-item">
                        <span className="benefit-icon"><ShieldIcon size={14} /></span>
                        <span>Secure & Private</span>
                      </div>
                      <div className="benefit-item">
                        <span className="benefit-icon"><CoinsIcon size={14} /></span>
                        <span>Low Fees</span>
                      </div>
                      <div className="benefit-item">
                        <span className="benefit-icon"><ZapIcon size={14} /></span>
                        <span>Fast Processing</span>
                      </div>
                    </div>
                  </div>
                )}

                {/* Fiat Payment Options */}
                {paymentType === 'fiat' && (
                  <>
                    <div className="fiat-section">
                      <div className="fiat-options">
                        <button className="fiat-option selected">
                          <CardIcon size={24} />
                          <div className="fiat-option-info">
                            <span className="fiat-name">Credit/Debit Card</span>
                            <span className="fiat-fee">2.5% fee • Instant</span>
                          </div>
                        </button>
                        <button className="fiat-option disabled" disabled>
                          <BankIcon size={24} />
                          <div className="fiat-option-info">
                            <span className="fiat-name">Bank Transfer</span>
                            <span className="fiat-fee">Free • 1-3 days</span>
                          </div>
                          <span className="coming-soon-badge">Soon</span>
                        </button>
                      </div>
                    </div>

                    <div className="amount-section">
                      <div className="amount-label">
                        <span>Amount to Deposit</span>
                        {currentTier.bonus > 0 && (
                          <span className="bonus-hint"><StarIcon size={12} /> {currentTier.label}</span>
                        )}
                      </div>
                      <div className={`amount-input-container deposit-focus`}>
                        <div className="amount-input-wrapper">
                          <span className="amount-currency">$</span>
                          <input
                            ref={inputRef}
                            type="text"
                            inputMode="decimal"
                            placeholder="0.00"
                            value={amount}
                            onChange={e => {
                              const val = e.target.value.replace(/[^0-9.]/g, '');
                              if (val.split('.').length <= 2) {
                                setAmount(val);
                                setError('');
                              }
                            }}
                            className={`amount-input ${amount ? 'has-value' : ''}`}
                          />
                        </div>
                        <div className="amount-limits">
                          <span>Min: $1.00</span>
                          {currentTier.bonus > 0 && <span>+${bonusAmount} bonus</span>}
                        </div>
                      </div>
                    </div>

                    <div className="quick-amounts-section">
                      <div className="quick-amounts-grid">
                        {QUICK_AMOUNTS.map(amt => {
                          const tier = getBonusTier(amt);
                          return (
                            <button
                              key={amt}
                              className={`quick-amount-btn ${parseFloat(amount) === amt ? 'selected' : ''}`}
                              onClick={() => setAmount(amt.toString())}
                            >
                              {tier.bonus > 0 && <span className="bonus-badge">+{tier.bonus}%</span>}
                              <span>${amt}</span>
                            </button>
                          );
                        })}
                      </div>
                    </div>

                    {/* Bonus tier progress */}
                    {amountNum >= 10 && nextTier && (
                      <div className="bonus-tier-section">
                        <div className="bonus-tier-header">
                          <span className="bonus-tier-label"><GiftIcon /> Current Bonus</span>
                          <span className="bonus-tier-value">{currentTier.bonus > 0 ? currentTier.label : 'None'}</span>
                        </div>
                        <div className="bonus-tier-progress">
                          <div 
                            className="bonus-tier-progress-bar" 
                            style={{ width: `${Math.min(100, (amountNum - currentTier.min) / (nextTier.min - currentTier.min) * 100)}%` }}
                          />
                        </div>
                        <p className="bonus-tier-hint">
                          Deposit <strong>${nextTier.min}</strong> to unlock <strong>{nextTier.label}</strong>
                        </p>
                      </div>
                    )}

                    {requires2FA && (
                      <div className={`security-badge ${twoFaStatus?.enabled ? 'enabled' : ''}`}>
                        <div className="security-badge-icon"><LockIcon /></div>
                        <div className="security-badge-content">
                          <div className="security-badge-title">
                            {twoFaStatus?.enabled ? '2FA Verification Required' : '2FA Setup Required'}
                          </div>
                          <div className="security-badge-subtitle">
                            {twoFaStatus?.enabled ? 'Confirm with your authenticator app' : 'Deposits over $50 require 2FA protection'}
                          </div>
                        </div>
                      </div>
                    )}

                    {error && <p className="error-message">{error}</p>}
                  </>
                )}

                <div className="info-card">
                  <div className="info-card-icon"><InfoIcon /></div>
                  <div className="info-card-content">
                    <h4>Demo Mode Active</h4>
                    <p>This is a demonstration. No real money transactions are processed.</p>
                  </div>
                </div>
              </div>
            </div>

            {paymentType === 'fiat' && (
              <div className="wallet-modal-actions">
                <button className="action-btn secondary" onClick={onClose}>Cancel</button>
                <button 
                  className="action-btn primary deposit"
                  disabled={!isValidAmount || isLoading}
                  onClick={handleDeposit}
                >
                  {requires2FA && !twoFaStatus?.enabled 
                    ? 'Enable 2FA First' 
                    : `Deposit $${formatCurrency(amount || 0)}`
                  }
                </button>
              </div>
            )}
          </>
        );
    }
  };

  return (
    <div className="wallet-modal-overlay" ref={modalRef} onClick={handleBackdropClick}>
      <div className={`wallet-modal deposit-mode ${step !== 'form' ? 'centered' : ''}`}>
        {renderContent()}
      </div>
    </div>
  );
}

// ============================================
// CRYPTO WITHDRAW VIEW COMPONENT
// ============================================
function CryptoWithdrawView({ crypto, onBack, amount, onConfirm, isLoading }) {
  const [walletAddress, setWalletAddress] = useState('');
  const [selectedNetwork, setSelectedNetwork] = useState(crypto.network);
  const [error, setError] = useState('');

  const handleWithdraw = () => {
    if (!walletAddress || walletAddress.length < 20) {
      setError('Please enter a valid wallet address');
      return;
    }
    onConfirm(walletAddress, selectedNetwork);
  };

  return (
    <div className="crypto-withdraw-view">
      <button className="crypto-back-btn" onClick={onBack}>
        ← Back to payment methods
      </button>

      <div className="crypto-deposit-header">
        <div className="crypto-icon-large">
          {getCryptoIcon(crypto.id, 48)}
        </div>
        <h3>Withdraw to {crypto.name}</h3>
        <p className="crypto-subtitle">Enter your {crypto.symbol} wallet address</p>
      </div>

      {crypto.networks && (
        <div className="network-selector">
          <label>Select Network</label>
          <div className="network-options">
            {crypto.networks.map(net => (
              <button
                key={net}
                className={`network-option ${selectedNetwork === net ? 'selected' : ''}`}
                onClick={() => setSelectedNetwork(net)}
              >
                {net}
              </button>
            ))}
          </div>
          <p className="network-warning">
            <AlertTriangleIcon size={13} /> Ensure you select the correct network that matches your receiving wallet
          </p>
        </div>
      )}

      <div className="crypto-address-section">
        <label>Your {crypto.symbol} Wallet Address ({selectedNetwork})</label>
        <div className="wallet-address-input-container">
          <input
            type="text"
            className="wallet-address-input"
            placeholder={`Enter your ${crypto.symbol} address...`}
            value={walletAddress}
            onChange={e => { setWalletAddress(e.target.value); setError(''); }}
          />
        </div>
        {error && <p className="error-message">{error}</p>}
      </div>

      <div className="withdraw-summary">
        <div className="summary-row">
          <span>Amount</span>
          <span className="summary-value">${amount.toFixed(2)} USD</span>
        </div>
        <div className="summary-row">
          <span>Network Fee</span>
          <span className="summary-value">~$2.50 (varies)</span>
        </div>
        <div className="summary-row total">
          <span>You Receive</span>
          <span className="summary-value">~${(amount - 2.50).toFixed(2)} in {crypto.symbol}</span>
        </div>
      </div>

      <div className="demo-notice">
        <div className="demo-badge">DEMO MODE</div>
        <p>This is a demonstration. No real cryptocurrency will be sent.</p>
      </div>

      <div className="wallet-modal-actions">
        <button className="action-btn secondary" onClick={onBack} disabled={isLoading}>
          Cancel
        </button>
        <button 
          className="action-btn primary withdraw"
          onClick={handleWithdraw}
          disabled={isLoading || !walletAddress}
        >
          {isLoading ? <SpinnerIcon size={20} /> : 'Confirm Withdrawal'}
        </button>
      </div>
    </div>
  );
}

// ============================================
// WITHDRAW MODAL
// ============================================
function WithdrawModal({ isOpen, onClose, userBalance }) {
  const [step, setStep] = useState('form');
  const [paymentType, setPaymentType] = useState('crypto');
  const [selectedCrypto, setSelectedCrypto] = useState(null);
  const [pendingCrypto, setPendingCrypto] = useState(null); // Track crypto selection during 2FA flow
  const [amount, setAmount] = useState('');
  const [twoFaStatus, setTwoFaStatus] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const modalRef = useRef(null);
  const inputRef = useRef(null);

  const QUICK_AMOUNTS = [10, 25, 50, 100, 250, 500];
  const amountNum = parseFloat(amount || 0);
  const amountInCents = amountNum * 100;
  const minWithdraw = 100;
  const maxWithdraw = userBalance || 0;
  const isValidAmount = amountInCents >= minWithdraw && amountInCents <= maxWithdraw;
  const requires2FA = amountInCents >= 5000; // $50+ requires 2FA for all payment types

  useEffect(() => {
    if (isOpen) {
      check2FAStatus();
      document.body.style.overflow = 'hidden';
      setTimeout(() => inputRef.current?.focus(), 100);
    } else {
      document.body.style.overflow = '';
      setStep('form');
      setPaymentType('crypto');
      setSelectedCrypto(null);
      setPendingCrypto(null);
      setAmount('');
      setError('');
    }
    return () => { document.body.style.overflow = ''; };
  }, [isOpen]);

  const check2FAStatus = async () => {
    try {
      const res = await fetch('/api/2fa/status', { credentials: 'include' });
      if (res.ok) setTwoFaStatus(await res.json());
    } catch (err) { console.error('2FA check failed:', err); }
  };

  const handleBackdropClick = (e) => {
    if (e.target === modalRef.current) onClose();
  };

  const handleSelectCrypto = (crypto) => {
    if (!isValidAmount) {
      setError('Please enter a valid withdrawal amount first');
      return;
    }
    
    // For crypto withdrawals, also check 2FA if amount >= $50
    if (requires2FA) {
      setPendingCrypto(crypto); // Remember which crypto was selected
      if (!twoFaStatus?.enabled) {
        setStep('2fa-setup');
        return;
      }
      setStep('2fa-verify');
      return;
    }
    
    setSelectedCrypto(crypto);
    setStep('crypto-withdraw');
  };

  const handleWithdraw = () => {
    if (!isValidAmount) {
      setError(amountInCents < minWithdraw ? 'Minimum withdrawal is $1.00' : 'Insufficient balance');
      return;
    }
    if (requires2FA) {
      if (!twoFaStatus?.enabled) {
        setStep('2fa-setup');
        return;
      }
      setStep('2fa-verify');
      return;
    }
    processWithdrawal();
  };

  const processWithdrawal = async (twoFaCode = null) => {
    setStep('processing');
    setIsLoading(true);
    try {
      const res = await fetch('/api/wallet/withdraw', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ amount: amountInCents, two_factor_code: twoFaCode })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.detail || 'Withdrawal failed');
      setStep('success');
      // Update balance with floating animation (negative delta)
      const newBalance = data.new_balance !== undefined ? data.new_balance : (userBalance - amountInCents);
      if (window.updateCoinRushBalance) {
        window.updateCoinRushBalance(newBalance, -amountInCents);
      }
      if (typeof window.refreshUserBalance === 'function') window.refreshUserBalance();
    } catch (err) {
      setError(err.message);
      setStep('error');
    } finally {
      setIsLoading(false);
    }
  };

  if (!isOpen) return null;

  // Handle 2FA verification - for crypto, proceed to crypto-withdraw; for fiat, process withdrawal
  const handleTwoFaVerified = (twoFaCode) => {
    if (pendingCrypto) {
      // Crypto withdrawal - after 2FA, show the crypto withdraw view
      setSelectedCrypto(pendingCrypto);
      setPendingCrypto(null);
      setStep('crypto-withdraw');
    } else {
      // Fiat withdrawal - process immediately
      processWithdrawal(twoFaCode);
    }
  };

  const renderContent = () => {
    switch (step) {
      case '2fa-setup':
        return <TwoFactorSetup onSetupComplete={() => { check2FAStatus(); setStep('2fa-verify'); }} onCancel={() => { setPendingCrypto(null); setStep('form'); }} />;
      
      case '2fa-verify':
        return <TwoFactorVerify amount={amountInCents} onVerify={handleTwoFaVerified} onCancel={() => { setPendingCrypto(null); setStep('form'); }} isLoading={isLoading} type="withdraw" />;
      
      case 'processing':
        return (
          <div className="wallet-modal-state">
            <div className="state-icon processing"><SpinnerIcon size={48} /></div>
            <h3>Processing Withdrawal</h3>
            <p>Transferring your funds...</p>
          </div>
        );
      
      case 'success':
        return (
          <div className="wallet-modal-state">
            <div className="state-icon-container">
              <div className="state-icon success"><CheckIcon /></div>
            </div>
            <h3>Withdrawal Complete!</h3>
            <p className="success-amount" style={{ color: '#fbbf24' }}>-${formatCurrency(amount)}</p>
            <p>Funds have been transferred successfully</p>
            <button className="action-btn primary withdraw" onClick={onClose}>Done</button>
          </div>
        );
      
      case 'error':
        return (
          <div className="wallet-modal-state">
            <div className="state-icon error">✕</div>
            <h3>Withdrawal Failed</h3>
            <p>{error}</p>
            <button className="action-btn primary" onClick={() => setStep('form')}>Try Again</button>
          </div>
        );
      
      case 'crypto-withdraw':
        return (
          <>
            <button className="modal-close-btn" onClick={onClose} aria-label="Close"><CloseIcon /></button>
            <div className="wallet-modal-scroll">
              <CryptoWithdrawView 
                crypto={selectedCrypto} 
                onBack={() => { setSelectedCrypto(null); setStep('form'); }}
                amount={amountNum}
                onConfirm={(address, network) => processWithdrawal()}
                isLoading={isLoading}
              />
            </div>
          </>
        );

      default:
        return (
          <>
            <button className="modal-close-btn" onClick={onClose} aria-label="Close"><CloseIcon /></button>
            
            <div className="wallet-modal-scroll">
              <div className="wallet-modal-header">
                <div className="header-icon-container">
                  <div className="header-icon withdraw"><ArrowUpIcon /></div>
                </div>
                <h2>Withdraw Funds</h2>
                <div className="balance-display" style={{ background: 'rgba(251, 191, 36, 0.08)', borderColor: 'rgba(251, 191, 36, 0.2)' }}>
                  <WalletIcon style={{ color: '#fbbf24' }} />
                  <span>Available:</span>
                  <span className="balance-amount" style={{ color: '#fbbf24' }}>${formatBalance(userBalance)}</span>
                </div>
              </div>

              <div className="wallet-modal-body">
                {/* Amount Section First */}
                <div className="amount-section">
                  <div className="amount-label">
                    <span>Amount to Withdraw</span>
                  </div>
                  <div className={`amount-input-container withdraw-focus`}>
                    <div className="amount-input-wrapper">
                      <span className="amount-currency">$</span>
                      <input
                        ref={inputRef}
                        type="text"
                        inputMode="decimal"
                        placeholder="0.00"
                        value={amount}
                        onChange={e => {
                          const val = e.target.value.replace(/[^0-9.]/g, '');
                          if (val.split('.').length <= 2) {
                            setAmount(val);
                            setError('');
                          }
                        }}
                        className={`amount-input ${amount ? 'has-value' : ''}`}
                      />
                      <button 
                        className="max-button" 
                        onClick={() => setAmount((maxWithdraw / 100).toFixed(2))}
                      >
                        MAX
                      </button>
                    </div>
                    <div className="amount-limits">
                      <span>Min: $1.00</span>
                      <span>Max: ${formatBalance(maxWithdraw)}</span>
                    </div>
                  </div>
                </div>

                <div className="quick-amounts-section">
                  <div className="quick-amounts-grid">
                    {QUICK_AMOUNTS.filter(a => a * 100 <= maxWithdraw).map(amt => (
                      <button
                        key={amt}
                        className={`quick-amount-btn ${parseFloat(amount) === amt ? 'selected' : ''}`}
                        onClick={() => setAmount(amt.toString())}
                      >
                        <span>${amt}</span>
                      </button>
                    ))}
                  </div>
                </div>

                {/* Payment Method Tabs */}
                <div className="payment-method-tabs" style={{ marginTop: '20px' }}>
                  <button 
                    className={`payment-tab ${paymentType === 'crypto' ? 'active' : ''}`}
                    onClick={() => setPaymentType('crypto')}
                  >
                    <BitcoinIcon size={18} />
                    <span>Cryptocurrency</span>
                    <span className="tab-badge popular">Fast</span>
                  </button>
                  <button 
                    className={`payment-tab ${paymentType === 'fiat' ? 'active' : ''}`}
                    onClick={() => setPaymentType('fiat')}
                  >
                    <BankIcon size={18} />
                    <span>Bank Transfer</span>
                  </button>
                </div>

                {/* Crypto Withdrawal Options */}
                {paymentType === 'crypto' && (
                  <div className="crypto-section">
                    <p className="section-hint">Select cryptocurrency to receive</p>
                    <div className="crypto-grid">
                      {PAYMENT_METHODS.crypto.map(crypto => (
                        <button
                          key={crypto.id}
                          className={`crypto-option ${crypto.popular ? 'popular' : ''} ${!isValidAmount ? 'disabled' : ''}`}
                          onClick={() => handleSelectCrypto(crypto)}
                          disabled={!isValidAmount}
                        >
                          <div className="crypto-option-icon">
                            {getCryptoIcon(crypto.id, 32)}
                          </div>
                          <div className="crypto-option-info">
                            <span className="crypto-name">{crypto.name}</span>
                            <span className="crypto-network">{crypto.network}</span>
                          </div>
                          {crypto.popular && <span className="crypto-popular-badge"><ZapIcon size={12} /></span>}
                        </button>
                      ))}
                    </div>
                    {!isValidAmount && amountNum > 0 && (
                      <p className="error-message" style={{ marginTop: '12px' }}>
                        {amountInCents < minWithdraw ? 'Minimum withdrawal is $1.00' : 'Insufficient balance'}
                      </p>
                    )}
                  </div>
                )}

                {/* Fiat Withdrawal */}
                {paymentType === 'fiat' && (
                  <div className="fiat-section">
                    <div className="fiat-options">
                      <button className="fiat-option disabled" disabled>
                        <BankIcon size={24} />
                        <div className="fiat-option-info">
                          <span className="fiat-name">Bank Transfer</span>
                          <span className="fiat-fee">3-5 business days</span>
                        </div>
                        <span className="coming-soon-badge">Coming Soon</span>
                      </button>
                    </div>
                    <p className="fiat-notice">
                      Bank transfers are not yet available. Please use cryptocurrency for withdrawals.
                    </p>
                  </div>
                )}

                {requires2FA && (
                  <div className={`security-badge ${twoFaStatus?.enabled ? 'enabled' : ''}`}>
                    <div className="security-badge-icon"><LockIcon /></div>
                    <div className="security-badge-content">
                      <div className="security-badge-title">
                        {twoFaStatus?.enabled ? '2FA Verification Required' : '2FA Setup Required'}
                      </div>
                      <div className="security-badge-subtitle">
                        {twoFaStatus?.enabled ? 'Confirm with your authenticator app' : 'Withdrawals over $50 require 2FA protection'}
                      </div>
                    </div>
                  </div>
                )}

                {error && <p className="error-message">{error}</p>}

                <div className="info-card">
                  <div className="info-card-icon"><InfoIcon /></div>
                  <div className="info-card-content">
                    <h4>Demo Mode</h4>
                    <p>This is a demonstration. No real money or crypto is being transferred.</p>
                  </div>
                </div>
              </div>
            </div>
          </>
        );
    }
  };

  return (
    <div className="wallet-modal-overlay" ref={modalRef} onClick={handleBackdropClick}>
      <div className={`wallet-modal withdraw-mode ${step !== 'form' ? 'centered' : ''}`}>
        {renderContent()}
      </div>
    </div>
  );
}

// ============================================
// GLOBAL MODAL MANAGER
// ============================================
function WalletModalsManager() {
  const [depositOpen, setDepositOpen] = useState(false);
  const [withdrawOpen, setWithdrawOpen] = useState(false);
  const [userBalance, setUserBalance] = useState(0);

  useEffect(() => {
    window.openDepositModal = () => { fetchBalance(); setDepositOpen(true); };
    window.openWithdrawModal = () => { fetchBalance(); setWithdrawOpen(true); };
    return () => { window.openDepositModal = null; window.openWithdrawModal = null; };
  }, []);

  const fetchBalance = async () => {
    try {
      const res = await fetch('/me', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setUserBalance(data.balance || 0);
      }
    } catch (err) { console.error('Balance fetch failed:', err); }
  };

  return (
    <>
      <DepositModal isOpen={depositOpen} onClose={() => setDepositOpen(false)} userBalance={userBalance} />
      <WithdrawModal isOpen={withdrawOpen} onClose={() => setWithdrawOpen(false)} userBalance={userBalance} />
    </>
  );
}

// Auto-mount
document.addEventListener('DOMContentLoaded', () => {
  let container = document.getElementById('wallet-modals-root');
  if (!container) {
    container = document.createElement('div');
    container.id = 'wallet-modals-root';
    document.body.appendChild(container);
  }
  ReactDOM.render(React.createElement(WalletModalsManager), container);
});

// Mount if ready
if (document.readyState !== 'loading') {
  setTimeout(() => {
    let container = document.getElementById('wallet-modals-root');
    if (!container) {
      container = document.createElement('div');
      container.id = 'wallet-modals-root';
      document.body.appendChild(container);
    }
    if (!container.hasChildNodes()) {
      ReactDOM.render(React.createElement(WalletModalsManager), container);
    }
  }, 100);
}

// Exports
window.DepositModal = DepositModal;
window.WithdrawModal = WithdrawModal;
window.openDepositModal = window.openDepositModal || (() => {});
window.openWithdrawModal = window.openWithdrawModal || (() => {});
