import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test, vi } from "vitest";
import { AppProviders } from "@/app/providers.jsx";
import { GameWhitelistDialog } from "./GameWhitelistDialog.jsx";

test("renders current members and exposes whitelist toggle, add and remove actions", async () => {
    const user = userEvent.setup();
    const page = {
        abilities: { canUpdate: true },
        addWhitelistUser: vi.fn((event) => event.preventDefault()),
        changeWhitelistEnabled: vi.fn(),
        loadingAction: "",
        removeWhitelistUser: vi.fn(),
        setWhitelistUserId: vi.fn(),
        whitelistGame: { gameId: "private_slot", gameName: "Private Slot", whitelistEnabled: true },
        whitelistItems: [
            {
                createdAtMs: 1700000000000,
                displayUserId: "90001",
                status: "active",
                userId: "42",
                username: "Alice",
            },
        ],
        whitelistLoading: false,
        whitelistUserId: "42",
    };

    render(
        <AppProviders>
            <GameWhitelistDialog open page={page} onClose={vi.fn()} />
        </AppProviders>,
    );

    expect(screen.getByText("游戏白名单 · Private Slot")).toBeInTheDocument();
    expect(screen.getByText("Alice")).toBeInTheDocument();
    expect(screen.getByText("90001")).toBeInTheDocument();

    await user.click(screen.getByRole("switch", { name: "游戏白名单状态" }));
    expect(page.changeWhitelistEnabled).toHaveBeenCalledWith(false);

    await user.click(screen.getByRole("button", { name: "添加" }));
    expect(page.addWhitelistUser).toHaveBeenCalledOnce();

    await user.click(screen.getByRole("button", { name: "移出白名单" }));
    expect(page.removeWhitelistUser).toHaveBeenCalledWith(page.whitelistItems[0]);
});
