"use client";

import { useEffect, useState } from "react";

/** The delay every search box in the app had settled on independently. */
export const DEFAULT_DEBOUNCE_MS = 500;

/**
 * A value that follows `value` after it has stopped changing.
 *
 * Every list screen with a search box had written this out itself — eighteen
 * copies of the same six lines, each holding its own `debouncedSearch` state and
 * its own `setTimeout`/`clearTimeout` effect. They are one hook because the
 * delay and the cleanup are the whole behaviour: a copy that forgets the
 * `clearTimeout` fires a request per keystroke, which is exactly what the
 * debounce was added to stop.
 *
 * `set-state-in-effect` is unavoidable here and correct: the value is derived
 * from another *over time*, which is the case that rule exempts. Doing it once
 * in one hook is the difference between one documented instance and eighteen
 * undocumented ones.
 */
export function useDebouncedValue<T>(
  value: T,
  delayMs: number = DEFAULT_DEBOUNCE_MS
): T {
  const [debounced, setDebounced] = useState<T>(value);

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

  return debounced;
}
