'use client';

import { useEffect, useState } from 'react';
import { useReducedMotion } from 'framer-motion';

/**
 * Shows one hero image at a time, crossfading to the next every few seconds.
 *
 * Replaces a continuous horizontal marquee, which never let any single image be
 * looked at — everything was always mid-slide, and the duplicated track meant
 * each picture was on screen twice at once.
 *
 * The images are stacked and toggled by opacity rather than swapped in and out,
 * so the browser keeps all of them decoded and a transition never lands on an
 * unpainted frame.
 */
export function HeroSlideshow({
  images,
  imageClassName = 'h-full w-full object-cover',
  interval = 3000,
}: {
  images: string[];
  imageClassName?: string;
  interval?: number;
}) {
  const [current, setCurrent] = useState(0);
  const reduce = useReducedMotion();

  useEffect(() => {
    // Nothing to cycle through, or the visitor has asked motion to stop: hold
    // on the first frame rather than running a timer that changes the view
    // underneath them.
    if (images.length < 2 || reduce) return;

    const id = setInterval(
      () => setCurrent((i) => (i + 1) % images.length),
      interval,
    );
    return () => clearInterval(id);
  }, [images.length, interval, reduce]);

  return (
    <div className="absolute inset-0">
      {images.map((src, i) => (
        // eslint-disable-next-line @next/next/no-img-element
        <img
          key={src}
          src={src}
          alt=""
          aria-hidden="true"
          className={`absolute inset-0 transition-opacity duration-1000 ease-in-out ${imageClassName} ${
            i === current ? 'opacity-100' : 'opacity-0'
          }`}
        />
      ))}
    </div>
  );
}
