(function( $ ) {
    'use strict';

    var SifencyModalHandler = function( $scope, $ ) {
        
        var $btn = $scope.find('.sifency-modal-trigger-btn');
        var $modalWrapper = $scope.find('.sifency-modal-overlay-wrapper');
        var $closeBtn = $modalWrapper.find('.sifency-modal-close');
        var $backdrop = $modalWrapper.find('.sifency-modal-backdrop');
        if ( $modalWrapper.parent().is( $scope.find('.sifency-modal-widget-wrapper') ) ) {
            $modalWrapper.appendTo('body');
        }

        // Open
        $btn.on('click', function(e) {
            e.preventDefault();
            $modalWrapper.addClass('is-open').attr('aria-hidden', 'false');
            $('body').addClass('sifency-noscroll');
        });

        function closeModal() {
            $modalWrapper.removeClass('is-open').attr('aria-hidden', 'true');
            setTimeout(function(){
                 if(!$('.sifency-modal-overlay-wrapper.is-open').length) {
                     $('body').removeClass('sifency-noscroll');
                 }
            }, 300);
        }

        $closeBtn.on('click', closeModal);
        $backdrop.on('click', closeModal);

        $(document).on('keyup', function(e) {
            if (e.key === "Escape" && $modalWrapper.hasClass('is-open')) {
                closeModal();
            }
        });
    };

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

})( jQuery );