// @vitest-environment jsdom

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

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

describe("CmdKButton", () => {
  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 renderButton() {
    root = createRoot(container);
    act(() => {
      root!.render(<CmdKButton />);
    });
    return {
      getButton: () => container.querySelector("button[aria-label='Open command palette']") as HTMLButtonElement,
      getKbd: () => container.querySelector("kbd")?.textContent?.trim(),
    };
  }

  it("renders a button with the ⌘K kbd glyph", () => {
    const { getButton, getKbd } = renderButton();
    expect(getButton()).not.toBeNull();
    expect(getKbd()).toBe("⌘K");
  });

  it("dispatches a Meta+K keydown on document when clicked", () => {
    const listener = vi.fn();
    document.addEventListener("keydown", listener);

    const { getButton } = renderButton();
    act(() => {
      getButton().click();
    });

    expect(listener).toHaveBeenCalledTimes(1);
    const event = listener.mock.calls[0]![0] as KeyboardEvent;
    expect(event.key).toBe("k");
    expect(event.metaKey).toBe(true);

    document.removeEventListener("keydown", listener);
  });
});
