// verify-page.mjs — drive the built /tools/sky-now/ page in a real browser and
// assert the tool works end to end.
//   npm run build && node research/sky-now/verify-page.mjs
//
// Sky Now reuses the verified ephem.mjs (checked by
// research/the-sky-above-you/verify.mjs, 42/42). This script checks the TOOL
// wiring: the location form + the manual-coordinate fallback set a place; the
// time controls re-render; the sky chart draws the 7 bodies; the planet rows,
// moon phase, twilight ladder and hood fill in; scrubbing moves a body; the
// share URL carries place + moment; and the stratum-only layers (the /api/marks
// map and the ground-portal cross-links) are gone while the canonical way-out
// footer + top-bar loader are present.
//
// Exits non-zero on any JS/console error, missing element, or empty content.

// Resolved, not hardcoded (corrected 2026-08-06): this was an absolute path into
// one machine's global node_modules, so the verifier only ran on that machine.
// A verifier a stranger cannot run is not showing the check, it is describing it.
const { chromium } = await import('playwright');
import { BRIGHT_STARS } from './catalogue.mjs';
import { createServer } from 'http';
import { readFileSync, mkdirSync } from 'fs';
import { extname, join, dirname } from 'path';

const root = new 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',
  '.json':'application/json','.xml':'application/xml','.md':'text/markdown',
};
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(8098, 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}]`);

  // Land with a known place + moment via URL params (deterministic).
  const T_MS = Date.UTC(2026, 5, 13, 22, 0, 0);   // 2026-06-13 22:00 UT
  await page.goto(
    `http://localhost:8098/tools/sky-now/?place=London&lat=51.5074&lng=-0.1278&t=${T_MS}`,
    { waitUntil: 'networkidle' }
  );
  await page.waitForTimeout(300);

  ok('no JS / console errors', errs.length === 0);
  if (errs.length) console.log('     ' + errs.join('\n     '));

  // Auto-loaded from the URL: the output is visible.
  const outVisible = await page.$eval('#out', el => !el.classList.contains('hidden'));
  ok('URL params auto-load the sky (place + lat/lng + t)', outVisible);

  // The sky disc has the 7 bodies (Sun, Moon, 5 planets).
  const bodyCircles = await page.$$eval('#sky circle.sun, #sky circle.moon, #sky circle.mercury, #sky circle.venus, #sky circle.mars, #sky circle.jupiter, #sky circle.saturn', els => els.length);
  ok('sky disc has 7 body circles (Sun + Moon + 5 planets)', bodyCircles === 7, 'count=' + bodyCircles);

  const eclLen = await page.$eval('#sky path.ecliptic', p => p.getAttribute('d').length).catch(() => 0);
  ok('ecliptic path drawn', eclLen > 200, 'd.len=' + eclLen);

  const compass = await page.$$eval('#sky text.compass', els => els.map(e => e.textContent));
  ok('cardinal directions N/E/S/W on sky chart',
     ['N','E','S','W'].every(d => compass.includes(d)), compass.join(','));

  const cards = await page.$$eval('#bodies .body', els => els.map(e => e.dataset.name));
  ok('7 body cards listed',
     cards.length === 7 && cards[0] === 'Sun' && cards[1] === 'Moon' && cards.includes('Mercury') && cards.includes('Saturn'),
     cards.join(','));

  const altRe = /[+-]?\d+\.\d°/;
  for (const name of ['Sun', 'Moon', 'Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn']) {
    const alt = await page.textContent(`#bodies .body[data-name="${name}"] .alt`);
    ok(`${name} shows altitude + azimuth`, altRe.test(alt), alt.slice(0, 50).replace(/\s+/g, ' '));
  }
  for (const name of ['Sun', 'Moon', 'Jupiter']) {
    const rts = await page.textContent(`#bodies .body[data-name="${name}"] .rts`);
    ok(`${name} has rise/transit/set`,
       /rise/i.test(rts) && /transit/i.test(rts) && /set/i.test(rts) && /\d{1,2}:\d{2}|—|never/.test(rts),
       rts.replace(/\s+/g, ' ').slice(0, 60));
  }

  const moonD = await page.$eval('#moonLit', el => el.getAttribute('d') || '');
  ok('Moon phase SVG path set', moonD.length > 20, 'd.len=' + moonD.length);
  const moonName = await page.textContent('#moonName');
  ok('Moon phase named', /Moon|Crescent|Gibbous|Quarter|Full|New/.test(moonName), moonName);
  const moonPct = await page.textContent('#moonPct');
  ok('Moon illumination % is a number', /^\d+%$/.test(moonPct.trim()), moonPct);

  const twRows = await page.$$eval('#twilight .row', els => els.length);
  ok('twilight ladder has 8 rows', twRows === 8, 'rows=' + twRows);
  const daylen = await page.textContent('#daylen');
  ok('day-length line present', /daylight|Sun does not/.test(daylen), daylen.slice(0, 70));

  const hood = await page.textContent('#hoodDetails');
  ok('hood shows JD + sidereal time + observer coords',
     /JD [0-9.]+/.test(hood) && /Greenwich mean sidereal time/.test(hood) && /lat 51\.5/.test(hood),
     hood.slice(0, 60).replace(/\s+/g, ' '));

  // Scrub moves the Sun.
  const sunBefore = await page.$eval('#sky circle.sun', e => e.getAttribute('cx') + ',' + e.getAttribute('cy'));
  await page.$eval('#scrub', el => { el.value = 6; el.dispatchEvent(new Event('input')); });
  await page.waitForTimeout(200);
  const sunAfter = await page.$eval('#sky circle.sun', e => e.getAttribute('cx') + ',' + e.getAttribute('cy'));
  ok('scrubbing time moves the Sun', sunBefore !== sunAfter, `${sunBefore} → ${sunAfter}`);
  const scrubT = await page.textContent('#scrubT');
  ok('scrub readout reflects offset', /\+?6/.test(scrubT), scrubT);

  // Share URL reflects place + moment.
  const url = await page.evaluate(() => location.href);
  ok('shareable URL carries place + lat/lng + t',
     /place=London/.test(url) && /lat=51\.5074/.test(url) && /[?&]t=\d+/.test(url), url.slice(0, 90));

  await page.click('#nowBtn');
  await page.waitForTimeout(200);
  ok('"Now" resets the scrub', (await page.textContent('#scrubT')) === 'now');

  // TOOL-SPECIFIC: manual coordinate entry works with no geocoder.
  await page.fill('#latIn', '-33.87');
  await page.fill('#lngIn', '151.21');
  await page.click('#coordForm button[type=submit]');
  await page.waitForTimeout(250);
  const hoodCoord = await page.textContent('#hoodDetails');
  ok('manual lat/lng entry sets the observer (Sydney)',
     /lat -33\.87/.test(hoodCoord) && /lng 151\.21/.test(hoodCoord),
     hoodCoord.slice(0, 60).replace(/\s+/g, ' '));

  // Bad coordinates never take effect — the observer stays at the last valid
  // place (native min/max validation and the JS range-guard both reject 999).
  await page.fill('#latIn', '999'); await page.fill('#lngIn', '0');
  await page.click('#coordForm button[type=submit]');
  await page.waitForTimeout(150);
  const hoodBad = await page.textContent('#hoodDetails');
  ok('out-of-range latitude does not change the observer (stays Sydney)',
     /lat -33\.87/.test(hoodBad), hoodBad.slice(0, 50).replace(/\s+/g, ' '));

  // The stratum-only layers are gone.
  ok('no /api/marks collective layer in the tool', (await page.$('#marks')) === null);
  ok('no ground-portal cross-links in the tool', (await page.$('#doorway')) === null);
  const htmlSrc = await page.content();
  ok('no world-outline / marks script pulled in', !/world-outline\.js/.test(htmlSrc) && !/\/api\/marks/.test(htmlSrc));

  // Canonical chrome per design-system §6.
  ok('canonical way-out footer present', (await page.$('footer.aw-wayout')) !== null);
  ok('home-banner top-bar loader present', /\/media\/home-banner\.js/.test(htmlSrc));

  // ── the fixed stars, the Milky Way, and the addressable link (added 2026-08-06) ──
  {
    const nStars = await page.locator('#sky circle.star').count();
    ok('the catalogue is drawn on the chart', nStars > 0 && nStars <= BRIGHT_STARS.length,
       nStars + ' of ' + BRIGHT_STARS.length + ' stars above this horizon');
    // The shipped catalogue must be the one the builder produced, byte for byte.
    ok('the page ships the catalogue the builder wrote, unchanged',
       readFileSync(new URL('../../public/tools/sky-now/catalogue.mjs', import.meta.url)).equals(
         readFileSync(new URL('./catalogue.mjs', import.meta.url))));
    const listed = await page.locator('#starsList .row').count();
    ok('and listed underneath it, brightest first', listed > 0, listed + ' rows');
    const mags = await page.evaluate(() =>
      [...document.querySelectorAll('#starsList .val')].map((e) => parseFloat(e.textContent.replace(/^mag\s+/, ''))));
    ok('the listed stars really are in magnitude order',
       mags.every((m, i) => i === 0 || mags[i - 1] <= m + 1e-9), mags.slice(0, 5).join(', '));
    const mw = (await page.locator('#milkyWay').textContent()).trim();
    ok('the galactic centre is reported with an altitude', /Milky Way/.test(mw) && /[-+]?\d/.test(mw), mw.slice(0, 90));
    ok('and it does not claim the band is visible when the Sun is up',
       !(/sky is astronomically dark/.test(mw) && /Sun is only \+/.test(mw)));
    // Rebuilt 2026-09-26: Hipparcos rows moved by stars.mjs, no longer SIMBAD.
    ok('the catalogue provenance is on the page, with ESA\'s licence and credit line',
       /Hipparcos/.test(htmlSrc) && /CC BY-NC 3\.0 IGO/.test(htmlSrc) && /Credit: ESA/.test(htmlSrc));
    ok('the page says proper motion IS applied and names what is not',
       /moved along its own proper motion/.test(htmlSrc) && /aberration and the nutation of the star's position are not/.test(htmlSrc.replace(/\s+/g, ' ')));
    ok('the page runs the same stars.mjs the stratum runs, byte for byte',
       readFileSync(new URL('../../public/tools/sky-now/stars.mjs', import.meta.url)).equals(
         readFileSync(new URL('../../public/strata/the-sky-above-you/stars.mjs', import.meta.url))));
    const rk = await page.evaluate(() => [...document.querySelectorAll('#sky circle.star title')].map((t) => t.textContent));
    ok('star tooltips name the star and its magnitude', rk.length > 0 && rk.every((t) => /magnitude -?\d/.test(t)), rk.slice(0, 2).join(' | '));
    ok('the URL grammar is documented on the page', /the link is documented/i.test(htmlSrc) || /Any sky is a link/.test(htmlSrc));
  }

  // A PLACE NAME ALONE must open a sky. This is the property that lets somebody
  // (or a model) write a link by hand, and it is the whole point of the grammar.
  {
    const p2 = await browser.newPage({ viewport: { width: 1280, height: 900 } });
    const errs2 = [];
    p2.on('pageerror', (e) => errs2.push(String(e)));
    await p2.goto('http://localhost:8098/tools/sky-now/?place=Reykjavik', { waitUntil: 'networkidle' });
    await p2.waitForTimeout(4500);
    const st = (await p2.locator('#status').textContent()).trim();
    ok('a place name on its own opens that sky', /Reykjav/i.test(st) && /sky above/i.test(st), st.slice(0, 80));
    const url2 = p2.url();
    ok('and the address is rewritten with the resolved coordinates, so the next share needs no lookup',
       /[?&]lat=-?\d/.test(url2) && /[?&]lng=-?\d/.test(url2), url2.slice(0, 100));
    ok('no JS errors on the place-only path', errs2.length === 0, errs2.join(' | '));
    await p2.close();
  }

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

  // debug full-page screenshot (the feature card is made by shoot-card.mjs)
  const shot = `research/sky-now/page-${vp.name}.png`;
  await page.screenshot({ path: shot, fullPage: true });
  console.log(`     screenshot → ${shot}`);

  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);
