import { CacheProvider } from "@emotion/react";
import styled from "@emotion/styled";
import rtlPlugin from "@mui/stylis-plugin-rtl";
import { render } from "@testing-library/react";
import { createElement } from "react";
import { compile, middleware, serialize, stringify } from "stylis";
import { describe, expect, test } from "vitest";
import { externalEmotionCache } from "./emotionCache.js";

describe("external admin RTL Emotion cache", () => {
  test("uses isolated LTR and RTL caches", () => {
    expect(externalEmotionCache("ltr").key).toBe("external-ltr");
    expect(externalEmotionCache("rtl").key).toBe("external-rtl");
    expect(externalEmotionCache("rtl")).not.toBe(externalEmotionCache("ltr"));
  });

  test("mirrors physical MUI-style declarations for Arabic", () => {
    const css = serialize(
      compile(".control{margin-left:8px;padding-right:12px;text-align:left}"),
      middleware([rtlPlugin, stringify])
    );

    expect(css).toContain("margin-right:8px");
    expect(css).toContain("padding-left:12px");
    expect(css).toContain("text-align:right");
    expect(css).not.toContain("margin-left:8px");
  });

  test("inserts ::placeholder rules through the RTL cache without crashing", () => {
    // Regression: the standalone stylis 4.4 prefixer crashed in lift() when Emotion's
    // bundled stylis 4.2 compiled a ::placeholder rule, unmounting the whole app in Arabic.
    const Input = styled.input({ "&::placeholder": { color: "red", textAlign: "left" } });

    expect(() => render(
      createElement(CacheProvider, { value: externalEmotionCache("rtl") },
        createElement(Input, { placeholder: "مثال" }))
    )).not.toThrow();
  });
});
