/* @vitest-environment jsdom */

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

import { ChatActionCard } from "../chat-action-card";

describe("ChatActionCard", () => {
  let container: HTMLDivElement;
  let root: Root;

  beforeEach(() => {
    (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
      .IS_REACT_ACT_ENVIRONMENT = true;
    container = document.createElement("div");
    document.body.append(container);
    root = createRoot(container);
  });

  afterEach(() => {
    act(() => root.unmount());
    container.remove();
  });

  it("reports one view, opens the action and can be dismissed", async () => {
    const onViewed = vi.fn();
    const onActivate = vi.fn(async () => undefined);
    const onDismiss = vi.fn();
    const action = {
      actionId: "action-1",
      kind: "support" as const,
      type: "openFeedback" as const,
      copy: "Share the screenshot and approximate payment time here.",
      ctaLabel: "Open Feedback",
      ruleId: null,
      orderId: null,
    };

    await act(async () => {
      root.render(
        <ChatActionCard
          action={action}
          onViewed={onViewed}
          onActivate={onActivate}
          onDismiss={onDismiss}
        />,
      );
    });
    expect(onViewed).toHaveBeenCalledTimes(1);
    expect(container.querySelector("[data-chat-action='openFeedback']"))
      .not.toBeNull();

    const openButton = Array.from(container.querySelectorAll("button")).find(
      (button) => button.textContent?.includes("Open Feedback"),
    );
    await act(async () => openButton?.click());
    expect(onActivate).toHaveBeenCalledWith(action);

    const dismissButton = container.querySelector<HTMLButtonElement>(
      'button[aria-label="Dismiss"]',
    );
    act(() => dismissButton?.click());
    expect(onDismiss).toHaveBeenCalledWith(action);
    expect(container.innerHTML).toBe("");
  });
});
