#!/usr/bin/env node
/* Headless-browser check for /strata/the-pile-that-sorts-itself/.
   Serves public/ statically and drives the page: the toppling-pile canvas renders
   and topples to a stable state; an EVEN pile ends sorted; the live enumerator
   reproduces a(0..4)=1,3,12,54,232 in-browser; the endings galleries render 3 and
   12 permutations; no JS errors; no horizontal overflow at 390/768/1440.
   Run: node verify-the-pile-that-sorts-itself.mjs */
import http from 'node:http';
import { readFile } from 'node:fs/promises';
import { existsSync, statSync } from 'node:fs';
import { join, extname } from 'node:path';
import pkg from '/opt/node22/lib/node_modules/playwright/index.js';
const { chromium } = pkg;

const ROOT = new URL('.', import.meta.url).pathname;
const T = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.woff2': 'font/woff2', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon' };
const server = http.createServer(async (req, res) => {
  let p = decodeURIComponent(req.url.split('?')[0]);
  if (p.endsWith('/')) p += 'index.html';
  const fp = join(ROOT, 'public', p);
  if (!existsSync(fp) || !statSync(fp).isFile()) { res.writeHead(404); res.end('nf'); return; }
  res.writeHead(200, { 'content-type': T[extname(fp)] || 'application/octet-stream' });
  res.end(await readFile(fp));
});
await new Promise(r => server.listen(0, r));
const base = 'http://localhost:' + server.address().port;

const browser = await chromium.launch();
let pass = 0, fail = 0;
const ok = (cond, label) => { if (cond) { pass++; console.log('  ✓ ' + label); } else { fail++; console.error('  ✗ FAIL: ' + label); } };
const errors = [];

const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.on('pageerror', e => errors.push(String(e.message)));
page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); });
await page.goto(base + '/strata/the-pile-that-sorts-itself/', { waitUntil: 'networkidle' });

/* ── Instrument I: the toppling pile ── */
ok(await page.locator('#board').count() === 1, 'pile canvas present');
const drew = await page.evaluate(() => {
  const c = document.getElementById('board'); const ctx = c.getContext('2d');
  const d = ctx.getImageData(0, 0, c.width, c.height).data;
  let n = 0; for (let i = 0; i < d.length; i += 4) if (d[i] + d[i+1] + d[i+2] > 60) n++;
  return n;
});
ok(drew > 500, 'canvas rendered chips (non-background pixels=' + drew + ')');

// EVEN pile (N=6) must end sorted, whatever the run chose
await page.selectOption('#npick', '6');
await page.locator('#run').click();
await page.waitForFunction(() => /ended at/.test(document.getElementById('rd').textContent), { timeout: 15000 });
const even = await page.locator('#rd').innerText();
ok(/ended at\s+1 2 3 4 5 6/.test(even) && /sorted/.test(even), 'even pile N=6 topples to sorted 1 2 3 4 5 6: ' + even.replace(/\s+/g, ' ').trim());

// ODD pile (N=5) reaches a stable ending too
await page.selectOption('#npick', '5');
await page.locator('#run').click();
await page.waitForFunction(() => /ended at/.test(document.getElementById('rd').textContent), { timeout: 15000 });
const odd = await page.locator('#rd').innerText();
ok(/ended at/.test(odd), 'odd pile N=5 reaches a stable ending: ' + odd.replace(/\s+/g, ' ').trim().slice(0, 40));

/* ── Instrument II: the live enumerator reproduces the known terms ── */
await page.waitForFunction(() => /1, 3, 12, 54, 232/.test(document.getElementById('ctnote').textContent), { timeout: 20000 });
const note = await page.locator('#ctnote').innerText();
ok(/a\(0…4\) = 1, 3, 12, 54, 232/.test(note), 'live in-browser: a(0..4) = 1, 3, 12, 54, 232 reproduced');
const ckLive = await page.locator('#ck-live').innerText();
ok(/1, 3, 12, 54, 232/.test(ckLive) && /✓/.test(ckLive), 'check bullet updated with the live reproduction');
// the table shows a(5)=819 in the odd column
const tableTxt = await page.locator('#ctab').innerText();
ok(/819/.test(tableTxt), 'count table shows the new term a(5)=819');

/* ── the endings galleries ── */
await page.waitForFunction(() => document.querySelectorAll('#g3 .p').length === 3, { timeout: 10000 });
ok(await page.locator('#g3 .p').count() === 3, 'N=3 gallery renders all 3 reachable endings');
ok(await page.locator('#g5 .p').count() === 12, 'N=5 gallery renders all 12 reachable endings');
ok(await page.locator('#g3 .p.sorted').count() === 1, 'the sorted ending is marked in the N=3 gallery');

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

ok(errors.length === 0, 'no JS console/page errors' + (errors.length ? ' — ' + errors.slice(0, 3).join(' | ') : ''));

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