"use client";

import { useEffect, useState } from "react";

import { getNavState, type NavStateKey } from "@/lib/navigationState";

/**
 * Read a `lib/navigationState` payload once, after hydration.
 *
 * **Why this is an effect and not a lazy `useState` initializer.** A lazy
 * initializer runs during render, and a Client Component is still rendered on
 * the server to produce the initial HTML — where `sessionStorage` does not
 * exist. `getNavState` guards that with `typeof window === "undefined"` and
 * returns `null`, so a render-time read would always yield `null` on the
 * server and then disagree with the client's first render: a hydration
 * mismatch. Reading in an effect is the correct shape here, which is why the
 * `react-hooks/set-state-in-effect` report on the line below is accepted
 * rather than worked around.
 *
 * **The three states matter.** `null` means "not read yet" — distinct from
 * `{}`, which means "read, and nothing was stashed". Screens that decide
 * anything from the payload must wait for the first, or they flash the
 * nothing-stashed branch for one frame. Callers therefore read through `?.`.
 *
 * Replaces six copies of this exact `useState(null)` + mount-effect pair
 * (`RegisterList`, `RegisterListForLearnandServe`, `ScanPermission`,
 * `RegisterNow`, `LearnServeRegistrationModals`, `useVolunteerListNavState`),
 * each of which was separately reported by the rule.
 */
export function useNavState<T>(key: NavStateKey): T | null {
  const [value, setValue] = useState<T | null>(null);

  useEffect(() => {
    // `?? ({} as T)` distinguishes "read, empty" from the initial "not read".
    setValue(getNavState<T>(key) ?? ({} as T));
  }, [key]);

  return value;
}
