'use client';
import { useCallback, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { GAME_TYPES, createGame, joinGame, listGames, pruneMyGames, saveSession } from './api';
import useTicker from './useTicker';
const STATUS_STYLE = {
WAITING: 'bg-amber-500/20 text-amber-300 border-amber-500/40',
PLAYING: 'bg-blue-500/20 text-blue-300 border-blue-500/40',
CLOSED: 'bg-neutral-700/40 text-neutral-400 border-neutral-600',
};
export default function MultiplayerLobby() {
const router = useRouter();
const [games, setGames] = useState(null);
const [listError, setListError] = useState('');
const [showCreate, setShowCreate] = useState(false);
const [joining, setJoining] = useState(null);
const [joinError, setJoinError] = useState('');
const [myGames, setMyGames] = useState([]);
const refresh = useCallback(async () => {
try {
const list = await listGames();
setGames(list);
setMyGames(pruneMyGames(list));
setListError('');
} catch (err) {
setListError(err.message || 'Cannot reach the server');
}
}, []);
useTicker(refresh, 3000);
const enterGame = (res) => {
saveSession(res.gameId, res.playerToken, res.state?.you?.slot);
router.push('/multiplayer/play');
};
// Return to one of your own unfinished games (after closing the tab, a refresh or a connection loss).
const handleResume = (mine) => {
saveSession(mine.gameId, mine.token, mine.slot);
router.push('/multiplayer/play');
};
const handleJoin = async (id) => {
setJoining(id);
setJoinError('');
try {
enterGame(await joinGame(id));
} catch (err) {
setJoinError(err.message);
refresh();
} finally {
setJoining(null);
}
};
return (
{/* 3-column grid keeps the title centred without the Home link overlapping it on narrow screens */}
Games
{listError && {listError}
}
{joinError && {joinError}
}
{games === null && !listError && Loading…
}
{games?.length === 0 && (
No games yet. Create one and invite a friend!
)}
{games?.map((g) => {
const mine = myGames.filter((m) => m.gameId === g.id);
return (
-
{g.name}
{GAME_TYPES[g.type]?.label} · {g.digits} digits · {g.players}/2 players
{g.status.toLowerCase()}
{g.status !== 'CLOSED' &&
mine.map((m) => (
))}
{g.status === 'WAITING' && mine.length === 0 && (
)}
);
})}
{showCreate && setShowCreate(false)} onCreated={enterGame} />}
);
}
function CreateGameModal({ onClose, onCreated }) {
const [name, setName] = useState('');
const [digits, setDigits] = useState('4');
const [type, setType] = useState('AUTO_GUESSTURES');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const digitNum = parseInt(digits, 10);
const digitsValid = !isNaN(digitNum) && digitNum >= 3 && digitNum <= 10;
const valid = name.trim() !== '' && digitsValid;
const handleSubmit = async (e) => {
e.preventDefault();
if (!valid) return;
setLoading(true);
setError('');
try {
onCreated(await createGame(name.trim(), digitNum, type));
} catch (err) {
setError(err.message);
setLoading(false);
}
};
return (
);
}