/**
 * CoinRush Premium Jackpot - React Version
 * Hourly high-stakes jackpot with modern UI
 * VERSION: 8 - Compact participants panel, thinner history bar
 */

console.log('Premium Jackpot v8 loaded - Compact layout');

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

// ============================================
// CONFIG
// ============================================
const CONFIG = {
  minBet: 100,
  maxBet: 1000000,
  wsReconnectDelay: 3000,
  refreshInterval: 30000
};

// ============================================
// SVG ICONS
// ============================================
const Icons = {
  trophy: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M6 9V2h12v7a6 6 0 01-12 0z"/>
      <path d="M6 4H4a2 2 0 000 4h2M18 4h2a2 2 0 010 4h-2"/>
      <path d="M9 22h6M12 15v7"/>
    </svg>
  ),
  coin: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="12" cy="12" r="10"/>
      <path d="M12 6v12M8 10h8M8 14h8"/>
    </svg>
  ),
  users: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <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.87M16 3.13a4 4 0 010 7.75"/>
    </svg>
  ),
  clock: (
    <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>
  ),
  spinner: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M21 12a9 9 0 11-6.219-8.56"/>
    </svg>
  ),
  diamond: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M2.7 10.3l9.3 11.4 9.3-11.4L16.4 2H7.6L2.7 10.3z"/>
      <path d="M2.7 10.3h18.6M12 21.7L7.6 2m4.4 19.7L16.4 2"/>
    </svg>
  ),
  star: (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <polygon points="12,2 15,9 22,9 17,14 19,22 12,17 5,22 7,14 2,9 9,9"/>
    </svg>
  ),
  zap: (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>
    </svg>
  ),
  flame: (
    <svg viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 23c-4.4 0-8-3.6-8-8 0-3.5 2.3-6.5 5.5-7.5-.3 1.1-.5 2.3-.5 3.5 0 3.9 3.1 7 7 7 1.2 0 2.4-.3 3.5-.9C18.1 20.6 15.3 23 12 23zm0-20c-.8 0-1.5.1-2.2.3C11.2 4.5 12 6.2 12 8c0 2.8-2.2 5-5 5-.5 0-1-.1-1.4-.2C6.4 15.3 8 17 10 17c2.2 0 4-1.8 4-4 0-1.5-.8-2.8-2-3.5.8-.5 1.4-1.2 1.8-2 .1-.3.2-.7.2-1 0-1.7-1.3-3-3-3-.3 0-.7.1-1 .2-.3.1-.6.2-.8.3z"/>
    </svg>
  ),
  gift: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <rect x="3" y="8" width="18" height="4" rx="1"/>
      <rect x="5" y="12" width="14" height="10" rx="1"/>
      <line x1="12" y1="8" x2="12" y2="22"/>
      <path d="M12 8c-2-4-6-4-6 0s4 4 6 0"/>
      <path d="M12 8c2-4 6-4 6 0s-4 4-6 0"/>
    </svg>
  ),
  target: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="12" cy="12" r="10"/>
      <circle cx="12" cy="12" r="6"/>
      <circle cx="12" cy="12" r="2"/>
    </svg>
  ),
  swords: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M14.5 17.5L3 6V3h3l11.5 11.5"/>
      <path d="M13 19l6-6M16 16l4 4M19 21l2-2"/>
    </svg>
  ),
  slotMachine: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <rect x="3" y="3" width="18" height="18" rx="2"/>
      <line x1="9" y1="3" x2="9" y2="21"/>
      <line x1="15" y1="3" x2="15" y2="21"/>
      <line x1="3" y1="9" x2="21" y2="9"/>
      <line x1="3" y1="15" x2="21" y2="15"/>
    </svg>
  ),
  lock: (
    <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 0110 0v4"/>
    </svg>
  ),
  check: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <polyline points="20 6 9 17 4 12"/>
    </svg>
  ),
  close: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <line x1="18" y1="6" x2="6" y2="18"/>
      <line x1="6" y1="6" x2="18" y2="18"/>
    </svg>
  ),
  history: (
    <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>
  ),
  crown: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M2 4l3 12h14l3-12-6 7-4-7-4 7-6-7z"/>
      <path d="M3 20h18"/>
    </svg>
  ),
  plus: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
      <path d="M12 5v14M5 12h14"/>
    </svg>
  ),
  chevronDown: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <polyline points="6 9 12 15 18 9"/>
    </svg>
  ),
  send: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <line x1="22" y1="2" x2="11" y2="13"/>
      <polygon points="22 2 15 22 11 13 2 9 22 2"/>
    </svg>
  ),
  info: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <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>
  ),
  layers: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <polygon points="12 2 2 7 12 12 22 7 12 2"/>
      <polyline points="2 17 12 22 22 17"/>
      <polyline points="2 12 12 17 22 12"/>
    </svg>
  )
};

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

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

const getColor = (username) => {
  if (!username) return '#3b82f6';
  let hash = 0;
  for (let i = 0; i < username.length; i++) {
    hash = ((hash << 5) - hash) + username.charCodeAt(i);
  }
  const hue = Math.abs(hash % 360);
  const sat = 70 + (Math.abs(hash) % 30);
  const lit = 50 + (Math.abs(hash >> 8) % 20);
  return `hsl(${hue}, ${sat}%, ${lit}%)`;
};

// ============================================
// DAILY REWARDS HELPERS
// ============================================
const getRewardIcon = (type) => {
  const typeIcons = {
    'xp_boost': Icons.zap,
    'coinflip_discount': Icons.target,
    'barbarian_discount': Icons.swords,
    'jackpot_discount': Icons.slotMachine,
    'combo': Icons.star
  };
  return typeIcons[type] || Icons.gift;
};

const getRewardColor = (type) => {
  const colors = {
    'xp_boost': { primary: '#ffd700', secondary: '#ff9500', gradient: 'linear-gradient(135deg, #ffd700, #ff9500)' },
    'coinflip_discount': { primary: '#3b82f6', secondary: '#1d4ed8', gradient: 'linear-gradient(135deg, #3b82f6, #1d4ed8)' },
    'barbarian_discount': { primary: '#ef4444', secondary: '#dc2626', gradient: 'linear-gradient(135deg, #ef4444, #dc2626)' },
    'jackpot_discount': { primary: '#a855f7', secondary: '#7c3aed', gradient: 'linear-gradient(135deg, #a855f7, #7c3aed)' },
    'combo': { primary: '#4fffb0', secondary: '#2dd490', gradient: 'linear-gradient(135deg, #4fffb0, #2dd490)' }
  };
  return colors[type] || { primary: '#4fffb0', secondary: '#2dd490', gradient: 'linear-gradient(135deg, #4fffb0, #2dd490)' };
};

// ============================================
// BONUS DATA (No emojis - use icons)
// ============================================
const BONUS_DATA = {
  'rush_hour': { 
    title: 'Rush Hour',
    icon: 'zap',
    description: 'Winner gets DOUBLE prize + 1000 XP!',
    special: true
  },
  'diamond_rush': { 
    title: 'Diamond Rush',
    icon: 'diamond',
    description: 'Winner gets +500 XP & Neon Crown',
    special: false
  },
  'golden_hour': { 
    title: 'Golden Hour',
    icon: 'star',
    description: 'Winner gets +300 XP & Gold Badge',
    special: false
  },
  'lucky_streak': { 
    title: 'Lucky Streak',
    icon: 'target',
    description: 'Winner gets +400 XP & Lucky Charm',
    special: false
  },
  'mega_boost': { 
    title: 'Mega Boost',
    icon: 'zap',
    description: 'Winner gets +350 XP & Rocket Badge',
    special: false
  }
};

// ============================================
// BET PANEL COMPONENT
// ============================================
function BetPanel({ user, round, onDeposit, isLocked }) {
  const [amount, setAmount] = useState('100');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [isPlacing, setIsPlacing] = useState(false);

  const presets = [100, 250, 500, 1000, 2500];

  const handleQuickBet = (value) => {
    setAmount(String(value));
    setError('');
  };

  const handleMaxBet = () => {
    if (!user) return;
    const maxBet = Math.floor(user.balance / 100);
    setAmount(String(maxBet));
    setError('');
  };

  const handlePlaceBet = async () => {
    setError('');
    setSuccess('');

    if (!user) {
      window.openAuthModal?.('login');
      return;
    }

    const betAmount = parseFloat(amount);
    if (isNaN(betAmount) || betAmount <= 0) {
      setError('Please enter a valid amount');
      return;
    }

    if (betAmount < CONFIG.minBet) {
      setError(`Minimum bet is ${CONFIG.minBet} coins`);
      return;
    }

    const balanceCoins = user.balance / 100;
    if (betAmount > balanceCoins) {
      setError(`Insufficient balance. You have ${fmt(balanceCoins)} coins`);
      return;
    }

    if (isLocked) {
      setError('Betting is closed for this round');
      return;
    }

    setIsPlacing(true);
    try {
      await onDeposit(betAmount);
      setSuccess(`Successfully bet ${fmt(betAmount)} coins!`);
      setAmount('100');
      setTimeout(() => setSuccess(''), 5000);
    } catch (e) {
      setError(e.message || 'Failed to place bet');
    } finally {
      setIsPlacing(false);
    }
  };

  // Calculate user's current chance
  const userBets = round?.participants?.filter(p => p.username === user?.username) || [];
  const totalUserBet = userBets.reduce((sum, p) => sum + (p.amount || 0), 0);
  const totalPool = round?.total || 0;
  const userChance = totalPool > 0 ? (totalUserBet / totalPool * 100) : 0;

  return (
    <div className="bet-panel">
      <div className="bet-input-container">
        <input
          type="number"
          className="bet-input"
          value={amount}
          onChange={(e) => { setAmount(e.target.value); setError(''); }}
          placeholder="Enter amount..."
          min={CONFIG.minBet}
          disabled={isPlacing || isLocked}
        />
        <button className="bet-max-btn" onClick={handleMaxBet} disabled={!user}>
          MAX
        </button>
      </div>

      <div className="bet-presets">
        {presets.map(preset => (
          <button
            key={preset}
            className={`bet-preset ${amount === String(preset) ? 'active' : ''}`}
            onClick={() => handleQuickBet(preset)}
            disabled={isPlacing || isLocked}
          >
            {preset}
          </button>
        ))}
      </div>

      <button 
        className="bet-submit"
        onClick={handlePlaceBet}
        disabled={isPlacing || isLocked}
      >
        {isPlacing ? (
          <>{Icons.spinner} Placing...</>
        ) : isLocked ? (
          <>{Icons.lock} Closed</>
        ) : (
          <>{Icons.send} Place Bet</>
        )}
      </button>

      {error && <div className="bet-error">{error}</div>}
      {success && <div className="bet-success">{success}</div>}

      <div className="bet-footer">
        <span>Min: {CONFIG.minBet} coins</span>
        <span>Fee: 3.2%</span>
      </div>
    </div>
  );
}

// ============================================
// COUNTDOWN DISPLAY COMPONENT
// ============================================
function CountdownDisplay({ round, winner, onTimerEnd }) {
  const [timeLeft, setTimeLeft] = useState({ minutes: '--', seconds: '--', total: 0 });
  const [showWinner, setShowWinner] = useState(false);
  const timerEndedRef = useRef(false);
  
  useEffect(() => {
    // Reset timer ended flag when round changes
    timerEndedRef.current = false;
    
    const updateCountdown = () => {
      if (!round?.scheduled_at) {
        setTimeLeft({ minutes: '--', seconds: '--', total: 0 });
        return;
      }
      
      const now = Date.now();
      const scheduledAt = new Date(round.scheduled_at).getTime();
      let totalSeconds = Math.floor((scheduledAt - now) / 1000);
      
      // If timer just hit 0 and we haven't notified yet
      if (totalSeconds <= 0 && !timerEndedRef.current) {
        timerEndedRef.current = true;
        onTimerEnd?.();
      }
      
      // Cap at 59 minutes
      if (totalSeconds > 3540) totalSeconds = 3540;
      if (totalSeconds < 0) totalSeconds = 0;
      
      const minutes = Math.floor(totalSeconds / 60);
      const seconds = totalSeconds % 60;
      
      setTimeLeft({
        minutes: String(minutes).padStart(2, '0'),
        seconds: String(seconds).padStart(2, '0'),
        total: totalSeconds
      });
    };
    
    updateCountdown();
    const interval = setInterval(updateCountdown, 1000);
    return () => clearInterval(interval);
  }, [round?.scheduled_at, round?.id, onTimerEnd]);
  
  // Show winner when there is one
  useEffect(() => {
    if (winner) {
      setShowWinner(true);
    } else {
      setShowWinner(false);
    }
  }, [winner]);
  
  const isUrgent = timeLeft.minutes === '00' && parseInt(timeLeft.seconds) <= 10;
  const isWarning = timeLeft.minutes === '00';
  // Only show drawing if timer is 0 AND we don't have a winner yet
  const isDrawing = timeLeft.total === 0 && !winner && !showWinner;
  
  // WINNER MODE - Show for resolved rounds (HIGHEST PRIORITY)
  // This takes priority over everything else when winner exists
  if (winner) {
    return (
      <div className="countdown-display winner-mode">
        <div className="winner-glow"></div>
        <div className="winner-content">
          <div className="winner-crown-icon">{Icons.crown}</div>
          <div className="winner-label">WINNER</div>
          <div className="winner-name-large">{winner.name}</div>
          <div className="winner-prize-display">
            <span className="prize-won-label">WON</span>
            <span className="prize-won-amount">{fmtCents(winner.prize)}</span>
            <span className="prize-won-coins">coins</span>
          </div>
          <div className="winner-next-round">
            Next round starting soon...
          </div>
        </div>
        <div className="winner-confetti">
          {[...Array(30)].map((_, i) => (
            <div 
              key={i} 
              className="confetti-piece"
              style={{
                left: `${Math.random() * 100}%`,
                animationDelay: `${Math.random() * 2}s`,
                backgroundColor: ['#ffd700', '#ff6b6b', '#4fffb0', '#a855f7', '#3b82f6'][Math.floor(Math.random() * 5)]
              }}
            />
          ))}
        </div>
      </div>
    );
  }
  
  // DRAWING MODE
  if (isDrawing) {
    return (
      <div className="countdown-display drawing-mode">
        <div className="drawing-spinner"></div>
        <div className="drawing-text">Drawing Winner...</div>
      </div>
    );
  }
  
  // NORMAL COUNTDOWN MODE
  return (
    <div className={`countdown-display ${isUrgent ? 'urgent' : ''} ${isWarning ? 'warning' : ''}`}>
      <div className="countdown-header">
        <span className="countdown-label">Next Draw In</span>
        {round?.bonus_id && BONUS_DATA[round.bonus_id] && (
          <div className={`countdown-bonus ${BONUS_DATA[round.bonus_id]?.special ? 'special' : ''}`}>
            {BONUS_DATA[round.bonus_id]?.title || 'Bonus Active'}
          </div>
        )}
      </div>
      <div className="countdown-timer">
        <div className="countdown-block">
          <span className="countdown-value">{timeLeft.minutes}</span>
          <span className="countdown-unit">min</span>
        </div>
        <span className="countdown-separator">:</span>
        <div className="countdown-block">
          <span className="countdown-value">{timeLeft.seconds}</span>
          <span className="countdown-unit">sec</span>
        </div>
      </div>
      <div className="countdown-status">
        {isUrgent ? 'Drawing very soon!' : 
         isWarning ? 'Drawing soon!' : 
         (round?.status === 'open' || round?.status === 'scheduled' || round?.status === 'countdown') ? 'Open for betting' : 'Preparing...'}
      </div>
    </div>
  );
}

// ============================================
// JACKPOT HERO DISPLAY (Combined Prize + Timer)
// Prize is the HERO, Timer builds tension
// ============================================
function JackpotHeroDisplay({ round, winner, onTimerEnd, onWinnerDismiss }) {
  const [timeLeft, setTimeLeft] = useState({ minutes: '--', seconds: '--', total: 0 });
  const timerEndedRef = useRef(false);
  
  // Auto-dismiss winner after 15 seconds
  useEffect(() => {
    if (winner && onWinnerDismiss) {
      const timer = setTimeout(onWinnerDismiss, 15000);
      return () => clearTimeout(timer);
    }
  }, [winner, onWinnerDismiss]);
  
  useEffect(() => {
    timerEndedRef.current = false;
    
    const updateCountdown = () => {
      if (!round?.scheduled_at) {
        setTimeLeft({ minutes: '--', seconds: '--', total: 0 });
        return;
      }
      
      const now = Date.now();
      const scheduledAt = new Date(round.scheduled_at).getTime();
      let totalSeconds = Math.floor((scheduledAt - now) / 1000);
      
      if (totalSeconds <= 0 && !timerEndedRef.current) {
        timerEndedRef.current = true;
        onTimerEnd?.();
      }
      
      if (totalSeconds > 3540) totalSeconds = 3540;
      if (totalSeconds < 0) totalSeconds = 0;
      
      const minutes = Math.floor(totalSeconds / 60);
      const seconds = totalSeconds % 60;
      
      setTimeLeft({
        minutes: String(minutes).padStart(2, '0'),
        seconds: String(seconds).padStart(2, '0'),
        total: totalSeconds
      });
    };
    
    updateCountdown();
    const interval = setInterval(updateCountdown, 1000);
    return () => clearInterval(interval);
  }, [round?.scheduled_at, round?.id, onTimerEnd]);
  
  const total = round?.total || 0;
  const participantCount = round?.participants?.length || 0;
  const uniquePlayers = new Set(round?.participants?.map(p => p.username) || []).size;
  
  const isUrgent = timeLeft.minutes === '00' && parseInt(timeLeft.seconds) <= 10;
  const isWarning = timeLeft.minutes === '00';
  const isDrawing = timeLeft.total === 0 && !winner;
  
  // Pre-compute confetti positions (memoized to avoid re-renders)
  const confettiPieces = React.useMemo(() => {
    const colors = ['#ffd700', '#ff6b6b', '#4fffb0', '#a855f7', '#3b82f6'];
    return [...Array(20)].map((_, i) => ({
      left: `${(i * 5) + Math.random() * 5}%`,
      delay: `${(i * 0.15)}s`,
      color: colors[i % 5]
    }));
  }, []);
  
  // WINNER MODE - Show the winner's name prominently!
  if (winner) {
    console.log('🏆 JackpotHeroDisplay WINNER MODE:', winner);
    return (
      <div className="jackpot-display winner-mode">
        <div className="jackpot-glow"></div>
        <div className="jackpot-winner-content">
          <div className="jackpot-crown">{Icons.crown}</div>
          <div className="jackpot-winner-label">WINNER</div>
          <div className="jackpot-winner-name">{winner.name || 'Lucky Player'}</div>
          <div className="jackpot-winner-prize">
            <span className="jackpot-prize-amount">{fmtCents(winner.prize)}</span>
            <span className="jackpot-prize-coins">coins won!</span>
          </div>
          <div className="jackpot-winner-actions">
            <button 
              className="jackpot-continue-btn"
              onClick={onWinnerDismiss}
            >
              Continue to Next Round
            </button>
          </div>
        </div>
        <div className="jackpot-confetti">
          {confettiPieces.map((piece, i) => (
            <div 
              key={i} 
              className="confetti-piece"
              style={{
                left: piece.left,
                animationDelay: piece.delay,
                backgroundColor: piece.color
              }}
            />
          ))}
        </div>
      </div>
    );
  }
  
  // DRAWING MODE
  if (isDrawing) {
    return (
      <div className="jackpot-display drawing-mode">
        <div className="drawing-spinner"></div>
        <div className="drawing-text">Drawing Winner...</div>
        <div className="jackpot-prize-hero">
          <span className="jackpot-prize-amount">{fmtCents(total)}</span>
        </div>
      </div>
    );
  }
  
  // NORMAL MODE - Prize is the HERO
  return (
    <div className={`jackpot-display ${isUrgent ? 'urgent' : ''} ${isWarning ? 'warning' : ''}`}>
      {/* Bonus Badge */}
      {round?.bonus_id && BONUS_DATA[round.bonus_id] && (
        <div className={`jackpot-bonus ${BONUS_DATA[round.bonus_id]?.special ? 'special' : ''}`}>
          {BONUS_DATA[round.bonus_id]?.title || 'Bonus Active'}
        </div>
      )}
      
      {/* Main Prize - THE HERO */}
      <div className="jackpot-prize-section">
        <div className="jackpot-trophy">{Icons.trophy}</div>
        <div className="jackpot-prize-hero">
          <span className="jackpot-prize-amount">{fmtCents(total)}</span>
          <span className="jackpot-prize-label">PRIZE POOL</span>
        </div>
      </div>
      
      {/* Timer - Secondary but tension-building */}
      <div className="jackpot-timer-section">
        <div className="jackpot-timer">
          <span className="jackpot-timer-value">{timeLeft.minutes}</span>
          <span className="jackpot-timer-sep">:</span>
          <span className="jackpot-timer-value">{timeLeft.seconds}</span>
        </div>
        <div className="jackpot-timer-label">
          {isUrgent ? 'DRAWING NOW!' : isWarning ? 'FINAL MINUTE!' : 'until draw'}
        </div>
      </div>
      
      {/* Stats Row */}
      <div className="jackpot-stats">
        <div className="jackpot-stat">
          <span className="jackpot-stat-icon">{Icons.users}</span>
          <span className="jackpot-stat-value">{uniquePlayers}</span>
          <span className="jackpot-stat-label">Players</span>
        </div>
        <div className="jackpot-stat">
          <span className="jackpot-stat-icon">{Icons.layers}</span>
          <span className="jackpot-stat-value">{participantCount}</span>
          <span className="jackpot-stat-label">Entries</span>
        </div>
      </div>
      
      {/* Status */}
      <div className="jackpot-status">
        {isUrgent ? 'Last chance to bet!' : 
         isWarning ? 'Drawing soon!' : 
         'Open for betting'}
      </div>
    </div>
  );
}

// ============================================
// PRIZE POOL DISPLAY (legacy, keeping for compatibility)
// ============================================
function PrizePoolDisplay({ round }) {
  const total = round?.total || 0;
  const participantCount = round?.participants?.length || 0;
  
  // Calculate unique players
  const uniquePlayers = new Set(round?.participants?.map(p => p.username) || []).size;
  
  return (
    <div className="prize-pool-display">
      <div className="prize-pool-main">
        <div className="prize-pool-icon">{Icons.trophy}</div>
        <div className="prize-pool-value">{fmtCents(total)}</div>
        <div className="prize-pool-label">Total Prize Pool</div>
      </div>
      <div className="prize-pool-stats">
        <div className="pool-stat">
          <span className="pool-stat-icon">{Icons.users}</span>
          <span className="pool-stat-value">{uniquePlayers}</span>
          <span className="pool-stat-label">Players</span>
        </div>
        <div className="pool-stat">
          <span className="pool-stat-icon">{Icons.layers}</span>
          <span className="pool-stat-value">{participantCount}</span>
          <span className="pool-stat-label">Entries</span>
        </div>
      </div>
    </div>
  );
}

// ============================================
// SLIDING HISTORY BAR (Top)
// ============================================
function SlidingHistoryBar({ history }) {
  if (!history || history.length === 0) return null;
  
  // Duplicate for seamless loop
  const items = [...history, ...history];
  
  return (
    <div className="premium-history-bar">
      <div className="history-bar-inner">
        {items.map((round, index) => {
          const color = getColor(round.winner);
          const date = new Date(round.scheduled_at);
          const timeStr = date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
          
          return (
            <div key={`${round.id}-${index}`} className="history-bar-item">
              <div className="history-bar-avatar" style={{ background: color }}>
                {round.winner?.charAt(0).toUpperCase() || '?'}
              </div>
              <div className="history-bar-info">
                <span className="history-bar-name">{round.winner || 'Unknown'}</span>
                <span className="history-bar-prize">{fmtCents(round.winner_prize)} coins</span>
              </div>
              <span className="history-bar-time">{timeStr}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ============================================
// COMPACT PARTICIPANTS PANEL (Left Sidebar)
// ============================================
function CompactParticipantsPanel({ participants, currentUser }) {
  // Aggregate by username
  const aggregated = new Map();
  (participants || []).forEach(p => {
    if (aggregated.has(p.username)) {
      const existing = aggregated.get(p.username);
      existing.amount += p.amount;
      existing.share_pct += p.share_pct;
    } else {
      aggregated.set(p.username, { ...p });
    }
  });
  
  const sorted = Array.from(aggregated.values())
    .sort((a, b) => b.share_pct - a.share_pct);
  
  return (
    <div className="participants-panel-compact">
      <div className="panel-header">
        <span className="panel-icon">{Icons.users}</span>
        <span className="panel-title">Participants</span>
        <span className="panel-count">{sorted.length}</span>
      </div>
      
      {sorted.length === 0 ? (
        <div className="participants-compact-empty">
          <p>No bets yet</p>
          <span>Be the first to join!</span>
        </div>
      ) : (
        <div className="participants-compact-list">
          {sorted.map((p) => {
            const isYou = currentUser?.username === p.username;
            const color = getColor(p.username);
            
            return (
              <div key={p.username} className={`participant-compact ${isYou ? 'is-you' : ''}`}>
                <div className="participant-compact-avatar" style={{ background: color }}>
                  {p.username.charAt(0).toUpperCase()}
                </div>
                <div className="participant-compact-info">
                  <div className="participant-compact-name">
                    {p.username}
                    {isYou && <span className="you-badge">You</span>}
                  </div>
                  <div className="participant-compact-bet">{p.amount.toFixed(2)} coins</div>
                </div>
                <span className="participant-compact-pct">{p.share_pct.toFixed(1)}%</span>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ============================================
// BOTTOM PARTICIPANTS BAR (keeping for compatibility)
// ============================================
function BottomParticipantsBar({ participants, currentUser }) {
  // Aggregate by username
  const aggregated = new Map();
  (participants || []).forEach(p => {
    if (aggregated.has(p.username)) {
      const existing = aggregated.get(p.username);
      existing.amount += p.amount;
      existing.share_pct += p.share_pct;
    } else {
      aggregated.set(p.username, { ...p });
    }
  });
  
  const sorted = Array.from(aggregated.values())
    .sort((a, b) => b.share_pct - a.share_pct);
  
  return (
    <div className="premium-bottom-bar">
      <div className="bottom-bar-header">
        <div className="bottom-bar-title">
          {Icons.users}
          <span>Active Participants</span>
        </div>
        <span className="bottom-bar-count">{sorted.length} players</span>
      </div>
      
      {sorted.length === 0 ? (
        <div className="bottom-bar-empty">
          No participants yet - be the first to join!
        </div>
      ) : (
        <div className="bottom-bar-participants">
          {sorted.map((p) => {
            const isYou = currentUser?.username === p.username;
            const color = getColor(p.username);
            
            return (
              <div key={p.username} className={`bottom-participant ${isYou ? 'is-you' : ''}`}>
                <div className="bottom-participant-avatar" style={{ background: color }}>
                  {p.username.charAt(0).toUpperCase()}
                </div>
                <div className="bottom-participant-info">
                  <div className="bottom-participant-name">
                    {p.username}
                    {isYou && <span className="you-badge">You</span>}
                  </div>
                  <div className="bottom-participant-bet">{p.amount.toFixed(2)} coins</div>
                </div>
                <div className="bottom-participant-chance">
                  <span className="bottom-participant-pct">{p.share_pct.toFixed(1)}%</span>
                  <div className="bottom-participant-bar">
                    <div 
                      className="bottom-participant-fill" 
                      style={{ width: `${Math.min(100, p.share_pct)}%`, background: color }} 
                    />
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ============================================
// PARTICIPANTS LIST COMPONENT (keeping for compatibility)
// ============================================
function ParticipantsList({ participants, currentUser }) {
  if (!participants || participants.length === 0) {
    return (
      <div className="participants-panel">
        <div className="panel-header">
          <span className="panel-icon">{Icons.users}</span>
          <span className="panel-title">Participants</span>
          <span className="panel-count">0</span>
        </div>
        <div className="participants-empty">
          <div className="empty-icon">{Icons.users}</div>
          <p>No bets yet</p>
          <span>Be the first to join!</span>
        </div>
      </div>
    );
  }
  
  // Aggregate by username
  const aggregated = new Map();
  participants.forEach(p => {
    if (aggregated.has(p.username)) {
      const existing = aggregated.get(p.username);
      existing.amount += p.amount;
      existing.share_pct += p.share_pct;
    } else {
      aggregated.set(p.username, { ...p });
    }
  });
  
  const sorted = Array.from(aggregated.values())
    .sort((a, b) => b.share_pct - a.share_pct);
  
  return (
    <div className="participants-panel">
      <div className="panel-header">
        <span className="panel-icon">{Icons.users}</span>
        <span className="panel-title">Participants</span>
        <span className="panel-count">{sorted.length}</span>
      </div>
      <div className="participants-list">
        {sorted.map((p, index) => {
          const isYou = currentUser?.username === p.username;
          const color = getColor(p.username);
          
          return (
            <div key={p.username} className={`participant-item ${isYou ? 'is-you' : ''}`}>
              <div className="participant-rank">#{index + 1}</div>
              <div className="participant-avatar" style={{ background: color }}>
                {p.username.charAt(0).toUpperCase()}
              </div>
              <div className="participant-info">
                <div className="participant-name">
                  {p.username}
                  {isYou && <span className="you-badge">You</span>}
                </div>
                <div className="participant-amount">{p.amount.toFixed(2)} coins</div>
              </div>
              <div className="participant-chance">
                <span className="chance-value">{p.share_pct.toFixed(1)}%</span>
                <div className="chance-bar">
                  <div className="chance-fill" style={{ width: `${Math.min(100, p.share_pct)}%`, background: color }} />
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ============================================
// HISTORY PANEL COMPONENT
// ============================================
function HistoryPanel({ history }) {
  if (!history || history.length === 0) {
    return (
      <div className="history-panel">
        <div className="panel-header">
          <span className="panel-icon">{Icons.history}</span>
          <span className="panel-title">Recent Winners</span>
        </div>
        <div className="history-empty">
          <p>No recent draws</p>
        </div>
      </div>
    );
  }
  
  const sorted = [...history].sort((a, b) => 
    new Date(b.scheduled_at).getTime() - new Date(a.scheduled_at).getTime()
  );
  
  return (
    <div className="history-panel">
      <div className="panel-header">
        <span className="panel-icon">{Icons.history}</span>
        <span className="panel-title">Recent Winners</span>
      </div>
      <div className="history-list">
        {sorted.slice(0, 10).map((round, index) => {
          const date = new Date(round.scheduled_at);
          const timeStr = date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
          const dateStr = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
          const color = getColor(round.winner);
          
          return (
            <div key={round.id} className="history-item">
              <div className="history-avatar" style={{ background: color }}>
                {round.winner?.charAt(0).toUpperCase() || '?'}
              </div>
              <div className="history-info">
                <div className="history-winner">{round.winner || 'Unknown'}</div>
                <div className="history-time">{dateStr} at {timeStr}</div>
              </div>
              <div className="history-prize">
                <span className="prize-amount">{fmtCents(round.winner_prize)}</span>
                <span className="prize-label">coins</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ============================================
// RULES MODAL
// ============================================
function RulesModal({ isOpen, onClose }) {
  const [activeTab, setActiveTab] = useState('basics');
  
  if (!isOpen) return null;
  
  const tabs = [
    { id: 'basics', label: 'Basics', icon: Icons.info },
    { id: 'how', label: 'How to Play', icon: Icons.target },
    { id: 'prizes', label: 'Prizes', icon: Icons.trophy },
    { id: 'bonuses', label: 'Bonuses', icon: Icons.star }
  ];
  
  return (
    <div className="rules-overlay" onClick={onClose}>
      <div className="rules-modal" onClick={e => e.stopPropagation()}>
        <button className="rules-close" onClick={onClose}>{Icons.close}</button>
        
        <div className="rules-header">
          <div className="rules-icon">{Icons.diamond}</div>
          <h2>Premium Jackpot Rules</h2>
          <p>Hourly high-stakes draws</p>
        </div>
        
        <div className="rules-tabs">
          {tabs.map(tab => (
            <button 
              key={tab.id}
              className={`rules-tab ${activeTab === tab.id ? 'active' : ''}`}
              onClick={() => setActiveTab(tab.id)}
            >
              {tab.icon}
              <span>{tab.label}</span>
            </button>
          ))}
        </div>
        
        <div className="rules-content">
          {activeTab === 'basics' && (
            <div className="rules-section">
              <h3>What is Premium Jackpot?</h3>
              <p>Premium Jackpot is an hourly high-stakes lottery where players compete for a shared prize pool. Every hour on the hour, a winner is randomly selected based on their contribution to the pool.</p>
              <ul>
                <li>Draws happen every hour at :00</li>
                <li>Minimum bet: 100 coins</li>
                <li>Higher bets = higher chance to win</li>
                <li>House fee: 3.2%</li>
              </ul>
            </div>
          )}
          
          {activeTab === 'how' && (
            <div className="rules-section">
              <h3>How to Play</h3>
              <ol>
                <li><strong>Place Your Bet</strong> - Enter the amount you want to bet (minimum 100 coins)</li>
                <li><strong>Wait for the Draw</strong> - Watch the countdown timer</li>
                <li><strong>Winner Selection</strong> - A random winner is picked at :00</li>
                <li><strong>Collect Winnings</strong> - If you win, the prize is automatically credited</li>
              </ol>
              <p>Your winning chance = Your Bet ÷ Total Pool × 100%</p>
            </div>
          )}
          
          {activeTab === 'prizes' && (
            <div className="rules-section">
              <h3>Prize Distribution</h3>
              <ul>
                <li>Winner receives the entire prize pool minus 3.2% house fee</li>
                <li>XP rewards based on participation and wins</li>
                <li>Special bonuses during Rush Hour events</li>
              </ul>
            </div>
          )}
          
          {activeTab === 'bonuses' && (
            <div className="rules-section">
              <h3>Hourly Bonuses</h3>
              <p>Each hour features a random bonus that enhances the winner's reward:</p>
              <ul>
                <li><strong>Rush Hour</strong> - DOUBLE prize + 1000 XP (rare!)</li>
                <li><strong>Diamond Rush</strong> - +500 XP & Neon Crown</li>
                <li><strong>Golden Hour</strong> - +300 XP & Gold Badge</li>
                <li><strong>Lucky Streak</strong> - +400 XP & Lucky Charm</li>
                <li><strong>Mega Boost</strong> - +350 XP & Rocket Badge</li>
              </ul>
            </div>
          )}
        </div>
        
        <div className="rules-footer">
          <button className="rules-close-btn" onClick={onClose}>
            Got it!
          </button>
        </div>
      </div>
    </div>
  );
}

// ============================================
// DAILY REWARD MODAL
// ============================================
function DailyRewardModal({ isOpen, onClose, user, onClaim }) {
  const [status, setStatus] = useState(null);
  const [loading, setLoading] = useState(true);
  const [claiming, setClaiming] = useState(false);
  const [claimResult, setClaimResult] = useState(null);
  const [showConfetti, setShowConfetti] = useState(false);
  
  useEffect(() => {
    if (isOpen && user) {
      setLoading(true);
      setClaimResult(null);
      fetch('/api/daily-reward/status', { credentials: 'include' })
        .then(res => res.ok ? res.json() : null)
        .then(data => {
          setStatus(data);
          setLoading(false);
        })
        .catch(() => setLoading(false));
    }
  }, [isOpen, user]);
  
  const handleClaim = async () => {
    if (claiming || !status || status.daily_reward_claimed) return;
    
    setClaiming(true);
    try {
      const res = await fetch('/api/daily-reward/claim', {
        method: 'POST',
        credentials: 'include'
      });
      const data = await res.json();
      
      if (res.ok) {
        setClaimResult(data);
        setShowConfetti(true);
        setStatus(prev => ({ ...prev, daily_reward_claimed: true }));
        onClaim?.(data);
        setTimeout(() => setShowConfetti(false), 3000);
      } else {
        setClaimResult({ error: data.detail || 'Failed to claim reward' });
      }
    } catch (e) {
      setClaimResult({ error: 'Network error' });
    }
    setClaiming(false);
  };
  
  if (!isOpen) return null;
  
  const streak = status?.login_streak || 1;
  const reward = status?.today_reward || {};
  const claimed = status?.daily_reward_claimed || false;
  const rewardColor = getRewardColor(reward.type);
  
  const allRewards = status?.all_rewards || {};
  const visibleDays = [];
  const startDay = Math.max(1, streak - 3);
  const endDay = Math.min(30, startDay + 6);
  for (let i = startDay; i <= endDay; i++) {
    visibleDays.push({
      day: i,
      reward: allRewards[i] || {},
      isCurrent: i === streak,
      isPast: i < streak,
      isFuture: i > streak
    });
  }
  
  const hasActiveBonuses = status?.active_bonuses && (
    status.active_bonuses.xp_boost > 0 ||
    status.active_bonuses.coinflip_discounts > 0 ||
    status.active_bonuses.barbarian_discounts > 0 ||
    status.active_bonuses.jackpot_discounts > 0
  );
  
  return (
    <div className="daily-modal-overlay" onClick={onClose}>
      <div className="daily-modal-v2" onClick={(e) => e.stopPropagation()}>
        {showConfetti && (
          <div className="daily-confetti">
            {[...Array(60)].map((_, i) => (
              <div 
                key={i} 
                className="confetti-piece"
                style={{
                  left: `${Math.random() * 100}%`,
                  animationDelay: `${Math.random() * 0.5}s`,
                  animationDuration: `${2 + Math.random() * 2}s`,
                  backgroundColor: ['#4fff9f', '#ffd700', '#ff6b6b', '#3b82f6', '#a855f7'][Math.floor(Math.random() * 5)]
                }}
              />
            ))}
          </div>
        )}
        
        <div className="daily-modal-bg">
          <div className="daily-bg-orb orb-1"></div>
          <div className="daily-bg-orb orb-2"></div>
        </div>
        
        <button className="daily-close-btn" onClick={onClose}>{Icons.close}</button>
        
        <div className="daily-modal-content">
          {loading ? (
            <div className="daily-loading">
              <div className="daily-spinner">{Icons.spinner}</div>
              <span>Loading rewards...</span>
            </div>
          ) : !user ? (
            <div className="daily-login-prompt">
              <div className="login-prompt-icon">{Icons.lock}</div>
              <h3>Login Required</h3>
              <p>Please login to claim your daily rewards!</p>
              <button 
                className="daily-login-btn"
                onClick={() => { onClose(); window.openAuthModal?.('login'); }}
              >
                Log In
              </button>
            </div>
          ) : (
            <>
              <div className="daily-hero">
                <div className="daily-hero-icon" style={{ background: rewardColor.gradient }}>
                  {getRewardIcon(reward.type)}
                </div>
                <div className="daily-hero-streak">
                  <div className="streak-flame-icon">{Icons.flame}</div>
                  <span className="streak-count">{streak}</span>
                  <span className="streak-text">Day Streak</span>
                </div>
                <h2 className="daily-hero-title">
                  {claimed ? 'Reward Claimed!' : 'Daily Reward'}
                </h2>
                <p className="daily-hero-subtitle">
                  {claimed 
                    ? 'Come back tomorrow to continue your streak!'
                    : 'Claim your reward and keep your streak alive!'
                  }
                </p>
              </div>
              
              <div className={`daily-reward-box ${claimed ? 'claimed' : ''}`} style={{ '--reward-color': rewardColor.primary }}>
                <div className="reward-box-badge">Day {streak}</div>
                <div className="reward-box-icon" style={{ background: rewardColor.gradient }}>
                  {getRewardIcon(reward.type)}
                </div>
                <div className="reward-box-info">
                  <h3 className="reward-box-name">{reward.name || 'Daily Reward'}</h3>
                  <p className="reward-box-desc">{reward.description || 'Claim your daily reward!'}</p>
                </div>
                {claimed && <div className="reward-box-check">{Icons.check}</div>}
              </div>
              
              <div className="daily-timeline">
                <div className="timeline-label">Reward Calendar</div>
                <div className="timeline-track">
                  {visibleDays.map(({ day, reward: dayReward, isCurrent, isPast, isFuture }) => {
                    const dayColor = getRewardColor(dayReward.type);
                    return (
                      <div 
                        key={day}
                        className={`timeline-day ${isCurrent ? 'current' : ''} ${isPast ? 'past' : ''} ${isFuture ? 'future' : ''}`}
                      >
                        <div className="timeline-day-num">Day {day}</div>
                        <div 
                          className="timeline-day-icon" 
                          style={{ 
                            background: isCurrent ? dayColor.gradient : 'rgba(255,255,255,0.05)',
                            color: isCurrent ? '#000' : dayColor.primary
                          }}
                        >
                          {getRewardIcon(dayReward.type)}
                        </div>
                        {isPast && <div className="timeline-check">{Icons.check}</div>}
                      </div>
                    );
                  })}
                </div>
              </div>
              
              {hasActiveBonuses && (
                <div className="daily-bonuses-section">
                  <div className="bonuses-section-label">Active Power-Ups</div>
                  <div className="bonuses-row">
                    {status.active_bonuses.xp_boost > 0 && (
                      <div className="power-up-chip xp">
                        {Icons.zap}
                        <span>+{status.active_bonuses.xp_boost}% XP</span>
                      </div>
                    )}
                    {status.active_bonuses.coinflip_discounts > 0 && (
                      <div className="power-up-chip cf">
                        {Icons.target}
                        <span>{status.active_bonuses.coinflip_discounts}x Flip</span>
                      </div>
                    )}
                    {status.active_bonuses.barbarian_discounts > 0 && (
                      <div className="power-up-chip bd">
                        {Icons.swords}
                        <span>{status.active_bonuses.barbarian_discounts}x Duel</span>
                      </div>
                    )}
                    {status.active_bonuses.jackpot_discounts > 0 && (
                      <div className="power-up-chip jp">
                        {Icons.slotMachine}
                        <span>{status.active_bonuses.jackpot_discounts}x Jackpot</span>
                      </div>
                    )}
                  </div>
                </div>
              )}
              
              <div className="daily-action">
                {claimed ? (
                  <div className="daily-claimed-notice">
                    {Icons.clock}
                    <span>Next reward in <strong>Tomorrow</strong></span>
                  </div>
                ) : (
                  <button 
                    className={`daily-claim-button ${claiming ? 'loading' : ''}`}
                    onClick={handleClaim}
                    disabled={claiming}
                    style={{ '--btn-gradient': rewardColor.gradient }}
                  >
                    {claiming ? (
                      <>
                        <span className="btn-spinner">{Icons.spinner}</span>
                        Claiming...
                      </>
                    ) : (
                      <>
                        {Icons.gift}
                        Claim Reward
                      </>
                    )}
                  </button>
                )}
                
                {claimResult?.error && (
                  <div className="daily-error">{claimResult.error}</div>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ============================================
// WINNER CELEBRATION OVERLAY
// ============================================
function WinnerCelebration({ winner, onClose }) {
  if (!winner) return null;
  
  useEffect(() => {
    const timer = setTimeout(onClose, 10000);
    return () => clearTimeout(timer);
  }, [onClose]);
  
  return (
    <div className="celebration-overlay" onClick={onClose}>
      <div className="celebration-modal" onClick={e => e.stopPropagation()}>
        <div className="celebration-confetti">
          {[...Array(50)].map((_, i) => (
            <div 
              key={i} 
              className="confetti-piece"
              style={{
                left: `${Math.random() * 100}%`,
                animationDelay: `${Math.random() * 0.5}s`,
                animationDuration: `${2 + Math.random() * 2}s`,
                backgroundColor: ['#ffd700', '#ff6b6b', '#4fffb0', '#3b82f6', '#a855f7'][Math.floor(Math.random() * 5)]
              }}
            />
          ))}
        </div>
        <div className="celebration-crown">{Icons.crown}</div>
        <div className="celebration-title">WINNER!</div>
        <div className="celebration-name">{winner.name}</div>
        <div className="celebration-prize">
          <span className="prize-value">{fmtCents(winner.prize)}</span>
          <span className="prize-label">coins</span>
        </div>
        <button className="celebration-close" onClick={onClose}>Continue</button>
      </div>
    </div>
  );
}

// ============================================
// MAIN APP COMPONENT
// ============================================
function PremiumJackpotApp() {
  const [user, setUser] = useState(null);
  const [round, setRound] = useState(null);
  const [history, setHistory] = useState([]);
  const [isConnected, setIsConnected] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [showRules, setShowRules] = useState(false);
  const [showDailyModal, setShowDailyModal] = useState(false);
  const [winner, setWinner] = useState(null);
  const [showAuthModal, setShowAuthModal] = useState(false);
  const [authMode, setAuthMode] = useState('login');
  
  const wsRef = useRef(null);
  const winnerRef = useRef(null);
  const userRef = useRef(null);
  
  // Keep refs in sync
  useEffect(() => {
    winnerRef.current = winner;
  }, [winner]);
  
  useEffect(() => {
    userRef.current = user;
  }, [user]);
  
  // Expose functions to window for navbar
  useEffect(() => {
    window.showPremiumRules = () => setShowRules(true);
    window.dailyRewardsModal = {
      open: () => setShowDailyModal(true),
      close: () => setShowDailyModal(false)
    };
    window.openAuthModal = (mode = 'login') => {
      setAuthMode(mode);
      setShowAuthModal(true);
    };
    return () => {
      delete window.showPremiumRules;
      delete window.dailyRewardsModal;
      delete window.openAuthModal;
    };
  }, []);
  
  // Fetch user on mount
  useEffect(() => {
    const fetchUser = async () => {
      try {
        const res = await fetch('/me', { credentials: 'include' });
        if (res.ok) {
          const data = await res.json();
          setUser(data);
        }
      } catch (e) {
        console.error('Failed to fetch user:', e);
      }
    };
    fetchUser();
  }, []);
  
  // Fetch round data
  const fetchRound = useCallback(async () => {
    try {
      const res = await fetch('/premium-jackpot/current', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setRound(data);
      }
    } catch (e) {
      console.error('Failed to fetch round:', e);
    } finally {
      setIsLoading(false);
    }
  }, []);
  
  useEffect(() => {
    fetchRound();
    const interval = setInterval(fetchRound, CONFIG.refreshInterval);
    return () => clearInterval(interval);
  }, [fetchRound]);
  
  // Fetch history
  useEffect(() => {
    const fetchHistory = async () => {
      try {
        const res = await fetch('/premium-jackpot/history', { credentials: 'include' });
        if (res.ok) {
          const data = await res.json();
          setHistory(data);
        }
      } catch (e) {
        console.error('Failed to fetch history:', e);
      }
    };
    fetchHistory();
  }, []);
  
  // WebSocket connection
  useEffect(() => {
    const connect = () => {
      const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
      const ws = new WebSocket(`${protocol}://${window.location.host}/ws/lobby`);
      
      ws.onopen = () => {
        console.log('🔗 Premium Jackpot WS connected');
        setIsConnected(true);
      };
      
      ws.onerror = (error) => {
        console.error('❌ Premium Jackpot WS error:', error);
      };
      
      ws.onclose = () => {
        console.log('🔌 Premium Jackpot WS disconnected');
        setIsConnected(false);
        setTimeout(connect, CONFIG.wsReconnectDelay);
      };
      
      ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          handleWSMessage(data);
        } catch (e) {
          console.error('WS message error:', e);
        }
      };
      
      wsRef.current = ws;
    };
    
    connect();
    
    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
    };
  }, []);
  
  const handleWSMessage = (data) => {
    console.log('📥 Premium Jackpot WS:', data.type, data);
    
    switch (data.type) {
      case 'premium_jp_deposit':
        // Someone deposited - refresh round data
        fetchRound();
        break;
        
      case 'premium_jp_winner':
        // Winner announced! Set winner state
        console.log('[PJ] Winner announced:', data.winner, 'Prize:', data.prize);
        setWinner({ name: data.winner, prize: data.prize });
        
        // Refresh round and history after a delay (but winner display stays)
        setTimeout(() => {
          console.log('[PJ] Refreshing round data (winner still displayed)');
          fetchRound();
        }, 3000);
        
        setTimeout(() => {
          fetch('/premium-jackpot/history', { credentials: 'include' })
            .then(r => r.ok ? r.json() : [])
            .then(setHistory);
        }, 4000);
        
        // Clear winner after 55 seconds so it shows until ~59:05
        setTimeout(() => {
          console.log('[PJ] Clearing winner display after 55s');
          setWinner(null);
        }, 55000);
        break;
        
      case 'premium_jp_new_round':
        // New round started - DON'T clear winner here, let the timeout handle it
        console.log('[PJ] New round started (keeping winner if exists)');
        fetchRound();
        break;
        
      case 'premium_jp_status':
        fetchRound();
        break;
        
      case 'balance_update':
        // LIVE BALANCE UPDATE - use ref to get current user
        const currentUser = userRef.current;
        if (currentUser && data.username === currentUser.username) {
          const oldBalance = currentUser.balance || 0;
          const newBalance = data.balance_raw || data.balance;  // Support both formats
          const delta = newBalance - oldBalance;
          
          console.log('[PJ] Balance update:', oldBalance, '->', newBalance, 'Delta:', delta);
          
          // Update local user state immediately
          setUser(prev => prev ? { ...prev, balance: newBalance } : prev);
          
          // Trigger navbar balance animation
          if (window.updateCoinRushBalance) {
            window.updateCoinRushBalance(newBalance, delta);
          }
        }
        break;
    }
  };
  
  const handleDeposit = async (amount) => {
    const res = await fetch('/premium-jackpot/deposit', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ amount: parseFloat(amount) })
    });
    
    if (!res.ok) {
      const error = await res.json().catch(() => ({ detail: 'Failed to place bet' }));
      throw new Error(error.detail || 'Failed to place bet');
    }
    
    const data = await res.json();
    setRound(data);
    
    // Update user balance with floating animation
    const newBalance = (user?.balance || 0) - amount * 100;
    setUser(prev => prev ? { ...prev, balance: newBalance } : prev);
    if (window.updateCoinRushBalance) {
      window.updateCoinRushBalance(newBalance, -amount * 100);
    }
    
    // Refresh user data
    fetch('/me', { credentials: 'include' })
      .then(r => r.ok ? r.json() : null)
      .then(data => { if (data) setUser(data); });
  };
  
  const handleLogout = async () => {
    try {
      await fetch('/auth/logout', { method: 'POST', credentials: 'include' });
    } finally {
      setUser(null);
      window.location.reload();
    }
  };
  
  // Only lock when resolved - scheduled, open, and countdown all allow betting
  const isLocked = round?.status === 'resolved';
  
  return (
    <div className="premium-app">
      <CoinRushNavbar 
        user={user}
        isConnected={isConnected}
        activePage="premium"
        onLogout={handleLogout}
      />
      
      <RulesModal isOpen={showRules} onClose={() => setShowRules(false)} />
      
      <DailyRewardModal
        isOpen={showDailyModal}
        onClose={() => setShowDailyModal(false)}
        user={user}
        onClaim={() => {
          fetch('/me', { credentials: 'include' })
            .then(res => res.ok ? res.json() : null)
            .then(data => { if (data) setUser(data); });
        }}
      />
      
      {/* Auth Modal */}
      {typeof AuthModal !== 'undefined' && (
        <AuthModal
          isOpen={showAuthModal}
          onClose={() => setShowAuthModal(false)}
          initialMode={authMode}
          onSuccess={(userData) => {
            setUser(userData);
            setShowAuthModal(false);
          }}
        />
      )}
      
      {/* Winner is now shown inline in JackpotHeroDisplay, not as overlay */}

      {/* Sliding History Bar at Top */}
      <SlidingHistoryBar history={history} />
      
      <main className="premium-main">
        {isLoading ? (
          <div className="premium-loading">
            <div className="loading-spinner">{Icons.spinner}</div>
            <span>Loading Premium Jackpot...</span>
          </div>
        ) : (
          <div className="premium-layout">
            {/* Left Column - Bet Panel + Participants */}
            <aside className="premium-sidebar left">
              <BetPanel 
                user={user}
                round={round}
                onDeposit={handleDeposit}
                isLocked={isLocked || winner !== null}
              />
              <CompactParticipantsPanel 
                participants={round?.participants}
                currentUser={user}
              />
            </aside>
            
            {/* Center - Main Display */}
            <section className="premium-center">
              <JackpotHeroDisplay 
                round={round} 
                winner={winner}
                onTimerEnd={() => {
                  console.log('[PJ] Timer ended, waiting for winner...');
                }}
                onWinnerDismiss={() => setWinner(null)}
              />
            </section>
            
            {/* Right Column - Chat Only (stretched) */}
            <aside className="premium-sidebar right">
              <div className="premium-chat-container">
                <CoinRushChatApp currentUser={user} theme="purple" />
              </div>
            </aside>
          </div>
        )}
      </main>
    </div>
  );
}

// ============================================
// RENDER
// ============================================
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<PremiumJackpotApp />);
