import { useState, useEffect } from 'react';
import { ArrowLeft, Phone, Play, Pause, Trophy, Users, Crown, Copy, Volume2, UserMinus } from 'lucide-react';
import Ticket from './Ticket';
import NumberBoard from './NumberBoard';
import Chat from './Chat';
import { GAME_MODES, checkTicketWin, playSound, calculatePlayerProgress } from '../utils/gameUtils';

function Game({ socket, playerData, roomData, playerTicket, onLeaveRoom, initialCalledNumbers = [], initialCurrentNumber = null, initialGameMode = null, isConnected = true, connectionHealth = 'good', reconnectAttempts = 0, onShowResults }) {
  const [localTicket, setLocalTicket] = useState(null);
  const [calledNumbers, setCalledNumbers] = useState(initialCalledNumbers);
  const [currentNumber, setCurrentNumber] = useState(initialCurrentNumber);
  const [gameMode, setGameMode] = useState(initialGameMode || roomData?.gameMode);
  
  // NEW: Multi-mode support
  const [activeGameModes, setActiveGameModes] = useState(roomData?.activeGameModes || null);
  const [winnersByMode, setWinnersByMode] = useState(roomData?.winnersByMode || {});
  const [claimableWins, setClaimableWins] = useState({}); // Track which modes the player can claim
  
  const [autoCall, setAutoCall] = useState(false);
  const [autoCallInterval, setAutoCallInterval] = useState(10); // Default 10 seconds
  const [showIntervalSetting, setShowIntervalSetting] = useState(false);
  const [canClaimWin, setCanClaimWin] = useState(false);
  const [winners, setWinners] = useState([]);
  const [celebrationWinner, setCelebrationWinner] = useState(null);
  const [toastNotifications, setToastNotifications] = useState([]);
  const [notificationTimeouts, setNotificationTimeouts] = useState(new Map());
  const [showRankingPanel, setShowRankingPanel] = useState(true);
  const [rankingPulse, setRankingPulse] = useState(false);
  const [requiredWinners, setRequiredWinners] = useState(3);
  const [showRoomCode, setShowRoomCode] = useState(false);
  const [playerProgress, setPlayerProgress] = useState(new Map()); // Store other players' progress

  // HOST SUPERPOWERS - New state variables
  const [isPaused, setIsPaused] = useState(false);
  const [showPlayerManagement, setShowPlayerManagement] = useState(false);
  const [showTransferHost, setShowTransferHost] = useState(false);
  const [showKickConfirm, setShowKickConfirm] = useState(false);
  const [selectedPlayerToKick, setSelectedPlayerToKick] = useState(null);
  const [selectedPlayerForHost, setSelectedPlayerForHost] = useState(null);
  const [hostActionLoading, setHostActionLoading] = useState(false);

  const isHost = roomData?.players?.find(p => p.id === playerData?.playerId)?.isHost;
  const currentPlayer = roomData?.players?.find(p => p.id === playerData?.playerId);
  const connectedPlayersCount = roomData?.players?.filter(p => p.isConnected).length || 0;
  const isGamePausedForPlayers = (roomData?.gameState === 'playing' && connectedPlayersCount < 2);
  
  // NEW: Check if this is a multi-mode game
  const isMultiMode = activeGameModes && Array.isArray(activeGameModes) && activeGameModes.length > 0;
  
  // In multi-mode games, only consider player "fully won" if all modes are claimed or game is complete
  // In single-mode games, hasWon means they can't compete anymore
  const hasWon = isMultiMode 
    ? (currentPlayer?.hasWon && Object.keys(winnersByMode || {}).length === (activeGameModes || []).length) // All modes claimed in multi-mode
    : (currentPlayer?.hasWon || winners.some(w => w.player.id === playerData?.playerId)); // Traditional single-mode logic

  // Helper function for adding notifications with proper cleanup
  const addNotification = (message, type = 'info', duration = 3000) => {
    const toastId = Date.now();
    
    // Clear any existing timeout for similar messages
    setNotificationTimeouts(prev => {
      const existingTimeout = prev.get(message);
      if (existingTimeout) {
        clearTimeout(existingTimeout);
      }
      return new Map(prev);
    });
    
    // Remove any existing notification with same message to prevent duplicates
    setToastNotifications(prev => prev.filter(t => t.message !== message));
    
    setToastNotifications(prev => [...prev, { 
      id: toastId, 
      message, 
      type
    }]);
    
    // Auto-remove toast after specified duration
    const timeoutId = setTimeout(() => {
      setToastNotifications(prev => prev.filter(t => t.id !== toastId));
      setNotificationTimeouts(prev => {
        const newMap = new Map(prev);
        newMap.delete(message);
        return newMap;
      });
    }, duration);
    
    // Store timeout for potential cleanup
    setNotificationTimeouts(prev => new Map(prev.set(message, timeoutId)));
    
    return { toastId, timeoutId };
  };

  // Send initial progress when ticket is ready
  useEffect(() => {
    if (localTicket && socket && playerData) {
      if (isMultiMode && activeGameModes && activeGameModes.length > 0) {
        // Send progress for each active game mode in multi-mode
        activeGameModes.forEach(mode => {
          const progress = calculatePlayerProgress(localTicket, mode, calledNumbers);
          socket.emit('updatePlayerProgress', {
            playerId: playerData.playerId,
            gameMode: mode,
            progress
          });
        });
      } else if (gameMode) {
        // Single mode progress
        const progress = calculatePlayerProgress(localTicket, gameMode, calledNumbers);
        socket.emit('updatePlayerProgress', {
          playerId: playerData.playerId,
          gameMode: gameMode,
          progress
        });
      }
    }
  }, [localTicket, socket, playerData, gameMode, isMultiMode, activeGameModes, calledNumbers]);

  // Sync prop ticket to local state
  useEffect(() => {
    if (playerTicket && !localTicket) {
      setLocalTicket(playerTicket);
    }
  }, [playerTicket, localTicket]);

  // NEW: Sync multi-mode data from roomData
  useEffect(() => {
    if (roomData?.activeGameModes) {
      setActiveGameModes(roomData.activeGameModes);
    }
    if (roomData?.winnersByMode) {
      setWinnersByMode(roomData.winnersByMode);
    }
  }, [roomData?.activeGameModes, roomData?.winnersByMode]);

  // Sync initial game state for rejoining players
  useEffect(() => {
    if (initialCalledNumbers.length > 0) {
      setCalledNumbers(initialCalledNumbers);
    }
    if (initialCurrentNumber) {
      setCurrentNumber(initialCurrentNumber);
    }
    if (initialGameMode) {
      setGameMode(initialGameMode);
    }
  }, [initialCalledNumbers, initialCurrentNumber, initialGameMode]);

  // Initialize auto-call interval from room data
  useEffect(() => {
    if (roomData?.autoCallInterval) {
      setAutoCallInterval(roomData.autoCallInterval);
    }
  }, [roomData?.autoCallInterval]);

  useEffect(() => {
    if (!socket) return;

    // Connection recovery - request state sync on reconnection
    const handleReconnection = () => {
      if (playerData && roomData) {
        socket.emit('requestFullSync', { 
          roomCode: roomData.code, 
          playerId: playerData.playerId 
        });
      }
    };

    // Listen for reconnection
    socket.on('connect', handleReconnection);

    // Handle full game state sync
    socket.on('fullGameSync', (syncData) => {
      if (syncData.calledNumbers) {
        setCalledNumbers(syncData.calledNumbers);
      }
      if (syncData.currentNumber) {
        setCurrentNumber(syncData.currentNumber);
      }
      if (syncData.autoCallStatus !== undefined) {
        setAutoCall(syncData.autoCallStatus);
      }
      
      // Acknowledge the sync
      if (syncData.timestamp) {
        socket.emit('messageAck', { messageId: `sync_${syncData.timestamp}` });
      }
    });

    socket.on('numberCalled', (data) => {
      setCalledNumbers(data.calledNumbers);
      setCurrentNumber(data.number);
      playSound('number');
      
      // Acknowledge critical message if required
      if (data.requireAck && data.messageId) {
        socket.emit('messageAck', { messageId: data.messageId });
      }
    });

    socket.on('autoCallToggled', (data) => {
      setAutoCall(data.autoCall);
    });

    socket.on('playerWon', (data) => {
      // Someone won - show immediate feedback
      playSound('win');
      
      // Note: We don't show toast notification here because the 'rankingUpdated' event
      // that follows will handle the visual celebration to prevent duplicate notifications
    });

    socket.on('rankingUpdated', (data) => {
      const prevWinnersCount = winners.length;
      const newWinners = data.winners;
      setWinners(newWinners);
      
      // Update required winners count
      if (data.requiredWinners) setRequiredWinners(data.requiredWinners);
      
      // Show celebration for new winner
      if (newWinners.length > prevWinnersCount) {
        const newWinner = newWinners[newWinners.length - 1];
        const rank = newWinners.length;
        
        // Pulse the ranking panel to draw attention
        setRankingPulse(true);
        setTimeout(() => setRankingPulse(false), 3000);
        
        // Show full-screen celebration only for the winning player
        if (newWinner.player.id === playerData?.playerId) {
          setCelebrationWinner({
            ...newWinner,
            rank,
            isYou: true
          });
          
          // Auto-hide celebration after 4 seconds
          setTimeout(() => {
            setCelebrationWinner(null);
          }, 4000);
        }
      }
      
      playSound('win');
    });

    socket.on('verificationVoteReceived', (data) => {
      // Handle verification vote updates - keeping for future use
    });

    socket.on('gameResumed', (data) => {
      setIsPaused(false);
      
      // Clear any existing resume notifications first
      setToastNotifications(prev => prev.filter(t => 
        !t.message.includes('resumed') && !t.message.includes('Auto-call')
      ));
      
      if (data.resumedBy) {
        addNotification(`Game resumed by ${data.resumedBy}`, 'success', 3000);
        if (data.autoCallResumed) {
          // Add a small delay to prevent notification overlap
          setTimeout(() => {
            addNotification('Auto-call has been resumed', 'info', 2000);
          }, 100);
        }
      } else if (data.gameState === 'playing') {
        // Only show notification if multiple players rejoined (important event)
        if (data.message && data.message.includes('reconnected')) {
          addNotification(data.message, 'success', 3000);
        }
      }
    });

    socket.on('gamePaused', (data) => {
      setIsPaused(true);
      if (data.pausedBy) {
        addNotification(`Game paused by ${data.pausedBy}`, 'warning', 4000);
      } else if (data.message && !data.message.includes('waiting for') && !data.message.includes('minimum')) {
        // Only show notification for important pause events (not frequent disconnects)
        addNotification(data.message, 'warning', 4000);
      }
    });

    // HOST SUPERPOWERS - New socket listeners
    socket.on('playerKicked', (data) => {
      // Check if this player was kicked
      if (data.playerId === playerData?.playerId) {
        addNotification(`You were removed from the game by ${data.kickedBy}`, 'error', 5000);
        // Redirect to home after a short delay
        setTimeout(() => {
          onLeaveRoom();
        }, 2000);
      }
    });

    socket.on('hostTransferred', (data) => {
      if (data.newHost.id === playerData?.playerId) {
        addNotification(`You are now the host!`, 'success', 4000);
      } else {
        addNotification(`${data.newHost.nickname} is now the host`, 'info', 3000);
      }
    });

    socket.on('playerProgressUpdated', (data) => {
      // Update the stored progress for other players
      if (data.playerId !== playerData?.playerId) {
        setPlayerProgress(prev => {
          const newProgress = new Map(prev);
          const playerProgress = newProgress.get(data.playerId) || {};
          playerProgress[data.gameMode] = data.progress;
          newProgress.set(data.playerId, playerProgress);
          return newProgress;
        });
      }
    });

    socket.on('autoCallIntervalChanged', (data) => {
      setAutoCallInterval(data.interval);
      
      // Only show notification if you're the host (you changed it)
      if (playerData?.isHost) {
        const toastId = Date.now();
        setToastNotifications(prev => [...prev, { 
          id: toastId, 
          message: `Auto-call interval set to ${data.interval} seconds`, 
          type: 'success'
        }]);
        
        // Auto-remove toast after 2 seconds
        setTimeout(() => {
          setToastNotifications(prev => prev.filter(t => t.id !== toastId));
        }, 2000);
      }
    });

    // NEW: Multi-mode specific win events - PATTERN COMPLETION
    socket.on('playerWonMode', (data) => {
      // Only show notification if it's the current player who won
      if (data.playerId === playerData?.playerId) {
        // Player themselves won a pattern
        playSound('win');
        
        const toastId = Date.now();
        const patternName = GAME_MODES[data.gameMode]?.name || data.gameMode;
        const rankDisplay = data.modeRank === 1 ? '1st' : data.modeRank === 2 ? '2nd' : '3rd';
        
        // FIXED: Pattern completion notification (not overall ranking)
        setToastNotifications(prev => [...prev, { 
          id: toastId, 
          message: `🎯 You completed ${patternName}!`, 
          type: 'success',
          patternWin: true,
          gameMode: data.gameMode,
          modeRank: data.modeRank
        }]);
        
        // Auto-remove toast after 4 seconds
        setTimeout(() => {
          setToastNotifications(prev => prev.filter(t => t.id !== toastId));
        }, 4000);
      }
      // Don't show notifications for other players winning patterns to reduce spam
    });

    socket.on('multiModeRankingUpdated', (data) => {
      const prevWinnersCount = winners.length;
      const newWinners = data.winners;
      setWinners(newWinners);
      
      // Update winners by mode
      if (data.winnersByMode) {
        setWinnersByMode(data.winnersByMode);
      }
      
      // Update required winners count
      if (data.room?.players) {
        const totalPlayers = data.room.players.length;
        const requiredWinners = totalPlayers === 2 ? 2 : Math.min(3, totalPlayers);
        setRequiredWinners(requiredWinners);
      }
      
      // FIXED: Show celebration ONLY for new OVERALL winner (when someone achieves final rank)
      if (newWinners.length > prevWinnersCount) {
        // Find the actually NEW winner by comparing with previous winners
        // BUG FIX: Don't use newWinners[length-1] because the array is sorted by rank
        const newWinner = newWinners.find(winner => 
          !winners.some(prevWinner => 
            prevWinner.player.id === winner.player.id && 
            prevWinner.gameMode === winner.gameMode
          )
        );
        
        if (!newWinner) {
          console.log('🐛 No new winner found in multiModeRankingUpdated');
          return;
        }
        
        // For multi-mode games, use overallRank (based on host's mode selection order)
        const rank = newWinner.overallRank || newWinners.length;
        
        console.log(`🎊 Multi-mode celebration: Player ${newWinner.player.nickname}, overallRank: ${newWinner.overallRank}, completionOrder: ${newWinner.completionOrder}, using rank: ${rank}`);
        
        // Pulse the ranking panel to draw attention
        setRankingPulse(true);
        setTimeout(() => setRankingPulse(false), 3000);
        
        // Show full-screen celebration only for the winning player (OVERALL final rank achievement)
        if (newWinner.player.id === playerData?.playerId) {
          setCelebrationWinner({
            ...newWinner,
            rank,
            isYou: true,
            isPatternWin: false // This is overall ranking win
          });
          
          // FIXED: Also show ranking notification
          const rankTitle = rank === 1 ? 'Champion 🏆' : rank === 2 ? '2nd Place 🥈' : '3rd Place 🥉';
          const toastId = Date.now();
          setToastNotifications(prev => [...prev, { 
            id: toastId, 
            message: `🎊 You achieved ${rankTitle}!`, 
            type: 'success',
            rank: rank,
            isOverallRanking: true
          }]);
          
          // Auto-remove toast after 5 seconds
          setTimeout(() => {
            setToastNotifications(prev => prev.filter(t => t.id !== toastId));
          }, 5000);
          
          // Auto-hide celebration after 4 seconds
          setTimeout(() => {
            setCelebrationWinner(null);
          }, 4000);
        } else {
          // For other players' overall wins, show a simple notification
          const championTitle = rank === 1 ? 'Champion 🏆' : rank === 2 ? '2nd Place 🥈' : '3rd Place 🥉';
          addNotification(
            `🎊 ${newWinner.player.nickname} achieved ${championTitle}!`,
            'info',
            4000
          );
        }
      }
      
      playSound('win');
    });

    // Handle claim errors
    socket.on('error', (data) => {
      // Show error toast notification
      const toastId = Date.now();
      setToastNotifications(prev => [...prev, { 
        id: toastId, 
        message: data.message, 
        type: 'error'
      }]);
      
      // Auto-remove toast after 5 seconds
      setTimeout(() => {
        setToastNotifications(prev => prev.filter(t => t.id !== toastId));
      }, 5000);
    });

    return () => {
      socket.off('connect');
      socket.off('fullGameSync');
      socket.off('numberCalled');
      socket.off('autoCallToggled');
      socket.off('rankingUpdated');
      socket.off('playerWonMode');
      socket.off('multiModeRankingUpdated');
      socket.off('verificationVoteReceived');
      socket.off('gameResumed');
      socket.off('gamePaused');
      socket.off('playerProgressUpdated');
      socket.off('autoCallIntervalChanged');
      socket.off('error');
      // HOST SUPERPOWERS - cleanup
      socket.off('playerKicked');
      socket.off('hostTransferred');
      socket.off('numberReplayed');
    };
  }, [socket, gameMode]);

  // HOST SUPERPOWERS - Click outside handler for player management dropdown
  useEffect(() => {
    const handleClickOutside = (event) => {
      // Only trigger if the dropdown is actually open and the click is outside
      if (showPlayerManagement && 
          !event.target.closest('.player-management-dropdown') && 
          !event.target.closest('[data-player-management-trigger]')) {
        setShowPlayerManagement(false);
      }
    };

    // Only add listener when dropdown is open
    if (showPlayerManagement) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }
  }, [showPlayerManagement]);

  // Sync local isPaused state with room's gameState and player count
  useEffect(() => {
    if (roomData?.gameState === 'paused' || isGamePausedForPlayers) {
      setIsPaused(true);
    } else if (roomData?.gameState === 'playing' && !isGamePausedForPlayers) {
      setIsPaused(false);
    }
  }, [roomData?.gameState, isGamePausedForPlayers]);

  // Check win condition whenever ticket or called numbers change
  useEffect(() => {
    // In multi-mode games, allow checking for claims even if player has won one mode
    // In single-mode games, don't check if player has already won
    if (localTicket && calledNumbers.length > 0 && (!hasWon || isMultiMode)) {
      if (isMultiMode && activeGameModes && activeGameModes.length > 0) {
        // Check which modes the player can claim wins for
        const newClaimableWins = {};
        let hasAnyClaimableWin = false;
        
        activeGameModes.forEach(mode => {
          const canWin = checkTicketWin(localTicket, mode, calledNumbers);
          const hasAlreadyWonThisMode = winnersByMode[mode]?.some(w => w.player.id === playerData?.playerId);
          const modeAlreadyClaimed = winnersByMode[mode] && winnersByMode[mode].length > 0; // Check if ANY player has claimed this mode
          
          if (canWin && !hasAlreadyWonThisMode && !modeAlreadyClaimed) {
            newClaimableWins[mode] = true;
            hasAnyClaimableWin = true;
          }
        });
        
        setClaimableWins(newClaimableWins);
        setCanClaimWin(hasAnyClaimableWin);
      } else if (gameMode) {
        // Single mode win checking
        const canWin = checkTicketWin(localTicket, gameMode, calledNumbers);
        setCanClaimWin(canWin);
      }
    } else {
      setCanClaimWin(false);
      setClaimableWins({});
    }
  }, [localTicket, calledNumbers, gameMode, hasWon, isMultiMode, activeGameModes, winnersByMode, playerData?.playerId]);

  // Calculate initial required winners based on room data
  useEffect(() => {
    if (roomData?.players) {
      const totalPlayers = roomData.players.length;
      const initialRequiredWinners = totalPlayers === 2 ? 2 : Math.min(3, totalPlayers);
      setRequiredWinners(initialRequiredWinners);
    }
  }, [roomData?.players?.length]);

  const handleMarkNumber = (number, rowIndex, colIndex, shouldMark) => {
    if (!localTicket) return;
    
    // In multi-mode games, allow marking even if player has won one mode (they can still compete for others)
    // In single-mode games, prevent marking if player has already won
    if (!isMultiMode && hasWon) return;
    
    // Only allow marking, not unmarking
    if (!shouldMark) return;
    
    // Create a new ticket with the updated marking for immediate UI feedback
    const newTicket = localTicket.map((row, rIdx) =>
      row.map((cell, cIdx) => {
        if (rIdx === rowIndex && cIdx === colIndex) {
          if (cell === null) return null;
          const cellNumber = typeof cell === 'object' ? cell.number : cell;
          if (cellNumber === number) {
            return { number, marked: true };
          }
        }
        return cell;
      })
    );
    
    setLocalTicket(newTicket);
    
    // Send the manual marking to server
    if (socket) {
      socket.emit('manualMark', {
        number,
        rowIndex,
        colIndex,
        marked: true
      });
    }
    
    // Check win condition after manual marking
    if (isMultiMode && activeGameModes && activeGameModes.length > 0) {
      // Check each active game mode
      const newClaimableWins = {};
      let hasAnyClaimableWin = false;
      
      activeGameModes.forEach(mode => {
        const canWin = checkTicketWin(newTicket, mode, calledNumbers);
        const hasAlreadyWonThisMode = winnersByMode[mode]?.some(w => w.player.id === playerData?.playerId);
        const modeAlreadyClaimed = winnersByMode[mode] && winnersByMode[mode].length > 0; // Check if ANY player has claimed this mode
        
        if (canWin && !hasAlreadyWonThisMode && !modeAlreadyClaimed) {
          newClaimableWins[mode] = true;
          hasAnyClaimableWin = true;
        }
      });
      
      setClaimableWins(newClaimableWins);
      setCanClaimWin(hasAnyClaimableWin);
    } else if (gameMode) {
      const canWin = checkTicketWin(newTicket, gameMode, calledNumbers);
      setCanClaimWin(canWin);
    }
    
    // Update and broadcast player progress
    if (socket && playerData) {
      if (isMultiMode && activeGameModes && activeGameModes.length > 0) {
        // Send progress for each active game mode
        activeGameModes.forEach(mode => {
          const progress = calculatePlayerProgress(newTicket, mode, calledNumbers);
          socket.emit('updatePlayerProgress', {
            playerId: playerData.playerId,
            gameMode: mode,
            progress
          });
        });
      } else if (gameMode) {
        const progress = calculatePlayerProgress(newTicket, gameMode, calledNumbers);
        socket.emit('updatePlayerProgress', {
          playerId: playerData.playerId,
          gameMode: gameMode,
          progress
        });
      }
    }
  };

  const copyRoomCode = async () => {
    try {
      await navigator.clipboard.writeText(roomData?.code || '');
      setShowRoomCode(true);
      setTimeout(() => setShowRoomCode(false), 2000);
    } catch (err) {
      // Fallback for older browsers
      const textArea = document.createElement('textarea');
      textArea.value = roomData?.code || '';
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      setShowRoomCode(true);
      setTimeout(() => setShowRoomCode(false), 2000);
    }
  };

  const announceCurrentNumber = () => {
    if (currentNumber) {
      playSound('number');
      // Try to use speech synthesis if available
      if ('speechSynthesis' in window) {
        const utterance = new SpeechSynthesisUtterance(`${currentNumber}`);
        utterance.rate = 0.8;
        utterance.volume = 0.7;
        window.speechSynthesis.speak(utterance);
      }
    }
  };

  const handleCallNumber = () => {
    if (socket && isHost) {
      socket.emit('callNumber');
    }
  };

  const handleToggleAutoCall = () => {
    if (socket && isHost) {
      socket.emit('toggleAutoCall');
    }
  };

  const handleClaimWin = (specificMode = null) => {
    if (socket && canClaimWin) {
      if (isMultiMode && specificMode) {
        // Claim win for specific mode in multi-mode game
        socket.emit('claimWinForMode', { gameMode: specificMode });
        playSound('win');
      } else {
        // Traditional single-mode claim or claim all available in multi-mode
        socket.emit('claimWin');
        playSound('win');
      }
    }
  };

  // NEW: Helper function to claim win for specific mode
  const handleClaimModeWin = (gameMode) => {
    if (socket && claimableWins[gameMode]) {
      socket.emit('claimWinForMode', { gameMode });
      playSound('win');
    }
  };

  const handleSetAutoCallInterval = (seconds) => {
    if (socket && isHost && seconds >= 5 && seconds <= 60) {
      socket.emit('setAutoCallInterval', { seconds });
      setShowIntervalSetting(false);
    }
  };

  // HOST SUPERPOWERS - New handler functions
  const handlePauseGame = () => {
    if (socket && isHost && !hostActionLoading) {
      setHostActionLoading(true);
      socket.emit('pauseGame');
      setTimeout(() => setHostActionLoading(false), 1000);
    }
  };

  const handleResumeGame = () => {
    if (socket && isHost && !hostActionLoading) {
      // Check if there are enough players to resume
      if (connectedPlayersCount < 2) {
        addNotification('Cannot resume - need at least 2 players connected', 'error', 3000);
        return;
      }
      setHostActionLoading(true);
      socket.emit('resumeGame');
      setTimeout(() => setHostActionLoading(false), 1000);
    }
  };

  const handleKickPlayer = (playerId) => {
    if (socket && isHost && playerId && !hostActionLoading) {
      setHostActionLoading(true);
      socket.emit('kickPlayer', { targetPlayerId: playerId });
      setShowKickConfirm(false);
      setSelectedPlayerToKick(null);
      setTimeout(() => setHostActionLoading(false), 1000);
    }
  };

  const handleTransferHost = (playerId) => {
    if (socket && isHost && playerId && !hostActionLoading) {
      setHostActionLoading(true);
      socket.emit('transferHost', { targetPlayerId: playerId });
      setShowTransferHost(false);
      setSelectedPlayerForHost(null);
      setTimeout(() => setHostActionLoading(false), 1000);
    }
  };

  const openKickConfirmation = (player) => {
    setSelectedPlayerToKick(player);
    setShowKickConfirm(true);
    setShowPlayerManagement(false);
  };

  const openTransferHostDialog = () => {
    setShowTransferHost(true);
    setShowPlayerManagement(false);
  };

  const confirmKickPlayer = () => {
    if (!selectedPlayerToKick || !socket) return;
    
    setHostActionLoading(true);
    socket.emit('kickPlayer', { targetPlayerId: selectedPlayerToKick.id });
    
    setTimeout(() => {
      setHostActionLoading(false);
      setShowKickConfirm(false);
      setSelectedPlayerToKick(null);
    }, 1000);
  };

  const confirmTransferHost = () => {
    if (!selectedPlayerForHost || !socket) return;
    
    setHostActionLoading(true);
    socket.emit('transferHost', { targetPlayerId: selectedPlayerForHost });
    
    setTimeout(() => {
      setHostActionLoading(false);
      setShowTransferHost(false);
      setSelectedPlayerForHost(null);
    }, 1000);
  };
  
  return (
    <div className="p-2 sm:p-4 landscape-game-container py-4">
      {/* Chat Component - Now modal-based, no layout impact */}
      <Chat 
        socket={socket}
        playerData={playerData}
        roomData={roomData}
        isGameMode={true}
      />
      
      <div className="landscape-main-container max-w-none sm:max-w-7xl mx-auto px-2 sm:px-4">
        {/* Mobile-First Current Number Header - Optimized height for better toast positioning */}
        <div className="sticky-game-header sticky top-0 z-50 text-white p-2 sm:p-3 rounded-xl shadow-2xl mb-3 sm:mb-4 landscape-spacing" style={{
          background: 'linear-gradient(135deg, #FEA37E 0%, #FFE083 50%, #88D8DA 100%)',
          border: '3px solid #ffd700'
        }}>
          <div className="flex items-center justify-between flex-wrap gap-2 landscape-header-content">
            <div className="flex items-center gap-2 sm:gap-3 min-w-0">
              <div className="text-sm sm:text-lg md:text-xl font-bold truncate">
                Room: {roomData?.code}
              </div>
              <button
                onClick={copyRoomCode}
                className="bg-white/20 hover:bg-white/30 p-1 sm:p-1.5 rounded-full transition-colors flex-shrink-0"
                title="Copy room code"
              >
                <Copy className="w-3 h-3 sm:w-4 sm:h-4" />
              </button>
              
              {/* Connection Status Indicator */}
              <div className="flex items-center gap-1 text-xs sm:text-sm">
                <div 
                  className={`w-2 h-2 rounded-full ${
                    !isConnected 
                      ? 'bg-red-400' 
                      : connectionHealth === 'good' 
                        ? 'bg-green-400' 
                        : connectionHealth === 'fair' 
                          ? 'bg-yellow-400' 
                          : 'bg-orange-400'
                  } ${isConnected && connectionHealth === 'good' ? 'animate-pulse' : ''}`}
                  title={`Connection: ${isConnected ? connectionHealth : 'disconnected'}`}
                />
                {!isConnected && reconnectAttempts > 0 && (
                  <span className="text-xs opacity-90">
                    Reconnecting... ({reconnectAttempts}/5)
                  </span>
                )}
                {isConnected && connectionHealth !== 'good' && (
                  <span className="text-xs opacity-90 hidden sm:inline">
                    {connectionHealth}
                  </span>
                )}
              </div>
            </div>
            
            {/* View Results button for ended games */}
            {roomData?.gameState === 'ended' && winners.length > 0 && onShowResults && (
              <button
                onClick={onShowResults}
                className="bg-white/20 hover:bg-white/30 px-3 py-1.5 rounded-lg text-xs sm:text-sm font-medium transition-colors flex items-center gap-1"
                title="View final results"
              >
                <Trophy className="w-3 h-3 sm:w-4 sm:h-4" />
                <span className="hidden sm:inline">View Results</span>
                <span className="sm:hidden">Results</span>
              </button>
            )}
            
            {showRoomCode && (
              <span className="text-xs bg-green-500 px-2 py-1 rounded text-white animate-pulse flex-shrink-0">
                Copied!
              </span>
            )}
            
            {currentNumber && (
              <div className="flex items-center gap-1 sm:gap-2 flex-shrink-0">
                <button
                  onClick={announceCurrentNumber}
                  className="bg-white/20 hover:bg-white/30 p-1.5 sm:p-2 rounded-full transition-colors"
                  title="Repeat current number"
                >
                  <Volume2 className="w-3 h-3 sm:w-4 sm:h-4" />
                </button>
                <div className="text-right">
                  <div className="text-xs sm:text-sm opacity-90">Current Number</div>
                  <div className="text-xl sm:text-2xl md:text-3xl font-bold animate-pulse">
                    {currentNumber}
                  </div>
                </div>
              </div>
            )}
            
            {!currentNumber && (
              <div className="text-right flex-shrink-0">
                <div className="text-xs sm:text-sm opacity-90">Ready to Start</div>
                <div className="text-sm sm:text-lg font-semibold truncate">
                  {isMultiMode ? 'Multi-Mode Game' : (GAME_MODES[gameMode]?.name || gameMode)}
                </div>
              </div>
            )}
          </div>
          
          {/* Last few numbers for reference - Better mobile layout */}
          {calledNumbers.length > 0 && (
            <div className="mt-2 pt-2 border-t border-white/20">
              <div className="text-xs opacity-75 mb-1">Recent:</div>
              <div className="flex gap-1 flex-wrap">
                {calledNumbers.slice(-6).map((num, index) => (
                  <span
                    key={index}
                    className="bg-white/20 px-1.5 sm:px-2 py-1 rounded text-xs flex-shrink-0"
                  >
                    {num}
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Header with improved Leave button */}
        <div className="flex items-center justify-between mb-4 sm:mb-6">
          <button
            onClick={onLeaveRoom}
            className="flex items-center gap-2 px-4 py-2 rounded-full font-bold text-white shadow-lg hover:shadow-xl transition-all duration-200 transform hover:scale-105"
            style={{
              background: 'linear-gradient(135deg, #ff69b4 0%, #9370db 100%)',
              border: '3px solid #ffd700'
            }}
          >
            <ArrowLeft className="w-4 h-4" />
            Leave
            {winners.length > 0 && (
              <span className="ml-2 bg-yellow-500 text-purple-700 text-xs px-2 py-1 rounded-full font-bold">
                Rankings Saved
              </span>
            )}
          </button>

          {/* Page indicator like in the image with stars */}
          <div className="flex items-center gap-2 px-4 py-2 rounded-full font-bold text-white shadow-lg" style={{
            background: 'linear-gradient(135deg, #9370db 0%, #dda0dd 100%)',
            border: '2px solid #ffd700'
          }}>
            <span style={{ fontSize: '16px' }}>⭐</span>
            <div className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center">
              <div className="w-3 h-3 rounded-full bg-white" />
            </div>
            <span className="text-sm">
              {winners.length}/{requiredWinners}
            </span>
            <span style={{ fontSize: '16px' }}>⭐</span>
          </div>

          <div className="text-center">
            <h1 className="text-xl sm:text-2xl font-bold text-gray-800">
              {isMultiMode ? 'Multi-Mode Tambola' : (GAME_MODES[gameMode]?.name || 'Tambola Game')}
            </h1>
            <p className="text-gray-600 text-xs sm:text-sm">
              {isMultiMode 
                ? `Playing: ${(activeGameModes || []).map(mode => GAME_MODES[mode]?.name).join(', ')}`
                : GAME_MODES[gameMode]?.description
              }
            </p>
            {/* Multi-mode winner count display */}
            {isMultiMode ? (
              <div className="mt-2 flex justify-center gap-2 flex-wrap">
                {(activeGameModes || []).map((mode, index) => {
                  const modeWinners = winnersByMode[mode] || [];
                  const rankDisplay = index === 0 ? '1st' : index === 1 ? '2nd' : '3rd';
                  return (
                    <div key={mode} className="inline-block bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full font-medium">
                      {GAME_MODES[mode]?.icon} {rankDisplay}: {modeWinners.length > 0 ? `✅ ${modeWinners[0]?.player.nickname}` : 'Available'}
                    </div>
                  );
                })}
              </div>
            ) : winners.length > 0 && (
              <div className="mt-2 inline-block bg-warning-100 text-warning-800 text-xs px-3 py-1 rounded-full font-medium">
                🏆 {winners.length}/{requiredWinners} Winners Found
              </div>
            )}
          </div>

          <div className="flex items-center gap-2 text-xs sm:text-sm text-gray-600">
            <Users className="w-3 h-3 sm:w-4 sm:h-4" />
            <span>
              {roomData?.players?.filter(p => p.isConnected).length || 0}/
              {roomData?.players?.length || 0} Players Connected
            </span>
            {winners.length > 0 && (
              <span className="ml-2 text-warning-600 font-medium">
                • {(() => {
                  const connectedCount = roomData?.players?.filter(p => p.isConnected).length || 0;
                  if (isMultiMode) {
                    // In multi-mode: A player is only inactive when ALL patterns are complete
                    // Check if all patterns are completed (all activeGameModes have winners)
                    const allPatternsComplete = activeGameModes?.every(mode => 
                      winnersByMode[mode] && winnersByMode[mode].length > 0
                    ) || false;
                    
                    if (allPatternsComplete) {
                      // Game is complete, no one is active anymore
                      const activeCount = 0;
                      console.log(`🎯 Multi-mode: All patterns complete - ${activeCount} active`);
                      return activeCount;
                    } else {
                      // Game is ongoing, all connected players are still active
                      const completedPatterns = Object.keys(winnersByMode || {}).filter(mode => winnersByMode[mode]?.length > 0).length;
                      const totalPatterns = activeGameModes?.length || 0;
                      const activeCount = connectedCount;
                      console.log(`🎯 Multi-mode: Game ongoing - ${activeCount} active (${completedPatterns}/${totalPatterns} patterns complete)`);
                      return activeCount;
                    }
                  } else {
                    // In single-mode: Active = connected players minus overall winners
                    const activeCount = Math.max(0, connectedCount - winners.length);
                    console.log(`🎯 Single-mode active count: ${connectedCount} connected - ${winners.length} winners = ${activeCount} active`);
                    return activeCount;
                  }
                })()} Active
              </span>
            )}
          </div>
        </div>

        {/* Game State Indicator - Better mobile spacing */}
        {(roomData?.gameState === 'paused' || isGamePausedForPlayers) && (
          <div className="card p-3 sm:p-4 mb-4 sm:mb-6 bg-gradient-to-r from-amber-50 to-orange-50 border-2 border-amber-300">
            <div className="flex items-center justify-center gap-2 sm:gap-3 text-amber-800">
              <Pause className="w-4 h-4 sm:w-5 sm:h-5 animate-pulse flex-shrink-0" />
              <div className="text-center min-w-0">
                <div className="font-semibold text-sm sm:text-base">
                  {roomData?.gameState === 'paused' ? 'Game Paused' : 'Waiting for Players'}
                </div>
                <div className="text-xs sm:text-sm opacity-75">
                  {roomData?.gameState === 'paused' 
                    ? 'Waiting for host to resume...' 
                    : connectedPlayersCount < 2 
                      ? 'Waiting for players to reconnect or join...'
                      : 'Waiting for players to reconnect...'
                  }
                </div>
              </div>
              <Pause className="w-4 h-4 sm:w-5 sm:h-5 animate-pulse flex-shrink-0" />
            </div>
          </div>
        )}

        {/* Host Controls */}
        {isHost && (
          <div className="card p-3 sm:p-4 mb-4 sm:mb-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Crown className="w-5 h-5 text-warning-600" />
                <span className="font-medium text-gray-800">Host Controls</span>
              </div>
              
              <div className="flex flex-wrap items-center gap-3">
                {/* Auto Call Interval Setting */}
                {showIntervalSetting && (
                  <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div className="bg-white rounded-lg p-6 max-w-sm w-full mx-4">
                      <h3 className="text-lg font-semibold mb-4">Set Auto-Call Interval</h3>
                      <div className="space-y-4">
                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-2">
                            Interval (seconds): {autoCallInterval}s
                          </label>
                          <input
                            type="range"
                            min="5"
                            max="60"
                            step="1"
                            value={autoCallInterval}
                            onChange={(e) => setAutoCallInterval(Number(e.target.value))}
                            className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
                          />
                          <div className="flex justify-between text-xs text-gray-500 mt-1">
                            <span>5s</span>
                            <span>60s</span>
                          </div>
                        </div>
                        <div className="flex gap-3">
                          <button
                            onClick={() => handleSetAutoCallInterval(autoCallInterval)}
                            className="btn-primary flex-1"
                          >
                            Set Interval
                          </button>
                          <button
                            onClick={() => setShowIntervalSetting(false)}
                            className="btn-secondary flex-1"
                          >
                            Cancel
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {/* Pause/Resume Game Button - Only show during active game */}
                {(roomData?.gameState === 'playing' || roomData?.gameState === 'paused') && (
                  <button
                    onClick={isPaused ? handleResumeGame : handlePauseGame}
                    disabled={hostActionLoading || (isPaused && connectedPlayersCount < 2)}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-all disabled:opacity-50 ${
                      isPaused
                        ? 'bg-green-100 text-green-800 hover:bg-green-200'
                        : 'bg-red-100 text-red-800 hover:bg-red-200'
                    }`}
                    title={
                      isPaused 
                        ? (connectedPlayersCount < 2 ? 'Need at least 2 players to resume' : 'Resume game')
                        : 'Pause game'
                    }
                  >
                    {hostActionLoading ? (
                      <div className="w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />
                    ) : isPaused ? (
                      <Play className="w-4 h-4" />
                    ) : (
                      <Pause className="w-4 h-4" />
                    )}
                    {isPaused ? 'Resume' : 'Pause'}
                  </button>
                )}

                {/* Player Management Dropdown */}
                <div className="relative">
                  <button
                    onClick={() => setShowPlayerManagement(!showPlayerManagement)}
                    data-player-management-trigger="true"
                    className="flex items-center gap-2 px-3 py-2 rounded-lg font-medium transition-colors bg-gray-100 text-gray-700 hover:bg-gray-200 text-sm"
                    title="Manage players"
                  >
                    <Users className="w-4 h-4" />
                    Manage
                  </button>
                  
                  {showPlayerManagement && (
                    <div className="absolute top-full left-0 mt-2 bg-white rounded-lg shadow-lg border border-gray-200 z-50 min-w-48 player-management-dropdown">
                      <div className="p-2">
                        <button
                          onClick={openTransferHostDialog}
                          className="w-full flex items-center gap-2 px-3 py-2 text-left text-sm text-gray-700 hover:bg-gray-100 rounded"
                        >
                          <Crown className="w-4 h-4" />
                          Transfer Host
                        </button>
                        <div className="border-t border-gray-100 my-1"></div>
                        <div className="text-xs text-gray-500 px-3 py-1 font-medium">Kick Players:</div>
                        {roomData?.players?.filter(p => p.id !== playerData?.playerId && p.isConnected).map(player => (
                          <button
                            key={player.id}
                            onClick={() => openKickConfirmation(player)}
                            className="w-full flex items-center gap-2 px-3 py-2 text-left text-sm text-red-600 hover:bg-red-50 rounded"
                          >
                            <UserMinus className="w-4 h-4" />
                            {player.nickname}
                          </button>
                        ))}
                      </div>
                    </div>
                  )}
                </div>

                <button
                  onClick={() => setShowIntervalSetting(true)}
                  className="flex items-center gap-2 px-3 py-2 rounded-lg font-medium transition-all bg-gray-100 text-gray-700 hover:bg-gray-200 text-sm"
                  title="Set auto-call interval"
                >
                  ⚙️ {autoCallInterval}s
                </button>
                
                <button
                  onClick={handleToggleAutoCall}
                  disabled={isPaused}
                  className={`flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-all disabled:opacity-50 ${
                    autoCall
                      ? 'bg-warning-100 text-warning-800 hover:bg-warning-200'
                      : 'bg-primary-100 text-primary-800 hover:bg-primary-200'
                  }`}
                >
                  {autoCall ? (
                    <>
                      <Pause className="w-4 h-4" />
                      Stop Auto Call
                    </>
                  ) : (
                    <>
                      <Play className="w-4 h-4" />
                      Auto Call ({autoCallInterval}s)
                    </>
                  )}
                </button>
                
                <button
                  onClick={handleCallNumber}
                  disabled={autoCall || isPaused}
                  className="btn-primary flex items-center gap-2 disabled:opacity-50"
                >
                  <Phone className="w-4 h-4" />
                  Call Number
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Enhanced Winners Ranking Panel - Now at top for better visibility */}
        {winners.length > 0 && (
          <div className="card p-4 mb-6 bg-gradient-to-r from-yellow-50 via-amber-50 to-orange-50 border-2 border-warning-300 shadow-xl">
            <div className="flex items-center justify-center mb-4">
              <h2 className="text-xl font-bold text-gray-800 flex items-center gap-3">
                <Trophy className="w-6 h-6 text-warning-600 animate-pulse" />
                🏆 Live Rankings - {winners.length}/{requiredWinners} Winners Found
                <Trophy className="w-6 h-6 text-warning-600 animate-pulse" />
              </h2>
            </div>
            
            <div className="mb-4 text-center">
              <div className="inline-block bg-white/70 rounded-full px-4 py-2 text-sm font-medium text-gray-700 shadow-sm">
                🎯 {Math.max(0, requiredWinners - winners.length)} more winner{requiredWinners - winners.length !== 1 ? 's' : ''} needed
              </div>
            </div>
            
            <div className={`grid gap-4 ${
              requiredWinners === 2 ? 'md:grid-cols-2' : 'md:grid-cols-3'
            }`}>
              {/* Show dynamic podium positions based on required winners */}
              {Array.from({ length: requiredWinners }, (_, position) => {
                // FIXED: For multi-mode games, use ONLY overallRank (host's intended rank)
                // For single-mode games, use completion order fallback
                const targetRank = position + 1; // position 0 = rank 1, position 1 = rank 2, etc.
                
                // Debug logging for multi-mode games
                if (isMultiMode && winners.length > 0) {
                  console.log(`🏆 Looking for rank ${targetRank} winner:`, 
                    winners.map(w => `${w.player.nickname}: overallRank=${w.overallRank}, completionOrder=${w.completionOrder}, gameMode=${w.gameMode}`)
                  );
                }
                
                const winner = winners.find(w => {
                  // In multi-mode games, use only overallRank to avoid duplicates
                  if (isMultiMode) {
                    return w.overallRank === targetRank;
                  } else {
                    // In single-mode games, use completion order or fallback to array index
                    return (w.completionOrder === targetRank) || 
                           (w.overallRank === targetRank) || 
                           (!w.completionOrder && !w.overallRank && position === winners.indexOf(w));
                  }
                });
                const isOccupied = !!winner;
                
                return (
                  <div
                    key={position}
                    className={`relative p-4 rounded-xl border-2 transition-all duration-300 ${
                      isOccupied 
                        ? winner.player.id === playerData?.playerId
                          ? 'bg-gradient-to-br from-orange-100 to-orange-200 border-orange-400 shadow-lg transform scale-105'
                          : 'bg-gradient-to-br from-white to-gray-50 border-gray-300 shadow-md'
                        : 'bg-gradient-to-br from-gray-100 to-gray-200 border-gray-300 border-dashed opacity-75'
                    }`}
                  >
                    {/* Position indicator */}
                    <div className={`w-12 h-12 rounded-full mx-auto mb-3 flex items-center justify-center text-lg font-bold text-white shadow-lg ${
                      position === 0 ? 'bg-gradient-to-r from-orange-400 to-orange-600' : 
                      position === 1 ? 'bg-gradient-to-r from-primary-400 to-primary-600' : 
                      'bg-gradient-to-r from-fun-500 to-fun-700'
                    }`}>
                      {position + 1}
                    </div>
                    
                    {/* Medal */}
                    <div className="text-center text-3xl mb-2">
                      {position === 0 ? '🥇' : position === 1 ? '🥈' : '🥉'}
                    </div>
                    
                    {/* Winner info or placeholder */}
                    <div className="text-center">
                      {isOccupied ? (
                        <>
                          <div className={`font-bold text-lg ${
                            winner.player.id === playerData?.playerId ? 'text-warning-800' : 'text-gray-800'
                          }`}>
                            {winner.player.nickname}
                            {winner.player.id === playerData?.playerId && (
                              <div className="text-warning-600 text-sm font-medium mt-1">
                                (You!) 🎉
                              </div>
                            )}
                          </div>
                          {/* Show the game mode that was won */}
                          {winner.gameMode && (
                            <div className="text-xs text-gray-600 mt-1 mb-1">
                              <span className="text-lg mr-1">{GAME_MODES[winner.gameMode]?.icon}</span>
                              {GAME_MODES[winner.gameMode]?.name}
                            </div>
                          )}
                          <div className="text-xs text-gray-600 mt-1">
                            {new Date(winner.timestamp).toLocaleTimeString()}
                          </div>
                        </>
                      ) : (
                        <div className="text-gray-500 text-sm font-medium">
                          {position === 0 ? '1st Place' : 
                           position === 1 ? '2nd Place' : 
                           '3rd Place'}
                          <div className="text-xs mt-1">Available</div>
                        </div>
                      )}
                    </div>
                    
                    {/* Special effects for player's own position */}
                    {isOccupied && winner.player.id === playerData?.playerId && (
                      <div className="absolute -top-1 -right-1 bg-warning-500 text-white text-xs px-2 py-1 rounded-full font-bold shadow-md animate-bounce">
                        YOU!
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        )}

        <div className="grid landscape-responsive-grid gap-4 sm:gap-6 landscape-grid">
          {/* Left Column - Player's Ticket */}
          <div className="landscape-ticket-column space-y-4 sm:space-y-6 landscape-spacing">
            {localTicket && (
              <div className="landscape-ticket-container">
                <Ticket 
                  ticket={localTicket}
                  gameMode={isMultiMode ? (activeGameModes || []) : gameMode}
                  activeGameModes={activeGameModes}
                  isMultiMode={isMultiMode}
                  playerId={playerData?.playerId}
                  currentPlayer={playerData?.playerId}
                  calledNumbers={calledNumbers}
                  winnersByMode={winnersByMode}
                  onMarkNumber={handleMarkNumber}
                />
              </div>
            )}

            {/* Claim Win Button or Winner Status */}
            {hasWon ? (
              <div className="card p-4 bg-gradient-to-r from-warning-50 to-yellow-50 border-warning-200 shadow-lg">
                <div className="text-center">
                  <div className="text-warning-700 font-bold text-lg mb-2">
                    🎉 Congratulations! You've Won! 🎉
                  </div>
                  <div className="text-sm text-gray-600">
                    Continue watching others compete for remaining positions
                  </div>
                  <div className="mt-3 text-xs text-warning-600 font-medium">
                    Your position is secured in the rankings above ⬆️
                  </div>
                </div>
              </div>
            ) : canClaimWin ? (
              <div className="card p-4 bg-gradient-to-r from-success-50 to-green-50 border-success-200 shadow-lg">
                <div className="text-center">
                  <div className="text-success-700 font-bold text-lg mb-3">
                    🎉 You can claim win{isMultiMode && Object.keys(claimableWins).length > 1 ? 's' : ''}! 🎉
                  </div>
                  
                  {isMultiMode ? (
                    /* Multi-mode claim buttons */
                    <div className="space-y-2">
                      {Object.entries(claimableWins).map(([mode, canClaim]) => {
                        if (!canClaim) return null;
                        const modeIndex = activeGameModes?.indexOf(mode) || 0;
                        const rankDisplay = modeIndex === 0 ? '1st' : modeIndex === 1 ? '2nd' : '3rd';
                        return (
                          <button
                            key={mode}
                            onClick={() => handleClaimModeWin(mode)}
                            className={`btn-success flex items-center gap-2 mx-auto animate-pulse text-sm px-6 py-2 ${
                              modeIndex === 0 ? 'bg-yellow-600 hover:bg-yellow-700' :
                              modeIndex === 1 ? 'bg-gray-600 hover:bg-gray-700' :
                              'bg-amber-600 hover:bg-amber-700'
                            }`}
                          >
                            <Trophy className="w-4 h-4" />
                            <span className="text-lg">{GAME_MODES[mode]?.icon}</span>
                            Claim {GAME_MODES[mode]?.name} ({rankDisplay} Place)!
                          </button>
                        );
                      })}
                    </div>
                  ) : (
                    /* Single-mode claim button */
                    <button
                      onClick={handleClaimWin}
                      className="btn-success flex items-center gap-2 mx-auto animate-pulse text-lg px-8 py-3"
                    >
                      <Trophy className="w-5 h-5" />
                      Claim Win Now!
                    </button>
                  )}
                </div>
              </div>
            ) : null}

            {/* Enhanced Players List with Rankings */}
            <div className="card p-4 landscape-controls" style={{
              background: 'linear-gradient(145deg, #fff8dc 0%, #fffacd 100%)',
              border: '3px solid #ffd700',
              borderRadius: '20px',
              boxShadow: '0 8px 32px rgba(0, 0, 0, 0.15)'
            }}>
              <h3 className="font-bold mb-3 flex items-center gap-2" style={{ color: '#4169e1' }}>
                <Users className="w-4 h-4" />
                Players Status
              </h3>
              <div className="space-y-3 landscape-players-list">{roomData?.players?.map((player) => {
                  // In multi-mode: Only count as overall winner if player won ALL active modes
                  // In single-mode: Count as winner if in winners array
                  let hasWonOverall = false;
                  let rank = null;
                  
                  if (isMultiMode && activeGameModes && winnersByMode) {
                    // Check if player has won ALL active game modes
                    const hasWonAllModes = activeGameModes.every(mode => 
                      winnersByMode[mode] && winnersByMode[mode].find(w => w.player.id === player.id)
                    );
                    
                    if (hasWonAllModes) {
                      // Find their overall rank based on when they completed all modes
                      const overallWinners = winners.filter(w => {
                        return activeGameModes.every(mode => 
                          winnersByMode[mode] && winnersByMode[mode].find(mw => mw.player.id === w.player.id)
                        );
                      });
                      const winnerInfo = overallWinners.find(w => w.player.id === player.id);
                      hasWonOverall = !!winnerInfo;
                      rank = winnerInfo ? overallWinners.findIndex(w => w.player.id === player.id) + 1 : null;
                    }
                  } else {
                    // Single mode: Use existing logic
                    const winnerInfo = winners.find(w => w.player.id === player.id);
                    hasWonOverall = !!winnerInfo;
                    rank = winnerInfo ? winners.findIndex(w => w.player.id === player.id) + 1 : null;
                  }
                  
                  // In multimode, check if player has won any individual patterns but not overall
                  let hasWonAnyPattern = false;
                  let wonPatterns = [];
                  if (isMultiMode && winnersByMode) {
                    Object.entries(winnersByMode).forEach(([mode, modeWinners]) => {
                      if (modeWinners && modeWinners.find(w => w.player.id === player.id)) {
                        hasWonAnyPattern = true;
                        wonPatterns.push(mode);
                      }
                    });
                  }
                  
                  // Calculate progress for this player
                  let allProgress = {};
                  if (player.id === playerData?.playerId) {
                    // For current player, calculate from their local ticket
                    if (isMultiMode && activeGameModes && activeGameModes.length > 0) {
                      // Calculate progress for all active game modes
                      activeGameModes.forEach(mode => {
                        allProgress[mode] = calculatePlayerProgress(localTicket, mode, calledNumbers);
                      });
                    } else {
                      allProgress[gameMode] = calculatePlayerProgress(localTicket, gameMode, calledNumbers);
                    }
                  } else {
                    // For other players, use stored progress data
                    const playerProgressData = playerProgress.get(player.id) || {};
                    if (isMultiMode && activeGameModes && activeGameModes.length > 0) {
                      // Get progress for all active game modes
                      activeGameModes.forEach(mode => {
                        allProgress[mode] = playerProgressData[mode] || { marked: 0, total: 0, percentage: 0 };
                      });
                    } else {
                      allProgress[gameMode] = playerProgressData[gameMode] || { marked: 0, total: 0, percentage: 0 };
                    }
                  }
                  
                  return (
                    <div
                      key={player.id}
                      className={`text-sm p-4 rounded-xl transition-all shadow-lg ${
                        hasWonOverall 
                          ? 'border-3 border-yellow-400' 
                          : hasWonAnyPattern 
                          ? 'border-3 border-green-400'
                          : 'border-3 border-purple-400'
                      }`}
                      style={{
                        background: player.id === playerData?.playerId 
                          ? 'linear-gradient(145deg, #ffebcd 0%, #ffeaa7 100%)'
                          : hasWonOverall 
                          ? 'linear-gradient(145deg, #fff8dc 0%, #fffacd 100%)'
                          : 'linear-gradient(145deg, #e6e6fa 0%, #dda0dd 100%)',
                        boxShadow: '0 4px 15px rgba(0, 0, 0, 0.1)'
                      }}
                    >
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center gap-3">
                          {/* Player Avatar Circle */}
                          <div className={`w-10 h-10 rounded-full flex items-center justify-center font-bold text-white text-lg ${
                            player.id === playerData?.playerId 
                              ? 'bg-gradient-to-r from-orange-400 to-orange-600'
                              : hasWonOverall 
                              ? 'bg-gradient-to-r from-yellow-400 to-yellow-600'
                              : 'bg-gradient-to-r from-purple-400 to-purple-600'
                          }`} style={{
                            border: '3px solid #ffd700',
                            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.2)'
                          }}>
                            {player.nickname.charAt(0).toUpperCase()}
                          </div>
                          
                          {/* Winner rank indicator */}
                          {hasWonOverall && (
                            <div className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white ${
                              rank === 1 ? 'bg-yellow-500' : 
                              rank === 2 ? 'bg-gray-400' : 
                              'bg-amber-600'
                            }`} style={{
                              border: '2px solid #ffd700',
                              boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)'
                            }}>
                              {rank}
                            </div>
                          )}
                          
                          {/* Show small indicators for won patterns in multimode */}
                          {!hasWonOverall && hasWonAnyPattern && isMultiMode && (
                            <div className="flex gap-1">
                              {wonPatterns.map((pattern, idx) => (
                                <div 
                                  key={pattern}
                                  className="w-4 h-4 rounded-full bg-green-500 text-white text-xs flex items-center justify-center font-bold"
                                  title={`Won ${GAME_MODES[pattern]?.name}`}
                                  style={{ border: '1px solid #ffd700' }}
                                >
                                  {idx + 1}
                                </div>
                              ))}
                            </div>
                          )}
                          
                          <div>
                            <span className={`font-bold ${
                              player.id === playerData?.playerId 
                                ? 'text-orange-700' 
                                : hasWonOverall 
                                ? 'text-yellow-700'
                                : hasWonAnyPattern
                                ? 'text-green-700'
                                : 'text-purple-700'
                            }`}>
                              {player.nickname}
                              {player.id === playerData?.playerId && ' (You)'}
                              {hasWonOverall && (
                                <span className="ml-1 text-xs">
                                  {rank === 1 ? '🥇' : rank === 2 ? '🥈' : '🥉'}
                                </span>
                              )}
                            </span>
                            {player.isHost && (
                              <div className="flex items-center gap-1 mt-1">
                                <Crown className="w-3 h-3 text-yellow-600" />
                                <span className="text-xs text-yellow-600 font-medium">Host</span>
                              </div>
                            )}
                          </div>
                        </div>
                        
                        <div className="flex flex-col items-end gap-1">
                          {/* Winner status */}
                          {hasWonOverall ? (
                            <span className="text-xs font-bold px-2 py-1 rounded-full" style={{
                              background: 'linear-gradient(135deg, #ffd700 0%, #ffed4e 100%)',
                              color: '#8b4513',
                              border: '1px solid #ffa500'
                            }}>
                              {rank === 1 ? 'Champion' : rank === 2 ? 'Runner-up' : '3rd Place'}
                            </span>
                          ) : hasWonAnyPattern && isMultiMode ? (
                            <span className="text-xs font-bold px-2 py-1 rounded-full" style={{
                              background: 'linear-gradient(135deg, #32cd32 0%, #90ee90 100%)',
                              color: '#006400'
                            }}>
                              {wonPatterns.length} Pattern{wonPatterns.length > 1 ? 's' : ''} Won
                            </span>
                          ) : (
                            <span className="text-xs font-medium px-2 py-1 rounded-full" style={{
                              background: 'linear-gradient(135deg, #9370db 0%, #dda0dd 100%)',
                              color: 'white'
                            }}>
                              In Progress
                            </span>
                          )}
                          
                          {/* Connection indicator */}
                          <div className={`w-2 h-2 rounded-full ${
                            player.isConnected ? 'bg-green-500' : 'bg-red-500'
                          }`} title={player.isConnected ? 'Connected' : 'Disconnected'} />
                        </div>
                      </div>
                      
                      {/* Progress display - Show for all non-overall-winners OR in multimode show remaining patterns */}
                      {(!hasWonOverall || (isMultiMode && !hasWonOverall)) && (
                        (player.id === playerData?.playerId && localTicket) ||
                        (player.id !== playerData?.playerId && playerProgress.has(player.id))
                      ) && (
                        <div className="space-y-2">
                          {isMultiMode && activeGameModes && activeGameModes.length > 0 ? (
                            // Multi-mode: Show progress for all patterns, highlight won ones
                            <div className="space-y-2">
                              <span className="text-xs text-gray-500 font-medium">Pattern Progress:</span>
                              {activeGameModes.map((mode, index) => {
                                const progress = allProgress[mode] || { marked: 0, total: 0, percentage: 0 };
                                const rankDisplay = index === 0 ? '1st' : index === 1 ? '2nd' : '3rd';
                                const hasWonThisPattern = wonPatterns.includes(mode);
                                return (
                                  <div key={mode} className="space-y-1">
                                    <div className="flex items-center justify-between text-xs">
                                      <span className={`${hasWonThisPattern ? 'text-green-600 font-medium' : 'text-gray-600'}`}>
                                        {GAME_MODES[mode]?.icon} {rankDisplay}: {GAME_MODES[mode]?.name}
                                        {hasWonThisPattern && <span className="ml-1">✅</span>}
                                      </span>
                                      <span className={`font-medium ${
                                        hasWonThisPattern 
                                          ? 'text-green-600' 
                                          : player.id === playerData?.playerId 
                                          ? 'text-primary-600' 
                                          : 'text-gray-600'
                                      }`}>
                                        {progress.marked}/{progress.total} ({progress.percentage}%)
                                      </span>
                                    </div>
                                    <div className="w-full bg-gray-200 rounded-full h-1.5">
                                      <div 
                                        className={`h-1.5 rounded-full transition-all duration-300 ${
                                          hasWonThisPattern 
                                            ? 'bg-green-500' 
                                            : player.id === playerData?.playerId 
                                            ? 'bg-primary-500' 
                                            : 'bg-gray-400'
                                        }`}
                                        style={{ width: `${progress.percentage}%` }}
                                      ></div>
                                    </div>
                                  </div>
                                );
                              })}
                            </div>
                          ) : (
                            // Single mode: Show single progress
                            <div className="space-y-1">
                              <div className="flex items-center justify-between text-xs">
                                <span className="text-gray-500">Progress</span>
                                <span className={`font-medium ${
                                  player.id === playerData?.playerId ? 'text-primary-600' : 'text-gray-600'
                                }`}>
                                  {allProgress[gameMode]?.marked || 0}/{allProgress[gameMode]?.total || 0} ({allProgress[gameMode]?.percentage || 0}%)
                                </span>
                              </div>
                              <div className="w-full bg-gray-200 rounded-full h-2">
                                <div 
                                  className={`h-2 rounded-full transition-all duration-300 ${
                                    player.id === playerData?.playerId 
                                      ? 'bg-primary-500' 
                                      : 'bg-gray-400'
                                  }`}
                                  style={{ width: `${allProgress[gameMode]?.percentage || 0}%` }}
                                ></div>
                              </div>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Center/Right Column - Number Board */}
          <div className="landscape-numberboard-column">
            <NumberBoard 
              calledNumbers={calledNumbers}
              currentNumber={currentNumber}
            />
          </div>
        </div>

        {/* Enhanced Toast Notifications - Positioned to never overlap with sticky header */}
        <div className="toast-notifications space-y-2 max-w-xs sm:max-w-sm">
          {toastNotifications.map((toast, index) => (
            <div
              key={toast.id}
              className={`p-3 sm:p-4 rounded-xl shadow-2xl border-2 transform transition-all duration-500 animate-slide-in-right ${
                toast.rank === 1 ? 'bg-gradient-to-r from-yellow-100 to-amber-100 border-yellow-400 text-yellow-800' :
                toast.rank === 2 ? 'bg-gradient-to-r from-gray-100 to-slate-100 border-gray-400 text-gray-800' :
                toast.patternWin ? 'bg-gradient-to-r from-lime-100 to-lime-200 border-lime-400 text-lime-800' :
                toast.type === 'error' ? 'bg-gradient-to-r from-red-100 to-fun-100 border-red-400 text-red-800' :
                toast.type === 'info' ? 'bg-gradient-to-r from-primary-100 to-primary-200 border-primary-400 text-primary-800' :
                toast.type === 'warning' ? 'bg-gradient-to-r from-orange-100 to-red-100 border-orange-400 text-orange-800' :
                'bg-gradient-to-r from-amber-100 to-orange-100 border-amber-400 text-amber-800'
              }`}
              style={{
                transform: `translateY(${index * 3}px)`,
                zIndex: 60 - index
              }}
            >
              {toast.patternWin ? (
                // PATTERN COMPLETION NOTIFICATION
                <div className="flex items-center gap-2 sm:gap-3">
                  <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-full flex items-center justify-center text-white font-bold shadow-lg text-sm sm:text-base bg-gradient-to-r from-green-500 to-emerald-600">
                    🎯
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-bold text-xs sm:text-sm truncate">{toast.message}</div>
                    <div className="text-xs opacity-75 mt-1">
                      Pattern Completed!
                    </div>
                  </div>
                  <div className="text-lg sm:text-2xl ml-1">
                    ✨
                  </div>
                </div>
              ) : toast.rank || toast.isOverallRanking ? (
                // OVERALL RANKING NOTIFICATION  
                <div className="flex items-center gap-2 sm:gap-3">
                  <div className={`w-8 h-8 sm:w-10 sm:h-10 rounded-full flex items-center justify-center text-white font-bold shadow-lg text-sm sm:text-base ${
                    toast.rank === 1 ? 'bg-gradient-to-r from-yellow-400 to-yellow-600' :
                    toast.rank === 2 ? 'bg-gradient-to-r from-gray-400 to-gray-600' :
                    'bg-gradient-to-r from-amber-500 to-amber-700'
                  }`}>
                    {toast.rank}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-bold text-xs sm:text-sm truncate">{toast.message}</div>
                    <div className="text-xs opacity-75 mt-1">
                      {toast.rank === 1 ? 'Champion!' : toast.rank === 2 ? 'Runner-up!' : 'Third Place!'}
                    </div>
                  </div>
                  <div className="text-lg sm:text-2xl ml-1">
                    {toast.rank === 1 ? '🥇' : toast.rank === 2 ? '🥈' : '🥉'}
                  </div>
                </div>
              ) : (
                <div className="flex items-center gap-2">
                  <div className={`w-6 h-6 sm:w-8 sm:h-8 rounded-full flex items-center justify-center text-white font-bold shadow-lg text-xs sm:text-sm ${
                    toast.type === 'error' ? 'bg-gradient-to-r from-red-500 to-pink-600' :
                    toast.type === 'info' ? 'bg-gradient-to-r from-blue-500 to-indigo-600' :
                    toast.type === 'warning' ? 'bg-gradient-to-r from-orange-500 to-red-600' :
                    'bg-gradient-to-r from-green-500 to-emerald-600'
                  }`}>
                    {toast.type === 'error' ? '❌' : toast.type === 'info' ? 'ℹ️' : toast.type === 'warning' ? '⚠️' : '✅'}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-medium text-xs sm:text-sm truncate">{toast.message}</div>
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>

        {/* Enhanced Celebration Overlay */}
        {celebrationWinner && (
          <div className="fixed inset-0 bg-black bg-opacity-80 flex items-center justify-center z-50 animate-fade-in">
            <div className="text-center text-white max-w-lg mx-auto p-8 relative">
              {/* Enhanced Confetti Effect - Different colors for pattern vs overall wins */}
              <div className="absolute inset-0 pointer-events-none overflow-hidden">
                {[...Array(30)].map((_, i) => (
                  <div
                    key={i}
                    className={`absolute w-3 h-3 rounded-full animate-confetti ${
                      celebrationWinner.isPatternWin ? 'bg-green-400' : (
                        celebrationWinner.rank === 1 ? 'bg-yellow-400' :
                        celebrationWinner.rank === 2 ? 'bg-gray-400' :
                        'bg-amber-500'
                      )
                    }`}
                    style={{
                      left: `${Math.random() * 100}%`,
                      top: `${Math.random() * 100}%`,
                      animationDelay: `${Math.random() * 3}s`,
                      animationDuration: `${3 + Math.random() * 2}s`
                    }}
                  />
                ))}
              </div>

              {/* Celebration Content */}
              <div className="relative z-10">
                {/* Animated Winner Circle - Different for pattern vs overall wins */}
                {celebrationWinner.isPatternWin ? (
                  <div className="w-32 h-32 rounded-full mx-auto mb-6 flex items-center justify-center text-4xl font-bold text-white shadow-2xl animate-bounce-gentle bg-gradient-to-r from-green-500 to-emerald-600">
                    🎯
                  </div>
                ) : (
                  <div className={`w-40 h-40 rounded-full mx-auto mb-6 flex items-center justify-center text-7xl font-bold text-white shadow-2xl animate-bounce-gentle ${
                    celebrationWinner.rank === 1 ? 'bg-gradient-to-r from-yellow-400 to-yellow-600' :
                    celebrationWinner.rank === 2 ? 'bg-gradient-to-r from-gray-400 to-gray-600' :
                    'bg-gradient-to-r from-amber-500 to-amber-700'
                  }`}>
                    {celebrationWinner.rank}
                  </div>
                )}

                {/* Medal - Different for pattern vs overall wins */}
                <div className="text-6xl mb-6 animate-pulse">
                  {celebrationWinner.isPatternWin ? '🎯' : (
                    celebrationWinner.rank === 1 ? '🥇' : celebrationWinner.rank === 2 ? '🥈' : '🥉'
                  )}
                </div>

                {/* Title */}
                <h2 className="text-4xl font-bold mb-4 text-gradient-gold">
                  {celebrationWinner.isPatternWin ? (
                    celebrationWinner.isYou ? '🎊 PATTERN COMPLETED! 🎊' : `${celebrationWinner.player.nickname} Won Pattern!`
                  ) : (
                    celebrationWinner.isYou ? '🎉 CONGRATULATIONS! 🎉' : `${celebrationWinner.player.nickname} Wins!`
                  )}
                </h2>

                {/* Achievement */}
                <div className="bg-white bg-opacity-20 rounded-2xl p-6 mb-6 backdrop-blur-sm">
                  {celebrationWinner.isPatternWin ? (
                    <>
                      <p className="text-2xl mb-2 font-bold">
                        {celebrationWinner.isYou ? 'You completed' : 'Completed'}{' '}
                        <span className="inline-block px-4 py-2 rounded-full text-white font-bold bg-gradient-to-r from-green-500 to-emerald-600">
                          {celebrationWinner.patternName}
                        </span>
                      </p>
                      
                      {celebrationWinner.isYou && (
                        <p className="text-lg text-green-200 mb-2">
                          Great job! Continue playing for more patterns! 🌟
                        </p>
                      )}
                    </>
                  ) : (
                    <>
                      <p className="text-2xl mb-2 font-bold">
                        {celebrationWinner.isYou ? 'You achieved' : 'Achieved'}{' '}
                        <span className={`inline-block px-4 py-2 rounded-full text-white font-bold ${
                          celebrationWinner.rank === 1 ? 'bg-yellow-500' :
                          celebrationWinner.rank === 2 ? 'bg-gray-500' :
                          'bg-amber-600'
                        }`}>
                          {celebrationWinner.rank === 1 ? '1st Place' : 
                           celebrationWinner.rank === 2 ? '2nd Place' : 
                           '3rd Place'}
                        </span>
                      </p>
                      
                      {celebrationWinner.isYou && (
                        <p className="text-lg text-yellow-200 mb-2">
                          Amazing job! Your victory is now secured! 🌟
                        </p>
                      )}
                    </>
                  )}
                  
                  {!celebrationWinner.isYou && winners.length < requiredWinners && (
                    <p className="text-lg text-blue-200">
                      Keep playing for remaining positions!
                    </p>
                  )}
                </div>

                {/* Progress indicator */}
                <div className="mb-6">
                  <div className="text-sm text-gray-300 mb-2">Game Progress</div>
                  <div className="flex justify-center gap-2">
                    {Array.from({ length: requiredWinners }, (_, pos) => (
                      <div
                        key={pos + 1}
                        className={`w-4 h-4 rounded-full ${
                          (pos + 1) <= winners.length 
                            ? pos === 0 ? 'bg-yellow-400' : pos === 1 ? 'bg-gray-400' : 'bg-amber-500'
                            : 'bg-gray-600'
                        }`}
                      />
                    ))}
                  </div>
                  <div className="text-xs text-gray-400 mt-1">
                    {winners.length}/{requiredWinners} positions filled
                  </div>
                </div>

                {/* Auto-close info */}
                <div className="text-sm opacity-60 animate-pulse">
                  Closes automatically in a few seconds...
                </div>
              </div>
            </div>
          </div>
        )}
        
        {/* HOST SUPERPOWERS - Confirmation Dialogs */}
        
        {/* Kick Player Confirmation */}
        {showKickConfirm && selectedPlayerToKick && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white rounded-lg p-6 max-w-sm w-full mx-4">
              <h3 className="text-lg font-semibold mb-4 text-red-600">Kick Player</h3>
              <p className="text-gray-700 mb-6">
                Are you sure you want to kick <strong>{selectedPlayerToKick.nickname}</strong> from the game?
              </p>
              <div className="flex gap-3">
                <button
                  onClick={confirmKickPlayer}
                  disabled={hostActionLoading}
                  className="flex-1 bg-red-600 text-white px-4 py-2 rounded-lg font-medium hover:bg-red-700 disabled:opacity-50"
                >
                  {hostActionLoading ? 'Kicking...' : 'Kick Player'}
                </button>
                <button
                  onClick={() => {
                    setShowKickConfirm(false);
                    setSelectedPlayerToKick(null);
                  }}
                  className="flex-1 bg-gray-300 text-gray-700 px-4 py-2 rounded-lg font-medium hover:bg-gray-400"
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Transfer Host Confirmation */}
        {showTransferHost && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white rounded-lg p-6 max-w-sm w-full mx-4">
              <h3 className="text-lg font-semibold mb-4 text-warning-600">Transfer Host</h3>
              <p className="text-gray-700 mb-4">
                Choose a player to transfer host role to:
              </p>
              <div className="space-y-2 mb-6">
                {roomData?.players?.filter(p => p.id !== playerData?.playerId && p.isConnected).map(player => (
                  <label key={player.id} className="flex items-center space-x-3">
                    <input
                      type="radio"
                      name="hostTransfer"
                      value={player.id}
                      checked={selectedPlayerForHost === player.id}
                      onChange={(e) => setSelectedPlayerForHost(e.target.value)}
                      className="text-warning-600 focus:ring-warning-500"
                    />
                    <span className="text-gray-700">{player.nickname}</span>
                  </label>
                ))}
              </div>
              <div className="flex gap-3">
                <button
                  onClick={confirmTransferHost}
                  disabled={hostActionLoading || !selectedPlayerForHost}
                  className="flex-1 bg-warning-600 text-white px-4 py-2 rounded-lg font-medium hover:bg-warning-700 disabled:opacity-50"
                >
                  {hostActionLoading ? 'Transferring...' : 'Transfer Host'}
                </button>
                <button
                  onClick={() => {
                    setShowTransferHost(false);
                    setSelectedPlayerForHost(null);
                  }}
                  className="flex-1 bg-gray-300 text-gray-700 px-4 py-2 rounded-lg font-medium hover:bg-gray-400"
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default Game;
