;(function ($) {
   "use strict";
    console.log('Showcase Slider script loaded successfully!');
var ShowcaseSlider = function ($scope, $) {
        console.log("Showcase Slider JS Initialized for Widget");
        const setBackgroundImages = () => {
            var elements = $scope.find("[data-bg-src]");
            if (elements?.length > 0) {
                elements.each(function () {
                    var src = $(this).attr("data-bg-src");
                    $(this).css("background-image", "url(" + src + ")");
                    $(this).addClass("background-image");
                    $(this).removeAttr("data-bg-src");
                });
            }
        };

        const letterShowcase = () => {
            const letterShowcaseSlider = $scope.find(".letter-showcase__slider");
            const bulletsUl = $scope.find(".bullets ul");
            const sliderImages = $scope.find(".slider-images ul");

            if (
                letterShowcaseSlider.length &&
                bulletsUl.length &&
                sliderImages.length &&
                typeof Swiper !== "undefined"
            ) {
                // Clear existing bullets to prevent duplication on re-render
                bulletsUl.empty(); 
                
                const lnx = $scope.find(".swiper-slide .slide-content .title");
                if (lnx.length > 0) {
                    lnx.each(function () {
                        var txt = $(this).text().charAt(0);
                        var li = $('<li></li>').addClass('magnetize').attr('data-dist', '1');
                        var span = $('<span></span>').attr('data-cursor-type', 'medium').text(txt);
                        li.append(span);
                        bulletsUl.append(li);
                    });

                    bulletsUl.find("li:first-child").addClass("focus");
                    sliderImages.find("li:first-child").addClass("focus");

                    const swiper = new Swiper(letterShowcaseSlider[0], {
                        speed: 1000,
                        direction: "vertical",
                        slidesPerView: "auto",
                        simulateTouch: false,
                        mousewheel: true,
                        on: {
                            slideChange: function () {
                                const aktifindex = swiper.activeIndex;
                                const coord = aktifindex * -55;

                                const allBullets = bulletsUl.find("li");
                                const allSliderImages = sliderImages.find("li");

                                allBullets.removeClass("focus");
                                allSliderImages.removeClass("focus");

                                $(allBullets[aktifindex]).addClass("focus");
                                $(allSliderImages[aktifindex]).addClass("focus");

                                bulletsUl.css("margin-top", coord + "px");

                                const videos = sliderImages.find("video");
                                videos.each(function() {
                                    this.pause();
                                });

                                const focusedVideo = sliderImages.find(".focus video");
                                if (focusedVideo.length) {
                                    focusedVideo[0].play();
                                }
                            },
                        },
                    });

                    bulletsUl.find("li").each(function (index) {
                        $(this).on("click", function () {
                            swiper.slideTo(index);
                        });
                    });
                }
            }
        };

        const creativeThumbSlider = () => {
            const creativeThumbBackgroundDisplay = $scope.find(".creative-thumb__background");
            const showcaseTitle = $scope.find(".creative-thumb-title");
            const creativeThumbSlider = $scope.find(".creative-thumb__slider");
            const creativeThumbPagination = $scope.find(".creative-thumb__pagination");

            if (!creativeThumbSlider.length) return;

            function updateShowcase(swiper) {
                const activeVisualIndex = swiper.realIndex; // Use realIndex for loop mode
                const activeSlide = $(swiper.slides[swiper.activeIndex]);

                if (!activeSlide.length) return;
                
                const nudgeAmount = 25;

                $(swiper.slides).removeClass("custom-active-slide").css("transform", "");

                activeSlide.addClass("custom-active-slide");

                const prevSlide = activeSlide.prev('.swiper-slide');
                if (prevSlide.length) {
                    prevSlide.css("transform", `translateX(-${nudgeAmount}px)`);
                }
                const nextSlide = activeSlide.next('.swiper-slide');
                if (nextSlide.length) {
                    nextSlide.css("transform", `translateX(${nudgeAmount}px)`);
                }

                const title = activeSlide.data("title");
                const bgUrl = activeSlide.data("src");

                if (creativeThumbBackgroundDisplay.length) {
                    creativeThumbBackgroundDisplay.css("background-image", `url('${bgUrl}')`);
                }

                if (showcaseTitle.length && showcaseTitle.text() !== title) {
                    showcaseTitle.css("opacity", "0");
                    setTimeout(() => {
                        showcaseTitle.text(title);
                        showcaseTitle.css("opacity", "1");
                    }, 300);
                }
            }

            const swiper = new Swiper(creativeThumbSlider[0], {
                slidesPerView: 3,
                spaceBetween: 15,
                loop: true,
                mousewheel: true,
                grabCursor: true,
                speed: 1000,
                centeredSlides: true,
                pagination: {
                    el: creativeThumbPagination.length ? creativeThumbPagination[0] : null,
                    type: "progressbar",
                },
                breakpoints: {
                    768: {
                        slidesPerView: 3,
                        spaceBetween: 15,
                    },
                    992: {
                        slidesPerView: 4,
                        spaceBetween: 15,
                    },
                },
                on: {
                    init: function () {
                        updateShowcase(this);
                    },
                    slideChange: function () {
                        updateShowcase(this);
                    },
                },
            });
        };

        const verticalShowcase = () => {
            const verticalShowcaseSlider = $scope.find(".vertical-showcase__slider");
            const verticalShowcaseNavigation = $scope.find(".vertical-showcase__navigation");

            if (verticalShowcaseSlider.length && verticalShowcaseNavigation.length && typeof gsap !== 'undefined' && typeof SplitText !== 'undefined') {
                const titles = gsap.utils.toArray(verticalShowcaseSlider.find(".title"));
                const charsArray = titles.map(
                    (title) => new SplitText(title, { type: "chars" }).chars
                );

                gsap.set(charsArray, {
                    opacity: 0,
                    filter: "blur(10px)",
                    y: 10,
                });

                var swiper = new Swiper(verticalShowcaseSlider[0], {
                    slidesPerView: 1,
                    loop: true,
                    speed: 1000,
                    navigation: {
                        nextEl: verticalShowcaseNavigation.find(".button-next")[0],
                        prevEl: verticalShowcaseNavigation.find(".button-prev")[0],
                    },
                    on: {
                        init: function (swiper) {
                            const activeChars = charsArray[swiper.realIndex];
                            gsap.to(activeChars, {
                                opacity: 1,
                                filter: "blur(0px)",
                                y: 0,
                                duration: 0.6,
                                stagger: 0.1,
                                ease: "power2.out",
                            });
                        },
                        slideChange: function (swiper) {
                            gsap.set(charsArray, {
                                opacity: 0,
                                filter: "blur(10px)",
                                y: 10,
                            });
                            const activeChars = charsArray[swiper.realIndex];
                            gsap.to(activeChars, {
                                opacity: 1,
                                filter: "blur(0px)",
                                y: 0,
                                duration: 0.6,
                                stagger: 0.1,
                                ease: "power2.out",
                            });
                        },
                    },
                });
            }
        };
        setBackgroundImages();
        letterShowcase();
        creativeThumbSlider();
        verticalShowcase();
    };
    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-showcase-slider.default', ShowcaseSlider);
        
        // Handle editor preview mode
        if (elementorFrontend.isEditMode) {
            // Initialize showcase slider in editor preview
            elementorFrontend.hooks.addAction('frontend/element_ready/global', function ($scope) {
                if ($scope.find('.uafe-showcase-wrapper').length) {
                    setTimeout(function() {
                        ShowcaseSlider($scope, $);
                    }, 200);
                }
            });
            
            // Also initialize on editor preview refresh
            $(window).on('elementor:preview:loaded', function() {
                setTimeout(function() {
                    $('.elementor-widget-unlockafe-showcase-slider').each(function() {
                        var $scope = $(this);
                        ShowcaseSlider($scope, $);
                    });
                }, 300);
            });
        }
    });
    
    // Initialize on document ready for non-Elementor pages and editor mode
    $(document).ready(function() {
        $('.elementor-widget-unlockafe-showcase-slider').each(function() {
            var $scope = $(this);
            ShowcaseSlider($scope, $);
        });
        
        // Also initialize in editor mode after a delay to ensure libraries are loaded
        if (typeof elementorFrontend !== 'undefined' && elementorFrontend.isEditMode) {
            var initAttempts = 0;
            var maxAttempts = 15;
            
            var tryInit = function() {
                initAttempts++;
                if (typeof Swiper === 'undefined') {
                    if (initAttempts < maxAttempts) {
                        setTimeout(tryInit, 200);
                    }
                    return;
                }
                
                $('.elementor-widget-unlockafe-showcase-slider').each(function() {
                    var $scope = $(this);
                    ShowcaseSlider($scope, $);
                });
                
                console.log('Showcase Slider: Initialized in editor mode');
            };
            
            setTimeout(tryInit, 300);
            setTimeout(tryInit, 600);
            setTimeout(tryInit, 1000);
        }
    });

})(jQuery);
