"use client"; import { useState, useEffect, useTransition } from "react"; import { useRouter } from "next/navigation"; import { startTimer, startTimerForClient, stopTimer } from "@/app/admin/timer-actions"; function formatDuration(seconds: number): string { const h = Math.floor(seconds / 3600); const m = Math.floor((seconds % 3600) / 60); const s = seconds % 60; if (h > 0) return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`; return `${m}:${String(s).padStart(2, "0")}`; } export function TimerCell({ clientId, projectId, activeEntryId, activeStartedAt, totalTrackedSeconds, }: { clientId: string; projectId?: string; activeEntryId: string | null; activeStartedAt: Date | null; totalTrackedSeconds: number; }) { const router = useRouter(); const [, startTransition] = useTransition(); const isRunning = activeEntryId !== null; // Live elapsed counter const [elapsed, setElapsed] = useState(() => { if (!activeStartedAt) return 0; return Math.round((Date.now() - new Date(activeStartedAt).getTime()) / 1000); }); useEffect(() => { if (!isRunning) { setElapsed(0); return; } const start = activeStartedAt ? new Date(activeStartedAt).getTime() : Date.now(); const tick = () => setElapsed(Math.round((Date.now() - start) / 1000)); tick(); const id = setInterval(tick, 1000); return () => clearInterval(id); }, [isRunning, activeStartedAt]); function handleToggle() { startTransition(async () => { if (isRunning && activeEntryId) { await stopTimer(activeEntryId); } else if (projectId) { await startTimer(projectId); } else { await startTimerForClient(clientId); } router.refresh(); }); } const displayTotal = formatDuration(totalTrackedSeconds + (isRunning ? elapsed : 0)); return (