import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, expect, test } from "vitest";
import { TimeZoneProvider, useTimeZone } from "@/app/timezone/TimeZoneProvider.jsx";
import { TimeRangeText, TimeText } from "@/shared/ui/TimeText.jsx";

const startMs = Date.UTC(2026, 4, 9, 19, 21, 0);
const endMs = Date.UTC(2026, 4, 9, 19, 22, 0);

beforeEach(() => {
  window.localStorage.clear();
});

test("renders single times and ranges using the selected admin timezone", async () => {
  const user = userEvent.setup();

  render(
    <TimeZoneProvider>
      <TimeTextFixture />
    </TimeZoneProvider>
  );

  expect(screen.getByTestId("single-time")).toHaveTextContent("2026-05-10 03:21:00");
  expect(screen.getByTestId("range-time")).toHaveTextContent("2026-05-10 03:21:00 - 2026-05-10 03:22:00");

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

  expect(screen.getByTestId("single-time")).toHaveTextContent("2026-05-09 19:21:00");
  expect(screen.getByTestId("single-time")).not.toHaveTextContent("UTC");
  expect(screen.getByTestId("range-time")).toHaveTextContent("2026-05-09 19:21:00 - 2026-05-09 19:22:00");
  expect(screen.getByTestId("range-time")).not.toHaveTextContent("UTC");
});

function TimeTextFixture() {
  const { setTimeZone } = useTimeZone();

  return (
    <>
      <button type="button" onClick={() => setTimeZone("UTC")}>
        UTC
      </button>
      <span data-testid="single-time">
        <TimeText value={startMs} />
      </span>
      <span data-testid="range-time">
        <TimeRangeText end={endMs} start={startMs} />
      </span>
    </>
  );
}
