"use client"; import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; import { readableTextColor } from "@/lib/color"; import { useRefreshChannel } from "@/lib/hooks/use-refresh-channel"; import { useSound } from "@/lib/hooks/use-sound"; import { channelNames } from "@/lib/realtime-channels"; import type { ScoreboardPayload, ScoreboardTeam } from "@/lib/scoreboard"; import { soundsForUpdate } from "@/lib/scoreboard-sounds"; import { CountUp } from "./count-up"; import { ScoreboardTimer } from "./scoreboard-timer"; const MOVE_MS = 600; const IDLE_MS = 3000; const connectionDot = { live: "bg-signal", connecting: "bg-white/40", offline: "bg-alert" }; const connectionLabel = { live: "live", connecting: "connecting…", offline: "offline — reconnecting" }; const prefersReducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches; export function Scoreboard({ token, initial }: { token: string; initial: ScoreboardPayload }) { const [payload, setPayload] = useState(initial); const [fetchFailed, setFetchFailed] = useState(false); const refetch = useCallback(async () => { try { const response = await fetch(`/api/public/scoreboard/${token}`, { cache: "no-store" }); if (!response.ok) throw new Error(String(response.status)); setPayload((await response.json()) as ScoreboardPayload); setFetchFailed(false); } catch { // Keep showing the last good scores; the dot tells the host something is wrong. setFetchFailed(true); } }, [token]); const socket = useRefreshChannel(channelNames.scoreboard(token), refetch); const connection = fetchFailed || socket === "disconnected" ? "offline" : socket === "connected" ? "live" : "connecting"; // Teams already revealed when this page loaded appear at once; only teams revealed // while watching get the drum-roll. const [revealedOnLoad] = useState( () => new Set(initial.teams.filter((team) => team.rank !== undefined).map((team) => team.id)), ); // Sound effects for what just changed: a new game, a team being revealed. const sound = useSound(); const { play } = sound; const previousPayload = useRef(initial); useEffect(() => { const before = previousPayload.current; previousPayload.current = payload; if (before === payload) return; soundsForUpdate(before, payload, { reducedMotion: prefersReducedMotion() }).forEach(play); }, [payload, play]); const rowElements = useRef(new Map()); const lastTops = useRef(new Map()); // FLIP: rows are re-ordered in the DOM, then slid from where they were to where they are. useLayoutEffect(() => { const animate = !prefersReducedMotion(); rowElements.current.forEach((element, id) => { // offsetTop ignores transforms, so a move that interrupts another still measures correctly. const top = element.offsetTop; const previous = lastTops.current.get(id); if (animate && previous !== undefined && previous !== top) { element.animate( [{ transform: `translateY(${previous - top}px)` }, { transform: "translateY(0)" }], { duration: MOVE_MS, easing: "cubic-bezier(0.2, 0.8, 0.2, 1)" }, ); // The one bold moment: a team that climbs gets a floodlight flash. if (top < previous) { element.animate( [ { boxShadow: "0 0 0 0 var(--floodlight)" }, { boxShadow: "0 0 0 0.6vh var(--floodlight)", offset: 0.35 }, { boxShadow: "0 0 0 0 transparent" }, ], { duration: MOVE_MS * 1.5, easing: "ease-out" }, ); } } lastTops.current.set(id, top); }); for (const id of lastTops.current.keys()) { if (!rowElements.current.has(id)) lastTops.current.delete(id); } }, [payload]); // A resize moves every row; re-measure so the next update doesn't animate from stale positions. useEffect(() => { const remeasure = () => rowElements.current.forEach((element, id) => lastTops.current.set(id, element.offsetTop)); window.addEventListener("resize", remeasure); return () => window.removeEventListener("resize", remeasure); }, []); const idle = useIdle(IDLE_MS); const { isFullscreen, toggleFullscreen } = useFullscreen(); const revealing = payload.reveal?.active ?? false; const hidden = payload.visibility === "hidden" && !revealing; const { currentGame } = payload; return (

{payload.eventName}

{currentGame && (

Game {currentGame.index} of {currentGame.total}: {" "} {currentGame.title}

)}
{payload.timer && } {hidden && (

Scores are hidden — final reveal soon

)}
    {payload.teams.length === 0 && (
  1. No teams yet
  2. )} {payload.teams.map((team, index) => revealing && team.rank === undefined ? ( // Keyed by slot, not team: a mystery row must say nothing about who is in it.
  3. ?
  4. ) : ( { if (element) rowElements.current.set(team.id, element); else rowElements.current.delete(team.id); }} /> ), )}
{payload.visibility === "frozen" && !revealing && ( Scores frozen )} {connectionLabel[connection]} {/* Stays visible while sound is off or waiting, so the host can't miss that it's silent. */}
); } function TeamRow({ team, showScore, drumRoll, register, }: { team: ScoreboardTeam; showScore: boolean; /** Play the reveal build-up when this row first appears. */ drumRoll: boolean; register: (element: HTMLLIElement | null) => void; }) { const isLeader = showScore && team.rank === 1 && (team.total ?? 0) > 0; return (
  • {drumRoll && ( // Visual drum-roll: a shaking "?" covers the row for a beat before the team appears.
    ?
    )}
    {showScore && team.rank !== undefined ? team.rank : ""}
    {team.name}
    {showScore && (
    {team.total !== undefined ? : "–"}
    )}
  • ); } /** True after `ms` without mouse or keyboard activity (hides the cursor on the projector). */ function useIdle(ms: number) { const [idle, setIdle] = useState(false); useEffect(() => { let timer: ReturnType; const wake = () => { setIdle(false); clearTimeout(timer); timer = setTimeout(() => setIdle(true), ms); }; const events = ["mousemove", "mousedown", "keydown", "touchstart"] as const; events.forEach((name) => window.addEventListener(name, wake)); timer = setTimeout(() => setIdle(true), ms); return () => { clearTimeout(timer); events.forEach((name) => window.removeEventListener(name, wake)); }; }, [ms]); return idle; } function useFullscreen() { const [isFullscreen, setIsFullscreen] = useState(false); useEffect(() => { const onChange = () => setIsFullscreen(document.fullscreenElement !== null); document.addEventListener("fullscreenchange", onChange); return () => document.removeEventListener("fullscreenchange", onChange); }, []); const toggleFullscreen = useCallback(() => { // Rejections (e.g. the browser blocking fullscreen) are harmless; the button just does nothing. if (document.fullscreenElement) void document.exitFullscreen().catch(() => {}); else void document.documentElement.requestFullscreen().catch(() => {}); }, []); return { isFullscreen, toggleFullscreen }; }