'use client'; import { useState, useEffect } from 'react'; import { useSocket } from '../hooks/useSocket'; import { motion, AnimatePresence } from 'framer-motion'; import Image from 'next/image'; import GameBoard from '../components/GameBoard'; import { GameRoom } from '../../../shared/types'; // Constantes de apellidos const SURNAMES = [ // Franceses 'Dubois', 'Leroy', 'Moreau', 'Petit', 'Lefebvre', 'Michel', 'Durand', // Británicos 'Smith', 'Jones', 'Williams', 'Brown', 'Taylor', 'Wilson', 'Evans', // Americanos 'Miller', 'Davis', 'Garcia', 'Rodriguez', 'Martinez', 'Hernandez' ]; type ViewState = 'login' | 'lobby' | 'game'; export default function Home() { const { isConnected, gameState, roomsList, actions, socket } = useSocket(); // Estados locales de UI const [view, setView] = useState('login'); const [playerName, setPlayerName] = useState(''); // El apellido se genera al loguearse const [fullPlayerName, setFullPlayerName] = useState(''); // UI Create/Join const [showCreateModal, setShowCreateModal] = useState(false); const [createConfig, setCreateConfig] = useState({ maxPlayers: 5, password: '' }); const [passwordPromptRoomId, setPasswordPromptRoomId] = useState(null); const [joinPassword, setJoinPassword] = useState(''); // Efecto para cambiar a vista de juego cuando el servidor nos une useEffect(() => { if (gameState?.roomId) { setView('game'); } else if (view === 'game' && !gameState) { // Si estábamos en juego y volvemos a null, volver al lobby setView('lobby'); } }, [gameState]); const handleLogin = (e: React.FormEvent) => { e.preventDefault(); if (playerName) { // Generar apellido aleatorio const randomSurname = SURNAMES[Math.floor(Math.random() * SURNAMES.length)]; setFullPlayerName(`${playerName} ${randomSurname}`); setView('lobby'); actions.refreshRooms(); } }; const handleCreateGame = (e: React.FormEvent) => { e.preventDefault(); actions.createGame(fullPlayerName, createConfig.maxPlayers, createConfig.password); setShowCreateModal(false); }; const requestJoinGame = (room: GameRoom) => { if (room.isPrivate) { setPasswordPromptRoomId(room.id); setJoinPassword(''); } else { actions.joinGame(room.id, fullPlayerName); } }; const submitJoinPassword = () => { if (passwordPromptRoomId) { actions.joinGame(passwordPromptRoomId, fullPlayerName, joinPassword); setPasswordPromptRoomId(null); } }; // --- RENDER DE JUEGO O SALA DE ESPERA --- if (view === 'game' && gameState && socket) { // ¿Estamos en fase de lobby dentro de la partida? if (gameState.phase === 'lobby') { const isHost = gameState.hostId === socket.id; // Podríamos obtener maxPlayers del array players si no lo tenemos en gameState, // pero lo ideal sería tenerlo. Por ahora asumimos que si ya estamos dentro, // sabemos cuantos somos. // NOTA: GameState no tiene maxPlayers explicitamente, pero podemos deducirlo o añadirlo. // Por simplicidad, usaremos el length para validar minimo. return (
War Room

Sala de Espera

Operación en curso. Esperando activación...

{gameState.players.map(player => (
{player.name} {player.id === gameState.hostId && ( HOST )}
))} {/* Rellenar huecos vacíos visualmente si quisieramos */}
{isHost ? ( <>

Jugadores: {gameState.players.length} {gameState.players.length < 5 && (Mínimo 5 requeridos)}

) : (

Esperando al Comandante...

La misión comenzará cuando el líder dé la orden.

)}
); } return ( ); } return (
{/* FONDO COMÚN LOBBY/LOGIN */}
Lobby Background
{/* HEADER / LOGO */}
Logo

Francia Ocupada

{view === 'lobby' && (
AGENTE: {fullPlayerName}
)}
{/* --- PANTALLA DE LOGIN --- */} {view === 'login' && (

Identificación

setPlayerName(e.target.value)} className="w-full bg-white/10 border border-white/20 p-3 rounded text-white focus:outline-none focus:border-yellow-500 transition-colors" placeholder="Ej: Agente" />
{/* APELLIDO ELIMINADO - SE GENERA AUTOMÁTICAMENTE */}
)} {/* --- PANTALLA DE LOBBY (LISTA DE SALAS) --- */} {view === 'lobby' && (

MISIONES ACTIVAS

Selecciona una operación o inicia una nueva.

{roomsList.length === 0 ? (
No hay misiones activas en este momento.
) : ( roomsList.map((room) => (
{room.isPrivate ? ( 🔒 ) : ( 🔓 )}

{room.name}

HOST: {room.hostId.substring(0, 6)}...
{room.currentPlayers} / {room.maxPlayers}
{/* Barra de progreso visual */}
)) )}
)}
{/* --- MODALES --- */} {/* Modal Crear */} {showCreateModal && (

Configurar Operación

setCreateConfig({ ...createConfig, password: e.target.value })} className="w-full bg-black/40 border border-white/10 p-2 rounded text-white font-mono" placeholder="Dejar vacío para pública" />
)} {/* Modal Password */} {passwordPromptRoomId && (

🔒 Acceso Restringido

Esta operación es clasificada. Introduce la clave de acceso.

setJoinPassword(e.target.value)} onKeyDown={e => e.key === 'Enter' && submitJoinPassword()} className="w-full bg-black/40 border border-red-900/30 p-2 rounded text-white font-mono mb-4 focus:border-red-500 outline-none" placeholder="Clave de acceso..." />
)}
{isConnected ? ● CONEXIÓN SEGURA : ● BUSCANDO SEÑAL...}
); }