// verify-page.mjs — render the portal in a real headless browser and check it.
//   npm run build && node research/the-first-word-is-the-hardest/verify-page.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 = new URL('../../dist/', import.meta.url).pathname;
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' };
const server = createServer((req,res)=>{
  let p = decodeURIComponent(req.url.split('?')[0]);
  if (p.endsWith('/')) p += 'index.html';
  try { const buf = readFileSync(join(root, p)); res.writeHead(200, {'content-type': types[extname(p)]||'application/octet-stream'}); res.end(buf); }
  catch { res.writeHead(404); res.end('404'); }
});
await new Promise(r => server.listen(8123, r));

let pass = 0, fail = 0;
const ok = (n,c,g)=>{ if(c){pass++;console.log(`  ok   ${n}`);} else {fail++;console.log(`  FAIL ${n}${g!==undefined?`  → ${JSON.stringify(g)}`:''}`);} };

const browser = await chromium.launch();
for (const vp of [{w:390,h:844,nm:'mobile 390'},{w:768,h:1024,nm:'tablet 768'},{w:1440,h:900,nm:'desktop 1440'}]){
  const page = await browser.newPage({ viewport:{width:vp.w,height:vp.h}, 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:8123/strata/the-first-word-is-the-hardest/', { waitUntil:'networkidle' });
  await page.waitForTimeout(400);
  console.log(`\n— ${vp.nm} —`);
  ok('no JS / console errors', errs.length===0, errs);
  const ofw = await page.evaluate(()=> document.documentElement.scrollWidth - document.documentElement.clientWidth);
  ok('no horizontal overflow', ofw<=1, ofw);

  if (vp.w===1440){
    // live check tally
    const tally = await page.textContent('#checkTally');
    ok('live check reports 11 / 11', /\b11 \/ 11\b/.test(tally), tally);
    // Greek renders with the right font (no tofu): measure the source line width is non-trivial
    const gkOK = await page.evaluate(()=>{
      const el = document.querySelector('.pb-source'); if(!el) return false;
      const r = el.getBoundingClientRect();
      // tofu boxes collapse to near-zero or render as identical missing-glyph boxes;
      // a real rendered Greek line is comfortably wide.
      return r.width > 150 && r.height > 10;
    });
    ok('Greek source line renders with width (font loaded, no tofu)', gkOK);
    // Instrument I drew both poem blocks with bars
    const blocks = await page.$$eval('#cmp .poem-block', n=>n.length);
    ok('Instrument I drew 2 poem blocks', blocks===2, blocks);
    const ilRows = await page.$$eval('#cmp .poem-block:nth-child(1) .row', n=>n.length);
    ok('Iliad block has 8 translator rows', ilRows===8, ilRows);
    const aeRows = await page.$$eval('#cmp .poem-block:nth-child(2) .row', n=>n.length);
    ok('Aeneid block has 12 translator rows', aeRows===12, aeRows);
    /* WHICH ROW IS WHICH, not merely how many there are.
       This page's whole subject is that a translated word keeps its sense and loses
       its PLACE, and until 2026-08-14 every assertion here was a count or a
       substring. The arrangement sweep reversed every sequence the page renders, 96
       slots of them, which put Chapman's badge on Butler's row and Butler at the top
       of a chronological list, and this check stayed green. A page about position,
       checked without reading one. Record: arrange-order-*.json. */
    const ilNames = await page.$$eval('#cmp .poem-block:nth-child(1) .row .row-top span:first-child', ns=>ns.map(n=>n.textContent.trim()));
    ok('Iliad rows read oldest translation first, in order',
      ilNames.join(',') === 'Chapman,Pope,Cowper,Buckley,Derby,Bryant,Lang,Butler', ilNames.join(','));
    const aeNames = await page.$$eval('#cmp .poem-block:nth-child(2) .row .row-top span:first-child', ns=>ns.map(n=>n.textContent.trim()));
    ok('Aeneid rows read oldest translation first, in order',
      aeNames.join(',') === 'Douglas,Dryden,Pitt,Conington,Cranch,Morris,Mackail,Bowen,Rhoades,Taylor,Williams,Jackson', aeNames.join(','));
    /* A third assertion stood here and was deleted before it shipped: it read
       `#idTab .row .badge`, that selector matches nothing on this page, and a
       conditional assertion over an empty list passes without ever running. On a
       page about checks that cannot fail, shipping one would have been the joke
       telling itself. */
    // toggle the cause
    await page.click('#causeBtn'); await page.waitForTimeout(150);
    const v = await page.textContent('#cmpVerdict');
    ok('cause toggle updates the verdict', /cano/.test(v), v.slice(0,40));
    // tab to identity, count rows
    await page.click('#tab2 button[data-stage=ident]'); await page.waitForTimeout(150);
    const idRows = await page.$$eval('#identList .ilist-row', n=>n.length);
    ok('Beowulf identity tab has 12 rows', idRows===12, idRows);
    // programme tab steps
    await page.click('#tab2 button[data-stage=prog]'); await page.waitForTimeout(100);
    const tok = await page.$$eval('#progWord .tok', n=>n.length);
    ok('programme tab renders the Latin line tokens', tok===8, tok);
  }
  await page.close();
}
await browser.close(); server.close();
console.log(`\n${fail===0?'✅ ALL PAGE CHECKS PASS':'❌ FAILURES'} — ${pass} ok, ${fail} fail`);
process.exit(fail===0?0:1);
