import { useEffect, useState } from "react";
import useEmblaCarousel from "embla-carousel-react";
import type { HeroCarouselBlock } from "@/types/sections";
import { useLocale } from "@/i18n/LocaleContext";
import { cn } from "@/lib/utils";

export function HeroCarousel({ block }: { block: HeroCarouselBlock }) {
  const { t } = useLocale();
  const [emblaRef, emblaApi] = useEmblaCarousel({ loop: true, align: "start" });
  const [selected, setSelected] = useState(0);

  useEffect(() => {
    if (!emblaApi) return;
    const onSelect = () => setSelected(emblaApi.selectedScrollSnap());
    emblaApi.on("select", onSelect);
    onSelect();
    return () => {
      emblaApi.off("select", onSelect);
    };
  }, [emblaApi]);

  useEffect(() => {
    if (!emblaApi || !block.autoplayMs) return;
    const id = window.setInterval(() => {
      emblaApi.scrollNext();
    }, block.autoplayMs);
    return () => window.clearInterval(id);
  }, [emblaApi, block.autoplayMs]);

  return (
    <section aria-roledescription="carousel" className="relative bg-bar">
      <div className="overflow-hidden" ref={emblaRef}>
        <div className="flex">
          {block.slides.map((slide, idx) => (
            <div
              key={idx}
              role="group"
              aria-roledescription="slide"
              aria-label={`${idx + 1} / ${block.slides.length}`}
              className="relative min-w-0 flex-[0_0_100%]"
            >
              <div className="relative aspect-[21/9] w-full sm:aspect-[21/8] md:aspect-[21/7]">
                <img
                  src={slide.image.src}
                  alt={t(slide.image.alt)}
                  className="absolute inset-0 h-full w-full object-cover"
                  loading={idx === 0 ? "eager" : "lazy"}
                  fetchPriority={idx === 0 ? "high" : undefined}
                />
                <div className="absolute inset-0 bg-gradient-to-t from-bar/70 via-bar/20 to-transparent" />
                {(slide.eyebrow || slide.title || slide.subtitle) && (
                  <div className="absolute inset-0 flex items-end">
                    <div className="container pb-12 sm:pb-16 md:pb-20 text-bar-foreground animate-fade-in">
                      {slide.eyebrow && (
                        <p className="text-xs sm:text-sm uppercase tracking-[0.2em] text-bar-foreground/80 mb-3">
                          {t(slide.eyebrow)}
                        </p>
                      )}
                      {slide.title && (
                        <h2 className="font-display italic text-4xl sm:text-5xl md:text-6xl lg:text-7xl text-balance">
                          {t(slide.title)}
                        </h2>
                      )}
                      {slide.subtitle && (
                        <p className="mt-3 max-w-2xl text-base sm:text-lg md:text-xl text-bar-foreground/90">
                          {t(slide.subtitle)}
                        </p>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Dots */}
      <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2">
        {block.slides.map((_, i) => (
          <button
            key={i}
            type="button"
            aria-label={`Slide ${i + 1}`}
            aria-current={selected === i}
            onClick={() => emblaApi?.scrollTo(i)}
            className={cn(
              "h-2 w-2 rounded-full transition-all",
              selected === i
                ? "bg-bar-foreground w-6"
                : "bg-bar-foreground/40 hover:bg-bar-foreground/70",
            )}
          />
        ))}
      </div>
    </section>
  );
}