GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / code-generator / apps/substation-finder/Si

Substation Finder — Si Page (part 2)

A map page in Code Generator that maps grid 400kV, grid 275kV, grid 220kV and grid 132kV, using haversine. Published at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

700 lines of HTML from code-generator, in 1 file. Topic: Grid network and substations. Section 297 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. Substation Finder — Si Page geodesy · code-generator / apps/substation-finder/Si/index.html lines 1211–1910

Substation Finder — Si Page

A map page in Code Generator that maps grid 400kV, grid 275kV, grid 220kV and grid 132kV, using haversine. Published at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

geodesycode-generator / apps/substation-finder/Si/index.html · lines 1211–1910 of 5013 (continued from section 295) · Entry point · pattern enterFullscreen (shared by 2 files)

What it does
It maps grid 400kV, grid 275kV, grid 220kV and grid 132kV. Defines 104 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, enterFullscreen, exitFullscreen. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'substation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV, 275kV, 220kV, 132kV, 66kV, 11kV.
Inputs & outputs
In: GeoJSON file grid_400kv.geojson; GeoJSON file grid_275kv.geojson; GeoJSON file grid_220kv.geojson; GeoJSON file grid_132kv.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file grid_11kv_ukpn.geojson; GeoJSON file grid_substations.geojson; GeoJSON file power_plants.geojson. Out: JSON file manifest_v4.json; web page; interactive map. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 400kV, 275kV, 220kV, 132kV, 66kV, 11kV.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.
What it achieves
It normalizes status (`normalizeStatus`), toggles curtain (`toggleCurtain`) and gets radius (`getRadiusValue`). Its `snapLines` function gives line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged from line features and substation point features (VEDIC: snap line ends to substations). Its code works with 132 kV, 220 kV and 275 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
code-generator · apps/substation-finder/Si · page
VEDIC
SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
Uses
https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.css, https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.js, https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.css, https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.js, https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js
Used by
mentioned in Standalone (comment link)
Produces
deepFreeze, escapeHTML, normalizeStatus, enterFullscreen, exitFullscreen, toggleCurtain, getRadiusValue, validateRadiusInput, fmt, updateMeasureDisplay, updateMeasureLayers, clearMeasure
Defines here
deepFreeze, updateUIState, FetchQueue, fetchWithTimeout, fetchAndParseGeoJSON, snapLines, buildSearchButtons, flyToProject, searchProjects, buildDOM
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/index.html:1211-1910 · blob 4e9b8b6a923698ac72c91325688593fcae31ffb3 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
        'Technology Type',
        'Development Status (short)',
        'Installed Capacity (MWelec)',
        'X-coordinate',
        'Y-coordinate',
        'Operator (or Applicant)'
    ]

    OPTIONAL_COLUMNS = [
        'Mounting Type for Solar'
    ]

    def __init__(self, registry_path="config/registry.yaml"):
        print("📡 VENTUS REPD UPDATER v5.10 | BOOTING SYSTEM...")
        try:
            with open(registry_path, 'r') as f:
                self.config = yaml.safe_load(f)
        except FileNotFoundError:
            print(f"❌ ERROR: {registry_path} not found.")
            exit(1)
        self.output_dir   = "dist"
        self.raw_data_dir = "data"
        os.makedirs(self.output_dir,   exist_ok=True)
        os.makedirs(self.raw_data_dir, exist_ok=True)
        self.transformer = Transformer.from_crs("epsg:27700", "epsg:4326", always_xy=True)

    def validate_schema(self, df):
        cols = set(df.columns)
        missing_required = [c for c in self.REQUIRED_COLUMNS if c not in cols]
        missing_optional = [c for c in self.OPTIONAL_COLUMNS if c not in cols]
        if missing_required:
            print(f"❌ SCHEMA ERROR — missing required columns: {missing_required}")
            print(f"   Available columns: {sorted(cols)}")
            exit(1)
        if missing_optional:
            print(f"⚠️  Missing optional columns (degraded output): {missing_optional}")
        else:
            print(f"✅ Schema valid — all required and optional columns present")

    def discover_latest_url(self):
        print("🔍 Discovering latest REPD URL from Gov.uk...")
        try:
            r = requests.get(self.REPD_PAGE, timeout=30)
            r.raise_for_status()
            soup = BeautifulSoup(r.text, 'html.parser')
            for a in soup.find_all('a', href=True):
                href = a['href']
                if href.endswith('.csv') and 'repd' in href.lower():
                    url = href if href.startswith('http') else f"https://www.gov.uk{href}"
                    print(f"✅ Latest REPD URL: {url}")
                    return url
            print("⚠️ Could not find CSV link — falling back to registry URL")
            return None
        except Exception as e:
            print(f"⚠️ Discovery failed: {e} — falling back to registry URL")
            return None

    def already_current(self, url):
        manifest_path = f"{self.output_dir}/manifest_v4.json"
        if not os.path.exists(manifest_path):
            return False
        try:
            with open(manifest_path) as f:
                manifest = json.load(f)
            if manifest.get('source_url') == url:
                print("✅ REPD unchanged since last sync — skipping pipeline.")
                return True
        except Exception:
            pass
        return False

    def fetch_data(self, url):
        print(f"📥 FETCHING: {url}")
        try:
            r = requests.get(url, timeout=60)
            r.raise_for_status()
            path = f"{self.raw_data_dir}/latest_repd.csv"
            with open(path, 'wb') as f:
                f.write(r.content)
            return path
        except Exception as e:
            print(f"⚠️ FETCH FAILED: {e}")
            return None

    def classify_tech(self, tech_raw, mounting):
        """
        Substring matching throughout — immune to encoding artifacts.
        Hydrogen checked before hydro — no collision possible.
        """
        t  = tech_raw.strip()
        tl = t.lower()

        # --- Solar — mounting drives rooftop split ---
        if 'solar photovoltaic' in tl or 'solar pv' in tl:
            return 'solar_roof' if mounting == 'roof' else 'solar'

        # --- Wind ---
        if 'wind onshore' in tl or 'wind offshore' in tl or tl == 'wind':
            return 'wind'

        # --- Hydrogen — MUST be before hydro ---
        if tl == 'hydrogen' or 'fuel cell (hydrogen)' in tl:
            return 'hydrogen'

        # --- Hydro ---
        if 'large hydro' in tl or 'small hydro' in tl or 'pumped storage hydro' in tl:
            return 'hydro'

        # --- Compressed / Liquid Air Energy Storage ---
        if 'compressed air energy storage' in tl or 'liquid air energy storage' in tl:
            return 'caes'

        # --- Battery ---
        if tl == 'battery' or tl == 'battery storage':
            return 'bess'

        # --- Biomass family ---
        if any(x in tl for x in [
            'biomass', 'efw incineration', 'anaerobic digestion',
            'landfill gas', 'sewage sludge', 'co-firing',
            'energy from waste', 'incineration'
        ]):
            return 'biomass'

        # --- Advanced Conversion Technologies ---
        if 'advanced conversion' in tl or 'gasification' in tl or 'pyrolysis' in tl:
            return 'act'

        # --- Geothermal ---
        if 'geothermal' in tl or 'hot dry rocks' in tl:
            return 'geothermal'

        # --- Tidal / Wave ---
        if 'tidal' in tl or 'shoreline wave' in tl:
            return 'tidal'

        # --- Flywheel ---
        if 'flywheel' in tl:
            return 'flywheel'

        # --- Generic storage fallback ---
        if 'storage' in tl or 'battery' in tl:
            return 'bess'

        # --- Generic wind fallback ---
        if 'wind' in tl:
            return 'wind'

        return 'other'

    def refine_dataset(self, csv_path):
        print("🧪 REFINING MASTER DATASET...")
        df = pd.read_csv(csv_path, encoding='unicode_escape', on_bad_lines='skip', engine='python')
        df.columns = [c.strip() for c in df.columns]

        self.validate_schema(df)

        if 'Mounting Type for Solar' in df.columns:
            mounting_col = 'Mounting Type for Solar'
        elif 'Mounting Type' in df.columns:
            mounting_col = 'Mounting Type'
        else:
            mounting_col = None
            print("⚠️ No mounting type column found — all solar mapped to 'solar'")

        print(f"🔍 Mounting column: '{mounting_col}'")
        if mounting_col:
            print(f"🔍 Mounting values: {df[mounting_col].dropna().unique()}")
        print(f"🔍 Tech Types (all): {sorted(df['Technology Type'].dropna().unique())}")

        df['Development Status (short)'] = (
            df['Development Status (short)']
            .astype(str).str.strip().str.lower()
        )
        df = df[df['Development Status (short)'].isin(self.VIABLE_STATUSES)]
        print(f"🔍 Rows after status filter: {len(df)}")

        features = []
        skipped  = 0

        for _, row in df.iterrows():
            try:
                e = float(row['X-coordinate'])
                n = float(row['Y-coordinate'])
                if not e or not n or e == 0 or n == 0:
                    skipped += 1
                    continue

                lon, lat = self.transformer.transform(e, n)
                if not (isfinite(lon) and isfinite(lat)):
                    skipped += 1
                    continue

                if not (self.UK_LON_MIN < lon < self.UK_LON_MAX and
                        self.UK_LAT_MIN < lat < self.UK_LAT_MAX):
                    skipped += 1
                    continue

                tech_raw = str(row.get('Technology Type', '')).strip()
                mounting = ''
                if mounting_col:
                    mounting = str(row.get(mounting_col, '')).strip().lower()

                tech_map = self.classify_tech(tech_raw, mounting)

                try:
                    capacity = float(row.get('Installed Capacity (MWelec)', 0))
                    if not isfinite(capacity):
                        capacity = 0.0
                    if tech_map == 'solar_roof' and capacity > 50:
                        capacity = round(capacity / 1000, 4)
                    if tech_map == 'biomass' and capacity > 100:
                        capacity = round(capacity / 1000, 4)
                except (ValueError, TypeError):
                    capacity = 0.0

                features.append({
                    "type": "Feature",
                    "properties": {
                        "name":     str(row.get('Site Name', 'Unknown')),
                        "operator": str(row.get('Operator (or Applicant)', 'Unknown')).upper(),
                        "capacity": capacity,
                        "status":   str(row.get('Development Status (short)', '')).strip(),
                        "tech":     tech_map,
                        "raw_tech": tech_raw,
                        "mounting": mounting
                    },
                    "geometry": {
                        "type": "Point",
                        "coordinates": [round(lon, 6), round(lat, 6)]
                    }
                })

            except (ValueError, TypeError):
                skipped += 1
                continue

        print(f"⚠️  Skipped: {skipped}")
        tech_counts = {}
        for f in features:
            t = f['properties']['tech']
            tech_counts[t] = tech_counts.get(t, 0) + 1
        print(f"📊 Tech distribution: {tech_counts}")

        other_count = tech_counts.get('other', 0)
        if other_count > 0:
            other_techs = set(
                f['properties']['raw_tech'] for f in features
                if f['properties']['tech'] == 'other'
            )
            print(f"⚠️  {other_count} unmapped — raw tech values: {other_techs}")

        return {"type": "FeatureCollection", "features": features}

    def execute(self):
        for layer in self.config['layers']:
            if layer['id'] == 'repd' or layer['type'] == 'csv':

                url = self.discover_latest_url() or layer['url']

                if self.already_current(url):
                    return

                local_csv = self.fetch_data(url)
                if not local_csv:
                    return

                geojson = self.refine_dataset(local_csv)
                output = f"{self.output_dir}/repd_master.json"
                with open(output, 'w') as f:
                    json.dump(geojson, f)
                print(f"✅ MASTER SYNC: {len(geojson['features'])} assets.")

                manifest = {
                    "system":     "VENTUS_CORE",
                    "last_sync":  datetime.now().isoformat(),
                    "source_url": url,
                    "status":     "OPERATIONAL"
                }
                with open(f"{self.output_dir}/manifest_v4.json", 'w') as f:
                    json.dump(manifest, f, indent=2)

if __name__ == "__main__":
    REPDUpdater().execute()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>GlobalGrid2050 | Ventus Core</title>
    <link href="https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.css" rel="stylesheet" />
    <style>
        html, body { margin: 0; padding: 0; width: 100%; height: 100%; background: #000; font-family: 'Courier New', monospace; color: white; overflow: hidden; }
        .dashboard { display: flex; flex-direction: column; height: 100vh; height: 100dvh; width: 100vw; padding: 4px; gap: 4px; box-sizing: border-box; }
        #fatal-banner { display: none; position: fixed; top: 0; left: 0; width: 100%; background: #ff0000; color: #fff; text-align: center; padding: 10px; font-weight: bold; z-index: 9999; text-transform: uppercase; font-size: 12px; letter-spacing: 1px; }
        .hud-header { background: #0a0a0a; border: 1px solid #333; border-radius: 6px; padding: 6px 12px; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; }
        .hud-val { font-size: 16px; font-weight: bold; color: #00ffff; text-shadow: 0 0 5px #00ffff; }
        .ventus-brand { text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; line-height: 1.2; }
        .ventus-main { font-family: -apple-system, sans-serif; font-size: 17px; font-weight: 800; color: #fff; letter-spacing: 5px; text-transform: uppercase; margin-bottom: 2px; }
        .ventus-sub { font-family: -apple-system, sans-serif; font-size: 6.5px; color: #888; letter-spacing: 2px; text-transform: uppercase; }
        .map-container { position: relative; flex-grow: 1; min-height: 0; border: 1px solid #222; border-radius: 6px; overflow: hidden; background: #0b0e14; }
        #map { width: 100%; height: 100%; }
        .podcast-shoutout { position: absolute; bottom: 6px; right: 8px; font-family: -apple-system, sans-serif; font-size: 8px; color: #fff; opacity: 0.5; text-align: right; text-transform: uppercase; letter-spacing: 1px; pointer-events: none; z-index: 10; text-shadow: 1px 1px 2px #000; }
        .scada-wrapper { background: #050505; border: 1px solid #444; border-radius: 6px; padding: 12px; display: flex; flex-direction: column; flex-shrink: 0; max-height: 38vh; }
        .scada-brand { display: flex; align-items: center; gap: 8px; padding-bottom: 8px; margin-bottom: 8px; border-bottom: 1px solid #222; flex-shrink: 0; }
        .scada-brand-main { font-family: -apple-system, sans-serif; font-size: 11px; font-weight: 800; color: #fff; letter-spacing: 4px; text-transform: uppercase; }
        .scada-brand-sub { font-family: -apple-system, sans-serif; font-size: 6px; color: #555; letter-spacing: 2px; text-transform: uppercase; }
        .scada-brand-tag { margin-left: auto; font-family: 'Courier New', monospace; font-size: 7px; color: #333; text-transform: uppercase; letter-spacing: 1px; }
        .scada-keys { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 12px; overflow-y: auto; padding-bottom: 5px; }
        .key-group { border-left: 2px solid #333; padding-left: 10px; margin-bottom: 4px; }
        .key-title { font-size: 10px; color: #66ccff; text-transform: uppercase; margin-bottom: 6px; font-weight: bold; }
        .key-item { display: flex; align-items: center; gap: 8px; font-size: 13px; margin-bottom: 8px; cursor: pointer; }
        input[type="checkbox"], input[type="radio"] { transform: scale(1.3); margin-right: 4px; accent-color: #00ffff; }
        .maplibregl-popup-content { background: #000; color: #00ffff; border: 1px solid #444; font-family: monospace; font-size: 12px; padding: 8px; }
        .disclaimer-box { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; text-align: justify; font-size: 9px; line-height: 1.5; color: #666; margin-top: 10px; padding-top: 10px; border-top: 1px solid #222; user-select: none; pointer-events: none; flex-shrink: 0; }
        .custom-map-attrib { position: absolute; top: 10px; left: 10px; background: rgba(5, 5, 5, 0.7); color: #888; font-family: 'Courier New', monospace; font-size: 9px; border-radius: 4px; padding: 4px 8px; z-index: 10; border: 1px solid #333; pointer-events: auto; }
        .custom-map-attrib a { color: #00ffff; text-decoration: none; }
        .custom-map-attrib a:hover { text-decoration: underline; }
        .popup-search-btns { display: flex; gap: 6px; margin-top: 8px; }
        .popup-btn { flex: 1; padding: 5px 0; font-family: monospace; font-size: 11px; font-weight: bold; border: 1px solid #444; border-radius: 3px; cursor: pointer; text-align: center; text-decoration: none; display: block; transition: border-color 0.15s, color 0.15s; }
        .popup-btn-news { background: #0a0a0a; color: #ffae00; border-color: #ffae00; }
        .popup-btn-news:hover { background: #ffae00; color: #000; }
        .popup-btn-images { background: #0a0a0a; color: #00ffff; border-color: #00ffff; }
        .popup-btn-images:hover { background: #00ffff; color: #000; }
        .search-bar-wrapper { position: absolute; top: 46px; right: 10px; z-index: 20; display: flex; gap: 6px; }
        .search-input { background: rgba(5,5,5,0.85); border: 1px solid #444; border-radius: 4px; color: #00ffff; font-family: 'Courier New', monospace; font-size: 11px; padding: 5px 10px; width: 220px; outline: none; }
        .search-input::placeholder { color: #444; }
        .search-input:focus { border-color: #00ffff; }
        .search-btn { background: #0a0a0a; border: 1px solid #00ffff; border-radius: 4px; color: #00ffff; font-family: 'Courier New', monospace; font-size: 11px; padding: 5px 10px; cursor: pointer; }
        .search-btn:hover { background: #00ffff; color: #000; }
        .search-results { position: absolute; top: 36px; right: 0; background: #050505; border: 1px solid #333; border-radius: 4px; width: 300px; max-height: 220px; overflow-y: auto; z-index: 21; display: none; }
        .search-result-item { padding: 7px 10px; font-family: 'Courier New', monospace; font-size: 10px; color: #888; cursor: pointer; border-bottom: 1px solid #111; line-height: 1.5; }
        .search-result-item:hover { background: #111; color: #00ffff; }
        .search-result-item b { color: #ffcc00; }
        .search-no-results { padding: 8px 10px; font-family: 'Courier New', monospace; font-size: 10px; color: #444; }
    </style>
</head>
<body>

<div id="fatal-banner">CRITICAL ERROR: SYSTEM DEPENDENCIES FAILED TO LOAD</div>

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

    <div class="map-container">
        <div id="map"></div>
        <div class="custom-map-attrib">
            Data © <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener noreferrer">OpenStreetMap contributors | openstreetmap.org</a> | © CARTO
        </div>
        <div class="search-bar-wrapper">
            <div style="position:relative">
                <input class="search-input" id="search-input" type="text" placeholder="Search project name..." autocomplete="off" />
                <div class="search-results" id="search-results"></div>
            </div>
            <button class="search-btn" id="search-btn">GO</button>
        </div>
        <div class="podcast-shoutout">In support of The Future of Solar Photovoltaics podcast<br>&amp; all participants to date</div>
    </div>

    <div class="scada-wrapper">
        <div class="scada-brand">
            <div>
                <div class="scada-brand-main">Ventus</div>
                <div class="scada-brand-sub">Cables &amp; Connectivity&reg;</div>
            </div>
            <div class="scada-brand-tag">globalgrid2050.com | open infrastructure intelligence</div>
        </div>
        <div class="scada-keys" id="scada-ui-container"></div>
        <div class="disclaimer-box">
            This interface is based on publicly available and open source infrastructure data, including public energy datasets such as REPD where applicable. It is presented for analytical and visualisation purposes only and does not include live operational or other non public operational data.
        </div>
    </div>
</div>

<script src="https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.js"></script>
<script>
'use strict';

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

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

const GRID_CONFIG = deepFreeze([
    {
        group: "Topology (GeoJSON)",
        layers: [
            { id: "400",  label: "400kV", color: "#0054ff", type: "line", width: 2.5, url: "/grid_400kv.geojson", snap: true, preload: true },
            { id: "275",  label: "275kV", color: "#ff0000", type: "line", width: 2.0, url: "/grid_275kv.geojson", snap: true, preload: true },
            { id: "220",  label: "220kV", color: "#ff9900", type: "line", width: 1.8, url: "/grid_220kv.geojson", snap: true, preload: true },
            { id: "132",  label: "132kV", color: "#00cc00", type: "line", width: 1.5, url: "/grid_132kv.geojson", snap: true, preload: true },
            { id: "66",   label: "66kV",  color: "#b200ff", type: "line", width: 1.2, url: "/grid_66kv.geojson", snap: true, preload: true },
            { id: "subs", label: "Subs",  color: "#ffffff", type: "point", radius: 4.5, url: "/grid_substations.geojson", isSubs: true, preload: true }
        ]
    },
    {
        group: "Assets (GeoJSON)",
        layers: [
            { id: "nuc",  label: "Nuclear",   color: "#39ff14", type: "point", radius: 4.5, url: "/power_plants.geojson", filter: ['==', ['get', 'source'], 'nuclear'], preload: true },
            { id: "gas",  label: "Gas",       color: "#ff4500", type: "point", radius: 4.5, url: "/power_plants.geojson", filter: ['!=', ['get', 'source'], 'nuclear'], preload: true },
            { id: "ind",  label: "Industry",  color: "#ff6600", type: "point", radius: 4.5, url: "/industrial_offtakers.geojson", preload: true },
            { id: "dc",   label: "Data Ctrs", color: "#00ffff", type: "point", radius: 4.5, url: "/datacentres.geojson", preload: true },
            { id: "air",  label: "Airports",  color: "#ff00ff", type: "point", radius: 4.5, url: "/airports.geojson", preload: true },
            { id: "rail", label: "Railways",  color: "#ffd700", type: "point", radius: 4.5, url: "/railways.geojson", preload: true }
        ]
    },
    {
        group: "REPD (GeoJSON)",
        layers: [
            { id: "solar",      label: "Solar PV",                color: "#ffff00", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'solar'],      preload: false },
            { id: "solar_roof", label: "Solar Roof",              color: "#ffcc00", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'solar_roof'], preload: false },
            { id: "wind",       label: "Wind",                    color: "#00ffff", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'wind'],       preload: false },
            { id: "bess",       label: "Battery Storage",         color: "#ffae00", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'bess'],       preload: false },
            { id: "biomass",    label: "Biomass & EfW",           color: "#39ff14", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'biomass'],    preload: false },
            { id: "tidal",      label: "Tidal & Wave",            color: "#00bfff", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'tidal'],      preload: false },
            { id: "hydrogen",   label: "Hydrogen",                color: "#ffffff", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'hydrogen'],   preload: false },
            { id: "hydro",      label: "Hydro & Pumped Storage",  color: "#00aaff", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'hydro'],      preload: false },
            { id: "flywheel",   label: "Flywheel",                color: "#ff69b4", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'flywheel'],   preload: false },
            { id: "act",        label: "Advanced Conversion",     color: "#ff6600", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'act'],        preload: false },
            { id: "geothermal", label: "Geothermal",              color: "#ff3300", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'geothermal'], preload: false },
            { id: "caes",       label: "Compressed Air Storage",  color: "#88aaff", type: "point", radius: 8, url: "/dist/repd_master.json", filter: ['==', ['get', 'tech'], 'caes'],       preload: false }
        ]
    }
]);

const REPD_IDS = [
    'solar', 'solar_roof', 'wind', 'bess', 'biomass', 'tidal',
    'hydrogen', 'hydro', 'flywheel', 'act', 'geothermal', 'caes'
];

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

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

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

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

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

function updateUIState(id, state) {
    RUNTIME_STATE[id].status = state;
    const span = document.getElementById(`lbl-${id}`);
    if (span) {
        const baseText = span.getAttribute('data-base-label');
        span.innerText = `${baseText} [${state}]`;
        span.style.opacity = state === 'FAIL' ? '0.5' : '1';
    }
}

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

const networkQueue = new FetchQueue(4);
const urlCache = {};
let globalSubsData = null;

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

async function fetchAndParseGeoJSON(url) {
    if (urlCache[url]) return await urlCache[url];
    const promise = fetchWithTimeout(url)
        .then(res => res.json())
        .then(data => {
            if (!data || !Array.isArray(data.features)) {
                console.error(`[INVALID GEOJSON] ${url}`, data);
                return [];
            }
            console.log(`[DATA LOADED] ${url}: ${data.features.length} features`);
            return data.features;
        })
        .catch(err => {
            console.error(`[FETCH ERROR] ${url}`, err);
            throw err;
        });
    urlCache[url] = promise;
    return promise;
}

function snapLines(features, subs) {
    if (!subs || !subs.length) return features;
    const tol = 0.05, rad = Math.PI / 180;
    features.forEach(f => {
        const c = f.geometry && f.geometry.coordinates;
        if (!c || c.length < 2) return;
        [0, c.length - 1].forEach(i => {
            let best = c[i], min = Infinity;
            const latCos = Math.cos(c[i][1] * rad);
            subs.forEach(s => {
                const sc = s.geometry && s.geometry.coordinates;
                if (!sc) return;
                const dx = (c[i][0] - sc[0]) * latCos;
                const dy = (c[i][1] - sc[1]);
                const d = (dx * dx) + (dy * dy);
                if (d < min && d < tol * tol) { min = d; best = sc; }
            });
            c[i] = best;
        });
    });
    return features;
}

function buildSearchButtons(name, capacity, tech) {
    const threshold = SEARCH_THRESHOLD[tech] !== undefined ? SEARCH_THRESHOLD[tech] : 50;
    if (capacity < threshold) return '';
    const techTerms = {
        'solar':      'solar farm',
        'solar_roof': 'rooftop solar',
        'wind':       'wind farm',
        'bess':       'battery storage',
        'biomass':    'biomass plant',
        'tidal':      'tidal energy',
        'hydrogen':   'hydrogen plant',
        'hydro':      'hydro power',
        'flywheel':   'flywheel storage',
        'act':        'advanced conversion energy',
        'geothermal': 'geothermal energy',
        'caes':       'compressed air energy storage'
    };
    const term = techTerms[tech] || 'energy project';
    const q = encodeURIComponent(`${name} ${term} UK`);
    const newsUrl = `https://news.google.com/search?q=${q}`;
    const imgsUrl = `https://www.google.com/search?q=${q}&tbm=isch`;
    return `
        <div class="popup-search-btns">
            <a class="popup-btn popup-btn-news"   href="${newsUrl}" target="_blank" rel="noopener noreferrer">📰 NEWS</a>
            <a class="popup-btn popup-btn-images" href="${imgsUrl}" target="_blank" rel="noopener noreferrer">🖼 IMAGES</a>
        </div>`;
}

function flyToProject(feature) {
    const [lon, lat] = feature.geometry.coordinates;
    const p = feature.properties;
    const cap = p.capacity ? `${p.capacity} MW` : '';
    const mounting = p.mounting ? ` | ${p.mounting}` : '';
    map.flyTo({ center: [lon, lat], zoom: 12, duration: 1800, essential: true });
    setTimeout(() => {
        new maplibregl.Popup({ maxWidth: '300px' })
            .setLngLat([lon, lat])
            .setHTML(`
                <div style="font-family:monospace;background:#000;padding:6px">
                    <b style="color:#00ffff;font-size:13px">${p.name}</b><br>
                    <span style="color:#888">${p.raw_tech || p.tech}${mounting}</span><br>
                    <span style="color:#ffae00">${cap}</span>
                    <span style="color:#666"> | ${p.status}</span><br>
                    <span style="color:#555;font-size:10px">${p.operator}</span>
                    ${REPD_IDS.includes(p.tech) ? buildSearchButtons(p.name, parseFloat(p.capacity)||0, p.tech) : ''}
                </div>`)
            .addTo(map);
    }, 1900);
}

function searchProjects(query) {
    const resultsEl = document.getElementById('search-results');
    if (!query || query.length < 2) { resultsEl.style.display = 'none'; return; }
    const source = map.getSource('src-repd');
    if (!source || !source._data || !source._data.features || !source._data.features.length) {
        resultsEl.innerHTML = '<div class="search-no-results">Load a REPD layer first to enable search</div>';
        resultsEl.style.display = 'block';
        return;
    }
    const q = query.toLowerCase();
    const matches = source._data.features
        .filter(f => f.properties.name && f.properties.name.toLowerCase().includes(q))
        .sort((a, b) => (b.properties.capacity || 0) - (a.properties.capacity || 0))
        .slice(0, 12);
    if (!matches.length) {
        resultsEl.innerHTML = '<div class="search-no-results">No projects found</div>';
        resultsEl.style.display = 'block';
        return;
    }
    const techColours = {
        'solar': '#ffff00', 'solar_roof': '#ffcc00', 'wind': '#00ffff',
        'bess': '#ffae00', 'biomass': '#39ff14', 'tidal': '#00bfff',
        'hydrogen': '#ffffff', 'hydro': '#00aaff', 'flywheel': '#ff69b4',
        'act': '#ff6600', 'geothermal': '#ff3300', 'caes': '#88aaff'
    };
    resultsEl.innerHTML = matches.map((f, i) => {
        const p = f.properties;
        const cap = p.capacity ? ` — ${p.capacity} MW` : '';
        const col = techColours[p.tech] || '#888';
        return `<div class="search-result-item" data-idx="${i}">
            <b>${p.name}</b><span style="color:#555">${cap}</span><br>
            <span style="color:${col};font-size:9px">${p.raw_tech || p.tech}</span>
            <span style="color:#444;font-size:9px"> | ${p.status}</span>
        </div>`;
    }).join('');
    resultsEl.querySelectorAll('.search-result-item').forEach((el, i) => {
        el.addEventListener('click', () => {
            flyToProject(matches[i]);
            resultsEl.style.display = 'none';
            document.getElementById('search-input').value = matches[i].properties.name;
        });
    });
    resultsEl.style.display = 'block';
}

function buildDOM() {
    const container = document.getElementById('scada-ui-container');
    container.innerHTML = '';
    const fragment = document.createDocumentFragment();
    GRID_CONFIG.forEach(group => {
        const groupDiv = document.createElement('div');
        groupDiv.className = 'key-group';
        groupDiv.innerHTML = `<div class="key-title">${group.group}</div>`;
        group.layers.forEach(layer => {
            const label = document.createElement('label');
            label.className = 'key-item';
            const input = document.createElement('input');
            input.type = 'checkbox';
            input.dataset.layerId = layer.id;
            const span = document.createElement('span');
            span.id = `lbl-${layer.id}`;
            span.setAttribute('data-base-label', layer.label);
            span.style.color = layer.color;
            span.innerText = `${layer.label} [WAIT]`;
            label.appendChild(input);
            label.appendChild(document.createTextNode(' '));
            label.appendChild(span);
            groupDiv.appendChild(label);
        });
        fragment.appendChild(groupDiv);
    });
    const bmGroup = document.createElement('div');