document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.reviews-block').forEach(function(block) {
        const blockId = block.getAttribute('data-reviews-id');
        initReviewsBlock(blockId);
    });
});

function initReviewsBlock(blockId) {
    const container = document.getElementById(blockId);
    if (!container) return;

    const swipers = {};
    let lightbox;

    function initAllSwipers() {
        container.querySelectorAll('.reviews-swiper').forEach(swiperEl => {
            const tabId = swiperEl.id.replace('swiper-', '');

            swipers[tabId] = new Swiper(`#${blockId} #swiper-${tabId}`, {
                slidesPerView: 'auto',
                spaceBetween: 24,
                grabCursor: true,
                watchSlidesProgress: true,
                scrollbar: {
                    el: `#${blockId} #swiper-${tabId} .swiper-scrollbar`,
                    draggable: true,
                },
            });
        });
    }

    function initLightbox(tabId) {
        const currentSelector = `#${blockId} #tab-${tabId} .glightbox`;

        if (lightbox?.settings?.selector !== currentSelector) {
            if (lightbox) {
                lightbox.destroy();
            }

            const isVideo = tabId === 'video';

            lightbox = GLightbox({
                selector: currentSelector,
                touchNavigation: true,
                loop: true,
                autoplayVideos: false,
                videosWidth: isVideo ? '90vw' : 'auto',
                videosHeight: isVideo ? '80vh' : 'auto',
                plyr: isVideo ? {
                    css: 'https://cdn.plyr.io/3.7.8/plyr.css',
                    js: 'https://cdn.plyr.io/3.7.8/plyr.js',
                    config: {
                        ratio: '16:9',
                        fullscreen: { enabled: true, fallback: true, iosNative: true },
                        controls: [
                            'play-large',
                            'play',
                            'progress',
                            'current-time',
                            'duration',
                            'mute',
                            'volume',
                            'fullscreen'
                        ]
                    }
                } : undefined,
            });
        }
    }

    function toggleRatingSection(show) {
        const ratingSection = container.querySelector('.rating-section');
        if (ratingSection) {
            if (show) {
                ratingSection.classList.remove('hidden');
                ratingSection.classList.add('flex');
            } else {
                ratingSection.classList.remove('flex');
                ratingSection.classList.add('hidden');
            }
        }
    }

    function updateRatingAndStars(rating, stars) {

        if (stars) {
            const starsElement = container.querySelector('[data-reviews="stars"]');
            if (starsElement) {
                const starCount = parseInt(stars);
                const lastDigit = starCount % 10;
                const lastTwoDigits = starCount % 100;

                let ending;
                if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
                    ending = ' оценок';
                } else if (lastDigit == 1) {
                    ending = ' оценка';
                } else if (lastDigit >= 2 && lastDigit <= 4) {
                    ending = ' оценки';
                } else {
                    ending = ' оценок';
                }

                starsElement.textContent = starCount + ending;
            }
        }
    }

    function debounce(func, wait) {
        let timeout;
        return (...args) => {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), wait);
        };
    }


    initAllSwipers();


    const activeTab = container.querySelector('.tab-button.active');
    if (activeTab) {
        const tabId = activeTab.getAttribute('data-tab');
        initLightbox(tabId);
    }


    container.querySelectorAll('.tab-button').forEach(button => {
        button.addEventListener('click', debounce(() => {
            const tabId = button.getAttribute('data-tab');
            const rating = button.getAttribute('data-rating');
            const stars = button.getAttribute('data-stars');
            const isVideoTab = tabId === 'video';


            container.querySelectorAll('.tab-button').forEach(btn => {
                btn.classList.remove('active');
            });
            button.classList.add('active');


            toggleRatingSection(!isVideoTab);


            if (!isVideoTab) {
                updateRatingAndStars(rating, stars);
            }


            container.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('block');
                content.classList.add('hidden');
            });

            const targetTab = container.querySelector(`#tab-${tabId}`);
            targetTab.classList.remove('hidden');
            targetTab.classList.add('block');


            initLightbox(tabId);


            if (!isVideoTab && swipers[tabId]) {
                requestAnimationFrame(() => {
                    swipers[tabId].update();
                });
            }

        }, 100));
    });


    window.addEventListener('beforeunload', () => {
        Object.values(swipers).forEach(swiper => swiper?.destroy());
        if (lightbox) lightbox.destroy();
    });
}