export default function initializeCounter(shadowRoot, config) {
  const { startAt, endAt } = config;

  const startDate = new Date(startAt);
  const endDate = new Date(endAt);

  const timer = shadowRoot.querySelector(".firevert-widget__left-side-timer");

  if (!timer) return;

  const formatTime = (totalSeconds) => {
    const days = Math.floor(totalSeconds / 86400);
    const hrs = Math.floor((totalSeconds % 86400) / 3600);
    const mins = Math.floor((totalSeconds % 3600) / 60);
    const secs = totalSeconds % 60;

    const timeString = `${hrs.toString().padStart(2, "0")}:${mins
      .toString()
      .padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;

    return days > 0 ? `${days}d ${timeString}` : timeString;
  };

  const timerInterval = setInterval(() => {
    const now = new Date();

    if (now > endDate) {
      clearInterval(timerInterval);
      timer.textContent = "00:00:00";
      return;
    }

    const targetTime = endDate - now;
    const totalSeconds = Math.floor(targetTime / 1000);

    if (totalSeconds <= 0) {
      clearInterval(timerInterval);
      timer.textContent = "00:00:00";
      return;
    }

    timer.textContent = formatTime(totalSeconds);
  }, 1000);

  const initialUpdate = () => {
    const now = new Date();

    if (now > endDate) {
      timer.textContent = "00:00:00";
      return;
    }

    const targetTime = endDate - now;
    const totalSeconds = Math.floor(targetTime / 1000);

    if (totalSeconds <= 0) {
      timer.textContent = "00:00:00";
      return;
    }

    timer.textContent = formatTime(totalSeconds);
  };

  initialUpdate();
}
