// @vitest-environment jsdom

import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { WorkshopGrid } from "./WorkshopGrid";
import { WORKSHOPS } from "./workshops";

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

describe("WorkshopGrid", () => {
  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 renderGrid(onSelect: (slug: string) => void) {
    root = createRoot(container);
    act(() => {
      root!.render(<WorkshopGrid workshops={WORKSHOPS} onSelect={onSelect} />);
    });
  }

  it("renders one card per workshop (8 total for Phase 10)", () => {
    renderGrid(() => {});
    const cards = container.querySelectorAll("button[data-testid^='workshop-card-']");
    expect(cards.length).toBe(8);
  });

  it("renders the cards in canonical Phase 10 order", () => {
    renderGrid(() => {});
    const cards = Array.from(
      container.querySelectorAll("button[data-testid^='workshop-card-']"),
    );
    const slugs = cards.map((c) =>
      (c.getAttribute("data-testid") ?? "").replace("workshop-card-", ""),
    );
    expect(slugs).toEqual([
      "diagrams",
      "icons",
      "themes",
      "wallpapers",
      "documents",
      "brand-kits",
      "social",
      "convert",
    ]);
  });

  it("fires onSelect with the correct slug when a card is clicked", () => {
    const onSelect = vi.fn();
    renderGrid(onSelect);
    const convert = container.querySelector(
      "button[data-testid='workshop-card-convert']",
    ) as HTMLButtonElement;
    act(() => {
      convert.click();
    });
    expect(onSelect).toHaveBeenCalledWith("convert");
  });

  it("applies the responsive grid classes from §6.2", () => {
    renderGrid(() => {});
    const grid = container.querySelector("[data-testid='workshop-grid']") as HTMLElement;
    expect(grid.className).toContain("grid-cols-1");
    expect(grid.className).toContain("sm:grid-cols-2");
    expect(grid.className).toContain("lg:grid-cols-3");
  });

  it("exposes a list role with a descriptive aria-label", () => {
    renderGrid(() => {});
    const grid = container.querySelector("[role='list']") as HTMLElement;
    expect(grid.getAttribute("aria-label")).toBe("Studio workshops");
  });
});
