tix-tracker 0.12.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
//! Planning-management widgets (cycles + milestones modal and its form).
//!
//! A pure view + model like `settings` and `filter_modal`: the widgets never
//! read keys or mutate the registry — the app routes keys and applies planner
//! mutations (`App::handle_planning_key` / `App::handle_planning_form_key`).

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

use crate::config::PlanningCycle;
use crate::planning::Milestone;

use super::modal::modal_rect;

/// The list segment currently in view.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PlanningSegment {
    #[default]
    Cycles,
    Milestones,
}

impl PlanningSegment {
    pub fn label(self) -> &'static str {
        match self {
            Self::Cycles => "Cycles",
            Self::Milestones => "Milestones",
        }
    }
}

/// The kind of item a [`PlanningForm`] creates or edits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlanningKind {
    Cycle,
    Milestone,
}

impl PlanningKind {
    pub fn noun(self) -> &'static str {
        match self {
            Self::Cycle => "cycle",
            Self::Milestone => "milestone",
        }
    }
}

/// A rendered planning row: the fields shown for one cycle or milestone.
/// `date_a` is the anchor (cycle start date / milestone target date); `date_b`
/// is the cycle due date — `None` for milestones (field does not apply) and
/// `Some("")` for a cycle carrying no due date (field present, value blank).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlanningRow {
    pub name: String,
    pub description: String,
    pub date_a: String,
    pub date_b: Option<String>,
    pub issues: usize,
}

pub fn issues_word(n: usize) -> &'static str {
    if n == 1 { "issue" } else { "issues" }
}

/// The flat row text the modal renders for a planning item. Missing fields
/// render blank (spec: "blank for fields the item does not carry").
pub fn row_line(row: &PlanningRow) -> String {
    let mut text = format!("{} | {} | {}", row.name, row.description, row.date_a);
    if let Some(date_b) = &row.date_b {
        text.push_str(" | ");
        text.push_str(date_b);
    }
    text.push_str(&format!(" | {} {}", row.issues, issues_word(row.issues)));
    text
}

/// The scroll window of row lines a planning surface draws around `selected`.
///
/// Extracted from [`PlanningModal::render_with_bindings`] so the Config mode's
/// cycle and milestone sections show the *same* rows with the same cursor and
/// the same counts — a second renderer is how the two surfaces would drift.
/// Returns an empty vector for an empty list; the caller draws its own
/// "nothing here yet" hint (the modal suppresses it under a delete prompt, the
/// Config mode does not).
pub fn rows_lines(rows: &[PlanningRow], selected: usize, view_h: usize) -> Vec<Line<'static>> {
    if rows.is_empty() {
        return Vec::new();
    }
    let sel = usize::min(selected, rows.len() - 1);
    let top = sel.saturating_sub(view_h.saturating_sub(1));
    let end = (top + view_h.max(1)).min(rows.len());
    let mut lines = Vec::new();
    for (i, row) in rows
        .iter()
        .enumerate()
        .skip(top)
        .take(end.saturating_sub(top))
    {
        let cursor = if i == sel { "> " } else { "  " };
        let style = if i == sel {
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::White)
        };
        lines.push(Line::from(vec![
            Span::styled(cursor, style),
            Span::styled(row_line(row), style),
        ]));
    }
    lines
}

/// The confirmation line for an active planning prompt, naming the reference
/// count. Shared with the Config mode for the same reason as [`rows_lines`].
pub fn prompt_line(prompt: &PlanningPrompt) -> Line<'static> {
    match prompt {
        PlanningPrompt::ConfirmDelete { name, referencing } => Line::from(Span::styled(
            format!(
                "Delete '{name}'? {referencing} {} reference it. [y/N]",
                issues_word(*referencing)
            ),
            Style::default().fg(Color::Cyan),
        )),
    }
}

/// An active inline prompt inside the planning modal.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlanningPrompt {
    /// Confirming deletion of `name`; `referencing` issues reference it.
    ConfirmDelete { name: String, referencing: usize },
}

/// The planning modal: a segment switch (cycles/milestones) over a row list
/// with a clamped cursor, a render-time vertical scroll window, and an
/// optional inline confirmation prompt.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PlanningModal {
    /// Active segment (cycles or milestones).
    pub segment: PlanningSegment,
    /// Row cursor within the active segment.
    pub selected: usize,
    /// Active inline prompt (None = browsing the list).
    pub prompt: Option<PlanningPrompt>,
}

impl PlanningModal {
    pub fn new() -> Self {
        Self::default()
    }

    /// Move the row cursor, clamped to `len` (the active segment's rows).
    pub fn move_selected(&mut self, delta: isize, len: usize) {
        if len == 0 {
            self.selected = 0;
            return;
        }
        let next = self.selected as isize + delta;
        self.selected = next.clamp(0, len as isize - 1) as usize;
    }

    pub fn switch_segment(&mut self) {
        self.selected = 0;
        self.segment = match self.segment {
            PlanningSegment::Cycles => PlanningSegment::Milestones,
            PlanningSegment::Milestones => PlanningSegment::Cycles,
        };
    }

    /// Jump the row cursor straight to `row` (a row click), clamped to the same
    /// range the arrow keys navigate.
    pub fn move_selected_to(&mut self, row: usize, len: usize) {
        if len == 0 {
            self.selected = 0;
            return;
        }
        self.selected = row.min(len - 1);
    }

    /// Render the modal over `area` for the given cycle and milestone rows.
    pub fn render(
        &self,
        f: &mut Frame,
        area: Rect,
        cycles: &[PlanningRow],
        milestones: &[PlanningRow],
    ) {
        let bindings =
            crate::keybindings::KeyBindings::resolve(&crate::keybindings::KeyBindings::default())
                .expect("built-in bindings are valid");
        self.render_with_bindings(
            f,
            area,
            cycles,
            milestones,
            &bindings,
            crate::keybindings::InputContext::PlanningManagement,
        );
    }

    pub fn render_with_bindings(
        &self,
        f: &mut Frame,
        area: Rect,
        cycles: &[PlanningRow],
        milestones: &[PlanningRow],
        bindings: &crate::keybindings::EffectiveBindings,
        context: crate::keybindings::InputContext,
    ) {
        let (rows, label) = match self.segment {
            PlanningSegment::Cycles => (cycles, "Cycles"),
            PlanningSegment::Milestones => (milestones, "Milestones"),
        };
        let rect = modal_rect(area);
        let inner = rect.height.saturating_sub(2) as usize;
        let view_h = if self.prompt.is_some() {
            inner.saturating_sub(4)
        } else {
            inner.saturating_sub(3)
        };

        let mut lines: Vec<Line> = Vec::new();
        lines.push(Line::from(Span::styled(
            format!(" {label} — Tab to switch segment "),
            Style::default().fg(Color::DarkGray),
        )));

        if rows.is_empty() {
            if self.prompt.is_none() {
                lines.push(Line::from(format!(
                    "No {label} yet — press n to create one."
                )));
            }
        } else {
            lines.extend(rows_lines(rows, self.selected, view_h));
        }

        lines.push(Line::from(""));
        match &self.prompt {
            Some(prompt) => lines.push(prompt_line(prompt)),
            None => {
                lines.push(Line::from(Span::styled(
                    format!(
                        "{}: move · {}: switch · {}: new · {}: edit · {}: delete · {}: close",
                        bindings.label(context, crate::keybindings::TuiAction::MoveDown),
                        bindings.label(context, crate::keybindings::TuiAction::Next),
                        bindings.label(context, crate::keybindings::TuiAction::NewPlanningItem),
                        bindings.label(context, crate::keybindings::TuiAction::EditPlanningItem),
                        bindings.label(context, crate::keybindings::TuiAction::DeletePlanningItem),
                        bindings.label(context, crate::keybindings::TuiAction::Close),
                    ),
                    Style::default().fg(Color::DarkGray),
                )));
            }
        }

        let block = Block::default()
            .borders(Borders::ALL)
            .title(" Planned items ")
            .style(Style::default().fg(Color::Cyan));
        let para = Paragraph::new(lines).block(block).style(Style::default());
        f.render_widget(Clear, rect);
        f.render_widget(para, rect);
    }
}

/// The create/edit form for a cycle or milestone: a list of labelled field
/// rows with a focused cursor. `editing` is `Some(old name)` when the form
/// edits an existing item (a changed name triggers the rename cascade).
#[derive(Debug, Clone)]
pub struct PlanningForm {
    pub kind: PlanningKind,
    pub rows: Vec<(String, String)>,
    pub cursor: usize,
    pub editing: Option<String>,
}

impl PlanningForm {
    /// A blank create form for `kind`.
    pub fn new(kind: PlanningKind) -> Self {
        let labels: Vec<&str> = match kind {
            PlanningKind::Cycle => vec!["Name", "Description", "Start date", "Due date"],
            PlanningKind::Milestone => vec!["Name", "Description", "Target date"],
        };
        Self {
            kind,
            rows: labels
                .into_iter()
                .map(|l| (l.to_string(), String::new()))
                .collect(),
            cursor: 0,
            editing: None,
        }
    }

    /// An edit form for a cycle, prefilled from `name` + `cycle`.
    pub fn from_cycle(name: &str, cycle: &PlanningCycle) -> Self {
        Self {
            kind: PlanningKind::Cycle,
            rows: vec![
                ("Name".into(), name.to_string()),
                (
                    "Description".into(),
                    cycle.description.clone().unwrap_or_default(),
                ),
                (
                    "Start date".into(),
                    cycle.start_date.clone().unwrap_or_default(),
                ),
                (
                    "Due date".into(),
                    cycle.due_date.clone().unwrap_or_default(),
                ),
            ],
            cursor: 0,
            editing: Some(name.to_string()),
        }
    }

    /// An edit form for a milestone, prefilled from `m`.
    pub fn from_milestone(m: &Milestone) -> Self {
        Self {
            kind: PlanningKind::Milestone,
            rows: vec![
                ("Name".into(), m.name.clone()),
                ("Description".into(), m.description.clone()),
                ("Target date".into(), m.target_date.clone()),
            ],
            cursor: 0,
            editing: Some(m.name.clone()),
        }
    }

    pub fn is_new(&self) -> bool {
        self.editing.is_none()
    }

    /// The focused field's typed value.
    pub fn name(&self) -> &str {
        self.field_value(0)
    }

    pub fn description(&self) -> &str {
        self.field_value(1)
    }

    /// Cycle start date / milestone target date.
    pub fn date_a(&self) -> &str {
        self.field_value(2)
    }

    /// Cycle due date (empty for milestones).
    pub fn date_b(&self) -> &str {
        match self.kind {
            PlanningKind::Cycle => self.field_value(3),
            PlanningKind::Milestone => "",
        }
    }

    fn field_value(&self, index: usize) -> &str {
        self.rows
            .get(index)
            .map(|(_, value)| value.as_str())
            .unwrap_or("")
    }

    pub fn focused_label(&self) -> &str {
        &self.rows[self.cursor].0
    }

    /// The focused field's typed value.
    pub fn focused_value(&self) -> &str {
        self.field_value(self.cursor)
    }

    /// Whether the focused field is a picker-only date field. Date fields are
    /// always the rows after `Name` and `Description`.
    pub fn focused_is_date(&self) -> bool {
        self.cursor >= 2
    }

    /// Whether the focused date field already holds a complete, valid date.
    pub fn focused_date_is_complete(&self) -> bool {
        self.focused_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.focused_is_date() {
            if let Some((_, current)) = self.rows.get_mut(self.cursor) {
                *current = value.to_string();
            }
        }
    }

    pub fn focus_next(&mut self) {
        self.cursor = (self.cursor + 1) % self.rows.len();
    }

    pub fn focus_prev(&mut self) {
        self.cursor = (self.cursor + self.rows.len() - 1) % self.rows.len();
    }

    pub fn insert_char(&mut self, c: char) {
        if self.focused_is_date() {
            if let Some(next) = crate::ui::date_picker::type_date(self.focused_value(), c) {
                if let Some((_, value)) = self.rows.get_mut(self.cursor) {
                    *value = next;
                }
            }
            return;
        }
        if let Some((_, value)) = self.rows.get_mut(self.cursor) {
            value.push(c);
        }
    }

    pub fn delete_char(&mut self) {
        if self.focused_is_date() {
            let next = crate::ui::date_picker::backspace_date(self.focused_value());
            if let Some((_, value)) = self.rows.get_mut(self.cursor) {
                *value = next;
            }
            return;
        }
        if let Some((_, value)) = self.rows.get_mut(self.cursor) {
            value.pop();
        }
    }

    /// Render the form over `area`.
    pub fn render(&self, f: &mut Frame, area: Rect) {
        let bindings =
            crate::keybindings::KeyBindings::resolve(&crate::keybindings::KeyBindings::default())
                .expect("built-in bindings are valid");
        self.render_with_bindings(
            f,
            area,
            &bindings,
            crate::keybindings::InputContext::PlanningForm,
        );
    }

    pub fn render_with_bindings(
        &self,
        f: &mut Frame,
        area: Rect,
        bindings: &crate::keybindings::EffectiveBindings,
        context: crate::keybindings::InputContext,
    ) {
        // The editor fills the whole content area rather than a centered dialog
        // (tui-config-mode / planning-management): the record's fields get the
        // surface, and the Config mode's drill-down reads as "detail = full
        // screen".
        let rect = area;
        let title = if self.is_new() {
            format!(" New {} ", self.kind.noun())
        } else {
            format!(" Edit {} ", self.kind.noun())
        };

        let mut lines: Vec<Line> = Vec::new();
        for (i, (label, value)) in self.rows.iter().enumerate() {
            let cursor = if i == self.cursor { "> " } else { "  " };
            let style = if i == self.cursor {
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::White)
            };
            let shown = if value.is_empty() {
                "(empty)"
            } else {
                value.as_str()
            };
            lines.push(Line::from(vec![
                Span::styled(cursor, style),
                Span::styled(format!("{label}: "), style),
                Span::styled(shown, style),
            ]));
        }

        lines.push(Line::from(""));
        let hint = format!(
            "{}: save/pick date · {}: cancel · {}: next field · {}: date{}",
            bindings.label(context, crate::keybindings::TuiAction::Submit),
            bindings.label(context, crate::keybindings::TuiAction::Cancel),
            bindings.label(context, crate::keybindings::TuiAction::Next),
            bindings.label(context, crate::keybindings::TuiAction::OpenPicker),
            if self.is_new() {
                ""
            } else {
                " · renaming rewrites issues"
            },
        );
        lines.push(Line::from(Span::styled(
            hint,
            Style::default().fg(Color::DarkGray),
        )));

        let block = Block::default()
            .borders(Borders::ALL)
            .title(title)
            .style(Style::default().fg(Color::Cyan));
        let para = Paragraph::new(lines).block(block).style(Style::default());
        f.render_widget(Clear, rect);
        f.render_widget(para, rect);
    }
}

// ---------------------------------------------------------------------------
// WP04 T020 — the epic view
// ---------------------------------------------------------------------------

/// The TUI epic view's cursor state (WP04 T020, FR-003/FR-004/FR-005).
///
/// A cursor over the epics, and a second into the selected epic's member list. The
/// member list is the **direct issue navigation** surface: [`Self::target_member`]
/// names the issue `Enter` opens, so a user reaches an issue's own detail pane from
/// here rather than only through the epic layer (FR-004).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EpicViewState {
    /// Cursor into the epic list, in the service's declaration order.
    pub selected: usize,
    /// Cursor into the selected epic's member list.
    pub member: usize,
}

impl EpicViewState {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Move the epic cursor, clamped to `len`; the member cursor resets, because it
    /// indexes the newly selected epic's own list.
    pub fn move_selected(&mut self, delta: isize, len: usize) {
        self.selected = clamp_cursor(self.selected, delta, len);
        self.member = 0;
    }

    /// Move the member cursor, clamped to the selected epic's member `len`.
    pub fn move_member(&mut self, delta: isize, len: usize) {
        self.member = clamp_cursor(self.member, delta, len);
    }

    /// The member issue `Enter` opens, when the selected epic has one (FR-004).
    ///
    /// `None` for an empty view or an epic with no members, so the key is inert rather
    /// than opening an arbitrary issue.
    #[must_use]
    pub fn target_member(&self, entries: &[crate::commands::view::EpicViewEntry]) -> Option<u32> {
        let entry = entries.get(self.selected)?;
        entry.members.get(self.member).map(|member| member.number)
    }

    /// Render the epic view over `area`.
    ///
    /// The body is the pure [`epic_lines`], so the content is pinned by a unit test
    /// rather than by a TTY-bound draw; this method only adds the frame and the
    /// navigation affordance.
    pub fn render(
        &self,
        f: &mut Frame,
        area: Rect,
        entries: &[crate::commands::view::EpicViewEntry],
    ) {
        let rect = modal_rect(area);
        // Reserve the header, the blank separator and the hint line, so a long list
        // cannot push the direct-navigation affordance out of the frame.
        let view_h = (rect.height.saturating_sub(2) as usize).saturating_sub(3);
        let mut lines: Vec<Line> = Vec::new();
        lines.push(Line::from(Span::styled(
            format!(" Epics — {} in declaration order ", entries.len()),
            Style::default().fg(Color::DarkGray),
        )));
        if entries.is_empty() {
            lines.push(Line::from(
                "No epics yet — create one with `tix epic create`.",
            ));
        } else {
            // The body is truncated to the reserved height so the footer below always
            // fits; a window that overshot its own frame would clip the affordance.
            for line in epic_lines(entries, self, view_h).into_iter().take(view_h) {
                lines.push(line);
            }
        }
        lines.push(Line::from(""));
        // The direct-navigation affordance is stated, not implied (FR-004).
        lines.push(Line::from(Span::styled(
            "Enter: open the member issue directly · move · ←/→: member · Esc: close",
            Style::default().fg(Color::DarkGray),
        )));
        let block = Block::default()
            .borders(Borders::ALL)
            .title(" Epics ")
            .style(Style::default().fg(Color::Cyan));
        let para = Paragraph::new(lines).block(block).style(Style::default());
        f.render_widget(Clear, rect);
        f.render_widget(para, rect);
    }
}

fn clamp_cursor(current: usize, delta: isize, len: usize) -> usize {
    if len == 0 {
        return 0;
    }
    let next = current as isize + delta;
    next.clamp(0, len as isize - 1) as usize
}

/// The epic view's body lines, anchored at the selected epic (WP04 T020).
///
/// Pure and extracted, like [`rows_lines`]. The lines are the **same** canonical rows
/// the issue detail block and `tix show` render ([`crate::commands::view::EpicViewEntry`]),
/// so the three surfaces agree on every figure (C-008); the member list below them is
/// the direct issue navigation surface (FR-004). A member renders as an ordinary issue:
/// there is no task section, because there is no task entity (C-001).
#[must_use]
pub fn epic_lines(
    entries: &[crate::commands::view::EpicViewEntry],
    state: &EpicViewState,
    view_h: usize,
) -> Vec<Line<'static>> {
    if entries.is_empty() {
        return Vec::new();
    }
    let selected = state.selected.min(entries.len() - 1);
    // The window is measured in **rendered lines**, not entries: an epic occupies a
    // heading, its context lines and its member list, so stepping back one entry per
    // visible line pushed the selected epic (and its cursor) out of the frame — with
    // three epics at `view_h` 20 the loop broke before the selected one was drawn.
    // Reserving the selected entry's own height first keeps the cursor inside the
    // frame, which is the whole point of a selection.
    let height = |entry: &crate::commands::view::EpicViewEntry| {
        1 + entry.epic.detail.len() + 1 + entry.members.len().max(1)
    };
    let mut start = selected;
    let mut budget = view_h.max(1).saturating_sub(height(&entries[selected]));
    while start > 0 {
        let above = height(&entries[start - 1]);
        if above > budget {
            break;
        }
        budget -= above;
        start -= 1;
    }
    let mut lines: Vec<Line<'static>> = Vec::new();
    for (index, entry) in entries.iter().enumerate().skip(start) {
        if lines.len() >= view_h.max(1) {
            break;
        }
        let is_selected = index == selected;
        let style = if is_selected {
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::White)
        };
        lines.push(Line::from(vec![
            Span::styled(if is_selected { "> " } else { "  " }, style),
            Span::styled(entry.epic.heading.clone(), style),
        ]));
        for detail in &entry.epic.detail {
            lines.push(Line::from(vec![
                Span::styled("    ", Style::default()),
                Span::styled(detail.clone(), Style::default().fg(Color::Gray)),
            ]));
        }
        if entry.members.is_empty() {
            lines.push(Line::from(Span::styled(
                "    members: (none)",
                Style::default().fg(Color::DarkGray),
            )));
            continue;
        }
        lines.push(Line::from(Span::styled(
            "    members:",
            Style::default().fg(Color::DarkGray),
        )));
        let member_cursor = if is_selected {
            state.member.min(entry.members.len() - 1)
        } else {
            usize::MAX
        };
        for (member_index, member) in entry.members.iter().enumerate() {
            let marker = if member_index == member_cursor {
                "      > "
            } else {
                "        "
            };
            lines.push(Line::from(Span::styled(
                format!("{marker}{}", member.display),
                Style::default().fg(Color::Cyan),
            )));
        }
    }
    lines
}

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

    fn row(
        name: &str,
        description: &str,
        date_a: &str,
        date_b: Option<&str>,
        issues: usize,
    ) -> PlanningRow {
        PlanningRow {
            name: name.into(),
            description: description.into(),
            date_a: date_a.into(),
            date_b: date_b.map(str::to_string),
            issues,
        }
    }

    fn cycle_rows() -> Vec<PlanningRow> {
        vec![
            row("Sprint 3", "kickoff", "2026-10-01", Some("2026-10-14"), 1),
            row("Sprint 4", "", "", Some(""), 0),
        ]
    }

    fn milestone_rows() -> Vec<PlanningRow> {
        vec![
            row("GA", "ship it", "2026-12-31", None, 3),
            row("Beta", "", "2026-11-30", None, 2),
        ]
    }

    /// Render the modal into a buffer and return the terminal rows as strings.
    fn render_modal(modal: &PlanningModal) -> Vec<String> {
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let cycles = cycle_rows();
        let milestones = milestone_rows();
        terminal
            .draw(|f| modal.render(f, f.area(), &cycles, &milestones))
            .unwrap();
        let buffer = terminal.backend().buffer();
        let mut rows: Vec<String> = Vec::new();
        for y in 0..buffer.area().height {
            let mut line = String::new();
            for x in 0..buffer.area().width {
                line.push(buffer[(x, y)].symbol().chars().next().unwrap_or(' '));
            }
            rows.push(line);
        }
        rows
    }

    /// Render a planning form into a buffer and return its rows as strings.
    fn render_form(form: &PlanningForm) -> Vec<String> {
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|f| form.render(f, f.area())).unwrap();
        let buffer = terminal.backend().buffer();
        (0..buffer.area().height)
            .map(|y| {
                (0..buffer.area().width)
                    .map(|x| buffer[(x, y)].symbol().chars().next().unwrap_or(' '))
                    .collect()
            })
            .collect()
    }

    /// The editor is the record's full-screen detail (tui-config-mode /
    /// planning-management), not a centered dialog: its border and title sit on
    /// the content area's own edges.
    #[test]
    fn form_editor_fills_the_whole_content_area() {
        let form = PlanningForm::new(PlanningKind::Cycle);
        let rows = render_form(&form);
        assert!(
            rows[0].contains("New cycle"),
            "the title is on the content's first row: {:?}",
            rows[0]
        );
        assert!(
            rows[0].starts_with('┌') && rows[0].ends_with('┐'),
            "the border spans the full width: {:?}",
            rows[0]
        );
        assert!(
            rows[23].starts_with('└') && rows[23].ends_with('┘'),
            "the border reaches the last row: {:?}",
            rows[23]
        );
    }

    #[test]
    fn row_line_for_cycle_includes_all_fields() {
        assert_eq!(
            row_line(&row(
                "Sprint 3",
                "kickoff",
                "2026-10-01",
                Some("2026-10-14"),
                1
            )),
            "Sprint 3 | kickoff | 2026-10-01 | 2026-10-14 | 1 issue"
        );
        assert_eq!(
            row_line(&row(
                "Sprint 5",
                "next",
                "2026-11-01",
                Some("2026-11-15"),
                2
            )),
            "Sprint 5 | next | 2026-11-01 | 2026-11-15 | 2 issues"
        );
    }

    #[test]
    fn row_line_for_milestone_omits_due_date() {
        assert_eq!(
            row_line(&row("GA", "ship it", "2026-12-31", None, 3)),
            "GA | ship it | 2026-12-31 | 3 issues"
        );
    }

    #[test]
    fn row_line_renders_missing_fields_blank() {
        assert_eq!(
            row_line(&row("Sprint 4", "", "", Some(""), 0)),
            "Sprint 4 |  |  |  | 0 issues"
        );
    }

    #[test]
    fn renders_cycle_rows_with_cursor_and_footer() {
        let modal = PlanningModal {
            selected: 1,
            ..PlanningModal::default()
        };
        let rows = render_modal(&modal);

        let row_of =
            |needle: &str| -> Option<usize> { rows.iter().position(|r| r.contains(needle)) };
        let sprint3 = row_of("Sprint 3 | kickoff | 2026-10-01 | 2026-10-14 | 1 issue")
            .expect("first cycle renders with fields and count");
        let sprint4 = row_of("Sprint 4 |").expect("second cycle renders");
        assert!(sprint3 < sprint4, "cycles render in declaration order");

        assert!(
            rows[sprint4].contains('>'),
            "selected cycle row shows the cursor"
        );
        assert!(
            !rows[sprint3].contains('>'),
            "unselected cycle row has no cursor"
        );
        assert!(
            rows.iter().any(|r| r.contains("Down / j: move")),
            "browse hint renders on the cycles segment"
        );
    }

    #[test]
    fn renders_milestone_segment_after_switch() {
        let mut modal = PlanningModal::new();
        modal.switch_segment();
        assert_eq!(modal.segment, PlanningSegment::Milestones);
        let rows = render_modal(&modal);

        let row_of =
            |needle: &str| -> Option<usize> { rows.iter().position(|r| r.contains(needle)) };
        let ga = row_of("GA | ship it | 2026-12-31 | 3 issues")
            .expect("milestone rows render on the milestones segment");
        let footer =
            row_of("Down / j: move").expect("footer hint renders beneath the milestones list");
        assert!(
            ga < footer,
            "milestone rows render above the footer hint (ga at {ga}, footer at {footer})"
        );
    }

    #[test]
    fn renders_empty_segment_notice() {
        let modal = PlanningModal::new();
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| modal.render(f, f.area(), &[], &[]))
            .unwrap();
        let buffer = terminal.backend().buffer();
        let mut rows: Vec<String> = Vec::new();
        for y in 0..buffer.area().height {
            let mut line = String::new();
            for x in 0..buffer.area().width {
                line.push(buffer[(x, y)].symbol().chars().next().unwrap_or(' '));
            }
            rows.push(line);
        }
        assert!(
            rows.iter()
                .any(|r| r.contains("No Cycles yet — press n to create one.")),
            "empty segment shows a create hint: {:?}",
            rows
        );
    }

    #[test]
    fn renders_confirm_delete_prompt() {
        let modal = PlanningModal {
            prompt: Some(PlanningPrompt::ConfirmDelete {
                name: "Sprint 3".into(),
                referencing: 2,
            }),
            ..PlanningModal::default()
        };
        let rows = render_modal(&modal);
        assert!(
            rows.iter()
                .any(|r| r.contains("Delete 'Sprint 3'? 2 issues reference it. [y/N]")),
            "confirm prompt shows the referencing count: {:?}",
            rows
        );
    }

    #[test]
    fn scroll_window_keeps_selected_in_view_on_small_terminal() {
        let many: Vec<PlanningRow> = (0..40)
            .map(|i| row(&format!("Item {i}"), "", "2026-01-01", Some(""), 0))
            .collect();
        let backend = TestBackend::new(60, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let modal = PlanningModal {
            selected: 39,
            ..PlanningModal::default()
        };
        terminal
            .draw(|f| modal.render(f, f.area(), &many, &[]))
            .unwrap();
        let buffer = terminal.backend().buffer();
        let mut rows: Vec<String> = Vec::new();
        for y in 0..buffer.area().height {
            let mut line = String::new();
            for x in 0..buffer.area().width {
                line.push(buffer[(x, y)].symbol().chars().next().unwrap_or(' '));
            }
            rows.push(line);
        }
        assert!(
            rows.iter().any(|r| r.contains("Item 39")),
            "the selected (deep) row stays visible via the scroll window"
        );
        assert!(
            !rows.iter().any(|r| r.contains("Item 0")),
            "the first row scrolls out of the window"
        );
    }

    #[test]
    fn move_selected_clamps_and_scrolls() {
        let mut modal = PlanningModal::new();
        modal.move_selected(-3, 2);
        assert_eq!(modal.selected, 0);
        modal.move_selected(5, 2);
        assert_eq!(modal.selected, 1);
        modal.move_selected(1, 0);
        assert_eq!(modal.selected, 0);
    }

    #[test]
    fn smoke_tiny_20x5_does_not_panic() {
        let modal = PlanningModal::new();
        let backend = TestBackend::new(20, 5);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| modal.render(f, f.area(), &cycle_rows(), &milestone_rows()))
            .unwrap();
    }

    #[test]
    fn form_labels_match_kind() {
        let cycle = PlanningForm::new(PlanningKind::Cycle);
        assert_eq!(cycle.rows.len(), 4);
        let labels: Vec<&str> = cycle.rows.iter().map(|(l, _)| l.as_str()).collect();
        assert_eq!(labels, ["Name", "Description", "Start date", "Due date"]);

        let milestone = PlanningForm::new(PlanningKind::Milestone);
        assert_eq!(milestone.rows.len(), 3);
        let labels: Vec<&str> = milestone.rows.iter().map(|(l, _)| l.as_str()).collect();
        assert_eq!(labels, ["Name", "Description", "Target date"]);
        assert!(milestone.is_new());
        assert!(cycle.is_new());
    }

    #[test]
    fn form_prefills_from_cycle_and_milestone() {
        let cycle = PlanningForm::from_cycle(
            "Sprint 3",
            &PlanningCycle {
                description: Some("kickoff".into()),
                start_date: Some("2026-10-01".into()),
                due_date: Some("2026-10-14".into()),
            },
        );
        assert_eq!(cycle.name(), "Sprint 3");
        assert_eq!(cycle.description(), "kickoff");
        assert_eq!(cycle.date_a(), "2026-10-01");
        assert_eq!(cycle.date_b(), "2026-10-14");
        assert!(!cycle.is_new());
        assert_eq!(cycle.editing.as_deref(), Some("Sprint 3"));

        let milestone = PlanningForm::from_milestone(&Milestone {
            name: "GA".into(),
            target_date: "2026-12-31".into(),
            description: "ship it".into(),
            created: "2026-01-01".into(),
            updated: "2026-01-02".into(),
            file_name: "2026-01-01-ga.md".into(),
            color: None,
        });
        assert_eq!(milestone.name(), "GA");
        assert_eq!(milestone.description(), "ship it");
        assert_eq!(milestone.date_a(), "2026-12-31");
        assert_eq!(milestone.date_b(), "", "milestones have no due-date field");
        assert_eq!(milestone.editing.as_deref(), Some("GA"));
    }

    #[test]
    fn form_cursor_and_typing() {
        let mut form = PlanningForm::new(PlanningKind::Cycle);
        assert_eq!(form.focused_label(), "Name");
        form.insert_char('S');
        form.insert_char('3');
        assert_eq!(form.name(), "S3");
        form.focus_next();
        assert_eq!(form.focused_label(), "Description");
        form.insert_char('k');
        assert_eq!(form.description(), "k");
        form.delete_char();
        assert_eq!(form.description(), "");
        form.focus_prev();
        assert_eq!(form.focused_label(), "Name");

        form.focus_next();
        form.focus_next();
        form.focus_next();
        form.focus_next();
        assert_eq!(form.focused_label(), "Name", "Tab wraps to the first field");
        form.focus_prev();
        assert_eq!(
            form.focused_label(),
            "Due date",
            "Shift+Tab wraps to the last field"
        );
    }

    #[test]
    fn form_render_smokes_at_80x24_and_tiny() {
        for (w, h) in [(80, 24), (20, 5)] {
            let form = PlanningForm::from_milestone(&Milestone {
                name: "GA".into(),
                target_date: "2026-12-31".into(),
                description: "ship it".into(),
                created: "2026-01-01".into(),
                updated: "2026-01-02".into(),
                file_name: "2026-01-01-ga.md".into(),
                color: None,
            });
            let backend = TestBackend::new(w, h);
            let mut terminal = Terminal::new(backend).unwrap();
            terminal.draw(|f| form.render(f, f.area())).unwrap();
        }
    }

    #[test]
    fn edit_form_renders_edit_title() {
        let form = PlanningForm::from_cycle(
            "Sprint 3",
            &PlanningCycle {
                description: None,
                start_date: None,
                due_date: None,
            },
        );
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|f| form.render(f, f.area())).unwrap();
        let buffer = terminal.backend().buffer();
        let mut rows: Vec<String> = Vec::new();
        for y in 0..buffer.area().height {
            let mut line = String::new();
            for x in 0..buffer.area().width {
                line.push(buffer[(x, y)].symbol().chars().next().unwrap_or(' '));
            }
            rows.push(line);
        }
        assert!(
            rows.iter().any(|r| r.contains("Edit cycle")),
            "edit form titles itself: {rows:?}"
        );
    }

    // ---- WP04 T020: the epic view ------------------------------------------

    /// One epic view entry, shaped exactly as `view::epic_view` builds it.
    fn epic_entry(
        name: &str,
        id: &str,
        progress: &str,
        members: &[u32],
    ) -> crate::commands::view::EpicViewEntry {
        crate::commands::view::EpicViewEntry {
            epic: crate::commands::view::EpicBlockEntry {
                heading: format!("{name} ({id})"),
                detail: vec![
                    format!("progress: {progress}"),
                    "weighted progress: none (no weighted children)".to_string(),
                    "weight: unset".to_string(),
                    "children: 0".to_string(),
                    "parent: (none)".to_string(),
                    "depth: 0".to_string(),
                    "blocked: 0".to_string(),
                ],
            },
            members: members
                .iter()
                .map(|number| crate::commands::view::EpicMemberRef {
                    number: *number,
                    display: format!("#{number} Issue {number}"),
                })
                .collect(),
        }
    }

    /// Render the epic view into a buffer and return its rows as strings.
    fn render_epic(
        entries: &[crate::commands::view::EpicViewEntry],
        state: &EpicViewState,
    ) -> Vec<String> {
        let backend = TestBackend::new(90, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| state.render(f, f.area(), entries))
            .unwrap();
        let buffer = terminal.backend().buffer();
        (0..buffer.area().height)
            .map(|y| {
                (0..buffer.area().width)
                    .map(|x| buffer[(x, y)].symbol().chars().next().unwrap_or(' '))
                    .collect()
            })
            .collect()
    }

    #[test]
    fn t020_the_epic_view_lists_epics_in_declaration_order_with_context_and_members() {
        let entries = vec![
            epic_entry("Alpha", "e-aaa111", "1/2 done", &[5, 6]),
            epic_entry("Beta", "e-bbb222", "0/1 done", &[7]),
        ];
        let rows = render_epic(&entries, &EpicViewState::new());
        let text = rows.join("\n");
        assert!(text.contains("Epics — 2 in declaration order"), "{text}");
        assert!(text.contains("Alpha (e-aaa111)"), "{text}");
        assert!(text.contains("progress: 1/2 done"), "{text}");
        assert!(text.contains("members:"), "{text}");
        assert!(
            text.contains("#5 Issue 5") && text.contains("#6 Issue 6"),
            "{text}"
        );
        let alpha = rows
            .iter()
            .position(|row| row.contains("Alpha (e-aaa111)"))
            .unwrap();
        let beta = rows
            .iter()
            .position(|row| row.contains("Beta (e-bbb222)"))
            .unwrap();
        assert!(alpha < beta, "the service's declaration order is kept");
        assert!(
            text.contains("Enter: open the member issue directly"),
            "the direct issue navigation affordance is explicit (FR-004): {text}"
        );
    }

    #[test]
    fn t020_the_cursor_targets_the_selected_member_issue_directly() {
        let entries = vec![
            epic_entry("Alpha", "e-aaa111", "1/2 done", &[5, 6]),
            epic_entry("Beta", "e-bbb222", "0/1 done", &[7]),
        ];
        let mut state = EpicViewState::new();
        assert_eq!(state.target_member(&entries), Some(5));
        state.move_member(1, 2);
        assert_eq!(
            state.target_member(&entries),
            Some(6),
            "the member cursor selects the member `Enter` opens"
        );
        state.move_selected(1, 2);
        assert_eq!(state.target_member(&entries), Some(7));
        // An empty view and an epic with no members are inert, not arbitrary.
        assert_eq!(EpicViewState::new().target_member(&[]), None);
        assert_eq!(
            EpicViewState::new().target_member(&[epic_entry("Alpha", "e-aaa111", "0/0 done", &[])]),
            None
        );
    }

    #[test]
    fn t020_a_task_labelled_member_is_an_ordinary_member() {
        // There is no task section because there is no task entity (C-001): a member is
        // rendered by its service display label like any other.
        let entries = vec![epic_entry("Alpha", "e-aaa111", "0/1 done", &[9])];
        let text = epic_lines(&entries, &EpicViewState::new(), 40)
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|span| span.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");
        assert!(text.contains("#9 Issue 9"), "{text}");
        assert!(!text.contains("task"), "no task section exists: {text}");
    }

    #[test]
    fn t020_an_empty_registry_draws_an_empty_state_not_a_blank() {
        let text = render_epic(&[], &EpicViewState::new()).join("\n");
        assert!(text.contains("No epics yet"), "{text}");
    }

    /// Flatten a rendered line's spans, for a content assertion.
    fn row_text(line: &Line<'_>) -> String {
        line.spans
            .iter()
            .map(|span| span.content.as_ref())
            .collect()
    }

    #[test]
    fn t020_the_selected_epic_stays_in_the_frame_when_the_window_is_small() {
        // The reviewer's trigger: the window stepped back one **entry** per visible
        // line while bounding the loop by **rendered lines**, and an epic is ~10 lines,
        // so with the third epic selected the loop broke before drawing it — the cursor
        // (and `target_member`'s row) was still live but invisible.
        let entries: Vec<crate::commands::view::EpicViewEntry> = (0..3)
            .map(|index| {
                epic_entry(
                    &format!("E{index}"),
                    &format!("e-aaa{index}{index}{index}"),
                    "0/1 done",
                    &[index + 1],
                )
            })
            .collect();

        let mut state = EpicViewState::new();
        state.move_selected(2, 3);
        let lines = epic_lines(&entries, &state, 10);
        let text = lines.iter().map(row_text).collect::<Vec<_>>().join("\n");
        assert!(
            text.contains("E2 (e-aaa222)"),
            "the selected epic must be inside the frame: {text}"
        );
        assert!(
            lines
                .iter()
                .any(|line| row_text(line).contains("> E2 (e-aaa222)")),
            "and it must carry the cursor, because `Enter` acts on it: {text}"
        );

        // The minimal two-entry case the old arithmetic also broke: one entry drew,
        // the selected one did not.
        let mut state = EpicViewState::new();
        state.move_selected(1, 2);
        let text = epic_lines(&entries[..2], &state, 10)
            .iter()
            .map(row_text)
            .collect::<Vec<_>>()
            .join("\n");
        assert!(text.contains("> E1 (e-aaa111)"), "{text}");
    }
}