import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Image from 'next/image';
import { GameState, GamePhase, Player, GAME_CONFIG, Faction } from '../../../shared/types';
import MissionReveal from './MissionReveal';
import MissionResult from './MissionResult';
import VictoryScreen from './VictoryScreen';
import ExitGameButton from './ExitGameButton';

interface GameBoardProps {
    gameState: GameState;
    currentPlayerId: string;
    actions: any;
    fullPlayerName: string;
}

export default function GameBoard({ gameState, currentPlayerId, actions, fullPlayerName }: GameBoardProps) {
    const [selectedTeam, setSelectedTeam] = useState<string[]>([]);

    // Hooks para FASE REVEAL ROLE
    const [revealCard, setRevealCard] = useState(false);

    // Orden aleatorio de cartas de misión (se genera una vez)
    const [cardOrder] = useState(() => Math.random() > 0.5);

    // Track del voto de misión del jugador
    const [missionVote, setMissionVote] = useState<boolean | null>(null);
    const [expandedMission, setExpandedMission] = useState<number | null>(null);

    // Estado para controlar el colapso del panel de jugadores
    const [isPlayersCollapsed, setIsPlayersCollapsed] = useState(true);

    // Estado para controlar el colapso del historial de misiones
    const [isHistoryCollapsed, setIsHistoryCollapsed] = useState(true);


    // Timer para avanzar automáticamente en REVEAL_ROLE
    useEffect(() => {
        if (gameState.phase === 'reveal_role' as any) {
            const timer = setTimeout(() => {
                actions.finishReveal();
            }, 10000);
            return () => clearTimeout(timer);
        }
    }, [gameState.phase, actions]);

    // Reset missionVote cuando cambia la fase
    useEffect(() => {
        if (gameState.phase !== GamePhase.MISSION) {
            setMissionVote(null);
        }
    }, [gameState.phase]);

    // Reset selectedTeam cuando no estamos en TEAM_BUILDING o cambia el líder
    useEffect(() => {
        if (gameState.phase !== GamePhase.TEAM_BUILDING) {
            setSelectedTeam([]);
        }
    }, [gameState.phase, gameState.currentLeaderId]);

    // Estado para controlar cuándo mostrar el tablero
    const [showBoard, setShowBoard] = useState(false);

    // Mostrar tablero durante MISSION_RESULT
    useEffect(() => {
        if (gameState.phase === GamePhase.MISSION_RESULT) {
            setShowBoard(true);
        } else {
            setShowBoard(false);
        }
    }, [gameState.phase]);


    const currentPlayer = gameState.players.find(p => p.id === currentPlayerId);
    const isLeader = gameState.currentLeaderId === currentPlayerId; // FIX: Usar currentLeaderId del estado
    const config = GAME_CONFIG[gameState.players.length as keyof typeof GAME_CONFIG];
    const currentQuestSize = config?.quests[gameState.currentRound - 1];

    // Manejar selección de equipo
    const toggleTeamSelection = (playerId: string) => {
        if (selectedTeam.includes(playerId)) {
            setSelectedTeam(selectedTeam.filter(id => id !== playerId));
        } else {
            if (selectedTeam.length < currentQuestSize) {
                setSelectedTeam([...selectedTeam, playerId]);
            }
        }
    };

    const handleMissionVote = (vote: boolean) => {
        setMissionVote(vote);
        actions.voteMission(vote);
    };


    // Coordenadas porcentuales de los hexágonos de misión en el mapa
    const missionCoords = [
        { left: '18%', top: '60%' }, // Misión 1 - Abajo izquierda
        { left: '25%', top: '18%' }, // Misión 2 - Arriba izquierda
        { left: '50%', top: '75%' }, // Misión 3 - Abajo centro
        { left: '50%', top: '30%' }, // Misión 4 - Centro
        { left: '80%', top: '45%' }, // Misión 5 - Derecha
    ];

    // Nombres de las misiones
    const missionNames = [
        'Sabotaje en el Tren',
        'Rescate del Prisionero',
        'Destrucción del Puente',
        'Robo de Documentos',
        'Asalto al Cuartel General'
    ];

    // --- UI/Efectos para FASES TEMPRANAS ---
    const isHost = gameState.hostId === currentPlayerId;

    // FASE INTRO
    if (gameState.phase === 'intro' as any) {
        return (
            <div className="relative w-full h-screen flex flex-col items-center justify-center bg-black overflow-hidden text-white">
                <div className="absolute inset-0 z-0">
                    <Image src="/assets/images/ui/bg_intro.png" alt="Battlefield" fill className="object-cover" />
                    <div className="absolute inset-0 bg-black/40" />
                </div>

                <h1 className="z-10 text-[2.55rem] font-bold uppercase tracking-[0.3em] mb-8 text-yellow-500 drop-shadow-lg text-center">
                    Traición en París
                </h1>

                {/* Audio Auto-Play - Solo para el host */}
                {isHost && (
                    <audio
                        src="/assets/audio/Intro.ogg"
                        autoPlay
                        onEnded={() => actions.finishIntro()}
                    />
                )}

                {isHost && (
                    <button
                        onClick={() => actions.finishIntro()}
                        className="z-10 bg-white/20 hover:bg-white/40 border border-white px-6 py-2 rounded text-sm uppercase tracking-widest backdrop-blur-sm transition-all"
                    >
                        Omitir Introducción
                    </button>
                )}
            </div>
        );
    }

    // FASE REVEAL ROLE NO HOOKS HERE

    if (gameState.phase === 'reveal_role' as any) {
        // Determinar imagen basada en el rol
        // Mapeo actualizado: 
        // Marlene -> good_merlin.png
        // Capitán Philippe -> good_percival.png
        // Partisano -> good_soldier_X.png (random)
        // Francotirador -> evil_assassin.png
        // Agente Doble -> evil_morgana.png
        // Comandante Schmidt -> evil_mordred.png
        // Infiltrado -> evil_oberon.png
        // Colaboracionista -> evil_minion_X.png

        let roleImage = '/assets/images/characters/good_soldier_1.png'; // Default

        const role = currentPlayer?.role;
        if (role === 'marlene') roleImage = '/assets/images/characters/good_merlin.png';
        else if (role === 'francotirador') roleImage = '/assets/images/characters/evil_assassin.png';
        else if (role === 'capitan_philippe') roleImage = '/assets/images/characters/good_percival.png';
        else if (role === 'agente_doble') roleImage = '/assets/images/characters/evil_morgana.png';
        else if (role === 'comandante_schmidt') roleImage = '/assets/images/characters/evil_mordred.png';
        else if (role === 'infiltrado') roleImage = '/assets/images/characters/evil_oberon.png';
        else if (role === 'partisano') {
            // Random soldier 1-5
            const idx = (currentPlayerId.charCodeAt(0) % 5) + 1;
            roleImage = `/assets/images/characters/good_soldier_${idx}.png`;
        }
        else if (role === 'colaboracionista') {
            // Random minion 1-3
            const idx = (currentPlayerId.charCodeAt(0) % 3) + 1;
            roleImage = `/assets/images/characters/evil_minion_${idx}.png`;
        }

        return (
            <div className="relative w-full h-screen flex flex-col items-center justify-center bg-black overflow-hidden text-white font-mono">
                {/* FONDO (Mismo que Roll Call) */}
                <div className="absolute inset-0 z-0">
                    <Image src="/assets/images/ui/bg_roll_call.png" alt="Resistance HQ" fill className="object-cover" />
                    <div className="absolute inset-0 bg-black/70" />
                </div>

                <div className="z-10 flex flex-col items-center gap-8">
                    <h2 className="text-2xl uppercase tracking-[0.2em] text-gray-300">
                        Tu Identidad Secreta
                    </h2>

                    <p className="text-sm text-gray-400 mb-4 animate-pulse">
                        Desliza hacia arriba para revelar
                    </p>

                    <div className="relative w-64 h-96 perspective-1000">
                        {/* Carta Revelada (Fondo) */}
                        <div className="absolute inset-0 w-full h-full rounded-xl overflow-hidden shadow-2xl border-4 border-yellow-600 bg-gray-900 flex items-center justify-center">
                            <Image
                                src={roleImage}
                                alt="Role"
                                fill
                                className="object-cover"
                            />
                            <div className="absolute bottom-0 w-full bg-black/80 text-center py-2 font-bold text-yellow-500 uppercase">
                                {role?.replace('_', ' ')}
                            </div>
                        </div>

                        {/* Reverso de Carta (Draggable) */}
                        <motion.div
                            drag="y"
                            dragConstraints={{ top: -300, bottom: 0 }}
                            dragElastic={0.5}
                            dragSnapToOrigin={true}
                            whileHover={{ scale: 1.02 }}
                            whileTap={{ scale: 0.98, cursor: 'grabbing' }}
                            className="absolute inset-0 w-full h-full rounded-xl overflow-hidden shadow-2xl z-20 cursor-grab active:cursor-grabbing hover:ring-2 hover:ring-white/50 transition-all"
                        >
                            <Image
                                src="/assets/images/characters/card_back.png"
                                alt="Card Back"
                                fill
                                className="object-cover pointer-events-none" // Importante: pointer-events-none en la imagen para que no capture el drag
                            />
                        </motion.div>
                    </div>


                </div>
            </div>
        );
    }

    // FASE ROLL CALL
    if (gameState.phase === 'roll_call' as any) {
        return (
            <div className="relative w-full h-screen flex flex-col bg-black overflow-hidden text-white font-mono">


                <div className="absolute inset-0 z-0">
                    <Image src="/assets/images/ui/bg_roll_call.png" alt="Resistance HQ" fill className="object-cover" />
                    <div className="absolute inset-0 bg-black/70" />
                </div>

                {/* --- 1. SECCIÓN SUPERIOR: TÍTULO (20-25% altura) --- */}
                <div className="relative z-10 w-full h-[20vh] flex items-center justify-center px-4 border-b border-gray-600/50 bg-black/20 backdrop-blur-sm">
                    <h2 className="text-2xl md:text-3xl lg:text-4xl text-center uppercase tracking-[0.2em] text-gray-300 drop-shadow-lg">
                        Pasando Lista...
                    </h2>
                </div>

                {/* --- 2. SECCIÓN INFERIOR: JUGADORES (Resto de altura) --- */}
                <div className="relative z-10 w-full flex-1 overflow-y-auto p-4 flex flex-col items-center">
                    {isHost && (
                        <audio
                            src="/assets/audio/Rondas.mp3"
                            autoPlay
                            onEnded={() => actions.finishRollCall()} // Host avanza cuando acaba audio
                        />
                    )}

                    <div className="w-full max-w-6xl grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3 md:gap-8 justify-items-center content-center py-4">
                        {gameState.players.map((p, i) => {
                            return (
                                <motion.div
                                    key={p.id}
                                    initial={{ opacity: 0, scale: 0.8 }}
                                    animate={{ opacity: 1, scale: 1 }}
                                    transition={{ delay: i * 0.3 }} // Aparecen uno a uno
                                    className="flex flex-col items-center gap-1 md:gap-3 w-full"
                                >
                                    {/* Avatar Responsive */}
                                    <div className="w-20 h-20 md:w-32 md:h-32 rounded-full border-2 md:border-4 border-gray-400 overflow-hidden relative shadow-2xl bg-black">
                                        <Image
                                            src={`/assets/images/characters/${p.avatar}`}
                                            alt="Avatar"
                                            fill
                                            className="object-cover grayscale contrast-125"
                                        />
                                    </div>
                                    {/* Nombre Responsive */}
                                    <div className="bg-black/80 px-2 py-0.5 md:px-4 md:py-1 rounded border border-white/20 text-xs md:text-xl font-bold text-yellow-500 uppercase text-center w-full truncate max-w-[120px] md:max-w-none">
                                        {p.name}
                                    </div>
                                </motion.div>
                            );
                        })}
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="relative w-full h-screen flex flex-col overflow-hidden">
            {/* Botón de Salir de la Partida - No mostrar en pantallas de victoria */}
            {gameState.phase !== GamePhase.ALLIED_WIN && gameState.phase !== GamePhase.NAZIS_WIN && (
                <ExitGameButton
                    onExit={() => actions.leaveGame()}
                    playerName={fullPlayerName}
                />
            )}

            {/* Fondo */}
            <div className="absolute inset-0 z-0 opacity-40">
                <Image
                    src={
                        gameState.phase === GamePhase.ALLIED_WIN
                            ? "/assets/images/tokens/mission_success.png"
                            : gameState.phase === GamePhase.NAZIS_WIN
                                ? "/assets/images/tokens/mission_fail.png"
                                : "/assets/images/ui/bg_game.png"
                    }
                    alt="Game Background"
                    fill
                    className="object-cover"
                />
                <div className="absolute inset-0 bg-black/60" />
            </div>

            {/* Contenedor principal */}
            <div className="relative z-10 w-full flex flex-col items-center pb-32">

                {/* --- MAPA TÁCTICO (TABLERO) O CARTA DE MISIÓN O ASSASSIN_PHASE --- */}
                {/* No mostrar el tablero en fases de victoria */}
                {gameState.phase !== GamePhase.ALLIED_WIN && gameState.phase !== GamePhase.NAZIS_WIN && (
                    <div className="relative w-full max-w-5xl aspect-video mt-4 shadow-2xl border-4 border-gray-800 rounded-lg overflow-hidden bg-[#2a2a2a]">
                        {gameState.phase === GamePhase.ASSASSIN_PHASE ? (
                            /* IMAGEN LASTSHOT PARA ASSASSIN_PHASE */
                            <>
                                <Image
                                    src="/assets/images/tokens/lastshot.jpg"
                                    alt="Last Shot"
                                    fill
                                    className="object-cover"
                                    priority
                                />
                                {/* Overlay oscuro para mejorar legibilidad */}
                                <div className="absolute inset-0 bg-black/40" />

                                {/* Título sobre la imagen - centrado verticalmente */}
                                <div className="absolute top-1/3 left-0 right-0 flex flex-col items-center z-10">
                                    <h1 className="text-5xl font-bold text-red-600 mb-2 drop-shadow-[0_4px_8px_rgba(0,0,0,0.9)]">
                                        ¡ÚLTIMA OPORTUNIDAD!
                                    </h1>
                                    {currentPlayer?.role === 'francotirador' ? (
                                        <p className="text-xl text-white drop-shadow-[0_2px_4px_rgba(0,0,0,0.9)] font-bold">
                                            Francotirador, elige a quién crees que es <span className="text-yellow-400">MARLENE</span>
                                        </p>
                                    ) : (
                                        <p className="text-xl text-gray-300 drop-shadow-[0_2px_4px_rgba(0,0,0,0.9)] font-bold">
                                            El Francotirador está decidiendo...
                                        </p>
                                    )}
                                </div>
                            </>
                        ) : showBoard ? (
                            <>
                                {/* TABLERO CON TOKENS */}
                                <Image
                                    src="/assets/images/ui/board_map.jpg"
                                    alt="Tactical Map"
                                    fill
                                    className="object-contain"
                                />

                                {/* TOKENS SOBRE EL MAPA */}
                                {missionCoords.map((coord, idx) => {
                                    const result = gameState.questResults[idx];
                                    const isCurrent = gameState.currentRound === idx + 1;

                                    return (
                                        <div
                                            key={idx}
                                            className="absolute w-[10%] aspect-square flex items-center justify-center"
                                            style={{
                                                left: coord.left,
                                                top: coord.top,
                                                transform: 'translate(-50%, -50%)'
                                            }}
                                        >
                                            {/* Marcador de Ronda Actual */}
                                            {isCurrent && (
                                                <motion.div
                                                    layoutId="round-marker"
                                                    className="absolute inset-0 z-10"
                                                    initial={{ scale: 1.5, opacity: 0 }}
                                                    animate={{ scale: 1, opacity: 1 }}
                                                    transition={{ type: "spring", stiffness: 300, damping: 20 }}
                                                >
                                                    <Image
                                                        src="/assets/images/tokens/marker_round.png"
                                                        alt="Current Round"
                                                        fill
                                                        className="object-contain drop-shadow-lg"
                                                    />
                                                </motion.div>
                                            )}

                                            {/* Resultado de Misión (Éxito/Fracaso) */}
                                            {result === true && (
                                                <motion.div
                                                    initial={{ scale: 0 }} animate={{ scale: 1 }}
                                                    className="absolute inset-0 z-20 flex items-center justify-center"
                                                >
                                                    <div className="w-[80%] h-[80%] relative">
                                                        <Image src="/assets/images/tokens/marker_score_blue.png" alt="Success" fill className="object-contain drop-shadow-lg" />
                                                    </div>
                                                </motion.div>
                                            )}
                                            {result === false && (
                                                <motion.div
                                                    initial={{ scale: 0 }} animate={{ scale: 1 }}
                                                    className="absolute inset-0 z-20 flex items-center justify-center"
                                                >
                                                    <div className="w-[80%] h-[80%] relative">
                                                        <Image src="/assets/images/tokens/marker_score_red.png" alt="Fail" fill className="object-contain drop-shadow-lg" />
                                                    </div>
                                                </motion.div>
                                            )}
                                        </div>
                                    );
                                })}
                            </>
                        ) : (
                            /* CARTA DE MISIÓN CON TÍTULO */
                            <>
                                <Image
                                    src={`/assets/images/missions/mission${gameState.currentRound}.png`}
                                    alt={`Mission ${gameState.currentRound}`}
                                    fill
                                    className="object-contain"
                                />
                                {/* Título y subtítulo sobre la carta */}
                                <div className="absolute top-4 left-0 right-0 flex flex-col items-center z-10">
                                    <h2 className="text-4xl font-bold text-white drop-shadow-[0_4px_8px_rgba(0,0,0,0.8)] mb-2 uppercase tracking-wider">
                                        Misión {gameState.currentRound}
                                    </h2>
                                    <h3 className="text-2xl font-semibold text-yellow-400 drop-shadow-[0_4px_8px_rgba(0,0,0,0.8)] uppercase tracking-wide">
                                        {missionNames[gameState.currentRound - 1]}
                                    </h3>
                                </div>
                            </>
                        )}
                    </div>
                )}

                {/* --- ÁREA DE JUEGO (CARTAS Y ACCIONES) --- */}
                <div className="flex-1 w-full max-w-6xl relative mt-4 px-4">
                    <AnimatePresence mode="wait">

                        {/* FASE: VOTACIÓN DE LÍDER */}
                        {gameState.phase === 'vote_leader' as any && (
                            <motion.div
                                key="vote-leader"
                                initial={{ opacity: 0, scale: 0.9 }}
                                animate={{ opacity: 1, scale: 1 }}
                                className="flex flex-col items-center gap-6"
                            >
                                <div className="bg-black/80 p-4 rounded text-white text-center border border-yellow-500/50 relative">
                                    <h3 className="text-xl font-mono mb-2 text-yellow-500 uppercase tracking-widest">
                                        Confirmar Líder
                                    </h3>
                                    <div className="text-2xl font-bold mb-2">
                                        ¿Aceptas a <span className="text-yellow-400">{gameState.players.find(p => p.id === gameState.currentLeaderId)?.name}</span> como Líder?
                                    </div>

                                    {/* Timer visual (solo muestra el tiempo, el servidor controla el timeout) */}
                                    {!gameState.leaderVotes?.[currentPlayerId] && (
                                        <VotingTimer key={gameState.currentLeaderId} />
                                    )}
                                </div>

                                {gameState.leaderVotes?.[currentPlayerId] === undefined ? (
                                    <div className="flex gap-8">
                                        <button onClick={() => actions.voteLeader(true)} className="group">
                                            <div className="w-32 h-32 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-green-500 transition-all transform group-hover:-translate-y-4 relative overflow-hidden">
                                                <Image src="/assets/images/tokens/accept_leader.png" alt="Accept Leader" fill className="object-contain" />
                                            </div>
                                            <span className="block text-center text-white mt-2 font-bold bg-green-600 px-2 rounded uppercase tracking-widest">ACEPTAR</span>
                                        </button>
                                        <button onClick={() => actions.voteLeader(false)} className="group">
                                            <div className="w-32 h-32 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-red-500 transition-all transform group-hover:-translate-y-4 relative overflow-hidden">
                                                <Image src="/assets/images/tokens/deny_leader.png" alt="Deny Leader" fill className="object-contain" />
                                            </div>
                                            <span className="block text-center text-white mt-2 font-bold bg-red-600 px-2 rounded uppercase tracking-widest">RECHAZAR</span>
                                        </button>
                                    </div>
                                ) : (
                                    <div className="text-white text-xl font-mono animate-pulse bg-black/50 px-6 py-3 rounded-full border border-white/20">
                                        VOTO REGISTRADO. ESPERANDO AL RESTO...
                                    </div>
                                )}
                            </motion.div>
                        )}

                        {/* FASE: CONSTRUCCIÓN DE EQUIPO */}
                        {gameState.phase === GamePhase.TEAM_BUILDING && (
                            <motion.div
                                key="team-building"
                                initial={{ opacity: 0, y: 20 }}
                                animate={{ opacity: 1, y: 0 }}
                                exit={{ opacity: 0, y: -20 }}
                                className="flex flex-col items-center gap-6 w-full max-w-4xl"
                            >
                                {/* Información del líder */}
                                {/* Información del líder - SOLO para NO líderes */}
                                {!isLeader && (
                                    <div className="bg-yellow-600/90 text-black p-2 rounded-lg shadow-xl border-4 border-yellow-400 w-full text-center mb-2">
                                        <div className="flex items-center justify-center gap-3">
                                            <div>
                                                <div className="text-xs uppercase tracking-wider font-bold">Líder Actual</div>
                                                <div className="text-xl font-bold">
                                                    {gameState.players.find(p => p.id === gameState.currentLeaderId)?.name || 'Desconocido'}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* Mensaje para el líder o para los demás */}
                                {/* Mensaje para el líder o para los demás */}
                                <div className="bg-paper-bg text-black p-4 md:p-6 rounded shadow-2xl w-full text-center">
                                    <h2 className="text-xl md:text-2xl font-bold font-mono mb-2 uppercase text-resistance-blue">
                                        {isLeader ? '🎯 TU TURNO: ELIGE TU EQUIPO' : '⏳ ESPERANDO AL LÍDER...'}
                                    </h2>
                                    {isLeader && (
                                        <p className="mb-4 font-serif italic text-gray-700">
                                            Se necesitan <span className="font-bold text-red-700 text-xl">{currentQuestSize} agentes</span> para la misión #{gameState.currentRound}.
                                        </p>
                                    )}

                                    {/* Contador de seleccionados */}
                                    {isLeader && (
                                        <div className="mb-4 text-lg font-bold">
                                            Seleccionados: <span className={selectedTeam.length === currentQuestSize ? 'text-green-600' : 'text-orange-600'}>
                                                {selectedTeam.length} / {currentQuestSize}
                                            </span>
                                        </div>
                                    )}

                                    {isLeader && (
                                        <button
                                            onClick={() => actions.proposeTeam(selectedTeam)}
                                            disabled={selectedTeam.length !== currentQuestSize}
                                            className="w-full bg-resistance-blue text-white font-bold py-3 px-4 rounded hover:bg-blue-900 transition-colors disabled:opacity-50 disabled:cursor-not-allowed uppercase tracking-widest shadow-lg"
                                        >
                                            {selectedTeam.length === currentQuestSize ? '✓ CONFIRMAR EQUIPO' : `Selecciona ${currentQuestSize - selectedTeam.length} más`}
                                        </button>
                                    )}

                                    {!isLeader && (
                                        <div className="text-gray-600 animate-pulse">
                                            El líder está seleccionando el equipo de misión...
                                        </div>
                                    )}
                                </div>
                            </motion.div>
                        )}

                        {/* FASE: VOTACIÓN DE EQUIPO */}
                        {gameState.phase === GamePhase.VOTING_TEAM && (
                            <motion.div
                                key="voting"
                                initial={{ scale: 0.8, opacity: 0 }}
                                animate={{ scale: 1, opacity: 1 }}
                                className="flex flex-col items-center gap-6"
                            >
                                <div className="bg-black/80 p-4 rounded text-white text-center border border-white/20">
                                    <h3 className="text-xl font-mono mb-2 text-yellow-500">PROPUESTA DE MISIÓN</h3>
                                    <div className="flex gap-2 justify-center">
                                        {gameState.proposedTeam.map(id => {
                                            const p = gameState.players.find(pl => pl.id === id);
                                            return (
                                                <div key={id} className="bg-white/10 px-3 py-1 rounded text-sm">
                                                    {p?.name}
                                                </div>
                                            );
                                        })}
                                    </div>
                                </div>

                                {gameState.teamVotes[currentPlayerId] === undefined ? (
                                    <div className="flex gap-8">
                                        <button onClick={() => actions.voteTeam(true)} className="group">
                                            <div className="w-32 h-48 bg-white rounded-lg shadow-xl flex flex-col items-center justify-center border-2 border-blue-500 group-hover:border-blue-400 group-hover:shadow-blue-500/50 transition-all transform group-hover:-translate-y-4 relative overflow-hidden p-2">
                                                <span className="text-blue-600 font-bold text-sm uppercase tracking-wider mb-1 z-10">Éxito</span>
                                                <div className="relative w-full h-full flex items-center justify-center">
                                                    <Image src="/assets/images/tokens/vote_approve.png" alt="Approve" fill className="object-contain" />
                                                </div>
                                            </div>
                                        </button>
                                        <button onClick={() => actions.voteTeam(false)} className="group">
                                            <div className="w-32 h-48 bg-white rounded-lg shadow-xl flex flex-col items-center justify-center border-2 border-red-500 group-hover:border-red-400 group-hover:shadow-red-500/50 transition-all transform group-hover:-translate-y-4 relative overflow-hidden p-2">
                                                <span className="text-red-600 font-bold text-sm uppercase tracking-wider mb-1 z-10">Fracaso</span>
                                                <div className="relative w-full h-full flex items-center justify-center">
                                                    <Image src="/assets/images/tokens/vote_reject.png" alt="Reject" fill className="object-contain" />
                                                </div>
                                            </div>
                                        </button>
                                    </div>
                                ) : (
                                    <div className="text-white text-xl font-mono animate-pulse">
                                        VOTO REGISTRADO. ESPERANDO AL RESTO...
                                        ```
                                    </div>
                                )}
                            </motion.div>
                        )}

                        {/* FASE: MISIÓN */}
                        {gameState.phase === GamePhase.MISSION && (
                            <motion.div
                                key="mission"
                                className="fixed inset-0 flex items-start justify-center bg-black/90 z-50 pt-20"
                                initial={{ opacity: 0 }}
                                animate={{ opacity: 1 }}
                            >
                                {gameState.proposedTeam.includes(currentPlayerId) ? (
                                    <div className="flex flex-col items-center gap-4 w-full max-w-6xl px-4">
                                        <h2 className="text-4xl md:text-5xl font-bold text-white mb-2 drop-shadow-2xl text-center uppercase tracking-wider animate-pulse">
                                            🎯 REALIZA LA MISIÓN
                                        </h2>
                                        <p className="text-white text-xl mb-2 text-center">
                                            Elige si quieres un éxito o un fracaso
                                        </p>

                                        {/* Cartas en orden aleatorio */}
                                        <div className="flex gap-12 flex-wrap justify-center">
                                            {cardOrder ? (
                                                <>
                                                    {/* Carta de Éxito primero */}
                                                    <button
                                                        onClick={() => handleMissionVote(true)}
                                                        className={`group transition-opacity ${missionVote === true ? 'opacity-100' : 'opacity-50'}`}
                                                        disabled={missionVote !== null}
                                                    >
                                                        <motion.div
                                                            className="w-32 h-48 bg-gradient-to-br from-blue-600 to-blue-900 rounded-2xl shadow-2xl border-4 border-blue-400 flex flex-col items-center justify-center p-4 transform transition-all hover:scale-110 hover:rotate-3 hover:shadow-blue-500/50"
                                                            whileHover={{ scale: 1.1, rotate: 3 }}
                                                            whileTap={{ scale: 0.95 }}
                                                        >
                                                            <Image src="/assets/images/tokens/vote_approve.png" alt="Success" width={80} height={80} className="drop-shadow-2xl" />
                                                            <span className="mt-2 text-white font-bold text-lg tracking-widest uppercase">ÉXITO</span>
                                                        </motion.div>
                                                    </button>

                                                    {/* Carta de Sabotaje segundo (solo para alemanes) */}
                                                    {currentPlayer?.faction === Faction.ALEMANES && (
                                                        <button
                                                            onClick={() => handleMissionVote(false)}
                                                            className={`group transition-opacity ${missionVote === false ? 'opacity-100' : 'opacity-50'}`}
                                                            disabled={missionVote !== null}
                                                        >
                                                            <motion.div
                                                                className="w-32 h-48 bg-gradient-to-br from-red-600 to-red-900 rounded-2xl shadow-2xl border-4 border-red-400 flex flex-col items-center justify-center p-4 transform transition-all hover:scale-110 hover:-rotate-3 hover:shadow-red-500/50"
                                                                whileHover={{ scale: 1.1, rotate: -3 }}
                                                                whileTap={{ scale: 0.95 }}
                                                            >
                                                                <Image src="/assets/images/tokens/vote_reject.png" alt="Fail" width={80} height={80} className="drop-shadow-2xl" />
                                                                <span className="mt-2 text-white font-bold text-lg tracking-widest uppercase">SABOTAJE</span>
                                                            </motion.div>
                                                        </button>
                                                    )}
                                                </>
                                            ) : (
                                                <>
                                                    {/* Carta de Sabotaje primero (solo para alemanes) */}
                                                    {currentPlayer?.faction === Faction.ALEMANES && (
                                                        <button
                                                            onClick={() => handleMissionVote(false)}
                                                            className={`group transition-opacity ${missionVote === false ? 'opacity-100' : 'opacity-50'}`}
                                                            disabled={missionVote !== null}
                                                        >
                                                            <motion.div
                                                                className="w-32 h-48 bg-gradient-to-br from-red-600 to-red-900 rounded-2xl shadow-2xl border-4 border-red-400 flex flex-col items-center justify-center p-4 transform transition-all hover:scale-110 hover:-rotate-3 hover:shadow-red-500/50"
                                                                whileHover={{ scale: 1.1, rotate: -3 }}
                                                                whileTap={{ scale: 0.95 }}
                                                            >
                                                                <Image src="/assets/images/tokens/vote_reject.png" alt="Fail" width={80} height={80} className="drop-shadow-2xl" />
                                                                <span className="mt-2 text-white font-bold text-lg tracking-widest uppercase">SABOTAJE</span>
                                                            </motion.div>
                                                        </button>
                                                    )}

                                                    {/* Carta de Éxito segundo */}
                                                    <button
                                                        onClick={() => handleMissionVote(true)}
                                                        className={`group transition-opacity ${missionVote === true ? 'opacity-100' : 'opacity-50'}`}
                                                        disabled={missionVote !== null}
                                                    >
                                                        <motion.div
                                                            className="w-32 h-48 bg-gradient-to-br from-blue-600 to-blue-900 rounded-2xl shadow-2xl border-4 border-blue-400 flex flex-col items-center justify-center p-4 transform transition-all hover:scale-110 hover:rotate-3 hover:shadow-blue-500/50"
                                                            whileHover={{ scale: 1.1, rotate: 3 }}
                                                            whileTap={{ scale: 0.95 }}
                                                        >
                                                            <Image src="/assets/images/tokens/vote_approve.png" alt="Success" width={80} height={80} className="drop-shadow-2xl" />
                                                            <span className="mt-2 text-white font-bold text-lg tracking-widest uppercase">ÉXITO</span>
                                                        </motion.div>
                                                    </button>
                                                </>
                                            )}
                                        </div>
                                    </div>
                                ) : (
                                    <div className="text-white text-3xl font-mono bg-black/70 p-8 rounded-xl border-2 border-white/20 text-center">
                                        <div className="animate-pulse mb-4 text-5xl">⏳</div>
                                        La misión está en curso...<br />
                                        <span className="text-lg text-gray-400 mt-2 block">Esperando a que el equipo complete su votación.</span>
                                    </div>
                                )}
                            </motion.div>
                        )}

                        {/* FASE: REVELACIÓN DE CARTAS */}
                        {gameState.phase === 'mission_reveal' as any && (
                            <MissionReveal
                                votes={gameState.revealedVotes || []}
                                onFinished={() => actions.finishMissionReveal()}
                            />
                        )}

                        {/* FASE: RESULTADO DE MISIÓN */}
                        {gameState.phase === 'mission_result' as any && (
                            <MissionResult
                                gameState={gameState}
                                isHost={isHost}
                                onContinue={() => isHost && actions.finishMissionResult()}
                            />
                        )}

                        {/* FASE: ASESINO (FRANCOTIRADOR) */}
                        {gameState.phase === GamePhase.ASSASSIN_PHASE && (
                            <motion.div
                                className="w-full flex flex-col items-center gap-6"
                                initial={{ opacity: 0, y: 20 }}
                                animate={{ opacity: 1, y: 0 }}
                            >
                                {currentPlayer?.role === 'francotirador' && (
                                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 max-w-4xl">
                                        {gameState.players
                                            .filter(p => p.faction === Faction.ALIADOS) // Solo jugadores Aliados
                                            .map(player => (
                                                <motion.button
                                                    key={player.id}
                                                    onClick={() => actions.assassinKill(player.id)}
                                                    className="bg-black/60 hover:bg-red-600/70 border-2 border-white/30 hover:border-red-500 p-3 rounded-lg transition-all backdrop-blur-sm flex flex-col items-center gap-2"
                                                    whileHover={{ scale: 1.05 }}
                                                    whileTap={{ scale: 0.95 }}
                                                >
                                                    <div className="w-20 h-20 rounded-full border-2 border-white/50 overflow-hidden bg-black relative shadow-xl">
                                                        <Image
                                                            src={`/assets/images/characters/${player.avatar}`}
                                                            alt={player.name}
                                                            fill
                                                            className="object-cover"
                                                        />
                                                    </div>
                                                    <p className="text-white font-bold text-sm drop-shadow-[0_2px_4px_rgba(0,0,0,0.8)]">{player.name}</p>
                                                </motion.button>
                                            ))}
                                    </div>
                                )}

                                {currentPlayer?.role !== 'francotirador' && (
                                    <div className="text-white text-xl font-mono bg-black/50 px-6 py-3 rounded-full border border-white/20 animate-pulse">
                                        El Francotirador está decidiendo...
                                    </div>
                                )}
                            </motion.div>
                        )}

                        {/* FASE: VICTORIA NAZIS */}
                        {gameState.phase === GamePhase.NAZIS_WIN && (
                            <VictoryScreen
                                gameState={gameState}
                                isHost={isHost}
                                onRestart={() => actions.restartGame()}
                                onFinalize={() => actions.finalizeGame()}
                            />
                        )}

                        {/* FASE: VICTORIA ALIADOS */}
                        {gameState.phase === GamePhase.ALLIED_WIN && (
                            <VictoryScreen
                                gameState={gameState}
                                isHost={isHost}
                                onRestart={() => actions.restartGame()}
                                onFinalize={() => actions.finalizeGame()}
                            />
                        )}

                    </AnimatePresence>
                </div>

                {/* JUGADORES - POSICIONADOS ABSOLUTAMENTE EN EL FONDO */}
                <motion.div
                    className="fixed bottom-0 left-0 right-0 z-50 bg-black/80 border-t border-white/10 backdrop-blur-md"
                    initial={false}
                    animate={{
                        y: isPlayersCollapsed ? '100%' : '0%'
                    }}
                    transition={{ type: "spring", stiffness: 300, damping: 30 }}
                >
                    {/* Botón de colapso/expansión */}
                    <div className="absolute -top-10 left-1/2 transform -translate-x-1/2">
                        <button
                            onClick={() => setIsPlayersCollapsed(!isPlayersCollapsed)}
                            className="bg-gradient-to-b from-yellow-600 to-yellow-700 hover:from-yellow-500 hover:to-yellow-600 text-white rounded-t-lg px-6 py-2 shadow-lg border-2 border-yellow-500 border-b-0 transition-all hover:shadow-yellow-500/50 flex items-center gap-2"
                        >
                            <motion.svg
                                xmlns="http://www.w3.org/2000/svg"
                                className="h-5 w-5"
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke="currentColor"
                                animate={{ rotate: isPlayersCollapsed ? 180 : 0 }}
                                transition={{ duration: 0.3 }}
                            >
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M19 9l-7 7-7-7" />
                            </motion.svg>
                            <span className="text-sm font-bold uppercase tracking-wider">
                                {isPlayersCollapsed ? 'Mostrar' : 'Ocultar'}
                            </span>
                        </button>
                    </div>

                    <div className="w-full px-4 py-2 flex flex-wrap items-center justify-center gap-4">
                        {gameState.players.map((player) => {
                            const isSelected = selectedTeam.includes(player.id);
                            const isMe = player.id === currentPlayerId;

                            // Avatar logic
                            const avatarSrc = `/assets/images/characters/${player.avatar}`;

                            return (
                                <div
                                    key={player.id}
                                    onClick={() => isLeader && gameState.phase === GamePhase.TEAM_BUILDING && toggleTeamSelection(player.id)}
                                    className={`
                                    relative flex flex-col items-center cursor-pointer transition-all duration-300 group
                                    ${isSelected ? 'scale-110 z-10' : 'scale-100 opacity-70 hover:opacity-100 hover:scale-105'}
                                `}
                                >
                                    {/* Avatar */}
                                    <div className="relative rounded-full border-2 overflow-hidden shadow-lg bg-black transition-all w-16 h-16
                                        ${isSelected ? 'border-yellow-400 ring-4 ring-yellow-400/30 shadow-yellow-400/20' : 'border-gray-500 group-hover:border-gray-300'}
                                        ${gameState.currentLeaderId === player.id ? 'ring-2 ring-white' : ''}
                                    ">
                                        <Image
                                            src={avatarSrc}
                                            alt={player.name}
                                            fill
                                            className="object-cover"
                                        />

                                        {/* Icono de Líder */}
                                        {gameState.currentLeaderId === player.id && (
                                            <div className="absolute bottom-0 right-0 bg-yellow-500 rounded-full p-1 w-6 h-6 flex items-center justify-center text-[10px] text-black font-bold border border-white z-20 shadow-sm">
                                                L
                                            </div>
                                        )}

                                        {/* Icono de Miembro del Equipo de Misión */}
                                        {gameState.proposedTeam.includes(player.id) && (
                                            gameState.phase === GamePhase.VOTING_TEAM ||
                                            gameState.phase === GamePhase.MISSION ||
                                            gameState.phase === 'mission_reveal' as any ||
                                            gameState.phase === 'mission_result' as any
                                        ) && (
                                                <div className="absolute top-0 left-0 bg-green-500 rounded-full p-1 w-6 h-6 flex items-center justify-center text-xs text-white font-bold border border-white z-20">
                                                    ⭐
                                                </div>
                                            )}
                                    </div>

                                    {/* Nombre */}
                                    <span className={`
                                    mt-1 text-xs font-mono px-2 py-0.5 rounded shadow-sm whitespace-nowrap max-w-[100px] truncate
                                    ${isMe ? 'bg-blue-600 text-white font-bold' : 'bg-black/60 text-gray-300 border border-white/10'}
                                `}>
                                        {player.name}
                                    </span>
                                </div>
                            );
                        })}
                    </div>
                </motion.div>

                {/* HISTÓRICO DE MISIONES (Esquina superior derecha) */}
                {gameState.missionHistory.length > 0 && (
                    <motion.div
                        className="fixed top-[60px] right-0 z-50"
                        initial={false}
                        animate={{
                            x: isHistoryCollapsed ? '0%' : '0%'
                        }}
                        transition={{ type: "spring", stiffness: 300, damping: 30 }}
                    >
                        {/* Botón de colapso/expansión */}
                        <motion.button
                            onClick={() => setIsHistoryCollapsed(!isHistoryCollapsed)}
                            className="absolute top-0 bg-gradient-to-l from-yellow-600 to-yellow-700 hover:from-yellow-500 hover:to-yellow-600 text-white rounded-l-lg px-2 py-3 shadow-lg border-2 border-yellow-500 border-r-0 transition-all hover:shadow-yellow-500/50 flex items-center"
                            initial={false}
                            animate={{
                                right: isHistoryCollapsed ? '0px' : '100%'
                            }}
                            transition={{ type: "spring", stiffness: 300, damping: 30 }}
                        >
                            <motion.svg
                                xmlns="http://www.w3.org/2000/svg"
                                className="h-4 w-4"
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke="currentColor"
                                animate={{ rotate: isHistoryCollapsed ? 0 : 180 }}
                                transition={{ duration: 0.3 }}
                            >
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M15 19l-7-7 7-7" />
                            </motion.svg>
                        </motion.button>

                        {/* Panel del historial */}
                        <motion.div
                            className="bg-black/80 p-3 rounded-lg border border-white/20 backdrop-blur-sm"
                            initial={false}
                            animate={{
                                x: isHistoryCollapsed ? '100%' : '0%'
                            }}
                            transition={{ type: "spring", stiffness: 300, damping: 30 }}
                        >
                            <div className="text-[10px] text-gray-400 uppercase mb-2 text-center font-bold tracking-wider">Historial</div>
                            <div className="flex gap-2">
                                {gameState.missionHistory.map((mission, idx) => {
                                    const isExpanded = expandedMission === idx;

                                    return (
                                        <div key={idx} className="relative">
                                            <div
                                                className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold border-2 cursor-pointer transition-all hover:scale-110 ${mission.isSuccess
                                                    ? 'bg-blue-600 border-blue-400 text-white'
                                                    : 'bg-red-600 border-red-400 text-white'
                                                    } ${isExpanded ? 'ring-2 ring-yellow-400 relative z-[60]' : ''}`}
                                                title={`Misión ${mission.round}: ${mission.isSuccess ? 'Éxito' : 'Fracaso'} (${mission.successes}✓ ${mission.fails}✗)`}
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    console.log('Click en misión', idx);
                                                    setExpandedMission(prev => prev === idx ? null : idx);
                                                }}
                                            >
                                                {mission.round}
                                            </div>

                                            {/* Lista de participantes */}
                                            {isExpanded && (
                                                <div className="absolute top-10 right-0 bg-black/95 p-2 rounded border border-white/30 min-w-max z-[100]">
                                                    {mission.team.map((playerId) => {
                                                        const player = gameState.players.find(p => p.id === playerId);
                                                        return (
                                                            <div key={playerId} className="text-xs text-white whitespace-nowrap">
                                                                {player?.name || playerId}
                                                            </div>
                                                        );
                                                    })}
                                                </div>
                                            )}
                                        </div>
                                    );
                                })}
                            </div>
                        </motion.div>
                    </motion.div>
                )}
            </div>
        </div>
    );
}

// Subcomponente para el Timer de Votación (solo visual, el servidor controla el timeout real)
function VotingTimer() {
    const [timeLeft, setTimeLeft] = useState(10);

    useEffect(() => {
        if (timeLeft <= 0) {
            return; // El servidor se encargará de forzar la resolución
        }
        const interval = setInterval(() => setTimeLeft(t => t - 1), 1000);
        return () => clearInterval(interval);
    }, [timeLeft]);

    return (
        <div className="fixed top-5 left-5 bg-red-600/80 text-white w-16 h-16 rounded-full flex items-center justify-center border-4 border-red-400 animate-pulse text-2xl font-bold font-mono">
            {timeLeft}
        </div>
    );
}
