"use client"; import { usePathname, useRouter } from "next/navigation"; import { useEffect, useState } from "react"; import { Progress } from "@/components/ui/progress"; const calculateTimeLeft = (expiresAt: string) => { const now = Date.now(); const expirationTime = new Date(expiresAt).getTime(); return Math.max(0, Math.floor((expirationTime - now) / 1000)); }; const HumanizeTimeLeft = (seconds: number) => { const minutes = Math.floor(seconds / 60); const remainingSeconds = seconds % 60; return `${minutes}m ${remainingSeconds}s`; }; export default function ExpiryCountDown({ expiresAt, expiryLabel, }: { expiresAt: string; expiryLabel: string; }) { const [timeLeft, setTimeLeft] = useState(calculateTimeLeft(expiresAt)); const [mounted, setMounted] = useState(false); const router = useRouter(); const pathname = usePathname(); useEffect(() => { setMounted(true); }, []); useEffect(() => { const timer = setInterval(() => { setTimeLeft(calculateTimeLeft(expiresAt)); }, 1000); return () => clearInterval(timer); }, [expiresAt]); useEffect(() => { if (timeLeft <= 0) { router.replace(pathname); } }, [timeLeft, router, pathname]); if (!mounted) { return null; } return (
{timeLeft ? ( Time left: {HumanizeTimeLeft(timeLeft)} ) : ( {expiryLabel} has expired. )} {timeLeft > 0 && ( )}
); }