---
import type { SliderProps } from '@/types/globalInterfaces';

// Иконки стрелок
const ChevronLeft = `<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>`;
const ChevronRight = `<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"></polyline></svg>`;

const { slides = [] } = Astro.props as SliderProps;

// Фильтрация активных слайдов и сортировка по полю order
const activeSlides = slides
    .filter(slide => slide.is_active)
    .sort((a, b) => a.order - b.order);

// Если нет слайдов, используем заглушку
const displaySlides = activeSlides.length > 0 ? activeSlides : [
    {
        image: '/images/fleet/luxury_car01.avif',
        title: 'Unsere Premium-Flotte für Berlin',
        description: 'Luxus, Komfort und Sicherheit auf höchstem Niveau für Ihre Reisen in und um Berlin.',
    },
    {
        image: '/images/fleet/luxury_car02.avif',
        title: 'Exklusive Fahrzeuge für jeden Anlass',
        description: 'Entdecken Sie unsere sorgfältig ausgewählte Kollektion an Premium-Fahrzeugen für Ihr Event.',
    },
    {
        image: '/images/fleet/luxury_car03.avif',
        title: 'Perfekter Service von A bis Z',
        description: 'Erleben Sie unseren erstklassigen Chauffeur-Service von der Buchung bis zur Ankunft am Ziel.',
    }
];
---

<div class="slider-container relative h-[60vh] min-h-[400px] w-full overflow-hidden group" id="hero-slider">
    <!-- Slides -->
    {displaySlides.map((slide, index) => (
            <div class={`slide absolute inset-0 w-full h-full transition-opacity duration-1000 ease-in-out ${index === 0 ? 'opacity-100 z-10' : 'opacity-0 z-0'}`} data-index={index}>
                <img
                        src={`${import.meta.env.POCKETBASE_URL}/api/files/${slide.collectionId}/${slide.id}/${slide.image}`}
                        alt={slide.title}
                        width="1200"
                        height="600"
                        class="h-full w-full object-cover"
                />
                <div class="absolute inset-0 bg-gradient-to-b from-black/80 via-black/70 to-black/90"></div>

                <!-- Content -->
                <div class="absolute inset-0 flex flex-col items-center justify-center text-center text-white p-6">
                    <div class="bg-black/40 backdrop-blur-sm rounded-2xl p-8 max-w-3xl mx-auto content-wrapper transform transition-all duration-700 translate-y-10 opacity-0">
                        <h2 class="text-4xl md:text-6xl font-extrabold tracking-tight drop-shadow-xl">
                            {slide.title}
                        </h2>
                        <p class="mt-4 max-w-2xl mx-auto text-lg md:text-xl text-gray-100 drop-shadow-lg">
                            {slide.description}
                        </p>
                    </div>
                </div>
            </div>
    ))}

    <!-- Controls -->
    <button id="prev-slide" class="absolute left-4 top-1/2 z-20 -translate-y-1/2 p-2 rounded-full bg-white/10 hover:bg-white/30 text-white transition-all duration-300 ease-out hover:cursor-pointer hover:scale-110 active:scale-95" aria-label="Previous slide" set:html={ChevronLeft}></button>

    <button id="next-slide" class="absolute right-4 top-1/2 z-20 -translate-y-1/2 p-2 rounded-full bg-white/10 hover:bg-white/30 text-white transition-all duration-300 ease-out hover:cursor-pointer hover:scale-110 active:scale-95" aria-label="Next slide" set:html={ChevronRight}></button>

    <!-- Dots -->
    <div class="absolute bottom-6 left-1/2 z-20 flex -translate-x-1/2 space-x-2 bg-black/50 backdrop-blur-sm py-2 px-4 rounded-full">
        {displaySlides.map((_, index) => (
                <button
                        class={`dot h-2 w-2 rounded-full transition-all duration-300 ease-in-out hover:cursor-pointer ${index === 0 ? 'bg-white scale-125' : 'bg-white/50 hover:bg-white'}`}
                        data-index={index}
                        aria-label={`Go to slide ${index + 1}`}
                ></button>
        ))}
    </div>
</div>

<script>
    const container = document.getElementById('hero-slider');
    if (container) {
        const slides = container.querySelectorAll('.slide');
        const dots = container.querySelectorAll('.dot');
        const prevBtn = document.getElementById('prev-slide');
        const nextBtn = document.getElementById('next-slide');

        let currentIndex = 0;
        let intervalId;
        let isPaused = false;

        const updateSlide = (newIndex) => {
            // Hide current
            slides[currentIndex].classList.remove('opacity-100', 'z-10');
            slides[currentIndex].classList.add('opacity-0', 'z-0');
            slides[currentIndex].querySelector('.content-wrapper')?.classList.remove('opacity-100', 'translate-y-0');
            slides[currentIndex].querySelector('.content-wrapper')?.classList.add('opacity-0', 'translate-y-10');

            dots[currentIndex].classList.remove('bg-white', 'scale-125');
            dots[currentIndex].classList.add('bg-white/50');

            // Update index
            currentIndex = newIndex;

            // Show new
            slides[currentIndex].classList.remove('opacity-0', 'z-0');
            slides[currentIndex].classList.add('opacity-100', 'z-10');

            // Animate Content with delay
            setTimeout(() => {
                slides[currentIndex].querySelector('.content-wrapper')?.classList.remove('opacity-0', 'translate-y-10');
                slides[currentIndex].querySelector('.content-wrapper')?.classList.add('opacity-100', 'translate-y-0');
            }, 300);

            dots[currentIndex].classList.remove('bg-white/50');
            dots[currentIndex].classList.add('bg-white', 'scale-125');
        };

        const next = () => {
            updateSlide((currentIndex + 1) % slides.length);
        };

        const prev = () => {
            updateSlide((currentIndex - 1 + slides.length) % slides.length);
        };

        // Init first slide content
        setTimeout(() => {
            slides[0].querySelector('.content-wrapper')?.classList.remove('opacity-0', 'translate-y-10');
            slides[0].querySelector('.content-wrapper')?.classList.add('opacity-100', 'translate-y-0');
        }, 100);

        // Event Listeners
        nextBtn?.addEventListener('click', next);
        prevBtn?.addEventListener('click', prev);

        dots.forEach((dot, idx) => {
            dot.addEventListener('click', () => updateSlide(idx));
        });

        // Auto play
        const startTimer = () => {
            intervalId = window.setInterval(() => {
                if (!isPaused) next();
            }, 8000);
        };

        container.addEventListener('mouseenter', () => { isPaused = true; });
        container.addEventListener('mouseleave', () => { isPaused = false; });

        startTimer();
    }
</script>
