"use client";

import { useSyncExternalStore } from "react";

import { useAuthStore } from "@/store/authStore";

const subscribe = (onChange: () => void) =>
  useAuthStore.persist.onFinishHydration(onChange);

const getSnapshot = () => useAuthStore.persist.hasHydrated();

/**
 * Is this render working from the real session, or from the server snapshot?
 *
 * **`false` during the server render and during the hydration render; `true`
 * from the re-render immediately after.** It is not a loading flag — `persist`
 * reads `localStorage` synchronously while the store module is evaluated, so
 * the session is already in `getState()` before React runs at all. What this
 * reports is which *snapshot* the current render is working from.
 *
 * ## Why a render can see no session even though one exists
 *
 * `zustand/react`'s `useStore` is `useSyncExternalStore`, and it already passes
 * a server snapshot:
 *
 * ```js
 * React.useSyncExternalStore(
 *   api.subscribe,
 *   () => selector(api.getState()),        // client
 *   () => selector(api.getInitialState()), // server *and hydration*
 * )
 * ```
 *
 * React uses the third argument for the SSR render **and for the hydration
 * render**, then compares it with the second and schedules an ordinary
 * re-render if they differ. `getInitialState()` is the signed-out default —
 * measured, in `tests/sessionHydration.test.ts` — so the server HTML and
 * React's first client render agree, and there is **no hydration mismatch**.
 * That part needs no fixing and has not been changed.
 *
 * What does need handling is the **effect** attached to that first render.
 * Measured, in the same file: for a signed-in reader the render sequence is
 * `[null, null, user]` and the effect sequence is `[null, user]`. So an effect
 * runs once with no session, before the re-render that has one.
 *
 * For `ProtectedRoute` that was a real defect: `routeAccess` correctly answers
 * `/login` for a null user, so **a signed-in reader was redirected to `/login`
 * on every reload of a guarded page.** Gating the redirect on this hook is the
 * fix. For `RedirectIfLoggedIn` the same gate prevents the inverse — a
 * signed-out visitor bounced off the sign-in form.
 *
 * It is also why four detail screens gate their query on it: they put the token
 * in the query key, so without the gate the first committed render fires a
 * request keyed "no token" and the re-render fires a second keyed "token".
 *
 * **Components that only *render* from the session need none of this.** Both
 * snapshots already agree with the server, so they are consistent by
 * construction; this is only for code that *acts*.
 */
export function useSessionReady(): boolean {
  return useSyncExternalStore(subscribe, getSnapshot, () => false);
}
