(function( $ ) {
    'use strict';

    var SifencyAutoPopupHandler = function( $scope, $ ) {
        
        var $wrapper = $scope.find('.sifency-auto-popup-wrapper');
        var $overlay = $wrapper.find('.sifency-auto-popup-overlay');
        var $container = $wrapper.find('.sifency-auto-popup-container');
        var $closeBtn = $wrapper.find('.sifency-auto-popup-close');
        
        var delay = $wrapper.data('delay');
        var showOnce = $wrapper.data('show-once');
        var preventScroll = $wrapper.data('prevent-scroll');
        var widgetId = $wrapper.data('widget-id');
        var storageKey = 'sifency_popup_seen_' + widgetId;

        if ( showOnce === 'yes' && sessionStorage.getItem(storageKey) ) {
            return;
        }
        if ( $wrapper.parent().is( $scope ) ) {
            $wrapper.appendTo('body');
        }

        function openPopup() {
            $wrapper.fadeIn(300).addClass('is-active');
            
            if(preventScroll === 'yes') {
                $('body').addClass('sifency-noscroll');
            }
        }

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

        function closePopup() {
            $wrapper.fadeOut(300).removeClass('is-active');
            $('body').removeClass('sifency-noscroll');
g
            if ( showOnce === 'yes' ) {
                sessionStorage.setItem(storageKey, 'true');
            }
        }

        $closeBtn.on('click', closePopup);
        $overlay.on('click', closePopup);

        $(document).on('keyup', function(e) {
            if (e.key === "Escape" && $wrapper.hasClass('is-active')) {
                closePopup();
            }
        });
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-widget-auto-popup.default', SifencyAutoPopupHandler);
    });

})( jQuery );