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
//! The `F8` Schedule page: the **Series** tab (tix #1593, mission
//! `recurring-issues-01M3C7G7` WP07) and the **Cycle schedules** tab (mission
//! `repeating-cycle-schedules-01M3C7W1` WP07, tix #181).
//!
//! # What the page is for
//!
//! The due warning ([`crate::ui::recurring_warning`]) answers "something is due —
//! what now?" once. This page is where the series *live*: their identity, rule,
//! lifecycle state, cursor and skipped dates, and the keys that act on them. It is
//! a top-level mode like `F4`/`F5`/`F6`, not a modal, so the board's own state is
//! not borrowed while a user manages a schedule.
//!
//! # Three tabs
//!
//! `F8` Schedule holds three tabs — Series (#175), Cycle schedules (#181, this one)
//! and Capacity (#182, WP06 of mission `cycle-capacity-planning-01M3C85C`). Series
//! ships with the recurring-issues mission, Cycle schedules with #181 and Capacity
//! with the cycle-capacity mission; the strip draws exactly the tabs that exist
//! rather than pretending others do.
//!
//! All three tabs are *renderers*: the page owns no registry, no evaluator and no
//! generator. Every value comes from [`crate::app::App`], which reads the one
//! service each figure belongs to — so a tab and `tix recurring …`/
//! `tix cycle schedule …`/`tix capacity …` cannot disagree (C-008/NFR-003), and the
//! page can hold no second evaluator, cursor or History grammar. The one thing the
//! page *does* define is the two **forms** that collect a record's fields —
//! [`ScheduleForm`] for a cycle schedule and [`SeriesForm`] for a recurring series —
//! and each submit is the shared service's: the cycle registry's
//! [`create`](crate::cycle_schedule::registry::create)/
//! [`edit`](crate::cycle_schedule::registry::edit) — which the CLI's `--confirm` and
//! the MCP tools also reach — and `tix recurring create`'s own `create_series`,
//! which the CLI and this page's form share (no MCP tool creates a series).
//!
//! # The Capacity tab renders what the CLI exposes
//!
//! Each row is one configured scope ([`CapacityRow`]): the resolved display label
//! `tix capacity list` prints, beside the shared calculation's compact values and
//! unit. The detail pane carries the **same fields `tix capacity calculate` prints**
//! (`print_calculation`'s order, verbatim), each finding through the shared
//! [`crate::capacity::warning::CapacityWarning::render`] — its reason and its remedy
//! — and, for a cycle scope, the immutable close evidence `tix capacity snapshot`
//! reads back, labelled historical beside the live values (T033). Nothing is
//! recomputed here: every number is a field of [`crate::capacity::calculate::CapacityCalculation`]
//! or [`crate::capacity::snapshot::CapacitySnapshot`], and an absent value prints `-`
//! rather than `0`.
//!
//! # The Cycle schedules tab renders what the CLI exposes
//!
//! Each schedule row carries the fields `tix cycle schedule list` prints; the detail
//! pane carries the values `tix cycle schedule show` prints (identity, cadence,
//! duration, start date, timezone, look-ahead and the derived cursor), the schedule's
//! generated cycles (`id`, `sequence`, `name`, dates, `state`), its closed snapshots
//! (`docs/cycle_snapshots/…`) and the findings [`crate::cycle_schedule::identity`]
//! reported — plus the warnings `tix cycle schedule detect` evaluates. Nothing is a
//! TUI-only number, and both empty states say how to stop being empty.
//!
//! # The keys act through the shared services
//!
//! Series tab: `n` defines a series (the same `tix recurring create` the CLI runs),
//! `p`ause / `r`esume / `x` end change lifecycle state; `g`enerate,
//! `s`kip, `d`efer and `i`gnore act on the series' **due candidate** as the shared
//! detector reports it. Cycle schedules tab: `n` defines a schedule and `E`
//! (`e`xtend owns the lowercase) edits the selected one through the form; `g`enerate
//! runs WP04's confirmed generator; `p`ause/`r`esume/adjust-future (`a`)/`i`gnore act
//! on the schedule, and `c`lose / `e`xtend / `s`kip act on its current instance —
//! each as a WP05 confirmed lifecycle request. The four actions that record a reason
//! collect one first, and every outcome is the service's own word
//! (`created`/`no-op`/`rejected`, `applied`/`no-op`/`rejected`) rather than a private
//! success/failure notion. A series or schedule with nothing to act on says so instead
//! of inventing a target, and no answer is ever a refresh effect (C-003/C-004).
//!
//! `Tab`/`Shift+Tab` switch tabs. They are read raw by the page (the page's
//! `[keybindings.schedule]` section binds the Series actions), exactly as the
//! Portfolio page's Roadmap tab reads its own command letters raw — and for the same
//! reason `E`, `c`, `R`, `e` and `a` on the Cycle schedules tab are.

use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};

use crate::app::App;
use crate::cycle_schedule::config::CycleScheduleId;
use crate::cycle_schedule::identity::GeneratedCycleId;
use crate::cycle_schedule::lifecycle::LifecycleAction;
use crate::keybindings::TuiAction;

/// Which tab of the page is showing.
///
/// A `const ALL` in display order, like the Library and Portfolio pages' tabs: the
/// strip, the hint line, the cursor clamp and the empty state all read this list,
/// so a further tab (Capacity, #182) is additive here and nowhere else.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum ScheduleTab {
    /// The recurring series (mission `recurring-issues-01M3C7G7`, #175).
    #[default]
    Series,
    /// The configured cycle schedules and the cycles they generated (#181).
    Cycles,
    /// The configured capacity scopes and their shared calculations (mission
    /// `cycle-capacity-planning-01M3C85C`, WP06, #182).
    Capacity,
}

impl ScheduleTab {
    /// The tabs in display order.
    pub const ALL: [Self; 3] = [Self::Series, Self::Cycles, Self::Capacity];

    /// The tab's label in the strip.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Series => "Series",
            Self::Cycles => "Cycle schedules",
            Self::Capacity => "Capacity",
        }
    }

    /// The next tab, wrapping. `Tab` moves forward.
    pub const fn next(self) -> Self {
        match self {
            Self::Series => Self::Cycles,
            Self::Cycles => Self::Capacity,
            Self::Capacity => Self::Series,
        }
    }

    /// The previous tab, wrapping. `Shift+Tab` moves backward.
    ///
    /// Spelled out rather than delegated to [`Self::next`]: with three tabs `next`
    /// and `prev` are no longer inverses of one another, so sharing one body would
    /// make `Shift+Tab` step forward.
    pub const fn prev(self) -> Self {
        match self {
            Self::Series => Self::Capacity,
            Self::Cycles => Self::Series,
            Self::Capacity => Self::Cycles,
        }
    }

    /// The keys this tab answers to, as its hint line.
    pub const fn hint(self) -> &'static str {
        match self {
            Self::Series => SERIES_KEYS,
            Self::Cycles => CYCLE_SCHEDULE_KEYS,
            Self::Capacity => CAPACITY_KEYS,
        }
    }

    /// What the tab says when there is nothing to show, including how to fill it.
    ///
    /// Kept here rather than in the app so the sentence is a property of the page a
    /// test can assert, not a string literal inside a render function.
    pub const fn empty_hint(self) -> &'static str {
        match self {
            Self::Series => {
                "No recurring series yet. Create one with \
                 `tix recurring create --title <TITLE> --rule daily --anchor <DATE>`, \
                 or press `n` to create one here."
            }
            Self::Cycles => {
                "No cycle schedules yet. Create one with `tix cycle schedule create --id <ID> \
                 --name <NAME> --cadence <KIND> --duration <N> --duration-unit <UNIT> \
                 --start-date <DATE> --timezone <TZ> --confirm`."
            }
            Self::Capacity => {
                "No capacity configured. Configure one with `tix capacity set --scope \
                 <cycle|team|assignee> --id <REFERENCE> --value <N> --unit <UNIT>`."
            }
        }
    }
}

/// The page's own state: which tab is showing, which row the cursor is on, the reason
/// prompt when one is open, and the create/edit form when one is.
///
/// Session-only: nothing here is persisted, and the page owns no value the services
/// do not already own.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScheduleState {
    /// The tab in view.
    pub tab: ScheduleTab,
    /// The selected row within the active tab.
    pub selected: usize,
    /// The reason prompt, `Some` exactly while the page is collecting the reason a
    /// lifecycle action records (T037).
    pub prompt: Option<CycleReasonPrompt>,
    /// The create/edit form, `Some` exactly while the page is defining a schedule
    /// (T036).
    pub form: Option<ScheduleForm>,
    /// The Series tab's create form, `Some` exactly while the page is defining a
    /// recurring series.
    ///
    /// A **separate** field from [`Self::form`] rather than a variant of it: the two
    /// forms collect different fields (`title`/`rule`/`anchor` against the ten cycle
    /// schedule fields) and submit to different services, and one `Option` per form
    /// is what makes "which tab defined what" a property of the state rather than
    /// something a render has to infer.
    pub series_form: Option<SeriesForm>,
}

impl ScheduleState {
    /// A fresh page, on the first tab with the cursor on the first row.
    pub fn new() -> Self {
        Self::default()
    }

    /// Move the cursor by `delta`, clamped to `rows` entries.
    pub fn move_selected(&mut self, delta: isize, rows: usize) -> bool {
        let last = rows.saturating_sub(1);
        let before = self.selected;
        let next = if delta.is_negative() {
            self.selected.saturating_sub(delta.unsigned_abs())
        } else {
            self.selected.saturating_add(delta as usize)
        };
        self.selected = next.min(last);
        self.selected != before
    }

    /// Clamp the cursor into `rows` entries, for a registry that changed under the
    /// page.
    pub fn clamp_selected(&mut self, rows: usize) {
        self.selected = self.selected.min(rows.saturating_sub(1));
    }

    /// Step to the next (`delta` ≥ 0) or previous tab, wrapping, and reset the row
    /// cursor: it indexes the *active* tab's rows, so it must not carry over.
    pub fn switch_tab(&mut self, delta: isize) {
        self.tab = if delta.is_negative() {
            self.tab.prev()
        } else {
            self.tab.next()
        };
        self.selected = 0;
    }
}

/// One row of the Series tab, as display data: the widget never reads a registry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScheduleEntry {
    /// The series' display name.
    pub title: String,
    /// Its stable id, rule, state and cursor, as one dimmed tail.
    pub subtitle: String,
    /// Whether the series is currently due (its candidate has arrived).
    pub due: bool,
}

/// One row of the **Cycle schedules** tab, as display data.
///
/// The twin of [`ScheduleEntry`] for the other tab; the widget still reads nothing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CycleScheduleEntry {
    /// The schedule's display name.
    pub title: String,
    /// Its stable id, state, cadence, anchor and generated count, as one dimmed tail.
    pub subtitle: String,
    /// Whether the last evaluation reported a warning for it.
    pub warned: bool,
}

/// The `key: value` lines of the Series tab's detail pane, plus its heading.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScheduleDetail {
    /// The heading, e.g. `Series`.
    pub heading: String,
    /// The lines, in a stable order.
    pub lines: Vec<(String, String)>,
}

/// The Cycle schedules tab's detail pane: the schedule's own fields, then its
/// generated cycles, closed snapshots, identity findings and evaluated warnings.
///
/// Every section is a list of already-rendered lines, so the widget composes text
/// and computes nothing — the same rule the Series tab's [`ScheduleDetail`] follows.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CycleScheduleDetail {
    /// The schedule record's own `key: value` facts.
    pub fields: Vec<(String, String)>,
    /// One line per generated cycle.
    pub cycles: Vec<String>,
    /// One line per closed snapshot.
    pub snapshots: Vec<String>,
    /// One line per identity finding.
    pub findings: Vec<String>,
    /// One line per evaluated warning.
    pub warnings: Vec<String>,
}

/// One row of the **Capacity** tab, as display data (WP06 T030/T032).
///
/// Every figure it names is a field of the shared [`crate::capacity::calculate::CapacityCalculation`],
/// already formatted by the caller: the widget composes text and computes nothing, the
/// same rule the page's other tabs follow.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CapacityRow {
    /// The scope's resolved display label — **which scope the figures belong to**, the
    /// same `display` `tix capacity list`/`calculate` print.
    pub title: String,
    /// The compact `key: value` tail: the scope kind, the state, the values and the
    /// unit, with an absent value as `-` (never `0`).
    pub subtitle: String,
    /// Whether the calculation carried any finding (an overflow, an uncountable
    /// estimate, an unresolved reference).
    pub warned: bool,
    /// Whether the scope's committed work exceeds its ceiling
    /// ([`crate::capacity::calculate::CapacityCalculation::is_over_capacity`]).
    pub overflowing: bool,
}

/// A closed cycle's immutable capacity evidence, as the Capacity tab's detail draws it
/// (WP06 T033).
///
/// The `label` is the explicit **current-vs-historical** statement; the fields are the
/// ones `tix capacity snapshot <CYCLE>` prints, in that command's order.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CapacitySnapshotView {
    /// The current-vs-historical label, and whether the cycle has been reopened or
    /// edited since the close.
    pub label: String,
    /// The stored evidence's own fields, exactly as the close wrote them.
    pub fields: Vec<(String, String)>,
}

/// The Capacity tab's detail pane (WP06 T030/T033): the selected scope's shared
/// calculation, its findings with their remedies, and — for a cycle scope with a closed
/// snapshot — the immutable close evidence beside the live values.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CapacityDetail {
    /// The pane's heading: the scope's resolved display label.
    pub heading: String,
    /// The calculation's own fields, in `tix capacity calculate`'s order.
    pub fields: Vec<(String, String)>,
    /// Each finding, rendered through [`crate::capacity::warning::CapacityWarning::render`]
    /// — its reason **and** its remedy, one string per line.
    pub diagnostics: Vec<String>,
    /// The immutable close evidence, `Some` exactly when the scope is a cycle with a
    /// recorded snapshot.
    pub snapshot: Option<CapacitySnapshotView>,
}

/// The capacity read the page renders (WP06): the configured scopes' rows and their
/// details, plus the compact per-cycle cells the board's cycle group headers show.
///
/// Built once per refresh by [`crate::app::App`] from the **shared** DTOs — the same
/// one-pass pair and the same `for_scope` the CLI's `tix capacity calculate` calls — so
/// no value here is a TUI-only number (C-007/NFR-003).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CapacityView {
    /// One row per configured scope, in declaration order.
    pub rows: Vec<CapacityRow>,
    /// The selected row's detail, by the same index as [`Self::rows`].
    pub details: Vec<CapacityDetail>,
    /// A compact cell per cycle scope, keyed by the reference a card names **and** by
    /// the scope's resolved display label, for the board's grouped-by-cycle headers.
    pub summaries: std::collections::BTreeMap<String, String>,
}

/// The reason a lifecycle action records, being typed.
///
/// The action and its target are captured when the prompt opens, so confirming it
/// cannot drift onto another row: the prompt carries the schedule and the instance
/// it is about.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CycleReasonPrompt {
    /// The schedule the action names.
    pub schedule: CycleScheduleId,
    /// The action that records the reason.
    pub action: LifecycleAction,
    /// The instance the action names, when it names one.
    pub cycle: Option<GeneratedCycleId>,
    /// The reason being typed.
    pub buffer: String,
}

/// One row of the `create`/`edit` form (T036).
///
/// The spellings are the CLI's: the form collects text and the shared registry parses
/// it, so "is `fortnightly` a cadence family" has one answer for every surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ScheduleField {
    /// The stable id; the registry key, and create-only.
    Id,
    /// The display label.
    Name,
    /// The cadence family.
    Cadence,
    /// How many cadence units between starts.
    Interval,
    /// The unit an `interval` cadence counts in.
    Unit,
    /// How long one cycle lasts.
    Duration,
    /// The duration's unit.
    DurationUnit,
    /// The anchor date.
    StartDate,
    /// The fixed UTC offset.
    Timezone,
    /// How many future cycles to consider.
    LookAhead,
}

impl ScheduleField {
    /// Every field, in the form's row order.
    pub const ALL: [Self; 10] = [
        Self::Id,
        Self::Name,
        Self::Cadence,
        Self::Interval,
        Self::Unit,
        Self::Duration,
        Self::DurationUnit,
        Self::StartDate,
        Self::Timezone,
        Self::LookAhead,
    ];

    /// The fields an **edit** shows: everything but the identity, which is the
    /// registry key and does not change — a rename is a new `name`, not a new id.
    pub const EDIT: [Self; 9] = [
        Self::Name,
        Self::Cadence,
        Self::Interval,
        Self::Unit,
        Self::Duration,
        Self::DurationUnit,
        Self::StartDate,
        Self::Timezone,
        Self::LookAhead,
    ];

    /// The row's label.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Id => "id",
            Self::Name => "name",
            Self::Cadence => "cadence",
            Self::Interval => "interval",
            Self::Unit => "unit",
            Self::Duration => "duration",
            Self::DurationUnit => "duration-unit",
            Self::StartDate => "start-date",
            Self::Timezone => "timezone",
            Self::LookAhead => "look-ahead",
        }
    }

    /// What the field accepts, shown beside it. The spellings are the contract's.
    pub const fn hint(self) -> &'static str {
        match self {
            Self::Id => "stable, never reused",
            Self::Name => "display label",
            Self::Cadence => "daily | weekly | monthly | interval",
            Self::Interval => "1-1000 (interval cadence)",
            Self::Unit => "days | weeks | months",
            Self::Duration => "positive count",
            Self::DurationUnit => "days | weeks | months",
            Self::StartDate => "YYYY-MM-DD",
            Self::Timezone => "UTC or ±HH:MM",
            Self::LookAhead => "future cycles to consider",
        }
    }

    /// Whether the field carries a calendar date, for the hint's sake.
    pub const fn is_date(self) -> bool {
        matches!(self, Self::StartDate)
    }
}

/// The `create`/`edit` form the Cycle schedules tab shows (T036).
///
/// A **page-local** form: the page owns it, exactly as it owns the reason prompt, so
/// defining a schedule needs no new mode, no new `InputContext` and no new binding.
/// It collects text and nothing else — every rule about what the text may be is the
/// shared registry's, and a refusal keeps the form open with the message on it rather
/// than closing and losing what was typed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScheduleForm {
    /// The id being edited, or `None` when the form creates a new schedule.
    pub editing: Option<String>,
    /// The fields shown, in row order.
    pub fields: Vec<ScheduleField>,
    /// The typed value per shown field, in the same order.
    pub values: Vec<String>,
    /// The focused row.
    pub focus: usize,
    /// The refusal the last save produced, kept while the form stays open.
    pub error: Option<String>,
}

impl ScheduleForm {
    /// A form that creates a schedule: every field empty, the id focused first.
    pub fn create() -> Self {
        let fields = ScheduleField::ALL.to_vec();
        let values = vec![String::new(); fields.len()];
        Self {
            editing: None,
            fields,
            values,
            focus: 0,
            error: None,
        }
    }

    /// A form that edits `id`, pre-filled from `values` (in [`ScheduleField::EDIT`]
    /// order).
    ///
    /// A short or long `values` is tolerated rather than panicking: the form is a
    /// session value a test can build by hand, and a missing value is an empty field.
    pub fn edit(id: String, values: Vec<String>) -> Self {
        let fields = ScheduleField::EDIT.to_vec();
        let mut filled = values;
        filled.resize(fields.len(), String::new());
        Self {
            editing: Some(id),
            fields,
            values: filled,
            focus: 0,
            error: None,
        }
    }

    /// The form's block title: what it is about to do, and to what.
    pub fn title(&self) -> String {
        match &self.editing {
            Some(id) => format!("Edit cycle schedule `{id}` (enter: save, esc: cancel)"),
            None => "New cycle schedule (enter: save, esc: cancel)".to_string(),
        }
    }

    /// The focused field.
    pub fn focused(&self) -> ScheduleField {
        self.fields
            .get(self.focus)
            .copied()
            .unwrap_or(ScheduleField::Id)
    }

    /// The typed value of `field` (`""` when the form does not show it).
    pub fn value(&self, field: ScheduleField) -> &str {
        self.fields
            .iter()
            .position(|shown| *shown == field)
            .and_then(|index| self.values.get(index))
            .map(String::as_str)
            .unwrap_or("")
    }

    /// Step the focus forward, wrapping.
    pub fn focus_next(&mut self) {
        let len = self.fields.len().max(1);
        self.focus = (self.focus + 1) % len;
    }

    /// Step the focus backward, wrapping.
    pub fn focus_prev(&mut self) {
        let len = self.fields.len().max(1);
        self.focus = (self.focus + len - 1) % len;
    }

    /// Append a character to the focused field.
    pub fn insert_char(&mut self, c: char) {
        let focus = self.focus;
        if let Some(value) = self.values.get_mut(focus) {
            value.push(c);
        }
    }

    /// Remove the focused field's last character.
    pub fn delete_char(&mut self) {
        let focus = self.focus;
        if let Some(value) = self.values.get_mut(focus) {
            value.pop();
        }
    }

    /// Empty the focused field, for a value being replaced rather than extended.
    pub fn clear_field(&mut self) {
        let focus = self.focus;
        if let Some(value) = self.values.get_mut(focus) {
            value.clear();
        }
    }

    /// Keep the refusal on the form, so the message and what was typed stay together.
    pub fn set_error(&mut self, message: String) {
        self.error = Some(message);
    }
}

/// One row of the Series tab's create form.
///
/// The spellings are the CLI's: the form collects text and the shared create service
/// parses it, so "is `fortnightly` a rule family" has one answer for every surface.
/// Only the three fields a first series cannot do without are collected — the issue's
/// `--body`/`--status`/`--priority`/… keep their CLI defaults, and `--name` defaults
/// to the title, exactly as `tix recurring create` leaves them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SeriesField {
    /// The series issue's title (and the default display name).
    Title,
    /// The rule family: what `--rule` accepts.
    Rule,
    /// The schedule origin, `YYYY-MM-DD`.
    Anchor,
}

impl SeriesField {
    /// Every field, in the form's row order.
    pub const ALL: [Self; 3] = [Self::Title, Self::Rule, Self::Anchor];

    /// The row's label.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Title => "title",
            Self::Rule => "rule",
            Self::Anchor => "anchor",
        }
    }

    /// What the field accepts, shown beside it. The spellings are the contract's.
    ///
    /// The rule hint names only the families the form's three fields can complete:
    /// `interval` needs a count and a unit and `cron-like` needs an expression, so
    /// offering them here would advertise a choice the form always refuses. They are
    /// named in [`SeriesForm::NOTE`] as the CLI's, not the form's.
    pub const fn hint(self) -> &'static str {
        match self {
            Self::Title => "issue title (required)",
            Self::Rule => "daily | weekly | monthly",
            Self::Anchor => "YYYY-MM-DD",
        }
    }
}

/// The Series tab's create form.
///
/// A **page-local** form, the twin of [`ScheduleForm`]: the page owns it, so defining
/// a series needs no new mode, no new `InputContext` and no new binding. It collects
/// text and nothing else — every rule about what the text may be is the shared create
/// service's, and a refusal keeps the form open with the message on it rather than
/// closing and losing what was typed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SeriesForm {
    /// The fields shown, in row order.
    pub fields: Vec<SeriesField>,
    /// The typed value per shown field, in the same order.
    pub values: Vec<String>,
    /// The focused row.
    pub focus: usize,
    /// The refusal the last save produced, kept while the form stays open.
    pub error: Option<String>,
}

impl SeriesForm {
    /// Where the rule families the form cannot express are defined.
    ///
    /// The three fields complete `daily`, `weekly` and `monthly`. The other two
    /// families need arguments the form does not collect, so rather than offer them
    /// (and refuse), the form says where they live — the same service, the CLI's own
    /// flags. Asserted against [`SeriesField::Rule::hint`] by a test, so the two can
    /// not drift apart again.
    pub const NOTE: &'static str = "`interval` and `cron-like` rules need the CLI: \
                                    `tix recurring create --rule <FAMILY> --interval \
                                    <N> --unit <UNIT>`.";

    /// A form that creates a series: every field empty, the title focused first.
    pub fn create() -> Self {
        Self {
            fields: SeriesField::ALL.to_vec(),
            values: vec![String::new(); SeriesField::ALL.len()],
            focus: 0,
            error: None,
        }
    }

    /// The form's block title: what it is about to do, and the keys it answers to.
    pub fn title(&self) -> &'static str {
        "New recurring series (enter: save, esc: cancel)"
    }

    /// The focused field.
    pub fn focused(&self) -> SeriesField {
        self.fields
            .get(self.focus)
            .copied()
            .unwrap_or(SeriesField::Title)
    }

    /// The typed value of `field` (`""` when the form does not show it).
    pub fn value(&self, field: SeriesField) -> &str {
        self.fields
            .iter()
            .position(|shown| *shown == field)
            .and_then(|index| self.values.get(index))
            .map(String::as_str)
            .unwrap_or("")
    }

    /// Step the focus forward, wrapping.
    pub fn focus_next(&mut self) {
        let len = self.fields.len().max(1);
        self.focus = (self.focus + 1) % len;
    }

    /// Step the focus backward, wrapping.
    pub fn focus_prev(&mut self) {
        let len = self.fields.len().max(1);
        self.focus = (self.focus + len - 1) % len;
    }

    /// Append a character to the focused field.
    pub fn insert_char(&mut self, c: char) {
        let focus = self.focus;
        if let Some(value) = self.values.get_mut(focus) {
            value.push(c);
        }
    }

    /// Remove the focused field's last character.
    pub fn delete_char(&mut self) {
        let focus = self.focus;
        if let Some(value) = self.values.get_mut(focus) {
            value.pop();
        }
    }

    /// Empty the focused field, for a value being replaced rather than extended.
    pub fn clear_field(&mut self) {
        let focus = self.focus;
        if let Some(value) = self.values.get_mut(focus) {
            value.clear();
        }
    }

    /// Keep the refusal on the form, so the message and what was typed stay together.
    pub fn set_error(&mut self, message: String) {
        self.error = Some(message);
    }
}

/// The rows the `?` overlay shows on the **Cycle schedules** tab, as
/// `(action, description)` for the keys the page's binding section binds.
///
/// The Series tab is served by the keybinding table's own list and its own wording.
/// This tab needs its own: the same letters act on the *schedules* rather than on a
/// series, two bound Series keys (`x` end, `d` defer) have no meaning here and must
/// not be advertised as if they did, and four of the tab's keys are read raw. Keeping
/// the list here is what stops the overlay and the tab from describing different keys.
pub const CYCLE_HELP_ACTIONS: &[(TuiAction, &str)] = &[
    (TuiAction::MoveUp, "move the cursor up"),
    (TuiAction::MoveDown, "move the cursor down"),
    (
        TuiAction::SeriesGenerate,
        "generate the schedule's look-ahead",
    ),
    (TuiAction::SeriesSkip, "skip the current cycle"),
    (TuiAction::SeriesPause, "pause the schedule"),
    (TuiAction::SeriesResume, "resume the schedule"),
    (
        TuiAction::SeriesIgnore,
        "close a warning without deciding anything",
    ),
    (TuiAction::Help, "this help"),
    (TuiAction::Close, "back to the board"),
];

/// The keys the Cycle schedules tab answers to that **no** [`TuiAction`] names,
/// because the page reads them raw: `(key, description)`.
pub const CYCLE_HELP_RAW: &[(&str, &str)] = &[
    ("tab / shift+tab", "switch tabs"),
    ("n", "define a new schedule"),
    ("E", "edit the selected schedule"),
    ("c", "close the current cycle (asks why)"),
    ("R", "reopen the closed cycle (asks why)"),
    ("e", "extend the current cycle (asks why)"),
    ("s", "skip the current cycle (asks why)"),
    ("a", "re-derive future cycles (asks why)"),
];

/// The keys the **Series** tab answers to, as its hint line.
pub const SERIES_KEYS: &str = "j/k: move  n: new  g: generate  p: pause  r: resume  x: end  \
                               s: skip  d: defer  i: ignore  q: back to the board";

/// The Series tab's hint, kept under its original name.
pub const SCHEDULE_KEYS: &str = SERIES_KEYS;

/// The keys the **Cycle schedules** tab answers to, as its hint line.
pub const CYCLE_SCHEDULE_KEYS: &str = "j/k: move  Tab: tabs  n: new  E: edit  g: generate  \
                                       c: close  R: reopen  e: extend  s: skip  p: pause  \
                                       r: resume  a: adjust-future  i: ignore  q: back to the board";

/// The keys the **Capacity** tab answers to, as its hint line.
///
/// The tab is read-only: it shows the shared calculation and acts on nothing, so
/// `j`/`k`, the tab switch and the way back are all it names.
pub const CAPACITY_KEYS: &str = "j/k: move  Tab: tabs  q: back to the board";

/// The rows the `?` overlay shows on the **Capacity** tab.
///
/// Like the Cycle schedules tab, the tab has its own row set rather than the Series
/// tab's: `g`enerate, `p`ause and the rest act on a series and mean nothing on this
/// tab, so advertising them here would name keys that do nothing.
pub const CAPACITY_HELP_ACTIONS: &[(TuiAction, &str)] = &[
    (TuiAction::MoveUp, "move the cursor up"),
    (TuiAction::MoveDown, "move the cursor down"),
    (TuiAction::Help, "this help"),
    (TuiAction::Close, "back to the board"),
];

/// The keys the Capacity tab answers to that **no** [`TuiAction`] names, because the
/// page reads them raw: `(key, description)`.
pub const CAPACITY_HELP_RAW: &[(&str, &str)] = &[("tab / shift+tab", "switch tabs")];

fn dim() -> Style {
    Style::default().fg(Color::DarkGray)
}

/// The tab strip: the page's name and every tab, the active one cyan and bold.
fn tab_line(active: ScheduleTab) -> Line<'static> {
    let mut spans = vec![
        Span::styled("F8 Schedule", Style::default().add_modifier(Modifier::BOLD)),
        Span::raw("  "),
    ];
    for (index, tab) in ScheduleTab::ALL.iter().enumerate() {
        if index > 0 {
            spans.push(Span::raw("  "));
        }
        let style = if *tab == active {
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD)
        } else {
            dim()
        };
        spans.push(Span::styled(format!("[{}]", tab.label()), style));
    }
    Line::from(spans)
}

/// The rect of every tab in the strip, in display order (WP06).
///
/// The strip is drawn by [`tab_line`] on the page's first row; this mirrors that
/// line's own widths so a pointer click can address a tab. Kept beside the renderer
/// so the two cannot drift: a label or a separator changed in one changes both.
pub fn tab_rects(area: Rect) -> Vec<(ScheduleTab, Rect)> {
    use unicode_width::UnicodeWidthStr;

    // The page's name, then the two-space gap before the first tab.
    let mut x = area.x + UnicodeWidthStr::width("F8 Schedule") as u16 + 2;
    let mut rects = Vec::with_capacity(ScheduleTab::ALL.len());
    for (index, tab) in ScheduleTab::ALL.iter().enumerate() {
        if index > 0 {
            x += 2;
        }
        let label = format!("[{}]", tab.label());
        let width = UnicodeWidthStr::width(label.as_str()) as u16;
        rects.push((*tab, Rect::new(x, area.y, width, 1)));
        x += width;
    }
    rects
}

/// The reason prompt's line: what is being decided, and what is being typed.
fn prompt_line(prompt: &CycleReasonPrompt) -> Line<'static> {
    let mut spans = vec![Span::styled(
        prompt.action.as_str().to_string(),
        Style::default().add_modifier(Modifier::BOLD),
    )];
    if let Some(cycle) = &prompt.cycle {
        spans.push(Span::raw(format!(" {cycle}")));
    }
    spans.push(Span::styled("  reason> ", dim()));
    spans.push(Span::raw(prompt.buffer.clone()));
    spans.push(Span::styled(
        "  (enter: apply  esc: cancel, nothing written)",
        dim(),
    ));
    Line::from(spans)
}

/// Draw the page: strip and hints, then the active tab's body.
pub fn render(app: &App, f: &mut Frame, area: Rect) {
    let state = app.schedule_state();

    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),
            Constraint::Length(1),
            Constraint::Min(1),
        ])
        .split(area);
    f.render_widget(Paragraph::new(tab_line(state.tab)), rows[0]);
    // A reason prompt owns the hint row: the line under the strip is the page's one
    // status line, and what the user is typing has to be visible on it.
    match state.prompt.as_ref() {
        Some(prompt) => f.render_widget(Paragraph::new(prompt_line(prompt)), rows[1]),
        None => f.render_widget(
            Paragraph::new(Span::styled(state.tab.hint(), dim())),
            rows[1],
        ),
    }

    // The create/edit form takes the whole body: it is the page's only mode that is
    // about one record rather than a list, and a half-drawn list beside it would
    // invite the page's other keys while they are inert (the form owns every key).
    // Only one of the two forms can be open — each `n` opens the one its tab owns.
    if let Some(form) = state.series_form.as_ref() {
        render_series_form(form, f, rows[2]);
        return;
    }
    if let Some(form) = state.form.as_ref() {
        render_form(form, f, rows[2]);
        return;
    }

    match state.tab {
        ScheduleTab::Series => render_series(app, f, rows[2], &state),
        ScheduleTab::Cycles => render_cycles(app, f, rows[2], &state),
        ScheduleTab::Capacity => render_capacity(app, f, rows[2], &state),
    }
}

/// The create/edit form: one row per field, the focused one marked and highlighted,
/// the keys and the last refusal under it.
///
/// It draws no value the page does not hold: the fields and the text are the state's,
/// and the refusal is the shared registry's own rendered block.
fn render_form(form: &ScheduleForm, f: &mut Frame, area: Rect) {
    let rows: Vec<(String, String, String)> = form
        .fields
        .iter()
        .map(|field| {
            (
                field.label().to_string(),
                form.value(*field).to_string(),
                field.hint().to_string(),
            )
        })
        .collect();
    render_form_fields(
        f,
        area,
        &form.title(),
        &rows,
        form.focus,
        form.error.as_deref(),
        None,
    );
}

/// The Series tab's create form: the same shape as [`render_form`], its own fields.
fn render_series_form(form: &SeriesForm, f: &mut Frame, area: Rect) {
    let rows: Vec<(String, String, String)> = form
        .fields
        .iter()
        .map(|field| {
            (
                field.label().to_string(),
                form.value(*field).to_string(),
                field.hint().to_string(),
            )
        })
        .collect();
    render_form_fields(
        f,
        area,
        form.title(),
        &rows,
        form.focus,
        form.error.as_deref(),
        Some(SeriesForm::NOTE),
    );
}

/// Draw a form body: `(label, value, hint)` per row, the focused one marked and
/// highlighted, the field keys and the last refusal under it.
///
/// One renderer for both the Cycle schedules form and the Series form, so a form key
/// hint or a refusal block cannot drift between the page's two tabs.
fn render_form_fields(
    f: &mut Frame,
    area: Rect,
    title: &str,
    rows: &[(String, String, String)],
    focus: usize,
    error: Option<&str>,
    note: Option<&str>,
) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title(title.to_string());
    let inner = block.inner(area);
    f.render_widget(block, area);

    let mut lines: Vec<Line<'static>> = Vec::new();
    for (index, (label, value, hint)) in rows.iter().enumerate() {
        let focused = index == focus;
        let mut spans = vec![Span::raw(if focused { "> " } else { "  " })];
        spans.push(Span::styled(
            format!("{label}: "),
            if focused {
                Style::default().add_modifier(Modifier::BOLD)
            } else {
                dim()
            },
        ));
        spans.push(Span::raw(value.clone()));
        if focused {
            spans.push(Span::styled("▏", Style::default().fg(Color::Cyan)));
        }
        spans.push(Span::styled(format!("  ({hint})"), dim()));
        lines.push(Line::from(spans));
    }
    lines.push(Line::from(""));
    if let Some(note) = note {
        lines.push(Line::from(Span::styled(note.to_string(), dim())));
        lines.push(Line::from(""));
    }
    lines.push(Line::from(Span::styled(
        "tab / shift+tab: field  enter: save  esc: cancel, nothing written",
        dim(),
    )));
    if let Some(error) = error {
        lines.push(Line::from(""));
        for line in error.lines() {
            lines.push(Line::from(Span::styled(
                line.to_string(),
                Style::default().fg(Color::Red),
            )));
        }
    }
    f.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
}

/// The Series tab: the list of series beside the selected one's detail.
fn render_series(app: &App, f: &mut Frame, area: Rect, state: &ScheduleState) {
    let entries = app.schedule_entries();
    let detail = app.schedule_detail(state.selected);

    let body = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(45), Constraint::Min(24)])
        .split(area);

    let list = Block::default()
        .borders(Borders::ALL)
        .title(format!("Series ({})", entries.len()));
    if entries.is_empty() {
        f.render_widget(
            Paragraph::new(ScheduleTab::Series.empty_hint())
                .block(list)
                .wrap(Wrap { trim: true })
                .style(dim()),
            body[0],
        );
    } else {
        let mut lines: Vec<Line<'static>> = Vec::new();
        for (index, entry) in entries.iter().enumerate() {
            let selected = index == state.selected;
            let mut spans = vec![Span::raw(if selected { "> " } else { "  " })];
            spans.push(Span::styled(
                entry.title.clone(),
                if selected {
                    Style::default().add_modifier(Modifier::BOLD)
                } else {
                    Style::default()
                },
            ));
            if entry.due {
                spans.push(Span::styled("  [due]", Style::default().fg(Color::Cyan)));
            }
            lines.push(Line::from(spans));
            lines.push(Line::from(Span::styled(
                format!("    {}", entry.subtitle),
                dim(),
            )));
        }
        f.render_widget(Paragraph::new(lines).block(list), body[0]);
    }

    let block = Block::default()
        .borders(Borders::ALL)
        .title("Series detail");
    match detail.as_ref() {
        Some(detail) => {
            let lines: Vec<Line<'static>> = detail
                .lines
                .iter()
                .map(|(key, value)| {
                    Line::from(vec![
                        Span::styled(format!("{key}: "), dim()),
                        Span::raw(value.clone()),
                    ])
                })
                .collect();
            f.render_widget(
                Paragraph::new(lines)
                    .block(block)
                    .wrap(Wrap { trim: false }),
                body[1],
            );
        }
        None => f.render_widget(
            Paragraph::new(Span::styled(
                "Nothing selected: a series has to exist before the page can describe it.",
                dim(),
            ))
            .block(block)
            .wrap(Wrap { trim: true }),
            body[1],
        ),
    }
}

/// The Cycle schedules tab: the schedule list (with any finding that belongs to no
/// listed schedule under it) beside the selected schedule's detail.
fn render_cycles(app: &App, f: &mut Frame, area: Rect, state: &ScheduleState) {
    let entries = app.cycle_schedule_entries();
    let detail = app.cycle_schedule_detail(state.selected);
    let unattached = app.cycle_schedule_unattached_findings();

    let body = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(45), Constraint::Min(24)])
        .split(area);

    // A dangling identity — a generated cycle naming a schedule that is not in the
    // registry — has no row of its own, so it gets its own block under the list
    // rather than being silently counted. Its height is the block it needs, capped
    // so a wall of findings cannot swallow the list.
    if unattached.is_empty() {
        render_cycle_list(f, body[0], &entries, state.selected);
    } else {
        // Two rows of chrome, plus three rows per finding: a rendered diagnostic is
        // one long sentence that wraps in a pane this narrow, and clipping it to a
        // single row would hide the half that says which schedule is missing. Capped
        // so a wall of findings cannot swallow the list.
        let height = (unattached.len() as u16 * 3 + 2).min(12);
        let columns = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(3), Constraint::Length(height)])
            .split(body[0]);
        render_cycle_list(f, columns[0], &entries, state.selected);
        let findings: Vec<Line<'static>> = unattached
            .iter()
            .map(|line| Line::from(Span::styled(line.clone(), dim())))
            .collect();
        f.render_widget(
            Paragraph::new(findings)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .title(format!("Unattached findings ({})", unattached.len())),
                )
                .wrap(Wrap { trim: true }),
            columns[1],
        );
    }

    let block = Block::default()
        .borders(Borders::ALL)
        .title("Cycle schedule detail");
    match detail.as_ref() {
        Some(detail) => {
            let mut lines: Vec<Line<'static>> = detail
                .fields
                .iter()
                .map(|(key, value)| {
                    Line::from(vec![
                        Span::styled(format!("{key}: "), dim()),
                        Span::raw(value.clone()),
                    ])
                })
                .collect();
            section(&mut lines, "cycles", &detail.cycles);
            section(&mut lines, "snapshots", &detail.snapshots);
            section(&mut lines, "findings", &detail.findings);
            section(&mut lines, "warnings", &detail.warnings);
            f.render_widget(
                Paragraph::new(lines)
                    .block(block)
                    .wrap(Wrap { trim: false }),
                body[1],
            );
        }
        None => f.render_widget(
            Paragraph::new(Span::styled(
                "Nothing selected: a cycle schedule has to exist before the page can \
                 describe it.",
                dim(),
            ))
            .block(block)
            .wrap(Wrap { trim: true }),
            body[1],
        ),
    }
}

/// The schedule list block, its empty state explicit.
fn render_cycle_list(f: &mut Frame, area: Rect, entries: &[CycleScheduleEntry], selected: usize) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!("Cycle schedules ({})", entries.len()));
    if entries.is_empty() {
        f.render_widget(
            Paragraph::new(ScheduleTab::Cycles.empty_hint())
                .block(block)
                .wrap(Wrap { trim: true })
                .style(dim()),
            area,
        );
        return;
    }
    let mut lines: Vec<Line<'static>> = Vec::new();
    for (index, entry) in entries.iter().enumerate() {
        let is_selected = index == selected;
        let mut spans = vec![Span::raw(if is_selected { "> " } else { "  " })];
        spans.push(Span::styled(
            entry.title.clone(),
            if is_selected {
                Style::default().add_modifier(Modifier::BOLD)
            } else {
                Style::default()
            },
        ));
        if entry.warned {
            spans.push(Span::styled("  [warn]", Style::default().fg(Color::Yellow)));
        }
        lines.push(Line::from(spans));
        lines.push(Line::from(Span::styled(
            format!("    {}", entry.subtitle),
            dim(),
        )));
    }
    f.render_widget(Paragraph::new(lines).block(block), area);
}

/// Append one `heading (N):` section and its lines — or an explicit `none`, so a
/// section can never be mistaken for a rendering failure.
fn section(lines: &mut Vec<Line<'static>>, heading: &str, body: &[String]) {
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        format!("{heading} ({}):", body.len()),
        Style::default().add_modifier(Modifier::BOLD),
    )));
    if body.is_empty() {
        lines.push(Line::from(Span::styled("  none", dim())));
        return;
    }
    for line in body {
        lines.push(Line::from(Span::raw(format!("  {line}"))));
    }
}

/// The Capacity tab: the configured scopes beside the selected one's shared
/// calculation, its findings and — for a cycle scope — its immutable close evidence.
///
/// Read-only: it draws what [`crate::app::App`] read from the shared DTOs and offers
/// no key that writes. Its empty state is a sentence — both when nothing is
/// configured and when nothing is committed — so a blank pane can never be mistaken
/// for a rendering failure; and a **failed** read is distinguished from an empty
/// selection in both panes, so neither can claim nothing is configured while the
/// question was never answered.
fn render_capacity(app: &App, f: &mut Frame, area: Rect, state: &ScheduleState) {
    let rows = app.capacity_rows();
    let body = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(45), Constraint::Min(24)])
        .split(area);

    let list = Block::default()
        .borders(Borders::ALL)
        .title(format!("Capacity ({})", rows.len()));
    if !app.capacity_read() {
        f.render_widget(
            Paragraph::new(
                "Could not read the capacity snapshot for this project, so no capacity view \
                 is available.",
            )
            .block(list)
            .wrap(Wrap { trim: true })
            .style(dim()),
            body[0],
        );
    } else if rows.is_empty() {
        f.render_widget(
            Paragraph::new(ScheduleTab::Capacity.empty_hint())
                .block(list)
                .wrap(Wrap { trim: true })
                .style(dim()),
            body[0],
        );
    } else {
        let mut lines: Vec<Line<'static>> = Vec::new();
        for (index, row) in rows.iter().enumerate() {
            let selected = index == state.selected;
            let mut spans = vec![Span::raw(if selected { "> " } else { "  " })];
            spans.push(Span::styled(
                row.title.clone(),
                if selected {
                    Style::default().add_modifier(Modifier::BOLD)
                } else {
                    Style::default()
                },
            ));
            if row.overflowing {
                spans.push(Span::styled("  [over]", Style::default().fg(Color::Red)));
            } else if row.warned {
                spans.push(Span::styled("  [warn]", Style::default().fg(Color::Yellow)));
            }
            lines.push(Line::from(spans));
            lines.push(Line::from(Span::styled(
                format!("    {}", row.subtitle),
                dim(),
            )));
        }
        // "Nothing committed" is a fact about the work rather than about the
        // configuration, and a reader must not have to infer it from `-` values.
        if app.capacity_nothing_committed() {
            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                "no committed work in any configured scope yet",
                dim(),
            )));
        }
        f.render_widget(Paragraph::new(lines).block(list), body[0]);
    }

    let block = Block::default()
        .borders(Borders::ALL)
        .title("Capacity detail");
    match app.capacity_detail(state.selected) {
        Some(detail) => {
            let mut lines: Vec<Line<'static>> = Vec::new();
            for (key, value) in &detail.fields {
                lines.push(Line::from(vec![
                    Span::styled(format!("{key}: "), dim()),
                    Span::raw(value.clone()),
                ]));
            }
            section(&mut lines, "findings", &detail.diagnostics);
            if let Some(snapshot) = &detail.snapshot {
                lines.push(Line::from(""));
                lines.push(Line::from(Span::styled(
                    format!("closed snapshot — {}", snapshot.label),
                    Style::default().add_modifier(Modifier::BOLD),
                )));
                for (key, value) in &snapshot.fields {
                    lines.push(Line::from(vec![
                        Span::styled(format!("{key}: "), dim()),
                        Span::raw(value.clone()),
                    ]));
                }
                if snapshot.fields.is_empty() {
                    lines.push(Line::from(Span::styled("  none", dim())));
                }
            }
            f.render_widget(
                Paragraph::new(lines)
                    .block(block)
                    .wrap(Wrap { trim: false }),
                body[1],
            );
        }
        None => {
            // A missing detail has two causes, and they are not the same statement:
            // there is nothing selected, or the read that would have supplied the
            // rows failed. The list pane already distinguishes them; a detail pane
            // claiming "nothing is configured" over a failed read would be exactly the
            // conflation the mission's absent-value rules forbid.
            let sentence = if app.capacity_read() {
                "Nothing selected: a capacity scope has to be configured before the page \
                 can describe it."
            } else {
                "Could not read the capacity snapshot for this project, so no capacity \
                 view is available."
            };
            f.render_widget(
                Paragraph::new(Span::styled(sentence, dim()))
                    .block(block)
                    .wrap(Wrap { trim: true }),
                body[1],
            );
        }
    }
}

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

    #[test]
    fn the_cursor_clamps_to_the_row_count() {
        let mut state = ScheduleState::new();
        assert!(state.move_selected(3, 5));
        assert_eq!(state.selected, 3);
        assert!(state.move_selected(9, 5), "clamped to the last row");
        assert_eq!(state.selected, 4);
        assert!(!state.move_selected(1, 5));
        state.move_selected(-9, 5);
        assert_eq!(state.selected, 0);
        state.move_selected(1, 0);
        assert_eq!(state.selected, 0, "an empty list keeps the cursor at zero");
    }

    #[test]
    fn a_shrinking_registry_clamps_the_cursor() {
        let mut state = ScheduleState {
            selected: 4,
            ..Default::default()
        };
        state.clamp_selected(2);
        assert_eq!(state.selected, 1);
        state.clamp_selected(0);
        assert_eq!(state.selected, 0);
    }

    #[test]
    fn the_tab_strip_has_all_three_tabs_and_the_series_tab_is_the_default() {
        assert_eq!(ScheduleTab::default(), ScheduleTab::Series);
        assert_eq!(
            ScheduleTab::ALL,
            [
                ScheduleTab::Series,
                ScheduleTab::Cycles,
                ScheduleTab::Capacity
            ]
        );
        assert_eq!(ScheduleTab::Series.label(), "Series");
        assert_eq!(ScheduleTab::Cycles.label(), "Cycle schedules");
        assert_eq!(ScheduleTab::Capacity.label(), "Capacity");
        let drawn: String = tab_line(ScheduleTab::Capacity)
            .spans
            .iter()
            .map(|span| span.content.clone())
            .collect();
        assert!(drawn.contains("[Series]"), "{drawn}");
        assert!(drawn.contains("[Cycle schedules]"), "{drawn}");
        assert!(drawn.contains("[Capacity]"), "{drawn}");
        assert!(drawn.contains("F8 Schedule"), "{drawn}");
    }

    #[test]
    fn the_tab_strip_geometry_matches_the_drawn_line() {
        // The pointer addresses a tab by the rect this reports, so it must land on
        // the label the strip actually draws — a mismatch would make a click switch
        // to the wrong tab. Each rect's label is read back out of the same line.
        let area = Rect::new(3, 7, 80, 24);
        let drawn: Vec<String> = tab_line(ScheduleTab::Series)
            .spans
            .iter()
            .map(|span| span.content.to_string())
            .collect();
        let line = drawn.concat();
        let rects = tab_rects(area);
        assert_eq!(rects.len(), ScheduleTab::ALL.len());
        for (tab, rect) in rects {
            assert_eq!(rect.y, area.y, "the strip is one row at the top");
            assert_eq!(rect.height, 1);
            let start = usize::from(rect.x - area.x);
            let end = start + usize::from(rect.width);
            assert_eq!(
                &line[start..end],
                format!("[{}]", tab.label()),
                "the rect addresses {tab:?}'s own label"
            );
        }
    }

    #[test]
    fn switching_tabs_wraps_and_resets_the_row_cursor() {
        let mut state = ScheduleState {
            selected: 3,
            ..Default::default()
        };
        state.switch_tab(1);
        assert_eq!(state.tab, ScheduleTab::Cycles);
        assert_eq!(
            state.selected, 0,
            "the cursor indexes the active tab's rows"
        );
        state.switch_tab(1);
        assert_eq!(state.tab, ScheduleTab::Capacity);
        state.switch_tab(1);
        assert_eq!(state.tab, ScheduleTab::Series, "`Tab` wraps");
        state.switch_tab(-1);
        assert_eq!(state.tab, ScheduleTab::Capacity, "`Shift+Tab` steps back");
    }

    #[test]
    fn every_tab_has_an_explicit_empty_state() {
        for tab in ScheduleTab::ALL {
            assert!(
                tab.empty_hint().contains("No ") || tab.empty_hint().contains("yet"),
                "{tab:?} says what is missing: {}",
                tab.empty_hint()
            );
        }
    }

    #[test]
    fn the_series_empty_state_keeps_the_cli_hint_and_adds_the_tui_offer() {
        let hint = ScheduleTab::Series.empty_hint();
        assert!(
            hint.contains(
                "Create one with `tix recurring create --title <TITLE> --rule daily \
                 --anchor <DATE>`"
            ),
            "the CLI hint survives verbatim: {hint}"
        );
        assert!(
            hint.contains("press `n` to create one here"),
            "and the TUI offers its own key: {hint}"
        );
    }

    #[test]
    fn the_hint_line_advertises_every_key_the_series_tab_handles() {
        for expected in [
            "j/k",
            "n: new",
            "g: generate",
            "p: pause",
            "r: resume",
            "x: end",
            "s: skip",
            "d: defer",
            "i: ignore",
            "q: back",
        ] {
            assert!(
                SERIES_KEYS.contains(expected),
                "the page advertises `{expected}`: {SERIES_KEYS}"
            );
        }
    }

    #[test]
    fn the_cycle_tab_hint_advertises_every_key_it_handles() {
        for expected in [
            "j/k",
            "Tab: tabs",
            "n: new",
            "E: edit",
            "g: generate",
            "c: close",
            "e: extend",
            "s: skip",
            "p: pause",
            "r: resume",
            "a: adjust-future",
            "i: ignore",
            "q: back",
        ] {
            assert!(
                CYCLE_SCHEDULE_KEYS.contains(expected),
                "the tab advertises `{expected}`: {CYCLE_SCHEDULE_KEYS}"
            );
        }
    }

    #[test]
    fn the_cycle_help_rows_advertise_the_same_keys_as_the_hint() {
        // The `?` overlay and the page's own hint row are two instructions to the
        // same user; a key the tab acts on must be in both, or one of them lies.
        let advertised: Vec<&str> = CYCLE_HELP_RAW.iter().map(|(key, _)| *key).collect();
        for key in ["tab / shift+tab", "n", "E", "c", "e", "s", "a"] {
            assert!(
                advertised.contains(&key),
                "the help names `{key}`: {advertised:?}"
            );
        }
        // And the two rows the tab does not act on are gone.
        let actions: Vec<TuiAction> = CYCLE_HELP_ACTIONS.iter().map(|(a, _)| *a).collect();
        assert!(
            !actions.contains(&TuiAction::SeriesEnd),
            "`x` ends a series and means nothing here"
        );
        assert!(
            !actions.contains(&TuiAction::SeriesDefer),
            "`d` defers a series' due date and means nothing here"
        );
    }

    #[test]
    fn the_capacity_help_rows_advertise_the_same_keys_as_the_hint() {
        // The Capacity tab is read-only, so its overlay must name only the keys it
        // acts on: `j`/`k`, the tab switch and the way back. A series action here
        // would be an instruction that does nothing.
        let actions: Vec<TuiAction> = CAPACITY_HELP_ACTIONS.iter().map(|(a, _)| *a).collect();
        for action in [
            TuiAction::MoveUp,
            TuiAction::MoveDown,
            TuiAction::Help,
            TuiAction::Close,
        ] {
            assert!(
                actions.contains(&action),
                "the help names {action:?}: {actions:?}"
            );
        }
        for absent in [
            TuiAction::SeriesGenerate,
            TuiAction::SeriesPause,
            TuiAction::SeriesEnd,
        ] {
            assert!(
                !actions.contains(&absent),
                "{absent:?} acts on nothing here"
            );
        }
        assert!(CAPACITY_KEYS.contains("j/k"), "{CAPACITY_KEYS}");
        assert!(CAPACITY_KEYS.contains("Tab: tabs"), "{CAPACITY_KEYS}");
        assert!(CAPACITY_KEYS.contains("q: back"), "{CAPACITY_KEYS}");
        assert_eq!(
            CAPACITY_HELP_RAW
                .iter()
                .map(|(key, _)| *key)
                .collect::<Vec<_>>(),
            vec!["tab / shift+tab"]
        );
    }

    #[test]
    fn the_create_form_shows_every_field_and_the_edit_form_every_but_the_id() {
        let create = ScheduleForm::create();
        assert_eq!(create.fields, ScheduleField::ALL);
        assert_eq!(create.focused(), ScheduleField::Id);
        assert!(create.title().contains("New cycle schedule"));

        let edit = ScheduleForm::edit("cs-x".to_string(), vec!["Name".to_string()]);
        assert_eq!(edit.fields, ScheduleField::EDIT);
        assert!(
            !edit.fields.contains(&ScheduleField::Id),
            "the identity is the registry key and does not change"
        );
        assert_eq!(edit.value(ScheduleField::Name), "Name");
        assert_eq!(
            edit.value(ScheduleField::Id),
            "",
            "not shown by the edit form"
        );
        assert_eq!(
            edit.value(ScheduleField::StartDate),
            "",
            "a missing value is empty"
        );
        assert!(edit.title().contains("cs-x"));
    }

    #[test]
    fn the_form_focus_wraps_and_typing_lands_in_the_focused_field() {
        let mut form = ScheduleForm::create();
        form.insert_char('c');
        form.insert_char('s');
        assert_eq!(form.value(ScheduleField::Id), "cs");
        form.focus_next();
        assert_eq!(form.focused(), ScheduleField::Name);
        form.insert_char('X');
        assert_eq!(form.value(ScheduleField::Name), "X");
        form.delete_char();
        assert_eq!(form.value(ScheduleField::Name), "");
        form.focus_prev();
        assert_eq!(form.focused(), ScheduleField::Id, "backward wraps too");
        // Forward from the last field wraps to the first.
        for _ in 0..ScheduleField::ALL.len() {
            form.focus_next();
        }
        assert_eq!(form.focused(), ScheduleField::Id);

        // A refusal is kept on the form, so what was typed survives it.
        form.set_error("nope".to_string());
        assert_eq!(form.error.as_deref(), Some("nope"));
    }

    #[test]
    fn the_series_create_form_asks_for_the_three_required_fields() {
        let form = SeriesForm::create();
        assert_eq!(form.fields, SeriesField::ALL);
        assert_eq!(
            form.fields,
            [SeriesField::Title, SeriesField::Rule, SeriesField::Anchor],
            "the first-run path is title, rule, anchor — the three the CLI requires"
        );
        assert_eq!(form.focused(), SeriesField::Title);
        // Every field names the vocabulary it accepts, so the form is its own remedy.
        for field in SeriesField::ALL {
            assert!(!field.label().is_empty(), "{field:?} has a label");
            assert!(!field.hint().is_empty(), "{field:?} has a hint");
        }
        assert_eq!(
            SeriesField::Rule.hint(),
            "daily | weekly | monthly",
            "the rule hint names only the families the form's three fields can complete"
        );
        assert!(
            SeriesForm::NOTE.contains("`interval`")
                && SeriesForm::NOTE.contains("`cron-like`")
                && SeriesForm::NOTE.contains("tix recurring create"),
            "the families the form cannot complete are named as the CLI's: {}",
            SeriesForm::NOTE
        );
        assert_eq!(SeriesField::Anchor.hint(), "YYYY-MM-DD");
        assert!(form.title().contains("New recurring series"));
    }

    #[test]
    fn the_series_form_focus_wraps_and_typing_lands_in_the_focused_field() {
        let mut form = SeriesForm::create();
        for c in "Nightly".chars() {
            form.insert_char(c);
        }
        assert_eq!(form.value(SeriesField::Title), "Nightly");
        form.focus_next();
        assert_eq!(form.focused(), SeriesField::Rule);
        for c in "daily".chars() {
            form.insert_char(c);
        }
        assert_eq!(form.value(SeriesField::Rule), "daily");
        form.focus_next();
        form.insert_char('X');
        assert_eq!(form.value(SeriesField::Anchor), "X");
        form.delete_char();
        assert_eq!(form.value(SeriesField::Anchor), "");
        form.clear_field();
        assert_eq!(form.value(SeriesField::Anchor), "");
        form.focus_prev();
        assert_eq!(form.focused(), SeriesField::Rule, "backward wraps too");
        // Forward from the last field wraps to the first.
        form.focus_next(); // anchor
        form.focus_next(); // wraps back to the title
        assert_eq!(
            form.focused(),
            SeriesField::Title,
            "forward wraps to the first field"
        );
        for _ in 0..SeriesField::ALL.len() {
            form.focus_next();
        }
        assert_eq!(form.focused(), SeriesField::Title);

        form.set_error("refused".to_string());
        assert_eq!(form.error.as_deref(), Some("refused"));
        // A field the form does not show reads as empty rather than panicking.
        assert_eq!(form.value(SeriesField::Title), "Nightly");
    }
}