morpharch 2.2.3

Monorepo architecture drift visualizer with animated TUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
// =============================================================================
// tui/graph_renderer.rs — Verlet physics + Ratatui Canvas graph rendering
// =============================================================================
//
// Force-directed graph layout using Verlet integration:
//   1. Repulsion: Barnes-Hut — optimized O(V log V) repulsion using Quadtree
//   2. Attraction: Hooke spring — edge-connected nodes attract toward ideal length
//   3. Center gravity: Gentle pull toward canvas center prevents drift
//   4. Micro-jitter: Temperature-scaled random perturbation for organic feel
//   5. Damping: Velocity reduced each step for convergence
//   6. Bounds enforcement: Nodes stay within the drawing area
//   7. Temperature decay: Graph gradually settles; reheat for re-energize
//
// The ideal edge length adapts dynamically to node count and canvas area,
// ensuring good layouts for both small (3 nodes) and large (100+) graphs.
//
// Performance: O(V log V) repulsion + O(E) attraction
//
// Coloring: Green -> red gradient based on drift score (Catppuccin Mocha)
// =============================================================================

use rand::Rng;
use ratatui::style::Color;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GraphRelationSemantic {
    Neutral,
    Focus,
    Hover,
    Inbound,
    Outbound,
    Bidirectional,
    Related,
    SearchMatch,
    CascadeSource,
    CascadeDimmed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClusterMapSemantic {
    Hovered,
    Central,
    ThirdParty,
    Entrypoint,
    Support,
    Neutral,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OverviewEdgeSemantic {
    PrimaryBridge,
    ExternalBridge,
    ExternalSink,
}

/// 2D position and velocity for Verlet integration.
///
/// `prev_x/prev_y` encode velocity implicitly:
///   velocity = (pos - prev_pos) * damping
///   new_pos  = pos + velocity + acceleration
#[derive(Debug, Clone)]
pub struct NodePosition {
    pub x: f64,
    pub y: f64,
    pub prev_x: f64,
    pub prev_y: f64,
    /// Whether the node is pinned (for mouse drag)
    pub pinned: bool,
}

/// Barnes-Hut Quadtree for O(V log V) repulsion.
struct Quadtree {
    mass: f64,
    com_x: f64,
    com_y: f64,
    x: f64,
    y: f64,
    size: f64,
    children: Option<Box<[Quadtree; 4]>>,
    node_idx: Option<usize>,
    depth: usize,
}

const MAX_QUADTREE_DEPTH: usize = 20;

impl Quadtree {
    fn new(x: f64, y: f64, size: f64, depth: usize) -> Self {
        Self {
            mass: 0.0,
            com_x: 0.0,
            com_y: 0.0,
            x,
            y,
            size,
            children: None,
            node_idx: None,
            depth,
        }
    }

    fn insert(&mut self, idx: usize, px: f64, py: f64) {
        // If this node already has mass but no children, we need to split
        // or just add to the current node if we've reached max depth.
        if self.mass > 0.0 && self.children.is_none() {
            // Check depth to prevent infinite recursion if positions are identical
            if self.depth >= MAX_QUADTREE_DEPTH {
                // At max depth, just update center of mass/mass but don't split.
                // This essentially treats the nodes as a single mass at this point.
                let new_mass = self.mass + 1.0;
                self.com_x = (self.com_x * self.mass + px) / new_mass;
                self.com_y = (self.com_y * self.mass + py) / new_mass;
                self.mass = new_mass;
                return;
            }

            let half = self.size / 2.0;
            let d = self.depth + 1;
            let mut children = Box::new([
                Quadtree::new(self.x, self.y, half, d),
                Quadtree::new(self.x + half, self.y, half, d),
                Quadtree::new(self.x, self.y + half, half, d),
                Quadtree::new(self.x + half, self.y + half, half, d),
            ]);

            if let Some(old_idx) = self.node_idx.take() {
                let ox = self.com_x;
                let oy = self.com_y;
                let q = self.get_quadrant(ox, oy);
                children[q].insert(old_idx, ox, oy);
            }
            self.children = Some(children);
        }

        let q = self.get_quadrant(px, py);
        if let Some(children) = &mut self.children {
            children[q].insert(idx, px, py);
        } else {
            // First node in this leaf
            self.node_idx = Some(idx);
            self.com_x = px;
            self.com_y = py;
        }

        // Update center of mass
        let new_mass = self.mass + 1.0;
        self.com_x = (self.com_x * self.mass + px) / new_mass;
        self.com_y = (self.com_y * self.mass + py) / new_mass;
        self.mass = new_mass;
    }

    fn get_quadrant(&self, px: f64, py: f64) -> usize {
        let mid_x = self.x + self.size / 2.0;
        let mid_y = self.y + self.size / 2.0;
        match (px >= mid_x, py >= mid_y) {
            (false, false) => 0,
            (true, false) => 1,
            (false, true) => 2,
            (true, true) => 3,
        }
    }

    fn compute_repulsion(
        &self,
        idx: usize,
        pos: (f64, f64),
        theta: f64,
        repulsion_const: f64,
        force: &mut (f64, f64),
    ) {
        if self.mass == 0.0 || (self.node_idx == Some(idx)) {
            return;
        }

        let dx = self.com_x - pos.0;
        let dy = self.com_y - pos.1;
        let dist_sq = dx * dx + dy * dy;
        let dist = dist_sq.sqrt().max(0.5);

        // Barnes-Hut criterion: s / d < theta
        if self.children.is_none() || (self.size / dist < theta) {
            let f = (repulsion_const * self.mass) / dist_sq.max(1.0);
            force.0 -= f * (dx / dist);
            force.1 -= f * (dy / dist);
        } else if let Some(children) = &self.children {
            for child in children.iter() {
                child.compute_repulsion(idx, pos, theta, repulsion_const, force);
            }
        }
    }
}

/// Force-directed graph layout engine using Verlet integration.
pub struct GraphLayout {
    /// Node positions (index = graph order)
    pub positions: Vec<NodePosition>,
    /// Edge list: (from_index, to_index) pairs
    pub edges: Vec<(usize, usize)>,
    /// Edge weights: `weight[i]` corresponds to `edges[i]` (import count)
    pub edge_weights: Vec<u32>,
    /// Node labels (module names)
    pub labels: Vec<String>,
    /// Repulsion coefficient (Coulomb constant)
    pub repulsion: f64,
    /// Attraction coefficient (Hooke spring constant)
    pub attraction: f64,
    /// Velocity damping factor (0.0 = full stop, 1.0 = no damping)
    pub damping: f64,
    /// Dynamic ideal edge length based on node count and area
    pub ideal_length: f64,
    /// Drawing area width
    pub width: f64,
    /// Drawing area height
    pub height: f64,
    /// Simulation temperature (1.0 = hot/active, 0.0 = frozen).
    /// Scales jitter and force magnitude. Decays each step for natural settling.
    pub temperature: f64,
}

impl GraphLayout {
    /// Creates a new graph layout with circular initial placement.
    ///
    /// Nodes start on a circle around the center with small jitter
    /// and initial velocity for immediate visible motion.
    pub fn new(
        labels: Vec<String>,
        edges: Vec<(usize, usize)>,
        edge_weights: Vec<u32>,
        width: f64,
        height: f64,
    ) -> Self {
        let mut rng = rand::rng();
        let n = labels.len();

        // Place nodes in a circle with generous radius for spread
        let radius = width.min(height) * 0.40;
        let cx = width / 2.0;
        let cy = height / 2.0;

        let positions: Vec<NodePosition> = labels
            .iter()
            .enumerate()
            .map(|(i, _)| {
                // Distribute evenly on circle with angle jitter
                let angle = (i as f64 / n.max(1) as f64) * std::f64::consts::TAU
                    + rng.random_range(-0.15..0.15);
                let r = radius + rng.random_range(-5.0..5.0);
                let x = cx + angle.cos() * r;
                let y = cy + angle.sin() * r;
                // Small initial velocity for immediate motion
                NodePosition {
                    x,
                    y,
                    prev_x: x + rng.random_range(-1.5..1.5),
                    prev_y: y + rng.random_range(-1.5..1.5),
                    pinned: false,
                }
            })
            .collect();

        let ideal_length = compute_ideal_length(n, width, height);

        Self {
            positions,
            edges,
            edge_weights,
            labels,
            repulsion: 1500.0,
            attraction: 0.045,
            damping: 0.7, // 0.7 offers good balance between stiffness and fluid response
            ideal_length,
            width,
            height,
            temperature: 1.0,
        }
    }

    /// Advances one Verlet physics step.
    ///
    /// # Algorithm
    /// 1. Barnes-Hut repulsion using Quadtree (O(V log V))
    /// 2. Hooke spring attraction for every edge (O(E))
    /// 3. Center gravity pull (O(V))
    /// 4. Temperature-scaled micro-jitter (O(V))
    /// 5. Verlet integration with velocity/force clamping (O(V))
    /// 6. Bounds enforcement (O(V))
    /// 7. Temperature decay
    pub fn step(&mut self) {
        let n = self.positions.len();
        if n == 0 {
            return;
        }

        let mut fx = vec![0.0f64; n];
        let mut fy = vec![0.0f64; n];

        // 1. Barnes-Hut Repulsion: build quadtree then compute forces
        let q_size = self.width.max(self.height).max(1.0);
        let mut qt = Quadtree::new(0.0, 0.0, q_size, 0);
        for (i, pos) in self.positions.iter().enumerate() {
            qt.insert(i, pos.x, pos.y);
        }

        let theta = 0.7; // Barnes-Hut approximation threshold

        // ── DYNAMIC REPULSION ──
        // High node count (e.g. 400+) needs LESS repulsion to stay within bounds.
        // Base: 1500.0
        // N=100 -> 1500.0
        // N=400 -> ~700.0
        let dynamic_repulsion = if n > 100 {
            (self.repulsion * (100.0 / n as f64).sqrt()).max(400.0)
        } else {
            self.repulsion
        };
        let repulsion_const = dynamic_repulsion;

        for i in 0..n {
            let mut f = (0.0, 0.0);
            qt.compute_repulsion(
                i,
                (self.positions[i].x, self.positions[i].y),
                theta,
                repulsion_const,
                &mut f,
            );
            fx[i] += f.0;
            fy[i] += f.1;
        }

        // 2. Attraction (Hooke spring): connected nodes attract toward ideal length
        for &(from, to) in &self.edges {
            if from >= n || to >= n {
                continue;
            }
            let dx = self.positions[to].x - self.positions[from].x;
            let dy = self.positions[to].y - self.positions[from].y;
            let dist = (dx * dx + dy * dy).sqrt().max(0.5);

            let displacement = dist - self.ideal_length;
            let force = self.attraction * displacement;
            let ux = dx / dist;
            let uy = dy / dist;

            fx[from] += force * ux;
            fy[from] += force * uy;
            fx[to] -= force * ux;
            fy[to] -= force * uy;
        }

        // 3. Center gravity: pull toward canvas center
        let cx = self.width / 2.0;
        let cy = self.height / 2.0;

        // Scale gravity with node count: more nodes = stronger pull to center
        let gravity = if n > 200 { 0.08 } else { 0.05 };

        for i in 0..n {
            let dx = cx - self.positions[i].x;
            let dy = cy - self.positions[i].y;
            fx[i] += dx * gravity;
            fy[i] += dy * gravity;

            // 3b. Soft boundary force: push nodes away from edges more strongly
            // as they approach the margins.
            let margin_soft = 50.0;
            let push_strength = 0.25; // Increased from 0.15 to prevent wall-clumping
            if self.positions[i].x < margin_soft {
                fx[i] += (margin_soft - self.positions[i].x) * push_strength;
            } else if self.positions[i].x > self.width - margin_soft {
                fx[i] -= (self.positions[i].x - (self.width - margin_soft)) * push_strength;
            }
            if self.positions[i].y < margin_soft {
                fy[i] += (margin_soft - self.positions[i].y) * push_strength;
            } else if self.positions[i].y > self.height - margin_soft {
                fy[i] -= (self.positions[i].y - (self.height - margin_soft)) * push_strength;
            }
        }

        // 4. Temperature-scaled micro-jitter: alive feel that fades as graph settles
        // We only apply this jitter initially when graph is "hot" so dragging doesn't cause noise.
        let mut rng = rand::rng();
        let jitter = if self.temperature > 0.5 {
            0.5 * self.temperature
        } else {
            0.0
        };
        if jitter > 0.001 {
            for i in 0..n {
                fx[i] += rng.random_range(-jitter..jitter);
                fy[i] += rng.random_range(-jitter..jitter);
            }
        }

        // 5. Verlet integration with clamping
        let max_disp = 5.0;
        for i in 0..n {
            if self.positions[i].pinned {
                continue;
            }

            let vx = (self.positions[i].x - self.positions[i].prev_x) * self.damping;
            let vy = (self.positions[i].y - self.positions[i].prev_y) * self.damping;

            // Temperature acts as alpha multiplier (d3-force style).
            // It scales the forces uniformly so the target equilibrium never changes,
            // but the nodes eventually stop moving when cold.
            let mut fxi = fx[i] * self.temperature;
            let mut fyi = fy[i] * self.temperature;

            // Clamp velocity and force to prevent explosions
            let vx = vx.clamp(-max_disp, max_disp);
            let vy = vy.clamp(-max_disp, max_disp);
            fxi = fxi.clamp(-max_disp, max_disp);
            fyi = fyi.clamp(-max_disp, max_disp);

            let new_x = self.positions[i].x + vx + fxi;
            let new_y = self.positions[i].y + vy + fyi;

            self.positions[i].prev_x = self.positions[i].x;
            self.positions[i].prev_y = self.positions[i].y;
            self.positions[i].x = new_x;
            self.positions[i].y = new_y;
        }

        // 6. Bounds enforcement (zero velocity at wall to prevent sticking)
        let margin = 8.0;
        for pos in &mut self.positions {
            if pos.x < margin {
                pos.x = margin;
                pos.prev_x = margin;
            } else if pos.x > self.width - margin {
                pos.x = self.width - margin;
                pos.prev_x = self.width - margin;
            }
            if pos.y < margin {
                pos.y = margin;
                pos.prev_y = margin;
            } else if pos.y > self.height - margin {
                pos.y = self.height - margin;
                pos.prev_y = self.height - margin;
            }
        }

        // 7. Temperature decay — graph settles quickly then freezes.
        // Rate 0.997 per step: with 90 steps/sec (~30fps * 3 substeps),
        // temperature drops to ~7% after 10s, ~2% after 15s → physics freezes.
        self.temperature = (self.temperature * 0.997).max(0.001);
    }

    /// Runs multiple physics steps at once (for warmup or faster convergence).
    pub fn multi_step(&mut self, count: usize) {
        for _ in 0..count {
            self.step();
        }
    }

    /// Sets temperature to a high value, re-energizing the simulation.
    ///
    /// Call this when the user presses 'r' or when the graph changes
    /// to make nodes spread out and find a new equilibrium.
    pub fn reheat(&mut self) {
        self.temperature = 1.5;
    }

    /// Re-places all nodes on a circle at the current width/height.
    ///
    /// Call this after `resize()` but before warmup so the initial
    /// placement matches the actual canvas dimensions exactly.
    pub fn reinitialize_positions(&mut self) {
        let mut rng = rand::rng();
        let n = self.labels.len();
        let radius = self.width.min(self.height) * 0.35;
        let cx = self.width / 2.0;
        let cy = self.height / 2.0;

        self.positions = (0..n)
            .map(|i| {
                let angle = (i as f64 / n.max(1) as f64) * std::f64::consts::TAU
                    + rng.random_range(-0.15..0.15);
                let r = radius + rng.random_range(-5.0..5.0);
                let x = cx + angle.cos() * r;
                let y = cy + angle.sin() * r;
                NodePosition {
                    x,
                    y,
                    prev_x: x + rng.random_range(-1.5..1.5),
                    prev_y: y + rng.random_range(-1.5..1.5),
                    pinned: false,
                }
            })
            .collect();

        self.temperature = 1.0;
        self.ideal_length = compute_ideal_length(n, self.width, self.height);
    }

    /// Shifts all node positions so the centroid sits at the canvas center.
    ///
    /// Force-directed layouts can settle slightly off-center due to
    /// asymmetric forces. This post-warmup correction eliminates visible drift.
    pub fn center_layout(&mut self) {
        let n = self.positions.len();
        if n == 0 {
            return;
        }
        let avg_x: f64 = self.positions.iter().map(|p| p.x).sum::<f64>() / n as f64;
        let avg_y: f64 = self.positions.iter().map(|p| p.y).sum::<f64>() / n as f64;
        let dx = self.width / 2.0 - avg_x;
        let dy = self.height / 2.0 - avg_y;

        let margin = 8.0;
        for pos in &mut self.positions {
            pos.x = (pos.x + dx).clamp(margin, self.width - margin);
            pos.y = (pos.y + dy).clamp(margin, self.height - margin);
            pos.prev_x = (pos.prev_x + dx).clamp(margin, self.width - margin);
            pos.prev_y = (pos.prev_y + dy).clamp(margin, self.height - margin);
        }
    }

    /// Updates drawing area dimensions, rescaling positions proportionally.
    pub fn resize(&mut self, width: f64, height: f64) {
        if (self.width - width).abs() < 1.0 && (self.height - height).abs() < 1.0 {
            return;
        }
        // Skip if dimensions haven't meaningfully changed
        if (self.width - width).abs() < 0.5 && (self.height - height).abs() < 0.5 {
            return;
        }
        // Rescale existing positions to fit new dimensions
        if self.width > 0.0 && self.height > 0.0 {
            let sx = width / self.width;
            let sy = height / self.height;
            for pos in &mut self.positions {
                pos.x *= sx;
                pos.y *= sy;
                pos.prev_x *= sx;
                pos.prev_y *= sy;
            }
        }
        self.width = width;
        self.height = height;
        self.ideal_length = compute_ideal_length(self.labels.len(), width, height);
    }

    /// Updates the layout with a new graph snapshot.
    ///
    /// Preserves existing positions where possible (name matching).
    /// New nodes are placed at random positions near center.
    /// Reheats temperature to 0.8 so the new layout settles organically.
    pub fn update_graph(
        &mut self,
        labels: Vec<String>,
        edges: Vec<(usize, usize)>,
        edge_weights: Vec<u32>,
    ) {
        use std::collections::HashMap;

        // Save old positions by name
        let old_positions: HashMap<&str, &NodePosition> = self
            .labels
            .iter()
            .zip(self.positions.iter())
            .map(|(l, p)| (l.as_str(), p))
            .collect();

        let mut rng = rand::rng();
        let cx = self.width / 2.0;
        let cy = self.height / 2.0;

        // Create new positions, preserving known nodes
        let new_positions: Vec<NodePosition> = labels
            .iter()
            .map(|label| {
                if let Some(old) = old_positions.get(label.as_str()) {
                    NodePosition {
                        x: old.x,
                        y: old.y,
                        prev_x: old.prev_x,
                        prev_y: old.prev_y,
                        pinned: false,
                    }
                } else {
                    // New node: random position near center with initial velocity
                    let x = cx + rng.random_range(-30.0..30.0);
                    let y = cy + rng.random_range(-30.0..30.0);
                    NodePosition {
                        x,
                        y,
                        prev_x: x + rng.random_range(-1.0..1.0),
                        prev_y: y + rng.random_range(-1.0..1.0),
                        pinned: false,
                    }
                }
            })
            .collect();

        self.positions = new_positions;
        self.labels = labels;
        self.edges = edges;
        self.edge_weights = edge_weights;
        self.ideal_length = compute_ideal_length(self.labels.len(), self.width, self.height);
        // Warm reheat so the new graph spreads out
        self.temperature = 0.8;
    }
}

/// Computes ideal edge length based on node count and canvas area.
///
/// Uses the Fruchterman-Reingold heuristic: k = C * sqrt(area / n),
/// clamped to a reasonable range for the canvas dimensions.
fn compute_ideal_length(node_count: usize, width: f64, height: f64) -> f64 {
    if node_count <= 1 {
        return width.min(height) * 0.3;
    }
    let area = width * height;
    let k = 0.7 * (area / node_count as f64).sqrt();
    k.clamp(25.0, width.min(height) * 0.45)
}

/// Returns the node color based on drift score.
///
/// Catppuccin Mocha color theme:
/// - 0-30:  Green (#a6e3a1)
/// - 31-60: Yellow (#f9e2af)
/// - 61-80: Peach  (#fab387)
/// - 81+:   Red    (#f38ba8)
pub fn drift_color(drift_score: u8) -> Color {
    match drift_score {
        0..=30 => Color::Rgb(166, 227, 161),  // Catppuccin Green
        31..=60 => Color::Rgb(249, 226, 175), // Catppuccin Yellow
        61..=80 => Color::Rgb(250, 179, 135), // Catppuccin Peach
        _ => Color::Rgb(243, 139, 168),       // Catppuccin Red
    }
}

/// Returns an edge color scaled by weight (import count).
///
/// Uses warm-shift progression: dim → cool blue → warm orange → red
/// so heavy edges naturally draw attention.
pub fn weighted_edge_color(weight: u32) -> Color {
    match weight {
        1 => Color::Rgb(69, 71, 90), // Surface2 — barely visible (trivial dep)
        2..=3 => Color::Rgb(88, 91, 112), // Overlay0 — light coupling
        4..=7 => Color::Rgb(116, 199, 236), // Sapphire — normal coupling
        8..=15 => Color::Rgb(250, 179, 135), // Peach — heavy coupling (warm = attention)
        _ => Color::Rgb(243, 139, 168), // Red — critical (spaghetti)
    }
}

pub fn graph_relation_color(role: GraphRelationSemantic) -> Color {
    match role {
        GraphRelationSemantic::Neutral => Color::Rgb(166, 173, 200),
        GraphRelationSemantic::Focus | GraphRelationSemantic::CascadeSource => {
            Color::Rgb(255, 232, 115)
        }
        GraphRelationSemantic::Hover => Color::White,
        GraphRelationSemantic::Inbound => Color::Rgb(148, 226, 213),
        GraphRelationSemantic::Outbound => Color::Rgb(250, 179, 135),
        GraphRelationSemantic::Bidirectional => Color::Rgb(203, 166, 247),
        GraphRelationSemantic::Related => Color::Rgb(116, 150, 200),
        GraphRelationSemantic::SearchMatch => Color::Rgb(137, 220, 255),
        GraphRelationSemantic::CascadeDimmed => Color::Rgb(49, 50, 68),
    }
}

pub fn cluster_map_color(role: ClusterMapSemantic) -> Color {
    match role {
        ClusterMapSemantic::Hovered => graph_relation_color(GraphRelationSemantic::Focus),
        ClusterMapSemantic::Central => Color::Rgb(166, 227, 161),
        ClusterMapSemantic::ThirdParty => Color::Rgb(125, 173, 189),
        ClusterMapSemantic::Entrypoint => Color::Rgb(250, 179, 135),
        ClusterMapSemantic::Support => ACCENT_LAVENDER,
        ClusterMapSemantic::Neutral => FG_TEXT,
    }
}

pub fn overview_edge_color(role: OverviewEdgeSemantic) -> Color {
    match role {
        OverviewEdgeSemantic::PrimaryBridge => Color::Rgb(166, 227, 161),
        OverviewEdgeSemantic::ExternalBridge => Color::Rgb(245, 169, 127),
        OverviewEdgeSemantic::ExternalSink => Color::Rgb(108, 112, 136),
    }
}

pub fn palette_node_color(index: usize) -> Color {
    NODE_PALETTE[index % NODE_PALETTE.len()]
}

/// Returns a node color based on blast radius score (0.0–1.0).
///
/// Cool-to-hot gradient matching the Catppuccin theme:
///   - 0–10%:  Blue (low impact)
///   - 11–25%: Teal (moderate)
///   - 26–45%: Green (noticeable)
///   - 46–65%: Yellow (significant)
///   - 66–80%: Peach (high)
///   - 81%+:   Red (critical blast radius)
pub fn blast_color(score: f64) -> Color {
    match (score * 100.0) as u32 {
        0..=10 => Color::Rgb(137, 180, 250),  // Blue — low impact
        11..=25 => Color::Rgb(148, 226, 213), // Teal — moderate
        26..=45 => Color::Rgb(166, 227, 161), // Green — noticeable
        46..=65 => Color::Rgb(249, 226, 175), // Yellow — significant
        66..=80 => Color::Rgb(250, 179, 135), // Peach — high
        _ => Color::Rgb(243, 139, 168),       // Red — critical
    }
}

/// Returns a cascade-affected node color based on hop distance from the source.
///
/// Closer = hotter (red), farther = cooler (blue).
pub fn cascade_distance_color(distance: u32) -> Color {
    match distance {
        1 => Color::Rgb(243, 139, 168),     // Red — direct dependent
        2 => Color::Rgb(250, 179, 135),     // Peach
        3 => Color::Rgb(249, 226, 175),     // Yellow
        4..=5 => Color::Rgb(166, 227, 161), // Green
        _ => Color::Rgb(137, 180, 250),     // Blue — distant
    }
}

// =============================================================================
// Catppuccin Mocha color palette — used throughout the TUI
// =============================================================================

/// Catppuccin Mocha background color
pub const BG_BASE: Color = Color::Rgb(30, 30, 46);
/// Catppuccin Mocha text color
pub const FG_TEXT: Color = Color::Rgb(205, 214, 244);
/// Catppuccin Mocha surface color (panel backgrounds)
pub const BG_SURFACE: Color = Color::Rgb(36, 39, 58);
/// Catppuccin Mocha blue accent
pub const ACCENT_BLUE: Color = Color::Rgb(137, 180, 250);
/// Catppuccin Mocha lavender
pub const ACCENT_LAVENDER: Color = Color::Rgb(180, 190, 254);
/// Catppuccin Mocha mauve
pub const ACCENT_MAUVE: Color = Color::Rgb(203, 166, 247);
/// Catppuccin Mocha overlay — secondary text
pub const FG_OVERLAY: Color = Color::Rgb(108, 112, 134);

/// Catppuccin node color palette for individual node coloring
pub const NODE_PALETTE: [Color; 8] = [
    Color::Rgb(148, 226, 213), // Teal
    Color::Rgb(137, 180, 250), // Blue
    Color::Rgb(203, 166, 247), // Mauve
    Color::Rgb(166, 227, 161), // Green
    Color::Rgb(249, 226, 175), // Yellow
    Color::Rgb(250, 179, 135), // Peach
    Color::Rgb(243, 139, 168), // Pink
    Color::Rgb(180, 190, 254), // Lavender
];

// =============================================================================
// Tests
// =============================================================================
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_graph_layout_creation() {
        let labels = vec!["A".to_string(), "B".to_string(), "C".to_string()];
        let edges = vec![(0, 1), (1, 2)];
        let weights = vec![1, 2];
        let layout = GraphLayout::new(labels.clone(), edges, weights, 200.0, 100.0);

        assert_eq!(layout.positions.len(), 3, "Should have 3 node positions");
        assert_eq!(layout.labels.len(), 3);
        assert_eq!(layout.edges.len(), 2);
        assert_eq!(layout.edge_weights.len(), 2);
        assert!(layout.ideal_length > 0.0, "Ideal length should be positive");
        assert!(
            (layout.temperature - 1.0).abs() < 0.001,
            "Initial temperature should be 1.0"
        );
    }

    #[test]
    fn test_verlet_step_convergence() {
        let labels = vec!["A".to_string(), "B".to_string()];
        let edges = vec![(0, 1)];
        let weights = vec![1];
        let mut layout = GraphLayout::new(labels, edges, weights, 200.0, 100.0);

        let initial_ax = layout.positions[0].x;

        // Advance 100 steps — positions should change
        for _ in 0..100 {
            layout.step();
        }

        let final_ax = layout.positions[0].x;
        assert!(
            layout.positions[0].x >= 0.0 && layout.positions[0].x <= 200.0,
            "X should be within bounds"
        );
        assert!(
            layout.positions[0].y >= 0.0 && layout.positions[0].y <= 100.0,
            "Y should be within bounds"
        );

        let moved = (final_ax - initial_ax).abs() > 0.001;
        assert!(moved, "Nodes should move");
    }

    #[test]
    fn test_multi_step() {
        let labels = vec!["A".to_string(), "B".to_string()];
        let edges = vec![(0, 1)];
        let weights = vec![1];
        let mut layout = GraphLayout::new(labels, edges, weights, 200.0, 100.0);

        let initial_ax = layout.positions[0].x;
        layout.multi_step(50);

        let moved = (layout.positions[0].x - initial_ax).abs() > 0.001;
        assert!(moved, "Nodes should move after multi_step");
    }

    #[test]
    fn test_bounds_enforcement() {
        let labels = vec!["A".to_string()];
        let layout = GraphLayout::new(labels, vec![], vec![], 100.0, 50.0);

        let pos = &layout.positions[0];
        assert!(pos.x >= 0.0 && pos.x <= 100.0);
        assert!(pos.y >= 0.0 && pos.y <= 50.0);
    }

    #[test]
    fn test_drift_color_ranges() {
        assert_eq!(drift_color(0), Color::Rgb(166, 227, 161));
        assert_eq!(drift_color(30), Color::Rgb(166, 227, 161));
        assert_eq!(drift_color(31), Color::Rgb(249, 226, 175));
        assert_eq!(drift_color(60), Color::Rgb(249, 226, 175));
        assert_eq!(drift_color(61), Color::Rgb(250, 179, 135));
        assert_eq!(drift_color(81), Color::Rgb(243, 139, 168));
        assert_eq!(drift_color(100), Color::Rgb(243, 139, 168));
    }

    #[test]
    fn test_graph_relation_semantics_are_distinct() {
        assert_eq!(
            graph_relation_color(GraphRelationSemantic::Hover),
            Color::White
        );
        assert_ne!(
            graph_relation_color(GraphRelationSemantic::Neutral),
            graph_relation_color(GraphRelationSemantic::Focus)
        );
        assert_ne!(
            graph_relation_color(GraphRelationSemantic::SearchMatch),
            graph_relation_color(GraphRelationSemantic::Related)
        );
    }

    #[test]
    fn test_cluster_and_edge_semantics_are_stable() {
        assert_ne!(
            cluster_map_color(ClusterMapSemantic::ThirdParty),
            cluster_map_color(ClusterMapSemantic::Central)
        );
        assert_ne!(
            overview_edge_color(OverviewEdgeSemantic::PrimaryBridge),
            overview_edge_color(OverviewEdgeSemantic::ExternalSink)
        );
    }

    #[test]
    fn test_empty_graph_step() {
        let mut layout = GraphLayout::new(vec![], vec![], vec![], 100.0, 100.0);
        layout.step(); // Should not crash on empty graph
        assert_eq!(layout.positions.len(), 0);
    }

    #[test]
    fn test_update_graph_preserves_positions() {
        let labels = vec!["A".to_string(), "B".to_string()];
        let edges = vec![(0, 1)];
        let weights = vec![1];
        let mut layout = GraphLayout::new(labels, edges, weights, 200.0, 100.0);

        // Advance a few steps
        for _ in 0..10 {
            layout.step();
        }
        let a_pos = layout.positions[0].x;

        // Update graph — A still exists, C is new
        let new_labels = vec!["A".to_string(), "C".to_string()];
        let new_edges = vec![(0, 1)];
        let new_weights = vec![1];
        layout.update_graph(new_labels, new_edges, new_weights);

        assert_eq!(layout.positions.len(), 2);
        // A's position should be preserved
        assert!(
            (layout.positions[0].x - a_pos).abs() < 0.01,
            "A position should be preserved"
        );
    }

    #[test]
    fn test_compute_ideal_length() {
        let k = compute_ideal_length(3, 100.0, 100.0);
        assert!(k > 15.0, "Ideal length should be reasonable: {k}");
        assert!(k < 50.0, "Ideal length should not be too large: {k}");

        let k1 = compute_ideal_length(1, 100.0, 100.0);
        assert!(k1 > 0.0, "Single node should have positive ideal length");
    }

    #[test]
    fn test_resize_rescales() {
        let labels = vec!["A".to_string(), "B".to_string()];
        let mut layout = GraphLayout::new(labels, vec![], vec![], 100.0, 100.0);

        // Set a known position
        layout.positions[0].x = 50.0;
        layout.positions[0].y = 50.0;
        layout.positions[0].prev_x = 50.0;
        layout.positions[0].prev_y = 50.0;

        layout.resize(200.0, 100.0);
        assert!(
            (layout.positions[0].x - 100.0).abs() < 0.01,
            "X should double when width doubles"
        );
        assert!(
            (layout.positions[0].y - 50.0).abs() < 0.01,
            "Y should stay same when height unchanged"
        );
    }

    #[test]
    fn test_temperature_decay() {
        let labels = vec!["A".to_string(), "B".to_string()];
        let mut layout = GraphLayout::new(labels, vec![(0, 1)], vec![1], 200.0, 100.0);

        let initial_temp = layout.temperature;
        layout.multi_step(100);

        assert!(
            layout.temperature < initial_temp,
            "Temperature should decay over time"
        );
        assert!(
            layout.temperature >= 0.01,
            "Temperature should not drop below minimum"
        );
    }

    #[test]
    fn test_reheat() {
        let labels = vec!["A".to_string(), "B".to_string()];
        let mut layout = GraphLayout::new(labels, vec![(0, 1)], vec![1], 200.0, 100.0);

        // Cool down
        layout.multi_step(200);
        let cold_temp = layout.temperature;

        // Reheat
        layout.reheat();
        assert!(
            layout.temperature > cold_temp,
            "Temperature should increase after reheat"
        );
        assert!(
            (layout.temperature - 1.5).abs() < 0.001,
            "Reheat should set temperature to 1.5"
        );
    }
}