// verify-page.mjs — headless-browser check of the percolation stratum.
//   npm run build && node research/percolation/verify-page.mjs
// Serves dist/, loads the page, drives the three instruments, and asserts:
//   - no console/page errors
//   - Instrument I: dragging p past pc makes the grid span; order-parameter readout moves
//   - Instrument II: the threshold finder accumulates samples and its needle lands near
//     the true pc for site(≈0.593), bond(0.5), triangle(0.5)
//   - Instrument III: the (n+1)xn crossing fraction converges to 0.5
//   - no horizontal overflow at 390px and 1100px
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','.mjs':'text/javascript','.woff2':'font/woff2','.png':'image/png','.svg':'image/svg+xml','.ico':'image/x-icon','.xml':'application/xml' };
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(8131,r));

const browser = await chromium.launch();
let fail = 0; const log = (ok,msg)=>{ console.log((ok?'  ✓ ':'  ✗ ')+msg); if(!ok) fail++; };

async function run(width){
  const page = await browser.newPage({ viewport:{width,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('http://localhost:8131/strata/percolation/',{waitUntil:'networkidle'});
  console.log(`\n— viewport ${width}px —`);
  log(errs.length===0, `no JS/console errors ${errs.length?('('+errs.join(' | ')+')'):''}`);

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

  // Instrument I — set p low then high, observe spanning flip
  await page.evaluate(()=>{ const s=document.getElementById('prange'); s.value=300; s.dispatchEvent(new Event('input')); });
  await page.waitForTimeout(60);
  const spanLow = await page.evaluate(()=> document.getElementById('r-span').textContent.trim());
  await page.evaluate(()=>{ const s=document.getElementById('prange'); s.value=750; s.dispatchEvent(new Event('input')); });
  await page.waitForTimeout(60);
  const spanHigh = await page.evaluate(()=> document.getElementById('r-span').textContent.trim());
  log(spanLow==='no' && spanHigh==='yes', `Instrument I: spans flips no→yes across pc (low=${spanLow}, high=${spanHigh})`);
  // snap to pc button works
  await page.click('#snap'); await page.waitForTimeout(40);
  const pv = await page.evaluate(()=> document.getElementById('pval').textContent);
  log(Math.abs(parseFloat(pv)-0.5927)<0.01, `Instrument I: snap to site pc → p=${pv}`);

  if (width>=1000){
    // Instrument II — let it accumulate, check the needle for each lattice
    async function estFor(btn){
      await page.click(btn); // resets samples
      // run ~2.2s of accumulation
      await page.waitForTimeout(2400);
      return await page.evaluate(()=> ({ est: parseFloat(document.getElementById('tf-est').textContent), n: document.getElementById('tf-n').textContent }));
    }
    const site = await estFor('#t-site');
    log(Number.isFinite(site.est) && Math.abs(site.est-0.593)<0.03, `Instrument II site□: needle ${site.est} ≈ 0.593 (n=${site.n})`);
    const bond = await estFor('#t-bond');
    log(Number.isFinite(bond.est) && Math.abs(bond.est-0.5)<0.03, `Instrument II bond□: needle ${bond.est} ≈ 0.500 (n=${bond.n})`);
    const tri = await estFor('#t-tri');
    log(Number.isFinite(tri.est) && Math.abs(tri.est-0.5)<0.03, `Instrument II site△: needle ${tri.est} ≈ 0.500 (n=${tri.n})`);

    // Instrument III — converges to 0.5
    await page.click('#d-reset');
    await page.waitForTimeout(2600);
    const dual = await page.evaluate(()=> ({ f: parseFloat(document.getElementById('d-cross').textContent), n: document.getElementById('d-n').textContent, err: parseFloat(document.getElementById('d-err').textContent) }));
    log(Math.abs(dual.f-0.5)<0.02, `Instrument III: crossing fraction ${dual.f} → ½ (|err|=${dual.err}, n=${dual.n})`);

    // Instrument IV — measured dots land on Cardy's exact curve, each lattice
    async function gapAfter(btn, secs){
      await page.evaluate(()=>document.getElementById('cardycv').scrollIntoView());
      await page.click(btn); await page.click('#c-reset');
      await page.waitForTimeout(secs*1000);
      return await page.evaluate(()=> ({ gap: parseFloat(document.getElementById('c-gap').textContent), n: document.getElementById('c-n').textContent, status: document.getElementById('c-status').textContent }));
    }
    const c4tri = await gapAfter('#c-tri', 4);
    log(Number.isFinite(c4tri.gap) && c4tri.gap<0.05, `Instrument IV site△ (proved): max gap to Cardy ${c4tri.gap} < 0.05 (n=${c4tri.n}, "${c4tri.status}")`);
    const bond4 = await gapAfter('#c-bond', 4);
    log(Number.isFinite(bond4.gap) && bond4.gap<0.05, `Instrument IV bond□ (conj.): max gap to Cardy ${bond4.gap} < 0.05 (n=${bond4.n}, "${bond4.status}")`);
    const site4 = await gapAfter('#c-site', 4);
    log(Number.isFinite(site4.gap) && site4.gap<0.06, `Instrument IV site□ (conj.): max gap to Cardy ${site4.gap} < 0.06 (n=${site4.n}, "${site4.status}")`);
    const all4 = await gapAfter('#c-all', 4);
    log(Number.isFinite(all4.gap) && all4.gap<0.06, `Instrument IV all-three (universality): max gap ${all4.gap} < 0.06 (n=${all4.n})`);
  }
  await page.close();
}

await run(1100);
await run(390);
await browser.close(); server.close();
console.log('\n'+(fail? `FAILED (${fail})` : 'ALL CHECKS PASSED'));
process.exit(fail?1:0);
