import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test } from "vitest";
import { CountryPerformanceTable } from "./CountryPerformanceTable.jsx";

const countryItems = [
  createCountryRow({
    country: "阿富汗",
    flag: "🇦🇫",
    recharge_usd_minor: 50000,
    registrations: 10
  }),
  createCountryRow({
    country: "巴西",
    flag: "🇧🇷",
    recharge_usd_minor: 10000,
    registrations: 30
  }),
  createCountryRow({
    country: "中国",
    flag: "🇨🇳",
    recharge_usd_minor: 30000,
    registrations: 20
  })
];

test("sorts country table headers ascending and descending", async () => {
  const user = userEvent.setup();

  render(<CountryPerformanceTable gameRanking={[]} giftRanking={[]} items={countryItems} />);

  expect(firstCountryCell()).toHaveTextContent("阿富汗");

  await user.click(screen.getByRole("button", { name: /注册/ }));

  expect(screen.getByRole("columnheader", { name: /注册/ })).toHaveAttribute("aria-sort", "descending");
  expect(firstCountryCell()).toHaveTextContent("巴西");

  await user.click(screen.getByRole("button", { name: /注册/ }));

  expect(screen.getByRole("columnheader", { name: /注册/ })).toHaveAttribute("aria-sort", "ascending");
  expect(firstCountryCell()).toHaveTextContent("阿富汗");
});

function createCountryRow(overrides) {
  return {
    active_users: 0,
    arppu_usd_minor: 0,
    arpu_usd_minor: 0,
    avg_recharge_usd_minor: 0,
    country: "",
    flag: "",
    new_user_recharge_usd_minor: 0,
    paid_users: 0,
    payer_rate: 0,
    recharge_conversion_rate: 0,
    recharge_users: 0,
    recharge_usd_minor: 0,
    registrations: 0,
    trend_rate: 0,
    ...overrides
  };
}

function firstCountryCell() {
  const [, firstDataRow] = screen.getAllByRole("row");

  return within(firstDataRow).getAllByRole("cell")[1];
}
