import { cleanup, render, screen } from "@testing-library/react";
import assert from "node:assert";
import {
  afterEach,
  beforeEach,
  describe,
  test,
} from "node:test";
import { constants } from "../../constants";
import { Localisation } from "../../plugins/localisation";
import { Locale } from "./index";

describe("Locale", () => {
  let prevLocalisationInstance: typeof Localisation.instance;

  beforeEach(() => {
    prevLocalisationInstance = Localisation.instance;
    Localisation.instance = {} as unknown as Localisation;
  });

  afterEach(() => {
    cleanup();
    Localisation.instance = prevLocalisationInstance;
  });

  test("renders fallback children in SSR mode and keeps locale config attr", () => {
    render(
      <constants.globalCtx value={{ isSSR: true, mode: "SSR" }}>
        <Locale code={"forms.invalidInput"}>
          <span>Fallback text</span>
        </Locale>
      </constants.globalCtx>
    );

    const node = document.querySelector("ins[data-js-locale]");
    assert.notStrictEqual(node, null);
    assert.strictEqual(node?.getAttribute("data-js-locale")?.includes("forms.invalidInput"), true);
    assert.notStrictEqual(screen.queryByText("Fallback text"), null);
    assert.strictEqual(node?.classList.contains(constants.stateClasses.translationLoading), true);
  });

  test("renders static container in SSG mode", () => {
    render(
      <constants.globalCtx value={{ isSSR: false, mode: "SSG" }}>
        <Locale code={"forms.invalidInput"}>
          <span>SSG locale content</span>
        </Locale>
      </constants.globalCtx>
    );

    const staticNode = document.querySelector("ins.locale[data-js-locale]");
    assert.notStrictEqual(staticNode, null);
    assert.strictEqual(staticNode?.getAttribute("data-js-locale")?.includes("forms.invalidInput"), true);
    assert.notStrictEqual(screen.queryByText("SSG locale content"), null);
  });
});
