import { useRef, useEffect } from 'react';

export function useDebounce<T extends (...args: any[]) => void>(callback: T, delay = 300) {
  const timer = useRef<NodeJS.Timeout | null>(null);

  const debounced = (...args: Parameters<T>) => {
    if (timer.current) clearTimeout(timer.current);
    timer.current = setTimeout(() => callback(...args), delay);
  };

  useEffect(
    () => () => {
      if (timer.current) clearTimeout(timer.current);
    },
    []
  );

  return debounced as T;
}

export function useThrottle<T extends (...args: any[]) => void>(callback: T, limit = 300) {
  const waiting = useRef(false);

  const throttled = (...args: Parameters<T>) => {
    if (!waiting.current) {
      callback(...args);
      waiting.current = true;
      setTimeout(() => {
        waiting.current = false;
      }, limit);
    }
  };

  return throttled as T;
}
