import { useState, useEffect } from 'react';

/**
 * Debounces a rapidly-changing value.
 *
 * Returns a stable copy of `value` that only updates once `delay` milliseconds
 * have elapsed since the last change. Useful for search inputs, filter fields,
 * and any scenario where you want to avoid triggering expensive operations on
 * every keystroke.
 *
 * @example
 * ```tsx
 * const [query, setQuery] = useState('');
 * const debouncedQuery = useDebounce(query, 300);
 *
 * useEffect(() => {
 *   // Only fires 300 ms after the user stops typing
 *   fetchResults(debouncedQuery);
 * }, [debouncedQuery]);
 * ```
 */
export function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(timer);
    };
  }, [value, delay]);

  return debouncedValue;
}
