import assert from "node:assert/strict"
import { describe, it } from "node:test"
import {
  extractDocxPageBackground,
  parseDocumentBackgroundXml,
  parseWatermarkFromHeaderXml,
  resolvePageBackgroundLayers,
} from "./doc-page-background.ts"

describe("doc-page-background", () => {
  it("parses solid page color from w:background", () => {
    const result = parseDocumentBackgroundXml(
      `<w:background w:color="C6D9F1"><v:background fillcolor="#c6d9f1"/></w:background>`,
      {}
    )
    assert.equal(result.pageColor, "#C6D9F1")
  })

  it("parses gradient fill css", () => {
    const result = parseDocumentBackgroundXml(
      `<w:background w:color="FFFFFF">
        <v:background>
          <v:fill type="gradient" color="#c0504d" color2="#f0504d" angle="45"/>
        </v:background>
      </w:background>`,
      {}
    )
    assert.match(result.background?.gradientCss ?? "", /linear-gradient\(45deg/)
  })

  it("parses text watermark from header vml", () => {
    const watermark = parseWatermarkFromHeaderXml(
      `<w:hdr>
        <w:p><w:r><w:pict>
          <v:shape style="rotation:315" fillcolor="#d9d9d9">
            <v:fill opacity=".35"/>
            <v:textpath string="CONFIDENTIEL"/>
          </v:shape>
        </w:pict></w:r></w:p>
      </w:hdr>`,
      {},
      "word/_rels/header1.xml.rels"
    )
    assert.equal(watermark?.kind, "text")
    assert.equal(watermark?.text, "CONFIDENTIEL")
    assert.equal(watermark?.rotationDeg, 315)
  })

  it("resolves background layers for rendering", () => {
    const layers = resolvePageBackgroundLayers({
      gradientCss: "linear-gradient(180deg, #fff, #eee)",
      watermark: {
        kind: "text",
        text: "BROUILLON",
        color: "#cccccc",
        opacity: 0.4,
        rotationDeg: -45,
      },
    })
    assert.ok(layers.gradientCss)
    assert.equal(layers.watermarkStyle?.text, "BROUILLON")
  })

  it("extracts background from document xml archive", () => {
    const archive = {
      "word/document.xml": new TextEncoder().encode(
        `<w:document><w:background w:color="FFF2CC"/></w:document>`
      ),
    }
    const result = extractDocxPageBackground(archive, new TextDecoder().decode(archive["word/document.xml"]))
    assert.equal(result.pageColor, "#FFF2CC")
  })
})
