GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / tools/intelligence/cartridges/grid-distance-column

Grid Proximity and 1 more file

A JavaScript module in PipelineNews that marks tabs, renders radius and sort, calculates great-circle distances and angles and reads inputs for gp centre, gp radius and gp target pick.

700 lines of JavaScript from pipelinenews, in 2 files. Topic: Electricity markets and data pipelines. Section 1039 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. Proof render · pipelinenews / tools/intelligence/cartridges/grid-distance-column/proof.mjs lines 1–312
  2. Grid Proximity geodesy · pipelinenews / tools/intelligence/cartridges/grid-proximity/assets/{GEN}-grid-proximity.mjs lines 1–388

Proof

A JavaScript module in the grid distance column folder of PipelineNews that fetches the Renewable Energy Planning Database (REPD) register, postcodes and cables.

renderpipelinenews / tools/intelligence/cartridges/grid-distance-column/proof.mjs · lines 1–312 of 312 · Not reached from any entry point (candidate for review) · pattern clickAndRead (shared by 2 files)

What it does
It fetches the REPD register, postcodes and cables. Defines 8 functions or classes, including check, $, rowsOf, cellsOf, refOf. Uses libraries node:fs/promises, node:path, node:url, node:crypto, jsdom. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): 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, postcodes, cables.
Inputs & outputs
In: JSON file 202608270055-8ab1807551bc-v8-fast-projects.json; JSON file 202608291447-registry.json; command-line arguments.
What it achieves
It is built from the check step (`check`), the rows of helper (`rowsOf`) and the cells of helper (`cellsOf`). Grid-distance-column render proof.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · tools/intelligence/cartridges/grid-distance-column · JavaScript module
Uses
node:fs/promises, node:path, node:url, node:crypto, jsdom
Used by
none found
Produces
check, $, rowsOf, cellsOf, refOf, kmOf, clickAndRead, expected
Defines here
check, $, rowsOf, cellsOf, refOf, kmOf, clickAndRead, expected
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/grid-distance-column/proof.mjs:1-312 · blob 53b691baed62fa99bb9e3c0cb5224d3d18f2d08b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * grid-distance-column render proof.
 *
 * This cartridge does not add a panel. It changes the project table itself --
 * a new column and a new sort mode -- so the only proof worth anything is
 * booting the whole app against the real release and reading the table it
 * produces.
 *
 * Every expectation is re-derived from the payload independently. A sort
 * assertion that compares the app's output to the app's own comparator proves
 * nothing, and a cell assertion that reads the number back out of the cell it
 * came from proves less than that.
 *
 * It also checks the two things that make this column honest rather than merely
 * present: that a project with no mapped circuit renders a dash rather than a
 * number, and that the BETA caveat on the page actually says headroom cannot be
 * inferred from distance.
 *
 * Usage:
 *   node proof.mjs <path-to-release-dir> <generation>
 *
 * It is NOT a browser: it proves the code runs, the column carries the right
 * values, and the heading reorders the rows correctly. It does not prove layout
 * or that a human can read the result.
 */

import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { webcrypto } from "node:crypto";
import { JSDOM } from "jsdom";

const root = process.argv[2];
const gen = process.argv[3];
if (!root || !gen) {
  console.error("usage: node proof.mjs <release-dir> <generation>");
  process.exit(2);
}

let passed = 0;
const failures = [];
function check(label, condition, detail = "") {
  if (condition) {
    passed += 1;
  } else {
    failures.push(`${label}${detail ? ` -- ${detail}` : ""}`);
  }
}

// ---------------------------------------------------------------- the DOM --
const html = await readFile(join(root, "index.html"), "utf8");
const dom = new JSDOM(html, {
  url: "http://localhost/",
  pretendToBeVisual: true,
  runScripts: "outside-only",
});
const { window } = dom;

window.fetch = async (input) => {
  const url = new URL(input instanceof URL ? input.href : String(input?.url ?? input),
                      "http://localhost/");
  const file = join(root, decodeURIComponent(url.pathname).replace(/^\//, ""));
  try {
    const body = await readFile(file, "utf8");
    return { ok: true, status: 200, json: async () => JSON.parse(body), text: async () => body };
  } catch {
    return { ok: false, status: 404, json: async () => ({}), text: async () => "" };
  }
};

const FROM_WINDOW = [
  "document", "location", "history", "navigator", "screen", "matchMedia",
  "getComputedStyle", "requestAnimationFrame", "cancelAnimationFrame",
  "Event", "CustomEvent", "EventTarget", "AbortController", "AbortSignal",
  "Node", "Element", "HTMLElement", "HTMLInputElement", "HTMLSelectElement",
  "HTMLOptionElement", "Option", "Image", "DocumentFragment", "NodeList",
  "DOMParser", "XMLHttpRequest", "FormData", "Blob", "URL", "URLSearchParams",
  "MutationObserver", "IntersectionObserver", "ResizeObserver",
  "localStorage", "sessionStorage", "innerWidth", "innerHeight",
];
for (const key of FROM_WINDOW) {
  let value;
  try { value = window[key]; } catch { continue; }
  if (value === undefined) continue;
  try {
    Object.defineProperty(globalThis, key, { value, writable: true, configurable: true });
  } catch { /* non-configurable on this runtime */ }
}
for (const [key, value] of [["window", window],
                            ["fetch", window.fetch],
                            ["crypto", webcrypto],
                            ["addEventListener", window.addEventListener.bind(window)],
                            ["dispatchEvent", window.dispatchEvent.bind(window)]]) {
  Object.defineProperty(globalThis, key, { value, writable: true, configurable: true });
}

// ------------------------------------------------------------ boot the app --
const appUrl = pathToFileURL(join(root, "assets", "202608291447-app.mjs")).href;
await import(appUrl);

const ready = await new Promise((resolve) => {
  const started = Date.now();
  const poll = setInterval(() => {
    if (window.document.body.dataset.fastReady === "true") { clearInterval(poll); resolve(true); }
    else if (window.document.body.dataset.fastFailed === "true") { clearInterval(poll); resolve(false); }
    else if (Date.now() - started > 60000) { clearInterval(poll); resolve(false); }
  }, 40);
});
check("app boots", ready, window.document.body.dataset.fastFailed === "true"
  ? "boot() threw and the table failed closed" : "timed out");
if (!ready) {
  console.error("\nthe app did not boot; nothing below can be trusted\n");
  console.error(failures.join("\n"));
  process.exit(1);
}

const doc = window.document;
const $ = (sel) => doc.querySelector(sel);
const rowsOf = () => [...doc.querySelectorAll("#tbody tr")];
const cellsOf = (tr) => [...tr.querySelectorAll("td")];

// ------------------------------------------------------- the payload, again --
const payload = JSON.parse(await readFile(
  join(root, "data", `${gen}-grid-distance.json`), "utf8"));
const projects = JSON.parse(await readFile(
  join(root, "data", "202608270055-8ab1807551bc-v8-fast-projects.json"), "utf8"));
const F = Object.fromEntries(projects.fields.map((name, index) => [name, index]));
const refOf = (row) => String(row[F.repd_ref]);
const kmOf = (row) => {
  const hit = payload.grid[refOf(row)];
  return hit && typeof hit.k === "number" ? hit.k : null;
};

check("payload schema is the one the registry declares",
  payload.schema === "pipelinenews.grid-distance.v1", payload.schema);
check("payload generation matches the release", payload.generation === gen, payload.generation);
check("payload makes no runtime network claim", payload.network_at_runtime === false);

// ------------------------------------------------------------- the columns --
const headings = [...doc.querySelectorAll("thead th")]
  .map((th) => th.textContent.replace(/\s+/g, " ").trim());
// From 202608311858 the GRID column was deliberately removed and the distance
// moved into the ACTIONS cell beside MAP, because the column sat past the fold
// on any window narrower than about 1920px. This proof describes the releases
// that HAD the column; on a later one it stands down rather than reporting a
// failure for a change that was the point. The check must come BEFORE the
// column-count assertion, or standing down still leaves a recorded failure.
if (!headings.some((h) => h.startsWith("GRID"))) {
  console.log("\nSKIP  this release has no GRID column.");
  console.log("      The distance moved into ACTIONS in 202608311858; that placement");
  console.log("      is covered by cartridges/grid-actions-inline/proof.mjs.");
  process.exit(0);
}

check("table has 14 columns", headings.length === 14,
  `found ${headings.length}: ${headings.join(" | ")}`);

const gridIndex = headings.findIndex((h) => h.startsWith("GRID"));
const postcodeIndex = headings.findIndex((h) => h.startsWith("POSTCODE"));
const operatorIndex = headings.findIndex((h) => h.startsWith("OPERATOR"));
check("GRID column present", gridIndex !== -1, headings.join(" | "));
check("GRID sits between POSTCODE and OPERATOR",
  postcodeIndex !== -1 && gridIndex === postcodeIndex + 1 && operatorIndex === gridIndex + 1,
  `postcode ${postcodeIndex}, grid ${gridIndex}, operator ${operatorIndex}`);
check("GRID heading carries the BETA marker",
  doc.querySelector("#gridHeader .beta-chip")?.textContent.trim() === "BETA",
  doc.querySelector("#gridHeader")?.textContent.replace(/\s+/g, " ").trim());
check("GRID heading is a sort control",
  doc.querySelector("#gridHeader button#sortGrid") !== null);

// -------------------------------------------------------------- the cells --
const first = rowsOf();
check("rows render", first.length > 0, `${first.length} rows`);
check("every row has 14 cells", first.every((tr) => cellsOf(tr).length === 14),
  `widths ${[...new Set(first.map((tr) => cellsOf(tr).length))].join(",")}`);

const failRow = (await readFile(join(root, "assets", "202608291447-app.mjs"), "utf8"))
  .match(/colspan="(\d+)" class="fast-fail"/);
check("fail-closed row spans the whole table", failRow && failRow[1] === "14",
  failRow ? failRow[1] : "not found");

const byRef = new Map(projects.rows.map((row) => [refOf(row), row]));
let cellMatches = 0;
let dashes = 0;
let dashesCorrect = 0;
for (const tr of first) {
  const ref = tr.id.replace(/^repd-/, "");
  const cell = cellsOf(tr)[gridIndex];
  const text = cell.textContent.replace(/\s+/g, " ").trim();
  const want = kmOf(byRef.get(ref) ?? []);
  if (want === null) {
    dashes += 1;
    if (text === "-") dashesCorrect += 1;
  } else if (text === `${want.toFixed(2)}km` || text === `${want.toFixed(2)}km · ${payload.grid[ref].v}kV`) {
    cellMatches += 1;
  }
}
check("every measured GRID cell matches the payload",
  cellMatches + dashes === first.length,
  `${cellMatches} matched, ${dashes} blank, of ${first.length}`);
check("a project with no mapped circuit shows a dash, never a number",
  dashes === dashesCorrect, `${dashes - dashesCorrect} of ${dashes} blanks were not a dash`);

// ---------------------------------------------------------------- the sort --
const clickAndRead = (selector) => {
  $(selector).dispatchEvent(new window.Event("click", { bubbles: true }));
  return rowsOf().map((tr) => tr.id.replace(/^repd-/, ""));
};

// Independently re-derived: sort the payload the way the column claims to and
// take the first window. Blanks last in BOTH directions.
const WINDOW = 100;
function expected(direction) {
  const order = projects.rows.map((_row, index) => index);
  order.sort((left, right) => {
    const a = kmOf(projects.rows[left]);
    const b = kmOf(projects.rows[right]);
    if (a === null && b === null) return left - right;
    if (a === null) return 1;
    if (b === null) return -1;
    return direction * (a - b) || left - right;
  });
  return order.slice(0, WINDOW).map((index) => refOf(projects.rows[index]));
}

for (const [label, wanted, mode, aria] of [
  ["GRID first click sorts nearest first", () => expected(1), "grid_asc", "ascending"],
  ["GRID second click sorts furthest first", () => expected(-1), "grid_desc", "descending"],
]) {
  const got = clickAndRead("#sortGrid");
  const want = wanted();
  check(label, got.join(",") === want.join(","),
    `first 5 got ${got.slice(0, 5).join(",")} want ${want.slice(0, 5).join(",")}`);
  check(`${label} syncs the sort control`, $("#sortProjects").value === mode,
    $("#sortProjects").value);
  check(`${label} sets aria-sort`,
    doc.getElementById("gridHeader").getAttribute("aria-sort") === aria,
    doc.getElementById("gridHeader").getAttribute("aria-sort"));
}

// Nearest-first must really ascend, and blanks must really be at the bottom.
$("#sortProjects").value = "grid_asc";
$("#sortProjects").dispatchEvent(new window.Event("change", { bubbles: true }));
const ascending = rowsOf().map((tr) => kmOf(byRef.get(tr.id.replace(/^repd-/, "")) ?? []));
check("grid_asc really ascends",
  ascending.every((v, i) => i === 0 || v === null || ascending[i - 1] === null || ascending[i - 1] <= v),
  ascending.slice(0, 6).join(","));

$("#sortProjects").value = "grid_desc";
$("#sortProjects").dispatchEvent(new window.Event("change", { bubbles: true }));
const descending = rowsOf().map((tr) => kmOf(byRef.get(tr.id.replace(/^repd-/, "")) ?? []));
check("grid_desc really descends",
  descending.every((v, i) => i === 0 || v === null || descending[i - 1] === null || descending[i - 1] >= v),
  descending.slice(0, 6).join(","));
check("blanks sit last in both directions",
  ascending.indexOf(null) === -1 || ascending.slice(ascending.indexOf(null)).every((v) => v === null));

// ------------------------------------------------------------- the caveat --
const note = doc.getElementById("gridDistanceNote");
check("the GRID note rendered", note !== null && note.textContent.trim().length > 0,
  note?.textContent);
check("the note marks the column BETA", /BETA/.test(note?.textContent ?? ""), note?.textContent);
check("the note says it is not a cable route",
  /not a cable route/i.test(note?.textContent ?? ""), note?.textContent);
check("the note says the column is not headroom",
  /headroom/i.test(note?.textContent ?? ""), note?.textContent);

const title = note?.getAttribute("title") ?? "";
check("the caveat names DNO data as what headroom needs",
  /DNO/.test(title) && /impedance/i.test(title), title.slice(0, 200));
check("the caveat says headroom needs a connection study",
  /connection study/i.test(title), title.slice(0, 200));
check("the caveat states absence from a layer is not absence on the ground",
  /absence on the ground/i.test(title), title.slice(0, 200));
check("the caveat names the canonical implementation",
  /grid-distance-maths/.test(title), title.slice(0, 300));

// A cell tooltip must carry the same limits as the strip, or a user who reads
// only the cell is told less than one who reads only the note.
const measured = first.find((tr) => kmOf(byRef.get(tr.id.replace(/^repd-/, "")) ?? []) !== null);
const cellTitle = measured ? cellsOf(measured)[gridIndex].querySelector("span")?.getAttribute("title") ?? "" : "";
check("a measured cell carries the straight-line caveat",
  /not a cable route/i.test(cellTitle), cellTitle.slice(0, 160));
check("a measured cell carries the headroom caveat",
  /headroom/i.test(cellTitle) && /impedance/i.test(cellTitle), cellTitle.slice(0, 240));

// ------------------------------------------------------ the numbers are the panel's --
const proximityFile = (await readFile(join(root, "data", "202608291447-registry.json"), "utf8"))
  .match(/"(\d{12})-grid-proximity\.json"/);
if (proximityFile) {
  const panel = JSON.parse(await readFile(
    join(root, "data", `${proximityFile[1]}-grid-proximity.json`), "utf8"));
  let same = 0;
  let differ = 0;
  for (const row of panel.rows) {
    const mine = payload.grid[String(row.ref)];
    const theirs = row.circuit?.km;
    if (mine === undefined || theirs === undefined || theirs === null) continue;
    if (Math.abs(mine.k - theirs) < 1e-9) same += 1; else differ += 1;
  }
  check("every column value is the GRID panel's own number", differ === 0,
    `${same} identical, ${differ} differ`);
}

// ------------------------------------------------------------------ report --
console.log(`\ngrid-distance-column proof: ${passed} passed, ${failures.length} failed`);
if (failures.length) {
  console.error("\nFAILURES");
  for (const f of failures) console.error("  " + f);
  process.exit(1);
}
console.log("the column renders, sorts, blanks honestly, and carries its caveat.");

Grid Proximity

A JavaScript module in PipelineNews that marks tabs, renders radius and sort, calculates great-circle distances and angles and reads inputs for gp centre, gp radius and gp target pick.

Set aside from the main view: 96% of its lines are the same as pipelinenews_intelligence/202609020611/assets/202608311610-grid-proximity.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Grid Proximity; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9603 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 pipelinenews_intelligence/202609020611/assets/202608311610-grid-proximity.mjs:1-702 00dafd47a1693591572cf0c05ec350151da8b181
  • sha256 aee81376b86ecb580ad084ba9a402f1d5e863c4d4bce92f73be321dbb9e53f26
  • target sha256 be8e57089d3075334085d91c77b68ac32b01171b24d8203d40a94d356bfd0cf5
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesypipelinenews / tools/intelligence/cartridges/grid-proximity/assets/{GEN}-grid-proximity.mjs · lines 1–388 of 698 · Not reached from any entry point (candidate for review) · pattern mountGridProximity (shared by 3 files)

What it does
It draws substations, the REPD register, 66kV and cables. Defines 27 functions or classes, including atlasHaversineKm, boundingBox, esc, km, mw. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: substations, the REPD register, 66kV, cables, 132kV.
Inputs & outputs
In: form fields (user input). Out: canvas drawing. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 132kV, 66kV.
What it achieves
It marks tabs (`markTabs`), renders radius (`renderRadius`) and renders sort (`renderSort`). Deployment: not-authorised. Its code works with 66 kV and 132 kV. It responds to click and keydown events.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · tools/intelligence/cartridges/grid-proximity/assets · JavaScript module
Uses
none found
Used by
none found
Produces
GRID_PROXIMITY_CARTRIDGE_CONTRACT, mountGridProximity
Defines here
atlasHaversineKm, boundingBox, esc, km, mw, mountGridProximity, markTabs, ensurePayload, select, renderRadius, run, renderSort, value, draw, renderConnect
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/grid-proximity/assets/{GEN}-grid-proximity.mjs:1-388 · blob 6b75a075e8e52f68847e138ecf2b58caa0cb1654 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
/**
 * PipelineNews grid-proximity cartridge.
 * Generation {GEN}. DRAFT - deployment: not-authorised.
 *
 * ADDITIVE ONLY. Adds a tabbed panel inside its own host div. It does not
 * modify, re-render, restyle or re-order any existing part of the application.
 * If it fails to load, the core product is unchanged.
 *
 * What it adds, all of it ported from work that already exists in the estate:
 *
 *   RADIUS      Geodesic radius search around any centre, using the same
 *               haversine and the same Earth radius as the GridAtlas radius
 *               tool (ventus-corev8engine.js) and the GIS SLD sandbox
 *               (atlasHaversineKm). A distance read here equals the distance
 *               read there.
 *
 *   SORT        The project table sorted by capacity, town, county, postcode
 *               region, circuit distance or substation distance. Click a
 *               heading; click again to reverse.
 *
 *   CONNECT     For every project, the line to the nearest point on the
 *               nearest circuit and the line to the nearest substation, the
 *               same nearestPointOnLine idea the sandbox uses for cable
 *               routes. Exports as GeoJSON that the Atlas and the sandbox
 *               both already read.
 *
 *   TARGET      A scope that locks onto a site and draws straight to the
 *               nearest substation, with every voltage in reach shown in the
 *               colour the REPD atlas grid model has always used for it.
 *               Range rings are geodesic. It is a picture of the same
 *               arithmetic the other tabs print as numbers.
 *
 *   METHOD      What the numbers are, and what they are not.
 *
 * PUBLIC WORDING: caveats are read from the payload's `caveat` block. Nothing
 * about accuracy is hardcoded here. To change wording, edit build_payload.py
 * and regenerate.
 *
 * It uses classes already in the frozen stylesheet (.card, .btn, .filters,
 * .gauges, .meta, .section-title) so it inherits the design freeze. The scope
 * adds its own styles, every selector scoped under #gridProximityHost, so
 * nothing outside the cartridge's own host is restyled.
 */

export const GRID_PROXIMITY_CARTRIDGE_CONTRACT = Object.freeze({
  schema: "pipelinenews.grid-proximity-cartridge.v1",
  generation: "{GEN}",
  deployment: "not-authorised",
  activation: "dynamic-import-on-user-open; payload-fetch-on-first-tab-selection",
  additive_only: true,
  mutates_existing_dom: false,
  project_bindings: 0,
  eligible_for_news_signal: false,
  asserts_no_personal_data: true,
  derived_values_are_inferred: true,
  corroboration_adapters_built: false,
  one_signal_policy: "WITHHOLD",
  tabs: Object.freeze(["RADIUS", "SORT", "CONNECT", "TARGET", "METHOD"]),
});

/* ---- geodesy -------------------------------------------------------------
   Byte-for-byte the same formula and constant as ventus-corev8engine.js
   haversine() and gis-sld-v5-drawing.js atlasHaversineKm(). Do not "improve"
   this to 6371.0088 - that is what made the old circuit_km read 0.112% short
   and disagree with every other Ventus tool.                               */
const R_ATLAS = 6378.137;
const DEG = Math.PI / 180;

function atlasHaversineKm(lon1, lat1, lon2, lat2) {
  const dLat = (lat2 - lat1) * DEG;
  const dLon = (lon2 - lon1) * DEG;
  const x = Math.sin(dLat / 2) ** 2
    + Math.cos(lat1 * DEG) * Math.cos(lat2 * DEG) * Math.sin(dLon / 2) ** 2;
  return R_ATLAS * 2 * Math.atan2(Math.sqrt(x), Math.sqrt(1 - x));
}

/* A cheap bounding box in degrees, so a radius query does not measure every
   project. Latitude is the tighter bound; longitude widens with latitude. */
function boundingBox(lon, lat, km) {
  const dLat = km / (R_ATLAS * DEG);
  const cos = Math.max(Math.cos(lat * DEG), 1e-6);
  return { dLat, dLon: dLat / cos };
}

const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g,
  (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));

const km = (v) => (!Number.isFinite(v) ? "n/a" : v < 1 ? `${Math.round(v * 1000)} m` : `${v.toFixed(2)} km`);
/* Grid probable is deliberately quiet: a plain word and a rank, no traffic
   lights and no banner. The working is one click away for whoever wants it. */
const BAND_RANK = { STRONG: 0, MODERATE: 1, DISTANT: 2, REMOTE: 3, UNKNOWN: 4 };
const mw = (v) => (!Number.isFinite(v) ? "n/a" : v >= 100 ? v.toFixed(0) : v.toFixed(1));

export function mountGridProximity({ host, payloadAsset }) {
  let payloadRequests = 0;
  let data = null;
  let active = "RADIUS";
  let pendingTarget = null;

  const root = document.createElement("div");
  root.className = "card";
  host.appendChild(root);

  const tabs = document.createElement("div");
  tabs.className = "filters";
  tabs.setAttribute("role", "tablist");
  const body = document.createElement("div");
  const note = document.createElement("p");
  note.className = "meta";

  root.append(tabs, note, body);

  GRID_PROXIMITY_CARTRIDGE_CONTRACT.tabs.forEach((code) => {
    const b = document.createElement("button");
    b.className = "btn";
    b.type = "button";
    b.textContent = code;
    b.setAttribute("role", "tab");
    b.addEventListener("click", () => select(code));
    tabs.appendChild(b);
  });

  function markTabs() {
    Array.from(tabs.children).forEach((b) => {
      const on = b.textContent === active;
      b.setAttribute("aria-selected", String(on));
      b.style.fontWeight = on ? "bold" : "";
    });
  }

  async function ensurePayload() {
    if (data) return data;
    note.textContent = "LOAD · requesting the derived proximity index";
    payloadRequests += 1;
    const response = await fetch(payloadAsset.url);
    if (!response.ok) throw new Error(`payload ${response.status}`);
    data = await response.json();
    if (data.schema !== "pipelinenews.v9.grid-proximity.v1") {
      throw new Error("unexpected payload schema");
    }
    note.textContent = `${data.record_count} projects · ${data.network.segments.toLocaleString()} circuit segments · `
      + `${data.network.substations.toLocaleString()} substations · ${data.network.voltages_kv.join("/")} kV`;
    return data;
  }

  async function select(code) {
    active = code;
    markTabs();
    body.textContent = "";
    try {
      const d = await ensurePayload();
      if (code === "RADIUS") renderRadius(d);
      else if (code === "SORT") renderSort(d);
      else if (code === "CONNECT") renderConnect(d);
      else if (code === "TARGET") renderTarget(d, pendingTarget);
      else renderMethod(d);
      pendingTarget = null;
    } catch (error) {
      console.error("grid proximity", error);
      note.textContent = "FAIL · grid proximity unavailable; core product unchanged";
    }
  }

  /* ---- RADIUS ---------------------------------------------------------- */
  function renderRadius(d) {
    const wrap = document.createElement("div");
    wrap.innerHTML = `
      <p class="section-title">PROJECTS WITHIN A RADIUS</p>
      <p class="meta">Centre on any project by name or REPD reference, or type a coordinate as
        <code>lat, lon</code>. Distances are ${esc(d.earth_model.formula)} on
        R = ${d.earth_model.radius_km} km, the same figure the Atlas radius tool uses.</p>
      <div class="filters">
        <input id="gpCentre" type="text" placeholder="Project name, REPD ref, or lat, lon" style="min-width:18rem">
        <input id="gpRadius" type="number" value="10" min="0.1" max="500" step="0.5" style="width:6rem">
        <span class="meta">km</span>
        <button class="btn" id="gpGo" type="button">SEARCH</button>
      </div>
      <div id="gpOut"></div>`;
    body.appendChild(wrap);

    const run = () => {
      const out = wrap.querySelector("#gpOut");
      const raw = wrap.querySelector("#gpCentre").value.trim();
      const radius = Math.max(0.1, Math.min(500, Number(wrap.querySelector("#gpRadius").value) || 10));
      if (!raw) { out.innerHTML = `<p class="meta">Enter a centre to search from.</p>`; return; }

      let centre = null;
      let label = "";
      const coord = raw.match(/^\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*$/);
      if (coord) {
        centre = [Number(coord[2]), Number(coord[1])];
        label = `${centre[1].toFixed(5)}, ${centre[0].toFixed(5)}`;
      } else {
        const needle = raw.toLowerCase();
        const hit = d.rows.find((r) => r.ref === raw)
          || d.rows.find((r) => (r.name || "").toLowerCase().includes(needle));
        if (!hit) { out.innerHTML = `<p class="meta">No project matches that. Try a REPD reference, or <code>lat, lon</code>.</p>`; return; }
        centre = hit.at;
        label = `${hit.name} (REPD ${hit.ref})`;
      }

      const box = boundingBox(centre[0], centre[1], radius);
      const found = [];
      for (const r of d.rows) {
        if (Math.abs(r.at[1] - centre[1]) > box.dLat) continue;
        if (Math.abs(r.at[0] - centre[0]) > box.dLon) continue;
        const dist = atlasHaversineKm(centre[0], centre[1], r.at[0], r.at[1]);
        if (dist <= radius) found.push({ r, dist });
      }
      found.sort((a, b) => a.dist - b.dist);

      const totalMw = found.reduce((s, f) => s + (f.r.mw || 0), 0);
      out.innerHTML = `
        <div class="gauges">
          <div><strong>${found.length}</strong><span>projects within ${radius} km</span></div>
          <div><strong>${mw(totalMw)}</strong><span>MW in the circle</span></div>
          <div><strong>${esc(label)}</strong><span>centre</span></div>
        </div>
        ${table(found.map((f) => ({ ...f.r, _d: f.dist })), [
          ["_d", "DISTANCE", (r) => km(r._d)],
          ["name", "PROJECT", (r) => esc(r.name)],
          ["mw", "MW", (r) => mw(r.mw)],
          ["tech", "TECH", (r) => esc(r.tech)],
          ["town", "TOWN", (r) => esc(r.town)],
          ["circuit", "CIRCUIT", (r) => (r.circuit ? `${km(r.circuit.km)} · ${r.circuit.kv} kV` : "n/a")],
        ])}`;
    };

    wrap.querySelector("#gpGo").addEventListener("click", run);
    wrap.querySelector("#gpCentre").addEventListener("keydown", (e) => { if (e.key === "Enter") run(); });
  }

  /* ---- SORT ------------------------------------------------------------ */
  function renderSort(d) {
    let key = "mw";
    let dir = -1;
    const wrap = document.createElement("div");
    body.appendChild(wrap);

    const columns = [
      ["name", "PROJECT", (r) => esc(r.name)],
      ["mw", "MW", (r) => mw(r.mw)],
      ["tech", "TECH", (r) => esc(r.tech)],
      ["town", "TOWN", (r) => esc(r.town)],
      ["county", "COUNTY", (r) => esc(r.county)],
      ["region", "REGION", (r) => esc(r.region)],
      ["_ckm", "CIRCUIT", (r) => (r.circuit ? km(r.circuit.km) : "n/a")],
      ["_ckv", "kV", (r) => (r.circuit ? r.circuit.kv : "n/a")],
      ["_tkm", "TRANSMISSION", (r) => (r.circuit_transmission ? `${km(r.circuit_transmission.km)} · ${r.circuit_transmission.kv}` : "n/a")],
      ["_skm", "SUBSTATION", (r) => (r.substation ? km(r.substation.km) : "n/a")],
      ["_gp", "GRID", (r) => `<button class="gp-lock" type="button" data-why="${esc(r.ref)}"
        title="show the working">${esc(r.grid_probable.band.toLowerCase())}</button>`],
    ];

    const value = (r, k) => (
      k === "_tkm" ? (r.circuit_transmission ? r.circuit_transmission.km : Infinity)
        : k === "_gp" ? BAND_RANK[r.grid_probable.band]
        : k === "_ckm" ? (r.circuit ? r.circuit.km : Infinity)
        : k === "_ckv" ? (r.circuit ? r.circuit.kv : -1)
          : k === "_skm" ? (r.substation ? r.substation.km : Infinity)
            : r[k]);

    function draw() {
      const rows = d.rows.slice().sort((a, b) => {
        const x = value(a, key);
        const y = value(b, key);
        if (typeof x === "string" || typeof y === "string") {
          return String(x || "").localeCompare(String(y || "")) * dir;
        }
        return ((x ?? Infinity) - (y ?? Infinity)) * dir;
      });
      wrap.innerHTML = `
        <p class="section-title">EVERY PROJECT, SORTED</p>
        <p class="meta">Click a heading to sort. Click it again to reverse. Sorting by town or county
          clusters a region together; sorting by circuit distance puts the best-connected first.</p>
        <div id="gpWhy"></div>
        ${table(rows.slice(0, 400), columns, key, dir)}
        <p class="meta">Showing the first 400 of ${d.record_count}. Narrow with the RADIUS tab.</p>`;
      injectScopeStyle();
      wrap.querySelectorAll("button[data-why]").forEach((btn) => {
        btn.addEventListener("click", () => {
          const r = d.rows.find((x) => x.ref === btn.dataset.why);
          const rule = d.grid_probable_rule;
          const box = wrap.querySelector("#gpWhy");
          box.innerHTML = `<div class="gp-readout"><h4>${esc(r.grid_probable.band)} · ${esc(r.name)}</h4>
            <dl><dt>NEAREST CIRCUIT</dt><dd>${km(r.circuit.km)} · ${r.circuit.kv} kV</dd>
            <dt>NEAREST SUBSTATION</dt><dd>${km(r.substation.km)}</dd>
            <dt>CAPACITY</dt><dd>${mw(r.mw)} MW</dd></dl>
            <p class="meta" style="margin:10px 0 0;font-size:11px;color:#4d7a5f">${esc(rule.purpose)}</p>
            <p class="meta" style="margin:6px 0 0;font-size:11px;color:#4d7a5f"><strong>Not modelled:</strong>
              ${rule.not_modelled.map(esc).join("; ")}.</p></div>`;
        });
      });
      wrap.querySelectorAll("th[data-k]").forEach((th) => {
        th.style.cursor = "pointer";
        th.addEventListener("click", () => {
          const k = th.dataset.k;
          if (k === key) dir = -dir; else { key = k; dir = (k === "name" || k === "town" || k === "county" || k === "region" || k === "tech") ? 1 : -1; }
          draw();
        });
      });
    }
    draw();
  }

  /* ---- CONNECT --------------------------------------------------------- */
  function renderConnect(d) {
    const wrap = document.createElement("div");
    const closest = d.rows
      .filter((r) => r.substation && r.circuit)
      .slice()
      .sort((a, b) => a.substation.km - b.substation.km)
      .slice(0, 60);
    wrap.innerHTML = `
      <p class="section-title">AUTO-DRAWN CONNECTIONS</p>
      <p class="meta">For every project the panel holds two indicative lines: the site to the
        nearest point on the nearest circuit, and the site to the nearest mapped substation.
        The circuit point is a true perpendicular onto the line, not the nearest drawn vertex.
        ${esc(d.caveat.substation)}</p>
      <div class="filters">
        <button class="btn" id="gpGeo" type="button">EXPORT ALL AS GEOJSON</button>
        <span class="meta">Opens in the Atlas and the GIS SLD sandbox</span>
      </div>
      ${table(closest, [
        ["name", "PROJECT", (r) => esc(r.name)],
        ["mw", "MW", (r) => mw(r.mw)],
        ["_sub", "NEAREST SUBSTATION", (r) => esc(r.substation.name || "unnamed")],
        ["_skv", "kV", (r) => (r.substation.kv.length ? r.substation.kv.join("/") : "n/a")],
        ["_skm", "TO SUBSTATION", (r) => km(r.substation.km)],
        ["_ckm", "TO CIRCUIT", (r) => `${km(r.circuit.km)} · ${r.circuit.kv} kV`],
        ["_lock", "", (r) => `<button class="gp-lock" type="button" data-ref="${esc(r.ref)}">LOCK</button>`],
      ])}
      <p class="meta">The 60 projects closest to a mapped substation. Every one of the
        ${d.record_count} rows carries the same two lines in the export.</p>`;
    body.appendChild(wrap);

    injectScopeStyle();
    wrap.querySelectorAll("button.gp-lock").forEach((btn) => {
      btn.addEventListener("click", () => {
        pendingTarget = d.rows.find((r) => r.ref === btn.dataset.ref) || null;
        select("TARGET");
      });
    });

    wrap.querySelector("#gpGeo").addEventListener("click", () => {
      const features = [];
      for (const r of d.rows) {
        if (r.circuit) {
          features.push(lineFeature(r.at, r.circuit.foot, {
            type: "indicative_circuit_connection",
            repd_ref: r.ref, project: r.name, mw: r.mw,
            circuit_kv: r.circuit.kv, circuit_name: r.circuit.line || null,
            length_km: r.circuit.km,
            measurement_method: "atlas_haversine_6378_137_km",
            basis: "perpendicular to the nearest mapped circuit segment",
          }));
        }
        if (r.substation) {
          features.push(lineFeature(r.at, r.substation.at, {
            type: "indicative_substation_connection",
            repd_ref: r.ref, project: r.name, mw: r.mw,
            substation: r.substation.name || null,
            substation_kv: r.substation.kv,
            length_km: r.substation.km,
            measurement_method: "atlas_haversine_6378_137_km",
            basis: "straight line to the nearest mapped substation point",
          }));
        }
      }
      const blob = new Blob([JSON.stringify({
        type: "FeatureCollection",
        properties: {
          generation: d.generation,
          note: "Indicative screening geometry. Not a cable route, wayleave or connection offer.",
          caveat: d.caveat,
          provenance: d.provenance,
        },
        features,
      })], { type: "application/geo+json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${d.generation}-indicative-connections.geojson`;
      a.click();
      setTimeout(() => URL.revokeObjectURL(url), 4000);
    });
  }