/**
 * Server HTML, then hydration, with and without a persisted session.
 *
 * Two different questions, and they have different answers. This file exists
 * because an earlier pass of this review got the first one wrong.
 *
 * **1. Is there a hydration mismatch? No.** `zustand/react`'s `useStore` is
 * `useSyncExternalStore`, and it passes `api.getInitialState()` as the server
 * snapshot — which React uses for the SSR render *and for the hydration
 * render*. `persist` reads `localStorage` synchronously during store creation,
 * so `getState()` has the session, but `getInitialState()` stays the
 * signed-out default. Server HTML and first client render therefore agree.
 * Pass 19 of the review reported a mismatch here; that was wrong, and the
 * assertions below are what settle it.
 *
 * **2. Does an effect on that render see the session? No — and that was a real
 * defect.** The render sequence for a signed-in reader is `[null, null, user]`
 * and the effect sequence is `[null, user]`: an effect runs once with no
 * session, before the re-render that has one. `ProtectedRoute`'s effect
 * therefore called `router.replace("/login")`, so **a signed-in reader was
 * redirected to the sign-in page on every reload of a guarded page.** The fix
 * is `useSessionReady`, and `tests/routeGuards.test.ts` covers the decision it
 * gates.
 *
 * **Why the existing mounted-hook tests could not catch either.** `render()`
 * mounts a fresh client tree: there is no server output to disagree with, and
 * no hydration render, so the first committed value is already the real
 * session. Both questions are about `renderToString` followed by
 * `hydrateRoot`, so both have to run. React also *reports* a mismatch through
 * `onRecoverableError` rather than throwing, so it has to be collected or a
 * mismatched tree hydrates "successfully".
 *
 * **What this cannot test.** The real `Header`, `ProtectedRoute` and
 * `RedirectIfLoggedIn` are `.tsx`, which Node's type stripping cannot load, so
 * the probe below is built with `createElement`. It reads the session through
 * the same store and the same `useSyncExternalStore` shape, so the behaviour
 * under test is the real one; their markup is not covered, and the visible
 * result is item 1 of the browser acceptance set.
 */
import { beforeEach, describe, test } from "node:test";
import assert from "node:assert/strict";
import { pathToFileURL } from "node:url";
import { join } from "node:path";

import { hydrate, installDom } from "./reactHarness";
import { routeAccess } from "@/components/shared/routeAccess";
import type { User } from "@/store/authStore";

const PERSISTED_USER: User = {
  id: 7,
  first_name: "Amal",
  last_name: "Nasser",
  email: "amal@fursa.test",
  profile_pic: null,
  social_media_id: null,
  social_media_provider: null,
  user_type: "volunteer",
  manual_id: "V-7",
  is_new_user: false,
  is_verified: true,
  auth_token: "persisted-token",
};

/** A `localStorage` the test controls, installed before any store import. */
function installLocalStorage() {
  const map = new Map<string, string>();
  const storage = {
    getItem: (k: string) => map.get(k) ?? null,
    setItem: (k: string, v: string) => void map.set(k, String(v)),
    removeItem: (k: string) => void map.delete(k),
    clear: () => map.clear(),
    key: (i: number) => Array.from(map.keys())[i] ?? null,
    get length() {
      return map.size;
    },
  } as Storage;
  for (const target of [globalThis, globalThis.window as unknown as object]) {
    Object.defineProperty(target, "localStorage", {
      value: storage,
      configurable: true,
    });
  }
  return storage;
}

/**
 * A fresh copy of the store module.
 *
 * `persist` reads `localStorage` while the module is evaluated, so each case
 * needs its own evaluation with its own seeded storage — hence the
 * cache-busting query on the file URL. The `@/` alias resolver takes a bare
 * path, not a query, so the URL is built here.
 */
async function freshAuthStore() {
  const url = pathToFileURL(
    join(import.meta.dirname, "..", "src", "store", "authStore.ts")
  );
  url.searchParams.set("case", String(Math.random()));
  return (await import(url.href)) as typeof import("@/store/authStore");
}

/**
 * The probe: the two decisions the auth-dependent chrome makes, read through
 * the same hooks the real components use.
 */
async function sessionProbe(authStore: typeof import("@/store/authStore")) {
  const { createElement } = await import("react");
  const { useSyncExternalStore } = await import("react");

  /* `useSessionReady`, inlined against *this* copy of the store — the shipped
     hook closes over the singleton, and each case here needs its own. The two
     are identical, and `tests/routeGuards.test.ts` exercises the real one. */
  const useReady = () =>
    useSyncExternalStore(
      authStore.useAuthStore.persist.onFinishHydration,
      () => authStore.useAuthStore.persist.hasHydrated(),
      () => false
    );

  return function Probe() {
    const user = authStore.useAuthStore((s) => s.user);
    const ready = useReady();
    return createElement(
      "div",
      null,
      createElement("span", { id: "auth" }, user ? "signed-in" : "signed-out"),
      createElement("span", { id: "name" }, user?.first_name ?? "none"),
      createElement("span", { id: "ready" }, ready ? "ready" : "unknown")
    );
  };
}

const text = (html: string, id: string) =>
  new RegExp(`<span id="${id}"[^>]*>([^<]*)</span>`).exec(html)?.[1] ?? null;

/** Hydration mismatches, as React words them. */
const mismatches = (errors: string[]) =>
  errors.filter((e) => /hydrat|did not match|server.*client|Minified React error #41[89]/i.test(e));

let storage: Storage;
beforeEach(() => {
  installDom();
  storage = installLocalStorage();
});

describe("a persisted signed-in session", () => {
  test("hydrates with no mismatch, and shows the signed-in UI afterwards", async () => {
    /*
     * The real sequence: the server renders knowing nothing (the token is in
     * `localStorage`, not a cookie), then the browser hydrates with the
     * session already on disk.
     */
    const serverStore = await freshAuthStore();
    const ServerProbe = await sessionProbe(serverStore);

    let clientStore!: typeof import("@/store/authStore");
    let ClientProbe!: () => unknown;

    const { createElement } = await import("react");

    const result = await hydrate(
      () => createElement(ServerProbe),
      () => createElement(ClientProbe as never),
      {
        async onBeforeHydrate() {
          /* Seed the session *between* the two renders, then evaluate a fresh
             copy of the store so `persist` reads it — which is what a browser
             does on a reload. */
          storage.setItem(
            "fursa-auth",
            JSON.stringify({ state: { user: PERSISTED_USER }, version: 0 })
          );
          clientStore = await freshAuthStore();
          ClientProbe = await sessionProbe(clientStore);
        },
      }
    );

    // The server could only produce the signed-out tree, and did.
    assert.equal(text(result.html, "auth"), "signed-out");
    assert.equal(text(result.html, "ready"), "unknown");

    // The whole point.
    assert.deepEqual(
      mismatches(result.errors),
      [],
      `React reported a hydration mismatch: ${result.errors.join(" | ")}`
    );

    // And the signed-in UI is there once hydration settles.
    assert.equal(text(result.hydrated, "auth"), "signed-in");
    assert.equal(text(result.hydrated, "name"), "Amal");
    assert.equal(text(result.hydrated, "ready"), "ready");

    result.unmount();
  });

  test("the session is readable outside React from the first module evaluation", async () => {
    /*
     * `lib/api/client.ts`'s request interceptor reads the token through
     * `getState()`, before any component renders — and `getState()` is
     * hydrated from module evaluation. This is why every request carries its
     * `Authorization` header even on the render that has no session in React,
     * and so why the one-render gap cannot cause a 401 logout. It is also why
     * moving the rehydrate into an effect would be wrong: a root provider's
     * effect runs *after* its children's, so a child's query would go out
     * unauthenticated.
     */
    storage.setItem(
      "fursa-auth",
      JSON.stringify({ state: { user: PERSISTED_USER }, version: 0 })
    );
    const store = await freshAuthStore();

    assert.equal(
      store.useAuthStore.getState().user?.auth_token,
      "persisted-token",
      "the interceptor would send no Authorization header"
    );
  });

  test("React's server snapshot stays signed-out even though the store is hydrated", async () => {
    /* The mechanism, asserted directly. This is the assertion that corrects
       pass 19: `getInitialState()` is what zustand hands React for the
       hydration render, and it is **not** polluted by `persist`'s synchronous
       read. Had it been, a mismatch would follow on every subtree that reads
       the store — which is what pass 19 claimed. */
    storage.setItem(
      "fursa-auth",
      JSON.stringify({ state: { user: PERSISTED_USER }, version: 0 })
    );
    const store = await freshAuthStore();

    assert.equal(store.useAuthStore.getInitialState().user, null);
    assert.equal(store.useAuthStore.getState().user?.id, 7);
  });

  test("an effect on the hydration render sees no session — the defect's root", async () => {
    /*
     * The measurement the fix rests on. A guard-shaped component: it reads the
     * store the way `useStore` does and records what each render and each
     * effect observed.
     *
     * Both sequences matter. `renders` shows the hydration render using the
     * server snapshot — that is what makes the HTML agree and why there is no
     * mismatch. `effects` shows an effect firing *before* the re-render, with
     * no session, which is exactly when `ProtectedRoute` used to call
     * `router.replace("/login")` for a reader who was signed in all along.
     */
    storage.setItem(
      "fursa-auth",
      JSON.stringify({ state: { user: PERSISTED_USER }, version: 0 })
    );
    const { createElement, useEffect, useSyncExternalStore } = await import("react");

    const renders: (number | null)[] = [];
    const effects: (number | null)[] = [];
    const sessionReadyAtEffect: boolean[] = [];

    const serverStore = await freshAuthStore();
    let store = serverStore;

    function Probe() {
      const user = useSyncExternalStore(
        store.useAuthStore.subscribe,
        () => store.useAuthStore.getState().user,
        () => store.useAuthStore.getInitialState().user
      );
      const ready = useSyncExternalStore(
        store.useAuthStore.persist.onFinishHydration,
        () => store.useAuthStore.persist.hasHydrated(),
        () => false
      );
      renders.push(user?.id ?? null);
      useEffect(() => {
        effects.push(user?.id ?? null);
        sessionReadyAtEffect.push(ready);
      }, [user, ready]);
      return createElement("span", null, String(user?.id ?? "none"));
    }

    const result = await hydrate(
      () => createElement(Probe),
      () => createElement(Probe),
      {
        async onBeforeHydrate() {
          store = await freshAuthStore();
        },
      }
    );

    assert.equal(renders[0], null, "the hydration render uses the server snapshot");
    assert.equal(renders[renders.length - 1], 7, "and settles on the real session");
    assert.deepEqual(mismatches(result.errors), [], "so there is no mismatch");

    assert.equal(
      effects[0],
      null,
      "an effect fires before the re-render — this is what redirected a signed-in reader to /login"
    );
    assert.equal(
      sessionReadyAtEffect[0],
      false,
      "and `useSessionReady` is false on exactly that pass, which is what the guards gate on"
    );
    assert.ok(
      sessionReadyAtEffect.includes(true),
      "it must become true, or the guard would never redirect anyone"
    );

    /* The decision itself, on both passes: correct each time, and harmful only
       if acted on during the first. */
    assert.equal(
      routeAccess({
        user: store.useAuthStore.getInitialState().user,
        userType: "volunteer",
      }).redirectTo,
      "/login"
    );
    assert.deepEqual(
      routeAccess({ user: store.useAuthStore.getState().user, userType: "volunteer" }),
      { allow: true, redirectTo: null }
    );

    result.unmount();
  });

  test("the control: this harness does detect a mismatch when there is one", async () => {
    /* Without this, every "no mismatch" assertion above would also pass
       against a harness that cannot see one. */
    const { createElement } = await import("react");
    const result = await hydrate(
      () => createElement("div", null, "SERVER"),
      () => createElement("div", null, "CLIENT")
    );

    assert.equal(mismatches(result.errors).length, 1);
    assert.match(result.errors[0], /Hydration failed/);

    result.unmount();
  });
});

describe("no persisted session", () => {
  test("hydrates with no mismatch and stays signed out", async () => {
    const serverStore = await freshAuthStore();
    const ServerProbe = await sessionProbe(serverStore);
    const { createElement } = await import("react");

    let ClientProbe!: () => unknown;
    const result = await hydrate(
      () => createElement(ServerProbe),
      () => createElement(ClientProbe as never),
      {
        async onBeforeHydrate() {
          ClientProbe = await sessionProbe(await freshAuthStore());
        },
      }
    );

    assert.equal(text(result.html, "auth"), "signed-out");
    assert.deepEqual(mismatches(result.errors), []);
    assert.equal(text(result.hydrated, "auth"), "signed-out");
    assert.equal(text(result.hydrated, "name"), "none");
    /* `ready` still flips: the session is *known* to be absent, which is what
       lets the guard redirect an anonymous visitor rather than waiting. */
    assert.equal(text(result.hydrated, "ready"), "ready");

    result.unmount();
  });

  test("a corrupt persisted entry hydrates cleanly and reads as signed out", async () => {
    storage.setItem("fursa-auth", "{not json");
    const serverStore = await freshAuthStore();
    const ServerProbe = await sessionProbe(serverStore);
    const { createElement } = await import("react");

    let ClientProbe!: () => unknown;
    const result = await hydrate(
      () => createElement(ServerProbe),
      () => createElement(ClientProbe as never),
      {
        async onBeforeHydrate() {
          ClientProbe = await sessionProbe(await freshAuthStore());
        },
      }
    );

    assert.deepEqual(mismatches(result.errors), []);
    assert.equal(text(result.hydrated, "auth"), "signed-out");

    result.unmount();
  });
});

describe("the language store has the same shape", () => {
  test("its fallback server snapshot defaults to Arabic", async () => {
    // The application now receives its SSR language from a cookie-scoped provider.
    storage.setItem(
      "fursa-language",
      JSON.stringify({ state: { language: "ar" }, version: 0 })
    );
    const url = pathToFileURL(
      join(import.meta.dirname, "..", "src", "store", "languageStore.ts")
    );
    url.searchParams.set("case", String(Math.random()));
    const { useLanguageStore } = (await import(
      url.href
    )) as typeof import("@/store/languageStore");

    assert.equal(useLanguageStore.getInitialState().language, "ar");
    assert.equal(useLanguageStore.getState().language, "ar");
  });
});
