import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { ExternalI18nProvider } from "../i18n/ExternalI18nProvider.jsx";
import { EXTERNAL_LOCALE_STORAGE_KEY } from "../i18n/messages.js";
import { ExternalAdminLayout } from "./ExternalAdminLayout.jsx";

const auth = vi.hoisted(() => ({
  logout: vi.fn(),
  session: {
    account: "fami-manager",
    appCode: "fami",
    appName: "Fami",
    capabilities: ["user:list", "room:list"]
  }
}));
const viewport = vi.hoisted(() => ({ mobile: false }));

vi.mock("../auth/ExternalAuthProvider.jsx", () => ({ useExternalAuth: () => auth }));
vi.mock("@mui/material/useMediaQuery", () => ({ default: () => viewport.mobile }));

describe("ExternalAdminLayout RTL", () => {
  beforeEach(() => {
    localStorage.setItem(EXTERNAL_LOCALE_STORAGE_KEY, "ar");
    viewport.mobile = false;
  });

  test("opens the mobile navigation from the right in Arabic", async () => {
    const user = userEvent.setup();
    viewport.mobile = true;
    renderLayout();

    await user.click(screen.getByRole("button", { name: "فتح القائمة" }));

    const openTemporaryDrawer = Array.from(document.querySelectorAll(".MuiDrawer-paper")).find((node) => node.closest(".MuiModal-root"));
    expect(openTemporaryDrawer).toBeInTheDocument();
    expect(openTemporaryDrawer.parentElement).not.toHaveStyle({ visibility: "hidden" });
    expect(screen.getAllByRole("link", { name: "ملخص الصلاحيات" }).length).toBeGreaterThan(0);
  });

  test("places the desktop navigation drawer on the right for Arabic", () => {
    renderLayout();

    expect(document.documentElement).toHaveAttribute("dir", "rtl");
    expect(document.documentElement).toHaveAttribute("lang", "ar");
    const permanentDrawer = document.querySelectorAll(".MuiDrawer-paper")[0];
    const generatedClass = Array.from(permanentDrawer.classList).find((className) => className.startsWith("css-"));
    const drawerRule = Array.from(document.styleSheets)
      .flatMap((sheet) => Array.from(sheet.cssRules || []))
      .map((rule) => rule.cssText)
      .find((cssText) => cssText.includes(`.${generatedClass}`));
    expect(drawerRule).toContain("right: 0px");
    expect(drawerRule).toContain("border-left:");
    expect(screen.getAllByText("ملخص الصلاحيات").length).toBeGreaterThan(0);
    expect(screen.getByRole("combobox", { name: "اللغة" })).toHaveTextContent("العربية");
  });
});

function renderLayout() {
  return render(
    <ExternalI18nProvider>
      <MemoryRouter initialEntries={["/overview"]}>
        <Routes>
          <Route element={<ExternalAdminLayout />}>
            <Route element={<div>overview content</div>} path="/overview" />
          </Route>
        </Routes>
      </MemoryRouter>
    </ExternalI18nProvider>
  );
}
