'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}

); } if (!state) return

Loading game…

; const type = GAME_TYPES[state.type]; const roundBased = state.type !== 'TIME_CHALLENGE'; const elapsed = state.stage === 'PLAYING' ? state.elapsedMs + (Date.now() - receivedAt) : state.elapsedMs; return (

{state.name}

{type?.label} · {state.digits} digits

{(state.stage === 'PLAYING' || finished) && state.elapsedMs > 0 && ( ⏱ {formatTime(elapsed)} )} {roundBased && state.stage === 'PLAYING' && ( Round {state.round} )}
{/* Mobile: one scrolling column (game, then history). Desktop: side by side, each scrolls on its own. */}
{/* my-auto centres the content when there is room without clipping its top when there isn't */}
{state.stage === 'WAITING' && } {state.stage === 'SETUP' && ( )} {state.stage === 'PLAYING' && ( )} {finished && } {actionError &&

{actionError}

}
{(state.stage === 'PLAYING' || finished) && ( )}
); } function CenterMessage({ children }) { return
{children}
; } function WaitingPanel({ state }) { return (

Waiting for a rival to join…

Your friend can join “{state.name}” from the Multiplayer lobby. Keep this page open: leaving closes the game.

); } function SetupPanel({ state, busy, onSubmit }) { const { you, rival } = state; return ( <>

Choose a {state.digits}-digit number for your rival

Each digit can be used only once.

{you.secretChosen && (

Your rival will search for {you.secretForRival}

)}

{rival?.secretChosen ? 'Rival has chosen your number.' : 'Rival is choosing your number…'}

); } function PlayingPanel({ state, busy, onSubmit }) { const { you, rival } = state; const roundBased = state.type !== 'TIME_CHALLENGE'; let status; if (roundBased) { if (state.waitingForRival) status = Waiting for your rival's guess…; else if (rival && rival.attempts >= state.round) status = Your rival has guessed. Your turn!; else status = 'Make your guess.'; } else if (you.found) { status = ( You found it in {you.attempts} turns ({formatTime(you.timeMs)}), score {you.score}. Waiting for your rival to finish… ); } else { status = 'Find the number as fast as you can!'; } return ( <>

{status}

{!(state.type === 'TIME_CHALLENGE' && you.found) && ( )} {state.type === 'PLAYER_GUESSTURES' && you.secretForRival && (

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 && ( {rows.map(([label, render]) => ( ))}
You Rival
{label} {render(you)} {render(rival)}
)}

Score = 1000 × digits − 100 × turns − 2 × seconds (min 100 if found, 0 if not found).

); } function History({ title, history }) { const items = [...history].reverse(); return (

{title}

{items.length === 0 &&

No guesses yet.

} {items.map((h) => (
{h.turn}. {h.guess} {h.positive === null ? ( … ) : ( <> +{h.positive} -{h.negative} )}
))}
); }