import { useEffect, useMemo, useRef, useState } from 'react'; import { formatCountdown } from '@/utils/fasting'; interface CountdownOptions { target: Date | null | undefined; intervalMs?: number; autoStart?: boolean; } export const useCountdown = ({ target, intervalMs = 1000, autoStart = true }: CountdownOptions) => { const [now, setNow] = useState(() => new Date()); const timerRef = useRef | null>(null); const targetTimestamp = target instanceof Date ? target.getTime() : null; useEffect(() => { if (!autoStart) return undefined; if (targetTimestamp == null) return undefined; timerRef.current && clearInterval(timerRef.current); timerRef.current = setInterval(() => { setNow(new Date()); }, intervalMs); return () => { if (timerRef.current) { clearInterval(timerRef.current); timerRef.current = null; } }; }, [targetTimestamp, intervalMs, autoStart]); useEffect(() => { if (targetTimestamp == null) return; setNow(new Date()); }, [targetTimestamp]); const diffMs = useMemo(() => { if (targetTimestamp == null) return 0; return targetTimestamp - now.getTime(); }, [targetTimestamp, now]); const formatted = useMemo(() => { if (targetTimestamp == null) return '--:--:--'; return formatCountdown(new Date(targetTimestamp), now); }, [targetTimestamp, now]); return { now, diffMs, formatted, isExpired: diffMs <= 0, hasTarget: targetTimestamp != null, }; };