import { describe, expect, it } from "vitest"
import { mount } from "@vue/test-utils"
import ButtonGroupAction, {
  type ButtonGroupItem,
} from "./ButtonGroupAction.vue"

const baseItems: ButtonGroupItem[] = [
  { label: "Edit", emit: "edit" },
  { label: "Delete", variant: "destructive", emit: "delete" },
]

describe("ButtonGroupAction (props-based composition)", () => {
  it("mounts without items", () => {
    const wrapper = mount(ButtonGroupAction)
    expect(wrapper.find("[role='group']").exists()).toBe(true)
  })

  it("renders one button per item", () => {
    const wrapper = mount(ButtonGroupAction, { props: { items: baseItems } })
    expect(wrapper.findAll("button").length).toBe(2)
    expect(wrapper.text()).toContain("Edit")
    expect(wrapper.text()).toContain("Delete")
  })

  it("emits a named action when an emit-only item is clicked", async () => {
    const wrapper = mount(ButtonGroupAction, { props: { items: baseItems } })
    await wrapper.findAll("button")[0]!.trigger("click")
    const emitted = wrapper.emitted("action")
    expect(emitted).toBeTruthy()
    expect(emitted![0]![0]).toMatchObject({ name: "edit" })
  })

  it("renders href items as anchors and does not emit on click", async () => {
    const items: ButtonGroupItem[] = [
      { label: "Docs", href: "https://example.com", target: "_blank" },
    ]
    const wrapper = mount(ButtonGroupAction, { props: { items } })
    const anchor = wrapper.find("a")
    expect(anchor.exists()).toBe(true)
    expect(anchor.attributes("href")).toBe("https://example.com")
    expect(anchor.attributes("target")).toBe("_blank")
    await anchor.trigger("click")
    expect(wrapper.emitted("action")).toBeFalsy()
  })

  it("respects each item's variant; falls back to group variant", () => {
    const wrapper = mount(ButtonGroupAction, {
      props: {
        items: [
          { label: "X", emit: "x" }, // inherits group variant
          { label: "Y", emit: "y", variant: "destructive" },
        ],
        variant: "secondary",
      },
    })
    expect(wrapper.findAll("button").length).toBe(2)
  })

  it("respects disabled per item", () => {
    const wrapper = mount(ButtonGroupAction, {
      props: { items: [{ label: "Off", disabled: true }] },
    })
    expect(
      (wrapper.find("button").element as HTMLButtonElement).disabled,
    ).toBe(true)
  })

  it("supports sm / md / lg sizes", () => {
    const sizes = ["sm", "md", "lg"] as const
    for (const size of sizes) {
      const wrapper = mount(ButtonGroupAction, {
        props: { items: [{ label: "X" }], size },
      })
      expect(wrapper.find("button").exists()).toBe(true)
    }
  })

  it("applies flex-1 to children when block=true", () => {
    const wrapper = mount(ButtonGroupAction, {
      props: { items: [{ label: "X" }], block: true },
    })
    expect(wrapper.find("button").classes()).toContain("flex-1")
  })
})
