/**
 * Hall of Fame - React Edition v3.0
 * Premium Design with SVG Icons - Uses shared CoinRushNavbar
 */

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

// Use shared CoinRushNavbar
const CoinRushNavbar = window.CoinRushNavbar;

// ============================================
// SVG ICONS - Premium Design
// ============================================
const Icons = {
  trophy: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 9V2h12v7a6 6 0 01-6 6 6 6 0 01-6-6z"/>
      <path d="M6 3H4a2 2 0 000 4h2"/>
      <path d="M18 3h2a2 2 0 010 4h-2"/>
      <path d="M12 15v3"/>
      <path d="M8 21h8"/>
      <path d="M8 18h8"/>
    </svg>
  ),
  crown: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2 18l3-12 5 6 2-8 2 8 5-6 3 12H2z"/>
      <path d="M2 18h20v3H2z"/>
    </svg>
  ),
  medal: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="15" r="6"/>
      <path d="M9 2h6l-3 7-3-7z"/>
      <path d="M6 2l3 7"/>
      <path d="M18 2l-3 7"/>
      <path d="M12 12v2"/>
      <path d="M10 17h4"/>
    </svg>
  ),
  star: (
    <svg viewBox="0 0 24 24" fill="currentColor" stroke="none">
      <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"/>
    </svg>
  ),
  fire: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 22c4-2.5 6-6.5 6-10 0-6-6-10-6-10S6 6 6 12c0 3.5 2 7.5 6 10z"/>
      <path d="M12 22c-2-1.5-3-3.5-3-6 0-3 3-5 3-5s3 2 3 5c0 2.5-1 4.5-3 6z"/>
    </svg>
  ),
  coins: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="9" cy="9" r="7"/>
      <path d="M15 15a7 7 0 11-7-7"/>
      <path d="M9 6v6l3 2"/>
    </svg>
  ),
  chart: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="4,18 9,13 13,15 20,6"/>
      <polyline points="15,6 20,6 20,11"/>
    </svg>
  ),
  lightning: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <polygon points="13,2 3,14 12,14 11,22 21,10 12,10"/>
    </svg>
  ),
  users: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/>
      <circle cx="9" cy="7" r="4"/>
      <path d="M23 21v-2a4 4 0 00-3-3.87"/>
      <path d="M16 3.13a4 4 0 010 7.75"/>
    </svg>
  ),
  gamepad: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="6" width="20" height="12" rx="2"/>
      <path d="M6 12h4M8 10v4"/>
      <circle cx="17" cy="10" r="1" fill="currentColor"/>
      <circle cx="15" cy="12" r="1" fill="currentColor"/>
    </svg>
  ),
  clock: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="10"/>
      <polyline points="12,6 12,12 16,14"/>
    </svg>
  ),
  dice: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="3" width="18" height="18" rx="2"/>
      <circle cx="8" cy="8" r="1.5" fill="currentColor"/>
      <circle cx="16" cy="16" r="1.5" fill="currentColor"/>
      <circle cx="12" cy="12" r="1.5" fill="currentColor"/>
    </svg>
  ),
  arrow: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14M12 5l7 7-7 7"/>
    </svg>
  ),
  chevronDown: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="6 9 12 15 18 9"/>
    </svg>
  ),
  close: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="6" x2="6" y2="18"/>
      <line x1="6" y1="6" x2="18" y2="18"/>
    </svg>
  ),
  check: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 6 9 17 4 12"/>
    </svg>
  ),
  gift: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 12 20 22 4 22 4 12"/>
      <rect x="2" y="7" width="20" height="5"/>
      <line x1="12" y1="22" x2="12" y2="7"/>
      <path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"/>
      <path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"/>
    </svg>
  ),
  info: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="10"/>
      <line x1="12" y1="16" x2="12" y2="12"/>
      <line x1="12" y1="8" x2="12.01" y2="8"/>
    </svg>
  )
};

// ============================================
// UTILITIES
// ============================================
const fmt = (n) => new Intl.NumberFormat().format(n || 0);
const fmtMoney = (cents) => {
  const d = (cents || 0) / 100;
  return d >= 1000 ? `$${(d/1000).toFixed(1)}K` : `$${d.toFixed(2)}`;
};

const countdown = (end) => {
  const ms = end - Date.now();
  if (ms <= 0) return { days: 0, hours: 0, mins: 0, secs: 0 };
  return {
    days: Math.floor(ms / 86400000),
    hours: Math.floor((ms % 86400000) / 3600000),
    mins: Math.floor((ms % 3600000) / 60000),
    secs: Math.floor((ms % 60000) / 1000)
  };
};

const REWARDS = {
  weekly: ['$200', '$100', '$50'],
  monthly: ['$3,000', '$1,500', '$500'],
};

// ============================================
// INTERACTIVE HOOKS & COMPONENTS
// ============================================

// Ripple effect for buttons
function useRipple() {
  const createRipple = (e) => {
    const btn = e.currentTarget;
    const circle = document.createElement('span');
    const rect = btn.getBoundingClientRect();
    const size = Math.max(rect.width, rect.height);
    circle.style.cssText = `
      position: absolute;
      width: ${size}px;
      height: ${size}px;
      left: ${e.clientX - rect.left - size/2}px;
      top: ${e.clientY - rect.top - size/2}px;
      background: rgba(255,255,255,0.3);
      border-radius: 50%;
      transform: scale(0);
      animation: ripple-effect 0.6s ease-out;
      pointer-events: none;
    `;
    btn.style.position = 'relative';
    btn.style.overflow = 'hidden';
    btn.appendChild(circle);
    setTimeout(() => circle.remove(), 600);
  };
  return createRipple;
}

// Tooltip component
function Tooltip({ children, text, position = 'top' }) {
  const [show, setShow] = useState(false);
  return (
    <div 
      className="tooltip-wrapper"
      onMouseEnter={() => setShow(true)}
      onMouseLeave={() => setShow(false)}
    >
      {children}
      {show && <div className={`tooltip tooltip-${position}`}>{text}</div>}
    </div>
  );
}

// Sparkle effect for medals
function Sparkles({ active }) {
  if (!active) return null;
  return (
    <div className="sparkles">
      {[...Array(6)].map((_, i) => (
        <div 
          key={i} 
          className="sparkle" 
          style={{
            '--delay': `${i * 0.1}s`,
            '--angle': `${i * 60}deg`
          }}
        />
      ))}
    </div>
  );
}

// Progress bar with animation
function ProgressBar({ value, max, label, color = 'green' }) {
  const [width, setWidth] = useState(0);
  const percent = Math.min((value / max) * 100, 100);
  
  useEffect(() => {
    setTimeout(() => setWidth(percent), 100);
  }, [percent]);
  
  return (
    <div className="progress-container">
      {label && <div className="progress-label">{label}</div>}
      <div className="progress-bar">
        <div 
          className={`progress-fill progress-${color}`}
          style={{ width: `${width}%` }}
        />
      </div>
      <div className="progress-value">{value.toLocaleString()} / {max.toLocaleString()}</div>
    </div>
  );
}

// Intersection Observer hook for scroll animations
function useOnScreen(ref, threshold = 0.1) {
  const [isVisible, setIsVisible] = useState(false);
  
  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          observer.disconnect();
        }
      },
      { threshold }
    );
    
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, [ref, threshold]);
  
  return isVisible;
}

// ============================================
// ANIMATED NUMBER
// ============================================
function AnimatedNumber({ value, prefix = '', suffix = '', duration = 1500 }) {
  const [display, setDisplay] = useState(0);
  const animRef = useRef(null);
  
  useEffect(() => {
    const start = display;
    const target = value;
    const t0 = performance.now();
    
    const tick = (t) => {
      const p = Math.min((t - t0) / duration, 1);
      const eased = 1 - Math.pow(1 - p, 4);
      setDisplay(Math.floor(start + (target - start) * eased));
      if (p < 1) animRef.current = requestAnimationFrame(tick);
    };
    
    animRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(animRef.current);
  }, [value]);
  
  return <span>{prefix}{fmt(display)}{suffix}</span>;
}

// ============================================
// COUNTDOWN TIMER - Premium Design
// ============================================
function CountdownTimer({ type }) {
  const [time, setTime] = useState({ days: 0, hours: 0, mins: 0, secs: 0 });
  
  useEffect(() => {
    const update = () => {
      const now = new Date();
      let end;
      
      if (type === 'weekly') {
        end = new Date(now);
        end.setDate(now.getDate() + (7 - now.getDay()));
        end.setHours(23, 59, 59);
      } else {
        end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59);
      }
      
      setTime(countdown(end));
    };
    
    update();
    const interval = setInterval(update, 1000);
    return () => clearInterval(interval);
  }, [type]);
  
  return (
    <div className="countdown-timer">
      <div className="countdown-icon">{Icons.clock}</div>
      <div className="countdown-segments">
        <div className="countdown-segment">
          <span className="countdown-value">{String(time.days).padStart(2, '0')}</span>
          <span className="countdown-label">D</span>
        </div>
        <span className="countdown-sep">:</span>
        <div className="countdown-segment">
          <span className="countdown-value">{String(time.hours).padStart(2, '0')}</span>
          <span className="countdown-label">H</span>
        </div>
        <span className="countdown-sep">:</span>
        <div className="countdown-segment">
          <span className="countdown-value">{String(time.mins).padStart(2, '0')}</span>
          <span className="countdown-label">M</span>
        </div>
      </div>
    </div>
  );
}

// ============================================
// HERO SECTION - Premium Centered Design with Glowing Prize
// ============================================
function HeroSection({ stats }) {
  const [visible, setVisible] = useState(false);
  const [prizeHovered, setPrizeHovered] = useState(false);
  
  useEffect(() => {
    setTimeout(() => setVisible(true), 100);
  }, []);
  
  return (
    <section className={`hero-premium ${visible ? 'visible' : ''}`}>
      {/* Floating Glowing Orbs Background */}
      <div className="hero-orbs">
        <div className="orb orb-1"></div>
        <div className="orb orb-2"></div>
        <div className="orb orb-3"></div>
        <div className="orb orb-4"></div>
        <div className="orb orb-5"></div>
        <div className="orb orb-6"></div>
        <div className="orb orb-7"></div>
        <div className="orb orb-8"></div>
      </div>
      
      {/* Animated Background Particles */}
      <div className="hero-particles">
        {[...Array(30)].map((_, i) => (
          <div 
            key={i} 
            className="particle" 
            style={{
              '--delay': `${i * 0.2}s`,
              '--x': `${Math.random() * 100}%`,
              '--duration': `${3 + Math.random() * 4}s`,
              '--size': `${2 + Math.random() * 4}px`
            }}
          />
        ))}
      </div>
      
      <div className="hero-premium-content">
        {/* Subtle Page Title at Top */}
        <div className="hero-page-title">
          <span className="page-title-icon">{Icons.trophy}</span>
          <span className="page-title-text">Hall of Fame</span>
        </div>
        
        {/* Main Prize Pool - Fully Centered & Prominent */}
        <div 
          className={`prize-pool-container ${prizeHovered ? 'hovered' : ''}`}
          onMouseEnter={() => setPrizeHovered(true)}
          onMouseLeave={() => setPrizeHovered(false)}
        >
          {/* Multi-layer glow effect */}
          <div className="prize-glow-layer prize-glow-1"></div>
          <div className="prize-glow-layer prize-glow-2"></div>
          <div className="prize-glow-layer prize-glow-3"></div>
          
          <div className="prize-content">
            <div className="prize-label-top">Total Prize Pool</div>
            <div className="prize-amount-wrapper">
              <span className="prize-currency">$</span>
              <span className="prize-amount">5,350</span>
            </div>
            <div className="prize-label-bottom">in weekly & monthly rewards</div>
          </div>
          
          {/* Sparkle effects on hover */}
          <div className="prize-sparkles">
            {[...Array(12)].map((_, i) => (
              <div 
                key={i} 
                className="sparkle" 
                style={{ '--angle': `${i * 30}deg`, '--delay': `${i * 0.08}s` }}
              />
            ))}
          </div>
        </div>
        
        {/* Subtitle */}
        <p className="hero-tagline">
          Compete in weekly & monthly competitions for real cash prizes
        </p>
        
        {/* Stats Row */}
        <div className="hero-stats-premium">
          <div className="stat-pill">
            <div className="stat-pill-icon">{Icons.coins}</div>
            <div className="stat-pill-content">
              <span className="stat-pill-value gold">$350</span>
              <span className="stat-pill-label">Weekly</span>
            </div>
          </div>
          
          <div className="stat-pill">
            <div className="stat-pill-icon">{Icons.crown}</div>
            <div className="stat-pill-content">
              <span className="stat-pill-value gold">$5,000</span>
              <span className="stat-pill-label">Monthly</span>
            </div>
          </div>
          
          <div className="stat-pill">
            <div className="stat-pill-icon">{Icons.users}</div>
            <div className="stat-pill-content">
              <span className="stat-pill-value"><AnimatedNumber value={stats.totalUsers || 0} /></span>
              <span className="stat-pill-label">Players</span>
            </div>
          </div>
          
          <div className="stat-pill">
            <div className="stat-pill-icon">{Icons.gamepad}</div>
            <div className="stat-pill-content">
              <span className="stat-pill-value"><AnimatedNumber value={stats.totalGames || 0} /></span>
              <span className="stat-pill-label">Games</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============================================
// MEDAL COMPONENT - SVG Based
// ============================================
function Medal({ rank, size = 'medium' }) {
  const [hovered, setHovered] = useState(false);
  const colors = {
    1: { primary: '#FFD700', secondary: '#FFA500', glow: 'rgba(255, 215, 0, 0.4)', name: '1st Place' },
    2: { primary: '#C0C0C0', secondary: '#A8A8A8', glow: 'rgba(192, 192, 192, 0.4)', name: '2nd Place' },
    3: { primary: '#CD7F32', secondary: '#A0522D', glow: 'rgba(205, 127, 50, 0.4)', name: '3rd Place' }
  };
  
  const c = colors[rank] || colors[1];
  const sizeClass = `medal-${size}`;
  
  return (
    <div 
      className={`medal-wrapper ${sizeClass}`}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      <Sparkles active={hovered} />
      <div className="medal" style={{ '--medal-primary': c.primary, '--medal-secondary': c.secondary, '--medal-glow': c.glow }}>
      <svg viewBox="0 0 60 80" fill="none">
        {/* Ribbon */}
        <path d="M20 0 L30 25 L40 0 L45 0 L32 30 L28 30 L15 0 Z" fill={c.secondary} opacity="0.8"/>
        <path d="M15 0 L28 30 L22 30 L5 0 Z" fill={c.primary}/>
        <path d="M45 0 L32 30 L38 30 L55 0 Z" fill={c.primary}/>
        
        {/* Medal Circle */}
        <circle cx="30" cy="52" r="24" fill={`url(#medalGrad${rank})`} stroke={c.primary} strokeWidth="3"/>
        <circle cx="30" cy="52" r="18" fill="none" stroke={c.secondary} strokeWidth="1" opacity="0.5"/>
        
        {/* Rank Number */}
        <text x="30" y="58" textAnchor="middle" fill="#0a0f14" fontSize="20" fontWeight="bold" fontFamily="Sora, sans-serif">
          {rank}
        </text>
        
        {/* Gradient Definitions */}
        <defs>
          <linearGradient id={`medalGrad${rank}`} x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor={c.primary}/>
            <stop offset="100%" stopColor={c.secondary}/>
          </linearGradient>
        </defs>
      </svg>
      </div>
    </div>
  );
}

// ============================================
// LEADERBOARD ROW - Premium Design
// ============================================
function LeaderboardRow({ data, rank, prize, delay = 0, isCurrentUser = false }) {
  const [visible, setVisible] = useState(false);
  
  useEffect(() => {
    const timer = setTimeout(() => setVisible(true), delay);
    return () => clearTimeout(timer);
  }, [delay]);
  
  const isTop3 = rank <= 3;
  
  return (
    <div className={`leaderboard-row ${isTop3 ? `rank-${rank}` : ''} ${visible ? 'visible' : ''} ${isCurrentUser ? 'current-user' : ''}`}>
      <div className="row-rank">
        {isTop3 ? (
          <Tooltip text={`${rank === 1 ? '🥇 Champion' : rank === 2 ? '🥈 Runner-up' : '🥉 Third Place'}`}>
            <Medal rank={rank} size="small" />
          </Tooltip>
        ) : (
          <span className="rank-number">{rank}</span>
        )}
      </div>
      <div className="row-player">
        <Tooltip text={`View ${data.username || 'Anonymous'}'s profile`} position="bottom">
          <div className="player-avatar" style={{ 
            background: `linear-gradient(135deg, hsl(${(data.username || 'A').charCodeAt(0) * 15}, 70%, 45%), hsl(${(data.username || 'A').charCodeAt(0) * 15}, 60%, 35%))` 
          }}>
            {(data.username || '?')[0].toUpperCase()}
          </div>
        </Tooltip>
        <div className="player-info">
          <div className="player-name">
            {data.username || 'Anonymous'}
            {isCurrentUser && <span className="you-badge">YOU</span>}
          </div>
          <div className="player-level">
            <span className="level-icon">{Icons.lightning}</span>
            Level {data.level || 1}
          </div>
        </div>
      </div>
      <div className="row-wagered">
        <Tooltip text="Total amount wagered this period">
          <span className="wagered-value">{fmtMoney(data.wagered)}</span>
        </Tooltip>
      </div>
      {prize ? (
        <div className="row-prize">
          <Tooltip text="Prize if competition ends now">
            <span className="prize-value">{prize}</span>
          </Tooltip>
        </div>
      ) : (
        <div className="row-prize">
          <span className="prize-value no-prize">—</span>
        </div>
      )}
    </div>
  );
}

// ============================================
// COMPETITION CARD - Premium Design
// ============================================
function CompetitionCard({ type, leaders, isHot = false }) {
  const isMonthly = type === 'monthly';
  const prizes = isMonthly ? REWARDS.monthly : REWARDS.weekly;
  const [currentUser, setCurrentUser] = useState(null);
  
  // Fetch current user on mount
  useEffect(() => {
    const fetchUser = async () => {
      try {
        const res = await fetch('/me', { credentials: 'include' });
        if (res.ok) {
          const data = await res.json();
          setCurrentUser(data);
        }
      } catch (e) {
        // Not logged in
      }
    };
    fetchUser();
  }, []);
  
  // Find the current user's position in the leaderboard
  const getUserRankData = () => {
    if (!currentUser || !leaders || leaders.length === 0) return null;
    
    const idx = leaders.findIndex(l => l.username === currentUser.username);
    if (idx === -1) return null; // User not on leaderboard
    if (idx < 3) return null; // User is already in top 3, don't show twice
    
    return {
      rank: idx + 1,
      data: leaders[idx],
      prize: idx < 3 ? prizes[idx] : null
    };
  };
  
  const userRankData = getUserRankData();
  
  return (
    <article className={`competition-card ${isMonthly ? 'monthly' : 'weekly'}`}>
      {/* Glow Effect */}
      <div className="card-glow"></div>
      <div className="card-border"></div>
      
      {/* Hot Badge */}
      {isHot && (
        <div className="hot-badge">
          <span className="hot-icon">{Icons.fire}</span>
          <span>HOT</span>
        </div>
      )}
      
      {/* Header */}
      <header className="card-header">
        <div className="card-title">
          <div className="title-icon">{isMonthly ? Icons.crown : Icons.trophy}</div>
          <div className="title-text">
            <span className="title-type">{type.toUpperCase()}</span>
            <span className="title-sub">Competition</span>
          </div>
        </div>
        <div className="card-header-right">
          <div className="live-indicator is-live">
            <span className="live-dot"></span>
            <span className="live-text">LIVE</span>
          </div>
          <CountdownTimer type={type} />
        </div>
      </header>
      
      {/* Prize Podium */}
      <div className="prize-podium">
        {/* 2nd Place */}
        <div className="podium-item podium-2">
          <Medal rank={2} size="medium" />
          <div className="podium-prize">{prizes[1]}</div>
          <div className="podium-label">2nd Place</div>
          <div className="podium-stand"></div>
        </div>
        
        {/* 1st Place */}
        <div className="podium-item podium-1">
          <Medal rank={1} size="large" />
          <div className="podium-prize champion">{prizes[0]}</div>
          <div className="podium-label">{isMonthly ? 'Champion' : '1st Place'}</div>
          <div className="podium-stand"></div>
        </div>
        
        {/* 3rd Place */}
        <div className="podium-item podium-3">
          <Medal rank={3} size="medium" />
          <div className="podium-prize">{prizes[2]}</div>
          <div className="podium-label">3rd Place</div>
          <div className="podium-stand"></div>
        </div>
      </div>
      
      {/* Divider */}
      <div className="card-divider">
        <span className="divider-text">Leaderboard</span>
      </div>
      
      {/* Leaderboard */}
      <div className="leaderboard">
        <div className="leaderboard-header">
          <span>Rank</span>
          <span>Player</span>
          <span>Wagered</span>
          <span>Prize</span>
        </div>
        
        {leaders && leaders.length > 0 ? (
          <>
            {/* Top 3 players */}
            {leaders.slice(0, 3).map((leader, i) => (
              <LeaderboardRow 
                key={leader.username || i}
                data={leader}
                rank={i + 1}
                prize={prizes[i]}
                delay={i * 80}
                isCurrentUser={currentUser && leader.username === currentUser.username}
              />
            ))}
            
            {/* Current user's position (if not in top 3) */}
            {userRankData && (
              <>
                <div className="leaderboard-separator">
                  <span className="separator-dots">•••</span>
                </div>
                <LeaderboardRow 
                  data={userRankData.data}
                  rank={userRankData.rank}
                  prize={userRankData.prize}
                  delay={300}
                  isCurrentUser={true}
                />
              </>
            )}
          </>
        ) : (
          <div className="empty-state">
            <div className="empty-icon">{Icons.trophy}</div>
            <div className="empty-text">Be the first to compete!</div>
            <div className="empty-sub">Start playing to climb the leaderboard</div>
          </div>
        )}
      </div>
    </article>
  );
}

// ============================================
// STAT CARD - Premium Design
// ============================================
function StatCard({ title, icon, type, data, colorClass }) {
  const getValue = (item) => {
    if (type === 'wins') return fmtMoney(item.amount || item.profit);
    if (type === 'profit') return (item.net_profit >= 0 ? '+' : '') + fmtMoney(item.net_profit);
    return `Lvl ${item.level}`;
  };
  
  return (
    <div className={`stat-card-large ${colorClass}`}>
      <div className="stat-card-header">
        <div className="stat-card-icon">{icon}</div>
        <h3 className="stat-card-title">{title}</h3>
      </div>
      
      <div className="stat-card-list">
        {data && data.length > 0 ? (
          data.slice(0, 3).map((item, i) => (
            <div key={i} className={`stat-row rank-${i + 1}`}>
              <div className="stat-row-rank">
                <Medal rank={i + 1} size="tiny" />
              </div>
              <div className="stat-row-player">
                <div className="stat-avatar" style={{ 
                  background: `linear-gradient(135deg, hsl(${(item.username || 'A').charCodeAt(0) * 15}, 70%, 45%), hsl(${(item.username || 'A').charCodeAt(0) * 15}, 60%, 35%))` 
                }}>
                  {(item.username || '?')[0].toUpperCase()}
                </div>
                <span className="stat-name">{item.username || 'Anonymous'}</span>
              </div>
              <div className={`stat-value ${colorClass}`}>{getValue(item)}</div>
            </div>
          ))
        ) : (
          <div className="empty-mini">No data yet</div>
        )}
      </div>
    </div>
  );
}

// ============================================
// STATS SECTION
// ============================================
function StatsSection({ biggestWins, topProfit, highestLevel }) {
  return (
    <section className="stats-section">
      <div className="section-header">
        <div className="section-icon">{Icons.star}</div>
        <h2 className="section-title">Legends & Records</h2>
        <p className="section-subtitle">Hall of fame's greatest achievements</p>
      </div>
      
      <div className="stats-grid">
        <StatCard 
          title="Biggest Wins"
          icon={Icons.coins}
          type="wins"
          data={biggestWins}
          colorClass="gold"
        />
        <StatCard 
          title="Top Profit"
          icon={Icons.chart}
          type="profit"
          data={topProfit}
          colorClass="green"
        />
        <StatCard 
          title="Highest Level"
          icon={Icons.lightning}
          type="level"
          data={highestLevel}
          colorClass="purple"
        />
      </div>
    </section>
  );
}

// ============================================
// RULES MODAL - Hall of Fame Guide
// ============================================
function RulesModal({ isOpen, onClose }) {
  if (!isOpen) return null;
  
  return (
    <div className="rules-modal-overlay" onClick={onClose}>
      <div className="rules-modal" onClick={(e) => e.stopPropagation()}>
        <div className="rules-modal-header">
          <h2 className="rules-modal-title">
            <span className="rules-modal-icon">{Icons.trophy}</span>
            Hall of Fame
          </h2>
          <button className="rules-modal-close" onClick={onClose}>
            {Icons.close}
          </button>
        </div>
        
        <div className="rules-modal-body">
          {/* Welcome Section */}
          <section className="rules-section">
            <h3 className="rules-section-title">
              <span className="rules-section-icon">{Icons.crown}</span>
              Welcome to the Legends
            </h3>
            <div className="rules-info-box">
              <p>
                The Hall of Fame is where CoinRush's greatest players are immortalized. 
                Every bet you place, every game you win, contributes to your legacy. 
                This is where champions are made and legends are born.
              </p>
              <p style={{marginTop: '12px', color: 'var(--hof-gold)'}}>
                Will your name be etched among the greats?
              </p>
            </div>
          </section>
          
          {/* Weekly Competition */}
          <section className="rules-section">
            <h3 className="rules-section-title">
              <span className="rules-section-icon">{Icons.clock}</span>
              Weekly Competition
            </h3>
            <div className="rules-steps">
              <div className="rules-step">
                <div className="rules-step-number" style={{background: 'linear-gradient(135deg, #5bffb2, #4de69c)'}}>1</div>
                <div className="rules-step-content">
                  <strong>Play Any Game</strong>
                  <p>Every wager you place across all CoinRush games counts towards your weekly total.</p>
                </div>
              </div>
              <div className="rules-step">
                <div className="rules-step-number" style={{background: 'linear-gradient(135deg, #5bffb2, #4de69c)'}}>2</div>
                <div className="rules-step-content">
                  <strong>Climb the Ranks</strong>
                  <p>Your total wagered amount determines your position on the weekly leaderboard.</p>
                </div>
              </div>
              <div className="rules-step">
                <div className="rules-step-number" style={{background: 'linear-gradient(135deg, #5bffb2, #4de69c)'}}>3</div>
                <div className="rules-step-content">
                  <strong>Claim Your Prize</strong>
                  <p>At week's end, top players receive cash rewards directly to their accounts!</p>
                </div>
              </div>
            </div>
            <div className="rules-info-box" style={{marginTop: '16px'}}>
              <div className="rules-rewards-grid">
                <div className="rules-reward-item">
                  <span className="reward-place" style={{color: '#FFD700'}}>🥇 1st Place</span>
                  <span className="reward-amount">$200</span>
                </div>
                <div className="rules-reward-item">
                  <span className="reward-place" style={{color: '#C0C0C0'}}>🥈 2nd Place</span>
                  <span className="reward-amount">$100</span>
                </div>
                <div className="rules-reward-item">
                  <span className="reward-place" style={{color: '#CD7F32'}}>🥉 3rd Place</span>
                  <span className="reward-amount">$50</span>
                </div>
              </div>
            </div>
          </section>
          
          {/* Monthly Competition */}
          <section className="rules-section">
            <h3 className="rules-section-title">
              <span className="rules-section-icon">{Icons.fire}</span>
              Monthly Championship
            </h3>
            <div className="rules-info-box rules-house-edge-box">
              <p>
                The ultimate test of skill and dedication. Monthly competitions feature 
                <strong style={{color: 'var(--hof-gold)'}}> MASSIVE prize pools</strong> for those 
                who prove themselves over 30 days of intense gameplay.
              </p>
              <div className="rules-rewards-grid" style={{marginTop: '16px'}}>
                <div className="rules-reward-item">
                  <span className="reward-place" style={{color: '#FFD700'}}>🏆 Champion</span>
                  <span className="reward-amount" style={{fontSize: '1.2rem'}}>$3,000</span>
                </div>
                <div className="rules-reward-item">
                  <span className="reward-place" style={{color: '#C0C0C0'}}>🥈 Runner-up</span>
                  <span className="reward-amount">$1,500</span>
                </div>
                <div className="rules-reward-item">
                  <span className="reward-place" style={{color: '#CD7F32'}}>🥉 3rd Place</span>
                  <span className="reward-amount">$500</span>
                </div>
              </div>
            </div>
          </section>
          
          {/* How Ranking Works */}
          <section className="rules-section">
            <h3 className="rules-section-title">
              <span className="rules-section-icon">{Icons.chart}</span>
              How Rankings Work
            </h3>
            <div className="rules-list">
              <div className="rules-list-item">
                <span className="rules-list-icon">{Icons.check}</span>
                <p><strong>Total Wagered:</strong> Your ranking is based on total amount wagered, not winnings</p>
              </div>
              <div className="rules-list-item">
                <span className="rules-list-icon">{Icons.check}</span>
                <p><strong>All Games Count:</strong> Jackpot, Crash, Slice 'n Dice, Knights Arena - every bet matters</p>
              </div>
              <div className="rules-list-item">
                <span className="rules-list-icon">{Icons.check}</span>
                <p><strong>Real-Time Updates:</strong> Leaderboards update instantly as you play</p>
              </div>
              <div className="rules-list-item">
                <span className="rules-list-icon">{Icons.check}</span>
                <p><strong>Fair Play:</strong> Only real wagers count - no exploits or manipulation</p>
              </div>
            </div>
          </section>
          
          {/* Other Leaderboards */}
          <section className="rules-section">
            <h3 className="rules-section-title">
              <span className="rules-section-icon">{Icons.star}</span>
              Glory Beyond Rankings
            </h3>
            <div className="rules-info-box">
              <p>The Hall of Fame celebrates more than just volume. We honor:</p>
              <div className="rules-list" style={{marginTop: '12px'}}>
                <div className="rules-list-item">
                  <span className="rules-list-icon" style={{color: '#FFD700'}}>{Icons.coins}</span>
                  <p><strong>Biggest Wins:</strong> Land a massive multiplier? Your victory will be immortalized.</p>
                </div>
                <div className="rules-list-item">
                  <span className="rules-list-icon" style={{color: '#5bffb2'}}>{Icons.chart}</span>
                  <p><strong>Top Profit:</strong> Smart players who consistently come out ahead.</p>
                </div>
                <div className="rules-list-item">
                  <span className="rules-list-icon" style={{color: '#a855f7'}}>{Icons.lightning}</span>
                  <p><strong>Highest Levels:</strong> Dedication rewarded - the most experienced players.</p>
                </div>
              </div>
            </div>
          </section>
          
          {/* Tips */}
          <section className="rules-section">
            <h3 className="rules-section-title">
              <span className="rules-section-icon">{Icons.gift}</span>
              Pro Tips
            </h3>
            <div className="rules-info-box" style={{background: 'linear-gradient(135deg, rgba(91, 255, 178, 0.1), rgba(168, 85, 247, 0.1))'}}>
              <div className="rules-example">
                <strong>🎯 Consistency is Key:</strong> Regular play beats sporadic big bets for leaderboard climbing.
              </div>
              <div className="rules-example" style={{marginTop: '12px'}}>
                <strong>🎮 Diversify:</strong> Try all games - you might find your lucky one!
              </div>
              <div className="rules-example" style={{marginTop: '12px'}}>
                <strong>⏰ Timing:</strong> Competitions reset weekly (Monday) and monthly (1st). Plan accordingly!
              </div>
            </div>
          </section>
        </div>
        
        <div className="rules-modal-footer">
          <button className="rules-modal-button" onClick={onClose}>
            Let's Go!
          </button>
        </div>
      </div>
    </div>
  );
}

// ============================================
// CTA SECTION
// ============================================
function CTASection() {
  const ripple = useRipple();
  
  return (
    <section className="cta-section">
      <div className="cta-glow"></div>
      <div className="cta-content">
        <div className="cta-icon float-badge">{Icons.dice}</div>
        <h2 className="cta-title">Ready to compete?</h2>
        <p className="cta-text">Every bet counts towards your rank. Start playing now and climb the leaderboard!</p>
        <a href="/slice-dice" className="cta-button" onClick={ripple}>
          <span className="cta-btn-icon">{Icons.gamepad}</span>
          <span>Start Playing</span>
          <span className="cta-btn-arrow">{Icons.arrow}</span>
        </a>
      </div>
    </section>
  );
}

// ============================================
// AUTH MODAL - Use shared component from auth-react.jsx
// ============================================
// The AuthModal is now loaded from /static/js/auth-react.jsx
// which includes OAuth buttons (Discord, Google, X)
// Access it via window.AuthModal

// ============================================
// MAIN APP - Uses shared CoinRushNavbar
// ============================================
function HallOfFameApp() {
  const [user, setUser] = useState(null);
  const [showRules, setShowRules] = useState(false);
  const [showAuthModal, setShowAuthModal] = useState(false);
  const [authModalMode, setAuthModalMode] = useState('login');
  const [data, setData] = useState({
    weeklyLeaders: [],
    monthlyLeaders: [],
    biggestWins: [],
    topProfit: [],
    highestLevel: [],
    stats: { totalUsers: 0, totalGames: 0 }
  });
  const [loading, setLoading] = useState(true);
  
  // Expose rules modal to navbar
  useEffect(() => {
    window.showFameRules = () => setShowRules(true);
    return () => { delete window.showFameRules; };
  }, []);
  
  // Expose auth modal to navbar
  useEffect(() => {
    window.openAuthModal = (mode = 'login') => {
      setAuthModalMode(mode);
      setShowAuthModal(true);
    };
    return () => { delete window.openAuthModal; };
  }, []);
  
  // Fetch user
  useEffect(() => {
    const fetchUser = async () => {
      try {
        const res = await fetch('/me', { credentials: 'include' });
        if (res.ok) {
          const data = await res.json();
          setUser(data);
        }
      } catch (e) {
        // Not logged in
      }
    };
    fetchUser();
  }, []);
  
  const handleLogout = async () => {
    try {
      await fetch('/auth/logout', { method: 'POST', credentials: 'include' });
      setUser(null);
      window.location.reload();
    } catch (e) {
      console.error('Logout failed', e);
    }
  };
  
  const fetchData = useCallback(async () => {
    try {
      const res = await fetch('/api/hall-of-fame/stats', { credentials: 'include' });
      const json = await res.json();
      
      setData({
        weeklyLeaders: json.weekly_leaders || [],
        monthlyLeaders: json.monthly_leaders || [],
        biggestWins: json.biggest_wins || [],
        topProfit: json.top_players || [],
        highestLevel: json.top_by_level || [],
        stats: {
          totalUsers: json.platform_stats?.total_users || 0,
          totalGames: json.platform_stats?.total_games_played || 0
        }
      });
      setLoading(false);
    } catch (e) {
      console.error('[HoF] Fetch error:', e);
      setLoading(false);
    }
  }, []);
  
  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 60000);
    return () => clearInterval(interval);
  }, [fetchData]);
  
  return (
    <div className="hall-of-fame-app">
      {CoinRushNavbar && (
        <CoinRushNavbar 
          user={user} 
          activePage="fame" 
          isConnected={true}
          onLogout={handleLogout}
        />
      )}
      
      <RulesModal isOpen={showRules} onClose={() => setShowRules(false)} />
      
      {/* Auth Modal (uses shared component from auth-react.jsx with OAuth buttons) */}
      {window.AuthModal && (
        <window.AuthModal 
          isOpen={showAuthModal}
          initialMode={authModalMode}
          onClose={() => setShowAuthModal(false)}
          onSuccess={(userData) => {
            setUser(userData);
            setShowAuthModal(false);
          }}
        />
      )}
      
      <main className="main-content">
        <HeroSection stats={data.stats} />
        
        <section className="competitions-section">
          <div className="section-header">
            <div className="section-icon">{Icons.trophy}</div>
            <h2 className="section-title">Live Competitions</h2>
            <p className="section-subtitle">Race to the top and claim your rewards</p>
          </div>
          
          <div className="competitions-grid">
            <CompetitionCard type="weekly" leaders={data.weeklyLeaders} />
            <CompetitionCard type="monthly" leaders={data.monthlyLeaders} isHot={true} />
          </div>
        </section>
        
        <StatsSection 
          biggestWins={data.biggestWins}
          topProfit={data.topProfit}
          highestLevel={data.highestLevel}
        />
        
        <CTASection />
      </main>
    </div>
  );
}

// Render the app
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<HallOfFameApp />);
