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

export const useShortcutCooldown = (
  onShortcutCast: (index: number) => void
) => {
  const [shortcutCooldown, setShortcutCooldown] = useState(0);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const clearCooldownInterval = useCallback(() => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
  }, []);

  const handleShortcutCast = useCallback(
    (index: number) => {
      if (shortcutCooldown <= 0) {
        setShortcutCooldown(1.5);
      }
      onShortcutCast(index);
    },
    [shortcutCooldown, onShortcutCast]
  );

  useEffect(() => {
    if (shortcutCooldown > 0 && !intervalRef.current) {
      intervalRef.current = setInterval(() => {
        setShortcutCooldown(prev => {
          const next = prev - 0.1;
          if (next <= 0) {
            clearCooldownInterval();
            return 0;
          }
          return next;
        });
      }, 100);
    }

    return () => {
      clearCooldownInterval();
    };
  }, [shortcutCooldown > 0, clearCooldownInterval]);

  return { shortcutCooldown, handleShortcutCast };
};
