document.addEventListener("DOMContentLoaded", () => {
  const popups = {
    exit: {
      element: document.querySelector(".popup--exit"),
      close: document.querySelector(".popup--exit .popup__close"),
      button: document.querySelector(".popup--exit .popup__button"),
    },
    discount: {
      element: document.querySelector(".popup--discount"),
      close: document.querySelector(".popup--discount .popup__close"),
      button: document.querySelector(".popup--discount .popup__button"),
    },
  };

  let popupToShow = "discount";
  const showPopup = () => {
    // Se o popup for exit, esconde o popup de discount
    if (popupToShow === "exit") hidePopup(popups.discount);
    else hidePopup(popups.exit);

    const popup = popupToShow === "exit" ? popups.exit : popups.discount;
    popup.element.style.display = "flex";
  };

  const hidePopup = popup => (popup.element.style.display = "none");

  const handleMouseLeave = event => event.clientY <= 0 && showPopup();

  // Eventos de mouse
  document.addEventListener("mouseleave", handleMouseLeave);

  // Eventos de fechamento
  popups.exit.close.addEventListener("click", () => hidePopup(popups.exit));
  popups.exit.button.addEventListener("click", () => hidePopup(popups.exit));
  popups.discount.close.addEventListener("click", () => hidePopup(popups.discount));
  popups.discount.button.addEventListener("click", () => hidePopup(popups.discount));

  $(window).on("showHiddenElements", () => {
    popupToShow = "exit";
  });

  document.querySelector(".popup__button--close")?.addEventListener("click", e => {
    e.preventDefault();
    e.stopPropagation();

    hidePopup(popups.exit);
    hidePopup(popups.discount);
  });

  document.addEventListener("mouseleave", event => event.clientY <= 0 && showPopup());
});
