/**
 * CoinRush Barbarian Arena - React Version
 * Turn-based PvP duel game with premium UI
 * VERSION: 43 - Fixed view button for open battles
 */

// Log version on load to verify browser cache
console.log('🏰 Barbarian Arena v43 loaded - VIEW BUTTON FIX');

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

// ============================================
// CONFIG
// ============================================
const CONFIG = {
  minStake: 1,
  maxStake: 100000,
  battleCountdown: 15000,
  turnTimer: 15000,
  wsReconnectDelay: 3000
};

// Attack types with stats
const ATTACKS = {
  quick: { name: 'Quick Strike', hitChance: 85, damage: [18, 24], icon: 'quickStrike', color: '#3b82f6', desc: 'High accuracy, low damage' },
  normal: { name: 'Normal Attack', hitChance: 70, damage: [22, 30], icon: 'normalAttack', color: '#f59e0b', desc: 'Balanced risk and reward' },
  hard: { name: 'Heavy Smash', hitChance: 50, damage: [32, 40], icon: 'heavySmash', color: '#ef4444', desc: 'High risk, high reward' }
};

// Potion config (separate from attacks)
const POTION = {
  name: 'Health Potion',
  heal: [20, 30],
  icon: 'potion',
  color: '#22c55e',
  desc: 'Restore 20-30 HP (1 per battle)'
};

// ============================================
// SVG ICONS
// ============================================
const Icons = {
  sword: (
    <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-6"/>
      <path d="M16 16l4 4"/>
      <path d="M19 21l2-2"/>
    </svg>
  ),
  shield: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
    </svg>
  ),
  trophy: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/>
      <path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/>
      <path d="M4 22h16"/>
      <path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/>
      <path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/>
      <path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/>
    </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>
  ),
  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>
  ),
  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>
  ),
  play: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <polygon points="5 3 19 12 5 21 5 3"/>
    </svg>
  ),
  eye: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
      <circle cx="12" cy="12" r="3"/>
    </svg>
  ),
  plus: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <line x1="12" y1="5" x2="12" y2="19"/>
      <line x1="5" y1="12" x2="19" y2="12"/>
    </svg>
  ),
  x: (
    <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>
  ),
  heart: (
    <svg viewBox="0 0 24 24" fill="currentColor" stroke="none">
      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
    </svg>
  ),
  zap: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>
    </svg>
  ),
  volumeOn: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M11 5L6 9H2v6h4l5 4V5z"/>
      <path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>
      <path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>
    </svg>
  ),
  volumeOff: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M11 5L6 9H2v6h4l5 4V5z"/>
      <line x1="23" y1="9" x2="17" y2="15"/>
      <line x1="17" y1="9" x2="23" y2="15"/>
    </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>
  ),
  // Attack icons
  quickStrike: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" fill="currentColor" opacity="0.2"/>
      <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>
    </svg>
  ),
  normalAttack: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M14.5 17.5L3 6V3h3l11.5 11.5" fill="currentColor" opacity="0.2"/>
      <path d="M14.5 17.5L3 6V3h3l11.5 11.5"/>
      <path d="M13 19l6-6"/>
      <path d="M16 16l4 4"/>
      <path d="M19 21l2-2"/>
      <circle cx="6" cy="6" r="2" fill="currentColor" opacity="0.3"/>
    </svg>
  ),
  heavySmash: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M12 2L9 9H2l6 5-2 8 6-5 6 5-2-8 6-5h-7L12 2z" fill="currentColor" opacity="0.2"/>
      <path d="M12 2L9 9H2l6 5-2 8 6-5 6 5-2-8 6-5h-7L12 2z"/>
      <circle cx="12" cy="12" r="3" fill="currentColor" opacity="0.4"/>
    </svg>
  ),
  // Health potion icon
  potion: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M8 3h8v3a4 4 0 0 1 4 4v6a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4v-6a4 4 0 0 1 4-4V3z" fill="#22c55e" opacity="0.3"/>
      <path d="M8 3h8v3a4 4 0 0 1 4 4v6a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4v-6a4 4 0 0 1 4-4V3z"/>
      <path d="M10 3h4" strokeWidth="3"/>
      <path d="M12 10v6M9 13h6" stroke="#22c55e" strokeWidth="2"/>
    </svg>
  ),
  // Dice icon
  dice: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <rect x="3" y="3" width="18" height="18" rx="3" fill="currentColor" opacity="0.2"/>
      <rect x="3" y="3" width="18" height="18" rx="3"/>
      <circle cx="8" cy="8" r="1.5" fill="currentColor"/>
      <circle cx="12" cy="12" r="1.5" fill="currentColor"/>
      <circle cx="16" cy="16" r="1.5" fill="currentColor"/>
    </svg>
  ),
  // Trophy icon
  trophy: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M6 9H3a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h3" fill="currentColor" opacity="0.2"/>
      <path d="M6 9H3a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h3"/>
      <path d="M18 9h3a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1h-3" fill="currentColor" opacity="0.2"/>
      <path d="M18 9h3a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1h-3"/>
      <path d="M6 4v6a6 6 0 0 0 12 0V4" fill="currentColor" opacity="0.2"/>
      <path d="M6 4v6a6 6 0 0 0 12 0V4"/>
      <path d="M12 16v4"/>
      <path d="M8 20h8"/>
    </svg>
  ),
  // Crown icon for winner
  crown: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M2 8l4 12h12l4-12-5 4-5-6-5 6-5-4z" fill="currentColor" opacity="0.3"/>
      <path d="M2 8l4 12h12l4-12-5 4-5-6-5 6-5-4z"/>
      <circle cx="5" cy="8" r="1" fill="currentColor"/>
      <circle cx="12" cy="5" r="1" fill="currentColor"/>
      <circle cx="19" cy="8" r="1" fill="currentColor"/>
    </svg>
  ),
  // Skull icon for loser
  skull: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="12" cy="10" r="8" fill="currentColor" opacity="0.2"/>
      <circle cx="12" cy="10" r="8"/>
      <circle cx="9" cy="9" r="2"/>
      <circle cx="15" cy="9" r="2"/>
      <path d="M9 18v3"/>
      <path d="M12 18v3"/>
      <path d="M15 18v3"/>
      <path d="M8 14h8"/>
    </svg>
  ),
  // Timer/Clock icon
  timer: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="12" cy="13" r="8" fill="currentColor" opacity="0.2"/>
      <circle cx="12" cy="13" r="8"/>
      <path d="M12 9v4l2.5 2.5"/>
      <path d="M9 2h6"/>
      <path d="M12 2v2"/>
    </svg>
  ),
  // Heart icon for HP
  heart: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" fill="currentColor" opacity="0.3"/>
      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
    </svg>
  ),
  // Close/X icon
  close: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
      <path d="M18 6L6 18"/>
      <path d="M6 6l12 12"/>
    </svg>
  ),
  // VS icon
  versus: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <text x="12" y="17" textAnchor="middle" fontSize="12" fontWeight="bold" fill="currentColor" stroke="none">VS</text>
    </svg>
  ),
  // Coins icon
  coins: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="9" cy="10" r="6" fill="currentColor" opacity="0.3"/>
      <circle cx="9" cy="10" r="6"/>
      <circle cx="15" cy="14" r="6" fill="currentColor" opacity="0.3"/>
      <circle cx="15" cy="14" r="6"/>
      <path d="M9 7v6" strokeWidth="1.5"/>
      <path d="M7 10h4" strokeWidth="1.5"/>
      <path d="M15 11v6" strokeWidth="1.5"/>
      <path d="M13 14h4" strokeWidth="1.5"/>
    </svg>
  ),
  // Plus icon
  plus: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
      <path d="M12 5v14"/>
      <path d="M5 12h14"/>
    </svg>
  ),
  // Bot icon
  bot: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <rect x="3" y="8" width="18" height="12" rx="2" fill="currentColor" opacity="0.2"/>
      <rect x="3" y="8" width="18" height="12" rx="2"/>
      <circle cx="9" cy="14" r="2"/>
      <circle cx="15" cy="14" r="2"/>
      <path d="M12 2v4"/>
      <circle cx="12" cy="2" r="1.5" fill="currentColor"/>
      <path d="M8 18v2"/>
      <path d="M16 18v2"/>
    </svg>
  ),
  // Arrow icon
  arrow: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
      <path d="M5 12h14"/>
      <path d="M12 5l7 7-7 7"/>
    </svg>
  ),
  // Target icon
  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" fill="currentColor"/>
    </svg>
  ),
  // Refresh icon
  refresh: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M21 2v6h-6"/>
      <path d="M3 12a9 9 0 0 1 15-6.7L21 8"/>
      <path d="M3 22v-6h6"/>
      <path d="M21 12a9 9 0 0 1-15 6.7L3 16"/>
    </svg>
  ),
  // Eye icon for viewing
  eye: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" fill="currentColor" opacity="0.1"/>
      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
      <circle cx="12" cy="12" r="3" fill="currentColor" opacity="0.3"/>
      <circle cx="12" cy="12" r="3"/>
    </svg>
  ),
  // Resume/Play icon
  play: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <polygon points="5 3 19 12 5 21 5 3" fill="currentColor" opacity="0.3"/>
      <polygon points="5 3 19 12 5 21 5 3"/>
    </svg>
  ),
  // Daily Rewards Modal Icons
  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>
  ),
  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>
  ),
  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>
  ),
  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>
  ),
  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>
  ),
  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"/>
      <path d="M9.5 17.5L21 6V3h-3L6.5 14.5"/>
      <path d="M11 19l-6-6M8 16l-4 4M5 21l-2-2"/>
    </svg>
  )
};

// ============================================
// DAILY REWARDS HELPERS
// ============================================
// Helper to get SVG icon for reward type
const getRewardIcon = (type) => {
  const typeIcons = {
    'xp_boost': Icons.zap,
    'coinflip_discount': Icons.target,
    'barbarian_discount': Icons.swords,
    'jackpot_discount': Icons.slotMachine,
    'combo': Icons.star
  };
  if (typeIcons[type]) return typeIcons[type];
  return Icons.gift;
};

// Get reward color based on type
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)' };
};

// ============================================
// UTILITY FUNCTIONS
// ============================================
function formatCoins(hundredths) {
  const coins = hundredths / 100;
  return coins.toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
}

function generatePlayerColor(username) {
  const colors = [
    { bg: 'linear-gradient(135deg, #f97316, #facc15)', solid: '#f97316' },
    { bg: 'linear-gradient(135deg, #ef4444, #f97316)', solid: '#ef4444' },
    { bg: 'linear-gradient(135deg, #8b5cf6, #ec4899)', solid: '#8b5cf6' },
    { bg: 'linear-gradient(135deg, #3b82f6, #06b6d4)', solid: '#3b82f6' },
    { bg: 'linear-gradient(135deg, #10b981, #34d399)', solid: '#10b981' },
    { bg: 'linear-gradient(135deg, #f59e0b, #fbbf24)', solid: '#f59e0b' }
  ];
  // Handle null/undefined username
  if (!username) {
    return { bg: 'linear-gradient(135deg, #666, #888)', solid: '#666' };
  }
  let hash = 0;
  for (let i = 0; i < username.length; i++) {
    hash = username.charCodeAt(i) + ((hash << 5) - hash);
  }
  return colors[Math.abs(hash) % colors.length];
}

function getTimeRemaining(expiresAt) {
  const now = Date.now();
  const expires = new Date(expiresAt).getTime();
  const remaining = Math.max(0, expires - now);
  const mins = Math.floor(remaining / 60000);
  const secs = Math.floor((remaining % 60000) / 1000);
  return { mins, secs, total: remaining };
}

// ============================================
// AVATAR COMPONENT
// ============================================
function Avatar({ username, size = 'md', showBorder = true, level = 1, showLevel = false }) {
  // Size classes
  const sizeClasses = {
    xs: 'cf-avatar--xs',
    sm: 'cf-avatar--sm',
    md: 'cf-avatar--md',
    lg: 'cf-avatar--lg',
    xl: 'cf-avatar--xl'
  };

  // Border frame sizes
  const frameSizes = {
    xs: 44,
    sm: 72,
    md: 86,
    lg: 100,
    xl: 120
  };

  // Background color
  const getBackground = () => {
    if (typeof window.colorFrom === 'function') {
      return window.colorFrom(username || 'X');
    }
    const hue = [...(username || 'X')].reduce((a, c) => a + c.charCodeAt(0), 0) % 360;
    return `linear-gradient(135deg, hsl(${hue} 70% 50%), hsl(${hue} 70% 35%))`;
  };

  // Border frame image
  const getBorderFrame = () => {
    if (level >= 40) return '/static/img/borders/Challengerborder.png';
    if (level >= 30) return '/static/img/borders/Diamondborder.png';
    if (level >= 20) return '/static/img/borders/Rubyborder.png';
    if (level >= 15) return '/static/img/borders/Goldborder.png';
    if (level >= 10) return '/static/img/borders/Silverborder.png';
    if (level >= 5) return '/static/img/borders/Bronzeborder.png';
    return null;
  };

  // Border class
  const getBorderClass = () => {
    if (typeof window.getAvatarBorderClass === 'function') {
      return window.getAvatarBorderClass(level);
    }
    return '';
  };

  const borderClass = showBorder ? getBorderClass() : '';
  const frameUrl = showBorder ? getBorderFrame() : null;
  const frameSize = frameSizes[size] || 86;

  return (
    <div
      className={`cf-avatar player-avatar ${sizeClasses[size] || ''} ${borderClass}`}
      style={{ background: getBackground() }}
    >
      <span className="cf-avatar__initials">
        {(username || 'X').slice(0, 2).toUpperCase()}
      </span>
      {showLevel && level > 0 && (
        <span className="cf-avatar__level">{level}</span>
      )}
      {frameUrl && (
        <img
          src={frameUrl}
          alt=""
          className="cf-avatar__frame"
          style={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            width: frameSize,
            height: frameSize,
            pointerEvents: 'none',
            zIndex: 10
          }}
        />
      )}
    </div>
  );
}

// ============================================
// CREATE DUEL PANEL
// ============================================
function CreateDuelPanel({ user, onCreateDuel, isCreating }) {
  const [amount, setAmount] = useState('');
  const [soundEnabled, setSoundEnabled] = useState(true);
  
  const handleCreate = () => {
    const stake = parseInt(amount, 10);
    if (stake >= CONFIG.minStake && user) {
      onCreateDuel(stake);
    }
  };
  
  const adjustAmount = (delta) => {
    const current = parseInt(amount, 10) || 0;
    setAmount(Math.max(0, current + delta).toString());
  };
  
  const setMax = () => {
    if (user) {
      setAmount(Math.floor(user.balance / 100).toString());
    }
  };
  
  const canCreate = user && parseInt(amount, 10) >= CONFIG.minStake && !isCreating;
  
  return (
    <div className="create-duel-panel">
      <div className="panel-header">
        <div className="panel-header-bg"></div>
        <div className="panel-header-content">
          <div className="panel-icon">{Icons.sword}</div>
          <div>
            <h2 className="panel-title">CREATE DUEL</h2>
            <p className="panel-subtitle">Set your stake and challenge warriors</p>
          </div>
        </div>
      </div>
      
      <div className="panel-body">
        <div className="stake-header">
          <label className="stake-label">STAKE (COINS)</label>
          <button 
            className={`sound-toggle ${soundEnabled ? 'on' : 'off'}`}
            onClick={() => setSoundEnabled(!soundEnabled)}
            title={soundEnabled ? 'Mute sounds' : 'Enable sounds'}
          >
            {soundEnabled ? Icons.volumeOn : Icons.volumeOff}
          </button>
        </div>
        
        <input
          type="number"
          className="stake-input"
          placeholder="Enter amount..."
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
          min={CONFIG.minStake}
        />
        
        <div className="quick-amounts">
          <button onClick={() => setAmount('')} className="quick-btn">Clear</button>
          <button onClick={() => adjustAmount(1)} className="quick-btn">+1</button>
          <button onClick={() => adjustAmount(5)} className="quick-btn">+5</button>
          <button onClick={() => adjustAmount(10)} className="quick-btn">+10</button>
          <button onClick={() => adjustAmount(50)} className="quick-btn">+50</button>
          <button onClick={() => adjustAmount(100)} className="quick-btn">+100</button>
          <button onClick={() => setAmount(Math.floor((parseInt(amount, 10) || 0) / 2).toString())} className="quick-btn">½</button>
          <button onClick={() => setAmount(((parseInt(amount, 10) || 0) * 2).toString())} className="quick-btn">×2</button>
          <button onClick={setMax} className="quick-btn max">Max</button>
        </div>
        
        <button
          className={`create-btn ${canCreate ? '' : 'disabled'}`}
          onClick={handleCreate}
          disabled={!canCreate}
        >
          {isCreating ? (
            <span className="btn-loading">Creating...</span>
          ) : !user ? (
            <span>Login Required</span>
          ) : (
            <>
              <span>CREATE FIGHT</span>
              {Icons.sword}
            </>
          )}
        </button>
      </div>
    </div>
  );
}

// ============================================
// BATTLE CARD
// ============================================
function BattleCard({ battle, user, onJoin, onView, isJoining }) {
  const [timeLeft, setTimeLeft] = useState(300); // 5 minutes in seconds
  
  const isOwn = user?.username === battle.creator;
  const isOpponent = battle.opponent && user?.username === battle.opponent;
  const isParticipant = isOwn || isOpponent;
  const isResolved = battle.status === 'resolved';
  const isActive = battle.status === 'active';
  const canJoin = user && battle.status === 'open' && !isOwn;
  
  // Countdown timer for open battles
  useEffect(() => {
    if (battle.status !== 'open') return;
    
    let createdAtStr = battle.created_at;
    if (createdAtStr && !createdAtStr.endsWith('Z') && !createdAtStr.includes('+')) {
      createdAtStr += 'Z';
    }
    const createdAt = new Date(createdAtStr).getTime();
    if (!Number.isFinite(createdAt)) return;
    
    const updateTimer = () => {
      const elapsed = (Date.now() - createdAt) / 1000;
      const remaining = Math.max(0, 300 - elapsed); // 5 min timeout
      setTimeLeft(remaining);
    };
    
    updateTimer();
    const interval = setInterval(updateTimer, 1000);
    return () => clearInterval(interval);
  }, [battle.created_at, battle.status]);
  
  const isUrgent = timeLeft < 60;
  const isWarning = timeLeft < 120 && timeLeft >= 60;
  const winnerIsCreator = isResolved && battle.winner === battle.creator;
  
  const formatTime = (secs) => {
    const m = Math.floor(secs / 60);
    const s = Math.floor(secs % 60);
    return `${m}:${s.toString().padStart(2, '0')}`;
  };

  return (
    <div className={[
      'bc',
      isResolved && 'bc--resolved',
      isActive && 'bc--active',
      isOwn && 'bc--own'
    ].filter(Boolean).join(' ')}>
      
      {/* Main row with players */}
      <div className="bc__row">
        {/* Creator */}
        <div className={`bc__player ${isResolved && winnerIsCreator ? 'bc__player--winner' : ''}`}>
          <div className="bc__avatar-wrap">
            <Avatar username={battle.creator} size="sm" level={battle.creator_level || 1} showLevel={true} />
          </div>
          <div className="bc__info">
            <span className="bc__name">{battle.creator}</span>
            <span className="bc__bet">{formatCoins(battle.amount)}</span>
          </div>
          {isResolved && winnerIsCreator && <span className="bc__crown">{Icons.crown}</span>}
        </div>

        {/* VS */}
        <div className="bc__vs">VS</div>

        {/* Opponent or waiting */}
        <div className={`bc__player bc__player--right ${isResolved && !winnerIsCreator ? 'bc__player--winner' : ''}`}>
          {battle.opponent ? (
            <>
              {isResolved && !winnerIsCreator && <span className="bc__crown">{Icons.crown}</span>}
              <div className="bc__info bc__info--right">
                <span className="bc__name">{battle.opponent}</span>
                <span className="bc__bet">{formatCoins(battle.join_amount || battle.amount)}</span>
              </div>
              <div className="bc__avatar-wrap">
                <Avatar username={battle.opponent} size="sm" level={battle.opponent_level || 1} showLevel={true} />
              </div>
            </>
          ) : (
            <div className="bc__waiting">
              <span className="bc__waiting-icon">?</span>
              <span className="bc__waiting-text">Waiting...</span>
            </div>
          )}
        </div>
      </div>

      {/* Footer */}
      <div className="bc__footer">
        <div className="bc__pot">
          <img src="/static/coinrushlogos.png" alt="" className="bc__coin" />
          <span>{formatCoins(battle.total_pot || battle.amount * 2)}</span>
        </div>

        {/* Status */}
        <div className={[
          'bc__status',
          isResolved ? 'bc__status--resolved' : isActive ? 'bc__status--active' : 'bc__status--open',
          !isResolved && !isActive && isUrgent && 'bc__status--urgent',
          !isResolved && !isActive && isWarning && 'bc__status--warning'
        ].filter(Boolean).join(' ')}>
          {isResolved ? (
            <>{battle.winner} WINS</>
          ) : isActive ? (
            <><span className="bc__live-dot"></span> LIVE</>
          ) : (
            <><span className="bc__timer-icon">{Icons.clock}</span> {formatTime(timeLeft)}</>
          )}
        </div>

        {/* Actions */}
        <div className="bc__actions">
          {/* Eye button - always visible for spectating/viewing */}
          <button className="bc__btn bc__btn--view" onClick={() => onView(battle.id)} title={isResolved ? 'Watch replay' : 'Spectate'}>
            <span className="bc__btn-icon">{isResolved ? Icons.play : Icons.eye}</span>
          </button>
          
          {/* Join button - for open battles that aren't your own */}
          {battle.status === 'open' && !isOwn && (
            <button 
              className="bc__btn bc__btn--join" 
              onClick={() => onJoin(battle.id)} 
              disabled={isJoining || !user}
              title={!user ? 'Login to join' : 'Join this duel'}
            >
              {isJoining ? '...' : <>{Icons.sword} Join</>}
            </button>
          )}
          
          {/* Resume button - for active battles you're in */}
          {isActive && isParticipant && (
            <button className="bc__btn bc__btn--join" onClick={() => onView(battle.id)}>
              Resume
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ============================================
// LIVE DUELS LIST
// ============================================
function LiveDuelsList({ battles, user, onJoin, onView, isLoading, isJoining }) {
  const openBattles = battles.filter(b => b.status === 'open');
  const activeBattles = battles.filter(b => b.status === 'active');
  const recentResolved = battles.filter(b => b.status === 'resolved').slice(0, 5);
  
  if (isLoading) {
    return (
      <div className="duels-panel">
        <div className="panel-header simple">
          <span className="panel-icon">{Icons.trophy}</span>
          <h2 className="panel-title">LIVE DUELS</h2>
        </div>
        <div className="duels-loading">
          <div className="spinner"></div>
          <span>Loading battles...</span>
        </div>
      </div>
    );
  }
  
  const allBattles = [...activeBattles, ...openBattles, ...recentResolved];
  
  return (
    <div className="duels-panel">
      <div className="panel-header simple">
        <div className="header-left">
          <span className="panel-icon">{Icons.trophy}</span>
          <h2 className="panel-title">LIVE DUELS</h2>
        </div>
        <div className="header-stats">
          {activeBattles.length > 0 && (
            <span className="stat active">{activeBattles.length} Active</span>
          )}
          {openBattles.length > 0 && (
            <span className="stat open">{openBattles.length} Open</span>
          )}
        </div>
      </div>
      
      <div className="duels-list">
        {allBattles.length === 0 ? (
          <div className="empty-state">
            <div className="empty-icon">{Icons.trophy}</div>
            <h3>No Active Duels</h3>
            <p>Create the first duel to start battling!</p>
          </div>
        ) : (
          allBattles.map(battle => (
            <BattleCard
              key={battle.id}
              battle={battle}
              user={user}
              onJoin={onJoin}
              onView={onView}
              isJoining={isJoining}
            />
          ))
        )}
      </div>
    </div>
  );
}

// ============================================
// FLOATING DAMAGE TEXT COMPONENT
// ============================================
function FloatingDamage({ damage, isHit, targetSide, isHeal }) {
  const [visible, setVisible] = useState(true);
  
  useEffect(() => {
    const timer = setTimeout(() => setVisible(false), 1500);
    return () => clearTimeout(timer);
  }, []);
  
  if (!visible) return null;
  
  // Heal effect: green positive number
  if (isHeal) {
    return (
      <div className={`floating-damage ${targetSide} heal`}>
        +{damage}
      </div>
    );
  }
  
  return (
    <div className={`floating-damage ${targetSide} ${isHit ? 'hit' : 'miss'}`}>
      {isHit ? `-${damage}` : 'MISS!'}
    </div>
  );
}

// ============================================
// BLOOD SPLATTER COMPONENT
// ============================================
function BloodSplatter({ side, intensity }) {
  const [particles, setParticles] = useState([]);
  
  useEffect(() => {
    // Generate random blood particles
    const count = Math.min(intensity / 5, 8) + 3;
    const newParticles = [];
    for (let i = 0; i < count; i++) {
      newParticles.push({
        id: i,
        x: (Math.random() - 0.5) * 60,
        y: (Math.random() - 0.5) * 40,
        size: Math.random() * 8 + 4,
        delay: Math.random() * 0.2,
        duration: 0.5 + Math.random() * 0.3
      });
    }
    setParticles(newParticles);
    
    // Clean up after animation
    const timer = setTimeout(() => setParticles([]), 1500);
    return () => clearTimeout(timer);
  }, [intensity]);
  
  return (
    <div className={`blood-splatter ${side}`}>
      {particles.map(p => (
        <div
          key={p.id}
          className="blood-particle"
          style={{
            '--x': `${p.x}px`,
            '--y': `${p.y}px`,
            '--size': `${p.size}px`,
            '--delay': `${p.delay}s`,
            '--duration': `${p.duration}s`
          }}
        />
      ))}
    </div>
  );
}

// ============================================
// BATTLE OVERLAY (Duel Arena)
// ============================================
function BattleOverlay({ battle, user, onClose, onAttack, isMyTurn, battleLog, countdown, turnTimer, diceRoll, battlePhase, damageEffect, attackAnimation }) {
  if (!battle) return null;
  
  const isCreator = user?.username === battle.creator;
  const isOpponent = user?.username === battle.opponent;
  const isParticipant = isCreator || isOpponent;
  const isSpectator = !isParticipant;
  
  const myRole = isCreator ? 'creator' : 'opponent';
  const myHP = isCreator ? battle.creator_hp : battle.opponent_hp;
  const opponentHP = isCreator ? battle.opponent_hp : battle.creator_hp;
  const myName = isCreator ? battle.creator : battle.opponent;
  const opponentName = isCreator ? battle.opponent : battle.creator;
  
  const myColor = generatePlayerColor(myName || 'You');
  const opponentColor = generatePlayerColor(opponentName || 'Opponent');
  
  const isBattleComplete = battle.status === 'resolved';
  const isWinner = battle.winner === user?.username;
  
  // Determine sprite states based on animations
  const getCreatorSprite = () => {
    if (damageEffect?.target === 'creator' && damageEffect.isHeal) return 'potion'; // Drinking animation for heal
    if (damageEffect?.target === 'creator' && !damageEffect.isHeal) return 'hurt';
    if (attackAnimation?.attacker === 'creator') return attackAnimation.type;
    return 'idle';
  };
  
  const getOpponentSprite = () => {
    if (damageEffect?.target === 'opponent' && damageEffect.isHeal) return 'potion'; // Drinking animation for heal
    if (damageEffect?.target === 'opponent' && !damageEffect.isHeal) return 'hurt';
    if (attackAnimation?.attacker === 'opponent') return attackAnimation.type;
    return 'idle';
  };
  
  const creatorSprite = getCreatorSprite();
  const opponentSprite = getOpponentSprite();
  
  // Check if we're in countdown phase (show countdown in center instead of VS)
  const isCountdownPhase = battlePhase === 'countdown';
  
  return (
    <div className="battle-overlay">
      <div className="battle-overlay-backdrop" onClick={onClose}></div>
      
      <div className="battle-arena">
        {/* Close button - always visible */}
        <button className="arena-close" onClick={onClose} title="Minimize battle (you can resume later)">
          {Icons.x}
        </button>
        
        {/* Arena Header */}
        <div className="arena-header">
          <h2 className="arena-title">
            {isBattleComplete ? (
              <>{Icons.trophy} BATTLE COMPLETE</>
            ) : (isCountdownPhase || battlePhase === 'waiting') ? (
              <>{Icons.sword} GET READY</>
            ) : (
              <>{Icons.sword} BATTLE IN PROGRESS</>
            )}
          </h2>
          <div className="arena-pot">
            Total Pot: <strong>{formatCoins(battle.total_pot || battle.amount * 2)}</strong> coins
          </div>
        </div>
        
        {/* Unified Battle Arena */}
        <div className="unified-arena">
          {/* Fighter Stats - Left (ALWAYS CREATOR) */}
          <div className="fighter-stats left">
            <div className="fighter-name" style={{ color: generatePlayerColor(battle.creator).solid }}>
              {battle.creator}
              {isCreator && <span className="you-tag">YOU</span>}
            </div>
            <div className="fighter-hp-bar">
              <div 
                className="hp-fill" 
                style={{ 
                  width: `${battle.creator_hp || 0}%`,
                  background: 'linear-gradient(90deg, #ef4444, #f97316)'
                }}
              ></div>
            </div>
            <div className="fighter-hp-text">
              {Icons.heart} {battle.creator_hp || 0} HP
            </div>
          </div>
          
          {/* Battle Stage - Both fighters in same box */}
          <div className="battle-stage">
            {/* Left Fighter Sprite */}
            <div className={`fighter-sprite-container left ${attackAnimation?.attacker === 'creator' && attackAnimation?.type !== 'potion' ? 'attacking' : ''} ${damageEffect?.target === 'creator' && damageEffect.isHeal ? 'healing' : ''}`}>
              <div className={`fighter-sprite creator sprite-${creatorSprite} ${damageEffect?.target === 'creator' && !damageEffect.isHeal ? 'shake' : ''}`}></div>
              {damageEffect?.target === 'creator' && damageEffect.hit && !damageEffect.isHeal && (
                <BloodSplatter side="left" intensity={damageEffect.damage} />
              )}
              {damageEffect?.target === 'creator' && (
                <FloatingDamage damage={damageEffect.damage} isHit={damageEffect.hit} targetSide="left" isHeal={damageEffect.isHeal} />
              )}
            </div>
            
            {/* Center: VS badge, countdown, or loading */}
            {battlePhase === 'waiting' ? (
              <div className="stage-loading">
                <div className="loading-spinner"></div>
              </div>
            ) : isCountdownPhase ? (
              <div className="stage-countdown">
                <div className="battle-countdown-num" key={countdown}>
                  {countdown}
                </div>
                {diceRoll?.firstPlayer && (
                  <div className="first-attacker-announce">
                    {diceRoll.firstPlayer} attacks first!
                  </div>
                )}
              </div>
            ) : (
              <div className="stage-vs">VS</div>
            )}
            
            {/* Right Fighter Sprite */}
            <div className={`fighter-sprite-container right ${attackAnimation?.attacker === 'opponent' && attackAnimation?.type !== 'potion' ? 'attacking' : ''} ${damageEffect?.target === 'opponent' && damageEffect.isHeal ? 'healing' : ''}`}>
              <div className={`fighter-sprite opponent sprite-${opponentSprite} ${damageEffect?.target === 'opponent' && !damageEffect.isHeal ? 'shake' : ''}`}></div>
              {damageEffect?.target === 'opponent' && damageEffect.hit && !damageEffect.isHeal && (
                <BloodSplatter side="right" intensity={damageEffect.damage} />
              )}
              {damageEffect?.target === 'opponent' && (
                <FloatingDamage damage={damageEffect.damage} isHit={damageEffect.hit} targetSide="right" isHeal={damageEffect.isHeal} />
              )}
            </div>
          </div>
          
          {/* Fighter Stats - Right (ALWAYS OPPONENT) */}
          <div className="fighter-stats right">
            <div className="fighter-name" style={{ color: battle.opponent ? generatePlayerColor(battle.opponent).solid : '#666' }}>
              {battle.opponent || 'Waiting...'}
              {isOpponent && <span className="you-tag">YOU</span>}
            </div>
            <div className="fighter-hp-bar">
              <div 
                className="hp-fill" 
                style={{ 
                  width: `${battle.opponent_hp || 0}%`,
                  background: 'linear-gradient(90deg, #3b82f6, #8b5cf6)'
                }}
              ></div>
            </div>
            <div className="fighter-hp-text">
              {Icons.heart} {battle.opponent_hp || 0} HP
            </div>
          </div>
        </div>
        
        {/* Battle Controls */}
        {!isBattleComplete && (
          <div className="arena-controls">
            {/* Fighting Phase - Your Turn */}
            {battlePhase === 'fighting' && isParticipant && isMyTurn && (
              <>
                <div className={`turn-indicator your-turn ${turnTimer <= 5 ? 'urgent' : ''}`}>
                  <span className="turn-pulse"></span>
                  YOUR TURN
                  {turnTimer > 0 && (
                    <span className={`turn-timer ${turnTimer <= 5 ? 'critical' : turnTimer <= 10 ? 'warning' : ''}`}>
                      {turnTimer}s
                    </span>
                  )}
                </div>
                <div className="combat-controls">
                  <div className="attack-buttons">
                    {Object.entries(ATTACKS).map(([key, attack]) => (
                      <button
                        key={key}
                        className={`attack-btn ${key}`}
                        onClick={() => {
                          console.log('🔘 Attack button clicked:', key);
                          onAttack(key);
                        }}
                      >
                        <span className="attack-icon">{Icons[attack.icon]}</span>
                        <span className="attack-name">{attack.name}</span>
                        <div className="attack-stats">
                          <span>{attack.hitChance}% Hit</span>
                          <span>{attack.damage[0]}-{attack.damage[1]} DMG</span>
                        </div>
                      </button>
                    ))}
                  </div>
                  
                  {/* Potion Button - Side panel */}
                  {(() => {
                    const myPotionUsed = isCreator ? battle.creator_potion_used : battle.opponent_potion_used;
                    return (
                      <button
                        className={`potion-btn ${myPotionUsed ? 'used' : ''}`}
                        onClick={() => {
                          console.log('🧪 Potion button clicked, used:', myPotionUsed);
                          if (!myPotionUsed) onAttack('potion');
                        }}
                        disabled={myPotionUsed}
                        title={myPotionUsed ? 'Already used this battle' : 'Use potion to heal 20-30 HP (doesn\'t end your turn)'}
                      >
                        <img 
                          src="/static/img/barbarian/potion.png" 
                          alt="Health Potion" 
                          className="potion-img"
                        />
                        <span className="potion-label">
                          {myPotionUsed ? 'Used' : `+${POTION.heal[0]}-${POTION.heal[1]} HP`}
                        </span>
                      </button>
                    );
                  })()}
                </div>
                <div className="keyboard-hints">
                  Press <kbd>1</kbd> <kbd>2</kbd> <kbd>3</kbd> to attack • <kbd>4</kbd> for potion
                </div>
              </>
            )}
            
            {/* Phase 3: Fighting - Waiting for opponent */}
            {battlePhase === 'fighting' && isParticipant && !isMyTurn && (
              <div className="turn-indicator waiting">
                <div className="waiting-spinner"></div>
                Waiting for opponent...
                {turnTimer > 0 && (
                  <span className={`turn-timer ${turnTimer <= 5 ? 'critical' : ''}`}>
                    {turnTimer}s
                  </span>
                )}
              </div>
            )}
            
            {/* Spectator view */}
            {isSpectator && (
              <div className="spectator-badge">
                {Icons.eye} Spectating
              </div>
            )}
          </div>
        )}
        
        {/* Victory/Defeat Banner */}
        {isBattleComplete && (
          <div className={`result-banner ${isWinner ? 'victory' : isSpectator ? 'neutral' : 'defeat'}`}>
            <div className="result-icon">
              {isWinner ? Icons.trophy : isSpectator ? Icons.sword : Icons.skull}
            </div>
            <div className="result-text">
              {isWinner ? 'VICTORY!' : isSpectator ? `${battle.winner} Wins!` : 'DEFEAT'}
            </div>
            {isWinner && (
              <div className="result-prize">
                +{formatCoins(battle.total_pot * 0.975)} coins
              </div>
            )}
            <button className="result-close-btn" onClick={onClose}>
              Close
            </button>
          </div>
        )}
        
        {/* Battle Log */}
        <div className="battle-log">
          <div className="log-header">Battle Log</div>
          <div className="log-entries">
            {battleLog.map((entry, i) => (
              <div key={i} className={`log-entry ${entry.type || ''}`}>
                {entry.message}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================
// RULES MODAL
// ============================================
function RulesModal({ isOpen, onClose }) {
  const [activeTab, setActiveTab] = useState('basics');
  
  if (!isOpen) return null;
  
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="rules-modal-v2" onClick={e => e.stopPropagation()}>
        <button className="modal-close-btn" onClick={onClose}>{Icons.x}</button>
        
        {/* Header */}
        <div className="rules-header-v2">
          <div className="rules-title-icon">{Icons.sword}</div>
          <h2>Knight Duel Rules</h2>
          <p>Master the art of combat and claim victory!</p>
        </div>
        
        {/* Tab Navigation */}
        <div className="rules-tabs">
          <button 
            className={`rules-tab ${activeTab === 'basics' ? 'active' : ''}`}
            onClick={() => setActiveTab('basics')}
          >
            {Icons.info} Basics
          </button>
          <button 
            className={`rules-tab ${activeTab === 'combat' ? 'active' : ''}`}
            onClick={() => setActiveTab('combat')}
          >
            {Icons.sword} Combat
          </button>
          <button 
            className={`rules-tab ${activeTab === 'items' ? 'active' : ''}`}
            onClick={() => setActiveTab('items')}
          >
            {Icons.potion} Items
          </button>
          <button 
            className={`rules-tab ${activeTab === 'rewards' ? 'active' : ''}`}
            onClick={() => setActiveTab('rewards')}
          >
            {Icons.trophy} Rewards
          </button>
        </div>
        
        {/* Tab Content */}
        <div className="rules-body">
          {/* BASICS TAB */}
          {activeTab === 'basics' && (
            <div className="rules-tab-content">
              <div className="rules-card">
                <div className="rules-card-header">
                  <span className="rules-card-number">1</span>
                  <h3>Create or Join a Duel</h3>
                </div>
                <p>Set your stake amount and create a new duel, or browse existing duels and join one that matches your budget.</p>
              </div>
              
              <div className="rules-card">
                <div className="rules-card-header">
                  <span className="rules-card-number">2</span>
                  <h3>Wait for an Opponent</h3>
                </div>
                <p>Your duel will appear in the lobby. When someone joins, a dice roll determines who attacks first!</p>
              </div>
              
              <div className="rules-card">
                <div className="rules-card-header">
                  <span className="rules-card-number">3</span>
                  <h3>Battle to Victory</h3>
                </div>
                <p>Take turns attacking until one knight's HP reaches 0. Each turn has a 15-second timer - act fast!</p>
              </div>
              
              <div className="rules-info-box">
                <div className="info-icon">{Icons.shield}</div>
                <div className="info-content">
                  <strong>Both knights start with 100 HP</strong>
                  <span>Reduce your opponent's health to zero to win!</span>
                </div>
              </div>
            </div>
          )}
          
          {/* COMBAT TAB */}
          {activeTab === 'combat' && (
            <div className="rules-tab-content">
              <p className="rules-intro">Choose your attack wisely! Each attack has different hit chance and damage.</p>
              
              <div className="combat-moves-grid">
                <div className="combat-move-card quick">
                  <div className="move-icon">{Icons.quickStrike}</div>
                  <div className="move-details">
                    <h4>Quick Strike</h4>
                    <div className="move-stats">
                      <span className="stat hit">85% Hit</span>
                      <span className="stat dmg">18-24 DMG</span>
                    </div>
                    <p>High accuracy, lower damage. Safe and reliable.</p>
                  </div>
                </div>
                
                <div className="combat-move-card normal">
                  <div className="move-icon">{Icons.normalAttack}</div>
                  <div className="move-details">
                    <h4>Normal Attack</h4>
                    <div className="move-stats">
                      <span className="stat hit">70% Hit</span>
                      <span className="stat dmg">22-30 DMG</span>
                    </div>
                    <p>Balanced risk and reward. The standard choice.</p>
                  </div>
                </div>
                
                <div className="combat-move-card hard">
                  <div className="move-icon">{Icons.heavySmash}</div>
                  <div className="move-details">
                    <h4>Heavy Smash</h4>
                    <div className="move-stats">
                      <span className="stat hit">50% Hit</span>
                      <span className="stat dmg">32-40 DMG</span>
                    </div>
                    <p>High risk, high reward. Miss more, but hit harder!</p>
                  </div>
                </div>
              </div>
              
              <div className="rules-tip-box">
                <span className="tip-badge">⌨️ TIP</span>
                <p>Use keyboard shortcuts <kbd>1</kbd> <kbd>2</kbd> <kbd>3</kbd> for quick attacks!</p>
              </div>
            </div>
          )}
          
          {/* ITEMS TAB */}
          {activeTab === 'items' && (
            <div className="rules-tab-content">
              <p className="rules-intro">Each knight has access to special items during battle.</p>
              
              <div className="item-showcase">
                <div className="item-card potion">
                  <div className="item-image">
                    <img src="/static/img/barbarian/potion.png" alt="Health Potion" />
                  </div>
                  <div className="item-info">
                    <h4>Health Potion</h4>
                    <div className="item-effect">
                      <span className="effect-value">+20-30 HP</span>
                    </div>
                    <ul className="item-rules">
                      <li>Restores 20-30 health points</li>
                      <li>Can only be used <strong>once per battle</strong></li>
                      <li>Does <strong>NOT</strong> end your turn - attack after healing!</li>
                      <li>Press <kbd>4</kbd> or click the potion button</li>
                    </ul>
                  </div>
                </div>
              </div>
              
              <div className="rules-strategy-box">
                <h5>💡 Strategy Tips</h5>
                <ul>
                  <li>Save your potion for when you're low on HP</li>
                  <li>Using potion + attack in one turn can turn the tide!</li>
                  <li>Don't waste it early - you only get one!</li>
                </ul>
              </div>
            </div>
          )}
          
          {/* REWARDS TAB */}
          {activeTab === 'rewards' && (
            <div className="rules-tab-content">
              <div className="rewards-showcase">
                <div className="reward-card winner">
                  <div className="reward-icon">{Icons.trophy}</div>
                  <h4>Winner Takes All</h4>
                  <p>The victorious knight claims the entire prize pool!</p>
                </div>
              </div>
              
              <div className="prize-breakdown">
                <h4>Prize Calculation</h4>
                <div className="prize-formula">
                  <div className="formula-row">
                    <span className="label">Your Stake</span>
                    <span className="value">+ Opponent's Stake</span>
                  </div>
                  <div className="formula-row">
                    <span className="label">Total Pot</span>
                    <span className="value">= Combined Stakes</span>
                  </div>
                  <div className="formula-row fee">
                    <span className="label">House Fee</span>
                    <span className="value">- 2.5%</span>
                  </div>
                  <div className="formula-row final">
                    <span className="label">Your Prize</span>
                    <span className="value">= 97.5% of Total Pot</span>
                  </div>
                </div>
              </div>
              
              <div className="example-box">
                <h5>📊 Example</h5>
                <p>You stake <strong>100 coins</strong>, opponent stakes <strong>100 coins</strong></p>
                <p>Total pot: <strong>200 coins</strong></p>
                <p>Winner receives: <strong>195 coins</strong> (after 2.5% fee)</p>
              </div>
              
              <div className="rules-warning-box">
                <span className="warning-icon">⏱️</span>
                <div>
                  <strong>Turn Timer</strong>
                  <p>You have 15 seconds per turn. If time runs out, a random attack is made for you!</p>
                </div>
              </div>
            </div>
          )}
        </div>
        
        {/* Footer */}
        <div className="rules-footer">
          <button className="rules-close-btn" onClick={onClose}>
            Got it, let's fight!
          </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);
  
  // Fetch status when modal opens
  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);
  
  // Get visible days for calendar (show 7 days centered on current)
  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
    });
  }
  
  // Check if there are any active bonuses
  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()}>
        {/* Confetti Effect */}
        {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>
        )}
        
        {/* Decorative Background */}
        <div className="daily-modal-bg">
          <div className="daily-bg-orb orb-1"></div>
          <div className="daily-bg-orb orb-2"></div>
        </div>
        
        {/* Close Button */}
        <button className="daily-close-btn" onClick={onClose}>
          {Icons.close}
        </button>
        
        {/* Content */}
        <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>
          ) : (
            <>
              {/* Hero Section */}
              <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>
              
              {/* Today's Reward Card */}
              <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>
              
              {/* Calendar Timeline */}
              <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>
              
              {/* Active Bonuses (if any) */}
              {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>
              )}
              
              {/* Claim Button */}
              <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>
  );
}

// ============================================
// MAIN APP
// ============================================
function BarbarianApp() {
  const [user, setUser] = useState(null);
  const [battles, setBattles] = useState([]);
  const [history, setHistory] = useState([]); // Recent battle history for ticker
  const [isConnected, setIsConnected] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [isCreating, setIsCreating] = useState(false);
  const [isJoining, setIsJoining] = useState(false); // Prevent double-clicks on join
  const [showRules, setShowRules] = useState(false);
  const [showDailyModal, setShowDailyModal] = useState(false);
  const [showSocialPanel, setShowSocialPanel] = useState(false);
  const [activeBattle, setActiveBattle] = useState(null);
  const [isMyTurn, setIsMyTurn] = useState(false);
  const [battleLog, setBattleLog] = useState([]);
  const [countdown, setCountdown] = useState(0);
  const [turnTimer, setTurnTimer] = useState(0);
  const [showAuthModal, setShowAuthModal] = useState(false);
  const [authMode, setAuthMode] = useState('login');
  const [diceRoll, setDiceRoll] = useState(null); // { rolling: bool, result: 'creator'|'opponent', firstPlayer: string }
  const [battlePhase, setBattlePhase] = useState('waiting'); // 'waiting' | 'dice_roll' | 'countdown' | 'fighting'
  const [damageEffect, setDamageEffect] = useState(null); // { target: 'creator'|'opponent', damage: number, hit: bool }
  const [attackAnimation, setAttackAnimation] = useState(null); // { attacker: 'creator'|'opponent', type: 'quick'|'normal'|'hard' }
  
  const wsRef = useRef(null);
  const userRef = useRef(null);
  const turnTimerRef = useRef(null);
  const battlePhaseRef = useRef(null);
  const isMyTurnRef = useRef(false);
  
  // Keep ref in sync
  useEffect(() => {
    userRef.current = user;
  }, [user]);
  
  useEffect(() => {
    battlePhaseRef.current = battlePhase;
  }, [battlePhase]);
  
  useEffect(() => {
    isMyTurnRef.current = isMyTurn;
  }, [isMyTurn]);
  
  // Expose openAuthModal to window
  useEffect(() => {
    window.openAuthModal = (mode = 'login') => {
      setAuthMode(mode);
      setShowAuthModal(true);
    };
    return () => { delete window.openAuthModal; };
  }, []);
  
  // Expose dailyRewardsModal to window for navbar
  useEffect(() => {
    window.dailyRewardsModal = {
      open: () => setShowDailyModal(true),
      close: () => setShowDailyModal(false)
    };
    return () => { delete window.dailyRewardsModal; };
  }, []);
  
  // Expose rules modal to window
  useEffect(() => {
    window.showBarbarianRules = () => setShowRules(true);
    return () => { delete window.showBarbarianRules; };
  }, []);
  
  // Expose social panel toggle to window
  useEffect(() => {
    window.toggleSocialPanel = () => setShowSocialPanel(prev => !prev);
    return () => { delete window.toggleSocialPanel; };
  }, []);
  
  // 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 battles
  const fetchBattles = useCallback(async () => {
    try {
      const res = await fetch('/barbarian/list', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setBattles(data || []);
      }
    } catch (e) {
      console.error('Failed to fetch battles:', e);
    } finally {
      setIsLoading(false);
    }
  }, []);
  
  // Fetch history
  const fetchHistory = useCallback(async () => {
    try {
      const res = await fetch('/barbarian/history', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setHistory(data || []);
      }
    } catch (e) {
      console.error('Failed to fetch history:', e);
    }
  }, []);
  
  useEffect(() => {
    fetchBattles();
    fetchHistory();
  }, [fetchBattles, 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('🔗 WebSocket connected');
        setIsConnected(true);
      };
      
      ws.onclose = () => {
        console.log('🔌 WebSocket disconnected');
        setIsConnected(false);
        setTimeout(connect, CONFIG.wsReconnectDelay);
      };
      
      ws.onmessage = (event) => {
        try {
          const msg = JSON.parse(event.data);
          handleWSMessage(msg);
        } catch (e) {
          console.error('WS parse error:', e);
        }
      };
      
      wsRef.current = ws;
    };
    
    connect();
    
    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
    };
  }, []);
  
  // Handle WebSocket messages
  const handleWSMessage = useCallback((msg) => {
    console.log('📨 WS Message:', msg.type, msg);
    
    switch (msg.type) {
      case 'bb_create':
        // New battle created
        fetchBattles();
        break;
        
      case 'bb_joined':
        // Someone joined a battle - just update the list
        // The countdown will be handled by bb_countdown message
        fetchBattles();
        
        // If it's our battle, set up the battle data (countdown will come from bb_countdown)
        if (userRef.current && (msg.creator === userRef.current.username || msg.opponent === userRef.current.username)) {
          const battle = {
            id: msg.id,
            creator: msg.creator,
            opponent: msg.opponent,
            amount: msg.amount * 100, // Convert to cents
            join_amount: (msg.join_amount || msg.amount) * 100,
            total_pot: (msg.amount + (msg.join_amount || msg.amount)) * 100,
            status: 'active',
            creator_hp: 100,
            opponent_hp: 100,
            current_turn: msg.first_turn,
            first_turn: msg.first_turn
          };
          setActiveBattle(battle);
          setBattleLog([]);
          setBattlePhase('waiting'); // Wait for bb_countdown
          console.log('🎲 bb_joined - Battle set up, waiting for countdown:', battle.id);
        }
        break;
        
      case 'bb_countdown': {
        // Countdown update from server - BOTH players see this
        console.log('⏱️ bb_countdown received:', msg);
        console.log('⏱️ userRef.current:', userRef.current);
        console.log('⏱️ activeBattleRef.current:', activeBattleRef.current);
        
        // If we're involved in this battle (either as creator or joiner)
        const myUsername = userRef.current?.username;
        const isCreatorMatch = msg.creator === myUsername;
        const isOpponentMatch = msg.opponent === myUsername;
        const isBattleMatch = activeBattleRef.current?.id === msg.battle_id;
        
        console.log('⏱️ Checking involvement:', { 
          myUsername, 
          msgCreator: msg.creator, 
          msgOpponent: msg.opponent,
          isCreatorMatch, 
          isOpponentMatch, 
          isBattleMatch 
        });
        
        const isInvolvedInBattle = isBattleMatch || isCreatorMatch || isOpponentMatch;
        
        if (isInvolvedInBattle) {
          console.log('✅ User IS involved in battle, showing countdown!');
          // If we don't have the battle open yet (joiner case), set it up
          if (!activeBattleRef.current || activeBattleRef.current.id !== msg.battle_id) {
            const battle = {
              id: msg.battle_id,
              creator: msg.creator,
              opponent: msg.opponent,
              status: 'active',
              creator_hp: 100,
              opponent_hp: 100,
              current_turn: msg.first_turn,
              first_turn: msg.first_turn
            };
            setActiveBattle(battle);
            setBattleLog([]);
          }
          
          // Set first attacker info
          setDiceRoll({ rolling: false, result: msg.first_turn, firstPlayer: msg.first_attacker });
          setBattlePhase('countdown');
          
          const countdownSeconds = msg.countdown_seconds || 5;
          setCountdown(countdownSeconds);
          setBattleLog([{ message: `${msg.first_attacker} attacks first!`, type: 'system' }]);
          
          // Determine if it's our turn
          const isCreator = msg.creator === userRef.current?.username;
          const myRole = isCreator ? 'creator' : 'opponent';
          const nowMyTurn = msg.first_turn === myRole;
          setIsMyTurn(nowMyTurn);
          isMyTurnRef.current = nowMyTurn;
          console.log('⏱️ bb_countdown - Turn setup:', { isCreator, myRole, firstTurn: msg.first_turn, nowMyTurn });
          
          // Start countdown timer synced with server start_time
          const startTime = msg.start_time ? new Date(msg.start_time).getTime() : Date.now() + (countdownSeconds * 1000);
          const updateCountdown = () => {
            const remaining = Math.max(0, Math.ceil((startTime - Date.now()) / 1000));
            setCountdown(remaining);
            if (remaining > 0) {
              setTimeout(updateCountdown, 100);
            }
          };
          updateCountdown();
        } else {
          console.log('❌ User NOT involved in this battle, ignoring countdown');
        }
        break;
      }
        
      case 'bb_start':
        // Battle started - countdown finished, time to fight!
        console.log('🚀 bb_start received:', msg);
        console.log('🔍 activeBattleRef.current:', activeBattleRef.current);
        console.log('🔍 msg.battle.id:', msg.battle?.id, 'activeBattleRef.current?.id:', activeBattleRef.current?.id);
        fetchBattles();
        if (msg.battle && activeBattleRef.current?.id === msg.battle.id) {
          console.log('✅ bb_start matches - starting fight phase');
          // Convert amounts from coins to cents for display consistency
          const battleData = {
            ...msg.battle,
            amount: (msg.battle.amount || 0) * 100,
            join_amount: (msg.battle.join_amount || 0) * 100,
            total_pot: (msg.battle.total_pot || 0) * 100,
          };
          
          setActiveBattle(prev => ({
            ...prev,
            ...battleData,
            creator_hp: msg.hp?.creator ?? 100,
            opponent_hp: msg.hp?.opponent ?? 100,
            current_turn: msg.current_turn_role
          }));
          setCountdown(0);
          setDiceRoll(null); // Clear any remaining dice roll state
          setBattlePhase('fighting');
          
          // Determine if it's our turn
          if (userRef.current) {
            const battleCreator = msg.battle.creator;
            const myUsername = userRef.current.username;
            const isCreator = battleCreator === myUsername;
            const myRole = isCreator ? 'creator' : 'opponent';
            const currentTurn = msg.current_turn_role || msg.battle.current_turn;
            const nowMyTurn = currentTurn === myRole;
            
            console.log('🎮 bb_start - Turn calculation:', { 
              battleCreator, 
              myUsername, 
              isCreator, 
              myRole, 
              currentTurn,
              'msg.current_turn_role': msg.current_turn_role,
              'msg.battle.current_turn': msg.battle.current_turn,
              nowMyTurn 
            });
            
            setIsMyTurn(nowMyTurn);
            isMyTurnRef.current = nowMyTurn; // Keep ref in sync immediately
            
            // Sync turn timer with server deadline
            const deadline = msg.turn_deadline ? new Date(msg.turn_deadline).getTime() : Date.now() + 15000;
            if (turnTimerRef.current) clearInterval(turnTimerRef.current);
            
            const updateTurnTimer = () => {
              const remaining = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
              setTurnTimer(remaining);
              if (remaining > 0) {
                turnTimerRef.current = setTimeout(updateTurnTimer, 500);
              }
            };
            updateTurnTimer();
          } else {
            console.warn('⚠️ userRef.current is null in bb_start');
          }
          
          const currentPlayer = msg.current_player || (msg.current_turn_role === 'creator' ? msg.battle.creator : msg.battle.opponent);
          setBattleLog(prev => [...prev, { message: `[FIGHT] ${currentPlayer}'s turn!`, type: 'system' }]);
        } else {
          console.log('⚠️ bb_start - battle ID mismatch or no msg.battle');
        }
        break;
        
      case 'bb_move':
        console.log('📥 Received bb_move:', msg);
        // Attack happened
        if (msg.battle_id === activeBattleRef.current?.id) {
          console.log('✅ bb_move matches active battle');
          // Determine who was the target (opposite of attacker)
          const attackerRole = msg.attacker_role;
          const targetRole = attackerRole === 'creator' ? 'opponent' : 'creator';
          const moveType = msg.move || msg.move_type || 'normal'; // quick, normal, hard
          const isPotion = msg.is_potion || moveType === 'potion';
          
          console.log('🎬 Animation details:', { attackerRole, targetRole, moveType, isPotion, damage: msg.damage, hit: msg.hit });
          
          if (isPotion) {
            // Potion: Show drinking animation on attacker, then heal effect
            console.log('🧪 Setting potion animation');
            setAttackAnimation({
              attacker: attackerRole,
              type: 'potion' // This triggers sprite-potion CSS class
            });
            
            // After drinking animation, show heal effect
            setTimeout(() => {
              setAttackAnimation(null);
              console.log('💚 Setting heal effect');
              setDamageEffect({
                target: attackerRole, // Heal targets self
                damage: msg.heal || 0,
                hit: true,
                isHeal: true
              });
              
              // Clear heal effect after animation
              setTimeout(() => {
                setDamageEffect(null);
              }, 1200);
            }, 600);
          } else {
            // Regular attack: Trigger attack animation on attacker FIRST
            console.log('⚔️ Setting attack animation:', { attacker: attackerRole, type: moveType });
            setAttackAnimation({
              attacker: attackerRole,
              type: moveType
            });
            
            // After a short delay, show damage on target
            setTimeout(() => {
              setAttackAnimation(null);
              
              // Trigger damage effect animation
              console.log('💥 Setting damage effect:', { target: targetRole, damage: msg.damage, hit: msg.hit });
              setDamageEffect({
                target: targetRole,
                damage: msg.damage || 0,
                hit: msg.hit,
                isHeal: false
              });
              
              // Clear damage effect after animation completes
              setTimeout(() => {
                setDamageEffect(null);
              }, 1200);
            }, 400);
          }
          
          setActiveBattle(prev => prev ? {
            ...prev,
            creator_hp: msg.hp?.creator ?? prev.creator_hp,
            opponent_hp: msg.hp?.opponent ?? prev.opponent_hp,
            current_turn: msg.next_turn_role || msg.next_turn,
            creator_potion_used: msg.potion_used?.creator ?? prev.creator_potion_used,
            opponent_potion_used: msg.potion_used?.opponent ?? prev.opponent_potion_used
          } : prev);
          
          // Add to battle log
          const attacker = msg.attacker || 'Someone';
          const moveLabel = msg.move_label || msg.move_type || 'attack';
          const logMessage = msg.is_potion 
            ? `[HEAL] ${attacker} uses Health Potion for +${msg.heal} HP!`
            : msg.hit 
              ? `[HIT] ${attacker} uses ${moveLabel} for ${msg.damage} damage!`
              : `[MISS] ${attacker} uses ${moveLabel} - missed!`;
          setBattleLog(prev => [...prev, { message: logMessage, type: msg.is_potion ? 'heal' : (msg.hit ? 'hit' : 'miss') }]);
          
          // Check if it's our turn now and sync timer with server deadline
          if (userRef.current) {
            const isCreator = activeBattleRef.current?.creator === userRef.current.username;
            const myRole = isCreator ? 'creator' : 'opponent';
            const nextTurnRole = msg.next_turn_role || msg.next_turn;
            const nowMyTurn = nextTurnRole === myRole;
            setIsMyTurn(nowMyTurn);
            isMyTurnRef.current = nowMyTurn; // Keep ref in sync immediately
            console.log('🔄 bb_move - Turn updated:', { myRole, nextTurnRole, nowMyTurn });
            
            // Sync turn timer with server deadline
            if (turnTimerRef.current) {
              clearTimeout(turnTimerRef.current);
              clearInterval(turnTimerRef.current);
            }
            
            const deadline = msg.turn_deadline ? new Date(msg.turn_deadline).getTime() : Date.now() + 15000;
            const updateTurnTimer = () => {
              const remaining = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
              setTurnTimer(remaining);
              if (remaining > 0) {
                turnTimerRef.current = setTimeout(updateTurnTimer, 500);
              }
            };
            updateTurnTimer();
          }
        } else {
          console.log('⚠️ bb_move for different battle:', { msgBattleId: msg.battle_id, activeBattleId: activeBattleRef.current?.id });
        }
        break;
      
      case 'bb_move_ack':
        console.log('✅ Move acknowledged by server:', msg);
        break;
      
      case 'bb_move_error':
        console.error('❌ Move error from server:', msg);
        // Re-enable turn if there was an error
        setIsMyTurn(true);
        isMyTurnRef.current = true;
        alert(`Attack failed: ${msg.error || 'Unknown error'}`);
        break;
        
      case 'bb_resolved':
        // Battle ended
        fetchBattles();
        fetchHistory(); // Refresh history from server
        
        // Add to history ticker (convert from coins to cents for display)
        const totalPotCents = typeof msg.total_pot === 'number' ? msg.total_pot * 100 : (activeBattleRef.current?.total_pot || 0);
        setHistory(prev => [{
          id: msg.battle_id,
          creator: activeBattleRef.current?.creator || msg.creator,
          opponent: activeBattleRef.current?.opponent || msg.opponent,
          winner: msg.winner,
          total_pot: totalPotCents,
          amount: activeBattleRef.current?.amount || 0
        }, ...prev].slice(0, 50));
        
        if (msg.battle_id === activeBattleRef.current?.id || msg.id === activeBattleRef.current?.id) {
          // Clear turn timer
          if (turnTimerRef.current) {
            clearInterval(turnTimerRef.current);
            turnTimerRef.current = null;
          }
          
          setActiveBattle(prev => prev ? {
            ...prev,
            status: 'resolved',
            winner: msg.winner,
            creator_hp: msg.hp?.creator ?? prev.creator_hp,
            opponent_hp: msg.hp?.opponent ?? prev.opponent_hp,
            winner_prize: msg.prize
          } : prev);
          
          const winnerName = msg.winner || 'Someone';
          setBattleLog(prev => [...prev, { message: `[VICTORY] ${winnerName} WINS THE BATTLE!`, type: 'victory' }]);
          setIsMyTurn(false);
          setTurnTimer(0);
          setBattlePhase('finished');
          
          // Show pending balance animation now that battle is finished
          if (window.showPendingBalanceAnimation) {
            setTimeout(() => window.showPendingBalanceAnimation(), 500);
          }
        }
        break;
      
      case 'bb_cancelled':
        // Battle was cancelled (expired or manually)
        console.log('Battle cancelled:', msg);
        fetchBattles();
        
        // If we're viewing this battle, close it
        if (activeBattleRef.current?.id === msg.battle_id) {
          setActiveBattle(null);
          setBattlePhase('waiting');
        }
        break;
        
      case 'balance_update':
        if (userRef.current && msg.username === userRef.current.username) {
          const oldBalance = userRef.current.balance || 0;
          const newBalance = msg.balance;
          const delta = newBalance - oldBalance;
          setUser(prev => prev ? { ...prev, balance: newBalance } : prev);
          // Queue animation if battle in progress, show immediately if finished
          if (delta > 0 && window.updateCoinRushBalance) {
            const isBattling = ['dice_roll', 'countdown', 'fighting'].includes(battlePhaseRef.current);
            window.updateCoinRushBalance(newBalance, delta, !isBattling);
          }
        }
        break;
    }
  }, [fetchBattles, fetchHistory]);
  
  // Keep activeBattle ref in sync
  const activeBattleRef = useRef(null);
  useEffect(() => {
    activeBattleRef.current = activeBattle;
  }, [activeBattle]);
  
  // Create duel
  const handleCreateDuel = async (stake) => {
    if (!user || isCreating) return;
    
    setIsCreating(true);
    try {
      const res = await fetch('/barbarian/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ amount: stake * 100 })
      });
      
      if (res.ok) {
        const battle = await res.json();
        setBattles(prev => [battle, ...prev]);
        const newBalance = (user.balance || 0) - stake * 100;
        setUser(prev => prev ? { ...prev, balance: newBalance } : prev);
        // Show floating -bet animation
        if (window.updateCoinRushBalance) {
          window.updateCoinRushBalance(newBalance, -stake * 100);
        }
      } else {
        const error = await res.json();
        alert(error.detail || 'Failed to create duel');
      }
    } catch (e) {
      console.error('Create duel error:', e);
      alert('Failed to create duel');
    } finally {
      setIsCreating(false);
    }
  };
  
  // Join duel
  const handleJoinDuel = async (battleId) => {
    if (!user) {
      window.openAuthModal?.('login');
      return;
    }
    
    // Prevent double-clicks
    if (isJoining) {
      console.log('Already joining, ignoring duplicate click');
      return;
    }
    setIsJoining(true);
    console.log('Attempting to join battle:', battleId);
    console.log('🔌 WebSocket connected:', isConnected);
    console.log('👤 Current user:', userRef.current);
    
    try {
      const res = await fetch('/barbarian/join', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ battle_id: battleId })
      });
      
      console.log('Join response status:', res.status, res.ok);
      
      if (res.ok) {
        const battle = await res.json();
        console.log('Join successful, battle:', battle);
        
        // Set the battle data and phase - start countdown immediately for joiner
        if (!activeBattleRef.current || activeBattleRef.current.id !== battle.id) {
          setActiveBattle(battle);
          setBattleLog([]);
          
          // For joiner: start countdown immediately since backend is starting it
          const firstAttacker = battle.current_turn === 'creator' ? battle.creator : battle.opponent;
          setBattlePhase('countdown');
          setDiceRoll({ rolling: false, result: battle.current_turn, firstPlayer: firstAttacker });
          setCountdown(5); // Backend uses 5 second countdown
          setBattleLog([{ message: `${firstAttacker} attacks first!`, type: 'system' }]);
          
          // Set turn info
          const isCreator = battle.creator === userRef.current?.username;
          const myRole = isCreator ? 'creator' : 'opponent';
          const nowMyTurn = battle.current_turn === myRole;
          setIsMyTurn(nowMyTurn);
          isMyTurnRef.current = nowMyTurn;
          
          console.log('📱 HTTP Join - Battle set up with countdown!', { battle: battle.id, firstAttacker, nowMyTurn });
          
          // Start local countdown timer (bb_countdown will sync with server time if received)
          const startTime = Date.now() + 5000;
          const updateCountdown = () => {
            const remaining = Math.max(0, Math.ceil((startTime - Date.now()) / 1000));
            setCountdown(remaining);
            if (remaining > 0) {
              setTimeout(updateCountdown, 100);
            }
          };
          setTimeout(updateCountdown, 100);
        }
        
        // Refresh user balance
        try {
          const userRes = await fetch('/me', { credentials: 'include' });
          if (userRes.ok) {
            setUser(await userRes.json());
          }
        } catch (balanceErr) {
          console.error('Failed to refresh balance:', balanceErr);
        }
        fetchBattles();
      } else {
        // Only show error if we're not already in a battle (WebSocket might have beaten us)
        if (!activeBattleRef.current) {
          let errorMsg = 'Failed to join duel';
          try {
            const error = await res.json();
            errorMsg = error.detail || errorMsg;
          } catch (parseErr) {
            console.error('Failed to parse error response:', parseErr);
          }
          console.error('Join failed with status:', res.status, errorMsg);
          alert(errorMsg);
        } else {
          console.log('HTTP failed but WebSocket already opened battle, ignoring error');
        }
      }
    } catch (e) {
      // Only show error if we're not already in a battle
      if (!activeBattleRef.current) {
        console.error('Join duel error:', e);
        alert('Failed to join duel: ' + e.message);
      } else {
        console.log('HTTP error but WebSocket already opened battle, ignoring');
      }
    } finally {
      setIsJoining(false);
    }
  };
  
  // View/spectate battle (also used for Resume Battle)
  const handleViewBattle = async (battleId) => {
    try {
      const res = await fetch(`/barbarian/battle/${battleId}`, { credentials: 'include' });
      if (res.ok) {
        const battle = await res.json();
        setActiveBattle(battle);
        
        // Set battle phase based on status
        if (battle.status === 'open') {
          // Spectating an open battle - show waiting phase
          setBattlePhase('waiting');
          setCountdown(0);
          setBattleLog([{ message: 'Spectating - waiting for opponent...', type: 'system' }]);
        } else if (battle.status === 'active') {
          setBattlePhase('fighting');
          setCountdown(0);
          setDiceRoll(null);
          setBattleLog([{ message: 'Battle in progress...', type: 'system' }]);
          
          // Check if participant and set turn state
          if (user) {
            const isCreator = battle.creator === user.username;
            const myRole = isCreator ? 'creator' : 'opponent';
            const currentTurnRole = battle.current_turn;
            const isMyTurnNow = currentTurnRole === myRole;
            setIsMyTurn(isMyTurnNow);
            
            // Sync turn timer with server deadline if available
            if (turnTimerRef.current) {
              clearTimeout(turnTimerRef.current);
              clearInterval(turnTimerRef.current);
            }
            
            const deadline = battle.turn_deadline ? new Date(battle.turn_deadline).getTime() : Date.now() + 15000;
            const updateTurnTimer = () => {
              const remaining = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
              setTurnTimer(remaining);
              if (remaining > 0) {
                turnTimerRef.current = setTimeout(updateTurnTimer, 500);
              }
            };
            updateTurnTimer();
          }
        } else if (battle.status === 'resolved') {
          setBattlePhase('finished');
          setIsMyTurn(false);
          setBattleLog([{ message: 'Battle finished', type: 'system' }]);
        }
      }
    } catch (e) {
      console.error('View battle error:', e);
    }
  };
  
  // Make attack via WebSocket
  const handleAttack = (attackType) => {
    const currentBattle = activeBattleRef.current;
    const myTurn = isMyTurnRef.current;
    
    console.log('🗡️ handleAttack called:', { 
      attackType, 
      battleId: currentBattle?.id, 
      isMyTurn: myTurn, 
      battlePhase: battlePhaseRef.current,
      wsState: wsRef.current?.readyState
    });
    
    if (!currentBattle) {
      console.warn('❌ Attack blocked: No active battle');
      return;
    }
    if (!myTurn) {
      console.warn('❌ Attack blocked: Not my turn (isMyTurnRef.current =', myTurn, ')');
      return;
    }
    
    // Send attack via WebSocket
    if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
      const message = {
        type: 'battle_move',
        battle_id: currentBattle.id,
        move_type: attackType
      };
      console.log('📤 Sending battle_move:', message);
      wsRef.current.send(JSON.stringify(message));
      setIsMyTurn(false); // Optimistically disable
      isMyTurnRef.current = false; // Also update ref immediately
      setTurnTimer(0);
    } else {
      console.error('❌ WebSocket not connected - readyState:', wsRef.current?.readyState);
    }
  };
  
  // Keyboard shortcuts for attacks
  useEffect(() => {
    const handleKeyDown = (e) => {
      if (!activeBattle || !isMyTurn) return;
      
      const isCreator = user?.username === activeBattle.creator;
      const myPotionUsed = isCreator ? activeBattle.creator_potion_used : activeBattle.opponent_potion_used;
      
      switch (e.key) {
        case '1': handleAttack('quick'); break;
        case '2': handleAttack('normal'); break;
        case '3': handleAttack('hard'); break;
        case '4': if (!myPotionUsed) handleAttack('potion'); break;
      }
    };
    
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [activeBattle, isMyTurn]);
  
  // Countdown effect
  useEffect(() => {
    if (countdown <= 0) return;
    
    const timer = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearInterval(timer);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    
    return () => clearInterval(timer);
  }, [countdown]);
  
  // Logout handler
  const handleLogout = async () => {
    try {
      await fetch('/auth/logout', { method: 'POST', credentials: 'include' });
      setUser(null);
      window.location.href = '/';
    } catch (e) {}
  };
  
  // Handle auth success
  const handleAuthSuccess = async () => {
    setShowAuthModal(false);
    try {
      const res = await fetch('/me', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setUser(data);
      }
    } catch (e) {}
  };
  
  return (
    <div className="barbarian-app">
      <CoinRushNavbar 
        user={user}
        isConnected={isConnected}
        activePage="barbarian"
        onLogout={handleLogout}
      />
      
      <RulesModal isOpen={showRules} onClose={() => setShowRules(false)} />
      
      <DailyRewardModal
        isOpen={showDailyModal}
        onClose={() => setShowDailyModal(false)}
        user={user}
        onClaim={() => {
          // Refresh user data after claiming
          fetch('/me', { credentials: 'include' })
            .then(res => res.ok ? res.json() : null)
            .then(data => { if (data) setUser(data); })
            .catch(() => {});
        }}
      />
      
      {/* Social Panel */}
      {user && showSocialPanel && (
        <SocialPanel 
          onClose={() => setShowSocialPanel(false)}
          currentUser={user}
        />
      )}
      
      {activeBattle && (
        <BattleOverlay
          battle={activeBattle}
          user={user}
          onClose={() => {
            // Don't clear activeBattle - just hide the overlay
            // The battle continues in the background
            setActiveBattle(null);
          }}
          onAttack={handleAttack}
          isMyTurn={isMyTurn}
          battleLog={battleLog}
          countdown={countdown}
          turnTimer={turnTimer}
          diceRoll={diceRoll}
          battlePhase={battlePhase}
          damageEffect={damageEffect}
          attackAnimation={attackAnimation}
        />
      )}
      
      {/* History Ticker */}
      <div className="ba-ticker">
        <div className="ba-ticker-track">
          {history.length > 0 ? (
            <>
              {history.map((b, i) => (
                <div key={b.id || i} className="ba-ticker-item">
                  <span className="ba-ticker-id">#{b.id}</span>
                  <span className="ba-ticker-winner">{b.winner}</span>
                  <span className="ba-ticker-text">defeated</span>
                  <span className="ba-ticker-winner">{b.winner === b.creator ? b.opponent : b.creator}</span>
                  <span className="ba-ticker-text">for</span>
                  <span className="ba-ticker-amount">{formatCoins(b.total_pot || b.amount * 2)} coins</span>
                </div>
              ))}
              {/* Duplicate for seamless loop */}
              {history.map((b, i) => (
                <div key={`dup-${b.id || i}`} className="ba-ticker-item">
                  <span className="ba-ticker-id">#{b.id}</span>
                  <span className="ba-ticker-winner">{b.winner}</span>
                  <span className="ba-ticker-text">defeated</span>
                  <span className="ba-ticker-winner">{b.winner === b.creator ? b.opponent : b.creator}</span>
                  <span className="ba-ticker-text">for</span>
                  <span className="ba-ticker-amount">{formatCoins(b.total_pot || b.amount * 2)} coins</span>
                </div>
              ))}
            </>
          ) : (
            /* Placeholder when no history */
            <div className="ba-ticker-item">
              <span className="ba-ticker-text">No recent battles yet...</span>
            </div>
          )}
        </div>
      </div>
      
      <main className="barbarian-main">
        <div className="barbarian-layout">
          {/* Left Column - Create Duel */}
          <aside className="sidebar">
            <CreateDuelPanel
              user={user}
              onCreateDuel={handleCreateDuel}
              isCreating={isCreating}
            />
          </aside>
          
          {/* Center - Live Duels */}
          <section className="main-content">
            <LiveDuelsList
              battles={battles}
              user={user}
              onJoin={handleJoinDuel}
              onView={handleViewBattle}
              isLoading={isLoading}
              isJoining={isJoining}
            />
          </section>
          
          {/* Right Column - Chat (Full Height) */}
          <aside className="sidebar sidebar--right">
            <div id="arena-chat-container">
              <CoinRushChatApp currentUser={user} theme="green" />
            </div>
          </aside>
        </div>
      </main>
    </div>
  );
}

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