// verify-ship-of-theseus.mjs — drive the immersive "Ship of Theseus" page in a real
// headless browser: no JS errors; the canvas renders; the slider + / − controls move k;
// the live readout reports the correct N−k / k arithmetic; the three position toggles
// update their description and aria-pressed; no horizontal overflow at phone/tablet/desktop.
//   npm run build && node verify-ship-of-theseus.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(8186,r));
const URL_ = 'http://localhost:8186/strata/ship-of-theseus/';

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

// canvas painted (non-empty)
const painted = await page.evaluate(()=>{
  const cv=document.getElementById('ships'); if(!cv) return false;
  const c=cv.getContext('2d'); const d=c.getImageData(0,0,cv.width,Math.min(40,cv.height)).data;
  // look across whole canvas for any non-background pixel
  const full=c.getImageData(0,0,cv.width,cv.height).data; let nonbg=0;
  for(let i=0;i<full.length;i+=4){ if(full[i]>30||full[i+1]>30||full[i+2]>40) nonbg++; }
  return nonbg>500 && d.length>0;
});
ok('canvas renders the ships', painted);

// default state k=0
let ro = (await page.textContent('#readout')).replace(/\s+/g,' ').trim();
ok('k=0 readout: 16 original, 0 new', /0 of 16 planks replaced/.test(ro) && /16 original, 0 new/.test(ro), ro);

// drag slider to k=16 via setting value + dispatching input
await page.$eval('#k', el=>{ el.value='16'; el.dispatchEvent(new Event('input',{bubbles:true})); });
ro = (await page.textContent('#readout')).replace(/\s+/g,' ').trim();
ok('k=16 readout: 0 original, 16 new; rebuilt 16 original', /16 of 16 planks replaced/.test(ro) && /0 original, 16 new/.test(ro) && /Rebuilt ship: 16 original/.test(ro), ro);
let cap = (await page.textContent('#caption')).replace(/\s+/g,' ').trim();
ok('k=16 caption poses "two ships, which is the Ship of Theseus?"', /Two ships/.test(cap) && /Which is the Ship of Theseus/.test(cap), cap);

// + / − buttons
await page.click('#minus');
ro = (await page.textContent('#readout')).replace(/\s+/g,' ').trim();
ok('minus → k=15 (15 new, 1 original)', /15 of 16 planks replaced/.test(ro) && /1 original, 15 new/.test(ro), ro);
await page.click('#plus');
ro = (await page.textContent('#readout')).replace(/\s+/g,' ').trim();
ok('plus → back to k=16', /16 of 16 planks replaced/.test(ro), ro);

// the three positions
for (const [v, needle] of [['continuity','never left the water'],['matter','original timber'],['deflation','decision about how we choose']]) {
  await page.click(`#views button[data-v="${v}"]`);
  const pressed = await page.getAttribute(`#views button[data-v="${v}"]`, 'aria-pressed');
  const desc = (await page.textContent('#viewdesc')).replace(/\s+/g,' ').trim();
  ok(`position "${v}" toggles on and shows its honest text`, pressed==='true' && desc.includes(needle), desc.slice(0,60));
  await page.click(`#views button[data-v="${v}"]`); // toggle back off
}
const allOff = await page.evaluate(()=>Array.from(document.querySelectorAll('#views button')).every(b=>b.getAttribute('aria-pressed')==='false'));
ok('no position is selected by default / after toggling off (none marked correct)', allOff);

// verbatim quotes present in the DOM
const body = (await page.textContent('body')).replace(/\s+/g,' ');
ok('Plutarch verbatim present', body.includes('the logical question of things that grow'));
ok('Hobbes verbatim present', body.includes('two ships numerically the same, which is absurd'));

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

await browser.close(); await new Promise(r=>server.close(r));
console.log(fails===0 ? '\nPASS — page behaves and is honest.' : `\nFAIL — ${fails} check(s).`);
process.exit(fails?1:0);
