// verify-is-fire-a-plasma.mjs — drive the immersive "Is Fire a Plasma?" page in a
// real headless browser: no JS errors, all three instrument canvases render, the
// Saha dial responds to species + temperature, the incandescence swatch changes
// colour, the spectrum toggle switches modes, and nothing overflows horizontally
// at phone / tablet / desktop widths.
//   node verify-is-fire-a-plasma.mjs
import pw from 'playwright';
const { chromium } = pw;
import { createServer } from 'http';
import { readFileSync } from 'fs';
import { extname, join } from 'path';
import { fileURLToPath } from 'url';

const root = fileURLToPath(new URL('./public/', import.meta.url));
const types = { '.html':'text/html','.css':'text/css','.js':'text/javascript','.woff2':'font/woff2','.png':'image/png','.svg':'image/svg+xml','.ico':'image/x-icon','.xml':'application/xml','.txt':'text/plain','.json':'application/json' };
const server = createServer((req,res)=>{ let p=decodeURIComponent(req.url.split('?')[0]); if(p.endsWith('/'))p+='index.html'; const fp=join(root,p);
  try{ const buf=readFileSync(fp); res.writeHead(200,{'content-type':types[extname(fp)]||'application/octet-stream'}); res.end(buf); }
  catch{ res.writeHead(404); res.end('404'); } });
await new Promise(r=>server.listen(0,'127.0.0.1',r));
const URL_ = `http://127.0.0.1:${server.address().port}/strata/is-fire-a-plasma/`;

let fails = 0; const ok=(n,c,x='')=>{ if(!c)fails++; console.log(`${c?'  ok':'FAIL'}  ${n}${x?'   '+x:''}`); };

const browser = await chromium.launch();
for (const [label, w, h] of [['phone',390,844],['tablet',768,1024],['desktop',1280,900]]) {
  const ctx = await browser.newContext({ viewport:{width:w,height:h} });
  const page = await ctx.newPage();
  const errs=[]; page.on('pageerror',e=>errs.push(String(e))); page.on('console',m=>{ if(m.type()==='error') errs.push(m.text()); });
  await page.goto(URL_, { waitUntil:'networkidle' });

  ok(`[${label}] no JS errors`, errs.length===0, errs.slice(0,2).join(' | '));

  // all three canvases render with non-zero size
  const canv = await page.$$eval('canvas', els=>els.map(e=>({w:e.clientWidth,h:e.clientHeight})));
  ok(`[${label}] 3 canvases render with size`, canv.length===3 && canv.every(c=>c.w>0&&c.h>0), JSON.stringify(canv));

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

  // INSTRUMENT 1: default is N2; readout names the gas and the 1% crossing temperature
  const read0 = await page.$eval('#ion-read', e=>e.textContent);
  ok(`[${label}] ion readout populated (N2 default)`, /N₂|Reaching 1%/i.test(read0), read0.slice(0,60));
  const verdict0 = await page.$eval('#ion-verdict', e=>e.textContent);
  ok(`[${label}] default verdict = under 1%`, /under 1%/i.test(verdict0), verdict0.slice(0,50));

  // switch species to Cs, verdict still "under 1%" but readout changes
  await page.$$eval('#species .chip', els=>{ const b=els.find(x=>/caesium|Cs/i.test(x.textContent)); b&&b.click(); });
  const readCs = await page.$eval('#ion-read', e=>e.textContent);
  ok(`[${label}] species switch to Cs updates readout`, /caesium/i.test(readCs), readCs.slice(0,40));

  // drag temperature to max (12000 K): for Cs it should now read over 1% ionized
  await page.$eval('#ion-T', el=>{ el.value=12000; el.dispatchEvent(new Event('input',{bubbles:true})); });
  const verdictHot = await page.$eval('#ion-verdict', e=>e.textContent);
  ok(`[${label}] Cs at 12000 K → over 1% ionized`, /over 1% ionized/i.test(verdictHot), verdictHot.slice(0,50));

  // INSTRUMENT 2 — swatch has a background colour; changing T changes it
  const sw1 = await page.$eval('#inc-swatch', e=>getComputedStyle(e).backgroundColor);
  await page.$eval('#inc-T', el=>{ el.value=3000; el.dispatchEvent(new Event('input',{bubbles:true})); });
  const sw2 = await page.$eval('#inc-swatch', e=>getComputedStyle(e).backgroundColor);
  ok(`[${label}] incandescence swatch is coloured`, /rgb/.test(sw1) && sw1!=='rgba(0, 0, 0, 0)', sw1);
  ok(`[${label}] swatch colour changes with temperature`, sw1!==sw2, `${sw1} → ${sw2}`);
  const incRead = await page.$eval('#inc-read', e=>e.textContent);
  ok(`[${label}] incandescence readout names a colour + peak`, /black-body|λ/i.test(incRead), incRead.slice(0,50));

  // INSTRUMENT 3 — mode toggle changes the readout
  await page.$$eval('#spec-mode .chip', els=>{ const b=els.find(x=>/clean blue/i.test(x.textContent)); b&&b.click(); });
  const specBlue = await page.$eval('#spec-read', e=>e.textContent);
  ok(`[${label}] spectrum names CH* blue and OH* ultraviolet`,
     /CH\* emits blue light near 430 nm/.test(specBlue) &&
     /OH\* band near 310 nm is ultraviolet/.test(specBlue), specBlue);

  await ctx.close();
}
await browser.close(); server.close();
console.log(fails ? `\n${fails} CHECK(S) FAILED` : '\nAll headless checks passed.');
process.exit(fails ? 1 : 0);
