tix-tracker 0.11.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
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
use ratatui::Frame;
use ratatui::layout::{Position, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};
use unicode_width::UnicodeWidthChar;

use crate::model::Issue;

/// Byte offset of `char_index` in `value`, clamped to the value's length.
fn byte_offset(value: &str, char_index: usize) -> usize {
    value
        .char_indices()
        .nth(char_index)
        .map_or(value.len(), |(byte, _)| byte)
}

/// Whether `c` counts as part of a word for Ctrl-Left/Ctrl-Right and Ctrl-W.
fn is_word_char(c: char) -> bool {
    c.is_alphanumeric() || c == '_'
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormFocus {
    Title,
    Status,
    Priority,
    Labels,
    Assignee,
    Estimate,
    Cycles,
    Milestones,
    Reviewer,
    StartDate,
    DueDate,
    /// The parent issue (WP06 / T026). Appended **last**, not slotted next to
    /// `Assignee` where it would read better: every existing row's index is the
    /// identity of that row in `render_with_bindings`'s `fields` array, and
    /// inserting in the middle renumbers all five rows after it. Appending keeps
    /// the eleven existing indices stable, so no render or golden assertion moves.
    Parent,
    /// The entry target of the F4 New Issue mode (`tui-new-issue-mode`): Triage or
    /// Todo. Appended, per the rule above. It is a **toggle**, not a text field:
    /// Enter/Space flips it and Left/Right pick a side, and typing into it does
    /// nothing. Choosing a side writes the same status the submit path would use,
    /// so the Status row below stays the authoritative value.
    Target,
    /// The selected new-issue template's name, or empty for none. Enter/F2 opens
    /// the template picker (a scratch [`crate::ui::pickers::DropdownState`] over
    /// the configured `[templates.<name>]` names); selecting one pre-fills the
    /// rows. Not a free-text field: the value names a configured record.
    Template,
    /// The issue body (Markdown), which a template pre-fills. Editable like the
    /// other text rows; newlines are escaped as `\n` on screen so the row stays a
    /// single line, but the submitted body keeps them verbatim.
    Body,
    /// The issue's **project associations** (WP06 T029), the comma-joined spelling
    /// of the ids the form will associate.
    ///
    /// Appended after `Body` for the rule the rows above already state: every
    /// existing row's index is its identity in the renderer, and inserting in the
    /// middle renumbers every row after it. The value is a **list of resolved ids**,
    /// and the row is **picker-only** — a project the form invented would be one the
    /// registry does not hold, and a reference is chosen from a picker, never typed.
    Projects,
    /// The issue's **epic references** (WP06 T031), the comma-joined spelling of the
    /// ids the form will reference.
    ///
    /// Appended after `Projects` for the rule every row above states — no existing
    /// index moves. The exact analogue of [`FormFocus::Projects`] for the epic
    /// registry: a list of resolved ids, chosen through the **multi-select** picker
    /// and never typed, because an epic the form invented would be one the registry
    /// does not hold. The form constructs and validates no epic itself — the ids come
    /// from [`crate::epics::list_epics`] and are handed to
    /// [`crate::commands::epic::resolve_epics`] at submit.
    Epics,
}

/// Where a new issue created from the F4 New Issue mode enters the board.
///
/// The explicit choice the mode exists for: a form can default to one entry point
/// but cannot *say* which one it is using, and the two destinations mean different
/// things (the inbox is a queue with an age; `todo` is scheduled work). The chosen
/// target's status is written into [`FormState::status`], which remains the value
/// submitted — so the Status row reflects the choice and can still be overridden
/// for a column the target does not name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NewIssueTarget {
    /// Enter the triage inbox's entry status.
    Triage,
    /// Enter the todo status directly.
    #[default]
    Todo,
}

impl NewIssueTarget {
    /// The label shown in the Target row.
    pub fn label(self) -> &'static str {
        match self {
            NewIssueTarget::Triage => "Triage",
            NewIssueTarget::Todo => "Todo",
        }
    }

    /// The other side of the toggle.
    pub fn next(self) -> Self {
        match self {
            NewIssueTarget::Triage => NewIssueTarget::Todo,
            NewIssueTarget::Todo => NewIssueTarget::Triage,
        }
    }
}

impl FormFocus {
    pub fn next(self) -> Self {
        match self {
            FormFocus::Title => FormFocus::Status,
            FormFocus::Status => FormFocus::Priority,
            FormFocus::Priority => FormFocus::Labels,
            FormFocus::Labels => FormFocus::Assignee,
            FormFocus::Assignee => FormFocus::Estimate,
            FormFocus::Estimate => FormFocus::Cycles,
            FormFocus::Cycles => FormFocus::Milestones,
            FormFocus::Milestones => FormFocus::Reviewer,
            FormFocus::Reviewer => FormFocus::StartDate,
            FormFocus::StartDate => FormFocus::DueDate,
            FormFocus::DueDate => FormFocus::Parent,
            FormFocus::Parent => FormFocus::Target,
            FormFocus::Target => FormFocus::Template,
            FormFocus::Template => FormFocus::Body,
            FormFocus::Body => FormFocus::Projects,
            FormFocus::Projects => FormFocus::Epics,
            FormFocus::Epics => FormFocus::Title,
        }
    }

    pub fn prev(self) -> Self {
        match self {
            // `Epics`, not `Projects`: `RING` now ends at `Epics`, and the two
            // must agree or the backward wrap lands on a different field than the
            // forward one.
            FormFocus::Title => FormFocus::Epics,
            FormFocus::Status => FormFocus::Title,
            FormFocus::Priority => FormFocus::Status,
            FormFocus::Labels => FormFocus::Priority,
            FormFocus::Assignee => FormFocus::Labels,
            FormFocus::Estimate => FormFocus::Assignee,
            FormFocus::Cycles => FormFocus::Estimate,
            FormFocus::Milestones => FormFocus::Cycles,
            FormFocus::Reviewer => FormFocus::Milestones,
            FormFocus::StartDate => FormFocus::Reviewer,
            FormFocus::DueDate => FormFocus::StartDate,
            FormFocus::Parent => FormFocus::DueDate,
            FormFocus::Target => FormFocus::Parent,
            FormFocus::Template => FormFocus::Target,
            FormFocus::Body => FormFocus::Template,
            FormFocus::Projects => FormFocus::Body,
            FormFocus::Epics => FormFocus::Projects,
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            FormFocus::Title => "Title",
            FormFocus::Status => "Status",
            FormFocus::Priority => "Priority",
            FormFocus::Labels => "Labels",
            FormFocus::Assignee => "Assignee",
            FormFocus::Estimate => "Estimate",
            FormFocus::Cycles => "Cycles",
            FormFocus::Milestones => "Milestones",
            FormFocus::Reviewer => "Reviewer",
            FormFocus::StartDate => "Start date",
            FormFocus::DueDate => "Due date",
            FormFocus::Parent => "Parent",
            FormFocus::Target => "Target",
            FormFocus::Template => "Template",
            FormFocus::Body => "Body",
            FormFocus::Projects => "Projects",
            FormFocus::Epics => "Epics",
        }
    }

    /// The focus ring, in `next()` order, starting at `Title`.
    ///
    /// One list, so `render_with_bindings` can derive both the focus index and the
    /// row labels from it. It used to hold a hand-written `match` for the index
    /// beside a positional array of labels, which agree only by inspection — and
    /// the two disagree *silently*, as a bold cursor on the wrong row.
    pub const RING: [FormFocus; 17] = [
        FormFocus::Title,
        FormFocus::Status,
        FormFocus::Priority,
        FormFocus::Labels,
        FormFocus::Assignee,
        FormFocus::Estimate,
        FormFocus::Cycles,
        FormFocus::Milestones,
        FormFocus::Reviewer,
        FormFocus::StartDate,
        FormFocus::DueDate,
        FormFocus::Parent,
        FormFocus::Target,
        FormFocus::Template,
        FormFocus::Body,
        // WP06 T029, appended last: `RING.len()` moved, no existing index did.
        FormFocus::Projects,
        // WP06 T031: `Epics` appended last, for the same reason.
        FormFocus::Epics,
    ];

    /// This field's row in [`FormFocus::RING`].
    pub fn index(self) -> usize {
        Self::RING
            .iter()
            .position(|f| *f == self)
            .expect("every FormFocus variant is in RING")
    }

    /// Whether this field holds a date (picker-only, no free typing).
    pub fn is_date(self) -> bool {
        matches!(self, FormFocus::StartDate | FormFocus::DueDate)
    }

    /// Whether this field holds a parent (picker-only, single-select).
    pub fn is_parent(self) -> bool {
        matches!(self, FormFocus::Parent)
    }

    /// Whether this field holds the issue's board column (Status).
    ///
    /// Chosen from the active board's columns, never typed: a board column is a
    /// named position on a board, not a value to invent by hand, and free text
    /// could name one the board does not configure.
    pub fn is_status(self) -> bool {
        matches!(self, FormFocus::Status)
    }

    /// Whether this field holds the issue's priority.
    ///
    /// Chosen from the built-in set plus the priorities the project already uses,
    /// never typed, for the same reason as Status — with the picker's `+` inline
    /// create as the escape hatch for a priority the options do not list yet.
    pub fn is_priority(self) -> bool {
        matches!(self, FormFocus::Priority)
    }

    /// Whether this field is the New Issue target toggle.
    pub fn is_target(self) -> bool {
        matches!(self, FormFocus::Target)
    }

    /// Whether this field names a selected template.
    ///
    /// Chosen from the template picker, never typed: the value has to name a
    /// configured `[templates.<name>]` record, and free text could only ever fail
    /// to resolve to one.
    pub fn is_template(self) -> bool {
        matches!(self, FormFocus::Template)
    }

    /// Whether this field holds the issue's **project associations** (WP06 T029).
    ///
    /// Picker-only, for the reason `Status`/`Priority`/`Parent` are: the value has
    /// to name projects the registry holds, and the form may not construct or
    /// validate one itself — so a typed id could only ever be a guess, and the
    /// picker is fed by [`crate::projects::list_projects`].
    pub fn is_project(self) -> bool {
        matches!(self, FormFocus::Projects)
    }

    /// Whether this field holds the issue's **epic references** (WP06 T031).
    ///
    /// Picker-only, for the reason `Projects` is: the value has to name epics the
    /// registry holds, and the form may not construct or validate one itself — so a
    /// typed id could only ever be a guess, and the picker is fed by
    /// [`crate::epics::list_epics`].
    pub fn is_epic(self) -> bool {
        matches!(self, FormFocus::Epics)
    }

    /// Whether typing and backspace are refused on this field.
    ///
    /// `Parent` (picked by number), `Target` (toggled), `Template` (picked by
    /// name), `Status` and `Priority` (picked from their dropdowns) all hold
    /// values that are *chosen*, so a character has no meaning here. They guard
    /// `insert_char`/`delete_char` from one predicate rather than five inline
    /// checks, so a further control field cannot be added and silently left
    /// typeable.
    pub fn refuses_typing(self) -> bool {
        self.is_parent()
            || self.is_target()
            || self.is_template()
            || self.is_status()
            || self.is_priority()
            || self.is_project()
            || self.is_epic()
    }

    /// Whether the field's value is **chosen** from a picker rather than typed.
    ///
    /// Typing is refused on the chosen rows, because a half-typed number or a
    /// hand-typed priority is not a value: the service validates a parent by
    /// resolved number, and Status/Priority are picked from their dropdowns, so
    /// free text here could only ever fail or invent a column. This is the
    /// general form of what `is_date` was already doing for dates alone.
    pub fn is_picker_only(self) -> bool {
        self.is_date()
            || self.is_parent()
            || self.is_status()
            || self.is_priority()
            || self.is_project()
            || self.is_epic()
    }
}

#[derive(Debug, Clone)]
pub struct FormState {
    pub title: String,
    pub status: String,
    pub priority: String,
    pub labels: String,
    pub assignee: String,
    pub estimate: String,
    pub cycles: String,
    pub milestones: String,
    pub reviewer: String,
    pub start_date: String,
    pub due_date: String,
    /// The chosen parent's **number**, as a string (WP06 / T026).
    ///
    /// A `String` for the same reason `assignee` is one: the form's fields are
    /// uniformly text, and each is parsed and validated at submit rather than at
    /// Empty means no parent, which carries the same meaning as an
    /// empty `--parent ""` on the CLI.
    pub parent: String,
    /// The entry target of the F4 New Issue mode. Choosing a side writes the
    /// matching status into [`Self::status`], which is what submit reads.
    pub target: NewIssueTarget,
    /// The selected template's identity, or empty for none.
    ///
    /// A **stable template ID** (`[issue_templates.<id>]`) when
    /// [`Self::template_scope`] is set, otherwise the legacy
    /// `[templates.<name>]` record's name. A label only: the fields it filled are
    /// held separately, so clearing the selection keeps what was typed.
    ///
    /// The stable-ID case is identity, not a display label (C-002): a rename in
    /// `tix.toml` changes the label the row *shows* through
    /// [`Self::display_value`], never this value — so a submit resolves against
    /// the same template after the rename.
    pub template: String,
    /// The explicit scope of the selected stable template, when one is selected.
    ///
    /// `Some("repository")`/`Some("board:<name>")`/`Some("team:<label>")` marks
    /// the selection as a stable-ID template and makes the scope **visible**
    /// (FR-005): [`Self::display_value`] renders it beside the ID. `None` means
    /// no stable template is selected — either none at all, or a legacy
    /// `[templates.<name>]` pre-fill. The scope is the template's own declared
    /// scope, split out here so it travels with the selection and is what the
    /// shared resolver is asked for.
    pub template_scope: Option<String>,
    /// The issue body (Markdown). Submitted verbatim; rendered with newlines
    /// escaped so the row stays one line.
    pub body: String,
    /// The issue's **project associations** (WP06 T029), as the comma-joined
    /// spelling of the resolved project ids — the same shape `labels`, `cycles`
    /// and `milestones` use, and the shape the submit path parses.
    ///
    /// A set of ids, not a display string: the picker offers
    /// [`crate::projects::list_projects`]' ids, [`Self::from_issue`] pre-selects the
    /// issue's stored associations so an edit cannot silently drop the ones the user
    /// did not touch, and the **service** validates them at submit. The form itself
    /// never constructs or validates a project.
    pub projects: String,
    /// The issue's **epic references** (WP06 T031), as the comma-joined spelling of
    /// the resolved epic ids — the same shape `projects`, `labels`, `cycles` and
    /// `milestones` use, and the shape the submit path parses.
    ///
    /// A set of ids, not a display string: the picker offers
    /// [`crate::epics::list_epics`]' ids, [`Self::from_issue`] pre-selects the
    /// issue's stored references so an edit or clone cannot silently drop the ones
    /// the user did not touch, and the **service** validates them at submit. The form
    /// itself never constructs or validates an epic.
    pub epics: String,
    pub focus: FormFocus,
    /// The insertion point in the focused field, in **characters** (not bytes,
    /// so a multi-byte value is never split). Always clamped to the field's
    /// value when used; every writer that replaces a value wholesale resets it
    /// to the end.
    pub cursor: usize,
}

impl FormState {
    pub fn new(default_status: &str) -> Self {
        Self::with_default_assignee(default_status, "")
    }

    pub fn with_default_assignee(default_status: &str, default_assignee: &str) -> Self {
        FormState {
            title: String::new(),
            status: default_status.to_string(),
            priority: String::new(),
            labels: String::new(),
            assignee: default_assignee.to_string(),
            estimate: String::new(),
            cycles: String::new(),
            milestones: String::new(),
            reviewer: String::new(),
            start_date: String::new(),
            due_date: String::new(),
            parent: String::new(),
            target: NewIssueTarget::default(),
            template: String::new(),
            template_scope: None,
            body: String::new(),
            projects: String::new(),
            epics: String::new(),
            focus: FormFocus::Title,
            cursor: 0,
        }
    }

    /// Pre-fill the rows a template sets, leaving rows it omits untouched.
    ///
    /// *Untouched* rather than *cleared* is the whole point: a template is applied
    /// to a form the user may already have typed into, and a template that named
    /// only `labels` must not silently erase their title. Vector fields follow the
    /// same rule as the submit path — they are the comma-joined spelling of the
    /// list they would create.
    pub fn apply_template(&mut self, name: &str, template: &crate::config::IssueTemplate) {
        if let Some(title) = &template.title {
            self.title = title.clone();
        }
        if let Some(body) = &template.body {
            self.body = body.clone();
        }
        if !template.labels.is_empty() {
            self.labels = template.labels.join(",");
        }
        if let Some(status) = &template.status {
            self.status = status.clone();
        }
        if let Some(priority) = &template.priority {
            self.priority = priority.clone();
        }
        if let Some(assignee) = &template.assignee {
            self.assignee = assignee.clone();
        }
        if let Some(estimate) = &template.estimate {
            self.estimate = estimate.clone();
        }
        if let Some(reviewer) = &template.reviewer {
            self.reviewer = reviewer.clone();
        }
        if !template.cycles.is_empty() {
            self.cycles = template.cycles.join(",");
        }
        if !template.milestones.is_empty() {
            self.milestones = template.milestones.join(",");
        }
        if let Some(start) = &template.start_date {
            self.start_date = start.clone();
        }
        if let Some(due) = &template.due_date {
            self.due_date = due.clone();
        }
        self.template = name.to_string();
        self.template_scope = None;
        self.cursor_to_end();
    }

    /// Pre-fill the rows a **stable-ID** template sets, and record its ID + scope.
    ///
    /// The sibling of [`Self::apply_template`] for `[issue_templates.<id>]`
    /// records (WP05/T024), and deliberately the same shape: only rows the
    /// template actually sets are written, so applying a labels-only template
    /// cannot erase a title the user already typed.
    ///
    /// The values come from the template's `defaults` and its prompt `default`s,
    /// in the **same precedence the shared resolver merges them** (`contracts/
    /// resolver.md`): a prompt's default wins over the block default for the same
    /// key, because user input would. This is seeding only — required prompts with
    /// no value are left empty and reported by the resolver at submit, not
    /// pre-filled with a placeholder.
    ///
    /// `template.extensions` (unknown metadata) is **not read**: it is preserved
    /// data, never interpreted as a form field (C-006). List-valued defaults are
    /// joined with the same comma rule the submit path parses, and rows this form
    /// does not have (`files`, `related_issues`, `type`) are applied by the
    /// resolver from the defaults at submit instead — the form neither invents a
    /// row for them nor silently drops them.
    pub fn apply_stable_template(
        &mut self,
        id: &str,
        scope: &str,
        template: &crate::templates::Template,
    ) {
        /// The prompt default for `key`, when a prompt declares a non-blank one.
        ///
        /// Returned **verbatim**: the resolver clones a default rather than
        /// trimming it, so trimming here would make the seeded form disagree with
        /// what a submit actually writes (a Markdown body's trailing newline is
        /// content). The registry already refuses a blank default.
        fn prompt_default(template: &crate::templates::Template, key: &str) -> Option<String> {
            template
                .prompts
                .iter()
                .find(|prompt| prompt.key == key)
                .and_then(|prompt| prompt.default.as_deref())
                .filter(|value| !value.trim().is_empty())
                .map(str::to_string)
        }
        // Precedence: prompt default, then block default, then leave untouched.
        // Both are taken verbatim, matching the resolver's merge.
        let scalar = |key: &str, fallback: Option<&String>| -> Option<String> {
            prompt_default(template, key).or_else(|| fallback.cloned())
        };
        // A list field: a prompt default is already comma-joined, a block default
        // is joined with the submit path's rule. Empty means "leave untouched".
        let list = |key: &str, values: &[String]| -> Option<String> {
            if let Some(value) = prompt_default(template, key) {
                return Some(value);
            }
            let joined = values
                .iter()
                .filter(|value| !value.trim().is_empty())
                .cloned()
                .collect::<Vec<_>>()
                .join(",");
            (!joined.is_empty()).then_some(joined)
        };

        let defaults = &template.defaults;
        if let Some(value) = scalar("title", defaults.title.as_ref()) {
            self.title = value;
        }
        if let Some(value) = scalar("body", defaults.body.as_ref()) {
            self.body = value;
        }
        if let Some(value) = scalar("status", defaults.status.as_ref()) {
            self.status = value;
        }
        if let Some(value) = scalar("priority", defaults.priority.as_ref()) {
            self.priority = value;
        }
        if let Some(value) = scalar("assignee", defaults.assignee.as_ref()) {
            self.assignee = value;
        }
        if let Some(value) = scalar("estimate", defaults.estimate.as_ref()) {
            self.estimate = value;
        }
        if let Some(value) = scalar("reviewer", defaults.reviewer.as_ref()) {
            self.reviewer = value;
        }
        if let Some(value) = scalar("start_date", defaults.start_date.as_ref()) {
            self.start_date = value;
        }
        if let Some(value) = scalar("due_date", defaults.due_date.as_ref()) {
            self.due_date = value;
        }
        if let Some(value) = scalar("parent", defaults.parent.as_ref()) {
            self.parent = value;
        }
        if let Some(value) = list("labels", &defaults.labels) {
            self.labels = value;
        }
        if let Some(value) = list("cycles", &defaults.cycles) {
            self.cycles = value;
        }
        if let Some(value) = list("milestones", &defaults.milestones) {
            self.milestones = value;
        }
        self.template = id.to_string();
        self.template_scope = Some(scope.to_string());
        self.cursor_to_end();
    }

    /// This form with every field prefilled from an existing issue — the TUI's
    /// "clone issue" action (tix #1484).
    ///
    /// Exactly the fields the form *has* are carried over, which is exactly the
    /// fields creation takes: `number`, `created`, `commit` and `History` are not
    /// creation inputs, so they are not carried. The title is copied **verbatim**
    /// rather than suffixed with "copy": the user asked for the source's data, a
    /// title is not an identity (numbers are), and inventing a naming convention
    /// here would put a string in the user's issue that no command in this tool
    /// produces.
    ///
    /// Multivalued fields are filled in the same comma-separated form the submit
    /// path parses (`labels`, `cycles`, `milestones`), so a clone submitted
    /// unchanged round-trips the source's values exactly.
    pub fn from_issue(issue: &Issue) -> Self {
        fn joined(values: &Option<Vec<String>>) -> String {
            values.as_deref().map(|v| v.join(",")).unwrap_or_default()
        }
        FormState {
            title: issue.title.clone(),
            status: issue.status.to_string(),
            priority: issue.priority.to_string(),
            labels: issue.labels.join(","),
            assignee: issue.assignee.clone().unwrap_or_default(),
            estimate: issue.estimate.clone().unwrap_or_default(),
            cycles: joined(&issue.cycles),
            milestones: joined(&issue.milestones),
            reviewer: issue.reviewer.clone().unwrap_or_default(),
            start_date: issue.start_date.clone().unwrap_or_default(),
            due_date: issue.due_date.clone().unwrap_or_default(),
            parent: issue.parent.map(|n| n.to_string()).unwrap_or_default(),
            // The body is a form row now (`tui-new-issue-mode`), so a clone that
            // dropped it would be the partial copy #1484's own doc warns about.
            body: issue.body.clone(),
            // WP06 T029 step 2: the associations are pre-selected in the same
            // comma-joined shape the submit path parses, so an edit or clone cannot
            // silently drop the associations the user did not touch. The stored ids
            // are carried **verbatim** (including a dangling reference the registry
            // no longer holds): dropping it here would hide a reference `tix lint`
            // still reports, and the row's own picker lists the current value so it
            // stays visible and removable.
            projects: joined(&issue.projects),
            // WP06 T031 step 2: the references are pre-selected in the same
            // comma-joined shape the submit path parses, so an edit or clone cannot
            // silently drop the references the user did not touch. The stored ids are
            // carried **verbatim** (including a dangling reference the registry no
            // longer holds): dropping it here would hide a reference `tix lint` still
            // reports, and the row's own picker lists the current value so it stays
            // visible and removable.
            epics: joined(&issue.epics),
            // A clone copies the source's status verbatim; the target is set to
            // match it so the Target row does not claim a destination the form is
            // not using. `App` refines `Triage` when the source sits in the inbox.
            target: NewIssueTarget::Todo,
            template: String::new(),
            template_scope: None,
            focus: FormFocus::Title,
            cursor: issue.title.chars().count(),
        }
    }

    /// This form's value for `focus`, regardless of which field is focused.
    ///
    /// `focused_value` is `value_of(self.focus)`. The indirection exists so the
    /// renderer can walk [`FormFocus::RING`] and read each field in turn, which is
    /// what lets one list drive both the labels and the focus index.
    pub fn value_of(&self, focus: FormFocus) -> &str {
        match focus {
            FormFocus::Title => &self.title,
            FormFocus::Status => &self.status,
            FormFocus::Priority => &self.priority,
            FormFocus::Labels => &self.labels,
            FormFocus::Assignee => &self.assignee,
            FormFocus::Estimate => &self.estimate,
            FormFocus::Cycles => &self.cycles,
            FormFocus::Milestones => &self.milestones,
            FormFocus::Reviewer => &self.reviewer,
            FormFocus::StartDate => &self.start_date,
            FormFocus::DueDate => &self.due_date,
            FormFocus::Parent => &self.parent,
            // Not a stored string: the target is an enum with two labels, and
            // rendering its label here is what keeps it a row like every other.
            FormFocus::Target => self.target.label(),
            FormFocus::Template => &self.template,
            FormFocus::Body => &self.body,
            FormFocus::Projects => &self.projects,
            FormFocus::Epics => &self.epics,
        }
    }

    /// The text actually drawn for `focus`.
    ///
    /// Identical to [`Self::value_of`] everywhere but two rows. The body's
    /// newlines are escaped (`\n`) so a multi-line Markdown body occupies one row
    /// and the row arithmetic the caret depends on stays true; the submitted value
    /// keeps the real newlines. The Template row appends the selected template's
    /// **explicit scope** (`id [scope]`) so the scope is visible before submit
    /// (FR-005); the stored [`Self::template`] stays the bare ID, which is what
    /// selection and resolution read.
    pub fn display_value(&self, focus: FormFocus) -> std::borrow::Cow<'_, str> {
        let value = self.value_of(focus);
        if focus == FormFocus::Body && value.contains('\n') {
            return std::borrow::Cow::Owned(value.replace('\n', "\\n"));
        }
        if focus == FormFocus::Template
            && !value.is_empty()
            && let Some(scope) = &self.template_scope
        {
            return std::borrow::Cow::Owned(format!("{value} [{scope}]"));
        }
        std::borrow::Cow::Borrowed(value)
    }

    /// [`Self::display_value`] for the focused row.
    pub fn focused_display_value(&self) -> std::borrow::Cow<'_, str> {
        self.display_value(self.focus)
    }

    pub fn focused_value(&self) -> &str {
        self.value_of(self.focus)
    }

    /// The focused field's editable buffer, or `None` when the field has none.
    ///
    /// `Option` rather than a `panic` for the control rows: `Target` is an enum
    /// with no buffer of its own, and the alternative — a `&mut String` arm that
    /// panics — would make a guard in `insert_char` the only thing standing
    /// between a mis-set focus and an abort. A `None` makes the callers handle it.
    pub fn focused_value_mut(&mut self) -> Option<&mut String> {
        match self.focus {
            FormFocus::Title => Some(&mut self.title),
            FormFocus::Status => Some(&mut self.status),
            FormFocus::Priority => Some(&mut self.priority),
            FormFocus::Labels => Some(&mut self.labels),
            FormFocus::Assignee => Some(&mut self.assignee),
            FormFocus::Estimate => Some(&mut self.estimate),
            FormFocus::Cycles => Some(&mut self.cycles),
            FormFocus::Milestones => Some(&mut self.milestones),
            FormFocus::Reviewer => Some(&mut self.reviewer),
            FormFocus::StartDate => Some(&mut self.start_date),
            FormFocus::DueDate => Some(&mut self.due_date),
            FormFocus::Parent => Some(&mut self.parent),
            FormFocus::Template => Some(&mut self.template),
            FormFocus::Body => Some(&mut self.body),
            FormFocus::Projects => Some(&mut self.projects),
            FormFocus::Epics => Some(&mut self.epics),
            FormFocus::Target => None,
        }
    }

    /// The insertion point, clamped to the focused value's length.
    pub fn cursor(&self) -> usize {
        self.cursor.min(self.focused_value().chars().count())
    }

    /// Whether the focused row supports insert/cursor editing.
    ///
    /// A picker-only field refuses typing, and a date field is edited as a whole
    /// value (`type_date` appends), so neither has an insertion point to move.
    fn editable_text(&self) -> bool {
        !self.focus.refuses_typing() && !self.focus.is_date()
    }

    /// Put the insertion point after the focused field's last character.
    pub fn cursor_to_end(&mut self) {
        self.cursor = self.focused_value().chars().count();
    }

    /// Put the insertion point before the focused field's first character.
    pub fn cursor_to_start(&mut self) {
        if self.editable_text() {
            self.cursor = 0;
        }
    }

    /// Move the insertion point one character left (no-op at the start).
    pub fn move_cursor_left(&mut self) {
        if self.editable_text() {
            self.cursor = self.cursor().saturating_sub(1);
        }
    }

    /// Move the insertion point one character right (no-op at the end).
    pub fn move_cursor_right(&mut self) {
        if self.editable_text() {
            self.cursor = (self.cursor() + 1).min(self.focused_value().chars().count());
        }
    }

    /// Move the insertion point to the start of the previous word.
    ///
    /// Skips the run of non-word characters before the caret first, then the
    /// word itself, which is the readline/Emacs rule `Ctrl-Left` follows.
    pub fn move_cursor_word_left(&mut self) {
        if !self.editable_text() {
            return;
        }
        let chars: Vec<char> = self.focused_value().chars().collect();
        let mut index = self.cursor();
        while index > 0 && !is_word_char(chars[index - 1]) {
            index -= 1;
        }
        while index > 0 && is_word_char(chars[index - 1]) {
            index -= 1;
        }
        self.cursor = index;
    }

    /// Move the insertion point to the end of the next word.
    pub fn move_cursor_word_right(&mut self) {
        if !self.editable_text() {
            return;
        }
        let chars: Vec<char> = self.focused_value().chars().collect();
        let mut index = self.cursor();
        while index < chars.len() && !is_word_char(chars[index]) {
            index += 1;
        }
        while index < chars.len() && is_word_char(chars[index]) {
            index += 1;
        }
        self.cursor = index;
    }

    /// Delete the character before the insertion point (`Backspace`).
    pub fn delete_char(&mut self) {
        if self.focus.refuses_typing() {
            return;
        }
        if self.focus.is_date() {
            let next = crate::ui::date_picker::backspace_date(self.focused_value());
            if let Some(value) = self.focused_value_mut() {
                *value = next;
            }
            return;
        }
        let index = self.cursor();
        if index == 0 {
            return;
        }
        let byte = byte_offset(self.focused_value(), index - 1);
        if let Some(value) = self.focused_value_mut() {
            value.remove(byte);
        }
        self.cursor = index - 1;
    }

    /// Delete the character at the insertion point (`Delete`).
    pub fn delete_forward_char(&mut self) {
        if !self.editable_text() {
            return;
        }
        let index = self.cursor();
        let byte = byte_offset(self.focused_value(), index);
        if byte < self.focused_value().len()
            && let Some(value) = self.focused_value_mut()
        {
            value.remove(byte);
        }
    }

    /// Delete from the insertion point to the end of the value (`Ctrl-K`).
    pub fn delete_to_end(&mut self) {
        if !self.editable_text() {
            return;
        }
        let byte = byte_offset(self.focused_value(), self.cursor());
        if let Some(value) = self.focused_value_mut() {
            value.truncate(byte);
        }
    }

    /// Delete from the start of the value to the insertion point (`Ctrl-U`).
    pub fn delete_to_start(&mut self) {
        if !self.editable_text() {
            return;
        }
        let byte = byte_offset(self.focused_value(), self.cursor());
        if let Some(value) = self.focused_value_mut() {
            value.drain(..byte);
        }
        self.cursor = 0;
    }

    /// Delete the word before the insertion point (`Ctrl-W`, `Alt-Backspace`).
    pub fn delete_word_backward(&mut self) {
        if !self.editable_text() {
            return;
        }
        let chars: Vec<char> = self.focused_value().chars().collect();
        let end = self.cursor();
        let mut start = end;
        while start > 0 && !is_word_char(chars[start - 1]) {
            start -= 1;
        }
        while start > 0 && is_word_char(chars[start - 1]) {
            start -= 1;
        }
        if start == end {
            return;
        }
        let from = byte_offset(self.focused_value(), start);
        let to = byte_offset(self.focused_value(), end);
        if let Some(value) = self.focused_value_mut() {
            value.drain(from..to);
        }
        self.cursor = start;
    }

    pub fn insert_char(&mut self, c: char) {
        if self.focus.refuses_typing() {
            // Picked or toggled, never typed: a parent by number, a target by
            // side, a template by name.
            return;
        }
        if self.focus.is_date() {
            if let Some(next) = crate::ui::date_picker::type_date(self.focused_value(), c)
                && let Some(value) = self.focused_value_mut()
            {
                *value = next;
            }
            return;
        }
        let index = self.cursor();
        let byte = byte_offset(self.focused_value(), index);
        if let Some(value) = self.focused_value_mut() {
            value.insert(byte, c);
        }
        self.cursor = index + 1;
    }

    /// Whether the focused field is a picker-only date field.
    pub fn is_date_focus(&self) -> bool {
        self.focus.is_date()
    }

    /// Whether the focused date field already holds a complete, valid date.
    pub fn focused_date_is_complete(&self) -> bool {
        self.focus.is_date() && crate::ui::date_picker::is_complete_date(self.focused_value())
    }

    /// Overwrite the focused date field (no-op when it isn't a date field).
    pub fn set_focused_date(&mut self, value: &str) {
        if self.focus.is_date()
            && let Some(field) = self.focused_value_mut()
        {
            *field = value.to_string();
        }
    }

    pub fn move_focus_next(&mut self) {
        self.focus = self.focus.next();
        self.cursor_to_end();
    }

    pub fn move_focus_prev(&mut self) {
        self.focus = self.focus.prev();
        self.cursor_to_end();
    }
}

pub fn render(form: &FormState, f: &mut Frame, area: Rect) {
    let bindings =
        crate::keybindings::KeyBindings::resolve(&crate::keybindings::KeyBindings::default())
            .expect("built-in bindings are valid");
    render_with_bindings(
        form,
        f,
        area,
        &bindings,
        crate::keybindings::InputContext::Form,
    );
    // This entry point renders the form as the active surface, so it places the
    // caret too. `render_with_bindings` cannot: it is also what draws the form as a
    // backdrop under a picker, where the cursor belongs to the overlay.
    place_caret(form, f, area);
}

pub fn render_with_bindings(
    form: &FormState,
    f: &mut Frame,
    area: Rect,
    bindings: &crate::keybindings::EffectiveBindings,
    context: crate::keybindings::InputContext,
) {
    // Both the focus index and the row labels come from `FormFocus::RING`, so the
    // cursor and the label it labels cannot drift apart. The value for each field
    // is read through `focused_value`-style indexing into `FormState` below, which
    // is why the pairing is by position and not by name.
    let focus_idx = form.focus.index();
    let fields: Vec<(&'static str, std::borrow::Cow<'_, str>)> = FormFocus::RING
        .iter()
        .map(|focus| (focus.label(), form.display_value(*focus)))
        .collect();

    let inner_width = usize::from(area.width.saturating_sub(2));

    let mut lines: Vec<Line<'static>> = Vec::new();
    for (i, (label, value)) in fields.iter().enumerate() {
        let cursor = if i == focus_idx { "> " } else { "  " };
        let label_style = if i == focus_idx {
            Style::default()
                .add_modifier(Modifier::BOLD)
                .fg(Color::Cyan)
        } else {
            Style::default()
        };
        let (display, value_style) = if value.is_empty() && i != focus_idx {
            ("(empty)".to_string(), Style::default().fg(Color::DarkGray))
        } else if i == focus_idx {
            let available = inner_width.saturating_sub(Span::raw(format!("> {label}: ")).width());
            let text = focused_row_window(form, available)
                .map_or_else(|| value.to_string(), |(text, _)| text);
            (text, Style::default().add_modifier(Modifier::UNDERLINED))
        } else {
            (value.to_string(), Style::default())
        };
        lines.push(Line::from(vec![
            Span::styled(format!("{cursor}{label}: "), label_style),
            Span::styled(display, value_style),
        ]));
    }

    lines.push(Line::from(""));
    let submit = bindings.label(context, crate::keybindings::TuiAction::Submit);
    let cancel = bindings.label(context, crate::keybindings::TuiAction::Cancel);
    let next = bindings.label(context, crate::keybindings::TuiAction::Next);
    let previous = bindings.label(context, crate::keybindings::TuiAction::Previous);
    let picker = bindings.label(context, crate::keybindings::TuiAction::OpenPicker);
    lines.push(Line::from(Span::styled(
        format!(
            "{submit}: Submit | {cancel}: Cancel | {next}/{previous}: Fields | \
             {picker}: Picker/Date/Parent | Arrows: Caret/Target | \
             Ctrl-A/E: Start/End | Ctrl-W: Word"
        ),
        Style::default().fg(Color::DarkGray),
    )));

    let para =
        Paragraph::new(lines).block(Block::default().borders(Borders::ALL).title("New Issue"));

    f.render_widget(para, area);
}

/// Where the terminal caret belongs for `form` rendered into `area`, or `None`
/// when this form shows no insertion point.
///
/// Split from [`place_caret`] so the arithmetic — the part that can be wrong — is
/// testable without a terminal.
///
/// The insertion point is [`FormState::cursor`], clamped to the focused value. A
/// picker-only field gets no caret, because typing is refused on it: a caret on
/// `Parent` would advertise an insertion point that does not exist. The date
/// fields do accept typed digits, so they keep one — at the end, where
/// `type_date` appends.
///
/// A value wider than the row is windowed by [`focused_row_window`], the same
/// helper the renderer uses, so the caret is on screen and points at the text
/// that is actually drawn.
pub fn caret_position(form: &FormState, area: Rect) -> Option<Position> {
    if form.focus.refuses_typing() {
        return None;
    }
    let row = field_row_rect(area, form.focus)?;
    // The same prefix the row renderer writes: focus marker, label, colon, space.
    // Measured on the rendered spans rather than by character count, so a value
    // wider than it is long (any non-ASCII in a title) still lands the caret
    // correctly.
    let prefix = format!("> {}: ", form.focus.label());
    let prefix_width = Span::raw(prefix).width();
    let available = usize::from(row.width).saturating_sub(prefix_width);
    let (_, caret_cells) = focused_row_window(form, available)?;
    let column = u16::try_from(prefix_width + caret_cells).unwrap_or(u16::MAX);
    Some(Position::new(
        row.x + column.min(row.width.saturating_sub(1)),
        row.y,
    ))
}

/// The text the focused row should draw and the caret's **cell** offset inside
/// it.
///
/// `None` on a row that shows no insertion point. A value that fits is returned
/// whole. A wider one is windowed around the caret: the window starts as far
/// back in the value as the row can hold, so the caret stays visible while
/// editing the middle of a long title. The escape applied to a body's newlines is
/// accounted for, so the caret still lands on the cell its character occupies.
fn focused_row_window(form: &FormState, available: usize) -> Option<(String, usize)> {
    if form.focus.refuses_typing() {
        return None;
    }
    let display = form.focused_display_value().into_owned();
    let chars: Vec<char> = display.chars().collect();
    if available == 0 {
        return Some((String::new(), 0));
    }
    // A date is edited as a whole value, so its caret belongs at the end.
    let caret_chars = if form.focus.is_date() {
        chars.len()
    } else {
        let cursor = form.cursor();
        if form.focus == FormFocus::Body {
            let newlines = form
                .focused_value()
                .chars()
                .take(cursor)
                .filter(|c| *c == '\n')
                .count();
            (cursor + newlines).min(chars.len())
        } else {
            cursor.min(chars.len())
        }
    };
    let caret_cells: usize = chars[..caret_chars]
        .iter()
        .map(|c| UnicodeWidthChar::width(*c).unwrap_or(0))
        .sum();
    if Span::raw(display.as_str()).width() <= available {
        return Some((display, caret_cells));
    }
    // The caret must sit inside the row: cells `0..=available - 1`.
    let budget = available - 1;
    let mut start = caret_chars;
    let mut width = 0usize;
    while start > 0 {
        let cells = UnicodeWidthChar::width(chars[start - 1]).unwrap_or(0);
        if width + cells > budget {
            break;
        }
        width += cells;
        start -= 1;
    }
    Some((chars[start..].iter().collect(), width))
}

/// The one-row inner rectangle `focus` occupies when the form is drawn into
/// `area`, or `None` when that row is outside the visible form.
///
/// The single arithmetic shared by the caret and by the hit region the New Issue
/// mode records for the Template row: two copies of "inner rect plus the focus
/// index" would be two chances to disagree about where a row is.
pub fn field_row_rect(area: Rect, focus: FormFocus) -> Option<Rect> {
    let inner = Block::default().borders(Borders::ALL).inner(area);
    if inner.width == 0 || inner.height == 0 {
        return None;
    }
    let y = inner.y.checked_add(u16::try_from(focus.index()).ok()?)?;
    if y >= inner.y + inner.height {
        return None;
    }
    Some(Rect {
        x: inner.x,
        y,
        width: inner.width,
        height: 1,
    })
}

/// Put the terminal's text cursor at the end of the focused field's value.
///
/// Until this existed, `set_cursor_position` was never called anywhere in the
/// crate: the cursor stayed wherever the previously rendered widget left it, and
/// the form showed no insertion point at all. "Create issue" opened on an empty
/// Title row that was underlined and nothing else, and characters appeared with the
/// caret parked elsewhere (#1486).
///
/// Called by the owner of the frame rather than from `render_with_bindings`,
/// because where the form is a **backdrop** — under the date-picker overlay — the
/// overlay owns the cursor and a caret on the row behind it would point at the
/// wrong surface.
pub fn place_caret(form: &FormState, f: &mut Frame, area: Rect) {
    if let Some(position) = caret_position(form, area) {
        f.set_cursor_position(position);
    }
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;

    #[test]
    fn focus_cycles_forward() {
        assert_eq!(FormFocus::Title.next(), FormFocus::Status);
        assert_eq!(FormFocus::DueDate.next(), FormFocus::Parent);
        assert_eq!(FormFocus::Parent.next(), FormFocus::Target);
        assert_eq!(FormFocus::Target.next(), FormFocus::Template);
        assert_eq!(FormFocus::Template.next(), FormFocus::Body);
        // WP06 T029/T031: `Projects` and then `Epics` are appended, so `Body` is no
        // longer the last row and the wrap home starts from `Epics`.
        assert_eq!(FormFocus::Body.next(), FormFocus::Projects);
        assert_eq!(FormFocus::Projects.next(), FormFocus::Epics);
        assert_eq!(FormFocus::Epics.next(), FormFocus::Title);
    }

    #[test]
    fn focus_cycles_backward() {
        assert_eq!(FormFocus::Title.prev(), FormFocus::Epics);
        assert_eq!(FormFocus::Status.prev(), FormFocus::Title);
        assert_eq!(FormFocus::Body.prev(), FormFocus::Template);
        assert_eq!(FormFocus::Projects.prev(), FormFocus::Body);
        assert_eq!(FormFocus::Epics.prev(), FormFocus::Projects);
    }

    /// `next`, `prev`, and `RING` are three statements of the same order, and the
    /// compiler cannot check that they agree — an out-of-date arm compiles and
    /// silently sends the cursor to the wrong field.
    ///
    /// Asserted as a walk over the ring rather than as a list of pairs, so adding a
    /// field cannot leave the pairs stale: the test has to be updated to pass, and
    /// updating it means reading the ring.
    #[test]
    fn the_ring_and_the_next_prev_chains_agree() {
        let ring = FormFocus::RING;
        for (i, focus) in ring.iter().enumerate() {
            let forward = ring[(i + 1) % ring.len()];
            let backward = ring[(i + ring.len() - 1) % ring.len()];
            assert_eq!(focus.next(), forward, "next() after {focus:?} in RING");
            assert_eq!(focus.prev(), backward, "prev() after {focus:?} in RING");
        }
    }

    /// `RING` must contain every variant, or a field becomes unreachable: there is
    /// no way to tab onto it and no way off whatever precedes it. `index()` panics
    /// on a variant missing from `RING`, so this is that panic's guard, as a test.
    #[test]
    fn the_ring_covers_every_field() {
        for (i, focus) in FormFocus::RING.iter().enumerate() {
            assert_eq!(focus.index(), i, "{focus:?} must sit at its RING position");
        }
        // And a fresh form starts on a field that is in the ring.
        assert!(FormFocus::RING.contains(&FormState::new("todo").focus));
    }

    /// The parent field is chosen from a picker, so typing into it must do nothing.
    /// A half-typed number is not a parent, and the service validates by resolved
    /// number — free text here could only ever be a value that fails at submit.
    #[test]
    fn the_parent_field_refuses_typed_characters() {
        let mut form = FormState::new("todo");
        form.move_focus_next();
        for _ in 0..FormFocus::RING.len() {
            if form.focus == FormFocus::Parent {
                break;
            }
            form.move_focus_next();
        }
        assert_eq!(form.focus, FormFocus::Parent, "the ring must reach Parent");
        assert!(form.focus.is_picker_only());
        assert!(!form.focus.is_date(), "Parent is picker-only, not a date");

        form.insert_char('9');
        form.insert_char('x');
        form.delete_char();
        assert_eq!(form.parent, "", "typing must not reach the parent field");
        assert_eq!(form.focused_value(), "");

        // But a *picked* value does, and it reads back through the same accessor.
        form.parent = "42".to_string();
        assert_eq!(form.focused_value(), "42");
    }

    #[test]
    fn form_insert_and_delete() {
        let mut form = FormState::new("todo");
        form.insert_char('h');
        form.insert_char('i');
        assert_eq!(form.title, "hi");
        form.delete_char();
        assert_eq!(form.title, "h");
    }

    /// Typing, Backspace and Delete act at the insertion point, not at the end
    /// (tix #1746).
    #[test]
    fn form_edits_at_the_insertion_point() {
        let mut form = FormState::new("todo");
        for c in "abcd".chars() {
            form.insert_char(c);
        }
        form.move_cursor_left();
        form.move_cursor_left();
        assert_eq!(form.cursor(), 2);

        form.insert_char('X');
        assert_eq!(form.title, "abXcd");
        assert_eq!(form.cursor(), 3);

        form.delete_char();
        assert_eq!(form.title, "abcd", "Backspace removes before the caret");
        assert_eq!(form.cursor(), 2);

        form.delete_forward_char();
        assert_eq!(form.title, "abd", "Delete removes at the caret");
        assert_eq!(form.cursor(), 2);
    }

    #[test]
    fn form_cursor_home_end_and_word_jumps() {
        let mut form = FormState::new("todo");
        for c in "one two three".chars() {
            form.insert_char(c);
        }
        assert_eq!(form.cursor(), 13);

        form.cursor_to_start();
        assert_eq!(form.cursor(), 0);
        form.move_cursor_word_right();
        assert_eq!(form.cursor(), 3, "end of `one`");
        form.move_cursor_word_right();
        assert_eq!(form.cursor(), 7, "end of `two`");

        form.cursor_to_end();
        assert_eq!(form.cursor(), 13);
        form.move_cursor_word_left();
        assert_eq!(form.cursor(), 8, "start of `three`");
        form.move_cursor_word_left();
        assert_eq!(form.cursor(), 4, "start of `two`");
    }

    #[test]
    fn form_kill_commands_operate_on_the_insertion_point() {
        let mut form = FormState::new("todo");
        for c in "alpha beta gamma".chars() {
            form.insert_char(c);
        }
        form.delete_word_backward();
        assert_eq!(form.title, "alpha beta ");
        form.delete_to_start();
        assert_eq!(form.title, "", "Ctrl-U removes everything before the caret");

        for c in "abcd".chars() {
            form.insert_char(c);
        }
        assert_eq!(form.title, "abcd");
        form.cursor = 2;
        form.delete_to_end();
        assert_eq!(form.title, "ab", "Ctrl-K removes from the caret to the end");
    }

    /// The cursor moves by characters, so a multi-byte value is never split and
    /// inserting or deleting a non-ASCII character keeps the text valid.
    #[test]
    fn form_cursor_is_character_indexed_not_byte_indexed() {
        let mut form = FormState::new("todo");
        for c in "héllo".chars() {
            form.insert_char(c);
        }
        form.move_cursor_left();
        form.move_cursor_left();
        form.insert_char('ü');
        assert_eq!(form.title, "hélülo");
        form.delete_char();
        assert_eq!(form.title, "héllo");
    }

    #[test]
    fn form_move_focus() {
        let mut form = FormState::new("todo");
        assert_eq!(form.focus, FormFocus::Title);
        form.move_focus_next();
        assert_eq!(form.focus, FormFocus::Status);
        form.move_focus_prev();
        assert_eq!(form.focus, FormFocus::Title);
    }

    #[test]
    fn render_smoke() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        // Tall enough for every row: the ring is 15 fields, plus the blank
        // separator, the hint, and the two border rows.
        let backend = TestBackend::new(80, 22);
        let mut terminal = Terminal::new(backend).unwrap();
        let form = FormState::new("todo");
        terminal.draw(|f| render(&form, f, f.area())).unwrap();

        let buf = terminal.backend().buffer();
        let mut text = String::new();
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                text.push_str(buf[(x, y)].symbol());
            }
            text.push('\n');
        }
        assert!(text.contains("F2: Picker"), "got {text:?}");
    }

    /// The regression from #1486: with nothing drawn over it, rendering the create
    /// form leaves the terminal cursor **on the focused row**. Before this,
    /// `set_cursor_position` was called nowhere in the crate, so the cursor stayed
    /// wherever the previous frame put it and the form showed no insertion point.
    #[test]
    fn rendering_the_create_form_puts_the_caret_on_the_title_row() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let mut terminal = Terminal::new(TestBackend::new(60, 16)).unwrap();
        let form = FormState::new("todo");
        terminal.draw(|f| render(&form, f, f.area())).unwrap();

        // The block's border puts the inner area at (1, 1); the row prefix for an
        // empty title is "> Title: ".
        assert_eq!(
            terminal.backend().cursor_position(),
            Position::new(1 + "> Title: ".len() as u16, 1)
        );
    }

    #[test]
    fn caret_follows_the_typed_value() {
        let area = Rect::new(10, 5, 40, 20);
        let mut form = FormState::new("todo");
        for c in "abc".chars() {
            form.insert_char(c);
        }
        assert_eq!(
            caret_position(&form, area),
            // inner starts one cell inside the border, at (11, 6).
            Some(Position::new(11 + "> Title: abc".len() as u16, 6))
        );
    }

    #[test]
    fn caret_moves_with_the_focused_row() {
        let area = Rect::new(0, 0, 40, 20);
        let mut form = FormState::new("todo");
        // Status and Priority are picker rows and show no caret (tix #1508), so
        // walk on to the first typeable row below them: the caret moved with the
        // focused row, and it is on *that* row.
        for _ in 0..3 {
            form.move_focus_next();
        }
        assert_eq!(form.focus, FormFocus::Labels);
        assert_eq!(
            caret_position(&form, area),
            // Row 3 of the ring, and the inner area already starts one row down.
            Some(Position::new(1 + "> Labels: ".len() as u16, 4))
        );
    }

    /// The caret follows the insertion point, not the end of the value, and a
    /// long value is windowed so the caret stays inside the row (tix #1746).
    #[test]
    fn caret_follows_the_insertion_point_inside_a_long_value() {
        let area = Rect::new(0, 0, 20, 20);
        let mut form = FormState::new("todo");
        form.title = "x".repeat(100);
        form.cursor_to_start();
        // Inner width is 18; the caret at the start sits right after "> Title: ".
        assert_eq!(
            caret_position(&form, area),
            Some(Position::new(1 + "> Title: ".len() as u16, 1))
        );

        form.cursor = 50;
        assert_eq!(
            caret_position(&form, area),
            Some(Position::new(18, 1)),
            "mid-value, the caret is still the last cell the row can hold"
        );
    }

    /// Width is not length: a two-character title occupies four cells, and the caret
    /// follows the cells.
    #[test]
    fn caret_measures_display_width_not_char_count() {
        let area = Rect::new(0, 0, 40, 20);
        let mut form = FormState::new("todo");
        form.title = "中日".to_string();
        form.cursor_to_end();
        assert_eq!(
            caret_position(&form, area),
            Some(Position::new(1 + "> Title: ".len() as u16 + 4, 1))
        );
    }

    /// A value wider than the field is clipped, so its true caret is off-screen; the
    /// position must stay inside the row rather than point past the border.
    #[test]
    fn caret_is_clamped_into_the_visible_row() {
        let area = Rect::new(0, 0, 20, 20);
        let mut form = FormState::new("todo");
        form.title = "x".repeat(100);
        form.cursor_to_end();
        // Inner width is 18, so the row's last cell is x = 18.
        assert_eq!(caret_position(&form, area), Some(Position::new(18, 1)));
    }

    #[test]
    fn no_caret_on_a_picker_only_field() {
        let area = Rect::new(0, 0, 40, 20);
        let mut form = FormState::new("todo");
        form.focus = FormFocus::Parent;
        assert_eq!(caret_position(&form, area), None);
    }

    #[test]
    fn caret_is_not_placed_outside_the_visible_form() {
        // Four rows: the ring's later fields are below the fold and get no caret,
        // because a position outside the rendered area would be drawn nowhere.
        let area = Rect::new(0, 0, 40, 4);
        let mut form = FormState::new("todo");
        form.focus = FormFocus::Reviewer;
        assert_eq!(caret_position(&form, area), None);
    }

    #[test]
    fn with_default_assignee_populates_assignee_field() {
        let form = FormState::with_default_assignee("in progress", "alice");
        assert_eq!(form.assignee, "alice");
        assert_eq!(form.status, "in progress");
        assert_eq!(form.focus, FormFocus::Title);
    }

    /// WP06 T029/T031: the Projects and Epics rows are picker-only lists of resolved
    /// ids, appended in that order at the end of the ring.
    #[test]
    fn t029_the_projects_and_epics_rows_are_picker_only_and_appended_in_the_ring() {
        assert!(FormFocus::Projects.is_project());
        assert!(FormFocus::Projects.refuses_typing());
        assert!(FormFocus::Projects.is_picker_only());
        assert!(!FormFocus::Projects.is_date());
        assert_eq!(FormFocus::Projects.label(), "Projects");
        assert_eq!(
            FormFocus::RING.len(),
            17,
            "the rows are appended, not slotted in"
        );
        assert_eq!(
            FormFocus::RING[15],
            FormFocus::Projects,
            "no existing index moved"
        );
        // WP06 T031: `Epics` is the newest last row, the exact analogue of `Projects`.
        assert!(FormFocus::Epics.is_epic());
        assert!(FormFocus::Epics.refuses_typing());
        assert!(FormFocus::Epics.is_picker_only());
        assert_eq!(FormFocus::Epics.label(), "Epics");
        assert_eq!(FormFocus::RING[16], FormFocus::Epics, "last in the ring");

        let mut form = FormState::new("todo");
        assert_eq!(form.projects, "", "a new issue starts unassociated");
        assert_eq!(form.epics, "", "and references no epic");
        form.focus = FormFocus::Projects;
        form.insert_char('p');
        assert_eq!(form.projects, "", "typing is refused on the Projects row");
        form.focus = FormFocus::Epics;
        form.insert_char('e');
        assert_eq!(form.epics, "", "typing is refused on the Epics row");

        // A multi-select picker writes the chosen ids back as a comma-joined list,
        // which is the shape `apply_picker_selection` and the submit path share.
        *form
            .focused_value_mut()
            .expect("the row has a buffer to receive a selection") = "e-1,e-2".to_string();
        assert_eq!(form.value_of(FormFocus::Epics), "e-1,e-2");
        assert_eq!(form.focused_value(), "e-1,e-2");
    }

    /// WP06 T031 step 2: an edit pre-selects the issue's current references, so
    /// submitting after touching nothing cannot drop them.
    #[test]
    fn t031_an_edit_preselects_the_issues_current_epic_references() {
        let issue = Issue::parse(
            "---\nnumber: 7\ntitle: T\nstatus: todo\nlabels: []\npriority: medium\nepics:\n- e-1\n- e-gone\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nB.",
        )
        .unwrap();
        let form = FormState::from_issue(&issue);
        assert_eq!(
            form.epics, "e-1,e-gone",
            "the stored references travel verbatim, including a dangling one"
        );
    }

    /// WP06 T029 step 2: an edit pre-selects the issue's current associations, so
    /// submitting after touching nothing cannot drop them.
    #[test]
    fn t029_from_issue_carries_the_associations_and_a_dangling_reference_verbatim() {
        let issue = Issue::parse(
            "---\nnumber: 7\ntitle: T\nstatus: todo\nlabels: []\npriority: medium\nprojects:\n- p-1\n- p-gone\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nB.",
        )
        .unwrap();
        let form = FormState::from_issue(&issue);
        assert_eq!(
            form.projects, "p-1,p-gone",
            "the stored list is carried verbatim, including a reference the registry \
             no longer holds, so a clone cannot quietly drop it"
        );
        assert_eq!(form.value_of(FormFocus::Projects), "p-1,p-gone");
    }

    /// The control rows are chosen or toggled, never typed: a keypress on them
    /// must not reach a buffer.
    #[test]
    fn control_rows_refuse_typed_characters() {
        let mut form = FormState::new("todo");
        for (focus, before) in [
            (FormFocus::Target, form.target.label().to_string()),
            (FormFocus::Template, form.template.clone()),
            (FormFocus::Projects, form.projects.clone()),
        ] {
            form.focus = focus;
            assert!(focus.refuses_typing(), "{focus:?} refuses typing");
            form.insert_char('9');
            form.delete_char();
            assert_eq!(
                form.value_of(focus),
                before,
                "typing must not reach {focus:?}"
            );
        }
        // The body is *not* a control row: it accepts typed text like the rest.
        form.focus = FormFocus::Body;
        form.insert_char('h');
        form.insert_char('i');
        assert_eq!(form.body, "hi");
    }

    /// Status and Priority are chosen from dropdowns (tix #1508), so typed
    /// characters and backspace must leave their buffers exactly as they were —
    /// free text could name a column the board does not configure, or a priority
    /// no issue carries.
    #[test]
    fn the_status_and_priority_rows_refuse_typed_characters() {
        let mut form = FormState::new("todo");
        form.priority = "high".to_string();
        for (focus, before) in [
            (FormFocus::Status, form.status.clone()),
            (FormFocus::Priority, form.priority.clone()),
        ] {
            form.focus = focus;
            assert!(focus.refuses_typing(), "{focus:?} refuses typing");
            assert!(focus.is_picker_only(), "{focus:?} is picker-only");
            assert!(!focus.is_date(), "{focus:?} is not a date row");
            form.insert_char('9');
            form.insert_char('x');
            form.delete_char();
            assert_eq!(
                form.value_of(focus),
                before,
                "typing must not reach {focus:?}"
            );
        }
        // But a *picked* value does reach them, through the same accessors.
        form.focus = FormFocus::Status;
        form.status = "in progress".to_string();
        assert_eq!(form.focused_value(), "in progress");
        form.focus = FormFocus::Priority;
        assert_eq!(form.focused_value(), "high");
    }

    /// A chosen row shows no insertion point: the caret must not advertise an
    /// editing affordance the row refuses (tix #1508).
    #[test]
    fn no_caret_on_the_status_and_priority_rows() {
        let area = Rect::new(0, 0, 40, 30);
        let mut form = FormState::new("todo");
        form.focus = FormFocus::Status;
        assert_eq!(caret_position(&form, area), None);
        form.focus = FormFocus::Priority;
        assert_eq!(caret_position(&form, area), None);
    }

    /// A multi-line body is folded to one display row, so the row arithmetic the
    /// caret depends on holds; the stored value keeps the real newlines.
    #[test]
    fn body_newlines_are_escaped_for_display_only() {
        let mut form = FormState::new("todo");
        form.body = "a\nb".to_string();
        assert_eq!(form.body, "a\nb", "the stored body is verbatim");
        assert_eq!(form.display_value(FormFocus::Body), "a\\nb");

        let area = Rect::new(0, 0, 40, 30);
        form.focus = FormFocus::Body;
        form.cursor_to_end();
        let row = field_row_rect(area, FormFocus::Body).expect("body row is visible");
        assert_eq!(
            caret_position(&form, area),
            Some(Position::new(row.x + "> Body: a\\nb".len() as u16, row.y)),
            "the caret follows the folded display, not the raw newline"
        );
    }

    /// A template pre-fills the rows it sets and leaves the rest alone, so a
    /// labels-only template cannot erase a title the user already typed.
    #[test]
    fn apply_template_fills_set_fields_and_keeps_the_others() {
        let mut form = FormState::new("todo");
        form.title = "typed".to_string();
        let template = crate::config::IssueTemplate {
            body: Some("template body".to_string()),
            labels: vec!["bug".to_string(), "urgent".to_string()],
            ..crate::config::IssueTemplate::default()
        };
        form.apply_template("bug-report", &template);
        assert_eq!(form.template, "bug-report");
        assert_eq!(form.body, "template body");
        assert_eq!(form.labels, "bug,urgent");
        assert_eq!(form.title, "typed", "an omitted field is left untouched");
    }

    #[test]
    fn no_caret_on_a_target_or_template_row() {
        let area = Rect::new(0, 0, 40, 30);
        let mut form = FormState::new("todo");
        form.focus = FormFocus::Target;
        assert_eq!(caret_position(&form, area), None);
        form.focus = FormFocus::Template;
        assert_eq!(caret_position(&form, area), None);
    }

    /// A stable-ID template seeds only the rows it sets, records its **ID** (not
    /// its display name) and its explicit scope, and never interprets unknown
    /// metadata (WP05/T024).
    #[test]
    fn apply_stable_template_seeds_rows_and_records_the_stable_id_and_scope() {
        use crate::templates::registry::{PromptKind, TemplateDefaults, TemplatePrompt};
        let mut form = FormState::new("todo");
        form.title = "typed".to_string();
        let template = crate::templates::Template {
            name: Some("Bug report".to_string()),
            defaults: TemplateDefaults {
                body: Some("## Steps\n".to_string()),
                labels: vec!["bug".to_string()],
                ..TemplateDefaults::default()
            },
            // A prompt default outranks the block default for the same key, the
            // same precedence the resolver merges them with.
            prompts: vec![
                TemplatePrompt {
                    key: "priority".to_string(),
                    label: None,
                    kind: PromptKind::Select,
                    required: false,
                    default: Some("high".to_string()),
                    options_ref: None,
                },
                // An unknown-metadata-ish key cannot exist (the registry rejects
                // it), so a prompt with no default leaves its row untouched.
                TemplatePrompt {
                    key: "estimate".to_string(),
                    label: None,
                    kind: PromptKind::Text,
                    required: true,
                    default: None,
                    options_ref: None,
                },
            ],
            ..crate::templates::Template::default()
        };
        form.apply_stable_template("bug", "repository", &template);
        assert_eq!(form.template, "bug", "the stored value is the stable ID");
        assert_eq!(form.template_scope.as_deref(), Some("repository"));
        assert_eq!(form.body, "## Steps\n");
        assert_eq!(form.labels, "bug");
        assert_eq!(form.priority, "high", "a prompt default wins");
        assert_eq!(form.title, "typed", "an omitted row is left untouched");
        assert_eq!(
            form.estimate, "",
            "a required prompt with no value stays empty for the resolver"
        );

        // The scope is visible on the row without changing the stored ID.
        assert_eq!(form.display_value(FormFocus::Template), "bug [repository]");
    }

    /// Selecting a legacy `[templates.<name>]` record clears any stable scope, so
    /// the submit path cannot route a legacy pre-fill through the stable resolver.
    #[test]
    fn legacy_apply_template_clears_the_stable_scope() {
        let mut form = FormState::new("todo");
        form.apply_stable_template("bug", "repository", &crate::templates::Template::default());
        assert!(form.template_scope.is_some());
        form.apply_template(
            "old",
            &crate::config::IssueTemplate {
                labels: vec!["legacy".to_string()],
                ..crate::config::IssueTemplate::default()
            },
        );
        assert_eq!(form.template, "old");
        assert_eq!(form.template_scope, None);
    }
}