import { describe, it, expect, vi, beforeEach } from "vitest";
import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { matrixServiceMock, resetWailsMocks } from "../test/mocks/wails";
import { renderWithMantine } from "../test/utils";

vi.mock("../../wailsjs/go/main/MatrixService", () => matrixServiceMock);

import LoginScreen from "../LoginScreen";

describe("LoginScreen", () => {
  beforeEach(() => resetWailsMocks());

  it("renders the 'Sign in with Matrix' button", () => {
    renderWithMantine(<LoginScreen onLogin={() => {}} />);
    expect(
      screen.getByRole("button", { name: /sign in with matrix/i }),
    ).toBeInTheDocument();
  });

  it("calls Login() and forwards the user id to onLogin on click", async () => {
    const user = userEvent.setup();
    const onLogin = vi.fn();
    matrixServiceMock.Login.mockResolvedValueOnce("@alice:server");

    renderWithMantine(<LoginScreen onLogin={onLogin} />);
    await user.click(screen.getByRole("button", { name: /sign in with matrix/i }));

    await waitFor(() => {
      expect(matrixServiceMock.Login).toHaveBeenCalledTimes(1);
      expect(onLogin).toHaveBeenCalledWith("@alice:server");
    });
  });

  it("shows a red Alert when Login() rejects", async () => {
    const user = userEvent.setup();
    matrixServiceMock.Login.mockRejectedValueOnce(new Error("MAS unreachable"));

    renderWithMantine(<LoginScreen onLogin={() => {}} />);
    await user.click(screen.getByRole("button", { name: /sign in with matrix/i }));

    const alert = await screen.findByRole("alert");
    expect(alert).toHaveTextContent(/MAS unreachable/i);
  });
});
