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

const apps = [
  { appCode: "huwaa", appName: "Huwaa" },
  { appCode: "lalu", appName: "Lalu" }
];

test("renders selected App scope and emits individual changes", async () => {
  const user = userEvent.setup();
  const onAppChecked = vi.fn();
  render(
    <UserAppScopeEditor
      apps={apps}
      appCodes={["lalu"]}
      mode="selected"
      onAppChecked={onAppChecked}
      onModeChange={vi.fn()}
    />
  );

  expect(screen.getByText("已选 1 项")).toBeInTheDocument();
  await user.click(screen.getByRole("checkbox", { name: /Huwaa/ }));
  expect(onAppChecked).toHaveBeenCalledWith("huwaa", true);
});

test("all mode is explicit and selects every visible App", async () => {
  const user = userEvent.setup();
  const onModeChange = vi.fn();
  render(
    <UserAppScopeEditor apps={apps} appCodes={[]} mode="all" onAppChecked={vi.fn()} onModeChange={onModeChange} />
  );

  expect(screen.getByText("已选 2 项")).toBeInTheDocument();
  expect(screen.getAllByRole("checkbox").every((item) => item.checked)).toBe(true);
  await user.click(screen.getByRole("checkbox", { name: "全部 App" }));
  expect(onModeChange).toHaveBeenCalledWith("none");
});
