GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / globalgrid2050 / testcode/202609060300/atlas/cartridges

Single-Line Diagram (SLD) Sandbox (part 7)

A JavaScript file in the cartridges folder of GlobalGrid2050 that maps grid substations, connection points, GB transmission network and price decade rollup, using haversine.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Grid network and substations. Section 356 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. Single-Line Diagram (SLD) Sandbox geodesy · globalgrid2050 / testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js lines 4201–4900

Single-Line Diagram (SLD) Sandbox

A JavaScript file in the cartridges folder of GlobalGrid2050 that maps grid substations, connection points, GB transmission network and price decade rollup, using haversine.

geodesyglobalgrid2050 / testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js · lines 4201–4900 of 7736 · version 2026-09-06 03:00 (continued from section 350) · Not reached from any entry point (candidate for review) · pattern widerFleetBuckets (shared by 6 files)

What it does
It maps grid substations, connection points, GB transmission network and price decade rollup. Defines 233 functions or classes, including distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg. 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 experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV.
Inputs & outputs
In: GeoJSON file grid_substations.geojson; JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; browser storage (getItem); DuckDB queries; form fields (user input). Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 110kV, 66kV.
What it achieves
It creates compute observer (`createComputeObserver`), builds stats (`buildStats`) and applies development stage defaults (`applyDevelopmentStageDefaults`). Its `distanceKm` function gives distance km from two coordinate pairs (VEDIC: measure). Its code works with 400 kV, 132 kV and 33 kV. It responds to click, keydown and touchstart events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609060300/atlas/cartridges · script
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
VEDIC
VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver, publish
Defines here
removeArrivalFallback, markArrivalIdentityState, ensureArrivalCard, injectDeclaredOnly, armCardKeeper, disarmCardKeeper, removeCardBlock, emptyCollection, ensureLayers, stopAnimation, startAnimation, step, clearLinks, drawLinks, frame, enableSubstationLayer, fromOwnUi, statusHost, showStatus, clearStatus, retryArrival, retryIdentityOwnerThenArrival, injectStatusStyle, watchForLayerControls, waitForLayerControls, enableTechnologyLayer
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js:4201-4900 · blob b9451a6d240116dae04211c0cc8216a75da78ad1 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unreached_review
     from, and if the register's own card lands later, the fallback yields
     to it rather than standing beside it. */
  let arrivalFallbackPopup = null;

  function removeArrivalFallback() {
    if (!arrivalFallbackPopup) return;
    try { arrivalFallbackPopup.remove(); } catch (_) { /* already gone */ }
    arrivalFallbackPopup = null;
  }

  function markArrivalIdentityState(status, repdRef, message = '') {
    const node = document.querySelector('.gridatlas-arrival-identity');
    if (!node) return;
    const ref = String(repdRef || '').trim();
    node.dataset.state = String(status || 'UNKNOWN');
    if (status === 'NOT_IN_ACTIVE_REGISTER') {
      node.textContent = 'REPD ' + ref + ' · not in the active-register snapshot; '
        + 'project details and point are from the arrival link.';
    } else if (status === 'FAILED') {
      node.textContent = 'REPD ' + ref + ' · active-register check failed'
        + (message ? ': ' + message : '') + '; supplied point retained.';
    } else if (status === 'RESOLVED' || status === 'VERIFIED') {
      node.textContent = 'REPD ' + ref + ' · verified in the active-register snapshot.';
    }
  }

  function ensureArrivalCard(lon, lat, name, tech, statedMw, repdRef, suppliedStatus) {
    if (document.querySelector('.maplibregl-popup-content')) return;
    const gl = window.maplibregl;
    if (!gl?.Popup || !capturedMap) return;
    try {
      const cap = Number.isFinite(statedMw) && statedMw > 0
        ? `${statedMw} MW` : '';
      const ref = String(repdRef || '').trim();
      const status = String(suppliedStatus || '').trim();
      arrivalFallbackPopup = new gl.Popup({ maxWidth: '340px', closeOnClick: false })
        .setLngLat([lon, lat])
        .setHTML('<div style="font-family:monospace;background:#000;padding:6px">'
          + `<b style="color:#00ffff;font-size:13px">${escapeHtml(name)}</b><br>`
          + `<span style="color:#888">${escapeHtml(tech)}</span>`
          + (cap ? `<br><span style="color:#ffae00">${escapeHtml(cap)}</span>` : '')
          + (ref ? `<br><span class="gridatlas-arrival-identity" data-state="PENDING" style="color:#8fb3b8;font-size:10px">REPD ${escapeHtml(ref)} · checking the active-register snapshot</span>` : '')
          + (status ? `<br><span class="gridatlas-arrival-status" style="color:#888;font-size:10px">Status supplied by arrival link: ${escapeHtml(status)}</span>` : '')
          + '<br><span style="color:#555;font-size:9px">Card and point built from the arrival link.</span></div>')
        .addTo(capturedMap);
      link.arrival_card = 'from-link-fields';
      link.arrival_card_identity = {
        repd_ref: ref || null,
        name: String(name || ''),
        technology: String(tech || ''),
        capacity_mw: Number.isFinite(statedMw) && statedMw > 0 ? statedMw : null,
        supplied_status: status || null,
        provenance: 'ARRIVAL_LINK'
      };
    } catch (error) {
      link.failures.push('arrival card: ' + String(error?.message || error));
    }
  }

  function injectDeclaredOnly() {
    const content = document.querySelector('.maplibregl-popup-content');
    if (!content || !currentDeclared) return false;
    if (content.querySelector(`.${BLOCK_CLASS}`)) return false;  // never over a measured block
    try {
      installStyles();
      resetCardGeometry(content);
      addCardBar(content);
    content.querySelector('.testcode-location-source')?.remove();
    const provenance=window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.location_provenance;
    if(provenance && content.textContent.includes(window.__GRIDATLAS_PLACE_SEARCH__.deep_link.name)){
      const note=document.createElement('p');note.className='testcode-location-source';note.style.cssText='color:#ffd18a;padding:8px;border:1px solid #97783f';note.textContent=provenance.notice+' ';
      const a=document.createElement('a');a.href=provenance.source_item;a.target='_blank';a.rel='noopener';a.textContent='Source';note.append(a);content.insertBefore(note,content.children[1]||null);
    }
      const holder = document.createElement('div');
      holder.innerHTML = `<div class="${BLOCK_CLASS}">`
        + declaredBlockHtml(true) + caveatHtml() + `</div>`;
      const block = holder.firstElementChild;
      if (!block) return false;
      content.appendChild(block);
      requestAnimationFrame(boundCardToMap);
      link.declared_shown_before_measurement = true;
      return true;
    } catch (error) {
      link.failures.push('provisional card: ' + String(error?.message || error));
      return false;
    }
  }

  let cardKeeper = null;
  let cardKeeperPayload = null;

  function armCardKeeper(links, direction, layerLoaded) {
    cardKeeperPayload = { links, direction, layerLoaded };
    if (cardKeeper || typeof MutationObserver !== 'function') return;
    try {
      cardKeeper = new MutationObserver(() => {
        const payload = cardKeeperPayload;
        if (!payload) return;
        // If the register's own card has landed beside the fallback, the
        // fallback yields: one card, and the resolved one wins.
        if (arrivalFallbackPopup
            && document.querySelectorAll('.maplibregl-popup-content').length > 1) {
          removeArrivalFallback();
        }
        const content = document.querySelector('.maplibregl-popup-content');
        if (!content || content.querySelector(`.${BLOCK_CLASS}`)) return;
        injectIntoCard(payload.links, payload.direction, payload.layerLoaded);
      });
      cardKeeper.observe(document.body, { childList: true, subtree: true });
    } catch (error) {
      link.failures.push('card keeper: ' + String(error?.message || error));
      cardKeeper = null;
    }
  }

  function disarmCardKeeper() {
    cardKeeperPayload = null;
  }

  function removeCardBlock() {
    document.querySelectorAll(`.${BLOCK_CLASS}`).forEach(node => node.remove());
  }

  /* ── the map layers ──────────────────────────────────────────────────── */

  let capturedMap = null;
  let animationHandle = null;
  let dashPhase = 0;

  function emptyCollection() {
    return { type: 'FeatureCollection', features: [] };
  }

  function ensureLayers(map) {
    if (map.getSource(SRC)) return;

    map.addSource(SRC, { type: 'geojson', data: emptyCollection() });
    map.addSource(SRC_NODES, { type: 'geojson', data: emptyCollection() });

    // Three stacked strokes make the neon: a wide soft glow, a bright core, and
    // a dashed overlay whose offset is animated so the line reads as flowing
    // towards the substation.
    map.addLayer({
      id: L_GLOW, type: 'line', source: SRC,
      layout: { 'line-cap': 'round', 'line-join': 'round' },
      paint: {
        'line-color': ['get', 'colour'],
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 5, 12, 12],
        'line-opacity': 0.10,
        'line-blur': ['interpolate', ['linear'], ['zoom'], 6, 3, 12, 8]
      }
    });
    map.addLayer({
      id: L_CORE, type: 'line', source: SRC,
      layout: { 'line-cap': 'round', 'line-join': 'round' },
      paint: {
        'line-color': ['get', 'colour'],
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 0.9, 12, 1.8],
        'line-opacity': ['get', 'strength']
      }
    });
    // Two flow layers, half a period apart, so a link reads as a stream of
    // electrons rather than one dot going round.
    map.addLayer({
      id: L_FLOW, type: 'line', source: SRC,
      layout: { 'line-cap': 'round' },
      paint: {
        'line-color': FLOW_COLOUR,
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 1.2, 12, 2.4],
        'line-opacity': 0.8,
        'line-dasharray': [0.2, 3.2]
      }
    });
    map.addLayer({
      id: L_FLOW_B, type: 'line', source: SRC,
      layout: { 'line-cap': 'round' },
      paint: {
        'line-color': FLOW_COLOUR,
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 0.9, 12, 1.8],
        'line-opacity': 0.45,
        'line-dasharray': [0.2, 3.2]
      }
    });

    map.addLayer({
      id: L_NODE_RING, type: 'circle', source: SRC_NODES,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 6, 12, 13],
        'circle-color': 'rgba(0,0,0,0)',
        'circle-stroke-color': SUBSTATION_COLOUR,
        'circle-stroke-width': 1,
        'circle-stroke-opacity': 0.4
      }
    });
    map.addLayer({
      id: L_NODE, type: 'circle', source: SRC_NODES,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 2.2, 12, 4],
        'circle-color': SUBSTATION_COLOUR,
        'circle-opacity': 0.8
      }
    });
    const neonFont = styleTextFont(map);
    if (!neonFont) {
      link.labels_drawn = false;
      link.failures.push('the basemap serves no glyphs, so link labels are omitted');
    } else {
      // Defer until a glyph range actually comes back. Nothing waits on
      // labels: the links are already drawn and the distances are on the
      // card.
      addLabelLayerWhenDrawable(map, neonFont, {
          id: L_LABEL, type: 'symbol', source: SRC_NODES,
          layout: {
            'text-field': ['get', 'label'],
            'text-size': 10,
            'text-offset': [0, -1.5],
            'text-anchor': 'bottom',
            'text-allow-overlap': false,
            'text-font': neonFont
          },
          paint: {
            'text-color': '#a9c4c9',
            'text-halo-color': '#000c10',
            'text-halo-width': 1.5,
            'text-opacity': 0.9
          }
        }, 'link');
    }
        link.installed = true;
  }

  function stopAnimation() {
    forgetDashMemo();
    if (animationHandle !== null) {
      cancelAnimationFrame(animationHandle);
      animationHandle = null;
    }
  }

  function startAnimation(map) {
    stopAnimation();
    const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true;
    link.reduced_motion = reduced;
    if (reduced) {
      // Motion is a preference, not a requirement. The lines, the nodes and
      // every number stay; only the travelling dash stops.
      try {
        map.setPaintProperty(L_FLOW, 'line-opacity', 0);
        map.setPaintProperty(L_FLOW_B, 'line-opacity', 0);
      } catch (_) { /* layer gone */ }
      return;
    }
    const step = () => {
      dashPhase = (dashPhase + FLOW_SPEED) % FLOW_PERIOD;
      const half = (dashPhase + FLOW_PERIOD / 2) % FLOW_PERIOD;
      try {
        setFlowDash(map, L_FLOW, dashPhase);
        setFlowDash(map, L_FLOW_B, half);
      } catch (_) {
        stopAnimation();
        return;
      }
      animationHandle = requestAnimationFrame(step);
    };
    animationHandle = requestAnimationFrame(step);
  }

  function clearLinks() {
    invalidatePendingArrival('clear');
    stopAnimation();
    const map = capturedMap;
    if (map && map.getSource(SRC)) {
      setSourceData(map, SRC, emptyCollection());
      setSourceData(map, SRC_NODES, emptyCollection());
    }
    disarmCardKeeper();
    removeArrivalFallback();
    removeCardBlock();
    clearPin(capturedMap);
    link.links_drawn = 0;
    link.last_selection = null;
    currentRepdRef = null;
    currentDeclared = null;
    currentNearest400 = null;
  }

  function drawLinks(map, origin, name, tech, links, direction, statedMw, layerLoaded = true) {
    ensureLayers(map);
    // A link takes the colour of the project end, whichever end was clicked.
    const colour = direction === 'from-substation'
      ? SUBSTATION_COLOUR
      : (TECH_COLOUR[tech] || SUBSTATION_COLOUR);

    const lines = links.map((l, index) => ({
      type: 'Feature',
      properties: {
        colour,
        // The nearest link burns brightest; the rest fade back in order, so
        // rank is legible without reading the numbers.
        strength: Math.max(0.20, 0.62 - index * 0.10),
        km: l.km
      },
      geometry: { type: 'LineString', coordinates: [origin, l.at] }
    }));

    const nodes = links.map(l => {
      const tail = l.kv && l.kv.length ? `${l.kv[0]} kV`
        : (l.mw != null ? `${l.mw} MW` : '');
      return {
        type: 'Feature',
        properties: {
          colour,
          label: tail ? `${l.km.toFixed(2)} km · ${tail}` : `${l.km.toFixed(2)} km`
        },
        geometry: { type: 'Point', coordinates: l.at }
      };
    });

    // Draw the measured transmission result even beyond the 40 km nearby search.
    // This is indicative straight-line screening, never an agreed connection.
    if (direction === 'to-substation' && currentNearest400?.at &&
        !links.some(l => l.at[0] === currentNearest400.at[0] && l.at[1] === currentNearest400.at[1])) {
      const t = currentNearest400;
      lines.push({type:'Feature',properties:{colour:'#ffd166',strength:0.75,km:t.km,role:'indicative-nearest-transmission'},geometry:{type:'LineString',coordinates:[origin,t.at]}});
      nodes.push({type:'Feature',properties:{colour:'#ffd166',label:`Indicative 400 kV · ${t.km.toFixed(2)} km`},geometry:{type:'Point',coordinates:t.at}});
    }
    if (direction === 'to-substation' && currentDeclared?.at) {
      // The declared link is public record, drawn in its own colour so it
      // never reads as one more nearest-neighbour measurement.
      const unbuilt = currentDeclared.poc_status === 'not_built'
        || currentDeclared.poc_status === 'under_construction';
      const declaredColour = unbuilt ? DECLARED_UNBUILT_COLOUR : DECLARED_COLOUR;
      lines.push({ type: 'Feature',
        properties: { colour: declaredColour, strength: 0.85, km: currentDeclared.km },
        geometry: { type: 'LineString', coordinates: [origin, currentDeclared.at] } });
      nodes.push({ type: 'Feature',
        properties: { colour: declaredColour,
          label: `PoC \u00b7 ${currentDeclared.km.toFixed(2)} km \u00b7 ${currentDeclared.kv} kV` },
        geometry: { type: 'Point', coordinates: currentDeclared.at } });
    }
    setSourceData(map, SRC, { type: 'FeatureCollection', features: lines });
    setSourceData(map, SRC_NODES, { type: 'FeatureCollection', features: nodes });

    // The popup is built by the engine and rendered synchronously in its own
    // click handler, but MapLibre attaches it on the next frame in some paths.
    // One retry covers that without polling forever.
    armCardKeeper(links, direction, layerLoaded);
    if (!injectIntoCard(links, direction, layerLoaded)) {
      requestAnimationFrame(() => injectIntoCard(links, direction, layerLoaded));
    }
    startAnimation(map);

    link.links_drawn = links.length;
    link.last_selection = { name, tech, direction, count: links.length,
      nearest_km: links.length ? Number(links[0].km.toFixed(3)) : null };
    lastSelection = { origin, name, tech, direction, links, statedMw: statedMw || null };
    if (new URLSearchParams(location.search).has('repd_ref')) {
      if (!map.__testcodeUserMovementBound) {
        map.__testcodeUserMovementBound=true;
        for (const event of ['dragstart','zoomstart','rotatestart']) map.on(event,e=>{if(e.originalEvent)map.__testcodeUserMoved=true;});
      }
      const frame = (force=false) => {
        if (!lastSelection || (!force && map.__testcodeUserMoved)) return;
        const points=[lastSelection.origin,...lastSelection.links.map(l=>l.at),currentNearest400?.at,currentDeclared?.at].filter(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite));
        if (!points.length) return;
        map.resize();
        const narrow=innerWidth<=700, h=map.getContainer().clientHeight;
        const padding=narrow?{left:28,right:28,top:125,bottom:Math.min(h*.5,innerHeight*.4+90)}:{left:380,right:70,top:85,bottom:70};
        map.fitBounds([[Math.min(...points.map(p=>p[0])),Math.min(...points.map(p=>p[1]))],[Math.max(...points.map(p=>p[0])),Math.max(...points.map(p=>p[1]))]],{padding,maxZoom:lastSelection.tech==='wind_offshore'?8.5:13,duration:700});
        link.context_frame={points:points.length,coordinates:points.map(p=>p.slice()),padding,project:lastSelection.name};
      };
      requestAnimationFrame(()=>frame());
      let button=document.getElementById('testcode-fit');
      if(!button){button=document.createElement('button');button.id='testcode-fit';button.type='button';button.textContent='Fit connections';map.getContainer().parentElement.append(button);}
      button.onclick=()=>frame(true);
    }
    if (direction !== 'from-substation') setPin(map, origin, name, tech);
  }

  /* ── selection ───────────────────────────────────────────────────────── */

  // Tick the engine's own Subs control. Going through the checkbox means the
  // engine hydrates the layer, updates its UI state and stays the owner of it;
  // adding the source here instead would leave its panel lying about what is on.
  function enableSubstationLayer() {
    try {
      /* The engine tags its own controls with data-layer-id, and that is
         what enableTechnologyLayer and the mobile tray have both used for
         generations. This searched LABEL TEXT for "subs " instead, which
         is the one part of a control guaranteed to change: the labels
         carry live counts and a [WAIT]/[OK]/[LOAD] state. Attribute
         first; the label stays only as a fallback for a control that
         somehow lacks it. Codex, 202609011823. */
      const box = document.querySelector('input[type=checkbox][data-layer-id="subs"]')
        || [...document.querySelectorAll('input[type=checkbox]')].find((input) => {
          const label = (input.closest('label') || input.parentElement)?.textContent || '';
          return label.replace(/\s+/g, ' ').trim().toLowerCase().startsWith('subs ');
        });
      if (!box) { noteFailure('subs: control not found'); return false; }
      if (!box.checked) box.click();
      link.substation_layer_enabled = true;
      recoverFailures(/^subs: control not found$/);
      return true;
    } catch (error) {
      link.failures.push('subs: ' + String(error?.message || error));
      return false;
    }
  }

  // True when a click came from one of our own surfaces -- the card block or
  // the layout panel -- rather than from the map itself. MapLibre delivers
  // container clicks as map clicks, so without this every button we add fires
  // whatever is under it.
  function fromOwnUi(event) {
    const target = event?.originalEvent?.target;
    if (!target || typeof target.closest !== 'function') return false;
    return Boolean(target.closest('.maplibregl-popup')
      || target.closest('#gridatlas-sld-panel'));
  }

  // The engine's own layer control for a technology. Arriving from Pipeline
  // News the project itself was invisible: the deep link switched the
  // substations on and left the project's layer off, so the card described a
  // scheme with no pixel under it and the links appeared to start from nowhere.
  // The engine tags each layer control with the layer it drives:
  //   <input type=checkbox data-layer-id="solar">
  // so the technology IS the hook, and no mapping table is needed. Matching on
  // the label text worked, but the labels carry live counts -- "Solar PV [2819
  // | 52.3GW]" -- so it was matching prose that changes with the data. The
  // label match stays as a fallback for a control the engine has not tagged.
  const TECH_LABEL_FALLBACK = {
    solar: "Solar PV [", solar_operational: "Solar PV (Operational",
    solar_roof: "Solar Roof [",
    bess: "Battery Storage [", bess_operational: "Battery Storage (Operational",
    wind: "Wind [", wind_onshore_operational: "Onshore Wind (Operational",
  };

  /* ── say what is happening ────────────────────────────────────────────
     Vikram, tonight: "the map feature from pipelinenews doesnt load on
     iphone". Reproduced in kind on the desktop: a black rectangle, no
     controls, and a deep link waiting for substations that could not arrive.
     Nothing on screen said so. A black map is indistinguishable from a broken
     one, and the reader is left to guess which they have.

     The Atlas boots a 35.7 MB query engine before it can answer anything. On
     a phone over cellular that is a long wait and sometimes not a wait at all,
     and the honest thing is to say which. This chip says what is being waited
     for, and when the wait has failed it says that too, with a way to try
     again -- because a retry after the network recovers is usually all it
     needs, and a reload throws away the deep link.

     It removes itself the moment the controls arrive, so a working Atlas is
     never decorated with news about itself. */

  const STATUS_ID = 'gridatlas-boot-status';

  function statusHost() {
    return document.querySelector('.maplibregl-map') || document.body;
  }

  function showStatus(message, kind) {
    try {
      let el = document.getElementById(STATUS_ID);
      if (!el) {
        el = document.createElement('div');
        el.id = STATUS_ID;
        el.setAttribute('role', 'status');
        el.setAttribute('aria-live', 'polite');
        statusHost().appendChild(el);
      }
      el.dataset.kind = kind || 'waiting';
      el.textContent = message;
      if (kind === 'failed') {
        const again = document.createElement('button');
        again.type = 'button';
        again.textContent = 'Try again';
        again.addEventListener('click', (event) => {
          event.stopPropagation();
          event.preventDefault();
          retryArrival();
        });
        el.appendChild(again);
      }
      link.status_message = message;
    } catch (error) {
      link.failures.push('status: ' + String(error?.message || error));
    }
  }

  function clearStatus() {
    document.getElementById(STATUS_ID)?.remove();
    link.status_message = null;
  }

  // Re-run the arrival rather than reloading: a reload on a phone repeats the
  // whole 35.7 MB boot, and the deep link is in the URL either way.
  let retryArrival = () => {};
  let rerunDeepLink = null;

  async function retryIdentityOwnerThenArrival() {
    clearStatus();
    const owner = window.__GRIDATLAS_PLACE_SEARCH__;
    if (typeof owner?.retry_exact_deep_link !== 'function') {
      showStatus('The active-register identity owner cannot retry in this composition.',
        'failed');
      return false;
    }
    const invalidatedEpoch = invalidatePendingArrival('identity-retry');
    const retryEpoch = claimPendingArrival(window.location.search);
    link.arrival_retry = {
      status: 'OWNER_PENDING', invalidated_epoch: invalidatedEpoch,
      owner_epoch: retryEpoch, measurement_epoch: retryEpoch
    };
    try {
      await owner.retry_exact_deep_link(retryEpoch);
    } catch (error) {
      link.arrival_retry.status = 'FAILED';
      showStatus('The active-register identity retry failed: '
        + String(error?.message || error), 'failed');
      return false;
    }
    const terminal = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link;
    if (!arrivalGate.isCurrent(retryEpoch)
        || terminal?.owner_epoch !== retryEpoch
        || terminal?.status === 'CANCELLED') {
      link.arrival_retry.status = 'CANCELLED';
      return false;
    }
    if (terminal?.status === 'FAILED') {
      link.arrival_retry.status = 'FAILED';
      showStatus('The active-register identity check failed: '
        + String(terminal.message || 'identity loader unavailable'), 'failed');
      return false;
    }
    if (typeof rerunDeepLink !== 'function') {
      link.arrival_retry.status = 'FAILED';
      showStatus('The grid measurement owner cannot retry in this composition.',
        'failed');
      return false;
    }
    link.arrival_retry.status = 'MEASUREMENT_PENDING';
    const completed = await rerunDeepLink(retryEpoch);
    if (!arrivalGate.isCurrent(retryEpoch)) {
      link.arrival_retry.status = 'CANCELLED';
      return false;
    }
    link.arrival_retry.status = terminal.status === 'NOT_IN_ACTIVE_REGISTER'
      ? 'NOT_IN_ACTIVE_REGISTER' : (completed === false ? 'FAILED' : 'RESOLVED');
    return completed !== false;
  }

  function injectStatusStyle() {
    if (document.getElementById(STATUS_ID + '-style')) return;
    const style = document.createElement('style');
    style.id = STATUS_ID + '-style';
    style.textContent = SLD_STYLES.bootStatus(STATUS_ID);
    document.head.appendChild(style);
  }

  // Resolve when the engine has rendered its layer dashboard, or when the
  // wait is up. Returning false is a fact worth having, not an error: it says
  // the engine had not finished, which is a different problem from the layer
  // being missing.
  /* Watch for the controls; do not guess how long they will take.
     ----------------------------------------------------------------------
     A fixed budget is always the wrong number. Twelve seconds was generous on
     one load and hopeless on the next: the engine builds its layer dashboard
     from its own data, and that has been measured arriving in two seconds and
     not arriving at all in eighty-six.

     Giving up after a budget also gave up permanently. If the dashboard
     appeared at thirteen seconds -- which it often does -- the layers the
     arrival depends on stayed off for the rest of the session, with a card on
     screen saying the grid data had not loaded while the controls sat there.

     So: the wait still bounds how long the user is asked to look at a spinner,
     because that is a promise about the interface. But an observer keeps
     watching afterwards, and switches the layers on whenever they arrive,
     however late. The status line is cleared at the same moment, because a
     failure notice that outlives the failure is its own bug.

     The observer disconnects the first time it fires. It is not a subscription
     to the page; it is one deferred question. */

  const LAYER_CONTROL = 'input[type=checkbox][data-layer-id]';
  let layerWatcher = null;

  function watchForLayerControls(onReady) {
    if (layerWatcher || typeof MutationObserver !== 'function') return;
    try {
      layerWatcher = new MutationObserver(() => {
        if (!document.querySelector(LAYER_CONTROL)) return;
        layerWatcher.disconnect();
        layerWatcher = null;
        link.layer_controls_arrived_late = true;
        recoverFailures(/^the engine had not rendered its layer controls within/);
        clearStatus();
        try { onReady(); } catch (error) {
          link.failures.push('late layers: ' + String(error?.message || error));
        }
      });
      layerWatcher.observe(document.body, { childList: true, subtree: true });
    } catch (error) {
      link.failures.push('layer watcher: ' + String(error?.message || error));
      layerWatcher = null;
    }
  }

  /* iOS Safari, reported live by the architect and reproduced independently
     against a page opened hidden: this budget used to be charged in WALL
     CLOCK time regardless of whether anyone could see the result of
     spending it. Pipeline News' MAP control opens on touch devices with
     target="_blank", and on iOS Safari a background tab is not guaranteed
     to be composited while the reader is still looking at the page they
     tapped from -- requestAnimationFrame does not tick there, so the
     engine's own dashboard build (which the boot trigger gates behind
     style.load/load, both paint-driven) can stall for the WHOLE budget
     without ever having had a real chance. Elapsed time while hidden buys
     nothing observable and is not charged against the budget; only time
     the tab was actually visible counts down. */
  async function waitForLayerControls(budgetMs) {
    let elapsed = 0;
    const started = Date.now();
    /* Visible time governs the BUDGET; wall clock still bounds the WAIT.
       ----------------------------------------------------------------------
       Charging the budget in visible time is what stops a background tab
       spending it before anyone can see the result. But a tab that is never
       made visible would then poll every 200ms forever, which is a hang by any
       honest definition and costs battery on the device least able to afford
       it. So an absolute ceiling backstops the visible-time budget: whichever
       runs out first ends the wait. Ten minutes matches the last-resort stop
       the arrival lane already uses for a lane that died silently. */
    const HARD_CEILING_MS = 600000;
    if (!document.querySelector(LAYER_CONTROL)) {
      injectStatusStyle();
      showStatus('Switching the grid layers on as soon as the map\u2019s own '
        + 'controls appear. The distances do not wait for them.', 'waiting');
    }
    while (elapsed < budgetMs && Date.now() - started < HARD_CEILING_MS) {
      if (document.querySelector(LAYER_CONTROL)) {
        /* Both clocks are published, because they answer different questions:
           visible time is what the budget was actually spent from, wall time
           is what the reader sat through. Reporting only one of them makes a
           background arrival look instant or a foreground one look slow. */
        link.layer_controls_ready_ms = Date.now() - started;
        link.layer_controls_ready_visible_ms = elapsed;
        clearStatus();
        return true;
      }
      await new Promise(resolve => setTimeout(resolve, 200));
      if (document.visibilityState === 'visible') elapsed += 200;
    }
    link.layer_controls_ready_ms = null;
    link.failures.push(
      'the engine had not rendered its layer controls within '
      + Math.round(budgetMs / 1000) + 's; still watching, and the layers will '
      + 'be switched on if they arrive');
    if (link.links_drawn > 0) {
      // The answer is already on the map. Late layers are not a failure the
      // reader has to act on, and a red notice over a working map is noise.
      clearStatus();
    } else {
      injectStatusStyle();
      showStatus('The grid data has not finished loading yet. The distances '
        + 'below are already measured; the layers will switch on by themselves '
        + 'if it arrives.', 'failed');
    }
    return false;
  }

  function enableTechnologyLayer(tech) {
    if (!tech) return false;
    // Resolved through the ONE table above. 'wind_onshore' and
    // 'wind_offshore' are Pipeline buckets, not layer ids -- searching the
    // DOM for a control literally named that always failed. 'other' has no
    // layer at all, and is said plainly rather than searched for.
    const layerId = layerIdForBucket(tech);
    if (layerId === null) {
      link.technology_layer = Object.assign({}, link.technology_layer, {
        requested: tech, layer_id: null, enabled: false,
        reason: 'GridAtlas has no map layer for the "' + tech + '" technology; '
          + 'nothing to switch on. The card and the distances above it are '
          + 'unaffected.'
      });
      return false;
    }
    try {
      const boxes = [...document.querySelectorAll('input[type=checkbox]')];
      let box = boxes.find((input) => input.dataset?.layerId === layerId);
      if (!box) {
        const label = TECH_LABEL_FALLBACK[layerId];
        if (label) {
          box = boxes.find((input) => {
            const text = (input.closest('label') || input.parentElement)?.textContent || "";
            return text.replace(/\s+/g, " ").trim().toLowerCase()
              .startsWith(label.toLowerCase());
          });
        }
      }
      if (!box) { noteFailure('layer control not found: ' + layerId); return false; }