/**
 * Enough of a DOM and a React root to mount a hook for real.
 *
 * The consume-once `sessionStorage` hooks cannot be checked by testing their
 * parsing helpers: what makes them delicate is the *lifecycle* — the read
 * deletes the entry, so whether the hook survives StrictMode's double effect
 * invocation, an unmount/remount, and a second consumer mounting in the same
 * commit is a property of React's scheduling, not of the parser. So those are
 * driven through an actual `createRoot` render.
 *
 * jsdom is a transitive dependency (the app's own `lib/sanitizeHtml` runs
 * isomorphic-dompurify on it server-side), not a test-only addition.
 */
import { JSDOM } from "jsdom";
import { createElement, StrictMode, type ReactElement } from "react";
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";

/** A `sessionStorage` whose contents a test can inspect and seed directly. */
export class MemoryStorage implements Storage {
  private map = new Map<string, string>();
  get length() {
    return this.map.size;
  }
  clear() {
    this.map.clear();
  }
  getItem(key: string) {
    return this.map.has(key) ? (this.map.get(key) as string) : null;
  }
  key(index: number) {
    return Array.from(this.map.keys())[index] ?? null;
  }
  removeItem(key: string) {
    this.map.delete(key);
  }
  setItem(key: string, value: string) {
    this.map.set(key, String(value));
  }
}

export interface Harness {
  /** Values the probe returned, one per committed render. */
  readonly renders: unknown[];
  /** The last committed value. */
  last(): unknown;
  mount(): void;
  unmount(): void;
  /** Re-render without remounting, so a prop change can be driven. */
  rerender(): void;
}

/**
 * Mounts `hook` and records what it returns on every commit.
 *
 * `strict` wraps the probe in `StrictMode`, which in development double-invokes
 * effects as mount → cleanup → mount. That is the sequence that breaks a naive
 * consume-once hook: the second mount's read finds the entry already gone.
 */
export function renderHook<T>(hook: () => T, { strict = false } = {}): Harness {
  const renders: unknown[] = [];

  function Probe() {
    renders.push(hook());
    return null;
  }

  /* Built fresh per render, never cached: React bails out of re-rendering a
     subtree handed the referentially identical element, which would make
     `rerender()` a no-op. */
  const tree = (): ReactElement =>
    strict
      ? createElement(StrictMode, null, createElement(Probe))
      : createElement(Probe);

  let root: Root | null = null;
  const container = document.createElement("div");

  return {
    renders,
    last: () => renders[renders.length - 1],
    mount() {
      act(() => {
        root = createRoot(container);
        root.render(tree());
      });
    },
    rerender() {
      act(() => root?.render(tree()));
    },
    unmount() {
      act(() => root?.unmount());
      root = null;
    },
  };
}

/**
 * Server-renders an element to an HTML string, then hydrates that string.
 *
 * This is the only way to test a hydration mismatch. `render` below mounts a
 * fresh client tree, which cannot mismatch by construction — there is no
 * server output for it to disagree with. A mismatch is a disagreement between
 * `renderToString` and `hydrateRoot`, so both have to run.
 *
 * `onRecoverableError` is what makes the assertion possible: React reports a
 * hydration mismatch there rather than throwing, so without collecting it a
 * mismatched tree hydrates "successfully" and the test passes while the defect
 * remains. Everything React recovers from is collected and returned.
 */
export async function hydrate(
  server: () => ReactElement,
  client: () => ReactElement,
  { onBeforeHydrate }: { onBeforeHydrate?: () => void | Promise<void> } = {}
) {
  const { renderToString } = await import("react-dom/server");
  const { hydrateRoot } = await import("react-dom/client");

  const html = renderToString(server());

  const container = document.createElement("div");
  container.innerHTML = html;
  document.body.appendChild(container);

  /* The hook between the two renders: this is where a test seeds the
     `localStorage` session, so the server string is produced without it and
     the client hydrates with it — exactly the sequence that produced the
     defect. */
  await onBeforeHydrate?.();

  const errors: string[] = [];
  let root: { unmount: () => void } | null = null;
  await act(async () => {
    root = hydrateRoot(container, client(), {
      onRecoverableError: (error) => {
        errors.push(error instanceof Error ? error.message : String(error));
      },
    });
  });

  return {
    html,
    /** What React recovered from, hydration mismatches included. */
    errors,
    /** The container's HTML after hydration settled. */
    get hydrated() {
      return container.innerHTML;
    },
    unmount() {
      act(() => root?.unmount());
      container.remove();
    },
  };
}

/**
 * Mounts an arbitrary element, for testing a component rather than a hook.
 *
 * `renderHook` renders a probe that *returns* a value; a guard component has
 * to be rendered as itself, with a child that reports whether it was reached.
 */
export function render(element: ReactElement, { strict = false } = {}) {
  const tree = () =>
    strict ? createElement(StrictMode, null, element) : element;

  let root: Root | null = null;
  const container = document.createElement("div");

  return {
    container,
    mount() {
      act(() => {
        root = createRoot(container);
        root.render(tree());
      });
    },
    rerender() {
      act(() => root?.render(tree()));
    },
    unmount() {
      act(() => root?.unmount());
      root = null;
    },
  };
}

/**
 * Installs a DOM, a fresh `sessionStorage`, and React's act environment.
 *
 * Returns the storage so a test can seed an entry and then assert it was
 * consumed. Call from `beforeEach`.
 */
export function installDom(): MemoryStorage {
  const dom = new JSDOM("<!doctype html><html><body></body></html>", {
    url: "https://fursa.test/",
  });
  const storage = new MemoryStorage();
  const globals = globalThis as Record<string, unknown>;
  globals.window = dom.window;
  globals.document = dom.window.document;
  /* Node 24 defines `navigator` as a getter-only global, so it is replaced
     rather than assigned. React reads it when scheduling. */
  Object.defineProperty(globalThis, "navigator", {
    value: dom.window.navigator,
    configurable: true,
    writable: true,
  });
  globals.HTMLElement = dom.window.HTMLElement;
  globals.Node = dom.window.Node;
  globals.Event = dom.window.Event;
  globals.IS_REACT_ACT_ENVIRONMENT = true;
  Object.defineProperty(dom.window, "sessionStorage", {
    value: storage,
    configurable: true,
  });
  globals.sessionStorage = storage;
  return storage;
}
