GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-bess-topology-v2

Indexforgis Single-Line Diagram (SLD) V2

A map page in GlobalGrid2050 that maps sat s, l sat, l subs and topology, and uses data from OpenStreetMap Nominatim. Published at https://globalgrid2050.com/solar-bess-topology-v2/indexforgis-sld-v2.html.

700 lines of HTML from globalgrid2050, in 1 file. Topic: Solar and storage design. Section 75 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. Indexforgis Single-Line Diagram (SLD) V2 electrical · globalgrid2050 / solar-bess-topology-v2/indexforgis-sld-v2.html lines 678–1377

Indexforgis Single-Line Diagram (SLD) V2

A map page in GlobalGrid2050 that maps sat s, l sat, l subs and topology, and uses data from OpenStreetMap Nominatim. Published at https://globalgrid2050.com/solar-bess-topology-v2/indexforgis-sld-v2.html.

electricalglobalgrid2050 / solar-bess-topology-v2/indexforgis-sld-v2.html · lines 678–1377 of 1406 (continued from section 74) · Entry point · pattern triggerDownload (shared by 3 files)

What it does
It maps sat s, l sat, l subs and topology. Defines 35 functions or classes, including initMap, onMapLoad, showPopup, onSubstationClick, onInverterClick. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'bess'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 33kV.
Inputs & outputs
In: data source: OpenStreetMap Nominatim; JSON file style.json; form fields (user input). Out: web page; interactive map. Voltage levels named: 33kV.
Downstream impact
It is itself an entry point, published at https://globalgrid2050.com/solar-bess-topology-v2/indexforgis-sld-v2.html.
What it achieves
It shows popup (`showPopup`), reads physical inputs (`readPhysicalInputs`) and builds stats (`buildStats`). GIS SLD Financial Sandbox V2. Its code works with 33 kV. It responds to click, keydown and change events.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · solar-bess-topology-v2 · page
Uses
GIS Single-Line Diagram (SLD) V2 Config (script src), GIS Single-Line Diagram (SLD) V2 Helpers (script src), GIS Single-Line Diagram (SLD) V2 State (script src), GIS Single-Line Diagram (SLD) V2 Substations (script src), GIS Single-Line Diagram (SLD) V2 (stylesheet), 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://cdn.jsdelivr.net/npm/@turf/turf@6/turf.min.js
Used by
mentioned in Standalone (comment link)
Produces
initMap, onMapLoad, showPopup, onSubstationClick, onInverterClick, onPoiClick, readPhysicalInputs, zeroStats, buildStats, computeStringStats, computeCentralStats, computeStats
Defines here
computeStats, applyDevelopmentStageDefaults, computeFinance, renderFinance, renderFinanceWarnings, renderTechSummary, renderBenchmark, updateSelectedSubstationDisplay, recalcAll, updateLegend, getRectPolygon, getBlockAspect, computeAndDraw, exportGeoJSON, triggerDownload, switchTab, applyLogisticsPreset, autoFillBifacial, searchLocation, triggerDrawAtCenter, toggleBasemap, toggleSubs, wireEvents
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-v2/indexforgis-sld-v2.html:678-1377 · blob b5c7689b86d9bf022a6b0e8f9a1984c0d8ae3b7d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
    const ac_mw_direct = total_blocks * inv_ac_mw;

    return buildStats({
        total_blocks, module_count, ac_mw_direct, dc_ac_ratio, physical,
        combiner_boxes_per_inverter, total_combiner_boxes
    });
}

function computeStats() {
    return state.activeTab === "string" ? computeStringStats() : computeCentralStats();
}

// ============================================================
// FINANCIALS
// ============================================================
function applyDevelopmentStageDefaults(prefix) {
    const stage = $(prefix + "_dev_stage");
    const cost = $(prefix + "_dev_cost_mw");
    if (!stage || !cost) return;
    cost.value = stage.value;

    const success = $(prefix + "_dev_success");
    const successByStage = {
        "3000": 10,
        "15000": 15,
        "35000": 30,
        "55000": 55,
        "70000": 70,
        "80000": 80,
        "100000": 95
    };
    if (success && successByStage[stage.value] !== undefined) {
        success.value = successByStage[stage.value];
    }
}
function computeFinance(prefix, stats) {
    const dc_mwp = stats.dc_mwp, ac_mw = stats.ac_mw;

    const price = num(prefix + "_price");
    const other = num(prefix + "_other");
    const yieldVal = num(prefix + "_yield");
    const bifacial = num(prefix + "_bifacial");
    const baseLoss = num(prefix + "_losses");
    const deg = num(prefix + "_deg");
    const opexRate = num(prefix + "_opex");

    const epcEx = num(prefix + "_epc_ex");
    const floodAdder = checked(prefix + "_flood") ? num(prefix + "_flood_rate") : 0;
    const modules = num(prefix + "_modules");
    const otherCapex = num(prefix + "_other_capex");
    const fixedCapex = num(prefix + "_fixed_capex");
    const cont = num(prefix + "_cont");

    const lossExtras = num(prefix + "_loss_dc_string") + num(prefix + "_loss_lv_dc") +
                       num(prefix + "_loss_lv_ac") + num(prefix + "_loss_tx") + num(prefix + "_loss_other");
    const totalLoss = baseLoss + lossExtras;

    const bessMw = num(prefix + "_bess_mw");
    const bessMwh = num(prefix + "_bess_mwh");
    const bessCapexRate = num(prefix + "_bess_capex");
    const bessCycles = num(prefix + "_bess_cycles");
    const bessSpread = num(prefix + "_bess_spread");
    const bessEff = num(prefix + "_bess_eff") / 100;

    const safeLoss = Math.min(Math.max(totalLoss, 0), 100);
    const safeBessEff = Math.min(Math.max(bessEff, 0), 1);
    const effectiveYield = yieldVal * (1 + bifacial / 100);

    const year1Gen = dc_mwp * effectiveYield * (1 - safeLoss / 100);

    // Cumulative generation
    let gen25 = 0, gen35 = 0;
    for (let y = 1; y <= 35; y++) {
        const yr = year1Gen * Math.pow(1 - deg / 100, y - 1);
        if (y <= 25) gen25 += yr;
        gen35 += yr;
    }

    const annualSolarRevenue = year1Gen * (price + other);
    const bessAnnualValue = bessMwh * bessCycles * bessSpread * safeBessEff;
    const annualRevenue = annualSolarRevenue + bessAnnualValue;
    const revenue25 = gen25 * (price + other) + bessAnnualValue * 25;
    const revenue35 = gen35 * (price + other) + bessAnnualValue * 35;

    const annualOpex = ac_mw * opexRate;

    const baseCapexWp = epcEx + modules + otherCapex + floodAdder;
    const baseCapex = dc_mwp * 1_000_000 * baseCapexWp;
    const contingency = baseCapex * (cont / 100);
    const bessCapex = bessMwh * bessCapexRate;
    const totalCapex = baseCapex + contingency + fixedCapex + bessCapex;
    const capexPerWp = dc_mwp > 0 ? totalCapex / (dc_mwp * 1_000_000) : 0;

    const surplus25 = revenue25 - annualOpex * 25 - totalCapex;
    const surplus35 = revenue35 - annualOpex * 35 - totalCapex;

const devCostPerMw = num(prefix + "_dev_cost_mw");
const devModulePerMwp = num(prefix + "_dev_module_mwp");
const devEpcPerMw = num(prefix + "_dev_epc_mw");
const devOwnerPerMw = num(prefix + "_dev_owner_mw");
const devGridPerMw = num(prefix + "_dev_grid_mw");
const devExitPerMwp = num(prefix + "_dev_exit_mwp");
const devNpvPerMwp = num(prefix + "_dev_npv_mwp");
const devSuccessPct = num(prefix + "_dev_success");
const devYears = num(prefix + "_dev_years");
const devStageEl = $(prefix + "_dev_stage");
const devStage = devStageEl ? devStageEl.options[devStageEl.selectedIndex]?.text || "Manual" : "Manual";

const devCapitalAtRisk = dc_mwp * devCostPerMw;
const devModuleCost = dc_mwp * devModulePerMwp;
const devEpcCost = dc_mwp * devEpcPerMw;
const devOwnerCost = dc_mwp * devOwnerPerMw;
const devGridCost = dc_mwp * devGridPerMw;
const devTotalBuildCost = devCapitalAtRisk + devModuleCost + devEpcCost + devOwnerCost + devGridCost;
const devExitValue = dc_mwp * devExitPerMwp;
const devOperatingNpv = dc_mwp * devNpvPerMwp;
const devGrossMargin = devExitValue - devTotalBuildCost;
const devRiskAdjustedValue = devGrossMargin * (devSuccessPct / 100);
const devReturnMultiple = devCapitalAtRisk > 0 ? devGrossMargin / devCapitalAtRisk : 0;

    return {
        annualRevenue, revenue25, revenue35, totalCapex, capexPerWp, surplus25, surplus35,
        devStage, devCostPerMw, devModulePerMwp, devEpcPerMw, devOwnerPerMw, devGridPerMw, devExitPerMwp, devNpvPerMwp, devSuccessPct, devYears,
        devCapitalAtRisk, devModuleCost, devEpcCost, devOwnerCost, devGridCost, devTotalBuildCost, devExitValue, devOperatingNpv,
        devGrossMargin, devRiskAdjustedValue, devReturnMultiple,
        // raw inputs for export
        price, other, yieldVal, bifacial, baseLoss, deg, opexRate,
        epcEx, floodActive: checked(prefix + "_flood"), floodRate: num(prefix + "_flood_rate"),
        modules, otherCapex, fixedCapex, cont, totalLoss,
        bessMw, bessMwh, bessCapexRate, bessCycles, bessSpread, bessEff: num(prefix + "_bess_eff"),
        // for warnings
        epcIncModules: epcEx + modules
    };
}

function renderFinance(prefix, fin) {
    setText(prefix + "_annual_rev", money(fin.annualRevenue));
    setText(prefix + "_25_rev", money(fin.revenue25));
    setText(prefix + "_35_rev", money(fin.revenue35));
    setText(prefix + "_capex", money(fin.totalCapex));
    setText(prefix + "_capex_wp", "£" + fin.capexPerWp.toFixed(2) + "/Wp");
    setText(prefix + "_surplus_25", money(fin.surplus25));
    setText(prefix + "_surplus_35", money(fin.surplus35));
setText(prefix + "_dev_capital", money(fin.devCapitalAtRisk));
setText(prefix + "_dev_module_cost", money(fin.devModuleCost));
setText(prefix + "_dev_epc_cost", money(fin.devEpcCost));
setText(prefix + "_dev_owner_cost", money(fin.devOwnerCost));
setText(prefix + "_dev_grid_cost", money(fin.devGridCost));
setText(prefix + "_dev_total_cost", money(fin.devTotalBuildCost));
setText(prefix + "_dev_exit_value", money(fin.devExitValue));
setText(prefix + "_dev_operating_npv", money(fin.devOperatingNpv));
setText(prefix + "_dev_margin", money(fin.devGrossMargin));
setText(prefix + "_dev_risk_value", money(fin.devRiskAdjustedValue));
setText(prefix + "_dev_multiple", fin.devReturnMultiple.toFixed(2) + "x");
}

function renderFinanceWarnings(prefix, fin, stats) {
    const w = [];
    if (fin.price < 0) w.push("Energy price cannot be negative.");
    if (fin.opexRate < 0) w.push("OPEX cannot be negative.");
    if (fin.totalLoss < 0) w.push("Losses cannot be negative.");
    if (fin.epcIncModules < 0) w.push("EPC cannot be negative.");
    if (fin.capexPerWp < 0) w.push("CAPEX cannot be negative.");
    if (fin.bessMwh < 0 || fin.bessMw < 0) w.push("BESS size cannot be negative.");
    if (fin.bessMwh > 0 && fin.bessEff / 100 <= 0) w.push("BESS efficiency missing.");
    if (fin.bessEff / 100 > 1) w.push("BESS efficiency above 100 percent.");

    if (fin.price < 50) w.push("Low energy price case.");
    if (fin.price > 85) w.push("High energy price case.");
    if (fin.epcIncModules < 0.42) w.push("Aggressive EPC pricing.");
    if (fin.capexPerWp > 1.00) w.push("Full project cost territory.");
    if (fin.capexPerWp > 1.25) w.push("Complex project or asset value territory.");
if (fin.devCostPerMw > 100000) w.push("Development cost is above typical EPC signature range.");
if (fin.devModulePerMwp < 100000 && fin.devModulePerMwp > 0) w.push("Module supply cost may be aggressive.");
if (fin.devEpcPerMw < 550000 && fin.devEpcPerMw > 0) w.push("EPC cost may be aggressive against UK benchmark range.");
if (fin.devEpcPerMw > 850000) w.push("EPC cost is above typical non BESS UK benchmark range.");
if (fin.devNpvPerMwp < 900000 && fin.devNpvPerMwp > 0) w.push("Operating asset Net Present Value (NPV) assumption is below current screening range.");
if (fin.devNpvPerMwp > 1400000) w.push("Operating asset Net Present Value (NPV) assumption is above current screening range and may require strong evidence.");
if (stats.dc_mwp > 100) w.push("Project capacity is above 100 megawatts peak. Nationally Significant Infrastructure Project (NSIP) and Development Consent Order (DCO) planning assumptions may apply and development cost, timescale and owner cost defaults may be too low.");
if (fin.devGridPerMw > 1000000) w.push("Grid connection cost assumption is very high and may indicate major reinforcement, transmission interface or abnormal connection risk.");
if (fin.devGridPerMw < 100000 && fin.devGridPerMw > 0) w.push("Grid connection cost assumption is low and should be checked against the project specific connection scope.");
if (fin.devSuccessPct < 8) w.push("Development success probability is below typical greenfield to EPC outcome range.");
if (fin.devSuccessPct > 25) w.push("Development success probability may be optimistic unless project is already materially de risked.");
    if (fin.opexRate < 10000 && fin.opexRate >= 0) w.push("OPEX may be unrealistically low.");
    if (fin.totalLoss > 6) w.push("High loss assumption.");
    if (fin.bifacial > 12) w.push("Aggressive bifacial gain assumption.");
    if (fin.bessMwh > 0 && fin.bessMw <= 0) w.push("BESS MW missing.");
    if (fin.bessMw > 0 && fin.bessMwh / fin.bessMw > 8) w.push("Unusually long BESS duration.");
    if (fin.bessCycles > 365) w.push("Aggressive storage cycling assumption.");

    const elecZero = num(prefix + "_loss_dc_string") + num(prefix + "_loss_lv_dc") +
                     num(prefix + "_loss_lv_ac") + num(prefix + "_loss_tx") + num(prefix + "_loss_other");
    if (elecZero === 0) w.push("Specialist electrical loss fields are blank or zero. Revenue may be overstated until verified.");

    const gf = state.activeTab === "string" ? num("gross_factor") : num("gross_factor_c");
    if (gf < 1.15) w.push("Gross site factor may be too low for roads, buffers, substations, drainage and ecology.");
    if (stats.mods_pallet <= 0 || stats.mods_container <= 0) w.push("Module logistics assumptions are missing.");

    const el = $(prefix + "_warnings");
    if (el) el.innerHTML = w.join("<br>");
}

// ============================================================
// RENDER TECHNICAL SUMMARY
// ============================================================
function renderTechSummary(stats) {
    setText("out_module_count", stats.module_count.toLocaleString());
    setText("out_dc_capacity", stats.dc_mwp.toFixed(2) + " MWp");
    setText("out_ac_capacity", stats.ac_mw.toFixed(2) + " MWac");
    setText("out_actual_dcac", stats.dc_ac_ratio.toFixed(2));
    setText("out_cb_per_inv", stats.combiner_boxes_per_inverter.toLocaleString());
    setText("out_total_cb", stats.total_combiner_boxes.toLocaleString());
    setText("out_net_mod_area", (stats.net_mod_area_m2 / CONSTANTS.M2_PER_ACRE).toFixed(0) + " Acres");
    setText("out_net_array_area", (stats.net_array_area_m2 / CONSTANTS.M2_PER_ACRE).toFixed(0) + " Acres");
    setText("out_gross_area", (stats.gross_site_area_m2 / CONSTANTS.M2_PER_ACRE).toFixed(0) + " Acres");
    setText("out_mod_per_pallet", stats.mods_pallet);
    setText("out_pallets", stats.pallets.toLocaleString());
    setText("out_mod_per_cont", stats.mods_container);
    setText("out_containers", stats.containers.toLocaleString());
    setText("out_spare_pct", stats.spares_pct.toFixed(1) + "%");
    setText("out_containers_spares", stats.containers_inc_spares.toLocaleString());

    const tabClass = state.activeTab === "central" ? "stat-val orange" : "stat-val cyan";
    setClass("out_dc_capacity", tabClass);
    setClass("out_containers_spares", tabClass);

    const cpm = stats.dc_mwp > 0 ? stats.containers_inc_spares / stats.dc_mwp : 0;
    setText("out_cont_per_mwp", cpm.toFixed(2));
    setClass("out_cont_per_mwp", tabClass);
}

function renderBenchmark() {
    const mw = num("ref_mw"), mods = num("ref_modules");
    const implied = mw > 0 ? mods / mw : 0;
    setText("out_ref_implied", `~ ${Math.round(implied).toLocaleString()} modules/MW`);
}

function updateSelectedSubstationDisplay() {
    const s = state.selectedSubstation;
    if (!s) {
        setText("out_selected_sub_name", "None selected");
        setText("out_selected_sub_voltage", "Unknown");
        setText("out_selected_sub_lon", "n/a");
        setText("out_selected_sub_lat", "n/a");
        return;
    }
    setText("out_selected_sub_name", s.name || "Selected Substation");
    setText("out_selected_sub_voltage", s.voltage || "Unknown");
    setText("out_selected_sub_lon", s.coordinates ? Number(s.coordinates[0]).toFixed(6) : "n/a");
    setText("out_selected_sub_lat", s.coordinates ? Number(s.coordinates[1]).toFixed(6) : "n/a");
}

// ============================================================
// MAIN RECALC
// ============================================================
function recalcAll() {
    const stats = computeStats();
    state.lastStats = stats;
    renderTechSummary(stats);

    const prefix = state.activeTab === "string" ? "fin_string" : "fin_central";
    const fin = computeFinance(prefix, stats);
    state.lastFinance[prefix] = fin;
    renderFinance(prefix, fin);
    renderFinanceWarnings(prefix, fin, stats);

    renderBenchmark();
    updateSelectedSubstationDisplay();
}

const recalcDebounced = debounce(recalcAll, CONSTANTS.RECALC_DEBOUNCE_MS);

// ============================================================
// LEGEND
// ============================================================
function updateLegend() {
    const legend = $("map_legend");
    if (!legend) return;
    let html = `
        <div class="legend-item"><div class="swatch" style="background:#ffffff; border-color:#ff3333;"></div> Atlas Substation Dataset</div>
        <div class="legend-item"><div class="swatch" style="background:var(--substation);"></div> Point of Interconnection</div>
        <div class="legend-item"><div class="swatch" style="background:transparent; border-bottom: 2px dashed var(--substation);"></div> Export Cable</div>
        <div class="legend-item"><div class="swatch" style="background:var(--private-sub);"></div> Customer Substation</div>
        <div class="legend-item"><div class="swatch" style="background:var(--bess);"></div> BESS Compound</div>
        <div class="legend-item"><div class="swatch" style="background:var(--array-blue); opacity: 0.3; border-style: dashed;"></div> Total Array Boundary</div>`;
    if (state.activeTab === "string") {
        html += `<div class="legend-item"><div class="swatch" style="background:var(--inverter);"></div> String Substation Block</div>
                 <div class="legend-item"><div class="swatch" style="background:transparent; border-bottom: 2px solid var(--accent);"></div> Radial 33kV Spine</div>`;
    } else {
        html += `<div class="legend-item"><div class="swatch" style="background:var(--accent-alt);"></div> Central Inverter Block</div>
                 <div class="legend-item"><div class="swatch" style="background:transparent; border-bottom: 2px solid var(--accent);"></div> Radial 33kV Spine</div>`;
    }
    legend.innerHTML = html;
}

// ============================================================
// DRAWING
// ============================================================
function getRectPolygon(centerCoord, width_km, length_km, propType) {
    const pt = turf.point(centerCoord);
    const ptN = turf.destination(pt, length_km / 2, 0, { units: "kilometers" }).geometry.coordinates;
    const ptS = turf.destination(pt, length_km / 2, 180, { units: "kilometers" }).geometry.coordinates;
    const nw = turf.destination(turf.point(ptN), width_km / 2, -90, { units: "kilometers" }).geometry.coordinates;
    const ne = turf.destination(turf.point(ptN), width_km / 2, 90, { units: "kilometers" }).geometry.coordinates;
    const se = turf.destination(turf.point(ptS), width_km / 2, 90, { units: "kilometers" }).geometry.coordinates;
    const sw = turf.destination(turf.point(ptS), width_km / 2, -90, { units: "kilometers" }).geometry.coordinates;
    return turf.polygon([[nw, ne, se, sw, nw]], { type: propType });
}

function getBlockAspect() {
    const mountingVal = state.activeTab === "string" ? $("mounting_type").value : $("mounting_type_c").value;
    if (mountingVal === "0.45") return 1 / 1.4;
    if (mountingVal === "0.75") return 1.0;
    return 1.4;
}

function computeAndDraw() {
    if (!state.activeDrawCenter || !map) return;
    const stats = computeStats();
    state.lastStats = stats;

    if (stats.total_blocks === 0) {
        recalcAll();
        return;
    }

    const N = stats.total_blocks;
    const cols = Math.ceil(Math.sqrt(N));
    const rows = Math.ceil(N / cols);
    const block_area_km2 = stats.block_ground_area_m2 / 1_000_000;

    const aspect = getBlockAspect();
    const block_w = Math.sqrt(block_area_km2 / aspect);
    const block_l = block_w * aspect;
    const spacing = CONSTANTS.BLOCK_SPACING_KM;

    const grid_w = cols * block_w + (cols - 1) * spacing;
    const grid_l = rows * block_l + (rows - 1) * spacing;

    const features = [];
    const publicSubCoord = state.activeDrawCenter;
    const arrayOffsetKm = grid_l / 2 + CONSTANTS.ARRAY_OFFSET_KM;
    const gridCenter = turf.destination(turf.point(publicSubCoord), arrayOffsetKm, 0, { units: "kilometers" }).geometry.coordinates;
    const privateSubCoord = turf.destination(turf.point(gridCenter), grid_l / 2, 180, { units: "kilometers" }).geometry.coordinates;

    features.push(turf.point(publicSubCoord, {
        type: "poi",
        selected_substation_name: state.selectedSubstation?.name || "Local Grid Node",
        selected_substation_voltage: state.selectedSubstation?.voltage || "Unknown"
    }));
    features.push(turf.point(privateSubCoord, {
        type: "private_sub",
        selected_substation_name: "Customer Substation",
        selected_substation_voltage: "Local Voltage"
    }));
    features.push(turf.lineString([privateSubCoord, publicSubCoord], { type: "export_cable" }));
    features.push(getRectPolygon(gridCenter, grid_w + CONSTANTS.BOUNDARY_BUFFER_KM, grid_l + CONSTANTS.BOUNDARY_BUFFER_KM, "array_boundary"));

    const ptN = turf.destination(turf.point(gridCenter), grid_l / 2, 0, { units: "kilometers" }).geometry.coordinates;
    const ptNW = turf.destination(turf.point(ptN), grid_w / 2, -90, { units: "kilometers" }).geometry.coordinates;

    const inverters = [];
    let count = 0;
    for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
            if (count >= N) break;
            const posE = turf.destination(turf.point(ptNW), c * block_w + c * spacing + block_w / 2, 90, { units: "kilometers" }).geometry.coordinates;
            const finalPos = turf.destination(turf.point(posE), r * block_l + r * spacing + block_l / 2, 180, { units: "kilometers" }).geometry.coordinates;
            const nodeType = state.activeTab === "string" ? "string_substation" : "central_inverter";
            const footType = state.activeTab === "string" ? "skid_footprint" : "central_footprint";
            features.push(getRectPolygon(finalPos, block_w, block_l, footType));
            inverters.push({ coords: finalPos, type: nodeType });
            features.push(turf.point(finalPos, { type: nodeType }));
            count++;
        }
    }

    // BESS
    const prefix = state.activeTab === "string" ? "fin_string" : "fin_central";
    const bess_mwh = num(prefix + "_bess_mwh");
    if (bess_mwh > 0) {
        const bess_area_km2 = (bess_mwh * CONSTANTS.BESS_M2_PER_MWH) / 1_000_000;
        const bess_w = Math.sqrt(bess_area_km2 * CONSTANTS.BESS_ASPECT);
        const bess_l = bess_area_km2 / bess_w;
        const bessCenter = turf.destination(turf.point(privateSubCoord), bess_w / 2 + 0.05, -90, { units: "kilometers" }).geometry.coordinates;
        features.push(getRectPolygon(bessCenter, bess_w, bess_l, "bess_footprint"));
        features.push(turf.point(bessCenter, { type: "bess_compound", mwh: bess_mwh }));
        features.push(turf.lineString([bessCenter, privateSubCoord], { type: "33kv_radial" }));
    }

    // Spine
    if (inverters.length > 0) {
        let spineN = -90, spineS = 90;
        inverters.forEach(inv => {
            if (inv.coords[1] > spineN) spineN = inv.coords[1];
            if (inv.coords[1] < spineS) spineS = inv.coords[1];
        });
        if (privateSubCoord[1] > spineN) spineN = privateSubCoord[1];
        if (privateSubCoord[1] < spineS) spineS = privateSubCoord[1];
        features.push(turf.lineString([[privateSubCoord[0], spineS], [privateSubCoord[0], spineN]], { type: "33kv_radial" }));
        inverters.forEach(inv => {
            features.push(turf.lineString([inv.coords, [privateSubCoord[0], inv.coords[1]]], { type: "33kv_radial" }));
        });
    }

    state.currentGeoJSON = turf.featureCollection(features);
    const src = map.getSource("topology");
    if (src) src.setData(state.currentGeoJSON);

    if (features.length > 0) {
        const bbox = turf.bbox(state.currentGeoJSON);
        map.fitBounds(bbox, { padding: 60, duration: 800 });
    }

    // Refresh side-panel values
    renderTechSummary(stats);
    const fin = computeFinance(prefix, stats);
    state.lastFinance[prefix] = fin;
    renderFinance(prefix, fin);
    renderFinanceWarnings(prefix, fin, stats);
}

// ============================================================
// EXPORT
// ============================================================
function exportGeoJSON() {
    if (state.currentGeoJSON.features.length === 0) return;
    const exportData = JSON.parse(JSON.stringify(state.currentGeoJSON));
    const boundary = exportData.features.find(f => f.properties.type === "array_boundary");
    if (!boundary) return triggerDownload(exportData);

    const stats = state.lastStats || computeStats();
    const prefix = state.activeTab === "string" ? "fin_string" : "fin_central";
    const fin = state.lastFinance[prefix] || computeFinance(prefix, stats);

    const suffix = state.activeTab === "string" ? "" : "_c";
    const logisticsPreset = $("logistics_preset" + suffix)?.value || "manual";
    const grossFactor = num("gross_factor" + suffix);
    const gcr = parseFloat($("mounting_type" + suffix)?.value) || 0;
    const moduleRatingWp = num("mod_wp" + suffix);

    const topologyProps = state.activeTab === "string" ? {
        tech_modules_per_string: intVal("x_mods"),
        tech_strings_per_inverter: intVal("z_strings"),
        tech_inverters_per_substation: intVal("y_invs"),
        tech_substations_per_33kv_ring: intVal("s_subs"),
        tech_33kv_rings: intVal("b_cols")
    } : {
        tech_central_ac_rating_mwac: num("inv_ac_mw_c"),
        tech_modules_per_string: intVal("x_mods_c"),
        tech_strings_per_combiner_box: intVal("str_per_cb_c"),
        tech_central_inverters_per_mv_station: intVal("inv_per_mv_c"),
        tech_mv_stations_per_33kv_ring: intVal("mv_per_ring_c"),
        tech_33kv_rings: intVal("rings_c"),
        tech_combiner_boxes_per_inverter: stats.combiner_boxes_per_inverter,
        tech_total_combiner_boxes: stats.total_combiner_boxes
    };

    boundary.properties = {
        ...boundary.properties,
        fin_active_tab: state.activeTab,
        fin_export_note: "Engineering screening output only. Not construction design, financial advice, EPC pricing, grid compliance, logistics planning or transport instruction. Electrical loss fields are assumption fields and require competent project specific verification. Selected substation is a public dataset reference point and does not confirm available capacity, connection rights, voltage  … [line shortened here: 434 characters; full line on GitHub]

        grid_selected_substation_name: state.selectedSubstation?.name || null,
        grid_selected_substation_voltage: state.selectedSubstation?.voltage || null,
        grid_selected_substation_lon: state.selectedSubstation?.coordinates?.[0] ?? null,
        grid_selected_substation_lat: state.selectedSubstation?.coordinates?.[1] ?? null,
        grid_selected_substation_properties: state.selectedSubstation?.properties || null,

        tech_module_rating_wp: moduleRatingWp,
        tech_module_length_m: num("mod_l" + suffix),
        tech_module_width_m: num("mod_w" + suffix),
        tech_ground_coverage_ratio: gcr,
        tech_gross_site_factor: grossFactor,

        tech_logistics_preset: logisticsPreset,
        tech_modules_per_packing_unit: stats.mods_pallet,
        tech_modules_per_40ft_container: stats.mods_container,
        tech_spare_allowance_percent: stats.spares_pct,
        tech_total_base_packing_units: stats.pallets,
        tech_total_base_containers: stats.containers,
        tech_total_modules_inc_spares: stats.modules_inc_spares,
        tech_total_packing_units_inc_spares: stats.pallets_inc_spares,
        tech_total_containers_inc_spares: stats.containers_inc_spares,
        tech_containers_per_mwp: stats.dc_mwp > 0 ? Number((stats.containers_inc_spares / stats.dc_mwp).toFixed(2)) : 0,

        ...topologyProps,

        tech_module_count: stats.module_count,
        tech_dc_capacity_mwp: stats.dc_mwp,
        tech_ac_capacity_mwac: stats.ac_mw,
        tech_net_mod_area_m2: stats.net_mod_area_m2,
        tech_net_array_area_m2: stats.net_array_area_m2,
        tech_gross_site_area_m2: stats.gross_site_area_m2,

        // Finance — numbers, not formatted strings
        fin_total_capex_gbp: Math.round(fin.totalCapex),
        fin_capex_per_wp_gbp: Number(fin.capexPerWp.toFixed(4)),
        fin_annual_rev_gbp: Math.round(fin.annualRevenue),
        fin_25yr_revenue_gbp: Math.round(fin.revenue25),
        fin_35yr_revenue_gbp: Math.round(fin.revenue35),
        fin_25yr_surplus_gbp: Math.round(fin.surplus25),
        fin_35yr_surplus_gbp: Math.round(fin.surplus35),
fin_development_stage: fin.devStage,
fin_development_cost_gbp_mw: fin.devCostPerMw,
fin_development_module_supply_cost_gbp_mwp: fin.devModulePerMwp,
fin_development_epc_cost_gbp_mw: fin.devEpcPerMw,
fin_development_owner_cost_gbp_mw: fin.devOwnerPerMw,
fin_development_grid_connection_cost_gbp_mw: fin.devGridPerMw,
fin_development_exit_value_gbp_mwp: fin.devExitPerMwp,
fin_development_operating_npv_gbp_mwp: fin.devNpvPerMwp,
fin_development_success_probability_percent: fin.devSuccessPct,
fin_development_years: fin.devYears,
fin_development_capital_at_risk_gbp: Math.round(fin.devCapitalAtRisk),
fin_development_module_supply_cost_gbp: Math.round(fin.devModuleCost),
fin_development_epc_cost_gbp: Math.round(fin.devEpcCost),
fin_development_owner_cost_gbp: Math.round(fin.devOwnerCost),
fin_development_grid_connection_cost_gbp: Math.round(fin.devGridCost),
fin_development_total_build_cost_gbp: Math.round(fin.devTotalBuildCost),
fin_development_target_exit_value_gbp: Math.round(fin.devExitValue),
fin_development_operating_npv_gbp: Math.round(fin.devOperatingNpv),
fin_development_gross_margin_gbp: Math.round(fin.devGrossMargin),
fin_development_risk_adjusted_value_gbp: Math.round(fin.devRiskAdjustedValue),
fin_development_return_multiple: Number(fin.devReturnMultiple.toFixed(4)),

        fin_energy_price_gbp_mwh: fin.price,
        fin_other_income_gbp_mwh: fin.other,
        fin_yield_kwh_kwp: fin.yieldVal,
        fin_bifacial_gain: fin.bifacial,
        fin_flood_resilience: fin.floodActive,
        fin_flood_adder_gbp_wp: fin.floodRate,

        fin_base_losses_percent: fin.baseLoss,
        fin_loss_dc_string_percent: num(prefix + "_loss_dc_string"),
        fin_loss_lv_main_dc_percent: num(prefix + "_loss_lv_dc"),
        fin_loss_lv_ac_percent: num(prefix + "_loss_lv_ac"),
        fin_loss_transformer_percent: num(prefix + "_loss_tx"),
        fin_loss_other_electrical_percent: num(prefix + "_loss_other"),

        fin_opex_gbp_mwac_year: fin.opexRate,
        fin_epc_ex_modules_gbp_wp: fin.epcEx,
        fin_modules_gbp_wp: fin.modules,
        fin_other_capex_gbp_wp: fin.otherCapex,
        fin_fixed_capex_gbp: fin.fixedCapex,
        fin_contingency_percent: fin.cont,
        fin_bess_mw: fin.bessMw,
        fin_bess_mwh: fin.bessMwh,
        fin_bess_capex_gbp_mwh: fin.bessCapexRate,
        fin_bess_cycles_year: fin.bessCycles,
        fin_bess_spread_gbp_mwh: fin.bessSpread,
        fin_bess_efficiency_percent: fin.bessEff
    };

    triggerDownload(exportData);
}

function triggerDownload(data) {
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `gis_sld_${state.activeTab}_neat_grid.geojson`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    setTimeout(() => URL.revokeObjectURL(url), 1000);
}

// ============================================================
// 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();
    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 }));
    }
}

// ============================================================
// 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];
    computeAndDraw();
    updateSelectedSubstationDisplay();
}

// ============================================================
// 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);
    }
}

// ============================================================
// WIRE EVERYTHING UP
// ============================================================
function wireEvents() {
    // 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);

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

    // 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"));