(($) => {
    window["vidplexFeaturedVideo"] = (n) => {
        const element = $(`#${n}`);
        const attributes = window[n];

        if (attributes.type === "default") {
            const $iframeHolder = element.find(".iframe__holder");

            function convertTimeToSeconds(time) {
                let seconds = 0;

                if (time.h || time.m || time.s) {
                    if (String(time.h).length > 0) {
                        seconds += Number(time.h) * 3600;
                    }

                    if (String(time.m).length > 0) {
                        seconds += Number(time.m) * 60;
                    }

                    if (String(time.s).length > 0) {
                        seconds += Number(time.s);
                    }
                }

                return seconds;
            }

            function initializeYoutubeAPI() {
                const videoId = attributes.video.id;

                if (!videoId) return;

                const videoRenderer = element
                    .find(".iframe__holder > div")
                    .get(0);

                if (!videoRenderer || videoRenderer.dataset.playerInitialized)
                    return;

                let startTime = convertTimeToSeconds(attributes.video.start);
                let endTime = convertTimeToSeconds(attributes.video.end);

                let playerVars = {
                    autoplay: attributes.video.autoplay ? 1 : 0,
                    mute: 1,
                    disablekb: 1,
                    rel: 1,
                    controls: attributes.video.controls ? 1 : 0,
                    iv_load_policy: 3,
                    playsinline: 1,
                    fs: 0,
                    // start: startTime,
                    // end: endTime,
                    playlist: videoId,
                    enablejsapi: 1,
                };

                if (Number(startTime) > 0 && attributes.isPremium) {
                    playerVars.start = startTime;
                }

                if (Number(endTime) > 0 && attributes.isPremium) {
                    playerVars.end = endTime;
                }

                YTPlayerManager.create({
                    id: n,
                    el: videoRenderer,
                    videoId,
                    options: playerVars,
                    onReady: () => {
                        // Update end time if he duration is less than end time
                        setInterval(() => {
                            const stickyPlayer = YTPlayerManager.get(n);

                            const duration = stickyPlayer.getDuration();

                            if (duration <= endTime) {
                                endTime = duration;
                            }
                        }, 200);
                    },
                    onStateChange: (e) => {
                        if (e.data === YT.PlayerState.PLAYING) {
                            const stickyPlayer = YTPlayerManager.get(n);
                            if (attributes.video.loop && attributes.isPremium) {
                                const interval = setInterval(() => {
                                    if (
                                        stickyPlayer.getCurrentTime() >
                                            endTime &&
                                        Number(endTime) > 0
                                    ) {
                                        clearInterval(interval);
                                        stickyPlayer.seekTo(startTime, true);
                                    }
                                }, 200);
                            }
                        }
                    },
                });
            }

            initializeYoutubeAPI();

            const $closeIcon = element.find(".close__icon");
            $closeIcon.click(function () {
                if (attributes.isPremium && "default" === attributes.mode) {
                    $iframeHolder.addClass("iframe__wrapper");
                    $iframeHolder.removeClass("sticky-iframe__wrapper");
                    $closeIcon.addClass("display__none");

                    $(window).off("scroll");
                } else if (
                    !attributes.isPremium ||
                    "always" === attributes.mode
                ) {
                    $iframeHolder.addClass("hide");
                }

                stickyPlayer.pauseVideo();
            });

            if (attributes.isPremium && "default" === attributes.mode) {
                function checkStickyVisibility() {
                    const scrollTop = $(window).scrollTop();

                    const elTop = Number(element.attr("data-original-top"));
                    const elHeight = Number(
                        element.attr("data-original-height"),
                    );
                    const elBottom = elTop + elHeight;

                    // Trigger when element top has hit viewport top
                    // AND at least bottom 20% is still visible
                    const threshold = 0.2 * elHeight;

                    return scrollTop > elBottom - threshold;
                }

                // Save original section height on page load
                const originalTop = element.offset().top;
                const originalHeight = element.outerHeight();
                element
                    .attr("data-original-height", element.outerHeight())
                    .attr("data-original-top", originalTop)
                    .attr("data-original-height", originalHeight);

                let isSticky = false;

                // Scroll / resize handler
                $(window).on("scroll", function () {
                    const changeMode = checkStickyVisibility();

                    // No state change → do nothing
                    if (changeMode === isSticky) return;

                    isSticky = changeMode;

                    if (isSticky) {
                        $iframeHolder.addClass("sticky-iframe__wrapper");
                        $iframeHolder.removeClass("iframe__wrapper");
                        $closeIcon.removeClass("display__none");

                        $iframeHolder.addClass("transform-sticky");

                        setTimeout(() => {
                            $iframeHolder.removeClass("transform-sticky");
                        }, 200);
                    } else {
                        $iframeHolder.addClass("is-changing");

                        setTimeout(() => {
                            $iframeHolder.removeClass("is-changing");
                        }, 200);

                        $iframeHolder.addClass("iframe__wrapper");
                        $iframeHolder.removeClass("sticky-iframe__wrapper");
                        $closeIcon.addClass("display__none");
                    }
                });

                // Trigger once on load
                $(window).trigger("scroll");
            }
        } else if (attributes.type === "bg") {
            function convertTimeToSeconds(time) {
                let seconds = 0;

                if (time.h || time.m || time.s) {
                    if (String(time.h).length > 0) {
                        seconds += Number(time.h) * 3600;
                    }

                    if (String(time.m).length > 0) {
                        seconds += Number(time.m) * 60;
                    }

                    if (String(time.s).length > 0) {
                        seconds += Number(time.s);
                    }
                }

                return seconds;
            }

            function initializeYoutubeAPI(el, index) {
                const attrs = JSON.parse(el.attr("data-attributes"));
                const videoId = attrs.videoId;
                const videoRenderer = el.find(".iframe__holder > div").get(0);

                el.find(".video__image").addClass("display__none");

                if (!videoRenderer || videoRenderer.dataset.playerInitialized)
                    return;

                let startTime = convertTimeToSeconds(attrs.startTime);
                let endTime = convertTimeToSeconds(attrs.endTime);

                let playerVars = {
                    autoplay: attributes.controls.autoplay ? 1 : 0,
                    mute:
                        attributes.controls.mute || attributes.controls.autoplay
                            ? 1
                            : 0,
                    disablekb: 1,
                    rel: 1,
                    iv_load_policy: 3,
                    playsinline: 1,
                    fs: 0,
                    controls: attributes.controls.showControls ? 1 : 0,
                    playlist: videoId,
                    enablejsapi: 1,
                };

                if (Number(startTime) > 0) {
                    playerVars.start = startTime;
                }

                if (Number(endTime) > 0) {
                    playerVars.end = endTime;
                }

                YTPlayerManager.create({
                    id: n + "_" + index,
                    el: videoRenderer,
                    videoId,
                    options: playerVars,
                    onReady: () => {
                        // Update end time if he duration is less than end time
                        setInterval(() => {
                            const player = YTPlayerManager.get(n + "_" + index);
                            const duration = player.getDuration();

                            if (duration <= endTime) {
                                endTime = duration;
                            }
                        }, 200);
                    },
                    onStateChange: (e) => {
                        if (e.data === YT.PlayerState.PLAYING) {
                            if (attributes.controls.loop) {
                                const player = YTPlayerManager.get(
                                    n + "_" + index,
                                );
                                const interval = setInterval(() => {
                                    if (
                                        player.getCurrentTime() > endTime &&
                                        Number(endTime) > 0
                                    ) {
                                        clearInterval(interval);
                                        player.seekTo(startTime, true);
                                    }
                                }, 200);
                            }
                        } else if (e.data === YT.PlayerState.ENDED) {
                            if (attributes.controls.loop) {
                                const player = YTPlayerManager.get(
                                    n + "_" + index,
                                );
                                player.seekTo(startTime, true);
                            }
                        }
                    },
                });
            }

            element
                .find(".vidplex-background-video-item")
                .each(function (index) {
                    const $this = $(this);

                    initializeYoutubeAPI($this, index);
                });

            if (attributes.isPremium && attributes.layout === "slider") {
                console.log(attributes.carousel.slidesPerView);

                let swiperAttrs = {
                    init: true,
                    direction: "horizontal",
                    slidesPerView: attributes.carousel.slidesPerView?.desktop,
                    centeredSlides: attributes.carousel.centeredSlides,
                    speed: attributes.carousel.speed,
                    spaceBetween: attributes.carousel.spaceBetween,
                    loop: attributes.carousel.loop,
                    breakpoints: {
                        1: {
                            slidesPerView:
                                attributes.carousel.slidesPerView?.mobile,
                        },
                        768: {
                            slidesPerView:
                                attributes.carousel.slidesPerView?.tablet,
                        },
                        1025: {
                            slidesPerView:
                                attributes.carousel.slidesPerView?.desktop,
                        },
                    },
                    navigation: {
                        nextEl: `#${n} .swiper-button-next`,
                        prevEl: `#${n} .swiper-button-prev`,
                    },
                    pagination: {
                        el: `#${n} .swiper-pagination`,
                    },
                };

                if (attributes.carousel.autoplay.status) {
                    swiperAttrs.autoplay = {
                        ...attributes.carousel.autoplay,
                    };
                } else {
                    delete swiperAttrs.autoplay;
                }

                const swiperContainer = element.find(".swiper-container");

                const swiper = new Swiper(swiperContainer[0], swiperAttrs);
            }
        }
    };
})(jQuery);
