/**
 * CoinRush User Profile & Settings - React App
 * Complete premium profile/settings page with modern UI
 */

const { useState, useEffect, useRef } = React;

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

const colorFrom = (name) => {
  if (!name) return '#5bffb2';
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = ((hash << 5) - hash) + name.charCodeAt(i);
  }
  const hue = Math.abs(hash % 360);
  return `hsl(${hue}, 65%, 50%)`;
};

const formatDate = (dateStr) => {
  if (!dateStr) return '—';
  return new Date(dateStr).toLocaleDateString('en-US', { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric' 
  });
};

const formatTimeAgo = (dateStr) => {
  if (!dateStr) return 'Never';
  const diff = Date.now() - new Date(dateStr);
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'Just now';
  if (mins < 60) return `${mins}m ago`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  return `${days}d ago`;
};

// Get the PNG border image path based on level
const getBorderImage = (level) => {
  if (level >= 50) return '/static/img/borders/Challengerborder.png';
  if (level >= 40) return '/static/img/borders/Rubyborder.png';
  if (level >= 30) return '/static/img/borders/Diamondborder.png';
  if (level >= 20) return '/static/img/borders/Goldborder.png';
  if (level >= 10) return '/static/img/borders/Silverborder.png';
  return '/static/img/borders/Bronzeborder.png';
};

// ============================================
// FLOATING ORBS COMPONENT
// ============================================
function FloatingOrbs() {
  return (
    <>
      <div className="floating-orb orb-1" />
      <div className="floating-orb orb-2" />
      <div className="floating-orb orb-3" />
      <div className="floating-orb orb-4" />
      {[...Array(12)].map((_, i) => (
        <div
          key={i}
          className="floating-particle"
          style={{
            left: `${Math.random() * 100}%`,
            top: `${Math.random() * 100}%`,
            animationDelay: `${Math.random() * 15}s`,
            animationDuration: `${12 + Math.random() * 8}s`,
            width: `${3 + Math.random() * 4}px`,
            height: `${3 + Math.random() * 4}px`,
          }}
        />
      ))}
    </>
  );
}

// ============================================
// LOADING COMPONENT
// ============================================
function LoadingState() {
  return (
    <div className="loading-container">
      <div className="loading-spinner" />
      <div className="loading-text">Loading your profile...</div>
    </div>
  );
}

// ============================================
// TOGGLE SWITCH COMPONENT
// ============================================
function Toggle({ checked, onChange, disabled }) {
  return (
    <button 
      className={`toggle-switch ${checked ? 'active' : ''} ${disabled ? 'disabled' : ''}`}
      onClick={() => !disabled && onChange(!checked)}
      disabled={disabled}
    >
      <span className="toggle-slider" />
    </button>
  );
}

// ============================================
// TAB NAVIGATION
// ============================================
function TabNav({ activeTab, onTabChange }) {
  const tabs = [
    { id: 'overview', label: 'Overview', icon: 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6' },
    { id: 'stats', label: 'Statistics', icon: 'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z' },
    { id: 'referrals', label: 'Referrals', icon: 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z', special: true },
    { id: 'security', label: 'Security', icon: 'M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z' },
    { id: 'settings', label: 'Settings', icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z' },
  ];
  
  return (
    <div className="tab-nav">
      {tabs.map(tab => (
        <button
          key={tab.id}
          className={`tab-btn ${activeTab === tab.id ? 'active' : ''} ${tab.special ? 'referral-glow-tab' : ''}`}
          onClick={() => onTabChange(tab.id)}
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d={tab.icon} />
          </svg>
          <span>{tab.label}</span>
          {tab.special && <span className="tab-badge">$$$</span>}
        </button>
      ))}
    </div>
  );
}

// ============================================
// PROFILE HERO SECTION
// ============================================
function ProfileHero({ user, stats, levelInfo, xpBoost }) {
  const avatarColor = colorFrom(user?.username);
  const avatarInitials = user?.username ? user.username.slice(0, 2).toUpperCase() : '??';
  const level = user?.level || 1;
  
  // Level progress calculation
  const currentXP = levelInfo?.progress_in_level || 0;
  const xpToNext = levelInfo?.next_level_wagered ? (levelInfo.next_level_wagered - (levelInfo.current_level_wagered || 0)) : 10000;
  const progressPct = xpToNext > 0 ? Math.min(100, (currentXP / xpToNext) * 100) : 100;
  
  // Account tier based on level
  const getTier = (lvl) => {
    if (lvl >= 50) return { name: 'Challenger', color: '#ff6b6b', glow: 'rgba(255, 107, 107, 0.3)' };
    if (lvl >= 40) return { name: 'Ruby', color: '#e11d48', glow: 'rgba(225, 29, 72, 0.3)' };
    if (lvl >= 30) return { name: 'Diamond', color: '#06b6d4', glow: 'rgba(6, 182, 212, 0.3)' };
    if (lvl >= 20) return { name: 'Gold', color: '#fbbf24', glow: 'rgba(251, 191, 36, 0.3)' };
    if (lvl >= 10) return { name: 'Silver', color: '#94a3b8', glow: 'rgba(148, 163, 184, 0.3)' };
    return { name: 'Bronze', color: '#cd7f32', glow: 'rgba(205, 127, 50, 0.3)' };
  };
  
  const tier = getTier(level);
  const borderImage = getBorderImage(level);
  
  return (
    <div className="profile-hero">
      {/* Avatar Section */}
      <div className="hero-avatar-section">
        <div className="avatar-wrapper large">
          <div className="avatar-glow" style={{ background: avatarColor }} />
          <div className="avatar large" style={{ background: avatarColor }}>
            {avatarInitials}
          </div>
          <img 
            src={borderImage} 
            alt="Level Border" 
            className="avatar-border-image"
          />
          <div className="avatar-tier-ring" style={{ borderColor: tier.color, boxShadow: `0 0 20px ${tier.glow}` }} />
        </div>
        <div className="hero-username">{user?.username || 'Player'}</div>
        <div className="hero-email">{user?.email || ''}</div>
        
        {/* Tier Badge */}
        <div className="tier-badge" style={{ background: `${tier.color}20`, borderColor: `${tier.color}50`, color: tier.color }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
            <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" />
          </svg>
          {tier.name} Tier
        </div>
      </div>
      
      {/* Level Progress */}
      <div className="hero-level-section">
        <div className="level-header">
          <span className="level-label">Level {level}</span>
          <span className="level-xp">{fmt(currentXP)} / {fmt(xpToNext)}</span>
        </div>
        <div className="level-progress-bar">
          <div className="level-progress-fill" style={{ width: `${progressPct}%` }}>
            <div className="level-progress-glow" />
          </div>
        </div>
        <div className="level-next">
          {xpToNext - currentXP > 0 ? `${fmt(xpToNext - currentXP)} to Level ${level + 1}` : 'Max Level!'}
        </div>
        
        {/* XP Boost Indicator */}
        {xpBoost > 0 && (
          <div className="xp-boost-badge">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" />
            </svg>
            +{xpBoost}% XP Boost Active
          </div>
        )}
      </div>
      
      {/* Balance Display */}
      <div className="hero-balance">
        <div className="balance-card">
          <div className="balance-icon">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <circle cx="12" cy="12" r="10" />
              <path d="M12 6v12M9 9h6M9 15h6" />
            </svg>
          </div>
          <div className="balance-info">
            <div className="balance-label">Available Balance</div>
            <div className="balance-amount">{fmt(user?.balance || 0)}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================
// QUICK STATS CARDS
// ============================================
function QuickStats({ user, stats }) {
  const overall = stats?.overall || {};
  const cf = stats?.coinflip || {};
  const bb = stats?.barbarian || {};
  
  const totalBattles = (cf.played || 0) + (bb.played || 0);
  const totalWins = (cf.wins || 0) + (bb.wins || 0);
  const winRate = totalBattles > 0 ? Math.round((totalWins / totalBattles) * 100) : 0;
  const netPL = overall.net || 0;
  
  const statsData = [
    { label: 'Total Wagered', value: fmt(user?.total_wagered || overall.wagered || 0), icon: 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z' },
    { label: 'Games Played', value: totalBattles, icon: 'M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z M21 12a9 9 0 11-18 0 9 9 0 0118 0z' },
    { label: 'Win Rate', value: `${winRate}%`, icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z', highlight: winRate >= 50 },
    { label: 'Net P/L', value: `${netPL >= 0 ? '+' : ''}${fmt(Math.abs(netPL))}`, icon: 'M13 7h8m0 0v8m0-8l-8 8-4-4-6 6', isPositive: netPL >= 0, isNegative: netPL < 0 },
  ];
  
  return (
    <div className="quick-stats-grid">
      {statsData.map((stat, i) => (
        <div key={i} className={`quick-stat-card ${stat.highlight ? 'highlight' : ''} ${stat.isPositive ? 'positive' : ''} ${stat.isNegative ? 'negative' : ''}`}>
          <div className="quick-stat-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d={stat.icon} />
            </svg>
          </div>
          <div className="quick-stat-value">{stat.value}</div>
          <div className="quick-stat-label">{stat.label}</div>
        </div>
      ))}
    </div>
  );
}

// ============================================
// RECENT ACTIVITY
// ============================================
function RecentActivity({ stats }) {
  const activities = stats?.recent_activity || [];
  
  if (activities.length === 0) {
    return (
      <div className="section-card">
        <h3 className="section-title">
          <span className="section-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </span>
          Recent Activity
        </h3>
        <div className="empty-state">
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
            <path d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
          </svg>
          <p>No recent activity yet</p>
          <span>Start playing to see your game history here!</span>
        </div>
      </div>
    );
  }
  
  return (
    <div className="section-card">
      <h3 className="section-title">
        <span className="section-icon">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        </span>
        Recent Activity
      </h3>
      <div className="activity-list">
        {activities.slice(0, 5).map((act, i) => (
          <div key={i} className={`activity-item ${act.type}`}>
            <div className={`activity-icon ${act.type}`}>
              {act.type === 'win' ? (
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M5 13l4 4L19 7" />
                </svg>
              ) : (
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M6 18L18 6M6 6l12 12" />
                </svg>
              )}
            </div>
            <div className="activity-details">
              <div className="activity-title">{act.description}</div>
              <div className="activity-time">{formatTimeAgo(act.timestamp)}</div>
            </div>
            <div className={`activity-amount ${act.type}`}>
              {act.type === 'win' ? '+' : ''}{fmt(Math.abs(act.amount || 0))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================
// GAME STATISTICS TAB
// ============================================
function StatisticsTab({ stats }) {
  const cf = stats?.coinflip || {};
  const bb = stats?.barbarian || {};
  const jp = stats?.jackpot || {};
  const lottery = stats?.lottery || {};
  const sliceDice = stats?.slice_dice || {};
  const crash = stats?.crash || {};
  
  const games = [
    { name: 'Coinflip', data: cf, color: '#fbbf24', icon: 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z' },
    { name: 'Knights Arena', data: bb, color: '#ef4444', icon: 'M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z' },
    { name: 'Jackpot', data: jp, color: '#22c55e', icon: 'M12 8v13m0-13V6a2 2 0 112 2h-2zm0 0V5.5A2.5 2.5 0 109.5 8H12zm-7 4h14M5 12a2 2 0 110-4h14a2 2 0 110 4M5 12v7a2 2 0 002 2h10a2 2 0 002-2v-7' },
    { name: 'Lottery', data: lottery, color: '#a855f7', icon: 'M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z' },
    { name: "Slice n' Dice", data: sliceDice, color: '#ec4899', icon: 'M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z' },
    { name: 'Crash', data: crash, color: '#06b6d4', icon: 'M13 7h8m0 0v8m0-8l-8 8-4-4-6 6' },
  ];
  
  return (
    <div className="statistics-tab">
      {/* Game Cards */}
      <div className="game-stats-grid">
        {games.map((game, i) => (
          <div key={i} className="game-stat-card" style={{ '--game-color': game.color }}>
            <div className="game-stat-header">
              <div className="game-stat-icon-wrapper" style={{ background: `${game.color}20`, borderColor: `${game.color}40` }}>
                <svg viewBox="0 0 24 24" fill="none" stroke={game.color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d={game.icon} />
                </svg>
              </div>
              <h4>{game.name}</h4>
            </div>
            <div className="game-stat-body">
              <div className="game-stat-row">
                <span>Games Played</span>
                <strong>{game.data.played || 0}</strong>
              </div>
              <div className="game-stat-row">
                <span>Wins</span>
                <strong className="positive">{game.data.wins || 0}</strong>
              </div>
              <div className="game-stat-row">
                <span>Losses</span>
                <strong className="negative">{game.data.losses || 0}</strong>
              </div>
              <div className="game-stat-row">
                <span>Win Rate</span>
                <strong>{game.data.win_rate || 0}%</strong>
              </div>
              <div className="game-stat-row highlight">
                <span>Net P/L</span>
                <strong className={(game.data.net || 0) >= 0 ? 'positive' : 'negative'}>
                  {(game.data.net || 0) >= 0 ? '+' : ''}{fmt(game.data.net || 0)}
                </strong>
              </div>
              {(game.data.biggest_win || 0) > 0 && (
                <div className="game-stat-row">
                  <span>Biggest Win</span>
                  <strong className="positive">{fmt(game.data.biggest_win)}</strong>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
      
      {/* Overall Stats */}
      <div className="section-card">
        <h3 className="section-title">
          <span className="section-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M16 8v8m-4-5v5m-4-2v2m-2 4h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
          </span>
          Overall Performance
        </h3>
        <div className="stats-overview-grid">
          <div className="overview-stat">
            <div className="overview-stat-value">{fmt(stats?.overall?.wagered || 0)}</div>
            <div className="overview-stat-label">Total Wagered</div>
          </div>
          <div className="overview-stat">
            <div className={`overview-stat-value ${(stats?.overall?.net || 0) >= 0 ? 'positive' : 'negative'}`}>
              {(stats?.overall?.net || 0) >= 0 ? '+' : ''}{fmt(Math.abs(stats?.overall?.net || 0))}
            </div>
            <div className="overview-stat-label">Net Profit/Loss</div>
          </div>
          <div className="overview-stat">
            <div className={`overview-stat-value ${(stats?.overall?.roi || 0) >= 0 ? 'positive' : 'negative'}`}>
              {stats?.overall?.roi || 0}%
            </div>
            <div className="overview-stat-label">Return on Investment</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================
// REFERRALS TAB (Affiliate Program) - Premium Glowing Design
// ============================================
function ReferralsTab({ referralData, onClaimBonus, onClaimVault, vaultClaimLoading, hasReferrer }) {
  const [copyText, setCopyText] = useState('Copy');
  const [claimCode, setClaimCode] = useState('');
  const [claimMessage, setClaimMessage] = useState(null);
  const [isClaimLoading, setIsClaimLoading] = useState(false);
  
  const copyReferralCode = () => {
    navigator.clipboard.writeText(referralData?.referral_code || '');
    setCopyText('Copied!');
    setTimeout(() => setCopyText('Copy'), 2000);
  };
  
  const handleClaimBonus = async () => {
    if (!claimCode.trim()) {
      setClaimMessage({ type: 'error', text: 'Please enter a referral code' });
      return;
    }
    
    setIsClaimLoading(true);
    setClaimMessage(null);
    
    try {
      const res = await fetch('/api/referral/claim-bonus', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ referral_code: claimCode.trim() })
      });
      
      const data = await res.json();
      
      if (!res.ok) {
        throw new Error(data.detail || 'Failed to claim bonus');
      }
      
      setClaimMessage({ type: 'success', text: data.message });
      onClaimBonus();
    } catch (error) {
      setClaimMessage({ type: 'error', text: error.message });
    } finally {
      setIsClaimLoading(false);
    }
  };
  
  const unclaimedAmount = referralData?.unclaimed_earnings || 0;
  
  return (
    <div className="referrals-tab">
      {/* Floating Reward Particles - SVG coins */}
      <div className="referral-particles">
        {[...Array(8)].map((_, i) => (
          <div key={i} className="referral-particle-svg" style={{
            left: `${10 + Math.random() * 80}%`,
            animationDelay: `${Math.random() * 5}s`,
            animationDuration: `${4 + Math.random() * 3}s`
          }}>
            <svg viewBox="0 0 24 24" fill="none" stroke="#fbbf24" strokeWidth="2">
              <circle cx="12" cy="12" r="10" />
              <circle cx="12" cy="12" r="4" />
            </svg>
          </div>
        ))}
      </div>
      
      {/* Vault Section - Clean & Glowy */}
      {unclaimedAmount > 0 && (
        <div className="vault-card-new">
          <div className="vault-glow-effect" />
          <div className="vault-left">
            <div className="vault-icon-box">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                <path d="M7 11V7a5 5 0 0 1 10 0v4" />
              </svg>
            </div>
          </div>
          <div className="vault-center">
            <div className="vault-label-text">REFERRAL VAULT</div>
            <div className="vault-amount-value">{fmt(unclaimedAmount)}</div>
            <div className="vault-ready-text">Ready to claim!</div>
          </div>
          <div className="vault-right">
            <button 
              className="vault-claim-btn" 
              onClick={onClaimVault}
              disabled={vaultClaimLoading}
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M12 19V5M5 12l7-7 7 7" />
              </svg>
              <span>{vaultClaimLoading ? 'Claiming...' : 'Claim Now'}</span>
            </button>
          </div>
        </div>
      )}
      
      {/* Hero Banner - Attention Grabbing */}
      <div className="referral-hero-banner">
        <div className="banner-glow-bg" />
        <div className="banner-content">
          <div className="banner-icon-wrapper">
            <div className="banner-icon-glow" />
            <div className="banner-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
              </svg>
            </div>
          </div>
          <div className="banner-text">
            <h2>Earn Up To <span className="highlight-amount">$2.50</span> Per Friend!</h2>
            <p>Share your code • Friends sign up • You earn 1% of their first $250 in winnings</p>
          </div>
        </div>
        <div className="banner-badge">
          <svg viewBox="0 0 24 24" fill="currentColor" stroke="none">
            <path d="M12 23c-3.866 0-7-3.134-7-7 0-2.5 1.5-4.5 3-6.5.378-.504.757-1.008 1.136-1.512C10.5 6.5 11.5 5 12 2c.5 3 1.5 4.5 2.864 6.012.379.504.758 1.008 1.136 1.512 1.5 2 3 4 3 6.476 0 3.866-3.134 7-7 7zm0-3c2.21 0 4-1.79 4-4 0-1.5-1-3-2-4-.333-.333-.667-.667-1-1-.333.333-.667.667-1 1-1 1-2 2.5-2 4 0 2.21 1.79 4 4 4z"/>
          </svg>
          <span>Popular</span>
        </div>
      </div>
      
      {/* How It Works - Visual Steps */}
      <div className="section-card referral-steps-card">
        <h3 className="section-title glow-title">
          <span className="section-icon glow-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
            </svg>
          </span>
          How It Works
        </h3>
        
        <div className="referral-how-it-works premium">
          <div className="step glow-step">
            <div className="step-number">1</div>
            <div className="step-icon-svg">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" />
                <polyline points="16 6 12 2 8 6" />
                <line x1="12" y1="2" x2="12" y2="15" />
              </svg>
            </div>
            <div className="step-content">
              <strong>Share Your Code</strong>
              <p>Copy your unique referral code below</p>
            </div>
          </div>
          <div className="step-connector">
            <div className="connector-line" />
            <div className="connector-arrow">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <line x1="5" y1="12" x2="19" y2="12" />
                <polyline points="12 5 19 12 12 19" />
              </svg>
            </div>
          </div>
          <div className="step glow-step">
            <div className="step-number">2</div>
            <div className="step-icon-svg">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
                <circle cx="9" cy="7" r="4" />
                <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
                <path d="M16 3.13a4 4 0 0 1 0 7.75" />
              </svg>
            </div>
            <div className="step-content">
              <strong>Friends Sign Up</strong>
              <p>They register using your code</p>
            </div>
          </div>
          <div className="step-connector">
            <div className="connector-line" />
            <div className="connector-arrow">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <line x1="5" y1="12" x2="19" y2="12" />
                <polyline points="12 5 19 12 12 19" />
              </svg>
            </div>
          </div>
          <div className="step glow-step highlight">
            <div className="step-number">3</div>
            <div className="step-icon-svg reward">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <line x1="12" y1="1" x2="12" y2="23" />
                <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
              </svg>
            </div>
            <div className="step-content">
              <strong>Earn Rewards!</strong>
              <p>Get 1% of their first $250 winnings</p>
            </div>
          </div>
        </div>
      </div>
      
      {/* Your Referral Code - Premium Glow Box */}
      <div className="section-card referral-code-card glow-card">
        <div className="card-glow-effect" />
        <h3 className="section-title">
          <span className="section-icon glow-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14" />
            </svg>
          </span>
          Your Referral Code
          <span className="copy-hint">Click to copy!</span>
        </h3>
        <div className="referral-code-box premium">
          <input 
            type="text" 
            className="referral-code-input glow-input" 
            readOnly 
            value={referralData?.referral_code?.toUpperCase() || 'LOADING...'}
            onClick={copyReferralCode}
          />
          <button className="btn btn-primary btn-glow" onClick={copyReferralCode}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
              <path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" />
            </svg>
            {copyText}
          </button>
        </div>
        
        {/* Referral Stats - Glowing Cards */}
        <div className="referral-stats-row premium">
          <div className="referral-stat glow-stat">
            <div className="stat-glow" />
            <div className="referral-stat-icon-svg">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
                <circle cx="9" cy="7" r="4" />
                <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
                <path d="M16 3.13a4 4 0 0 1 0 7.75" />
              </svg>
            </div>
            <div className="referral-stat-value">{referralData?.total_referrals || 0}</div>
            <div className="referral-stat-label">Total Referrals</div>
          </div>
          <div className="referral-stat glow-stat success">
            <div className="stat-glow" />
            <div className="referral-stat-icon-svg">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <line x1="12" y1="1" x2="12" y2="23" />
                <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
              </svg>
            </div>
            <div className="referral-stat-value">{fmt(referralData?.total_earnings || 0)}</div>
            <div className="referral-stat-label">Total Earned</div>
          </div>
          <div className="referral-stat glow-stat pending">
            <div className="stat-glow" />
            <div className="referral-stat-icon-svg">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <circle cx="12" cy="12" r="10" />
                <polyline points="12 6 12 12 16 14" />
              </svg>
            </div>
            <div className="referral-stat-value">{fmt(unclaimedAmount)}</div>
            <div className="referral-stat-label">Pending</div>
          </div>
        </div>
      </div>
      
      {/* Claim a Code */}
      {!hasReferrer && (
        <div className="section-card claim-code-card">
          <h3 className="section-title">
            <span className="section-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z" />
              </svg>
            </span>
            Have a Friend's Code?
          </h3>
          {claimMessage && (
            <div className={`message ${claimMessage.type}`}>{claimMessage.text}</div>
          )}
          <div className="claim-code-box">
            <input 
              type="text" 
              className="referral-code-input" 
              placeholder="Enter friend's code"
              value={claimCode}
              onChange={(e) => setClaimCode(e.target.value.toUpperCase())}
            />
            <button 
              className="btn btn-primary" 
              onClick={handleClaimBonus}
              disabled={isClaimLoading}
            >
              {isClaimLoading ? 'Processing...' : 'Apply Code'}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ============================================
// SECURITY TAB
// ============================================
function SecurityTab({ user }) {
  const [twoFactorEnabled, setTwoFactorEnabled] = useState(user?.two_factor_enabled || false);
  const [showPasswordModal, setShowPasswordModal] = useState(false);
  
  return (
    <div className="security-tab">
      {/* Account Security Status */}
      <div className="section-card">
        <h3 className="section-title">
          <span className="section-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
            </svg>
          </span>
          Security Status
        </h3>
        <div className="security-status-grid">
          <div className={`security-item ${user?.email_verified ? 'secure' : 'warning'}`}>
            <div className="security-item-icon">
              {user?.email_verified ? (
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              ) : (
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
              )}
            </div>
            <div className="security-item-content">
              <div className="security-item-title">Email Verification</div>
              <div className="security-item-status">
                {user?.email_verified ? 'Verified' : 'Not verified'}
              </div>
            </div>
          </div>
          
          <div className={`security-item ${twoFactorEnabled ? 'secure' : 'neutral'}`}>
            <div className="security-item-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
              </svg>
            </div>
            <div className="security-item-content">
              <div className="security-item-title">Two-Factor Authentication</div>
              <div className="security-item-status">
                {twoFactorEnabled ? 'Enabled' : 'Disabled'}
              </div>
            </div>
            <Toggle 
              checked={twoFactorEnabled} 
              onChange={(val) => setTwoFactorEnabled(val)} 
            />
          </div>
        </div>
      </div>
      
      {/* Password & Sessions */}
      <div className="section-card">
        <h3 className="section-title">
          <span className="section-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
            </svg>
          </span>
          Password & Access
        </h3>
        <div className="security-actions">
          <button className="btn btn-secondary" onClick={() => setShowPasswordModal(true)}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
            </svg>
            Change Password
          </button>
          <button className="btn btn-secondary btn-danger-outline">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
            </svg>
            Log Out All Devices
          </button>
        </div>
      </div>
      
      {/* Login History */}
      <div className="section-card">
        <h3 className="section-title">
          <span className="section-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </span>
          Recent Logins
        </h3>
        <div className="login-history">
          <div className="login-item current">
            <div className="login-device">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
                <line x1="8" y1="21" x2="16" y2="21" />
                <line x1="12" y1="17" x2="12" y2="21" />
              </svg>
            </div>
            <div className="login-details">
              <div className="login-location">Current Session</div>
              <div className="login-time">Active now</div>
            </div>
            <span className="login-badge current">This device</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================
// SETTINGS TAB
// ============================================
function SettingsTab({ user, preferences, onUpdatePreferences }) {
  const [soundEnabled, setSoundEnabled] = useState(preferences?.sound ?? true);
  const [notificationsEnabled, setNotificationsEnabled] = useState(preferences?.notifications ?? true);
  const [compactMode, setCompactMode] = useState(preferences?.compactMode ?? false);
  const [showConfirmations, setShowConfirmations] = useState(preferences?.confirmations ?? true);
  
  return (
    <div className="settings-tab">
      {/* Display Preferences */}
      <div className="section-card">
        <h3 className="section-title">
          <span className="section-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
            </svg>
          </span>
          Display
        </h3>
        <div className="settings-list">
          <div className="setting-item">
            <div className="setting-info">
              <div className="setting-title">Compact Mode</div>
              <div className="setting-desc">Use a more condensed layout</div>
            </div>
            <Toggle checked={compactMode} onChange={setCompactMode} />
          </div>
        </div>
      </div>
      
      {/* Sound & Notifications */}
      <div className="section-card">
        <h3 className="section-title">
          <span className="section-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z" />
            </svg>
          </span>
          Sound & Notifications
        </h3>
        <div className="settings-list">
          <div className="setting-item">
            <div className="setting-info">
              <div className="setting-title">Sound Effects</div>
              <div className="setting-desc">Play sounds for wins, losses, and actions</div>
            </div>
            <Toggle checked={soundEnabled} onChange={setSoundEnabled} />
          </div>
          <div className="setting-item">
            <div className="setting-info">
              <div className="setting-title">Browser Notifications</div>
              <div className="setting-desc">Get notified about game results</div>
            </div>
            <Toggle checked={notificationsEnabled} onChange={setNotificationsEnabled} />
          </div>
        </div>
      </div>
      
      {/* Gameplay */}
      <div className="section-card">
        <h3 className="section-title">
          <span className="section-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
              <path d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </span>
          Gameplay
        </h3>
        <div className="settings-list">
          <div className="setting-item">
            <div className="setting-info">
              <div className="setting-title">Bet Confirmations</div>
              <div className="setting-desc">Show confirmation dialog before placing bets</div>
            </div>
            <Toggle checked={showConfirmations} onChange={setShowConfirmations} />
          </div>
        </div>
      </div>
      
      {/* Account Info */}
      <div className="section-card">
        <h3 className="section-title">
          <span className="section-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
            </svg>
          </span>
          Account
        </h3>
        <div className="account-info-display">
          <div className="account-info-row">
            <span className="account-info-label">Username</span>
            <span className="account-info-value">{user?.username}</span>
          </div>
          <div className="account-info-row">
            <span className="account-info-label">Email</span>
            <span className="account-info-value">{user?.email}</span>
          </div>
          <div className="account-info-row">
            <span className="account-info-label">Member Since</span>
            <span className="account-info-value">{formatDate(user?.created_at)}</span>
          </div>
          <div className="account-info-row">
            <span className="account-info-label">Account ID</span>
            <span className="account-info-value code">#{user?.id || '—'}</span>
          </div>
        </div>
      </div>
      
      {/* Danger Zone */}
      <div className="section-card danger-zone">
        <h3 className="section-title">
          <span className="section-icon danger">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
          </span>
          Danger Zone
        </h3>
        <p className="danger-text">These actions are irreversible. Please be certain.</p>
        <div className="danger-actions">
          <button className="btn btn-danger-outline">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
            Delete Account
          </button>
        </div>
      </div>
    </div>
  );
}

// ============================================
// MAIN APP COMPONENT
// ============================================
function UserProfileApp() {
  const [user, setUser] = useState(null);
  const [stats, setStats] = useState(null);
  const [referralData, setReferralData] = useState(null);
  const [levelInfo, setLevelInfo] = useState(null);
  const [xpBoost, setXpBoost] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('overview');
  const [vaultClaimLoading, setVaultClaimLoading] = useState(false);
  const [preferences, setPreferences] = useState({});
  
  useEffect(() => {
    loadData();
  }, []);
  
  const loadData = async () => {
    try {
      // Check authentication
      const meRes = await fetch('/me', { credentials: 'include' });
      if (!meRes.ok) {
        alert('You need to be logged in to view your profile.');
        window.location.href = '/';
        return;
      }
      const meData = await meRes.json();
      setUser(meData);
      setLevelInfo(meData.level_info);
      
      // Fetch extended profile stats
      const profileRes = await fetch('/api/user/profile', { credentials: 'include' });
      if (profileRes.ok) {
        const profileData = await profileRes.json();
        setStats(profileData.statistics);
        setUser(prev => ({ ...prev, ...profileData.user }));
      }
      
      // Fetch daily reward status for XP boost
      try {
        const dailyRes = await fetch('/api/daily-reward/status', { credentials: 'include' });
        if (dailyRes.ok) {
          const dailyData = await dailyRes.json();
          if (dailyData.active_bonuses?.xp_boost > 0) {
            setXpBoost(dailyData.active_bonuses.xp_boost);
          }
        }
      } catch {}
      
      // Fetch referral data
      await loadReferralData();
      
    } catch (error) {
      console.error('Failed to load profile:', error);
    } finally {
      setIsLoading(false);
    }
  };
  
  const loadReferralData = async () => {
    try {
      const res = await fetch('/api/referral/stats', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setReferralData(data);
      }
    } catch (error) {
      console.error('Error loading referral data:', error);
    }
  };
  
  const claimVaultEarnings = async () => {
    setVaultClaimLoading(true);
    
    try {
      const res = await fetch('/api/referral/claim-earnings', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' }
      });
      
      const data = await res.json();
      
      if (res.ok && data.success) {
        setUser(prev => ({ ...prev, balance: data.new_balance * 100 }));
        await loadReferralData();
      }
    } catch (error) {
      console.error('Error claiming vault:', error);
    } finally {
      setVaultClaimLoading(false);
    }
  };
  
  if (isLoading) {
    return (
      <>
        <FloatingOrbs />
        <CoinRushNavbar activePage="profile" />
        <div className="profile-page">
          <div className="profile-container">
            <LoadingState />
          </div>
        </div>
      </>
    );
  }
  
  return (
    <>
      <FloatingOrbs />
      <CoinRushNavbar activePage="profile" />
      
      <div className="profile-page">
        <div className="profile-container">
          {/* Profile Hero */}
          <ProfileHero 
            user={user} 
            stats={stats} 
            levelInfo={levelInfo}
            xpBoost={xpBoost}
          />
          
          {/* Tab Navigation */}
          <TabNav activeTab={activeTab} onTabChange={setActiveTab} />
          
          {/* Tab Content */}
          <div className="tab-content">
            {activeTab === 'overview' && (
              <>
                <QuickStats user={user} stats={stats} />
                <RecentActivity stats={stats} />
              </>
            )}
            
            {activeTab === 'stats' && (
              <StatisticsTab stats={stats} />
            )}
            
            {activeTab === 'referrals' && (
              <ReferralsTab 
                referralData={referralData}
                onClaimBonus={loadReferralData}
                onClaimVault={claimVaultEarnings}
                vaultClaimLoading={vaultClaimLoading}
                hasReferrer={!!referralData?.referred_by_user_id}
              />
            )}
            
            {activeTab === 'security' && (
              <SecurityTab user={user} />
            )}
            
            {activeTab === 'settings' && (
              <SettingsTab 
                user={user} 
                preferences={preferences}
                onUpdatePreferences={setPreferences}
              />
            )}
          </div>
          
          {/* Back Button */}
          <div className="back-button-container">
            <a href="/" className="back-btn">
              <span>←</span>
              <span>Back to Casino</span>
            </a>
          </div>
        </div>
      </div>
    </>
  );
}

// ============================================
// MOUNT APP
// ============================================
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<UserProfileApp />);
