// @vitest-environment jsdom

import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { MemoryRouter } from "@/lib/router";
import { ModeBreadcrumb, deriveBreadcrumbSegments } from "./ModeBreadcrumb";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;

// Match the pattern from IconRail.test.tsx — @/lib/router Link calls
// useCompany() internally, so we stub CompanyContext for isolated testing.
vi.mock("@/context/CompanyContext", () => ({
  useCompany: () => ({
    companies: [],
    selectedCompany: null,
    selectedCompanyId: null,
    setSelectedCompanyId: () => {},
    selectionSource: null,
    loading: false,
  }),
}));

describe("deriveBreadcrumbSegments", () => {
  it.each([
    ["/NEX/assistant", ["ASSISTANT"]],
    ["/NEX/assistant/conv-abc", ["ASSISTANT"]],
    ["/NEX/content-studio", ["STUDIO"]],
    ["/NEX/content-studio/diagrams", ["STUDIO", "DIAGRAMS"]],
    ["/NEX/convert", ["STUDIO", "CONVERT"]],
    ["/NEX/convert/pdf/docx", ["STUDIO", "CONVERT"]],
    ["/NEX/projects", ["PROJECTS"]],
    ["/NEX/projects/nexus-design", ["PROJECTS", "NEXUS-DESIGN"]],
    ["/NEX/issues", ["PROJECTS"]],
    ["/NEX/issues/NEX-42", ["PROJECTS", "NEX-42"]],
    ["/NEX/agents", ["PROJECTS"]],
    ["/NEX/routines", ["PROJECTS"]],
    ["/instance/settings/general", ["SETTINGS"]],
    ["/instance/settings/integrations", ["SETTINGS", "INTEGRATIONS"]],
    ["/instance/settings", ["SETTINGS"]],
    ["/instance/settings-foo", ["HOME"]],
    ["/instance/settings-foo/bar", ["HOME"]],
    ["/", ["HOME"]],
    ["/unknown/path", ["HOME"]],
  ])("maps %s to %o", (input, expected) => {
    expect(deriveBreadcrumbSegments(input as string)).toEqual(expected);
  });
});

describe("ModeBreadcrumb (rendered)", () => {
  let container: HTMLDivElement;
  let root: ReturnType<typeof createRoot> | null = null;

  beforeEach(() => {
    container = document.createElement("div");
    document.body.appendChild(container);
    root = null;
  });

  afterEach(() => {
    if (root) {
      act(() => {
        root!.unmount();
      });
      root = null;
    }
    if (container.parentNode) container.remove();
  });

  function renderCrumb(pathname: string) {
    root = createRoot(container);
    act(() => {
      root!.render(
        <MemoryRouter initialEntries={[pathname]}>
          <ModeBreadcrumb />
        </MemoryRouter>,
      );
    });
    return {
      getRoot: () => container.querySelector("[data-testid='mode-breadcrumb']") as HTMLElement | null,
      getSegments: () =>
        Array.from(container.querySelectorAll("[data-testid='mode-breadcrumb-segment']")).map(
          (el) => el.textContent?.trim() ?? "",
        ),
      getSeparators: () =>
        container.querySelectorAll("[data-testid='mode-breadcrumb-sep']").length,
    };
  }

  it("renders a single ASSISTANT segment and no separator", () => {
    const { getSegments, getSeparators } = renderCrumb("/NEX/assistant");
    expect(getSegments()).toEqual(["ASSISTANT"]);
    expect(getSeparators()).toBe(0);
  });

  it("renders two segments with one separator for /NEX/content-studio/diagrams", () => {
    const { getSegments, getSeparators } = renderCrumb("/NEX/content-studio/diagrams");
    expect(getSegments()).toEqual(["STUDIO", "DIAGRAMS"]);
    expect(getSeparators()).toBe(1);
  });

  it("renders PROJECTS / NEX-42 for /NEX/issues/NEX-42", () => {
    const { getSegments } = renderCrumb("/NEX/issues/NEX-42");
    expect(getSegments()).toEqual(["PROJECTS", "NEX-42"]);
  });
});
