import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { MemoryRouter } from "react-router-dom";
import { afterEach, describe, expect, it, vi } from "vitest";
import LoginPage from "./LoginPage";

const authState = {
  isAuthenticated: false,
  isLoading: false,
  activeNavigator: undefined as string | undefined,
  signinRedirect: vi.fn(),
};

vi.mock("react-oidc-context", () => ({
  useAuth: () => authState,
}));

function renderLoginPage(initialEntry: string) {
  const container = document.createElement("div");
  document.body.appendChild(container);
  const root = createRoot(container);

  act(() => {
    root.render(
      <MemoryRouter initialEntries={[initialEntry]}>
        <LoginPage />
      </MemoryRouter>,
    );
  });

  return { container, root };
}

function cleanupRendered(container: HTMLDivElement, root: Root) {
  act(() => {
    root.unmount();
  });
  container.remove();
}

describe("OrgFront LoginPage auto login", () => {
  afterEach(() => {
    vi.clearAllMocks();
    authState.isAuthenticated = false;
    authState.isLoading = false;
    authState.activeNavigator = undefined;
  });

  it("does not start auto login again when the orgfront session is already authenticated", () => {
    authState.isAuthenticated = true;

    const rendered = renderLoginPage(
      "/login?auto=1&returnTo=%2Fembed%2Fpicker%3Fmode%3Dsingle",
    );

    expect(authState.signinRedirect).not.toHaveBeenCalled();
    cleanupRendered(rendered.container, rendered.root);
  });

  it("starts auto login once when auto mode is requested without an authenticated session", () => {
    const rendered = renderLoginPage(
      "/login?auto=1&returnTo=%2Fembed%2Fpicker%3Fmode%3Dsingle",
    );

    expect(authState.signinRedirect).toHaveBeenCalledTimes(1);
    expect(authState.signinRedirect).toHaveBeenCalledWith({
      state: {
        returnTo: "/embed/picker?mode=single",
      },
    });
    cleanupRendered(rendered.container, rendered.root);
  });
});
