'use client'

import { useState } from 'react'
import Image from 'next/image'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import type { HeroBanner } from '@/lib/db/queries/getHeroBanners'

interface HeroCarouselProps {
  images: HeroBanner[]
  labels: {
    previous: string
    next: string
    // Pre-rendered per-image, not a function — functions can't cross the
    // Server -> Client Component boundary (not serializable as RSC props).
    goTo: string[]
  }
}

// Client-only for the interactive bits (slide index, prev/next, dots) —
// the images themselves are rendered server-side by HeroSection so the
// first (LCP) image is in the initial HTML instead of waiting on a client
// mount + fetch.
export default function HeroCarousel({ images, labels }: HeroCarouselProps) {
  const [currentImage, setCurrentImage] = useState(0)

  if (images.length === 0) return null

  const nextImage = () => setCurrentImage((prev) => (prev + 1) % images.length)
  const prevImage = () => setCurrentImage((prev) => (prev - 1 + images.length) % images.length)

  return (
    <div className="relative group">
      <div className="relative w-full h-80 md:h-96 lg:h-100">
        <Image
          src={images[currentImage].imageUrl}
          alt={images[currentImage].alt}
          fill
          sizes="(max-width: 1024px) 100vw, 50vw"
          className="rounded-2xl shadow-lg transition-transform duration-500 object-cover"
          priority
        />
      </div>

      {images.length > 1 && (
        <>
          <button
            onClick={prevImage}
            className="absolute left-2 top-1/2 -translate-y-1/2 bg-white/80 hover:bg-white rounded-full p-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300"
            aria-label={labels.previous}
          >
            <ChevronLeft size={20} />
          </button>
          <button
            onClick={nextImage}
            className="absolute right-2 top-1/2 -translate-y-1/2 bg-white/80 hover:bg-white rounded-full p-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300"
            aria-label={labels.next}
          >
            <ChevronRight size={20} />
          </button>

          <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2">
            {images.map((image, index) => (
              <button
                key={image.id}
                onClick={() => setCurrentImage(index)}
                className={`w-2 h-2 rounded-full transition-all duration-300 ${
                  currentImage === index
                    ? 'bg-primary w-4'
                    : 'bg-white/50 hover:bg-white/80'
                }`}
                aria-label={labels.goTo[index]}
              />
            ))}
          </div>
        </>
      )}
    </div>
  )
}
