Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript
77.0 KB
Raw Blame
/**
 * Pure proof-document logic with no Konva or DOM dependency.
 *
 * Panels share a row height and rows stack vertically. Shape coordinates use
 * each panel's natural pixels so layout and zoom do not invalidate the spec.
 */

import { formatCoords as renderCoords } from './coords.js';
import {
  normalizeSourceCrop, normalizeSurfaceAngle, surfaceImageSize,
} from './proofSurface.js';
import { ICON_SIZE_DEFAULT } from './proofIcons.js';
import { isPageMark } from './pageMarks.js';
import { proofFontId } from './proofFonts.js';

export const PANEL_H = 720;
export const PAD = 20;
export const GAP = 16;
export const ROW_GAP = 18;
export const LEGEND_COL_MIN = 340; // min px width before the legend splits columns

// Tweet centre-crop aspect guides (width / height): X shows a single image with
// object-fit: cover into a box of this aspect, cropping whatever overflows.
export const TWEET_GUIDES = {
  '16:9': 16 / 9,
  '4:5': 4 / 5,
};

export const ANNO_COLORS = ['#ff5252', '#40c4ff', '#ffd740', '#69f0ae', '#e040fb', '#ff9e40', '#ffffff'];
export const MAX_ANNO_COLORS = ANNO_COLORS.length;
export const MAX_EXPORT_DIMENSION = 16_384;
export const MAX_EXPORT_PIXELS = 64_000_000;

/** Ordered drawing palette, with invalid/duplicate colours removed. */
export function normalizePreferredColors(colors) {
  const source = Array.isArray(colors) && colors.length ? colors : ANNO_COLORS;
  const seen = new Set();
  const palette = [];
  for (const value of source) {
    const color = String(value ?? '').trim().toLowerCase();
    if (!/^#[0-9a-f]{6}$/.test(color) || seen.has(color)) continue;
    seen.add(color);
    palette.push(color);
    if (palette.length === MAX_ANNO_COLORS) break;
  }
  return palette.length ? palette : [...ANNO_COLORS];
}

/** Replace one palette slot; choosing an existing colour swaps the two slots. */
export function replacePreferredColor(colors, index, value) {
  const color = String(value ?? '').trim().toLowerCase();
  const palette = normalizePreferredColors(colors);
  if (!Number.isInteger(index) || index < 0 || index >= palette.length) return palette;
  if (!/^#[0-9a-f]{6}$/.test(color)) return palette;
  const existing = palette.indexOf(color);
  if (existing >= 0 && existing !== index) {
    [palette[index], palette[existing]] = [palette[existing], palette[index]];
  } else {
    palette[index] = color;
  }
  return palette;
}

export const BG = '#0d1117';
export const TEXT_MAIN = '#e8edf6';
export const TEXT_DIM = '#94a3b8';
export const TEXT_FAINT = '#64748b';

// Text palette for a light proof background, so captions/legend/footer stay
// legible when the analyst picks a pale backdrop. textColors() chooses between
// this and the dark palette from the background's luminance — one `bg` field
// drives both, no second colour to keep in sync.
export const TEXT_MAIN_LIGHT = '#0d1117';
export const TEXT_DIM_LIGHT = '#475569';
export const TEXT_FAINT_LIGHT = '#64748b';

/** True when `hex` (#rgb or #rrggbb) is light enough to want dark text on it. */
export function isLightColor(hex) {
  const c = String(hex || '').trim().replace('#', '');
  const full = c.length === 3 ? c.split('').map((x) => x + x).join('') : c;
  if (full.length !== 6) return false;
  const r = parseInt(full.slice(0, 2), 16);
  const g = parseInt(full.slice(2, 4), 16);
  const b = parseInt(full.slice(4, 6), 16);
  if ([r, g, b].some(Number.isNaN)) return false;
  // relative luminance (sRGB weights); above ~0.6 reads as a light backdrop
  return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255 > 0.6;
}

/** Caption/legend/footer colours for a proof background (auto dark-on-light). */
export function textColors(bg = BG) {
  return isLightColor(bg)
    ? { main: TEXT_MAIN_LIGHT, dim: TEXT_DIM_LIGHT, faint: TEXT_FAINT_LIGHT }
    : { main: TEXT_MAIN, dim: TEXT_DIM, faint: TEXT_FAINT };
}

function boundedNumber(value, fallback, min, max) {
  return Number.isFinite(value) ? clamp(value, min, max) : fallback;
}

function normalizedColor(value, fallback) {
  const color = typeof value === 'string' ? value.trim().toLowerCase() : '';
  return /^#[0-9a-f]{6}$/.test(color) ? color : fallback;
}

/** Panel spacing in doc px; malformed fields fall back to shipped defaults. */
export function normSpace(space) {
  return {
    pad: boundedNumber(space?.pad, PAD, 0, 200),
    gap: boundedNumber(space?.gap, GAP, 0, 200),
    rowGap: boundedNumber(space?.rowGap, ROW_GAP, 0, 200),
  };
}

let idSeq = 0;
export function newId(prefix) {
  return `${prefix}${Date.now().toString(36)}${(idSeq++).toString(36)}`;
}

/**
 * Search and category filter for the proof panel picker. Satellite captures
 * carry `kind: satellite`; every other case image carries `kind: media`.
 * The search reads the title the analyst gave the image (its `label`) and the
 * folder it sits in, not the file name on disk — a downloaded photo keeps a
 * name nobody chose, so matching it drowns the titles that mean something.
 */
export function filterProofPanelItems(items, query = '', category = 'all') {
  const needle = String(query).trim().toLocaleLowerCase();
  return (items ?? []).filter((item) => {
    if (category === 'satellite' && item.kind !== 'satellite') return false;
    if (category === 'media' && item.kind !== 'media') return false;
    if (!needle) return true;
    const text = [
      item.label,
      item.folder,
      item.meta?.provider,
      item.meta?.date,
      item.meta?.imagery_date,
    ].filter(Boolean).join(' ').toLocaleLowerCase();
    return text.includes(needle);
  });
}

/**
 * What a panel picker cell should show for a case image.
 *
 * Only the cached thumbnail is small enough for a 150px cell: falling back to
 * the original meant every open of the picker downloaded and decoded the
 * full-resolution captures. `thumbnail` is null unless the listing found the
 * cached file, so a missing one is a placeholder, and a queued or running
 * thumbnail job is a pending one the caller can poll on.
 */
export function panelPreview(item) {
  const state = item?.thumb_state;
  return {
    thumb: state === 'ready' ? (item.thumbnail ?? null) : null,
    thumbPending: state === 'queued' || state === 'running',
  };
}

/** A proof has nothing to render until it contains at least one panel. */
export function hasProofCanvasContent(proof) {
  return Array.isArray(proof?.panels) && proof.panels.length > 0;
}

export const CAPTION_SIZE = 20; // default caption font size (px, editable per proof)
export const LEGEND_SIZE = 20; // default legend text size
export const FOOTER_SIZE = 15; // default footer / attribution text size

export const PANEL_DIRECTIONS = [
  { id: 'horizontal', label: 'Side by side' },
  { id: 'vertical', label: 'Stacked' },
];

/** Apply a template's preferred arrangement to its first two panels. */
export function orientFirstPanels(panels, direction = 'horizontal') {
  if (!panels?.length) return panels;
  panels[0].row = 0;
  if (panels.length > 1) panels[1].row = direction === 'vertical' ? 1 : 0;
  return panels;
}

/** Height of the caption band under a row for a given caption font size. */
export function captionBand(captionSize = CAPTION_SIZE) {
  return Math.round(captionSize + 17);
}

/** Height of one legend line for a given legend font size. */
export function legendLineHeight(legendSize = LEGEND_SIZE) {
  return Math.round(legendSize + 13);
}

/** Height of the footer band for a given footer font size and line count.
 *  One line is the attribution; the coordinates, when the proof prints them,
 *  add their own above it. */
export function footerBand(footerSize = FOOTER_SIZE, lines = 1) {
  return Math.round(footerSize + 13) * Math.max(1, lines);
}

/** Distinct row indices in ascending order (default row 0). */
function rowOrder(panels) {
  return [...new Set(panels.map((p) => p.row ?? 0))].sort((a, b) => a - b);
}

/** Whether any panel in row `r` carries caption text — the band collapses when none does. */
function rowHasCaption(panels, r) {
  return panels.some((p) => (p.row ?? 0) === r && (p.caption ?? '').trim());
}

/** Per-panel height in doc units: base PANEL_H times the panel's own scale. */
export function panelHeight(p) {
  return PANEL_H * (p.scale ?? 1);
}

/** The pixels a panel draws — its crop when it has one, else its whole source. */
const panelImage = (p) => surfaceImageSize(p.sourceNatural ?? p.natural, p.crop);

/**
 * How a panel's own pixels map to doc pixels. Its height is applied to the
 * image and never to the upright box a turned image sits in, or turning a photo
 * would shrink it to keep that growing box the same height.
 */
export function panelScale(p) {
  return panelHeight(p) / panelImage(p)[1];
}

/** The upright room a panel occupies, scaled: its own box, turn included. */
function panelBox(p) {
  const scale = panelScale(p);
  return { scale, w: p.natural[0] * scale, h: p.natural[1] * scale };
}

/**
 * Panel layout boxes in doc space: [{x, y, w, h, scale, baseScale, row}] aligned
 * with the input `panels`. In the default `grid` layout panels are grouped by
 * `row` and centred; rows stack top→bottom with a caption band + ROW_GAP between
 * them (see layoutPanelsGrid). In the `free` layout each panel sits at its own
 * stored x/y (see layoutPanelsFree) and overlap is allowed — array order is the
 * z-order, front→back (the first panel is the foreground one).
 *
 * `scale` maps a panel's natural pixels → doc pixels (grows/shrinks with the
 * user scale); `baseScale` is that mapping at scale 1, which proofs saved before
 * ink moved to page pixels measured their widths against (see `withInkOnPage`).
 */
export function layoutPanels(panels, captionSize = CAPTION_SIZE, layout = 'grid', space) {
  return layout === 'free'
    ? layoutPanelsFree(panels, captionSize, space)
    : layoutPanelsGrid(panels, captionSize, space);
}

/**
 * Grid layout: each panel is laid out at PANEL_H × its own `scale`, so a row's
 * height is its tallest panel and the shorter panels are bottom-aligned so
 * their captions share one baseline.
 */
function layoutPanelsGrid(panels, captionSize = CAPTION_SIZE, space) {
  const { pad, gap, rowGap } = normSpace(space);
  const rows = rowOrder(panels);
  // A row reserves a caption band only when one of its panels is captioned, so a
  // caption-less proof has no empty strip under the panels (and none below the
  // last row — the bottom "bar" a footer-less, margin-less proof would show).
  const bandOf = (r) => (rowHasCaption(panels, r) ? captionBand(captionSize) : 0);
  // width + height of each row, to centre narrower rows and stack by height
  const rowWidth = new Map();
  const rowHeight = new Map();
  for (const r of rows) {
    let w = 0;
    let h = 0;
    const inRow = panels.filter((p) => (p.row ?? 0) === r);
    inRow.forEach((p, k) => {
      const box = panelBox(p);
      h = Math.max(h, box.h);
      w += box.w + (k ? gap : 0);
    });
    rowWidth.set(r, w);
    rowHeight.set(r, h);
  }
  const contentW = rows.length ? Math.max(...rowWidth.values()) : 0;
  // cumulative top of each row (rows differ in height once panels are scaled)
  const rowTop = new Map();
  let cy = pad;
  for (const r of rows) {
    rowTop.set(r, cy);
    cy += rowHeight.get(r) + bandOf(r) + rowGap;
  }
  // running x cursor per row so array order stays left→right within a row
  const cursor = new Map(rows.map((r) => [r, pad + (contentW - rowWidth.get(r)) / 2]));
  return panels.map((p) => {
    const r = p.row ?? 0;
    const { scale, w, h } = panelBox(p);
    const baseScale = PANEL_H / panelImage(p)[1];
    const y = rowTop.get(r) + (rowHeight.get(r) - h); // bottom-align within row
    const box = { x: cursor.get(r), y, w, h, scale, baseScale, row: r };
    cursor.set(r, cursor.get(r) + w + gap);
    return box;
  });
}

/**
 * Free layout: each panel sits at its stored doc-space x/y (its size still
 * derives from PANEL_H × scale, exactly as in the grid). Positions are
 * normalised so the top/left-most panel lands at PAD — stored coordinates can
 * drift while dragging, the document always hugs its content. A panel that has
 * no position yet (just added, or a grid spec toggled to free) falls back to
 * where the grid would have put it, so nothing jumps when entering the mode.
 */
export function layoutPanelsFree(panels, captionSize = CAPTION_SIZE, space) {
  if (!panels.length) return [];
  const { pad } = normSpace(space);
  const grid = layoutPanelsGrid(panels, captionSize, space); // fallback positions
  const pos = panels.map((p, i) => ({
    x: p.x ?? grid[i].x,
    y: p.y ?? grid[i].y,
  }));
  const dx = pad - Math.min(...pos.map((q) => q.x));
  const dy = pad - Math.min(...pos.map((q) => q.y));
  return panels.map((p, i) => {
    const { scale, w, h } = panelBox(p);
    return {
      x: pos[i].x + dx,
      y: pos[i].y + dy,
      w,
      h,
      scale,
      baseScale: PANEL_H / panelImage(p)[1],
      row: p.row ?? 0,
    };
  });
}

/**
 * Shift that re-anchors stored free positions at PAD (the normalisation
 * layoutPanelsFree applies on the fly). The caller folds it into every panel's
 * stored x/y after a drag/resize so stored coordinates always equal rendered
 * ones — and can offset the stage by the same amount so nothing jumps on screen.
 */
export function freeNormalizeDelta(panels, captionSize = CAPTION_SIZE, space) {
  if (!panels.length) return { dx: 0, dy: 0 };
  const { pad } = normSpace(space);
  const grid = layoutPanelsGrid(panels, captionSize, space);
  const xs = panels.map((p, i) => p.x ?? grid[i].x);
  const ys = panels.map((p, i) => p.y ?? grid[i].y);
  return { dx: pad - Math.min(...xs), dy: pad - Math.min(...ys) };
}

/** Height of the stacked panel block (rows + their caption bands), no legend. */
export function panelsBlockHeight(panels, captionSize = CAPTION_SIZE, space) {
  const { rowGap } = normSpace(space);
  const rows = rowOrder(panels);
  if (!rows.length) return 0;
  let total = 0;
  for (const r of rows) {
    const inRow = panels.filter((p) => (p.row ?? 0) === r);
    const band = rowHasCaption(panels, r) ? captionBand(captionSize) : 0;
    total += Math.max(...inRow.map((p) => panelBox(p).h)) + band;
  }
  return total + (rows.length - 1) * rowGap;
}

/**
 * Doc-space y where the panel block ends and the legend may start. Grid: PAD +
 * the stacked block (every row reserves its caption band). Free: the lowest
 * panel bottom, plus a caption band only under panels that actually carry one.
 */
export function panelsBottom(panels, captionSize = CAPTION_SIZE, layout = 'grid', space) {
  const { pad } = normSpace(space);
  if (!panels.length) return pad;
  if (layout !== 'free') return pad + panelsBlockHeight(panels, captionSize, space);
  const boxes = layoutPanelsFree(panels, captionSize, space);
  const band = captionBand(captionSize);
  return Math.max(
    ...boxes.map((b, i) => b.y + b.h + (panels[i].caption?.trim() ? band : 0))
  );
}

/**
 * Distinct colors in order of first use → feature numbering (same color = same
 * feature). Text labels are excluded — they annotate, they aren't features. So
 * is a blur box: it hides something rather than pointing at it, and its colour
 * is never drawn, so a legend row for it would key a feature on a colour the
 * plate does not show.
 */
export function featureColors(shapes) {
  const seen = [];
  for (const s of shapes) {
    if (s.kind === 'text' || s.kind === 'blur') continue;
    if (!seen.includes(s.color)) seen.push(s.color);
  }
  return seen;
}

/**
 * `featureColors` order (first use), overridden by an explicit `legendOrder`
 * (array of colors) where one is given: known colors keep that order, colors
 * no longer in use are dropped, newly-used colors not yet in `legendOrder`
 * are appended after the known ones (first-use order among themselves).
 */
export function orderedFeatureColors(shapes, legendOrder = []) {
  const used = featureColors(shapes);
  const known = legendOrder.filter((c) => used.includes(c));
  const extra = used.filter((c) => !known.includes(c));
  return [...known, ...extra];
}

/**
 * Legend lines: one per used color (feature), text taken from the per-color
 * `notes` map, ordered by `legendOrder` (falls back to first-use order).
 * Annotations are written by color, not per element.
 */
export function legendLines(shapes, notes = {}, legendOrder = []) {
  const colors = orderedFeatureColors(shapes, legendOrder);
  return colors.map((color, i) => ({
    color,
    n: i + 1,
    text: (notes?.[color] ?? '').trim(),
  }));
}

/**
 * Build a per-color notes map from legacy per-shape comments (old specs stored
 * the legend text on each shape). Used once when opening an old proof.
 */
export function notesFromShapes(shapes) {
  const notes = {};
  for (const s of shapes) {
    const c = s.comment?.trim();
    if (!c) continue;
    const existing = notes[s.color];
    if (!existing) notes[s.color] = c;
    else if (!existing.split(' · ').includes(c)) notes[s.color] = `${existing} · ${c}`;
  }
  return notes;
}

/** Unique attribution strings from panel metadata. */
export function attributionLine(panels) {
  return 'Composed with Azimut';
}

// ---- coordinates + source (auto-derived from panels, user-overridable) ------

/** First panel (add order) that carries geo → {lat, lon}, else null. */
export function autoCoords(panels) {
  for (const p of panels ?? []) {
    const lat = p.meta?.lat;
    const lon = p.meta?.lon;
    if (lat != null && lon != null) return { lat: Number(lat), lon: Number(lon) };
  }
  return null;
}

/**
 * True when the panel `autoCoords` reads was aimed: its point is a pin somebody
 * put on the target, not the middle of whatever the capture framed.
 */
export function autoAimed(panels) {
  for (const p of panels ?? []) {
    if (p.meta?.lat != null && p.meta?.lon != null) return p.meta.aimed === true;
  }
  return false;
}

/**
 * True when a capture's point is a pin moved onto the target before it was taken.
 *
 * Otherwise the point is the middle of the frame: the screen's centre, or the
 * rectangle's, which is only where the analyst stood the camera. A wide capture of
 * an airbase puts that hundreds of metres from the hangar the proof is about. A
 * map screenshot the extension filed reads its point off the page address, which is
 * the page's centre, and records no second point, so it is never aimed.
 */
export function captureAimed(s) {
  if (s?.center_lat == null || s?.center_lon == null || s.lat == null || s.lon == null) return false;
  return Math.abs(Number(s.lat) - Number(s.center_lat)) > 1e-6
    || Math.abs(Number(s.lon) - Number(s.center_lon)) > 1e-6;
}

/**
 * A {lat, lon} rendered in the reader's coordinate format, or '' when null.
 * Defaults to decimal degrees so this stays a pure function — components pass
 * the user's preference in (state.svelte.js `prefs.coordFormat`).
 */
export function formatCoords(c, format = 'dd') {
  return c && c.lat != null && c.lon != null ? renderCoords(c.lat, c.lon, format) : '';
}

/**
 * Trace a media item back to its original *source link(s)*. A source is always a
 * URL (a downloaded webpage): a file uploaded from disk is NOT a source. Inspect
 * derivatives (frames, adjustments, collages) don't carry a URL themselves —
 * their `source` records the case paths they were derived from (`from` and, for
 * collages, `sources`), so we follow those through `mediaByPath` until we reach
 * the download that owns a `webpage_url`. Returns de-duplicated URLs.
 */
export function resolveSourceUrls(item, mediaByPath, seen = new Set()) {
  if (!item) return [];
  const s = item.source ?? {};
  const direct = s.webpage_url || (typeof s.url === 'string' && /^https?:\/\//i.test(s.url) ? s.url : null);
  if (direct) return [direct];
  const parents = [];
  if (s.from) parents.push(s.from);
  if (Array.isArray(s.sources)) parents.push(...s.sources);
  const urls = [];
  for (const path of parents) {
    if (!path || seen.has(path)) continue;
    seen.add(path);
    urls.push(...resolveSourceUrls(mediaByPath?.get?.(path), mediaByPath, seen));
  }
  return [...new Set(urls)];
}

/** Source URLs already resolved onto a panel's meta (array, first-mirrored). */
function panelSourceUrls(p) {
  if (Array.isArray(p.meta?.source_urls)) return p.meta.source_urls.filter(Boolean);
  return p.meta?.source_url ? [p.meta.source_url] : [];
}

/** Distinct source URLs across all panels (satellite imagery has none). */
export function autoSourceUrls(panels) {
  const set = new Set();
  for (const p of panels ?? []) for (const u of panelSourceUrls(p)) set.add(u);
  return [...set];
}

//: What joins several addresses into the block a post and a report read. A line each:
//: they are addresses, and a reader scanning four of them down a column reads them where
//: four strung along one line with a dot between is a wall to pick apart.
export const SOURCE_SEPARATOR = '\n';

//: One http(s) address and nothing else.
const ADDRESS = /^https?:\/\/\S+$/i;

/**
 * The addresses a proof states for itself, as a list.
 *
 * An array is the shape a proof carries now. A string is what one saved before this
 * carried, and it splits back into its parts only when every part is an address —
 * the line the composer wrote itself. Anything else is one thing the analyst typed,
 * and it stays one entry rather than being cut at its spaces.
 */
export function normalizeSources(value) {
  let list;
  if (Array.isArray(value)) {
    list = value;
  } else {
    const text = String(value ?? '').trim();
    const parts = text ? text.split(/\s*·\s*|\s+/) : [];
    list = parts.every((part) => ADDRESS.test(part)) ? parts : [text];
  }
  return [...new Set(list.map((one) => String(one ?? '').trim()).filter(Boolean))];
}

/**
 * The addresses a proof states, or `null` when it states none of its own.
 *
 * The distinction is the whole point: **an empty list is an answer**. A proof whose
 * source boxes have all been emptied says it has no public source — the footage was
 * handed over privately, and saying so is not the same as never having said anything.
 * Falling back to the panels there put addresses back on a proof somebody had just
 * taken them off, and carried them into the post behind their back.
 *
 * `null`/absent, or the empty string a proof saved before this carried, is "nothing
 * stated" and the panels answer for it.
 */
export function statedSources(value) {
  if (value === null || value === undefined) return null;
  if (typeof value === 'string') return value.trim() ? normalizeSources(value) : null;
  return Array.isArray(value) ? normalizeSources(value) : null;
}

/**
 * Case files a proof rests on, each with the address that brought it in.
 *
 * The address is what makes the list reconcilable: taking a source off the proof has to
 * take what that source brought with it, and a bare path cannot say which row it came
 * from. A proof saved before this carried bare paths, and they read as material nothing
 * named — kept, since the list cannot disown what it cannot name.
 */
export function normalizeMaterial(value) {
  const seen = new Set();
  const held = [];
  for (const one of Array.isArray(value) ? value : []) {
    const path = String((typeof one === 'string' ? one : one?.path) ?? '').trim();
    if (!path || seen.has(path)) continue;
    seen.add(path);
    held.push({ path, url: String(one?.url ?? '').trim() });
  }
  return held;
}

/** The material still answered for by one of the addresses the proof states. */
export function statedMaterial(material, sources) {
  const stated = new Set(sources);
  return normalizeMaterial(material).filter((one) => !one.url || stated.has(one.url));
}

/** Auto source line: distinct panel source links joined, or '' when none. */
export function autoSource(panels) {
  return autoSourceUrls(panels).join(SOURCE_SEPARATOR);
}

/** How many points one proof may state. Mirrors `satellite.MAX_PROOF_POINTS`:
 *  past fifteen a proof is a case, and the panel is a wall rather than a reading. */
export const MAX_POINTS = 15;

/** True when the single-point field says something the list does not.
 *
 *  The two are written together and never drift (`statePoints`), so a disagreement
 *  means the field was set by something that does not know the list — an older
 *  build, a route stating one point. What it says is the newer answer.
 *  Mirrors `engine/satellite._mirror_broken`. */
function mirrorBroken(p, entries) {
  if (!('coordsText' in (p ?? {}))) return false;
  const first = entries[0] && typeof entries[0] === 'object' ? entries[0] : {};
  return String(p.coordsText ?? '').trim() !== String(first.coords ?? '').trim();
}

/**
 * The points a proof states, its conclusion first — `{coords, label, pov}` each,
 * with `coords` still the text the analyst typed.
 *
 * A proof shows more than one place more often than it shows one: three impacts,
 * a building, the camera that filmed it. The first is the conclusion — the map
 * mark, the coordinate a post cites — and `pov` rides on the point that carries
 * it, at most one, because a camera stood in one place.
 *
 * A spec written before the list reads as the one point it holds, so nothing
 * migrates. Mirrors `engine/satellite.spec_points`, minus the parsing: the
 * server reads the text, this side only carries it.
 */
export function specPoints(p) {
  const entries = Array.isArray(p?.points) ? p.points : null;
  const stated = entries && !mirrorBroken(p, entries)
    ? entries
        .filter((one) => one && typeof one === 'object')
        .map((one) => ({
          coords: String(one.coords ?? '').trim(),
          label: String(one.label ?? '').trim(),
          pov: one.pov === true,
          ...(one.proposed === true ? { proposed: true } : {}),
        }))
        .filter((one) => one.coords)
    : [];
  const points = stated.length
    ? stated
    : (String(p?.coordsText ?? '').trim()
        ? [{ coords: String(p.coordsText).trim(), label: '', pov: p?.pov === true }]
        : []);
  let taken = false;
  return points.map((one) => {
    const pov = one.pov && !taken;
    taken = taken || pov;
    return { ...one, pov };
  });
}

/**
 * Write what a proof states onto a spec: the list, and the mirror of it.
 *
 * The mirror is not a leftover. A case bundle travels between installations and
 * the binaries are versioned, so a build older than the list has to find the
 * conclusion where it has always been rather than open a proof with no point.
 * Mirrors `engine/satellite.state_points`.
 */
export function statePoints(spec, points) {
  const stated = (points ?? [])
    .map((one) => ({
      coords: String(one?.coords ?? '').trim(),
      label: String(one?.label ?? '').trim(),
      pov: one?.pov === true,
      proposed: one?.proposed === true,
    }))
    .filter((one) => one.coords)
    .map((one) => ({
      coords: one.coords,
      ...(one.label ? { label: one.label } : {}),
      ...(one.pov ? { pov: true } : {}),
      ...(one.proposed ? { proposed: true } : {}),
    }));
  spec.points = stated;
  spec.coordsText = stated[0]?.coords ?? '';
  spec.pov = stated[0]?.pov === true;
  return spec;
}

/**
 * The rows a proof holds once a panel carrying a place has landed on it.
 *
 * A panel with coordinates used to be able to *replace* the proof's answer
 * without saying so: the field reads the first geo panel (`autoCoords`) while no
 * row is typed, and in free layout a new panel is prepended — so dropping a
 * second capture onto the canvas quietly renamed the place the proof concluded
 * on. In grid layout the same panel went the other way and was never heard at
 * all: it lands behind the first, and its place was simply lost.
 *
 * So the place is added rather than swapped. The answer already on screen is
 * written down first (`answered`, read before the panel landed), because an
 * answer the panels happen to give is not one the analyst chose, and the new
 * point joins the list under it. A proof that had no coordinates at all is left
 * alone: that panel *is* the answer, and the field reads it off the panels as it
 * always has.
 *
 * Both rows keep saying whether anyone checked them: the new one is proposed
 * unless its capture was aimed, and the answer written down stays as proposed as
 * it was while the field read it.
 *
 * @param {Array} points the rows as edited, at least one
 * @param {object} panel the panel that just landed
 * @param {string} answered what the proof answered with before it did
 * @param {string} format the reader's coordinate format
 * @param {boolean} answeredProposed whether that answer was the panels' unchecked one
 */
export function statePanelPoint(points, panel, answered, format = 'dd', answeredProposed = false) {
  const { lat, lon } = panel?.meta ?? {};
  if (lat == null || lon == null) return points;
  const text = formatCoords({ lat: Number(lat), lon: Number(lon) }, format);
  if (!text || !answered) return points;
  const rows = points?.length ? points : [{ coords: '', label: '', pov: false }];
  if (rows.length >= MAX_POINTS) return points;
  const stated = rows.map((one) => String(one.coords ?? '').trim()).filter(Boolean);
  // The same place twice is one place: two captures of one point, taken on two
  // dates, are the proof's whole subject and must not read as two.
  if ((stated.length ? stated : [answered]).includes(text)) return points;
  return [
    ...rows.map((one, at) =>
      at === 0 && !String(one.coords ?? '').trim()
        ? { ...one, coords: answered, ...(answeredProposed ? { proposed: true } : {}) }
        : one
    ),
    { coords: text, label: '', pov: false, ...(panel.meta.aimed === true ? {} : { proposed: true }) },
  ];
}

/**
 * True when row `i` holds a point nobody checked: one the imagery proposed.
 *
 * A first row with no text reads the panels, so it is proposed exactly when there
 * is a panel answer and its capture was not aimed. Any other row says so itself,
 * and typing coordinates or placing them on the map is what clears it.
 */
export function pointProposed(points, i, panels) {
  const row = points?.[i];
  if (!row) return false;
  if (i === 0 && !String(row.coords ?? '').trim()) {
    return autoCoords(panels) != null && !autoAimed(panels);
  }
  return row.proposed === true && Boolean(String(row.coords ?? '').trim());
}

/** The rows a save or a post has to have checked first, in the order they show. */
export function uncheckedPoints(points, panels) {
  return (points ?? []).map((_, i) => i).filter((i) => pointProposed(points, i, panels));
}

/** Effective coordinates text for a proof/spec: what it concludes on, else auto. */
export function proofCoordsText(p, format = 'dd') {
  const stated = specPoints(p)[0]?.coords;
  if (stated) return stated;
  return formatCoords(autoCoords(p.panels ?? []), format);
}

/** Every point a proof states, ready to print: `{coords, label}` per line.
 *  Falls back to the one the panels give it, which is what the field shows. */
export function proofCoordsLines(p, format = 'dd') {
  const stated = specPoints(p);
  if (stated.length) return stated.map(({ coords, label }) => ({ coords, label }));
  const auto = formatCoords(autoCoords(p.panels ?? []), format);
  return auto ? [{ coords: auto, label: '' }] : [];
}

/** The coordinates as the plate prints them, one string per line.
 *
 *  Unnamed points share a line: three impacts nobody named are three numbers, and
 *  giving each its own line grows the picture for nothing. A point the analyst
 *  named earns its line, because the name is what they wanted read. */
export function coordsPlateLines(lines) {
  const bare = (lines ?? []).filter((one) => !one.label).map((one) => one.coords);
  const named = (lines ?? [])
    .filter((one) => one.label)
    .map((one) => `${one.label} — ${one.coords}`);
  return [...(bare.length ? [bare.join(' · ')] : []), ...named];
}

/** The coordinates as a post carries them: one per line, named when named.
 *  A tweet has no height to save, so nothing is joined. */
export function coordsPostLines(lines) {
  return (lines ?? []).map((one) => (one.label ? `${one.label} — ${one.coords}` : one.coords));
}

/** Every line the plate's footer prints: the coordinates when asked, then the
 *  credit line unless it was turned off. One source for the height and for the
 *  drawing, so a proof that grew a line cannot be measured as if it had not.
 *
 *  Empty is a valid answer — a footer switched on with nothing to print takes no
 *  band at all, rather than an empty strip under the panels. */
export function footerLines(proof, format = 'dd') {
  const printed = proof?.footerCoords === true
    ? coordsPlateLines(proofCoordsLines(proof, format))
    : [];
  const credit = proof?.footerText === false
    ? []
    : [proof?.footer?.trim() || attributionLine(proof?.panels ?? [])];
  return [...printed, ...credit];
}

/**
 * A source row as a link the browser may open, or '' when it is not one.
 *
 * The field takes whatever says where the material came from — an address, a
 * case number, a sentence — so the press that opens a tab is offered only for
 * the rows that are web addresses. Anything else, `javascript:` included, is not
 * a link here.
 */
export function openableSource(text) {
  const value = String(text ?? '').trim();
  if (!value) return '';
  try {
    const url = new URL(value);
    return url.protocol === 'http:' || url.protocol === 'https:' ? url.toString() : '';
  } catch {
    return '';
  }
}

/** Effective source line for a proof/spec: the stated addresses, else the traced ones.
 *
 *  Always one line, whatever the proof holds: a plate, a post and a report all read a
 *  source as text. Only editing it is a list.
 */
export function proofSource(p) {
  const stated = statedSources(p.sources ?? p.source ?? null);
  if (stated) return stated.join(SOURCE_SEPARATOR);
  return autoSource(p.panels ?? []);
}

/** How many columns the legend splits into for a given content width + count. */
export function legendColumns(width, count, space) {
  if (count <= 1) return 1;
  const { pad, gap } = normSpace(space);
  const fit = Math.floor((width - pad * 2 + gap) / (LEGEND_COL_MIN + gap));
  return Math.max(1, Math.min(3, count, fit));
}

/** Number of stacked legend rows once split into columns. */
export function legendRowCount(count, columns) {
  return columns > 0 ? Math.ceil(count / columns) : 0;
}

/**
 * Full document size given panels + shapes. Legend grows with the feature
 * count and every text band grows with its own font size (all editable per
 * proof via `text = { captionSize, legendSize, footerSize }`).
 */
export function docSize(panels, shapes, notes = {}, text = {}, legendOrder = [], layout = 'grid', space, extent = null) {
  const {
    captionSize = CAPTION_SIZE, legendSize = LEGEND_SIZE, footerSize = FOOTER_SIZE,
    footerEnabled = true, footerLines = 1,
  } = text;
  const { pad } = normSpace(space);
  const boxes = layoutPanels(panels, captionSize, layout, space);
  const width = boxes.length
    ? Math.max(...boxes.map((b) => b.x + b.w)) + pad
    : 640;
  // `extent` is how far right and down the marks free on the page reach: the
  // page grows to hold them, and the footer stays under them.
  const contentW = Math.max(width, 640, extent ? Math.ceil(extent.right + pad) : 0);
  const legend = legendLines(shapes, notes, legendOrder).filter((l) => l.text);
  const cols = legendColumns(contentW, legend.length, space);
  const legendRows = legendRowCount(legend.length, cols);
  const footer = footerEnabled && footerLines > 0 ? footerBand(footerSize, footerLines) : 0;
  const height = Math.max(
    panelsBottom(panels, captionSize, layout, space) +
      (legend.length ? 10 + legendRows * legendLineHeight(legendSize) : 0) + footer + pad,
    extent?.bottom > 0 ? Math.ceil(extent.bottom + 8 + footer + pad) : 0,
  );
  return { width: contentW, height, legend, cols };
}

// ---- signature: the analyst's logo, stamped on a proof they choose to sign ---

/** Doc corners the signature can hang off: top/bottom × left/right. */
export const SIG_ANCHORS = [
  { id: 'tl', label: 'Top left' },
  { id: 'tr', label: 'Top right' },
  { id: 'bl', label: 'Bottom left' },
  { id: 'br', label: 'Bottom right' },
];

export const SIG_MARGIN = PAD; // inset from the doc edge at zero offset
export const SIG_SCALE = 0.08; // default logo footprint, as a share of the proof
export const SIG_OPACITY = 0.9;

/** A fresh signature record — bottom right, the corner a byline usually takes. */
export function newSignature() {
  return { anchor: 'br', dx: 0, dy: 0, scale: SIG_SCALE, opacity: SIG_OPACITY };
}

/**
 * Where the signature lands in doc space: {x, y, w, h}.
 *
 * Size fits inside a `scale` share of both document dimensions, so wide, square
 * and tall PNGs start with the same visual footprint. Position is an `anchor`
 * corner plus a user `dx`/`dy` nudge
 * — the document grows every time a panel or a font size changes, so a raw x/y
 * would drift off the image; an anchored offset stays put.
 *
 * The result is clamped inside the document: a nudge can't push the logo off
 * the export, where it would be silently cropped rather than visibly wrong.
 */
export function signatureBox(sig, docW, docH, natural) {
  const [nw, nh] = natural;
  const scale = sig.scale ?? SIG_SCALE;
  const maxW = docW * scale;
  const maxH = docH * scale;
  const aspect = nw > 0 && nh > 0 ? nw / nh : 1;
  const w = aspect >= maxW / Math.max(maxH, 1) ? maxW : maxH * aspect;
  const h = w / aspect;
  const right = (sig.anchor ?? 'br').endsWith('r');
  const bottom = (sig.anchor ?? 'br').startsWith('b');
  const x = right ? docW - SIG_MARGIN - w : SIG_MARGIN;
  const y = bottom ? docH - SIG_MARGIN - h : SIG_MARGIN;
  const relative = relativePlacement(sig, docW, docH, w, h);
  return relative ?? {
    x: clamp(x + (sig.dx ?? 0), 0, Math.max(0, docW - w)),
    y: clamp(y + (sig.dy ?? 0), 0, Math.max(0, docH - h)),
    w,
    h,
  };
}

/** Whether an anchored item is still at its untouched corner position. */
function hasDefaultPlacement(item) {
  return item
    && !Number.isFinite(item.xRatio)
    && !Number.isFinite(item.yRatio)
    && (item.dx ?? 0) === 0
    && (item.dy ?? 0) === 0;
}

/**
 * Default logo + account-handle stack. When both items still share an untouched
 * corner, the logo sits above the centered handle. Once either item is moved or
 * assigned another corner, callers use their independent positions instead.
 */
export function signaturePairPositions(
  signature, signatureText, docW, docH, logoBox, handleW, handleH,
) {
  if (!logoBox || !hasDefaultPlacement(signature) || !hasDefaultPlacement(signatureText)) return null;
  if ((signature.anchor ?? 'br') !== (signatureText.anchor ?? 'br')) return null;

  const anchor = signature.anchor ?? 'br';
  const right = anchor.endsWith('r');
  const bottom = anchor.startsWith('b');
  const gap = Math.max(8, Math.round(handleH * 0.3));
  const groupW = Math.max(logoBox.w, handleW);
  const groupH = logoBox.h + gap + handleH;
  const groupX = right ? docW - SIG_MARGIN - groupW : SIG_MARGIN;
  const groupY = bottom ? docH - SIG_MARGIN - groupH : SIG_MARGIN;
  const x = clamp(groupX, 0, Math.max(0, docW - groupW));
  const y = clamp(groupY, 0, Math.max(0, docH - groupH));

  return {
    logo: { ...logoBox, x: x + (groupW - logoBox.w) / 2, y },
    handle: { x: x + (groupW - handleW) / 2, y: y + logoBox.h + gap },
  };
}

function clamp(v, lo, hi) {
  return Math.max(lo, Math.min(hi, v));
}

/** Resolve a dragged placement as a share of the available document area. */
function relativePlacement(a, docW, docH, w, h) {
  if (!Number.isFinite(a?.xRatio) || !Number.isFinite(a?.yRatio)) return null;
  const maxX = Math.max(0, docW - w);
  const maxY = Math.max(0, docH - h);
  return {
    x: clamp(a.xRatio, 0, 1) * maxX,
    y: clamp(a.yRatio, 0, 1) * maxY,
    w,
    h,
  };
}

/**
 * {x, y} of a w×h box anchored to a document corner with a `dx`/`dy` nudge,
 * clamped inside the document. The general form behind signatureBox — used by
 * the text signature too, whose width is measured at render time.
 */
export function anchoredPos(a, docW, docH, w, h, margin = SIG_MARGIN) {
  const relative = relativePlacement(a, docW, docH, w, h);
  if (relative) return { x: relative.x, y: relative.y };
  const right = (a?.anchor ?? 'br').endsWith('r');
  const bottom = (a?.anchor ?? 'br').startsWith('b');
  const x = right ? docW - margin - w : margin;
  const y = bottom ? docH - margin - h : margin;
  return {
    x: clamp(x + (a?.dx ?? 0), 0, Math.max(0, docW - w)),
    y: clamp(y + (a?.dy ?? 0), 0, Math.max(0, docH - h)),
  };
}

/** The `dx`/`dy` placing an anchored box's top-left at (x, y) — inverse of anchoredPos. */
export function anchoredOffset(a, docW, docH, w, h, x, y, margin = SIG_MARGIN) {
  const base = anchoredPos({ ...a, dx: 0, dy: 0 }, docW, docH, w, h, margin);
  const maxX = Math.max(0, docW - w);
  const maxY = Math.max(0, docH - h);
  return {
    dx: x - base.x,
    dy: y - base.y,
    xRatio: maxX ? clamp(x / maxX, 0, 1) : 0,
    yRatio: maxY ? clamp(y / maxY, 0, 1) : 0,
  };
}

// Default doc-pixel height of a text signature (the Settings handle laid over
// the panels). The text itself is deliberately not stored in a proof/template:
// it is the analyst's app-wide identity, like the signature logo.
export const SIG_TEXT_SIZE = 28;

/** A fresh text-signature record — a handle in the bottom-right, over the panels. */
export function newSignatureText() {
  return { anchor: 'br', dx: 0, dy: 0, size: SIG_TEXT_SIZE, color: '#ffffff', opacity: 1 };
}

/** Copy a text-signature slot while dropping the legacy per-proof handle text. */
export function textSignatureStyle(signatureText) {
  if (!signatureText || typeof signatureText !== 'object' || Array.isArray(signatureText)) return null;
  const style = {
    anchor: ['tl', 'tr', 'bl', 'br'].includes(signatureText.anchor) ? signatureText.anchor : 'br',
    dx: boundedNumber(signatureText.dx, 0, -100_000, 100_000),
    dy: boundedNumber(signatureText.dy, 0, -100_000, 100_000),
    size: boundedNumber(signatureText.size, SIG_TEXT_SIZE, 12, 300),
    color: normalizedColor(signatureText.color, '#ffffff'),
    opacity: boundedNumber(signatureText.opacity, 1, 0, 1),
  };
  if (Number.isFinite(signatureText.xRatio)) style.xRatio = clamp(signatureText.xRatio, 0, 1);
  if (Number.isFinite(signatureText.yRatio)) style.yRatio = clamp(signatureText.yRatio, 0, 1);
  return style;
}

/**
 * The `dx`/`dy` that puts the signature's top-left at doc point (x, y) — the
 * inverse of signatureBox's anchoring, for writing a drag back to the spec.
 */
export function signatureOffset(sig, docW, docH, natural, x, y) {
  const base = signatureBox({ ...sig, dx: 0, dy: 0 }, docW, docH, natural);
  const maxX = Math.max(0, docW - base.w);
  const maxY = Math.max(0, docH - base.h);
  return {
    dx: x - base.x,
    dy: y - base.y,
    xRatio: maxX ? clamp(x / maxX, 0, 1) : 0,
    yRatio: maxY ? clamp(y / maxY, 0, 1) : 0,
  };
}

// ---- frames & pasted images --------------------------------------------------

export const FRAME_WIDTH = 6; // default border thickness, in page pixels like any ink
export const FRAME_WIDTH_MAX = 60;
export const FRAME_COLOR = ANNO_COLORS[0];

/**
 * A coloured border around a panel or a pasted image, or `null` for none.
 * Decoration only: unlike a drawn shape, a frame never enters the legend, so it
 * is not something the analyst has to explain. Drawn inset on the surface, so it
 * costs the layout nothing. Width 0 is how the UI turns a frame off.
 */
export function normalizeFrame(frame) {
  if (!frame || typeof frame !== 'object' || Array.isArray(frame)) return null;
  const width = Math.round(boundedNumber(frame.width, 0, 0, FRAME_WIDTH_MAX));
  return width ? { color: normalizedColor(frame.color, FRAME_COLOR), width } : null;
}

export function newFrame() {
  return { color: FRAME_COLOR, width: FRAME_WIDTH };
}

export const PASTE_SCALE_MIN = 0.02;
export const PASTE_SCALE_MAX = 8;
export const PASTE_SHARE = 0.4; // insertion width, as a share of the document

/**
 * A pasted image: pixels that live in this proof and nowhere else. It carries no
 * `src`, so nothing in the case claims it and the save files no derived-from
 * edge for it — `asset` is a file name inside the proof's own assets folder.
 */
export function newPaste(asset, natural, { x = 0, y = 0, scale = 1 } = {}) {
  return {
    id: newId('x'),
    asset,
    natural: [natural[0], natural[1]],
    x,
    y,
    scale: clampPasteScale(scale),
    frame: null,
  };
}

export function clampPasteScale(scale) {
  const v = Number.isFinite(scale) ? scale : 1;
  return Math.round(clamp(v, PASTE_SCALE_MIN, PASTE_SCALE_MAX) * 1000) / 1000;
}

/** Insertion scale: a share of the document width, never larger than life size. */
export function pasteInsertScale(natural, docW, share = PASTE_SHARE) {
  const w = natural?.[0];
  if (!w || !docW) return 1;
  return clampPasteScale(Math.min(1, Math.round(((docW * share) / w) * 1000) / 1000));
}

/**
 * Layout boxes for pasted images, in the same shape as panel boxes so a shape
 * can bind to either. A paste sits at its own doc position, and its `scale` maps
 * natural pixels straight to doc pixels (1 = life size). `baseScale` is 1: an
 * older proof's widths on a paste were in its natural pixels.
 */
export function pasteBoxes(pastes) {
  return (pastes ?? []).map((p) => {
    const scale = clampPasteScale(p.scale);
    return {
      x: p.x ?? 0,
      y: p.y ?? 0,
      w: p.natural[0] * scale,
      h: p.natural[1] * scale,
      scale,
      baseScale: 1,
      row: 0,
    };
  });
}

/**
 * Everything an annotation can be drawn on, front→back: pasted images first
 * (they float above the composition), then the panels in their own z-order.
 * Each entry is `{ id, kind, item, box, index }`, `index` being the item's
 * position inside its own array — what the mutating helpers take.
 */
export function surfaces(proof) {
  const panels = proof?.panels ?? [];
  const pastes = proof?.pastes ?? [];
  const panelBox = layoutPanels(panels, proof?.captionSize, proof?.layout, proof?.space);
  const pasteBox = pasteBoxes(pastes);
  return [
    ...pastes.map((item, index) => ({ id: item.id, kind: 'paste', item, box: pasteBox[index], index })),
    ...panels.map((item, index) => ({ id: item.id, kind: 'panel', item, box: panelBox[index], index })),
  ];
}

/**
 * How a surface sits on the page. The composer draws one as a group centred on
 * its layout box, turned and scaled about the middle of the pixels it draws, and
 * its annotations live in those pixels. `pageToSurface` and `surfaceToPage` are
 * that transform and its inverse, so a turned panel is read where it is drawn
 * rather than as the upright box the layout reserved for it.
 */
export function surfaceFrame(entry) {
  const { item, box } = entry;
  return {
    box,
    image: surfaceImageSize(item.sourceNatural ?? item.natural, item.crop),
    rotation: normalizeSurfaceAngle(item.rotation),
  };
}

function turned(x, y, degrees) {
  if (!degrees) return { x, y };
  const radians = (degrees * Math.PI) / 180;
  const cos = Math.cos(radians);
  const sin = Math.sin(radians);
  return { x: x * cos - y * sin, y: x * sin + y * cos };
}

/** A page point in a surface's own pixels. */
export function pageToSurface(point, frame) {
  const { box, image, rotation } = frame;
  const v = turned(
    (point.x - (box.x + box.w / 2)) / box.scale,
    (point.y - (box.y + box.h / 2)) / box.scale,
    -rotation,
  );
  return { x: v.x + image[0] / 2, y: v.y + image[1] / 2 };
}

/** A point in a surface's own pixels, on the page. */
export function surfaceToPage(point, frame) {
  const { box, image, rotation } = frame;
  const v = turned((point.x - image[0] / 2) * box.scale, (point.y - image[1] / 2) * box.scale, rotation);
  return { x: v.x + box.x + box.w / 2, y: v.y + box.y + box.h / 2 };
}

/** A step on the page as the same step in a surface's own pixels. */
export function pageStepOnSurface(dx, dy, frame) {
  const v = turned(dx / frame.box.scale, dy / frame.box.scale, -frame.rotation);
  return { dx: v.x, dy: v.y };
}

/**
 * Topmost surface under a page point, with the point in its own pixels. A turned
 * surface answers over its picture only, not in the corners of the upright box
 * the page keeps around it. The list is front→back, so the first hit wins.
 */
export function surfaceHitTest(list, point) {
  for (const entry of list) {
    const frame = surfaceFrame(entry);
    const p = pageToSurface(point, frame);
    if (p.x >= 0 && p.x <= frame.image[0] && p.y >= 0 && p.y <= frame.image[1]) {
      return { ...entry, frame, nx: p.x, ny: p.y };
    }
  }
  return null;
}

/** What `toSpec` writes to say its ink is measured in page pixels. */
export const INK_UNITS = 'page';

/**
 * A proof saved before ink was measured on the page, converted so it draws the
 * same. Its line widths grew and shrank with the panel's size, and its labels,
 * symbols, markers and frames were measured in the picture's own pixels, so one
 * number drew four times bigger on a small picture than on a large one. Where a
 * mark stands and what it spans are left alone: they belong to the picture.
 */
export function withInkOnPage(spec) {
  if (!spec || spec.ink === INK_UNITS) return spec;
  const boxes = new Map(surfaces(spec).map((entry) => [entry.id, entry.box]));
  const round = (value) => Math.round(value * 100) / 100;
  const framed = (item) => {
    const box = boxes.get(item.id);
    if (!box || !(item.frame?.width > 0)) return item;
    return { ...item, frame: { ...item.frame, width: Math.max(1, Math.round(item.frame.width * box.scale)) } };
  };
  const shapes = (spec.shapes ?? []).map((s) => {
    const box = boxes.get(s.panel);
    if (!box) return s;
    const out = { ...s };
    // a width drew at its value on a panel at 100%, and scaled with the panel
    const width = STROKED_KINDS.has(s.kind) ? (s.strokeWidth ?? 4) : s.strokeWidth;
    if (Number.isFinite(width)) out.strokeWidth = round((width * box.scale) / box.baseScale);
    if (s.kind === 'text') out.fontSize = round((s.fontSize ?? 28) * box.scale);
    if (s.kind === 'icon' || s.kind === 'number') {
      out.size = round((s.size ?? ICON_SIZE_DEFAULT / box.baseScale) * box.scale);
    }
    return out;
  });
  return {
    ...spec,
    ink: INK_UNITS,
    panels: (spec.panels ?? []).map(framed),
    pastes: (spec.pastes ?? []).map(framed),
    shapes,
  };
}

/** Kinds drawn with a line, whose width defaulted to 4 when a spec left it out. */
const STROKED_KINDS = new Set(['rect', 'ellipse', 'line', 'arrow', 'curve', 'freehand']);

/**
 * Keep a pasted image inside the document. The document is sized by its panels
 * alone, so a paste can never grow it — dragged to the edge, it stops there. One
 * bigger than the document is held so it covers the whole of it.
 */
export function clampPaste(paste, docW, docH) {
  const scale = clampPasteScale(paste.scale);
  const w = paste.natural[0] * scale;
  const h = paste.natural[1] * scale;
  return {
    x: clamp(paste.x ?? 0, Math.min(0, docW - w), Math.max(0, docW - w)),
    y: clamp(paste.y ?? 0, Math.min(0, docH - h), Math.max(0, docH - h)),
  };
}

/**
 * An image's crop and turn, left out of the spec when it has neither. Both are
 * read against the source size, which is what the spec's `natural` holds.
 */
function surfaceGeometry(surface) {
  const source = surface.sourceNatural ?? surface.natural;
  const crop = normalizeSourceCrop(surface.crop, source);
  const rotation = normalizeSurfaceAngle(surface.rotation);
  return { ...(crop ? { crop } : {}), ...(rotation ? { rotation } : {}) };
}

/** What the panels answer with, frozen for the spec, marked when nobody aimed it. */
function frozenCoords(panels) {
  const auto = autoCoords(panels);
  return auto && !autoAimed(panels) ? { ...auto, proposed: true } : auto;
}

/** Serializable spec from runtime state (drops live image objects). */
export function toSpec(proof) {
  return {
    azimut_proof: 1,
    ink: INK_UNITS,
    title: proof.title,
    // A proof keeps the selected house-style identity as well as its copied
    // style values, so reopening it can restore the template picker.
    templateId: typeof proof.templateId === 'string' ? proof.templateId : null,
    // auto geo (first geo panel), for reference. A first row left empty is stated by
    // this, so it carries whether anyone checked it, or the save would file the
    // middle of a capture as the proof's conclusion.
    coords: frozenCoords(proof.panels),
    // The points the proof concludes on, and the mirror of the first for a build
    // that predates the list. Whether a point is where the camera stood rather
    // than what it filmed rides on the point itself: the proof cannot deduce it —
    // a rooftop shot is recorded somewhere it never shows — so the analyst says,
    // per line, and the place filed on save takes its verb from that line
    // (engine/satellite.restate_proof_point).
    ...statePoints({}, proof.points),
    // What the proof says about itself, both optional and neither printed: the
    // date the material was taken, and the sentence a post is written from. They
    // are mirrored onto the entity on save — `when` is what the Timeline reads,
    // the description is the proof's notes — so the graph and search see them
    // without opening this file (`api/proofs.save_proof`).
    when: proof.when?.trim() ? proof.when.trim() : null,
    // The clock the date is read on when the analyst picked one; null leaves it to
    // the first point's zone, resolved on save, so moving the point moves the day.
    whenZone: proof.when?.trim() && proof.whenZone ? proof.whenZone : null,
    description: proof.description?.trim() ? proof.description.trim() : null,
    // What the plate's footer prints. `footer` is the credit line itself;
    // `footerText` is whether it prints at all, and `footerCoords` whether the
    // proof's points print above it. Coordinates are off unless asked: they are
    // the footer lines that change the picture's height.
    footerCoords: proof.footerCoords === true,
    footerText: proof.footerText !== false,
    // The addresses the proof states, empty → traced from the panels instead. Named
    // for the plural like the multi-parent key of a media's own origin (`sources`,
    // beside `from`), because it draws the same distinction: one of them, or several.
    // null → traced from the panels; a list, empty included, → what the analyst states.
    sources: statedSources(proof.sources ?? proof.source ?? null),
    // Case files the proof rests on without composing them: the clip a panel was cut
    // from, the second angle nobody cropped. The save states `derived-from` over these
    // as well as over the panels, which is what puts them in the chain and, through it,
    // on the point (`api/proofs.save_proof`).
    //
    // Only what a stated address still answers for. A source taken off the proof takes
    // its files out of the chain with it — otherwise removing a row left the line
    // shorter and the graph exactly as it was, which is a proof saying two things.
    material: statedMaterial(
      proof.material,
      statedSources(proof.sources ?? proof.source ?? null) ?? autoSourceUrls(proof.panels ?? []),
    ),
    captionSize: proof.captionSize ?? CAPTION_SIZE,
    legendSize: proof.legendSize ?? LEGEND_SIZE,
    footerSize: proof.footerSize ?? FOOTER_SIZE,
    footer: proof.footer?.trim() ? proof.footer.trim() : null, // null → default attribution line
    footerEnabled: proof.footerEnabled !== false, // false → no footer line at all
    footerColor: proof.footerColor ?? null, // null → auto from the background
    footerAlign: proof.footerAlign === 'right' ? 'right' : 'left',
    captionColor: proof.captionColor ?? null, // null → auto from the background
    captionsEnabled: proof.captionsEnabled !== false, // default caption for newly added panels
    font: proofFontId(proof.font),
    fontBold: proof.fontBold !== false,
    bg: proof.bg ?? BG, // proof background fill; text colours follow it (textColors)
    space: normSpace(proof.space), // panel spacing {pad, gap, rowGap}
    layout: proof.layout ?? 'grid', // 'grid' (rows) | 'free' (per-panel x/y, overlap allowed)
    panelDirection: proof.layout !== 'free' && proof.panels?.length > 1
      ? ((proof.panels[0].row ?? 0) === (proof.panels[1].row ?? 0) ? 'horizontal' : 'vertical')
      : (proof.panelDirection === 'vertical' ? 'vertical' : 'horizontal'),
    // null → unsigned. The logo itself lives in the workspace, never in the
    // spec: a shared case reads the same, it just renders no signature without
    // the file (see config.signature_path).
    signature: proof.signature ? { ...proof.signature } : null,
    // The handle value lives in Settings; this stores only its optional slot.
    signatureText: textSignatureStyle(proof.signatureText),
    palette: normalizePreferredColors(proof.palette),
    notes: { ...(proof.notes ?? {}) },
    legendOrder: [...(proof.legendOrder ?? [])],
    panels: proof.panels.map((p) => ({
      id: p.id, // kept so shapes stay bound to their panel on reload
      src: p.src,
      caption: p.caption ?? '',
      row: p.row ?? 0, // vertical row (0 = top); missing → single-row layout
      scale: p.scale ?? 1, // per-panel size multiplier (1 = default PANEL_H)
      x: p.x ?? null, // free-layout doc position; null → grid fallback
      y: p.y ?? null,
      // Runtime `natural` is the upright box the turned image occupies. The
      // spec keeps the source size, which the crop and turn are read against.
      natural: p.sourceNatural ?? p.natural,
      meta: p.meta ?? {},
      frame: normalizeFrame(p.frame), // decorative border; null → none
      ...surfaceGeometry(p), // crop and turn, absent when there are neither
    })),
    // Pasted images, front→back. They have no `src`: the case holds nothing for
    // them beyond the file in the proof's own assets folder.
    pastes: (proof.pastes ?? []).map((p) => ({
      id: p.id, // kept so shapes stay bound to their paste on reload
      asset: p.asset,
      natural: p.sourceNatural ?? p.natural,
      x: p.x ?? 0,
      y: p.y ?? 0,
      scale: clampPasteScale(p.scale),
      frame: normalizeFrame(p.frame),
      ...surfaceGeometry(p),
    })),
    shapes: proof.shapes.map((s) => ({ ...s })),
  };
}

// ---- reusable house-style templates -----------------------------------------

/**
 * A content-free house style extracted from a proof (or a loaded spec): the
 * fields that make a proof look like "yours" — background, spacing, layout
 * mode, text sizes, footer line, signature placement and preferred colours.
 * Never the panels, shapes, legend text, title, coordinates or source.
 */
export function templateFromProof(proof) {
  return normalizeProofStyle({
    bg: proof.bg ?? BG,
    space: normSpace(proof.space),
    layout: proof.layout ?? 'grid',
    captionSize: proof.captionSize ?? CAPTION_SIZE,
    legendSize: proof.legendSize ?? LEGEND_SIZE,
    footerSize: proof.footerSize ?? FOOTER_SIZE,
    footer: proof.footer ?? '',
    footerEnabled: proof.footerEnabled !== false,
    footerText: proof.footerText !== false,
    footerCoords: proof.footerCoords === true,
    footerColor: proof.footerColor ?? null,
    footerAlign: proof.footerAlign === 'right' ? 'right' : 'left',
    captionColor: proof.captionColor ?? null,
    captionsEnabled: proof.captionsEnabled !== false,
    panelDirection: proof.layout !== 'free' && proof.panels?.length > 1
      ? ((proof.panels[0].row ?? 0) === (proof.panels[1].row ?? 0) ? 'horizontal' : 'vertical')
      : (proof.panelDirection === 'vertical' ? 'vertical' : 'horizontal'),
    font: proofFontId(proof.font),
    fontBold: proof.fontBold !== false,
    signature: proof.signature ? { ...proof.signature } : null,
    signatureText: textSignatureStyle(proof.signatureText),
    palette: normalizePreferredColors(proof.palette),
  });
}

function normalizedSignature(signature) {
  if (!signature || typeof signature !== 'object' || Array.isArray(signature)) return null;
  const style = {
    anchor: ['tl', 'tr', 'bl', 'br'].includes(signature.anchor) ? signature.anchor : 'br',
    dx: boundedNumber(signature.dx, 0, -100_000, 100_000),
    dy: boundedNumber(signature.dy, 0, -100_000, 100_000),
    scale: boundedNumber(signature.scale, SIG_SCALE, 0.03, 0.6),
    opacity: boundedNumber(signature.opacity, SIG_OPACITY, 0, 1),
  };
  if (Number.isFinite(signature.xRatio)) style.xRatio = clamp(signature.xRatio, 0, 1);
  if (Number.isFinite(signature.yRatio)) style.yRatio = clamp(signature.yRatio, 0, 1);
  return style;
}

/** Canonical, content-free proof style safe to feed into preview/render code. */
export function normalizeProofStyle(style = {}) {
  const source = style && typeof style === 'object' && !Array.isArray(style) ? style : {};
  return {
    bg: normalizedColor(source.bg, BG),
    space: normSpace(source.space),
    layout: source.layout === 'free' ? 'free' : 'grid',
    captionSize: boundedNumber(source.captionSize, CAPTION_SIZE, 8, 80),
    legendSize: boundedNumber(source.legendSize, LEGEND_SIZE, 8, 80),
    footerSize: boundedNumber(source.footerSize, FOOTER_SIZE, 8, 80),
    footer: typeof source.footer === 'string' ? source.footer.slice(0, 200) : '',
    footerEnabled: typeof source.footerEnabled === 'boolean' ? source.footerEnabled : true,
    // A template saved before these existed says nothing about them, and a style
    // that says nothing must not change what a proof does: the credit line goes on
    // printing, the coordinates go on not printing.
    footerText: typeof source.footerText === 'boolean' ? source.footerText : true,
    footerCoords: source.footerCoords === true,
    footerColor: source.footerColor == null ? null : normalizedColor(source.footerColor, null),
    footerAlign: source.footerAlign === 'right' ? 'right' : 'left',
    captionColor: source.captionColor == null ? null : normalizedColor(source.captionColor, null),
    captionsEnabled: typeof source.captionsEnabled === 'boolean' ? source.captionsEnabled : true,
    panelDirection: source.panelDirection === 'vertical' ? 'vertical' : 'horizontal',
    // A style or a proof from before fonts says nothing, and keeps the system's.
    font: proofFontId(source.font),
    fontBold: typeof source.fontBold === 'boolean' ? source.fontBold : true,
    signature: normalizedSignature(source.signature),
    signatureText: textSignatureStyle(source.signatureText),
    palette: normalizePreferredColors(source.palette),
  };
}

/**
 * Apply a house style onto a proof, mutating it in place. Panel content,
 * shapes, title, coordinates and source stay untouched; the first pair's rows
 * may change when the template specifies their direction. Legend text and its
 * order are content, so templates leave both untouched.
 */
export function applyProofStyle(proof, style, available = {}) {
  if (!style) return proof;
  const source = typeof style === 'object' && !Array.isArray(style) ? style : {};
  const normalized = normalizeProofStyle(source);
  if ('bg' in source) proof.bg = normalized.bg;
  if ('space' in source) proof.space = normalized.space;
  if ('layout' in source) proof.layout = normalized.layout;
  if ('captionSize' in source) proof.captionSize = normalized.captionSize;
  if ('legendSize' in source) proof.legendSize = normalized.legendSize;
  if ('footerSize' in source) proof.footerSize = normalized.footerSize;
  if ('footer' in source) proof.footer = normalized.footer;
  if ('footerEnabled' in source) proof.footerEnabled = normalized.footerEnabled;
  // Absent from an older template, so an old house style leaves both alone rather
  // than quietly taking a proof's coordinates off its plate.
  if ('footerText' in source) proof.footerText = normalized.footerText;
  if ('footerCoords' in source) proof.footerCoords = normalized.footerCoords;
  if ('footerColor' in source) proof.footerColor = normalized.footerColor;
  if ('footerAlign' in source) proof.footerAlign = normalized.footerAlign;
  if ('captionColor' in source) proof.captionColor = normalized.captionColor;
  if ('captionsEnabled' in source) proof.captionsEnabled = normalized.captionsEnabled;
  if ('font' in source) proof.font = normalized.font;
  if ('fontBold' in source) proof.fontBold = normalized.fontBold;
  if ('panelDirection' in source) {
    proof.panelDirection = normalized.panelDirection;
    orientFirstPanels(proof.panels ?? [], proof.panelDirection);
  }
  proof.signature = normalized.signature && available.logo !== false ? normalized.signature : null;
  proof.signatureText = normalized.signatureText && available.handle !== false
    ? normalized.signatureText
    : null;
  if ('palette' in source) proof.palette = normalized.palette;
  return proof;
}

/**
 * Detached, plain deep copy of a shape spec (id stripped) for the clipboard.
 * A shape is pure JSON data, so a JSON round-trip both unwraps any reactive
 * proxy — `structuredClone` of a live proxy throws in the browser, and a shallow
 * spread leaves points-based shapes with a proxied `points` array,
 * which silently broke copy for those kinds — and fully detaches the copy.
 */
export function copyShapeSpec(shape) {
  const clone = JSON.parse(JSON.stringify(shape));
  delete clone.id;
  return clone;
}

/**
 * Copy of a shape spec moved by (`dx`, `dy`) of its surface's pixels, for
 * paste/duplicate. Points-based kinds shift every vertex; box/ellipse/text
 * shift their x/y. The returned spec carries no id — the caller assigns one.
 */
export function offsetShape(shape, dx, dy = dx) {
  const s = structuredClone(shape);
  delete s.id;
  if (Array.isArray(s.points)) {
    s.points = s.points.map((v, i) => v + (i % 2 === 0 ? dx : dy));
  } else {
    s.x = (s.x ?? 0) + dx;
    s.y = (s.y ?? 0) + dy;
  }
  return s;
}

/**
 * Panel input for a satellite capture. The caption is provider · coordinates,
 * dated with the imagery acquisition date (when the satellite scene was shot,
 * NOT when we fetched the tiles) — the date part is simply omitted when the
 * provider doesn't expose it, never substituted with the fetch date.
 */
export function satPanelInput(s, format = 'dd') {
  // the caption follows the reader's format; the panel meta below keeps the
  // raw decimal degrees, so provenance stays machine-readable either way
  const parts = [`${s.provider_label} · ${renderCoords(s.lat, s.lon, format)}`];
  if (s.imagery_date) parts.push(s.imagery_date);
  return {
    src: s.path,
    meta: {
      kind: 'satellite', attribution: s.attribution, lat: s.lat, lon: s.lon,
      aimed: captureAimed(s), zoom: s.zoom, provider: s.provider_label,
      date: s.fetched_at?.slice(0, 10), imagery_date: s.imagery_date ?? null,
    },
    caption: parts.join(' · '),
  };
}

/**
 * Panel input for a media image. Traces the real source link through the
 * derivation chain (a collage/frame carries no URL of its own — follow it back
 * to the downloaded original). A file uploaded from disk has no URL, so it
 * contributes no source. A picture of a saved Horizon view also brings the eye
 * it was drawn from, as the point the proof states, and the terrain's credits.
 */
export function mediaPanelInput(m, mediaList = []) {
  const byPath = new Map(mediaList.map((x) => [x.path, x]));
  const urls = resolveSourceUrls(m, byPath);
  const source = m.source ?? {};
  if (source.type === 'horizon' && source.lat != null && source.lon != null) {
    // a picture of a saved Horizon view stands where its eye stood, which the analyst
    // placed: the proof answers with that point, and the photo's own link is its source
    return {
      src: m.path,
      meta: {
        kind: 'horizon', source_url: urls[0], source_urls: urls, lat: source.lat, lon: source.lon,
        aimed: true, attribution: source.attribution ?? '', heading: source.heading ?? null,
      },
      caption: { photo: 'Photo, the terrain\'s ridge lines over it', terrain: 'Terrain, simulated from the same eye' }[source.kind] ?? '',
    };
  }
  return {
    src: m.path,
    meta: { kind: 'media', source_url: urls[0], source_urls: urls },
    caption: '',
  };
}

/**
 * Collapse picker items that share a `src` down to their first occurrence.
 * The picker builds its list so no `src` repeats, but a duplicate key would
 * throw Svelte's `each_key_duplicate` and blank the whole modal — so this is a
 * cheap last-line guard around that keyed `{#each … (item.src)}`. Callers list
 * the richer satellite entry first, so the kept one carries coords/attribution.
 */
export function dedupeBySrc(items) {
  const seen = new Set();
  return items.filter((it) => {
    if (seen.has(it.src)) return false;
    seen.add(it.src);
    return true;
  });
}

/**
 * Auto-arrange panels into stacked rows so the whole composite's aspect ratio
 * lands as close as possible to `target` (a tweet-friendly aspect: 16:9 shows
 * uncropped in the X timeline, 4:5 fills the feed). Array order is preserved —
 * we only choose where to break the sequence into rows — so the caller keeps
 * left→right ordering. Returns one row index per panel (aligned with `panels`).
 *
 * The composite includes the legend + footer bands (they're part of the image
 * that gets cropped), so `shapes`/`notes`/`text` are folded into the measure.
 * Exhaustive search stays useful for small proofs. Larger documents use a
 * deterministic balanced-row search so runtime remains bounded.
 */
export function autoLayoutRows(
  panels, shapes = [], notes = {}, text = {}, target = TWEET_GUIDES['16:9'], space,
) {
  const n = panels.length;
  if (n <= 1) return panels.map(() => 0);
  let best = null;
  const measure = (rows) => {
    const candidate = panels.map((p, i) => ({ ...p, row: rows[i], scale: 1 }));
    const { width, height } = docSize(candidate, shapes, notes, text, [], 'grid', space);
    const score = Math.abs(width / height - target);
    if (!best || score < best.score) best = { score, rows };
  };

  const exhaustiveLimit = 12;
  if (n <= exhaustiveLimit) {
    const combos = 2 ** (n - 1);
    for (let mask = 0; mask < combos; mask++) {
      let row = 0;
      const rows = [0];
      for (let i = 1; i < n; i++) {
        if (mask & (2 ** (i - 1))) row += 1;
        rows.push(row);
      }
      measure(rows);
    }
    return best.rows;
  }

  const weights = panels.map((panel) => {
    const width = panel?.natural?.[0];
    const height = panel?.natural?.[1];
    return Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0
      ? width / height
      : 1;
  });
  const total = weights.reduce((sum, weight) => sum + weight, 0);
  const maxRows = Math.min(n, 64);
  for (let rowCount = 1; rowCount <= maxRows; rowCount++) {
    const rows = [];
    let row = 0;
    let cumulative = 0;
    for (let i = 0; i < n; i++) {
      rows.push(row);
      cumulative += weights[i];
      const remainingItems = n - i - 1;
      const remainingRows = rowCount - row - 1;
      if (
        row < rowCount - 1
        && (remainingItems === remainingRows || cumulative >= total * (row + 1) / rowCount)
      ) {
        row += 1;
      }
    }
    measure(rows);
  }
  return best.rows;
}

/** Safe canvas export settings for a measured proof document. */
export function proofExportOptions(width, height) {
  if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
    throw new RangeError('Proof dimensions are invalid.');
  }
  const pixelRatio = Math.min(Math.max(1800 / width, 0.75), 2);
  const outputWidth = Math.ceil(width * pixelRatio);
  const outputHeight = Math.ceil(height * pixelRatio);
  if (
    outputWidth > MAX_EXPORT_DIMENSION
    || outputHeight > MAX_EXPORT_DIMENSION
    || outputWidth * outputHeight > MAX_EXPORT_PIXELS
  ) {
    throw new RangeError('Proof is too large to export. Reduce its panel count or spacing.');
  }
  return { pixelRatio, outputWidth, outputHeight };
}

// ---- editor geometry & ordering (pure helpers behind the canvas gestures) ---

/**
 * A mark carried from one surface onto another without changing on the page.
 *
 * Where it stands and what it spans are measured again in the new surface's
 * pixels, and its turn takes the difference between the two surfaces' turns.
 * Its ink is in page pixels already, so a line, a label or a symbol keeps its
 * weight. `from` and `to` are `surfaceFrame`s. A turned polyline has its turn
 * folded into the vertices, since each one is carried on its own.
 */
export function moveShapeToSurface(shape, from, to) {
  const across = (x, y) => pageToSurface(surfaceToPage({ x, y }, from), to);
  const out = { ...shape };
  if (Array.isArray(shape.points)) {
    const points = [];
    for (let i = 0; i < shape.points.length; i += 2) {
      const own = turned(shape.points[i], shape.points[i + 1], shape.rotation ?? 0);
      const q = across(own.x, own.y);
      points.push(q.x, q.y);
    }
    out.points = points;
    if ('rotation' in out) out.rotation = 0;
    return out;
  }
  const q = across(shape.x ?? 0, shape.y ?? 0);
  out.x = q.x;
  out.y = q.y;
  // A callout's tip is a point and an inset's frame stays square to its picture,
  // so neither takes a turn; their labels and enlargements stand upright anyway.
  if (!isPageMark(shape)) {
    const rotation = normalizeSurfaceAngle((shape.rotation ?? 0) + from.rotation - to.rotation);
    if (rotation || 'rotation' in out) out.rotation = rotation;
  }
  const k = from.box.scale / to.box.scale;
  if (Number.isFinite(shape.w)) out.w = shape.w * k;
  if (Number.isFinite(shape.h)) out.h = shape.h * k;
  // a view cone reaches as far on the page as it did
  if (Number.isFinite(shape.reach)) out.reach = shape.reach * k;
  return out;
}

/**
 * Index to swap `index` with when nudging it by `delta` (±1) while staying in
 * its own group: the nearest item in that direction sharing its group key
 * (`keyOf(item)` → a panel's row, a shape's panel). -1 when none (group edge).
 */
export function groupNeighborIndex(items, index, delta, keyOf) {
  const key = keyOf(items[index]);
  let target = index + delta;
  while (target >= 0 && target < items.length && keyOf(items[target]) !== key) {
    target += delta;
  }
  return target >= 0 && target < items.length && keyOf(items[target]) === key ? target : -1;
}

/** Whether `index` has a same-group item before it (delta<0) or after it (delta>0). */
export function hasGroupNeighbor(items, index, delta, keyOf) {
  const key = keyOf(items[index]);
  const side = delta < 0 ? items.slice(0, index) : items.slice(index + 1);
  return side.some((it) => keyOf(it) === key);
}

/**
 * Dense 0..n-1 row numbers for panels whose `row` indices went sparse after a
 * move emptied one. Ascending distinct rows map to 0,1,2,…; returns one value
 * per panel (aligned with `panels`) for the caller to assign back in place.
 */
export function denseRowValues(panels) {
  const order = [...new Set(panels.map((p) => p.row ?? 0))].sort((a, b) => a - b);
  const remap = new Map(order.map((r, i) => [r, i]));
  return panels.map((p) => remap.get(p.row ?? 0));
}

/** Clamp a panel scale after a `delta`, rounded to whole percent. */
export function clampPanelScale(current, delta, min, max) {
  return Math.round(Math.min(max, Math.max(min, (current ?? 1) + delta)) * 100) / 100;
}

/**
 * Drop the duplicate final vertex a double-click leaves on a drawn curve: if
 * the last point sits within `threshold` doc px of the previous one, trim it.
 * `points` is a flat [x0,y0,x1,y1,…] array; returns a (possibly shorter) copy.
 */
export function trimClosingDuplicate(points, threshold = 3) {
  const n = points.length;
  if (n >= 4 && Math.hypot(points[n - 2] - points[n - 4], points[n - 1] - points[n - 3]) < threshold) {
    return points.slice(0, n - 2);
  }
  return points.slice();
}

/**
 * Lightly smooth a pointer-drawn polyline. Samples closer than `minDistance`
 * are folded together first, then one weighted moving-average pass removes
 * hand jitter while preserving both endpoints.
 */
export function smoothFreehandPoints(points, minDistance = 1) {
  if (!Array.isArray(points) || points.length < 4) return [...(points ?? [])];
  const threshold = Math.max(0, minDistance);
  const sampled = [points[0], points[1]];
  for (let i = 2; i < points.length - 2; i += 2) {
    const lx = sampled[sampled.length - 2];
    const ly = sampled[sampled.length - 1];
    if (Math.hypot(points[i] - lx, points[i + 1] - ly) > threshold) {
      sampled.push(points[i], points[i + 1]);
    }
  }

  const endX = points[points.length - 2];
  const endY = points[points.length - 1];
  if (sampled.length === 2) sampled.push(endX, endY);
  else {
    const lx = sampled[sampled.length - 2];
    const ly = sampled[sampled.length - 1];
    if (Math.hypot(endX - lx, endY - ly) > threshold) sampled.push(endX, endY);
    else {
      sampled[sampled.length - 2] = endX;
      sampled[sampled.length - 1] = endY;
    }
  }
  if (sampled.length < 6) return sampled;

  const smoothed = [sampled[0], sampled[1]];
  for (let i = 2; i < sampled.length - 2; i += 2) {
    smoothed.push(
      (sampled[i - 2] + sampled[i] * 2 + sampled[i + 2]) / 4,
      (sampled[i - 1] + sampled[i + 1] * 2 + sampled[i + 3]) / 4,
    );
  }
  smoothed.push(sampled[sampled.length - 2], sampled[sampled.length - 1]);
  return smoothed;
}

/** Build a persisted freehand shape, or reject a click/tiny accidental drag. */
export function freehandShape(points, { minDistance = 1, minLength = 5 } = {}) {
  const smoothed = smoothFreehandPoints(points, minDistance);
  let length = 0;
  for (let i = 2; i < smoothed.length; i += 2) {
    length += Math.hypot(smoothed[i] - smoothed[i - 2], smoothed[i + 1] - smoothed[i - 1]);
  }
  return smoothed.length >= 4 && length > minLength
    ? { kind: 'freehand', points: smoothed, tension: 0.25 }
    : null;
}

/**
 * Whether the legend note on `oldColor` should follow a shape recolored to
 * `newColor`: only when `newColor` carries no note yet and no *other* shape
 * still uses `oldColor`, so the note is neither stranded on an unused color nor
 * stolen from shapes that keep it. `moving` is the shape being recolored.
 */
export function canReassignLegendNote(notes, oldColor, newColor, shapes, moving) {
  return Boolean(
    notes?.[oldColor] && !notes?.[newColor] &&
    !shapes.some((s) => s !== moving && s.color === oldColor),
  );
}

export function loadImage(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error(`could not load ${url}`));
    img.src = url;
  });
}