"use client";
import Image from "next/image";
import { useEffect, useState } from "react";

const slides = [
  { src: "/content/images/1.png", alt: "Powerlifting highlight 1" },
  { src: "/content/images/2.png", alt: "Powerlifting highlight 2" },
  { src: "/content/images/3.png", alt: "Powerlifting highlight 3" },
];

export function ImageCarousel() {
  const [index, setIndex] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setIndex((prev) => (prev + 1) % slides.length);
    }, 5000);
    return () => clearInterval(id);
  }, []);

  const goTo = (i: number) => setIndex(i % slides.length);
  const prev = () => setIndex((prev) => (prev - 1 + slides.length) % slides.length);
  const next = () => setIndex((prev) => (prev + 1) % slides.length);

  return (
    <section aria-label="Destaques" className="carousel" role="region">
      <div className="carousel-viewport" aria-live="polite">
        {slides.map((slide, i) => (
          <div
            key={slide.src}
            className={`carousel-slide ${i === index ? "active" : ""}`}
            aria-hidden={i !== index ? "true" : "false"}
          >
            <Image
              src={slide.src}
              alt={slide.alt}
              fill
              className="object-cover"
              sizes="(max-width: 768px) 100vw, 1200px"
              priority={i === 0}
              unoptimized
            />
          </div>
        ))}
      </div>
      <div className="carousel-controls">
        <button type="button" onClick={prev} aria-label="Imagem anterior" className="carousel-btn">‹</button>
        <div className="carousel-dots" role="tablist" aria-label="Selecionar imagem do carrossel">
          {slides.map((_, i) => (
            <button
              key={i}
              type="button"
              role="tab"
              aria-selected={i === index ? "true" : "false"}
              aria-label={`Ir para imagem ${i + 1}`}
              className={`carousel-dot ${i === index ? "active" : ""}`}
              onClick={() => goTo(i)}
            />
          ))}
        </div>
        <button type="button" onClick={next} aria-label="Próxima imagem" className="carousel-btn">›</button>
      </div>
    </section>
  );
}
