(function ($) {
    'use strict';

    const SifencyProjectCarousel = function ($scope, $) {
        const $wrapper = $scope.find('.sifency-project-carousel-wrapper');
        const $rows = $wrapper.find('.sifency-pc-swiper');
        const $previewImg = $wrapper.find('.sifency-pc-active-img');
        
        const speed = $wrapper.data('speed') || 5000;
        const intensity = $wrapper.data('intensity') || 3;
        const swipers = [];

        $rows.each(function () {
            const isRtl = $(this).attr('dir') === 'rtl';
            const swiper = new Swiper(this, {
                loop: true,
                slidesPerView: 'auto',
                speed: speed,
                freeMode: true,
                autoplay: {
                    delay: 0,
                    disableOnInteraction: false,
                    reverseDirection: isRtl
                },
                allowTouchMove: true,
            });
            swipers.push(swiper);
        });

        $wrapper.find('.sifency-pc-item').on('mouseenter', function() {
            const src = $(this).data('image');
            if (!src || $previewImg.attr('src') === src) return;

            $previewImg.css('opacity', 0);
            setTimeout(() => {
                $previewImg.attr('src', src);
                $previewImg.css('opacity', 1);
            }, 150);
        });

        let lastScrollTop = window.pageYOffset;
        
        $(window).on('scroll.sifencyMarquee', function() {
            const st = window.pageYOffset;
            const diff = st - lastScrollTop;
            const velocity = diff * intensity;

            swipers.forEach((s) => {
                const isRtl = $(s.el).attr('dir') === 'rtl';
                const dirFactor = isRtl ? 1 : -1;
                
                const currentTranslate = s.getTranslate();
                s.setTranslate(currentTranslate + (velocity * dirFactor));
            });

            lastScrollTop = st <= 0 ? 0 : st;
        });
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-project-carousel.default', SifencyProjectCarousel);
    });

})(jQuery);