import { useState, useEffect } from "react";

/**
 * Debounce a value — useful for search inputs that trigger API calls.
 *
 * @param value  The raw value to debounce.
 * @param delay  Delay in milliseconds (default 300ms).
 * @returns      The debounced value that updates only after `delay` ms of inactivity.
 *
 * @example
 * const [search, setSearch] = useState("");
 * const debouncedSearch = useDebounce(search, 300);
 * // use `debouncedSearch` in a TanStack Query key
 */
export function useDebounce<T>(value: T, delay = 300): T {
  const [debounced, setDebounced] = useState(value);

  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);

  return debounced;
}
