"use client";

import { useEffect, useRef } from "react";

/**
 * A ref that always holds the most recent render's value.
 *
 * For the case `react-hooks/exhaustive-deps` cannot express: an effect that
 * has to *read* a value but must not *re-run* when it changes. Listing the
 * value is wrong (the effect restarts on every keystroke); suppressing the
 * rule hides that the effect is reading a stale closure. A ref says which one
 * is meant — "whatever it is now" — and lets the dependency list be complete,
 * because a ref object's identity never changes.
 *
 * Two places this is load-bearing rather than cosmetic:
 *
 *  - the reverse-geocode effects read `values.location` **after an `await`**,
 *    to avoid overwriting something the organizer typed meanwhile. The closure
 *    holds the value from before the round trip, so the ref is also the more
 *    correct read.
 *  - the time-slot snapshot wants the list as it stands *when the modal
 *    opens*, which is exactly "latest at the moment the effect runs".
 *
 * It is not a general escape hatch. If an effect should re-run when a value
 * changes, list the value.
 */
export function useLatest<T>(value: T): { readonly current: T } {
  const ref = useRef(value);

  /* Assigned in an effect rather than during render: React may render a
     component without committing it, and a render-phase write would then
     publish a value that was never shown. No dependency array, so it runs
     after every commit. */
  useEffect(() => {
    ref.current = value;
  });

  return ref;
}
