import { onPageLoadComplete } from '@nimius/event-utility';

const getCookie = (name) => {
    const v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
    return v ? v[2] : null;
};

const setCookie = (name, value) => {
    document.cookie = name + "=" + value + ";path=/;expires=";
};

const initPopup = (popup) => {
    let cookie = getCookie('popup_dismissed');
    const closeButton = document.querySelector('[data-popup-close]');

    if (cookie == null) {
        popup.setAttribute('data-state', 'active');

        closeButton.addEventListener('click', (e) => {
            e.preventDefault();
            popup.setAttribute('data-state', 'inactive');
            setCookie('popup_dismissed', 'true');
            cookie = getCookie('popup_dismissed');
        });
    }
};

onPageLoadComplete(() => {
    const popup = document.querySelector('[data-popup]');

    if (popup) {
        setTimeout(() => {
            initPopup(popup);
        }, 5000);
    }
});
