import { fireEvent, render, screen } from "@testing-library/react";
import HealthRiskReport from "./HealthRiskReport";
import { PredictionResult } from "./types";

jest.mock("echarts-for-react", () => ({
  __esModule: true,
  default: () => <div data-testid="report-chart" />,
}));

const predictionResults: PredictionResult[] = [
  {
    link_id: "PIPE-007",
    survival_function: {
      x: [4, 5],
      y: [0.2, 0.15],
      a: 0,
      b: 0,
    },
  },
  {
    link_id: "PIPE-021",
    survival_function: {
      x: [4, 5],
      y: [0.8, 0.7],
      a: 0,
      b: 0,
    },
  },
];

describe("HealthRiskReport", () => {
  it("renders automatic report identity and priority results", () => {
    render(
      <HealthRiskReport
        open
        onClose={jest.fn()}
        predictionResults={predictionResults}
        currentYear={4}
        analysisQueryTime="2026-07-30T01:02:03.000Z"
        networkName="fengyang"
        generatedAt={new Date("2026-07-30T03:04:05.000Z")}
      />,
    );

    expect(
      screen.getByRole("heading", { name: "管网健康风险体检报告" }),
    ).toBeInTheDocument();
    expect(screen.getByText("fengyang")).toBeInTheDocument();
    expect(screen.getByText("第 4 年")).toBeInTheDocument();
    expect(screen.getByText("PIPE-007")).toBeInTheDocument();
    expect(screen.getAllByTestId("report-chart")).toHaveLength(2);
  });

  it("prints the report and restores document state after printing", () => {
    const originalTitle = document.title;
    const print = jest
      .spyOn(window, "print")
      .mockImplementation(() => undefined);

    render(
      <HealthRiskReport
        open
        onClose={jest.fn()}
        predictionResults={predictionResults}
        currentYear={4}
        analysisQueryTime="2026-07-30T01:02:03.000Z"
        networkName="fengyang"
        generatedAt={new Date("2026-07-30T03:04:05.000Z")}
      />,
    );

    fireEvent.click(screen.getByRole("button", { name: "打印" }));

    expect(print).toHaveBeenCalledTimes(1);
    expect(document.body).toHaveClass("health-risk-report-printing");
    expect(document.title).toContain("管网健康风险体检报告-fengyang");

    window.dispatchEvent(new Event("afterprint"));

    expect(document.body).not.toHaveClass("health-risk-report-printing");
    expect(document.title).toBe(originalTitle);
    print.mockRestore();
  });
});
