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

const noop = vi.fn();

test("switches to end time after selecting a start date", async () => {
  const user = userEvent.setup();

  render(
    <DatabiHeader
      appCode="lalu"
      appOptions={[{ code: "lalu", label: "Lalu", value: "lalu" }]}
      countryId={0}
      onAppChange={noop}
      onCountryChange={noop}
      onRangeChange={noop}
      onRegionChange={noop}
      onTimeZoneChange={noop}
      range={{ end: "2026-06-08", endTime: "23:59:59", start: "2026-06-08", startTime: "00:00:00" }}
      regionId="all"
      timeZone="UTC"
    />
  );

  await user.click(screen.getByRole("button", { name: /2026-06-08\s*~\s*2026-06-08/ }));

  const dialog = screen.getByRole("dialog");
  const calendar = dialog.querySelector(".calendar-pane");
  expect(within(dialog).getByRole("tab", { name: /开始时间/ })).toHaveAttribute("aria-selected", "true");

  await user.click(within(calendar).getByRole("button", { name: "22" }));

  expect(within(dialog).getByRole("tab", { name: /结束时间/ })).toHaveAttribute("aria-selected", "true");
});

test("selects all apps from app filter", async () => {
  const user = userEvent.setup();
  const onAppChange = vi.fn();

  render(
    <DatabiHeader
      appCode="lalu"
      appOptions={[
        { code: "", label: "全部", value: "" },
        { code: "lalu", label: "Lalu", value: "lalu" },
        { code: "aslan", label: "Aslan", value: "aslan" },
        { code: "yumi", label: "Yumi", value: "yumi" }
      ]}
      countryId={0}
      onAppChange={onAppChange}
      onCountryChange={noop}
      onRangeChange={noop}
      onRegionChange={noop}
      onTimeZoneChange={noop}
      range={{ end: "2026-06-08", endTime: "23:59:59", start: "2026-06-08", startTime: "00:00:00" }}
      regionId="all"
      timeZone="UTC"
    />
  );

  await user.click(screen.getByRole("button", { name: /App\s*Lalu/ }));
  await user.click(within(screen.getByRole("listbox")).getByRole("option", { name: "全部" }));

  expect(onAppChange).toHaveBeenCalledWith("");
});
