GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/theme

Pilot Modes and 3 more files

A JavaScript file in the theme folder of Cosmic that maps modes fade and uses data from OpenStreetMap tiles. It gets tile (`getTile`), draws tile (`drawTile`) and draws grid (`drawGrid`).

593 lines of JavaScript and CSS from cosmic, in 4 files. Topic: Kuiper, cosmos and drawing engines. Section 1150 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. Pilot Lightning geodesy · cosmic / tools/explore/theme/pilot-lightning.js lines 701–880
  2. Pilot Modes render · cosmic / tools/explore/theme/pilot-modes.css lines 1–15
  3. Pilot Modes render · cosmic / tools/explore/theme/pilot-modes.js lines 1–374
  4. Pilot Nav render · cosmic / tools/explore/theme/pilot-nav.css lines 1–24

Pilot Lightning

A JavaScript file in the theme folder of Cosmic that maps UK lightning and grid substations, using SHA-256 and haversine, and uses data from the GridAtlas, lightning and PipelineNews repositories.

geodesycosmic / tools/explore/theme/pilot-lightning.js · lines 701–880 of 880 (continued from section 1149) · Entry point · pattern describeOpticalFeedEvidence (shared by 2 files)

What it does
It maps UK lightning, grid substations, solar and the REPD register. Defines 86 functions or classes, including mm, finite, validPoint, rowLocation, positive. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (voltage levels 275kV (all 132kV or above)): 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: solar, the REPD register, 275kV.
Inputs & outputs
In: data source: gridatlas data; data source: lightning data; data source: pipelinenews data; GeoJSON file uk_lightning.geojson; JSON file index.json; GeoJSON file grid_substations.geojson; GeoJSON file kv.geojson; form fields (user input). Voltage levels named: 275kV.
Downstream impact
Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
It builds atlas v9 deep link (`buildAtlasV9DeepLink`), parses optical feed (`parseOpticalFeed`) and describes optical feed evidence (`describeOpticalFeedEvidence`). W08 (FLASHOVER-31); integrated and maintained by W10 (CAPSTAN-41). Its code works with 275 kV. It responds to click and submit events.
Why it matters
Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
Application
cosmic · tools/explore/theme · script
Uses
GridAtlas — Atlas Page (estate URL), GridAtlas — Index Page (estate URL)
Used by
loaded by Pilot (script src), mentioned in Standalone (comment link)
Produces
mm, finite, validPoint, rowLocation, positive, capacityOf, solarProject, numberInRange, projectFields, buildAtlasV9DeepLink, FEED_CONTRACT, utc
Defines here
loadIndex, loadPeriod, step, loadFeed, loadLines, loadSolar, refreshCard, setOn, setPeriod, nav, fly, measureAt, draw, hud, onClick, onSubmit, start
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-lightning.js:701-880 · blob 08456acac8c54365d0461b8f58ef5a5f222ec9d7 · 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: unknown
  /* ---------- loading: index, then months progressively ---------- */
  function loadIndex() {
    if (S.index) return Promise.resolve(S.index);
    return track(src.index()).then(function (ix) {
      if (!ix || ix.schema !== 'uk-lightning-history-index.v2' || !Array.isArray(ix.days)) throw new Error('index schema');
      S.index = ix; return ix;
    });
  }
  function loadPeriod() {
    if (!guard()) return Promise.resolve();
    var sn = ++S.serial;
    S.busy = true; S.err = null; S.G = null; S.progress = 'Loading archive index…'; render();
    return loadIndex().then(function (ix) {
      if (sn !== S.serial) return;
      var w = windowFor(S.period, S.end == null ? Date.now() : S.end), rows = windowRows(ix, w), months = monthsNeeded(rows), done = 0, failed = 0;
      S.w = w; S.rows = rows;
      var step = function () {
        if (sn !== S.serial) return Promise.resolve();
        S.G = cellsFrom(rows, S.gs); S.G.months = months.length; S.G.loaded = done; S.G.failed = failed;
        S.progress = done < months.length ? 'Loading month ' + (done + 1) + ' of ' + months.length + ' (' + fmt(S.G.n) + ' flashes so far)…' : null;
        setVis(); render();
        if (done >= months.length) return Promise.resolve();
        var m = months[done];
        var p = S.gs.has(m) ? Promise.resolve() : track(src.grid(m)).then(function (g) {
          if (!g || g.schema !== 'uk-lightning-history-grid.v1') throw new Error('grid schema');
          S.gs.set(m, g);
        }).catch(function () { failed++; S.gs.set(m, { days: [], cells: [] }); });
        return p.then(function () { done++; return new Promise(function (r) { setTimeout(r, 0); }); }).then(step);
      };
      return step();
    }).catch(function () { S.err = 'Lightning archive not loaded (offline?).'; })
      .then(function () { if (sn === S.serial) { S.busy = false; if (q('lgtest') && S.G) console.log('[lightning]', S.period, S.G.n, 'flashes,', S.G.k, 'drawn in', S.G.cells.length, 'cells, T', S.G.T); render(); } });
  }
  function loadFeed() {
    if (!guard()) return Promise.resolve();
    return track(src.feed()).then(function (fc) {
      // GridAtlas lab feed contract: dedupe, reject ambiguous, STALE_QUERY after 6 h
      var r = FEED_CONTRACT.parseOpticalFeed(fc, { staleAfterHours: 6 });
      S.F = packFlashes({ type: 'FeatureCollection', metadata: fc.metadata, features: r.observations }); S.Fsrc = 'feed';
      S.fresh = freshness(S.F.meta, S.F.n); S.fresh.stale = r.evidence.query_freshness !== 'RECENT_QUERY';
      S.fresh.text = S.fresh.text + ' · ' + FEED_CONTRACT.describeOpticalFeedEvidence(r.evidence);
    }).catch(function () { S.err = 'Live lightning feed not loaded (offline?).'; }).then(render);
  }
  function loadLines() {
    if (S.lines || !guard()) return Promise.resolve();
    var L = null;
    return Promise.all(['400', '275'].map(function (kv) { return track(src.line(kv)).then(function (fc) { return [fc, kv]; }); }))
      .then(function (a) { a.forEach(function (x) { L = indexLines(x[0], x[1], L); }); S.lines = L; })
      .catch(function () { S.err = 'Mapped lines not loaded (offline?).'; }).then(refreshCard);
  }
  function loadSolar() {
    if (S.solar || !guard()) return Promise.resolve();
    var parts = []; for (var i = 1; i <= 8; i++) parts.push(src.solar(i));
    return Promise.all(parts.map(track)).then(function (fcs) {
      S.solar = [].concat.apply([], fcs.map(function (fc) { return fc.features || []; })).map(solarProject).filter(Boolean);
    }).catch(function () { S.err = 'REPD solar partitions not loaded (offline?).'; }).then(refreshCard);
  }
  function refreshCard() {
    render();
    var el = document.querySelector('.p-lightning-ro');
    if (el && S.sel) el.innerHTML = readoutHtml(S.sel);
  }

  /* ---------- actions ---------- */
  function setOn(on) {
    S.on = on; setVis();
    if (on && !S.G && !S.busy) loadPeriod();
    if (P.hash) P.hash('lg', on ? S.period : null);
    if (!on) { S.sel = null; if (P.hash) P.hash('lgp', null); setVis(); }
    render();
  }
  function setPeriod(p) { S.period = p; S.end = null; S.on = true; if (P.hash) P.hash('lg', p); loadPeriod(); }
  function nav(dir) {
    if (!S.w) return;
    var now = Date.now();
    if (dir === 'latest') S.end = null;
    else if (dir === 'prev') S.end = S.w.s;
    else { var e = (S.end == null ? now : S.end) + S.w.span; S.end = e >= now ? null : e; }
    loadPeriod();
  }
  function fly(lat, lon, opts) { if (!P.flyTo) return; var p = P.flyTo(lat, lon, opts); if (p && p.catch) p.catch(function () {}); }
  function measureAt(lat, lon, from) {
    S.on = true; setVis();
    if (!S.G && !S.busy) loadPeriod();
    var c = choose(lon, lat, 'point', { from: from });
    if (P.card) P.card(c);
    fly(lat, lon, { alt: 1500, dist: 0, pitch: -1.3, label: 'Chosen point', source: 'lightning' });
    return c;
  }

  /* ---------- panel ---------- */
  var body = null;
  function draw() {
    var h = '<h3 class="p-lightning-title">' + esc(TITLE) + '</h3>';
    h += '<button type="button" class="p-lightning-toggle" data-p-lightning="toggle" aria-pressed="' + S.on + '">' + (S.on ? 'Lightning ON' : 'Lightning OFF') + '</button>';
    h += '<p class="p-lightning-nofault">' + esc(SCOPE) + '</p>';
    if (S.err) h += '<p class="p-lightning-err" role="status">' + esc(S.err) + ' <button type="button" class="p-lightning-btn" data-p-lightning="retry">Retry</button></p>';
    h += '<div class="p-lightning-chips" role="group" aria-label="Period (GridAtlas long periods)">' + PERIODS.map(function (p) {
      return '<button type="button" class="p-lightning-chip" data-p-lightning-period="' + p[0] + '" aria-pressed="' + (S.period === p[0]) + '">' + p[0].toUpperCase() + '</button>';
    }).join('') + '</div>';
    h += '<div class="p-lightning-chips"><button type="button" class="p-lightning-chip" data-p-lightning="prev">◀ PREV</button><button type="button" class="p-lightning-chip" data-p-lightning="latest"' + (S.end == null ? ' disabled' : '') + '>LATEST</button><button type="button" class="p-lightning-chip" data-p-lightning="next"' + (S.end == null ? ' disabled' : '') + '>NEXT ▶</button></div>';
    if (S.progress) h += '<p class="p-lightning-progress" role="status">' + esc(S.progress) + '</p>';
    if (S.index) {
      var gen = Date.parse(S.index.generated_utc), ageD = Math.floor((Date.now() - gen) / DAY);
      // Owner decision 2026-12-06 01:34: lightning is released as an ARCHIVE, not live; age is a label, not an error.
      h += '<p class="p-lightning-fresh p-lightning-archive">' + (ageD >= 1 ? 'Archive data — last collector run ' + esc(ymd(gen)) + '; not live.' : 'Archive generated ' + esc(T(gen)) + '.') + ' Later days are not searched (unknown, not zero).</p>';
    }
    if (S.G && S.w) {
      h += '<p class="p-lightning-dim">Window ' + ymd(S.w.s) + ' to ' + ymd(Math.max(S.w.s, S.w.e - 1)) + ' UTC · ' + fmt(S.G.n) + ' optical flashes on checked days; map limited to ≤30 km of REPD sites, not a national density map: ' +
        fmt(S.G.k) + ' in ' + fmt(S.G.cells.length) + ' 0.1° cells' + (S.G.st ? ' · ' + S.G.st + ' day(s) not yet mapped (unknown)' : '') + ' · tap a cell for nearest substations</p>' +
        '<div class="p-lightning-legend" aria-hidden="true"></div>';
    }
    h += '<div class="p-lightning-chips"><button type="button" class="p-lightning-chip" data-p-lightning="feed" aria-pressed="' + (S.ctx === 'feed') + '">7-day live feed (context)</button>' +
      '<button type="button" class="p-lightning-chip" data-p-lightning="here">Measure at view centre</button></div>';
    if (S.ctx === 'feed' && S.fresh) h += '<p class="p-lightning-fresh p-lightning-archive">' + esc(S.fresh.text) + '</p>';
    h += '<form class="p-lightning-form" data-p-lightning-form><label for="p-lightning-link">GridAtlas link or lat,lon</label><input id="p-lightning-link" class="p-lightning-input" placeholder="51.35, 0.95 or a GridAtlas project link" autocomplete="off"><button type="submit" class="p-lightning-btn">Measure</button></form>';
    if (S.sel) h += '<h4 class="p-lightning-h">Last readout (' + S.sel.lat.toFixed(4) + ', ' + S.sel.lon.toFixed(4) + ')</h4><ol class="p-lightning-subs">' +
      S.sel.rows.map(function (a) { return '<li>' + esc(gaLine(a)) + ' · ' + esc(bearingText(a.bearing)) + '</li>'; }).join('') + '</ol>';
    h += '<p class="p-lightning-src">' + esc(CREDIT) + '. ' + esc(SUB_CREDIT) + '.</p>' + provHtml();
    body.innerHTML = h;
    hud();
  }
  function hud() {
    if (!P.hud) return;
    if (!S.on) { P.hud('status:lightning', null); return; }
    var t = 'Lightning ' + S.period.toUpperCase() + ': ' + (S.progress ? S.progress : S.G ? fmt(S.G.n) + ' optical flashes' : 'loading');
    if (S.sel && S.sel.rows.length) t += ' · nearest ' + (S.sel.rows[0].name || 'substation') + ' ' + (+S.sel.rows[0].km).toFixed(2) + ' km ' + S.sel.rows[0].compass;
    P.hud('status:lightning', esc(t));
  }
  function onClick(e) {
    var t = e.target && e.target.closest ? e.target.closest('[data-p-lightning],[data-p-lightning-period],[data-p-lightning-fly],[data-p-lightning-kv]') : null;
    if (!t) return;
    if (t.hasAttribute('data-p-lightning-kv')) {   // re-run the readout at another minimum voltage
      S.minKv = +t.getAttribute('data-p-lightning-kv') || 0;
      if (S.sel) { var c = choose(S.sel.lon, S.sel.lat, S.sel.kind, S.sel.info); if (P.card) P.card(c); }
      return;
    }
    var a = t.getAttribute('data-p-lightning');
    if (a === 'toggle') setOn(!S.on);
    else if (a === 'retry') { S.err = null; loadPeriod(); }
    else if (a === 'prev' || a === 'next' || a === 'latest') nav(a);
    else if (a === 'feed') { S.ctx = S.ctx === 'feed' ? 'none' : 'feed'; if (S.ctx === 'feed' && !S.F) loadFeed(); render(); }
    else if (a === 'here') { var c = P.camLL ? P.camLL() : null; if (c) measureAt(c.lat, c.lon, 'view centre'); }
    else if (a === 'lines') loadLines();
    else if (a === 'solar') loadSolar();
    else if (t.hasAttribute('data-p-lightning-period')) setPeriod(t.getAttribute('data-p-lightning-period'));
    else if (t.hasAttribute('data-p-lightning-fly')) {
      var ll = t.getAttribute('data-p-lightning-fly').split(',');
      fly(+ll[0], +ll[1], { alt: 400, dist: 300, label: t.getAttribute('data-p-lightning-label') || '', source: 'lightning' });
    }
  }
  function onSubmit(e) {
    var f = e.target && e.target.closest ? e.target.closest('[data-p-lightning-form]') : null;
    if (!f) return;
    e.preventDefault();
    var v = (f.querySelector('input') || {}).value || '', m = /^\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*$/.exec(v), pt = m ? { lat: +m[1], lon: +m[2] } : pointFromLink(v.trim());
    if (!pt || !isFinite(pt.lat) || !isFinite(pt.lon)) { if (P.note) P.note('Give lat,lon or a GridAtlas link with latitude and longitude (Pipeline News links carry no coordinates).', 5000); return; }
    measureAt(pt.lat, pt.lon, pt.name ? 'GridAtlas link: ' + pt.name : 'entered point');
  }
  document.addEventListener('click', onClick);
  document.addEventListener('submit', onSubmit);

  function start() {
    if (P.panel) body = P.panel('lightning', '', { title: 'Lightning', icon: 'LI', open: false });
    var lg = P.hash ? P.hash('lg') : null, lgp = P.hash ? P.hash('lgp') : null;
    if (lg && /^(30d|3m|6m|12m)$/.test(lg)) { S.period = lg; setOn(true); }
    if (lgp && /^-?\d+(\.\d+)?,-?\d+(\.\d+)?$/.test(lgp)) { var a = lgp.split(','); S.on = true; setVis(); if (!S.G && !S.busy) loadPeriod(); var c = choose(+a[1], +a[0], 'point', { from: 'link' }); if (P.card) P.card(c); }
    render();
  }
  if (P.ready) P.ready(start); else start();

  layer._api = {
    S: S, src: src, stats: stats, PROV: PROV, windowFor: windowFor, windowRows: windowRows, monthsNeeded: monthsNeeded, cellsFrom: cellsFrom,
    readout: readout, cellOf: cellOf, gaLine: gaLine, bearingText: bearingText, compass: compass, words: words, nearbySolar: nearbySolar, pointFromLink: pointFromLink,
    packFlashes: packFlashes, FEED_CONTRACT: FEED_CONTRACT, loadFeed: loadFeed, freshness: freshness, indexLines: indexLines, nearestLine: nearestLine, rampRGB: rampRGB, coreRadius: coreRadius, glowRadius: glowRadius,
    setOn: setOn, setPeriod: setPeriod, loadPeriod: loadPeriod, loadSubs: loadSubs, loadSolar: loadSolar, loadLines: loadLines, measureAt: measureAt, choose: choose, safeBase: safeBase,
    engine: { distanceKm: distanceKm, initialBearingDeg: initialBearingDeg, representativePoint: representativePoint, voltagesKv: voltagesKv, buildDeepLink: buildDeepLink, buildAtlasV9DeepLink: buildAtlasV9DeepLink, STRAIGHT_LINE_CAVEAT: STRAIGHT_LINE_CAVEAT, solarProject: solarProject, mm: mm, LM: LM },
    TEXT: { TITLE: TITLE, SCOPE: SCOPE, OBS: OBS, CREDIT: CREDIT }
  };
})();

Pilot Modes

A style sheet in the theme folder of Cosmic.

rendercosmic / tools/explore/theme/pilot-modes.css · lines 1–15 of 15 · Entry point

What it does
Side effects: changes the web page (DOM).
Downstream impact
Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
Pilot MAP / SAT / STREET switch (Pilot-200 W03, BASEMAP-46).
Why it matters
Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
Application
cosmic · tools/explore/theme · style sheet
Uses
none found
Used by
loaded by Pilot (stylesheet)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-modes.css:1-15 · blob b68bd8534a2aa4240ea8c0d98ef3903a2749129c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* Pilot MAP / SAT / STREET switch (Pilot-200 W03, BASEMAP-46). Every class prefixed p-modes-. */
.p-modes-bar{display:flex;flex-wrap:wrap;gap:4px;max-width:100%;pointer-events:auto}
.p-modes-btn{min-width:44px;min-height:44px;padding:0 10px;border:1px solid rgba(0,255,255,.35);border-radius:8px;
  background:rgba(2,8,12,.78);color:#bfefff;font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.06em;cursor:pointer}
.p-modes-btn[aria-pressed="true"]{background:rgba(0,255,255,.2);border-color:#00ffff;color:#fff}
.p-modes-btn:focus-visible{outline:2px solid #ffae00;outline-offset:2px}
.p-modes-relief[aria-pressed="false"]{opacity:.65}
.p-modes-btn[hidden]{display:none}
.p-modes-credits h3{margin:.6em 0 .2em;font-size:13px}
.p-modes-credits p{margin:.2em 0;font-size:12px;line-height:1.4}
.p-modes-credits ul{margin:.2em 0 .6em;padding-left:1.1em;font-size:12px}
.p-modes-credits a{display:inline-block;min-height:44px;line-height:44px}
.p-modes-ref{opacity:.7}
@media (max-width:420px){.p-modes-btn{padding:0 7px;font-size:11px}}
@media (prefers-reduced-motion:reduce){.p-modes-btn{transition:none}}

Pilot Modes

A JavaScript file in the theme folder of Cosmic that maps modes fade and uses data from OpenStreetMap tiles. It gets tile (`getTile`), draws tile (`drawTile`) and draws grid (`drawGrid`).

rendercosmic / tools/explore/theme/pilot-modes.js · lines 1–374 of 374 · Entry point · pattern creditText (shared by 2 files)

What it does
It maps modes fade. Defines 23 functions or classes, including tileXY, tileLL, st, evict, getTile. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: data source: OpenStreetMap tiles; browser storage (getItem). Out: browser storage (setItem); canvas drawing.
Downstream impact
Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
Pilot MAP / SATELLITE / STREET ground modes, terrain relief and attribution (Pilot-200 W03, BASEMAP-46). It responds to click and keydown events.
Why it matters
Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
Application
cosmic · tools/explore/theme · script
Uses
none found
Used by
loaded by Pilot (script src)
Produces
tileXY, tileLL, st, evict, getTile, zoomFor, affine, drawTile, hillshade, shadeFor, drawGrid, makeGround
Defines here
tileXY, tileLL, st, evict, getTile, zoomFor, affine, drawTile, hillshade, shadeFor, drawGrid, makeGround, creditText, changed, buildUI, syncUI, choose, setRelief, panelBody, statusText, status, emitStatus, restore
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-modes.js:1-374 · blob bbb5e1d8e7505ef72c551ce5b374796255c628d8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: unknown · users: none · canonical: unknown
/* Pilot MAP / SATELLITE / STREET ground modes, terrain relief and attribution (Pilot-200 W03, BASEMAP-46).
   Plain script, no libraries, no CDN. Builds only on the window.PILOT contract v1 (registerMode, setMode, hud,
   panel, credit, hash, ground, on/emit). Nothing is stored on disk; the tile cache is memory-bounded.

   Ground sources (exactly as the estate's GridAtlas gives them; no other hosts):
   - MAP: CARTO dark_all raster, credit "© OpenStreetMap contributors · © CARTO"
     (Ventusltd/gridatlas atlas/labs/lightning-grid/map-view.mjs, source 'carto-dark').
   - STREET: OpenStreetMap standard tiles, credit "© OpenStreetMap contributors"
     (Ventusltd/gridatlas ui/site/atlas-v9.mjs and release-manifest id 'openstreetmap-standard-tiles').
     Polite use per the OSM tile policy: at most 2 requests in flight, zoom <= 16, browser cache only.
   - SAT: the core's built-in 'sat' ground (Esri World Imagery + AWS Terrain Tiles) with the core's credits.
   Terrain: the map mesh sits on PILOT.ground() (core's AWS Terrain Tiles); relief shading is computed from it. */
(function () {
  'use strict';
  if (!window.PILOT) return;
  var PILOT = window.PILOT, D = document;

  // ---- S01: sources
  var SRC = {
    map: { title: 'Map', label: 'MAP', url: 'https://basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
           credit: '© OpenStreetMap contributors · © CARTO', maxIn: 4, zmax: 18, bg: '#0e0e10',
           ref: 'gridatlas atlas/labs/lightning-grid/map-view.mjs (carto-dark)',
           links: [['OpenStreetMap copyright', 'https://www.openstreetmap.org/copyright'], ['CARTO attributions', 'https://carto.com/attributions']] },
    street: { title: 'Street', label: 'STREET', url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
           credit: '© OpenStreetMap contributors', maxIn: 2, zmax: 16, bg: '#f2efe9',
           ref: 'gridatlas ui/site/atlas-v9.mjs (openstreetmap-standard-tiles)',
           links: [['OpenStreetMap copyright', 'https://www.openstreetmap.org/copyright']] }
  };
  var SAT_INFO = { label: 'SAT', title: 'Satellite', credit: 'Imagery: Esri, Maxar, Earthstar Geographics',
                   ref: 'core pilot.js built-in (globalgrid2050 energy-transition-simulator overlay.html)',
                   links: [['Esri World Imagery', 'https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9']] };
  var TERRAIN = { credit: 'Terrain: AWS Terrain Tiles (open)', link: ['AWS Terrain Tiles (Registry of Open Data)', 'https://registry.opendata.aws/terrain-tiles/'] };
  var ORDER = ['map', 'sat', 'street'];
  var DEFAULT = 'sat';

  // ---- S02: slippy tile maths
  function tileXY(lat, lon, z) {
    var n = Math.pow(2, z), r = lat * Math.PI / 180;
    return [(lon + 180) / 360 * n, (1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2 * n];
  }
  function tileLL(x, y, z) {
    var n = Math.pow(2, z), lon = x / n * 360 - 180, r = Math.atan(Math.sinh(Math.PI * (1 - 2 * y / n)));
    return [r * 180 / Math.PI, lon];
  }

  // ---- S03: memory-bounded tile cache (per source), few requests in flight
  var CAP = 160, cache = {}, size = 0, tick = 0, held = false;
  var stats = { requested: 0, loaded: 0, failed: 0, evicted: 0 };
  function st(s) { return s.st || (s.st = { inflight: 0, ok: 0, fails: 0, dead: false, noted: false }); }
  function evict() {
    while (size > CAP) {
      var oldK = null, oldU = Infinity;
      for (var k in cache) { var t = cache[k]; if (!t.loading && t.used < oldU) { oldU = t.used; oldK = k; } }
      if (oldK === null) return;
      var o = cache[oldK]; if (o.im) { o.im.onload = o.im.onerror = null; o.im.src = ''; }
      delete cache[oldK]; size--; stats.evicted++;
    }
  }
  // Returns the cached tile ({ok, im}) or starts a request when allowed; null when nothing is available yet.
  function getTile(name, z, x, y, mayLoad) {
    var n = Math.pow(2, z); if (y < 0 || y >= n) return null;
    x = ((x % n) + n) % n;
    var s = SRC[name], k = name + '/' + z + '/' + x + '/' + y, t = cache[k];
    if (t) { t.used = ++tick; return t; }
    var S = st(s);
    if (!mayLoad || PILOT.offline || S.dead || held || S.inflight >= s.maxIn) return null;
    t = cache[k] = { ok: false, loading: true, used: ++tick, im: new Image() };
    size++; S.inflight++; stats.requested++;
    t.im.crossOrigin = 'anonymous';
    t.im.onload = function () { t.loading = false; t.ok = true; S.inflight--; S.ok++; stats.loaded++; changed(); };
    t.im.onerror = function () {
      t.loading = false; t.err = true; S.inflight--; S.fails++; stats.failed++;
      if (!S.ok && S.fails >= 8) { S.dead = true; changed(); }   // S09
      setTimeout(function () { if (cache[k] === t) { delete cache[k]; size--; } }, 15000);   // retry later
    };
    t.im.src = s.url.replace('{z}', z).replace('{x}', x).replace('{y}', y);
    evict();
    return t;
  }

  // ---- S07: zoom from height above ground and pitch; S18: one level coarser when fast/high
  var fastLevel = 0, flying = false;
  function zoomFor(agl, pitch, zmax) {
    var down = Math.max(0.35, Math.sin(-(pitch == null ? -1.45 : pitch)));
    var eff = Math.max(100, (agl || 0) / down);
    var z = Math.round(16 - Math.log(eff / 100) / Math.LN2);
    if (fastLevel >= 2 || (flying && agl > 3000)) z -= 1;
    return Math.max(9, Math.min(zmax || 18, z));
  }

  // ---- S04: draw an image region onto a projected ground mesh (affine triangles)
  function affine(g, im, s0, s1, s2, u0, u1, u2) {
    var den = u0[0] * (u1[1] - u2[1]) + u1[0] * (u2[1] - u0[1]) + u2[0] * (u0[1] - u1[1]); if (!den) return;
    var a = (s0.x * (u1[1] - u2[1]) + s1.x * (u2[1] - u0[1]) + s2.x * (u0[1] - u1[1])) / den,
        b = (s0.y * (u1[1] - u2[1]) + s1.y * (u2[1] - u0[1]) + s2.y * (u0[1] - u1[1])) / den,
        c = (s0.x * (u2[0] - u1[0]) + s1.x * (u0[0] - u2[0]) + s2.x * (u1[0] - u0[0])) / den,
        d = (s0.y * (u2[0] - u1[0]) + s1.y * (u0[0] - u2[0]) + s2.y * (u1[0] - u0[0])) / den,
        e = (s0.x * (u1[0] * u2[1] - u2[0] * u1[1]) + s1.x * (u2[0] * u0[1] - u0[0] * u2[1]) + s2.x * (u0[0] * u1[1] - u1[0] * u0[1])) / den,
        f = (s0.y * (u1[0] * u2[1] - u2[0] * u1[1]) + s1.y * (u2[0] * u0[1] - u0[0] * u2[1]) + s2.y * (u0[0] * u1[1] - u1[0] * u0[1])) / den;
    var mx = (s0.x + s1.x + s2.x) / 3, my = (s0.y + s1.y + s2.y) / 3, gr = function (p) {   // grow the clip ~0.6 px: no hairline seams
      var dx = p.x - mx, dy = p.y - my, l = Math.hypot(dx, dy) || 1; return [p.x + dx / l * 0.6, p.y + dy / l * 0.6]; };
    var q0 = gr(s0), q1 = gr(s1), q2 = gr(s2);
    g.save(); g.beginPath(); g.moveTo(q0[0], q0[1]); g.lineTo(q1[0], q1[1]); g.lineTo(q2[0], q2[1]); g.closePath(); g.clip();
    g.transform(a, b, c, d, e, f); g.drawImage(im, 0, 0); g.restore();
  }
  var drawn = 0, shadeOn = true, demSeen = false;
  // Mesh for tile (z,x,y): N x N cells; image region [ux, uy, us] in image px (parent fallback uses a sub-square).
  function drawTile(g, v, z, x, y, im, ux, uy, us, N, shade) {
    var P = [], i, j, ok = 0;
    for (j = 0; j <= N; j++) for (i = 0; i <= N; i++) {
      var ll = tileLL(x + i / N, y + j / N, z), p = v.project(ll[0], ll[1], null);
      P.push(p); if (p) ok++;
    }
    if (!ok) return 0;
    var cells = 0, sh = shade ? shadeFor(z, x, y, N) : null;
    for (j = 0; j < N; j++) for (i = 0; i < N; i++) {
      var a = P[j * (N + 1) + i], b = P[j * (N + 1) + i + 1], c = P[(j + 1) * (N + 1) + i + 1], d = P[(j + 1) * (N + 1) + i];
      if (!a || !b || !c || !d || a.d < 8 || b.d < 8 || c.d < 8 || d.d < 8) continue;   // too near the lens: skip, as core does
      var x0 = ux + us * i / N, x1 = ux + us * (i + 1) / N, y0 = uy + us * j / N, y1 = uy + us * (j + 1) / N;
      if (im) { affine(g, im, a, b, c, [x0, y0], [x1, y0], [x1, y1]); affine(g, im, a, c, d, [x0, y0], [x1, y1], [x0, y1]); }
      if (sh) { var al = sh[j * N + i]; if (al) {   // S16 relief: negative = shadow, positive = lit
        g.fillStyle = al < 0 ? 'rgba(0,0,0,' + (-al).toFixed(3) + ')' : 'rgba(255,255,255,' + al.toFixed(3) + ')';
        g.beginPath(); g.moveTo(a.x, a.y); g.lineTo(b.x, b.y); g.lineTo(c.x, c.y); g.lineTo(d.x, d.y); g.closePath(); g.fill(); } }
      cells++;
    }
    return cells;
  }

  // ---- S16: hillshade from PILOT.ground (sun from the north-west, 45 degrees up), cached per tile
  var shades = {}, shadeN = 0;
  function hillshade(dzdx, dzdy) {   // dz per metre east / north; returns -0.35..0.18 overlay alpha
    var slope = Math.atan(Math.hypot(dzdx, dzdy)); if (slope < 0.01) return 0;
    var aspect = Math.atan2(dzdx, dzdy) + Math.PI;   // downhill direction, radians from north clockwise
    var zen = Math.PI / 4, az = 315 * Math.PI / 180;
    var hs = Math.cos(zen) * Math.cos(slope) + Math.sin(zen) * Math.sin(slope) * Math.cos(az - aspect);
    var flat = Math.cos(zen), dlt = hs - flat;
    return dlt < 0 ? Math.max(-0.35, dlt * 0.9) : Math.min(0.18, dlt * 0.5);
  }
  function shadeFor(z, x, y, N) {
    var k = z + '/' + x + '/' + y + '/' + N, s = shades[k], now = Date.now();
    if (s && (s.real || now - s.t < 2000)) return s.a;
    var H = [], i, j, any = false;
    for (j = 0; j <= N; j++) for (i = 0; i <= N; i++) { var ll = tileLL(x + i / N, y + j / N, z), h = +PILOT.ground(ll[0], ll[1]) || 0; if (h) any = true; H.push(h); }
    var A = new Array(N * N), l0 = tileLL(x, y, z), l1 = tileLL(x + 1, y + 1, z);
    var cw = (l1[1] - l0[1]) / N * 111320 * Math.cos(l0[0] * Math.PI / 180), ch = (l0[0] - l1[0]) / N * 111320;
    for (j = 0; j < N; j++) for (i = 0; i < N; i++) {
      var h00 = H[j * (N + 1) + i], h10 = H[j * (N + 1) + i + 1], h01 = H[(j + 1) * (N + 1) + i], h11 = H[(j + 1) * (N + 1) + i + 1];
      var dzdx = ((h10 + h11) - (h00 + h01)) / 2 / cw, dzdy = ((h00 + h10) - (h01 + h11)) / 2 / ch;   // row j grows southwards
      A[j * N + i] = any ? hillshade(dzdx, dzdy) : 0;
    }
    if (any && !demSeen) { demSeen = true; changed(); }
    if (!s) { shadeN++; if (shadeN > 400) { shades = {}; shadeN = 1; } }
    shades[k] = { a: A, real: any, t: now };
    return A;
  }

  // ---- S09/S10: stylised ground grid when tiles are unavailable or the page is offline
  function drawGrid(g, v, light) {
    var c = v.cam, m = 200, R = 3000, k;
    var dLat = m / 111320, dLon = m / (111320 * Math.cos(c.lat * Math.PI / 180));
    var lat0 = Math.round(c.lat / dLat) * dLat, lon0 = Math.round(c.lon / dLon) * dLon, n = R / m;
    g.save(); g.lineWidth = 1; g.strokeStyle = light ? 'rgba(60,60,60,.25)' : 'rgba(0,255,255,.14)'; g.beginPath();
    for (k = -n; k <= n; k++) {
      v.line([lat0 + k * dLat, lon0 - n * dLon, 0], [lat0 + k * dLat, lon0 + n * dLon, 0]);
      v.line([lat0 - n * dLat, lon0 + k * dLon, 0], [lat0 + n * dLat, lon0 + k * dLon, 0]);
    }
    g.stroke(); g.restore();
  }

  // ---- ground renderer for one raster source (S04, S07, S08)
  function makeGround(name) {
    var s = SRC[name];
    return function (g, v) {
      g.save();
      g.fillStyle = s.bg; g.fillRect(0, 0, v.w, v.h);
      var S = st(s);
      if (PILOT.offline || S.dead) { drawGrid(g, v, name === 'street'); g.restore(); drawn = 0; return; }
      var c = v.cam, phone = v.w < 600, z = zoomFor(c.agl, c.pitch, s.zmax), N = phone ? 4 : 6, R = phone ? 1 : 2;
      // look point: where the view axis meets the ground (bounded), so the sharp block sits where the eye is
      var down = Math.max(0.12, Math.sin(-c.pitch)), reach = Math.min(4000, Math.max(0, c.agl) / down * 0.8);
      var hr = c.hdg * Math.PI / 180, lat = c.lat + Math.cos(hr) * reach / 111320, lon = c.lon + Math.sin(hr) * reach / (111320 * Math.cos(c.lat * Math.PI / 180));
      var cnt = 0;
      var t = tileXY(lat, lon, z), tx = Math.floor(t[0]), ty = Math.floor(t[1]);
      var list = [];
      for (var y = ty - R; y <= ty + R; y++) for (var x = tx - R; x <= tx + R; x++) list.push([x, y, Math.hypot(x + 0.5 - t[0], y + 0.5 - t[1])]);
      list.sort(function (p, q) { return p[2] - q[2]; });   // nearest first, so requests start where the eye is
      list.forEach(function (q) { getTile(name, z, q[0], q[1], true); });   // request the sharp block before the backdrop
      // backdrop: a coarse 3x3 block three levels up so the far field and the horizon are never empty
      var zb = Math.max(6, z - 3), tb = tileXY(lat, lon, zb), bx = Math.floor(tb[0]), by = Math.floor(tb[1]);
      for (var yy = by - 1; yy <= by + 1; yy++) for (var xx = bx - 1; xx <= bx + 1; xx++) {
        var tb2 = getTile(name, zb, xx, yy, true); if (tb2 && tb2.ok) drawTile(g, v, zb, xx, yy, tb2.im, 0, 0, 256, 2, false);
      }
      list.forEach(function (q) {
        var x = q[0], y = q[1], tl = getTile(name, z, x, y, false);
        if (tl && tl.ok) { drawTile(g, v, z, x, y, tl.im, 0, 0, 256, N, shadeOn); cnt++; return; }
        for (var up = 1; up <= 2; up++) {   // S08: a loaded parent's quarter while this tile loads
          var f = Math.pow(2, up), px = Math.floor(x / f), py = Math.floor(y / f), pt = getTile(name, z - up, px, py, false);
          if (pt && pt.ok) { var us = 256 / f; drawTile(g, v, z, x, y, pt.im, (x - px * f) * us, (y - py * f) * us, us, N, shadeOn); cnt++; return; }
        }
        if (shadeOn && demSeen) drawTile(g, v, z, x, y, null, 0, 0, 256, N, true);
      });
      drawn = cnt; lastZ = z;
      g.restore();
    };
  }
  var lastZ = 0;

  // ---- S05/S06: register the modes (credits are written by this module's own footer line, S14)
  Object.keys(SRC).forEach(function (name) {
    var s = SRC[name];
    s.mode = { title: s.title, credit: s.credit, ground: makeGround(name),
      enter: function () { changed(); }, exit: function () {} };
    PILOT.registerMode(name, s.mode);
  });

  // ---- S14: footer credit follows the mode; SAT keeps the core's own credits. The text lives on the registered
  // mode object (core lists the active mode's credit first in the footer); offline/failed states rewrite it.
  var cur = null;
  function creditText(m) {
    m = m || (PILOT.mode ? PILOT.mode() : cur);
    if (!SRC[m]) return null;
    var s = SRC[m], S = st(s), parts = [];
    if (PILOT.offline) parts.push('Offline: stylised grid (no map tiles fetched)');
    else if (S.dead) parts.push('Map tiles unavailable: stylised grid');
    else parts.push(s.credit);
    return parts.join(' · ');
  }
  var lastCredit, lastTerrain;
  function changed() {
    var t = creditText(), dirty = false;
    Object.keys(SRC).forEach(function (n) { var c = creditText(n); if (SRC[n].mode.credit !== c) { SRC[n].mode.credit = c; dirty = true; } });
    if (dirty || t !== lastCredit) { lastCredit = t; PILOT.credit('modes', null); }   // null: no extra line, just refresh the footer
    // terrain line kept separate and worded exactly as the core's, so the footer shows it once (core de-duplicates)
    var tt = demSeen && t ? TERRAIN.credit : null;
    if (tt !== lastTerrain) { lastTerrain = tt; PILOT.credit('modes-terrain', tt); }
    var m = PILOT.mode ? PILOT.mode() : cur, s = SRC[m];
    if (s && st(s).dead && !st(s).noted) { st(s).noted = true; PILOT.note(s.title + ' tiles could not load here, so the ground is a stylised grid. SAT may still work.', 7000); }
    syncUI(); panelBody(); emitStatus();
  }

  // ---- S11: MAP · SAT · STREET switch + S17 RELIEF toggle, in the top HUD row
  var ui = null;
  function buildUI() {
    var html = '<div class="p-modes-bar" role="group" aria-label="Ground view">' + ORDER.map(function (n) {
      var lab = n === 'sat' ? SAT_INFO.label : SRC[n].label, tit = n === 'sat' ? SAT_INFO.title : SRC[n].title;
      return '<button type="button" class="p-modes-btn" data-p-mode="' + n + '" aria-pressed="false" title="' + PILOT.esc(tit) + ' view (M)">' + lab + '</button>';
    }).join('') + '<button type="button" class="p-modes-btn p-modes-relief" data-p-relief="1" aria-pressed="true" title="Terrain relief shading on the map">RELIEF</button>' +
      '<button type="button" class="p-modes-btn p-modes-cr" data-p-credits="1" aria-label="Map and imagery credits" title="Credits">©</button></div>';
    ui = PILOT.hud('top:modes', html);
    if (!ui) return;
    ui.addEventListener('click', function (e) {
      var b = e.target.closest ? e.target.closest('button') : null; if (!b) return;
      if (b.hasAttribute('data-p-mode')) choose(b.getAttribute('data-p-mode'));
      else if (b.hasAttribute('data-p-relief')) setRelief(!shadeOn);
      else if (b.hasAttribute('data-p-credits')) { panelBody(true); if (PILOT.openPanel) PILOT.openPanel('credits'); }
    });
    syncUI();
  }
  function syncUI() {
    if (!ui) return;
    var m = PILOT.mode ? PILOT.mode() : cur;
    Array.prototype.forEach.call(ui.querySelectorAll('[data-p-mode]'), function (b) { b.setAttribute('aria-pressed', String(b.getAttribute('data-p-mode') === m)); });
    var r = ui.querySelector('[data-p-relief]');
    if (r) { r.setAttribute('aria-pressed', String(shadeOn)); r.hidden = !SRC[m]; }
  }
  function choose(name, quiet) {
    if (ORDER.indexOf(name) < 0) return;
    if ((PILOT.mode && PILOT.mode()) !== name) PILOT.setMode(name);
    cur = name;
    if (!quiet) PILOT.note((name === 'sat' ? SAT_INFO.title : SRC[name].title) + ' view', 1200);
    changed();
  }
  function setRelief(on) {
    shadeOn = !!on;
    if (PILOT.hash) PILOT.hash('relief', shadeOn ? null : '0');
    try { localStorage.setItem('pilot.relief', shadeOn ? '1' : '0'); } catch (e) {}
    changed();
  }

  // ---- S12: M cycles the views
  D.addEventListener('keydown', function (e) {
    if (e.target && /INPUT|TEXTAREA|SELECT/.test(e.target.tagName) || e.target.isContentEditable) return;
    if (e.ctrlKey || e.metaKey || e.altKey) return;
    if (e.key === 'm' || e.key === 'M') {
      var m = PILOT.mode ? PILOT.mode() : cur, i = ORDER.indexOf(m);
      choose(ORDER[(i + 1) % ORDER.length]); e.preventDefault();
    }
  });

  // ---- S15: credits panel, every source with its link and where in the estate it came from
  var panelEl = null;
  function panelBody(force) {
    if (!panelEl && !force) return;
    var m = PILOT.mode ? PILOT.mode() : cur;
    var rows = [];
    var info = m === 'sat' ? SAT_INFO : SRC[m];
    if (info) rows.push({ h: 'Ground: ' + info.title, t: info.credit, links: info.links, ref: info.ref });
    rows.push({ h: 'Terrain', t: TERRAIN.credit + (m === 'sat' || demSeen ? ' (in use)' : ' (not loaded)'), links: [TERRAIN.link], ref: 'core pilot.js DEM (Terrarium z12)' });
    var foot = D.getElementById('credit');
    var html = '<div class="p-modes-credits">' + rows.map(function (r) {
      return '<section><h3>' + PILOT.esc(r.h) + '</h3><p>' + PILOT.esc(r.t) + '</p><p class="p-modes-ref">Source in the estate: ' + PILOT.esc(r.ref) + '</p><ul>' +
        r.links.map(function (l) { return '<li><a href="' + PILOT.esc(l[1]) + '" target="_blank" rel="noopener noreferrer">' + PILOT.esc(l[0]) + '</a></li>'; }).join('') + '</ul></section>';
    }).join('') + (foot && foot.textContent ? '<section><h3>All credits on screen now</h3><p>' + PILOT.esc(foot.textContent) + '</p></section>' : '') + '</div>';
    panelEl = PILOT.panel('credits', html, { title: 'Credits', icon: '©', open: false }) || panelEl;
  }

  // ---- S19: short crossfade between views (none under reduced motion) + status line
  var fade = null;
  PILOT.addLayer({ id: 'modes-fade', title: 'View change fade', order: 1, visible: true,
    draw: function (g, v, now) {
      if (!fade) return;
      var a = 1 - (now - fade.t) / 250; if (a <= 0) { fade = null; return; }
      g.save(); g.setTransform(1, 0, 0, 1, 0, 0); g.globalAlpha = a; g.drawImage(fade.c, 0, 0); g.restore();
    } });
  var prevMode = null;
  PILOT.on('mode', function (d) {
    var name = d && d.name;
    if (prevMode && name !== prevMode && !PILOT.reduced) {
      var src = D.getElementById('pv');
      if (src && src.width) { try { var c = D.createElement('canvas'); c.width = src.width; c.height = src.height; c.getContext('2d').drawImage(src, 0, 0); fade = { c: c, t: performance.now() }; } catch (e) { fade = null; } }
    }
    prevMode = name; cur = name;
    if (ORDER.indexOf(name) >= 0) {   // remember the view whoever switched it (button, M key or another module)
      try { localStorage.setItem('pilot.mode', name); } catch (e) {}
      if (PILOT.hash) PILOT.hash('mode', name === DEFAULT ? null : name);
    }
    changed();
  });
  var lastStatus = '', statusT = 0;
  function statusText() {
    var m = PILOT.mode ? PILOT.mode() : cur, s = SRC[m]; if (!s) return '';
    var S = st(s);
    if (PILOT.offline) return s.label + ' offline';
    if (S.dead) return s.label + ' unavailable';
    return s.label + ' z' + lastZ + (S.inflight ? ' · ' + S.inflight + ' loading' : '') + (held ? ' · paused' : '')
      + (m === 'street' ? ' · map tiles, not street-level photography' : '');   // screening limit beside the view (review finding 3)
  }
  PILOT.onFrame(function (dt, now) {
    if (now - statusT < 250) return; statusT = now;
    var t = statusText();
    if (t !== lastStatus) { lastStatus = t; PILOT.hud('status:modes', t ? PILOT.esc(t) : null); }
    // S18: hold new requests while a fast arc is in the air or the camera is very high
    var c = PILOT.camLL ? PILOT.camLL() : null;
    held = flying && (fastLevel >= 2 || (c && c.agl > 3000));
  });
  PILOT.on('fast', function (d) { fastLevel = (d && d.level) || 0; });
  PILOT.on('depart', function () { flying = true; });
  PILOT.on('arrive', function () { flying = false; held = false; });

  // ---- S20: status/debug for QA (W10) and other modules
  function status() {
    var o = { mode: PILOT.mode ? PILOT.mode() : cur, z: lastZ, drawn: drawn, cache: size, cap: CAP, relief: shadeOn, dem: demSeen, held: held,
              requested: stats.requested, loaded: stats.loaded, failed: stats.failed, evicted: stats.evicted, sources: {} };
    Object.keys(SRC).forEach(function (n) { var S = st(SRC[n]); o.sources[n] = { inflight: S.inflight, ok: S.ok, fails: S.fails, dead: S.dead }; });
    return o;
  }
  var emitT = 0;
  function emitStatus() { var n = Date.now(); if (n - emitT < 200) return; emitT = n; PILOT.emit('modes:status', status()); }
  PILOT.on('modes:query', function (fn) { if (typeof fn === 'function') fn(status(), TEST); });
  var TEST = { tileXY: tileXY, tileLL: tileLL, zoomFor: zoomFor, hillshade: hillshade, getTile: getTile, cache: function () { return size; },
               setFast: function (l, fl) { fastLevel = l; flying = !!fl; }, stats: stats, SRC: SRC, creditText: creditText };
  PILOT.module('modes', { version: '1', owner: 'W03', status: status, _test: TEST });

  // ---- S13: restore the chosen view (hash wins over the last choice; default SAT)
  function restore() {
    var h = PILOT.hash ? PILOT.hash('mode') : null, ls = null, rl = PILOT.hash ? PILOT.hash('relief') : null;
    try { ls = localStorage.getItem('pilot.mode'); if (rl == null && localStorage.getItem('pilot.relief') === '0') rl = '0'; } catch (e) {}
    if (rl === '0') shadeOn = false;
    var want = ORDER.indexOf(h) >= 0 ? h : ORDER.indexOf(ls) >= 0 ? ls : DEFAULT;
    buildUI();
    choose(want, true);
  }
  if (PILOT.ready) PILOT.ready(restore); else restore();
})();

Pilot Nav

A style sheet in the theme folder of Cosmic.

rendercosmic / tools/explore/theme/pilot-nav.css · lines 1–24 of 24 · Entry point

What it does
Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage field_execution (path word 'nav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
Every selector prefixed p-nav-. Mobile first: 390 px, 44 px taps, no sideways scroll.
Why it matters
Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
Application
cosmic · tools/explore/theme · style sheet
Uses
none found
Used by
loaded by Pilot (stylesheet)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-nav.css:1-24 · blob 3160d4184e1f10ec419e8e56fdc61339b5ed1aca · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
/* Pilot SatNav (W09). Every selector prefixed p-nav-. Mobile first: 390 px, 44 px taps, no sideways scroll. */
.p-nav-hud{display:grid;grid-template-columns:auto 1fr auto;grid-template-rows:auto auto;column-gap:8px;align-items:center;
  max-width:min(460px,calc(100vw - 16px));box-sizing:border-box;padding:6px 10px;background:#081820e6;border:1px solid #ff3df0;
  border-radius:8px;color:#f4e9ff;font:13px/1.3 system-ui,sans-serif;overflow:hidden}
.p-nav-glyph{grid-row:1/3;font-size:28px;line-height:1;color:#ff3df0;min-width:32px;text-align:center}
.p-nav-cue{font-weight:600;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.p-nav-in{font-style:normal;font-weight:700;color:#ffd23d;white-space:nowrap}
.p-nav-sub{grid-column:2/4;color:#b9c7cc;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.p-nav{font:14px/1.4 system-ui,sans-serif;overflow-wrap:anywhere;max-width:100%;box-sizing:border-box}
.p-nav p{margin:4px 0}
.p-nav-cap{font-size:11px;letter-spacing:.08em;color:#68e8f5;margin-top:10px!important}
.p-nav-dest,.p-nav-sel{font-weight:600}
.p-nav-dim{color:#9fb3b8}
.p-nav-scope{font-size:12px;margin-top:10px!important}
.p-nav-warn{color:#ffd23d;font-weight:600}
.p-nav-legs{margin:4px 0;padding-left:22px}
.p-nav-legs li{margin:2px 0}
.p-nav-legs .p-nav-on{color:#ff3df0;font-weight:600}
.p-nav-row{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0}
.p-nav-btn{min-height:44px;min-width:44px;padding:6px 12px;background:#081820;color:#e4f7f7;border:1px solid #367078;border-radius:6px;
  font:inherit;cursor:pointer;touch-action:manipulation}
.p-nav-btn:focus-visible{outline:2px solid #fff;outline-offset:2px}
.p-nav-btn[data-nav=start],.p-nav-btn[data-nav=resume],.p-nav-btn[data-nav=next],.p-nav-btn[data-nav=route-sel],.p-nav-route{border-color:#ff3df0}
@media (prefers-reduced-motion: reduce){.p-nav-btn{transition:none}}