GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-bess-topology-v7/gis-sld-financial-sandbox

GIS Single-Line Diagram (SLD) V5 UI (part 2)

A JavaScript file in GlobalGrid2050 covering Renewable Energy Planning Database (REPD) master and uses data from OpenStreetMap Nominatim. Served with the page at https://globalgrid2050.com/solar-bess-topology-v7/gis-sld-financial-sandbox/.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Solar and storage design. Section 100 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. GIS Single-Line Diagram (SLD) V5 UI electrical · globalgrid2050 / solar-bess-topology-v7/gis-sld-financial-sandbox/gis-sld-v5-ui.js lines 1–700

GIS Single-Line Diagram (SLD) V5 UI

A JavaScript file in GlobalGrid2050 covering Renewable Energy Planning Database (REPD) master and uses data from OpenStreetMap Nominatim. Served with the page at https://globalgrid2050.com/solar-bess-topology-v7/gis-sld-financial-sandbox/.

electricalglobalgrid2050 / solar-bess-topology-v7/gis-sld-financial-sandbox/gis-sld-v5-ui.js · lines 1–700 of 1484 · Entry point · pattern wireAtlasV8PipelineDropdownWithStatus (shared by 2 files)

What it does
It draws REPD master, grid 66kV, grid 132kV and grid 275kV. Defines 98 functions or classes, including switchTab, applyLogisticsPreset, autoFillBifacial, updateExportCableLengthDisplay, updateArrayRotationDisplay. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 400kV, 275kV, 132kV, 66kV.
Inputs & outputs
In: data source: OpenStreetMap Nominatim; JSON file repd_master.json; GeoJSON file grid_66kv.geojson; GeoJSON file grid_132kv.geojson; GeoJSON file grid_275kv.geojson; GeoJSON file grid_400kv.geojson; form fields (user input). Voltage levels named: 400kV, 275kV, 132kV, 66kV.
Downstream impact
Used directly by 3 files: Solar Battery Energy Storage System (BESS) Topology V7 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v7/gis-sld-financial-sandbox/); Solar Battery Energy Storage System (BESS) Topology V7 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (globalgrid2050, https://globalgrid2050.com/testcode/202609052011/layer-apps/solar-bess-topology-v7/gis-sld-financial-sandbox/); Solar Battery Energy Storage System (BESS) Topology V7 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (testcode). Reached from 145 other entry points, including Iterations — 43 Registry Growth Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/43-registry-growth/); Iterations — 47 Federation Honesty Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/47-federation-honesty/); Demonstration Videos (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v7/docs/demonstration-videos.html). It is itself an entry point, published at https://globalgrid2050.com/solar-bess-topology-v7/gis-sld-financial-sandbox/.
What it achieves
It applies logistics preset (`applyLogisticsPreset`), updates export cable length display (`updateExportCableLengthDisplay`) and updates array rotation display (`updateArrayRotationDisplay`). Defines `switchTab`, `applyLogisticsPreset`, `autoFillBifacial` and 95 more. Its code works with 132 kV, 275 kV and 400 kV. It reads `/dist/repd_master.json`. It responds to click, focus and input events.
Why it matters
Loaded by the GIS Single-Line Diagram (SLD) Financial Sandbox page at https://globalgrid2050.com/solar-bess-topology-v7/gis-sld-financial-sandbox/ and 2 other pages.
Application
globalgrid2050 · solar-bess-topology-v7/gis-sld-financial-sandbox · script
Uses
none found
Used by
loaded by Solar Battery Energy Storage System (BESS) Topology V7 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (script src), loaded by Solar Battery Energy Storage System (BESS) Topology V7 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (script src), loaded by Solar Battery Energy Storage System (BESS) Topology V7 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (script src), mentioned in Standalone (comment link)
Produces
switchTab, applyLogisticsPreset, autoFillBifacial, updateExportCableLengthDisplay, updateArrayRotationDisplay, rotateArrayBy, resetArrayRotation, getCurrentArrayCenter, getArrayNudgeStepKm, clearRouteAfterArrayShift, nudgeArray, updateCableRouteStatus
Defines here
switchTab, applyLogisticsPreset, autoFillBifacial, updateExportCableLengthDisplay, updateArrayRotationDisplay, rotateArrayBy, resetArrayRotation, getCurrentArrayCenter, getArrayNudgeStepKm, clearRouteAfterArrayShift, nudgeArray, updateCableRouteStatus, injectExportCableLengthControl, redrawIfTopologyExists, setArrayMoveStatus, toggleArrayMoveMode, resetArrayLocation, placeArrayAtMapPoint, toggleCablePinMode, commitCablePinRoute, undoCablePin, clearCableRoute, addCableRoutePin, startCableRouteMode, finishCableRouteMode, addCableRouteWaypoint, searchLocation, triggerDrawAtCenter, gisSearchEscape, gisSearchPick
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-bess-topology-v7/gis-sld-financial-sandbox/gis-sld-v5-ui.js:1-700 · blob 71064ce4f68b527515dcd3f09e6b9697ef26bef3 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
"use strict";

// TAB SWITCHING
// ============================================================
function switchTab(tab) {
    state.activeTab = tab;
    $("tabbtn_string")?.classList.toggle("active", tab === "string");
    $("tabbtn_central")?.classList.toggle("active", tab === "central");
    $("string_tab")?.classList.toggle("active", tab === "string");
    $("central_tab")?.classList.toggle("active", tab === "central");
    $("btn_draw")?.classList.toggle("central", tab === "central");
    document.querySelectorAll(".central-only").forEach(el => {
        el.style.display = tab === "central" ? "flex" : "none";
    });
    updateLegend();
    syncMapSizeInputFromActiveTab?.();
    if (state.activeDrawCenter) computeAndDraw();
    else recalcAll();
}

// ============================================================
// LOGISTICS PRESET
// ============================================================
function applyLogisticsPreset(val, suffix) {
    const preset = CONSTANTS.LOGISTICS_PRESETS[val];
    if (!preset) return;
    const pEl = $("mods_pallet" + suffix);
    const cEl = $("mods_container" + suffix);
    if (pEl) pEl.value = preset.pallet;
    if (cEl) cEl.value = preset.container;
    recalcAll();
}

// ============================================================
// BIFACIAL AUTO-FILL
// ============================================================
function autoFillBifacial(gcrVal, targetId) {
    const bifacial = CONSTANTS.BIFACIAL_BY_GCR[gcrVal] ?? 0;
    const el = $(targetId);
    if (el) {
        el.value = bifacial;
        el.dispatchEvent(new Event("input", { bubbles: true }));
    }
}

// ============================================================
// SAFE EXPORT CABLE LENGTH CONTROL
// ============================================================
function updateExportCableLengthDisplay() {
    const el = $("out_export_cable_length_km");
    if (!el) return;
    const km = Number.isFinite(state.exportCableLengthKm) ? state.exportCableLengthKm : 0;
    el.textContent = km.toFixed(3) + " km";
}

function updateArrayRotationDisplay() {
    const el = $("out_array_rotation_deg");
    if (!el) return;
    const deg = Number.isFinite(state.arrayRotationDeg) ? state.arrayRotationDeg : 0;
    el.textContent = (((deg % 360) + 360) % 360).toFixed(0) + "°";
}

function rotateArrayBy(deltaDeg) {
    state.arrayRotationDeg = (((state.arrayRotationDeg || 0) + deltaDeg) % 360 + 360) % 360;
    state.cableRoutePins = [];
    state.cableRouteCommitted = false;
    state.cableRouteWaypoints = [];
    state.suppressNextMapFit = true;
    updateArrayRotationDisplay();
    redrawIfTopologyExists();
}

function resetArrayRotation() {
    state.arrayRotationDeg = 0;
    state.cableRoutePins = [];
    state.cableRouteCommitted = false;
    state.cableRouteWaypoints = [];
    state.suppressNextMapFit = true;
    updateArrayRotationDisplay();
    redrawIfTopologyExists();
}

function getCurrentArrayCenter() {
    if (Array.isArray(state.arrayOverrideCenter)) return state.arrayOverrideCenter;
    const boundary = state.currentGeoJSON?.features?.find(f => f.properties?.type === "array_boundary");
    if (!boundary || typeof turf === "undefined") return null;
    try {
        return turf.centroid(boundary).geometry.coordinates;
    } catch (err) {
        console.warn("Array centroid unavailable", err);
        return null;
    }
}

function getArrayNudgeStepKm() {
    const el = $("array_nudge_step_m");
    const metres = el ? parseFloat(el.value) : 25;
    const safeMetres = Number.isFinite(metres) && metres > 0 ? metres : 25;
    return safeMetres / 1000;
}

function clearRouteAfterArrayShift() {
    state.cableRoutePins = [];
    state.cableRouteCommitted = false;
    state.cableRouteWaypoints = [];
    state.cableRoutePinMode = false;
}

function nudgeArray(bearingDeg) {
    if (!state.activeDrawCenter) {
        setArrayMoveStatus("Draw a grid first, then nudge the array.", false);
        return;
    }
    const center = getCurrentArrayCenter();
    if (!center) {
        setArrayMoveStatus("Array centre unavailable. Draw the grid again.", false);
        return;
    }
    const moved = turf.destination(turf.point(center), getArrayNudgeStepKm(), bearingDeg, { units: "kilometers" }).geometry.coordinates;
    state.arrayOverrideCenter = moved;
    state.arrayMoveMode = false;
    state.suppressNextMapFit = true;
    clearRouteAfterArrayShift();
    setArrayMoveStatus("Array nudged. Grid point stayed fixed. Route pins cleared because the customer substation moved.", false);
    redrawIfTopologyExists();
}

function updateCableRouteStatus() {
    const el = $("cable_route_status");
    if (!el) return;
    const count = Array.isArray(state.cableRoutePins) ? state.cableRoutePins.length : 0;
    if (state.cableRoutePinMode) {
        el.textContent = "Pin mode active. Click the map to drop pseudo pylon pins. Pins: " + count;
        el.style.color = "#ff9900";
    } else if (state.cableRouteCommitted && count > 0) {
        el.textContent = "Pinned cable route drawn through " + count + " pins. Atlas haversine length is live.";
        el.style.color = "#00ff88";
    } else if (count > 0) {
        el.textContent = count + " pins dropped. Click Draw Cable to render route through pins.";
        el.style.color = "#ff9900";
    } else {
        el.textContent = "No pins. Export cable is direct until pins are dropped and drawn.";
        el.style.color = "var(--muted)";
    }
}

function injectExportCableLengthControl() {
    if ($("layout_export_extra_km")) return;

    const drawBtn = $("btn_draw");
    if (!drawBtn || !drawBtn.parentNode) return;

    const box = document.createElement("div");
    box.className = "stat-box";
    box.id = "export_cable_length_box";
    box.style.borderColor = "#00ffff";
    box.style.background = "rgba(0, 255, 255, 0.05)";
    box.style.marginBottom = "15px";
    box.innerHTML = `
        <h3 style="margin-top:0;color:#00ffff;border-bottom-color:#00ffff;">Grid Connection Length</h3>
        <div class="stat-row"><span>Live Export Cable Length:</span><span class="stat-val cyan" id="out_export_cable_length_km">0.000 km</span></div>
        <div class="stat-row"><span>Array Rotation:</span><span class="stat-val orange" id="out_array_rotation_deg">0°</span></div>
        <div class="input-group"><label>Export Cable Extra Length km</label><input type="number" id="layout_export_extra_km" value="0" step="0.05" min="-0.2"></div>
        <div style="font-size:10px;color:var(--muted);line-height:1.4;margin-top:6px;">
            Moves the whole array further from or closer to the point of connection along the existing axis. Pin routing measures the final cable route using Atlas style haversine maths.
        </div>
        <div style="border-top:1px dashed #333;margin:8px 0;"></div>
        <button class="btn" id="btn_rotate_left_30" style="background:#222;color:#fff;">Rotate Left 30°</button>
        <button class="btn" id="btn_rotate_right_30" style="margin-top:6px;background:#222;color:#fff;">Rotate Right 30°</button>
        <button class="btn" id="btn_rotate_right_90" style="margin-top:6px;background:#ff9900;color:#000000;">Rotate 90°</button>
        <button class="btn" id="btn_reset_rotation" style="margin-top:6px;">Reset Rotation</button>
        <div style="font-size:10px;color:var(--muted);line-height:1.4;margin-top:6px;">
            Rotation keeps the grid point fixed and redraws the export cable. Route pins are cleared when rotation changes.
        </div>
        <div style="border-top:1px dashed #333;margin:8px 0;"></div>
        <button class="btn" id="btn_pick_array" style="margin-top:8px;background:#00ffff;color:#001111;">Pick Up Array</button>
        <button class="btn" id="btn_reset_array_move" style="margin-top:6px;">Reset Array Location</button>
        <div class="input-group" style="margin-top:8px;"><label>Fine Nudge Step metres</label><input type="number" id="array_nudge_step_m" value="25" step="5" min="1"></div>
        <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px;margin-top:8px;align-items:center;">
            <span></span><button class="btn" id="btn_nudge_up" style="background:#222;color:#fff;padding:8px;">↑</button><span></span>
            <button class="btn" id="btn_nudge_left" style="background:#222;color:#fff;padding:8px;">←</button><button class="btn" id="btn_nudge_down" style="background:#222;color:#fff;padding:8px;">↓</button><button class="btn" id="btn_nudge_right" style="background:#222;color:#fff;padding:8px;">→</button>
        </div>
        <div id="array_move_status" style="font-size:10px;color:var(--muted);line-height:1.4;margin-top:6px;">
            Pick Up Array keeps the grid point fixed. Use arrows for fine field fitting.
        </div>
        <div style="border-top:1px dashed #333;margin:8px 0;"></div>
        <button class="btn" id="btn_drop_cable_pins" style="background:#ff9900;color:#000000;">Drop Cable Pins</button>
        <button class="btn" id="btn_draw_cable_route" style="margin-top:6px;background:#00ff88;color:#001111;">Draw Cable Through Pins</button>
        <button class="btn" id="btn_undo_cable_pin" style="margin-top:6px;">Undo Last Pin</button>
        <button class="btn" id="btn_clear_cable_route" style="margin-top:6px;">Clear Pins and Route</button>
        <div id="cable_route_status" style="font-size:10px;color:var(--muted);line-height:1.4;margin-top:6px;">
            No pins. Export cable is direct until pins are dropped and drawn.
        </div>
    `;

    drawBtn.parentNode.insertBefore(box, drawBtn);
    updateExportCableLengthDisplay();
    updateArrayRotationDisplay();
    updateCableRouteStatus();
}

function redrawIfTopologyExists() {
    if (state.activeDrawCenter) computeAndDraw();
    else recalcAll();
}

function setArrayMoveStatus(text, active = false) {
    const el = $("array_move_status");
    if (el) {
        el.textContent = text;
        el.style.color = active ? "#00ffff" : "var(--muted)";
    }
    const btn = $("btn_pick_array");
    if (btn) {
        btn.textContent = active ? "Click Map to Place" : "Pick Up Array";
        btn.style.background = active ? "#ff9900" : "#00ffff";
        btn.style.color = active ? "#000000" : "#001111";
    }
}

function toggleArrayMoveMode() {
    if (!state.activeDrawCenter) {
        setArrayMoveStatus("Draw a grid first, then pick up the array.", false);
        return;
    }
    state.cableRoutePinMode = false;
    state.arrayMoveMode = !state.arrayMoveMode;
    setArrayMoveStatus(
        state.arrayMoveMode ? "Move mode active. Click the map where the array centre should move." : "Move mode cancelled.",
        state.arrayMoveMode
    );
    updateCableRouteStatus();
}

function resetArrayLocation() {
    state.arrayMoveMode = false;
    state.arrayOverrideCenter = null;
    clearRouteAfterArrayShift();
    state.suppressNextMapFit = true;
    setArrayMoveStatus("Array reset to calculated default position.", false);
    redrawIfTopologyExists();
}

function placeArrayAtMapPoint(e) {
    if (!state.arrayMoveMode) return;
    if (!e || !e.lngLat) return;
    state.arrayOverrideCenter = [e.lngLat.lng, e.lngLat.lat];
    state.arrayMoveMode = false;
    state.suppressNextMapFit = true;
    clearRouteAfterArrayShift();
    setArrayMoveStatus("Array moved. Grid point stayed fixed and export cable length recalculated.", false);
    computeAndDraw();
}

function toggleCablePinMode() {
    if (!state.activeDrawCenter) {
        updateCableRouteStatus();
        return;
    }
    state.arrayMoveMode = false;
    state.cableRoutePinMode = !state.cableRoutePinMode;
    state.suppressNextMapFit = true;
    updateCableRouteStatus();
    redrawIfTopologyExists();
}

function commitCablePinRoute() {
    state.cableRoutePinMode = false;
    state.cableRouteCommitted = Array.isArray(state.cableRoutePins) && state.cableRoutePins.length > 0;
    updateCableRouteStatus();
    redrawIfTopologyExists();
}

function undoCablePin() {
    if (!Array.isArray(state.cableRoutePins) || state.cableRoutePins.length === 0) return;
    state.cableRoutePins.pop();
    state.cableRouteCommitted = false;
    state.suppressNextMapFit = true;
    updateCableRouteStatus();
    redrawIfTopologyExists();
}

function clearCableRoute() {
    state.cableRoutePinMode = false;
    state.cableRoutePins = [];
    state.cableRouteCommitted = false;
    state.cableRouteWaypoints = [];
    updateCableRouteStatus();
    redrawIfTopologyExists();
}

function addCableRoutePin(e) {
    if (!state.cableRoutePinMode) return;
    if (!e || !e.lngLat) return;
    state.cableRoutePins.push([e.lngLat.lng, e.lngLat.lat]);
    state.cableRouteCommitted = false;
    state.suppressNextMapFit = true;
    updateCableRouteStatus();
    redrawIfTopologyExists();
}

// Legacy wrappers retained so old references do not break.
function startCableRouteMode() { toggleCablePinMode(); }
function finishCableRouteMode() { commitCablePinRoute(); }
function addCableRouteWaypoint(e) { addCableRoutePin(e); }

// ============================================================
// LOCATION SEARCH
// ============================================================
async function searchLocation() {
    const q = $("loc_search")?.value;
    if (!q) return;
    try {
        const res = await fetch(`https://nominatim.openstreetmap.org/search?format=json&limit=1&q=${encodeURIComponent(q)}`);
        const data = await res.json();
        if (data && data.length > 0) {
            map.flyTo({ center: [parseFloat(data[0].lon), parseFloat(data[0].lat)], zoom: 14 });
        }
    } catch (e) {
        console.error("Geocoding failed:", e);
    }
}

// ============================================================
// DRAW BUTTON
// ============================================================
function triggerDrawAtCenter() {
    if (!map) return;
    state.selectedSubstation = null;
    state.activeDrawCenter = [map.getCenter().lng, map.getCenter().lat];
    state.arrayOverrideCenter = null;
    state.arrayMoveMode = false;
    state.cableRoutePinMode = false;
    state.cableRoutePins = [];
    state.cableRouteCommitted = false;
    computeAndDraw();
    updateSelectedSubstationDisplay();
    setArrayMoveStatus("Grid drawn. Use Pick Up Array or nudge arrows to relocate the array while the grid point stays fixed.", false);
    updateCableRouteStatus();
}



// ============================================================
// GIS MAP SEARCH: OPERATING ASSETS AND SUBSTATIONS
// ============================================================
let gisSearchReady = false;
let gisAssetSearchIndex = [];
let gisSubstationSearchIndex = [];

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

function gisSearchPick(prop, keys, fallback = "") {
    for (const key of keys) {
        if (prop && prop[key] !== undefined && prop[key] !== null && String(prop[key]).trim() !== "") return prop[key];
    }
    return fallback;
}

function gisSearchValidPoint(feature) {
    return feature && feature.geometry && feature.geometry.type === "Point" && Array.isArray(feature.geometry.coordinates);
}

async function buildGisSearchIndexes() {
    if (gisSearchReady) return;
    try {
        const [repdRes, subsRes] = await Promise.all([
            fetch("/dist/repd_master.json", { cache: "no-cache" }),
            fetch(SUBSTATIONS_URL, { cache: "no-cache" })
        ]);

        const repd = repdRes.ok ? await repdRes.json() : { features: [] };
        const subsRaw = subsRes.ok ? await subsRes.json() : { features: [] };
        const subs = normaliseSubstations?.(subsRaw) || { features: [] };

        gisAssetSearchIndex = (repd.features || [])
            .filter(gisSearchValidPoint)
            .filter(f => {
                const p = f.properties || {};
                return String(p.status || "").toLowerCase() === "operational" &&
                    (["solar", "bess"].includes(String(p.tech || "")) || ["Wind Onshore", "Wind Offshore"].includes(String(p.raw_tech || "")));
            })
            .map(f => {
                const p = f.properties || {};
                const name = gisSearchPick(p, ["name", "project", "site", "Site Name"], "Operating asset");
                const tech = gisSearchPick(p, ["raw_tech", "tech"], "Unknown");
                const capacity = Number(gisSearchPick(p, ["capacity", "capacity_mw"], 0)) || 0;
                return {
                    kind: "asset",
                    feature: f,
                    name,
                    tech,
                    capacity,
                    label: `${name} ${tech} ${capacity} MW`.toLowerCase()
                };
            });

        gisSubstationSearchIndex = (subs.features || [])
            .filter(gisSearchValidPoint)
            .map(f => {
                const p = f.properties || {};
                const name = gisSearchPick(p, ["name_clean", "name", "Name", "substation", "Substation"], "Substation");
                const voltage = gisSearchPick(p, ["voltage_clean", "voltage", "Voltage", "kv", "kV"], "Unknown");
                return {
                    kind: "substation",
                    feature: f,
                    name,
                    voltage,
                    capacity: 0,
                    label: `${name} ${voltage} substation`.toLowerCase()
                };
            });

        gisSearchReady = true;
    } catch (err) {
        console.error("GIS search index failed", err);
        setFetchStatus?.("Search index unavailable", true);
    }
}

function gisSearchResultsEl() {
    return $("gis_search_results");
}

function hideGisSearchResults() {
    const el = gisSearchResultsEl();
    if (el) el.style.display = "none";
}

function showGisSearchResults(html) {
    const el = gisSearchResultsEl();
    if (!el) return;
    el.innerHTML = html;
    el.style.display = "block";
}

function renderGisSearchResults(query) {
    const q = String(query || "").trim().toLowerCase();
    if (q.length < 2) {
        hideGisSearchResults();
        return;
    }

    const assetMatches = gisAssetSearchIndex
        .filter(item => item.label.includes(q))
        .sort((a, b) => b.capacity - a.capacity)
        .slice(0, 8);
    const subMatches = gisSubstationSearchIndex
        .filter(item => item.label.includes(q))
        .slice(0, 8);
    const matches = [...assetMatches, ...subMatches].slice(0, 12);

    if (!matches.length) {
        showGisSearchResults('<div class="gis-search-result-empty">No sites or substations found</div>');
        return;
    }

    showGisSearchResults(matches.map((item, idx) => {
        const meta = item.kind === "asset" ? `${gisSearchEscape(item.tech)} · ${item.capacity || "n/a"} MW` : `Substation · ${gisSearchEscape(item.voltage)}`;
        const cls = item.kind === "asset" ? "asset" : "substation";
        return `<button class="gis-search-result ${cls}" data-gis-search-idx="${idx}">
            <strong>${gisSearchEscape(item.name)}</strong>
            <span>${meta}</span>
        </button>`;
    }).join(""));

    const el = gisSearchResultsEl();
    if (!el) return;
    el.querySelectorAll("[data-gis-search-idx]").forEach((btn, idx) => {
        btn.addEventListener("click", () => flyToGisSearchItem(matches[idx]));
    });
}

function flyToGisSearchItem(item) {
    if (!map || !item || !gisSearchValidPoint(item.feature)) return;
    const coords = item.feature.geometry.coordinates.slice();
    map.flyTo({ center: coords, zoom: item.kind === "asset" ? 11.5 : 13.5, duration: 1200, essential: true });
    hideGisSearchResults();
    const input = $("gis_search_input");
    if (input) input.value = item.name;

    setTimeout(() => {
        if (item.kind === "asset") {
            const p = item.feature.properties || {};
            const name = gisSearchPick(p, ["name", "project", "site", "Site Name"], "Operating asset");
            const tech = gisSearchPick(p, ["raw_tech", "tech"], "Unknown technology");
            const status = gisSearchPick(p, ["status"], "Unknown status");
            const capacity = gisSearchPick(p, ["capacity", "capacity_mw"], "n/a");
            showPopup(coords, `
                <div style="margin-bottom:5px;color:#00ff88;font-weight:bold;font-size:13px;text-transform:uppercase;">Operating Asset</div>
                <div class="popup-row"><span>Name:</span><span class="popup-val" style="color:#fff;">${gisSearchEscape(name)}</span></div>
                <div class="popup-row"><span>Technology:</span><span class="popup-val" style="color:#fff;">${gisSearchEscape(tech)}</span></div>
                <div class="popup-row"><span>Status:</span><span class="popup-val" style="color:#fff;">${gisSearchEscape(status)}</span></div>
                <div class="popup-row"><span>Capacity:</span><span class="popup-val" style="color:#fff;">${gisSearchEscape(capacity)} MW</span></div>
            `);
        } else {
            const p = item.feature.properties || {};
            const name = gisSearchPick(p, ["name_clean", "name", "Name", "substation", "Substation"], "Substation");
            const voltage = gisSearchPick(p, ["voltage_clean", "voltage", "Voltage", "kv", "kV"], "Unknown");
            showPopup(coords, `
                <div style="margin-bottom:5px;color:#ff3333;font-weight:bold;font-size:13px;text-transform:uppercase;">Substation</div>
                <div class="popup-row"><span>Name:</span><span class="popup-val" style="color:#fff;">${gisSearchEscape(name)}</span></div>
                <div class="popup-row"><span>Voltage:</span><span class="popup-val" style="color:#fff;">${gisSearchEscape(voltage)}</span></div>
                <div class="popup-row"><span>Lon:</span><span class="popup-val" style="color:#fff;">${Number(coords[0]).toFixed(6)}</span></div>
                <div class="popup-row"><span>Lat:</span><span class="popup-val" style="color:#fff;">${Number(coords[1]).toFixed(6)}</span></div>
            `);
        }
    }, 1250);
}

async function wireGisMapSearch() {
    const input = $("gis_search_input");
    const btn = $("gis_search_btn");
    if (!input || !btn) return;

    input.addEventListener("focus", buildGisSearchIndexes);
    input.addEventListener("input", async () => {
        await buildGisSearchIndexes();
        renderGisSearchResults(input.value);
    });
    input.addEventListener("keydown", async e => {
        if (e.key === "Enter") {
            await buildGisSearchIndexes();
            const first = gisSearchResultsEl()?.querySelector(".gis-search-result");
            if (first) first.click();
            else renderGisSearchResults(input.value);
        }
        if (e.key === "Escape") hideGisSearchResults();
    });
    btn.addEventListener("click", async () => {
        await buildGisSearchIndexes();
        const first = gisSearchResultsEl()?.querySelector(".gis-search-result");
        if (first) first.click();
        else renderGisSearchResults(input.value);
    });
    document.addEventListener("click", e => {
        const wrap = $("gis_map_search");
        if (wrap && !wrap.contains(e.target)) hideGisSearchResults();
    });
}


// ============================================================
// V7 SITE INTELLIGENCE PANEL
// ============================================================
const siteIntelData = {
    ready: false,
    loading: false,
    assets: [],
    substations: [],
    grid: {
        "66 kV": [],
        "132 kV": [],
        "275 kV": [],
        "400 kV": []
    }
};

const siteIntelGridUrls = {
    "66 kV": "/repd_grid_atlasv8/data/grid_66kv.geojson",
    "132 kV": "/repd_grid_atlasv8/data/grid_132kv.geojson",
    "275 kV": "/repd_grid_atlasv8/data/grid_275kv.geojson",
    "400 kV": "/repd_grid_atlasv8/data/grid_400kv.geojson"
};

function siteIntelPick(prop, keys, fallback = "") {
    for (const key of keys) {
        if (prop && prop[key] !== undefined && prop[key] !== null && String(prop[key]).trim() !== "") return prop[key];
    }
    return fallback;
}

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

function siteIntelValidPoint(feature) {
    return feature && feature.geometry && feature.geometry.type === "Point" && Array.isArray(feature.geometry.coordinates);
}

function siteIntelFeatureCollection(raw) {
    if (!raw) return { type: "FeatureCollection", features: [] };
    if (raw.type === "FeatureCollection" && Array.isArray(raw.features)) return raw;
    if (Array.isArray(raw)) return { type: "FeatureCollection", features: raw };
    return { type: "FeatureCollection", features: [] };
}

function siteIntelFlattenLines(features) {
    const lines = [];
    (features || []).forEach(feature => {
        if (!feature || !feature.geometry) return;
        const prop = feature.properties || {};
        if (feature.geometry.type === "LineString") {
            lines.push({ type: "Feature", geometry: feature.geometry, properties: prop });
        } else if (feature.geometry.type === "MultiLineString") {
            feature.geometry.coordinates.forEach(coords => {
                lines.push({ type: "Feature", geometry: { type: "LineString", coordinates: coords }, properties: prop });
            });
        }
    });
    return lines;
}

function showSiteIntelPanel(html) {
    const panel = $("site_intel_panel");
    const body = $("site_intel_body");
    if (!panel || !body) return;
    body.innerHTML = html;
    panel.classList.remove("collapsed");
}

function hideSiteIntelPanel() {
    const panel = $("site_intel_panel");
    if (panel) panel.classList.add("collapsed");
}

async function loadSiteIntelData() {
    if (siteIntelData.ready || siteIntelData.loading) return;
    siteIntelData.loading = true;

    try {
        const [repdRes, subsRes, ...gridResponses] = await Promise.all([
            fetch("/dist/repd_master.json", { cache: "no-cache" }),
            fetch(SUBSTATIONS_URL, { cache: "no-cache" }),
            fetch(siteIntelGridUrls["66 kV"], { cache: "no-cache" }),
            fetch(siteIntelGridUrls["132 kV"], { cache: "no-cache" }),
            fetch(siteIntelGridUrls["275 kV"], { cache: "no-cache" }),
            fetch(siteIntelGridUrls["400 kV"], { cache: "no-cache" })
        ]);

        const repd = repdRes.ok ? await repdRes.json() : { features: [] };
        const subsRaw = subsRes.ok ? await subsRes.json() : { features: [] };
        const subs = typeof normaliseSubstations === "function" ? normaliseSubstations(subsRaw) : siteIntelFeatureCollection(subsRaw);
        const gridKeys = ["66 kV", "132 kV", "275 kV", "400 kV"];

        siteIntelData.assets = (siteIntelFeatureCollection(repd).features || [])
            .filter(siteIntelValidPoint)
            .filter(feature => {
                const p = feature.properties || {};
                const status = String(siteIntelPick(p, ["status", "Status"], "")).toLowerCase();
                const tech = String(siteIntelPick(p, ["tech"], "")).toLowerCase();
                const rawTech = String(siteIntelPick(p, ["raw_tech", "Technology Type"], ""));
                return status === "operational" && (tech === "solar" || tech === "bess" || rawTech === "Wind Onshore" || rawTech === "Wind Offshore");
            });

        siteIntelData.substations = (subs.features || []).filter(siteIntelValidPoint);

        for (let i = 0; i < gridKeys.length; i++) {
            const key = gridKeys[i];
            const res = gridResponses[i];
            const raw = res && res.ok ? await res.json() : { features: [] };
            siteIntelData.grid[key] = siteIntelFlattenLines(siteIntelFeatureCollection(raw).features);
        }

        siteIntelData.ready = true;
    } catch (err) {
        console.error("Site intelligence data load failed", err);
        showSiteIntelPanel(`<div class="site-intel-warning">Site intelligence data unavailable: ${siteIntelEscape(err.message || err)}</div>`);
    } finally {
        siteIntelData.loading = false;
    }
}

function siteIntelAssetGroup(feature) {
    const p = feature.properties || {};
    const tech = String(siteIntelPick(p, ["tech"], "")).toLowerCase();
    const rawTech = String(siteIntelPick(p, ["raw_tech", "Technology Type"], ""));
    if (tech === "solar") return "Operating Solar PV";
    if (tech === "bess") return "Operating Battery Storage";
    if (rawTech === "Wind Onshore") return "Operating Onshore Wind";
    if (rawTech === "Wind Offshore") return "Operating Offshore Wind";
    return "Operating Asset";
}

function nearestPointFeature(point, features, predicate) {
    let best = null;
    (features || []).forEach(feature => {
        if (!siteIntelValidPoint(feature)) return;
        if (predicate && !predicate(feature)) return;
        const d = turf.distance(point, turf.point(feature.geometry.coordinates), { units: "kilometers" });
        if (!best || d < best.distanceKm) best = { feature, distanceKm: d };
    });
    return best;
}

function nearestLineFeature(point, features) {
    let best = null;
    (features || []).forEach(feature => {