"use client"; import { useEffect, useState } from "react"; import type { TimerState } from "@/lib/timer"; /** * Milliseconds left on a timer, ticking locally while it runs. * `serverNow` is the server's clock when `timer` was computed; the difference from this * device's clock is applied so a projector PC with a wrong clock still counts down correctly. */ export function useCountdown(timer: TimerState | null, serverNow: string): number { const [remainingMs, setRemainingMs] = useState(timer?.remainingMs ?? 0); const running = timer?.status === "running" && timer.endsAt !== null; const endsAt = timer?.endsAt ?? null; useEffect(() => { if (!running || !endsAt) return; const clockOffset = Date.parse(serverNow) - Date.now(); const endsAtMs = Date.parse(endsAt); const tick = () => setRemainingMs(Math.max(0, endsAtMs - (Date.now() + clockOffset))); // Sync to the clock at once rather than 100ms late. tick(); const interval = setInterval(tick, 100); return () => clearInterval(interval); }, [running, endsAt, serverNow]); // When not running the server's value is exact; only a running timer needs the local clock. return running ? remainingMs : (timer?.remainingMs ?? 0); }