GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / uk_renewables_pipeline/202609081016/scripts/plugins

Projects V9 9

A JavaScript module in the plugins folder of GlobalGrid2050 that compares project updates v9, updates sort header, projects row and reads inputs for county and sort projects.

617 lines of JavaScript from globalgrid2050, in 1 file. Topic: Electricity markets and data pipelines. Section 933 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. Projects V9 9 energy-data · globalgrid2050 / uk_renewables_pipeline/202609081016/scripts/plugins/projects-v9-9.js lines 1–617

Projects V9 9

A JavaScript module in the plugins folder of GlobalGrid2050 that compares project updates v9, updates sort header, projects row and reads inputs for county and sort projects.

energy-dataglobalgrid2050 / uk_renewables_pipeline/202609081016/scripts/plugins/projects-v9-9.js · lines 1–617 of 617 · version 2026-09-08 10:16 · Not reached from any entry point (candidate for review) · pattern interconnectorRowHtml (shared by 2 files)

What it does
It draws the REPD register, interconnectors, solar and battery storage (BESS). Defines 29 functions or classes, including universeFor, atlasUrlV9_5_1, displayDate, repdUpdatedTimestamp, compareProjectUpdatesV9_5_1. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): 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, interconnectors, solar, battery storage (BESS).
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
Downstream impact
Used directly by 1 file: App V9 9 (globalgrid2050).
What it achieves
It compares project updates v9 (`compareProjectUpdatesV9_5_1`), updates sort header (`updateSortHeader`) and maps action HTML v9 (`mapActionHtmlV9_5_1`). Its `downloadCsv` function gives CSV download or refusal from active table owner, filtered register rows and official detail partitions (VEDIC: export filtered projects). It responds to click events.
Why it matters
Imported by App V9 9.
Application
globalgrid2050 · uk_renewables_pipeline/202609081016/scripts/plugins · JavaScript module
VEDIC
EXPORT FILTERED PROJECTS (GG2050-VEDIC-000060): Pipeline News · Renewable project register. active_table_owner, filtered_register_rows, official_detail_partitions → csv_download_or_refusal
Uses
Testcode — Pipeline (import), Atlas Receiver V9 7 (import), State (import), Project Filter V9 2 (import), Canonical Projects V9 5 1 (import), Gauges V9 2 (import), Newspaper V9 5 1 (import), Interconnectors V9 8 (import), and 1 more
Used by
imported by App V9 9 (import)
Produces
atlasUrlV9_5_1, compareProjectUpdatesV9_5_1, loadProjectsV9_8, refreshProjectsV9_8, bindProjectControlsV9_8
Defines here
universeFor, atlasUrlV9_5_1, displayDate, repdUpdatedTimestamp, compareProjectUpdatesV9_5_1, updateSortHeader, relationshipSummary, mapActionHtmlV9_5_1, schedule, interconnectorRowHtml, projectRowHtml, pageCount, pagerElement, renderPager, renderTable, updateResultSummary, syncFilterUrl, apply, populateCounties, setButtonState, hydrateFiltersFromUrl, csvCell, downloadCsv, clearFilters, copyProjectId, loadProjectsV9_8, refreshProjectsV9_8, bindProjectControlsV9_8, syncMapAtlasNavV9_7
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609081016/scripts/plugins/projects-v9-9.js:1-617 · blob 3196dfb277606aec091ae5248c19c675d325b3e8 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import { escapeHtml } from "../core/utils.js";
import {
  atlasCentresOnRepdPointV9_7,
  atlasReceiverV9_7,
  atlasUnavailableReasonV9_7,
  buildAtlasDeepLinkV9_7,
  verifyAtlasReceiverV9_7,
} from "../core/atlas-receiver-v9-7.js";
import { state } from "../core/state.js";
import {
  buildProjectSearchTextV9_2,
  projectMatchesV9_2,
  summariseProjectsV9_2,
  tokeniseSearchV9_2,
} from "../core/project-filter-v9-2.js";
import { loadCanonicalProjectsV9_5_1 } from "../data/canonical-projects-v9-5-1.js";
import {
  formatCapacityV9_2,
  formatLargestV9_2,
  setGaugeUniverseV9_2,
  updateGaugesV9_2,
} from "./gauges-v9-2.js";
import { signalForProjectV9_5_1 } from "./newspaper-v9-5-1.js";

import { loadInterconnectorsV9_8 } from "../data/interconnectors-v9-8.js";
import {
  buildAtlasInterconnectorLinkV9_8,
  interconnectorMapNoteV9_8,
  interconnectorMapUnavailableReasonV9_8,
} from "../core/atlas-interconnector-link-v9-8.js";

/* INTERCONNECTORS ARE A TAB, NOT A FIFTH REPD TECHNOLOGY.
   ALL TECH is the DESNZ register: 7,680 records, 356,474.09 MW, pinned by
   contract and by every gate. The sixteen GB interconnectors are not in that
   register and are not added to it. They live in their own pinned data product
   (data/v9.8), sit behind their own tab, and count only when that tab is
   selected - the count line says "of 16 interconnector records" so a reader
   never mistakes them for REPD rows. */
const LABELS = Object.freeze({
  solar: "Solar",
  bess: "Battery Storage",
  wind_onshore: "Onshore Wind",
  wind_offshore: "Offshore Wind",
  interconnector: "Interconnector",
});
const COLOURS = Object.freeze({ solar: "#ffff00", bess: "#ffae00", wind_onshore: "#00ffff", wind_offshore: "#0066ff", interconnector: "#0066ff" });
const UNITS = Object.freeze({ solar: "MWp", bess: "MW", wind_onshore: "MW", wind_offshore: "MW", interconnector: "MW" });
const ALLOWED_TECHNOLOGIES = new Set(["all", "solar", "bess", "wind_onshore", "wind_offshore", "interconnector"]);
const ALLOWED_STATUSES = new Set(["All", "Operational", "Under Construction", "Awaiting Construction", "Application Submitted"]);
const ALLOWED_SORTS = new Set(["capacity_desc", "updated_desc", "updated_asc"]);

let all = [];
let interconnectors = [];
let interconnectorFailure = "";
function universeFor() {
  return technology === "interconnector" ? interconnectors : all;
}
let filtered = [];
let page = 0;
let metadata = null;
let release = null;
let searchIndex = new Map();
let technology = "all";
let status = "All";
let county = "All";
let query = "";
let sortMode = "capacity_desc";
let controlsBound = false;

export function atlasUrlV9_5_1(project) {
  // The receiver is not named here. It is read from the deep-link contract the
  // engine publishes -- see ../core/atlas-receiver-v9-7.js for the measurement
  // that made this necessary. Seven files in this directory each held their own
  // copy of a route that had quietly stopped carrying the engine.
  return buildAtlasDeepLinkV9_7(project);
}

function displayDate(value) {
  if (!value) return "not supplied by REPD";
  const [year, month, day] = String(value).split("-");
  return year && month && day ? `${day}/${month}/${year}` : String(value);
}

function repdUpdatedTimestamp(project) {
  if (!project.repd_record_updated) return null;
  const value = Date.parse(`${project.repd_record_updated}T00:00:00Z`);
  return Number.isFinite(value) ? value : null;
}

export function compareProjectUpdatesV9_5_1(left, right, direction = "desc") {
  const leftTime = repdUpdatedTimestamp(left);
  const rightTime = repdUpdatedTimestamp(right);
  if (leftTime === null && rightTime === null) return 0;
  if (leftTime === null) return 1;
  if (rightTime === null) return -1;
  return direction === "asc" ? leftTime - rightTime : rightTime - leftTime;
}

function updateSortHeader() {
  const header = document.getElementById("repdUpdatedHeader");
  const button = document.getElementById("sortUpdated");
  const indicator = document.getElementById("updatedSortIndicator");
  if (!header || !button || !indicator) return;
  if (sortMode === "updated_desc") {
    header.setAttribute("aria-sort", "descending");
    indicator.textContent = "▼";
    button.setAttribute("aria-label", "REPD updated date sorted newest first; click for oldest first");
    button.title = "Newest first — click for oldest first";
    return;
  }
  if (sortMode === "updated_asc") {
    header.setAttribute("aria-sort", "ascending");
    indicator.textContent = "▲";
    button.setAttribute("aria-label", "REPD updated date sorted oldest first; click for newest first");
    button.title = "Oldest first — click for newest first";
    return;
  }
  header.setAttribute("aria-sort", "none");
  indicator.textContent = "↕";
  button.setAttribute("aria-label", "Sort by REPD updated date, newest first");
  button.title = "Click for newest first";
}

function relationshipSummary(project) {
  const development = Array.isArray(project.development_repd_refs) ? project.development_repd_refs.length : 0;
  const direct = Array.isArray(project.direct_related_repd_refs) ? project.direct_related_repd_refs.length : 0;
  const siblings = Array.isArray(project.planning_sibling_repd_refs) ? project.planning_sibling_repd_refs.length : 0;
  return `${development} development · ${direct} direct · ${siblings} planning sibling record(s)`;
}

/* WHAT THE MAP CELL SAYS, AND WHY IT SAYS IT IN THE CELL.

   This used to be a link or the two words NO MAP with its reason in a title
   attribute. A phone reports hover: none, so on a phone the reason could not be
   reached at all -- and 28 of these 7,680 records got the silent version.

   Those 28 are no longer denied a link. The contract requires only repd_ref;
   latitude and longitude are optional, and the canonical receiver resolves the
   project from its REPD reference and centres on its own geometry. Measured on
   REPD 13429 (Ossian), which has no REPD coordinate: the arrival names the
   project, its capacity and its reference. So they get a MAP button and a
   sentence saying whose coordinate the map is using -- which is the honest
   answer, and the opposite of a button that quietly does nothing. */
function mapActionHtmlV9_5_1(project) {
  const href = atlasUrlV9_5_1(project);
  if (!href) {
    return `<span class="action-disabled">NO MAP</span>`
      + `<div class="map-note">${escapeHtml(atlasUnavailableReasonV9_7(project))}</div>`;
  }
  const link = `<a class="action-link atlaslink" target="_blank" rel="noopener" href="${escapeHtml(href)}">MAP ↗</a>`;
  /* WHAT AN OFFSHORE ROW'S MAP BUTTON OPENS ON, SAID IN THE CELL.

     Since GridAtlas v9.154 an offshore wind arrival is answered by a separate
     engine. The onshore engine measures to the nearest mapped substations
     within 40 km; for an array 60 km out at sea that returns another
     company's offshore platform, which is an answer to the wrong question. The
     offshore engine instead reads NESO's connection registers - the
     Transmission Entry Capacity and Embedded registers, published by the body
     that issues the connection - binds the project to the substation it is
     contracted to, at whatever distance that is, draws the connection in gold
     and frames both ends. Hornsea 3 lands on Norwich Main; Berwick Bank on
     Branxton.

     The sentence is deliberately the same for every offshore row, because the
     button does the same thing for every offshore row and the Atlas says on
     arrival which of three things happened: the connection is drawn; the
     register names a substation this map cannot yet place, usually one not yet
     built; or the project is in neither register. No version number is printed
     here - the route is read from the engine's own contract, and a number typed
     into this file would drift the day the engine moves. */
  const offshoreNote = project.technology === "wind_offshore"
    ? `<div class="map-note">Opens on the offshore cable engine: where NESO's connection register names `
      + `the substation this project is contracted to, the Atlas draws that connection and frames it. `
      + `Nearest-substation distances are shown as nearest, never as the connection.</div>`
    : "";
  if (atlasCentresOnRepdPointV9_7(project)) return link + offshoreNote;
  return `${link}${offshoreNote}<div class="map-note">REPD published no coordinate for this record. `
    + `The Atlas resolves it from REPD ${escapeHtml(project.repd_ref)} and centres on its own geometry.</div>`;
}

/* PROGRESSIVE RENDER — measured, not guessed.
   The unfiltered view is 7,680 rows at 42 elements each: 323,802 DOM elements
   built from 13.7 MB of markup in a single synchronous innerHTML assignment.
   Measured on a desktop on 2026-09-06, that assignment blocks the main thread
   for 3.6 to 4.4 seconds. An iPhone is several times slower again, which is
   the freeze where nothing responds to a tap.

   The fetch is NOT the problem and was measured before being blamed: the first
   partition lands in about 80 ms and all sixteen in 458-571 ms at any
   concurrency between 4 and 16. Only the render is slow.

   So the first rows are painted at once and the remainder is appended a chunk
   per animation frame. Nothing is hidden and nothing is paginated: `all` and
   `filtered` are untouched, so search, the counts and the CSV export continue
   to see every record — which is the trap a pagination that slices the data
   rather than the view walks into.

   A render in flight is cancelled by the next one through renderToken, or
   changing a filter mid-render would append rows from the previous result on
   top of the new one. */
const FIRST_PAINT_ROWS = 100;
const CHUNK_ROWS = 300;
let renderToken = 0;

/* requestAnimationFrame does not fire in a background tab, so a reader who
   opens this in a second tab and comes back would find the table still holding
   only its first hundred rows. A timeout does fire there, throttled, so the
   table finishes either way: frames while the reader is looking, timeouts while
   they are not. */
function schedule(step) {
  if (document.visibilityState === "visible" && typeof requestAnimationFrame === "function") {
    requestAnimationFrame(step);
  } else {
    setTimeout(step, 0);
  }
}

/* AN INTERCONNECTOR ROW. Same eleven cells as a REPD row, so the table, the
   mobile layout and the reachability gate see one shape; different words in
   them, because the facts are different. There is no REPD reference, no
   planning authority and no news signal - news signals are REPD-bound by
   contract - and the row says so rather than printing a dash where a reader
   would infer a fact. The MAP link carries the link's own identity. */
function interconnectorRowHtml(record) {
  const label = LABELS[record.technology];
  const unit = UNITS[record.technology];
  const location = [record.county, record.region].filter(Boolean).join(" · ");
  const news = new URL("https://www.google.com/search");
  news.searchParams.set("q", `${record.name} interconnector`);
  news.searchParams.set("tbm", "nws");
  const href = buildAtlasInterconnectorLinkV9_8(record);
  const mapAction = href
    ? `<a class="action-link atlaslink" target="_blank" rel="noopener" href="${escapeHtml(href)}">MAP ↗</a><div class="map-note">${escapeHtml(interconnectorMapNoteV9_8(record))}</div>`
    : `<span class="action-disabled">NO MAP</span><div class="map-note">${escapeHtml(interconnectorMapUnavailableReasonV9_8(record))}</div>`;
  const identity = record.bmrs_code ? `BMRS ${record.bmrs_code}` : "NO BMRS CODE YET";
  const geometry = record.geometry_status === "valid"
    ? `straight line converter to converter, ${record.span.straight_line_km} km; the midpoint is a label anchor, not a location`
    : record.geometry_status === "gb_end_only"
      ? `GB converter ${record.gb_end.name}; the far converter is not held yet`
      : "no converter coordinates held";
  const gbEnd = record.gb_end && record.gb_end.name ? record.gb_end.name : "GB end not held";
  const farEnd = record.far_end && record.far_end.name ? record.far_end.name : `${record.country} end not held`;
  const flow = record.flow
    ? `${record.flow.net_direction}; ${Math.round(record.flow.net_mwh).toLocaleString("en-GB")} MWh net over ${record.flow.years}`
    : "flow data not wired for this link";
  const lifecycle = record.lifecycle + (record.target_operational ? ` · target ${record.target_operational}` : "");
  return `<tr id="repd-${escapeHtml(record.repd_ref)}" data-repd-updated="" data-technology="interconnector"><td class="site">${escapeHtml(record.name)}<div class="project-meta">${escapeHtml(identity)} · ${escapeHtml(record.gg_project_id)} · NOT A REPD RECORD</div><div class="mobile-extra">${escapeHtml(location)}</div><details class="project-record"><summary>INTERCONNECTOR RECORD</summary><div cla  … [line shortened here: 1,944 characters; full line on GitHub]
}

function projectRowHtml(project) {
  if (project.technology === "interconnector") return interconnectorRowHtml(project);
  const label = LABELS[project.technology];
    const unit = UNITS[project.technology];
    const location = [project.county, project.region].filter(Boolean).join(" · ");
    const signal = signalForProjectV9_5_1(project);
    const news = new URL("https://www.google.com/search");
    news.searchParams.set("q", `${project.name} ${label} UK`);
    news.searchParams.set("tbm", "nws");
    const mapAction = mapActionHtmlV9_5_1(project);
    const planning = project.planning_application_reference || "not supplied by REPD";
    const authority = project.planning_authority || "not supplied by REPD";
    const developmentId = project.gg_development_id || "not assigned";
    const updated = displayDate(project.repd_record_updated);
    return `<tr id="repd-${escapeHtml(project.repd_ref)}" data-repd-updated="${escapeHtml(project.repd_record_updated || "")}"><td class="site">${escapeHtml(project.name)}<div class="project-meta">REPD ${escapeHtml(project.repd_ref)} · ${escapeHtml(project.gg_project_id)} · UPDATED ${escapeHtml(updated)}</div><div class="mobile-extra">${escapeHtml([location, project.operator].filter(Boolean).join(  … [line shortened here: 2,120 characters; full line on GitHub]
}

/* TWENTY ROWS, AND THE REST BEHIND PAGES AND SEARCH.
 *
 * The previous build painted the first hundred rows and then streamed the
 * remaining seven and a half thousand into the DOM in chunks. That stopped the
 * page freezing, but it still built 7,680 table rows on a phone for a reader
 * who was going to look at the top of the list.
 *
 * So the VIEW is now a page of twenty, largest capacity first. The DATA is
 * untouched: `all` still holds every qualifying record, `filtered` still holds
 * every record matching the current tabs and search, the CSV still exports the
 * filtered set in full, and the count line still states both numbers. Nothing
 * is dropped from the pipeline - the reader is simply not made to render it.
 *
 * The tabs and the search box do the narrowing. Paging is for what is left. */
const PAGE_ROWS = 20;

function pageCount() {
  return Math.max(1, Math.ceil(filtered.length / PAGE_ROWS));
}

function pagerElement() {
  let el = document.getElementById("projectPager");
  if (!el) {
    el = document.createElement("nav");
    el.id = "projectPager";
    el.className = "pager";
    el.setAttribute("aria-label", "Project pages");
    const table = document.getElementById("tbody");
    const anchor = table ? table.closest("table") : null;
    if (anchor && anchor.parentNode) anchor.parentNode.insertBefore(el, anchor.nextSibling);
    else if (table) table.parentNode.appendChild(el);
  }
  return el;
}

function renderPager() {
  const el = pagerElement();
  const pages = pageCount();
  const total = filtered.length;
  if (!total) {
    el.innerHTML = '<span class="pager-meta">no records match the current filters</span>';
    return;
  }
  const from = page * PAGE_ROWS + 1;
  const to = Math.min(total, (page + 1) * PAGE_ROWS);
  el.innerHTML =
    '<button type="button" class="pager-btn" data-page-step="-1"' + (page === 0 ? ' disabled' : '') + '>&larr; PREV</button>' +
    '<span class="pager-meta">' + from.toLocaleString("en-GB") + '&ndash;' + to.toLocaleString("en-GB") +
      ' of ' + total.toLocaleString("en-GB") + ' &middot; page ' + (page + 1) + ' of ' + pages + '</span>' +
    '<button type="button" class="pager-btn" data-page-step="1"' + (page + 1 >= pages ? ' disabled' : '') + '>NEXT &rarr;</button>';
  el.dataset.page = String(page + 1);
  el.dataset.pages = String(pages);
  el.dataset.from = String(from);
  el.dataset.to = String(to);
}

function renderTable() {
  const body = document.getElementById("tbody");
  const total = filtered.length;
  const pages = pageCount();
  if (page > pages - 1) page = pages - 1;
  if (page < 0) page = 0;
  const from = page * PAGE_ROWS;
  const slice = filtered.slice(from, from + PAGE_ROWS);
  body.innerHTML = slice.map(projectRowHtml).join("");
  body.dataset.rendered = String(slice.length);
  body.dataset.total = String(total);
  body.dataset.page = String(page + 1);
  body.dataset.pages = String(pages);
  body.dataset.complete = "true";
  renderPager();
}

function updateResultSummary() {
  const summary = summariseProjectsV9_2(filtered);
  const element = document.getElementById("resultsMeta");
  const universe = universeFor();
  element.textContent = `${summary.count.toLocaleString("en-GB")} of ${universe.length.toLocaleString("en-GB")} ${technology === "interconnector" ? "interconnector records (outside the REPD spine)" : "records"} · ${formatCapacityV9_2(summary.capacity_mw)} MW · largest ${formatLargestV9_2(summary.largest_mw)} MW`;
  element.classList.toggle("is-filtered", summary.count !== universe.length);
  element.dataset.filteredCount = String(summary.count);
  element.dataset.totalCount = String(universe.length);
}

function syncFilterUrl() {
  const url = new URL(window.location.href);
  for (const parameter of ["technology", "status", "county", "q", "sort"]) url.searchParams.delete(parameter);
  if (technology !== "all") url.searchParams.set("technology", technology);
  if (status !== "All") url.searchParams.set("status", status);
  if (county !== "All") url.searchParams.set("county", county);
  if (query) url.searchParams.set("q", query);
  if (sortMode !== "capacity_desc") url.searchParams.set("sort", sortMode);
  history.replaceState(null, "", url);
}

function apply({ syncUrl = true } = {}) {
  const tokens = tokeniseSearchV9_2(query);
  filtered = universeFor().filter((project) => projectMatchesV9_2(project, {
    technology,
    status,
    county,
    tokens,
  }, searchIndex.get(project.repd_ref)));
  if (sortMode === "updated_desc") filtered.sort((left, right) => compareProjectUpdatesV9_5_1(left, right, "desc"));
  if (sortMode === "updated_asc") filtered.sort((left, right) => compareProjectUpdatesV9_5_1(left, right, "asc"));
  state.filtered = filtered;
  page = 0;
  updateGaugesV9_2(filtered);
  renderTable();
  updateResultSummary();
  updateSortHeader();
  if (syncUrl) syncFilterUrl();
}

function populateCounties() {
  const select = document.getElementById("county");
  select.replaceChildren(new Option("🌍 ALL COUNTIES", "All"));
  [...new Set(all.map((project) => project.county).filter(Boolean))]
    .sort((left, right) => left.localeCompare(right, "en-GB"))
    .forEach((value) => select.add(new Option(`📍 ${value}`, value)));
}

function setButtonState(container, dataKey, selected) {
  document.querySelectorAll(`${container} .btn`).forEach((button) => {
    const active = button.dataset[dataKey] === selected;
    button.classList.toggle("active", active);
    button.setAttribute("aria-pressed", String(active));
  });
}

function hydrateFiltersFromUrl() {
  const parameters = new URLSearchParams(window.location.search);
  const requestedTechnology = parameters.get("technology") || "all";
  const requestedStatus = parameters.get("status") || "All";
  const requestedCounty = parameters.get("county") || "All";
  const requestedSort = parameters.get("sort") || "capacity_desc";
  technology = ALLOWED_TECHNOLOGIES.has(requestedTechnology) ? requestedTechnology : "all";
  status = ALLOWED_STATUSES.has(requestedStatus) ? requestedStatus : "All";
  county = [...document.getElementById("county").options].some((option) => option.value === requestedCounty)
    ? requestedCounty
    : "All";
  query = parameters.get("q") || "";
  sortMode = ALLOWED_SORTS.has(requestedSort) ? requestedSort : "capacity_desc";
  setButtonState("#tech", "technology", technology);
  setButtonState("#status", "officialStatus", status);
  document.getElementById("county").value = county;
  document.getElementById("search").value = query;
  document.getElementById("sortProjects").value = sortMode;
}

function csvCell(value) {
  let text = value === null || value === undefined ? "" : String(value);
  if (/^(?:[=+\-@]|\s+[=+\-@]|\t|\r|\n)/u.test(text)) text = `'${text}`;
  return `"${text.replaceAll('"', '""')}"`;
}

function downloadCsv(event) {
  event.preventDefault();
  const headers = ["Site Name", "REPD Ref", "GlobalGrid Project ID", "GlobalGrid Development ID", "Identity Status", "Identity Confidence", "Technology", "Official REPD Technology", "Official REPD Capacity", "Capacity Unit", "Official REPD Status", "Derived Lifecycle", "Operator or Applicant", "County", "Region", "Country", "Planning Authority", "Planning Application Reference", "REPD Record Updat  … [line shortened here: 1,130 characters; full line on GitHub]
  const rows = filtered.map((project) => {
    const signal = signalForProjectV9_5_1(project);
    return [project.name, project.repd_ref, project.gg_project_id, project.gg_development_id, project.identity_status, project.identity_confidence, LABELS[project.technology], project.repd_technology, project.capacity_mw, UNITS[project.technology], project.status, project.lifecycle, project.operator, project.county, project.region, project.country, project.planning_authority, project.planning_appl  … [line shortened here: 1,392 characters; full line on GitHub]
  });
  const content = `\ufeff${[headers, ...rows].map((row) => row.map(csvCell).join(",")).join("\r\n")}`;
  const url = URL.createObjectURL(new Blob([content], { type: "text/csv;charset=utf-8" }));
  const anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = `globalgrid2050_uk_renewables_pipeline_v9_8_${new Date().toISOString().slice(0, 10)}.csv`;
  anchor.click();
  URL.revokeObjectURL(url);
  document.getElementById("exportMeta").textContent = `${filtered.length.toLocaleString("en-GB")} filtered records exported`;
}

function clearFilters(event) {
  event.preventDefault();
  technology = "all";
  status = "All";
  county = "All";
  query = "";
  sortMode = "capacity_desc";
  setButtonState("#tech", "technology", technology);
  setButtonState("#status", "officialStatus", status);
  document.getElementById("county").value = county;
  document.getElementById("search").value = "";
  document.getElementById("sortProjects").value = sortMode;
  apply();
}

async function copyProjectId(button) {
  const value = button.dataset.copyId;
  try {
    await navigator.clipboard.writeText(value);
  } catch {
    const field = document.createElement("textarea");
    field.value = value;
    field.setAttribute("readonly", "");
    field.style.position = "fixed";
    field.style.opacity = "0";
    document.body.appendChild(field);
    field.select();
    document.execCommand("copy");
    field.remove();
  }
  const original = button.textContent;
  button.textContent = "COPIED";
  button.classList.add("copied");
  setTimeout(() => {
    button.textContent = original;
    button.classList.remove("copied");
  }, 1200);
}

export async function loadProjectsV9_8() {
  try {
    /* NOTHING CROSS-ORIGIN GATES THE FIRST ROW.

       This was a Promise.all of the project payload AND a fetch to
       ventusltd.github.io, because atlasUrlV9_5_1() is synchronous and
       renderTable() calls it once per row, so the receiver had to be known
       before the first paint. The consequence, measured 2026-09-05 at a phone
       viewport: not one of 7,680 rows could appear until a request to a SECOND
       ORIGIN had done DNS, TCP, TLS and a round trip — 59 ms on a wired link,
       which is why every desktop check passed, and a cold-radio handshake on
       the device the complaint came from. index.html:157 paints an empty
       <tbody> with no placeholder, so the reader saw nothing at all for the
       duration.

       The receiver is now known at import (see core/atlas-receiver-v9-7.js),
       so this awaits the payload alone. The contract is still read — fired
       here, awaited by nobody — and the only thing it can do is change or
       withdraw the links, which re-renders. On a correct estate it never
       does, because the compiled contract is pinned to the published one by
       testcode/drivers/link-targets.mjs. */
    const verifying = verifyAtlasReceiverV9_7();
    const model = await loadCanonicalProjectsV9_5_1();
    all = [...model.projects];
    /* Loaded beside the spine, never merged into it. A failure here disables
       the INTERCONNECTORS tab with its reason and leaves the 7,680 untouched:
       the register must not fail closed because a sixteen-row product did. */
    try {
      const interconnectorModel = await loadInterconnectorsV9_8();
      interconnectors = [...interconnectorModel.records];
    } catch (error) {
      interconnectors = [];
      interconnectorFailure = String((error && error.message) || error);
      console.error(error);
      const tab = document.querySelector('#tech [data-technology="interconnector"]');
      if (tab) { tab.disabled = true; tab.title = interconnectorFailure; }
    }
    state.interconnectors = interconnectors;
    filtered = all;
    metadata = model.metadata;
    release = model.release;
    searchIndex = new Map(all.map((project) => [project.repd_ref, buildProjectSearchTextV9_2(project)]));
    for (const record of interconnectors) searchIndex.set(record.repd_ref, buildProjectSearchTextV9_2(record));
    state.all = all;
    state.filtered = filtered;
    state.canonicalModel = model;
    setGaugeUniverseV9_2(all);
    populateCounties();
    hydrateFiltersFromUrl();
    apply({ syncUrl: false });
    document.getElementById("releaseMeta").textContent = `V9.8 interface · V${release.data_parent.release} canonical data spine · ${interconnectors.length} interconnectors on their own tab · all ${all.length.toLocaleString("en-GB")} qualifying records loaded`;

    /* Re-render only if the engine's published contract disagrees with the one
       compiled in — a different canonical receiver, or this one retired. Not
       awaited, so a slow or dead contract costs the reader nothing, and on the
       normal path `changed` is false and this does no work at all. */
    verifying.then((result) => {
      if (result.changed) refreshProjectsV9_8();
      syncMapAtlasNavV9_7();
      if (!result.verified) console.warn(`V9.5.1 MAP: ${result.reason}`);
    });
  } catch (error) {
    console.error(error);
    document.getElementById("tbody").innerHTML = '<tr><td colspan="11" style="text-align:center;color:#ff6666">Canonical Q2 REPD data unavailable. V9.5.1 has failed closed.</td></tr>';
    document.getElementById("resultsMeta").textContent = "canonical data unavailable";
  }
}

export function refreshProjectsV9_8() {
  if (metadata) renderTable();
}

export function bindProjectControlsV9_8() {
  if (controlsBound) return;
  controlsBound = true;
  document.querySelectorAll("#tech .btn").forEach((button) => {
    button.onclick = () => {
      technology = button.dataset.technology;
      setButtonState("#tech", "technology", technology);
      apply();
    };
  });
  document.querySelectorAll("#status .btn").forEach((button) => {
    button.onclick = () => {
      status = button.dataset.officialStatus;
      setButtonState("#status", "officialStatus", status);
      apply();
    };
  });
  document.getElementById("county").onchange = (event) => { county = event.target.value; apply(); };
  document.getElementById("sortProjects").onchange = (event) => { sortMode = event.target.value; apply(); };
  document.getElementById("sortUpdated").onclick = () => {
    sortMode = sortMode === "updated_desc" ? "updated_asc" : "updated_desc";
    document.getElementById("sortProjects").value = sortMode;
    apply();
  };
  document.getElementById("search").oninput = (event) => { query = event.target.value.trim(); apply(); };
  /* Delegated, because the pager is rebuilt on every render. Paging moves the
     WINDOW over `filtered`; it never re-filters and never re-fetches. */
  document.addEventListener("click", (event) => {
    const button = event.target.closest ? event.target.closest("[data-page-step]") : null;
    if (!button || !document.getElementById("projectPager")) return;
    const step = Number(button.getAttribute("data-page-step"));
    if (!Number.isFinite(step)) return;
    const pages = pageCount();
    const next = Math.min(pages - 1, Math.max(0, page + step));
    if (next === page) return;
    page = next;
    renderTable();
    const table = document.getElementById("tbody");
    if (table && table.closest("table")) table.closest("table").scrollIntoView({ block: "start" });
  });

  document.getElementById("export").onclick = downloadCsv;
  document.getElementById("exportInline").onclick = downloadCsv;
  document.getElementById("clearFilters").onclick = clearFilters;
  document.getElementById("tbody").addEventListener("click", (event) => {
    const button = event.target.closest(".copy-id");
    if (button) copyProjectId(button);
  });
}

/* The MAP ATLAS nav button is static HTML, so it cannot follow the receiver the
   way a row's MAP cell does - and until 2026-09-05 it pointed at the retired V8
   Atlas while every row pointed at the canonical one. The href in index.html is
   now the compiled canonical route, which is correct before any network exists;
   this re-points it only if the live contract disagrees, and hides it if the
   contract withdraws the receiver entirely. Same signal, same moment, as the
   table's own re-render. */
function syncMapAtlasNavV9_7() {
  const nav = document.getElementById("mapAtlasNav");
  if (!nav) return;
  const route = atlasReceiverV9_7();
  if (!route) {
    nav.hidden = true;
    return;
  }
  nav.hidden = false;
  nav.href = route;
}