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

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

function layout(items: GridItem[]): GridLayout {
  return { lg: items }
}

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

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

  it("renders an empty-state when no items are configured", () => {
    const wrapper = mount(GridViewCard, { props: {} })
    expect(wrapper.find("[data-testid='grid-view-empty']").exists()).toBe(true)
  })

  it("renders one cell per GridItem", () => {
    const wrapper = mount(GridViewCard, {
      props: {
        gridLayout: layout([
          { i: "c1", x: 0, y: 0, w: 4, h: 2 },
          { i: "c2", x: 4, y: 0, w: 4, h: 2 },
          { i: "c3", x: 8, y: 0, w: 4, h: 2 },
        ]),
        cards: [
          makeChild("c1", "One"),
          makeChild("c2", "Two"),
          makeChild("c3", "Three"),
        ],
      },
    })
    expect(wrapper.findAll("[data-grid-item-id]")).toHaveLength(3)
  })

  it("positions each cell using gridColumn/gridRow inline styles", () => {
    const wrapper = mount(GridViewCard, {
      props: {
        gridLayout: layout([{ i: "c1", x: 2, y: 1, w: 3, h: 4 }]),
        cards: [makeChild("c1")],
      },
    })
    const cell = wrapper.find("[data-grid-item-id='c1']")
    const style = cell.attributes("style") ?? ""
    expect(style).toContain("grid-column: 3 / span 3")
    expect(style).toContain("grid-row: 2 / span 4")
  })

  it("uses cols.lg for the column count when set", () => {
    const wrapper = mount(GridViewCard, {
      props: {
        cols: { lg: 6 },
        gridLayout: layout([{ i: "c1", x: 0, y: 0, w: 6, h: 1 }]),
        cards: [makeChild("c1")],
      },
    })
    const container = wrapper.find("[data-testid='grid-view-container']")
    const style = container.attributes("style") ?? ""
    expect(style).toContain("grid-template-columns: repeat(6, minmax(0, 1fr))")
  })

  it("falls back through breakpoints when the highest-priority bp is empty", () => {
    const wrapper = mount(GridViewCard, {
      props: {
        gridLayout: { xs: [{ i: "only", x: 0, y: 0, w: 2, h: 1 }] },
        cards: [makeChild("only")],
      },
    })
    expect(wrapper.find("[data-grid-item-id='only']").exists()).toBe(true)
  })
})
