document.addEventListener('DOMContentLoaded', function () {
    const popupWrappers = document.querySelectorAll('.sifency-auto-popup-wrapper');

    popupWrappers.forEach(function (popup) {
        if (window.elementorFrontend && elementorFrontend.isEditMode()) {
            return;
        }

        const widgetId = popup.getAttribute('data-widget-id');
        const delay = parseInt(popup.getAttribute('data-delay')) || 0;
        const showOnce = popup.getAttribute('data-show-once') === 'yes';
        const preventScroll = popup.getAttribute('data-prevent-scroll') === 'yes';
        const closeBtn = popup.querySelector('.sifency-auto-popup-close');
        const overlay = popup.querySelector('.sifency-auto-popup-overlay');

        if (showOnce && sessionStorage.getItem('sifency-popup-' + widgetId)) {
            return;
        }

        setTimeout(function () {
            openPopup(popup, preventScroll);
        }, delay);

        const closePopup = function () {
            popup.classList.remove('is-active');
            if (preventScroll) {
                document.body.classList.remove('sifency-popup-open');
            }
            if (showOnce) {
                sessionStorage.setItem('sifency-popup-' + widgetId, 'true');
            }
        };

        closeBtn.addEventListener('click', closePopup);
        overlay.addEventListener('click', closePopup);
    });

    function openPopup(popup, preventScroll) {
        popup.classList.add('is-active');
        if (preventScroll) {
            document.body.classList.add('sifency-popup-open');
        }
    }
});