import { beforeEach, describe, expect, it } from "vitest"
import { flushPromises, mount } from "@vue/test-utils"
import { createPinia, setActivePinia } from "pinia"
import type { DisplayCard } from "@/definitions/cards"
import CardListCard from "./CardListCard.vue"
import { preloadCard } from "@/engine/useCardLoader"

function makeChild(id: string, title?: string): DisplayCard {
  return {
    id,
    cardType: "element-list",
    elementList: [],
    title,
  } as unknown as DisplayCard
}

describe("CardListCard", () => {
  beforeEach(async () => {
    setActivePinia(createPinia())
    await preloadCard("element-list")
  })

  it("mounts without error", () => {
    const wrapper = mount(CardListCard, { props: {} })
    expect(wrapper.exists()).toBe(true)
  })

  it("renders an empty-state message when no cards are passed", () => {
    const wrapper = mount(CardListCard, { props: {} })
    expect(
      wrapper.find("[data-testid='card-list-empty']").exists(),
    ).toBe(true)
  })

  it("renders one CardRenderer per resolved child card", async () => {
    const wrapper = mount(CardListCard, {
      props: {
        cards: [
          makeChild("c1", "Child One"),
          makeChild("c2", "Child Two"),
          makeChild("c3", "Child Three"),
        ],
      },
    })
    await flushPromises()
    expect(wrapper.findAll("[data-card-list-item-id]")).toHaveLength(3)
    expect(wrapper.find("[data-card-list-item-id='c1']").exists()).toBe(true)
    expect(wrapper.find("[data-card-list-item-id='c2']").exists()).toBe(true)
    expect(wrapper.find("[data-card-list-item-id='c3']").exists()).toBe(true)
  })

  it("renders title and subtitle when provided", () => {
    const wrapper = mount(CardListCard, {
      props: { title: "My Title", subtitle: "My subtitle" },
    })
    expect(wrapper.text()).toContain("My Title")
    expect(wrapper.text()).toContain("My subtitle")
  })

  it("marks items as draggable when draggable is true", () => {
    const wrapper = mount(CardListCard, {
      props: {
        cards: [makeChild("c1")],
        draggable: true,
      },
    })
    const item = wrapper.find("[data-card-list-item-id='c1']")
    expect(item.attributes("draggable")).toBe("true")
  })

  it("does not mark items draggable when draggable is false", () => {
    const wrapper = mount(CardListCard, {
      props: {
        cards: [makeChild("c1")],
        draggable: false,
      },
    })
    const item = wrapper.find("[data-card-list-item-id='c1']")
    expect(item.attributes("draggable")).toBe("false")
  })

  it("hides the chrome when showCard is false", () => {
    const wrapper = mount(CardListCard, {
      props: { showCard: false, title: "Plain" },
    })
    const root = wrapper.find(".gxp-card-list")
    expect(root.exists()).toBe(true)
    expect(root.classes()).not.toContain("border")
  })
})
