import { beforeEach, describe, expect, it } from "vitest"
import { flushPromises, mount } from "@vue/test-utils"
import { defineComponent, h, Suspense } from "vue"
import { createPinia, setActivePinia } from "pinia"
import type { CardElement } from "@/definitions/elements"
import { __clearElementCache, preloadElement } from "@/engine/useElementLoader"
import ElementsBlock from "./ElementsBlock.vue"

function mountWithSuspense(props: Record<string, unknown>) {
  const Host = defineComponent({
    setup() {
      return () =>
        h(Suspense, null, {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          default: () => h(ElementsBlock as any, props),
        })
    },
  })
  return mount(Host)
}

describe("ElementsBlock", () => {
  beforeEach(() => {
    setActivePinia(createPinia())
    __clearElementCache()
  })

  it("renders the empty state placeholder when no children are provided", () => {
    const wrapper = mount(ElementsBlock)
    expect(wrapper.text()).toContain("No elements configured.")
  })

  it("renders the default label", () => {
    const wrapper = mount(ElementsBlock)
    expect(wrapper.text()).toContain("Elements Block")
  })

  it("renders the label prop when provided", () => {
    const wrapper = mount(ElementsBlock, { props: { label: "General settings" } })
    expect(wrapper.text()).toContain("General settings")
  })

  it("renders nested child elements when nestedElements contains them", async () => {
    await preloadElement("input.text")
    const nestedElements: CardElement[] = [
      {
        id: "child-1",
        type: "input.text",
        name: "first_name",
        label: "First name",
      } as CardElement,
    ]
    const wrapper = mountWithSuspense({
      label: "Profile",
      nestedElements,
    })
    await flushPromises()
    expect(wrapper.text()).toContain("First name")
    expect(wrapper.find("input").exists()).toBe(true)
  })
})
