// Browser verification of /strata/there-is-no-magenta/ — drives the real built
// page in headless chromium, exercises both instruments + the live check, and
// confirms the live numbers match the offline ground truth (verify.mjs).
// Desktop + mobile. Run after `npm run build`.
//
//   node research/there-is-no-magenta/verify-page.mjs
import { chromium } from 'playwright-core';
import { fileURLToPath } from 'url';
import { dirname, resolve, join, extname } from 'path';
import { createServer } from 'http';
import { readFile } from 'fs/promises';

const __dirname = dirname(fileURLToPath(import.meta.url));
const DIST = resolve(__dirname, '../../dist');

const MIME = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.json': 'application/json', '.woff2': 'font/woff2', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.xml': 'application/xml', '.txt': 'text/plain' };
const server = createServer(async (req, res) => {
  try {
    let p = decodeURIComponent(req.url.split('?')[0]);
    if (p.endsWith('/')) p += 'index.html';
    const data = await readFile(join(DIST, p));
    res.writeHead(200, { 'content-type': MIME[extname(p)] || 'application/octet-stream' });
    res.end(data);
  } catch { res.writeHead(404); res.end('not found'); }
});
await new Promise((r) => server.listen(0, r));
const PORT = server.address().port;
const URL = `http://localhost:${PORT}/strata/there-is-no-magenta/index.html`;

let pass = 0, fail = 0;
const ok = (c, m) => { if (c) { pass++; console.log('  ✓', m); } else { fail++; console.log('  ✗ FAIL:', m); } };

const exe = process.env.PW_CHROMIUM || '/opt/pw-browsers/chromium_headless_shell-1194/chrome-linux/headless_shell';
const browser = await chromium.launch({ executablePath: exe });

for (const vp of [{ name: 'desktop', width: 1100, height: 900 }, { name: 'mobile', width: 390, height: 844 }]) {
  console.log(`\n[${vp.name} ${vp.width}×${vp.height}]`);
  const page = await browser.newPage({ viewport: { width: vp.width, height: vp.height } });
  const errors = [];
  page.on('pageerror', (e) => errors.push(String(e)));
  page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
  await page.goto(URL, { waitUntil: 'networkidle' });
  await page.waitForTimeout(250);

  ok(errors.length === 0, 'no JS / page errors' + (errors.length ? ': ' + errors.join(' | ') : ''));

  // --- the live check section: ALL PASS ---
  const verdict = await page.textContent('#checkverdict');
  ok(/ALL \d+ PASS/.test(verdict), `live check verdict reads "${verdict.trim()}"`);
  const checkout = await page.textContent('#checkout');
  ok(/5\/5 checks pass/.test(checkout), 'live check reports 5/5');
  ok(/OPEN arc/.test(checkout), 'live check confirms the rim is an OPEN arc');
  ok(/invented, not spectral/.test(checkout), 'live check confirms the deepest magenta is invented, not spectral');
  ok(/one colour/.test(checkout), 'live check confirms metamerism (two spectra, one colour)');

  // --- Instrument I: trace mode default ---
  let spec = await page.textContent('#i1-spec');
  ok(/yes/.test(spec), 'I·trace: a single wavelength is a colour on the rim ("yes — pure light")');

  // move the wavelength slider, chromaticity updates
  await page.fill('#i1-wl', '520');
  await page.dispatchEvent('#i1-wl', 'input');
  const xy520 = await page.textContent('#i1-xy');
  ok(/0\.07/.test(xy520) && /0\.83/.test(xy520), `I·520 nm reads ~(0.0743, 0.8338): "${xy520}"`);

  // switch to mix mode, drive to opposite ends -> a purple, NOT a wavelength
  await page.click('#i1-p-mix');
  await page.fill('#i1-wlA', '650'); await page.dispatchEvent('#i1-wlA', 'input');
  await page.fill('#i1-wlB', '420'); await page.dispatchEvent('#i1-wlB', 'input');
  await page.fill('#i1-mixt', '50'); await page.dispatchEvent('#i1-mixt', 'input');
  const mixSpec = await page.textContent('#i1-spec');
  ok(/no/.test(mixSpec), `I·mix red+violet yields a colour no wavelength makes: "${mixSpec.trim()}"`);

  // toggle the sRGB gamut overlay
  await page.click('#i1-p-srgb');
  const srgbPressed = await page.getAttribute('#i1-p-srgb', 'aria-pressed');
  ok(srgbPressed === 'true', 'I·screen-gamut overlay toggles on');

  // --- Instrument II: metamerism — drive apart, colour stays, XYZ identical ---
  await page.fill('#i2-amt', '95'); await page.dispatchEvent('#i2-amt', 'input');
  const gap = await page.textContent('#i2-gap');
  const dxyz = await page.textContent('#i2-dxyz');
  ok(parseFloat(gap) > 0.3, `II·spectra differ physically (sup gap ${gap})`);
  ok(/zero/.test(dxyz), `II·yet ΔXYZ is zero: "${dxyz.trim()}"`);
  const swp = await page.getAttribute('#i2-swp', 'style');
  const swm = await page.getAttribute('#i2-swm', 'style');
  ok(swp === swm, 'II·the two swatches are byte-identical colours');

  // --- no horizontal overflow ---
  const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
  ok(overflow <= 1, `no horizontal overflow (Δ=${overflow}px)`);

  await page.close();
}

await browser.close();
server.close();
console.log(`\n${pass}/${pass + fail} browser checks passed${fail ? ` — ${fail} FAILED` : ''}.`);
process.exit(fail ? 1 : 0);
