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

export const useShortcutCooldown = (
  onShortcutCast: (index: number) => void
) => {
  const [shortcutCooldown, setShortcutCooldown] = useState(0);
  const cooldownTimeout = useRef<NodeJS.Timeout | null>(null);

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

  useEffect(() => {
    if (cooldownTimeout.current) clearTimeout(cooldownTimeout.current);

    if (shortcutCooldown > 0) {
      cooldownTimeout.current = setTimeout(() => {
        setShortcutCooldown(shortcutCooldown - 0.1);
      }, 100);
    }
  }, [shortcutCooldown]);

  return { shortcutCooldown, handleShortcutCast };
};
