(function($) {
    $(window).on('elementor/frontend/init', () => {
        class VideoWidget extends elementorModules.frontend.handlers.Base {
            getDefaultSettings() {
                return {
                    selectors: {
                        outerWrap: '.pp-video',
                        videoPlay: '.pp-video-play',
                        innerWrap: '.pp-video-container',
                        stickyWrap: '.pp-video-sticky-wrap',
                    }
                };
            }

            getDefaultElements() {
                const selectors = this.getSettings('selectors');
                return {
                    $outerWrap: this.$element.find(selectors.outerWrap),
                    $videoPlay: this.$element.find(selectors.videoPlay),
                    $innerWrap: this.$element.find(selectors.innerWrap),
                    $stickyWrap: this.$element.find(selectors.stickyWrap),
                };
            }

            bindEvents() {
                this.initVideo();
            }

            initVideo() {
                const outerWrap = this.elements.$outerWrap,
                    innerWrap   = this.elements.$innerWrap,
                    videoSticky = this.getElementSettings('enable_sticky'),
                    viewport    = outerWrap.data('vs-viewport'),
                    isLightbox  = this.elements.$videoPlay.hasClass('pp-video-play-lightbox'),
                    self        = this;

                this.elements.$videoPlay.off('click').on('click', function(e) {
                    e.preventDefault();

                    const videoPlayer = $(this).find('.pp-video-player');
                    if (!isLightbox) {
                        self.videoPlay(videoPlayer, outerWrap);
                    }
                });

                if (!this.isEdit && this.elements.$videoPlay.data('autoplay') === '1' && !isLightbox) {
                    const autoplayPlayer = this.$element.find('.pp-video-player');
                    self.videoPlay(autoplayPlayer, outerWrap);
                }

                if (videoSticky === 'yes') {
                    const stickyMarginBottom = outerWrap.data('sticky-bottom');

                    const observer = new IntersectionObserver((entries) => {
                        entries.forEach(entry => {
                            if (!entry.isIntersecting && entry.boundingClientRect.top < 0) {
                                outerWrap.removeClass('pp-sticky-hide').addClass('pp-sticky-apply');
                                $(document).trigger('pp_after_sticky_applied', [entry.target]);
                            } else if (entry.isIntersecting) {
                                outerWrap.removeClass('pp-sticky-apply').addClass('pp-sticky-hide');
                            }
                        });
                    }, {
                        root: null,
                        rootMargin: '0px',
                        threshold: viewport / 100,
                    });

                    observer.observe(outerWrap[0]);

                    this.$element.find('.pp-video-sticky-close')
                        .off('click.closetrigger')
                        .on('click.closetrigger', () => {
                            observer.unobserve(outerWrap[0]);
                            outerWrap.removeClass('pp-sticky-apply pp-sticky-hide');
                        });

                    this.checkResize(observer);
                    this.checkScroll();

                    window.addEventListener('scroll', this.checkScroll.bind(this));
                    $(window).on('resize', () => this.checkResize(observer));

                    $(document).on('pp_after_sticky_applied', () => {
                        const infobar = this.$element.find('.pp-video-sticky-infobar');

                        if (infobar.length) {
                            let infobarHeight = infobar.outerHeight();

                            if (this.$element.hasClass('pp-video-sticky-center_left') || this.$element.hasClass('pp-video-sticky-center_right')) {
                                infobarHeight = Math.ceil(infobarHeight / 2);
                                innerWrap.css('top', `calc(50% - ${infobarHeight}px)`);
                            }

                            if ((this.$element.hasClass('pp-video-sticky-bottom_left') || this.$element.hasClass('pp-video-sticky-bottom_right')) && stickyMarginBottom !== '') {
                                const stickBottom = Math.ceil(infobarHeight) + stickyMarginBottom;
                                innerWrap.css('bottom', stickBottom);
                            }
                        }
                    });
                }

                // Fix Safari black border
                $(window).on('load', () => {
                    setTimeout(() => {
                        const videoFrame = $('.pp-video iframe');
                        if (videoFrame.length) {
                            videoFrame.each(function () {
                                $(this).contents().find('body').css('margin', '0');
                            });
                        }
                    }, 1000);
                });
            }

            videoPlay(selector, outerWrap) {
                const iframe = $('<iframe>', {
                    frameborder: '0',
                    allowfullscreen: '1',
                    allow: 'autoplay; encrypted-media;',
                });

                const videoSrc = selector.data('src');

                if (selector.find('iframe').length === 0) {
                    if (
                        outerWrap.hasClass('pp-video-type-youtube') ||
                        outerWrap.hasClass('pp-video-type-vimeo') ||
                        outerWrap.hasClass('pp-video-type-dailymotion')
                    ) {
                        iframe.attr('src', videoSrc);
                    }

                    selector.html(iframe);

                    if (outerWrap.hasClass('pp-video-type-hosted')) {
                        const hostedVideoHtml = JSON.parse(outerWrap.data('hosted-html'));

                        iframe.on('load', () => {
                            const iframeBody = iframe.contents().find('body');
                            iframeBody.html(hostedVideoHtml);

                            const videoEl = iframeBody.find('video');

                            if (videoEl.length) {
                                videoEl.css({
                                    width: '100%',
                                    height: '100%',
                                });
                                videoEl.attr('autoplay', 'autoplay');
                            }
                        });
                    }
                }
            }

            checkResize(observer) {
                const outerWrap = this.elements.$outerWrap,
                    stickyDevice = this.getElementSettings('sticky_hide_on');
                var currentDeviceMode = elementorFrontend.getCurrentDeviceMode();

                if (
                    Array.isArray(stickyDevice) &&
                    stickyDevice.includes(currentDeviceMode)
                ) {
                    this.disableSticky(observer);
                } else {
                    observer.observe(outerWrap[0]);
                }
            }

            disableSticky(observer) {
                observer.unobserve(this.elements.$outerWrap[0]);
                this.elements.$outerWrap.removeClass('pp-sticky-apply');
                this.elements.$outerWrap.removeClass('pp-sticky-hide');
            }

            checkScroll() {
                if (this.isEdit) {
                    return;
                }

                if (this.elements.$outerWrap.hasClass('pp-sticky-apply')) {
                    this.elements.$stickyWrap.draggable({
                        start: function () {
                            const $this = $(this);
                            $this.css({
                                transform: 'none',
                                top: `${$this.offset().top}px`,
                                left: `${$this.offset().left}px`,
                            });
                        },
                        containment: 'window',
                    });
                }
            }
        }

        elementorFrontend.elementsHandler.attachHandler('pp-video', VideoWidget);
    });
})(jQuery);
