import { CacheProvider } from "@emotion/react";
import Button from "@mui/material/Button";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import { render, screen } from "@testing-library/react";
import { expect, test } from "vitest";
import { externalEmotionCache } from "./emotionCache.js";

test("keeps MUI mounted when the live page switches from LTR to RTL", () => {
  const view = render(<DirectionProbe direction="ltr" />);
  expect(screen.getByRole("button", { name: "ltr" })).toBeInTheDocument();

  // Exercise Emotion's real insert pipeline: a standalone Stylis serializer test cannot detect a plugin resolved from a second, incompatible Stylis version.
  expect(() => view.rerender(<DirectionProbe direction="rtl" />)).not.toThrow();
  expect(screen.getByRole("button", { name: "rtl" })).toBeInTheDocument();
});

function DirectionProbe({ direction }) {
  return (
    <CacheProvider value={externalEmotionCache(direction)}>
      <ThemeProvider theme={createTheme({ direction })}>
        <Button sx={{ marginLeft: 1, paddingRight: 2 }}>{direction}</Button>
      </ThemeProvider>
    </CacheProvider>
  );
}
