(function ($) {

    const initHeroSlider = function ($scope) {
        $scope.find('.sitsel-hero-slider').each(function () {
            const sliderEl = this;
            const $slider  = $(this);

            if (typeof Swiper === 'undefined') return;
            if (sliderEl.swiper && !sliderEl.swiper.destroyed) {
                sliderEl.swiper.destroy(true, true);
            }

            const config = $slider.data('slider') || {};

            const autoplay   = !!config.autoplay;
            const autoplayMs = parseInt(config.autoplaySpeed, 10)   || 4000;
            const speed      = parseInt(config.transitionSpeed, 10) || 700;
            const loop       = !!config.loop;
            const pauseHover = !!config.pauseOnHover;
            const centered   = !!config.centeredSlides;

            const spv       = parseFloat(config.slidesPerView)       || 1;
            const spvTablet = parseFloat(config.slidesPerViewTablet) || spv;
            const spvMobile = parseFloat(config.slidesPerViewMobile) || 1;

            // Converts a value+unit pair to px — reads live font sizes so calling
            // it again after a viewport change always gives the correct result.
            function toPx(size, unit) {
                if (!size) return 0;
                switch (unit) {
                    case 'rem': return size * parseFloat(getComputedStyle(document.documentElement).fontSize);
                    case 'em':  return size * parseFloat(getComputedStyle(sliderEl).fontSize);
                    case '%':   return size / 100 * sliderEl.offsetWidth;
                    default:    return size;
                }
            }

            // Wrappers that always re-read live values — safe to call on resize.
            function spbDesktop() { return toPx(config.spaceBetween,       config.spaceBetweenUnit       || 'px'); }
            function spbTabletFn(){ return toPx(config.spaceBetweenTablet, config.spaceBetweenTabletUnit || 'px'); }
            function spbMobileFn(){ return toPx(config.spaceBetweenMobile, config.spaceBetweenMobileUnit || 'px'); }

            const $prevBtn     = $slider.find('.swiper-button-prev')[0] || null;
            const $nextBtn     = $slider.find('.swiper-button-next')[0] || null;
            const $pagEl       = $slider.find('.swiper-pagination')[0]  || null;
            const $scrollbarEl = $scope.find('.sitsel-slider-scrollbar')[0] || null;
            const showScrollbar = !!config.showScrollbar;

            new Swiper(sliderEl, {
                effect:         'slide',
                speed:          speed,
                loop:           loop,
                observer:       true,
                observeParents: true,
                resizeObserver: true,
                watchOverflow:  true,
                centeredSlides: centered,
                slidesPerView:  spv,
                spaceBetween:   spbDesktop(),
                touchStartPreventDefault: false,
                grabCursor: true,
                simulateTouch: true,

                breakpoints: {
                    0: {
                        slidesPerView: spvMobile,
                        spaceBetween:  spbMobileFn(),
                    },
                    768: {
                        slidesPerView: spvTablet,
                        spaceBetween:  spbTabletFn(),
                    },
                    1025: {
                        slidesPerView: spv,
                        spaceBetween:  spbDesktop(),
                    },
                },

                // Re-convert rem/em/% → px whenever the viewport changes so
                // responsive typography (e.g. smaller root font-size on mobile)
                // and %-based gaps always reflect the current viewport state.
                on: {
                    resize: function () {
                        this.params.breakpoints[0].spaceBetween    = spbMobileFn();
                        this.params.breakpoints[768].spaceBetween  = spbTabletFn();
                        this.params.breakpoints[1025].spaceBetween = spbDesktop();
                        // Force Swiper to re-evaluate breakpoints with new values.
                        this.currentBreakpoint = null;
                        this.update();
                    },
                },

                autoplay: autoplay ? {
                    delay:                autoplayMs,
                    pauseOnMouseEnter:    pauseHover,
                    disableOnInteraction: false,
                } : false,

                pagination: $pagEl ? {
                    el:              $pagEl,
                    clickable:       true,
                    bulletClass:       'sitsel-slider-dot',
                    bulletActiveClass: 'sitsel-active',
                    renderBullet: function (index, className) {
                        return '<button class="' + className + '" type="button"></button>';
                    },
                } : false,

                navigation: ($prevBtn && $nextBtn) ? {
                    prevEl: $prevBtn,
                    nextEl: $nextBtn,
                } : false,

                scrollbar: ($scrollbarEl && showScrollbar) ? {
                    el:            $scrollbarEl,
                    draggable:     true,
                    snapOnRelease: true,
                    dragSize:      'auto',
                } : false,
            });
        });
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sitsel_hero_slider.default',
            function ($scope) {
                if (document.readyState === 'complete') {
                    initHeroSlider($scope);
                } else {
                    $(window).one('load', function () {
                        initHeroSlider($scope);
                    });
                }
            }
        );
    });

})(jQuery);