// @vitest-environment jsdom
// SPEC: PJ2026-010405 云端控制台.
// Implementation reference: draft-2026-07-13-p0-cloud-console.
// Responsibility: 验证资源集合的统一 item 合同、激活事件与 list/listitem 无障碍语义。

import { mount } from "@vue/test-utils";
import { h } from "vue";
import { describe, expect, test, vi } from "vitest";
import ResourceCollection from "./ResourceCollection.vue";
import EntityCard from "./EntityCard.vue";

describe("ResourceCollection", () => {
  test("forwards EntityCard activation", async () => {
    const onSelect = vi.fn();
    const card = mount(EntityCard, { props: { title: "Node A", onSelect } });
    expect(card.get(".entity-card").attributes("role")).toBe("button");
    expect(card.get(".entity-card").attributes("aria-pressed")).toBe("false");
    await card.get(".entity-card").trigger("click");
    expect(onSelect).toHaveBeenCalledOnce();
  });

  test("keeps card/list modes on one item contract", async () => {
    const onView = vi.fn();
    const items = [
      { id: "node-a", title: "Node A", status: "ready" },
      { id: "node-b", title: "Node B", status: "blocked" }
    ];
    const wrapper = mount(ResourceCollection, {
      props: {
        items,
        itemKey: (item: object) => (item as { id: string }).id,
        itemTitle: (item: object) => (item as { title: string }).title,
        itemStatus: (item: object) => (item as { status: string }).status,
        selectedId: "node-a",
        "onUpdate:view": onView
      }
    });

    expect(wrapper.findAll(".entity-card")).toHaveLength(2);
    expect(wrapper.get(".entity-card").attributes("data-selected")).toBe("true");
    expect(wrapper.get(".resource-collection-items").attributes("role")).toBe("list");
    expect(wrapper.findAll(".resource-collection-item[role='listitem']")).toHaveLength(2);
    expect(wrapper.get(".entity-card").attributes("role")).toBe("button");
    expect(wrapper.get(".entity-card").attributes("aria-pressed")).toBe("true");

    const listButton = wrapper.findAll(".view-mode-switch button").find((button) => button.attributes("aria-label") === "列表");
    expect(listButton).toBeDefined();
    await listButton?.trigger("click");
    expect(onView).toHaveBeenCalledWith("list");
  });

  test("forwards the typed item through the card slot selection contract", async () => {
    const items = [{ id: "node-a", title: "Node A" }];
    const onSelect = vi.fn();
    const wrapper = mount(ResourceCollection, {
      props: {
        items,
        itemKey: (item: object) => (item as { id: string }).id,
        onSelect
      },
      slots: {
        card: ({ item, select }: { item: object; selected: boolean; select: () => void }) =>
          h("button", { class: "select-item", onClick: select }, (item as { title: string }).title)
      }
    });

    await wrapper.get(".select-item").trigger("click");
    expect(onSelect).toHaveBeenCalledWith(items[0]);
  });
});
