export function calculateTimeRemaining(endAtString) {
  const endTime = new Date(endAtString).getTime();
  const currentTime = new Date().getTime();
  const difference = endTime - currentTime;

  if (difference <= 0) {
    return null;
  }

  const days = Math.floor(difference / (1000 * 60 * 60 * 24));
  const hours = Math.floor(
    (difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
  );
  const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((difference % (1000 * 60)) / 1000);

  return { days, hours, minutes, seconds };
}

export function formatCountdownTime(timeRemaining) {
  if (!timeRemaining) return "00:00:00";

  const { hours, minutes, seconds } = timeRemaining;
  return `${hours.toString().padStart(2, "0")}:${minutes
    .toString()
    .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
}

export function formatCountdownText(timeRemaining, config) {
  if (!timeRemaining) return "Promocja zakończona";

  const { dayText } = config;
  const { days } = timeRemaining;

  return `${days} ${dayText}`;
}

export function startCountdown(shadowRoot, config) {
  const updateCountdown = () => {
    const { promotionEndText, endAt } = config;
    const timeRemaining = calculateTimeRemaining(endAt);
    const timeElement = shadowRoot.querySelector(
      ".firevert-promo-time-widget__bottom-text-time"
    );
    const textElement = shadowRoot.querySelector(
      ".firevert-promo-time-widget__bottom-text"
    );

    if (!timeRemaining) {
      const widgetContainer = shadowRoot.getRootNode().host;
      if (widgetContainer) {
        widgetContainer.style.display = "none";
      }
      return;
    }

    if (timeElement) {
      timeElement.textContent = formatCountdownTime(timeRemaining);
    }

    if (textElement) {
      const daysText = formatCountdownText(timeRemaining, config);
      const timerSpan = textElement.querySelector(
        ".firevert-promo-time-widget__bottom-text-time"
      );
      if (timerSpan) {
        textElement.innerHTML = `${daysText} <span class="firevert-promo-time-widget__bottom-text-time" style="${timerSpan.getAttribute(
          "style"
        )}">${formatCountdownTime(timeRemaining)}</span> ${promotionEndText}`;
      }
    }
  };

  updateCountdown();
  return setInterval(updateCountdown, 1000);
}
