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

describe("PasswordInput (props-based composition)", () => {
  it("mounts and renders the label via FieldFrame", () => {
    const wrapper = mount(PasswordInput, { props: { label: "Password" } })
    expect(wrapper.find("input").exists()).toBe(true)
    expect(wrapper.find("input").attributes("type")).toBe("password")
    expect(wrapper.text()).toContain("Password")
  })

  it("forwards modelValue", () => {
    const wrapper = mount(PasswordInput, { props: { modelValue: "secret" } })
    expect((wrapper.find("input").element as HTMLInputElement).value).toBe("secret")
  })

  it("emits update:modelValue on user typing", async () => {
    const wrapper = mount(PasswordInput, { props: { modelValue: "" } })
    await wrapper.find("input").setValue("abc123")
    const emitted = wrapper.emitted("update:modelValue")
    expect(emitted).toBeTruthy()
    expect(emitted![emitted!.length - 1]).toEqual(["abc123"])
  })

  it("does not render the visibility toggle by default", () => {
    const wrapper = mount(PasswordInput, { props: { label: "Password" } })
    expect(wrapper.find("[data-testid='password-toggle']").exists()).toBe(false)
  })

  it("renders the visibility toggle when togglePasswordVisibility is true", () => {
    const wrapper = mount(PasswordInput, {
      props: { label: "Password", togglePasswordVisibility: true },
    })
    expect(wrapper.find("[data-testid='password-toggle']").exists()).toBe(true)
  })

  it("toggles input type when the toggle button is clicked", async () => {
    const wrapper = mount(PasswordInput, {
      props: { label: "Password", togglePasswordVisibility: true },
    })
    expect(wrapper.find("input").attributes("type")).toBe("password")
    await wrapper.find("[data-testid='password-toggle']").trigger("click")
    expect(wrapper.find("input").attributes("type")).toBe("text")
    await wrapper.find("[data-testid='password-toggle']").trigger("click")
    expect(wrapper.find("input").attributes("type")).toBe("password")
  })

  it("renders errors and flips border to destructive", () => {
    const wrapper = mount(PasswordInput, { props: { errors: ["Too short"] } })
    expect(wrapper.find("[data-testid='field-frame-errors']").exists()).toBe(true)
    expect(wrapper.find("input").classes()).toContain("border-destructive")
  })

  it("works without any props at all", () => {
    const wrapper = mount(PasswordInput)
    expect(wrapper.find("input").exists()).toBe(true)
  })
})
