document.addEventListener('DOMContentLoaded', () => {
    const POPUP_TIMEOUT = 2887; // 48 minutos e 7 segundos (em segundos)

    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));

    setTimeout(() => {
        popupToShow = 'exit';
    }, POPUP_TIMEOUT * 1000);

    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());
});