GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / tools/ci/lightning

Overlay Engine Test (part 2)

A test in the lightning folder of GridAtlas that checks Minidom and Reference Module F, using SHA-256 and haversine.

700 lines of JavaScript from gridatlas, in 1 file. Topic: Maps, GIS and field navigation. Section 626 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Overlay Engine Test test · gridatlas / tools/ci/lightning/overlay-engine.test.mjs lines 701–1400

Overlay Engine Test

A test in the lightning folder of GridAtlas that checks Minidom and Reference Module F, using SHA-256 and haversine.

testgridatlas / tools/ci/lightning/overlay-engine.test.mjs · lines 701–1400 of 2505 (continued from section 625) · Entry point · pattern origNearest (shared by 2 files)

What it does
It tests the REPD register and solar. Defines 118 functions or classes, including track, TResponse, iso, ymd, enc. Uses libraries node:test, node:assert/strict, node:vm, node:fs, node:zlib. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar, 33kV.
Inputs & outputs
In: GeoJSON file f.geojson; JSON file index.json; JSON file x.json; JSON file 05.json; JSON file 00.json; GeoJSON file uk_lightning.geojson; JSON file g.json; JSON file repd_master.json. Out: interactive map. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid). Voltage levels named: 33kV.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
It adds event listener (`addEventListener`), wraps fetch (`wrapFetch`) and dumps card (`dumpCard`). Defines `track`, `TResponse`, `iso` and 109 more. Its code works with 10 MW, 33 kV and 0 MW. It reads `/index.json`.
Why it matters
Guards the behaviour of Minidom and Reference Module F.
Application
gridatlas · tools/ci/lightning · test
Uses
Minidom (import), Reference Module F (new URL import.meta.url), node:test, node:assert/strict, node:vm, node:fs, node:zlib, node:crypto
Used by
none found
Produces
track, TResponse, iso, ymd, enc, flash, feed, dayFile, mkIndex, boot, tapMap, XHR
Defines here
ser, pct, run, mins, searchedPct, tapFlash, haversine, hav, origNearest, installNeon, cellF, card, GC, gday, mkGrids, cellsSrc, gridUrls, cellHit, kmTo, partsRow
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/ci/lightning/overlay-engine.test.mjs:701-1400 · blob ae6f8517baf054d0d21ba75a5bb962bfb99bbad2 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
});

test('NF1: when day files fail with the index up, Actual is "unknown (day files failed)" and Flashes shows index vs loaded, never "at least 0"', async () => {
  const d = ymd(Date.now() - D), x = boot({ index: mkIndex({ [d]: { count: 7, bytes: 100, path: P(d), sha256: 'x' } }) });
  x.toggle(true); x.click(x.chip('48h')); await drain();
  assert.equal(x.S.last.state, 'FAIL');
  assert.equal(x.cap('actual'), 'Actual  unknown (day files failed)');
  assert.match(x.cap('flashes'), /^Flashes 7 in index · 0 loaded/); assert.doesNotMatch(x.cap('flashes'), /at least 0/);
});

test('NF2: a redirected index (fetch) or feed (XHR responseURL off the requested URL) is rejected', async () => {
  let x = boot({ index: mkIndex(), redirect: 'index' }); x.toggle(true); await drain();
  assert.equal(x.S.idx, null, 'redirected index accepted'); assert.match(x.S.ie || '', /redirected/);
  x = boot({ redirect: 'feed' }); x.toggle(true); await drain();
  assert.equal(x.S.last.state, 'FAIL', 'redirected feed accepted'); assert.equal(x.S.last.drawn, 0);
});

test('RO: the right inset follows the HIDE LAYERS button live size (ResizeObserver), also after the button is replaced', async () => {
  const x = boot({ ro: true, dash: { top: 788, bottom: 832, left: 274, right: 377, width: 103, height: 44 }, innerHeight: 844 });
  x.main.group._rect = { right: 385 }; x.toggle(true); await drain();
  assert.equal(x.main.group.style.paddingRight, '127px');
  assert.ok(x.robs.length >= 1, 'no ResizeObserver attached');
  x.dashEl._rect = { top: 788, bottom: 832, left: 234, right: 377, width: 143, height: 44 }; x.robs.at(-1).f();
  assert.equal(x.main.group.style.paddingRight, '167px');
  const nb = x.doc.createElement('button'); nb.id = 'gridatlas-dash-toggle'; nb._rect = { top: 788, bottom: 832, left: 254, right: 377, width: 123, height: 44 };
  x.dashEl.parentNode.removeChild(x.dashEl); x.doc.documentElement.children[0].appendChild(nb); x.fire('click');
  assert.equal(x.robs.at(-1).el, nb, 'observer not re-attached to the new button');
  assert.equal(x.main.group.style.paddingRight, '147px');
});

// ---------------------------------------------------------------- variant G (fail-first against fixed-module-F.js)
test('R1/CRF-1: a fractional part count (0.5) rejects the index', async () => {
  const d = ymd(Date.now());
  const x = boot({ index: mkIndex({ [d]: { count: 3, path: null, sealed: false, parts: [{ path: partPath(d, 1), count: 0.5, bytes: 1, sha256: 'x' }] } }) });
  x.toggle(true); await drain();
  assert.equal(x.S.idx, null); assert.match(x.S.ie || '', /parts/);
});

test('R2: a tampered SEALED shard is FAIL naming the mismatch, never "archive updating"', async () => {
  const d = ymd(Date.now() - 4 * D), s = shard(d, 2, Date.parse(d + 'T12:00:00Z'));
  const x = boot({ index: mkIndex({ [d]: { ...s.row, sha256: '0'.repeat(64), sealed: true } }), files: { [s.row.path]: s.b } });
  x.toggle(true); x.click(x.chip('7d')); await drain();
  assert.equal(x.S.last.state, 'FAIL');
  assert.match(x.cap('warning'), new RegExp(d + ' index mismatch: sha256'));
  assert.doesNotMatch(x.cap('warning'), /archive updating/);
});

test('T10/CRF-3b: after a failed retry the caption names date and field; status never SEARCHED n%; reason is not "gaps in window"', async () => {
  const d = ymd(Date.now() - D), t = Date.parse(d + 'T12:00:00Z'), old = shard(d, 1, t), cur = shard(d, 2, t);
  const x = boot({ index: mkIndex({ [d]: old.row }), files: { [cur.row.path]: cur.b } });
  x.toggle(true); x.click(x.chip('48h')); await drain();
  assert.match(x.cap('warning'), new RegExp(d + ' index mismatch: count[^·]*archive updating, reload later'));
  assert.doesNotMatch(x.status(), /SEARCHED \d+%/);
  assert.ok(!x.S.last.reasons.includes('gaps in window'), JSON.stringify(x.S.last.reasons));
});

test('E06 (G): a future-dated index does not read "<1 min ago"', async () => {
  const x = boot({ index: mkIndex({}, { generated_utc: iso(Date.now() + 2 * H), next_update_due_utc: iso(Date.now() + 3 * H) }) });
  x.toggle(true); await drain();
  assert.doesNotMatch(x.cap('refresh'), /<1 min ago/); assert.match(x.cap('refresh'), /\(\? ago/);
});

test('REST: before ON there are no requests, map sources or map listeners; outside the hidden controls the group is identical to F', async () => {
  const x = boot(); await drain();
  assert.equal(x.log.fetch.length + x.log.xhr.length, 0); assert.equal(x.sources.size, 0); assert.equal(x.handlers.length, 0, 'map listener before ON');
  assert.equal(x.main.ctl.hidden, true, 'controls not hidden at rest');
  const ser = el => el.hasAttribute && el.hasAttribute('data-lightning-controls') ? '[controls hidden=' + el.hidden + ']' : el.tagName + JSON.stringify([...el.attrs]) + el.children.map(c => c.tagName ? ser(c) : c.textContent).join('');
  globalThis.__SRC_OVERRIDE = readFileSync(new URL('./fixtures/reference-module-F.js', import.meta.url), 'utf8');
  let y; try { y = boot(); } finally { globalThis.__SRC_OVERRIDE = undefined; }
  assert.equal(ser(x.main.group), ser(y.main.group));
  assert.equal(JSON.stringify(x.main.group.style), JSON.stringify(y.main.group.style));
});

test('I01: without WebCrypto, a shard with valid count/bytes but a false sha256 is not drawn as verified (PARTIAL "not verified (no WebCrypto)")', async () => {
  const d = ymd(Date.now() - 4 * D), s = shard(d, 2, Date.parse(d + 'T12:00:00Z'));
  const x = boot({ noCrypto: true, index: mkIndex({ [d]: { ...s.row, sha256: 'f'.repeat(64) } }), files: { [s.row.path]: s.b } });
  x.toggle(true); x.click(x.chip('7d')); await drain();
  assert.equal(x.S.last.drawn, 0, 'unverified shard drawn');
  assert.equal(x.S.last.state, 'PARTIAL');
  assert.match(x.cap('warning'), new RegExp(d + ' not verified \\(no WebCrypto\\)'));
  assert.doesNotMatch(x.status(), /SEARCHED \d+%/);
});

// ---------------------------------------------------------------- variant H (fail-first against fixed-module-G.js)
const NOTICE = 'Only the last 7 days are available yet. The 12-month archive is being collected and backfilled; earlier months are unknown, not zero.';
const LBASE = 'Lightning Flashes (Optical)';

test('H1: feed-only 12M reads "[n · last 7 days only]", never "≥n | 12m"; bold first caption line; 7-DAY FEED ONLY status', async () => {
  const x = boot(); x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.equal(x.label(), `${LBASE} [1 | last 7 days only]`); // J: kv-words
  const capEl = x.main.group.querySelector('[data-lightning-caption]');
  assert.equal(capEl.children[1].dataset.cap, 'days'); assert.equal(x.cap('days'), 'Last 7 days only (live feed) · archive not yet published · earlier days unknown, not zero'); // J: kv-words
  assert.match(capEl.children[1].getAttribute('style'), /font-weight:bold/);
  assert.equal(x.status(), '1 FLASH · LAST 7 DAYS ONLY · OLDER NOT YET COLLECTED');
  for (const p of ['30d', '3m']) { x.click(x.chip(p)); await drain(); assert.match(x.label(), /\[1 \| last 7 days only\]/, p); }
  x.click(x.chip('7d')); await drain(); assert.doesNotMatch(x.cap('days'), /Last 7 days only/); assert.doesNotMatch(x.label(), /last 7 days only/);
});

test('H1: in feed fallback the 30D-12M chips carry a dim marker and stay tappable; with an archive they carry none', async () => {
  const x = boot(); x.toggle(true); await drain();
  for (const p of ['30d', '3m', '6m', '12m']) { const b = x.chip(p); assert.equal(b.disabled, false); assert.equal(b.lastChild.textContent, ' •', p); assert.equal(b.lastChild.style.opacity, '.55'); assert.ok(b.title); }
  assert.equal(x.chip('7d').textContent, '7D');
  const y = boot({ index: mkIndex() }); y.toggle(true); await drain();
  for (const p of ['30d', '12m']) assert.ok(!/•/.test(y.chip(p).textContent), 'marker with an archive');
  y.click(y.chip('12m')); await drain(); assert.doesNotMatch(y.label(), /last 7 days only/); assert.doesNotMatch(y.cap('days'), /live feed/);
});

test('H2: dots 6/8/10 px at z5/z8/z11 with a 1.5 px dark stroke and light core, plus an invisible >=22 px hit layer', async () => {
  const x = boot(); x.toggle(true); await drain();
  const p = x.layers.get('l-gridatlas-lightning').paint;
  assert.equal(JSON.stringify(p['circle-radius']), JSON.stringify(['interpolate', ['linear'], ['zoom'], 5, 6, 8, 8, 11, 10]));
  assert.equal(p['circle-stroke-width'], 1.5); assert.match(p['circle-stroke-color'], /^#[0-3][0-9a-f]{5}$/i);
  const hit = x.layers.get('gridatlas-lightning-hit'); assert.ok(hit, 'no hit layer');
  assert.ok(hit.paint['circle-radius'] >= 22); assert.equal(hit.paint['circle-opacity'], 0); assert.equal(hit.layout.visibility, 'visible');
  const pt = x.sources.get('gridatlas-lightning').data.features[0];
  assert.deepEqual([...pt.geometry.coordinates], [-1.5, 52], 'coordinates changed');
});

test('H2: above the phone cap clusters get count labels and a tap on a cluster zooms in', async () => {
  const fs = []; for (let k = 0; k < 10001; k++) fs.push(flash(Date.now() - H - k, 'c' + k, [-1.5 + (k % 100) / 1000, 52 + Math.floor(k / 100) / 1000]));
  const x = boot({ phone: true, feedFn: () => feed(fs) }); x.toggle(true); await drain();
  assert.ok(x.layers.get('l-gridatlas-lightning-count'), 'no cluster count layer');
  assert.equal(JSON.stringify(x.layers.get('l-gridatlas-lightning-count').layout['text-field']), '["get","point_count_abbreviated"]');
  x.sources.get('gridatlas-lightning').getClusterExpansionZoom = (id, cb) => cb(null, 9);
  x.tapMap([10, 10], { 'gridatlas-lightning-hit': [{ properties: { cluster: true, cluster_id: 7, point_count: 50 }, geometry: { coordinates: [-1.5, 52] } }] });
  assert.equal(x.camera.length, 1); assert.equal(x.camera[0][0], 'easeTo'); assert.equal(x.camera[0][1][0].zoom, 9);
});

test('H3/I1/J2: tapping a flash opens a Lightning-owned docked card (not maplibregl.Popup): bar "Flash <UTC>", lat/lon + short ID row, full ID, honesty line', async () => {
  // The flash must sit inside the 7D window whenever the suite runs: a fixed date (it was 2026-10-25) rots after 7 days.
  const t = Math.floor((Date.now() - 2 * H) / 1000) * 1000 + 149, f = flash(t, 'abc-123', [-4.4874, 55.1637]);
  const stamp = new Date(t).toISOString().slice(0, 19).replace('T', ' ');
  const x = boot({ feedFn: () => feed([f]) }); x.toggle(true); x.click(x.chip('7d')); await drain();
  x.tapMap([5, 5], { 'gridatlas-lightning-hit': [{ properties: { i: 0 }, geometry: { coordinates: [-4.49, 55.16] } }] });
  assert.equal(x.popups.length, 0, 'maplibregl.Popup used');
  const card = x.mapEl.querySelector('[data-lightning-card]'); assert.ok(card, 'no card in the map container');
  const txt = card.textContent;
  for (const s of [`Flash ${stamp} UTC`, 'lat 55.164, lon -4.487 · ID abc-123', 'Flash ID abc-123', 'EUMETSAT MTG Lightning Imager · optical flash, not necessarily a ground strike.']) assert.ok(txt.includes(s), s);
  x.tapMap([200, 200], {}); assert.equal(x.mapEl.querySelector('[data-lightning-card]'), null, 'card not closed on an empty tap');
  x.tapMap([5, 5], { 'gridatlas-lightning-hit': [{ properties: { i: 0 }, geometry: { coordinates: [0, 0] } }] });
  x.toggle(false); assert.equal(x.mapEl.querySelector('[data-lightning-card]'), null, 'card not closed on OFF');
});

test('H3: an original layer click handler still fires when no flash is under the tap (and when one is)', async () => {
  const x = boot(); let fired = 0; x.map.on('click', 'orig-substations', () => fired++);
  x.toggle(true); await drain();
  x.tapMap([1, 1], { 'orig-substations': [{ properties: { name: 'X' } }] });
  assert.equal(fired, 1); assert.equal(x.popups.length, 0);
  x.tapMap([1, 1], { 'orig-substations': [{ properties: { name: 'X' } }], 'gridatlas-lightning-hit': [{ properties: { i: 0 }, geometry: { coordinates: [0, 0] } }] });
  assert.equal(fired, 2);
});

test('H4: FIT FLASHES fits the map to drawn flashes only when tapped; the outside-view count is recounted on moveend', async () => {
  let b = [-3, 50, 2, 53];
  const t = Date.now() - 20 * H, x = boot({ bounds: null, feedFn: () => feed([flash(t, 'a', [-4.2, 55.3]), flash(t + 1, 'b', [-1.5, 52])]) });
  x.map.getBounds = () => ({ contains: ([lo, la]) => lo >= b[0] && la >= b[1] && lo <= b[2] && la <= b[3] });
  x.toggle(true); x.click(x.chip('48h')); await drain();
  assert.equal(x.nav('fit').hidden, false); assert.deepEqual(x.camera, []);
  assert.match(x.cap('flashes'), /1 of 2 outside the current view/);
  b = [-5, 50, 2, 56]; for (const h of x.handlers.filter(h => h.t === 'moveend')) h.f();
  assert.doesNotMatch(x.cap('flashes'), /outside the current view/);
  x.click(x.nav('fit'));
  assert.equal(x.camera.length, 1); assert.equal(x.camera[0][0], 'fitBounds');
  assert.equal(JSON.stringify(x.camera[0][1][0]), JSON.stringify([[-4.2, 52], [-1.5, 55.3]]));
});

test('H4: restored "12 months" period label and aria-live on the caption', async () => {
  const x = boot(); assert.equal(x.main.group.querySelector('[data-lightning-caption]').getAttribute('aria-live'), 'polite');
  x.toggle(true); x.click(x.chip('12m')); await drain(); assert.match(x.cap('window'), /12 months/);
});

test('H4 CRF-2/2b: a lost day is subtracted once even when scan windows overlap', async () => {
  const now = Date.now(), cutoff = Date.parse(ymd(now) + 'T00:00:00Z') - 365 * D, w1 = { start_utc: iso(cutoff), end_utc: iso(now), successful_runs: 9 };
  const d3 = ymd(now - 3 * D), lost = { [d3]: { coverage: 'none', scanned_seconds: 0, count: null, shard_lost: true } };
  const pct = async sw => { const x = boot({ index: mkIndex(lost, { scan_windows: sw }) }); x.toggle(true); x.click(x.chip('7d')); await drain(); return x.cap('searched'); };
  assert.equal(await pct([w1, { ...w1 }]), await pct([w1]));
});

test('H2b: the cluster label font comes from the basemap style (first symbol layer with text-font), else Open Sans Regular', async () => {
  const fs = []; for (let k = 0; k < 10001; k++) fs.push(flash(Date.now() - H - k, 'c' + k, [-1.5 + (k % 100) / 1000, 52 + Math.floor(k / 100) / 1000]));
  const run = async style => { const x = boot({ phone: true, feedFn: () => feed(fs) }); x.map.getStyle = () => style; x.toggle(true); await drain(); return JSON.stringify(x.layers.get('l-gridatlas-lightning-count').layout['text-font']); };
  assert.equal(await run({ glyphs: 'g', layers: [{ type: 'fill', layout: {} }, { type: 'symbol', layout: { 'text-field': 'x' } }, { type: 'symbol', layout: { 'text-font': ['Montserrat Medium', 'Open Sans Bold'] } }, { type: 'symbol', layout: { 'text-font': ['Other'] } }] }), '["Montserrat Medium","Open Sans Bold"]');
  assert.equal(await run({ layers: [{ type: 'fill' }] }), '["Open Sans Regular"]');
  assert.equal(await run(undefined), '["Open Sans Regular"]');
});

// ---------------------------------------------------------------- variant I (fail-first against fixed-module-H.js)
const mins = s => { let m = 0; for (const [, v, u] of s.matchAll(/(\d+) (h|min)/g)) m += u === 'h' ? 60 * v : +v; return m; };
const searchedPct = t => { const r = /Searched EUMETSAT (.+?) of (.+?)( ·|$)/.exec(t); return r ? Math.floor(100 * mins(r[1]) / mins(r[2])) : (/none of this window/.test(t) ? 0 : 100); };
const tapFlash = (x, i = 0) => x.tapMap([5, 5], { 'gridatlas-lightning-hit': [{ properties: { i }, geometry: { coordinates: [0, 0] } }] });
const haversine = (lo1, la1, lo2, la2) => { const r = Math.PI / 180, a = Math.sin((la2 - la1) * r / 2) ** 2 + Math.cos(la1 * r) * Math.cos(la2 * r) * Math.sin((lo2 - lo1) * r / 2) ** 2; return 2 * 6371.0088 * Math.asin(Math.sqrt(a)); };
// the original's public measure, reproduced from sld-sandbox 202609241334 C:3509 (nearestSubstations) with its geodesy (R 6378.137 km)
const hav = (lo1, la1, lo2, la2) => { const r = Math.PI / 180, a = Math.sin((la2 - la1) * r / 2) ** 2 + Math.cos(la1 * r) * Math.cos(la2 * r) * Math.sin((lo2 - lo1) * r / 2) ** 2; return 2 * 6378.137 * Math.asin(Math.sqrt(a)); };
const origNearest = (lon, lat, subs) => { const sc = []; let beyond = null; for (const sub of subs) { const km = hav(lon, lat, sub.at[0], sub.at[1]); if (km > 40) { if (!beyond || km < beyond.km) beyond = { ...sub, km }; continue; } sc.push({ ...sub, km }); }
  sc.sort((a, b) => a.km - b.km); const res = sc.slice(0, 5); res.beyondRadiusNearest = res.length ? null : beyond; res.radiusKm = 40; return res; };
const SUBS = [
  { at: [-1.505, 52.002], kv: [33], name: 'Tiny 33kV' }, { at: [-1.6, 52.0], kv: [132], name: 'A 132' }, { at: [-1.5, 52.2], kv: [400, 132], name: 'B 400' },
  { at: [-1.7, 52.1], kv: [66], name: 'C 66' }, { at: [-1.4, 51.9], kv: [275], name: 'D 275' }, { at: [-1.3, 52.15], kv: [33], name: 'E 33' }, { at: [-4.0, 55.0], kv: [400], name: 'Far 400' }];
const installNeon = (x, subs) => { x.neonCalls = []; x.W.__GRIDATLAS_NEON_LINKS__ = { substations: subs, measure: { nearestSubstations: (lo, la, ss) => { x.neonCalls.push([lo, la, ss]); return origNearest(lo, la, ss); } } }; };

test('I1/J2: the card is docked at the bottom (bar 44 px − and ×), explicit inline colours, minimise keeps the bar, × closes; repositioned on resize, not on move', async () => {
  const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); x.mapEl._rect = { top: 0, left: 0, right: 393, bottom: 700, width: 393, height: 700 }; x.toggle(true); await drain();
  tapFlash(x); const card = x.mapEl.querySelector('[data-lightning-card]'); assert.ok(card);
  const st = card.style.cssText; assert.match(st, /position:absolute/); assert.match(st, /background:#000/); assert.match(st, /color:#e8f4f5/); assert.match(st, /border:1px solid #2f6f75/);
  assert.equal(card.style.bottom, '8px'); assert.equal(card.style.top, undefined);
  const [mn, close] = card.querySelectorAll('button'); assert.equal(mn.getAttribute('aria-label'), 'Hide list'); assert.equal(mn.textContent, '▾ Hide list'); /* M6: a toggle that says what it does (was '−' Minimise) */ assert.match(close.style.cssText, /width:44px;height:44px/); assert.equal(close.getAttribute('aria-label'), 'Close');
  dispatch(mn, 'click', x.log.errors); assert.equal(card.querySelector('details').open, false); assert.notEqual(card.children[1].style.display, 'none', 'M6: the bar, summary and footer stay'); assert.equal(mn.getAttribute('aria-expanded'), 'false'); assert.match(mn.textContent, /^▸ Show (\d+ sites?|list)$/);
  assert.ok(x.handlers.some(h => h.t === 'resize'), 'no resize listener'); assert.ok(!x.handlers.some(h => h.t === 'move'), 'card still follows move');
  dispatch(close, 'click', x.log.errors); assert.equal(x.mapEl.querySelector('[data-lightning-card]'), null);
});

test('I2: 3M and 12M with 763 archived flashes load and draw points automatically', async () => {
  const files = {}, over = {}; let total = 0;
  for (let k = 1; k <= 18; k++) { const d = ymd(Date.now() - k * D), n = k === 18 ? 763 - total : 42; total += n; const s = shard(d, n, Date.parse(d + 'T10:00:00Z')); files[s.row.path] = s.b; over[d] = s.row; }
  for (const p of ['3m', '12m']) {
    const x = boot({ index: mkIndex(over), files }); x.toggle(true); x.click(x.chip(p)); await drain();
    assert.equal(x.S.res.mode, 'detail', p); assert.equal(x.S.last.drawn, 763, p); assert.equal(x.S.res.clp, undefined, p);
  }
});

test('I2: 12M with 50,000 archived flashes still asks first (LOAD POINTS); a phone asks above its 10,000 cap', async () => {
  const d1 = ymd(Date.now() - 40 * D), d2 = ymd(Date.now() - 41 * D);
  let x = boot({ index: mkIndex({ [d1]: { count: 25000, bytes: 1000, path: P(d1), sha256: 'x' }, [d2]: { count: 25000, bytes: 1000, path: P(d2), sha256: 'y' } }) });
  x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.equal(x.S.res.clp, true); assert.equal(x.nav('points').hidden, false); assert.equal(x.log.fetch.filter(u => u.includes('/days/')).length, 0);
  x = boot({ phone: true, index: mkIndex({ [d1]: { count: 15000, bytes: 1000, path: P(d1), sha256: 'x' } }) });
  x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.equal(x.S.res.clp, true, 'phone loaded 15,000 points without asking');
});

test('I3/J1: tapping a flash fires the original nearestSubstations (>=33 kV, <=40 km, 5) and draws the neon arrival; no NEAREST button', async () => {
  const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); installNeon(x, SUBS);
  x.toggle(true); await drain(); tapFlash(x);
  const card = x.mapEl.querySelector('[data-lightning-card]'); assert.equal(card.querySelector('[data-lightning-nearest]'), null, 'button still present');
  assert.deepEqual(x.neonCalls.map(a => [a[0], a[1]]), [[-1.5, 52]], 'original nearestSubstations not called with the flash');
  const src = x.sources.get('gridatlas-lightning-neon-links'); assert.ok(src, 'no neon links source');
  assert.equal(src.data.features.length, 5); assert.equal(src.data.features[0].properties.colour, '#d8c96a');
  assert.match(card.textContent, /0\.\d\d km · 33 kV · Tiny 33kV/); assert.doesNotMatch(card.textContent.split('REPD projects')[0], /Far 400|project/i); // M: projects follow the substation rows
  assert.match(card.textContent, /Screening · nearest substations to this optical flash, straight line\. Proximity, not exposure or a current path; not evidence any asset was struck\./);
  dispatch(card.querySelectorAll('button')[1], 'click', x.log.errors);
  assert.equal(x.sources.get('gridatlas-lightning-neon-links'), undefined); assert.equal(x.layers.get('gridatlas-lightning-neon-core'), undefined);
  tapFlash(x); assert.ok(x.sources.get('gridatlas-lightning-neon-links'));
  x.toggle(false); assert.equal(x.sources.get('gridatlas-lightning-neon-links'), undefined, 'lines kept after OFF');
});

test('I3: the module never invents a repd_ref, never touches the URL', () => {
  assert.doesNotMatch(SRC.replace(/\bo\.repd_ref\b/g, ''), /repd_ref|location\.(href|search|hash|assign|replace)|history\.(push|replace)State/); // M5: a shown record's own ref only
});

test('I1b: with overlapping hit circles, the tap opens the flash nearest the tap point', async () => {
  const t = Date.now() - H, x = boot({ feedFn: () => feed([flash(t, 'far', [-1.0, 52.0]), flash(t + 1, 'near', [-1.5, 52.0])]) });
  x.toggle(true); await drain();
  x.tapMap({ x: -14, y: 520 }, { 'gridatlas-lightning-hit': [{ properties: { i: 0 }, geometry: { coordinates: [0, 0] } }, { properties: { i: 1 }, geometry: { coordinates: [0, 0] } }] });
  assert.match(x.mapEl.querySelector('[data-lightning-card]').textContent, /Flash ID near/);
});

// ---------------------------------------------------------------- variant J (fail-first against fixed-module-I.js)
test('J1: a tap flies to zoom 12 over 1200 ms like the original arrival, and fitBounds (top 150, bottom clear of the card; LR-layout) only when a link end is off screen', async () => {
  let inView = true; const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); installNeon(x, SUBS);
  x.mapEl.clientHeight = 659; x.mapEl.clientWidth = 393; x.setProj(() => inView ? { x: 200, y: 200 } : { x: 200, y: 600 });
  x.toggle(true); await drain(); tapFlash(x); await Promise.resolve(); // M4: the in-view check also runs after the stop
  assert.equal(JSON.stringify(x.camera.map(c => c[0])), '["flyTo"]'); const fo = x.camera[0][1][0];
  assert.equal(fo.zoom, 12); assert.equal(fo.duration, 1200); assert.equal(JSON.stringify(fo.center), '[-1.5,52]');
  inView = false; x.camera.length = 0; tapFlash(x); await Promise.resolve(); // M4 (M2R-taps T1): the framing runs after the stop that fired moveend
  assert.equal(JSON.stringify(x.camera.map(c => c[0])), '["flyTo","fitBounds"]');
  { const c0 = x.mapEl.querySelector('[data-lightning-card]'); assert.equal(JSON.stringify(x.camera[1][1][1].padding), JSON.stringify({ top: 150, left: 40, right: 40, bottom: (c0.bb + c0.offsetHeight || 196) + 24 })); } // L3: LR-layout
});

test('J1: the arrival layers match the original (glow, core, 2 flow, node ring, node, label, origin halo + ring); colour #d8c96a; labels "x.xx km · N kV"', async () => {
  const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); installNeon(x, SUBS); x.map.getStyle = () => ({ glyphs: 'g', layers: [{ type: 'symbol', layout: { 'text-font': ['Montserrat Medium'] } }] });
  x.toggle(true); await drain(); tapFlash(x);
  for (const id of ['glow', 'core', 'flow', 'flow-b', 'node-ring', 'node', 'label', 'pin-halo', 'pin']) assert.ok(x.layers.get('gridatlas-lightning-neon-' + id), id);
  assert.equal(JSON.stringify(x.layers.get('gridatlas-lightning-neon-glow').paint), JSON.stringify({ 'line-color': ['get', 'colour'], 'line-width': ['interpolate', ['linear'], ['zoom'], 6, 5, 12, 12], 'line-opacity': 0.1, 'line-blur': ['interpolate', ['linear'], ['zoom'], 6, 3, 12, 8] }));
  assert.equal(x.layers.get('gridatlas-lightning-neon-node').paint['circle-color'], '#5fbdc2'); assert.equal(x.layers.get('gridatlas-lightning-neon-pin-halo').paint['circle-stroke-color'], '#d8c96a');
  const labels = x.sources.get('gridatlas-lightning-neon-nodes').data.features.map(f => f.properties.label);
  assert.ok(labels.every(l => /^\d+\.\d\d km · \d+ kV$/.test(l)), JSON.stringify(labels)); assert.equal(labels.length, 5);
  assert.ok(!['gridatlas-lightning-neon-core', 'gridatlas-lightning-hit'].some(id => id.startsWith('l-')));
});

test('J1: with no substation within 40 km the card says so with the nearest beyond, and nothing is drawn; not-loaded and errors are honest', async () => {
  const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'sea', [-10.5, 50.0])]) }); installNeon(x, SUBS);
  x.toggle(true); await drain(); tapFlash(x);
  assert.match(x.mapEl.querySelector('[data-lightning-card]').textContent, /No substation within 40 km \(nearest: C 66, \d+\.\d\d km\)/);
  assert.equal(x.sources.get('gridatlas-lightning-neon-links'), undefined); assert.deepEqual(x.camera, []);
  const y = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); y.W.__GRIDATLAS_NEON_LINKS__ = Object.create({ substations: SUBS, measure: { nearestSubstations: origNearest } });
  y.toggle(true); await drain(); tapFlash(y); assert.match(y.mapEl.querySelector('[data-lightning-card]').textContent, /Substation data not loaded yet/, 'inherited substations used');
  const z = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); z.W.__GRIDATLAS_NEON_LINKS__ = { substations: SUBS, measure: { nearestSubstations: () => { throw new Error('boom'); } } };
  z.toggle(true); await drain(); tapFlash(z); assert.match(z.mapEl.querySelector('[data-lightning-card]').textContent, /Substation data unavailable\./); assert.equal(z.sources.get('gridatlas-lightning-neon-links'), undefined);
});

test('J1/R2: the card and lines close on PREV and on a period change, but survive the 10-minute refresh', async () => {
  const x = boot({ index: mkIndex({ [ymd(Date.now() - D)]: (() => { const d = ymd(Date.now() - D), sh = shard(d, 1, Date.now() - 20 * H); x0files[sh.row.path] = sh.b; sh.row.at = 0; return sh.row; })() }), files: x0files });
  installNeon(x, SUBS); x.toggle(true); x.click(x.chip('48h')); await drain(); tapFlash(x);
  assert.ok(x.sources.get('gridatlas-lightning-neon-links'));
  x.log.intervals.find(i => i.ms === 6e5).f(); await drain();
  assert.ok(x.mapEl.querySelector('[data-lightning-card]'), 'refresh closed the card');
  x.click(x.nav('prev')); await drain();
  assert.equal(x.mapEl.querySelector('[data-lightning-card]'), null); assert.equal(x.sources.get('gridatlas-lightning-neon-links'), undefined);
  x.click(x.nav('latest')); await drain(); tapFlash(x); x.click(x.chip('7d')); await drain();
  assert.equal(x.mapEl.querySelector('[data-lightning-card]'), null, 'period change kept the card');
});
const x0files = {};

test('J2: the card shows a short ID and keeps the full ID; bidi/zero-width characters are stripped and IDs capped at 200; object ids are rejected; a stale tap opens nothing', async () => {
  const pid = 'W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+LI-2-LFL--FD--x-x--ARC-x_C_EUMT_20261022205024_L2PF_OPE_20261022204009_20261022205009_N__O_0125_0000:4458';
  let x = boot({ feedFn: () => feed([flash(Date.now() - H, pid, [-1.5, 52])]) }); x.toggle(true); await drain(); tapFlash(x);
  let t = x.mapEl.querySelector('[data-lightning-card]').textContent; assert.match(t, /ID 20:40–20:50 #4458/); assert.ok(t.includes('Flash ID ' + pid));
  x = boot({ feedFn: () => feed([flash(Date.now() - H, 'evil\u202Eid\u200B' + 'x'.repeat(400), [-1.5, 52])]) }); x.toggle(true); await drain(); tapFlash(x);
  t = x.mapEl.querySelector('[data-lightning-card]').textContent; assert.ok(!/[\u202E\u200B]/.test(t)); assert.ok(!t.includes('x'.repeat(201)));
  x = boot(); assert.equal(x.probe.ok({ ...flash(Date.now(), 'o'), id: { toString: () => 'x' } }), false);
  x = boot({ feedFn: () => feed([flash(Date.now() - H, 'a', [-1.5, 52])]) }); x.toggle(true); await drain();
  x.tapMap([5, 5], { 'gridatlas-lightning-hit': [{ properties: { i: 0, s: -1 }, geometry: { coordinates: [0, 0] } }] });
  assert.equal(x.mapEl.querySelector('[data-lightning-card]'), null, 'stale hit index opened a card');
});

test('J3: archive wording: "[1,480 | 29 of 31 days searched]"-style label, "N FLASHES · 29 OF 31 DAYS SEARCHED (k IN PART)" status, caption line 2; no "≥", no bare %', async () => {
  const over = {}, files = {}; for (const k of [1, 2]) { const d = ymd(Date.now() - k * D), sh = shard(d, 3, Date.parse(d + 'T10:00:00Z')); files[sh.row.path] = sh.b; over[d] = sh.row; }
  over[ymd(Date.now() - 3 * D)] = { coverage: 'partial', scanned_seconds: 3600 };
  for (const k of [20, 21]) over[ymd(Date.now() - k * D)] = { coverage: 'none', scanned_seconds: 0, count: null };
  const x = boot({ index: mkIndex(over), files }); x.toggle(true); x.click(x.chip('30d')); await drain();
  assert.equal(x.label(), `${LBASE} [6 | 29 of 31 days searched]`);
  assert.equal(x.status(), '6 FLASHES · 29 OF 31 DAYS SEARCHED (1 IN PART)');
  assert.match(x.cap('days'), /^29 of 31 days searched \(\d+ \w{3}–\d+ \w{3}, 1 in part\) · 2 not yet searched \(unknown, not zero\)$/);
  for (const s of [x.label(), x.status(), ...['window', 'days', 'actual', 'flashes', 'refresh', 'searched', 'warning'].map(k => x.cap(k))]) { assert.doesNotMatch(s, /≥/, s); assert.doesNotMatch(s, /\d%/, s); }
});

test('J3: STALE is the search frontier (not nextDue or a backfill-bumped generated_utc), shown as COLLECTOR LAST RAN …, on the latest page only', async () => {
  const now = Date.now(), cutoff = Date.parse(ymd(now) + 'T00:00:00Z') - 365 * D;
  const idx = mkIndex({}, { generated_utc: iso(now - 600e3), next_update_due_utc: iso(now + H), scan_windows: [{ start_utc: iso(cutoff), end_utc: iso(now - 6 * H), successful_runs: 9 }] });
  const x = boot({ index: idx }); x.toggle(true); x.click(x.chip('7d')); await drain();
  assert.equal(x.S.last.stale, true, 'backfill-bumped generated_utc hid a 6 h old frontier'); assert.match(x.status(), /COLLECTOR LAST RAN (\d\d? [A-Z]{3} )?\d\d:\d\d UTC, SEARCHED TO (\d\d? [A-Z]{3} )?\d\d:\d\d UTC · STALE$/); // M4: the date is named when the frontier (or, in the first 10 min after 00:00 UTC, the collector run) is on an earlier UTC day
  x.click(x.nav('prev')); await drain(); assert.equal(x.S.last.stale, false, 'STALE printed on an earlier page');
  const y = boot({ index: mkIndex({}, { generated_utc: iso(now - 600e3), next_update_due_utc: iso(now - 60e3) }) }); y.toggle(true); await drain();
  assert.equal(y.S.last.stale, false, 'nextDue alone made it STALE');
});

test('J3: pages before the searched history read "not yet searched", never "0"; PREV stops at the archive start; a period change and LATEST reset paging; CUSTOM To after today is refused', async () => {
  const now = Date.now(), cs = ymd(now - 10 * D), over = {};
  for (let k = 11; k <= 365; k++) over[ymd(now - k * D)] = { coverage: 'none', scanned_seconds: 0, count: null };
  const x = boot({ index: mkIndex(over, { coverage_start_utc: cs + 'T00:00:00Z', scan_windows: [{ start_utc: cs + 'T00:00:00Z', end_utc: iso(now), successful_runs: 9 }] }) });
  x.toggle(true); x.click(x.chip('7d')); await drain(); x.click(x.nav('prev')); await drain(); x.click(x.nav('prev')); await drain();
  assert.match(x.cap('flashes'), /^Flashes not yet searched \(unknown, not zero\)$/); assert.match(x.label(), /\[not yet searched \| 0 of \d+ days searched\]/);
  assert.equal(x.nav('prev').disabled, true, 'PREV still offered before the archive start');
  x.click(x.chip('48h')); await drain(); assert.equal(x.S.res.w.atLatest, true, 'period change kept the old page');
  assert.equal(x.S.h.length, 0);
  x.click(x.chip('custom')); await drain(); x.main.from.value = ymd(now); x.main.to.value = ymd(now + 2 * D); x.click(x.nav('apply')); await drain();
  assert.match(x.cap('warning'), /Custom dates invalid/);
});

test('J4: the shard cache holds a long window (no re-download on refresh); the label keeps the index count when day files fail', async () => {
  const over = {}, files = {}; for (let k = 2; k <= 13; k++) { const d = ymd(Date.now() - k * D), sh = shard(d, 1, Date.parse(d + 'T10:00:00Z')); files[sh.row.path] = sh.b; over[d] = sh.row; }
  const x = boot({ index: mkIndex(over), files }); x.toggle(true); x.click(x.chip('30d')); await drain();
  const n0 = x.log.fetch.filter(u => u.includes('/days/')).length; x.log.intervals.find(i => i.ms === 6e5).f(); await drain();
  assert.equal(x.log.fetch.filter(u => u.includes('/days/')).length, n0, 'sealed day files re-downloaded on the refresh');
  const d = ymd(Date.now() - D), y = boot({ index: mkIndex({ [d]: { count: 7, bytes: 10, path: P(d), sha256: 'x' } }) }); y.toggle(true); y.click(y.chip('48h')); await drain();
  assert.match(y.label(), /\[FAIL\]|\[7 \|/);
});

test('J5: a sub-day overview sums only the overlapping hourly parts; after consent the status reads "N OF M FLASHES"', async () => {
  const d = ymd(Date.now() - 40 * D), parts = [1, 2].map(h => ({ path: partPath(d, h), count: 30000, bytes: 1000, sha256: 'x' }));
  const x = boot({ phone: true, index: mkIndex({ [d]: { count: 60000, path: null, parts } }) }); x.toggle(true); x.click(x.chip('12m')); await drain();
  x.click(x.nav('points')); await drain();
  assert.match(x.status(), /OF 60,000 FLASHES|^FAIL/);
  const t = Date.now(), dd = ymd(t), hh = new Date(t).getUTCHours(), pp = [{ path: partPath(dd, (hh + 23) % 24), count: 5, bytes: 1, sha256: 'x' }, { path: partPath(dd, 0), count: 9, bytes: 1, sha256: 'y' }];
  if (hh >= 2) { const y = boot({ index: mkIndex({ [dd]: { count: 14, path: null, parts: pp, sealed: false } }) }); y.toggle(true); y.click(y.chip('12h')); await drain(); assert.ok(y.S.res.arch <= 14); }
});

test('J6 (kv-vogel a): a single ResizeObserver — the old one is disconnected when the button is replaced and on OFF; ON observes again', async () => {
  const x = boot({ ro: true, dash: { top: 788, bottom: 832, left: 274, right: 377, width: 103, height: 44 }, innerHeight: 844 });
  x.toggle(true); await drain(); const first = x.robs.at(-1).o;
  const nb = x.doc.createElement('button'); nb.id = 'gridatlas-dash-toggle'; nb._rect = { top: 788, bottom: 832, left: 254, right: 377, width: 123, height: 44 };
  x.dashEl.parentNode.removeChild(x.dashEl); x.doc.documentElement.children[0].appendChild(nb); x.fire('click');
  assert.equal(first.off, 1, 'old observer not disconnected'); const second = x.robs.at(-1).o; assert.notEqual(second, first);
  x.toggle(false); assert.equal(second.off, 1, 'observer kept after OFF');
  x.toggle(true); await drain(); assert.notEqual(x.robs.at(-1).o, second, 'not observed again after ON');
});

test('J7 (browser T4): a stale feed status ends with the collector phrase and "· STALE"', async () => {
  const x = boot({ feedFn: () => feed([flash(Date.now() - 7 * H, 'a')], 6) }); x.toggle(true); await drain();
  assert.match(x.status(), /COLLECTOR LAST RAN [^·]+ UTC · STALE$/);
});

test('J7 (browser T2): an unreadable index timestamp in the window is named in the 12M warning line', async () => {
  const d = ymd(Date.now() - 5 * D), sh = shard(d, 2, Date.parse(d + 'T10:00:00Z'));
  const x = boot({ index: mkIndex({ [d]: { ...sh.row, first_observation_utc: 'not-a-date', last_observation_utc: iso(Date.parse(d + 'T11:00:00Z')) } }), files: { [sh.row.path]: sh.b } });
  x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.match(x.cap('warning'), /1 archive entry unreadable \(malformed timestamp; unknown, not zero\)/);
  x.click(x.chip('7d')); await drain(); assert.match(x.cap('window'), /7 days/);
});

// ---------------------------------------------------------------- L-engine: a tap on a lightning CELL circle fires the same engine (fail-first against fixed-module-J.js)
const CELL = 'gridatlas-lightning-cell';
const cellF = (p, at) => ({ properties: { ...p }, geometry: { type: 'Point', coordinates: at || [p.lon, p.lat] } });
const C1 = { n: 1234, cell: 25 * 140 + 94, lon: -1.55, lat: 52.05 };
const bootCell = async (feedFlashes = [flash(Date.now() - H, 'z', [-1.5, 52])]) => {
  const x = boot({ feedFn: () => feed(feedFlashes) }); installNeon(x, SUBS); x.toggle(true); await drain();
  x.map.addLayer({ id: CELL, type: 'circle', source: 'gridatlas-lightning-cells' });
  // MapLibre throws on an unknown layer and on a NaN LngLat
  const q0 = x.map.queryRenderedFeatures; x.map.queryRenderedFeatures = (pt, o) => { for (const l of o.layers) if (!x.layers.has(l)) throw new Error(`layer ${l} does not exist`); return q0(pt, o); };
  x.setProj(ll => { if (!ll.every(Number.isFinite)) throw new Error('Invalid LngLat'); return { x: ll[0] * 10, y: ll[1] * 10 }; });
  return x;
};
const card = x => x.mapEl.querySelector('[data-lightning-card]');

test('LE1: tapping a cell fires the original nearestSubstations from the cell centre, draws the neon arrival and frames the camera like a flash', async () => {
  const x = await bootCell(); x.camera.length = 0;
  x.tapMap([-15.5, 520.5], { [CELL]: [cellF(C1)] });
  assert.deepEqual(x.neonCalls.map(a => [a[0], a[1]]), [[-1.55, 52.05]], 'engine not fired from the cell centre');
  const src = x.sources.get('gridatlas-lightning-neon-links'); assert.ok(src, 'no neon links'); assert.equal(src.data.features.length, 5);
  assert.deepEqual([...src.data.features[0].geometry.coordinates[0]], [-1.55, 52.05], 'links do not start at the cell centre');
  assert.deepEqual([...x.sources.get("gridatlas-lightning-neon-pin").data.features[0].geometry.coordinates], [-1.55, 52.05]);
  const fly = x.camera.find(c => c[0] === 'flyTo'); assert.ok(fly); assert.deepEqual([...fly[1][0].center], [-1.55, 52.05]); assert.equal(fly[1][0].zoom, 12);
  assert.equal(x.popups.length, 0);
});

test('LE2: the cell card: title "N optical flashes in this 0.1° cell", window dates, cell bounds, no flash ID or time, honesty kept', async () => {
  const x = await bootCell(); x.tapMap([-15.5, 520.5], { [CELL]: [cellF(C1)] });
  const c = card(x); assert.ok(c, 'no card'); const t = c.textContent, w = x.S.res.w;
  assert.equal(c.getAttribute('aria-label'), 'Lightning cell'); assert.equal(c.getAttribute('role'), 'dialog');
  assert.equal(c.children[0].children[0].textContent, '1,234 optical flashes in this 0.1° cell');
  assert.ok(t.includes(`${ymd(w.s)} to ${ymd(w.e - 1)} UTC · centre lat 52.050, lon -1.550 · 5 nearest substations`), 'summary row');
  assert.ok(t.includes('Cell lat 52.00–52.10, lon -1.60–-1.50: 0.1°, ≈6.9 km E–W × 11.1 km N–S, ≈76 km² here; the centre is not a flash location · searched UTC days only; unsearched days unknown, not zero'), 'bounds row');
  assert.ok(t.includes('Screening · nearest substations to this cell centre, straight line. Proximity, not exposure or a current path; not evidence any asset was struck.'), 'engine honesty line');
  assert.ok(t.includes('EUMETSAT MTG Lightning Imager · optical flash, not necessarily a ground strike.'), 'footer');
  assert.doesNotMatch(t, /Flash ID|· ID |Flash \d|\d\d:\d\d|\(none\)|undefined|NaN|unknown UTC|strike[sd]? (at|on)|affected/i);
  const [, close] = c.querySelectorAll('button'); dispatch(close, 'click', x.log.errors);
  assert.equal(card(x), null); assert.equal(x.sources.get('gridatlas-lightning-neon-links'), undefined, 'lines kept after ×');
});

test('LE3: when a flash and a cell are both under the tap, the flash wins (even if the cell centre is nearer)', async () => {
  const x = await bootCell();
  x.tapMap([-15.5, 520.5], { 'gridatlas-lightning-hit': [{ properties: { i: 0 }, geometry: { coordinates: [-1.5, 52] } }], [CELL]: [cellF(C1)] });
  assert.deepEqual(x.neonCalls.map(a => [a[0], a[1]]), [[-1.5, 52]]);
  assert.match(card(x).textContent, /^Flash \d{4}-\d\d-\d\d \d\d:\d\d:\d\d UTC/); assert.equal(card(x).getAttribute('aria-label'), 'Lightning flash');
  assert.match(card(x).textContent, /Screening · nearest substations to this optical flash, straight line/);
  // a cluster also wins over a cell
  x.camera.length = 0; x.neonCalls.length = 0; x.map.getSource('gridatlas-lightning').getClusterExpansionZoom = (id, cb) => cb(null, 9);
  x.tapMap([-15.5, 520.5], { 'gridatlas-lightning-hit': [{ properties: { cluster: true, cluster_id: 3 }, geometry: { coordinates: [-1.5, 52] } }], [CELL]: [cellF(C1)] });
  assert.equal(x.neonCalls.length, 0); assert.equal(card(x), null); assert.equal(x.camera[0][0], 'easeTo');
});

test('LE4: overlapping cell circles open the cell whose centre is nearest the tap; 1 flash is singular', async () => {
  const x = await bootCell(), C2 = { n: 1, cell: 25 * 140 + 95, lon: -1.45, lat: 52.05 };
  x.tapMap([-14.6, 520.5], { [CELL]: [cellF(C1), cellF(C2)] });
  assert.deepEqual(x.neonCalls.map(a => [a[0], a[1]]), [[-1.45, 52.05]]);
  assert.equal(card(x).children[0].children[0].textContent, '1 optical flash in this 0.1° cell');
});

test('LE5: malformed, inconsistent or stale cells open nothing and never throw; an empty tap still closes the card', async () => {
  const x = await bootCell();
  for (const p of [{}, { ...C1, n: 0 }, { ...C1, n: 1.5 }, { ...C1, n: '7' }, { ...C1, cell: -1 }, { ...C1, cell: 16800 }, { ...C1, lon: -1.65 }, { ...C1, lat: 52.15 }, { ...C1, lon: NaN }, { ...C1, lon: undefined }, { ...C1, s: -1 }]) {
    x.tapMap([-15.5, 520.5], { [CELL]: [cellF(p, [0, 0])] }); assert.equal(card(x), null, JSON.stringify(p));
  }
  assert.equal(x.neonCalls.length, 0); assert.deepEqual(x.log.errors, []);
  x.tapMap([-15.5, 520.5], { [CELL]: [cellF({ ...C1, s: x.S.res.s })] }); assert.ok(card(x), 'current-serial cell refused');
  x.tapMap([0, 0], {}); assert.equal(card(x), null);
});

test('LE6: without a cell layer a tap never queries it (MapLibre would throw); without a flash layer a cell still fires', async () => {
  const x = await bootCell(); x.map.removeLayer(CELL);
  tapFlash(x); assert.ok(card(x), 'flash tap broken without a cell layer');
  x.tapMap([0, 0], {}); assert.equal(card(x), null);
  const y = await bootCell(); for (const l of ['l-gridatlas-lightning', 'gridatlas-lightning-hit', 'l-gridatlas-lightning-count']) y.map.removeLayer(l);
  y.tapMap([-15.5, 520.5], { [CELL]: [cellF(C1)] }); assert.ok(card(y), 'cell needs the flash hit layer'); assert.equal(y.neonCalls.length, 1);
});

test('LE7: substations not loaded yet: the cell card retries the engine like a flash card', async () => {
  const x = await bootCell(); const L = x.W.__GRIDATLAS_NEON_LINKS__, subs = L.substations; L.substations = [];
  const st = x.sandbox.setTimeout, q = []; x.sandbox.setTimeout = (f, ms) => (ms === 2e3 ? q.push(f) : st(f, ms));
  x.tapMap([-15.5, 520.5], { [CELL]: [cellF(C1)] }); assert.match(card(x).textContent, /Substation data not loaded yet/); assert.equal(q.length, 1);
  L.substations = subs; q.shift()(); assert.deepEqual(x.neonCalls.map(a => [a[0], a[1]]), [[-1.55, 52.05]]); assert.match(card(x).textContent, /· 5 nearest substations/);
});

// ---------------------------------------------------------------- L-build: tappable cells above the cap (grid/YYYY-MM.json), land clip, projects win
const GC = (lon, lat) => Math.floor(Math.round((lat - 49.5) * 1e7) / 1e6) * 140 + Math.floor(Math.round((lon + 11) * 1e7) / 1e6);
const gday = (date, row, over = {}) => ({ date, coverage: row.coverage || 'full', count: row.count, sha256: row.path ? [row.sha256] : row.parts.map(p => p.sha256), ...over });
const mkGrids = (entries, tweak = g => g) => {
  const by = {};
  for (const e of entries) { const m = e.date.slice(0, 7), g = by[m] = by[m] || { days: [], cells: {} }; g.days.push(gday(e.date, e.row, e.day)); for (const [c, n] of Object.entries(e.cells)) (g.cells[c] = g.cells[c] || []).push(+e.date.slice(8), n); }
  return Object.fromEntries(Object.entries(by).map(([m, g]) => ['grid/' + m + '.json', (o => typeof o === 'string' ? o : enc(o))(tweak({ schema: 'uk-lightning-history-grid.v1', month: m, observation: 'satellite optical lightning flashes, not ground strikes', bounds_wsen: [-11, 49.5, 3, 61.5], cell_deg: 0.1, cols: 140, rows: 120, days: g.days, cells: Object.keys(g.cells).map(Number).sort((a, b) =>   … [line shortened here: 443 characters; full line on GitHub]
};
const KD = [40, 80].map(k => ymd(Date.now() - k * D));
const KROWS = { [KD[0]]: { count: 25000, bytes: 1000, path: P(KD[0]), sha256: 'x' }, [KD[1]]: { count: 25000, bytes: 1000, path: P(KD[1]), sha256: 'y' } };
const LC1 = GC(-1.5, 52), LC2 = GC(0.12, 51.5), SEA = GC(2.5, 56), EIRE = GC(-8.6, 53.1); // Midlands, London; North Sea, Galway
const KGRID = [{ date: KD[0], row: KROWS[KD[0]], cells: { [LC1]: 20000, [LC2]: 4000, [SEA]: 700, [EIRE]: 300 } }, { date: KD[1], row: KROWS[KD[1]], cells: { [LC1]: 25000 } }];
const cellsSrc = x => x.sources.get('gridatlas-lightning-cells');
const gridUrls = x => x.log.fetch.filter(u => u.includes('/grid/'));
const CLS = ['gridatlas-lightning-cell-glow', 'gridatlas-lightning-cell-core', 'gridatlas-lightning-cell'];
const cellHit = (x, f) => x.tapMap([f.properties.lon * 10, f.properties.lat * 10], { [CELL]: [f] });

test('L1: 12M above the cap draws tappable graduated cells (glow + core + 22 px hit), never a heatmap; only grid files fetched; honest caption', async () => {
  const full = { scan_windows: [{ start_utc: iso(Date.now() - 400 * D), end_utc: iso(Date.now() + 60e3), successful_runs: 999 }] };
  const x = boot({ index: mkIndex(KROWS, full), files: mkGrids(KGRID) }); x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.equal(x.S.res.clp, true); assert.equal(x.S.last.state, 'READY·CELLS', x.S.last.reasons.join()); assert.equal(x.S.last.cells, 2);
  assert.equal(x.log.fetch.filter(u => u.includes('/days/')).length, 0, 'day files fetched without consent');
  for (const u of gridUrls(x)) assert.match(u, /^https:\/\/raw\.githubusercontent\.com\/Ventusltd\/lightning\/main\/data\/history\/grid\/\d{4}-\d\d\.json$/);
  assert.equal(new Set(gridUrls(x)).size, 2);
  const f = Object.fromEntries(cellsSrc(x).data.features.map(q => [q.properties.n, q]));
  assert.deepEqual(Object.keys(f).map(Number).sort((a, b) => a - b), [4000, 45000]);
  const p = f[45000].properties; assert.equal(p.cell, LC1); assert.equal(p.s, x.S.res.s); assert.ok(Math.abs(p.lon - -1.45) < 1e-9 && Math.abs(p.lat - 52.05) < 1e-9, `${p.lon},${p.lat}`);
  assert.deepEqual([...f[45000].geometry.coordinates], [p.lon, p.lat]);
  for (const l of CLS) { assert.equal(x.layers.get(l).type, 'circle', l); assert.equal(x.layers.get(l).source, 'gridatlas-lightning-cells'); }
  assert.ok([...x.layers.keys()].every(l => !/heat/.test(l) && x.layers.get(l).type !== 'heatmap'), 'heatmap layer present');
  assert.ok(CLS.every(l => !l.startsWith('l-')), 'cell ids must not use the original\'s interactive l- prefix');
  const hit = x.layers.get(CELL).paint; assert.equal(hit['circle-radius'], 22); assert.equal(hit['circle-opacity'], 0);
  const core = x.layers.get(CLS[1]); assert.deepEqual([...core.layout['circle-sort-key']], ['get', 'n']); assert.equal(x.layers.get(CLS[0]).filter[2], 45000, 'glow floor = max(30, p95 of drawn cells)');
  assert.equal(x.sources.get('gridatlas-lightning').data.features.length, 0, 'points drawn without consent');
  assert.match(x.cap('flashes'), /^Flashes 50,000 archived on \d+ overlapping UTC dates · map limited to ≤30 km of REPD sites, not a national density map: 49,000 in 2 0.1° cells; 1,000 counted, not drawn · tap a cell for nearest substations · LOAD POINTS adds the newest 40,000 flashes$/);
  assert.equal(x.nav('points').hidden, false); assert.match(x.label(), /\[50,000 \| /);
});

test('L2: land clip is render-only: sea and Republic of Ireland cells are not drawn but stay in the totals', async () => {
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.equal(x.S.res.gd.n, 50000); assert.equal(x.S.res.gd.k, 49000);
  const cells = cellsSrc(x).data.features.map(q => q.properties.cell); assert.ok(!cells.includes(SEA) && !cells.includes(EIRE));
});

test('L3: tapping a cell fires the original nearestSubstations from the cell centre with the neon arrival and the cell card', async () => {
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); installNeon(x, SUBS); x.toggle(true); x.click(x.chip('12m')); await drain();
  const f = cellsSrc(x).data.features.find(q => q.properties.n === 45000); x.camera.length = 0; cellHit(x, f);
  assert.equal(x.neonCalls.length, 1); assert.ok(Math.abs(x.neonCalls[0][0] - -1.45) < 1e-9 && Math.abs(x.neonCalls[0][1] - 52.05) < 1e-9);
  assert.equal(x.sources.get('gridatlas-lightning-neon-links').data.features.length, 5);
  const c = card(x); assert.equal(c.getAttribute('aria-label'), 'Lightning cell'); assert.equal(c.children[0].children[0].textContent, '45,000 optical flashes in this 0.1° cell');
  assert.match(c.textContent, /searched UTC days only; unsearched days unknown, not zero/); assert.ok(x.camera.find(k => k[0] === 'flyTo'));
});

test('L4: a project or substation of the original under the tap wins over a cell (no second engine, no card); hidden ones do not', async () => {
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); installNeon(x, SUBS); x.toggle(true); x.click(x.chip('12m')); await drain();
  const vis = { 'l-solar': 'visible', 'l-solar-glow': 'visible', 'l-subs': 'visible', 'l-wind': 'none' };
  x.map.getStyle = () => ({ layers: [{ id: 'l-solar-glow', source: 'src-repd' }, { id: 'l-solar', source: 'src-repd' }, { id: 'l-wind', source: 'src-repd' }, { id: 'l-subs', source: 'src-subs' }, ...[...x.layers.keys()].map(id => ({ id, source: x.layers.get(id).source }))] });
  x.map.getLayoutProperty = (id, k) => vis[id] || 'visible';
  const f = cellsSrc(x).data.features[0], at = [f.properties.lon * 10, f.properties.lat * 10];
  for (const l of ['l-solar', 'l-subs']) { x.tapMap(at, { [l]: [{ properties: { tech: 'solar' } }], [CELL]: [f] }); assert.equal(card(x), null, l); assert.equal(x.neonCalls.length, 0, l); }
  x.tapMap(at, { 'l-wind': [{ properties: {} }], [CELL]: [f] }); assert.ok(card(x), 'a hidden project layer blocked the cell'); assert.equal(x.neonCalls.length, 1);
});

test('L5: cells are inserted below the original\'s first REPD layer (projects stay on top), else below our points', async () => {
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); const add = x.map.addLayer, before = {};
  x.map.addLayer = (l, b) => { before[l.id] = b; return add(l, b); };
  x.map.getStyle = () => ({ layers: [{ id: 'base' }, { id: 'l-solar-glow', source: 'src-repd' }, { id: 'l-solar', source: 'src-repd' }] }); x.map.getLayoutProperty = () => 'none';
  x.toggle(true); x.click(x.chip('12m')); await drain();
  for (const l of CLS) assert.equal(before[l], 'l-solar-glow', l);
  const y = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }), b2 = {}, a2 = y.map.addLayer; y.map.addLayer = (l, b) => { b2[l.id] = b; return a2(l, b); };
  y.toggle(true); y.click(y.chip('12m')); await drain(); for (const l of CLS) assert.equal(b2[l], 'l-gridatlas-lightning', l);
});

test('L6: stale (sha256/count differs) and never-searched grid days are not drawn and are named (unknown, not zero)', async () => {
  const g = [KGRID[0], { ...KGRID[1], day: { sha256: ['0'.repeat(64)] } }];
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(g) }); x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.equal(x.S.res.gd.n, 25000); assert.equal(x.S.res.gd.st, 1);
  assert.deepEqual(Array.from(cellsSrc(x).data.features, q => q.properties.n).sort((a, b) => a - b), [4000, 20000]);
  assert.match(x.cap('flashes'), /· 1 day not yet mapped \(unknown\) ·/);
  const d3 = ymd(Date.now() - 41 * D), idx = mkIndex({ ...KROWS, [d3]: { coverage: 'none', scanned_seconds: 0, count: null } });
  const y = boot({ index: idx, files: mkGrids([...KGRID, { date: d3, row: { count: 7, path: P(d3), sha256: 'q' }, cells: { [LC2]: 7 } }]) }); y.toggle(true); y.click(y.chip('12m')); await drain();
  assert.equal(y.S.res.gd.n, 50000); assert.equal(cellsSrc(y).data.features.find(q => q.properties.cell === LC2).properties.n, 4000);
});

test('L7: an invalid or unpublished grid is refused; nothing is drawn, the caption says why, never FAIL', async () => {
  const bad = [g => ({ ...g, schema: 'uk-lightning-history-grid.v0' }), g => ({ ...g, month: '1999-01' }), g => ({ ...g, cols: 141 }), g => ({ ...g, cells: [[16800, 1, 1]] }),
    g => ({ ...g, cells: g.cells.map(r => [r[0], 32, r[2]]) }), g => ({ ...g, cells: g.cells.map(r => [r[0], r[1], 0]) }), g => ({ ...g, cells: g.cells.map(r => [r[0], r[1], String(r[2])]) }),
    g => ({ ...g, cells: g.cells.slice(1) }), g => ({ ...g, days: g.days.map(d => ({ ...d, sha256: d.sha256[0] })) }), g => ({ ...g, cells: ['<img src=x onerror=alert(1)>'] }),
    g => ({ ...g, cells: g.cells.map(r => [r[0] + 0.5, ...r.slice(1)]) }), g => ({ ...g, days: Array(32).fill(g.days[0]) }), () => '{not json'];
  for (const [i, t] of bad.entries()) {
    const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID, t) }); x.toggle(true); x.click(x.chip('12m')); await drain();
    assert.equal(x.S.res.gd, undefined, 'variant ' + i); assert.equal(cellsSrc(x), undefined, 'variant ' + i); assert.equal(x.S.last.cells, 0); assert.notEqual(x.S.last.state, 'FAIL');
    assert.match(x.cap('flashes'), /none drawn \(summary mode; .*\) · cell grid archive unavailable: /, 'variant ' + i);
  }
  const x = boot({ index: mkIndex(KROWS), files: {} }); x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.match(x.cap('flashes'), /· cell grid archive not yet published: HTTP 404$/); assert.equal(x.log.errors.length, 0);
  const files = mkGrids(KGRID); delete files['grid/' + KD[1].slice(0, 7) + '.json'];
  const y = boot({ index: mkIndex(KROWS), files }); y.toggle(true); y.click(y.chip('12m')); await drain();
  assert.equal(y.S.res.gd.n, 25000); assert.match(y.cap('flashes'), /1 day not yet mapped \(unknown; HTTP 404\)/); // L3: LRB3 names the refused month
});

test('L8: phone over its 10,000 cap: cells by default; LOAD POINTS keeps them beneath tappable points; flash wins, cell still fires', async () => {
  const s1 = shard(KD[0], 6000, Date.parse(KD[0] + 'T10:00:00Z')), s2 = shard(KD[1], 6000, Date.parse(KD[1] + 'T10:00:00Z'));
  const rows = { [KD[0]]: s1.row, [KD[1]]: s2.row }, g = [{ date: KD[0], row: s1.row, cells: { [LC1]: 6000 } }, { date: KD[1], row: s2.row, cells: { [LC1]: 6000 } }];
  const x = boot({ phone: true, index: mkIndex(rows), files: { ...mkGrids(g), [s1.row.path]: s1.b, [s2.row.path]: s2.b } }); installNeon(x, SUBS); x.map.setPaintProperty = () => {};
  x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.equal(x.S.last.cells, 1); assert.equal(x.S.last.drawn, 0); const f = cellsSrc(x).data.features[0]; assert.equal(f.properties.n, 12000);
  cellHit(x, f); assert.equal(x.neonCalls.length, 1); assert.match(card(x).textContent, /^12,000 optical flashes in this 0.1° cell/);
  x.click(x.nav('points')); await drain();
  assert.equal(x.S.res.mode, 'detail'); assert.equal(x.sources.get('gridatlas-lightning').data.features.length, 12000); assert.ok(cellsSrc(x), 'cells removed after LOAD POINTS');
  assert.match(x.cap('flashes'), /· map limited to ≤30 km of REPD sites, not a national density map: 12,000 in 1 0.1° cell;/);
  x.neonCalls.length = 0; tapFlash(x); assert.deepEqual(x.neonCalls.map(a => [a[0], a[1]]), [[-1.5, 52]]); assert.equal(card(x).getAttribute('aria-label'), 'Lightning flash');
  const g2 = cellsSrc(x).data.features[0]; x.neonCalls.length = 0; cellHit(x, g2); assert.equal(x.neonCalls.length, 1, 'cell under LOAD POINTS'); assert.equal(card(x).getAttribute('aria-label'), 'Lightning cell');
});

test('L9: short windows within the cap keep J\'s dots only: no grid request, no cell layer; OFF and short windows remove the cells', async () => {
  const files = {}, over = {};
  for (let k = 1; k <= 3; k++) { const d = ymd(Date.now() - k * D), s = shard(d, 42, Date.parse(d + 'T10:00:00Z')); files[s.row.path] = s.b; over[d] = s.row; }
  let x = boot({ index: mkIndex(over), files }); x.toggle(true); x.click(x.chip('7d')); await drain();
  assert.equal(x.S.res.mode, 'detail'); assert.equal(x.S.last.drawn, 126); assert.equal(gridUrls(x).length, 0); assert.equal(cellsSrc(x), undefined); for (const l of CLS) assert.equal(x.layers.get(l), undefined);
  x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); x.toggle(true); x.click(x.chip('12m')); await drain(); assert.ok(cellsSrc(x));
  x.click(x.chip('7d')); await drain(); assert.equal(cellsSrc(x), undefined, 'cells kept on a window within the cap');
  x.click(x.chip('12m')); await drain(); assert.ok(cellsSrc(x)); x.toggle(false);
  assert.equal(cellsSrc(x), undefined); for (const l of CLS) assert.equal(x.layers.get(l), undefined);
});

test('L10: budget and discipline: module <= 44,781 B, one innerHTML, GS constant, grid path only from YYYY-MM, no heatmap', () => {
  assert.ok(Buffer.byteLength(SRC) <= 64781, `${Buffer.byteLength(SRC)} B`); assert.ok(435218 + 1 + Buffer.byteLength(SRC) <= 500000); // M2: owner's 500 kB gate
  assert.equal(SRC.split('innerHTML').length, 2); assert.match(SRC, /GS='uk-lightning-history-grid\.v1'/); assert.doesNotMatch(SRC, /heatmap/);
  assert.match(SRC, /if\(!\/\^\\d\{4\}-\\d\\d\$\/\.test\(mo\)\)E\('grid path'\);const u=AR\+'grid\/'\+mo\+'\.json'/);
});

test('L11 (real data, LIGHTNING_DATA=<lightning checkout>/data/history): 12M cells sum to the index; REPD 30 km clip; a real cell fires the engine', { skip: !process.env.LIGHTNING_DATA }, async () => {
  const dir = process.env.LIGHTNING_DATA, idx = JSON.parse(readFileSync(dir + '/index.json', 'utf8'));
  const files = new Proxy({}, { get: (_, k) => { try { return readFileSync(dir + '/' + String(k)); } catch { return undefined; } } });
  const x = boot({ phone: true, index: idx, files, now: Date.parse(idx.generated_utc) + 60e3 }); installNeon(x, SUBS); x.map.setPaintProperty = () => {}; x.toggle(true); x.click(x.chip('12m')); await drain();
  const want = idx.days.filter(r => r.count > 0 && Date.parse(r.date) >= x.S.res.w.s - D).reduce((a, r) => a + r.count, 0), fs = cellsSrc(x).data.features;
  assert.equal(x.S.res.gd.st, 0); assert.equal(x.S.res.gd.n, want); assert.equal(fs.reduce((a, f) => a + f.properties.n, 0), x.S.res.gd.k);
  console.log(`# L11 real 12M: ${want} flashes, ${fs.length} cells drawn holding ${x.S.res.gd.k} (glow floor ${x.S.res.gd.T}), ${new Set(gridUrls(x)).size} grid files · ${x.cap('flashes')}`);
  const big = fs.reduce((a, f) => f.properties.n > a.properties.n ? f : a); cellHit(x, big); assert.equal(x.neonCalls.length, 1); assert.ok(card(x));
  console.log(`# L11 tap cell ${big.properties.cell} n=${big.properties.n}: ${card(x).children[0].children[0].textContent}`);
  for (const p of ['7d', '30d', '3m', '6m']) { x.click(x.chip(p)); await drain(); console.log(`# L11 ${p}: ${x.S.last.state} cells ${x.S.last.cells} drawn ${x.S.last.drawn} · ${x.status()}`); }
});

// ================================================================ LR-bugs (evidence/LR-bugs/tests.part)

// ================================================================ LR-bugs: adversarial review of the L2 cell code
const BLOB = [-7.55716, 49.766807]; // REPD placeholder coordinate (OSGB 0,0) carried by 18 records with no real location
const kmTo = (lon, lat, [x, y]) => hav(lon, lat, x, y);

test('LRB1 (MAJOR): the land mask draws open-Atlantic cells ~100 km SW of Scilly as "within ≈30 km of UK land"', async () => {
  const SW = GC(-7.55, 49.75), FAR = GC(-7.3, 49.95);
  const g = [{ date: KD[0], row: KROWS[KD[0]], cells: { [LC1]: 24000, [SW]: 600, [FAR]: 400 } }, { date: KD[1], row: KROWS[KD[1]], cells: { [LC1]: 25000 } }];
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(g) }); x.toggle(true); x.click(x.chip('12m')); await drain();
  const sea = cellsSrc(x).data.features.filter(f => f.properties.lon < -6.6 && f.properties.lat < 50.3);
  assert.match(x.cap('flashes'), /limited to ≤30 km of REPD sites, not a national density map/); // V-geometry wording
  assert.equal(sea.length, 0, 'open-sea cells drawn under a "sea not drawn" caption: ' + JSON.stringify(sea.map(f => [f.properties.lon, f.properties.lat, f.properties.n])));
});

test('LRB1-real (MAJOR, LIGHTNING_DATA): real 12M draws cells around the REPD placeholder point in the Atlantic', { skip: !process.env.LIGHTNING_DATA }, async () => {
  const dir = process.env.LIGHTNING_DATA, idx = JSON.parse(readFileSync(dir + '/index.json', 'utf8'));
  const files = new Proxy({}, { get: (_, k) => { try { return readFileSync(dir + '/' + String(k)); } catch { return undefined; } } });
  const x = boot({ phone: true, index: idx, files, now: Date.parse(idx.generated_utc) + 60e3 }); x.toggle(true); x.click(x.chip('12m')); await drain();
  const sea = cellsSrc(x).data.features.filter(f => f.properties.lon < -6.6 && kmTo(f.properties.lon, f.properties.lat, BLOB) < 32);
  console.log(`# LRB1-real: ${sea.length} drawn cells, ${sea.reduce((a, f) => a + f.properties.n, 0)} flashes within 32 km of ${BLOB}: ${sea.map(f => f.properties.lon.toFixed(2) + ',' + f.properties.lat.toFixed(2) + ' n=' + f.properties.n).join('; ')}`);
  assert.equal(sea.length, 0);
});

test('LRB2 (MINOR): every grid day stale (no error) -> READY·CELLS with "0 of 0 in 0 cells … tap a cell", nothing drawn, no summary fallback', async () => {
  const g = KGRID.map(e => ({ ...e, day: { sha256: ['0'.repeat(64)] } }));
  const full = { scan_windows: [{ start_utc: iso(Date.now() - 400 * D), end_utc: iso(Date.now() + 60e3), successful_runs: 999 }] };
  const x = boot({ index: mkIndex(KROWS, full), files: mkGrids(g) }); x.toggle(true); x.click(x.chip('12m')); await drain();
  console.log('# LRB2 state ' + x.S.last.state + ' cells ' + x.S.last.cells + ' · ' + x.cap('flashes'));
  assert.equal(cellsSrc(x), undefined);
  assert.doesNotMatch(x.cap('flashes'), /0 of 0 in 0 cells/, 'empty grid reported as drawn cells');
  assert.doesNotMatch(x.cap('flashes'), /tap a cell/, 'invites a tap on nothing');
  assert.notEqual(x.S.last.state, 'READY·CELLS');
});

test('LRB3 (MINOR): one month grid refused (invalid / sha-type / timeout) while another loads -> named only as "not yet in the grid"; the error is swallowed', async () => {
  const files = mkGrids(KGRID), bad = 'grid/' + KD[1].slice(0, 7) + '.json'; files[bad] = enc({ schema: 'uk-lightning-history-grid.v0' });
  const x = boot({ index: mkIndex(KROWS), files }); x.toggle(true); x.click(x.chip('12m')); await drain();
  console.log('# LRB3 ' + x.cap('flashes') + ' · errors ' + JSON.stringify(x.S.errors));
  assert.ok(cellsSrc(x));
  assert.match(x.cap('flashes'), /invalid grid|unavailable/, 'a refused grid is reported as an ordinary lag');
});

// whole-UTC-day edge: a window starting mid-day on an hourly-parts day (real: 2026-05-27, 06-25..27, 08-27)
const PT = Date.UTC(2026, 6, 26, 12), PD = '2026-06-26', OD = '2026-07-10';
const partsRow = (date, per) => ({ count: 24 * per, bytes: null, path: null, sha256: null, parts: Array.from({ length: 24 }, (_, h) => ({ path: P(date).replace('.json', '/' + String(h).padStart(2, '0') + '.json'), count: per, bytes: 100, sha256: 'p' + h })) });

test('LRB4 (MINOR): 30D starting mid-day on a parts day: cells sum the whole day, so "k of n" exceeds the caption\'s "N archived"', async () => {
  const rows = { [PD]: partsRow(PD, 500), [OD]: { count: 6000, bytes: 1000, path: P(OD), sha256: 'o' } };
  const g = [{ date: PD, row: rows[PD], cells: { [LC1]: 12000 } }, { date: OD, row: rows[OD], cells: { [LC1]: 6000 } }];
  const x = boot({ phone: true, now: PT, index: mkIndex(rows, {}, PT), files: mkGrids(g) }); x.toggle(true); x.click(x.chip('30d')); await drain();
  const arch = x.S.res.arch, n = x.S.res.gd && x.S.res.gd.n; console.log(`# LRB4 arch ${arch} gd.n ${n} · ${x.cap('flashes')}`);
  assert.ok(n <= arch, `cells total ${n} > archived ${arch} in the same caption`);
});

test('LRB4-real (MINOR, LIGHTNING_DATA): 3M on 2026-11-27 13:20 UTC starts mid-day on parts day 2026-08-27', { skip: !process.env.LIGHTNING_DATA }, async () => {
  const dir = process.env.LIGHTNING_DATA, idx = JSON.parse(readFileSync(dir + '/index.json', 'utf8'));
  const files = new Proxy({}, { get: (_, k) => { try { return readFileSync(dir + '/' + String(k)); } catch { return undefined; } } });
  const now = Date.UTC(2026, 10, 27, 13, 20);
  const x = boot({ phone: true, index: idx, files, now }); x.toggle(true); x.click(x.chip('3m')); await drain();
  const r = x.S.res; console.log(`# LRB4-real 3M ${new Date(r.w.s).toISOString()}: arch ${r.arch} gd.n ${r.gd && r.gd.n} · ${x.cap('flashes')}`);
  assert.ok(r.gd.n <= r.arch, `cells total ${r.gd.n} > archived ${r.arch}`);
});

// ---------------------------------------------------------------- guards (expected PASS): races, 404, NaN, rapid taps
test('LRG1: toggle OFF while the grid fetch is in flight leaves no cell source/layer and no card', async () => {
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID), park: true }); x.toggle(true); x.click(x.chip('12m')); await drain();
  x.toggle(false); x.release(); await drain(); x.release(); await drain();
  assert.equal(cellsSrc(x), undefined); for (const l of CLS) assert.equal(x.layers.get(l), undefined); assert.equal(x.S.res, null);
});

test('LRG2: 12M -> 7D while the grid fetch is in flight: the late 12M grid never paints cells over 7D', async () => {
  const s = shard(ymd(Date.now() - D), 5, Date.now() - D);
  const x = boot({ index: mkIndex({ ...KROWS, [ymd(Date.now() - D)]: s.row }), files: { ...mkGrids(KGRID), [s.row.path]: s.b }, park: true }); x.toggle(true); x.click(x.chip('12m')); await drain();
  x.click(x.chip('7d')); for (let i = 0; i < 4; i++) { x.release(); await drain(); }
  assert.equal(x.S.res.w.period, '7d'); assert.equal(cellsSrc(x), undefined); assert.equal(x.S.last.drawn, 5);
});

test('LRG3: rapid taps on two cells leave exactly one card and one neon set (latest cell)', async () => {
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); installNeon(x, SUBS); x.map.setPaintProperty = () => {}; x.toggle(true); x.click(x.chip('12m')); await drain();
  const fs = cellsSrc(x).data.features; for (let i = 0; i < 6; i++) cellHit(x, fs[i % fs.length]);
  assert.equal(x.mapEl.querySelectorAll('[data-lightning-card]').length, 1); assert.equal(x.neonCalls.length, 6);
  const last = fs[5 % fs.length].properties; assert.deepEqual(x.neonCalls[5].slice(0, 2), [last.lon, last.lat]);