import { useState, useRef, useEffect, useCallback, useMemo } from "react";
import { getUtcDate } from "../utils/date";
import dayjs from "dayjs";
const keys = ["days", "hours", "minutes", "seconds"];
const maxValues = {
    days: 1,
    hours: 24,
    minutes: 60,
    seconds: 60,
};
const useCountdown = (deadline, excludedKeys, compact) => {
    const initialTimeDelta = useMemo(() => Object.fromEntries(keys
        .filter((k) => !excludedKeys?.some((e) => e === k))
        .map((k) => [k, undefined])), [excludedKeys]);
    const [timeDelta, setTimeDelta] = useState(initialTimeDelta);
    const timerId = useRef();
    const destroyStopwatch = useCallback(() => {
        if (timerId.current) {
            clearInterval(timerId.current);
            timerId.current = void 0;
        }
    }, [timerId]);
    const timeDeltaKeys = useMemo(() => keys.filter((k) => !excludedKeys?.some((e) => e === k)), [excludedKeys]);
    useEffect(() => {
        if (!deadline)
            return;
        const countdownTimer = () => {
            const utcDate = getUtcDate();
            const now = dayjs(utcDate);
            const diff = dayjs(deadline).diff(now);
            if (diff <= 0)
                destroyStopwatch();
            const nextTimeDelta = Object.fromEntries(timeDeltaKeys.map((key, index) => {
                const modulus = index === 0 ? Infinity : maxValues[key];
                const delta = dayjs(deadline).diff(now, key) % modulus;
                const time = delta.toString().padStart(2, "0");
                if (!compact)
                    return [key, time];
                return [key, time.at(0) === "0" ? time.slice(1) : time];
            }));
            setTimeDelta(nextTimeDelta);
        };
        if (!timerId.current) {
            timerId.current = setInterval(countdownTimer, 1000);
        }
        return destroyStopwatch;
    }, [timerId, destroyStopwatch, timeDeltaKeys, deadline, initialTimeDelta]);
    return timeDelta;
};
export { useCountdown };
//# sourceMappingURL=use-countdown.js.map