(function () {
  "use strict";

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

  function calculateParts(distance) {
    var totalSeconds = Math.max(0, Math.floor(distance / 1000));
    var years = Math.floor(totalSeconds / 31536000);
    var days = Math.floor((totalSeconds % 31536000) / 86400);
    var hours = Math.floor((totalSeconds % 86400) / 3600);
    var minutes = Math.floor((totalSeconds % 3600) / 60);
    var seconds = totalSeconds % 60;

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

  function updateCountdown(root) {
    var targetValue = root.getAttribute("data-target");
    if (!targetValue) {
      return;
    }

    var targetTime = new Date(targetValue).getTime();
    if (Number.isNaN(targetTime)) {
      return;
    }

    var now = Date.now();
    var distance = targetTime - now;
    var parts = calculateParts(distance);

    root.querySelectorAll("[data-pmc-unit]").forEach(function (item) {
      var unit = item.getAttribute("data-pmc-unit");
      var valueNode = item.querySelector("[data-pmc-value]");

      if (!valueNode || typeof parts[unit] === "undefined") {
        return;
      }

      valueNode.textContent = pad(parts[unit]);
    });

    if (distance <= 0) {
      root.classList.add("is-complete");
    }
  }

  document.addEventListener("DOMContentLoaded", function () {
    var countdown = document.querySelector("[data-pmc-countdown='1']");
    if (!countdown) {
      return;
    }

    updateCountdown(countdown);
    window.setInterval(function () {
      updateCountdown(countdown);
    }, 1000);
  });
})();
