import assert from "node:assert/strict"
import { describe, it } from "node:test"
import {
  bboxToPageCoords,
  normalizePageCoords,
  pageCoordsToStackStyle,
  pageIndexFromStackY,
  usesPageLayer,
} from "./docs-graphic-position.ts"
import { DOCS_GRAPHIC_DEFAULTS } from "./docs-graphic-types.ts"
import { DOCS_PAGE_GAP_PX } from "./docs-page-layout-constants.ts"

describe("docs-graphic-position", () => {
  it("usesPageLayer for fixed and behind/in-front wraps", () => {
    assert.equal(
      usesPageLayer({ ...DOCS_GRAPHIC_DEFAULTS, positionMode: "fixed-on-page" }),
      true
    )
    assert.equal(
      usesPageLayer({ ...DOCS_GRAPHIC_DEFAULTS, wrap: "behind", positionMode: "move-with-text" }),
      true
    )
    assert.equal(
      usesPageLayer({ ...DOCS_GRAPHIC_DEFAULTS, wrap: "square", placement: "absolute" }),
      false
    )
  })

  it("pageIndexFromStackY handles multi-page stack", () => {
    const pageHeight = 1000
    assert.equal(pageIndexFromStackY(0, pageHeight), 0)
    assert.equal(pageIndexFromStackY(pageHeight + DOCS_PAGE_GAP_PX, pageHeight), 1)
  })

  it("bboxToPageCoords maps viewport rect to page coords", () => {
    const pageHeight = 1000
    const stackRect = { left: 100, top: 50, width: 800, height: 3000 } as DOMRect
    const graphicRect = { left: 150, top: 120, width: 200, height: 100 } as DOMRect
    const coords = bboxToPageCoords(graphicRect, stackRect, 1, pageHeight)
    assert.equal(coords.pageIndex, 0)
    assert.equal(coords.pageX, 50)
    assert.equal(coords.pageY, 70)
  })

  it("normalizePageCoords re-resolves page index after cross-page drags", () => {
    const pageHeight = 1000
    const next = normalizePageCoords(0, pageHeight + DOCS_PAGE_GAP_PX + 50, pageHeight)
    assert.equal(next.pageIndex, 1)
    assert.equal(next.pageY, 50)

    const up = normalizePageCoords(1, -200, pageHeight)
    assert.equal(up.pageIndex, 0)
    assert.equal(up.pageY, Math.min(pageHeight, 800 + DOCS_PAGE_GAP_PX))

    const clamped = normalizePageCoords(0, -50, pageHeight)
    assert.equal(clamped.pageIndex, 0)
    assert.equal(clamped.pageY, 0)
  })

  it("pageCoordsToStackStyle stacks page offsets", () => {
    const pageHeight = 1000
    const style = pageCoordsToStackStyle(1, 40, 80, pageHeight)
    assert.equal(style.left, 40)
    assert.equal(style.top, pageHeight + DOCS_PAGE_GAP_PX + 80)
  })
})
