// @wuys/map · data/topology.js
// Decode Natural Earth topojson (delta-encoded) into a normalized structure:
//   { arcs: [ [[lon, lat], ...], ... ], geometries: [ {id, type, arcs, properties}, ... ] }
//
// We don't depend on topojson-client — the format is simple enough that a 30-line
// decoder is preferable to a dependency.

/**
 * @param {Object} topo  raw topojson document
 * @returns {{ arcs: Array<Array<[number,number]>>, geometries: Array<Object> }}
 */
export function decodeTopojson(topo) {
  const { transform, arcs: rawArcs, objects } = topo;
  const [sx, sy] = transform.scale;
  const [tx, ty] = transform.translate;
  const arcs = rawArcs.map((arc) => {
    const out = [];
    let x = 0, y = 0;
    for (const pair of arc) {
      x += pair[0];
      y += pair[1];
      out.push([x * sx + tx, y * sy + ty]);
    }
    return out;
  });
  // Pick the first named object — usually `countries`.
  const objName = Object.keys(objects)[0];
  const geometries = objects[objName].geometries;
  return { arcs, geometries };
}

/**
 * Resolve a list of arc indices to a flat ring of points.
 * Negative indices mean "reverse the arc". Skipping the first point on subsequent
 * arcs avoids duplicate vertices at arc seams.
 */
export function ringFromArcs(arcRefs, arcs) {
  const pts = [];
  for (const idx of arcRefs) {
    const reverse = idx < 0;
    const realIdx = reverse ? ~idx : idx;
    let arc = arcs[realIdx];
    if (reverse) arc = arc.slice().reverse();
    const start = pts.length ? 1 : 0;
    for (let i = start; i < arc.length; i++) pts.push(arc[i]);
  }
  return pts;
}
