// verify-page.mjs — drive the built "How You Know" page in a real browser and
// assert both instruments behave after the 2026-06-17 revision.
//   npm run build && node research/how-you-know/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','.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{ 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(8097,r));

let fails=0; const ok=(n,c,extra='')=>{ console.log((c?'  ✓ ':'  ✗ FAIL ')+n+(extra?'  '+extra:'')); if(!c)fails++; };
const browser = await chromium.launch();
for (const vp of [{w:1200,h:900,name:'desktop'},{w:380,h:820,name:'mobile'}]) {
  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:8097/strata/how-you-know/',{waitUntil:'networkidle'});
  await page.waitForTimeout(300);
  console.log(`\n[${vp.name} ${vp.w}x${vp.h}]`);
  ok('no JS / console errors', errs.length===0); if(errs.length) console.log('     '+errs.join('\n     '));

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

  // ── Instrument I (the witness) still renders ──
  const witnessOpts = await page.$$eval('#opts-evid .opt', els=>els.length);
  ok('witness: evidential column has 6 rows (none + 5)', witnessOpts===6, '#='+witnessOpts);

  // ── Tuyuca data table: 5 form cells, none a dash ──
  const tuyForms = await page.evaluate(()=>{
    const caps=[...document.querySelectorAll('table.para caption')];
    const t=caps.find(c=>/Tuyuca/.test(c.textContent));
    if(!t) return null;
    return [...t.closest('table').querySelectorAll('tbody td.form')].map(td=>td.textContent.trim());
  });
  ok('Tuyuca table found with 5 forms', Array.isArray(tuyForms)&&tuyForms.length===5, JSON.stringify(tuyForms));
  ok('Tuyuca table has no dash cell', tuyForms && tuyForms.every(f=>f!=='—'), JSON.stringify(tuyForms));
  ok('Tuyuca table == verified paradigm',
     tuyForms && JSON.stringify(tuyForms)===JSON.stringify(['-wi','-ti','-yi','-yigɨ','-hĩyi']),
     JSON.stringify(tuyForms));

  // ── Instrument II (the comparator) ──
  const srcBtns = await page.$$eval('#srcrow .srcbtn', els=>els.length);
  ok('comparator: 5 source buttons', srcBtns===5, '#='+srcBtns);
  const langCards = await page.$$eval('#langs .langcard', els=>els.length);
  ok('comparator: 3 language cards', langCards===3, '#='+langCards);

  // default state is "heard" — read the three cards
  const read = async () => page.$$eval('#langs .langcard', cards=>cards.map(c=>({
    name: c.querySelector('.lname').textContent,
    form: c.querySelector('.lform').textContent,
    merged: c.classList.contains('merged')
  })));
  let cards = await read();
  const byName = n => cards.find(c=>c.name===n);
  ok('on "heard": Quechua shows -mi and is MERGED', byName('Cuzco Quechua').form==='-mi' && byName('Cuzco Quechua').merged, JSON.stringify(byName('Cuzco Quechua')));
  ok('on "heard": Tuyuca shows -ti and is distinct', byName('Tuyuca').form==='-ti' && !byName('Tuyuca').merged, JSON.stringify(byName('Tuyuca')));
  ok('on "heard": Tariana shows -mahka and is distinct', byName('Tariana').form==='-mahka' && !byName('Tariana').merged, JSON.stringify(byName('Tariana')));
  // the Bashō bridge is showing on "heard"
  const bridgeShown = await page.$eval('#c-bridge', el=>el.classList.contains('show'));
  ok('on "heard": the frog/Bashō bridge is shown', bridgeShown);

  // click "I was told" (last button) — Quechua should now be -si and NOT merged
  await page.$$eval('#srcrow .srcbtn', btns=>{ btns[4].click(); });
  await page.waitForTimeout(120);
  cards = await read();
  ok('on "told": Quechua shows -si and is NOT merged', byName('Cuzco Quechua').form==='-si' && !byName('Cuzco Quechua').merged, JSON.stringify(byName('Cuzco Quechua')));
  ok('on "told": Tuyuca shows -yigɨ', byName('Tuyuca').form==='-yigɨ', JSON.stringify(byName('Tuyuca')));
  ok('on "told": Tariana shows -pidaka', byName('Tariana').form==='-pidaka', JSON.stringify(byName('Tariana')));

  // click "I saw it" (first) — Quechua -mi, merged again (with heard)
  await page.$$eval('#srcrow .srcbtn', btns=>{ btns[0].click(); });
  await page.waitForTimeout(120);
  cards = await read();
  ok('on "saw": Quechua -mi and MERGED (with heard)', byName('Cuzco Quechua').form==='-mi' && byName('Cuzco Quechua').merged, JSON.stringify(byName('Cuzco Quechua')));
  ok('on "saw": Tuyuca -wi and distinct', byName('Tuyuca').form==='-wi' && !byName('Tuyuca').merged);

  await page.close();
}
await browser.close(); server.close();
console.log('\n' + (fails===0 ? 'ALL BROWSER CHECKS PASS' : fails+' BROWSER CHECK(S) FAILED'));
process.exit(fails===0?0:1);
