import { render, screen } from "@testing-library/react";
import { expect, test, vi } from "vitest";

vi.mock("./EChart.jsx", () => ({
  EChart: ({ className }) => <div className={className} data-testid="distribution-echart" />
}));

import {
  createDistributionPieOption,
  DistributionPieChart,
  normalizeDistributionItems
} from "./DistributionPieChart.jsx";

test("shows the standard empty state when every distribution count is zero or invalid", () => {
  render(
    <DistributionPieChart
      ariaLabel="空分布"
      data={[
        { count: 0, key: "zero", label: "零" },
        { count: "invalid", key: "invalid", label: "无效" }
      ]}
    />
  );

  expect(screen.getByRole("status", { name: "空分布" })).toHaveTextContent("当前无数据");
  expect(screen.queryByTestId("distribution-echart")).not.toBeInTheDocument();
});

test("keeps a long distribution in a bounded legend instead of expanding the chart card", () => {
  const data = Array.from({ length: 12 }, (_, index) => ({
    count: 12 - index,
    key: `version-${index}`,
    label: `2.0.${index}`
  }));
  const { container } = render(<DistributionPieChart ariaLabel="版本分布" data={data} />);

  expect(screen.getAllByRole("listitem")).toHaveLength(12);
  expect(container.querySelector(".distribution-pie__legend")).toBeInTheDocument();
  expect(screen.getByTestId("distribution-echart")).toBeInTheDocument();
});

test("disables ECharts canvas animation when reduced motion is requested", () => {
  const items = normalizeDistributionItems([{ count: 8, key: "female", label: "女" }]);

  expect(createDistributionPieOption(items, true)).toMatchObject({
    animation: false,
    animationDuration: 0,
    animationDurationUpdate: 0
  });
  expect(createDistributionPieOption(items, false)).toMatchObject({
    animation: true,
    animationDuration: 450,
    animationDurationUpdate: 300
  });
});

test("maps normalized distribution rows into ECharts pie series", () => {
  const items = normalizeDistributionItems([
    { count: 8, key: "female", label: "女" },
    { count: 5, key: "male", label: "男" }
  ]);

  expect(createDistributionPieOption(items).series[0].data).toEqual([
    { name: "女", value: 8 },
    { name: "男", value: 5 }
  ]);
});
