import { expect, test, beforeEach, afterEach } from "vitest";
import { render, screen, act } from "@testing-library/react";
import { useTranslation } from "react-i18next";
import i18n from "./index";
import { useLocale } from "./use-locale";

beforeEach(async () => {
  await i18n.changeLanguage("en");
});

// Leave the shared i18n singleton on English so language-dependent assertions in
// other test files are never affected by this file's runtime switch to Swedish.
afterEach(async () => {
  await i18n.changeLanguage("en");
});

function Probe() {
  const { t } = useTranslation();
  const { setLocale } = useLocale();
  return (
    <div>
      <span data-testid="title">{t("objects.title")}</span>
      <button onClick={() => setLocale("sv")}>sv</button>
    </div>
  );
}

test("switches language at runtime", async () => {
  render(<Probe />);
  expect(screen.getByTestId("title")).toHaveTextContent("Objects");
  await act(async () => {
    screen.getByRole("button", { name: "sv" }).click();
  });
  expect(screen.getByTestId("title")).toHaveTextContent("Föremål");
});

test("syncs document.documentElement.lang on language change", async () => {
  await i18n.changeLanguage("sv");
  expect(document.documentElement.lang).toBe("sv");
  await i18n.changeLanguage("en");
  expect(document.documentElement.lang).toBe("en");
});
