gitstack 5.3.0

Git history viewer with insights - Author stats, file heatmap, code ownership
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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
//! Graph construction logic

use std::collections::{HashMap, HashSet};

use super::cell::GraphCell;
use super::colors::{ColorContext, PenaltyBasedColorAssigner};
use super::layout::{GraphLayout, GraphRow};
use crate::event::{GitEvent, GitEventKind};

/// Column tracking manager
struct ColumnTracker {
    /// Commit hash being tracked by each column (None means empty column)
    columns: Vec<Option<String>>,
    /// Hash -> color index mapping
    hash_colors: HashMap<String, usize>,
    /// Column -> color index mapping
    column_colors: HashMap<usize, usize>,
    /// Color assignment manager (penalty-based)
    color_assigner: PenaltyBasedColorAssigner,
    /// Commit hash -> fork point hash (for fork point detection)
    fork_points: HashMap<String, String>,
}

impl ColumnTracker {
    fn new() -> Self {
        Self {
            columns: Vec::new(),
            hash_colors: HashMap::new(),
            column_colors: HashMap::new(),
            color_assigner: PenaltyBasedColorAssigner::new(),
            fork_points: HashMap::new(),
        }
    }

    /// Find the column tracking the specified hash
    fn find_column(&self, hash: &str) -> Option<usize> {
        self.columns
            .iter()
            .position(|h| h.as_ref().is_some_and(|h| h == hash))
    }

    /// Find an empty column or create a new one
    fn find_or_create_column(&mut self) -> usize {
        if let Some(pos) = self.columns.iter().position(|h| h.is_none()) {
            pos
        } else {
            self.columns.push(None);
            self.columns.len() - 1
        }
    }

    /// Release a column
    fn release_column(&mut self, col: usize) {
        if col < self.columns.len() {
            self.columns[col] = None;
            self.column_colors.remove(&col);
            self.color_assigner.release_lane(col);
        }
    }

    /// Set a hash to a column
    fn set_column(&mut self, col: usize, hash: String, color_idx: usize) {
        while self.columns.len() <= col {
            self.columns.push(None);
        }
        self.columns[col] = Some(hash.clone());
        self.hash_colors.insert(hash, color_idx);
        self.column_colors.insert(col, color_idx);
    }

    /// Get the color of a column
    fn get_column_color(&self, col: usize) -> Option<usize> {
        self.column_colors.get(&col).copied()
    }

    /// Get the color of a hash
    fn get_hash_color(&self, hash: &str) -> Option<usize> {
        self.hash_colors.get(hash).copied()
    }

    /// Assign main branch color
    fn assign_main_color(&mut self, col: usize) -> usize {
        let ctx = ColorContext::new(col).with_main_branch(true);
        self.color_assigner.assign_with_context(&ctx)
    }

    /// Assign color considering context
    fn assign_color_with_context(
        &mut self,
        col: usize,
        fork_point: Option<String>,
        parent_color: Option<usize>,
    ) -> usize {
        let ctx = ColorContext::new(col)
            .with_fork_point(fork_point)
            .with_parent_color(parent_color);
        self.color_assigner.assign_with_context(&ctx)
    }

    /// Record a fork point
    fn set_fork_point(&mut self, hash: &str, fork_point: &str) {
        self.fork_points
            .insert(hash.to_string(), fork_point.to_string());
    }

    /// Get the fork point
    fn get_fork_point(&self, hash: &str) -> Option<String> {
        self.fork_points.get(hash).cloned()
    }

    /// Maximum index of active columns
    fn max_active_column(&self) -> usize {
        self.columns
            .iter()
            .enumerate()
            .filter(|(_, h)| h.is_some())
            .map(|(i, _)| i)
            .max()
            .unwrap_or(0)
    }
}

/// Build the graph
pub fn build_graph(events: &[GitEvent], head_hash: Option<&str>) -> GraphLayout {
    if events.is_empty() {
        return GraphLayout::empty();
    }

    let mut tracker = ColumnTracker::new();
    let mut rows: Vec<GraphRow> = Vec::new();
    let mut max_column: usize = 0;

    // Hash -> row index mapping
    let hash_to_idx: HashMap<&str, usize> = events
        .iter()
        .enumerate()
        .map(|(i, e)| (e.short_hash.as_str(), i))
        .collect();

    // Hashes of already displayed commits
    let mut shown_commits: HashSet<String> = HashSet::new();

    for (idx, event) in events.iter().enumerate() {
        // Fork point detection: when multiple columns are tracking the same commit,
        // insert a connector row to visualize the convergence
        let converging_columns: Vec<usize> = tracker
            .columns
            .iter()
            .enumerate()
            .filter(|(_, h)| h.as_ref().is_some_and(|h| h == &event.short_hash))
            .map(|(i, _)| i)
            .collect();

        if converging_columns.len() >= 2 {
            // Multiple columns converging: insert a connector row
            // SAFETY: converging_columns.len() >= 2 is guaranteed by the preceding if condition
            let main_col = *converging_columns
                .iter()
                .min()
                .expect("converging_columns is non-empty (len >= 2)");
            let merging_cols: Vec<usize> = converging_columns
                .iter()
                .filter(|&&c| c != main_col)
                .copied()
                .collect();

            // Update maximum column count
            for &col in &merging_cols {
                max_column = max_column.max(col);
            }
            max_column = max_column.max(main_col);

            // Build cells for the connector row
            let connector_cells = build_connector_cells(
                main_col,
                &merging_cols,
                &tracker.columns,
                &tracker.column_colors,
                max_column,
            );

            // Add connector row (no commit information)
            let main_color = tracker.get_column_color(main_col).unwrap_or(0);
            rows.push(GraphRow::new(None, main_col, main_color, connector_cells));

            // Release converged columns (except the main column)
            for col in merging_cols {
                tracker.release_column(col);
            }
        }

        // Find the column tracking this commit
        let commit_col = tracker
            .find_column(&event.short_hash)
            .unwrap_or_else(|| tracker.find_or_create_column());

        // Detect fork point (set if first parent exists)
        if let Some(first_parent) = event.parent_hashes.first() {
            tracker.set_fork_point(&event.short_hash, first_parent);
        }

        // Determine color
        let commit_color = if idx == 0 {
            // First commit (main branch)
            let color = tracker.assign_main_color(commit_col);
            tracker.set_column(commit_col, event.short_hash.clone(), color);
            color
        } else if let Some(color) = tracker.get_column_color(commit_col) {
            // Continue with the existing column's color
            color
        } else {
            // Assign a new color (considering fork point)
            let fork_point = tracker.get_fork_point(&event.short_hash);
            let parent_color = if let Some(first_parent) = event.parent_hashes.first() {
                tracker.get_hash_color(first_parent)
            } else {
                None
            };
            let color = tracker.assign_color_with_context(commit_col, fork_point, parent_color);
            tracker.set_column(commit_col, event.short_hash.clone(), color);
            color
        };

        // Clear this column (commit processing complete)
        if commit_col < tracker.columns.len() {
            tracker.columns[commit_col] = None;
        }

        // Process parent commits
        // (column, color, is being tracked, already shown)
        let mut parent_info: Vec<(usize, usize, bool, bool)> = Vec::new();

        for (parent_idx, parent_hash) in event.parent_hashes.iter().enumerate() {
            // Check if the parent is within the display range
            let in_display_range = hash_to_idx.contains_key(parent_hash.as_str());

            if !in_display_range {
                // Even if parent is outside display range, continue tracking the first parent in the same column (to maintain vertical line)
                if parent_idx == 0 {
                    tracker.set_column(commit_col, parent_hash.clone(), commit_color);
                }
                continue;
            }

            // Find the column tracking the parent
            let existing_col = tracker.find_column(parent_hash);

            // Whether the parent has already been displayed
            let already_shown = shown_commits.contains(parent_hash);

            let (parent_col, parent_color, is_existing) = if let Some(col) = existing_col {
                // An existing column is tracking the parent
                let color = tracker
                    .get_column_color(col)
                    .or_else(|| tracker.get_hash_color(parent_hash))
                    .unwrap_or(col);

                if parent_idx == 0 && col != commit_col {
                    // First parent is being tracked in a different column (branch commit)
                    // -> Start tracking in the current column too (for fork point detection)
                    tracker.set_column(commit_col, parent_hash.clone(), commit_color);
                    // -> Do not draw a horizontal line (return commit_col)
                    //    Fork points are visualized by connector rows
                    (commit_col, commit_color, true)
                } else {
                    // Second parent onwards (merge source), or same column
                    // -> Draw a horizontal line
                    (col, color, true)
                }
            } else if parent_idx == 0 {
                // First parent: continue in the same column
                tracker.set_column(commit_col, parent_hash.clone(), commit_color);
                (commit_col, commit_color, false)
            } else {
                // Second parent onwards: new column (considering fork point)
                let new_col = tracker.find_or_create_column();
                // Record the current commit as the fork point for second parent onwards
                let fork_point = Some(event.short_hash.clone());
                let new_color = tracker.assign_color_with_context(new_col, fork_point, None);
                tracker.set_column(new_col, parent_hash.clone(), new_color);
                (new_col, new_color, false)
            };

            parent_info.push((parent_col, parent_color, is_existing, already_shown));
        }

        // Update maximum column count
        max_column = max_column.max(commit_col).max(tracker.max_active_column());

        // Build cell array
        let cells = build_cells(
            commit_col,
            commit_color,
            &parent_info,
            &tracker.columns,
            &tracker.column_colors,
            max_column,
            event.kind == GitEventKind::Merge,
            head_hash == Some(&event.short_hash),
        );

        // Add row
        let is_head = head_hash == Some(&event.short_hash);
        let row =
            GraphRow::new(Some(event.clone()), commit_col, commit_color, cells).with_head(is_head);
        rows.push(row);

        // Mark this commit as displayed
        shown_commits.insert(event.short_hash.clone());

        // Note: columns are not released here
        // Columns are naturally recycled (cleared during commit processing -> reused by find_or_create_column)
        // Early column release causes a bug where vertical lines disappear when consecutive merges occur
    }

    GraphLayout { rows, max_column }
}

/// Build cell array for a single row
#[allow(clippy::too_many_arguments)]
fn build_cells(
    commit_col: usize,
    commit_color: usize,
    parent_info: &[(usize, usize, bool, bool)], // (column, color, is being tracked, already shown)
    active_columns: &[Option<String>],
    column_colors: &HashMap<usize, usize>,
    max_col: usize,
    is_merge: bool,
    is_head: bool,
) -> Vec<GraphCell> {
    // Cell count: 2 characters per column (one for node and one for spacing)
    let cell_count = (max_col + 1) * 2;
    let mut cells = vec![GraphCell::Empty; cell_count];

    // 1. Draw vertical lines on active columns
    for (col, hash) in active_columns.iter().enumerate() {
        if hash.is_some() && col != commit_col {
            let cell_idx = col * 2;
            if cell_idx < cells.len() {
                // Use the column's color
                let color_idx = column_colors.get(&col).copied().unwrap_or(col % 8);
                cells[cell_idx] = GraphCell::Vertical { color_idx };
            }
        }
    }

    // 2. Draw node at the commit position
    let commit_cell_idx = commit_col * 2;
    if commit_cell_idx < cells.len() {
        cells[commit_cell_idx] = if is_head {
            GraphCell::HeadNode {
                color_idx: commit_color,
            }
        } else if is_merge {
            GraphCell::MergeNode {
                color_idx: commit_color,
            }
        } else {
            GraphCell::Node {
                color_idx: commit_color,
            }
        };
    }

    // 3. Draw connection lines to parents
    for &(parent_col, parent_color, is_existing, already_shown) in parent_info {
        if parent_col == commit_col {
            // Same column: no connection line needed (drawn as vertical line in the next row)
            continue;
        }

        if parent_col > commit_col {
            // Connection to the right
            draw_horizontal_connection(
                &mut cells,
                commit_col,
                parent_col,
                parent_color,
                is_existing,
                already_shown,
                true, // Rightward
            );
        } else {
            // Connection to the left
            draw_horizontal_connection(
                &mut cells,
                parent_col,
                commit_col,
                parent_color,
                is_existing,
                already_shown,
                false, // Leftward
            );
        }
    }

    cells
}

/// Draw horizontal connection lines
fn draw_horizontal_connection(
    cells: &mut [GraphCell],
    left_col: usize,
    right_col: usize,
    color_idx: usize,
    is_existing: bool,
    already_shown: bool,
    is_right_direction: bool, // Whether direction is rightward from the commit
) {
    let start_idx = left_col * 2 + 1;
    let end_idx = right_col * 2;

    // Draw horizontal lines
    for idx in start_idx..end_idx {
        if idx < cells.len() {
            match cells[idx] {
                GraphCell::Vertical { color_idx: v_color } => {
                    // Crossing with vertical line
                    cells[idx] = GraphCell::Cross {
                        h_color: color_idx,
                        v_color,
                    };
                }
                GraphCell::Empty => {
                    cells[idx] = GraphCell::Horizontal { color_idx };
                }
                _ => {}
            }
        }
    }

    // Determine endpoint symbols
    // Based on keifu's logic:
    // - is_existing && already_shown: parent already displayed -> merge end (╯/╰)
    // - is_existing && !already_shown: parent not yet displayed -> tee connection (┤/├)
    // - !is_existing: new branch start -> curve (╮/╭)
    if is_right_direction {
        // Right endpoint symbol
        if end_idx < cells.len() {
            cells[end_idx] = if is_existing && already_shown {
                GraphCell::CurveDownLeft { color_idx } // ╯ merge end
            } else if is_existing {
                GraphCell::TeeLeft { color_idx } // ┤ tee connection (continues below)
            } else {
                GraphCell::CurveUpLeft { color_idx } // ╮ new branch start
            };
        }
    } else {
        // Left endpoint symbol
        let left_idx = left_col * 2;
        if left_idx < cells.len() {
            cells[left_idx] = if is_existing && already_shown {
                GraphCell::CurveDownRight { color_idx } // ╰ merge end
            } else if is_existing {
                GraphCell::TeeRight { color_idx } // ├ tee connection (continues below)
            } else {
                GraphCell::CurveUpRight { color_idx } // ╭ new branch start
            };
        }
    }
}

/// Build cells for fork point connector rows
/// Visualization when multiple columns converge to the same commit
/// Example: ├─┴─╯ (tee from main column, intermediate ┴, rightmost ╯)
fn build_connector_cells(
    main_col: usize,
    merging_cols: &[usize],
    active_columns: &[Option<String>],
    column_colors: &HashMap<usize, usize>,
    max_col: usize,
) -> Vec<GraphCell> {
    let cell_count = (max_col + 1) * 2;
    let mut cells = vec![GraphCell::Empty; cell_count];

    // Sort merging columns (process left to right)
    let mut sorted_merging: Vec<usize> = merging_cols.to_vec();
    sorted_merging.sort();

    // Rightmost merging column
    let rightmost_col = sorted_merging.last().copied().unwrap_or(main_col);

    // 1. Draw vertical lines on active columns (except main and merging columns)
    for (col, hash) in active_columns.iter().enumerate() {
        if hash.is_some() && col != main_col && !sorted_merging.contains(&col) {
            let cell_idx = col * 2;
            if cell_idx < cells.len() {
                let color_idx = column_colors.get(&col).copied().unwrap_or(col % 8);
                cells[cell_idx] = GraphCell::Vertical { color_idx };
            }
        }
    }

    // 2. Draw tee-right (├) on the main column
    let main_color = column_colors.get(&main_col).copied().unwrap_or(0);
    let main_cell_idx = main_col * 2;
    if main_cell_idx < cells.len() {
        cells[main_cell_idx] = GraphCell::TeeRight {
            color_idx: main_color,
        };
    }

    // 3. Draw horizontal lines from main column to each merging column
    for &merge_col in &sorted_merging {
        let merge_color = column_colors
            .get(&merge_col)
            .copied()
            .unwrap_or(merge_col % 8);

        // Horizontal line from main column to merging column
        let start_idx = main_col * 2 + 1;
        let end_idx = merge_col * 2;

        for idx in start_idx..end_idx {
            if idx < cells.len() {
                match cells[idx] {
                    GraphCell::Vertical { color_idx: v_color } => {
                        // Crossing with vertical line
                        cells[idx] = GraphCell::Cross {
                            h_color: merge_color,
                            v_color,
                        };
                    }
                    GraphCell::Empty => {
                        cells[idx] = GraphCell::Horizontal {
                            color_idx: merge_color,
                        };
                    }
                    GraphCell::Horizontal { .. } => {
                        // Keep existing horizontal line as-is
                    }
                    _ => {}
                }
            }
        }

        // Endpoint symbol for merging column
        if end_idx < cells.len() {
            if merge_col == rightmost_col {
                // Rightmost column: ╯ (merge end)
                cells[end_idx] = GraphCell::CurveDownLeft {
                    color_idx: merge_color,
                };
            } else {
                // Intermediate column: ┴ (tee-up, continues rightward)
                cells[end_idx] = GraphCell::TeeUp {
                    color_idx: merge_color,
                };
            }
        }
    }

    cells
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Local;

    fn create_event(hash: &str, parents: Vec<&str>) -> GitEvent {
        let mut event = GitEvent::commit(
            hash.to_string(),
            format!("commit {}", hash),
            "author".to_string(),
            Local::now(),
            0,
            0,
        );
        event.parent_hashes = parents.into_iter().map(|s| s.to_string()).collect();
        event
    }

    #[test]
    fn test_build_graph_empty() {
        let layout = build_graph(&[], None);
        assert!(layout.is_empty());
    }

    #[test]
    fn test_build_graph_single_commit() {
        let events = vec![create_event("abc1234", vec![])];
        let layout = build_graph(&events, None);
        assert_eq!(layout.len(), 1);
        assert_eq!(layout.rows[0].column, 0);
    }

    #[test]
    fn test_build_graph_linear_history() {
        let events = vec![
            create_event("commit3", vec!["commit2"]),
            create_event("commit2", vec!["commit1"]),
            create_event("commit1", vec![]),
        ];
        let layout = build_graph(&events, None);
        assert_eq!(layout.len(), 3);
        // All in the same column
        assert_eq!(layout.rows[0].column, 0);
        assert_eq!(layout.rows[1].column, 0);
        assert_eq!(layout.rows[2].column, 0);
    }

    #[test]
    fn test_build_graph_with_merge() {
        // Create a merge commit (with 2 parents)
        let mut merge_event = create_event("merge", vec!["main2", "feat1"]);
        merge_event.kind = GitEventKind::Merge;

        let events = vec![
            merge_event,
            create_event("feat1", vec!["main1"]),
            create_event("main2", vec!["main1"]),
            create_event("main1", vec![]),
        ];
        let layout = build_graph(&events, None);
        // 4 event rows (connector rows may also be added)
        let event_rows: Vec<_> = layout.rows.iter().filter(|r| r.event.is_some()).collect();
        assert_eq!(event_rows.len(), 4);
        // Merge commit should have MergeNode in its cells
        assert!(event_rows[0]
            .cells
            .iter()
            .any(|c| matches!(c, GraphCell::MergeNode { .. })));
    }

    #[test]
    fn test_build_graph_head_marker() {
        let events = vec![create_event("abc1234", vec![])];
        let layout = build_graph(&events, Some("abc1234"));
        assert!(layout.rows[0].is_head);
        assert!(layout.rows[0]
            .cells
            .iter()
            .any(|c| matches!(c, GraphCell::HeadNode { .. })));
    }

    #[test]
    fn test_column_tracker_find_or_create() {
        let mut tracker = ColumnTracker::new();
        let col1 = tracker.find_or_create_column();
        tracker.set_column(col1, "hash1".to_string(), 0);
        let col2 = tracker.find_or_create_column();
        assert_ne!(col1, col2);
    }

    #[test]
    fn test_column_tracker_release() {
        let mut tracker = ColumnTracker::new();
        let col = tracker.find_or_create_column();
        tracker.set_column(col, "hash1".to_string(), 0);
        tracker.release_column(col);
        assert!(tracker.find_column("hash1").is_none());
    }

    /// Test for parallel branches
    ///
    /// Commit history:
    /// ```
    /// merge ─┬─ main2 ─┬─ base
    ///        └─ feat1 ─┘
    /// ```
    #[test]
    fn test_parallel_branches() {
        let mut merge_event = create_event("merge", vec!["main2", "feat1"]);
        merge_event.kind = GitEventKind::Merge;

        let events = vec![
            merge_event,
            create_event("main2", vec!["base"]),
            create_event("feat1", vec!["base"]),
            create_event("base", vec![]),
        ];
        let layout = build_graph(&events, None);
        // 4 event rows (connector rows may also be added)
        let event_rows: Vec<_> = layout.rows.iter().filter(|r| r.event.is_some()).collect();
        assert_eq!(event_rows.len(), 4);

        // main2 and feat1 should be placed in different columns
        let main2_row = event_rows
            .iter()
            .find(|r| r.event.as_ref().is_some_and(|e| e.short_hash == "main2"))
            .unwrap();
        let feat1_row = event_rows
            .iter()
            .find(|r| r.event.as_ref().is_some_and(|e| e.short_hash == "feat1"))
            .unwrap();
        assert_ne!(main2_row.column, feat1_row.column);
    }

    /// Test for fork points (multiple branches diverge from the same commit)
    ///
    /// Commit history:
    /// ```
    /// feat2 ─┐
    /// feat1 ─┼─ base
    /// main  ─┘
    /// ```
    #[test]
    fn test_fork_point() {
        let events = vec![
            create_event("feat2", vec!["base"]),
            create_event("feat1", vec!["base"]),
            create_event("main", vec!["base"]),
            create_event("base", vec![]),
        ];
        let layout = build_graph(&events, None);
        // 4 event rows (connector rows may also be added)
        let event_rows: Vec<_> = layout.rows.iter().filter(|r| r.event.is_some()).collect();
        assert_eq!(event_rows.len(), 4);

        // Commits sharing base as parent are placed in different columns or consolidated into base
        // base should be placed in column 0
        let base_row = event_rows
            .iter()
            .find(|r| r.event.as_ref().is_some_and(|e| e.short_hash == "base"))
            .unwrap();
        assert_eq!(base_row.column, 0);
    }

    /// Test for uniqueness of color assignment
    #[test]
    fn test_color_assignment_unique() {
        let mut merge_event = create_event("merge", vec!["main2", "feat1"]);
        merge_event.kind = GitEventKind::Merge;

        let events = vec![
            merge_event,
            create_event("main2", vec!["base"]),
            create_event("feat1", vec!["base"]),
            create_event("base", vec![]),
        ];
        let layout = build_graph(&events, None);

        // Extract only event rows
        let event_rows: Vec<_> = layout.rows.iter().filter(|r| r.event.is_some()).collect();

        // Get event rows for main2 and feat1
        let main2_row = event_rows
            .iter()
            .find(|r| r.event.as_ref().is_some_and(|e| e.short_hash == "main2"))
            .unwrap();
        let feat1_row = event_rows
            .iter()
            .find(|r| r.event.as_ref().is_some_and(|e| e.short_hash == "feat1"))
            .unwrap();

        // Commits in different columns should have different colors
        // feat1 is placed in a new column, so a different color should be assigned
        if main2_row.column != feat1_row.column {
            assert_ne!(main2_row.color_idx, feat1_row.color_idx);
        }
    }

    /// Test for long merge chains
    #[test]
    fn test_long_merge_chain() {
        let mut merge1 = create_event("merge1", vec!["main3", "feat1"]);
        merge1.kind = GitEventKind::Merge;

        let events = vec![
            merge1,
            create_event("main3", vec!["main2"]),
            create_event("feat1", vec!["main1"]),
            create_event("main2", vec!["main1"]),
            create_event("main1", vec![]),
        ];
        let layout = build_graph(&events, Some("merge1"));
        // 5 event rows (connector rows may also be added)
        let event_rows: Vec<_> = layout.rows.iter().filter(|r| r.event.is_some()).collect();
        assert_eq!(event_rows.len(), 5);

        // Merge commit (first event row) should have HeadNode
        assert!(event_rows[0]
            .cells
            .iter()
            .any(|c| matches!(c, GraphCell::HeadNode { .. })));
    }

    /// Test for horizontal connections
    #[test]
    fn test_horizontal_connection() {
        let mut merge_event = create_event("merge", vec!["main", "feat"]);
        merge_event.kind = GitEventKind::Merge;

        let events = vec![
            merge_event,
            create_event("main", vec!["base"]),
            create_event("feat", vec!["base"]),
            create_event("base", vec![]),
        ];
        let layout = build_graph(&events, None);

        // Merge commit should contain horizontal lines (Horizontal) or curves (Curve)
        let has_connection = layout.rows[0].cells.iter().any(|c| {
            matches!(
                c,
                GraphCell::Horizontal { .. }
                    | GraphCell::CurveUpRight { .. }
                    | GraphCell::CurveUpLeft { .. }
                    | GraphCell::CurveDownRight { .. }
                    | GraphCell::CurveDownLeft { .. }
            )
        });
        assert!(has_connection);
    }

    /// Test for fork point connector rows
    /// When multiple branches diverge from the same commit, connector rows are inserted
    ///
    /// Commit history:
    /// ```
    /// feat2 ─┐
    /// feat1 ─┼─ base
    /// ```
    #[test]
    fn test_convergence_connector_row() {
        // feat1 and feat2 diverge from the same base
        let events = vec![
            create_event("feat2", vec!["base"]),
            create_event("feat1", vec!["base"]),
            create_event("base", vec![]),
        ];
        let layout = build_graph(&events, None);

        // 4 rows: feat2, feat1, connector row, base
        // Row count becomes 4 when a connector row is inserted
        assert_eq!(
            layout.len(),
            4,
            "Expected 4 rows (feat2, feat1, connector, base)"
        );

        // Connector rows should contain TeeRight
        let connector_row = layout.rows.iter().find(|row| row.event.is_none());
        assert!(
            connector_row.is_some(),
            "Expected a connector row (event=None)"
        );

        let connector_row = connector_row.unwrap();
        let has_tee_right = connector_row
            .cells
            .iter()
            .any(|c| matches!(c, GraphCell::TeeRight { .. }));
        assert!(has_tee_right, "Connector row should have TeeRight symbol");

        // The base row must always exist
        let has_base = layout
            .rows
            .iter()
            .any(|row| row.event.as_ref().is_some_and(|e| e.short_hash == "base"));
        assert!(has_base);
    }

    /// Strictly verify the cell layout of connector rows
    /// Connector rows follow the format of TeeRight on the main column, horizontal lines, and CurveDownLeft on the right end
    #[test]
    fn test_connector_row_cell_layout() {
        let events = vec![
            create_event("feat2", vec!["base"]),
            create_event("feat1", vec!["base"]),
            create_event("base", vec![]),
        ];
        let layout = build_graph(&events, None);

        // Get the connector row
        let connector_row = layout
            .rows
            .iter()
            .find(|row| row.event.is_none())
            .expect("Connector row should exist");

        // Convert cell array to string and verify
        let cells_str: String = connector_row.cells.iter().map(|c| c.to_char()).collect();

        // Contains TeeRight
        assert!(
            cells_str.contains(''),
            "Connector row should contain TeeRight (├): got '{}'",
            cells_str
        );

        // Contains CurveDownLeft (rightmost merging column)
        assert!(
            cells_str.contains(''),
            "Connector row should contain CurveDownLeft (╯): got '{}'",
            cells_str
        );
    }

    /// Strictly verify horizontal line connections for merge commits
    /// Merge commits contain horizontal lines to the second parent and curves (CurveUpLeft)
    #[test]
    fn test_merge_commit_horizontal_line() {
        let mut merge_event = create_event("merge", vec!["main", "feat"]);
        merge_event.kind = GitEventKind::Merge;

        let events = vec![
            merge_event,
            create_event("main", vec!["base"]),
            create_event("feat", vec!["base"]),
            create_event("base", vec![]),
        ];
        let layout = build_graph(&events, None);

        // Get the merge row
        let merge_row = layout
            .rows
            .iter()
            .find(|r| r.event.as_ref().is_some_and(|e| e.short_hash == "merge"))
            .expect("Merge row should exist");

        // MergeNode or HeadNode exists
        let has_merge_or_head_node = merge_row
            .cells
            .iter()
            .any(|c| matches!(c, GraphCell::MergeNode { .. } | GraphCell::HeadNode { .. }));
        assert!(has_merge_or_head_node, "Merge row should have MergeNode");

        // Horizontal line exists
        let has_horizontal = merge_row
            .cells
            .iter()
            .any(|c| matches!(c, GraphCell::Horizontal { .. }));
        assert!(
            has_horizontal,
            "Merge row should have Horizontal line for second parent"
        );

        // Curve (CurveUpLeft) exists (new branch start)
        let has_curve = merge_row
            .cells
            .iter()
            .any(|c| matches!(c, GraphCell::CurveUpLeft { .. }));
        assert!(
            has_curve,
            "Merge row should have CurveUpLeft for branch start"
        );
    }

    /// Verify that branch commits do not have horizontal lines
    /// Commits on a branched-off path use only vertical lines in the same column as the parent
    #[test]
    fn test_branch_commit_no_horizontal_line() {
        // feat branch forked from main
        // main: base -> main1
        // feat: base -> feat1 (branch commit)
        let events = vec![
            create_event("feat1", vec!["base"]),
            create_event("main1", vec!["base"]),
            create_event("base", vec![]),
        ];
        let layout = build_graph(&events, None);

        // Get the feat1 row
        let feat1_row = layout
            .rows
            .iter()
            .find(|r| r.event.as_ref().is_some_and(|e| e.short_hash == "feat1"))
            .expect("feat1 row should exist");

        // feat1 row should not have horizontal lines
        // Branch commits do not draw horizontal lines
        let has_horizontal = feat1_row
            .cells
            .iter()
            .any(|c| matches!(c, GraphCell::Horizontal { .. }));
        assert!(
            !has_horizontal,
            "Branch commit should NOT have Horizontal line"
        );
    }

    /// Verify that vertical lines continue even when a parent is outside the display range
    #[test]
    fn test_parent_outside_display_range() {
        // commit2's parent commit1 is within the display range, but commit1's parent is outside
        let events = vec![
            create_event("commit2", vec!["commit1"]),
            create_event("commit1", vec!["outside_parent"]), // outside_parent is out of range
        ];
        let layout = build_graph(&events, None);

        assert_eq!(layout.len(), 2);

        // Vertical line continues even on commit1's row (column is being tracked)
        // The column is tracked even when the parent is outside the range
        let commit1_row = layout
            .rows
            .iter()
            .find(|r| r.event.as_ref().is_some_and(|e| e.short_hash == "commit1"))
            .expect("commit1 row should exist");

        // commit1 is placed in column 0
        assert_eq!(commit1_row.column, 0);
    }

    /// Test for three or more parallel branches
    #[test]
    fn test_three_parallel_branches() {
        let mut merge = create_event("merge", vec!["main3", "feat1", "feat2"]);
        merge.kind = GitEventKind::Merge;

        let events = vec![
            merge,
            create_event("main3", vec!["main2"]),
            create_event("feat1", vec!["main1"]),
            create_event("feat2", vec!["main1"]),
            create_event("main2", vec!["main1"]),
            create_event("main1", vec![]),
        ];
        let layout = build_graph(&events, None);

        // There should be 6 event rows
        let event_rows: Vec<_> = layout.rows.iter().filter(|r| r.event.is_some()).collect();
        assert_eq!(event_rows.len(), 6);

        // Maximum column count should be at least 2 (3 parallel branches)
        assert!(
            layout.max_column >= 2,
            "Should have at least 3 columns for 3 parallel branches"
        );
    }

    /// In linear history, all commits are placed in the same column
    #[test]
    fn test_linear_history_same_column() {
        let events = vec![
            create_event("c5", vec!["c4"]),
            create_event("c4", vec!["c3"]),
            create_event("c3", vec!["c2"]),
            create_event("c2", vec!["c1"]),
            create_event("c1", vec![]),
        ];
        let layout = build_graph(&events, None);

        // All commits should be in column 0
        for row in &layout.rows {
            assert_eq!(
                row.column, 0,
                "All commits in linear history should be in column 0"
            );
        }

        // No connector rows (no branches)
        let connector_count = layout.rows.iter().filter(|r| r.event.is_none()).count();
        assert_eq!(
            connector_count, 0,
            "Linear history should have no connector rows"
        );
    }

    /// Verify that vertical line colors are correct
    #[test]
    fn test_vertical_line_colors() {
        let mut merge = create_event("merge", vec!["main", "feat"]);
        merge.kind = GitEventKind::Merge;

        let events = vec![
            merge,
            create_event("feat", vec!["base"]),
            create_event("main", vec!["base"]),
            create_event("base", vec![]),
        ];
        let layout = build_graph(&events, None);

        // Verify vertical line colors in each row
        for row in layout.rows.iter().filter(|r| r.event.is_some()) {
            for cell in &row.cells {
                if let GraphCell::Vertical { color_idx } = cell {
                    // Color index is within valid range
                    assert!(*color_idx < 8, "Color index should be < 8");
                }
            }
        }
    }

    /// Verify that cross cells are generated correctly
    #[test]
    fn test_cross_generation() {
        // Case where crossing occurs in a complex merge
        // main: base -> main1 -> main2
        // feat1: base -> feat1
        // feat2: base -> feat2
        // merge: main2 + feat1 + feat2
        let mut merge = create_event("merge", vec!["main2", "feat1", "feat2"]);
        merge.kind = GitEventKind::Merge;

        let events = vec![
            merge,
            create_event("main2", vec!["main1"]),
            create_event("feat1", vec!["base"]),
            create_event("feat2", vec!["base"]),
            create_event("main1", vec!["base"]),
            create_event("base", vec![]),
        ];
        let layout = build_graph(&events, None);

        // Check if cross cells exist
        // Note: whether crossing occurs depends on the configuration
        let has_cross = layout
            .rows
            .iter()
            .any(|r| r.cells.iter().any(|c| matches!(c, GraphCell::Cross { .. })));

        // If crossing exists, h_color and v_color should be set
        if has_cross {
            for row in &layout.rows {
                for cell in &row.cells {
                    if let GraphCell::Cross { h_color, v_color } = cell {
                        assert!(*h_color < 8, "h_color should be valid");
                        assert!(*v_color < 8, "v_color should be valid");
                    }
                }
            }
        }
    }

    /// Verify column release after merge
    #[test]
    fn test_column_release_after_merge() {
        let mut merge1 = create_event("merge1", vec!["main2", "feat1"]);
        merge1.kind = GitEventKind::Merge;

        let events = vec![
            merge1,
            create_event("feat1", vec!["main1"]),
            create_event("main2", vec!["main1"]),
            create_event("main1", vec![]),
            create_event("after_merge", vec!["main1"]), // Commit after merge
        ];
        let layout = build_graph(&events, None);

        // After merge, columns are released and reused
        // max_column should not grow excessively
        assert!(
            layout.max_column <= 2,
            "Columns should be reused after merge"
        );
    }

    /// Verify that node types are set correctly
    #[test]
    fn test_node_types() {
        let mut merge = create_event("merge", vec!["main", "feat"]);
        merge.kind = GitEventKind::Merge;

        let events = vec![
            merge,
            create_event("main", vec!["base"]),
            create_event("base", vec![]),
        ];

        // Without HEAD
        let layout_no_head = build_graph(&events, None);
        let merge_row = layout_no_head
            .rows
            .iter()
            .find(|r| r.event.as_ref().is_some_and(|e| e.short_hash == "merge"))
            .unwrap();
        assert!(
            merge_row
                .cells
                .iter()
                .any(|c| matches!(c, GraphCell::MergeNode { .. })),
            "Merge commit without HEAD should have MergeNode"
        );

        // With HEAD
        let layout_with_head = build_graph(&events, Some("merge"));
        let merge_row_head = layout_with_head
            .rows
            .iter()
            .find(|r| r.event.as_ref().is_some_and(|e| e.short_hash == "merge"))
            .unwrap();
        assert!(
            merge_row_head
                .cells
                .iter()
                .any(|c| matches!(c, GraphCell::HeadNode { .. })),
            "Merge commit with HEAD should have HeadNode"
        );

        // Normal commit
        let normal_row = layout_no_head
            .rows
            .iter()
            .find(|r| r.event.as_ref().is_some_and(|e| e.short_hash == "main"))
            .unwrap();
        assert!(
            normal_row
                .cells
                .iter()
                .any(|c| matches!(c, GraphCell::Node { .. })),
            "Normal commit should have Node"
        );
    }

    /// Verify TeeLeft generation
    #[test]
    fn test_tee_left_generation() {
        let mut merge = create_event("merge", vec!["main", "feat"]);
        merge.kind = GitEventKind::Merge;

        let events = vec![
            merge,
            // Place feat first and connect merge leftward
            create_event("feat", vec!["base"]),
            create_event("main", vec!["base"]),
            create_event("base", vec![]),
        ];
        let layout = build_graph(&events, None);

        // TeeLeft or CurveUpLeft should exist
        let has_tee_or_curve = layout.rows.iter().any(|r| {
            r.cells
                .iter()
                .any(|c| matches!(c, GraphCell::TeeLeft { .. } | GraphCell::CurveUpLeft { .. }))
        });
        assert!(
            has_tee_or_curve,
            "Should have TeeLeft or CurveUpLeft for rightward connection"
        );
    }

    /// Verify no panic with empty event list
    #[test]
    fn test_empty_events_no_panic() {
        let layout = build_graph(&[], None);
        assert!(layout.is_empty());
        assert_eq!(layout.max_column, 0);
    }

    /// Verify no panic with a single commit
    #[test]
    fn test_single_commit_no_panic() {
        let events = vec![create_event("only", vec![])];
        let layout = build_graph(&events, Some("only"));

        assert_eq!(layout.len(), 1);
        assert!(layout.rows[0].is_head);
        assert!(layout.rows[0]
            .cells
            .iter()
            .any(|c| matches!(c, GraphCell::HeadNode { .. })));
    }

    /// Verify that vertical lines are drawn correctly when consecutive merges occur
    /// (Bug fix in v2.10.3: prevent vertical line disappearance due to early column release)
    #[test]
    fn test_consecutive_merges_vertical_lines_preserved() {
        // Structure:
        // merge2 ─┬─ feat2 ─────────┐
        //         │                 │
        //         └─ main2 ─┬─ merge1
        //                   └─ feat1
        let mut merge2 = create_event("merge2", vec!["main2", "feat2"]);
        merge2.kind = GitEventKind::Merge;
        let mut merge1 = create_event("merge1", vec!["base", "feat1"]);
        merge1.kind = GitEventKind::Merge;

        let events = vec![
            merge2,
            create_event("feat2", vec!["merge1"]),
            create_event("main2", vec!["merge1"]),
            merge1,
            create_event("feat1", vec!["base"]),
            create_event("base", vec![]),
        ];
        let layout = build_graph(&events, None);

        // If connector rows exist between feat2 and main2, check for vertical lines
        // Count vertical line cells across all rows
        let mut vertical_count = 0;
        for row in &layout.rows {
            for cell in &row.cells {
                if matches!(cell, GraphCell::Vertical { .. }) {
                    vertical_count += 1;
                }
            }
        }

        // Confirm vertical lines are drawn properly (non-zero is OK)
        assert!(
            vertical_count > 0,
            "Vertical lines should be preserved between consecutive merges"
        );

        // Also confirm columns do not grow excessively
        assert!(
            layout.max_column <= 3,
            "Columns should be reused efficiently, got max_column={}",
            layout.max_column
        );
    }

    /// Verify that 10 or more parallel branches are drawn correctly
    #[test]
    fn test_many_parallel_branches() {
        // Structure: 12 branches fork from the same base and eventually merge
        //
        // final_merge ─┬─ branch01 ─┐
        //              ├─ branch02 ─┤
        //              ├─ branch03 ─┤
        //              ├─ branch04 ─┤
        //              ├─ branch05 ─┤
        //              ├─ branch06 ─┤
        //              ├─ branch07 ─┤
        //              ├─ branch08 ─┤
        //              ├─ branch09 ─┤
        //              ├─ branch10 ─┤
        //              ├─ branch11 ─┤
        //              └─ branch12 ─┴─ base

        let mut events = vec![];

        // final_merge: merge 12 branches
        let mut final_merge = create_event(
            "final",
            vec![
                "branch01", "branch02", "branch03", "branch04", "branch05", "branch06", "branch07",
                "branch08", "branch09", "branch10", "branch11", "branch12",
            ],
        );
        final_merge.kind = GitEventKind::Merge;
        events.push(final_merge);

        // Each branch (all having the same base as parent)
        for i in 1..=12 {
            events.push(create_event(&format!("branch{:02}", i), vec!["base"]));
        }

        // base commit
        events.push(create_event("base", vec![]));

        let layout = build_graph(&events, None);

        // Confirm completion without panic
        assert!(!layout.rows.is_empty());

        // Confirm each branch is placed in a different column
        let mut branch_columns: Vec<usize> = vec![];
        for row in &layout.rows {
            if let Some(ref event) = row.event {
                if event.short_hash.starts_with("branch") {
                    branch_columns.push(row.column);
                }
            }
        }
        // 12 branch columns should exist
        assert_eq!(branch_columns.len(), 12);

        // max_column should be at least 11 (columns 0-11 for 12 branches)
        assert!(
            layout.max_column >= 11,
            "Expected at least 12 columns for 12 parallel branches, got max_column={}",
            layout.max_column
        );
    }

    /// Verify that complex cross patterns are drawn correctly
    #[test]
    fn test_complex_cross_pattern() {
        // Structure: pattern where left and right branches cross
        //
        // merge_left ─┬─ left_branch ─────┬─ base
        //             └─ middle ─┬─ right_branch
        //                        └─ right2
        //
        // Lines of left_branch and right_branch cross each other

        let mut merge_left = create_event("merge_left", vec!["left_branch", "middle"]);
        merge_left.kind = GitEventKind::Merge;

        let mut middle = create_event("middle", vec!["right_branch", "right2"]);
        middle.kind = GitEventKind::Merge;

        let events = vec![
            merge_left,
            create_event("left_branch", vec!["base"]),
            middle,
            create_event("right_branch", vec!["base"]),
            create_event("right2", vec!["base"]),
            create_event("base", vec![]),
        ];

        let layout = build_graph(&events, None);

        // Completed without panic
        assert!(!layout.rows.is_empty());

        // Check if cross cells exist (when crossing occurs)
        let has_any_horizontal = layout.rows.iter().any(|row| {
            row.cells.iter().any(|c| {
                matches!(
                    c,
                    GraphCell::Horizontal { .. }
                        | GraphCell::Cross { .. }
                        | GraphCell::TeeLeft { .. }
                        | GraphCell::TeeRight { .. }
                )
            })
        });
        // Merges should have horizontal connection cells
        assert!(
            has_any_horizontal,
            "Complex merge pattern should have horizontal connections"
        );
    }

    /// Verify correct behavior with color wraparound for branches exceeding 16 colors
    #[test]
    fn test_color_wraparound_with_many_branches() {
        // Create 20 branches (exceeding the 16-color palette)
        let events: Vec<GitEvent> = (1..=20)
            .map(|i| {
                let hash = format!("commit{:02}", i);
                let parent = if i == 1 {
                    vec![]
                } else {
                    vec![format!("commit{:02}", i - 1)]
                };
                let mut event = GitEvent::commit(
                    hash.clone(),
                    format!("commit {}", hash),
                    "author".to_string(),
                    Local::now(),
                    0,
                    0,
                );
                event.parent_hashes = parent;
                event
            })
            .collect();

        let layout = build_graph(&events, None);

        // Completed without panic
        assert_eq!(layout.rows.len(), 20);

        // Confirm color indices are within palette size
        for row in &layout.rows {
            assert!(
                row.color_idx < 16,
                "Color index {} should be within palette size",
                row.color_idx
            );
        }
    }

    /// Verify that deeply nested merges are handled correctly
    #[test]
    fn test_deeply_nested_merges() {
        // Structure: chain of consecutive merges
        //
        // merge5 ─┬─ merge4 ─┬─ merge3 ─┬─ merge2 ─┬─ merge1 ─┬─ main
        //         │          │          │          │          └─ branch1
        //         │          │          │          └─ branch2
        //         │          │          └─ branch3
        //         │          └─ branch4
        //         └─ branch5

        let mut events = vec![];

        for i in (1..=5).rev() {
            let parent1 = if i == 1 {
                "main".to_string()
            } else {
                format!("merge{}", i - 1)
            };
            let parent2 = format!("branch{}", i);
            let mut merge = create_event(&format!("merge{}", i), vec![]);
            merge.parent_hashes = vec![parent1, parent2];
            merge.kind = GitEventKind::Merge;
            events.push(merge);
        }

        for i in (1..=5).rev() {
            events.push(create_event(&format!("branch{}", i), vec!["base"]));
        }
        events.push(create_event("main", vec!["base"]));
        events.push(create_event("base", vec![]));

        let layout = build_graph(&events, None);

        // Completed without panic
        assert!(!layout.rows.is_empty());

        // Confirm 5 merge nodes exist
        let merge_count = layout
            .rows
            .iter()
            .filter(|row| {
                row.cells
                    .iter()
                    .any(|c| matches!(c, GraphCell::MergeNode { .. }))
            })
            .count();
        assert_eq!(merge_count, 5, "Should have 5 merge nodes");
    }

    /// Verify that lines are not broken even when diamond patterns (branch then merge) occur consecutively
    #[test]
    fn test_diamond_pattern_chain() {
        // Structure: 3 consecutive diamond patterns
        //
        // merge3 ─┬─ feat3 ─┬─ merge2 ─┬─ feat2 ─┬─ merge1 ─┬─ feat1 ─┬─ base
        //         └─────────┘          └─────────┘          └─────────┘
        //
        // Each diamond involves branching, parallel development, and merging

        let mut events = vec![];

        // 3 diamond patterns
        for i in (1..=3).rev() {
            let parent = if i == 3 {
                "base".to_string()
            } else {
                format!("merge{}", i + 1)
            };

            // Merge commit
            let mut merge = create_event(&format!("merge{}", i), vec![]);
            merge.parent_hashes = vec![format!("feat{}", i), parent.clone()];
            merge.kind = GitEventKind::Merge;
            events.push(merge);

            // Feature branch
            events.push(create_event(&format!("feat{}", i), vec![&parent]));
        }

        events.push(create_event("base", vec![]));

        let layout = build_graph(&events, None);

        // Completed without panic
        assert!(!layout.rows.is_empty());

        // 3 merge nodes
        let merge_count = layout
            .rows
            .iter()
            .filter(|row| {
                row.cells
                    .iter()
                    .any(|c| matches!(c, GraphCell::MergeNode { .. }))
            })
            .count();
        assert_eq!(merge_count, 3, "Should have 3 merge nodes");

        // Vertical lines should exist (tree structure is preserved)
        let vertical_count: usize = layout
            .rows
            .iter()
            .map(|row| {
                row.cells
                    .iter()
                    .filter(|c| matches!(c, GraphCell::Vertical { .. }))
                    .count()
            })
            .sum();

        assert!(
            vertical_count > 0,
            "Vertical lines should exist in diamond pattern chain"
        );
    }

    /// Verify that lines are not broken even with alternating merge patterns (merging alternately from left and right)
    #[test]
    fn test_alternating_merge_pattern() {
        // Structure: pattern where merges alternate from left and right
        //
        // final ─┬─ right3 ───────────────────────────┐
        //        │                                    │
        //        └─ merge_r2 ─┬─ left2 ───────────────┼─┐
        //                     │                       │ │
        //                     └─ merge_l1 ─┬─ right1 ─┘ │
        //                                  │            │
        //                                  └─ left1 ────┴─ base

        let mut final_merge = create_event("final", vec!["merge_r2", "right3"]);
        final_merge.kind = GitEventKind::Merge;

        let mut merge_r2 = create_event("merge_r2", vec!["merge_l1", "left2"]);
        merge_r2.kind = GitEventKind::Merge;

        let mut merge_l1 = create_event("merge_l1", vec!["left1", "right1"]);
        merge_l1.kind = GitEventKind::Merge;

        let events = vec![
            final_merge,
            create_event("right3", vec!["base"]),
            merge_r2,
            create_event("left2", vec!["base"]),
            merge_l1,
            create_event("right1", vec!["base"]),
            create_event("left1", vec!["base"]),
            create_event("base", vec![]),
        ];

        let layout = build_graph(&events, None);

        // Completed without panic
        assert!(!layout.rows.is_empty());

        // 3 merge nodes
        let merge_count = layout
            .rows
            .iter()
            .filter(|row| {
                row.cells
                    .iter()
                    .any(|c| matches!(c, GraphCell::MergeNode { .. }))
            })
            .count();
        assert_eq!(merge_count, 3, "Should have 3 merge nodes");

        // All expected commits should exist
        let hashes: Vec<_> = layout
            .rows
            .iter()
            .filter_map(|row| row.event.as_ref().map(|e| e.short_hash.as_str()))
            .collect();

        assert!(hashes.contains(&"final"));
        assert!(hashes.contains(&"right3"));
        assert!(hashes.contains(&"merge_r2"));
        assert!(hashes.contains(&"left2"));
        assert!(hashes.contains(&"merge_l1"));
        assert!(hashes.contains(&"right1"));
        assert!(hashes.contains(&"left1"));
        assert!(hashes.contains(&"base"));
    }

    /// Verify that tree structure is preserved (row order and connectivity)
    #[test]
    fn test_tree_structure_preserved() {
        // Complex tree structure
        //
        // root ─┬─ child1 ─┬─ grandchild1
        //       │          └─ grandchild2
        //       └─ child2 ─┬─ grandchild3
        //                  └─ grandchild4

        let mut root = create_event("root", vec!["child1", "child2"]);
        root.kind = GitEventKind::Merge;

        let mut child1 = create_event("child1", vec!["grandchild1", "grandchild2"]);
        child1.kind = GitEventKind::Merge;

        let mut child2 = create_event("child2", vec!["grandchild3", "grandchild4"]);
        child2.kind = GitEventKind::Merge;

        let events = vec![
            root,
            child1,
            create_event("grandchild1", vec!["base"]),
            create_event("grandchild2", vec!["base"]),
            child2,
            create_event("grandchild3", vec!["base"]),
            create_event("grandchild4", vec!["base"]),
            create_event("base", vec![]),
        ];

        let layout = build_graph(&events, None);

        // Completed without panic
        assert!(!layout.rows.is_empty());

        // All commits should exist
        let event_count = layout.rows.iter().filter(|r| r.event.is_some()).count();
        assert_eq!(event_count, 8, "All 8 commits should be present");

        // Vertical and horizontal lines exist appropriately (tree structure connections)
        let has_vertical = layout.rows.iter().any(|row| {
            row.cells
                .iter()
                .any(|c| matches!(c, GraphCell::Vertical { .. }))
        });
        let has_horizontal = layout.rows.iter().any(|row| {
            row.cells.iter().any(|c| {
                matches!(
                    c,
                    GraphCell::Horizontal { .. }
                        | GraphCell::CurveUpLeft { .. }
                        | GraphCell::CurveUpRight { .. }
                        | GraphCell::CurveDownLeft { .. }
                        | GraphCell::CurveDownRight { .. }
                )
            })
        });

        assert!(has_vertical, "Tree should have vertical connections");
        assert!(has_horizontal, "Tree should have horizontal connections");

        // Columns are used efficiently (not excessively many)
        assert!(
            layout.max_column <= 5,
            "Columns should be reused efficiently, got max_column={}",
            layout.max_column
        );
    }
}