import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
import { TopCountriesPieChart } from "../TopCountriesPieChart";
import * as chartTheme from "../../utils/chartTheme";

vi.mock("recharts", () => ({
  ResponsiveContainer: ({ children }: { children: React.ReactNode }) => (
    <div>{children}</div>
  ),
  PieChart: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="pie-chart">{children}</div>
  ),
  Pie: () => null,
  Cell: () => null,
  Tooltip: () => null,
  Legend: () => null,
}));

function wrap(ui: React.ReactElement) {
  return render(
    <FluentProvider theme={webLightTheme}>{ui}</FluentProvider>,
  );
}

describe("TopCountriesPieChart", () => {
  it("shows empty state when countries is empty", () => {
    wrap(<TopCountriesPieChart countries={{}} countryNames={{}} />);
    expect(screen.getByText("No bans in this time range.")).toBeInTheDocument();
    expect(screen.queryByTestId("pie-chart")).not.toBeInTheDocument();
  });

  it("renders pie chart when country data is provided", () => {
    wrap(
      <TopCountriesPieChart
        countries={{ DE: 30, US: 20, CN: 10 }}
        countryNames={{ DE: "Germany", US: "United States", CN: "China" }}
      />,
    );
    expect(screen.getByTestId("pie-chart")).toBeInTheDocument();
  });

  it("memoizes palette token resolution across rerenders", () => {
    const spy = vi.spyOn(chartTheme, "resolveFluentToken");
    const props = {
      countries: { DE: 30, US: 20, CN: 10 },
      countryNames: { DE: "Germany", US: "United States", CN: "China" },
    };

    const { rerender } = wrap(<TopCountriesPieChart {...props} />);
    expect(spy).toHaveBeenCalledTimes(5);

    rerender(
      <FluentProvider theme={webLightTheme}>
        <TopCountriesPieChart {...props} />
      </FluentProvider>,
    );
    expect(spy).toHaveBeenCalledTimes(5);

    spy.mockRestore();
  });
});
