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

const roots: Root[] = [];

afterEach(() => {
  for (const root of roots.splice(0)) {
    act(() => {
      root.unmount();
    });
  }
  vi.restoreAllMocks();
  delete (navigator as Navigator & { clipboard?: unknown }).clipboard;
  Object.defineProperty(window, "isSecureContext", {
    value: false,
    configurable: true,
  });
  document.body.innerHTML = "";
});

function renderAllowedTenantBadge() {
  const container = document.createElement("div");
  document.body.appendChild(container);
  const root = createRoot(container);
  roots.push(root);

  act(() => {
    root.render(
      <AllowedTenantBadge
        tenant={{
          id: "11111111-2222-3333-4444-555555555555",
          name: "한맥기술",
          slug: "hanmac",
        }}
        onRemove={vi.fn()}
      />,
    );
  });

  return container;
}

describe("AllowedTenantBadge", () => {
  it("renders tenant name, slug, full UUID, and copies the UUID", async () => {
    const writeText = vi.fn().mockResolvedValue(undefined);
    Object.defineProperty(navigator, "clipboard", {
      value: { writeText },
      configurable: true,
    });
    Object.defineProperty(window, "isSecureContext", {
      value: true,
      configurable: true,
    });

    const container = renderAllowedTenantBadge();
    const badge = container.querySelector(
      '[data-testid="allowed-tenant-11111111-2222-3333-4444-555555555555"]',
    );

    expect(container.textContent).toContain("한맥기술");
    expect(container.textContent).toContain("hanmac");
    expect(container.textContent).toContain(
      "11111111-2222-3333-4444-555555555555",
    );
    expect(badge).not.toBeNull();

    const copyButton = container.querySelector(
      '[data-testid="allowed-tenant-copy-11111111-2222-3333-4444-555555555555"]',
    );
    expect(copyButton).not.toBeNull();

    await act(async () => {
      copyButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
    });

    expect(writeText).toHaveBeenCalledWith(
      "11111111-2222-3333-4444-555555555555",
    );
  });
});
