'use strict';

function XM_Countdown(args) {
  if (!args.containerEl) {
    return;
  }

  const date = new Date();
  const defaultTargetDate = date.setDate(date.getDate() + 10);

  const defaults = {
    unitsSelector: 'xm-countdown'
  };

  const options = Object.assign(defaults, args);

  // console.log('XM_Countdown - options: ', options);

  const units = ['days', 'hours', 'minutes', 'seconds'];
  const [daysElement, hoursElement, minutesElement, secondsElement] = units.map((unit) => {
    return options.containerEl.querySelector(`.${options.unitsSelector}__${unit}`);
  });

  // Target date
  const targetDate = new Date(options.targetDate ? options.targetDate : defaultTargetDate).getTime();

  // Today
  const currentDate = new Date().getTime();

  // Distance between today and the countdown date
  const distance = targetDate - currentDate;

  const expiredElement = document.createElement('p');
  expiredElement.classList.add('xm-countdown-expired-text');
  expiredElement.innerText = options.expirationText;

  // if countdown expired show a message and don't start the countdown
  if (distance < 0) {
    if (options.expirationText) {
      options.containerEl.innerHTML = '';
      options.containerEl.appendChild(expiredElement);
      // options.containerEl.innerHTML = options.expirationText;
    }
  } else {
    // Start the countdown and update it every second
    const intervalId = setInterval(function() {
      // Today
      const currentDate = new Date().getTime();

      // Distance between today and the countdown date
      const distance = targetDate - currentDate;

      // if countdown expired finish counting and show a message
      if (distance < 0) {
        clearInterval(intervalId);
        if (options.expirationText) {
          options.containerEl.innerHTML = '';
          options.containerEl.appendChild(expiredElement);
          // options.containerEl.innerHTML = options.expirationText;
        }
      } else {
        const days = Math.floor(distance / (1000 * 60 * 60 * 24));
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);

        daysElement.innerText = days;
        hoursElement.innerText = hours;
        minutesElement.innerText = minutes;
        secondsElement.innerText = seconds;
      }
    }, 1000);
  }
}