import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { ActionsControl } from "@repo/ui";
import { afterEach, describe, expect, it, vi } from "vitest";

afterEach(() => {
  cleanup();
});

describe("ActionsControl async item state", () => {
  it("loads and disables only the keyed action while keeping siblings usable", () => {
    const onAction = vi.fn();

    render(
      <ActionsControl
        actions={[
          { label: "Fix model", value: "model.fix" },
          { label: "Inspect", value: "inspect" },
        ]}
        actionStates={{
          "model.fix": { loading: true, loadingAriaLabel: "Optimizing model" },
        }}
        name="Model actions"
        onAction={onAction}
        showLabel={false}
      />,
    );

    const loadingAction = screen.getByRole("button", { name: "Optimizing model" });
    const siblingAction = screen.getByRole("button", { name: "Inspect" });

    expect((loadingAction as HTMLButtonElement).disabled).toBe(true);
    expect(loadingAction.getAttribute("aria-busy")).toBe("true");
    expect((siblingAction as HTMLButtonElement).disabled).toBe(false);

    fireEvent.click(siblingAction);

    expect(onAction).toHaveBeenCalledTimes(1);
    expect(onAction).toHaveBeenCalledWith("inspect");
  });

  it("keeps the action name accessible when loading copy is omitted", () => {
    render(
      <ActionsControl
        actions={[{ label: "Fix model", value: "model.fix" }]}
        actionStates={{
          "model.fix": { loading: true },
        }}
        name="Model actions"
        showLabel={false}
      />,
    );

    expect(
      screen
        .getByRole("button", { name: "Fix model" })
        .getAttribute("aria-busy"),
    ).toBe("true");
  });
});
