tix-tracker 0.5.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
//! 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,
    ) {
        let rect = modal_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);
    }
}

#[cfg(test)]
mod tests {
    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
    }

    #[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(),
        });
        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(),
            });
            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:?}"
        );
    }
}