import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { Mock } from "vitest";

// mock 版本模块：控制 checkUpdate 返回值、监视 openExternal。
vi.mock("../lib/version", () => ({
  checkUpdate: vi.fn(),
  openExternal: vi.fn(),
}));
import { UpdateBanner } from "./UpdateBanner";
import { checkUpdate, openExternal } from "../lib/version";

const mockCheck = checkUpdate as Mock;
const mockOpen = openExternal as Mock;

beforeEach(() => {
  mockCheck.mockReset();
  mockOpen.mockReset();
});

describe("UpdateBanner", () => {
  it("无更新（checkUpdate→null）时不渲染任何东西", async () => {
    mockCheck.mockResolvedValue(null);
    const { container } = render(<UpdateBanner />);
    await waitFor(() => expect(mockCheck).toHaveBeenCalled());
    expect(container).toBeEmptyDOMElement();
  });

  it("有更新时显示版本号，点「前往下载」调 openExternal(url)", async () => {
    mockCheck.mockResolvedValue({ version: "1.2.3", url: "https://rel", notes: "" });
    render(<UpdateBanner />);
    expect(await screen.findByText("v1.2.3")).toBeInTheDocument();

    await userEvent.click(screen.getByRole("button", { name: "前往下载" }));
    expect(mockOpen).toHaveBeenCalledWith("https://rel");
  });

  it("点忽略后横幅消失", async () => {
    mockCheck.mockResolvedValue({ version: "1.2.3", url: "https://rel", notes: "" });
    render(<UpdateBanner />);
    expect(await screen.findByText("v1.2.3")).toBeInTheDocument();

    await userEvent.click(screen.getByTitle("忽略"));
    expect(screen.queryByText("v1.2.3")).not.toBeInTheDocument();
  });
});
