import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it } from "vitest";

import {
  AuthProvider,
  useAuthDispatch,
  useAuthSelector,
} from "@/stores/auth/auth-context";

let container: HTMLDivElement | null = null;
let root: ReturnType<typeof createRoot> | null = null;

afterEach(() => {
  if (root) {
    act(() => root?.unmount());
  }
  container?.remove();
  container = null;
  root = null;
});

describe("AuthProvider selectors", () => {
  it("does not rerender a login-status subscriber for panel-only changes", () => {
    let renderCount = 0;

    function Probe() {
      const loginStatus = useAuthSelector(
        (state) => state.context.loginStatus,
      );
      const dispatch = useAuthDispatch();
      renderCount += 1;

      return (
        <button
          type="button"
          onClick={() =>
            dispatch({ type: "AuthPanelModeChanged", mode: "email" })
          }
        >
          {loginStatus}
        </button>
      );
    }

    container = document.createElement("div");
    document.body.append(container);
    root = createRoot(container);

    act(() => {
      root?.render(
        <AuthProvider>
          <Probe />
        </AuthProvider>,
      );
    });
    expect(renderCount).toBe(1);

    act(() => {
      container?.querySelector("button")?.click();
    });

    expect(renderCount).toBe(1);
    expect(container.textContent).toBe("notLoggedIn");
  });
});
