(function( $ ) {
    'use strict';

    var SifencyVideoHandler = function( $scope, $ ) {
        var $wrapper = $scope.find('.sifency-video-wrapper');
        var $button = $wrapper.find('.sifency-video-button');
        var $modal = $wrapper.find('.sifency-video-modal');
        var $modalContent = $modal.find('.sifency-video-modal-content');
        var $closeBtn = $modal.find('.sifency-video-modal-close');
        var $overlay = $modal.find('.sifency-modal-overlay');

        if( !$button.length ) {
            return;
        }

        var videoType = $wrapper.data('video-type');
        var videoUrl = $wrapper.data('video-url');
        var mute = $wrapper.data('mute');

        function getPlayableUrl() {
            var finalUrl = videoUrl;
            if (videoType === 'youtube' || videoType === 'vimeo') {
                var separator = finalUrl.includes('?') ? '&' : '?';
                finalUrl += separator + 'autoplay=1'; 
                if(mute === 'yes') {
                   finalUrl += '&mute=1'; 
                }
            }
            return finalUrl;
        }

        $button.on('click', function(e) {
            e.preventDefault();

            var html = '';

            if (videoType === 'self_hosted') {
                html = '<video controls autoplay ' + (mute === 'yes' ? 'muted' : '') + ' controlsList="nodownload" style="width:100%; height:100%;">';
                html += '<source src="' + videoUrl + '" type="video/mp4">';
                html += 'Your browser does not support the video tag.</video>';
            } else {
                html = '<iframe src="' + getPlayableUrl() + '" allow="autoplay; fullscreen" allowfullscreen style="width:100%; height:100%;"></iframe>';
            }

            $modal.appendTo('body');

            $modalContent.html(html);
            $modal.addClass('is-active').css('display', 'flex');
            $('body').addClass('sifency-modal-open');
        });

        function closeModal() {
            $modal.removeClass('is-active');
            
            setTimeout(function() {
                $modal.css('display', 'none');
                $modalContent.empty();
                $modal.appendTo($wrapper); 
            }, 300);
            
            $('body').removeClass('sifency-modal-open');
        }

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

        $(document).on('keyup', function(e) {
            if (e.key === "Escape") {
                closeModal();
            }
        });
    };
    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-widget-video.default', SifencyVideoHandler);
    });

})( jQuery );