/**
 * The consume-once `sessionStorage` hooks, mounted for real.
 *
 * These three hooks hold the only `react-hooks/set-state-in-effect` reports
 * left in the app, on the grounds that a browser-only value cannot be read
 * during a render that also happens on the server. That argument says the
 * *shape* is right; it says nothing about whether the lifecycle is. What can
 * actually go wrong here is scheduling — a read that deletes what it read has
 * to survive StrictMode running the effect twice, a remount after the entry is
 * gone, and a second consumer in the same commit — so these mount through
 * `createRoot` rather than exercising the parsing helpers underneath.
 */
import { beforeEach, describe, test } from "node:test";
import assert from "node:assert/strict";

import { installDom, renderHook, type MemoryStorage } from "./reactHarness";
import { useIsMounted } from "@/hooks/useIsMounted";
import { useNavState } from "@/hooks/useNavState";
import {
  useConsumedSocialPrefill,
  useStashedSocialProfile,
} from "@/features/auth/components/useStashedSocialProfile";
import {
  OAUTH_USER_KEY,
  setSocialPrefill,
  type SocialProfile,
} from "@/lib/auth/socialSignup";
import { NAV_STATE_KEYS, setNavState } from "@/lib/navigationState";

const PREFILL_KEY = "social_signup_prefill";

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

describe("useIsMounted", () => {
  test("is false on the first render and true once committed", () => {
    const probe = renderHook(() => useIsMounted());
    probe.mount();

    // The first render is the one that has to match the server's output.
    assert.equal(probe.renders[0], false);
    assert.equal(probe.last(), true);
  });

  test("stays true under StrictMode's double effect invocation", () => {
    const probe = renderHook(() => useIsMounted(), { strict: true });
    probe.mount();

    assert.equal(probe.last(), true);
    /* Nothing sets it back. StrictMode double-*renders* too, so the leading
       `false`s are expected — what must not happen is a `false` after the
       flag has flipped, which is the cleanup between the two effect passes
       undoing it and the measured layout flickering back to the server's. */
    const flipped = probe.renders.indexOf(true);
    assert.ok(flipped >= 0);
    assert.ok(!probe.renders.slice(flipped).includes(false));
  });
});

describe("useNavState", () => {
  test("reads the payload stashed by the previous screen", () => {
    setNavState(NAV_STATE_KEYS.registerList, { id: 7, title: "Beach clean" });
    const probe = renderHook(() =>
      useNavState<{ id: number }>(NAV_STATE_KEYS.registerList)
    );
    probe.mount();

    assert.equal(probe.renders[0], null, "first render must be the 'not read yet' state");
    assert.deepEqual(probe.last(), { id: 7, title: "Beach clean" });
  });

  test("distinguishes 'read, nothing stashed' from 'not read yet'", () => {
    const probe = renderHook(() =>
      useNavState<Record<string, never>>(NAV_STATE_KEYS.scanPermission)
    );
    probe.mount();

    /* `{}`, not `null`. Screens that redirect when the payload is missing hang
       on `null` forever otherwise, and screens that render from it flash the
       empty branch if they cannot tell the two apart. */
    assert.deepEqual(probe.last(), {});
  });

  test("does not consume the payload, so a remount still sees it", () => {
    setNavState(NAV_STATE_KEYS.volunteerForm, { id: 3 });

    const first = renderHook(() => useNavState<{ id: number }>(NAV_STATE_KEYS.volunteerForm));
    first.mount();
    assert.deepEqual(first.last(), { id: 3 });
    first.unmount();

    const second = renderHook(() => useNavState<{ id: number }>(NAV_STATE_KEYS.volunteerForm));
    second.mount();
    assert.deepEqual(
      second.last(),
      { id: 3 },
      "the form is remounted on every edit; a consuming read would empty it"
    );
  });

  test("answers {} for a corrupt entry rather than throwing", () => {
    storage.setItem(NAV_STATE_KEYS.eventForm, "{not json");
    const probe = renderHook(() => useNavState(NAV_STATE_KEYS.eventForm));
    probe.mount();

    assert.deepEqual(probe.last(), {});
  });

  test("is stable under StrictMode", () => {
    setNavState(NAV_STATE_KEYS.opportunityThankyou, { hours: 4 });
    const probe = renderHook(
      () => useNavState<{ hours: number }>(NAV_STATE_KEYS.opportunityThankyou),
      { strict: true }
    );
    probe.mount();

    assert.deepEqual(probe.last(), { hours: 4 });
  });
});

describe("useStashedSocialProfile", () => {
  const profile: SocialProfile = {
    email: "a@b.test",
    first_name: "Amal",
    social_media_provider: "google",
    social_token: "google-id-token",
  };

  test("reads the provider profile after mount", () => {
    storage.setItem(OAUTH_USER_KEY, JSON.stringify(profile));
    const probe = renderHook(() => useStashedSocialProfile<SocialProfile>());
    probe.mount();

    assert.equal(probe.renders[0], null);
    assert.deepEqual(probe.last(), profile);
  });

  test("leaves the entry in place for the later screens that re-read it", () => {
    storage.setItem(OAUTH_USER_KEY, JSON.stringify(profile));
    const probe = renderHook(() => useStashedSocialProfile<SocialProfile>(), {
      strict: true,
    });
    probe.mount();

    assert.deepEqual(probe.last(), profile);
    assert.ok(
      storage.getItem(OAUTH_USER_KEY),
      "clearSocialSignupState() owns the delete; reading must not consume"
    );
  });

  test("a corrupt profile reads as absent, not as a usable object", () => {
    storage.setItem(OAUTH_USER_KEY, "{\"email\":");
    const probe = renderHook(() => useStashedSocialProfile<SocialProfile>());
    probe.mount();

    /* `JoinUs` branches on `!== null` to decide whether a social sign-up is in
       progress; a half-written entry must not look like one. */
    assert.equal(probe.last(), null);
  });
});

describe("useConsumedSocialPrefill", () => {
  test("consumes the stash and keeps it through StrictMode's second pass", () => {
    setSocialPrefill("volunteer", { first_name: "Amal", last_name: "" });

    const probe = renderHook(() => useConsumedSocialPrefill("volunteer"), {
      strict: true,
    });
    probe.mount();

    /* The whole hazard: the first effect pass deletes the entry, the cleanup
       runs, and the second pass reads nothing. An unconditional
       `setPrefill(takeSocialPrefill(...))` would clear the answers here. */
    assert.deepEqual(probe.last(), { first_name: "Amal" });
    assert.equal(storage.getItem(PREFILL_KEY), null, "the stash must be consumed");
  });

  test("a re-render after consumption does not drop the answers", () => {
    setSocialPrefill("volunteer", { nickname: "amal" });
    const probe = renderHook(() => useConsumedSocialPrefill("volunteer"));
    probe.mount();
    probe.rerender();

    assert.deepEqual(probe.last(), { nickname: "amal" });
  });

  test("a remount after consumption starts empty", () => {
    setSocialPrefill("volunteer", { nickname: "amal" });

    const first = renderHook(() => useConsumedSocialPrefill("volunteer"));
    first.mount();
    assert.deepEqual(first.last(), { nickname: "amal" });
    first.unmount();

    const second = renderHook(() => useConsumedSocialPrefill("volunteer"));
    second.mount();
    /* Correct, and the point of consuming: an abandoned sign-up must not
       repopulate the next one in the same tab. */
    assert.equal(second.last(), null);
  });

  test("skip leaves the stash for the screen it was meant for", () => {
    setSocialPrefill("volunteer", { nickname: "amal" });

    // The mandate form rendered as a modal is handed its profile as a prop.
    const modal = renderHook(() => useConsumedSocialPrefill("volunteer", true), {
      strict: true,
    });
    modal.mount();

    assert.equal(modal.last(), null);
    assert.ok(storage.getItem(PREFILL_KEY), "a skipped consumer must not consume");
  });

  test("a consumer of the other account type leaves the stash alone", () => {
    setSocialPrefill("volunteer", { nickname: "amal" });

    const organization = renderHook(() => useConsumedSocialPrefill("organization"));
    organization.mount();
    assert.equal(organization.last(), null);
    assert.ok(
      storage.getItem(PREFILL_KEY),
      "this deleted first and checked the type afterwards, destroying the volunteer's answers"
    );

    const volunteer = renderHook(() => useConsumedSocialPrefill("volunteer"));
    volunteer.mount();
    assert.deepEqual(volunteer.last(), { nickname: "amal" });
  });

  test("two consumers of the same type: the first wins, the second gets nothing", () => {
    setSocialPrefill("volunteer", { nickname: "amal" });

    const first = renderHook(() => useConsumedSocialPrefill("volunteer"));
    const second = renderHook(() => useConsumedSocialPrefill("volunteer"));
    first.mount();
    second.mount();

    assert.deepEqual(first.last(), { nickname: "amal" });
    assert.equal(second.last(), null, "consume-once means exactly one reader");
  });

  test("a corrupt stash is cleared rather than left to poison the key", () => {
    storage.setItem(PREFILL_KEY, "{\"user_type\":\"volunteer\",\"values\":");

    const probe = renderHook(() => useConsumedSocialPrefill("volunteer"));
    probe.mount();

    assert.equal(probe.last(), null);
    assert.equal(storage.getItem(PREFILL_KEY), null);
  });

  test("an empty prefill is never written, so there is nothing to consume", () => {
    setSocialPrefill("volunteer", { first_name: "", nickname: null });

    const probe = renderHook(() => useConsumedSocialPrefill("volunteer"));
    probe.mount();

    /* A blank value would otherwise count as "already answered" and blank out
       a field the provider could have filled. */
    assert.equal(probe.last(), null);
    assert.equal(storage.getItem(PREFILL_KEY), null);
  });
});
