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

describe("MarkdownEditor (props-based composition)", () => {
  it("mounts and renders source + preview", () => {
    const wrapper = mount(MarkdownEditor, {
      props: { label: "Body" },
    })
    expect(
      wrapper.find("[data-testid='markdown-editor-source']").exists(),
    ).toBe(true)
    expect(
      wrapper.find("[data-testid='markdown-editor-preview']").exists(),
    ).toBe(true)
    expect(wrapper.text()).toContain("Body")
  })

  it("hides the label when hideLabel is true", () => {
    const wrapper = mount(MarkdownEditor, {
      props: { label: "Should hide", hideLabel: true },
    })
    expect(wrapper.find("[data-testid='field-frame-label']").exists()).toBe(
      false,
    )
  })

  it("forwards modelValue to the textarea", () => {
    const wrapper = mount(MarkdownEditor, {
      props: { modelValue: "# Hello" },
    })
    expect(
      (
        wrapper.find("[data-testid='markdown-editor-source']")
          .element as HTMLTextAreaElement
      ).value,
    ).toBe("# Hello")
  })

  it("renders a basic markdown preview", () => {
    const wrapper = mount(MarkdownEditor, {
      props: { modelValue: "**bold** and *italic*" },
    })
    const preview = wrapper.find("[data-testid='markdown-editor-preview']")
    expect(preview.html()).toContain("<strong>bold</strong>")
    expect(preview.html()).toContain("<em>italic</em>")
  })

  it("emits update:modelValue when the user types", async () => {
    const wrapper = mount(MarkdownEditor)
    await wrapper
      .find("[data-testid='markdown-editor-source']")
      .setValue("# Heading")
    const emitted = wrapper.emitted("update:modelValue")
    expect(emitted).toBeTruthy()
    expect(emitted![emitted!.length - 1]).toEqual(["# Heading"])
  })

  it("renders errors from props", () => {
    const wrapper = mount(MarkdownEditor, {
      props: { errors: ["Required"] },
    })
    expect(wrapper.text()).toContain("Required")
  })

  it("works without any props at all", () => {
    const wrapper = mount(MarkdownEditor)
    expect(
      wrapper.find("[data-testid='markdown-editor-source']").exists(),
    ).toBe(true)
  })
})
