document.addEventListener("DOMContentLoaded", function () {
  const timers = document.querySelectorAll(".countdown-timer");
  const timerInstances = new Map();

  // Initialize all timers
  timers.forEach(initTimer);

  // Listen for Shopify theme editor events
  if (typeof Shopify !== "undefined" && Shopify.designMode) {
    document.addEventListener("shopify:section:load", function (event) {
      // When a section is loaded/reloaded, reinitialize its timers
      const section = event.target;
      const newTimers = section.querySelectorAll(".countdown-timer");
      newTimers.forEach(initTimer);
    });

    document.addEventListener("shopify:block:select", function (event) {
      // When a block is selected, check if it contains a timer
      const selectedBlock = event.target;
      const timer = selectedBlock.querySelector(".countdown-timer");
      if (timer) {
        // Force reset timer when block is selected in design mode
        resetTimer(timer);
      }
    });
  }

  function initTimer(timer) {
    // Clean up existing timer for this element if it exists
    const timerId = timer.dataset.sectionId + "-" + timer.dataset.blockId;
    if (timerInstances.has(timerId)) {
      clearInterval(timerInstances.get(timerId));
      timerInstances.delete(timerId);
    }

    // Initialize new timer
    startTimer(timer);
  }

  function resetTimer(timer) {
    // Force reset the timer with current settings
    const timerId = timer.dataset.sectionId + "-" + timer.dataset.blockId;
    if (timerInstances.has(timerId)) {
      clearInterval(timerInstances.get(timerId));
      timerInstances.delete(timerId);
    }

    // Clear localStorage entries to force a fresh start
    const storageId = "countdown_" + window.location.pathname + "_" + timerId;
    localStorage.removeItem(storageId + "_endTime");
    localStorage.removeItem(storageId + "_startTime");
    localStorage.removeItem(storageId + "_duration");
    localStorage.removeItem(storageId + "_resets");

    // Start fresh
    startTimer(timer);
  }

  function startTimer(timer) {
    const timerType = timer.getAttribute("data-timer-type");
    const sectionId = timer.getAttribute("data-section-id");
    const blockId = timer.getAttribute("data-block-id");
    const timerId = sectionId + "-" + blockId;

    let endTime;
    let isDesignMode = typeof Shopify !== "undefined" && Shopify.designMode;
    const storageId = "countdown_" + window.location.pathname + "_" + timerId;

    if (timerType === "date") {
      // Set end time based on specific date (format: YYYY-MM-DD)
      const dateString = timer.getAttribute("data-end-date");
      if (dateString && dateString.match(/^\d{4}-\d{2}-\d{2}$/)) {
        // Create date object and set to end of day
        const endDate = new Date(dateString);
        endDate.setHours(23, 59, 59, 999);
        endTime = endDate.getTime();

        // Store the endTime for future page loads
        localStorage.setItem(storageId + "_endTime", endTime);
      } else {
        // Invalid date format, default to 7 days from now
        endTime = new Date().getTime() + 7 * 24 * 60 * 60 * 1000;
        localStorage.setItem(storageId + "_endTime", endTime);
      }
    } else if (timerType === "reset") {
      // Get hours and minutes for timer duration
      const hours = parseInt(timer.getAttribute("data-hours")) || 0;
      const minutes = parseInt(timer.getAttribute("data-minutes")) || 0;
      const durationMs = hours * 60 * 60 * 1000 + minutes * 60 * 1000;

      // Get stored values
      const savedEndTime = localStorage.getItem(storageId + "_endTime");
      const savedStartTime = localStorage.getItem(storageId + "_startTime");
      const savedDuration = localStorage.getItem(storageId + "_duration");

      if (
        savedEndTime &&
        savedDuration &&
        parseInt(savedDuration) === durationMs &&
        !isDesignMode
      ) {
        const parsedEndTime = parseInt(savedEndTime);
        const now = new Date().getTime();

        if (parsedEndTime > now) {
          // Timer hasn't expired yet, continue from saved state
          endTime = parsedEndTime;
        } else {
          // Timer expired, calculate how many complete cycles passed and set a new end time
          const elapsedTime = now - parsedEndTime;
          const completeCycles = Math.floor(elapsedTime / durationMs);

          // Set new end time based on the last expiration plus one duration
          endTime = parsedEndTime + (completeCycles + 1) * durationMs;

          // Update localStorage with new end time
          localStorage.setItem(storageId + "_endTime", endTime);
          localStorage.setItem(storageId + "_startTime", now);

          // Update reset count
          const currentResets = parseInt(
            localStorage.getItem(storageId + "_resets") || "0"
          );
          localStorage.setItem(
            storageId + "_resets",
            (currentResets + completeCycles + 1).toString()
          );
        }
      } else {
        // First time or settings changed, start fresh
        const now = new Date().getTime();
        endTime = now + durationMs;

        // Store values for persistence
        localStorage.setItem(storageId + "_endTime", endTime);
        localStorage.setItem(storageId + "_startTime", now);
        localStorage.setItem(storageId + "_duration", durationMs);
        localStorage.setItem(storageId + "_resets", "1");
      }
    }

    // Update the countdown every 1 second
    const intervalId = setInterval(function () {
      // Get current date and time
      const now = new Date().getTime();

      // Find the time remaining
      const timeRemaining = endTime - now;

      // Time calculations for days, hours, minutes and seconds
      const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
      const hours = Math.floor(
        (timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
      );
      const minutes = Math.floor(
        (timeRemaining % (1000 * 60 * 60)) / (1000 * 60)
      );
      const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);

      // Display the result in MM:SS format
      let totalMinutes = days * 24 * 60 + hours * 60 + minutes;
      let formattedSeconds = seconds < 10 ? "0" + seconds : seconds;

      timer.textContent = totalMinutes + ":" + formattedSeconds;

      // If the countdown is finished
      if (timeRemaining < 0) {
        clearInterval(intervalId);
        timerInstances.delete(timerId);

        if (timerType === "reset") {
          // Get timer duration
          const hours = parseInt(timer.getAttribute("data-hours")) || 0;
          const minutes = parseInt(timer.getAttribute("data-minutes")) || 0;
          const durationMs = hours * 60 * 60 * 1000 + minutes * 60 * 1000;

          // Set new end time
          const now = new Date().getTime();
          endTime = now + durationMs;

          // Update localStorage
          localStorage.setItem(storageId + "_endTime", endTime);
          localStorage.setItem(storageId + "_startTime", now);

          // Update reset count
          const currentResets = parseInt(
            localStorage.getItem(storageId + "_resets") || "0"
          );
          localStorage.setItem(
            storageId + "_resets",
            (currentResets + 1).toString()
          );

          // Start the countdown again
          startTimer(timer);
        } else {
          // Date-based timer expired, just show 0:00
          timer.textContent = "0:00";
        }
      }
    }, 1000);

    // Store the interval ID for cleanup
    timerInstances.set(timerId, intervalId);
  }
});
