"use client";
import { useCallback, useState, useEffect } from "react";
function useCountdown(targetDate, precision = "second") {
  const secondInMs = 1e3;
  const minuteInMs = 6e4;
  const hourInMs = 36e5;
  const dayInMs = 864e5;
  const getTimeLeft = useCallback(() => {
    const now = /* @__PURE__ */ new Date();
    const timeLeftInMs = targetDate.getTime() - now.getTime();
    const days = timeLeftInMs > 0 ? Math.floor(timeLeftInMs / dayInMs) : 0;
    const hours = timeLeftInMs > 0 ? Math.floor(timeLeftInMs / hourInMs % 24) : 0;
    const minutes = timeLeftInMs > 0 ? Math.floor(timeLeftInMs / minuteInMs % 60) : 0;
    const seconds = timeLeftInMs > 0 ? Math.floor(timeLeftInMs / secondInMs % 60) : 0;
    let formattedTimeLeft = null;
    if (timeLeftInMs > 0) {
      if (days > 0) {
        formattedTimeLeft = `${days} day${days === 1 ? "" : "s"}`;
      } else if (hours > 0) {
        formattedTimeLeft = `${hours} hour${hours === 1 ? "" : "s"}`;
      } else if (precision === "hour") {
        formattedTimeLeft = "less than an hour";
      } else if (minutes > 0) {
        formattedTimeLeft = `${minutes} minute${minutes === 1 ? "" : "s"}`;
      } else if (precision === "minute") {
        formattedTimeLeft = "less than a minute";
      } else if (seconds > 0) {
        formattedTimeLeft = `${seconds} second${seconds === 1 ? "" : "s"}`;
      }
    }
    switch (precision) {
      case "hour":
        return { formattedTimeLeft, days, hours };
      case "minute":
        return { formattedTimeLeft, days, hours, minutes };
      default:
        return { formattedTimeLeft, days, hours, minutes, seconds };
    }
  }, [targetDate, precision]);
  const [timeLeft, setTimeLeft] = useState(() => getTimeLeft());
  useEffect(() => {
    const interval = setInterval(
      () => {
        const timeLeft2 = getTimeLeft();
        setTimeLeft(timeLeft2);
        if (timeLeft2.formattedTimeLeft === null) {
          clearInterval(interval);
        }
      },
      precision === "second" ? secondInMs : minuteInMs
    );
    return () => clearInterval(interval);
  }, [getTimeLeft, precision]);
  return timeLeft;
}
export {
  useCountdown
};
