// verify-page-i3.mjs — load the live Einstein-Stone page in a real browser and
// exercise INSTRUMENT 03 ("the one road"): no JS errors; the tile + road canvases
// paint real pixels; the landmark buttons (comet/turtle/spectre/hat/chevron) drive
// the readout to the right member and the right periodic/aperiodic verdict; the
// slider morphs; no horizontal overflow on desktop or mobile. Serves public/ as-is.
//   node research/aperiodic-monotile/verify-page-i3.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('../../public/', import.meta.url).pathname;
if (!existsSync(root)) { console.error('public/ not found'); 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','.json':'application/json','.mjs':'text/javascript' };
const server = createServer((req,res)=>{ let p=decodeURIComponent(req.url.split('?')[0]); if(p.endsWith('/'))p+='index.html'; const fp=join(root,p);
  try{ res.writeHead(200,{'content-type':types[extname(fp)]||'application/octet-stream'}); res.end(readFileSync(fp)); }catch{ res.writeHead(404); res.end('404'); } });
await new Promise(r=>server.listen(8099,r));
const browser = await chromium.launch();

let fails=0; const ok=(c,m)=>{ if(!c){ fails++; console.log('  ✗ '+m); } else console.log('  ✓ '+m); };
const paint = (page,sel)=>page.evaluate((s)=>{ const c=document.querySelector(s); if(!c) return 0; const g=c.getContext('2d'); const d=g.getImageData(0,0,c.width,c.height).data; let nz=0; for(let i=3;i<d.length;i+=4*37) if(d[i]>0) nz++; return nz; }, sel);

async function clickMark(page, key){
  await page.evaluate((k)=>{ const b=[...document.querySelectorAll('#i3sel button')].find(x=>x.textContent.trim()===k); b.click(); }, key);
  await page.waitForTimeout(40);
  return page.evaluate(()=>document.getElementById('i3read').innerText);
}

async function run(viewport, label){
  console.log(`\n[${label}] ${viewport.width}×${viewport.height}`);
  const page = await browser.newPage({ viewport });
  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('http://localhost:8099/strata/aperiodic-monotile/', { waitUntil:'networkidle' });
  await page.waitForTimeout(120);

  ok(errs.length===0, 'no JS / page errors'+(errs.length?': '+errs.slice(0,3).join(' | '):''));
  ok(await paint(page,'#i3canvas') > 50, 'tile canvas paints real pixels');
  ok(await paint(page,'#i3road') > 20, 'road canvas paints real pixels');

  // landmark buttons → readout content + verdict
  const hat = await clickMark(page,'the hat');
  ok(/Tile\(1, √3\)/.test(hat) && /APERIODIC/.test(hat), 'hat → Tile(1, √3) + aperiodic verdict');
  const spectre = await clickMark(page,'spectre');
  ok(/Tile\(1, 1\)/.test(spectre) && /PERIODIC/.test(spectre) && /spectre/.test(spectre), 'spectre → Tile(1,1) + periodic-as-bare-polygon');
  const turtle = await clickMark(page,'turtle');
  ok(/Tile\(√3, 1\)/.test(turtle) && /APERIODIC/.test(turtle), 'turtle → Tile(√3, 1) + aperiodic');
  const comet = await clickMark(page,'comet');
  ok(/Tile\(1, 0\)/.test(comet) && /PERIODIC/.test(comet), 'comet → Tile(1, 0) + periodic');
  const chevron = await clickMark(page,'chevron');
  ok(/Tile\(0, 1\)/.test(chevron) && /PERIODIC/.test(chevron), 'chevron → Tile(0, 1) + periodic');

  // slider morph: set to an off-landmark angle and confirm aperiodic + a,b both > 0
  await page.evaluate(()=>{ const s=document.getElementById('i3theta'); s.value=5200; s.dispatchEvent(new Event('input')); });
  await page.waitForTimeout(40);
  const mid = await page.evaluate(()=>document.getElementById('i3read').innerText);
  ok(/APERIODIC/.test(mid) && /a = 0\.6/.test(mid), 'off-landmark slider → aperiodic, a,b both live ('+mid.split('\n')[1]+')');

  // no horizontal overflow
  const ov = await page.evaluate(()=>document.documentElement.scrollWidth - document.documentElement.clientWidth);
  ok(ov<=1, 'no horizontal overflow (Δ='+ov+'px)');

  await page.close();
}

await run({width:1100,height:900}, 'desktop');
await run({width:390,height:844}, 'mobile');

await browser.close(); server.close();
console.log(`\n${fails===0?'✓ ALL PAGE CHECKS PASS':'✗ '+fails+' FAILED'}`);
process.exit(fails?1:0);
