"use client";

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

type Slide = { src: string; alt: string };

const INTERVAL_MS = 5000;

/**
 * Full-width hero: photos cross-fade in the background while the title and
 * buttons (children) stay in front. Pauses for users who prefer reduced motion.
 */
export function HeroSlider({ slides, children }: { slides: Slide[]; children: React.ReactNode }) {
  const [index, setIndex] = useState(0);
  const [paused, setPaused] = useState(false);

  useEffect(() => {
    if (paused || slides.length < 2) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const t = setInterval(() => setIndex((i) => (i + 1) % slides.length), INTERVAL_MS);
    return () => clearInterval(t);
  }, [paused, slides.length]);

  return (
    <section
      className="hero-slider"
      aria-roledescription="carousel"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      {slides.map((s, i) => (
        <div key={s.src} className={`hero-slide${i === index ? " is-active" : ""}`} aria-hidden={i !== index}>
          <Image src={s.src} alt={s.alt} fill sizes="100vw" priority={i === 0} />
        </div>
      ))}
      <div className="hero-overlay" aria-hidden="true" />
      <div className="hero-content">{children}</div>
      {slides.length > 1 && (
        <div className="hero-dots">
          {slides.map((s, i) => (
            <button
              key={s.src}
              type="button"
              className={i === index ? "is-active" : ""}
              aria-label={`Show photo ${i + 1} of ${slides.length}`}
              aria-current={i === index}
              onClick={() => setIndex(i)}
            />
          ))}
        </div>
      )}
    </section>
  );
}
