/**
 * @vitest-environment jsdom
 */
import { describe, expect, it } from "bun:test"

import { normalizeTicketMentionHtml } from "@/components/ui/rich-text-editor"

function getAnchor(html: string): HTMLAnchorElement | null {
  const template = document.createElement("template")
  template.innerHTML = html
  return template.content.querySelector("a.ticket-mention")
}

describe("normalizeTicketMentionHtml", () => {
  it("returns original html when there is no ticket mention", () => {
    const input = "<p>Sem menções aqui</p>"
    expect(normalizeTicketMentionHtml(input)).toBe(input)
  })

  it("upgrades legacy mention markup with flattened text", () => {
    const input =
      '<p><a class="ticket-mention inline-flex items-center" href="/tickets/abc123">#41002•Integração ERP parada</a></p>'
    const output = normalizeTicketMentionHtml(input)
    const anchor = getAnchor(output)
    expect(anchor).not.toBeNull()
    expect(anchor?.dataset.ticketMention).toBe("true")
    expect(anchor?.dataset.ticketId).toBe("abc123")
    expect(anchor?.dataset.ticketReference).toBe("41002")
    expect(anchor?.dataset.ticketStatus).toBe("PENDING")
    expect(anchor?.dataset.ticketPriority).toBe("MEDIUM")
    expect(anchor?.querySelector(".ticket-mention-dot")).not.toBeNull()
    expect(anchor?.querySelector(".ticket-mention-ref")?.textContent).toBe("#41002")
    expect(anchor?.querySelector(".ticket-mention-subject")?.textContent).toBe("Integração ERP parada")
  })

  it("preserves existing structured markup while refreshing classes", () => {
    const input =
      '<p><a data-ticket-mention="true" data-ticket-id="xyz" data-ticket-reference="123" data-ticket-status="RESOLVED" data-ticket-priority="LOW" data-ticket-subject="Teste" href="/tickets/xyz" class="ticket-mention"><span class="ticket-mention-dot"></span><span class="ticket-mention-ref">#123</span><span class="ticket-mention-sep">•</span><span class="ticket-mention-subject">Teste</span></a></p>'
    const output = normalizeTicketMentionHtml(input)
    const anchor = getAnchor(output)
    expect(anchor).not.toBeNull()
    expect(anchor?.dataset.ticketStatus).toBe("RESOLVED")
    expect(anchor?.dataset.ticketPriority).toBe("LOW")
    expect(anchor?.className).toContain("ticket-mention")
    expect(anchor?.querySelector(".ticket-mention-dot")?.className).toContain("bg-emerald-500")
  })
})
