// verify-page.mjs — drive the immersive page in a real headless browser:
// confirm no JS errors, exercise all three instruments, check the live readouts
// reproduce the offline numbers, and check there's no mobile overflow.
//
//   npm run build  &&  node research/chsh-bell/verify-page.mjs
import pw from '/opt/node22/lib/node_modules/playwright/index.js';
const { chromium } = pw;
import { createServer } from 'http';
import { readFileSync, existsSync } from 'fs';
import { extname, join } from 'path';

const root = new URL('../../dist/', import.meta.url).pathname;
if (!existsSync(root)) { console.error('dist/ not found — run `npm run build` first.'); process.exit(1); }
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' };
const server = createServer((req,res)=>{ let p=decodeURIComponent(req.url.split('?')[0]); if(p.endsWith('/'))p+='index.html'; const fp=join(root,p);
  let body; try{ body=readFileSync(fp); }catch{ res.writeHead(404); res.end('404'); return; }
  res.writeHead(200,{'content-type':types[extname(fp)]||'application/octet-stream'}); res.end(body); });
await new Promise(r=>server.listen(8131,r));
const URL_ = 'http://localhost:8131/strata/a-game-you-shouldnt-win/';

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

const browser = await chromium.launch();

// ── desktop ──
const page = await browser.newPage({ viewport:{width:1280,height:900}, deviceScaleFactor:1 });
const errs=[]; page.on('pageerror',e=>errs.push(e.message)); page.on('console',m=>{ if(m.type()==='error')errs.push('console:'+m.text()); });
await page.goto(URL_,{waitUntil:'networkidle'});
await page.waitForTimeout(400);

ok('page loads with no JS/console errors', errs.length===0, errs.join(' | '));

// Instrument I — toggle a bit, enumerate
await page.click('#a1');                                   // strategy now a1=1
const i1val = await page.textContent('#i1val');
ok('Instrument I win-rate readout present', /%$/.test(i1val.trim()), `="${i1val}"`);
await page.click('#i1enum');
await page.waitForTimeout(reduceWait());
const barCount = await page.$$eval('#i1bars .bar', els=>els.length);
const hiCount  = await page.$$eval('#i1bars .bar.hi', els=>els.length);
ok('enumeration drew all 16 strategy bars', barCount===16, `bars=${barCount}`);
ok('exactly 8 strategies reach the 75% wall (hi bars)', hiCount===8, `hi=${hiCount}`);

// Instrument II — burst several times, read win rate + S
for(let i=0;i<6;i++){ await page.click('#i2burst'); }       // 60,000 rounds
await page.waitForTimeout(100);
const rounds = await page.textContent('#i2rounds');
const winTxt = await page.textContent('#i2win');
const winPct = parseFloat(winTxt);
const sTxt = parseFloat(await page.textContent('#i2S'));
ok('Instrument II played 60,000 rounds', rounds.replace(/[^0-9]/g,'')==='60000', `rounds=${rounds}`);
ok('quantum win rate ≈ 85.36% (live MC)', Math.abs(winPct-85.36)<1.0, `=${winPct}%`);
ok('running CHSH S ≈ 2.828 (live MC)', Math.abs(sTxt-2.828)<0.06, `S=${sTxt}`);
const e0 = parseFloat(await page.textContent('#i2e0'));
const e3 = parseFloat(await page.textContent('#i2e3'));
ok('E₀₀ ≈ +0.707', Math.abs(e0-0.707)<0.03, `E00=${e0}`);
ok('E₁₁ ≈ −0.707 (the anti-correlated case)', Math.abs(e3+0.707)<0.03, `E11=${e3}`);

// Instrument III — slider to 45 and 0
await page.fill('#theta','45'); await page.dispatchEvent('#theta','input'); await page.waitForTimeout(60);
const win45 = await page.textContent('#p-win'); const s45 = await page.textContent('#p-S');
ok('slider θ=45° → win 85.36%', win45.trim()==='85.36%', `="${win45}"`);
ok('slider θ=45° → S 2.828', s45.trim()==='2.828', `="${s45}"`);
await page.fill('#theta','0'); await page.dispatchEvent('#theta','input'); await page.waitForTimeout(60);
const win0 = await page.textContent('#p-win');
ok('slider θ=0° → win 75.00% (no advantage)', win0.trim()==='75.00%', `="${win0}"`);

// dial drawn
const spokes = await page.$$eval('#dial line', els=>els.length);
ok('angle dial rendered (gridlines + 4 spokes)', spokes>=8, `lines=${spokes}`);

// Prose vs computation: the sentences a reader sees must carry the computed figures,
// so a changed number in the header, the body, the meta text or the dek turns this red.
{
  const QWIN = (2+Math.SQRT2)/4, qPct = (QWIN*100).toFixed(2)+'%';      // 85.36%
  const band = (Math.acos((Math.sqrt(3)-1)/2)*180/Math.PI).toFixed(1);  // 68.5
  const html = await page.content();
  const text = await page.evaluate(()=>document.body.innerText);
  const spec = (await page.textContent('.specimen b.g')).trim();
  ok('header "with entanglement" figure = computed optimum', spec===qPct, `"${spec}" vs ${qPct}`);
  ok('header classical ceiling = 75%', (await page.textContent('.specimen b.w')).trim()==='75%');
  ok('body: "settles, stubbornly, on" the computed optimum', text.includes('settles, stubbornly, on '+qPct));
  ok('body: ten-thousand-round sentence names the computed optimum', text.includes('lands near '+qPct));
  ok('body: violation band edge in prose = computed arccos((√3−1)/2)', text.includes('about '+band+'°'), `${band}°`);
  ok('body: Tsirelson value 2√2 ≈ '+(2*Math.SQRT2).toFixed(3), text.includes('2√2 ≈ '+(2*Math.SQRT2).toFixed(3)));
  for (const sel of ['meta[name="description"]','meta[property="og:description"]','meta[name="twitter:description"]']){
    const c = await page.getAttribute(sel,'content');
    ok(`${sel} carries ${qPct} and 75%`, c.includes(qPct) && c.includes('75%'));
  }
  const md = readFileSync(new URL('../../src/content/strata/a-game-you-shouldnt-win.md', import.meta.url),'utf8');
  const dek = (md.match(/^dek: "(.*)"$/m)||[])[1]||'';
  ok('dek carries 75% and the computed optimum', dek.includes('75%') && dek.includes(qPct+' of the time'));
  // "17 checks" in the sources box must equal what verify.mjs actually passes.
  const { execFileSync } = await import('child_process');
  let out=''; try{ out = execFileSync(process.execPath,[new URL('./verify.mjs', import.meta.url).pathname],{encoding:'utf8'}); }catch(e){ out = String(e.stdout||''); }
  const m = out.match(/\((\d+) passed, (\d+) failed\)/);
  const claimed = (text.match(/\((\d+) checks:/)||[])[1];
  ok('sources box check count = verify.mjs passes, all green', m && m[2]==='0' && claimed===m[1], `page ${claimed}, verify.mjs ${m&&m[1]} passed ${m&&m[2]} failed`);
  ok('sources box links the published verifier', html.includes('href="/checks/research/chsh-bell/verify.mjs"'));
}

await page.screenshot({ path: new URL('./shot-desktop.png', import.meta.url).pathname, fullPage:true });

// ── mobile overflow ──
const m = await browser.newPage({ viewport:{width:390,height:840} });
const merrs=[]; m.on('pageerror',e=>merrs.push(e.message));
await m.goto(URL_,{waitUntil:'networkidle'}); await m.waitForTimeout(300);
const ov = await m.evaluate(()=> document.documentElement.scrollWidth - document.documentElement.clientWidth);
ok('no horizontal overflow at 390px', ov<=1, `overflow=${ov}px`);
await m.click('#i2burst'); await m.waitForTimeout(80);
ok('mobile: instrument II runs', merrs.length===0, merrs.join(' | '));
await m.screenshot({ path: new URL('./shot-mobile.png', import.meta.url).pathname, fullPage:true });

console.log(`\n${fails===0?'✓ PAGE VERIFIED — all checks pass':'✗ '+fails+' CHECK(S) FAILED'}`);
await browser.close(); server.close();
function reduceWait(){ return 700; }
process.exit(fails===0?0:1);
