document.addEventListener('DOMContentLoaded', function () {
    'use strict';

    const popup = document.getElementById('sifency-custom-popup');
    
    if (!popup) {
        console.error('Sifency Popup: HTML element not found!');
        return;
    } else {
        console.log('Sifency Popup: Element found.');
    }

    const openPopup = () => {
        console.log('Sifency Popup: Opening...');
        popup.classList.add('sifency-show');
        document.body.classList.add('sifency-popup-active');

        if ( window.elementorFrontend ) {
            setTimeout(() => {
                window.elementorFrontend.init();
            }, 200);
        }
    };

    const closePopup = () => {
        console.log('Sifency Popup: Closing...');
        popup.classList.remove('sifency-show');
        document.body.classList.remove('sifency-popup-active');
    };

    setTimeout(() => {
        openPopup();
    }, 2000); 

    popup.addEventListener('click', function(e) {
        if ( e.target.closest('[data-sifency-popup="close"]') ) {
            e.preventDefault();
            closePopup();
        }
    });

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && popup.classList.contains('sifency-show')) {
            closePopup();
        }
    });
});