"use client";

import { useEffect, useState } from "react";

type RotatingWordProps = {
  items: string[];
  intervalSeconds?: number;
};

export default function RotatingWord({
  items,
  intervalSeconds = 2.5,
}: RotatingWordProps) {
  const [activeIndex, setActiveIndex] = useState(0);

  useEffect(() => {
    if (items.length <= 1) return;
    const id = setInterval(() => {
      setActiveIndex((i) => (i + 1) % items.length);
    }, intervalSeconds * 1000);
    return () => clearInterval(id);
  }, [items.length, intervalSeconds]);

  return (
    <span className="relative inline-block align-baseline">
      {items.map((word, i) => (
        <span
          key={word}
          aria-hidden={i !== activeIndex}
          className={`transition-all ease-out ${
            i === activeIndex
              ? "opacity-100 translate-y-0 scale-100 duration-1200"
              : "absolute top-0 left-0 opacity-0 pointer-events-none duration-0"
          }`}
        >
          {word}
        </span>
      ))}
    </span>
  );
}
