GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / globalgrid2050 / pipelinenews_intelligence/202609040144/assets

GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v3 Page and 1 more file

A map page that maps grid 400kV, grid 275kV, grid 220kV and grid 132kV, using haversine. Published at https://globalgrid2050.com/repd_grid_atlasv3/. It normalizes status (`normalizeStatus`), toggles curtain (`toggleCurtain`) and gets radius (`getRadiusValue`).

700 lines of HTML and JavaScript from globalgrid2050, in 2 files. Topic: Maps, GIS and field navigation. Section 490 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. Atlas Pointer Deep Link transform · globalgrid2050 / pipelinenews_intelligence/202609040144/assets/202609040044-atlas-pointer-deep-link.mjs lines 1–128
  2. GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v3 Page geodesy · globalgrid2050 / repd_grid_atlasv3/index.html lines 1–572

Atlas Pointer Deep Link

A JavaScript module in the assets folder of GlobalGrid2050 that works with the Renewable Energy Planning Database (REPD) register and uses data from the GridAtlas repository.

transformglobalgrid2050 / pipelinenews_intelligence/202609040144/assets/202609040044-atlas-pointer-deep-link.mjs · lines 1–128 of 128 · version 2026-09-04 00:44 · pattern projectFields (shared by 3 files)

What it does
It calculates the REPD register. Defines numberInRange, projectFields, buildAtlasV9DeepLink, selfTest, check.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): 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.
Inputs & outputs
Coordinate systems named: WGS84 / EPSG:4326.
Downstream impact
Used directly by 4 files: Wider Fleet (globalgrid2050); GlobalGrid2050 — PipelineNews Intelligence (globalgrid2050); Wider Fleet (globalgrid2050); Testcode — Pipeline (globalgrid2050). Reached from 56 other entry points, including GlobalGrid2050 — PipelineNews Intelligence Page (globalgrid2050, https://globalgrid2050.com/pipelinenews_intelligence/202609050309/); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html); Homepage V038 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v038.html).
What it achieves
It builds atlas v9 deep link (`buildAtlasV9DeepLink`) and is built from the number in range helper (`numberInRange`) and the project fields helper (`projectFields`). One fail-closed Pipeline News -> GridAtlas transport contract.
Why it matters
Imported by 4 files, including Wider Fleet, GlobalGrid2050 — PipelineNews Intelligence and Testcode — Pipeline.
Application
globalgrid2050 · pipelinenews_intelligence/202609040144/assets · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL)
Used by
imported by Wider Fleet (import), imported by GlobalGrid2050 — PipelineNews Intelligence (import), imported by Wider Fleet (import), imported by Testcode — Pipeline (import)
Produces
CANONICAL_PROJECT_TECHNOLOGIES, ATLAS_DEEP_LINK_CONTRACT, buildAtlasV9DeepLink, selfTest
Defines here
numberInRange, projectFields, buildAtlasV9DeepLink, selfTest, check
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 pipelinenews_intelligence/202609040144/assets/202609040044-atlas-pointer-deep-link.mjs:1-128 · blob d379c9ce4e097d3a460b2414714e37f6ed18884b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
 * One fail-closed Pipeline News -> GridAtlas transport contract.
 *
 * Every clickable MAP action carries an exact REPD identity, one canonical
 * GridAtlas technology token, and a complete WGS84 coordinate pair.  Display
 * context remains advisory at the receiver; dropping identity is never a
 * fallback for a receiver defect.
 */

const RECEIVER = Object.freeze({
  base_url: "https://ventusltd.github.io/gridatlas/atlas/",
  hostname: "ventusltd.github.io",
  pathname: "/gridatlas/atlas/",
});

export const CANONICAL_PROJECT_TECHNOLOGIES = Object.freeze([
  "act", "bess", "biomass", "caes", "flywheel", "geothermal",
  "hydro", "hydrogen", "other", "solar", "solar_roof", "tidal",
  "wind_offshore", "wind_onshore",
]);

const TECHNOLOGIES = new Set(CANONICAL_PROJECT_TECHNOLOGIES);
const QUERY_PARAMETER_ORDER = Object.freeze([
  "repd_ref", "project", "technology", "capacity_mw",
  "latitude", "longitude", "zoom",
]);
const CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/u;
const DEFAULT_ZOOM = 12;

export const ATLAS_DEEP_LINK_CONTRACT = Object.freeze({
  schema: "pipelinenews.atlas-map-corpus-contract.v1",
  generation: "202609040044",
  active_target: "ported",
  receiver: RECEIVER,
  identity_anchor: "repd_ref",
  query_parameter_order: QUERY_PARAMETER_ORDER,
  canonical_project_technologies: CANONICAL_PROJECT_TECHNOLOGIES,
  context_parameters_are_advisory: true,
  clickable_requires: Object.freeze([
    "canonical repd_ref", "canonical technology", "finite latitude",
    "finite longitude", "non-negative capacity_mw",
  ]),
  receiver_candidate: Object.freeze({
    commit: "b73247803377233069acfeff415ecad4e8391cb2",
    module: "atlas/codex/20260904-finding-loop-30x/finding-loop.mjs",
    module_sha256: "fdaf16829275c904ef190ba96925415151c9ac6f409eac39d81440dbdd0c3d20",
    module_bytes: 60148,
    contract: "PROJECT_TECHNOLOGIES + parseProjectDeepLink",
  }),
});

function numberInRange(value, minimum, maximum) {
  if (value === null || value === undefined || value === "") return null;
  const number = Number(value);
  return Number.isFinite(number) && number >= minimum && number <= maximum
    ? number : null;
}

function projectFields(project) {
  const coordinates = Array.isArray(project?.ll) ? project.ll : null;
  return {
    repdRef: String(project?.repd_ref ?? project?.ref ?? "").trim(),
    // REPD 13263 contains an embedded line break in its official display
    // name. Whitespace canonicalisation preserves the words without putting a
    // control character into a query string or discarding the exact identity.
    name: String(project?.name ?? project?.n ?? "").replace(/\s+/gu, " ").trim(),
    technology: String(project?.technology ?? project?.t ?? "").trim(),
    capacity: numberInRange(project?.capacity_mw ?? project?.c, 0, Number.MAX_VALUE),
    latitude: numberInRange(project?.latitude ?? coordinates?.[1], -90, 90),
    longitude: numberInRange(project?.longitude ?? coordinates?.[0], -180, 180),
    geometryStatus: project?.geometry_status,
  };
}

/** Return a canonical absolute URL, or an empty string for a non-clickable row. */
export function buildAtlasV9DeepLink(project) {
  const fields = projectFields(project);
  if (fields.geometryStatus !== undefined && fields.geometryStatus !== "valid") return "";
  if (!/^[1-9]\d*$/u.test(fields.repdRef)) return "";
  if (!TECHNOLOGIES.has(fields.technology)) return "";
  if (CONTROL_CHARACTER.test(fields.name)) return "";
  if (fields.capacity === null || fields.latitude === null || fields.longitude === null) return "";

  const url = new URL(RECEIVER.base_url);
  url.searchParams.set("repd_ref", fields.repdRef);
  // An official blank stays blank. The parameter is still present, and no
  // replacement name is invented merely to make a URL look complete.
  url.searchParams.set("project", fields.name);
  url.searchParams.set("technology", fields.technology);
  url.searchParams.set("capacity_mw", String(fields.capacity));
  url.searchParams.set("latitude", String(fields.latitude));
  url.searchParams.set("longitude", String(fields.longitude));
  url.searchParams.set("zoom", String(DEFAULT_ZOOM));
  return url.href;
}

export function selfTest() {
  const checks = [];
  const check = (name, ok) => checks.push({ name, ok: Boolean(ok) });
  const fixture = {
    repd_ref: "155", name: "Markinch Biomass CHP Plant", technology: "biomass",
    capacity_mw: 65, latitude: 56.20118, longitude: -3.162255,
    geometry_status: "valid",
  };
  const href = buildAtlasV9DeepLink(fixture);
  const url = new URL(href);
  check("valid row emits", Boolean(href));
  check("stable receiver", url.hostname === RECEIVER.hostname && url.pathname === RECEIVER.pathname);
  check("exact ordered parameters",
    [...url.searchParams.keys()].join(",") === QUERY_PARAMETER_ORDER.join(","));
  check("identity retained", url.searchParams.get("repd_ref") === "155");
  check("canonical technology retained", url.searchParams.get("technology") === "biomass");
  check("coordinates retained",
    url.searchParams.get("latitude") === "56.20118"
      && url.searchParams.get("longitude") === "-3.162255");
  check("zero capacity remains explicit",
    new URL(buildAtlasV9DeepLink({ ...fixture, capacity_mw: 0 }))
      .searchParams.get("capacity_mw") === "0");
  check("missing identity is not worked around",
    buildAtlasV9DeepLink({ ...fixture, repd_ref: "" }) === "");
  check("unknown technology fails closed",
    buildAtlasV9DeepLink({ ...fixture, technology: "Biomass (dedicated)" }) === "");
  check("half coordinate fails closed",
    buildAtlasV9DeepLink({ ...fixture, longitude: null }) === "");
  check("invalid geometry fails closed",
    buildAtlasV9DeepLink({ ...fixture, geometry_status: "missing" }) === "");
  return Object.freeze({ ok: checks.every(({ ok }) => ok), checks: Object.freeze(checks) });
}

GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v3 Page

A map page that maps grid 400kV, grid 275kV, grid 220kV and grid 132kV, using haversine. Published at https://globalgrid2050.com/repd_grid_atlasv3/. It normalizes status (`normalizeStatus`), toggles curtain (`toggleCurtain`) and gets radius (`getRadiusValue`).

geodesyglobalgrid2050 / repd_grid_atlasv3/index.html · lines 1–572 of 1200 · Entry point · pattern enterFullscreen (shared by 2 files)

What it does
It maps grid 400kV, grid 275kV, grid 220kV and grid 132kV. Defines 37 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, enterFullscreen, exitFullscreen. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): 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: 400kV, 275kV, 220kV, 132kV, 66kV, 11kV.
Inputs & outputs
In: GeoJSON file grid_400kv.geojson; GeoJSON file grid_275kv.geojson; GeoJSON file grid_220kv.geojson; GeoJSON file grid_132kv.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file grid_11kv_ukpn.geojson; GeoJSON file grid_substations.geojson; GeoJSON file power_plants.geojson. Out: web page; interactive map. Voltage levels named: 400kV, 275kV, 220kV, 132kV, 66kV, 11kV.
Downstream impact
Used directly by 8 files: GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); Homepage V030 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v030.html); Homepage V031 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v031.html); Homepage V032 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v032.html); and 4 more. Reached from 87 other entry points, including GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html); Homepage V038 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v038.html). It is itself an entry point, published at https://globalgrid2050.com/repd_grid_atlasv3/.
What it achieves
Its `snapLines` function gives line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged from line features and substation point features (VEDIC: snap line ends to substations). Its code works with 100 kW, 11 kV and 132 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
Loaded by the GlobalGrid2050 Historical Builds map page at https://globalgrid2050.com/historical_builds.html and 7 other pages.
Application
globalgrid2050 · repd_grid_atlasv3 · page
VEDIC
SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
Uses
https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.css, https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.js
Used by
named by URL in GlobalGrid2050 Historical Builds (estate URL), named by URL in Homepage V030 (estate URL), named by URL in Homepage V031 (estate URL), named by URL in Homepage V032 (estate URL), named by URL in Homepage V033 (estate URL), named by URL in Homepage V034 (estate URL), named by URL in Homepage V035 (estate URL), named by URL in Homepage V036 (estate URL)
Produces
deepFreeze, escapeHTML, normalizeStatus, enterFullscreen, exitFullscreen, toggleCurtain, getRadiusValue, validateRadiusInput, fmt, updateMeasureDisplay, updateMeasureLayers, clearMeasure
Defines here
deepFreeze, escapeHTML, normalizeStatus, enterFullscreen, exitFullscreen, toggleCurtain, getRadiusValue, validateRadiusInput, fmt, updateMeasureDisplay, updateMeasureLayers, clearMeasure, toggleMeasureMode, updateUIState, FetchQueue, fetchWithTimeout, fetchAndParseGeoJSON
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv3/index.html:1-572 · blob 6709a72fd0351552373755d867d0c8ef4b24ee63 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>GlobalGrid2050 | Ventus Core</title>
    <link href="https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.css" rel="stylesheet" />
    <style>
        html, body { margin: 0; padding: 0; width: 100%; height: 100%; background: #000; font-family: 'Courier New', monospace; color: white; overflow: hidden; }
        .dashboard { display: flex; flex-direction: column; height: 100vh; height: 100dvh; width: 100vw; padding: 4px; gap: 4px; box-sizing: border-box; }
        #fatal-banner { display: none; position: fixed; top: 0; left: 0; width: 100%; background: #ff0000; color: #fff; text-align: center; padding: 10px; font-weight: bold; z-index: 9999; text-transform: uppercase; font-size: 12px; letter-spacing: 1px; }
        .hud-header { background: #0a0a0a; border: 1px solid #333; border-radius: 6px; padding: 6px 12px; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; }
        .hud-val { font-size: 16px; font-weight: bold; color: #00ffff; text-shadow: 0 0 5px #00ffff; }
        .ventus-brand { text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; line-height: 1.2; }
        .ventus-main { font-family: -apple-system, sans-serif; font-size: 17px; font-weight: 800; color: #fff; letter-spacing: 5px; text-transform: uppercase; margin-bottom: 2px; }
        .ventus-sub { font-family: -apple-system, sans-serif; font-size: 6.5px; color: #888; letter-spacing: 2px; text-transform: uppercase; }
        .map-container { position: relative; flex-grow: 1; min-height: 0; border: 1px solid #222; border-radius: 6px; overflow: hidden; background: #0b0e14; }
        #map { width: 100%; height: 100%; }
        .podcast-shoutout { position: absolute; bottom: 6px; right: 8px; font-family: -apple-system, sans-serif; font-size: 8px; color: #fff; opacity: 0.5; text-align: right; text-transform: uppercase; letter-spacing: 1px; pointer-events: none; z-index: 10; text-shadow: 1px 1px 2px #000; }
        .scada-wrapper { background: #050505; border: 1px solid #444; border-radius: 6px; padding: 12px; display: flex; flex-direction: column; flex-shrink: 0; max-height: 38vh; }
        .scada-brand { display: flex; align-items: center; gap: 8px; padding-bottom: 8px; margin-bottom: 8px; border-bottom: 1px solid #222; flex-shrink: 0; }
        .scada-brand-main { font-family: -apple-system, sans-serif; font-size: 11px; font-weight: 800; color: #fff; letter-spacing: 4px; text-transform: uppercase; }
        .scada-brand-sub { font-family: -apple-system, sans-serif; font-size: 6px; color: #555; letter-spacing: 2px; text-transform: uppercase; }
        .scada-brand-tag { margin-left: auto; font-family: 'Courier New', monospace; font-size: 7px; color: #333; text-transform: uppercase; letter-spacing: 1px; }
        .scada-keys { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 12px; overflow-y: auto; padding-bottom: 5px; }
        .key-group { border-left: 2px solid #333; padding-left: 10px; margin-bottom: 4px; }
        .key-title { font-size: 10px; color: #66ccff; text-transform: uppercase; margin-bottom: 6px; font-weight: bold; }
        .key-item { display: flex; align-items: center; gap: 8px; font-size: 13px; margin-bottom: 8px; cursor: pointer; }
        input[type="checkbox"], input[type="radio"] { transform: scale(1.3); margin-right: 4px; accent-color: #00ffff; }
        .maplibregl-popup-content { background: #000; color: #00ffff; border: 1px solid #444; font-family: monospace; font-size: 12px; padding: 8px; }
        .disclaimer-box { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; text-align: justify; font-size: 9px; line-height: 1.5; color: #666; margin-top: 10px; padding-top: 10px; border-top: 1px solid #222; user-select: none; pointer-events: none; flex-shrink: 0; }
        .custom-map-attrib { position: absolute; top: 10px; left: 10px; background: rgba(5, 5, 5, 0.7); color: #888; font-family: 'Courier New', monospace; font-size: 9px; border-radius: 4px; padding: 4px 8px; z-index: 10; border: 1px solid #333; pointer-events: auto; max-width: calc(100% - 60px); line-height: 1.6; }
        .custom-map-attrib a { color: #00ffff; text-decoration: none; }
        .custom-map-attrib a:hover { text-decoration: underline; }
        body.fs-active .custom-map-attrib { top: 44px; }
        .popup-search-btns { display: flex; gap: 6px; margin-top: 8px; }
        .popup-btn { flex: 1; padding: 5px 0; font-family: monospace; font-size: 11px; font-weight: bold; border: 1px solid #444; border-radius: 3px; cursor: pointer; text-align: center; text-decoration: none; display: block; transition: border-color 0.15s, color 0.15s; }
        .popup-btn-news { background: #0a0a0a; color: #ffae00; border-color: #ffae00; }
        .popup-btn-news:hover { background: #ffae00; color: #000; }
        .popup-btn-images { background: #0a0a0a; color: #00ffff; border-color: #00ffff; }
        .popup-btn-images:hover { background: #00ffff; color: #000; }
        .search-bar-wrapper { position: absolute; top: 72px; right: 10px; z-index: 20; display: flex; gap: 6px; }
        body.fs-active .search-bar-wrapper { top: 100px; }
        .search-input { background: rgba(5,5,5,0.85); border: 1px solid #444; border-radius: 4px; color: #00ffff; font-family: 'Courier New', monospace; font-size: 11px; padding: 5px 10px; width: 220px; outline: none; }
        .search-input::placeholder { color: #444; }
        .search-input:focus { border-color: #00ffff; }
        .search-btn { background: #0a0a0a; border: 1px solid #00ffff; border-radius: 4px; color: #00ffff; font-family: 'Courier New', monospace; font-size: 11px; padding: 5px 10px; cursor: pointer; }
        .search-btn:hover { background: #00ffff; color: #000; }
        .search-results { position: absolute; top: 36px; right: 0; background: #050505; border: 1px solid #333; border-radius: 4px; width: 300px; max-height: 220px; overflow-y: auto; z-index: 21; display: none; }
        .search-result-item { padding: 7px 10px; font-family: 'Courier New', monospace; font-size: 10px; color: #888; cursor: pointer; border-bottom: 1px solid #111; line-height: 1.5; }
        .search-result-item:hover { background: #111; color: #00ffff; }
        .search-result-item b { color: #ffcc00; }
        .search-no-results { padding: 8px 10px; font-family: 'Courier New', monospace; font-size: 10px; color: #444; }
        .map-controls { position: absolute; bottom: 30px; left: 10px; z-index: 20; display: flex; flex-direction: column; gap: 4px; }
        .map-ctrl-btn { background: rgba(5,5,5,0.85); border: 1px solid #333; border-radius: 4px; color: #888; font-family: 'Courier New', monospace; font-size: 9px; padding: 5px 8px; cursor: pointer; text-transform: uppercase; letter-spacing: 1px; white-space: nowrap; }
        .map-ctrl-btn:hover { border-color: #00ffff; color: #00ffff; }
        .map-ctrl-btn.active { border-color: #00ffff; color: #00ffff; background: rgba(0,255,255,0.08); }
        .radius-popup { position: absolute; bottom: 30px; left: 120px; z-index: 20; background: #050505; border: 1px solid #444; border-radius: 4px; padding: 8px 12px; display: none; }
        .radius-popup label { font-size: 9px; color: #888; text-transform: uppercase; letter-spacing: 1px; display: block; margin-bottom: 4px; }
        .radius-input-row { display: flex; align-items: center; gap: 4px; }
        #radius-input { background: #0a0a0a; border: 1px solid #333; color: #00ffff; font-family: 'Courier New', monospace; font-size: 12px; font-weight: bold; padding: 3px 6px; border-radius: 3px; width: 56px; outline: none; text-align: right; -moz-appearance: textfield; }
        #radius-input::-webkit-outer-spin-button, #radius-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
        #radius-input:focus { border-color: #00ffff; }
        #radius-input.invalid { border-color: #ff4444; color: #ff4444; }
        .radius-unit { font-size: 10px; color: #555; font-family: 'Courier New', monospace; white-space: nowrap; }
        .radius-hint { font-size: 8px; color: #444; margin-top: 4px; letter-spacing: 0.5px; }
        /* Measure display */
        #measure-display { position: absolute; bottom: 30px; left: 50%; transform: translateX(-50%); z-index: 20; background: rgba(5,5,5,0.92); border: 1px solid #00ffff; border-radius: 4px; padding: 8px 14px; display: none; font-family: 'Courier New', monospace; font-size: 10px; color: #00ffff; text-align: center; white-space: nowrap; pointer-events: none; }
        #measure-display .m-row { margin-bottom: 2px; color: #888; }
        #measure-display .m-row span { color: #00ffff; }
        #measure-display .m-hint { font-size: 8px; color: #444; margin-top: 4px; }
        /* Fullscreen letterhead */
        #fs-letterhead { display: none; position: fixed; top: 8px; right: 12px; z-index: 512; text-align: right; pointer-events: none; }
        #fs-letterhead .ventus-main { font-family: -apple-system, sans-serif; font-size: 15px; font-weight: 800; color: #fff; letter-spacing: 5px; text-transform: uppercase; margin-bottom: 1px; }
        #fs-letterhead .ventus-sub { font-family: -apple-system, sans-serif; font-size: 6px; color: #888; letter-spacing: 2px; text-transform: uppercase; }
        body.fs-active #fs-letterhead { display: block; }
        .status-legend { display: flex; gap: 8px; flex-wrap: wrap; padding: 4px 0 6px 0; border-bottom: 1px solid #222; margin-bottom: 6px; flex-shrink: 0; }
        .status-dot { display: inline-flex; align-items: center; gap: 4px; font-size: 8px; color: #555; }
        .status-dot span { width: 7px; height: 7px; border-radius: 50%; display: inline-block; }
        .map-container.is-fullscreen { position: fixed; top: 0; left: 0; width: 100vw; height: 100dvh; border-radius: 0; border: none; z-index: 500; }
        #btn-fullscreen { position: absolute; top: 10px; right: 10px; z-index: 25; background: rgba(5,5,5,0.85); border: 1px solid #333; border-radius: 4px; color: #888; font-family: 'Courier New', monospace; font-size: 11px; padding: 5px 8px; cursor: pointer; letter-spacing: 1px; line-height: 1; }
        #btn-fullscreen:hover { border-color: #00ffff; color: #00ffff; }
        #btn-fullscreen-exit { display: none; position: fixed; top: 8px; left: 12px; z-index: 510; background: rgba(5,5,5,0.9); border: 1px solid #00ffff; border-radius: 4px; color: #00ffff; font-family: 'Courier New', monospace; font-size: 10px; padding: 5px 10px; cursor: pointer; letter-spacing: 1px; }
        .is-fullscreen ~ #btn-fullscreen-exit, body.fs-active #btn-fullscreen-exit { display: block; }
        #fs-curtain { display: none; position: fixed; top: 0; left: 0; width: 100vw; z-index: 505; background: rgba(5, 5, 5, 0.96); border-bottom: 1px solid #333; transform: translateY(-100%); transition: transform 0.3s ease; max-height: 70dvh; overflow-y: auto; padding: 48px 16px 16px 16px; box-sizing: border-box; }
        #fs-curtain.curtain-open { transform: translateY(0); }
        body.fs-active #fs-curtain { display: block; }
        #fs-curtain-tab { display: none; position: fixed; top: 0; left: 50%; transform: translateX(-50%); z-index: 510; background: rgba(5,5,5,0.9); border: 1px solid #333; border-top: none; border-radius: 0 0 6px 6px; color: #555; font-family: 'Courier New', monospace; font-size: 9px; padding: 4px 16px 5px 16px; cursor: pointer; letter-spacing: 1px; text-transform: uppercase; white-space: nowrap;  … [line shortened here: 447 characters; full line on GitHub]
        #fs-curtain-tab:hover { color: #00ffff; border-color: #00ffff; }
        body.fs-active #fs-curtain-tab { display: block; }
        .map-container.is-fullscreen #fs-curtain-tab { display: block; }
        #fs-curtain-keys { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 16px; }
    </style>
</head>
<body>

<div id="fatal-banner">CRITICAL ERROR: SYSTEM DEPENDENCIES FAILED TO LOAD</div>
<button id="btn-fullscreen-exit" onclick="exitFullscreen()">✕ Exit</button>
<div id="fs-curtain-tab">⬇ Layers</div>
<div id="fs-curtain"><div id="fs-curtain-keys"></div></div>
<div id="fs-letterhead">
    <div class="ventus-main">Ventus</div>
    <div class="ventus-sub">Cables &amp; Connectivity&reg;</div>
</div>

<div class="dashboard">
    <div class="hud-header">
        <div>
            <small style="color:#888">SYSTEM TIME</small><br>
            <span class="hud-val" id="clock">--:--:--</span><br>
            <span id="date" style="font-size: 11px; color: #888;">--/--/----</span>
        </div>
        <div class="ventus-brand">
            <div class="ventus-main">Ventus</div>
            <div class="ventus-sub">Cables &amp; Connectivity&reg;</div>
        </div>
        <div style="text-align:right"><small style="color:#888">2050 TARGET</small><br><span class="hud-val" id="days" style="color:#ff9d00">-- DAYS</span></div>
    </div>

    <div class="map-container" id="map-container">
        <div id="map"></div>
        <div class="custom-map-attrib">
            Data © <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener noreferrer">OpenStreetMap contributors</a> | © CARTO | EV data © <a href="https://openchargemap.org" target="_blank" rel="noopener noreferrer">Open Charge Map</a>
        </div>
        <button id="btn-fullscreen" onclick="enterFullscreen()" title="Fullscreen">⛶</button>
        <div class="search-bar-wrapper">
            <div style="position:relative">
                <input class="search-input" id="search-input" type="text" placeholder="Search project name..." autocomplete="off" />
                <div class="search-results" id="search-results"></div>
            </div>
            <button class="search-btn" id="search-btn">GO</button>
        </div>
        <div class="map-controls">
            <button class="map-ctrl-btn" id="btn-export">⬇ Export CSV</button>
            <button class="map-ctrl-btn" id="btn-radius">◎ Radius Search</button>
            <button class="map-ctrl-btn" id="btn-status">◑ Status Colours</button>
            <button class="map-ctrl-btn" id="btn-measure">📏 Measure</button>
        </div>
        <div class="radius-popup" id="radius-popup">
            <label>Radius from click</label>
            <div class="radius-input-row">
                <input type="number" id="radius-input" value="10" min="1" max="160" step="1" />
                <span class="radius-unit">km</span>
            </div>
            <div class="radius-hint">1 – 160 km (100 mi) · press Enter to apply</div>
        </div>
        <div id="measure-display">
            <div class="m-row" id="m-line" style="display:none">━━ <span id="m-km"></span> km | <span id="m-m"></span> m | <span id="m-mi"></span> mi</div>
            <div class="m-row" id="m-perim" style="display:none">Perimeter: <span id="m-pkm"></span> km | <span id="m-pm"></span> m</div>
            <div class="m-row" id="m-area" style="display:none">Area: <span id="m-km2"></span> km² | <span id="m-ha"></span> ha | <span id="m-ac"></span> ac</div>
            <div class="m-hint" id="m-hint">Click to add points · Double-click to close polygon</div>
        </div>
        <div class="podcast-shoutout">In support of The Future of Solar Photovoltaics podcast<br>&amp; all participants to date</div>
    </div>

    <div class="scada-wrapper">
        <div class="scada-brand">
            <div>
                <div class="scada-brand-main">Ventus</div>
                <div class="scada-brand-sub">Cables &amp; Connectivity&reg;</div>
            </div>
            <div class="scada-brand-tag">globalgrid2050.com | open infrastructure intelligence</div>
        </div>
        <div class="status-legend">
            <div class="status-dot"><span style="background:#00ff88"></span>Operational</div>
            <div class="status-dot"><span style="background:#ffcc00"></span>Under Construction</div>
            <div class="status-dot"><span style="background:#ff8800"></span>Consented</div>
            <div class="status-dot"><span style="background:#8888ff"></span>Applied</div>
        </div>
        <div class="scada-keys" id="scada-ui-container"></div>
        <div class="disclaimer-box">
            This interface is based on publicly available and open source infrastructure data, including public energy datasets such as REPD where applicable. It is presented for analytical and visualisation purposes only and does not include live operational or other non public operational data.
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.js"></script>
<script>
'use strict';

if (typeof maplibregl === 'undefined') {
    document.getElementById('fatal-banner').style.display = 'block';
    throw new Error('CRITICAL: MapLibre failed to load.');
}

function deepFreeze(obj) {
    Object.keys(obj).forEach(prop => {
        if (typeof obj[prop] === 'object' && obj[prop] !== null) deepFreeze(obj[prop]);
    });
    return Object.freeze(obj);
}

function escapeHTML(value) {
    return String(value ?? '')
        .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}

function normalizeStatus(status) {
    return String(status ?? '').trim().toLowerCase();
}

let fsActive = false;
let curtainOpen = false;

function enterFullscreen() {
    fsActive = true;
    document.body.classList.add('fs-active');
    document.documentElement.classList.add('fs-active');
    document.getElementById('map-container').classList.add('is-fullscreen');
    document.getElementById('btn-fullscreen').style.display = 'none';
    const el = document.getElementById('map-container');
    if (el.requestFullscreen) { el.requestFullscreen().catch(() => {}); }
    else if (el.webkitRequestFullscreen) { el.webkitRequestFullscreen(); }
    setTimeout(() => map.resize(), 50);
}

function exitFullscreen() {
    fsActive = false;
    curtainOpen = false;
    document.body.classList.remove('fs-active');
    document.documentElement.classList.remove('fs-active');
    document.getElementById('map-container').classList.remove('is-fullscreen');
    document.getElementById('btn-fullscreen').style.display = '';
    document.getElementById('fs-curtain').classList.remove('curtain-open');
    if (document.fullscreenElement || document.webkitFullscreenElement) {
        if (document.exitFullscreen) document.exitFullscreen().catch(() => {});
        else if (document.webkitExitFullscreen) document.webkitExitFullscreen();
    }
    setTimeout(() => map.resize(), 50);
}

function toggleCurtain() {
    curtainOpen = !curtainOpen;
    const curtain = document.getElementById('fs-curtain');
    const tab = document.getElementById('fs-curtain-tab');
    curtain.classList.toggle('curtain-open', curtainOpen);
    tab.innerText = curtainOpen ? '⬆ Close' : '⬇ Layers';
}

document.addEventListener('fullscreenchange', () => { if (!document.fullscreenElement && fsActive) exitFullscreen(); });
document.addEventListener('webkitfullscreenchange', () => { if (!document.webkitFullscreenElement && fsActive) exitFullscreen(); });

const RADIUS_MIN = 1;
const RADIUS_MAX = 160;

function getRadiusValue() {
    const raw = parseFloat(document.getElementById('radius-input').value);
    if (isNaN(raw) || raw < RADIUS_MIN) return RADIUS_MIN;
    if (raw > RADIUS_MAX) return RADIUS_MAX;
    return raw;
}

function validateRadiusInput() {
    const input = document.getElementById('radius-input');
    const raw = parseFloat(input.value);
    const invalid = isNaN(raw) || raw < RADIUS_MIN || raw > RADIUS_MAX;
    input.classList.toggle('invalid', invalid);
    return !invalid;
}

// ── Measure tool state ──────────────────────────────────────────────
let measureMode = false;
let measurePoints = [];
let measureClosed = false;

function fmt(n, decimals) {
    return n.toLocaleString('en-GB', { maximumFractionDigits: decimals, minimumFractionDigits: decimals });
}

function updateMeasureDisplay() {
    const disp = document.getElementById('measure-display');
    const lineEl  = document.getElementById('m-line');
    const perimEl = document.getElementById('m-perim');
    const areaEl  = document.getElementById('m-area');
    const hint    = document.getElementById('m-hint');

    if (measurePoints.length < 2) {
        lineEl.style.display = 'none';
        perimEl.style.display = 'none';
        areaEl.style.display = 'none';
        hint.innerText = 'Click to add points · Double-click to close polygon';
        return;
    }

    // Total line length
    let totalKm = 0;
    for (let i = 1; i < measurePoints.length; i++) {
        totalKm += haversine(
            measurePoints[i-1][0], measurePoints[i-1][1],
            measurePoints[i][0],   measurePoints[i][1]
        );
    }

    if (!measureClosed) {
        lineEl.style.display = 'block';
        perimEl.style.display = 'none';
        areaEl.style.display = 'none';
        document.getElementById('m-km').innerText = fmt(totalKm, 2);
        document.getElementById('m-m').innerText  = fmt(totalKm * 1000, 0);
        document.getElementById('m-mi').innerText = fmt(totalKm * 0.621371, 2);
        hint.innerText = 'Double-click last point to close polygon';
    } else {
        // Closed polygon — add closing segment
        const closingKm = haversine(
            measurePoints[measurePoints.length-1][0], measurePoints[measurePoints.length-1][1],
            measurePoints[0][0], measurePoints[0][1]
        );
        const perimKm = totalKm + closingKm;

        // Shoelace area in km²
        let area = 0;
        const R = 6371;
        const pts = measurePoints;
        for (let i = 0; i < pts.length; i++) {
            const j = (i + 1) % pts.length;
            const xi = pts[i][0] * Math.PI / 180;
            const yi = pts[i][1] * Math.PI / 180;
            const xj = pts[j][0] * Math.PI / 180;
            const yj = pts[j][1] * Math.PI / 180;
            area += (xj - xi) * (2 + Math.sin(yi) + Math.sin(yj));
        }
        const areaKm2 = Math.abs(area) * R * R / 2;
        const areaHa  = areaKm2 * 100;
        const areaAc  = areaKm2 * 247.105;

        lineEl.style.display = 'none';
        perimEl.style.display = 'block';
        areaEl.style.display = 'block';
        document.getElementById('m-pkm').innerText = fmt(perimKm, 2);
        document.getElementById('m-pm').innerText  = fmt(perimKm * 1000, 0);
        document.getElementById('m-km2').innerText = fmt(areaKm2, 3);
        document.getElementById('m-ha').innerText  = fmt(areaHa, 1);
        document.getElementById('m-ac').innerText  = fmt(areaAc, 1);
        hint.innerText = 'Click 📏 Measure again to reset';
    }
}

function updateMeasureLayers() {
    if (!map.getSource('src-measure-line')) return;

    const lineCoords = [...measurePoints];
    if (measureClosed && measurePoints.length > 2) lineCoords.push(measurePoints[0]);

    map.getSource('src-measure-line').setData({
        type: 'FeatureCollection',
        features: lineCoords.length > 1 ? [{
            type: 'Feature',
            geometry: { type: 'LineString', coordinates: lineCoords }
        }] : []
    });

    map.getSource('src-measure-fill').setData({
        type: 'FeatureCollection',
        features: measureClosed && measurePoints.length > 2 ? [{
            type: 'Feature',
            geometry: { type: 'Polygon', coordinates: [[...measurePoints, measurePoints[0]]] }
        }] : []
    });

    map.getSource('src-measure-points').setData({
        type: 'FeatureCollection',
        features: measurePoints.map(c => ({
            type: 'Feature',
            geometry: { type: 'Point', coordinates: c }
        }))
    });
}

function clearMeasure() {
    measurePoints = [];
    measureClosed = false;
    updateMeasureLayers();
    updateMeasureDisplay();
    document.getElementById('measure-display').style.display = 'none';
}

function toggleMeasureMode() {
    measureMode = !measureMode;
    document.getElementById('btn-measure').classList.toggle('active', measureMode);
    map.getCanvas().style.cursor = measureMode ? 'crosshair' : '';
    if (!measureMode) {
        clearMeasure();
    } else {
        // Exit radius mode if active
        if (radiusMode) toggleRadiusMode();
        document.getElementById('measure-display').style.display = 'block';
        updateMeasureDisplay();
    }
}

const GRID_CONFIG = deepFreeze([
    {
        group: "Topology (GeoJSON)",
        layers: [
            { id: "400",  label: "400kV", color: "#0054ff", type: "line", width: 2.5, url: "/grid_400kv.geojson", snap: true, preload: true },
            { id: "275",  label: "275kV", color: "#ff0000", type: "line", width: 2.0, url: "/grid_275kv.geojson", snap: true, preload: true },
            { id: "220",  label: "220kV", color: "#ff9900", type: "line", width: 1.8, url: "/grid_220kv.geojson", snap: true, preload: true },
            { id: "132",  label: "132kV", color: "#00cc00", type: "line", width: 1.5, url: "/grid_132kv.geojson", snap: true, preload: true },
            { id: "66",   label: "66kV",  color: "#b200ff", type: "line", width: 1.2, url: "/grid_66kv.geojson", snap: true, preload: true },
            { id: "11kv", label: "11kV (UKPN)", color: "#ff00ff", type: "point", radius: ['interpolate', ['linear'], ['zoom'], 13.5, 4, 15, 8, 18, 18], url: "/grid_11kv_ukpn.geojson", minzoom: 13.5, preload: false },
            { id: "subs", label: "Subs",  color: "#ffffff", type: "point", radius: ['interpolate', ['linear'], ['zoom'], 5, 3, 10, 5, 14, 10, 18, 22], url: "/grid_substations.geojson", isSubs: true, preload: true }
        ]
    },
    {
        group: "Assets (GeoJSON)",
        layers: [
            { id: "nuc",  label: "Nuclear",   color: "#39ff14", type: "point", radius: 4.5, url: "/power_plants.geojson", filter: ['==', ['get', 'source'], 'nuclear'], preload: true },
            { id: "gas",  label: "Gas",       color: "#ff4500", type: "point", radius: 4.5, url: "/power_plants.geojson", filter: ['!=', ['get', 'source'], 'nuclear'], preload: true },
            { id: "ind",  label: "Industry",  color: "#ff6600", type: "point", radius: 4.5, url: "/industrial_offtakers.geojson", preload: true },
            { id: "dc",   label: "Data Ctrs", color: "#00ffff", type: "point", radius: 4.5, url: "/datacentres.geojson", preload: true },
            { id: "air",  label: "Airports",  color: "#ff00ff", type: "point", radius: 4.5, url: "/airports.geojson", preload: true },
            { id: "rail", label: "Railways",  color: "#ffd700", type: "point", radius: 4.5, url: "/railways.geojson", preload: true }
        ]
    },
    {
        group: "Supermarkets (GeoJSON)",
        layers: [
            { id: "tesco",      label: "Tesco",       color: "#ee1c2e", type: "point", radius: 4.5, url: "/supermarkets_tesco.geojson", preload: false },
            { id: "sainsburys", label: "Sainsbury's", color: "#ff8200", type: "point", radius: 4.5, url: "/supermarkets_sainsburys.geojson", preload: false },
            { id: "asda",       label: "Asda",        color: "#78be20", type: "point", radius: 4.5, url: "/supermarkets_asda.geojson", preload: false },
            { id: "morrisons",  label: "Morrisons",   color: "#ffd700", type: "point", radius: 4.5, url: "/supermarkets_morrisons.geojson", preload: false },
            { id: "aldi",       label: "Aldi",        color: "#003087", type: "point", radius: 4.5, url: "/supermarkets_aldi.geojson", preload: false },
            { id: "lidl",       label: "Lidl",        color: "#0050aa", type: "point", radius: 4.5, url: "/supermarkets_lidl.geojson", preload: false },
            { id: "waitrose",   label: "Waitrose",    color: "#7ab800", type: "point", radius: 4.5, url: "/supermarkets_waitrose.geojson", preload: false },
            { id: "ms",         label: "M&S Food",    color: "#009b77", type: "point", radius: 4.5, url: "/supermarkets_ms.geojson", preload: false },
            { id: "coop",       label: "Co-op",       color: "#00b1a9", type: "point", radius: 4.5, url: "/supermarkets_coop.geojson", preload: false },
            { id: "costco",     label: "Costco",      color: "#005daa", type: "point", radius: 4.5, url: "/supermarkets_costco.geojson", preload: false },
            { id: "booths",     label: "Booths",      color: "#6d2077", type: "point", radius: 4.5, url: "/supermarkets_booths.geojson", preload: false }
        ]
    },
    {
        group: "Transit (GeoJSON)",
        layers: [
            { id: "elizabeth", label: "Elizabeth Line", color: "#60399E", type: "point", radius: 5, url: "/elizabeth_line.geojson", preload: false },
            { id: "lu",    label: "London Underground", color: "#e32017", type: "point", radius: 5, url: "/london_underground.geojson", preload: false },
            { id: "dlr",   label: "DLR", color: "#00afad", type: "point", radius: 5, url: "/uk_metros_trams.geojson", preload: false,
              filter: ['all', ['in', 'Docklands', ['get', 'operator']], ['!', ['in', 'London Underground', ['get', 'operator']]]] },
            { id: "metro", label: "UK Metro", color: "#f3a712", type: "point", radius: 5, url: "/uk_metros_trams.geojson", preload: false,
              filter: ['any', ['in', 'Tyne', ['get', 'operator']], ['in', 'Metrolink', ['get', 'operator']], ['in', 'Supertram', ['get', 'operator']], ['in', 'Nottingham', ['get', 'operator']], ['in', 'Edinburgh', ['get', 'operator']], ['in', 'Midland Metro', ['get', 'operator']]] },
            { id: "tram",  label: "Trams & Light Rail", color: "#84329b", type: "point", radius: 5, url: "/uk_metros_trams.geojson", preload: false,
              filter: ['all', ['==', ['get', 'type'], 'Tram / Light Rail'], ['!', ['in', 'London Underground', ['get', 'operator']]]] },
            { id: "hs2",   label: "HS2", color: "#2c6fad", type: "point", radius: 4, url: "/hs2.geojson", preload: false }
        ]
    },
    {
        group: "Leisure & Sports (GeoJSON)",
        layers: [
            { id: "stadiums", label: "Major Stadiums", color: "#e5ff00", type: "point", radius: 5.5, url: "/stadiums.geojson", preload: false }
        ]
    },
    {
        group: "EV (GeoJSON)",
        layers: [
            { id: "ev", label: "EV Rapid (100kW+)", color: "#00ff88", type: "point", radius: 5, url: "/ev_chargers.geojson", preload: false }
        ]
    },
    {
        group: "REPD (GeoJSON)",
        layers: [
            { id: "solar",      label: "Solar PV",               color: "#ffff00", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'solar'],      preload: false },
            { id: "solar_roof", label: "Solar Roof",             color: "#ffcc00", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'solar_roof'], preload: false },
            { id: "wind",       label: "Wind",                   color: "#00ffff", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'wind'],       preload: false },
            { id: "bess",       label: "Battery Storage",        color: "#ffae00", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'bess'],       preload: false },
            { id: "biomass",    label: "Biomass & EfW",          color: "#39ff14", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'biomass'],    preload: false },
            { id: "tidal",      label: "Tidal & Wave",           color: "#00bfff", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'tidal'],      preload: false },
            { id: "hydrogen",   label: "Hydrogen",               color: "#ffffff", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'hydrogen'],   preload: false },
            { id: "hydro",      label: "Hydro & Pumped Storage", color: "#00aaff", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'hydro'],      preload: false },
            { id: "flywheel",   label: "Flywheel",               color: "#ff69b4", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'flywheel'],   preload: false },
            { id: "act",        label: "Advanced Conversion",    color: "#ff6600", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'act'],        preload: false },
            { id: "geothermal", label: "Geothermal",             color: "#ff3300", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'geothermal'], preload: false },
            { id: "caes",       label: "Compressed Air Storage", color: "#88aaff", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'caes'],       preload: false }
        ]
    }
]);

const REPD_IDS = ['solar','solar_roof','wind','bess','biomass','tidal','hydrogen','hydro','flywheel','act','geothermal','caes'];
const TRANSIT_IDS = ['elizabeth','lu','dlr','metro','tram','hs2'];
const TRANSIT_SOURCE_MAP = { 'elizabeth':'src-elizabeth','lu':'src-lu','dlr':'src-metros','metro':'src-metros','tram':'src-metros','hs2':'src-hs2' };
const TRANSIT_URLS = { 'src-elizabeth':'/elizabeth_line.geojson','src-lu':'/london_underground.geojson','src-metros':'/uk_metros_trams.geojson','src-hs2':'/hs2.geojson' };

const SEARCH_THRESHOLD = {
    'solar':50,'solar_roof':0.5,'wind':50,'bess':50,'biomass':50,
    'tidal':10,'hydrogen':10,'hydro':10,'flywheel':1,'act':10,'geothermal':1,'caes':1
};

const STATUS_COLOURS = {
    'operational':'#00ff88','under construction':'#ffcc00','awaiting construction':'#ffaa00',
    'consented':'#ff8800','planning permission granted':'#ff8800','planning approved':'#ff8800',
    'application submitted':'#8888ff','pre-construction':'#aaaaff'
};

let statusMode = false;
let radiusMode = false;
let radiusMarker = null;
let radiusCenter = null;

const RUNTIME_STATE = {};
GRID_CONFIG.forEach(group => {
    group.layers.forEach(layer => {
        RUNTIME_STATE[layer.id] = { status: 'WAIT', loading: false, loaded: false };
    });
});

const urlCache = {};
let globalSubsData = null;
let allREPDFeatures = [];
let searchIndex = [];

setInterval(() => {
    const now = new Date();
    const target = new Date(Date.UTC(2050, 0, 1, 0, 0, 0));
    document.getElementById('clock').innerText = now.toLocaleTimeString('en-GB');
    document.getElementById('date').innerText = now.toLocaleDateString('en-GB');
    document.getElementById('days').innerText = Math.floor((target - now) / 86400000) + ' DAYS';
}, 1000);

const map = new maplibregl.Map({
    container: 'map',
    style: 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json',
    center: [-3.5, 54.0],
    zoom: 4.2,
    attributionControl: false
});

new ResizeObserver(() => map.resize()).observe(document.getElementById('map'));

function updateUIState(id, state, stats) {
    RUNTIME_STATE[id].status = state;
    ['lbl-', 'fs-lbl-'].forEach(prefix => {
        const span = document.getElementById(`${prefix}${id}`);
        if (span) {
            const baseText = span.getAttribute('data-base-label');
            if (stats && stats.count > 0) {
                const mw = stats.mw >= 1000 ? `${(stats.mw/1000).toFixed(1)}GW` : `${Math.round(stats.mw)}MW`;
                span.innerText = `${baseText} [${stats.count} | ${mw}]`;
            } else {
                span.innerText = `${baseText} [${state}]`;
            }
            span.style.opacity = state === 'FAIL' ? '0.5' : '1';
        }
    });
}

class FetchQueue {
    constructor(concurrency) { this.concurrency = concurrency; this.active = 0; this.queue = []; }
    async add(task) {
        if (this.active >= this.concurrency) await new Promise(resolve => this.queue.push(resolve));
        this.active++;
        try { return await task(); }
        finally { this.active--; if (this.queue.length > 0) this.queue.shift()(); }
    }
}

const networkQueue = new FetchQueue(4);

async function fetchWithTimeout(url, ms = 15000) {
    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), ms);
    try {
        const response = await fetch(url, { signal: controller.signal, cache: 'no-cache' });
        clearTimeout(id);
        if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
        return response;
    } catch (err) { clearTimeout(id); throw err; }
}

async function fetchAndParseGeoJSON(url) {
    if (urlCache[url]) return await urlCache[url];
    const promise = fetchWithTimeout(url)
        .then(res => res.json())
        .then(data => {