GLOBALGRID2050 / EXPLORE CODE

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

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

A JavaScript file in GlobalGrid2050 that maps Renewable Energy Planning Database (REPD) master and grid 66kV, using haversine, and uses data from OpenStreetMap Nominatim. Served with the page at https://globalgrid2050.com/solar-bess-topology-v8/bess-gis-sld-financial-sandbox/.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Solar and storage design. Section 110 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-v8/bess-gis-sld-financial-sandbox/gis-sld-v5-ui.js lines 701–1400

GIS Single-Line Diagram (SLD) V5 UI

A JavaScript file in GlobalGrid2050 that maps Renewable Energy Planning Database (REPD) master and grid 66kV, using haversine, and uses data from OpenStreetMap Nominatim. Served with the page at https://globalgrid2050.com/solar-bess-topology-v8/bess-gis-sld-financial-sandbox/.

electricalglobalgrid2050 / solar-bess-topology-v8/bess-gis-sld-financial-sandbox/gis-sld-v5-ui.js · lines 701–1400 of 1667 (continued from section 109) · Not reached from any entry point (candidate for review) · pattern wireAtlasV8PipelineDropdownWithStatus (shared by 2 files)

What it does
It maps REPD master, grid 66kV, grid 132kV and grid 275kV. Defines 116 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). Out: GeoJSON file v8-bess-layout.geojson; downloaded file v8-bess-layout.geojson. Voltage levels named: 400kV, 275kV, 132kV, 66kV.
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 113 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
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-bess-topology-v8/bess-gis-sld-financial-sandbox · script
Uses
none found
Used by
none found
Produces
switchTab, applyLogisticsPreset, autoFillBifacial, updateExportCableLengthDisplay, updateArrayRotationDisplay, rotateArrayBy, resetArrayRotation, getCurrentArrayCenter, getArrayNudgeStepKm, clearRouteAfterArrayShift, nudgeArray, updateCableRouteStatus
Defines here
formatKm, formatCapacity, assetName, substationName, substationVoltage, siteIntelRow, siteIntelOpportunityNotes, inspectSiteIntelligenceAt, addAssetRow, wireSiteIntelligencePanel, setTopologyLayerVisibility, updateArrayToggleButton, toggleArrayVisibility, syncMapSizeInputFromActiveTab, setMapSizeStatus, setInputValue, applyTargetDcMwpFromActiveTab, wireArraySizingControls, toggleBasemap, toggleSubs, updateAtlasV8GridToggleButtons, readAssetFilterCapacityValue, updateAtlasV8OperatingAssetDropdown, applyAssetDropdownFromControls, wireAtlasV8PipelineDropdownWithStatus, updateAtlasV8OperatingAssetToggleButtons, wireAtlasV8OperatingAssetToggleButtons, wireAtlasV8GridToggleButtons, toggleMapExpand, toggleKeyCollapse
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-v8/bess-gis-sld-financial-sandbox/gis-sld-v5-ui.js:701-1400 · blob 4e77c00499d636771a34491f9e809f4bd9b34f41 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
        if (!feature || !feature.geometry || feature.geometry.type !== "LineString") return;
        try {
            const snapped = turf.nearestPointOnLine(feature, point, { units: "kilometers" });
            const d = Number(snapped.properties && snapped.properties.dist);
            if (Number.isFinite(d) && (!best || d < best.distanceKm)) best = { feature, distanceKm: d };
        } catch (err) {
            // Ignore malformed line fragments.
        }
    });
    return best;
}

function formatKm(value) {
    if (!Number.isFinite(value)) return "n/a";
    if (value < 1) return `${Math.round(value * 1000)} m`;
    return `${value.toFixed(1)} km`;
}

function formatCapacity(feature) {
    const p = feature?.properties || {};
    const capacity = Number(siteIntelPick(p, ["capacity", "capacity_mw", "Capacity (MW)"], NaN));
    return Number.isFinite(capacity) && capacity > 0 ? `${capacity.toFixed(capacity >= 100 ? 0 : 1)} MW` : "n/a";
}

function assetName(feature) {
    const p = feature?.properties || {};
    return siteIntelPick(p, ["name", "project", "site", "Site Name", "Project Name"], "Operating asset");
}

function substationName(feature) {
    const p = feature?.properties || {};
    return siteIntelPick(p, ["name_clean", "name", "Name", "site_name", "Site Name", "substation", "Substation"], "Substation");
}

function substationVoltage(feature) {
    const p = feature?.properties || {};
    return siteIntelPick(p, ["voltage_clean", "voltage", "Voltage", "kv", "kV", "Voltage kV"], "Unknown");
}

function siteIntelRow(label, main, meta, danger = false) {
    return `<div class="site-intel-row${danger ? " warn" : ""}">
        <div class="site-intel-label">${siteIntelEscape(label)}</div>
        <div class="site-intel-main">${siteIntelEscape(main)}</div>
        <div class="site-intel-meta">${siteIntelEscape(meta)}</div>
    </div>`;
}

function siteIntelOpportunityNotes(results) {
    const notes = [];
    const hvDistances = [results.grid["132 kV"], results.grid["275 kV"], results.grid["400 kV"]]
        .filter(Boolean)
        .map(item => item.distanceKm);
    const minHv = hvDistances.length ? Math.min(...hvDistances) : NaN;
    const nearestSolar = results.assets.solar?.distanceKm;
    const nearestBess = results.assets.bess?.distanceKm;

    if (Number.isFinite(minHv) && minHv <= 5) notes.push("Near high voltage corridor. Worth deeper grid screening.");
    if (Number.isFinite(minHv) && minHv > 15) notes.push("High voltage corridor not immediately nearby. Route and connection assumptions need care.");
    if (Number.isFinite(nearestSolar) && nearestSolar <= 10) notes.push("Existing operating solar nearby. Compare pattern, grid route and project scale.");
    if (Number.isFinite(nearestBess) && nearestBess <= 15) notes.push("Operating battery storage nearby. Check co location or grid constraint context.");
    if (!notes.length) notes.push("Use as early spatial screening only. Formal grid and design studies still required.");
    return notes;
}

async function inspectSiteIntelligenceAt(lngLat) {
    if (!lngLat || typeof turf === "undefined") return;
    showSiteIntelPanel(`<div class="site-intel-loading">Loading site intelligence…</div>`);
    await loadSiteIntelData();
    if (!siteIntelData.ready) return;

    const point = turf.point([lngLat.lng, lngLat.lat]);
    const results = {
        assets: {
            solar: nearestPointFeature(point, siteIntelData.assets, f => siteIntelAssetGroup(f) === "Operating Solar PV"),
            bess: nearestPointFeature(point, siteIntelData.assets, f => siteIntelAssetGroup(f) === "Operating Battery Storage"),
            onshore: nearestPointFeature(point, siteIntelData.assets, f => siteIntelAssetGroup(f) === "Operating Onshore Wind"),
            offshore: nearestPointFeature(point, siteIntelData.assets, f => siteIntelAssetGroup(f) === "Operating Offshore Wind")
        },
        substation: nearestPointFeature(point, siteIntelData.substations),
        grid: {}
    };

    Object.keys(siteIntelData.grid).forEach(key => {
        results.grid[key] = nearestLineFeature(point, siteIntelData.grid[key]);
    });

    const rows = [];
    rows.push(siteIntelRow("Clicked location", `${lngLat.lat.toFixed(5)}, ${lngLat.lng.toFixed(5)}`, "Reference point only"));

    const addAssetRow = (label, item) => {
        if (!item) rows.push(siteIntelRow(label, "No data", "Layer data unavailable", true));
        else rows.push(siteIntelRow(label, assetName(item.feature), `${formatKm(item.distanceKm)} · ${formatCapacity(item.feature)}`));
    };

    addAssetRow("Nearest solar", results.assets.solar);
    addAssetRow("Nearest BESS", results.assets.bess);
    addAssetRow("Nearest onshore wind", results.assets.onshore);
    addAssetRow("Nearest offshore wind", results.assets.offshore);

    if (results.substation) {
        rows.push(siteIntelRow("Nearest substation", substationName(results.substation.feature), `${formatKm(results.substation.distanceKm)} · ${substationVoltage(results.substation.feature)}`));
    } else {
        rows.push(siteIntelRow("Nearest substation", "No data", "Substation data unavailable", true));
    }

    ["66 kV", "132 kV", "275 kV", "400 kV"].forEach(key => {
        const item = results.grid[key];
        rows.push(siteIntelRow(`Nearest ${key}`, item ? formatKm(item.distanceKm) : "No data", "Atlas V8 corridor reference", !item));
    });

    const notes = siteIntelOpportunityNotes(results).map(note => `<li>${siteIntelEscape(note)}</li>`).join("");

    showSiteIntelPanel(`
        <div class="site-intel-section-title">Nearest infrastructure context</div>
        ${rows.join("")}
        <div class="site-intel-section-title">Screening notes</div>
        <ul class="site-intel-notes">${notes}</ul>
        <div class="site-intel-disclaimer">Indicative spatial screening only. Distances do not confirm capacity, rights, routes, consent or connection feasibility.</div>
    `);
}

function wireSiteIntelligencePanel() {
    $("site_intel_close")?.addEventListener("click", hideSiteIntelPanel);
    if (!map) return;
    map.on("click", e => {
        const target = e.originalEvent && e.originalEvent.target;
        if (target && target.closest && target.closest(".map-controls, .map-tool-overlay, .legend, .gis-map-search, .site-intel-panel")) return;
        inspectSiteIntelligenceAt(e.lngLat);
    });
}

// ============================================================
// ARRAY VISIBILITY AND TARGET MWp SIZING
// ============================================================
const TOPOLOGY_LAYER_IDS_FOR_ARRAY_TOGGLE = [
    "overall_boundary_fill",
    "overall_boundary_line",
    "footprints",
    "footprints_outline",
    "export_cable",
    "radial_spine",
    "export_cable_pins",
    "inverters",
    "substation"
];

function setTopologyLayerVisibility(visible) {
    if (!map) return;
    TOPOLOGY_LAYER_IDS_FOR_ARRAY_TOGGLE.forEach(layerId => {
        if (map.getLayer(layerId)) {
            map.setLayoutProperty(layerId, "visibility", visible ? "visible" : "none");
        }
    });
}

function updateArrayToggleButton() {
    const btn = $("btn_array_toggle");
    if (!btn) return;
    const visible = state.arrayVisible !== false;
    btn.textContent = visible ? "ARRAY ON" : "ARRAY OFF";
    btn.classList.toggle("active", visible);
}

function toggleArrayVisibility() {
    state.arrayVisible = state.arrayVisible === false;
    setTopologyLayerVisibility(state.arrayVisible !== false);
    updateArrayToggleButton();
}

function syncMapSizeInputFromActiveTab() {
    const mapInput = $("map_target_dc_mwp");
    if (!mapInput) return;
    const source = state.activeTab === "string" ? $("target_dc_mwp") : $("target_dc_mwp_c");
    mapInput.value = source?.value || "";
}

function setMapSizeStatus(text, ok = true) {
    const el = $("map_size_status");
    if (!el) return;
    el.textContent = text;
    el.style.color = ok ? "#00ff88" : "#ff9900";
}

function setInputValue(id, value) {
    const el = $(id);
    if (!el) return;
    el.value = String(value);
    el.dispatchEvent(new Event("input", { bubbles: true }));
    el.dispatchEvent(new Event("change", { bubbles: true }));
}

function applyTargetDcMwpFromActiveTab(source) {
    const suffix = state.activeTab === "string" ? "" : "_c";
    const targetInput = state.activeTab === "string" ? $("target_dc_mwp") : $("target_dc_mwp_c");
    const mapInput = $("map_target_dc_mwp");
    const raw = source === "map" ? parseFloat(mapInput?.value) : parseFloat(targetInput?.value);
    const targetMwp = Number.isFinite(raw) && raw > 0 ? raw : 0;

    if (!targetMwp) {
        setMapSizeStatus("Enter MWp DC", false);
        return;
    }

    if (state.activeTab === "string") {
        const modWp = num("mod_wp");
        const x = intVal("x_mods");
        const z = intVal("z_strings");
        const y = intVal("y_invs");
        const currentSkidsPerRing = Math.max(1, intVal("s_subs", 1));
        if (modWp <= 0 || x <= 0 || z <= 0 || y <= 0) {
            setMapSizeStatus("Check string inputs", false);
            return;
        }
        const dcPerSkidMwp = (modWp * x * z * y) / 1_000_000;
        const desiredSkids = Math.max(1, Math.ceil(targetMwp / dcPerSkidMwp));
        const rings = Math.max(1, Math.ceil(desiredSkids / currentSkidsPerRing));
        const skidsPerRing = Math.max(1, Math.ceil(desiredSkids / rings));
        const actualSkids = skidsPerRing * rings;
        const actualMwp = actualSkids * dcPerSkidMwp;

        setInputValue("s_subs", skidsPerRing);
        setInputValue("b_cols", rings);
        if (targetInput) targetInput.value = targetMwp;
        if (mapInput) mapInput.value = targetMwp;
        setMapSizeStatus(`String ${actualMwp.toFixed(1)} MWp via ${actualSkids} skids`, true);
    } else {
        const invDcMwp = getCentralInverterDcMwdc();
        const invPerSkid = Math.max(1, intVal("inv_per_mv_c", 1));
        const currentSkidsPerRing = Math.max(1, intVal("mv_per_ring_c", 1));
        if (invDcMwp <= 0 || invPerSkid <= 0) {
            setMapSizeStatus("Check central inputs", false);
            return;
        }
        const desiredInverters = Math.max(1, Math.ceil(targetMwp / invDcMwp));
        const desiredSkids = Math.max(1, Math.ceil(desiredInverters / invPerSkid));
        const rings = Math.max(1, Math.ceil(desiredSkids / currentSkidsPerRing));
        const skidsPerRing = Math.max(1, Math.ceil(desiredSkids / rings));
        const actualInverters = invPerSkid * skidsPerRing * rings;
        const actualMwp = actualInverters * invDcMwp;

        setInputValue("mv_per_ring_c", skidsPerRing);
        setInputValue("rings_c", rings);
        if (targetInput) targetInput.value = targetMwp;
        if (mapInput) mapInput.value = targetMwp;
        setMapSizeStatus(`Central ${actualMwp.toFixed(1)} MWp via ${actualInverters} inverter blocks`, true);
    }

    state.arrayOverrideCenter = null;
    state.suppressNextMapFit = true;
    redrawIfTopologyExists();
    setTopologyLayerVisibility(state.arrayVisible !== false);
    updateArrayToggleButton();
}

function wireArraySizingControls() {
    $("btn_array_toggle")?.addEventListener("click", toggleArrayVisibility);
    $("btn_map_apply_size")?.addEventListener("click", () => applyTargetDcMwpFromActiveTab("map"));
    $("map_target_dc_mwp")?.addEventListener("keydown", e => {
        if (e.key === "Enter") applyTargetDcMwpFromActiveTab("map");
    });
    $("target_dc_mwp")?.addEventListener("change", () => applyTargetDcMwpFromActiveTab("panel"));
    $("target_dc_mwp_c")?.addEventListener("change", () => applyTargetDcMwpFromActiveTab("panel"));
    updateArrayToggleButton();
    syncMapSizeInputFromActiveTab();
}

// ============================================================
// BASEMAP / SUBS TOGGLES
// ============================================================
function toggleBasemap() {
    if (!map || !map.getLayer("l-sat")) return;
    state.satActive = !state.satActive;
    map.setLayoutProperty("l-sat", "visibility", state.satActive ? "visible" : "none");
    const btn = $("btn_basemap");
    if (btn) {
        btn.textContent = state.satActive ? "DARK MATTER VIEW" : "SATELLITE VIEW";
        btn.classList.toggle("active", state.satActive);
    }
}

function toggleSubs() {
    if (!map || !map.getLayer("l-subs")) return;
    state.subsVisible = !state.subsVisible;
    map.setLayoutProperty("l-subs", "visibility", state.subsVisible ? "visible" : "none");
    const btn = $("btn_subs_toggle");
    if (btn) {
        btn.textContent = state.subsVisible ? "SUBS ON" : "SUBS OFF";
        btn.classList.toggle("active", state.subsVisible);
    }
}

function updateAtlasV8GridToggleButtons() {
    const labels = { "66kv": "66 kV", "132kv": "132 kV", "275kv": "275 kV", "400kv": "400 kV" };
    Object.keys(labels).forEach(voltageKey => {
        const btn = $(`btn_atlas_${voltageKey}`);
        if (!btn) return;
        const visible = atlasV8GridLayerVisibility?.[voltageKey] !== false;
        btn.textContent = `${labels[voltageKey]} ${visible ? "ON" : "OFF"}`;
        btn.classList.toggle("active", visible);
    });
}


function readAssetFilterCapacityValue(id) {
    const el = $(id);
    if (!el || String(el.value || "").trim() === "") return null;
    const value = Number(el.value);
    return Number.isFinite(value) && value >= 0 ? value : null;
}

function updateAtlasV8OperatingAssetDropdown() {
    const select = $("asset_layer_select");
    if (select) select.value = atlasV8AssetFilterState?.selected || "off";
    const statusSelect = $("asset_status_select");
    if (statusSelect) statusSelect.value = atlasV8AssetFilterState?.status || "all";
    const minInput = $("asset_min_mw");
    const maxInput = $("asset_max_mw");
    if (minInput && Number.isFinite(atlasV8AssetFilterState?.minMw)) minInput.value = atlasV8AssetFilterState.minMw;
    if (maxInput && Number.isFinite(atlasV8AssetFilterState?.maxMw)) maxInput.value = atlasV8AssetFilterState.maxMw;
}

function applyAssetDropdownFromControls() {
    const selected = $("asset_layer_select")?.value || "off";
    const status = $("asset_status_select")?.value || "all";
    let minMw = readAssetFilterCapacityValue("asset_min_mw");
    let maxMw = readAssetFilterCapacityValue("asset_max_mw");
    if (Number.isFinite(minMw) && Number.isFinite(maxMw) && minMw > maxMw) {
        const temp = minMw;
        minMw = maxMw;
        maxMw = temp;
        if ($("asset_min_mw")) $("asset_min_mw").value = minMw;
        if ($("asset_max_mw")) $("asset_max_mw").value = maxMw;
    }
    applyAtlasV8AssetDropdownFilter?.(selected, status, minMw, maxMw);
    updateAtlasV8OperatingAssetDropdown();
}

function wireAtlasV8PipelineDropdownWithStatus() {
    $("asset_layer_select")?.addEventListener("change", applyAssetDropdownFromControls);
    $("asset_status_select")?.addEventListener("change", applyAssetDropdownFromControls);
    $("btn_asset_filter_apply")?.addEventListener("click", applyAssetDropdownFromControls);
    ["asset_min_mw", "asset_max_mw"].forEach(id => {
        $(id)?.addEventListener("keydown", e => {
            if (e.key === "Enter") applyAssetDropdownFromControls();
        });
        $(id)?.addEventListener("change", applyAssetDropdownFromControls);
    });
    updateAtlasV8OperatingAssetDropdown();
}

function updateAtlasV8OperatingAssetToggleButtons() {
    const labels = {
        "solar_operational": "SOLAR OP",
        "wind_onshore_operational": "ONSHORE WIND",
        "wind_offshore_operational": "OFFSHORE WIND",
        "bess_operational": "BESS OP"
    };
    Object.keys(labels).forEach(assetKey => {
        const btn = $(`btn_asset_${assetKey}`);
        if (!btn) return;
        const visible = atlasV8OperatingAssetVisibility?.[assetKey] === true;
        btn.textContent = `${labels[assetKey]} ${visible ? "ON" : "OFF"}`;
        btn.classList.toggle("active", visible);
    });
}

function wireAtlasV8OperatingAssetToggleButtons() {
    document.querySelectorAll(".asset-layer-btn").forEach(btn => {
        btn.addEventListener("click", () => {
            toggleAtlasV8OperatingAssetLayer(btn.dataset.assetLayer);
            updateAtlasV8OperatingAssetToggleButtons();
        });
    });
    updateAtlasV8OperatingAssetToggleButtons();
}

function wireAtlasV8GridToggleButtons() {
    document.querySelectorAll(".atlas-voltage-btn").forEach(btn => {
        btn.addEventListener("click", () => {
            toggleAtlasV8GridLayer(btn.dataset.atlasVoltage);
            updateAtlasV8GridToggleButtons();
        });
    });
    updateAtlasV8GridToggleButtons();
}
function toggleMapExpand() {
    const panel = document.querySelector(".panel-right");
    const btn = $("btn_map_expand");
    if (!panel) return;
    const active = !panel.classList.contains("map-expanded");
    panel.classList.toggle("map-expanded", active);
    document.body.classList.toggle("map-expanded", active);
    if (btn) {
        btn.textContent = active ? "MAP MIN" : "MAP MAX";
        btn.classList.toggle("active", active);
    }
    setTimeout(() => { if (map && typeof map.resize === "function") map.resize(); }, 150);
}

function toggleKeyCollapse() {
    const legend = $("map_legend");
    const btn = $("btn_key_toggle");
    if (!legend) return;
    const hidden = !legend.classList.contains("key-collapsed");
    legend.classList.toggle("key-collapsed", hidden);
    if (btn) {
        btn.textContent = hidden ? "KEY OFF" : "KEY ON";
        btn.classList.toggle("active", !hidden);
    }
}
function toggleMapToolsOverlay() {
    const overlay = $("map_tool_overlay");
    const btn = $("btn_map_tools_toggle");
    if (!overlay || !btn) return;
    const collapsed = !overlay.classList.contains("tools-collapsed");
    overlay.classList.toggle("tools-collapsed", collapsed);
    btn.textContent = collapsed ? "TOOLS OFF" : "TOOLS ON";
    btn.classList.toggle("active", !collapsed);
}

function wireMapToolOverlayButtons() {
    $("btn_map_tools_toggle")?.addEventListener("click", toggleMapToolsOverlay);
    $("btn_map_draw")?.addEventListener("click", triggerDrawAtCenter);
    $("btn_map_pick_array")?.addEventListener("click", toggleArrayMoveMode);
    $("btn_map_drop_pins")?.addEventListener("click", toggleCablePinMode);
    $("btn_map_draw_route")?.addEventListener("click", commitCablePinRoute);
    $("btn_map_rotate_left")?.addEventListener("click", () => rotateArrayBy(-30));
    $("btn_map_rotate_right")?.addEventListener("click", () => rotateArrayBy(30));
    $("btn_map_rotate_90")?.addEventListener("click", () => rotateArrayBy(90));
    $("btn_map_reset_rotation")?.addEventListener("click", resetArrayRotation);
    $("btn_map_reset_array")?.addEventListener("click", resetArrayLocation);
    $("btn_map_nudge_up")?.addEventListener("click", () => nudgeArray(0));
    $("btn_map_nudge_right")?.addEventListener("click", () => nudgeArray(90));
    $("btn_map_nudge_down")?.addEventListener("click", () => nudgeArray(180));
    $("btn_map_nudge_left")?.addEventListener("click", () => nudgeArray(270));
    $("btn_map_undo_pin")?.addEventListener("click", undoCablePin);
    $("btn_map_clear_route")?.addEventListener("click", clearCableRoute);
}
// ============================================================
// WIRE EVERYTHING UP
// ============================================================
function wireEvents() {
    injectExportCableLengthControl();

    // Tab buttons
    document.querySelectorAll(".tab-btn").forEach(btn => {
        btn.addEventListener("click", () => switchTab(btn.dataset.tab));
    });

    // Map toggles
    $("btn_basemap")?.addEventListener("click", toggleBasemap);
    $("btn_subs_toggle")?.addEventListener("click", toggleSubs);
wireAtlasV8GridToggleButtons();
wireAtlasV8PipelineDropdownWithStatus();
$("btn_map_expand")?.addEventListener("click", toggleMapExpand);
$("btn_key_toggle")?.addEventListener("click", toggleKeyCollapse);
$("btn_print_report")?.addEventListener("click", () => window.print());
wireMapToolOverlayButtons();
wireArraySizingControls();
wireGisMapSearch();
wireSiteIntelligencePanel();




    // Draw / Export
    $("btn_draw")?.addEventListener("click", triggerDrawAtCenter);
    $("btn_export")?.addEventListener("click", exportGeoJSON);

    // Array rotation
    $("btn_rotate_left_30")?.addEventListener("click", () => rotateArrayBy(-30));
    $("btn_rotate_right_30")?.addEventListener("click", () => rotateArrayBy(30));
    $("btn_rotate_right_90")?.addEventListener("click", () => rotateArrayBy(90));
    $("btn_reset_rotation")?.addEventListener("click", resetArrayRotation);

    // Array movement
    $("btn_pick_array")?.addEventListener("click", toggleArrayMoveMode);
    $("btn_reset_array_move")?.addEventListener("click", resetArrayLocation);
    $("btn_nudge_up")?.addEventListener("click", () => nudgeArray(0));
    $("btn_nudge_right")?.addEventListener("click", () => nudgeArray(90));
    $("btn_nudge_down")?.addEventListener("click", () => nudgeArray(180));
    $("btn_nudge_left")?.addEventListener("click", () => nudgeArray(270));

    // Cable route pins
    $("btn_drop_cable_pins")?.addEventListener("click", toggleCablePinMode);
    $("btn_draw_cable_route")?.addEventListener("click", commitCablePinRoute);
    $("btn_undo_cable_pin")?.addEventListener("click", undoCablePin);
    $("btn_clear_cable_route")?.addEventListener("click", clearCableRoute);

    // Search
    $("btn_search")?.addEventListener("click", searchLocation);
    $("loc_search")?.addEventListener("keydown", (e) => { if (e.key === "Enter") searchLocation(); });

    // Logistics presets
    document.querySelectorAll("[data-suffix]").forEach(sel => {
        sel.addEventListener("change", () => applyLogisticsPreset(sel.value, sel.dataset.suffix));
    });

    // Bifacial auto-fill

// Development stage defaults
document.querySelectorAll("[data-dev-stage-prefix]").forEach(sel => {
    sel.addEventListener("change", () => {
        applyDevelopmentStageDefaults(sel.dataset.devStagePrefix);
        recalcAll();
    });
});
    $("mounting_type")?.addEventListener("change", (e) => autoFillBifacial(e.target.value, "fin_string_bifacial"));
    $("mounting_type_c")?.addEventListener("change", (e) => autoFillBifacial(e.target.value, "fin_central_bifacial"));

    // Safe export cable length adjustment
    $("layout_export_extra_km")?.addEventListener("input", () => {
        state.arrayOverrideCenter = null;
        clearRouteAfterArrayShift();
        redrawIfTopologyExists();
    });
    $("layout_export_extra_km")?.addEventListener("change", () => {
        state.arrayOverrideCenter = null;
        clearRouteAfterArrayShift();
        redrawIfTopologyExists();
    });

    // Global recalc on input changes (debounced)
    document.querySelectorAll("input, select").forEach(el => {
        el.addEventListener("input", recalcDebounced);
        el.addEventListener("change", recalcDebounced);
    });
}

function wireMapMoveEvents() {
    if (!map || map.__arrayMoveWired) return;
    map.__arrayMoveWired = true;
    map.on("click", (e) => {
        if (state.cableRoutePinMode) addCableRoutePin(e);
        else placeArrayAtMapPoint(e);
    });
}

// ============================================================
// BOOT
// ============================================================
function boot() {
    wireEvents();
    initMap();
    if (map) map.on("load", wireMapMoveEvents);
    wireMapMoveEvents();
    updateSelectedSubstationDisplay();
    renderBenchmark();
    setArrayMoveStatus("Draw a grid first. Then use Pick Up Array or nudge arrows to relocate the array centre.", false);
    updateExportCableLengthDisplay();
    updateArrayRotationDisplay();
    updateCableRouteStatus();
}

// Libraries loaded via defer, so DOMContentLoaded is the right signal.
if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", boot);
} else {
    boot();
}

// GLOBALGRID2050 GIS SLD PRINT MAP PACK
function sleepForPrintPack(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function setLayerVisibilityForPrintPack(layerId, visible) {
    if (!map || !map.getLayer(layerId)) return;
    map.setLayoutProperty(layerId, "visibility", visible ? "visible" : "none");
}

function setAtlasLayersDefaultOff() {
    if (typeof atlasV8GridLayerVisibility === "undefined") return;
    Object.keys(atlasV8GridLayerVisibility).forEach(voltageKey => {
        atlasV8GridLayerVisibility[voltageKey] = false;
        const layerId = atlasV8GridLayerIds?.[voltageKey];
        if (layerId) setLayerVisibilityForPrintPack(layerId, false);
    });
    updateAtlasV8GridToggleButtons?.();
    updateLegend?.();
}

function setSubsDefaultOff() {
    if (typeof state === "undefined") return;
    state.subsVisible = false;
    setLayerVisibilityForPrintPack("l-subs", false);
    updateSubsToggleButton?.();
    updateLegend?.();
}

function enforceCleanDefaultMapLayers() {
    setAtlasLayersDefaultOff();
    setSubsDefaultOff();
}

function getMapPrintState() {
    if (!map) return null;
    return {
        center: map.getCenter(),
        zoom: map.getZoom(),
        bearing: map.getBearing(),
        pitch: map.getPitch(),
        satActive: !!state.satActive,
        subsVisible: !!state.subsVisible,
        atlas: typeof atlasV8GridLayerVisibility !== "undefined" ? { ...atlasV8GridLayerVisibility } : {},
        keyCollapsed: $("map_legend")?.classList.contains("key-collapsed") || false,
        toolsCollapsed: $("map_tool_overlay")?.classList.contains("tools-collapsed") || false,
        mapExpanded: document.body.classList.contains("map-expanded")
    };
}

async function restoreMapPrintState(saved) {
    if (!map || !saved) return;

    if (typeof state !== "undefined") {
        state.satActive = saved.satActive;
        state.subsVisible = saved.subsVisible;
    }

    setLayerVisibilityForPrintPack("l-sat", saved.satActive);
    setLayerVisibilityForPrintPack("l-subs", saved.subsVisible);

    if (typeof atlasV8GridLayerVisibility !== "undefined") {
        Object.keys(saved.atlas || {}).forEach(voltageKey => {
            atlasV8GridLayerVisibility[voltageKey] = saved.atlas[voltageKey];
            const layerId = atlasV8GridLayerIds?.[voltageKey];
            if (layerId) setLayerVisibilityForPrintPack(layerId, saved.atlas[voltageKey]);
        });
    }

    const legend = $("map_legend");
    if (legend) legend.classList.toggle("key-collapsed", saved.keyCollapsed);
    const keyBtn = $("btn_key_toggle");
    if (keyBtn) {
        keyBtn.textContent = saved.keyCollapsed ? "KEY OFF" : "KEY ON";
        keyBtn.classList.toggle("active", !saved.keyCollapsed);
    }

    const overlay = $("map_tool_overlay");
    if (overlay) overlay.classList.toggle("tools-collapsed", saved.toolsCollapsed);
    const toolsBtn = $("btn_map_tools_toggle");
    if (toolsBtn) {
        toolsBtn.textContent = saved.toolsCollapsed ? "TOOLS OFF" : "TOOLS ON";
        toolsBtn.classList.toggle("active", !saved.toolsCollapsed);
    }

    document.body.classList.toggle("map-expanded", saved.mapExpanded);
    document.querySelector(".panel-right")?.classList.toggle("map-expanded", saved.mapExpanded);

    map.jumpTo({ center: saved.center, zoom: saved.zoom, bearing: saved.bearing, pitch: saved.pitch });
    updateSubsToggleButton?.();
    updateAtlasV8GridToggleButtons?.();
    updateLegend?.();
    map.resize();
    await sleepForPrintPack(350);
}

function ensurePrintMapPackContainer() {
    let pack = document.getElementById("print_map_pack");
    if (!pack) {
        pack = document.createElement("section");
        pack.id = "print_map_pack";
        pack.className = "print-map-pack";
        document.body.appendChild(pack);
    }
    pack.innerHTML = "";
    return pack;
}

function addPrintMapFigure(pack, title, dataUrl, note, landscape = false) {
    const page = document.createElement("section");
    page.className = landscape ? "print-map-page print-map-page-landscape" : "print-map-page";

    const heading = document.createElement("h2");
    heading.textContent = title;

    const img = document.createElement("img");
    img.src = dataUrl;
    img.alt = title;

    const caption = document.createElement("p");
    caption.textContent = note || "Map figure generated from current GIS SLD sandbox view. Indicative only.";

    page.appendChild(heading);
    page.appendChild(img);
    page.appendChild(caption);
    pack.appendChild(page);
}

async function captureCurrentMapForPrint() {
    if (!map) return "";
    map.resize();
    await sleepForPrintPack(650);
    return map.getCanvas().toDataURL("image/png");
}

function getTopologyBoundsForPrintPack() {
    if (typeof turf === "undefined" || !state?.currentGeoJSON?.features?.length) return null;
    try {
        const bbox = turf.bbox(state.currentGeoJSON);