"use client";

import Image from "next/image";
import { useEffect, useMemo, useState } from "react";
import type { HomepageHeroSlide, Locale } from "@/types/content";
import { getImageAlt, getImageUrl } from "@/lib/images";

type HomeHeroSliderProps = {
  locale: Locale;
  slides: HomepageHeroSlide[];
};

const slideIntervalMs = 8000;

export function HomeHeroSlider({ locale, slides }: HomeHeroSliderProps) {
  const usableSlides = useMemo(() => slides.filter((slide) => slide.title?.[locale]), [locale, slides]);
  const [activeIndex, setActiveIndex] = useState(0);
  const activeSlide = usableSlides[activeIndex] ?? usableSlides[0];
  const hasMultipleSlides = usableSlides.length > 1;

  useEffect(() => {
    if (!hasMultipleSlides) return;
    const timer = window.setInterval(() => {
      setActiveIndex((current) => (current + 1) % usableSlides.length);
    }, slideIntervalMs);
    return () => window.clearInterval(timer);
  }, [hasMultipleSlides, usableSlides.length]);

  if (!activeSlide) return null;

  const goToSlide = (index: number) => setActiveIndex((index + usableSlides.length) % usableSlides.length);

  return (
    <section className="hero hero-promo" aria-label={activeSlide.title[locale]}>
      <div className="hero-promo-track" aria-hidden="true">
        {usableSlides.map((slide, index) => (
          <HeroPromoMedia key={slide._key ?? `${slide.title.en}-${index}`} slide={slide} active={index === activeIndex} priority={index === 0} />
        ))}
      </div>
      <div className="container hero-grid">
        <div className="hero-promo-copy">
          <h1>{activeSlide.title[locale]}</h1>
          {activeSlide.body?.[locale] ? <p className="hero-copy">{activeSlide.body[locale]}</p> : null}
        </div>
      </div>
      {hasMultipleSlides ? (
        <>
          <button className="hero-slide-arrow hero-slide-prev" type="button" aria-label="Previous promo slide" onClick={() => goToSlide(activeIndex - 1)}>
            <span aria-hidden="true">‹</span>
          </button>
          <button className="hero-slide-arrow hero-slide-next" type="button" aria-label="Next promo slide" onClick={() => goToSlide(activeIndex + 1)}>
            <span aria-hidden="true">›</span>
          </button>
          <div className="hero-slide-dots" role="tablist" aria-label="Homepage promo slides">
            {usableSlides.map((slide, index) => (
              <button
                key={slide._key ?? `${slide.title.en}-dot-${index}`}
                type="button"
                className={index === activeIndex ? "active" : ""}
                aria-label={`Show slide ${index + 1}: ${slide.title[locale]}`}
                aria-current={index === activeIndex ? "true" : undefined}
                onClick={() => goToSlide(index)}
              />
            ))}
          </div>
        </>
      ) : null}
    </section>
  );
}

function HeroPromoMedia({ slide, active, priority }: { slide: HomepageHeroSlide; active: boolean; priority: boolean }) {
  const imageUrl = getImageUrl(slide.image);
  const videoUrl = slide.video?.url;

  return (
    <div className={`hero-promo-media ${active ? "active" : ""}`}>
      {slide.mediaType === "video" && videoUrl ? (
        <video src={videoUrl} autoPlay={active} loop muted playsInline preload={active ? "auto" : "metadata"} tabIndex={-1} />
      ) : imageUrl ? (
        <Image src={imageUrl} alt={getImageAlt(slide.image, slide.title.en)} fill priority={priority} quality={82} sizes="100vw" />
      ) : null}
    </div>
  );
}
