import type { ReactElement } from "react";
import { render } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { I18nProvider } from "../i18n";
import { ThemeProvider } from "../theme";
import type { Locale } from "../copy";

interface RenderWithProvidersOptions {
  route?: string;
  locale?: Locale;
}

export function renderWithProviders(
  ui: ReactElement,
  { route = "/", locale = "zh-CN" }: RenderWithProvidersOptions = {},
) {
  const wrap = (element: ReactElement) => (
    <I18nProvider initialLocale={locale} persist={false}>
      <ThemeProvider>
        <MemoryRouter initialEntries={[route]}>{element}</MemoryRouter>
      </ThemeProvider>
    </I18nProvider>
  );

  const view = render(wrap(ui));

  return {
    ...view,
    rerender: (nextUi: ReactElement) => view.rerender(wrap(nextUi)),
  };
}
