import { screen, waitFor } from "@testing-library/react";
import { describe, expect, test } from "bun:test";
import { createElement } from "react";

import { SettingsPage } from "../../../../src/web/features/settings/index";
import { installFetchMock, jsonResponse, renderWithProviders } from "../../test-utils";

function mockSettingsResponse(theme = "system"): Response {
  return jsonResponse({ theme });
}

describe("SettingsPage", () => {
  test("渲染主题卡片", () => {
    installFetchMock((call) => {
      if (call.url.includes("/api/settings")) return mockSettingsResponse();
      return jsonResponse({});
    });

    renderWithProviders(createElement(SettingsPage));

    expect(screen.getByText("主题")).not.toBeNull();
  });

  test("渲染主题 Segmented 选项", () => {
    installFetchMock((call) => {
      if (call.url.includes("/api/settings")) return mockSettingsResponse();
      return jsonResponse({});
    });

    renderWithProviders(createElement(SettingsPage));

    expect(screen.getByText("系统")).not.toBeNull();
    expect(screen.getByText("明亮")).not.toBeNull();
    expect(screen.getByText("黑暗")).not.toBeNull();
  });

  test("API 加载中时不显示保存状态", () => {
    installFetchMock((call) => {
      if (call.url.includes("/api/settings")) return mockSettingsResponse();
      return jsonResponse({});
    });

    renderWithProviders(createElement(SettingsPage));

    expect(screen.queryByText("保存中...")).toBeNull();
  });

  test("GET /api/settings 获取已保存主题", async () => {
    installFetchMock((call) => {
      if (call.url.includes("/api/settings")) return mockSettingsResponse("dark");
      return jsonResponse({});
    });

    renderWithProviders(createElement(SettingsPage));

    await waitFor(() => {
      const segmented = document.querySelector(".ant-segmented");
      expect(segmented).not.toBeNull();
    });
  });
});
