GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world

Pad and 1 more file

A JavaScript module in the world folder of GlobalGrid2050 that works with transformers, using ISO 668. It formats pad line (`formatPadLine`) and creates pad layer (`createPadLayer`).

515 lines of JavaScript from globalgrid2050, in 2 files. Topic: Solar and storage design. Section 148 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. Pad transform · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/pad.mjs lines 1–268
  2. Project UI interaction · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/project-ui.mjs lines 1–247

Pad

A JavaScript module in the world folder of GlobalGrid2050 that works with transformers, using ISO 668. It formats pad line (`formatPadLine`) and creates pad layer (`createPadLayer`).

transformglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/pad.mjs · lines 1–268 of 268 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern corners (shared by 2 files)

What it does
It calculates transformers. Defines 19 functions or classes, including frame, padFootprint, createPad, off, padGround.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: transformers.
Downstream impact
Used directly by 2 files: Design Earthworks (globalgrid2050); Design Earthworks (globalgrid2050).
What it achieves
Level platforms for transformer foundations, inverter skids and battery compounds.
Why it matters
Imported by Design Earthworks.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world · JavaScript module
Uses
Earthworks (import)
Used by
imported by Design Earthworks (import), imported by Design Earthworks (import), mentioned in Standalone (comment link)
Produces
PAD_DEFAULTS, PAD_KINDS, PAD_COLORS, frame, padFootprint, createPad, padGround, padLines, padUnits, padSolids, formatPadLine, createPadLayer
Defines here
frame, padFootprint, createPad, off, padGround, daylight, padLines, F, ring, batch, padUnits, corners, boxEdges, padSolids, fmt, formatPadLine, createPadLayer, specs, raw
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-design-studio/202609270330-site-world-v3/world/pad.mjs:1-268 · blob b9c94ae073c204ce7708aad55e3e91b906a525bb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// pad.mjs: level platforms for transformer foundations, inverter skids and battery compounds.
//
// Local metres: x east, y north, z up, as camera.mjs. The ground is any function groundAt(x, y).
// No DOM, no WebGL. Sampling, batters, volumes, the balanced level, the daylight search and the ground with pads in it
// come from the shared earthworks engine (lib/earthworks.mjs), which the trench and road cartridges use too. The
// default export is a pad layer for a host that imports it (it imports the engine, so it is not a blob-URL layer).
//
// A pad is a plan polygon (or a rectangle: centre, width, depth, compass heading) cut or filled to a
// formation level, with a stone layer on top and batters on every side. The finished surface is
//   inside the polygon:  formation + stone
//   outside:             clamp(ground, formation - d / fillBatter, formation + d / cutBatter)
// where d is the plan distance to the polygon. So a batter rises from the formation edge into higher
// ground, falls from it onto lower ground, and meets the ground at the daylight line. Batters are
// horizontal metres per metre of height; corners come out as part-cones (distance is round at a corner).
//
// Volumes are the midpoint rule over square cells, anchored exactly as measure.mjs cutFillForPlatform
// (floor of min x and y, centres at (i + 0.5) cell, the same even-odd test), so the platform share of
// the cut and fill equals cutFillForPlatform to the last digit (tests/pad.test.mjs checks it). Volumes
// are bank (in place) measure: no bulking or shrinkage is applied. import = stone + any fill shortfall;
// export = any surplus cut. Stone volume is the exact polygon area times the thickness.
//
// ASSUMED, TYPICAL VALUES (not from any survey or design for a real site):
//   stone 0.30 m: granular sub-base, as the Type 1 layer of the Specification for Highway Works (MCHW
//     Vol 1) Series 800, clause 803; thickness depends on the ground and the loads, and is a designer's call.
//   batters 1 in 2 in cut and in fill: ASSUMED typical starting slopes, no geotechnical data; the same
//     figures and wording as road.mjs, so one site has one set of slopes. (SHW Series 600 governs the fill
//     materials and compaction, not the slope.)
//   drainage fall: none unless `fall` is given (a fraction, e.g. 0.01 = 1 in 100, falling towards the compass
//     `fallHeading`); 1 in 100 to 1 in 200 is typical for plant pads (assumed). `level` is then the formation at
//     the pad centre.
//   topsoil: `topsoil` metres (0 unless given; 0.3 m typical, assumed) stripped under the platform and batters is
//     reported as volumes.topsoil. It is not counted as fill: it goes to a stockpile for reinstatement.
//   transformer pad 12 x 10 m with a 4 x 4 x 3 m unit: the station library's own figures (station.mjs,
//     source line L100 "4 x 4 x 3 m, 12 x 10 m pad"); plinth 5 x 5 x 0.3 m assumed.
//   inverter skid and battery units: 20 ft container outline, 6.058 x 2.438 x 2.591 m (ISO 668, series 1
//     freight container 1CC external size); pads, plinths, gaps and unit counts assumed.

import {
  inv, polyArea, sampleCells, volumesAt, balance, padHeight, nearPad, daylight as daylightAlong, composeGround
} from './lib/earthworks.mjs';

export { padHeight };
const EPS = 1e-9;
export const PAD_DEFAULTS = Object.freeze({ stone: 0.3, cutBatter: 2, fillBatter: 2, cell: 0.25, maxReach: 120, fall: 0, fallHeading: 0, topsoil: 0 });
const C20 = { w: 2.438, d: 6.058, h: 2.591 };
export const PAD_KINDS = Object.freeze({
  transformer: { width: 12, depth: 10, units: [{ x: 0, y: 0, w: 4, d: 4, h: 3, plinth: { w: 5, d: 5, h: 0.3 } }] },
  inverterSkid: { width: 5, depth: 9, units: [{ x: 0, y: 0, ...C20, plinth: { w: 3, d: 6.6, h: 0.3 } }] },
  batteryCompound: {
    width: 30, depth: 20,
    units: [-8, 0, 8].flatMap(x => [-4.5, 4.5].map(y => ({ x, y, ...C20, plinth: { w: 3, d: 6.6, h: 0.3 } })))
  }
});
export const PAD_COLORS = {
  outline: [0.86, 0.86, 0.82, 0.70], formation: [0.62, 0.58, 0.50, 0.50],
  batter: [0.72, 0.64, 0.48, 0.40], daylight: [0.80, 0.70, 0.50, 0.55], unit: [0.70, 0.80, 0.92, 0.65]
};

// ---------------------------------------------------------------- plan geometry

// Compass heading: 0 = the pad's +v points north, pi/2 = east. u runs across (width), v along (depth).
export function frame(centre, heading = 0) {
  const s = Math.sin(heading), c = Math.cos(heading), [cx, cy] = centre;
  return (u, v) => [cx + u * c + v * s, cy - u * s + v * c];
}

/** Anticlockwise open ring from a polygon, or from { centre, width, depth, heading }. */
export function padFootprint(spec) {
  let pts;
  if (Array.isArray(spec.polygon)) pts = spec.polygon.map(p => [Number(p[0]), Number(p[1])]);
  else {
    if (!(spec.width > 0 && spec.depth > 0) || !Array.isArray(spec.centre)) throw Error('pad: give a polygon, or a centre, width and depth');
    const at = frame(spec.centre, spec.heading || 0), w = spec.width / 2, d = spec.depth / 2;
    pts = [at(-w, -d), at(w, -d), at(w, d), at(-w, d)];
  }
  if (pts.length > 1) { const a = pts[0], b = pts[pts.length - 1]; if (Math.abs(a[0] - b[0]) < EPS && Math.abs(a[1] - b[1]) < EPS) pts.pop(); }
  if (pts.length < 3 || pts.some(p => !Number.isFinite(p[0]) || !Number.isFinite(p[1]))) throw Error('pad: polygon needs three finite points');
  let a = 0;
  for (let i = 0; i < pts.length; i++) { const p = pts[i], q = pts[(i + 1) % pts.length]; a += p[0] * q[1] - q[0] * p[1]; }
  if (Math.abs(a) < EPS) throw Error('pad: polygon has no area');
  return a > 0 ? pts : pts.reverse();
}

/**
 * createPad(spec, groundAt) -> pad
 * spec: polygon [[x, y], ...] or { centre, width, depth, heading }; kind (a PAD_KINDS key) fills in the
 * size and units; level (formation, m) or finishedLevel (top of stone), else the level balances cut and
 * fill; stone, cutBatter, fillBatter, cell, maxReach as PAD_DEFAULTS; units [{ x, y, w, d, h, plinth }].
 */
export function createPad(spec, groundAt) {
  if (typeof groundAt !== 'function') throw Error('pad: groundAt must be a function');
  const kind = spec.kind ? PAD_KINDS[spec.kind] : null;
  if (spec.kind && !kind) throw Error(`pad: unknown kind "${spec.kind}"`);
  const s = { ...PAD_DEFAULTS, ...(kind || {}), ...spec };
  if (!(s.stone >= 0) || !(s.cutBatter >= 0) || !(s.fillBatter >= 0) || !(s.cell > 0)) throw Error('pad: stone, batters and cell must be >= 0 (cell > 0)');
  const pts = padFootprint(s), invCut = inv(s.cutBatter), invFill = inv(s.fillBatter);
  if (!(s.fall >= 0 && s.fall < 0.2) || !(s.topsoil >= 0)) throw Error('pad: fall must be 0 to 0.2 and topsoil >= 0');
  const centre = spec.centre || pts.reduce((m, p) => [m[0] + p[0] / pts.length, m[1] + p[1] / pts.length], [0, 0]);
  const fx = Math.sin(s.fallHeading), fy = Math.cos(s.fallHeading);
  const off = (x, y) => -s.fall * ((x - centre[0]) * fx + (y - centre[1]) * fy); // formation falls towards fallHeading
  const chosen = Number.isFinite(s.level) ? s.level : Number.isFinite(s.finishedLevel) ? s.finishedLevel - s.stone : null;
  let reach = Math.max(s.cutBatter, s.fillBatter) > 0 ? Math.min(4, s.maxReach) : 0, cells, level, v;
  for (;;) {                                                      // grow the sample until the batters fit inside it
    cells = sampleCells(pts, groundAt, s.cell, reach, off);
    level = chosen ?? balance(cells, invCut, invFill);
    v = volumesAt(cells, level, invCut, invFill);
    if (!v.edge || reach >= s.maxReach) break;
    reach = Math.min(reach * 2, s.maxReach);
  }
  const cut = v.platformCut + v.batterCut, fill = v.platformFill + v.batterFill, polygonArea = polyArea(pts);
  const stone = polygonArea * s.stone;
  // Plant level: the lowest point of the finished top against the highest ground under the pad. Below it, the pad
  // sits in a hollow that collects water (a sump) unless it is drained.
  const topLow = level + s.stone + Math.min(...pts.map(p => off(p[0], p[1])));
  return {
    fall: s.fall, fallHeading: s.fallHeading, off, topsoil: s.topsoil,
    plant: { topLow, groundHigh: v.gMax, sump: topLow < v.gMax - 1e-9 },
    kind: spec.kind || null, polygon: pts, centre, heading: s.heading || 0, level, top: level + s.stone,
    stone: s.stone, cutBatter: s.cutBatter, fillBatter: s.fillBatter, balanced: chosen === null, units: s.units || [],
    reach, truncated: v.edge > 0, cell: s.cell,
    volumes: {
      cut, fill, net: cut - fill, stone, import: stone + Math.max(fill - cut, 0), export: Math.max(cut - fill, 0),
      platformCut: v.platformCut, platformFill: v.platformFill, batterCut: v.batterCut, batterFill: v.batterFill,
      area: v.area, polygonArea, footprint: v.footprint, topsoil: v.footprint * s.topsoil
    }
  };
}

/** The ground with every pad in the list pressed into it (the first pad containing the point wins). */
export const padGround = (pads, groundAt) => composeGround(groundAt, { pads: [...pads] });

// ---------------------------------------------------------------- drawing

// Distance along a ray from a boundary point to where the batter meets the ground (the daylight point).
function daylight(pad, px, py, ux, uy, groundAt) {
  const step = Math.max(pad.cell, 0.1), meets = t => {
    const x = px + ux * t, y = py + uy * t, g = groundAt(x, y);
    return !Number.isFinite(g) || Math.abs(padHeight(pad, x, y, groundAt) - g) < 1e-6;
  };
  return daylightAlong(meets, step, pad.reach + step);
}

/**
 * padLines(pad, groundAt, { spacing = 2, origin }) -> line batches for the substrate.
 * Outline at the top of stone, the formation edge, batter hachures from the formation edge to the
 * daylight line, the daylight line itself, and each unit and its plinth as a wireframe box.
 */
export function padLines(pad, groundAt, { spacing = 2, key = 'pad', version = 0 } = {}) {
  const o = [pad.centre[0], pad.centre[1], pad.top], P = (x, y, z) => [x - o[0], y - o[1], z - o[2]];
  const F = (x, y) => (pad.off ? pad.off(x, y) : 0);
  const ring = z => pad.polygon.flatMap((p, i) => { const q = pad.polygon[(i + 1) % pad.polygon.length]; return [...P(p[0], p[1], z + F(...p)), ...P(q[0], q[1], z + F(...q))]; });
  const hach = [], day = [];
  const n = pad.polygon.length;
  for (let i = 0; i < n; i++) {
    const a = pad.polygon[i], b = pad.polygon[(i + 1) % n], c = pad.polygon[(i + 2) % n];
    const len = Math.hypot(b[0] - a[0], b[1] - a[1]), ux = (b[1] - a[1]) / len, uy = -(b[0] - a[0]) / len; // outward (anticlockwise ring)
    const rays = [];
    const m = Math.max(1, Math.ceil(len / spacing));
    for (let k = 0; k <= m; k++) rays.push([a[0] + (b[0] - a[0]) * k / m, a[1] + (b[1] - a[1]) * k / m, ux, uy]);
    // Convex corner at b: fan the rays round the part-cone to the next edge's normal.
    const l2 = Math.hypot(c[0] - b[0], c[1] - b[1]), vx = (c[1] - b[1]) / l2, vy = -(c[0] - b[0]) / l2;
    const turn = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
    if (turn > 0) for (let f = 1, fans = Math.ceil(turn / (Math.PI / 12)); f < fans; f++) {
      const t = Math.atan2(uy, ux) + turn * f / fans; rays.push([b[0], b[1], Math.cos(t), Math.sin(t)]);
    }
    for (const [x, y, rx, ry] of rays) {
      const t = pad.reach > 0 ? daylight(pad, x, y, rx, ry, groundAt) : 0;
      const dx = x + rx * t, dy = y + ry * t, dz = padHeight(pad, dx, dy, groundAt);
      day.push([dx, dy, Number.isFinite(dz) ? dz : pad.level]);
      if (t > 0.05) hach.push(...P(x, y, pad.level + F(x, y)), ...P(dx, dy, day[day.length - 1][2]));
    }
  }
  const dayPos = day.flatMap((p, i) => { const q = day[(i + 1) % day.length]; return [...P(...p), ...P(...q)]; });
  const units = padUnits(pad).flatMap(bx => boxEdges(bx.corners, bx.z0, bx.z1).map(v => [v[0] - o[0], v[1] - o[1], v[2] - o[2]]).flat());
  const batch = (part, positions) => ({ key: `${key}/${part}`, version, origin: o, color: PAD_COLORS[part], positions: new Float32Array(positions) });
  return [batch('outline', ring(pad.top)), batch('formation', ring(pad.level)), batch('batter', hach),
    batch('daylight', dayPos), batch('unit', units)].filter(b => b.positions.length);
}

// Units and their plinths as boxes: plan corners in local metres, bottom and top heights.
export function padUnits(pad) {
  const at = frame(pad.centre, pad.heading), out = [];
  const corners = (x, y, w, d) => [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => at(x + a * w / 2, y + b * d / 2));
  for (const u of pad.units) {
    const ph = u.plinth ? u.plinth.h : 0, c = at(u.x, u.y), top = pad.top + (pad.off ? pad.off(c[0], c[1]) : 0);
    if (u.plinth) out.push({ part: 'plinth', corners: corners(u.x, u.y, u.plinth.w, u.plinth.d), z0: top, z1: top + ph });
    out.push({ part: 'unit', corners: corners(u.x, u.y, u.w, u.d), z0: top + ph, z1: top + ph + u.h });
  }
  return out;
}

function boxEdges(c, z0, z1) {
  const out = [];
  for (let i = 0; i < 4; i++) {
    const p = c[i], q = c[(i + 1) % 4];
    out.push([p[0], p[1], z0], [q[0], q[1], z0], [p[0], p[1], z1], [q[0], q[1], z1], [p[0], p[1], z0], [p[0], p[1], z1]);
  }
  return out;
}

/** Solids for walkers and the drone: the plan-aligned box round each plinth and unit. */
export function padSolids(pad) {
  return padUnits(pad).map(b => {
    const xs = b.corners.map(p => p[0]), ys = b.corners.map(p => p[1]);
    return { min: [Math.min(...xs), Math.min(...ys), b.z0], max: [Math.max(...xs), Math.max(...ys), b.z1] };
  });
}

const fmt = (x, dp = 1) => (Math.abs(x) < 0.5 * 10 ** -dp ? 0 : x).toFixed(dp).replace(/\B(?=(\d{3})+(?!\d))/g, ',');

/** "Pad 120.0 m² · formation 101.20 m (balanced) · cut 35.2 m³ · fill 35.2 m³ · stone 36.0 m³ · import 36.0 m³" */
export function formatPadLine(pad) {
  const v = pad.volumes;
  return [`Pad ${fmt(v.polygonArea)} m²`, `formation ${fmt(pad.level, 2)} m${pad.balanced ? ' (balanced)' : ''}`,
    `cut ${fmt(v.cut)} m³`, `fill ${fmt(v.fill)} m³`, `stone ${fmt(v.stone)} m³`,
    `import ${fmt(v.import)} m³`, v.export > 0.05 ? `surplus ${fmt(v.export)} m³` : null,
    pad.topsoil > 0 ? `topsoil strip ${fmt(v.topsoil)} m³` : 'bank volumes, no topsoil strip',
    pad.plant.sump ? 'top below the highest ground under the pad' : null,
    pad.truncated ? 'batters reach past the sampled area' : null].filter(Boolean).join(' · ');
}

// ---------------------------------------------------------------- layer

/**
 * createPadLayer({ pads }) or, from the manifest, config.pads: [{ kind, e, n, heading, ... }] in national-grid
 * metres (or x, y local, or polygon_en [[e, n], ...]). List it BEFORE terrain: its heightAt returns the
 * finished pad surface near a pad and NaN elsewhere, so the ground everyone stands on includes the pads.
 */
export function createPadLayer(opts = {}) {
  let api = null, ground = null, busy = false, built = { version: null, pads: [], batches: [] };
  const specs = () => {
    const list = opts.pads || api?.config?.pads || [], o = api?.origin?.() || { e: 0, n: 0 };
    return list.map(p => ({
      ...p, centre: p.centre || (Number.isFinite(p.e) ? [p.e - o.e, p.n - o.n] : Number.isFinite(p.x) ? [p.x, p.y] : undefined),
      polygon: p.polygon || (p.polygon_en ? p.polygon_en.map(([e, n]) => [e - o.e, n - o.n]) : undefined)
    }));
  };
  const layer = {
    id: 'pad', status: 'waiting for ground',
    init(a) { api = a; layer.status = 'ready'; },
    heightAt(x, y) {
      if (busy || !ground) return NaN;
      busy = true;                                             // the substrate's ground asks us again: say NaN
      try { for (const p of built.pads) if (nearPad(p, x, y)) return padHeight(p, x, y, ground); return NaN; } finally { busy = false; }
    },
    lines(ctx) {
      if (typeof ctx.heightAt !== 'function') return [];
      const o = api?.origin?.(), version = `${o ? `${o.e},${o.n},${o.id}` : ''}@${ctx.groundVersion ?? 0}`;
      if (built.version === version) return built.batches;
      ground = null; busy = true;                              // build on the bare ground, not on the old pads
      try {
        const raw = (x, y) => ctx.heightAt(x, y);
        const pads = specs().map(s => createPad(s, raw));
        const batches = pads.flatMap((p, i) => padLines(p, raw, { key: `pad/${i}`, version }));
        built = { version, pads, batches, solids: pads.flatMap(padSolids) };
        layer.status = pads.map(formatPadLine).join(' | ') || 'no pads';
        ground = raw;
      } catch (e) { layer.status = 'pads not built: ' + e.message; built = { version, pads: [], batches: [], solids: [] }; }
      finally { busy = false; }
      return built.batches;
    },
    solids: () => built.solids || [],
    debug: () => built
  };
  return layer;
}

export default createPadLayer();

Project UI

A JavaScript module in the world folder of GlobalGrid2050 that draws sites and cables. It hides choice (`hideChoice`), sets tour (`setTour`) and refreshes phases (`refreshPhases`).

interactionglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/project-ui.mjs · lines 1–247 of 247 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern refreshPhases (shared by 2 files)

What it does
It draws sites and cables. Defines 19 functions or classes, including save, plain, mountProject, $, note. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables.
Inputs & outputs
In: JSON file sites.json.
What it achieves
Project tools, placed under the dash's essentials: the design file (Save, Open, Share, Print), Tour and Construction phases in the Design panel; Test sites in the Find panel. It responds to click, change and toggle events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world · JavaScript module
Uses
Design Store (import), Tour (import), Print (import), Phases (import), Phases Design (import), Phases Slider (import), Sites UI (import)
Used by
mentioned in Standalone (comment link)
Produces
mountProject
Defines here
save, plain, mountProject, $, note, pts, toDoc, fromDoc, path, of, flyToDesign, hideChoice, shareTab, offerChoice, b, press, setTour, refreshPhases, ready
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-design-studio/202609270330-site-world-v3/world/project-ui.mjs:1-247 · blob 6228acf4a29559f0f443f860cd650446e68376e4 · 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: duplicate_candidate
// Project tools, placed under the dash's essentials: the design file (Save, Open, Share, Print), Tour and
// Construction phases in the Design panel; Test sites in the Find panel.
// It wires existing cartridges to the world through the substrate's extension api; it draws nothing itself.
//   design-store.mjs   the design as a world.design.v1 document in national-grid metres; kept in this browser
//   tour.mjs           record a walk or flight, play it back, save it; Open reads tour files too
//   print.mjs          the plan sheet (A3 or A4) with the current view and the exact credit
//   phases*.mjs        the construction sequence of the drawn trenches and cables, as a step slider with order checks
//   sites-ui.mjs       the staged sites (data/sites.json, local only); choosing one reloads the page with ?site=<name>
import { SCHEMA, exportFile, importText, makeShareLink, readShareLink, autosave, loadAutosave } from './design-store.mjs';
import { createRecorder, exportTour, importTour, createPlayer } from './tour.mjs';
import { buildSheet, captureView, openSheet } from './print.mjs';
import { createTimeline, validatePlan } from './phases.mjs';
import { itemsFromStore } from './phases-design.mjs';
import { createPhaseSlider } from './phases-slider.mjs';
import { parseSites, createSiteChooser, mountSiteSelect } from './sites-ui.mjs';

const SITES_URL = './world/data/sites.json';
const WORKS = ['road', 'pad', 'fence', 'piles', 'hdd']; // earthworks kinds (design-earthworks.mjs), kept with the design

export { siteFromUrl } from './sites-ui.mjs'; // kept here for callers of the old place

function save(doc, name, text, type = 'application/json') {
  const url = URL.createObjectURL(new Blob([text], { type })), a = doc.createElement('a');
  a.href = url; a.download = name; doc.body.appendChild(a); a.click();
  setTimeout(() => { URL.revokeObjectURL(url); a.remove(); }, 30000);
}
const plain = o => JSON.parse(JSON.stringify(o)); // drops undefined, so params stay plain JSON

export function mountProject(api, doc = document) {
  const $ = id => doc.getElementById(id);
  const note = msg => { $('project-note').textContent = msg; };
  const s0 = api.site(), o0 = api.origin();
  const site = s0 ? { name: s0.name, origin_e: s0.centre_e, origin_n: s0.centre_n } : { name: 'untitled', origin_e: o0.e, origin_n: o0.n };
  let generation = 0;

  // ---- design file ------------------------------------------------------------------------------------
  const pts = path => path.map(p => [p.e, p.n]);
  function toDoc() {
    const d = api.design();
    const items = [
      ...d.trenches.map((t, i) => ({ id: `trench-${i + 1}`, kind: 'trench', params: plain({ section: t.section }), points_bng: pts(t.path) })),
      ...d.cables.map((c, i) => ({ id: `cable-${i + 1}`, kind: 'cable', params: plain({ section: c.section, cable: c.cable }), points_bng: pts(c.path) })),
      ...(d.works || []).map((w, i) => ({ id: `${w.kind}-${i + 1}`, kind: w.kind, params: plain({ option: w.option, ...(w.cable ? { cable: w.cable } : {}) }), points_bng: pts(w.path) }))
    ];
    return { schema: SCHEMA, generation, site: { ...site }, items };
  }
  // quiet: a design that only arrived (a shared link) is shown but not yet kept over the one in this browser.
  let quiet = false;
  function fromDoc(d, { keep = true } = {}) {
    const path = it => it.points_bng.map(([e, n]) => ({ e, n }));
    const of = kind => d.items.filter(i => i.kind === kind);
    generation = Math.max(generation, d.generation);
    const works = d.items.filter(i => WORKS.includes(i.kind)).map(i => ({ kind: i.kind, option: i.params?.option, ...(i.params?.cable ? { cable: i.params.cable } : {}), path: path(i) }));
    api.replaceDesign({
      trenches: of('trench').map(i => ({ path: path(i), section: i.params.section })),
      cables: of('cable').map(i => ({ path: path(i), section: i.params.section, cable: i.params.cable })),
      works
    });
    quiet = !keep;
    api.hooks.design.forEach(f => f());
    return of('trench').length + of('cable').length + works.length;
  }
  // The drone flies to a design that arrived from a link or a file, framing all its points (phone review 4).
  function flyToDesign(d) {
    const pts = d.items.flatMap(i => i.points_bng || []);
    if (!pts.length || typeof api.flyTo !== 'function') return;
    const es = pts.map(p => p[0]), ns = pts.map(p => p[1]);
    const e = (Math.min(...es) + Math.max(...es)) / 2, n = (Math.min(...ns) + Math.max(...ns)) / 2;
    const span = Math.max(Math.max(...es) - Math.min(...es), Math.max(...ns) - Math.min(...ns));
    const o = api.origin(), p = api.state().pos;
    if (Math.hypot(o.e + p[0] - e, o.n + p[1] - n) < 30 && span < 60) return; // already there
    api.flyTo(e - o.e, n - o.n, { height: Math.min(1500, Math.max(80, span * 1.2)) });
  }
  // Every change is kept in this browser, per site; a shared link or a file replaces it only when asked.
  api.hooks.design.add(() => {
    generation++;
    if (quiet) quiet = false; else { autosave(toDoc()); hideChoice(); }
    if (!$('design').hidden && $('phases-fold').open) refreshPhases();
  });
  // A shared link that arrives while a design is kept here: both stay; the viewer chooses which to show.
  const choice = doc.createElement('div');
  choice.className = 'row'; choice.id = 'share-choice'; choice.hidden = true;
  $('project-note').after(choice);
  function hideChoice() { choice.hidden = true; choice.replaceChildren(); }
  // The choice sits in the Design panel's Share tab (design-tabs.mjs): show that tab, whether or not the tabs are wired yet.
  function shareTab() {
    for (const t of doc.querySelectorAll('#design [role="tab"]')) {
      const on = t.dataset.tab === 'share', p = $(t.getAttribute('aria-controls'));
      t.setAttribute('aria-selected', String(on)); t.tabIndex = on ? 0 : -1; if (p) p.hidden = !on;
    }
    $('design-tab-share-btn')?.click(); // once the tabs are wired, they keep their own record in step
  }
  function offerChoice(shared, mine) {
    const b = (id, label, fn) => { const e = doc.createElement('button'); e.type = 'button'; e.id = id; e.textContent = label; e.addEventListener('click', fn); return e; };
    choice.replaceChildren(
      b('share-open', 'Open shared design', () => {
        hideChoice();
        note(`Opened the shared design: ${fromDoc(shared, { keep: false })} items. Your own is kept until you change this one.`);
        flyToDesign(shared);
      }),
      b('share-keep', 'Keep mine', () => { hideChoice(); note(`Kept your design: ${fromDoc(mine, { keep: false })} items.`); }));
    choice.hidden = false;
    shareTab();
  }

  $('project-save').addEventListener('click', async () => {
    try { const f = await exportFile(toDoc()); save(doc, f.filename, f.text); note(`Saved ${f.filename}.`); }
    catch (e) { note('Could not save: ' + e.message); }
  });
  $('project-open').addEventListener('click', () => $('project-file').click());
  $('project-file').addEventListener('change', async () => {
    const file = $('project-file').files?.[0];
    $('project-file').value = '';
    if (!file) return;
    const text = await file.text();
    if (text.includes('"world.tour.v1"')) {
      try { setTour(await importTour(text)); note(`Opened tour "${tour.name || file.name}". Press Play.`); }
      catch (e) { note('Tour refused: ' + e.message); }
      return;
    }
    const r = await importText(text);
    note(r.ok ? `Opened ${file.name}: ${fromDoc(r.doc)} items.` : 'File refused: ' + r.errors.join('; '));
    if (r.ok) flyToDesign(r.doc);
  });
  $('project-share').addEventListener('click', async () => {
    const r = await makeShareLink(toDoc());
    if (!r.ok) { note(r.errors.join('; ')); return; }
    const url = location.href.split('#')[0] + r.fragment, box = $('project-link');
    try { await navigator.clipboard.writeText(url); box.hidden = true; note(`Share link copied (${r.chars} characters).`); }
    catch { box.value = url; box.hidden = false; box.select(); note('Copy the link above to share this design.'); }
  });

  // ---- print --------------------------------------------------------------------------------------------
  $('project-print').addEventListener('click', () => {
    const attribution = api.attribution();
    if (!attribution) { note('Print needs the data credits, which did not load.'); return; }
    const image = captureView(api.canvas, api.redraw); // redraw and read in the same task, or the copy is blank
    const s = api.state(), g = api.heightAt(s.pos[0], s.pos[1]);
    openSheet(paper => buildSheet({
      paper, batches: api.batches(), attribution, viewImage: image, fade: api.FADE_M,
      camera: { pos: s.pos, yaw: s.yaw, pitch: s.pitch, fov: api.FOV, label: api.VIEWS[s.view].label, eyeHeight: s.pos[2] - g,
        aspect: api.canvas.height / api.canvas.width },
      origin: api.origin(), site: { name: site.name }, generation: api.generation(), layerIds: api.live().map(l => l.id)
    }));
  });

  // ---- tour ---------------------------------------------------------------------------------------------
  let recorder = null, t0 = 0, tour = null, player = null;
  const caption = $('tour-caption');
  const press = (id, on, label) => { $(id).setAttribute('aria-pressed', String(on)); $(id).textContent = label; };
  function setTour(t) {
    player?.pause(); player = null; tour = t;
    $('tour-play').disabled = $('tour-save').disabled = false;
    press('tour-play', false, 'Play');
  }
  api.hooks.before.add(now => {
    if (recorder) recorder.sample((now - t0) / 1000, api.origin(), api.state());
    if (player?.playing) {
      // Any movement takes the camera back; the substrate's gate carries on at the walking rate (review A, 3).
      if (api.moving()) { player.pause(); press('tour-play', false, 'Play'); api.resumeGate?.(); }
      else player.frame(now);
    }
  });
  $('tour-record').addEventListener('click', () => {
    if (!recorder) {
      player?.pause();
      recorder = createRecorder({ kind: api.state().view === 'aerial' ? 'drone' : 'walk', name: `${site.name} tour` });
      t0 = performance.now(); recorder.sample(0, api.origin(), api.state());
      press('tour-record', true, 'Stop');
      note('Recording: walk or fly, then press Stop.');
      return;
    }
    recorder.sample((performance.now() - t0) / 1000, api.origin(), api.state());
    try { setTour(recorder.stop()); note(`Tour recorded: ${tour.keyframes.length} keyframes. Play it or save it.`); }
    catch (e) { note('Nothing kept: ' + e.message + '. Move while recording.'); }
    recorder = null;
    press('tour-record', false, 'Record');
  });
  $('tour-play').addEventListener('click', () => {
    if (!tour) return;
    if (player?.playing) { player.pause(); press('tour-play', false, 'Play'); return; }
    if (!player) {
      api.setView(tour.kind === 'drone' ? 'aerial' : 'standing');
      player = createPlayer(tour, {
        gate: api.gate, getOrigin: api.origin, apply: pose => api.setPose(pose),
        onCaption: text => { caption.textContent = text; caption.hidden = !text; },
        onEnd: () => press('tour-play', false, 'Play')
      });
    }
    player.play();
    press('tour-play', true, 'Pause');
  });
  $('tour-save').addEventListener('click', async () => {
    if (!tour) return;
    try { save(doc, `${site.name}-tour.json`, await exportTour(tour)); note('Tour saved.'); } catch (e) { note('Could not save the tour: ' + e.message); }
  });

  // ---- construction phases ------------------------------------------------------------------------------
  function refreshPhases() {
    const box = $('phases-box'), check = $('phases-check');
    box.replaceChildren();
    const items = itemsFromStore(toDoc());
    if (!items.length) { check.textContent = 'Draw a trench or cable in Design to sequence its construction.'; return; }
    createPhaseSlider(box, createTimeline(items));
    const v = validatePlan(items);
    check.textContent = v.ok ? `Order checks: no problems across ${items.length} items.`
      : `Order checks: ${v.errors.map(e => e.message).join(' ')}`;
  }
  $('phases-fold').addEventListener('toggle', () => { if ($('phases-fold').open) refreshPhases(); });

  // ---- site ---------------------------------------------------------------------------------------------
  (async () => {
    let sites = [];
    try { const r = await fetch(SITES_URL, { cache: 'no-cache' }); if (r.ok) sites = parseSites(await r.json()).sites; } catch { /* none staged */ }
    if (!sites.length) return; // the Site section stays hidden where no sites are staged
    const chooser = createSiteChooser(sites, {
      current: s0?.name ?? null,
      onChoose: s => { const u = new URL(location.href); u.searchParams.set('site', s.name); u.hash = ''; location.assign(u.href); }
    });
    const select = mountSiteSelect(doc, $('site-box'), chooser);
    $('site-section').hidden = false;
    // Find can fly far from the site: then no site is current and the picker works again (phone review 5).
    let away = false;
    api.hooks.after.add(() => {
      if (away || !chooser.current) return;
      const o = api.origin(), p = api.state().pos, c = chooser.current;
      if (Math.hypot(o.e + p[0] - c.centre_e, o.n + p[1] - c.centre_n) > 3000) { away = true; chooser.leave(); select.value = ''; }
    });
  })();

  // ---- start: a shared link never overwrites the copy kept in this browser without asking -----------------
  const ready = (async () => {
    const kept = await loadAutosave(site), mine = kept.ok && kept.doc.items.length ? kept.doc : null;
    if (/(^#|&)design=/.test(location.hash)) {
      const r = await readShareLink(location.hash);
      if (!r.ok) { note('Shared link refused: ' + r.errors.join('; ')); if (mine) fromDoc(mine, { keep: false }); return; }
      const same = mine && JSON.stringify(mine.items) === JSON.stringify(r.doc.items);
      if (!mine || same) { note(`Opened the shared design: ${fromDoc(r.doc)} items.`); flyToDesign(r.doc); return; }
      note(`This link carries a design (${r.doc.items.length} items); yours (${fromDoc(mine, { keep: false })} items) is shown and kept.`);
      offerChoice(r.doc, mine);
      return;
    }
    if (mine) note(`Restored the design kept in this browser: ${fromDoc(mine, { keep: false })} items.`);
  })();

  return Object.freeze({ ready, toDoc, tour: () => tour, playing: () => !!player?.playing, recording: () => !!recorder });
}