"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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { BomperatorLobby } from "./BomperatorLobby"; import { BomperatorGame } from "./BomperatorGame"; import { createBomperatorTransport, type BomperatorTransport, type TransportKind, } from "./transport"; 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"; 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]); /* ---- snapshot delivery: one transport, WS-first with HTTP fallback ---- */ const [transport, setTransport] = useState(null); /** Surfaced as a data-attribute for prod verification ("transport=ws"). */ const [transportKind, setTransportKind] = useState("http"); useEffect(() => { if (view !== "match" || matchId === null) return; // The transport owns every snapshot source: SSE bus + guarded poll on HTTP, // the arena socket on WS (see ./transport.ts). Version dedup in // applySnapshot keeps them consistent however they interleave. const next = createBomperatorTransport(matchId); const offSnapshot = next.onSnapshot(applySnapshot); const offTerminated = next.onTerminated((info) => { const message = info.reason === "host-ended" ? info.hostName ? `${info.hostName} ended the drill.` : "The host ended the drill." : "This drill has ended."; handleEnded(message); }); const offKind = next.onKindChange?.(setTransportKind); setTransportKind(next.kind); setTransport(next); next.start(); return () => { offSnapshot(); offTerminated(); offKind?.(); next.close(); setTransport(null); }; }, [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 && transport ? ( participant.name)} /> ) : (

Loading match…

)}
); }