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47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import dagre from '@dagrejs/dagre';

// Node types that form the plan itself; they are arranged by the layout.
const FLOW_TYPES = new Set(['sketch', 'condition', 'cluster']);
// Annotation-like nodes; they follow the plan node they are attached to.
const STICKER_TYPES = new Set(['comment', 'image', 'text']);

export const LAYOUT_MODES = ['web', 'flow'];

const DEFAULT_SIZES = {
  sketch: { width: 230, height: 115 },
  condition: { width: 170, height: 150 },
  cluster: { width: 280, height: 170 },
  comment: { width: 200, height: 150 },
  image: { width: 300, height: 200 },
  text: { width: 200, height: 60 },
};

const TAU = Math.PI * 2;

const toNumber = (value) => {
  if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;
  if (typeof value === 'string') {
    const parsed = parseFloat(value);
    return Number.isFinite(parsed) ? parsed : undefined;
  }
  return undefined;
};

export const getNodeSize = (node) => {
  const fallback = DEFAULT_SIZES[node.type] || DEFAULT_SIZES.sketch;
  return {
    width: toNumber(node.measured?.width) ?? toNumber(node.width) ?? toNumber(node.style?.width) ?? fallback.width,
    height: toNumber(node.measured?.height) ?? toNumber(node.height) ?? toNumber(node.style?.height) ?? fallback.height,
  };
};

// Half of the diagonal: the radius of a circle that contains the node
const radiusOf = (size) => 0.5 * Math.hypot(size.width, size.height);

const centerOf = (node) => {
  const { width, height } = getNodeSize(node);
  return { x: node.position.x + width / 2, y: node.position.y + height / 2 };
};

const boundsOf = (nodes, positionOf) => {
  let minX = Infinity;
  let minY = Infinity;
  nodes.forEach((n) => {
    const p = positionOf(n);
    minX = Math.min(minX, p.x);
    minY = Math.min(minY, p.y);
  });
  return { x: minX, y: minY };
};

// ---------------------------------------------------------------------------
// Flow mode: layered top-to-bottom graph (dagre)
// ---------------------------------------------------------------------------
const layoutFlow = (movable, edges, direction) => {
  const movableIds = new Set(movable.map((n) => n.id));
  const g = new dagre.graphlib.Graph({ multigraph: true });
  g.setGraph({ rankdir: direction, nodesep: 70, ranksep: 110, edgesep: 30, marginx: 0, marginy: 0 });
  g.setDefaultEdgeLabel(() => ({}));

  movable.forEach((n) => g.setNode(n.id, getNodeSize(n)));
  edges.forEach((e) => {
    if (movableIds.has(e.source) && movableIds.has(e.target) && e.source !== e.target) {
      g.setEdge(e.source, e.target, {}, e.id);
    }
  });

  dagre.layout(g);

  // dagre returns centers; React Flow positions are top-left corners
  const laidOut = {};
  movable.forEach((n) => {
    const { x, y } = g.node(n.id);
    const { width, height } = getNodeSize(n);
    laidOut[n.id] = { x: x - width / 2, y: y - height / 2 };
  });

  // Keep the block anchored where it was
  const before = boundsOf(movable, (n) => n.position);
  const after = boundsOf(movable, (n) => laidOut[n.id]);
  const result = {};
  movable.forEach((n) => {
    result[n.id] = { x: Math.round(laidOut[n.id].x + before.x - after.x), y: Math.round(laidOut[n.id].y + before.y - after.y) };
  });
  return result;
};

// ---------------------------------------------------------------------------
// Web mode: radial tree around the most connected node, like a spider web.
// Every node gets an angular slot proportional to the size of its branch and
// its own distance from the parent, so branches stay compact instead of being
// pushed onto huge shared rings.
// ---------------------------------------------------------------------------
const SIBLING_GAP = 50;
const PARENT_GAP = 70;

const layoutWebComponent = (compIds, adj, outDeg, inDeg, byId) => {
  const size = (id) => getNodeSize(byId.get(id));

  // Root: the hub of the component (most links), preferring a node nothing points to
  let root = compIds[0];
  let bestScore = -Infinity;
  compIds.forEach((id) => {
    const score = adj.get(id).size * 3 + outDeg.get(id) + (inDeg.get(id) === 0 ? 2 : 0);
    if (score > bestScore) {
      bestScore = score;
      root = id;
    }
  });

  // Spanning tree (BFS); children keep the order of their current angle around the parent
  const children = new Map(compIds.map((id) => [id, []]));
  const parent = new Map([[root, null]]);
  const order = [root];
  for (let i = 0; i < order.length; i++) {
    const v = order[i];
    const vc = centerOf(byId.get(v));
    const next = [...adj.get(v)].filter((u) => !parent.has(u));
    next.sort((a, b) => {
      const ca = centerOf(byId.get(a));
      const cb = centerOf(byId.get(b));
      return Math.atan2(ca.y - vc.y, ca.x - vc.x) - Math.atan2(cb.y - vc.y, cb.x - vc.x);
    });
    next.forEach((u) => {
      parent.set(u, v);
      children.get(v).push(u);
      order.push(u);
    });
  }

  // Branch weights: wide nodes and big branches need more angle
  const weight = new Map();
  for (let i = order.length - 1; i >= 0; i--) {
    const v = order[i];
    const kids = children.get(v);
    const own = Math.min(2, Math.max(0.8, size(v).width / 230));
    weight.set(v, kids.length ? Math.max(own, kids.reduce((s, c) => s + weight.get(c), 0)) : own);
  }

  // Angular slots
  const slot = new Map(); // id -> { from, to, angle }
  const firstKid = children.get(root)[0];
  const rootCenter = centerOf(byId.get(root));
  let start = -Math.PI / 2;
  if (firstKid) {
    const fc = centerOf(byId.get(firstKid));
    const share = (TAU * weight.get(firstKid)) / weight.get(root);
    start = Math.atan2(fc.y - rootCenter.y, fc.x - rootCenter.x) - share / 2;
  }
  slot.set(root, { from: start, to: start + TAU, angle: start });

  order.forEach((v) => {
    const kids = children.get(v);
    if (!kids.length) return;
    let { from, to, angle } = slot.get(v);
    let span = to - from;
    if (v !== root) {
      // Keep a fan tight around its parent instead of spreading over the whole sector
      const maxSpan = Math.min(span, Math.max(Math.PI / 3, kids.length * (Math.PI / 5)));
      from = angle - maxSpan / 2;
      span = maxSpan;
    }
    const total = kids.reduce((s, c) => s + weight.get(c), 0);
    let cursor = from;
    kids.forEach((c) => {
      const share = (span * weight.get(c)) / total;
      slot.set(c, { from: cursor, to: cursor + share, angle: cursor + share / 2 });
      cursor += share;
    });
  });

  // Distances: far enough from the parent, and wide enough apart from the siblings
  const radius = new Map([[root, 0]]);
  const centers = new Map([[root, { x: 0, y: 0 }]]);
  order.slice(1).forEach((v) => {
    const p = parent.get(v);
    const { from, to, angle } = slot.get(v);
    const share = Math.max(0.05, Math.min(Math.PI, to - from));
    const sv = size(v);
    const fromParent = radius.get(p) + radiusOf(size(p)) * (p === root ? 1 : 0.6) + radiusOf(sv) * 0.8 + PARENT_GAP;
    const forSiblings = (Math.max(sv.width, sv.height) + SIBLING_GAP) / (2 * Math.sin(share / 2));
    const r = Math.max(fromParent, forSiblings);
    radius.set(v, r);
    centers.set(v, { x: r * Math.cos(angle), y: r * Math.sin(angle) });
  });

  return { root, centers };
};

const layoutWeb = (movable, edges) => {
  const byId = new Map(movable.map((n) => [n.id, n]));
  const adj = new Map(movable.map((n) => [n.id, new Set()]));
  const outDeg = new Map(movable.map((n) => [n.id, 0]));
  const inDeg = new Map(movable.map((n) => [n.id, 0]));
  edges.forEach((e) => {
    if (e.source === e.target || !adj.has(e.source) || !adj.has(e.target)) return;
    adj.get(e.source).add(e.target);
    adj.get(e.target).add(e.source);
    outDeg.set(e.source, outDeg.get(e.source) + 1);
    inDeg.set(e.target, inDeg.get(e.target) + 1);
  });

  // Connected components, biggest first
  const seen = new Set();
  const components = [];
  movable.forEach((n) => {
    if (seen.has(n.id)) return;
    const comp = [];
    const stack = [n.id];
    seen.add(n.id);
    while (stack.length) {
      const v = stack.pop();
      comp.push(v);
      adj.get(v).forEach((u) => {
        if (!seen.has(u)) {
          seen.add(u);
          stack.push(u);
        }
      });
    }
    components.push(comp);
  });
  components.sort((a, b) => b.length - a.length);

  const result = {};
  const roots = {};
  const bboxOf = (ids, centers) => {
    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
    ids.forEach((id) => {
      const c = centers.get(id);
      const { width, height } = getNodeSize(byId.get(id));
      minX = Math.min(minX, c.x - width / 2);
      minY = Math.min(minY, c.y - height / 2);
      maxX = Math.max(maxX, c.x + width / 2);
      maxY = Math.max(maxY, c.y + height / 2);
    });
    return { minX, minY, maxX, maxY };
  };

  const graphs = components.filter((c) => c.length > 1);
  const singles = components.filter((c) => c.length === 1).map((c) => c[0]);

  let mainBox = null;
  let cursorX = 0;
  graphs.forEach((comp, i) => {
    const { root, centers } = layoutWebComponent(comp, adj, outDeg, inDeg, byId);
    let dx;
    let dy;
    const box = bboxOf(comp, centers);
    if (i === 0) {
      // The main web stays where its hub was
      const old = centerOf(byId.get(root));
      dx = old.x;
      dy = old.y;
      mainBox = { minX: box.minX + dx, minY: box.minY + dy, maxX: box.maxX + dx, maxY: box.maxY + dy };
      cursorX = mainBox.maxX + 200;
    } else {
      dx = cursorX - box.minX;
      dy = mainBox.minY - box.minY;
      cursorX += box.maxX - box.minX + 200;
      mainBox.maxY = Math.max(mainBox.maxY, box.maxY + dy);
    }
    comp.forEach((id) => {
      const c = centers.get(id);
      result[id] = { x: c.x + dx, y: c.y + dy };
    });
    roots[root] = true;
  });

  // Loose nodes line up under the webs
  if (singles.length) {
    const startX = mainBox ? mainBox.minX : centerOf(byId.get(singles[0])).x;
    let x = startX;
    let y = mainBox ? mainBox.maxY + 160 : centerOf(byId.get(singles[0])).y;
    let rowH = 0;
    const rowLimit = Math.max(1200, mainBox ? mainBox.maxX - mainBox.minX : 1200);
    singles.forEach((id) => {
      const { width, height } = getNodeSize(byId.get(id));
      if (x - startX + width > rowLimit) {
        x = startX;
        y += rowH + 60;
        rowH = 0;
      }
      result[id] = { x: x + width / 2, y: y + height / 2 };
      x += width + 60;
      rowH = Math.max(rowH, height);
    });
  }

  // Centers -> top-left corners
  const positions = {};
  Object.entries(result).forEach(([id, c]) => {
    const { width, height } = getNodeSize(byId.get(id));
    positions[id] = { x: Math.round(c.x - width / 2), y: Math.round(c.y - height / 2) };
  });
  return { positions, centers: result, hubCenters: Object.keys(roots).map((id) => result[id]) };
};

/**
 * Computes tidy positions for the plan nodes.
 *
 * mode "web":  radial "spider web" around the most connected node (compact, organic).
 * mode "flow": layered top-to-bottom graph.
 *
 * - Stickers, texts and images linked to a moved node move with it ("web" puts them
 *   on the outer side of their node, "flow" keeps their offset).
 * - Pinned and hidden nodes are left where they are.
 * - When `onlyIds` is given (e.g. the current selection), only those nodes are arranged.
 *
 * Returns a map { [nodeId]: { x, y } } with the new positions of the nodes that move.
 */
export const computeAutoLayout = (nodes, edges, { mode = 'flow', direction = 'TB', onlyIds = null } = {}) => {
  const scope = onlyIds ? new Set(onlyIds) : null;
  const movable = nodes.filter(
    (n) => FLOW_TYPES.has(n.type) && !n.hidden && !n.data?.isPinned && (!scope || scope.has(n.id))
  );
  if (movable.length < 2) return {};

  const nodeById = new Map(nodes.map((n) => [n.id, n]));
  const stickers = nodes.filter((n) => STICKER_TYPES.has(n.type) && !n.hidden && !n.data?.isPinned);

  if (mode !== 'web') {
    const result = layoutFlow(movable, edges, direction);
    stickers.forEach((sticker) => {
      if (result[sticker.id]) return;
      const link = edges.find(
        (e) => (e.source === sticker.id && result[e.target]) || (e.target === sticker.id && result[e.source])
      );
      if (!link) return;
      const anchorId = link.source === sticker.id ? link.target : link.source;
      const anchor = nodeById.get(anchorId);
      result[sticker.id] = {
        x: Math.round(sticker.position.x + (result[anchorId].x - anchor.position.x)),
        y: Math.round(sticker.position.y + (result[anchorId].y - anchor.position.y)),
      };
    });
    return result;
  }

  const { positions, centers, hubCenters } = layoutWeb(movable, edges);

  // Stickers go on the outer side of their node, fanned out when there are several
  const byAnchor = new Map();
  stickers.forEach((sticker) => {
    const link = edges.find(
      (e) => (e.source === sticker.id && centers[e.target]) || (e.target === sticker.id && centers[e.source])
    );
    if (!link) return;
    const anchorId = link.source === sticker.id ? link.target : link.source;
    if (!byAnchor.has(anchorId)) byAnchor.set(anchorId, []);
    byAnchor.get(anchorId).push(sticker);
  });

  byAnchor.forEach((list, anchorId) => {
    const anchorCenter = centers[anchorId];
    const hub = hubCenters.reduce(
      (best, h) => (!best || Math.hypot(h.x - anchorCenter.x, h.y - anchorCenter.y) < Math.hypot(best.x - anchorCenter.x, best.y - anchorCenter.y) ? h : best),
      null
    ) || anchorCenter;
    let base = Math.atan2(anchorCenter.y - hub.y, anchorCenter.x - hub.x);
    if (Math.hypot(anchorCenter.x - hub.x, anchorCenter.y - hub.y) < 1) base = 0;
    const anchorR = radiusOf(getNodeSize(nodeById.get(anchorId)));
    list.forEach((sticker, i) => {
      const step = Math.ceil(i / 2) * (i % 2 ? 1 : -1);
      const angle = base + step * 0.55;
      const size = getNodeSize(sticker);
      const dist = anchorR + radiusOf(size) * 0.85 + 40;
      positions[sticker.id] = {
        x: Math.round(anchorCenter.x + Math.cos(angle) * dist - size.width / 2),
        y: Math.round(anchorCenter.y + Math.sin(angle) * dist - size.height / 2),
      };
    });
  });

  return positions;
};

/**
 * Lays out a node list that has no meaningful positions yet (e.g. a built-in template).
 * Mutates nothing; returns a new node array.
 */
export const layoutFresh = (nodes, edges, options) => {
  const seeded = nodes.map((n, i) => ({ ...n, position: n.position || { x: 0, y: i } }));
  const flowOnly = seeded.filter((n) => FLOW_TYPES.has(n.type));
  const positions = computeAutoLayout(flowOnly, edges, options);
  const placed = seeded.map((n) => (positions[n.id] ? { ...n, position: positions[n.id] } : n));
  const byId = new Map(placed.map((n) => [n.id, n]));

  // Annotations without a position go to the right of the node they are linked to
  let looseY = 0;
  return placed.map((n) => {
    if (FLOW_TYPES.has(n.type) || n.position.x !== 0 || nodes.find((o) => o.id === n.id)?.position) return n;
    const link = edges.find((e) => (e.source === n.id && positions[e.target]) || (e.target === n.id && positions[e.source]));
    if (link) {
      const anchor = byId.get(link.source === n.id ? link.target : link.source);
      return { ...n, position: { x: anchor.position.x + getNodeSize(anchor).width + 80, y: anchor.position.y } };
    }
    const position = { x: -getNodeSize(n).width - 80, y: looseY };
    looseY += getNodeSize(n).height + 40;
    return { ...n, position };
  });
};

export const easeInOutCubic = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);