(function ($) {
    const getInitialSlidesPerView = function (desktop, tablet, mobile) {
        const viewportWidth = window.innerWidth || document.documentElement.clientWidth || 0;

        if (viewportWidth >= 1025) {
            return desktop;
        }

        if (viewportWidth >= 768) {
            return tablet;
        }

        return mobile;
    };

    const updateSwiperInstance = function (swiperInstance) {
        if (!swiperInstance || swiperInstance.destroyed) {
            return;
        }

        swiperInstance.updateSize();
        swiperInstance.updateSlides();
        swiperInstance.updateProgress();
        swiperInstance.updateSlidesClasses();
        swiperInstance.update();
    };

    const setNavigationVisibility = function ($wrap, shouldShow) {
        if (shouldShow) {
            $wrap.removeClass('sitsel-nav-hidden');
            return;
        }

        $wrap.addClass('sitsel-nav-hidden');
    };

    const initSwiper = function ($scope) {
    $scope.find('.sitsel-testimonial-slider').each(function () {
        const existing = this.swiper;
        if (existing && !existing.destroyed) {
            existing.destroy(true, true);
        }
    });

    $scope.find('.sitsel-swiper-wrap').each(function () {
            const $wrap = $(this);
            const $slider = $wrap.find('.sitsel-testimonial-slider');
            if (!$slider.length || typeof Swiper === 'undefined') {
                return;
            }

            $wrap.addClass('sitsel-swiper-pending');

            const layoutType = $slider.data('layout-type') || 'slider';
            if (layoutType !== 'slider') {
                return;
            }

            const columnsDesktop = parseInt($slider.data('columns'), 10) || 3;
            const columnsTablet = parseInt($slider.data('columns-tablet'), 10) || columnsDesktop;
            const columnsMobile = parseInt($slider.data('columns-mobile'), 10) || 1;
            const slidesToScroll = parseInt($slider.data('scroll'), 10) || 1;
            const spaceBetween = parseInt($slider.data('gutter'), 10) || 15;
            const loop = $slider.data('loop') === true || $slider.data('loop') === 'true';
            const effect = $slider.data('effect') || 'slide';
            const speed = parseInt($slider.data('speed'), 10) || 700;
            const pagination = $slider.data('pagination') === true || $slider.data('pagination') === 'true';
            const navigation = $slider.data('navigation') === true || $slider.data('navigation') === 'true';

            const paginationEl = $wrap.find('.swiper-pagination')[0] || null;
            const nextBtn = $wrap.find('.swiper-button-next')[0] || null;
            const prevBtn = $wrap.find('.swiper-button-prev')[0] || null;
            const hasNavigationUi = navigation && nextBtn && prevBtn;

            const totalSlides = $slider.find('.swiper-slide').length;
            const maxColumns = Math.max(columnsDesktop, columnsTablet, columnsMobile);
            const safeLoop = loop && totalSlides > Math.max(1, maxColumns);
            const useResponsiveColumns = effect !== 'fade';
            const initialSlidesPerView = useResponsiveColumns
                ? getInitialSlidesPerView(columnsDesktop, columnsTablet, columnsMobile)
                : 1;

            const shouldShowNavOnFirstPaint = hasNavigationUi && totalSlides > Math.max(1, initialSlidesPerView);
            setNavigationVisibility($wrap, shouldShowNavOnFirstPaint);

            const sliderEl = $slider[0];
            const sliderId = sliderEl.id || ('sitsel-testimonial-slider-' + Math.random().toString(36).slice(2, 10));
            sliderEl.id = sliderId;
            const windowEventNamespace = '.sitselTestimonialSwiper-' + sliderId;

            const existingResizeObserver = $slider.data('sitselResizeObserver');
            if (existingResizeObserver && typeof existingResizeObserver.disconnect === 'function') {
                existingResizeObserver.disconnect();
            }

            const existingSwiper = sliderEl.swiper;
            if (existingSwiper && !existingSwiper.destroyed) {
                existingSwiper.destroy(true, true);
            }

            const swiper = new Swiper(sliderEl, {
    slidesPerView: columnsMobile,
    slidesPerGroup: slidesToScroll,
    spaceBetween: spaceBetween,
    loop: safeLoop,
    effect: effect,
    speed: speed,
    observer: true,
    observeParents: true,
    resizeObserver: true,
    watchOverflow: true,
    pagination: pagination && paginationEl
        ? { el: paginationEl, clickable: true }
        : false,
    navigation: navigation && nextBtn && prevBtn
        ? { nextEl: nextBtn, prevEl: prevBtn }
        : false,
    breakpoints: useResponsiveColumns ? {
        0: {
            slidesPerView: columnsMobile,
        },
        768: {
            slidesPerView: columnsTablet,
        },
        1025: {
            slidesPerView: columnsDesktop,
        },
    } : {},
});

            const syncNavigationVisibility = function () {
                if (!hasNavigationUi) {
                    setNavigationVisibility($wrap, false);
                    return;
                }

                setNavigationVisibility($wrap, !swiper.isLocked);
            };

            const forceUpdate = function () {
                updateSwiperInstance(swiper);
                syncNavigationVisibility();
                $wrap.removeClass('sitsel-swiper-pending');
            };

            requestAnimationFrame(function () {
                requestAnimationFrame(forceUpdate);
            });
            setTimeout(forceUpdate, 80);
            setTimeout(forceUpdate, 250);

            $(window)
                .off('load' + windowEventNamespace)
                .off('resize' + windowEventNamespace)
                .off('orientationchange' + windowEventNamespace)
                .on('load' + windowEventNamespace + ' resize' + windowEventNamespace + ' orientationchange' + windowEventNamespace, forceUpdate);

            if ('ResizeObserver' in window) {
                const resizeObserver = new ResizeObserver(function () {
                    forceUpdate();
                });
                resizeObserver.observe(sliderEl);
                resizeObserver.observe($wrap[0]);
                $slider.data('sitselResizeObserver', resizeObserver);
            }

            swiper.on('lock unlock breakpoint resize observerUpdate', syncNavigationVisibility);

            if (hasNavigationUi) {
                const $navBtns = $wrap.find('.swiper-button-prev, .swiper-button-next');
                $navBtns.off('click.sitselNavActive').on('click.sitselNavActive', function () {
                    $navBtns.removeClass('is-active');
                    $(this).addClass('is-active');

                    const transitionMs = speed || 700;
                    const $btn = $(this);
                    clearTimeout($btn.data('sitselActiveTimer'));
                    $btn.data(
                        'sitselActiveTimer',
                        setTimeout(function () {
                            $btn.removeClass('is-active');
                        }, transitionMs)
                    );
                });
            }
        });
    };

    // REPLACE the entire initLayoutPagination function with this:
const initLayoutPagination = function ($scope) {
    $scope.find('.sitsel-testimonial-layout').each(function () {
        const $layout = $(this);
        const layoutType = $layout.data('layout-type') || 'grid';

        // Slider uses Swiper pagination — never touch it here
        if (layoutType === 'slider') {
            // Remove the pending class so nothing stays hidden
            $layout.removeClass('sitsel-pagination-pending');
            return;
        }

        const paginationEnabled = ($layout.data('enable-pagination') || 'no').toString() === 'yes';
        const paginationType   = ($layout.data('pagination-type') || 'numbers').toString();
        const itemsPerPage     = parseInt($layout.data('items-per-page'), 10) || 6;
        const $list            = $layout.find('.sitsel-testimonial-list').first();
        const $items           = $list.children('.sitsel-testimonial-item');
        const $pagination      = $layout.find('.sitsel-testimonial-pagination').first();

        // Always remove pending so CSS pre-hide is lifted before we take control
        $layout.removeClass('sitsel-pagination-pending');

        if (!$list.length || !$items.length) {
            return;
        }

        const totalItems = $items.length;
        const totalPages = Math.max(1, Math.ceil(totalItems / itemsPerPage));
        const limitItems = paginationEnabled && itemsPerPage > 0;

        const showAllItems = function () {
    $layout.removeClass('sitsel-pagination-pending');
    $items.show().attr('aria-hidden', 'false');
    if ($pagination.length) { $pagination.empty().hide(); }
};

        if (!paginationEnabled || !limitItems || totalItems <= itemsPerPage) {
            showAllItems();
            return;
        }

        const renderPage = function (page) {
            const currentPage = Math.min(Math.max(parseInt(page, 10) || 1, 1), totalPages);
            const start = (currentPage - 1) * itemsPerPage;
            const end   = start + itemsPerPage;

            $items.hide().attr('aria-hidden', 'true').slice(start, end).show().attr('aria-hidden', 'false');

            if (!$pagination.length || 'none' === paginationType) {
                if ($pagination.length) { $pagination.empty().hide(); }
                return;
            }

            const buttons    = [];
            const prevPage   = Math.max(1, currentPage - 1);
            const nextPage   = Math.min(totalPages, currentPage + 1);
            const prevDisabled = currentPage === 1;
            const nextDisabled = currentPage === totalPages;

            buttons.push(
                '<button class="sitsel-testimonial-page-btn sitsel-testimonial-page-prev' +
                (prevDisabled ? ' is-disabled' : '') +
                '" type="button" data-page="' + prevPage + '"' +
                (prevDisabled ? ' disabled aria-disabled="true"' : '') + '>Prev</button>'
            );

            if (paginationType === 'numbers') {
                for (let p = 1; p <= totalPages; p++) {
                    buttons.push(
                        '<button class="sitsel-testimonial-page-btn' +
                        (p === currentPage ? ' is-active' : '') +
                        '" type="button" data-page="' + p + '"' +
                        (p === currentPage ? ' aria-current="page"' : '') + '>' + p + '</button>'
                    );
                }
            }

            buttons.push(
                '<button class="sitsel-testimonial-page-btn sitsel-testimonial-page-next' +
                (nextDisabled ? ' is-disabled' : '') +
                '" type="button" data-page="' + nextPage + '"' +
                (nextDisabled ? ' disabled aria-disabled="true"' : '') + '>Next</button>'
            );

            $pagination.html('<div class="sitsel-testimonial-pagination-inner">' + buttons.join('') + '</div>').show();
        };

        $pagination.off('.sitselTestimonialPager').on('click.sitselTestimonialPager', 'button[data-page]', function () {
            const $btn = $(this);
            if ($btn.is(':disabled') || $btn.hasClass('is-disabled')) { return; }
            renderPage(parseInt($btn.data('page'), 10) || 1);
        });

        $layout.removeClass('sitsel-pagination-pending');
        renderPage(1);
    });
};

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sitsel_testimonial.default',
            function ($scope) {
                initSwiper($scope);
                initLayoutPagination($scope);
            }
        );
    });
})(jQuery);
