{state.name}
{type?.label} · {state.digits} digits
{actionError}
}'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import {
GAME_TYPES,
chooseSecret,
clearSession,
formatTime,
getState,
leaveGame,
leaveGameBeacon,
loadSession,
sendGuess,
} from '../api';
import NumberPad from '../NumberPad';
import useTicker from '../useTicker';
// Leaving on unmount is deferred so React StrictMode's mount → unmount → mount (dev) does not end the game.
let pendingLeave = null;
export default function MultiplayerPlayPage() {
const router = useRouter();
const [session, setSession] = useState(null);
const [state, setState] = useState(null);
const [receivedAt, setReceivedAt] = useState(0);
const [fatal, setFatal] = useState('');
const [actionError, setActionError] = useState('');
const [busy, setBusy] = useState(false);
const [, setClock] = useState(0);
const seq = useRef(0);
const applied = useRef(0);
const activeRef = useRef(false);
useEffect(() => {
const s = loadSession();
if (!s) router.replace('/multiplayer');
else setSession(s);
}, [router]);
// Ignore responses that are older than the latest applied one (poll vs. guess races).
const apply = (id, data) => {
if (id < applied.current) return;
applied.current = id;
setState(data);
setReceivedAt(Date.now());
activeRef.current = data.stage !== 'FINISHED';
};
const poll = useCallback(async () => {
if (!session) return;
const id = ++seq.current;
try {
apply(id, await getState(session.gameId, session.token));
} catch (err) {
if (err.status === 404 || err.status === 403) {
activeRef.current = false;
clearSession();
setFatal('This game is no longer available.');
}
}
}, [session]);
const finished = state?.stage === 'FINISHED';
useTicker(poll, 1000, !!session && !finished && !fatal);
// Local clock for the timer display.
useEffect(() => {
const t = setInterval(() => setClock((c) => c + 1), 500);
return () => clearInterval(t);
}, []);
// Closing / refreshing the tab or navigating away leaves the game.
useEffect(() => {
if (!session) return;
clearTimeout(pendingLeave);
const onPageHide = () => {
if (activeRef.current) leaveGameBeacon(session.gameId, session.token);
};
const onBeforeUnload = (e) => {
if (activeRef.current) {
e.preventDefault();
e.returnValue = '';
}
};
window.addEventListener('pagehide', onPageHide);
window.addEventListener('beforeunload', onBeforeUnload);
return () => {
window.removeEventListener('pagehide', onPageHide);
window.removeEventListener('beforeunload', onBeforeUnload);
if (activeRef.current) {
pendingLeave = setTimeout(() => leaveGameBeacon(session.gameId, session.token), 300);
}
};
}, [session]);
const runAction = async (fn) => {
setBusy(true);
setActionError('');
const id = ++seq.current;
try {
apply(id, await fn());
return true;
} catch (err) {
setActionError(err.message);
poll();
return false;
} finally {
setBusy(false);
}
};
const handleGuess = (number) => runAction(() => sendGuess(session.gameId, session.token, number));
const handleSecret = (number) => runAction(() => chooseSecret(session.gameId, session.token, number));
const handleLeave = async () => {
if (activeRef.current) {
if (!window.confirm('Leaving ends the game for both players. Leave?')) return;
activeRef.current = false;
await leaveGame(session.gameId, session.token);
}
clearSession();
router.push('/multiplayer');
};
if (fatal) {
return (
{fatal} Loading game…
{type?.label} · {state.digits} digits
{actionError}{state.name}
Waiting for a rival to join…
Your friend can join “{state.name}” from the Multiplayer lobby. Keep this page open: leaving closes the game.
Choose a {state.digits}-digit number for your rival
Each digit can be used only once.
Your rival will search for {you.secretForRival}
)}{rival?.secretChosen ? 'Rival has chosen your number.' : 'Rival is choosing your number…'}
{status}
{!(state.type === 'TIME_CHALLENGE' && you.found) && (Your rival is searching for {you.secretForRival}
)} > ); } function ResultPanel({ state, onBack }) { const { you, rival, outcome, endReason, youLeft } = state; const banner = { WIN: ['You Won!', 'text-emerald-400'], LOSE: ['You Lost', 'text-rose-400'], DRAW: ['Draw', 'text-amber-300'], }[outcome] || ['Game Closed', 'text-neutral-300']; let reason = ''; if (endReason === 'PLAYER_LEFT') reason = youLeft ? 'You left the game.' : 'Your rival left the game.'; else if (state.type === 'TIME_CHALLENGE') reason = 'Both players found the number.'; else reason = you.found && rival?.found ? 'Both players found their number in the same round.' : 'A number was found.'; const rows = [ ['Number to find', (p) => {p?.numberToFind ?? '-'}], ['Found', (p) => (p?.found ? '✔' : '✘')], ['Turns', (p) => p?.attempts ?? '-'], ['Time', (p) => formatTime(p?.timeMs)], ['Score', (p) => {p?.score ?? '-'}], ]; return ({banner[0]}
{reason}
{rival && (| You | Rival | |
|---|---|---|
| {label} | {render(you)} | {render(rival)} |
Score = 1000 × digits − 100 × turns − 2 × seconds (min 100 if found, 0 if not found).
No guesses yet.
} {items.map((h) => (