---
import ReviewCard from '@components/reviews/ReviewCard.astro';

interface ReviewRecord {
  id: string;
  name: string;
  surname?: string;
  profession?: string;
  text: string;
  rating: number;
  votesCount: number;
  created: string;
}

const PB_POCKETBASE_URL = import.meta.env.PB_POCKETBASE_URL || import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090';

let reviews: ReviewRecord[] = [];

try {
  const filter = 'status = "published"';
  const response = await fetch(
    `${PB_POCKETBASE_URL}/api/collections/reviews/records?filter=${encodeURIComponent(filter)}&sort=-created&perPage=10`
  );

  if (response.ok) {
    const data = await response.json();
    reviews = data.items || [];
  }
} catch (e) {
  console.error('[ReviewsSlider] Error:', e);
}

const displayReviews = reviews.length >= 3 
    ? [...reviews, ...reviews, ...reviews] 
    : [...reviews, ...reviews];

const getInitial = (name: string) => name.charAt(0).toUpperCase();

const colors = ['bg-gradient-1', 'bg-gradient-2', 'bg-gradient-3', 'bg-gradient-4', 'bg-gradient-5', 'bg-gradient-6'];
---

<!-- КРИТИЧНО: Скрипт скрывает элементы ДО рендера -->
<script is:inline>
    (function() {
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

        const style = document.createElement('style');
        style.textContent = '.animate-on-scroll{opacity:0;transform:translateY(30px)}' +
            '[data-animation="scale-up"]{transform:translateY(40px) scale(0.95)}' +
            '[data-animation="fade-in"]{opacity:0;transform:none}';
        document.head.appendChild(style);
    })();
</script>

<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) => {
                        const fullName = `${review.name} ${review.surname || ''}`.trim();
                        const colorIndex = index % 6;
                        return (
                            <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={fullName}
                                    profession={review.profession || 'Клиент'}
                                    text={review.text}
                                    rating={review.rating}
                                    initial={getInitial(review.name)}
                                    color={colors[colorIndex]}
                                    date={review.created}
                                    reviewId={review.id}
                                    initialLikes={review.votesCount || 0}
                                />
                            </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;
    }

    .card-item {
        scroll-snap-align: center;
        display: flex;
    }

    #sliderContainer {
        scroll-snap-type: x mandatory;
    }

    .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%;
    }

    /* ИСПРАВЛЕНИЕ LCP: opacity: 1 по умолчанию */
    .animate-on-scroll {
        opacity: 1;
        transform: translateY(0) scale(1);
        will-change: opacity, transform;
    }

    [data-animation="fade-up"] {
        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"] {
        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 !important;
            transform: none !important;
            transition: none !important;
        }
    }
</style>

<script>
    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(() => {
                        requestAnimationFrame(() => {
                            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 nextBtn = document.getElementById('nextBtn');
        const prevBtn = document.getElementById('prevBtn');
        const cards = document.querySelectorAll('.card-item');

        if (!container || !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();
</script>