import { fireEvent, render, screen } from "@testing-library/react";
import { App as AntApp, ConfigProvider } from "antd";
import { describe, expect, test } from "bun:test";
import { createElement } from "react";

import { ErrorBoundary } from "../../../src/web/components/ErrorBoundary";

function BrokenChild(): never {
  throw new Error("render failed");
}

function captureConsoleError(callback: () => void): string[] {
  const originalError = console.error;
  const errors: string[] = [];
  console.error = (...args: unknown[]) => {
    errors.push(args.map(String).join(" "));
  };

  try {
    callback();
  } finally {
    console.error = originalError;
  }

  return errors;
}

describe("ErrorBoundary", () => {
  test("子组件渲染失败后展示错误结果并隔离 console.error", () => {
    const errors = captureConsoleError(() => {
      render(
        createElement(
          ConfigProvider,
          null,
          createElement(AntApp, null, createElement(ErrorBoundary, null, createElement(BrokenChild))),
        ),
      );
    });

    expect(screen.getByText("渲染错误")).not.toBeNull();
    expect(screen.getByText("页面渲染出现异常，请刷新重试")).not.toBeNull();
    expect(screen.getByRole("button", { name: "刷新页面" })).not.toBeNull();
    expect(errors.some((line) => line.includes("渲染错误:"))).toBe(true);
  });

  test("点击刷新页面按钮不会破坏错误兜底界面", () => {
    captureConsoleError(() => {
      render(
        createElement(
          ConfigProvider,
          null,
          createElement(AntApp, null, createElement(ErrorBoundary, null, createElement(BrokenChild))),
        ),
      );
    });

    expect(() => {
      captureConsoleError(() => fireEvent.click(screen.getByRole("button", { name: "刷新页面" })));
    }).not.toThrow();
    expect(screen.getByText("渲染错误")).not.toBeNull();
  });
});
