import { expect, test, beforeEach } from "vitest";
import { screen, waitFor, render } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import i18n, { LOCALE_KEY } from "../i18n";
import { ConfigProvider } from "./config-provider";
import { useConfig } from "./config-context";

function Probe() {
  const config = useConfig();
  return <span data-testid="lang">{config.default_language}</span>;
}

function renderProvider() {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return render(
    <QueryClientProvider client={qc}>
      <ConfigProvider><Probe /></ConfigProvider>
    </QueryClientProvider>,
  );
}

beforeEach(() => {
  localStorage.clear();
  void i18n.changeLanguage("en");
});

test("exposes config and applies default language when no stored preference", async () => {
  renderProvider();
  expect(await screen.findByTestId("lang")).toHaveTextContent("sv");
  await waitFor(() => expect(i18n.language).toBe("sv"));
});

test("a stored locale preference wins over the instance default", async () => {
  localStorage.setItem(LOCALE_KEY, "en");
  void i18n.changeLanguage("en");
  renderProvider();
  await screen.findByTestId("lang");
  await waitFor(() => expect(i18n.language).toBe("en"));
});
