// verify-page.mjs — drive the built /tools/still-awake/ page in a real browser.
//   npm run build && node research/still-awake/verify-page.mjs
// Checks the wiring: adding a drink shows the chart; the band (two edges +
// shaded polygon) draws; the readout fills; changing the metabolizer profile
// shifts the half-life band; the reference slider + bedtime update; the share
// URL round-trips; the disclaimer + citations are on the page. Also captures
// the feature-card screenshot.
import pw from '/opt/node22/lib/node_modules/playwright/index.js';
const { chromium } = pw;
import { createServer } from 'http';
import { readFileSync, mkdirSync } from 'fs';
import { extname, join, dirname } from 'path';

const root = new globalThis.URL('../../dist/', import.meta.url).pathname;
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','.md':'text/markdown' };
const server = createServer((req, res) => {
  let p = decodeURIComponent(req.url.split('?')[0]); if (p.endsWith('/')) p += 'index.html';
  try { const b = readFileSync(join(root, p)); res.writeHead(200, { 'content-type': types[extname(p)] || 'application/octet-stream' }); res.end(b); }
  catch { res.writeHead(404); res.end('404'); }
});
await new Promise(r => server.listen(8101, 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: 1280, h: 1000, name: 'desktop' }, { w: 390, 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()); });
  console.log(`\n[${vp.name} ${vp.w}x${vp.h}]`);

  await page.goto('http://localhost:8101/tools/still-awake/', { waitUntil: 'networkidle' });
  await page.waitForTimeout(250);
  ok('no JS / console errors on load', errs.length === 0);
  if (errs.length) console.log('     ' + errs.join('\n     '));

  ok('disclaimer says not medical advice', /not medical advice/i.test(await page.textContent('.disclaimer')));
  ok('output hidden until a drink is added', await page.$eval('#out', el => el.classList.contains('hidden')));

  // add two coffees
  await page.click('#add button:nth-child(1)');   // + Coffee (8 oz)
  await page.waitForTimeout(150);
  await page.click('#add button:nth-child(1)');
  await page.waitForTimeout(200);
  ok('adding a drink reveals the chart', !(await page.$eval('#out', el => el.classList.contains('hidden'))));
  ok('two drink rows listed', (await page.$$('#list .drink-row')).length === 2);

  // chart drew: shaded band polygon + two edge paths
  const poly = await page.$$eval('#chart polygon', els => els.length);
  const paths = await page.$$eval('#chart path', els => els.length);
  ok('chart drew a shaded band polygon', poly >= 1, 'polys=' + poly);
  ok('chart drew the fast + slow edge curves', paths >= 2, 'paths=' + paths);

  // readout populated
  const readout = await page.textContent('#readout');
  ok('readout mentions the reference crossing with two times', /between|fast|slow|reference/i.test(readout));

  // set bedtime, expect a bedtime card with an mg range
  await page.fill('#bedtime', '23:30');
  await page.waitForTimeout(150);
  ok('bedtime card shows an mg range still in you', /mg likely still in you/i.test(await page.textContent('#readout')));

  // changing the profile shifts the half-life band (hood reflects it)
  await page.selectOption('#profile', 'smoker');
  await page.waitForTimeout(150);
  await page.click('#hood summary');
  const hoodSmoker = await page.textContent('#hoodBody');
  ok('profile=smoker shows the 2.5–4 h band', /2\.5[–-]4 h/.test(hoodSmoker), hoodSmoker.slice(0, 60).replace(/\s+/g, ' '));
  await page.selectOption('#profile', 'pregnant3');
  await page.waitForTimeout(150);
  ok('profile=pregnant shows the 10–15 h band', /10[–-]15 h/.test(await page.textContent('#hoodBody')));

  // reference slider updates its readout
  await page.$eval('#ref', el => { el.value = 50; el.dispatchEvent(new Event('input')); });
  await page.waitForTimeout(120);
  ok('reference slider readout updates', (await page.textContent('#refv')).includes('50'));

  // share URL round-trips place/drinks/profile
  await page.click('#share');
  await page.waitForTimeout(120);
  const url = await page.evaluate(() => location.href);
  ok('share URL carries drinks + profile + bedtime + ref', /[?&]d=/.test(url) && /[?&]p=pregnant3/.test(url) && /[?&]b=23%3A30|b=23:30/.test(url) && /[?&]r=50/.test(url), url.slice(0, 100));

  // citations present
  ok('links the NIH bookshelf + Drake sources', /NBK223808/.test(await page.content()) && /PMC3805807/.test(await page.content()));

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

  // Resolve the screenshot beside THIS file rather than from the working directory.
  // A root-relative path only lands correctly when the verifier is run from the repo
  // root; run it from its own directory, as the corpus sweep does, and it silently
  // creates research/<name>/research/<name>/page-*.png instead. Three verifiers did
  // that on 2026-08-21 and left 3.8 MB of duplicate screenshots behind.
  await page.screenshot({ path: new globalThis.URL(`./page-${vp.name}.png`, import.meta.url).pathname, fullPage: true });
  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);
