(function () {
  var STORAGE_KEY = "offer_countdown_end_time";
  var DURATION_MS = 72 * 60 * 60 * 1000; // 72 hours

  function pad(num) {
    return String(num).padStart(2, "0");
  }

  function initCountdown() {
    var hoursEl = document.getElementById("cd-hours");
    var minutesEl = document.getElementById("cd-minutes");
    var secondsEl = document.getElementById("cd-seconds");
    var timerBox = document.getElementById("countdown-timer");
    var endedMsg = document.getElementById("offer-ended-msg");

    if (!hoursEl || !minutesEl || !secondsEl || !timerBox || !endedMsg) {
      return;
    }

    if (timerBox.getAttribute("data-cd-initialized") === "1") {
      return; // already running for this element
    }
    timerBox.setAttribute("data-cd-initialized", "1");

    var endTime = localStorage.getItem(STORAGE_KEY);
    if (!endTime) {
      endTime = new Date().getTime() + DURATION_MS;
      localStorage.setItem(STORAGE_KEY, endTime);
    } else {
      endTime = parseInt(endTime, 10);
    }

    function updateCountdown() {
      var now = new Date().getTime();
      var distance = endTime - now;

      if (distance <= 0) {
        timerBox.style.display = "none";
        endedMsg.style.display = "block";
        clearInterval(timerInterval);
        return;
      }

      var hours = Math.floor(distance / (1000 * 60 * 60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);

      hoursEl.textContent = pad(hours);
      minutesEl.textContent = pad(minutes);
      secondsEl.textContent = pad(seconds);
    }

    updateCountdown();
    var timerInterval = setInterval(updateCountdown, 1000);
  }

  var tries = 0;
  var poll = setInterval(function () {
    tries++;
    initCountdown();
    if (tries > 20) clearInterval(poll); // stop after ~10 seconds of trying
  }, 500);

  if (document.readyState !== "loading") {
    initCountdown();
  } else {
    document.addEventListener("DOMContentLoaded", initCountdown);
  }
})();
