if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initExitPopup);
} else {
  initExitPopup();
}

function initExitPopup() {
  const TODAY = new Date().getTime(),
    FUTURE = TODAY + 24 * 60 * 60 * 1000,
    EXECUTION_DATE = parseInt(localStorage.getItem('popupTime')) || TODAY,
    EXIT_POPUP_CONTAINER = document.querySelector('.js-exit-popup-container'),
    BTN_REMOVE = EXIT_POPUP_CONTAINER.querySelector('.js-close');

  if (EXECUTION_DATE > TODAY) return;

  var initExitPopupEvents = function(e) {
    if (e.clientY > 5) return;

    localStorage.setItem('popupTime', FUTURE);
    displayExitPopup();
  };

  window.addEventListener('mousemove', initExitPopupEvents);

  function displayExitPopup() {
    const SLIDER = EXIT_POPUP_CONTAINER.querySelector('.carousel-container'),
      REFRESH_SLIDER = new Event('refresh');

    EXIT_POPUP_CONTAINER.classList.remove('hidden');
    SLIDER.dispatchEvent(REFRESH_SLIDER);
  }

  function removeExitPopup() {
    EXIT_POPUP_CONTAINER.remove();
    window.removeEventListener('mousemove', initExitPopupEvents);
  }

  //Evita que o modal seja removido ao clicar no overlay
  EXIT_POPUP_CONTAINER.querySelector('.js-exit-popup-content').addEventListener('mousedown', function(e) {
    e.stopPropagation();
  });

  EXIT_POPUP_CONTAINER.addEventListener('mousedown', removeExitPopup);
  BTN_REMOVE.addEventListener('mousedown', removeExitPopup);
}
