#!/usr/bin/env node
// verify-theme.mjs — prove the light mode is readable, by rendering it and measuring.
//
//   node research/au-coins/verify-theme.mjs
//
// The weak version of this check reads theme.mjs, contrasts the tokens it declares, and goes
// green. It would have passed on day one while the actual pages were still unreadable, because
// the palette is not the only place a colour comes from: app.mjs alone carries
// `border-color:#2c4133` and `color:#12131a` written straight into a rule, and a hardcoded
// colour is precisely what a palette check cannot see. So this drives a real browser, sets the
// theme the way a reader's browser would, and measures the COMPUTED colour of real text nodes
// against the COMPUTED background actually painted behind them.
//
// Three ways in, because they are three different mechanisms and only one of them is CSS:
//   - emulated prefers-color-scheme: light   the media query
//   - documentElement.dataset.theme = 'light' the explicit override
//   - the toggle clicked, then a reload       the localStorage round trip
//
// Every one of these checks has a negative control below. A contrast checker that has never
// been shown an unreadable page is a contrast checker you have no reason to believe.

import { chromium } from 'playwright'
import { readFileSync } from 'node:fs'
import { pathToFileURL } from 'node:url'
import { LIGHT, DARK } from './theme.mjs'

const OUT = 'public/tools/australian-coins'
const PAGES = [
  ['the catalogue front page', `${OUT}/index.html`],
  ['the collection HUD', `${OUT}/collection/index.html`],
  ['a denomination page', `${OUT}/penny/index.html`],
  ['the metal calculator', `${OUT}/what-metal-is-in-it/index.html`],
  ['the showing', `${OUT}/what-a-mintage-counts/index.html`],
  ['coins at actual size', `${OUT}/actual-size/index.html`],
]

let passed = 0, failed = 0, controls = 0, controlsFired = 0
const ok = (m) => { passed++; console.log(`  ok   ${m}`) }
const bad = (m, d = '') => { failed++; console.log(`  FAIL ${m}${d ? `\n       ${d}` : ''}`) }
const control = async (m, fn) => {
  controls++
  const fired = await fn()
  if (fired) { controlsFired++; console.log(`  red  ${m}`) }
  else { failed++; console.log(`  CONTROL DID NOT FIRE: ${m}`) }
}

// Relative luminance and contrast ratio, WCAG 2.1 definitions, computed here rather than
// trusted from a library so the numbers in theme.mjs's header can be re-derived by anyone.
const lum = ([r, g, b]) => {
  const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4 }
  return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b)
}
const ratio = (a, b) => { const [x, y] = [lum(a), lum(b)].sort((m, n) => n - m); return (x + 0.05) / (y + 0.05) }
const hexToRgb = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16))

// Walk the rendered page and hand back every text node with the colour it is painted in and
// the colour actually painted behind it. "Actually" is the load-bearing word: an element with
// a transparent background inherits whatever ancestor last painted one, so the naive reading
// (this element's own background-color) reports rgba(0,0,0,0) and silently passes everything.
const MEASURE = `(() => {
  const out = []
  const bgOf = (el) => {
    for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
      const c = getComputedStyle(n).backgroundColor
      if (c && c !== 'transparent' && !/rgba\\(0, 0, 0, 0\\)/.test(c)) return c
    }
    return getComputedStyle(document.body).backgroundColor
  }
  const px = (s) => (s.match(/[\\d.]+/g) || []).slice(0, 3).map(Number)
  const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT)
  const seen = new Set()
  let n
  while ((n = walk.nextNode())) {
    const t = (n.textContent || '').trim()
    if (t.length < 3) continue
    const el = n.parentElement
    if (!el || seen.has(el)) continue
    seen.add(el)
    const cs = getComputedStyle(el)
    if (cs.display === 'none' || cs.visibility === 'hidden' || Number(cs.opacity) === 0) continue
    const r = el.getBoundingClientRect()
    if (r.width < 1 || r.height < 1) continue
    const size = parseFloat(cs.fontSize) || 16
    const weight = Number(cs.fontWeight) || 400
    out.push({
      text: t.slice(0, 44), tag: el.tagName.toLowerCase(), cls: (el.className || '').toString().slice(0, 30),
      fg: px(cs.color), bg: px(bgOf(el)),
      // WCAG's large-text allowance: 18.66px bold, or 24px at any weight, may sit at 3:1.
      large: size >= 24 || (size >= 18.66 && weight >= 700),
    })
  }
  return out
})()`

const worst = (nodes) => {
  let w = null
  for (const n of nodes) {
    const r = ratio(n.fg, n.bg)
    const need = n.large ? 3 : 4.5
    if (!w || r - need < w.slack) w = { ...n, r, need, slack: r - need }
  }
  return w
}

const browser = await chromium.launch()

async function measure (file, { scheme = 'dark', attr = null, clickToggle = null } = {}) {
  const ctx = await browser.newContext({ colorScheme: scheme, viewport: { width: 1280, height: 900 } })
  const page = await ctx.newPage()
  await page.goto(pathToFileURL(file).href, { waitUntil: 'domcontentloaded' })
  if (attr) await page.evaluate((v) => { document.documentElement.dataset.theme = v }, attr)
  if (clickToggle) {
    await page.click(`[data-theme-set="${clickToggle}"]`)
    await page.reload({ waitUntil: 'domcontentloaded' })   // proves it was persisted, not just set
  }
  await page.waitForTimeout(220)
  const nodes = await page.evaluate(MEASURE)
  const ground = await page.evaluate(() => getComputedStyle(document.body).backgroundColor)
  await ctx.close()
  return { nodes, ground }
}

console.log('theme\n')

// ── 1. the palette itself, both modes, every token on every surface ────────────────────
for (const [name, P] of [['dark', DARK], ['light', LIGHT]]) {
  let bad_ = []
  for (const [tok, hex] of Object.entries(P)) {
    if (['ground', 'panel', 'panel2', 'line'].includes(tok)) continue
    for (const surf of ['ground', 'panel', 'panel2']) {
      const r = ratio(hexToRgb(hex), hexToRgb(P[surf]))
      if (r < 4.5) bad_.push(`--${tok} on --${surf} = ${r.toFixed(2)}`)
    }
  }
  bad_.length ? bad(`every ${name} token clears 4.5:1 on every surface`, bad_.join('; '))
              : ok(`every ${name} token clears 4.5:1 on every surface`)
}

// ── 2. the rendered pages, in both modes, by all three routes ──────────────────────────
for (const [label, file] of PAGES) {
  for (const [route, opts] of [
    ['system preference', { scheme: 'light' }],
    ['explicit data-theme', { scheme: 'dark', attr: 'light' }],
  ]) {
    const { nodes, ground } = await measure(file, opts)
    if (!nodes.length) { bad(`${label}: light via ${route} — no text measured`); continue }
    const isLight = lum((ground.match(/[\d.]+/g) || []).slice(0, 3).map(Number)) > 0.5
    if (!isLight) { bad(`${label}: light via ${route} did not actually go light`, `body background ${ground}`); continue }
    const w = worst(nodes)
    w.slack < 0
      ? bad(`${label}: light via ${route}, ${nodes.length} text nodes all readable`,
            `worst: <${w.tag} class="${w.cls}"> "${w.text}" at ${w.r.toFixed(2)}:1, needs ${w.need}`)
      : ok(`${label}: light via ${route}, ${nodes.length} text nodes, worst ${w.r.toFixed(2)}:1`)
  }
  // and dark must still be right, which is the regression this change could most easily cause
  const { nodes, ground } = await measure(file, { scheme: 'dark' })
  const isDark = lum((ground.match(/[\d.]+/g) || []).slice(0, 3).map(Number)) < 0.2
  const w = worst(nodes)
  isDark && w.slack >= 0
    ? ok(`${label}: dark is unchanged, ${nodes.length} text nodes, worst ${w.r.toFixed(2)}:1`)
    : bad(`${label}: dark is unchanged`, isDark ? `worst ${w.r.toFixed(2)}:1 needs ${w.need}` : `body background ${ground}`)
}

// ── 3. the toggle, which is a different mechanism from the CSS ─────────────────────────
{
  const file = `${OUT}/collection/index.html`
  const { ground } = await measure(file, { scheme: 'dark', clickToggle: 'light' })
  const isLight = lum((ground.match(/[\d.]+/g) || []).slice(0, 3).map(Number)) > 0.5
  isLight ? ok('the Light button survives a reload, so the choice is stored')
          : bad('the Light button survives a reload', `body background ${ground} after reload`)

  // The one the media query gets wrong if it is not guarded: a light MACHINE, reader picks dark.
  const ctx = await browser.newContext({ colorScheme: 'light' })
  const page = await ctx.newPage()
  await page.goto(pathToFileURL(file).href, { waitUntil: 'domcontentloaded' })
  await page.click('[data-theme-set="dark"]')
  await page.waitForTimeout(120)
  const g2 = await page.evaluate(() => getComputedStyle(document.body).backgroundColor)
  await ctx.close()
  lum((g2.match(/[\d.]+/g) || []).slice(0, 3).map(Number)) < 0.2
    ? ok('a reader on a light machine can still choose dark')
    : bad('a reader on a light machine can still choose dark', `body background ${g2}`)
}

// ── 4. the controls ────────────────────────────────────────────────────────────────────
console.log('')
await control('an unreadable token in the light palette is caught', async () => {
  const P = { ...LIGHT, dim: '#e8e6e0' }          // near-white text on near-white ground
  return ratio(hexToRgb(P.dim), hexToRgb(P.ground)) < 4.5
})
await control('a hardcoded colour in a real page is caught, not just a palette token', async () => {
  const ctx = await browser.newContext({ colorScheme: 'light' })
  const page = await ctx.newPage()
  await page.goto(pathToFileURL(`${OUT}/index.html`).href, { waitUntil: 'domcontentloaded' })
  // Exactly the fault the palette check cannot see: a literal colour, in a rule, on real text.
  await page.addStyleTag({ content: 'p, .note, li { color: #f2f0ea !important }' })
  await page.waitForTimeout(120)
  const nodes = await page.evaluate(MEASURE)
  await ctx.close()
  return worst(nodes).slack < 0
})
await control('a page that ignores the media query is caught', async () => {
  const ctx = await browser.newContext({ colorScheme: 'light' })
  const page = await ctx.newPage()
  await page.goto(pathToFileURL(`${OUT}/index.html`).href, { waitUntil: 'domcontentloaded' })
  await page.addStyleTag({ content: ':root{--ground:#0c0d11 !important} body{background:#0c0d11 !important}' })
  await page.waitForTimeout(120)
  const g = await page.evaluate(() => getComputedStyle(document.body).backgroundColor)
  await ctx.close()
  return lum((g.match(/[\d.]+/g) || []).slice(0, 3).map(Number)) <= 0.5
})
await control('a toggle that does not persist is caught', async () => {
  const ctx = await browser.newContext({ colorScheme: 'dark' })
  const page = await ctx.newPage()
  await page.goto(pathToFileURL(`${OUT}/collection/index.html`).href, { waitUntil: 'domcontentloaded' })
  // Set the attribute WITHOUT writing localStorage, which is the bug: looks right, forgets.
  await page.evaluate(() => { document.documentElement.dataset.theme = 'light' })
  await page.reload({ waitUntil: 'domcontentloaded' })
  await page.waitForTimeout(120)
  const g = await page.evaluate(() => getComputedStyle(document.body).backgroundColor)
  await ctx.close()
  return lum((g.match(/[\d.]+/g) || []).slice(0, 3).map(Number)) < 0.5
})
await control('a page whose boot script never ran shows the flash', async () => {
  // The flash is real and this is what it looks like: a reader with light stored, whose <head>
  // script did not run, gets a dark first paint. Blocking the inline script reproduces exactly
  // that, and the check is that we can SEE it happen, which is why the head script is load-bearing.
  const ctx = await browser.newContext({ colorScheme: 'dark' })
  const page = await ctx.newPage()
  await page.goto(pathToFileURL(`${OUT}/collection/index.html`).href, { waitUntil: 'domcontentloaded' })
  await page.evaluate(() => { try { localStorage.setItem('auc-theme', 'light') } catch (e) {} })
  await ctx.route('**/*', (r) => r.continue())
  await page.addInitScript(() => {
    // neuter the stored value at first paint only, which is the world without the head script
    const real = Storage.prototype.getItem
    Storage.prototype.getItem = function (k) { return k === 'auc-theme' ? null : real.call(this, k) }
    document.addEventListener('DOMContentLoaded', () => { Storage.prototype.getItem = real })
  })
  await page.reload({ waitUntil: 'domcontentloaded' })
  const painted = await page.evaluate(() => getComputedStyle(document.body).backgroundColor)
  await ctx.close()
  const dark = lum((painted.match(/[\d.]+/g) || []).slice(0, 3).map(Number)) < 0.2
  return dark   // it flashed dark, which is the fault the head script exists to prevent
})

await browser.close()
console.log(`\n${passed} passed, ${failed} failed`)
console.log(`${controlsFired}/${controls} negative controls fired`)
process.exit(failed === 0 && controlsFired === controls ? 0 : 1)
