#!/usr/bin/env node
/* THE SEVEN DOUBLED — page verifier (headless browser)
 *
 * Serves the built dist/ and drives the page in Chromium. Asserts:
 *   - HTTP 200, no JS errors / console errors
 *   - Arabic font actually paints (subset loaded, banner width measured)
 *   - Instrument I gallery has the 4 verbatim translators
 *   - Instrument II: clicking a word fills the wordpane (interlinear live)
 *   - Instrument III: the mālik/malik toggle swaps the alif and the readers
 *   - Instrument IV: both versifications render and total 7
 *   - Instrument V: 9 stratigraphy layers; Pickthall pull-quote present
 *   - the in-page live check ends N/N PASS
 *   - no horizontal overflow at 390 / 768 / 1100 px
 *
 * Usage: npm run build && node research/the-seven-doubled/verify-page.mjs
 */
import pkg from '/opt/node22/lib/node_modules/playwright/index.js';
const { chromium } = pkg;
import { createServer } from 'http';
import { readFileSync } from 'fs';
import { join, extname } 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','.json':'application/json','.ico':'image/x-icon','.xml':'application/xml','.txt':'text/plain' };
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(8137, r));
const URL_ = 'http://127.0.0.1:8137/strata/the-seven-doubled/index.html';

let pass = 0, fail = 0;
const check = (label, ok, detail = '') => { console.log(`  ${ok ? '✓' : '✗'} ${label}${detail ? '  ' + detail : ''}`); ok ? pass++ : fail++; };

const browser = await chromium.launch();
const page = await browser.newPage();
const errors = [], consoleMsgs = [];
page.on('pageerror', e => errors.push(String(e)));
page.on('console', m => { if (m.type() === 'error' || m.type() === 'warning') consoleMsgs.push(m.type() + ': ' + m.text()); });

console.log('\nTHE SEVEN DOUBLED — page verify\n');
const resp = await page.goto(URL_, { waitUntil: 'networkidle' });
check('HTTP 200', resp && resp.status() === 200, `(${resp ? resp.status() : 'no response'})`);
check('No JS errors', errors.length === 0, errors.join('; '));
check('No console errors/warnings', consoleMsgs.length === 0, consoleMsgs.join('; '));

const h1 = (await page.locator('h1').first().textContent() || '').trim();
check("Title is 'The Seven Doubled'", h1 === 'The Seven Doubled', `('${h1}')`);

// Arabic font paints
const bannerW = await page.evaluate(() => { const el = document.querySelector('.banner .ar .aya'); return el ? el.getBoundingClientRect().width : 0; });
check('Arabic font loaded and painted', bannerW > 200, `(banner āya width ${Math.round(bannerW)}px)`);

// Instrument I — 4 translators verbatim
check('Instrument I gallery has 4 rows', (await page.locator('#gallery .row').count()) === 4);
for (const phrase of ['the king of the day of judgment', 'King on the day of reckoning', 'Master of the day of requital', 'Owner of the Day of Judgment']) {
  check(`gallery verbatim: "${phrase.slice(0, 38)}…"`, (await page.locator(`text=${phrase}`).count()) > 0);
}

// Instrument II — interlinear click
check('interlinear renders 7 āyāt', (await page.locator('.interlin .ayah').count()) === 7);
await page.click('.interlin .word'); await page.waitForTimeout(120);
const pane = await page.locator('#wordpane').innerText();
check('clicking a word fills the wordpane', /name|basmala/i.test(pane), `(${pane.length} chars)`);
// click the mālik word and confirm it explains the alif
const malikWord = page.locator('.interlin .word', { hasText: 'مَٰلِكِ' }).first();
await malikWord.click(); await page.waitForTimeout(120);
check('clicking 1:4 mālik explains the absent alif', /alif/i.test(await page.locator('#wordpane').innerText()));

// Instrument III — the reading toggle
const alifWord = () => page.locator('#alif-word').textContent();
check('Instrument III defaults to mālik (Owner)', (await alifWord()).includes('مَالِك'));
await page.click('#rd-king'); await page.waitForTimeout(160);
const kingWord = await alifWord();
check('toggling to King swaps to مَلِك (no alif)', kingWord.includes('مَلِك') && !kingWord.includes('مَالِك'), `('${kingWord}')`);
check('King reading names its canonical readers', /Warsh|Seven|Ibn/i.test(await page.locator('#alif-readers').innerText()));
await page.click('#rd-malik'); await page.waitForTimeout(120);
check('toggling back restores مَالِك (Owner)', (await alifWord()).includes('مَالِك'));

// Instrument IV — both counts total 7
check('Kūfan column has 7 counted segments', (await page.locator('#col-kufa .seg').count()) === 7);
const basraNonBasmala = await page.locator('#col-basra .seg:not(.basmala)').count();
const basmalaUncounted = await page.locator('#col-basra .seg.basmala.uncounted').count();
check('Baṣran column: 7 segments + basmala shown uncounted', basraNonBasmala === 7 && basmalaUncounted === 1, `(${basraNonBasmala}+${basmalaUncounted})`);

// Instrument V — stratigraphy + pull-quotes
check('stratigraphy has 9 layers', (await page.locator('#strata .layer').count()) === 9);
check('Pickthall pull-quote present', (await page.locator('text=The Koran cannot be translated').count()) > 0);
check('Muhammad Ali pull-quote present', (await page.locator('text=two different words from the same root').count()) > 0);

// live check ends green
await page.waitForTimeout(250);
const live = await page.locator('#live-check').textContent();
const m = live.match(/(\d+)\/(\d+) checks PASS/);
check('in-page live check ends N/N PASS', !!m && m[1] === m[2], `('${(live || '').slice(0, 60)}')`);

// overflow
for (const w of [390, 768, 1100]) {
  await page.setViewportSize({ width: w, height: 1000 }); await page.waitForTimeout(100);
  const ov = await page.evaluate(() => Math.max(0, document.documentElement.scrollWidth - document.documentElement.clientWidth));
  check(`no horizontal overflow at ${w}px`, ov === 0, `(overflow ${ov}px)`);
}

console.log(`\n${pass}/${pass + fail} PASS — ${fail === 0 ? 'ALL CHECKS PASS' : fail + ' FAILED'}\n`);
await browser.close(); server.close();
process.exit(fail === 0 ? 0 : 1);
