import pkg from '/opt/node22/lib/node_modules/playwright/index.js';
const { chromium } = pkg;
import http from 'node:http';
import { readFile } from 'node:fs/promises';
import { extname, join, normalize } from 'node:path';

const ROOT = new URL('../../dist/', import.meta.url).pathname;
const MIME = { '.html':'text/html','.css':'text/css','.js':'text/javascript','.mjs':'text/javascript','.woff2':'font/woff2','.png':'image/png','.svg':'image/svg+xml','.xml':'application/xml','.ico':'image/x-icon','.json':'application/json','.txt':'text/plain' };
const server = http.createServer(async (req,res)=>{
  try {
    let p = decodeURIComponent(req.url.split('?')[0]);
    if (p.endsWith('/')) p += 'index.html';
    let fp = normalize(join(ROOT, p));
    if (!fp.startsWith(ROOT)) { res.writeHead(403); return res.end(); }
    const data = await readFile(fp);
    res.writeHead(200, { 'content-type': MIME[extname(fp)] || 'application/octet-stream' });
    res.end(data);
  } catch { res.writeHead(404); res.end('nf'); }
});
await new Promise(r=> server.listen(8137, r));
const URLP = 'http://127.0.0.1:8137/strata/canals-of-mars/';

const b = await chromium.launch();
let fail = 0;
const ok = (c,m)=>{ console.log((c?'  ✓':'  ✗')+' '+m); if(!c) fail++; };

for (const vw of [390, 1100]) {
  const ctx = await b.newContext({ viewport:{ width:vw, height:900 }, deviceScaleFactor:1 });
  const page = await ctx.newPage();
  const errs = [];
  page.on('pageerror', e=> errs.push(String(e)));
  page.on('console', m=> { if (m.type()==='error') errs.push('console: '+m.text()); });
  await page.goto(URLP, { waitUntil:'networkidle' });
  await page.waitForTimeout(400);
  console.log(`\n=== viewport ${vw}px ===`);
  ok(errs.length===0, 'no JS / console errors' + (errs.length?(' :: '+errs.join(' | ')):''));

  // horizontal overflow
  const ov = await page.evaluate(()=> document.documentElement.scrollWidth - document.documentElement.clientWidth);
  ok(ov<=1, `no horizontal overflow (scrollW-clientW=${ov})`);

  // instrument 1: crux toggle
  await page.click('#cruxSwitch button[data-read="art"]');
  const artText = await page.textContent('#cruxLine');
  ok(/canal/i.test(artText), 'crux toggle → "canal" reading shows');
  await page.click('#cruxSwitch button[data-read="nat"]');
  const natText = await page.textContent('#cruxLine');
  ok(/channel/i.test(natText), 'crux toggle → "channel" reading shows');

  // instrument 2: canvas painted (non-empty) + readout
  const cvInfo = await page.evaluate(()=>{
    const cv = document.getElementById('cv');
    if(!cv) return {painted:false};
    const ctx = cv.getContext('2d');
    const d = ctx.getImageData(0,0,cv.width,cv.height).data;
    let nz=0; for(let i=0;i<d.length;i+=4){ if(d[i]+d[i+1]+d[i+2]>10) nz++; }
    return { painted: nz>1000, w:cv.width };
  });
  ok(cvInfo.painted, `illusion canvas is painted (w=${cvInfo.w})`);
  const ro = await page.textContent('#readout');
  ok(/in the data.*0/s.test(ro), 'readout states 0 straight features in the data');

  // toggles work without error
  await page.click('#tgSpots'); await page.click('#tgCanals'); await page.click('#tgNew');
  await page.waitForTimeout(150);
  const ro2 = await page.textContent('#readout');
  ok(/spots placed/.test(ro2), 'toggles + "new field" run cleanly');

  // blur slider
  await page.fill('#blur','100').catch(()=>{});
  await page.evaluate(()=>{ const e=document.getElementById('blur'); e.value=100; e.dispatchEvent(new Event('input')); });
  const bv = await page.textContent('#blurVal');
  ok(/100/.test(bv), 'seeing slider updates (=100)');

  // instrument 3: stratigraphy layers render + expand
  const nLayers = await page.evaluate(()=> document.querySelectorAll('#strata .layer').length);
  ok(nLayers===8, `stratigraphy has 8 layers (${nLayers})`);
  await page.click('#strata .layer');
  const expanded = await page.evaluate(()=> document.querySelector('#strata .layer').getAttribute('aria-expanded'));
  ok(expanded==='true', 'stratigraphy layer expands on click');

  // sources rendered
  const src = await page.textContent('#srclist');
  ok(/Maunder/.test(src) && /Mariner/.test(src), 'sources list rendered');

  await ctx.close();
}
await b.close();
server.close();
console.log(fail? `\nFAILED: ${fail} check(s)` : '\nALL CHECKS PASSED');
process.exit(fail?1:0);
