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

export function useExitTransition(onExit, duration = 260) {
  const [exiting, setExiting] = useState(false);
  const actionRef = useRef(onExit);
  const timerRef = useRef(null);
  actionRef.current = onExit;

  const startExit = useCallback((afterExit) => {
    if (timerRef.current) return;
    const reducedMotion = globalThis.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;
    if (reducedMotion) {
      actionRef.current();
      afterExit?.();
      return;
    }
    setExiting(true);
    timerRef.current = setTimeout(() => {
      timerRef.current = null;
      setExiting(false);
      actionRef.current();
      afterExit?.();
    }, duration);
  }, [duration]);

  useEffect(() => () => clearTimeout(timerRef.current), []);
  return { exiting, startExit };
}
