import { throttle } from '../../utils.mjs';
import { useState, useEffect, useRef, useMemo } from 'react';

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    const timer = setTimeout(() => setDebouncedValue(value), delay || 500);
    return () => {
      clearTimeout(timer);
    };
  }, [value, delay]);
  return debouncedValue;
}
function useThrottle(value, wait) {
  const [throttledValue, setThrottledValue] = useState(value);
  const valueRef = useRef(value);
  valueRef.current = value;
  const throttledSetter = useMemo(() => {
    return throttle((next) => {
      setThrottledValue(next);
    }, wait ?? 500);
  }, [wait]);
  useEffect(() => {
    throttledSetter(valueRef.current);
    return () => {
      throttledSetter.cancel();
    };
  }, [throttledSetter]);
  useEffect(() => {
    throttledSetter(value);
  }, [value, throttledSetter]);
  return throttledValue;
}

export { useDebounce, useThrottle };
