import { describe, expect, it } from "vitest"
import {
  EMAIL_PREVIEW_HEIGHT_BUFFER,
  EMAIL_PREVIEW_MIN_IFRAME_HEIGHT,
  measureEmailPreviewIframeHeight,
} from "@/lib/email-preview-iframe-height"

function makeDoc(html: string) {
  const doc = document.implementation.createHTMLDocument("preview")
  doc.body.innerHTML = `<div data-ultimail-measure-root>${html}</div>`
  return doc
}

describe("measureEmailPreviewIframeHeight", () => {
  it("returns stable rounded height for short content", () => {
    const doc = makeDoc('<p style="margin:0">Hello</p>')
    const first = measureEmailPreviewIframeHeight(doc)
    const second = measureEmailPreviewIframeHeight(doc)
    expect(first).toBe(second)
    expect(first).toBeGreaterThanOrEqual(EMAIL_PREVIEW_MIN_IFRAME_HEIGHT)
  })

  it("prefers visible bounds over inflated scrollHeight", () => {
    const doc = makeDoc(`
      <div style="height:120px">Visible block</div>
      <div style="height:0;overflow:hidden;opacity:0">Hidden tail</div>
    `)
    const height = measureEmailPreviewIframeHeight(doc)
    expect(height).toBeLessThan(200 + EMAIL_PREVIEW_HEIGHT_BUFFER)
  })

  it("does not flip between bound and scroll estimates on repeat measure", () => {
    const doc = makeDoc(`
      <p style="margin:0 0 1em;line-height:1.6">Line one</p>
      <p style="margin:0 0 1em;line-height:1.6">Line two</p>
      <p style="margin:0 0 1em;line-height:1.6">Line three</p>
    `)
    const readings = Array.from({ length: 6 }, () =>
      measureEmailPreviewIframeHeight(doc)
    )
    expect(new Set(readings).size).toBe(1)
  })
})
