import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router-dom";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { AppProviders } from "@/app/providers.jsx";
import { GameRobotPage } from "@/features/games/pages/GameRobotPage.jsx";

vi.mock("@/app/auth/AuthProvider.jsx", () => ({
    AuthProvider: ({ children }) => children,
    useAuth: () => ({ can: () => true }),
}));

beforeEach(() => {
    vi.stubGlobal(
        "fetch",
        vi.fn(async () => jsonResponse({ items: [] })),
    );
});

afterEach(() => {
    vi.unstubAllGlobals();
});

test("renders game robot page without crashing", async () => {
    render(
        <AppProviders>
            <MemoryRouter>
                <GameRobotPage />
            </MemoryRouter>
        </AppProviders>,
    );

    await waitFor(() => expect(screen.getByText("机器人用户")).toBeInTheDocument());
});

test("shows account language selector when generating robots", async () => {
    const user = userEvent.setup();
    render(
        <AppProviders>
            <MemoryRouter>
                <GameRobotPage />
            </MemoryRouter>
        </AppProviders>,
    );

    await waitFor(() => expect(screen.getByText("机器人用户")).toBeInTheDocument());
    await user.click(screen.getByRole("button", { name: "批量创建" }));

    expect(screen.getByLabelText("账号语言")).toBeInTheDocument();
    await user.click(screen.getByRole("combobox", { name: "账号语言" }));
    expect(screen.getByRole("option", { name: "阿拉伯语账号" })).toBeInTheDocument();
    expect(screen.getByRole("option", { name: "英语账号" })).toBeInTheDocument();
});

function jsonResponse(body) {
    return {
        headers: new Headers({ "content-type": "application/json" }),
        ok: true,
        status: 200,
        text: async () => JSON.stringify(body),
    };
}
