import { useState, useCallback, useEffect } from "react"

// Carga automática de todas las imágenes de src/assets/img (orden alfabético por nombre de archivo)
const modules = import.meta.glob("../assets/img/*.{jpg,jpeg,png,webp}", { eager: true, import: "default" })
const IMAGES = Object.entries(modules)
  .sort(([a], [b]) => a.localeCompare(b))
  .map(([, url]) => url)

export default function Carrusel() {
  const [i, setI] = useState(0)
  const total = IMAGES.length

  const ir = useCallback((dir) => {
    setI((prev) => (prev + dir + total) % total)
  }, [total])

  // Navegación con teclado ← →
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "ArrowLeft") ir(-1)
      if (e.key === "ArrowRight") ir(1)
    }
    window.addEventListener("keydown", onKey)
    return () => window.removeEventListener("keydown", onKey)
  }, [ir])

  if (total === 0) return null

  return (
    <div className="relative mx-auto max-w-3xl">
      {/* Marco degradado estilo tarjeta */}
      <div className="rounded-[2rem] bg-gradient-to-br from-brand-400 to-azul-400 p-2 shadow-xl">
        <div className="relative overflow-hidden rounded-[1.5rem] bg-white">
          <img
            src={IMAGES[i]}
            alt={`Foto ${i + 1} de ${total} — Fundación Terapeandog`}
            className="aspect-video w-full object-cover"
            loading="lazy"
          />

          {/* Botón retroceder */}
          <button
            onClick={() => ir(-1)}
            aria-label="Anterior"
            className="absolute left-3 top-1/2 -translate-y-1/2 grid h-11 w-11 place-items-center rounded-full bg-white/90 text-brand-700 shadow-md hover:bg-white hover:text-brand-600 transition-colors"
          >
            <span className="text-2xl leading-none">‹</span>
          </button>

          {/* Botón avanzar */}
          <button
            onClick={() => ir(1)}
            aria-label="Siguiente"
            className="absolute right-3 top-1/2 -translate-y-1/2 grid h-11 w-11 place-items-center rounded-full bg-white/90 text-brand-700 shadow-md hover:bg-white hover:text-brand-600 transition-colors"
          >
            <span className="text-2xl leading-none">›</span>
          </button>

          {/* Contador */}
          <div className="absolute bottom-3 right-3 rounded-full bg-brand-900/70 px-3 py-1 text-xs font-medium text-white">
            {i + 1} / {total}
          </div>
        </div>
      </div>

      {/* Puntos indicadores */}
      <div className="mt-5 flex flex-wrap justify-center gap-2">
        {IMAGES.map((_, idx) => (
          <button
            key={idx}
            onClick={() => setI(idx)}
            aria-label={`Ir a la foto ${idx + 1}`}
            className={`h-2.5 rounded-full transition-all ${idx === i ? "w-6 bg-brand-600" : "w-2.5 bg-brand-200 hover:bg-brand-400"}`}
          />
        ))}
      </div>
    </div>
  )
}
