import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, test } from "vitest";
import { ExternalI18nProvider, useExternalI18n } from "./ExternalI18nProvider.jsx";
import { EXTERNAL_LOCALE_STORAGE_KEY } from "./messages.js";

describe("ExternalI18nProvider", () => {
  beforeEach(() => {
    localStorage.removeItem(EXTERNAL_LOCALE_STORAGE_KEY);
    document.documentElement.lang = "";
    document.documentElement.dir = "";
  });

  test("defaults to English instead of the browser locale", () => {
    Object.defineProperty(navigator, "language", { configurable: true, value: "zh-CN" });
    render(<ExternalI18nProvider><LocaleProbe /></ExternalI18nProvider>);

    expect(screen.getByTestId("locale")).toHaveTextContent("en");
    expect(screen.getByTestId("title")).toHaveTextContent("HYApp External Admin");
    expect(document.documentElement).toHaveAttribute("lang", "en");
    expect(document.documentElement).toHaveAttribute("dir", "ltr");
  });

  test("supports and persists Chinese, Arabic RTL and Turkish", async () => {
    const user = userEvent.setup();
    const firstRender = render(<ExternalI18nProvider><LocaleProbe /></ExternalI18nProvider>);

    await user.click(screen.getByRole("button", { name: "ar" }));
    expect(screen.getByTestId("title")).toHaveTextContent("إدارة HYApp الخارجية");
    expect(document.documentElement).toHaveAttribute("lang", "ar");
    expect(document.documentElement).toHaveAttribute("dir", "rtl");
    expect(document.body).toHaveAttribute("dir", "rtl");
    expect(localStorage.getItem(EXTERNAL_LOCALE_STORAGE_KEY)).toBe("ar");

    await user.click(screen.getByRole("button", { name: "tr" }));
    expect(screen.getByTestId("title")).toHaveTextContent("HYApp Harici Yönetim");
    expect(document.documentElement).toHaveAttribute("lang", "tr");
    expect(document.documentElement).toHaveAttribute("dir", "ltr");

    await user.click(screen.getByRole("button", { name: "zh-CN" }));
    expect(screen.getByTestId("title")).toHaveTextContent("HYApp 外管后台");
    expect(localStorage.getItem(EXTERNAL_LOCALE_STORAGE_KEY)).toBe("zh-CN");

    firstRender.unmount();
    render(<ExternalI18nProvider><LocaleProbe /></ExternalI18nProvider>);
    expect(screen.getByTestId("locale")).toHaveTextContent("zh-CN");
    expect(screen.getByTestId("title")).toHaveTextContent("HYApp 外管后台");
  });
});

function LocaleProbe() {
  const { locale, setLocale, t } = useExternalI18n();
  return (
    <div>
      <span data-testid="locale">{locale}</span>
      <span data-testid="title">{t("app.title")}</span>
      {["zh-CN", "ar", "tr"].map((value) => <button key={value} type="button" onClick={() => setLocale(value)}>{value}</button>)}
    </div>
  );
}
