// verify-gradient-curl-rest.mjs — drive the immersive "The Gradient, the Curl, and the Rest"
// page in a real headless browser: no JS errors; the canvas renders; the presets flip the
// energy bar the way the theorem demands (pure gradient → ~100% gradient, pure curl → ~100%
// curl, + drift raises the harmonic slice); the view toggles work; the live checks read tiny;
// and there is no horizontal overflow at phone / tablet / desktop widths. This is the second
// witness that the in-browser decomposition agrees with research/hodge-field (46/46).
//   npm run build && node verify-gradient-curl-rest.mjs
import pw from '/opt/node22/lib/node_modules/playwright/index.js';
const { chromium } = pw;
import { createServer } from 'http';
import { readFileSync } from 'fs';
import { extname, join } from 'path';

const root = '/home/user/Artificial-Wasteland/dist/';
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(8163,r));
const URL_ = 'http://localhost:8163/strata/the-gradient-the-curl-and-the-rest/';

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

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(' | '));

  const canv = await page.$$eval('canvas', els=>els.map(e=>({w:e.clientWidth,h:e.clientHeight})));
  ok(`[${label}] canvas renders with size`, canv.length>=1 && canv.every(c=>c.w>0&&c.h>0), JSON.stringify(canv));

  // canvas actually paints (not blank) — sample non-uniform pixels
  const painted = await page.evaluate(()=>{ const c=document.getElementById('cv'); const x=c.getContext('2d');
    const d=x.getImageData(0,0,c.width,c.height).data; let mn=255,mx=0; for(let i=0;i<d.length;i+=4*97){ mn=Math.min(mn,d[i]); mx=Math.max(mx,d[i]); } return mx-mn; });
  ok(`[${label}] canvas is painted (pixel spread)`, painted>20, `spread=${painted}`);

  // --- the theorem, exercised through the UI ---
  const clickPreset = async p => { await page.$$eval('#presets button', (els,p)=>{ const b=els.find(x=>x.dataset.p===p); b&&b.click(); }, p);
    await page.waitForTimeout(120); };
  const bar = async () => page.evaluate(()=>({
    g:document.getElementById('eg').style.flexBasis, c:document.getElementById('ec').style.flexBasis, h:document.getElementById('eh').style.flexBasis }));

  await clickPreset('puregrad'); let b = await bar();
  ok(`[${label}] pure gradient → gradient ≈ 100%`, pct(b.g)>99.5, `grad=${b.g}`);
  ok(`[${label}] pure gradient → curl ≈ 0%`, pct(b.c)<0.5, `curl=${b.c}`);

  await clickPreset('purecurl'); b = await bar();
  ok(`[${label}] pure curl → curl ≈ 100%`, pct(b.c)>99.5, `curl=${b.c}`);

  await clickPreset('source'); b = await bar();
  ok(`[${label}] source → mostly gradient`, pct(b.g)>80, `grad=${b.g}`);

  await clickPreset('vortex'); b = await bar();
  ok(`[${label}] vortex → mostly curl`, pct(b.c)>80, `curl=${b.c}`);

  // harmonic: load pure curl (harm ~0), add drift → harmonic slice rises
  await clickPreset('purecurl'); const hBefore = pct((await bar()).h);
  await clickPreset('drift'); const hAfter = pct((await bar()).h);
  ok(`[${label}] + drift raises the harmonic slice`, hAfter>hBefore+5, `${hBefore.toFixed(1)}% → ${hAfter.toFixed(1)}%`);

  // live checks read as tiny numbers (reconstruction/orthogonality/pythagoras)
  const chk = await page.evaluate(()=>({ r:document.getElementById('chk-recon').textContent,
    o:document.getElementById('chk-orth').textContent, p:document.getElementById('chk-pyth').textContent }));
  const tiny = s => { const v=parseFloat(s); return isFinite(v) && Math.abs(v)<1e-3; };
  ok(`[${label}] live reconstruction error is ~0`, tiny(chk.r), `recon=${chk.r}`);
  ok(`[${label}] live orthogonality is ~0`, tiny(chk.o), `orth=${chk.o}`);

  // view toggles switch the caption without error
  await page.$$eval('#views button', els=>{ const b=els.find(x=>x.dataset.view==='curl'); b&&b.click(); });
  const tag = await page.$eval('#cvtag', e=>e.textContent);
  ok(`[${label}] view toggle updates caption`, /curl/i.test(tag), tag);

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

  ok(`[${label}] no JS errors after interaction`, errs.length===0, errs.slice(0,2).join(' | '));
  await ctx.close();
}
await browser.close(); server.close();
console.log(`\n${fails===0?'✓':'✗'} ${fails===0?'all checks passed':fails+' FAILED'}`);
process.exit(fails===0?0:1);
