worktrunk 0.35.0

A CLI for Git worktree management, designed for parallel AI agent workflows
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
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
//! Column layout and priority allocation for the list command.
//!
//! # Status Column Structure
//!
//! The Status column uses a unified position-based grid system for all status
//! indicators including user-defined status.
//!
//! ## Unified Position Grid
//!
//! All status indicators use position-based alignment with selective rendering.
//! See [`super::model::StatusSymbols`] for the complete symbol list and categories.
//!
//! Only positions used by at least one row are included (position mask):
//! - Within those positions, symbols align vertically for scannability
//! - Empty positions render as single space for grid alignment
//! - No leading spaces before the first symbol
//!
//! Example with working_tree, main_state, and user_marker used:
//! ```text
//! Row 1: "   _🤖"   (working=space, main=_, user=🤖)
//! Row 2: "?! _  "   (working=?!, main=_, user=space)
//! Row 3: "    💬"   (working=space, main=space, user=💬)
//! ```
//!
//! ## Width Calculation
//!
//! ```text
//! status_width = max(rendered_width_across_all_items)
//! ```
//!
//! The width is calculated by rendering each item's status with the position
//! mask and taking the maximum width.
//!
//! ## Why This Design?
//!
//! **Single canonical system:**
//! - One alignment mechanism for all status indicators
//! - User marker treated consistently with git symbols
//!
//! **Eliminates wasted space:**
//! - Position mask removes columns for symbols that appear in zero rows
//! - User marker only takes space when present
//!
//! **Maintains alignment:**
//! - All symbols align vertically at their positions (vertical scannability)
//! - Grid adapts to minimize width based on active positions
//!
//! # Priority System Design
//!
//! ## Priority Scoring Model
//!
//! The allocation system uses a **priority scoring model**:
//! ```text
//! final_priority = base_priority + empty_penalty
//! ```
//!
//! **Base priorities** (0-12) are determined by **user need hierarchy** - what questions users need
//! answered when scanning worktrees:
//! - 0: Gutter (always present)
//! - 1: Branch (identity - "what is this?")
//! - 2-4: Critical (status, working diff, ahead/behind)
//! - 5-11: Context (CI, branch diff, path, upstream, URL, commit, time)
//! - 12: Message (nice-to-have, space-hungry)
//!
//! **Empty penalty**: +10 if column has no data (only header)
//! - Empty working_diff: 3 + 10 = priority 13
//! - Empty ahead/behind: 4 + 10 = priority 14
//! - etc.
//!
//! This creates two effective priority tiers:
//! - **Tier 1 (priorities 0-12)**: Columns with actual data
//! - **Tier 2 (priorities 12-22)**: Empty columns (visual consistency)
//!
//! The empty penalty is large (+10) but not infinite, so empty columns maintain their relative
//! ordering (empty working_diff still ranks higher than empty ci_status) for visual consistency.
//!
//! ## Why This Design?
//!
//! **Problem**: Terminal width is limited. We must decide what to show.
//!
//! **Goals**:
//! 1. Show critical data (uncommitted changes, sync status) at any terminal width
//! 2. Show nice-to-have data (message, commit hash) when space allows
//! 3. Maintain visual consistency - empty columns in predictable positions at wide widths
//!
//! **Key decision**: Message sits at the boundary (priority 12). Empty columns (priority 12+)
//! rank below message, so:
//! - Narrow terminals: Data columns + message (hide empty columns)
//! - Wide terminals: Data columns + message + empty columns (visual consistency)
//!
//! ## Limitation: Progressive Mode
//!
//! The empty penalty system requires knowing whether columns have data, but progressive rendering
//! computes layout before data arrives. Currently we assume most columns have data (optimistic),
//! which means empty penalties don't apply in progressive mode.
//!
//! Exceptions that we can compute instantly from items:
//! - `path`: true only if any worktree has `branch_worktree_mismatch` (computed from items)
//! - `branch_diff`/`ci_status`: false if their required task is skipped
//!
//! Other columns (status, working_diff, ahead_behind, upstream) require expensive git operations,
//! so we assume they have data until proven otherwise.
//!
//! ## Special Cases
//!
//! Some columns have non-standard behavior that extends beyond the basic two-tier model:
//!
//! 1. **BranchDiff** and **CiStatus** - Visibility gate (`show_full` flag)
//!    - Both require `show_full=true` (hidden by default as too noisy for typical usage)
//!    - Gated via `skip_tasks`: when `show_full=false`, their `TaskKind` is in `skip_tasks`
//!      and the column is filtered out entirely (bypasses the tier system)
//!    - Within the visibility gate, follows normal two-tier priority
//!      (BranchDiff: 6/16, CiStatus: 5/15)
//!
//! 2. **Low-priority columns** yield to Summary
//!    - Columns with effective priority > Summary's (10) are dropped to reclaim
//!      space, with thresholds based on priority distance:
//!      - Within 4 levels (Commit 11, Time 12, Message 13): Summary < 50
//!      - Beyond 4 levels (e.g., no-data Path 7+10=17): Summary < 70 (MAX)
//!    - Highest priority value drops first; no-data columns qualify via EMPTY_PENALTY
//!
//! 3. **Summary** - Flexible sizing with post-allocation expansion
//!    - Allocated at priority 10 with minimum width 10
//!    - After all columns allocated, expands up to 70 using leftover space
//!    - Reclaims no-data and low-priority columns as needed
//!    - Expands BEFORE Message, so Summary gets priority for space
//!
//! 4. **Message** - Flexible sizing, gated on Summary readability
//!    - Allocated at priority 13 with minimum width 10
//!    - **Only kept if Summary reaches 50 chars** — below that, Summary needs
//!      all flexible space and Message is dropped (its space reclaimed for Summary)
//!    - After Summary expansion, expands up to max 100 using remaining leftover space
//!
//! ## Implementation
//!
//! The code implements this using a centralized registry and priority-based allocation:
//!
//! ```rust
//! // Build candidates from centralized COLUMN_SPECS registry
//! let mut candidates: Vec<ColumnCandidate> = COLUMN_SPECS
//!     .iter()
//!     .filter(|spec| /* visibility gate: skip_tasks */)
//!     .map(|spec| ColumnCandidate {
//!         spec,
//!         priority: if spec.kind.has_data(&data_flags) {
//!             spec.base_priority
//!         } else {
//!             spec.base_priority + EMPTY_PENALTY
//!         }
//!     })
//!     .collect();
//!
//! // Sort by final priority
//! candidates.sort_by_key(|candidate| candidate.priority);
//!
//! // Allocate columns in priority order, building pending list
//! for candidate in candidates {
//!     if candidate.spec.kind == ColumnKind::Message {
//!         // Special handling: flexible width (min 20, preferred 50)
//!     } else if let Some(ideal) = candidate.spec.kind.ideal(...) {
//!         if let allocated = try_allocate(&mut remaining, ideal.width, ...) {
//!             pending.push(PendingColumn { spec: candidate.spec, width: allocated, format: ideal.format });
//!         }
//!     }
//! }
//!
//! // Post-allocation expansion: Summary first, then Message with leftovers
//! if let Some(summary_col) = pending.iter_mut().find(|col| col.spec.kind == ColumnKind::Summary) {
//!     summary_col.width += remaining.min(MAX_SUMMARY - summary_col.width);
//! }
//! if let Some(message_col) = pending.iter_mut().find(|col| col.spec.kind == ColumnKind::Message) {
//!     message_col.width += remaining.min(MAX_MESSAGE - message_col.width);
//! }
//! ```
//!
//! **Benefits**:
//! - Column metadata centralized in `COLUMN_SPECS` registry (single source of truth)
//! - Priority calculation explicit (base_priority + conditional EMPTY_PENALTY)
//! - Single unified allocation loop (no phase duplication)
//! - Easy to understand: build candidates → sort by priority → allocate → expand message
//! - Extensible: can add new modifiers (terminal width bonus, user config) without restructuring
//!
//! ## Helper Functions
//!
//! - `fit_header()`: Ensures column width ≥ header width to prevent overflow
//! - `try_allocate()`: Attempts to allocate space, returns 0 if insufficient

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use anstyle::Style;
use unicode_width::UnicodeWidthStr;
use worktrunk::styling::{ADDITION, DELETION, Stream, supports_hyperlinks};

use crate::display::{shorten_path, terminal_width};

use super::collect::{TaskKind, parse_port_from_url};
use super::columns::{COLUMN_SPECS, ColumnKind, ColumnSpec, column_display_index};

// Re-export DiffVariant for external use (e.g., picker module)
pub use super::columns::DiffVariant;

/// Width of short commit hash display (first 8 hex characters)
const COMMIT_HASH_WIDTH: usize = 8;

/// Ensures a column width is at least as wide as its header.
///
/// This is the general solution for preventing header overflow: pass the header
/// string and the calculated data width, and this returns the larger of the two.
///
/// For empty columns (data_width = 0), returns header width. This allows empty
/// columns to be allocated at low priority (base_priority + EMPTY_PENALTY) for
/// visual consistency on wide terminals.
fn fit_header(header: &str, data_width: usize) -> usize {
    data_width.max(header.width())
}

/// Helper: Try to allocate space for a column. Returns the allocated width if successful.
/// Updates `remaining` by subtracting the allocated width + spacing.
/// If is_first is true, doesn't require spacing before the column.
///
/// When `min_width` is provided, the column can shrink below its ideal width (down to
/// `min_width`) instead of being dropped entirely. This prevents high-priority columns
/// like Branch from disappearing on narrow terminals.
///
/// The spacing is consumed from the budget (subtracted from `remaining`) but not returned
/// as part of the column's width, since the spacing appears before the column content.
fn try_allocate(
    remaining: &mut usize,
    ideal_width: usize,
    min_width: Option<usize>,
    spacing: usize,
    is_first: bool,
) -> usize {
    if ideal_width == 0 {
        return 0;
    }
    let spacing_cost = if is_first { 0 } else { spacing };

    // Try ideal width first
    if *remaining >= ideal_width + spacing_cost {
        *remaining -= ideal_width + spacing_cost;
        return ideal_width;
    }

    // Fall back to whatever fits above min_width
    if let Some(min) = min_width
        && *remaining >= min + spacing_cost
    {
        let width = *remaining - spacing_cost;
        *remaining = 0;
        return width;
    }

    0
}

/// Width information for two-part columns: diffs ("+128 -147") and arrows ("↑6 ↓1")
#[derive(Clone, Copy, Debug)]
pub struct DiffWidths {
    pub total: usize,
    pub positive_digits: usize, // First part: +/↑/⇡
    pub negative_digits: usize, // Second part: -/↓/⇣
}

#[derive(Clone, Debug)]
pub struct ColumnWidths {
    pub branch: usize,
    pub status: usize, // Includes both git status symbols and user-defined status
    pub time: usize,
    pub url: usize,
    pub ci_status: usize,
    pub ahead_behind: DiffWidths,
    pub working_diff: DiffWidths,
    pub branch_diff: DiffWidths,
    pub upstream: DiffWidths,
}

/// Tracks which columns have actual data (vs just headers)
#[derive(Clone, Copy, Debug)]
pub struct ColumnDataFlags {
    pub status: bool, // True if any item has git status symbols or user-defined status
    pub working_diff: bool,
    pub ahead_behind: bool,
    pub branch_diff: bool,
    pub upstream: bool,
    pub url: bool,
    pub ci_status: bool,
    pub path: bool, // True if any worktree has branch_worktree_mismatch
}

/// Layout metadata including position mask for Status column
#[derive(Clone, Debug)]
pub struct LayoutMetadata {
    pub widths: ColumnWidths,
    pub data_flags: ColumnDataFlags,
    pub status_position_mask: super::model::PositionMask,
}

const EMPTY_PENALTY: u8 = 10;

#[derive(Clone, Copy, Debug)]
pub struct DiffDisplayConfig {
    pub variant: DiffVariant,
    pub positive_style: Style,
    pub negative_style: Style,
    pub always_show_zeros: bool,
}

impl DiffDisplayConfig {
    /// Format diff values with fixed-width alignment for tabular display.
    ///
    /// Numbers are right-aligned within a 3-digit column width.
    /// Returns empty spaces if both values are zero (unless `always_show_zeros` is set).
    #[cfg(unix)] // Only used by picker module which is unix-only
    pub fn format_aligned(&self, positive: usize, negative: usize) -> String {
        const DIGITS: usize = 3;
        let positive_width = 1 + DIGITS; // symbol + digits
        let negative_width = 1 + DIGITS;
        let total_width = positive_width + 1 + negative_width; // with separator

        let config = DiffColumnConfig {
            positive_digits: DIGITS,
            negative_digits: DIGITS,
            total_width,
            display: *self,
        };

        config.render_segment(positive, negative).render()
    }

    /// Format diff values as plain text with ANSI colors (no fixed-width alignment).
    ///
    /// Returns `None` if both values are zero (unless `always_show_zeros` is set).
    /// Format: `+N -M` with appropriate colors for each component.
    pub fn format_plain(&self, positive: usize, negative: usize) -> Option<String> {
        if !self.always_show_zeros && positive == 0 && negative == 0 {
            return None;
        }

        let symbols = self.variant.symbols();
        let mut parts = Vec::with_capacity(2);

        if positive > 0 || self.always_show_zeros {
            parts.push(format!(
                "{}{}{}{}",
                self.positive_style,
                symbols.positive,
                positive,
                self.positive_style.render_reset()
            ));
        }

        if negative > 0 || self.always_show_zeros {
            parts.push(format!(
                "{}{}{}{}",
                self.negative_style,
                symbols.negative,
                negative,
                self.negative_style.render_reset()
            ));
        }

        if parts.is_empty() {
            None
        } else {
            Some(parts.join(" "))
        }
    }
}

#[derive(Clone, Copy)]
pub(super) struct DiffSymbols {
    pub(super) positive: &'static str,
    pub(super) negative: &'static str,
}

impl DiffVariant {
    pub(super) fn symbols(self) -> DiffSymbols {
        match self {
            DiffVariant::Signs => DiffSymbols {
                positive: "+",
                negative: "-",
            },
            DiffVariant::Arrows => DiffSymbols {
                positive: "↑",
                negative: "↓",
            },
            DiffVariant::UpstreamArrows => DiffSymbols {
                positive: "⇡",
                negative: "⇣",
            },
        }
    }
}

impl ColumnKind {
    pub fn diff_display_config(self) -> Option<DiffDisplayConfig> {
        match self {
            ColumnKind::WorkingDiff | ColumnKind::BranchDiff => Some(DiffDisplayConfig {
                variant: DiffVariant::Signs,
                positive_style: ADDITION,
                negative_style: DELETION,
                always_show_zeros: false,
            }),
            ColumnKind::AheadBehind => Some(DiffDisplayConfig {
                variant: DiffVariant::Arrows,
                positive_style: ADDITION,
                negative_style: DELETION.dimmed(),
                always_show_zeros: false,
            }),
            ColumnKind::Upstream => Some(DiffDisplayConfig {
                variant: DiffVariant::UpstreamArrows,
                positive_style: ADDITION,
                negative_style: DELETION.dimmed(),
                always_show_zeros: false, // 0/0 case handled specially with | symbol
            }),
            _ => None,
        }
    }

    /// Format diff-style values as plain text with ANSI colors (for json-pretty).
    pub(crate) fn format_diff_plain(self, positive: usize, negative: usize) -> Option<String> {
        let config = self.diff_display_config()?;
        config.format_plain(positive, negative)
    }

    pub fn has_data(self, flags: &ColumnDataFlags) -> bool {
        match self {
            ColumnKind::Gutter => true, // Always present (shows @ ^ + or space)
            ColumnKind::Branch => true,
            ColumnKind::Status => flags.status,
            ColumnKind::WorkingDiff => flags.working_diff,
            ColumnKind::AheadBehind => flags.ahead_behind,
            ColumnKind::BranchDiff => flags.branch_diff,
            ColumnKind::Path => flags.path,
            ColumnKind::Upstream => flags.upstream,
            ColumnKind::Url => flags.url,
            ColumnKind::Time => true,
            ColumnKind::CiStatus => flags.ci_status,
            ColumnKind::Commit => true,
            ColumnKind::Summary => true, // Placeholder shown until data arrives
            ColumnKind::Message => true,
        }
    }

    /// Returns the ideal (width, format) for this column, or None if width is 0 or Message.
    fn ideal(
        self,
        widths: &ColumnWidths,
        max_path_width: usize,
        commit_width: usize,
    ) -> Option<(usize, ColumnFormat)> {
        let text = |w: usize| (w > 0).then_some((w, ColumnFormat::Text));
        let diff = |dw: DiffWidths| -> Option<(usize, ColumnFormat)> {
            if dw.total == 0 {
                return None;
            }
            let display = self.diff_display_config()?;
            Some((
                dw.total,
                ColumnFormat::Diff(DiffColumnConfig {
                    positive_digits: dw.positive_digits,
                    negative_digits: dw.negative_digits,
                    total_width: dw.total,
                    display,
                }),
            ))
        };

        match self {
            ColumnKind::Gutter => text(2), // Fixed width: symbol (1 char) + space (1 char)
            ColumnKind::Branch => text(widths.branch),
            ColumnKind::Status => text(widths.status),
            ColumnKind::Path => text(max_path_width),
            ColumnKind::Time => text(widths.time),
            ColumnKind::Url => text(widths.url),
            ColumnKind::CiStatus => text(widths.ci_status),
            ColumnKind::Commit => text(commit_width),
            ColumnKind::Summary => None, // Flexible: handled specially in allocation loop
            ColumnKind::Message => None,
            ColumnKind::WorkingDiff => diff(widths.working_diff),
            ColumnKind::AheadBehind => diff(widths.ahead_behind),
            ColumnKind::BranchDiff => diff(widths.branch_diff),
            ColumnKind::Upstream => diff(widths.upstream),
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub enum ColumnFormat {
    Text,
    Diff(DiffColumnConfig),
}

#[derive(Clone, Copy, Debug)]
pub struct DiffColumnConfig {
    pub positive_digits: usize,
    pub negative_digits: usize,
    pub total_width: usize,
    pub display: DiffDisplayConfig,
}

#[derive(Clone, Debug)]
pub struct ColumnLayout {
    pub kind: ColumnKind,
    pub header: &'static str,
    pub start: usize,
    pub width: usize,
    pub format: ColumnFormat,
}

pub struct LayoutConfig {
    pub columns: Vec<ColumnLayout>,
    pub main_worktree_path: PathBuf,
    pub max_message_len: usize,
    pub max_summary_len: usize,
    pub hidden_column_count: usize,
    pub status_position_mask: super::model::PositionMask,
}

#[derive(Clone, Copy)]
struct ColumnCandidate<'a> {
    spec: &'a ColumnSpec,
    priority: u8,
}

#[derive(Clone, Copy)]
struct PendingColumn<'a> {
    spec: &'a ColumnSpec,
    priority: u8,
    width: usize,
    format: ColumnFormat,
}

/// Estimate URL column width using heuristics.
///
/// When hyperlinks are supported, URLs display as `:PORT` (6 chars for 5-digit ports).
/// Otherwise, estimates full URL width from template structure.
fn estimate_url_width(url_template: Option<&str>, hyperlinks_supported: bool) -> usize {
    let Some(template) = url_template else {
        return 0;
    };

    // When hyperlinks are supported, URLs with ports display as ":XXXXX" (6 chars)
    if hyperlinks_supported {
        // Check for port patterns: template variables or static ports
        if template.contains("hash_port")
            || template.contains(":{{")
            || parse_port_from_url(template).is_some()
        {
            return 6; // ":12345"
        }
    }

    // Fallback: estimate full URL width from template structure
    // {{ branch | hash_port }} becomes a 5-digit port (10000-19999)
    // {{ branch }} becomes the branch name (unknown length, use 10 as average)
    template
        .replace("{{ branch | hash_port }}", "12345")
        .replace("{{ branch }}", "feature-xx")
        .len()
}

/// Build pre-allocated column width estimates.
///
/// Uses generous fixed allocations for expensive-to-compute columns (status, diffs, time, CI)
/// that handle overflow with compact notation (K suffix). This provides consistent layout
/// without requiring a data scan.
fn build_estimated_widths(
    max_branch: usize,
    skip_tasks: &HashSet<TaskKind>,
    has_branch_worktree_mismatch: bool,
    url_width: usize,
) -> LayoutMetadata {
    // Fixed widths for slow columns (require expensive git operations)
    // Values exceeding these widths use compact notation (K suffix)
    //
    // Status column: Must match PositionMask::FULL width for consistent alignment
    // PositionMask::FULL allocates: 1+1+1+1+1+1+2 = 8 chars (7 positions)
    let status_fixed = fit_header(ColumnKind::Status.header(), 8);
    let working_diff_fixed = fit_header(ColumnKind::WorkingDiff.header(), 9); // "+999 -999"
    let ahead_behind_fixed = fit_header(ColumnKind::AheadBehind.header(), 7); // "↑99 ↓99"
    let branch_diff_fixed = fit_header(ColumnKind::BranchDiff.header(), 9); // "+999 -999"
    let upstream_fixed = fit_header(ColumnKind::Upstream.header(), 7); // "↑99 ↓99"
    let age_estimate = 4; // "11mo" (short format)
    let ci_estimate = fit_header(ColumnKind::CiStatus.header(), 1); // Single indicator symbol

    // Assume columns will have data (better to show and hide than to not show).
    // This is a limitation of progressive mode - we can't know which columns have data
    // before the data arrives, so empty penalties don't apply properly.
    //
    // Exceptions that we can compute instantly from items:
    // - path: true only if any worktree has branch_worktree_mismatch
    // - branch_diff/ci_status: false if their required task is skipped
    let data_flags = ColumnDataFlags {
        status: true,
        working_diff: true,
        ahead_behind: true,
        branch_diff: !skip_tasks.contains(&TaskKind::BranchDiff),
        upstream: true,
        url: !skip_tasks.contains(&TaskKind::UrlStatus),
        ci_status: !skip_tasks.contains(&TaskKind::CiStatus),
        path: has_branch_worktree_mismatch,
    };

    // URL width estimated from template + longest branch (or fallback)
    // When url_width is 0 (no template), don't allocate any space for URL column
    let url_estimate = if url_width > 0 {
        fit_header(ColumnKind::Url.header(), url_width)
    } else {
        0
    };

    let widths = ColumnWidths {
        branch: max_branch,
        status: status_fixed,
        time: age_estimate,
        url: url_estimate,
        ci_status: ci_estimate,
        // Commit counts (Arrows): compact notation, 2 digits covers up to 99
        ahead_behind: DiffWidths {
            total: ahead_behind_fixed,
            positive_digits: 2,
            negative_digits: 2,
        },
        // Line diffs (Signs): show full numbers, 3 digits covers up to 999
        working_diff: DiffWidths {
            total: working_diff_fixed,
            positive_digits: 3,
            negative_digits: 3,
        },
        branch_diff: DiffWidths {
            total: branch_diff_fixed,
            positive_digits: 3,
            negative_digits: 3,
        },
        // Upstream (Arrows): compact notation, 2 digits covers up to 99
        upstream: DiffWidths {
            total: upstream_fixed,
            positive_digits: 2,
            negative_digits: 2,
        },
    };

    LayoutMetadata {
        widths,
        data_flags,
        status_position_mask: super::model::PositionMask::FULL,
    }
}

/// Allocate columns using priority-based allocation logic.
///
/// This is the core allocation algorithm used by `calculate_layout_from_basics()`
/// with pre-allocated width estimates for expensive-to-compute columns.
fn allocate_columns_with_priority(
    metadata: &LayoutMetadata,
    skip_tasks: &HashSet<TaskKind>,
    max_path_width: usize,
    commit_width: usize,
    terminal_width: usize,
    main_worktree_path: PathBuf,
) -> LayoutConfig {
    let spacing = 2;
    let mut remaining = terminal_width;

    // Build candidates with priorities
    // Filter out columns whose required task is being skipped
    let mut candidates: Vec<ColumnCandidate> = COLUMN_SPECS
        .iter()
        .filter(|spec| {
            spec.requires_task
                .is_none_or(|task| !skip_tasks.contains(&task))
        })
        .map(|spec| ColumnCandidate {
            spec,
            priority: if spec.kind.has_data(&metadata.data_flags) {
                spec.base_priority
            } else {
                spec.base_priority + EMPTY_PENALTY
            },
        })
        .collect();

    candidates.sort_by_key(|candidate| candidate.priority);

    // Store candidate kinds for later calculation of hidden columns
    let candidate_kinds: Vec<_> = candidates.iter().map(|c| c.spec.kind).collect();

    const MIN_SUMMARY: usize = 10;
    const MAX_SUMMARY: usize = 70;
    const MIN_MESSAGE: usize = 10;
    const MAX_MESSAGE: usize = 100;
    // Low-priority columns (Commit, Time, Message) are only shown when Summary
    // reaches this width — below that, Summary needs the space to be readable.
    const SUMMARY_THRESHOLD_FOR_LOW_PRIORITY: usize = 50;

    let mut pending: Vec<PendingColumn> = Vec::new();

    // Helper: check if spacing should be skipped (first column, or previous was Gutter)
    let needs_spacing = |pending: &[PendingColumn]| -> bool {
        if pending.is_empty() {
            return false;
        }
        // No gap after Gutter - its content includes the spacing
        if pending.last().map(|c| c.spec.kind) == Some(ColumnKind::Gutter) {
            return false;
        }
        true
    };

    // Allocate columns in priority order
    for candidate in candidates {
        let spec = candidate.spec;

        // Flexible columns: allocate at minimum, expand post-loop
        if matches!(spec.kind, ColumnKind::Summary | ColumnKind::Message) {
            let min_width = match spec.kind {
                ColumnKind::Summary => MIN_SUMMARY,
                _ => MIN_MESSAGE,
            };
            let spacing_cost = if needs_spacing(&pending) { spacing } else { 0 };
            if remaining > spacing_cost {
                let available = remaining - spacing_cost;
                if available >= min_width {
                    remaining = remaining.saturating_sub(min_width + spacing_cost);
                    pending.push(PendingColumn {
                        spec,
                        priority: candidate.priority,
                        width: min_width,
                        format: ColumnFormat::Text,
                    });
                }
            }
            continue;
        }

        // For non-message columns
        let Some((ideal_width, format)) =
            spec.kind
                .ideal(&metadata.widths, max_path_width, commit_width)
        else {
            continue;
        };

        let is_first = !needs_spacing(&pending);
        let min_width = if spec.shrinkable {
            Some(spec.kind.header().width().max(1))
        } else {
            None
        };
        let allocated = try_allocate(&mut remaining, ideal_width, min_width, spacing, is_first);
        if allocated > 0 {
            pending.push(PendingColumn {
                spec,
                priority: candidate.priority,
                width: allocated,
                format,
            });
        }
    }

    // Post-allocation expansion: Summary first, then Message with leftovers.
    // Low-priority columns (Commit, Time, Message) are dropped when Summary
    // hasn't reached SUMMARY_THRESHOLD_FOR_LOW_PRIORITY (50).
    let mut max_summary_len = 0;
    if let Some(summary_col) = pending
        .iter_mut()
        .find(|col| col.spec.kind == ColumnKind::Summary)
    {
        if summary_col.width < MAX_SUMMARY && remaining > 0 {
            let expansion = remaining.min(MAX_SUMMARY - summary_col.width);
            summary_col.width += expansion;
            remaining -= expansion;
        }
        max_summary_len = summary_col.width;
    }

    // Drop low-priority columns to give Summary more space. Columns with
    // effective priority > Summary's (10) are dropped based on priority distance:
    // - Within 4 levels (Commit 11, Time 12, Message 13): dropped when Summary < 50
    // - Beyond 4 levels (e.g., no-data Path 17): dropped when Summary < MAX_SUMMARY
    // No-data columns naturally qualify via EMPTY_PENALTY (e.g., Path 7+10=17).
    let summary_priority = ColumnKind::Summary.priority();
    while max_summary_len > 0 && max_summary_len < MAX_SUMMARY {
        let drop_pos = pending
            .iter()
            .enumerate()
            .filter(|(_, col)| {
                if col.spec.kind == ColumnKind::Summary || col.priority <= summary_priority {
                    return false;
                }
                let gap = col.priority - summary_priority;
                let threshold = if gap <= 4 {
                    SUMMARY_THRESHOLD_FOR_LOW_PRIORITY
                } else {
                    MAX_SUMMARY
                };
                max_summary_len < threshold
            })
            .max_by_key(|(_, col)| col.priority)
            .map(|(i, _)| i);

        let Some(pos) = drop_pos else { break };

        let reclaimed = pending[pos].width + spacing;
        pending.remove(pos);
        remaining += reclaimed;

        if let Some(summary_col) = pending
            .iter_mut()
            .find(|col| col.spec.kind == ColumnKind::Summary)
        {
            let expansion = remaining.min(MAX_SUMMARY - summary_col.width);
            summary_col.width += expansion;
            remaining -= expansion;
            max_summary_len = summary_col.width;
        }
    }

    let mut max_message_len = 0;
    if let Some(message_col) = pending
        .iter_mut()
        .find(|col| col.spec.kind == ColumnKind::Message)
    {
        if message_col.width < MAX_MESSAGE && remaining > 0 {
            let expansion = remaining.min(MAX_MESSAGE - message_col.width);
            message_col.width += expansion;
        }
        max_message_len = message_col.width;
    }

    // Sort by display order to maintain correct visual order
    pending.sort_by_key(|col| column_display_index(col.spec.kind));

    // Build final column layouts with positions
    let gap = 2;
    let mut position = 0;
    let mut columns = Vec::new();

    for col in pending {
        let start = if columns.is_empty() {
            0
        } else {
            // No gap after gutter column - its content includes the spacing
            let prev_was_gutter = columns
                .last()
                .map(|c: &ColumnLayout| c.kind == ColumnKind::Gutter)
                .unwrap_or(false);
            if prev_was_gutter {
                position
            } else {
                position + gap
            }
        };
        position = start + col.width;

        columns.push(ColumnLayout {
            kind: col.spec.kind,
            header: col.spec.kind.header(),
            start,
            width: col.width,
            format: col.format,
        });
    }

    // Count how many columns were hidden (not allocated).
    // This includes both data columns and empty columns that could show with more width.
    let allocated_kinds: std::collections::HashSet<_> =
        columns.iter().map(|col| col.kind).collect();
    let hidden_column_count = candidate_kinds
        .iter()
        .filter(|kind| !allocated_kinds.contains(kind))
        .count();

    LayoutConfig {
        columns,
        main_worktree_path,
        max_message_len,
        max_summary_len,
        hidden_column_count,
        status_position_mask: metadata.status_position_mask,
    }
}

/// Calculate responsive layout from basic worktree info.
///
/// Uses pre-allocated width estimates for expensive-to-compute columns (status, diffs, time, CI).
/// This is faster than scanning all data and provides consistent layout between buffered and
/// progressive modes. Values exceeding estimates use compact notation (K suffix).
///
/// Fast to compute from actual data:
/// - Branch names (from worktrees and standalone branches)
/// - Paths (relative to main worktree)
///
/// Pre-allocated estimates (generous to minimize truncation):
/// - Status: 8 chars (PositionMask::FULL, 7 positions)
/// - Working diff: 9 chars ("+999 -999")
/// - Ahead/behind: 7 chars ("↑99 ↓99")
/// - Branch diff: 9 chars ("+999 -999")
/// - Upstream: 7 chars ("↑99 ↓99")
/// - Age: 4 chars ("11mo" short format)
/// - CI: 1 char (indicator symbol)
/// - Message: flexible (20-100 chars)
/// - URL: estimated from template + longest branch
pub fn calculate_layout_from_basics(
    items: &[super::model::ListItem],
    skip_tasks: &HashSet<TaskKind>,
    main_worktree_path: &Path,
    url_template: Option<&str>,
) -> LayoutConfig {
    calculate_layout_with_width(
        items,
        skip_tasks,
        terminal_width(),
        main_worktree_path,
        url_template,
    )
}

/// Calculate layout with explicit width (for contexts like skim where available width differs)
pub fn calculate_layout_with_width(
    items: &[super::model::ListItem],
    skip_tasks: &HashSet<TaskKind>,
    terminal_width: usize,
    main_worktree_path: &Path,
    url_template: Option<&str>,
) -> LayoutConfig {
    // Calculate actual widths for things we know
    // Include branch names from both worktrees and standalone branches
    let longest_branch = items
        .iter()
        .filter_map(|item| item.branch.as_deref())
        .max_by_key(|b| b.width());

    let max_branch = longest_branch.map(|b| b.width()).unwrap_or(0);
    let max_branch = fit_header(ColumnKind::Branch.header(), max_branch);

    let path_data_width = items
        .iter()
        .filter_map(|item| item.worktree_path())
        .map(|path| shorten_path(path.as_path(), main_worktree_path).width())
        .max()
        .unwrap_or(0);
    let max_path_width = fit_header(ColumnKind::Path.header(), path_data_width);

    // Check if any worktree has a branch-worktree mismatch.
    // Path column is only useful when there's a mismatch; otherwise it's redundant with branch.
    let has_branch_worktree_mismatch = items
        .iter()
        .filter_map(|item| item.worktree_data())
        .any(|data| data.branch_worktree_mismatch);

    // Estimate URL width from template (heuristic, no expansion needed)
    let url_width = estimate_url_width(url_template, supports_hyperlinks(Stream::Stdout));

    // Build pre-allocated width estimates (same as buffered mode)
    let metadata = build_estimated_widths(
        max_branch,
        skip_tasks,
        has_branch_worktree_mismatch,
        url_width,
    );

    let commit_width = fit_header(ColumnKind::Commit.header(), COMMIT_HASH_WIDTH);

    allocate_columns_with_priority(
        &metadata,
        skip_tasks,
        max_path_width,
        commit_width,
        terminal_width,
        main_worktree_path.to_path_buf(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use worktrunk::git::LineDiff;

    #[test]
    fn test_fit_header() {
        // Data wider than header - return data width
        assert_eq!(fit_header("Age", 10), 10);

        // Header wider than data - return header width
        assert_eq!(fit_header("Branch", 3), 6);

        // Empty data - return header width
        assert_eq!(fit_header("Status", 0), 6);

        // Equal widths
        assert_eq!(fit_header("Path", 4), 4);
    }

    #[test]
    fn test_try_allocate() {
        // First column doesn't need spacing
        let mut remaining = 100;
        let allocated = try_allocate(&mut remaining, 20, None, 2, true);
        assert_eq!(allocated, 20);
        assert_eq!(remaining, 80);

        // Subsequent columns need spacing
        let allocated = try_allocate(&mut remaining, 15, None, 2, false);
        assert_eq!(allocated, 15);
        assert_eq!(remaining, 63); // 80 - 15 - 2

        // Zero width returns 0
        let mut remaining = 50;
        assert_eq!(try_allocate(&mut remaining, 0, None, 2, false), 0);
        assert_eq!(remaining, 50);

        // Insufficient space returns 0 (no min_width)
        let mut remaining = 10;
        assert_eq!(try_allocate(&mut remaining, 20, None, 2, false), 0);
        assert_eq!(remaining, 10);
    }

    #[test]
    fn test_try_allocate_with_min_width() {
        // Ideal fits: allocate ideal
        let mut remaining = 30;
        let allocated = try_allocate(&mut remaining, 20, Some(6), 2, false);
        assert_eq!(allocated, 20);
        assert_eq!(remaining, 8); // 30 - 20 - 2

        // Ideal doesn't fit, but min does: allocate whatever fits
        let mut remaining = 15;
        let allocated = try_allocate(&mut remaining, 20, Some(6), 2, false);
        assert_eq!(allocated, 13); // 15 - 2 spacing = 13 available
        assert_eq!(remaining, 0);

        // Neither ideal nor min fits: return 0
        let mut remaining = 5;
        let allocated = try_allocate(&mut remaining, 20, Some(6), 2, false);
        assert_eq!(allocated, 0);
        assert_eq!(remaining, 5);

        // First column with min_width (no spacing cost)
        let mut remaining = 10;
        let allocated = try_allocate(&mut remaining, 20, Some(6), 2, true);
        assert_eq!(allocated, 10); // all remaining space
        assert_eq!(remaining, 0);
    }

    #[test]
    fn test_column_kind_has_data() {
        let all_true = ColumnDataFlags {
            status: true,
            working_diff: true,
            ahead_behind: true,
            branch_diff: true,
            upstream: true,
            url: true,
            ci_status: true,
            path: true,
        };
        let all_false = ColumnDataFlags {
            status: false,
            working_diff: false,
            ahead_behind: false,
            branch_diff: false,
            upstream: false,
            url: false,
            ci_status: false,
            path: false,
        };

        // Always-have-data columns
        assert!(ColumnKind::Gutter.has_data(&all_false));
        assert!(ColumnKind::Branch.has_data(&all_false));
        assert!(ColumnKind::Time.has_data(&all_false));
        assert!(ColumnKind::Commit.has_data(&all_false));
        assert!(ColumnKind::Message.has_data(&all_false));

        // Flag-dependent columns
        assert!(ColumnKind::Status.has_data(&all_true));
        assert!(!ColumnKind::Status.has_data(&all_false));
        assert!(ColumnKind::WorkingDiff.has_data(&all_true));
        assert!(!ColumnKind::WorkingDiff.has_data(&all_false));
        assert!(ColumnKind::AheadBehind.has_data(&all_true));
        assert!(!ColumnKind::AheadBehind.has_data(&all_false));
        assert!(ColumnKind::BranchDiff.has_data(&all_true));
        assert!(!ColumnKind::BranchDiff.has_data(&all_false));
        assert!(ColumnKind::Upstream.has_data(&all_true));
        assert!(!ColumnKind::Upstream.has_data(&all_false));
        assert!(ColumnKind::Url.has_data(&all_true));
        assert!(!ColumnKind::Url.has_data(&all_false));
        assert!(ColumnKind::CiStatus.has_data(&all_true));
        assert!(!ColumnKind::CiStatus.has_data(&all_false));
        assert!(ColumnKind::Path.has_data(&all_true));
        assert!(!ColumnKind::Path.has_data(&all_false));
    }

    #[test]
    fn test_column_kind_diff_display_config() {
        // Diff columns have config
        assert!(ColumnKind::WorkingDiff.diff_display_config().is_some());
        assert!(ColumnKind::BranchDiff.diff_display_config().is_some());
        assert!(ColumnKind::AheadBehind.diff_display_config().is_some());
        assert!(ColumnKind::Upstream.diff_display_config().is_some());

        // Non-diff columns don't have config
        assert!(ColumnKind::Branch.diff_display_config().is_none());
        assert!(ColumnKind::Status.diff_display_config().is_none());
        assert!(ColumnKind::Path.diff_display_config().is_none());
        assert!(ColumnKind::Time.diff_display_config().is_none());
        assert!(ColumnKind::Message.diff_display_config().is_none());
        assert!(ColumnKind::Commit.diff_display_config().is_none());
        assert!(ColumnKind::CiStatus.diff_display_config().is_none());

        // Check variants
        let working = ColumnKind::WorkingDiff.diff_display_config().unwrap();
        assert!(matches!(working.variant, DiffVariant::Signs));

        let ahead = ColumnKind::AheadBehind.diff_display_config().unwrap();
        assert!(matches!(ahead.variant, DiffVariant::Arrows));

        let upstream = ColumnKind::Upstream.diff_display_config().unwrap();
        assert!(matches!(upstream.variant, DiffVariant::UpstreamArrows));
    }

    #[test]
    fn test_column_kind_ideal() {
        let widths = ColumnWidths {
            branch: 15,
            status: 8,
            time: 4,
            url: 0,
            ci_status: 2,
            ahead_behind: DiffWidths {
                total: 7,
                positive_digits: 2,
                negative_digits: 2,
            },
            working_diff: DiffWidths {
                total: 9,
                positive_digits: 3,
                negative_digits: 3,
            },
            branch_diff: DiffWidths {
                total: 9,
                positive_digits: 3,
                negative_digits: 3,
            },
            upstream: DiffWidths {
                total: 7,
                positive_digits: 2,
                negative_digits: 2,
            },
        };

        // Text columns return (width, ColumnFormat::Text)
        let (w, fmt) = ColumnKind::Gutter.ideal(&widths, 20, 8).unwrap();
        assert_eq!(w, 2);
        assert!(matches!(fmt, ColumnFormat::Text));

        let (w, fmt) = ColumnKind::Branch.ideal(&widths, 20, 8).unwrap();
        assert_eq!(w, 15);
        assert!(matches!(fmt, ColumnFormat::Text));

        let (w, fmt) = ColumnKind::Status.ideal(&widths, 20, 8).unwrap();
        assert_eq!(w, 8);
        assert!(matches!(fmt, ColumnFormat::Text));

        let (w, fmt) = ColumnKind::Path.ideal(&widths, 20, 8).unwrap();
        assert_eq!(w, 20);
        assert!(matches!(fmt, ColumnFormat::Text));

        let (w, fmt) = ColumnKind::Time.ideal(&widths, 20, 8).unwrap();
        assert_eq!(w, 4);
        assert!(matches!(fmt, ColumnFormat::Text));

        let (w, fmt) = ColumnKind::Commit.ideal(&widths, 20, 8).unwrap();
        assert_eq!(w, 8);
        assert!(matches!(fmt, ColumnFormat::Text));

        // Flexible columns return None (handled specially in allocation loop)
        assert!(ColumnKind::Summary.ideal(&widths, 20, 8).is_none());
        assert!(ColumnKind::Message.ideal(&widths, 20, 8).is_none());

        // Diff columns return (width, ColumnFormat::Diff(_))
        let (w, fmt) = ColumnKind::WorkingDiff.ideal(&widths, 20, 8).unwrap();
        assert_eq!(w, 9);
        assert!(matches!(fmt, ColumnFormat::Diff(_)));

        let (w, fmt) = ColumnKind::AheadBehind.ideal(&widths, 20, 8).unwrap();
        assert_eq!(w, 7);
        assert!(matches!(fmt, ColumnFormat::Diff(_)));

        // Zero width returns None
        let zero_widths = ColumnWidths {
            branch: 0,
            status: 0,
            time: 0,
            url: 0,
            ci_status: 0,
            ahead_behind: DiffWidths {
                total: 0,
                positive_digits: 0,
                negative_digits: 0,
            },
            working_diff: DiffWidths {
                total: 0,
                positive_digits: 0,
                negative_digits: 0,
            },
            branch_diff: DiffWidths {
                total: 0,
                positive_digits: 0,
                negative_digits: 0,
            },
            upstream: DiffWidths {
                total: 0,
                positive_digits: 0,
                negative_digits: 0,
            },
        };
        assert!(ColumnKind::Branch.ideal(&zero_widths, 0, 0).is_none());
        assert!(ColumnKind::WorkingDiff.ideal(&zero_widths, 0, 0).is_none());
    }

    #[test]
    fn test_pre_allocated_width_estimates() {
        // Test that build_estimated_widths() returns correct pre-allocated estimates
        // Empty skip set means all tasks are computed (equivalent to --full)
        // has_branch_worktree_mismatch=true to test the path flag is passed through
        // url_width=0 since we're not testing URL column here
        let metadata = build_estimated_widths(20, &HashSet::new(), true, 0);
        let widths = metadata.widths;

        // Line diffs (Signs variant: +/-) allocate 3 digits for 100-999 range
        // Format: "+999 -999" = 1+3+1+1+3 = 9, header "HEAD±" is 5, so total is 9
        assert_eq!(
            widths.working_diff.total, 9,
            "Working diff should pre-allocate for '+999 -999' (9 chars)"
        );
        assert_eq!(
            widths.working_diff.positive_digits, 3,
            "Pre-allocated for 3-digit positive count"
        );
        assert_eq!(
            widths.working_diff.negative_digits, 3,
            "Pre-allocated for 3-digit negative count"
        );

        // Branch diff also uses Signs variant when show_full=true
        // Format: "+999 -999" = 9, header "main…±" is 6, so total is 9
        assert_eq!(
            widths.branch_diff.total, 9,
            "Branch diff should pre-allocate for '+999 -999' (9 chars)"
        );
        assert_eq!(
            widths.branch_diff.positive_digits, 3,
            "Pre-allocated for 3-digit positive count"
        );
        assert_eq!(
            widths.branch_diff.negative_digits, 3,
            "Pre-allocated for 3-digit negative count"
        );

        // Commit counts (Arrows variant: ↑↓) use compact notation, allocate 2 digits
        // Format: "↑99 ↓99" = 1+2+1+1+2 = 7, header "main↕" is 5, so total is 7
        assert_eq!(
            widths.ahead_behind.total, 7,
            "Ahead/behind should pre-allocate for '↑99 ↓99' (7 chars)"
        );
        assert_eq!(
            widths.ahead_behind.positive_digits, 2,
            "Pre-allocated for 2-digit positive count (uses compact notation)"
        );
        assert_eq!(
            widths.ahead_behind.negative_digits, 2,
            "Pre-allocated for 2-digit negative count (uses compact notation)"
        );

        // Upstream also uses Arrows variant
        // Format: "↑99 ↓99" = 7, header "Remote⇅" is 7, so total is 7
        assert_eq!(
            widths.upstream.total, 7,
            "Upstream should pre-allocate for '↑99 ↓99' (7 chars)"
        );
        assert_eq!(
            widths.upstream.positive_digits, 2,
            "Pre-allocated for 2-digit positive count"
        );
        assert_eq!(
            widths.upstream.negative_digits, 2,
            "Pre-allocated for 2-digit negative count"
        );
    }

    #[test]
    fn test_visible_columns_follow_gap_rule() {
        use crate::commands::list::model::{
            ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields,
            ItemKind, ListItem, StatusSymbols, UpstreamStatus, WorktreeData,
        };

        // Create test data with specific widths to verify position calculation
        let item = ListItem {
            head: "abc12345".to_string(),
            branch: Some("feature".to_string()),
            commit: Some(CommitDetails {
                timestamp: 1234567890,
                commit_message: "Test commit message".to_string(),
            }),
            counts: Some(AheadBehind {
                ahead: 5,
                behind: 10,
            }),
            branch_diff: Some(BranchDiffTotals {
                diff: LineDiff::from((200, 30)),
            }),
            committed_trees_match: Some(false),
            has_file_changes: Some(true),
            would_merge_add: None,
            is_patch_id_match: None,
            is_ancestor: None,
            is_orphan: None,
            upstream: Some(UpstreamStatus {
                remote: Some("origin".to_string()),
                ahead: 4,
                behind: 2,
            }),
            pr_status: None,
            url: None,
            url_active: None,
            summary: None,
            status_symbols: Some(StatusSymbols::default()),
            display: DisplayFields::default(),
            kind: ItemKind::Worktree(Box::new(WorktreeData {
                path: PathBuf::from("/test/path"),
                detached: false,
                locked: None,
                prunable: None,
                working_tree_diff: Some(LineDiff::from((100, 50))),
                git_operation: ActiveGitOperation::None,
                is_main: false,
                is_current: false,
                is_previous: false,
                branch_worktree_mismatch: false,
                working_diff_display: None,
            })),
        };

        let items = vec![item];
        let skip_tasks: HashSet<TaskKind> = [TaskKind::BranchDiff, TaskKind::CiStatus]
            .into_iter()
            .collect();
        let main_worktree_path = PathBuf::from("/test");
        let layout = calculate_layout_from_basics(&items, &skip_tasks, &main_worktree_path, None);

        assert!(
            !layout.columns.is_empty(),
            "At least one column should be visible"
        );

        let mut columns_iter = layout.columns.iter();
        let first = columns_iter.next().expect("gutter column should exist");
        assert_eq!(
            first.kind,
            ColumnKind::Gutter,
            "Gutter column should be first"
        );
        assert_eq!(first.start, 0, "Gutter should begin at position 0");

        let mut previous_end = first.start + first.width;
        let mut prev_kind = first.kind;
        for column in columns_iter {
            // No gap after gutter column - its content includes the spacing
            let expected_gap = if prev_kind == ColumnKind::Gutter {
                0
            } else {
                2
            };
            assert_eq!(
                column.start,
                previous_end + expected_gap,
                "Columns should be separated by expected gap (0 after gutter, 2 otherwise)"
            );
            previous_end = column.start + column.width;
            prev_kind = column.kind;
        }

        // Path may or may not be visible depending on terminal width
        // At narrow widths (80 columns default in tests), Path may not fit
        if let Some(path_column) = layout
            .columns
            .iter()
            .find(|col| col.kind == ColumnKind::Path)
        {
            assert!(path_column.width > 0, "Path column must have width > 0");
        }
    }

    #[test]
    fn test_column_positions_with_empty_columns() {
        use crate::commands::list::model::{
            ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields,
            ItemKind, ListItem, StatusSymbols, UpstreamStatus, WorktreeData,
        };

        // Create minimal data - most columns will be empty
        let item = ListItem {
            head: "abc12345".to_string(),
            branch: Some("main".to_string()),
            commit: Some(CommitDetails {
                timestamp: 1234567890,
                commit_message: "Test".to_string(),
            }),
            counts: Some(AheadBehind {
                ahead: 0,
                behind: 0,
            }),
            branch_diff: Some(BranchDiffTotals {
                diff: LineDiff::default(),
            }),
            committed_trees_match: Some(false),
            has_file_changes: Some(true),
            would_merge_add: None,
            is_patch_id_match: None,
            is_ancestor: None,
            is_orphan: None,
            upstream: Some(UpstreamStatus::default()),
            pr_status: None,
            url: None,
            url_active: None,
            summary: None,
            status_symbols: Some(StatusSymbols::default()),
            display: DisplayFields::default(),
            kind: ItemKind::Worktree(Box::new(WorktreeData {
                path: PathBuf::from("/test"),
                detached: false,
                locked: None,
                prunable: None,
                working_tree_diff: Some(LineDiff::default()),
                git_operation: ActiveGitOperation::None,
                is_main: true, // Primary worktree: no ahead/behind shown
                is_current: false,
                is_previous: false,
                branch_worktree_mismatch: false,
                working_diff_display: None,
            })),
        };

        let items = vec![item];
        let skip_tasks: HashSet<TaskKind> = [TaskKind::BranchDiff, TaskKind::CiStatus]
            .into_iter()
            .collect();
        let main_worktree_path = PathBuf::from("/home/user/project");
        let layout = calculate_layout_from_basics(&items, &skip_tasks, &main_worktree_path, None);

        assert!(
            layout
                .columns
                .first()
                .map(|col| col.kind == ColumnKind::Gutter && col.start == 0)
                .unwrap_or(false),
            "Gutter column should start at position 0"
        );

        // Path visibility depends on terminal width and column priorities
        // At narrow widths (80 columns default in tests), Path may not fit
    }

    #[test]
    fn test_estimate_url_width_no_template() {
        assert_eq!(estimate_url_width(None, false), 0);
        assert_eq!(estimate_url_width(None, true), 0);
    }

    #[test]
    fn test_estimate_url_width_with_hash_port() {
        let template = "http://localhost:{{ branch | hash_port }}";

        // Without hyperlinks: full URL width from template expansion
        // Replaces {{ branch | hash_port }} with "12345" → "http://localhost:12345" = 22
        assert_eq!(estimate_url_width(Some(template), false), 22);

        // With hyperlinks: compact port display ":12345" = 6
        assert_eq!(estimate_url_width(Some(template), true), 6);
    }

    #[test]
    fn test_estimate_url_width_with_branch_variable() {
        // Template with branch variable but no port
        let template = "http://localhost/{{ branch }}";

        // Without hyperlinks: full URL width from template expansion
        // Replaces {{ branch }} with "feature-xx" → "http://localhost/feature-xx" = 27
        assert_eq!(estimate_url_width(Some(template), false), 27);

        // With hyperlinks: no port pattern, so still uses template estimation
        assert_eq!(estimate_url_width(Some(template), true), 27);
    }

    #[test]
    fn test_estimate_url_width_static_template() {
        let template = "http://localhost:3000";

        // Without hyperlinks: template length = 21
        assert_eq!(estimate_url_width(Some(template), false), 21);

        // With hyperlinks: has static port, compact display ":3000" = 6
        assert_eq!(estimate_url_width(Some(template), true), 6);
    }

    #[test]
    fn test_estimate_url_width_port_pattern() {
        let template = "http://localhost:{{ port }}";

        // Without hyperlinks: template length (no branch/hash_port replacement)
        assert_eq!(estimate_url_width(Some(template), false), template.len());

        // With hyperlinks: has ":{{" pattern, compact display = 6
        assert_eq!(estimate_url_width(Some(template), true), 6);
    }

    // --- Flexible column (Summary/Message) allocation tests ---

    /// Helper: create a minimal ListItem for layout tests.
    fn make_test_item(branch: &str) -> super::super::model::ListItem {
        use crate::commands::list::model::{
            ActiveGitOperation, DisplayFields, ItemKind, WorktreeData,
        };
        super::super::model::ListItem {
            head: "abc12345".to_string(),
            branch: Some(branch.to_string()),
            commit: None,
            counts: None,
            branch_diff: None,
            committed_trees_match: None,
            has_file_changes: None,
            would_merge_add: None,
            is_patch_id_match: None,
            is_ancestor: None,
            is_orphan: None,
            upstream: None,
            pr_status: None,
            url: None,
            url_active: None,
            summary: None,
            status_symbols: None,
            display: DisplayFields::default(),
            kind: ItemKind::Worktree(Box::new(WorktreeData {
                path: PathBuf::from("/test/wt"),
                detached: false,
                locked: None,
                prunable: None,
                working_tree_diff: None,
                git_operation: ActiveGitOperation::None,
                is_main: false,
                is_current: false,
                is_previous: false,
                branch_worktree_mismatch: false,
                working_diff_display: None,
            })),
        }
    }

    /// Helper: compute layout with explicit terminal width and skip_tasks.
    fn layout_at_width(width: usize, skip_tasks: &HashSet<TaskKind>) -> LayoutConfig {
        let items = vec![make_test_item("feature-branch")];
        calculate_layout_with_width(&items, skip_tasks, width, Path::new("/test"), None)
    }

    /// Default skip_tasks for non-full mode (Summary, BranchDiff, CI, WorkingTreeConflicts skipped).
    fn non_full_skip_tasks() -> HashSet<TaskKind> {
        [
            TaskKind::BranchDiff,
            TaskKind::CiStatus,
            TaskKind::WorkingTreeConflicts,
            TaskKind::SummaryGenerate,
        ]
        .into_iter()
        .collect()
    }

    /// Full mode skip_tasks (nothing skipped).
    fn full_skip_tasks() -> HashSet<TaskKind> {
        HashSet::new()
    }

    fn find_column(layout: &LayoutConfig, kind: ColumnKind) -> Option<&ColumnLayout> {
        layout.columns.iter().find(|c| c.kind == kind)
    }

    #[test]
    fn test_summary_absent_when_skipped() {
        // Non-full mode: SummaryGenerate in skip_tasks → no Summary column
        let layout = layout_at_width(200, &non_full_skip_tasks());

        assert!(
            find_column(&layout, ColumnKind::Summary).is_none(),
            "Summary should not appear when SummaryGenerate is skipped"
        );
        assert_eq!(layout.max_summary_len, 0);

        // Message should still be present and get leftover space
        assert!(find_column(&layout, ColumnKind::Message).is_some());
        assert!(layout.max_message_len > 0);
    }

    #[test]
    fn test_summary_present_in_full_mode() {
        let layout = layout_at_width(200, &full_skip_tasks());

        assert!(
            find_column(&layout, ColumnKind::Summary).is_some(),
            "Summary should appear in full mode"
        );
        assert!(layout.max_summary_len > 0);
    }

    #[test]
    fn test_summary_expands_before_message() {
        // At a moderate width, Summary should expand toward its max (70)
        // before Message gets leftover space.
        let layout = layout_at_width(200, &full_skip_tasks());

        let summary = find_column(&layout, ColumnKind::Summary);
        let message = find_column(&layout, ColumnKind::Message);

        assert!(summary.is_some(), "Summary should be allocated");
        assert!(message.is_some(), "Message should be allocated");

        let summary_width = summary.unwrap().width;
        let message_width = message.unwrap().width;

        // Summary should have expanded beyond its minimum of 10
        assert!(
            summary_width > 10,
            "Summary should expand beyond minimum: got {summary_width}"
        );
        assert_eq!(layout.max_summary_len, summary_width);
        assert_eq!(layout.max_message_len, message_width);
    }

    #[test]
    fn test_summary_capped_at_max() {
        // Very wide terminal: Summary should cap at MAX_SUMMARY (70)
        let layout = layout_at_width(500, &full_skip_tasks());

        let summary = find_column(&layout, ColumnKind::Summary).unwrap();
        assert_eq!(summary.width, 70, "Summary should cap at MAX_SUMMARY (70)");
        assert_eq!(layout.max_summary_len, 70);
    }

    #[test]
    fn test_message_capped_at_max() {
        // Very wide terminal: Message should cap at MAX_MESSAGE (100)
        let layout = layout_at_width(500, &full_skip_tasks());

        let message = find_column(&layout, ColumnKind::Message).unwrap();
        assert_eq!(
            message.width, 100,
            "Message should cap at MAX_MESSAGE (100)"
        );
        assert_eq!(layout.max_message_len, 100);
    }

    #[test]
    fn test_message_gets_more_space_when_summary_skipped() {
        // Compare Message width with and without Summary
        let with_summary = layout_at_width(200, &full_skip_tasks());
        let without_summary = layout_at_width(200, &non_full_skip_tasks());

        let msg_with = find_column(&with_summary, ColumnKind::Message)
            .unwrap()
            .width;
        let msg_without = find_column(&without_summary, ColumnKind::Message)
            .unwrap()
            .width;

        // Without Summary, Message should get more space (or equal if both maxed)
        assert!(
            msg_without >= msg_with,
            "Message should get at least as much space without Summary: \
             with={msg_with}, without={msg_without}"
        );
    }

    #[test]
    fn test_summary_display_order() {
        // Summary should appear between BranchDiff and Upstream in display order
        let layout = layout_at_width(500, &full_skip_tasks());

        let kinds: Vec<ColumnKind> = layout.columns.iter().map(|c| c.kind).collect();

        if let Some(summary_pos) = kinds.iter().position(|k| *k == ColumnKind::Summary) {
            // Summary should come after BranchDiff (if present) and before Upstream (if present)
            if let Some(branch_diff_pos) = kinds.iter().position(|k| *k == ColumnKind::BranchDiff) {
                assert!(
                    summary_pos > branch_diff_pos,
                    "Summary should appear after BranchDiff"
                );
            }
            if let Some(upstream_pos) = kinds.iter().position(|k| *k == ColumnKind::Upstream) {
                assert!(
                    summary_pos < upstream_pos,
                    "Summary should appear before Upstream"
                );
            }
        } else {
            panic!("Summary column should be present at width 500");
        }
    }

    #[test]
    fn test_low_priority_columns_gated_on_summary_threshold() {
        // Probe widths: when Summary is present but < 50, Commit/Time/Message must be absent.
        // At wide widths where Summary >= 50, they can appear.
        let mut found_below = false;
        for width in 80..200 {
            let l = layout_at_width(width, &full_skip_tasks());
            if let Some(s) = find_column(&l, ColumnKind::Summary)
                && s.width < 50
            {
                found_below = true;
                assert!(
                    find_column(&l, ColumnKind::Commit).is_none(),
                    "Commit present at width {width} with Summary {}",
                    s.width
                );
                assert!(
                    find_column(&l, ColumnKind::Time).is_none(),
                    "Time present at width {width} with Summary {}",
                    s.width
                );
                assert!(
                    find_column(&l, ColumnKind::Message).is_none(),
                    "Message present at width {width} with Summary {}",
                    s.width
                );
            }
        }
        assert!(found_below, "no width produced Summary < 50");

        // At 200, Summary is well above threshold and all columns appear.
        let l = layout_at_width(200, &full_skip_tasks());
        assert!(find_column(&l, ColumnKind::Summary).unwrap().width >= 50);
        assert!(find_column(&l, ColumnKind::Commit).is_some());
        assert!(find_column(&l, ColumnKind::Time).is_some());
        assert!(find_column(&l, ColumnKind::Message).is_some());
    }

    #[test]
    fn test_narrow_terminal_drops_flexible_columns() {
        // At a very narrow width, neither Summary nor Message should fit
        // after the critical fixed columns are allocated.
        let layout = layout_at_width(40, &full_skip_tasks());

        // At 40 chars, only Gutter (2) + Branch (~14) can fit
        assert!(
            find_column(&layout, ColumnKind::Summary).is_none(),
            "Summary should not fit at 40 chars"
        );
        assert!(
            find_column(&layout, ColumnKind::Message).is_none(),
            "Message should not fit at 40 chars"
        );
    }

    /// Helper: create a test item with a specific worktree path and no mismatch.
    fn make_test_item_at(branch: &str, path: &str) -> super::super::model::ListItem {
        use crate::commands::list::model::{
            ActiveGitOperation, DisplayFields, ItemKind, WorktreeData,
        };
        super::super::model::ListItem {
            head: "abc12345".to_string(),
            branch: Some(branch.to_string()),
            commit: None,
            counts: None,
            branch_diff: None,
            committed_trees_match: None,
            has_file_changes: None,
            would_merge_add: None,
            is_patch_id_match: None,
            is_ancestor: None,
            is_orphan: None,
            upstream: None,
            pr_status: None,
            url: None,
            url_active: None,
            summary: None,
            status_symbols: None,
            display: DisplayFields::default(),
            kind: ItemKind::Worktree(Box::new(WorktreeData {
                path: PathBuf::from(path),
                detached: false,
                locked: None,
                prunable: None,
                working_tree_diff: None,
                git_operation: ActiveGitOperation::None,
                is_main: false,
                is_current: false,
                is_previous: false,
                branch_worktree_mismatch: false,
                working_diff_display: None,
            })),
        }
    }

    /// When paths are consistent (no mismatch), Path should yield space to Summary.
    ///
    /// Scenario: 4 worktrees with `../agents.*` sibling paths (longest ~28 chars),
    /// full mode, moderate terminal width. Path is redundant (paths are predictable
    /// from branch names) and should not reduce Summary's readability.
    ///
    /// At very wide terminals both columns coexist. At moderate widths where space
    /// is constrained, Summary should be preferred over Path.
    #[test]
    fn test_path_yields_to_summary_when_no_mismatch() {
        // Mirrors the user's real setup: worktrees at sibling dirs with consistent naming
        let items = vec![
            {
                let mut item = make_test_item_at("main", "/test/worktrunk");
                if let super::super::model::ItemKind::Worktree(ref mut data) = item.kind {
                    data.is_main = true;
                }
                item
            },
            make_test_item_at("hourly-maintenance", "/test/agents.hourly-maintenance"),
            make_test_item_at("lab-continue", "/test/agents.lab-continue"),
            make_test_item_at("dry-run-pager", "/test/agents.dry-run-pager"),
        ];
        let main_path = Path::new("/test/worktrunk");

        // Full mode: all columns enabled
        let skip = full_skip_tasks();

        // At very wide terminals: both Path and Summary coexist
        let layout_wide = calculate_layout_with_width(&items, &skip, 300, main_path, None);
        assert!(
            find_column(&layout_wide, ColumnKind::Summary).is_some(),
            "Summary should be present at 300"
        );
        assert!(
            find_column(&layout_wide, ColumnKind::Path).is_some(),
            "Path should be present at 300 (infinite space → show everything)"
        );

        // At moderate widths (170): Summary should reach at least 50 chars.
        // Currently Path eats ~30 chars from Summary's expansion budget,
        // leaving Summary at ~48 and dropping Message entirely.
        let layout_170 = calculate_layout_with_width(&items, &skip, 170, main_path, None);
        let summary_170 = find_column(&layout_170, ColumnKind::Summary)
            .expect("Summary should be present at 170")
            .width;
        assert!(
            summary_170 >= 50,
            "Summary should reach at least 50 at width 170 when paths are consistent: got {summary_170}"
        );
    }

    /// Snapshot test rendering the motivating case: 4 worktrees with consistent
    /// paths, full mode, 170-char terminal. Verifies Summary gets adequate space
    /// by dropping redundant Path column.
    #[test]
    fn test_snapshot_path_yields_to_summary() {
        use crate::commands::list::model::{
            ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields,
            ItemKind, StatusSymbols, UpstreamStatus, WorktreeData,
        };
        use worktrunk::git::LineDiff;

        let ts = 1742500000; // fixed timestamp for reproducible "Age"

        let make_item = |branch: &str,
                         path: &str,
                         is_main: bool,
                         is_current: bool,
                         ahead: usize,
                         behind: usize,
                         diff: Option<(usize, usize)>,
                         summary: Option<&str>,
                         upstream: bool|
         -> super::super::model::ListItem {
            let counts = if is_main {
                None
            } else {
                Some(AheadBehind { ahead, behind })
            };
            let branch_diff = diff.map(|(a, d)| BranchDiffTotals {
                diff: LineDiff::from((a, d)),
            });
            let upstream_status = upstream.then(|| UpstreamStatus {
                remote: Some("origin".to_string()),
                ahead: 0,
                behind: 0,
            });
            super::super::model::ListItem {
                head: "a620bcfe".to_string(),
                branch: Some(branch.to_string()),
                commit: Some(CommitDetails {
                    timestamp: ts,
                    commit_message: "Some commit message".to_string(),
                }),
                counts,
                branch_diff,
                committed_trees_match: None,
                has_file_changes: None,
                would_merge_add: None,
                is_patch_id_match: None,
                is_ancestor: None,
                is_orphan: None,
                upstream: upstream_status,
                pr_status: Some(None), // loaded, no CI
                url: None,
                url_active: None,
                summary: Some(summary.map(|s| s.to_string())),
                status_symbols: Some(StatusSymbols::default()),
                display: DisplayFields::default(),
                kind: ItemKind::Worktree(Box::new(WorktreeData {
                    path: PathBuf::from(path),
                    detached: false,
                    locked: None,
                    prunable: None,
                    working_tree_diff: Some(LineDiff::default()),
                    git_operation: ActiveGitOperation::None,
                    is_main,
                    is_current,
                    is_previous: false,
                    branch_worktree_mismatch: false,
                    working_diff_display: None,
                })),
            }
        };

        let items = vec![
            make_item(
                "main",
                "/test/worktrunk",
                true,
                true,
                0,
                0,
                None,
                None,
                true,
            ),
            make_item(
                "hourly-maintenance",
                "/test/agents.hourly-maintenance",
                false,
                false,
                2,
                0,
                None,
                None,
                false,
            ),
            make_item(
                "lab-continue",
                "/test/agents.lab-continue",
                false,
                false,
                1,
                2,
                Some((28, 1)),
                Some("Add extend and block insert in Markdown parser"),
                true,
            ),
            make_item(
                "dry-run-pager",
                "/test/agents.dry-run-pager",
                false,
                false,
                3,
                1,
                None,
                None,
                true,
            ),
        ];
        let main_path = Path::new("/test/worktrunk");
        let skip = full_skip_tasks();

        let layout = calculate_layout_with_width(&items, &skip, 170, main_path, None);

        let mut lines = Vec::new();
        lines.push(layout.render_header_line().plain_text());
        for item in &items {
            lines.push(layout.render_list_item_line(item).plain_text());
        }
        let table = lines.join("\n");
        insta::assert_snapshot!(table);
    }

    #[test]
    fn test_branch_column_never_dropped() {
        // Branch is shrinkable: it should always be present, even at narrow widths
        // where its ideal width (longest branch name) doesn't fit.
        let items = vec![make_test_item(
            "feature/very-long-branch-name-that-exceeds-available-space",
        )];
        let skip = non_full_skip_tasks();
        let main_path = Path::new("/test");

        // At 30 cols, ideal branch width (~57) can't fit, but Branch should still
        // be allocated at a reduced width rather than dropped.
        let layout = calculate_layout_with_width(&items, &skip, 30, main_path, None);
        let branch = find_column(&layout, ColumnKind::Branch);
        assert!(
            branch.is_some(),
            "Branch column should never be dropped, even at 30 cols"
        );
        let branch_width = branch.unwrap().width;
        assert!(
            branch_width >= 6,
            "Branch should be at least header width (6): got {branch_width}"
        );

        // At 80 cols, Branch should fit comfortably
        let layout = calculate_layout_with_width(&items, &skip, 80, main_path, None);
        let branch = find_column(&layout, ColumnKind::Branch).unwrap();
        assert!(
            branch.width > 6,
            "Branch should have more than header width at 80 cols"
        );
    }

    #[test]
    fn test_summary_skipped_preserves_other_full_columns() {
        // Even with SummaryGenerate skipped, other full-mode columns should still appear
        let mut skip_only_summary: HashSet<TaskKind> = HashSet::new();
        skip_only_summary.insert(TaskKind::SummaryGenerate);

        let layout = layout_at_width(300, &skip_only_summary);

        assert!(
            find_column(&layout, ColumnKind::Summary).is_none(),
            "Summary should be skipped"
        );
        assert!(
            find_column(&layout, ColumnKind::BranchDiff).is_some(),
            "BranchDiff should still appear"
        );
        assert!(
            find_column(&layout, ColumnKind::CiStatus).is_some(),
            "CiStatus should still appear"
        );
        assert!(
            find_column(&layout, ColumnKind::Message).is_some(),
            "Message should still appear"
        );
    }
}