import { afterEach, expect, test } from "vitest";
import { render } from "@testing-library/react";
import "../i18n";
import { ConfigProvider } from "../config/config-provider";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useDocumentTitle } from "./use-document-title";

function Titled({ page }: { page: string }) {
  useDocumentTitle(page);
  return null;
}

function wrap(ui: React.ReactElement) {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return render(
    <QueryClientProvider client={qc}>
      <ConfigProvider>{ui}</ConfigProvider>
    </QueryClientProvider>,
  );
}

afterEach(() => {
  document.title = "";
});

test("sets document.title to '{page} | {app_name}'", () => {
  wrap(<Titled page="Objects" />);
  expect(document.title).toMatch(/^Objects \| .+/);
});

test("restores the previous title on unmount", () => {
  document.title = "Prev";
  const { unmount } = wrap(<Titled page="Objects" />);
  expect(document.title).toMatch(/^Objects \| /);
  unmount();
  expect(document.title).toBe("Prev");
});
