stakk 1.12.0

A CLI tool that bridges Jujutsu (jj) bookmarks to GitHub stacked pull requests
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
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
//! Screen 2: Bookmark assignment widget.
//!
//! Shows commits on the selected trunk→leaf path. Users can toggle existing
//! bookmarks on/off and generate new `stakk-<change_id>` bookmarks for
//! unmarked commits. Space/b cycles through state *types* (one stop per type);
//! r/R cycles *within* a state (existing bookmarks, TF-IDF variations).

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Color;
use ratatui::style::Modifier;
use ratatui::style::Style;
use ratatui::text::Line;
use ratatui::text::Span;
use ratatui::widgets::Widget;

use super::BookmarkAssignment;
use super::bookmark_gen;
use super::graph_layout::LayoutNode;
use super::tfidf;
use crate::jj::types::Signature;

/// Whether the user-input row is in normal mode or edit (typing) mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
    /// Not typing — normal key dispatch.
    Normal,
    /// Actively typing into the bookmark name field.
    Editing,
}

/// Whether a custom bookmark name is still loading or has been resolved.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CustomNameState {
    /// Waiting for the external command to return a name.
    Loading,
    /// The name has been resolved.
    Ready(String),
}

/// State for a TF-IDF generated bookmark name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TfidfNameState {
    /// The computed name.
    pub name: String,
    /// Which variation index produced this name.
    pub variation: usize,
}

/// The inclusion state of a bookmark row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RowState {
    /// Included in submission using the existing bookmark at the given index
    /// into `BookmarkRow::existing_bookmarks`.
    UseExisting(usize),
    /// Included in submission; a new stakk-xxx bookmark will be created.
    UseGenerated,
    /// Included in submission; a TF-IDF generated name from commit data.
    UseTfidf(TfidfNameState),
    /// Included in submission; a custom name from the bookmark command.
    UseCustom(CustomNameState),
    /// Included in submission; a user-typed bookmark name.
    UserInput(String),
    /// Excluded from submission.
    Unchecked,
}

/// A row in the bookmark assignment view.
#[derive(Debug, Clone)]
pub struct BookmarkRow {
    /// The jj change ID.
    pub change_id: String,
    /// Shortest unique change ID prefix (from jj).
    pub short_change_id: String,
    /// The jj commit ID.
    pub commit_id: String,
    /// The commit summary (first line of description).
    pub summary: String,
    /// Full commit description.
    pub description: String,
    /// Existing bookmark names on this change (may be empty).
    pub existing_bookmarks: Vec<String>,
    /// Whether and how this row is included in the submission.
    pub state: RowState,
    /// Generated bookmark name (`stakk-<change_id_prefix>`).
    pub generated_name: Option<String>,
    /// Custom name from the bookmark command (populated lazily).
    pub custom_name: Option<String>,
    /// TF-IDF name and its variation index (computed on demand).
    pub tfidf_name: Option<(String, usize)>,
    /// Cached user-typed bookmark name (preserved across state cycles).
    pub user_input_name: Option<String>,
    /// Cached index into `existing_bookmarks` (preserved across state cycles).
    pub existing_bookmark_idx: usize,
    /// Whether this is the trunk row (not toggleable).
    pub is_trunk: bool,
    /// Author signature.
    pub author: Signature,
    /// Files changed by this commit.
    pub files: Vec<String>,
    /// Whether a bookmark command is configured.
    pub has_bookmark_command: bool,
}

impl BookmarkRow {
    /// Get the effective bookmark name for this row.
    #[cfg_attr(not(test), expect(dead_code, reason = "used in tests for validation"))]
    pub fn effective_name(&self) -> Option<&str> {
        if self.is_trunk {
            return None;
        }
        match &self.state {
            RowState::UseExisting(idx) => self.existing_bookmarks.get(*idx).map(String::as_str),
            RowState::UseGenerated => self.generated_name.as_deref(),
            RowState::UseTfidf(ts) => Some(ts.name.as_str()),
            RowState::UseCustom(CustomNameState::Ready(name)) => Some(name.as_str()),
            RowState::UserInput(s) if !s.is_empty() => Some(s.as_str()),
            RowState::UserInput(_)
            | RowState::UseCustom(CustomNameState::Loading)
            | RowState::Unchecked => None,
        }
    }
}

/// Reasons why the selection cannot be confirmed.
#[derive(Debug)]
pub enum SelectionError {
    /// Two included rows resolved to the same bookmark name.
    DuplicateName(String),
    /// A custom name is still being computed.
    StillLoading,
    /// A user-typed bookmark name failed validation.
    InvalidName(String),
}

/// Result of a [`BookmarkAssignmentState::vary_current`] call.
#[derive(Debug, PartialEq, Eq)]
pub enum VaryResult {
    /// Nothing to vary (not on a variable state, or only one option).
    Noop,
    /// Cycled to a different existing bookmark.
    ExistingCycled,
    /// TF-IDF variation was cycled successfully.
    TfidfCycled,
    /// No other TF-IDF variation produced a different name.
    TfidfNoVariation,
    /// Custom name needs re-firing the external command.
    NeedsRefire,
}

/// Build `UseCustom` state from a row's cached custom name.
fn make_use_custom(row: &BookmarkRow) -> RowState {
    match &row.custom_name {
        Some(name) => RowState::UseCustom(CustomNameState::Ready(name.clone())),
        None => RowState::UseCustom(CustomNameState::Loading),
    }
}

/// Compute a TF-IDF bookmark name for a dynamic segment, with optional prefix.
fn compute_tfidf_for_segment(
    rows: &[BookmarkRow],
    row_idx: usize,
    variation: usize,
    auto_prefix: Option<&str>,
) -> Option<String> {
    let segment = bookmark_gen::dynamic_segment_commits(rows, row_idx);
    let commit_data: Vec<tfidf::CommitData<'_>> = segment
        .iter()
        .map(|r| tfidf::CommitData {
            description: &r.description,
            files: &r.files,
        })
        .collect();

    // Reserve space for the prefix in the max length budget.
    let prefix_len = auto_prefix.map_or(0, str::len);
    let max_length = bookmark_gen::MAX_BOOKMARK_LENGTH.saturating_sub(prefix_len);

    let name = tfidf::tfidf_bookmark_name(
        &commit_data,
        3,
        variation,
        max_length,
        bookmark_gen::DISALLOWED_CHARS,
    )?;

    match auto_prefix {
        Some(prefix) => Some(format!("{prefix}{name}")),
        None => Some(name),
    }
}

/// State for the bookmark assignment widget.
#[derive(Debug)]
pub struct BookmarkAssignmentState {
    /// The rows, in trunk-to-leaf order.
    pub rows: Vec<BookmarkRow>,
    /// Currently selected row index.
    pub cursor: usize,
    /// Optional prefix for auto-generated (TF-IDF) bookmark names.
    auto_prefix: Option<String>,
    /// Whether the user is currently typing into a `UserInput` row.
    pub input_mode: InputMode,
}

impl BookmarkAssignmentState {
    /// Build state from a path of layout nodes (trunk-to-leaf order).
    pub fn from_path(
        path: &[&LayoutNode],
        has_bookmark_command: bool,
        auto_prefix: Option<&str>,
    ) -> Self {
        let rows: Vec<BookmarkRow> = path
            .iter()
            .map(|node| {
                let existing_bookmarks = node.bookmark_names.clone();
                let generated_name = if node.is_trunk {
                    None
                } else {
                    Some(bookmark_gen::default_bookmark_name(&node.change_id))
                };
                let state = if existing_bookmarks.is_empty() {
                    RowState::Unchecked
                } else {
                    RowState::UseExisting(0)
                };

                BookmarkRow {
                    change_id: node.change_id.clone(),
                    short_change_id: node.short_change_id.clone(),
                    commit_id: node.commit_id.clone(),
                    summary: node.summary.clone(),
                    description: node.description.clone(),
                    existing_bookmarks,
                    state,
                    generated_name,
                    custom_name: None,
                    tfidf_name: None,
                    user_input_name: None,
                    is_trunk: node.is_trunk,
                    author: node.author.clone(),
                    files: node.files.clone(),
                    has_bookmark_command,
                    existing_bookmark_idx: 0,
                }
            })
            .collect();

        // Start cursor on the first non-trunk row.
        let cursor = rows.iter().position(|r| !r.is_trunk).unwrap_or(0);

        Self {
            rows,
            cursor,
            auto_prefix: auto_prefix.map(String::from),
            input_mode: InputMode::Normal,
        }
    }

    /// Toggle the state of the current row through the cycle.
    ///
    /// The cycle is: `UseExisting(0..N-1)` → `UseTfidf` → `UseGenerated`
    /// → `UseCustom` → `Unchecked` → back to start.
    ///
    /// - `UseTfidf` is skipped when it produces `None` or matches an
    ///   existing/generated name.
    /// - `UseGenerated` is skipped when it matches an existing bookmark.
    /// - `UseCustom` is skipped when no bookmark command is configured, or if
    ///   the custom name matches the generated or any existing name.
    ///
    /// When toggling to `UseCustom`, the state is set to
    /// `UseCustom(Loading)` — the caller (`app.rs`) is responsible for
    /// firing the command and filling in the real name.
    pub fn toggle_current(&mut self) {
        let cursor = self.cursor;
        let Some(row) = self.rows.get(cursor) else {
            return;
        };
        if row.is_trunk {
            return;
        }

        let has_distinct_generated = match &row.generated_name {
            Some(generated) => !row.existing_bookmarks.iter().any(|e| e == generated),
            None => false,
        };

        let has_distinct_custom = row.has_bookmark_command
            && match &row.custom_name {
                Some(custom) => {
                    let matches_generated = row.generated_name.as_ref() == Some(custom);
                    let matches_existing = row.existing_bookmarks.iter().any(|e| e == custom);
                    !matches_generated && !matches_existing
                }
                // No cached custom name yet — include UseCustom so it can be
                // resolved lazily.
                None => true,
            };

        let current_state = row.state.clone();

        // Compute next state. For UseTfidf, we need to compute from the
        // full rows slice, so we do that after releasing the borrow.
        let next = match &current_state {
            RowState::UseExisting(idx) => {
                self.rows[cursor].existing_bookmark_idx = *idx;
                self.next_after_existing(cursor)
            }
            RowState::UseTfidf(_) => self.next_after_tfidf(cursor),
            RowState::UserInput(text) => {
                // Cache typed text before leaving.
                self.rows[cursor].user_input_name = Some(text.clone());
                self.next_after_user_input(cursor, has_distinct_generated, has_distinct_custom)
            }
            RowState::UseGenerated => {
                if has_distinct_custom {
                    make_use_custom(&self.rows[cursor])
                } else {
                    RowState::Unchecked
                }
            }
            RowState::UseCustom(_) => RowState::Unchecked,
            RowState::Unchecked => {
                if row.existing_bookmarks.is_empty() {
                    self.next_after_existing(cursor)
                } else {
                    RowState::UseExisting(row.existing_bookmark_idx)
                }
            }
        };

        self.rows[cursor].state = next;

        // A toggle may change the dynamic segment for other UseTfidf rows
        // (e.g. toggling an earlier commit on/off changes which commits are
        // included in a later segment). Refresh all TF-IDF names.
        self.refresh_tfidf_names();
    }

    /// Toggle the state of the current row backward through the cycle.
    ///
    /// The reverse cycle is: `Unchecked` → `UseCustom` → `UseGenerated`
    /// → `UseTfidf` → `UseExisting(N-1..0)` → back to `Unchecked`.
    ///
    /// Skipping rules mirror `toggle_current`: states that produce no name
    /// or a duplicate name are skipped.
    pub fn toggle_current_reverse(&mut self) {
        let cursor = self.cursor;
        let Some(row) = self.rows.get(cursor) else {
            return;
        };
        if row.is_trunk {
            return;
        }

        let has_distinct_generated = match &row.generated_name {
            Some(generated) => !row.existing_bookmarks.iter().any(|e| e == generated),
            None => false,
        };

        let has_distinct_custom = row.has_bookmark_command
            && match &row.custom_name {
                Some(custom) => {
                    let matches_generated = row.generated_name.as_ref() == Some(custom);
                    let matches_existing = row.existing_bookmarks.iter().any(|e| e == custom);
                    !matches_generated && !matches_existing
                }
                None => true,
            };

        let current_state = row.state.clone();

        let prev = match &current_state {
            RowState::Unchecked => {
                self.prev_before_unchecked(cursor, has_distinct_generated, has_distinct_custom)
            }
            RowState::UseCustom(_) => {
                if has_distinct_generated {
                    RowState::UseGenerated
                } else {
                    self.prev_before_generated(cursor)
                }
            }
            RowState::UseGenerated => self.prev_before_generated(cursor),
            RowState::UserInput(text) => {
                // Cache typed text before leaving.
                self.rows[cursor].user_input_name = Some(text.clone());
                self.prev_before_user_input(cursor)
            }
            RowState::UseTfidf(_) => {
                if row.existing_bookmarks.is_empty() {
                    RowState::Unchecked
                } else {
                    RowState::UseExisting(row.existing_bookmark_idx)
                }
            }
            RowState::UseExisting(idx) => {
                self.rows[cursor].existing_bookmark_idx = *idx;
                RowState::Unchecked
            }
        };

        self.rows[cursor].state = prev;
        self.refresh_tfidf_names();
    }

    /// Compute the previous state before `Unchecked`: try `UseCustom`, then
    /// `UseGenerated`, then `UserInput`, then `UseTfidf`, then last
    /// `UseExisting`.
    fn prev_before_unchecked(
        &mut self,
        cursor: usize,
        has_distinct_generated: bool,
        has_distinct_custom: bool,
    ) -> RowState {
        if has_distinct_custom {
            return make_use_custom(&self.rows[cursor]);
        }
        if has_distinct_generated {
            return RowState::UseGenerated;
        }
        self.prev_before_generated(cursor)
    }

    /// Compute the previous state before `UseGenerated`: always `UserInput`.
    fn prev_before_generated(&mut self, cursor: usize) -> RowState {
        RowState::UserInput(
            self.rows[cursor]
                .user_input_name
                .clone()
                .unwrap_or_default(),
        )
    }

    /// Compute the previous state before `UserInput`: try `UseTfidf`, then
    /// last `UseExisting`, then `Unchecked`.
    fn prev_before_user_input(&mut self, cursor: usize) -> RowState {
        let cached_variation = self.rows[cursor].tfidf_name.as_ref().map_or(0, |(_, v)| *v);
        if let Some(tfidf_state) = self.try_make_tfidf(cursor, cached_variation) {
            return RowState::UseTfidf(tfidf_state);
        }
        let row = &self.rows[cursor];
        if row.existing_bookmarks.is_empty() {
            RowState::Unchecked
        } else {
            RowState::UseExisting(row.existing_bookmark_idx)
        }
    }

    /// Compute the next state after exhausting existing bookmarks (or from
    /// Unchecked with no existing bookmarks): try `UseTfidf`, then
    /// `UseGenerated`, then `UseCustom`, then `Unchecked`.
    fn next_after_existing(&mut self, cursor: usize) -> RowState {
        let cached_variation = self.rows[cursor].tfidf_name.as_ref().map_or(0, |(_, v)| *v);
        if let Some(tfidf_state) = self.try_make_tfidf(cursor, cached_variation) {
            return RowState::UseTfidf(tfidf_state);
        }
        self.next_after_tfidf(cursor)
    }

    /// Compute the next state after `UseTfidf`: always `UserInput`.
    fn next_after_tfidf(&mut self, cursor: usize) -> RowState {
        RowState::UserInput(
            self.rows[cursor]
                .user_input_name
                .clone()
                .unwrap_or_default(),
        )
    }

    /// Compute the next state after `UserInput`: try `UseGenerated`, then
    /// `UseCustom`, then `Unchecked`.
    fn next_after_user_input(
        &self,
        cursor: usize,
        has_distinct_generated: bool,
        has_distinct_custom: bool,
    ) -> RowState {
        if has_distinct_generated {
            return RowState::UseGenerated;
        }
        if has_distinct_custom {
            return make_use_custom(&self.rows[cursor]);
        }
        RowState::Unchecked
    }

    /// Try to compute a TF-IDF name for the given row. Returns `None` if
    /// it produces no name or the name matches an existing/generated name.
    fn try_make_tfidf(&mut self, cursor: usize, variation: usize) -> Option<TfidfNameState> {
        let name =
            compute_tfidf_for_segment(&self.rows, cursor, variation, self.auto_prefix.as_deref())?;

        let row = &self.rows[cursor];
        // Skip if it matches the generated name.
        if row.generated_name.as_ref() == Some(&name) {
            return None;
        }
        // Skip if it matches an existing bookmark.
        if row.existing_bookmarks.iter().any(|e| e == &name) {
            return None;
        }

        self.rows[cursor].tfidf_name = Some((name.clone(), variation));
        Some(TfidfNameState { name, variation })
    }

    /// Vary the current row's name within its current state type (cycle
    /// existing bookmarks, TF-IDF variations, or re-fire custom command).
    pub fn vary_current(&mut self) -> VaryResult {
        let cursor = self.cursor;
        let Some(row) = self.rows.get(cursor) else {
            return VaryResult::Noop;
        };
        if row.is_trunk {
            return VaryResult::Noop;
        }

        match &row.state {
            RowState::UseExisting(idx) => {
                let count = self.rows[cursor].existing_bookmarks.len();
                if count <= 1 {
                    return VaryResult::Noop;
                }
                let new_idx = (idx + 1) % count;
                self.rows[cursor].state = RowState::UseExisting(new_idx);
                self.rows[cursor].existing_bookmark_idx = new_idx;
                VaryResult::ExistingCycled
            }
            RowState::UseTfidf(ts) => {
                let old_variation = ts.variation;
                // Try up to 6 variations.
                for delta in 1..=6 {
                    let new_variation = (old_variation + delta) % 6;
                    if let Some(tfidf_state) = self.try_make_tfidf(cursor, new_variation) {
                        self.rows[cursor].state = RowState::UseTfidf(tfidf_state);
                        return VaryResult::TfidfCycled;
                    }
                }
                VaryResult::TfidfNoVariation
            }
            RowState::UseCustom(_) => {
                // Invalidate cached custom name and set to Loading.
                self.rows[cursor].custom_name = None;
                self.rows[cursor].state = RowState::UseCustom(CustomNameState::Loading);
                VaryResult::NeedsRefire
            }
            _ => VaryResult::Noop,
        }
    }

    /// Vary the current row's name backward (cycle existing bookmarks or
    /// TF-IDF variations in reverse, or re-fire custom command).
    pub fn vary_current_reverse(&mut self) -> VaryResult {
        let cursor = self.cursor;
        let Some(row) = self.rows.get(cursor) else {
            return VaryResult::Noop;
        };
        if row.is_trunk {
            return VaryResult::Noop;
        }

        match &row.state {
            RowState::UseExisting(idx) => {
                let count = self.rows[cursor].existing_bookmarks.len();
                if count <= 1 {
                    return VaryResult::Noop;
                }
                let new_idx = (idx + count - 1) % count;
                self.rows[cursor].state = RowState::UseExisting(new_idx);
                self.rows[cursor].existing_bookmark_idx = new_idx;
                VaryResult::ExistingCycled
            }
            RowState::UseTfidf(ts) => {
                let old_variation = ts.variation;
                // Try up to 6 variations in reverse.
                for delta in 1..=6 {
                    let new_variation = (old_variation + 6 - delta) % 6;
                    if let Some(tfidf_state) = self.try_make_tfidf(cursor, new_variation) {
                        self.rows[cursor].state = RowState::UseTfidf(tfidf_state);
                        return VaryResult::TfidfCycled;
                    }
                }
                VaryResult::TfidfNoVariation
            }
            RowState::UseCustom(_) => {
                // Same as forward — invalidate and re-fire.
                self.rows[cursor].custom_name = None;
                self.rows[cursor].state = RowState::UseCustom(CustomNameState::Loading);
                VaryResult::NeedsRefire
            }
            _ => VaryResult::Noop,
        }
    }

    /// Recompute TF-IDF names for all `UseTfidf` rows whose dynamic segment
    /// may have changed (e.g. because an earlier row was toggled).
    pub fn refresh_tfidf_names(&mut self) {
        let tfidf_indices: Vec<(usize, usize)> = self
            .rows
            .iter()
            .enumerate()
            .filter_map(|(i, row)| match &row.state {
                RowState::UseTfidf(ts) => Some((i, ts.variation)),
                _ => None,
            })
            .collect();

        for (idx, variation) in tfidf_indices {
            let old_name = match &self.rows[idx].state {
                RowState::UseTfidf(ts) => ts.name.clone(),
                _ => continue,
            };

            // Recompute from the (potentially changed) dynamic segment.
            match compute_tfidf_for_segment(&self.rows, idx, variation, self.auto_prefix.as_deref())
            {
                Some(new_name) if new_name != old_name => {
                    self.rows[idx].tfidf_name = Some((new_name.clone(), variation));
                    self.rows[idx].state = RowState::UseTfidf(TfidfNameState {
                        name: new_name,
                        variation,
                    });
                }
                None => {
                    // Segment no longer produces a TF-IDF name — fall back to
                    // Unchecked.
                    self.rows[idx].tfidf_name = None;
                    self.rows[idx].state = RowState::Unchecked;
                }
                Some(_) => {} // Same name, nothing to do.
            }
        }
    }

    /// Move cursor up (toward leaf = visually up, higher index in rows).
    pub fn cursor_up(&mut self) {
        if self.cursor < self.rows.len().saturating_sub(1) {
            self.cursor += 1;
        }
    }

    /// Move cursor down (toward trunk = visually down, lower index in rows).
    pub fn cursor_down(&mut self) {
        if self.cursor > 0 {
            let next = self.cursor - 1;
            // Don't land on trunk unless it's the only row.
            if self.rows.get(next).is_some_and(|r| r.is_trunk) && self.rows.len() > 1 {
                return;
            }
            self.cursor = next;
        }
    }

    /// Enter edit mode if the current row is `UserInput`. Returns `true` if
    /// edit mode was entered.
    pub fn enter_edit_mode(&mut self) -> bool {
        let cursor = self.cursor;
        if let Some(row) = self.rows.get(cursor)
            && matches!(row.state, RowState::UserInput(_))
        {
            self.input_mode = InputMode::Editing;
            true
        } else {
            false
        }
    }

    /// Exit edit mode.
    pub fn exit_edit_mode(&mut self) {
        self.input_mode = InputMode::Normal;
    }

    /// Insert a character into the current `UserInput` buffer.
    ///
    /// Silently rejects disallowed characters, ASCII control characters, and
    /// input that would exceed `MAX_BOOKMARK_LENGTH`.
    pub fn insert_char(&mut self, ch: char) {
        if ch.is_ascii_control() || bookmark_gen::DISALLOWED_CHARS.contains(ch) {
            return;
        }
        let cursor = self.cursor;
        if let Some(row) = self.rows.get_mut(cursor)
            && let RowState::UserInput(ref mut buf) = row.state
            && buf.len() < bookmark_gen::MAX_BOOKMARK_LENGTH
        {
            buf.push(ch);
        }
    }

    /// Delete the last character from the current `UserInput` buffer.
    pub fn delete_char(&mut self) {
        let cursor = self.cursor;
        if let Some(row) = self.rows.get_mut(cursor)
            && let RowState::UserInput(ref mut buf) = row.state
        {
            buf.pop();
        }
    }

    /// Whether the widget is currently in edit mode.
    pub fn is_editing(&self) -> bool {
        self.input_mode == InputMode::Editing
    }

    /// Build the selection result from included rows.
    ///
    /// Returns `Err` with the duplicate bookmark name if any two included rows
    /// resolve to the same name, or if any row is still loading
    /// (`UseCustom(Loading)`).
    pub fn build_result(&self) -> Result<Vec<BookmarkAssignment>, SelectionError> {
        let mut assignments = Vec::new();
        let mut seen = std::collections::HashSet::new();

        for r in &self.rows {
            if r.is_trunk || r.state == RowState::Unchecked {
                continue;
            }

            let (bookmark_name, is_new) = match &r.state {
                RowState::UseExisting(idx) => (
                    r.existing_bookmarks
                        .get(*idx)
                        .cloned()
                        .expect("UseExisting index in bounds"),
                    false,
                ),
                RowState::UseGenerated => (
                    r.generated_name
                        .clone()
                        .expect("UseGenerated requires name"),
                    true,
                ),
                RowState::UseTfidf(ts) => (ts.name.clone(), true),
                RowState::UseCustom(CustomNameState::Loading) => {
                    return Err(SelectionError::StillLoading);
                }
                RowState::UseCustom(CustomNameState::Ready(name)) => (name.clone(), true),
                RowState::UserInput(s) if s.is_empty() => {
                    return Err(SelectionError::InvalidName(
                        "bookmark name is empty".to_string(),
                    ));
                }
                RowState::UserInput(s) => {
                    bookmark_gen::validate_bookmark_name(s)
                        .map_err(|e| SelectionError::InvalidName(format!("{s}: {e}")))?;
                    (s.clone(), true)
                }
                RowState::Unchecked => unreachable!("filtered above"),
            };

            if !seen.insert(bookmark_name.clone()) {
                return Err(SelectionError::DuplicateName(bookmark_name));
            }

            assignments.push(BookmarkAssignment {
                change_id: r.change_id.clone(),
                bookmark_name,
                is_new,
            });
        }

        Ok(assignments)
    }
}

/// Shorten a string to `max` chars by keeping the start and end, joined by `…`.
///
/// `"jq -r '.commits' | tr ' ' '-' | tr '[:upper:]' '[:lower:]'"` with max=14
/// becomes `"jq -r…lower']"`.
fn shorten_middle(s: &str, max: usize) -> String {
    let len = s.chars().count();
    if len <= max {
        return s.to_string();
    }
    // 1 char for `…`, split the rest ~evenly favoring the start.
    let budget = max.saturating_sub(1);
    let head = budget.div_ceil(2);
    let tail = budget / 2;
    let start: String = s.chars().take(head).collect();
    let end: String = s.chars().skip(len - tail).collect();
    format!("{start}\u{2026}{end}")
}

/// Renders the bookmark assignment screen.
pub struct BookmarkWidget<'a> {
    state: &'a BookmarkAssignmentState,
    spinner_tick: usize,
    bookmark_command: Option<&'a str>,
    /// Which row (if any) is currently being edited (user typing).
    editing_row: Option<usize>,
}

const SPINNER_FRAMES: &[&str] = &["", "", "", "", "", "", "", "", "", ""];

/// Max display width for the command label between spinners.
const COMMAND_LABEL_MAX: usize = 16;

impl<'a> BookmarkWidget<'a> {
    pub fn new(
        state: &'a BookmarkAssignmentState,
        spinner_tick: usize,
        bookmark_command: Option<&'a str>,
        editing_row: Option<usize>,
    ) -> Self {
        Self {
            state,
            spinner_tick,
            bookmark_command,
            editing_row,
        }
    }

    fn build_lines(&self) -> Vec<Line<'a>> {
        let mut lines = Vec::new();

        // Render rows in reverse (leaf at top, trunk at bottom).
        for (idx, row) in self.state.rows.iter().enumerate().rev() {
            let is_selected = idx == self.state.cursor;

            if row.is_trunk {
                let style = Style::default().fg(Color::DarkGray);
                lines.push(Line::from(vec![
                    Span::styled("      ", style),
                    Span::styled("\u{25c6} ", style), //                    Span::styled("trunk", style),
                ]));
                continue;
            }

            let node_char = "\u{25cb}"; //            let cursor_indicator = if is_selected { "> " } else { "  " };

            // Per-state checkbox symbol and color.
            let (checkbox, state_color, state_bold) = match &row.state {
                RowState::UseExisting(_) => ("[x]", Color::Green, true),
                RowState::UseGenerated => ("[+]", Color::Yellow, true),
                RowState::UseTfidf(_) => ("[~]", Color::Blue, true),
                RowState::UseCustom(_) => ("[*]", Color::Cyan, true),
                RowState::UserInput(_) => ("[>]", Color::LightYellow, true),
                RowState::Unchecked => ("[ ]", Color::DarkGray, false),
            };

            let name_str = match &row.state {
                RowState::UseExisting(idx) => row
                    .existing_bookmarks
                    .get(*idx)
                    .cloned()
                    .unwrap_or_default(),
                RowState::UseGenerated => row
                    .generated_name
                    .as_ref()
                    .map(|n| format!("{n} (generated)"))
                    .unwrap_or_default(),
                RowState::UseTfidf(ts) => {
                    format!("{} (auto [{}])", ts.name, ts.variation)
                }
                RowState::UseCustom(CustomNameState::Loading) => {
                    let frame = SPINNER_FRAMES[self.spinner_tick % SPINNER_FRAMES.len()];
                    let label = self
                        .bookmark_command
                        .map(|cmd| shorten_middle(cmd, COMMAND_LABEL_MAX))
                        .unwrap_or_default();
                    format!("{frame}{label}{frame}")
                }
                RowState::UseCustom(CustomNameState::Ready(name)) => {
                    format!("{name} (custom)")
                }
                RowState::UserInput(s) => {
                    let is_editing = self.editing_row == Some(idx);
                    if is_editing {
                        format!("{s}\u{2502}") // │ cursor char
                    } else if s.is_empty() {
                        "(i to type)".to_string()
                    } else {
                        format!("{s} (user)")
                    }
                }
                RowState::Unchecked => {
                    if let Some(first) = row.existing_bookmarks.first() {
                        first.clone()
                    } else {
                        "(Space to assign)".to_string()
                    }
                }
            };

            let cursor_style = if is_selected {
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::DarkGray)
            };

            let state_style = {
                let base = Style::default().fg(state_color);
                if state_bold {
                    base.add_modifier(Modifier::BOLD)
                } else {
                    base
                }
            };

            let summary_style = if is_selected {
                Style::default().fg(Color::White)
            } else {
                Style::default().fg(Color::DarkGray)
            };

            let mut spans = vec![
                Span::styled(cursor_indicator.to_string(), cursor_style),
                Span::styled(format!("{checkbox} "), state_style),
                Span::styled(format!("{node_char} "), state_style),
            ];

            if !name_str.is_empty() {
                // Use red for user-input text that fails validation.
                let name_style = if let RowState::UserInput(s) = &row.state
                    && !s.is_empty()
                    && self.editing_row == Some(idx)
                    && bookmark_gen::validate_bookmark_name(s).is_err()
                {
                    Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
                } else {
                    state_style
                };
                spans.push(Span::styled(format!("{name_str}  "), name_style));
            }

            let change_id_style = if is_selected {
                Style::default().fg(Color::Magenta)
            } else {
                Style::default().fg(Color::DarkGray)
            };
            spans.push(Span::styled(
                format!("{:<4} ", row.short_change_id),
                change_id_style,
            ));
            if row.summary == "(no description)" {
                spans.push(Span::styled(
                    "(no description set)",
                    Style::default().fg(Color::DarkGray),
                ));
            } else {
                spans.push(Span::styled(row.summary.clone(), summary_style));
            }

            lines.push(Line::from(spans));
        }

        lines
    }
}

impl Widget for BookmarkWidget<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let lines = self.build_lines();

        for (i, line) in lines.iter().take(area.height as usize).enumerate() {
            let y = area.y + u16::try_from(i).expect("line index fits in u16");
            buf.set_line(area.x, y, line, area.width);
        }
    }
}

/// Build a help line for the bottom of the bookmark view.
pub fn bookmark_help_line(
    has_bookmark_command: bool,
    editing: bool,
    current_row_state: Option<&RowState>,
    existing_count: usize,
) -> Line<'static> {
    let key_style = Style::default()
        .fg(Color::Yellow)
        .add_modifier(Modifier::BOLD);

    if editing {
        return Line::from(vec![
            Span::raw(" Type name  "),
            Span::styled("Backspace", key_style),
            Span::raw(" delete  "),
            Span::styled("Esc/Enter", key_style),
            Span::raw(" done"),
        ]);
    }

    let cycle = if has_bookmark_command {
        " [x]use \u{2192} [~]auto \u{2192} [>]type \u{2192} [+]new \u{2192} [*]custom \u{2192} [ \
         ]skip  "
    } else {
        " [x]use \u{2192} [~]auto \u{2192} [>]type \u{2192} [+]new \u{2192} [ ]skip  "
    };
    let mut spans = vec![
        Span::styled(" \u{2191}\u{2193}/jk", key_style),
        Span::raw(" navigate  "),
        Span::styled("Space/b", key_style),
        Span::raw(cycle),
    ];
    if matches!(current_row_state, Some(RowState::UserInput(_))) {
        spans.push(Span::styled("i", key_style));
        spans.push(Span::raw(" edit  "));
    }
    match current_row_state {
        Some(RowState::UseExisting(_)) if existing_count > 1 => {
            spans.push(Span::styled("r/R", key_style));
            spans.push(Span::raw(" cycle  "));
        }
        Some(RowState::UseTfidf(_)) => {
            spans.push(Span::styled("r/R", key_style));
            spans.push(Span::raw(" vary  "));
        }
        Some(RowState::UseCustom(_)) => {
            spans.push(Span::styled("r/R", key_style));
            spans.push(Span::raw(" regenerate  "));
        }
        _ => {}
    }
    spans.push(Span::styled("Enter", key_style));
    spans.push(Span::raw(" confirm  "));
    spans.push(Span::styled("Esc/q", key_style));
    spans.push(Span::raw(" back"));
    Line::from(spans)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::select::graph_layout::LayoutNode;

    fn make_node(
        change_id: &str,
        summary: &str,
        bookmarks: &[&str],
        is_trunk: bool,
        is_leaf: bool,
    ) -> LayoutNode {
        LayoutNode {
            row: 0,
            col: 0,
            change_id: change_id.to_string(),
            commit_id: format!("commit_{change_id}"),
            summary: summary.to_string(),
            description: summary.to_string(),
            bookmark_names: bookmarks.iter().map(ToString::to_string).collect(),
            is_trunk,
            is_leaf,
            stack_index: 0,
            short_change_id: change_id[..4.min(change_id.len())].to_string(),
            author: crate::jj::types::Signature {
                name: "Test".to_string(),
                email: "test@test.com".to_string(),
                timestamp: "T".to_string(),
            },
            files: vec![],
        }
    }

    #[test]
    fn generate_name_from_change_id() {
        assert_eq!(
            bookmark_gen::default_bookmark_name("abcdefghijklmnop"),
            "stakk-abcdefghijkl"
        );
        assert_eq!(bookmark_gen::default_bookmark_name("short"), "stakk-short");
    }

    #[test]
    fn state_from_path_marks_existing_bookmarks() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "add base", &["base"], false, false),
            make_node("ch_b", "add feature", &[], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let state = BookmarkAssignmentState::from_path(&refs, false, None);

        assert_eq!(state.rows.len(), 3);

        // Trunk is not toggleable.
        assert!(state.rows[0].is_trunk);

        // Base has existing bookmark → UseExisting(0); generated_name is always set
        // now.
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));
        assert_eq!(state.rows[1].existing_bookmarks, vec!["base".to_string()]);
        assert_eq!(state.rows[1].generated_name, Some("stakk-ch_a".to_string()));

        // Unmarked commit has generated name, Unchecked by default.
        assert_eq!(state.rows[2].state, RowState::Unchecked);
        assert!(state.rows[2].existing_bookmarks.is_empty());
        assert!(state.rows[2].generated_name.is_some());
    }

    #[test]
    fn toggle_checks_and_unchecks() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &["feat"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Cursor should start on the non-trunk row; starts UseExisting.
        assert_eq!(state.cursor, 1);
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));

        // Cycle: UseExisting → UseTfidf → UserInput → UseGenerated →
        // Unchecked. "work" is NOT a stop word, so TF-IDF produces a name.
        state.toggle_current();
        assert!(
            matches!(&state.rows[1].state, RowState::UseTfidf(_)),
            "expected UseTfidf, got {:?}",
            state.rows[1].state
        );

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UserInput(String::new()));

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UseGenerated);

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::Unchecked);

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));
    }

    #[test]
    fn reverse_toggle_checks_and_unchecks() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &["feat"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Starts UseExisting(0).
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));

        // Reverse: UseExisting(0) → Unchecked.
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::Unchecked);

        // Reverse: Unchecked → UseGenerated (no custom cmd).
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UseGenerated);

        // Reverse: UseGenerated → UserInput.
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UserInput(String::new()));

        // Reverse: UserInput → UseTfidf.
        state.toggle_current_reverse();
        assert!(
            matches!(&state.rows[1].state, RowState::UseTfidf(_)),
            "expected UseTfidf, got {:?}",
            state.rows[1].state
        );

        // Reverse: UseTfidf → UseExisting(0) (last existing, which is idx 0).
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));
    }

    #[test]
    fn reverse_toggle_multiple_existing() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node(
                "ch_a",
                "work",
                &["feature", "wip", "experiment"],
                false,
                true,
            ),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Forward to Unchecked first.
        // Space skips past all existing as one stop:
        // UseExisting(0) → UseTfidf → UserInput → UseGenerated → Unchecked.
        state.toggle_current();
        state.toggle_current();
        state.toggle_current();
        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::Unchecked);

        // Reverse from Unchecked: → UseGenerated (no custom cmd).
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UseGenerated);

        // → UserInput
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UserInput(String::new()));

        // → UseTfidf
        state.toggle_current_reverse();
        assert!(matches!(&state.rows[1].state, RowState::UseTfidf(_)));

        // → UseExisting(0) (cached index, single stop)
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));

        // → Unchecked (single stop, no cycling through indices)
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::Unchecked);
    }

    #[test]
    fn reverse_toggle_no_existing() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_x", "feature", &[], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        assert_eq!(state.rows[1].state, RowState::Unchecked);

        // Reverse: Unchecked → UseGenerated.
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UseGenerated);

        // Reverse: UseGenerated → UserInput.
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UserInput(String::new()));

        // Reverse: UserInput → UseTfidf.
        state.toggle_current_reverse();
        assert!(matches!(&state.rows[1].state, RowState::UseTfidf(_)));

        // Reverse: UseTfidf → Unchecked (no existing bookmarks).
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::Unchecked);
    }

    #[test]
    fn reverse_toggle_tfidf_skipped_when_all_stop_words() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_x", "add update remove", &[], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        assert_eq!(state.rows[1].state, RowState::Unchecked);

        // Reverse: Unchecked → UseGenerated (TF-IDF skipped).
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UseGenerated);

        // Reverse: UseGenerated → UserInput.
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UserInput(String::new()));

        // Reverse: UserInput → Unchecked (TF-IDF skipped, no existing).
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::Unchecked);
    }

    #[test]
    fn reverse_toggle_trunk_is_noop() {
        let nodes = [make_node("", "trunk", &[], true, false)];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);
        state.cursor = 0;
        let state_before = state.rows[0].state.clone();
        state.toggle_current_reverse();
        assert_eq!(state.rows[0].state, state_before);
    }

    #[test]
    fn forward_then_reverse_is_identity() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &["feat"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        let initial = state.rows[1].state.clone();
        state.toggle_current();
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, initial);
    }

    #[test]
    fn toggle_trunk_is_noop() {
        let nodes = [make_node("", "trunk", &[], true, false)];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);
        state.cursor = 0;
        let state_before = state.rows[0].state.clone();
        state.toggle_current();
        assert_eq!(state.rows[0].state, state_before);
    }

    #[test]
    fn toggle_two_state_when_names_match() {
        // change_id "abcdefghijkl" (12 chars) → generated "stakk-abcdefghijkl"
        // existing bookmark matches generated → UseGenerated skipped.
        // "work" → UseTfidf → UserInput → Unchecked (generated skipped).
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("abcdefghijkl", "work", &["stakk-abcdefghijkl"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        assert_eq!(state.rows[1].state, RowState::UseExisting(0));

        state.toggle_current();
        assert!(matches!(&state.rows[1].state, RowState::UseTfidf(_)));

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UserInput(String::new()));

        // UseGenerated skipped (matches existing) → Unchecked.
        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::Unchecked);

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));
    }

    #[test]
    fn toggle_no_existing_includes_tfidf() {
        // No existing bookmark → Unchecked → UseTfidf → UserInput →
        // UseGenerated → Unchecked. "feature" is NOT a stop word so TF-IDF
        // produces it.
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_x", "feature", &[], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        assert_eq!(state.rows[1].state, RowState::Unchecked);

        state.toggle_current();
        assert!(matches!(&state.rows[1].state, RowState::UseTfidf(_)));

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UserInput(String::new()));

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UseGenerated);

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::Unchecked);
    }

    #[test]
    fn toggle_tfidf_skipped_when_all_stop_words() {
        // Description is only stop words → TF-IDF produces None → skipped
        // to UserInput, then UseGenerated.
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_x", "add update remove", &[], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        assert_eq!(state.rows[1].state, RowState::Unchecked);

        // TF-IDF skipped → lands on UserInput.
        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UserInput(String::new()));

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UseGenerated);

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::Unchecked);
    }

    #[test]
    fn build_result_includes_only_checked() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "base", &["base"], false, false),
            make_node("ch_b", "middle", &[], false, false),
            make_node("ch_c", "leaf", &["leaf"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Toggle the middle (unmarked) commit: Unchecked → UseTfidf.
        // "middle" produces a TF-IDF name.
        state.cursor = 2;
        state.toggle_current();

        let result = state.build_result().unwrap();
        assert_eq!(result.len(), 3);
        assert_eq!(result[0].bookmark_name, "base");
        assert!(!result[0].is_new);
        // Middle now gets a TF-IDF name (not stakk-xxx).
        assert!(!result[1].bookmark_name.starts_with("stakk-"));
        assert!(result[1].is_new);
        assert_eq!(result[2].bookmark_name, "leaf");
        assert!(!result[2].is_new);
    }

    #[test]
    fn build_result_empty_when_all_unchecked() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &["feat"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Toggle to Unchecked: UseExisting → UseTfidf → UserInput →
        // UseGenerated → Unchecked.
        state.cursor = 1;
        state.toggle_current(); // UseTfidf
        state.toggle_current(); // UserInput
        state.toggle_current(); // UseGenerated
        state.toggle_current(); // Unchecked

        let result = state.build_result().unwrap();
        assert!(result.is_empty());
    }

    fn make_bare_row(state: RowState) -> BookmarkRow {
        BookmarkRow {
            change_id: "a".to_string(),
            short_change_id: "a".to_string(),
            commit_id: "commit_a".to_string(),
            summary: "work".to_string(),
            description: "work".to_string(),
            existing_bookmarks: vec!["feat".to_string()],
            state,
            generated_name: Some("stakk-aaaaaaaaaaaa".to_string()),
            user_input_name: None,
            existing_bookmark_idx: 0,
            custom_name: None,
            tfidf_name: None,
            is_trunk: false,
            author: crate::jj::types::Signature {
                name: "Test".to_string(),
                email: "test@test.com".to_string(),
                timestamp: "T".to_string(),
            },
            files: vec![],
            has_bookmark_command: false,
        }
    }

    #[test]
    fn effective_name_returns_correct_values() {
        let row_existing = make_bare_row(RowState::UseExisting(0));
        assert_eq!(row_existing.effective_name(), Some("feat"));

        let mut row_generated = make_bare_row(RowState::UseGenerated);
        row_generated.existing_bookmarks = vec![];
        row_generated.generated_name = Some("stakk-bbbbbbbbb".to_string());
        assert_eq!(row_generated.effective_name(), Some("stakk-bbbbbbbbb"));

        let row_unchecked = make_bare_row(RowState::Unchecked);
        assert_eq!(row_unchecked.effective_name(), None);

        let row_custom = make_bare_row(RowState::UseCustom(CustomNameState::Ready(
            "my-branch".to_string(),
        )));
        assert_eq!(row_custom.effective_name(), Some("my-branch"));

        let row_loading = make_bare_row(RowState::UseCustom(CustomNameState::Loading));
        assert_eq!(row_loading.effective_name(), None);
    }

    #[test]
    fn build_result_blocks_when_loading() {
        let mut row = make_bare_row(RowState::UseCustom(CustomNameState::Loading));
        // Ensure the row is not trunk so it's included.
        row.is_trunk = false;
        let state = BookmarkAssignmentState {
            rows: vec![row],
            cursor: 0,
            auto_prefix: None,
            input_mode: InputMode::Normal,
        };
        assert!(matches!(
            state.build_result(),
            Err(SelectionError::StillLoading)
        ));
    }

    #[test]
    fn bookmark_widget_renders_to_buffer() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "add feature", &["feat"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let state = BookmarkAssignmentState::from_path(&refs, false, None);
        let widget = BookmarkWidget::new(&state, 0, None, None);

        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);
        widget.render(area, &mut buf);

        let content: String = (0..area.height)
            .map(|y| {
                (0..area.width)
                    .map(|x| buf.cell((x, y)).unwrap().symbol().to_string())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");

        assert!(content.contains("[x]"), "expected checkbox in output");
        assert!(content.contains("feat"), "expected bookmark name in output");
    }

    #[test]
    fn toggle_multiple_existing_bookmarks() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node(
                "ch_a",
                "work",
                &["feature", "wip", "experiment"],
                false,
                true,
            ),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        assert_eq!(state.rows[1].state, RowState::UseExisting(0));

        // Space skips past all existing as one stop → UseTfidf.
        // "work" produces a TF-IDF name.
        state.toggle_current();
        assert!(matches!(&state.rows[1].state, RowState::UseTfidf(_)));

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UserInput(String::new()));

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UseGenerated);

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::Unchecked);

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));

        // r/R cycles within existing bookmarks.
        let r = state.vary_current();
        assert_eq!(r, VaryResult::ExistingCycled);
        assert_eq!(state.rows[1].state, RowState::UseExisting(1));

        let r = state.vary_current();
        assert_eq!(r, VaryResult::ExistingCycled);
        assert_eq!(state.rows[1].state, RowState::UseExisting(2));

        let r = state.vary_current();
        assert_eq!(r, VaryResult::ExistingCycled);
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));
    }

    #[test]
    fn toggle_multiple_existing_one_matches_generated() {
        // "feature" and "stakk-abcdefghijkl" are existing bookmarks.
        // generated is "stakk-abcdefghijkl" which matches existing[1],
        // so UseGenerated is skipped in the cycle.
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node(
                "abcdefghijkl",
                "work",
                &["feature", "stakk-abcdefghijkl"],
                false,
                true,
            ),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        assert_eq!(state.rows[1].state, RowState::UseExisting(0));

        // Space skips past all existing → UseTfidf.
        // "work" produces a TF-IDF name.
        state.toggle_current();
        assert!(matches!(&state.rows[1].state, RowState::UseTfidf(_)));

        // → UserInput.
        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UserInput(String::new()));

        // Generated matches existing[1], so skip UseGenerated → Unchecked.
        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::Unchecked);

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));
    }

    #[test]
    fn build_result_with_second_existing_bookmark() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &["alpha", "beta"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Use r/R (vary) to cycle from UseExisting(0) → UseExisting(1).
        let vary = state.vary_current();
        assert_eq!(vary, VaryResult::ExistingCycled);

        let result = state.build_result().unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].bookmark_name, "beta");
        assert!(!result[0].is_new);
    }

    #[test]
    fn state_from_path_preserves_all_bookmarks() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &["alpha", "beta", "gamma"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let state = BookmarkAssignmentState::from_path(&refs, false, None);

        assert_eq!(state.rows[1].existing_bookmarks.len(), 3);
        assert_eq!(state.rows[1].existing_bookmarks[0], "alpha");
        assert_eq!(state.rows[1].existing_bookmarks[1], "beta");
        assert_eq!(state.rows[1].existing_bookmarks[2], "gamma");
    }

    #[test]
    fn build_result_extracts_tfidf_name() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node(
                "ch_a",
                "implement caching layer for database queries",
                &[],
                false,
                true,
            ),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Unchecked → UseTfidf (auto is first after existing/unchecked).
        state.toggle_current();
        assert!(matches!(&state.rows[1].state, RowState::UseTfidf(_)));

        let result = state.build_result().unwrap();
        assert_eq!(result.len(), 1);
        assert!(result[0].is_new);
        // The name should not start with "stakk-".
        assert!(
            !result[0].bookmark_name.starts_with("stakk-"),
            "expected TF-IDF name, got: {}",
            result[0].bookmark_name
        );
    }

    #[test]
    fn vary_cycles_tfidf_variation() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node(
                "ch_a",
                "implement caching layer for database queries",
                &[],
                false,
                true,
            ),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Get to UseTfidf (first toggle from Unchecked).
        state.toggle_current();
        let v0_name = match &state.rows[1].state {
            RowState::UseTfidf(ts) => {
                assert_eq!(ts.variation, 0);
                ts.name.clone()
            }
            other => panic!("expected UseTfidf, got {other:?}"),
        };

        // Vary should cycle variation.
        let result = state.vary_current();
        assert_ne!(result, VaryResult::NeedsRefire);
        match &state.rows[1].state {
            RowState::UseTfidf(ts) => {
                // Variation changed (unless all variations produce the same
                // result, which is fine).
                assert!(ts.variation != 0 || ts.name == v0_name);
            }
            other => panic!("expected UseTfidf after vary, got {other:?}"),
        }
    }

    #[test]
    fn effective_name_for_tfidf() {
        let mut row = make_bare_row(RowState::UseTfidf(TfidfNameState {
            name: "caching-database-layer".to_string(),
            variation: 0,
        }));
        row.existing_bookmarks = vec![];
        assert_eq!(row.effective_name(), Some("caching-database-layer"));
    }

    #[test]
    fn auto_prefix_prepended_to_tfidf_name() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node(
                "ch_a",
                "implement caching layer for database queries",
                &[],
                false,
                true,
            ),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, Some("gb-"));

        // Unchecked → UseTfidf (auto is first).
        state.toggle_current();
        match &state.rows[1].state {
            RowState::UseTfidf(ts) => {
                assert!(
                    ts.name.starts_with("gb-"),
                    "expected prefix 'gb-', got: {}",
                    ts.name
                );
            }
            other => panic!("expected UseTfidf, got {other:?}"),
        }
    }

    #[test]
    fn tfidf_refreshes_when_earlier_row_toggled() {
        // Three commits: trunk → middle → leaf.
        // Both middle and leaf are unchecked initially.
        // Toggle leaf to UseTfidf — its segment includes middle.
        // Then toggle middle to UseGenerated — leaf's segment shrinks.
        // The TF-IDF name on leaf should be recomputed.
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_mid", "authentication middleware", &[], false, false),
            make_node("ch_leaf", "rate limiting endpoints", &[], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Get leaf to UseTfidf: Unchecked → UseTfidf (auto is first).
        state.cursor = 2;
        state.toggle_current();
        let leaf_name_with_middle = match &state.rows[2].state {
            RowState::UseTfidf(ts) => ts.name.clone(),
            other => panic!("expected UseTfidf on leaf, got {other:?}"),
        };

        // Now toggle middle (Unchecked → UseTfidf) — this changes leaf's
        // dynamic segment (middle is no longer unchecked, so leaf's segment
        // shrinks to just leaf).
        state.cursor = 1;
        state.toggle_current();

        // Leaf should still be UseTfidf but with a potentially different
        // name (fewer commits in segment).
        match &state.rows[2].state {
            RowState::UseTfidf(ts) => {
                // The name may or may not differ depending on term overlap,
                // but it should have been recomputed. At minimum, the state
                // is still UseTfidf (not stale).
                assert!(
                    !ts.name.is_empty(),
                    "refreshed TF-IDF name should not be empty"
                );
                // If the names differ, that confirms refresh happened.
                // If they're the same, it's because the terms overlap.
                let _ = leaf_name_with_middle; // suppress unused warning
            }
            RowState::Unchecked => {
                // Also valid: if the reduced segment produces no TF-IDF
                // name, it falls back to Unchecked.
            }
            other => panic!("expected UseTfidf or Unchecked on leaf after refresh, got {other:?}"),
        }
    }

    #[test]
    fn user_input_edit_mode_insert_and_delete() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &[], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Toggle to UserInput.
        state.toggle_current(); // UseTfidf or UserInput depending on tfidf availability.
        while !matches!(state.rows[1].state, RowState::UserInput(_)) {
            state.toggle_current();
        }

        // Enter edit mode.
        assert!(state.enter_edit_mode());
        assert!(state.is_editing());

        // Type a name.
        state.insert_char('m');
        state.insert_char('y');
        state.insert_char('-');
        state.insert_char('b');
        assert_eq!(state.rows[1].state, RowState::UserInput("my-b".to_string()));

        // Backspace.
        state.delete_char();
        assert_eq!(state.rows[1].state, RowState::UserInput("my-".to_string()));

        // Disallowed char silently rejected.
        state.insert_char(' ');
        assert_eq!(state.rows[1].state, RowState::UserInput("my-".to_string()));

        // Exit edit mode.
        state.exit_edit_mode();
        assert!(!state.is_editing());
    }

    #[test]
    fn user_input_text_preserved_across_cycles() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "feature", &[], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Toggle to UserInput.
        while !matches!(state.rows[1].state, RowState::UserInput(_)) {
            state.toggle_current();
        }

        // Type a name.
        state.enter_edit_mode();
        state.insert_char('x');
        state.insert_char('y');
        state.exit_edit_mode();

        // Cycle away.
        state.toggle_current(); // UseGenerated
        assert_eq!(state.rows[1].state, RowState::UseGenerated);

        // Cycle back through to UserInput — text should be preserved.
        state.toggle_current(); // Unchecked
        state.toggle_current(); // UseTfidf
        state.toggle_current(); // UserInput
        assert_eq!(state.rows[1].state, RowState::UserInput("xy".to_string()));
    }

    #[test]
    fn user_input_empty_is_error_on_confirm() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &[], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Toggle to UserInput (empty).
        while !matches!(state.rows[1].state, RowState::UserInput(_)) {
            state.toggle_current();
        }

        // Empty UserInput is an error on confirm.
        assert!(matches!(
            state.build_result(),
            Err(SelectionError::InvalidName(_))
        ));
    }

    #[test]
    fn user_input_valid_name_in_build_result() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &[], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // Toggle to UserInput.
        while !matches!(state.rows[1].state, RowState::UserInput(_)) {
            state.toggle_current();
        }

        state.enter_edit_mode();
        for c in "my-branch".chars() {
            state.insert_char(c);
        }
        state.exit_edit_mode();

        let result = state.build_result().unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].bookmark_name, "my-branch");
        assert!(result[0].is_new);
    }

    #[test]
    fn effective_name_for_user_input() {
        let row_empty = make_bare_row(RowState::UserInput(String::new()));
        assert_eq!(row_empty.effective_name(), None);

        let row_filled = make_bare_row(RowState::UserInput("my-branch".to_string()));
        assert_eq!(row_filled.effective_name(), Some("my-branch"));
    }

    #[test]
    fn enter_edit_mode_fails_on_non_user_input() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &["feat"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, false, None);

        // On UseExisting — edit mode should not enter.
        assert!(!state.enter_edit_mode());
        assert!(!state.is_editing());
    }

    #[test]
    fn toggle_with_custom_command() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &["feat"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, true, None);

        assert_eq!(state.cursor, 1);
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));

        // Cycle: UseExisting → UseTfidf → UserInput → UseGenerated →
        // UseCustom(Loading) → Unchecked → UseExisting.
        state.toggle_current();
        assert!(
            matches!(&state.rows[1].state, RowState::UseTfidf(_)),
            "expected UseTfidf, got {:?}",
            state.rows[1].state
        );

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UserInput(String::new()));

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UseGenerated);

        state.toggle_current();
        assert!(
            matches!(
                &state.rows[1].state,
                RowState::UseCustom(CustomNameState::Loading)
            ),
            "expected UseCustom(Loading), got {:?}",
            state.rows[1].state
        );

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::Unchecked);

        state.toggle_current();
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));
    }

    #[test]
    fn reverse_toggle_with_custom_command() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &["feat"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, true, None);

        assert_eq!(state.rows[1].state, RowState::UseExisting(0));

        // Reverse: UseExisting(0) → Unchecked.
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::Unchecked);

        // Reverse: Unchecked → UseCustom(Loading).
        state.toggle_current_reverse();
        assert!(
            matches!(
                &state.rows[1].state,
                RowState::UseCustom(CustomNameState::Loading)
            ),
            "expected UseCustom(Loading), got {:?}",
            state.rows[1].state
        );

        // Reverse: UseCustom → UseGenerated.
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UseGenerated);

        // Reverse: UseGenerated → UserInput.
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UserInput(String::new()));

        // Reverse: UserInput → UseTfidf.
        state.toggle_current_reverse();
        assert!(matches!(&state.rows[1].state, RowState::UseTfidf(_)));

        // Reverse: UseTfidf → UseExisting(0).
        state.toggle_current_reverse();
        assert_eq!(state.rows[1].state, RowState::UseExisting(0));
    }

    #[test]
    fn toggle_custom_skipped_when_matches_existing() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &["feat"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, true, None);

        // Pre-populate custom_name matching an existing bookmark.
        state.rows[1].custom_name = Some("feat".to_string());

        // Cycle to UseGenerated, then toggle should skip UseCustom →
        // Unchecked.
        state.toggle_current(); // UseTfidf
        state.toggle_current(); // UserInput
        state.toggle_current(); // UseGenerated
        state.toggle_current(); // Should skip UseCustom → Unchecked
        assert_eq!(state.rows[1].state, RowState::Unchecked);
    }

    #[test]
    fn toggle_custom_skipped_when_matches_generated() {
        let nodes = [
            make_node("", "trunk", &[], true, false),
            make_node("ch_a", "work", &["feat"], false, true),
        ];
        let refs: Vec<&LayoutNode> = nodes.iter().collect();
        let mut state = BookmarkAssignmentState::from_path(&refs, true, None);

        // Pre-populate custom_name matching the generated name.
        let gen_name = state.rows[1].generated_name.clone().unwrap();
        state.rows[1].custom_name = Some(gen_name);

        // Cycle to UseGenerated, then toggle should skip UseCustom →
        // Unchecked.
        state.toggle_current(); // UseTfidf
        state.toggle_current(); // UserInput
        state.toggle_current(); // UseGenerated
        state.toggle_current(); // Should skip UseCustom → Unchecked
        assert_eq!(state.rows[1].state, RowState::Unchecked);
    }
}