import { describe, it } from "node:test"
import assert from "node:assert/strict"
import {
  classifyContrastRepairKind,
  contrastRatio,
  isLikelyLightPaintedBackground,
  parseCssColorToRgb,
  relativeLuminance,
} from "./email-preview-contrast.ts"

describe("email-preview-contrast math", () => {
  it("parseCssColorToRgb handles hex and rgb", () => {
    assert.deepEqual(parseCssColorToRgb("#ffffff"), [255, 255, 255])
    assert.deepEqual(parseCssColorToRgb("rgb(32, 33, 36)"), [32, 33, 36])
    assert.equal(parseCssColorToRgb("transparent"), null)
    assert.equal(parseCssColorToRgb("rgba(255,255,255,0)"), null)
  })

  it("contrastRatio is low for similar colors", () => {
    const white: [number, number, number] = [255, 255, 255]
    const nearWhite: [number, number, number] = [250, 250, 250]
    assert.ok(contrastRatio(white, nearWhite) < 1.2)
    assert.ok(contrastRatio(white, [0, 0, 0]) > 10)
  })

  it("relativeLuminance orders black below white", () => {
    assert.ok(relativeLuminance([0, 0, 0]) < relativeLuminance([255, 255, 255]))
  })

  it("classifyContrastRepairKind detects light-on-light", () => {
    assert.equal(
      classifyContrastRepairKind([232, 234, 237], [255, 255, 255]),
      "light-surface"
    )
    assert.equal(
      classifyContrastRepairKind([232, 234, 237], [236, 239, 245]),
      "light-surface"
    )
  })

  it("classifyContrastRepairKind ignores readable pairs", () => {
    assert.equal(classifyContrastRepairKind([32, 33, 36], [255, 255, 255]), null)
    assert.equal(
      classifyContrastRepairKind([255, 255, 255], [11, 30, 61]),
      null
    )
  })

  it("classifyContrastRepairKind detects dark gray on dark canvas", () => {
    assert.equal(
      classifyContrastRepairKind([51, 51, 51], [32, 33, 36]),
      "dark-surface"
    )
  })

  it("classifyContrastRepairKind keeps light-on-light even if dark canvas looked fine", () => {
    assert.equal(
      classifyContrastRepairKind([232, 234, 237], [255, 255, 255]),
      "light-surface"
    )
    assert.ok(
      contrastRatio([232, 234, 237], [32, 33, 36]) >= 3,
      "misleading high ratio vs dark assumed canvas"
    )
  })

  it("isLikelyLightPaintedBackground detects newsletter gradients", () => {
    assert.ok(
      isLikelyLightPaintedBackground(
        "linear-gradient(180deg, #f5f7fa 0%, #eceff5 100%)"
      )
    )
    assert.equal(
      isLikelyLightPaintedBackground("linear-gradient(180deg, #0b1e3d, #000)"),
      false
    )
  })
})
