"use client";

import { useState, useEffect, useRef, useCallback } from "react";

interface UseShowcaseRotationOptions {
  totalItems: number;
  autoPlayInterval?: number;
  pauseDuration?: number;
}

export function useShowcaseRotation({
  totalItems,
  autoPlayInterval = 4000,
  pauseDuration = 10000,
}: UseShowcaseRotationOptions) {
  const [activeIndex, setActiveIndex] = useState(0);
  const pausedUntil = useRef(0);
  const hoveringRef = useRef(false);

  const select = useCallback(
    (index: number) => {
      setActiveIndex(index);
      pausedUntil.current = Date.now() + pauseDuration;
    },
    [pauseDuration],
  );

  const setHovering = useCallback((hovering: boolean) => {
    hoveringRef.current = hovering;
  }, []);

  useEffect(() => {
    if (totalItems <= 1) return;

    const id = setInterval(() => {
      if (hoveringRef.current) return;
      if (Date.now() < pausedUntil.current) return;
      setActiveIndex((prev) => (prev + 1) % totalItems);
    }, autoPlayInterval);

    return () => clearInterval(id);
  }, [totalItems, autoPlayInterval]);

  return { activeIndex, select, setHovering };
}
