<section class="w-full py-16 sm:py-24 overflow-hidden" style="background-color: {{ trim($d['bg_color'] ?? '') ?: '#ffffff' }}">
    <div class="max-w-6xl mx-auto px-4 sm:px-6 min-w-0">
        @if(!empty($d['title']))
            <h2 class="text-2xl md:text-3xl font-bold text-slate-900 mb-12 text-center">{{ $d['title'] }}</h2>
        @endif
        @php $items = array_filter($d['items'] ?? [], fn($i) => !empty($i['image'])); @endphp
        @if(count($items) > 0)
        @php $carouselId = 'carousel-'.uniqid(); @endphp
        <div id="{{ $carouselId }}" class="carousel-section relative">
            <div class="carousel-track flex overflow-x-auto snap-x snap-mandatory gap-4 pb-4 scroll-smooth hide-scrollbar" style="scrollbar-width: none; -ms-overflow-style: none;">
                @foreach($items as $item)
                    @php $imgUrl = str_starts_with($item['image'], 'http') || str_starts_with($item['image'], '/') ? $item['image'] : asset('storage/'.$item['image']); @endphp
                    <div class="carousel-slide flex-shrink-0 w-[85%] min-w-[280px] max-w-md snap-center">
                        <figure class="aspect-[4/3] rounded-2xl overflow-hidden bg-slate-100 shadow-lg relative">
                            <img src="{{ $imgUrl }}" alt="{{ $item['title'] ?? '' }}" class="w-full h-full object-cover">
                            @if(!empty($item['title']) || !empty($item['caption']))
                                <figcaption class="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/70 to-transparent text-white">
                                    @if(!empty($item['title']))<strong class="block">{{ $item['title'] }}</strong>@endif
                                    @if(!empty($item['caption']))<span class="text-sm font-normal opacity-90 prose prose-invert prose-sm max-w-none">{!! \App\Support\SafeHtml::richText($item['caption']) !!}</span>@endif
                                </figcaption>
                            @endif
                        </figure>
                    </div>
                @endforeach
            </div>
            @if(count($items) > 1)
            <div class="flex justify-center items-center gap-4 mt-6">
                <button type="button" class="carousel-prev w-12 h-12 rounded-full bg-white border border-slate-200 shadow-md hover:bg-slate-50 flex items-center justify-center text-slate-600 transition shrink-0" aria-label="Précédent">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
                </button>
                <div class="flex justify-center gap-2">
                    @foreach($items as $i => $item)
                        <button type="button" class="carousel-dot w-2.5 h-2.5 rounded-full transition {{ $i === 0 ? 'bg-primary-500 scale-125' : 'bg-slate-300 hover:bg-slate-400' }}" data-index="{{ $i }}" aria-label="Diapositive {{ $i + 1 }}"></button>
                    @endforeach
                </div>
                <button type="button" class="carousel-next w-12 h-12 rounded-full bg-white border border-slate-200 shadow-md hover:bg-slate-50 flex items-center justify-center text-slate-600 transition shrink-0" aria-label="Suivant">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
                </button>
            </div>
            @endif
        </div>
        <style>
            .carousel-section .hide-scrollbar::-webkit-scrollbar { display: none; }
            .carousel-section figure { position: relative; }
        </style>
        @if(count($items) > 1)
        <script>
        (function() {
            const section = document.getElementById('{{ $carouselId }}');
            if (!section) return;

            const track = section.querySelector('.carousel-track');
            const slides = Array.from(section.querySelectorAll('.carousel-slide'));
            const prev = section.querySelector('.carousel-prev');
            const next = section.querySelector('.carousel-next');
            const dots = Array.from(section.querySelectorAll('.carousel-dot'));
            const slideCount = slides.length;
            const AUTOPLAY_INTERVAL = 5000;
            let currentIndex = 0;
            let autoplayTimer = null;
            let scrollEndTimer = null;

            if (!track || slideCount <= 1) return;

            function updateDots() {
                dots.forEach((d, i) => {
                    d.classList.toggle('bg-primary-500', i === currentIndex);
                    d.classList.toggle('scale-125', i === currentIndex);
                    d.classList.toggle('bg-slate-300', i !== currentIndex);
                });
            }

            function scrollToIndex(index, smooth = true) {
                currentIndex = ((index % slideCount) + slideCount) % slideCount;
                const target = slides[currentIndex];
                if (target && track) {
                    const slideLeft = target.offsetLeft;
                    const slideWidth = target.offsetWidth;
                    const trackWidth = track.offsetWidth;
                    const scrollPos = slideLeft - (trackWidth / 2) + (slideWidth / 2);
                    track.scrollTo({ left: scrollPos, behavior: smooth ? 'smooth' : 'auto' });
                }
                updateDots();
            }

            function stopAutoplay() {
                if (autoplayTimer) {
                    clearInterval(autoplayTimer);
                    autoplayTimer = null;
                }
            }

            function startAutoplay() {
                stopAutoplay();
                autoplayTimer = setInterval(() => {
                    scrollToIndex(currentIndex + 1);
                }, AUTOPLAY_INTERVAL);
            }

            function resetAutoplay() {
                startAutoplay();
            }

            prev?.addEventListener('click', () => {
                scrollToIndex(currentIndex - 1);
                resetAutoplay();
            });

            next?.addEventListener('click', () => {
                scrollToIndex(currentIndex + 1);
                resetAutoplay();
            });

            dots.forEach((d, i) => {
                d.addEventListener('click', () => {
                    scrollToIndex(i);
                    resetAutoplay();
                });
            });

            track.addEventListener('scroll', () => {
                clearTimeout(scrollEndTimer);
                scrollEndTimer = setTimeout(() => {
                    let closest = 0;
                    let minDistance = Infinity;
                    const trackRect = track.getBoundingClientRect();
                    const trackCenter = trackRect.left + (trackRect.width / 2);

                    slides.forEach((slide, idx) => {
                        const rect = slide.getBoundingClientRect();
                        const slideCenter = rect.left + (rect.width / 2);
                        const distance = Math.abs(slideCenter - trackCenter);
                        if (distance < minDistance) {
                            minDistance = distance;
                            closest = idx;
                        }
                    });

                    if (closest !== currentIndex) {
                        currentIndex = closest;
                        updateDots();
                        resetAutoplay();
                    }
                }, 120);
            });

            section.addEventListener('mouseenter', stopAutoplay);
            section.addEventListener('mouseleave', startAutoplay);

            scrollToIndex(0, false);
            startAutoplay();
        })();
        </script>
        @endif
        @else
            <p class="text-center text-slate-500 py-12">Aucune image dans le carrousel.</p>
        @endif
    </div>
</section>
