"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { endBomperatorMatch, fetchBomperatorMatch, leaveBomperatorMatch, startBomperatorMatch, type BomperatorView, } from "@/app/(frontend)/minigames/bomperator/actions"; import { toast } from "sonner"; import { useRealtimePresence } from "@/hooks/useRealtimePresence"; import { BOMP_STATE_EVENT, BOMP_TERMINATED_EVENT, type BomperatorStateDetail, type BomperatorTerminatedDetail, } from "@/hooks/useGameTick"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { BomperatorLobby } from "./BomperatorLobby"; import { BomperatorGame } from "./BomperatorGame"; export interface BomperatorStats { matchesPlayed: number; matchWins: number; roundsWon: number; kills: number; xpEarned: number; } const STAT_ITEMS = [ ["Drills run", "matchesPlayed"], ["Drills won", "matchWins"], ["Rounds won", "roundsWon"], ["Technicians down", "kills"], ["XP earned", "xpEarned"], ] as const satisfies readonly (readonly [string, keyof BomperatorStats])[]; type ArenaView = "lobby" | "match"; /** * Snapshot delivery is push-first: the server broadcasts a per-user snapshot over * the SSE bus on every tick (see registry.pushSnapshots). This poll is only a * correctness fallback for dropped pushes / dev module reloads, so it runs far * slower than a tick and skips entirely while a request is already in flight. * 500ms is deliberately conservative: it is ~50x lighter than the old 40ms flood * (which saturated the dev server and delayed inputs by seconds), yet still bounds * staleness to half a second even if the push path never lands. */ const FALLBACK_POLL_MS = 500; export function BomperatorArena({ initialStats, currentUserId, initialMatchId, }: { initialStats: BomperatorStats; currentUserId: number | string; initialMatchId?: string; }) { const [view, setView] = useState(initialMatchId ? "match" : "lobby"); const [match, setMatch] = useState(null); const [matchId, setMatchId] = useState(initialMatchId ?? null); const [error, setError] = useState(null); /** Highest snapshot version applied; drops stale pushes/polls that arrive late. */ const lastVersionRef = useRef(-1); /** Once we've handled leaving a match (self or remote), suppress repeat toasts. */ const endedRef = useRef(false); const resetToLobby = useCallback(() => { lastVersionRef.current = -1; setView("lobby"); setMatch(null); setMatchId(null); setError(null); if (typeof window !== "undefined") { window.history.replaceState(null, "", "/minigames/bomperator"); } }, []); /** Apply a snapshot from any source (push or poll), ignoring stale versions. */ const applySnapshot = useCallback((next: BomperatorView) => { if (next.version <= lastVersionRef.current) return; lastVersionRef.current = next.version; setMatch(next); setMatchId(next.matchId); setView("match"); setError(null); }, []); const applyMatch = useCallback((next: BomperatorView) => { // Fresh match opened from the lobby: accept it regardless of version history. endedRef.current = false; lastVersionRef.current = next.version; setMatch(next); setMatchId(next.matchId); setView("match"); setError(null); if (typeof window !== "undefined" && next.matchId) { window.history.replaceState( null, "", `/minigames/bomperator?match=${encodeURIComponent(next.matchId)}`, ); } }, []); /** * Leave the current match with an explanatory toast, at most once per match. * Used by both the host-ended SSE event and the poll's "not found" fallback, so * whichever lands first wins and the other is ignored. */ const handleEnded = useCallback( (message: string) => { if (endedRef.current) return; endedRef.current = true; toast.info(message); resetToLobby(); }, [resetToLobby], ); // Deep link into a match (as a player or a spectator). useEffect(() => { if (!initialMatchId) return; let cancelled = false; void fetchBomperatorMatch(initialMatchId) .then((result) => { if (cancelled) return; if (result.success && result.data) { endedRef.current = false; applySnapshot(result.data); if (typeof window !== "undefined") { window.history.replaceState( null, "", `/minigames/bomperator?match=${encodeURIComponent(initialMatchId)}`, ); } } else { setError(result.error ?? "This match was not found."); } }) .catch(() => undefined); return () => { cancelled = true; }; }, [initialMatchId, applySnapshot]); // Push-first: apply snapshots the server broadcasts over the SSE bus for this // match. The bus is globalThis-anchored so it reaches us from the action/tick // bundles; version dedup keeps it consistent with the fallback poll below. useEffect(() => { if (view !== "match" || matchId === null) return; const handleState = (event: Event) => { const detail = (event as CustomEvent).detail; if (!detail || detail.matchId !== matchId || !detail.snapshot) return; applySnapshot(detail.snapshot); }; window.addEventListener(BOMP_STATE_EVENT, handleState); return () => window.removeEventListener(BOMP_STATE_EVENT, handleState); }, [view, matchId, applySnapshot]); // The host ended the drill: tell everyone else why, then drop to the lobby. useEffect(() => { if (view !== "match" || matchId === null) return; const handleTerminated = (event: Event) => { const detail = (event as CustomEvent).detail; if (!detail || detail.matchId !== matchId) return; const message = detail.reason === "host-ended" ? detail.hostName ? `${detail.hostName} ended the drill.` : "The host ended the drill." : "This drill has ended."; handleEnded(message); }; window.addEventListener(BOMP_TERMINATED_EVENT, handleTerminated); return () => window.removeEventListener(BOMP_TERMINATED_EVENT, handleTerminated); }, [view, matchId, handleEnded]); // Slow, in-flight-guarded fallback poll: recovers dropped pushes and detects a // dissolved match. Not the latency path (the push is), so it stays gentle and // never stacks requests behind an outstanding one. useEffect(() => { if (view !== "match" || matchId === null) return; let cancelled = false; let inFlight = false; const run = () => { if (inFlight) return; inFlight = true; void fetchBomperatorMatch(matchId) .then((result) => { if (cancelled) return; if (result.success && result.data) { applySnapshot(result.data); } else if (result.error === "Match not found.") { // Fallback for a missed host-ended push: neutral wording, since the // poll alone cannot tell why the match disappeared. handleEnded("This drill has ended."); } }) .catch(() => undefined) .finally(() => { if (!cancelled) inFlight = false; }); }; const poll = window.setInterval(run, FALLBACK_POLL_MS); return () => { cancelled = true; window.clearInterval(poll); }; }, [view, matchId, applySnapshot, handleEnded]); const start = useCallback(async () => { if (!matchId) return; const result = await startBomperatorMatch(matchId); if (result.success && result.data) applySnapshot(result.data); else setError(result.error ?? "Could not start the drill."); }, [matchId, applySnapshot]); const leave = useCallback(async () => { endedRef.current = true; // self-initiated exit: no "ended" toast for us if (matchId) { try { await leaveBomperatorMatch(matchId); } catch { // Leaving is best-effort; resetting the view is what matters. } } resetToLobby(); }, [matchId, resetToLobby]); const end = useCallback(async () => { endedRef.current = true; // we are the host ending it; no toast for us if (matchId) { try { await endBomperatorMatch(matchId); } catch { // Best-effort; the host is leaving regardless. } } resetToLobby(); }, [matchId, resetToLobby]); const inMatch = view === "match" && matchId !== null; const operatorsOnline = useRealtimePresence("bomperator", inMatch, true); return (
Your disposal record

Rewards are granted when a drill ends. Free-for-all, 2-8 technicians.

{STAT_ITEMS.map(([label, key]) => (
{label} {initialStats[key].toLocaleString()}
))}
{error && (

{error}

)} {view === "lobby" ? ( ) : match ? ( participant.name)} /> ) : (

Loading match…

)}
); }