import { act, fireEvent, render, screen } from "@testing-library/react";
import Login from "./page";

const mockLogin = jest.fn();

jest.mock("@refinedev/core", () => ({
  useLogin: () => ({ mutate: mockLogin }),
}));

describe("Login", () => {
  beforeEach(() => {
    jest.useFakeTimers();
    mockLogin.mockClear();
  });

  afterEach(() => {
    jest.useRealTimers();
  });

  it("starts Keycloak login once when the page opens", () => {
    const { rerender } = render(<Login />);

    expect(mockLogin).toHaveBeenCalledTimes(1);
    expect(mockLogin).toHaveBeenCalledWith({});
    expect(screen.getByText("正在进入账号登录")).toBeInTheDocument();

    rerender(<Login />);
    expect(mockLogin).toHaveBeenCalledTimes(1);
  });

  it("shows a manual fallback when automatic redirect does not complete", () => {
    render(<Login />);

    expect(
      screen.queryByRole("button", { name: "继续登录" }),
    ).not.toBeInTheDocument();

    act(() => {
      jest.advanceTimersByTime(4000);
    });

    fireEvent.click(screen.getByRole("button", { name: "继续登录" }));
    expect(mockLogin).toHaveBeenCalledTimes(2);
  });
});
