import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router-dom";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { ExternalI18nProvider } from "../i18n/ExternalI18nProvider.jsx";
import { EXTERNAL_LOCALE_STORAGE_KEY } from "../i18n/messages.js";
import LoginPage from "./LoginPage.jsx";

const auth = vi.hoisted(() => ({ initializing: false, login: vi.fn(), session: null }));

vi.mock("../auth/ExternalAuthProvider.jsx", () => ({ useExternalAuth: () => auth }));

describe("LoginPage", () => {
  beforeEach(() => {
    localStorage.removeItem(EXTERNAL_LOCALE_STORAGE_KEY);
    auth.login.mockReset().mockResolvedValue({ appCode: "fami", passwordChangeRequired: false });
  });

  test("defaults to English, has no App field and submits only account and password", async () => {
    const user = userEvent.setup();
    const staleFavicon = document.createElement("link");
    staleFavicon.dataset.externalAppFavicon = "true";
    staleFavicon.rel = "icon";
    staleFavicon.href = "https://media.example.com/apps/lalu.png";
    document.head.append(staleFavicon);
    document.title = "Lalu";
    const { container } = renderLogin();

    expect(screen.getByRole("heading", { name: "External Admin" })).toBeInTheDocument();
    expect(container.querySelector("img")).toBeNull();
    expect(document.title).toBe("External Admin");
    expect(document.head.querySelector('link[data-external-app-favicon="true"]')).not.toBeInTheDocument();
    expect(screen.queryByRole("combobox", { name: "App" })).not.toBeInTheDocument();
    await user.type(screen.getByRole("textbox", { name: "Account" }), "fami-manager");
    expect(screen.getByRole("heading", { name: "External Admin" })).toBeInTheDocument();
    expect(container.querySelector("img")).toBeNull();
    await user.type(container.querySelector('input[autocomplete="current-password"]'), "secret-password");
    await user.click(screen.getByRole("button", { name: "Sign in" }));

    expect(auth.login).toHaveBeenCalledWith({ account: "fami-manager", password: "secret-password" });
  });

  test("localizes a numeric login 401 without exposing the backend message", async () => {
    const user = userEvent.setup();
    auth.login.mockRejectedValueOnce({ code: 40100, message: "账号已禁用", status: 401 });
    const { container } = renderLogin();

    await user.type(screen.getByRole("textbox", { name: "Account" }), "unknown-account");
    await user.type(container.querySelector('input[autocomplete="current-password"]'), "bad-password");
    await user.click(screen.getByRole("button", { name: "Sign in" }));

    expect(await screen.findByText("Incorrect account or password")).toBeInTheDocument();
    expect(screen.queryByText("账号已禁用")).not.toBeInTheDocument();
    expect(screen.queryByText("Your session has expired. Sign in again.")).not.toBeInTheDocument();
  });
});

function renderLogin() {
  return render(<ExternalI18nProvider><MemoryRouter><LoginPage /></MemoryRouter></ExternalI18nProvider>);
}
