(function ($) {
    function initializeSlider($slider) {
        const $track = $slider.find('.testimonials-track');
        const $cards = $track.children();
        const totalCards = $cards.length;

        const settings = {
            cardsPerView: getCardsPerView($slider),
            autoScroll: $slider.data('auto-scroll') === 'yes',
            interval: parseInt($slider.data('interval')) || 5000
        };

        let currentIndex = 0;
        let animationId = null;
        let autoScrollInterval = null;

        let cachedSizes = {
            cardWidth: 0,
            containerWidth: 0,
            effectiveCardsPerView: 0,
            maxIndex: 0
        };

        function getCardsPerView($slider) {
            if ($slider.hasClass('slider-1')) return 1;
            if ($slider.hasClass('slider-2')) return 2;
            if ($slider.hasClass('slider-3')) return 3;
            if ($slider.hasClass('slider-4')) return 4;
            return 3;
        }

        function updateCachedSizes() {
            cachedSizes.cardWidth = $cards.first().outerWidth(true);
            cachedSizes.containerWidth = $slider.width();
            cachedSizes.effectiveCardsPerView = window.innerWidth <= 768 ? 1 : settings.cardsPerView;
            cachedSizes.maxIndex = totalCards - cachedSizes.effectiveCardsPerView;
        }

        function updateSlider() {
            if (animationId) {
                cancelAnimationFrame(animationId);
            }

            animationId = requestAnimationFrame(() => {
                updateCachedSizes();

                currentIndex = Math.max(0, Math.min(currentIndex, cachedSizes.maxIndex));

                const totalWidthPx = cachedSizes.cardWidth * totalCards;
                let offset;

                if (currentIndex === cachedSizes.maxIndex && totalCards - currentIndex < cachedSizes.effectiveCardsPerView) {
                    const remainingCards = totalCards - currentIndex;
                    const remainingWidth = remainingCards * cachedSizes.cardWidth;
                    offset = -((totalWidthPx - cachedSizes.containerWidth) - (cachedSizes.containerWidth - remainingWidth) / 2);
                } else {
                    offset = -currentIndex * cachedSizes.cardWidth;
                }

                offset = Math.max(offset, -(totalWidthPx - cachedSizes.containerWidth));
                offset = Math.min(offset, 0);

                $track.css('transform', `translateX(${offset}px)`);
                animationId = null;
            });
        }

        function initReadMore() {
            $cards.each(function () {
                const $card = $(this);
                const $text = $card.find('.testimonial-text');
                const $button = $card.find('.read-more');

                if (!$text.length || !$button.length) return;

                const lineHeight = parseFloat($text.css('line-height')) || 20;
                const maxHeight = 8 * lineHeight;

                if ($text[0].scrollHeight > maxHeight) {
                    $button.show();
                }
            });
        }

        $slider.on('click', '.read-more', function (e) {
            e.preventDefault();
            const $button = $(this);
            const $text = $button.siblings('.testimonial-text');

            if ($text.hasClass('expanded')) {
                $text.removeClass('expanded');
                $button.removeClass('expanded').text('Read More');
            } else {
                $text.addClass('expanded');
                $button.addClass('expanded').text('Hide');
            }
        });

        function startAutoScroll() {
            if (!settings.autoScroll) return;

            autoScrollInterval = setInterval(() => {
                updateCachedSizes();
                if (currentIndex < cachedSizes.maxIndex) {
                    currentIndex++;
                } else {
                    currentIndex = 0;
                }
                updateSlider();
            }, settings.interval);
        }

        function stopAutoScroll() {
            if (autoScrollInterval) {
                clearInterval(autoScrollInterval);
                autoScrollInterval = null;
            }
        }

        const throttledResize = throttle(updateSlider, 100);

        initReadMore();
        updateSlider();
        startAutoScroll();

        $(window).on('resize', throttledResize);

        $slider.on('destroy', function () {
            stopAutoScroll();
            $(window).off('resize', throttledResize);
            if (animationId) {
                cancelAnimationFrame(animationId);
            }
        });

        return {
            next: function () {
                updateCachedSizes();
                if (currentIndex < cachedSizes.maxIndex) {
                    currentIndex++;
                    updateSlider();
                }
            },
            prev: function () {
                if (currentIndex > 0) {
                    currentIndex--;
                    updateSlider();
                }
            },
            destroy: function () {
                $slider.trigger('destroy');
            }
        };
    }

    const sliders = new Map();

    function initializeAllSliders() {
        $('.testimonials-slider').each(function () {
            const $slider = $(this);
            if (!sliders.has($slider[0])) {
                sliders.set($slider[0], initializeSlider($slider));
            }
        });
    }

    $(document).on('click', '.next-testimonial', function (e) {
        e.preventDefault();
        const $slider = $(this).closest('.testimonials-section').find('.testimonials-slider');
        const sliderInstance = sliders.get($slider[0]);
        if (sliderInstance) {
            sliderInstance.next();
        }
    });

    $(document).on('click', '.prev-testimonial', function (e) {
        e.preventDefault();
        const $slider = $(this).closest('.testimonials-section').find('.testimonials-slider');
        const sliderInstance = sliders.get($slider[0]);
        if (sliderInstance) {
            sliderInstance.prev();
        }
    });

    $(document).ready(initializeAllSliders);

    if (window.elementorFrontend) {
        $(window).on('elementor/frontend/init', function () {
            elementorFrontend.hooks.addAction('frontend/element_ready/testimonials_slider.default', function ($scope) {
                const $slider = $scope.find('.testimonials-slider');
                if ($slider.length) {
                    sliders.set($slider[0], initializeSlider($slider));
                }
            });
        });
    }

    window.testimonialSliders = {
        destroy: function () {
            sliders.forEach(slider => slider.destroy());
            sliders.clear();
        }
    };

})(jQuery);