import React from "react";
import "@testing-library/jest-dom";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";

import { api } from "./api";
import { I18nProvider, useI18n } from "./i18n/I18nProvider";

function Probe() {
  const { language, setLanguage, hydrateLanguage, t } = useI18n();
  return (
    <div>
      <output aria-label="language">{language}</output>
      <output aria-label="settings-label">{t("settings")}</output>
      <button onClick={() => setLanguage("en")}>English</button>
      <button onClick={() => setLanguage("nb")}>Norsk</button>
      <button onClick={() => hydrateLanguage("nb-NO")}>Restore server preference</button>
    </div>
  );
}

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

test("migrates the legacy Norwegian code and persists Bokmål using nb-NO", async () => {
  window.localStorage.setItem("uiLanguage", "no");
  render(<I18nProvider><Probe /></I18nProvider>);

  expect(screen.getByLabelText("language")).toHaveTextContent("nb");
  expect(screen.getByLabelText("settings-label")).toHaveTextContent("Innstillinger");
  expect(document.documentElement.lang).toBe("nb-NO");

  fireEvent.click(screen.getByRole("button", { name: "English" }));
  expect(screen.getByLabelText("settings-label")).toHaveTextContent("Settings");
  await waitFor(() => expect(api.put).toHaveBeenCalledWith("/auth/preferences/language", { language: "en" }));
});

test("hydrates an authenticated server preference without writing it back", () => {
  render(<I18nProvider><Probe /></I18nProvider>);
  fireEvent.click(screen.getByRole("button", { name: /Restore server preference/i }));

  expect(screen.getByLabelText("language")).toHaveTextContent("nb");
  expect(window.localStorage.getItem("uiLanguage")).toBe("nb");
  expect(api.put).not.toHaveBeenCalled();
});
