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

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

export default function GameBoard({ gameState, currentPlayerId, actions }: 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);


    // 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]);


    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);
    };

    // Componente de Debug para mostrar facción
    const DebugInfo = () => (
        <div className="fixed top-2 left-2 bg-black/80 text-white p-3 rounded-lg text-xs z-50 border border-yellow-500 font-mono shadow-xl pointer-events-none">
            <div className="font-bold text-yellow-400 mb-1 flex items-center gap-2">
                <span>🐛 DEBUG INFO</span>
            </div>
            <div className="space-y-1">
                <div>Fase: <span className="text-cyan-400 font-bold">{gameState.phase}</span></div>
                <div>ID: <span className="text-green-400">{currentPlayerId}</span></div>
                <div>Facción: <span className={`font-bold ${currentPlayer?.faction === 'spies' ? 'text-red-500' : 'text-blue-400'}`}>
                    {currentPlayer?.faction || 'UNDEFINED'}
                </span></div>
                <div>Rol: <span className="text-purple-400">{currentPlayer?.role || 'UNDEFINED'}</span></div>
                {gameState.currentLeaderId && (
                    <div>Líder: <span className="text-yellow-400">{gameState.currentLeaderId === currentPlayerId ? 'TÚ' : gameState.currentLeaderId}</span></div>
                )}
            </div>
        </div>
    );


    // Coordenadas porcentuales de los hexágonos de misión en el mapa
    const missionCoords = [
        { left: '12%', top: '55%' }, // Misión 1
        { left: '28%', top: '15%' }, // Misión 2
        { left: '52%', top: '25%' }, // Misión 3
        { left: '42%', top: '70%' }, // Misión 4
        { left: '82%', top: '40%' }, // Misión 5
    ];

    // --- 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-5xl font-bold uppercase tracking-[0.3em] mb-8 text-yellow-500 drop-shadow-lg text-center">
                    Guerra Total
                </h1>

                {/* Audio Auto-Play */}
                <audio
                    src="/assets/audio/Intro.ogg"
                    autoPlay
                    onEnded={() => isHost && 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 básico: 
        // Merlin -> good_merlin.png
        // Percival -> good_percival.png
        // Servant -> good_soldier_X.png (random)
        // Assassin -> evil_assassin.png
        // Morgana -> evil_morgana.png
        // Mordred -> evil_mordred.png
        // Oberon -> evil_oberon.png
        // Minion -> evil_minion_X.png

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

        const role = currentPlayer?.role;
        if (role === 'merlin') roleImage = '/assets/images/characters/good_merlin.png';
        else if (role === 'assassin') roleImage = '/assets/images/characters/evil_assassin.png';
        else if (role === 'percival') roleImage = '/assets/images/characters/good_percival.png';
        else if (role === 'morgana') roleImage = '/assets/images/characters/evil_morgana.png';
        else if (role === 'mordred') roleImage = '/assets/images/characters/evil_mordred.png';
        else if (role === 'oberon') roleImage = '/assets/images/characters/evil_oberon.png';
        else if (role === 'loyal_servant') {
            // Random soldier 1-5
            const idx = (currentPlayerId.charCodeAt(0) % 5) + 1;
            roleImage = `/assets/images/characters/good_soldier_${idx}.png`;
        }
        else if (role === 'minion') {
            // 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.2}
                            onDragEnd={(e, info) => {
                                // Reducir umbral a -50 para facilitar
                                if (info.offset.y < -50) {
                                    setRevealCard(true);
                                }
                            }}
                            whileHover={{ scale: 1.02 }}
                            whileTap={{ scale: 0.98, cursor: 'grabbing' }}
                            animate={revealCard ? { y: -1000, opacity: 0 } : { y: 0, opacity: 1 }}
                            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 items-center justify-center bg-black overflow-hidden text-white font-mono">
                {/* Debug Info */}
                <DebugInfo />

                <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 w-full max-w-5xl px-4">
                    <h2 className="text-3xl text-center mb-12 uppercase tracking-[0.2em] text-gray-300 border-b border-gray-600 pb-4">
                        Pasando Lista...
                    </h2>

                    {isHost && (
                        <audio
                            src="/assets/audio/Rondas.ogg"
                            autoPlay
                            onEnded={() => actions.finishRollCall()} // Host avanza cuando acaba audio
                        />
                    )}

                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8">
                        {gameState.players.map((p, i) => {
                            // Asignar avatar determinista basado en charCode
                            const avatarIdx = (p.name.length % 3) + 1;
                            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-3"
                                >
                                    <div className="w-32 h-32 rounded-full border-4 border-gray-400 overflow-hidden relative shadow-2xl bg-black">
                                        <Image
                                            src={`/assets/images/characters/avatar_${avatarIdx}.png`}
                                            alt="Avatar"
                                            fill
                                            className="object-cover grayscale contrast-125"
                                        />
                                    </div>
                                    <div className="bg-black/80 px-4 py-1 rounded border border-white/20 text-xl font-bold text-yellow-500 uppercase">
                                        {p.name}
                                    </div>
                                </motion.div>
                            );
                        })}
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="relative w-full h-screen flex flex-col items-center overflow-hidden">
            {/* Debug Info */}
            <DebugInfo />

            <div className="absolute inset-0 z-0 opacity-40">
                <Image src="/assets/images/ui/bg_game.png" alt="Game Background" fill className="object-cover" />
                <div className="absolute inset-0 bg-black/60" />
            </div>

            <div className="relative z-10 w-full flex flex-col items-center">

                {/* --- MAPA TÁCTICO (TABLERO) --- */}
                <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]">
                    <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-[12%] aspect-square flex items-center justify-center transform -translate-x-1/2 -translate-y-1/2"
                                style={{ left: coord.left, top: coord.top }}
                            >
                                {/* 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"
                                    >
                                        <Image src="/assets/images/tokens/marker_score_blue.png" alt="Success" fill className="object-contain drop-shadow-lg" />
                                    </motion.div>
                                )}
                                {result === false && (
                                    <motion.div
                                        initial={{ scale: 0 }} animate={{ scale: 1 }}
                                        className="absolute inset-0 z-20"
                                    >
                                        <Image src="/assets/images/tokens/marker_score_red.png" alt="Fail" fill className="object-contain drop-shadow-lg" />
                                    </motion.div>
                                )}
                            </div>
                        );
                    })}

                    {/* TRACK DE VOTOS FALLIDOS (Pequeño indicador en la esquina inferior izquierda del mapa) */}
                    <div className="absolute bottom-[5%] left-[2%] bg-black/60 p-2 rounded border border-white/20">
                        <div className="text-[10px] text-gray-300 uppercase mb-1 text-center">Votos Rechazados</div>
                        <div className="flex gap-1">
                            {[...Array(5)].map((_, i) => (
                                <div key={i} className={`w-3 h-3 rounded-full border border-gray-500 ${i < gameState.failedVotesCount ? 'bg-red-500' : 'bg-transparent'}`} />
                            ))}
                        </div>
                    </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 */}
                                    {!gameState.leaderVotes?.[currentPlayerId] && (
                                        <VotingTimer onTimeout={() => actions.voteLeader(null)} />
                                    )}
                                </div>

                                {gameState.leaderVotes?.[currentPlayerId] === undefined ? (
                                    <div className="flex gap-8">
                                        <button onClick={() => actions.voteLeader(true)} className="group">
                                            <div className="w-40 h-60 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-40 h-60 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 */}
                                <div className="bg-yellow-600/90 text-black p-4 rounded-lg shadow-xl border-4 border-yellow-400 w-full text-center">
                                    <div className="flex items-center justify-center gap-3">
                                        <Image src="/assets/images/tokens/token_leader.png" alt="Leader" width={40} height={40} />
                                        <div>
                                            <div className="text-sm uppercase tracking-wider font-bold">Líder Actual</div>
                                            <div className="text-2xl font-bold">
                                                {gameState.players.find(p => p.id === gameState.currentLeaderId)?.name || 'Desconocido'}
                                            </div>
                                        </div>
                                        <Image src="/assets/images/tokens/token_leader.png" alt="Leader" width={40} height={40} />
                                    </div>
                                </div>

                                {/* Mensaje para el líder o para los demás */}
                                <div className="bg-paper-bg text-black p-6 rounded shadow-2xl rotate-1 w-full text-center">
                                    <h2 className="text-2xl font-bold font-mono mb-2 uppercase text-resistance-blue">
                                        {isLeader ? '🎯 TU TURNO: ELIGE TU EQUIPO' : '⏳ ESPERANDO AL LÍDER...'}
                                    </h2>
                                    <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>

                                {!currentPlayer?.hasVoted ? (
                                    <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 items-center justify-center border-4 border-transparent group-hover:border-green-500 transition-all transform group-hover:-translate-y-4">
                                                <Image src="/assets/images/tokens/vote_approve.png" alt="Approve" width={100} height={100} />
                                            </div>
                                            <span className="block text-center text-white mt-2 font-bold bg-green-600 px-2 rounded">APROBAR</span>
                                        </button>
                                        <button onClick={() => actions.voteTeam(false)} className="group">
                                            <div className="w-32 h-48 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">
                                                <Image src="/assets/images/tokens/vote_reject.png" alt="Reject" width={100} height={100} />
                                            </div>
                                            <span className="block text-center text-white mt-2 font-bold bg-red-600 px-2 rounded">RECHAZAR</span>
                                        </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-center justify-center bg-black/90 z-50"
                                initial={{ opacity: 0 }}
                                animate={{ opacity: 1 }}
                            >
                                {gameState.proposedTeam.includes(currentPlayerId) ? (
                                    <div className="flex flex-col items-center gap-8 w-full max-w-6xl px-4">
                                        <h2 className="text-4xl md:text-5xl font-bold text-white mb-4 drop-shadow-2xl text-center uppercase tracking-wider animate-pulse">
                                            🎯 ¡ESTÁS EN LA MISIÓN!
                                        </h2>
                                        <p className="text-white text-xl mb-4 text-center">
                                            Elige el resultado de tu participación
                                        </p>

                                        {/* DEBUG INFO - TEMPORAL */}
                                        <div className="text-xs text-gray-400 bg-black/50 p-2 rounded mb-4">
                                            Debug: Tu ID: {currentPlayerId} | Equipo: [{gameState.proposedTeam.join(', ')}]
                                            <br />
                                            Tu facción: {currentPlayer?.faction || 'UNDEFINED'} | Rol: {currentPlayer?.role || 'UNDEFINED'}
                                        </div>

                                        {/* 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 !== null && missionVote !== true ? 'opacity-50' : 'opacity-100'}`}
                                                        disabled={missionVote !== null}
                                                    >
                                                        <motion.div
                                                            className="w-64 h-96 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-6 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={180} height={180} className="drop-shadow-2xl" />
                                                            <span className="mt-6 text-white font-bold text-2xl tracking-widest uppercase">ÉXITO</span>
                                                        </motion.div>
                                                    </button>

                                                    {/* Carta de Sabotaje segundo (solo para espías) */}
                                                    {currentPlayer?.faction === 'spies' && (
                                                        <button onClick={() => handleMissionVote(false)} className="group transition-opacity" style={{ opacity: missionVote !== null && missionVote !== false ? 0.5 : 1 }} disabled={missionVote !== null}>
                                                            <motion.div
                                                                className="w-64 h-96 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-6 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={180} height={180} className="drop-shadow-2xl" />
                                                                <span className="mt-6 text-white font-bold text-2xl tracking-widest uppercase">SABOTAJE</span>
                                                            </motion.div>
                                                        </button>
                                                    )}
                                                </>
                                            ) : (
                                                <>
                                                    {/* Carta de Sabotaje primero (solo para espías) */}
                                                    {currentPlayer?.faction === 'spies' && (
                                                        <button onClick={() => handleMissionVote(false)} className="group transition-opacity" style={{ opacity: missionVote !== null && missionVote !== false ? 0.5 : 1 }} disabled={missionVote !== null}>
                                                            <motion.div
                                                                className="w-64 h-96 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-6 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={180} height={180} className="drop-shadow-2xl" />
                                                                <span className="mt-6 text-white font-bold text-2xl tracking-widest uppercase">SABOTAJE</span>
                                                            </motion.div>
                                                        </button>
                                                    )}

                                                    {/* Carta de Éxito segundo */}
                                                    <button
                                                        onClick={() => handleMissionVote(true)}
                                                        className={`group transition-opacity ${missionVote !== null && missionVote !== true ? 'opacity-50' : 'opacity-100'}`}
                                                        disabled={missionVote !== null}
                                                    >
                                                        <motion.div
                                                            className="w-64 h-96 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-6 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={180} height={180} className="drop-shadow-2xl" />
                                                            <span className="mt-6 text-white font-bold text-2xl 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}
                                onContinue={() => isHost && actions.finishMissionResult()}
                            />
                        )}

                    </AnimatePresence>
                </div>

                {/* JUGADORES (TIENDA DE CAMPAÑA) */}
                <div className="z-10 w-full overflow-x-auto pb-4">
                    <div className="flex justify-center gap-4 min-w-max px-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
                  ${isSelected ? 'scale-110' : 'scale-100 opacity-80 hover:opacity-100'}
                `}
                                >
                                    {/* Avatar */}
                                    <div className={`
                  w-16 h-16 rounded-full border-2 overflow-hidden relative shadow-lg bg-black
                  ${isSelected ? 'border-yellow-400 ring-4 ring-yellow-400/30' : 'border-gray-400'}
                  ${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-xs text-black font-bold border border-white z-10">
                                                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-10">
                                                    ⭐
                                                </div>
                                            )}
                                    </div>

                                    {/* Nombre */}
                                    <span className={`mt-2 text-xs font-mono px-2 py-0.5 rounded ${isMe ? 'bg-blue-600 text-white' : 'bg-black/50 text-gray-300'}`}>
                                        {player.name}
                                    </span>
                                </div>
                            );
                        })}
                    </div>
                </div>

                {/* HISTÓRICO DE MISIONES (Esquina superior derecha) */}
                {gameState.missionHistory.length > 0 && (
                    <div className="absolute top-4 right-4 bg-black/80 p-3 rounded-lg border border-white/20 backdrop-blur-sm">
                        <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) => (
                                <div
                                    key={idx}
                                    className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold border-2 ${mission.isSuccess
                                        ? 'bg-blue-600 border-blue-400 text-white'
                                        : 'bg-red-600 border-red-400 text-white'
                                        }`}
                                    title={`Misión ${mission.round}: ${mission.isSuccess ? 'Éxito' : 'Fracaso'} (${mission.successes}✓ ${mission.fails}✗)`}
                                >
                                    {mission.round}
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}

// Subcomponente para el Timer de Votación
function VotingTimer({ onTimeout }: { onTimeout: () => void }) {
    const [timeLeft, setTimeLeft] = useState(10);

    useEffect(() => {
        if (timeLeft <= 0) {
            onTimeout();
            return;
        }
        const interval = setInterval(() => setTimeLeft(t => t - 1), 1000);
        return () => clearInterval(interval);
    }, [timeLeft, onTimeout]);

    return (
        <div className="absolute top-4 right-4 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>
    );
}
