// verify-ulam-spiral.mjs — drive the immersive "The Doodle That Sees the Primes"
// page in a real headless browser: no JS errors; the spiral canvas renders primes;
// the diagonal overlay reports the right quadratic; the polynomial lab gives
// Rabinowitsch's verdict correctly for lucky and non-lucky c; the Heegner census
// table is right; no horizontal overflow on phone/tablet/desktop.
//   node verify-ulam-spiral.mjs (serves the authored page in public/)
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(import.meta.url.includes('/public/checks/') ? '../' : './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/ulam-spiral/`;

let fails=0; const ok=(n,c,x='')=>{ if(!c)fails++; console.log(`${c?'  ok':'FAIL'}  ${n}${x?'   '+x:''}`); };
const browser = await chromium.launch();
const page = await browser.newPage({ viewport:{ width:390, height:840 } });
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('no JS errors on load', errs.length===0, errs.join(' | '));

// spiral canvas rendered prime cells (non-blank, but not fully filled)
const lit = await page.evaluate(()=>{ const cv=document.getElementById('spiral'); const ctx=cv.getContext('2d');
  const d=ctx.getImageData(0,0,cv.width,cv.height).data; let dark=0,total=0; for(let i=0;i<d.length;i+=4){ total++; if(d[i]+d[i+1]+d[i+2]<180) dark++; } return {dark,total}; });
ok('spiral canvas renders prime cells', lit.dark>3000 && lit.dark<lit.total*0.4, `dark=${lit.dark}/${lit.total}`);

// diagonal overlay: SE button should report the odd squares 4n²+4n+1
await page.click('button[data-diag="3"]');
let sr = await page.textContent('#spreadout');
ok('SE diagonal reported as 4n²+4n+1 (odd squares)', /4n²\+4n\+1/.test(sr) && /odd squares/.test(sr), sr.replace(/\s+/g,' ').trim());
// NE button -> 4n²−2n+1
await page.click('button[data-diag="0"]');
sr = await page.textContent('#spreadout');
ok('NE diagonal reported as 4n²−2n+1', /4n²−2n\+1/.test(sr), sr.replace(/\s+/g,' ').trim());

// Lab default c=41 has the full c-1 run: the lucky case, run 40, field h=1.
let lv = await page.textContent('#labverdict');
ok('lab default c=41: full run of 40 primes, Heegner, h=1', /run = 40 primes/.test(lv) && /Heegner/.test(lv) && /class number h = 1/.test(lv), lv.replace(/\s+/g,' ').trim().slice(0,140));
let goodClass = await page.getAttribute('#labverdict','class');
ok('c=41 verdict marked good (green)', /good/.test(goodClass));

// click a dud: c=7 should be the short-run "not squarefree" case
await page.click('button.lbtn[data-c="7"]');
lv = await page.textContent('#labverdict');
ok('lab c=7: short run, flagged as non-fundamental (1−4c=−27 not squarefree)', /short of the full/.test(lv) && /not squarefree/.test(lv), lv.replace(/\s+/g,' ').trim().slice(0,140));

// type a dud prime with h>1: c=13 -> 1-4c=-51 squarefree, h=2
await page.fill('#cin','13'); await page.click('#cgo');
lv = await page.textContent('#labverdict');
ok('lab c=13: short run, flagged class number h>1', /short of the full/.test(lv) && /class number h = 2/.test(lv), lv.replace(/\s+/g,' ').trim().slice(0,140));

// Nonfundamental cases must display the field class number and keep the
// separate squarefree test. c=25 used to print order h(-99)=2 instead of field h=1.
for (const [c, disc] of [[7,-3],[19,-3],[25,-11]]) {
  await page.fill('#cin', String(c)); await page.click('#cgo');
  lv = await page.textContent('#labverdict');
  ok(`c=${c}: fundamental discriminant ${disc}, field h=1`,
    lv.includes(`discriminant${c===25?' =':''} ${disc}`) && /class number h = 1/.test(lv), lv);
  if (c !== 25) ok(`c=${c}: squarefree failure still forbids the full run`, /not squarefree/.test(lv) && /short of the full/.test(lv));
}
for (const c of [2,3,5,11,17,41]) {
  await page.click(`button.lbtn[data-c="${c}"]`);
  lv = await page.textContent('#labverdict');
  ok(`c=${c}: positive Heegner number ${4*c-1}, full run ${c-1}`,
    lv.includes(`run = ${c-1} `) && lv.includes(`minus the Heegner number ${4*c-1}; field class number h = 1`));
}
await page.click('#clrdiag');
sr = await page.textContent('#spreadout');
ok('cleared spiral readout retains the qualified density wording', /odd diagonals; rows and columns have clusters too/.test(sr));

// Heegner census table: should contain the six discriminants and class numbers 1
const tableTxt = await page.textContent('#heegtable');
const hasAll = ['-7','-11','-19','-43','-67','-163'].every(d=>tableTxt.includes(d));
ok('Heegner census table lists discriminants −7…−163', hasAll, tableTxt.replace(/\s+/g,' ').trim().slice(0,120));

// Ramanujan readout present with true value
const ram = await page.textContent('#ramanujan');
ok('Ramanujan constant shown with true near-integer value', /262 537 412 640 768 743/.test(ram), ram.replace(/\s+/g,' ').trim().slice(0,90));

// responsive: no horizontal overflow at three widths
for(const w of [320,390,768,1100]){
  await page.setViewportSize({ width:w, height:900 });
  await page.waitForTimeout(60);
  const over = await page.evaluate(()=> document.documentElement.scrollWidth - document.documentElement.clientWidth);
  ok(`no horizontal overflow at ${w}px`, over<=1, `overflow=${over}px`);
}

await browser.close(); server.close();
console.log(`\n${fails===0?'✓':'✗'}  ${fails} failure(s)\n`);
process.exit(fails===0?0:1);
