---
import { reviewsData } from '@data/reviewsData';
import ReviewCard from '@components/reviews/ReviewCard.astro';

// Берём 6 последних отзывов (сортируем по дате, берём последние)
const latestReviews = [...reviewsData]
    .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
    .slice(0, 6);

// Для эффекта бесконечности клонируем элементы (один набор в начало, один в конец)
const displayReviews = [...latestReviews, ...latestReviews, ...latestReviews];
---

<section class="reviews-section py-16 bg-[#ffffff] overflow-hidden">
    <div class="site-container">
        <div class="section-header">
            <span class="subtitle animate-on-scroll" data-animation="fade-up">Отзывы клиентов</span>
            <h2 class="title animate-on-scroll" data-animation="fade-up" data-delay="100">Реальные истории водителей из Сургута</h2>
        </div>
    </div>

    <div class="slider-wrapper">
        <div class="relative max-w-6xl mx-auto px-4 group">
            <!-- Кнопка Назад -->
            <button id="prevBtn" class="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-2 md:-translate-x-10 z-10 bg-white w-12 h-12 rounded-full shadow-lg flex items-center justify-center text-slate-400 hover:text-blue-600 transition-all border border-slate-100 active:scale-95 hover:cursor-pointer animate-on-scroll" data-animation="fade-in" data-delay="200">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" /></svg>
            </button>

            <!-- Окно просмотра -->
            <div id="sliderContainer" class="overflow-x-hidden scroll-smooth">
                <div id="sliderTrack" class="flex gap-6 py-4 items-stretch">
                    {displayReviews.map((review, index) => (
                            <div
                                    class="card-item min-w-full md:min-w-[calc(33.333%-1rem)] select-none animate-on-scroll"
                                    data-animation="scale-up"
                                    data-delay={index * 100 + 300}
                            >
                                <ReviewCard
                                        name={review.name}
                                        car={review.car}
                                        text={review.text}
                                        rating={review.rating}
                                        initial={review.initial}
                                        color={review.color}
                                        date={review.date}
                                        votesCount={review.votesCount || 0}
                                        isHelpful={review.isHelpful || false}
                                />
                            </div>
                    ))}
                </div>
            </div>

            <!-- Кнопка Вперед -->
            <button id="nextBtn" class="absolute right-0 top-1/2 -translate-y-1/2 translate-x-2 md:translate-x-10 z-10 bg-white w-12 h-12 rounded-full shadow-lg flex items-center justify-center text-slate-400 hover:text-blue-600 transition-all border border-slate-100 active:scale-95 hover:cursor-pointer animate-on-scroll" data-animation="fade-in" data-delay="200">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" /></svg>
            </button>
        </div>
    </div>
</section>

<style>
    /* Скрываем скроллбар */
    #sliderContainer {
        -ms-overflow-style: none;
        scrollbar-width: none;
    }
    #sliderContainer::-webkit-scrollbar {
        display: none;
    }

    /* Карточка в слайдере — полностью сохраняет оригинальный дизайн ReviewCard */
    .card-item {
        scroll-snap-align: center;
        display: flex;
    }

    /* Центрирование карточки на мобильном */
    #sliderContainer {
        scroll-snap-type: x mandatory;
    }

    #sliderTrack {
        scroll-snap-align: center;
    }

    /* Убедимся, что карточка растягивается на всю ширину слайда */
    .card-item :global(.review-card) {
        width: 100%;
        margin: 0;
    }

    /* Уменьшаем имя для слайдера — влезает в одну строку */
    .card-item :global(.author-name) {
        font-size: 0.9rem;
    }

    /* Заголовок секции */
    .section-header {
        margin-bottom: 4rem;
        text-align: center;
    }

    .subtitle {
        display: inline-block;
        color: #d4af37;
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 3px;
        margin-bottom: 1rem;
        padding: 0.5rem 1rem;
        background: rgba(212, 175, 55, 0.1);
        border-radius: 6px;
    }

    .title {
        color: #1e293b;
        font-size: clamp(2rem, 4vw, 3rem);
        font-weight: 800;
        margin: 0;
        line-height: 1.2;
        letter-spacing: -0.02em;
    }

    .slider-wrapper {
        width: 100%;
    }

    /* Анимации при скроллинге */
    .animate-on-scroll {
        opacity: 0;
        will-change: opacity, transform;
    }

    [data-animation="fade-up"] {
        transform: translateY(30px);
        transition: opacity 0.8s cubic-bezier(0.4, 0, 0.2, 1),
        transform 0.8s cubic-bezier(0.4, 0, 0.2, 1);
    }

    [data-animation="fade-in"] {
        transition: opacity 0.6s cubic-bezier(0.4, 0, 0.2, 1);
    }

    [data-animation="scale-up"] {
        transform: translateY(40px) scale(0.95);
        transition: opacity 0.7s cubic-bezier(0.4, 0, 0.2, 1),
        transform 0.7s cubic-bezier(0.4, 0, 0.2, 1);
    }

    .animate-on-scroll.is-visible {
        opacity: 1;
        transform: translateY(0) scale(1);
    }

    @media (prefers-reduced-motion: reduce) {
        .animate-on-scroll {
            opacity: 1;
            transform: none;
            transition: none;
        }
    }
</style>

<script>
    // Intersection Observer для анимаций
    const setupAnimations = () => {
        const observerOptions = {
            root: null,
            rootMargin: '0px 0px -50px 0px',
            threshold: 0.1
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const el = entry.target as HTMLElement;
                    const delay = parseInt(el.dataset.delay || '0');

                    setTimeout(() => {
                        el.classList.add('is-visible');
                    }, delay);

                    observer.unobserve(el);
                }
            });
        }, observerOptions);

        document.querySelectorAll('.animate-on-scroll').forEach((el) => {
            observer.observe(el);
        });
    };

    const setupSlider = () => {
        const container = document.getElementById('sliderContainer');
        const track = document.getElementById('sliderTrack');
        const nextBtn = document.getElementById('nextBtn');
        const prevBtn = document.getElementById('prevBtn');
        const cards = document.querySelectorAll('.card-item');

        if (!container || !track || !nextBtn || !prevBtn || cards.length === 0) return;

        const totalOriginal = cards.length / 3;
        const firstCard = cards[0] as HTMLElement;
        let cardWidth = firstCard.offsetWidth + 24;

        const initialScroll = cardWidth * totalOriginal;
        container.scrollLeft = initialScroll;

        const handleNext = () => {
            container.scrollLeft += cardWidth;
        };

        const handlePrev = () => {
            container.scrollLeft -= cardWidth;
        };

        container.addEventListener('scroll', () => {
            const scrollPos = container.scrollLeft;
            const maxScroll = container.scrollWidth - container.clientWidth;

            if (scrollPos >= maxScroll - 5) {
                container.style.scrollBehavior = 'auto';
                container.scrollLeft = initialScroll;
                container.style.scrollBehavior = 'smooth';
            }

            if (scrollPos <= 5) {
                container.style.scrollBehavior = 'auto';
                container.scrollLeft = initialScroll;
                container.style.scrollBehavior = 'smooth';
            }
        });

        nextBtn.addEventListener('click', handleNext);
        prevBtn.addEventListener('click', handlePrev);

        window.addEventListener('resize', () => {
            const firstCard = cards[0] as HTMLElement;
            if (firstCard) {
                cardWidth = firstCard.offsetWidth + 24;
            }
        });
    };

    setupSlider();
    setupAnimations();

    document.addEventListener('astro:after-swap', () => {
        setupSlider();
        setupAnimations();
    });
</script>