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
//! The `F7` Stats page's **Burndown** tab (mission `burndown-scope-analytics-01M3C9J1`,
//! WP06 T029–T033).
//!
//! # A tab on a page that already ships
//!
//! The `F7` **Stats** page, its `TopMode::Stats`, its [`crate::keybindings::InputContext::Stats`]
//! and its `F7` binding all ship from `project-issue-health-status-01M3C8HX`, and its tab
//! strip from `per-issue-time-tracking-01M3C9A4`. This module is the page's **third** tab,
//! joining that strip — the rule [`crate::ui::roadmap`] documents for the `F10` Portfolio
//! page. Nothing here introduces a mode: there is no `TopMode`, no `InputContext`, no
//! `[shell]` action and no nav-tree limb, so
//! `every_mode_maps_to_a_distinct_shell_action` is untouched (analysis-report H3).
//!
//! # What the tab renders
//!
//! Every figure on the tab is a field of the shared DTOs — [`ChartExport`] and its
//! [`ChartSeries`](crate::analytics::chart::ChartSeries),
//! [`ChartProjection`](crate::analytics::chart::ChartProjection) and findings nodes — read
//! out of the **one** document the CLI's verbs read
//! ([`crate::commands::export::chart_document`]). The tab computes no series, converts no
//! unit, projects no date and groups nothing: it resolves a scope through the crate's own
//! resolver, asks the shared adapter for the document, and draws it (C-008, NFR-003). An
//! unanswerable value is `-` and never a `0` (C-005), a day's coverage marker travels beside
//! the values it qualifies, and a closed snapshot's binding is named on the scope line and
//! in the `closed_snapshot` finding (C-006).
//!
//! # The chart
//!
//! The `CHART` column is a hand-drawn terminal bar, not a dependency (C-009): one `█` per
//! unit of the day's **remaining** value, truncated at [`BAR_CELLS`] with a trailing `…`,
//! `·` for a known zero and a `-` for a day whose remaining work the record cannot answer —
//! the same value the `REMAINING` column spells, drawn. It assembles no scale, computes no
//! maximum and normalises nothing, so it can disagree with no other surface about a figure.
//!
//! # Read-only
//!
//! The tab's controls select a scope, a period source, a mode, a unit and a forecast
//! origin in **session state** and re-fold through the shared seam; none of them writes.
//! There is no key here that reaches a store's write path, and the tab's own tests assert
//! the project's bytes are untouched after every control (T033).
//!
//! [`ChartSeries`]: crate::analytics::chart::ChartSeries

use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};

use crate::analytics::chart::{ChartExport, ChartProjection};
use crate::analytics::events::{AnalyticsScope, Period};
use crate::analytics::series::{Coverage, CoverageSummary, DailyPoint, Mode};
use crate::keybindings::TuiAction;
use crate::ui::detail::dash_number;

/// How many cells the `CHART` column draws for one value before truncating it.
///
/// A cap, not a scale: past it the bar ends in `…`, and the value it stands for is
/// printed beside it in `REMAINING`. A bar that re-scaled every day against the series'
/// largest value would be a second arithmetic of the same figure.
const BAR_CELLS: usize = 20;

/// The glyph one unit of the chart's bar is drawn with.
const BAR: &str = "█";

/// The `CHART` column's own spelling for a value the record cannot answer.
const NO_BAR: &str = "-";

/// The `CHART` column's own spelling for a **known** zero: no work remains, and the record
/// says so.
///
/// Distinct from [`NO_BAR`] on purpose — a zero-length bar and an unanswerable value must not
/// render identically, or the chart would re-introduce the assumption C-005 forbids.
const ZERO_BAR: &str = "·";

/// The daily table's columns, in the data model's field order (T031).
const DAY_COLUMNS: [&str; 7] = [
    "DATE",
    "COVERAGE",
    "REMAINING",
    "SCOPE",
    "DONE",
    "+ADD",
    "-DONE",
];

/// The daily table's column widths, one per [`DAY_COLUMNS`] entry.
///
/// The two text columns (`DATE`, `COVERAGE`) are left-aligned and every numeric column
/// right-aligned, so a column of `-`s and a column of counts read as the same column — the
/// shape the page's other tables use.
const DAY_WIDTHS: [usize; 7] = [10, 16, 9, 9, 9, 9, 9];

/// Whether the column at `index` is text (left-aligned) rather than numeric.
const fn day_text_column(index: usize) -> bool {
    index < 2
}

/// The keys the Burndown tab answers to through the binding table (T029/T033).
///
/// The tab's cursor and the page's strip are the page's own actions — `j`/`k` (and the
/// arrows), `Tab`/`Shift+Tab`, `?` and `q` — exactly as the Health and Time tabs use them.
/// `Submit` is deliberately absent: `Enter` opens nothing on this tab, and an overlay that
/// advertised it would name a key that does nothing.
pub const HELP_ACTIONS: &[TuiAction] = &[
    TuiAction::MoveUp,
    TuiAction::MoveDown,
    TuiAction::Next,
    TuiAction::Previous,
    TuiAction::Help,
    TuiAction::Close,
];

/// The keys the Burndown tab answers to **raw**, with what each one does.
///
/// These are the controls T030 asks for, and they are raw for the reason the `F8` Schedule
/// page's tab keys are: none of them is bound in
/// [`crate::keybindings::InputContext::Stats`], so the binding layer would rewrite them to
/// the inert `F(12)` sentinel, and none of them is named by a [`TuiAction`] — so the tab
/// adds no action, no key-map row and no `docs/key-bindings.md` row (analysis-report H4).
pub const HELP_RAW: &[(&str, &str)] = &[
    ("[ / ]", "previous / next scope"),
    ("p", "period source (planning / observed)"),
    ("t", "mode (count / estimate)"),
    ("u", "next estimate unit"),
    ("v", "ask for the forecast"),
    ("d / D", "forecast origin (earlier / later)"),
];

/// The footer rows the `F7` Stats page draws for its **Burndown** tab.
///
/// The page's own cursor, strip and exit rows, and nothing from the Time tab: the footer
/// truncates, and a key that exists only on another tab is exactly the leak the tab scoping
/// exists to prevent. They are the overlay's own rows — one tab, one key set, so the two
/// surfaces cannot drift — and the controls themselves are spelled in [`HELP_RAW`] and in
/// the tab's own hint row.
pub const FOOTER_ACTIONS: &[TuiAction] = HELP_ACTIONS;

/// Which period the series covers (T030).
///
/// Two callers' choices, both of them the record's own: the scope's **planning** period
/// (what the CLI passes when no `--from`/`--to` is named) and the period the recorded
/// **events** themselves span (the fold resolves an absent bound to the observed extent —
/// its own documented answer, and the remedy the shared `missing_history` finding names).
/// Neither is arithmetic: no date is shifted, only a bound released.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum BurndownPeriod {
    /// The scope's own planning period — the cycle's declared dates, the milestone's target.
    #[default]
    Planning,
    /// Both bounds released, so the fold covers exactly the days the record's events span.
    Observed,
}

impl BurndownPeriod {
    /// Both sources, in cycle order.
    pub const ALL: [Self; 2] = [Self::Planning, Self::Observed];

    /// The source's name, as the tab spells it.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Planning => "planning",
            Self::Observed => "observed",
        }
    }

    /// The source's one-line explanation.
    pub const fn description(self) -> &'static str {
        match self {
            Self::Planning => "the scope's own planning period",
            Self::Observed => "the days the record's own events span",
        }
    }

    /// The next source, wrapping.
    pub fn next(self) -> Self {
        match self {
            Self::Planning => Self::Observed,
            Self::Observed => Self::Planning,
        }
    }
}

/// The `F7` Stats page's **Burndown** tab session state (T029–T032).
///
/// Every selection lives here and nowhere else: the scope, the period source, the mode, the
/// unit, whether the forecast is asked for, and the forecast's origin. Nothing is persisted
/// (a session default is not a preference), nothing is a total, and the tab's one **read** —
/// the shared [`ChartExport`] — is rebuilt when the tab is opened and after every control,
/// never during a render.
///
/// The origin is held as a count of days **back from the series' last covered day**, so a
/// refresh cannot leave it pointing at a day the fold no longer holds: the projection's own
/// refusal for an uncovered day is a statement the tab should never have to make.
#[derive(Debug, Clone, PartialEq)]
pub struct BurndownState {
    /// The scopes the record offers, resolved through the crate's own scope resolver.
    pub choices: Vec<AnalyticsScope>,
    /// Which choice is selected, as an index into [`Self::choices`].
    pub choice: usize,
    /// Which period source the series is folded over.
    pub period: BurndownPeriod,
    /// How the series counts.
    pub mode: Mode,
    /// The units the project declares a conversion for ([`crate::analytics::units::declared_units`]).
    pub units: Vec<String>,
    /// Which unit is selected, as an index into [`Self::units`]. Remembered in count mode,
    /// where the fold ignores it, so switching back does not lose the reader's choice.
    pub unit: usize,
    /// Whether the forecast is asked for.
    pub forecast: bool,
    /// The forecast origin: how many covered days back from the series' last covered day.
    pub origin_back: usize,
    /// Which daily row the cursor is on, as an index into the series' points.
    pub cursor: usize,
    /// The document the tab is showing, `None` when no fold has produced one.
    pub document: Option<ChartExport>,
    /// Why the last fold produced no document — a read that failed, or a request the
    /// record cannot carry. An explicit state, never a blank pane.
    pub problem: Option<String>,
}

impl BurndownState {
    /// A fresh tab over `choices`, with the scope's own period, count mode, unit `0`, no
    /// forecast, the origin on the series' last covered day and the cursor on the first row.
    pub fn new(choices: Vec<AnalyticsScope>, units: Vec<String>) -> Self {
        Self {
            choices,
            choice: 0,
            period: BurndownPeriod::Planning,
            mode: Mode::Count,
            units,
            unit: 0,
            forecast: false,
            origin_back: 0,
            cursor: 0,
            document: None,
            problem: None,
        }
    }

    /// The selected choice, when the record offers one.
    pub fn selected(&self) -> Option<&AnalyticsScope> {
        self.choices.get(self.choice)
    }

    /// The scope the fold is asked for: the selection with [`Self::period`] applied.
    ///
    /// The closed-snapshot binding travels with the choice (the record's close evidence), so
    /// it survives the period change — a snapshot-bound scope stays bound whatever period the
    /// reader looks through, which is what C-006 requires of a historical view.
    pub fn scope(&self) -> Option<AnalyticsScope> {
        let mut scope = self.selected()?.clone();
        if self.period == BurndownPeriod::Observed {
            scope.period = Period::unbounded();
        }
        Some(scope)
    }

    /// The unit the fold is asked for: the selection, and only in estimate mode — a count is
    /// unitless, which is what the CLI's `--unit` does too.
    pub fn unit(&self) -> Option<&str> {
        if self.mode != Mode::Estimate {
            return None;
        }
        self.units.get(self.unit).map(String::as_str)
    }

    /// The covered days the current document holds.
    pub fn days(&self) -> usize {
        self.document
            .as_ref()
            .map_or(0, |document| document.series.points.len())
    }

    /// The forecast origin: the covered day [`Self::origin_back`] days back from the last one.
    pub fn origin(&self) -> Option<&DailyPoint> {
        let points = &self.document.as_ref()?.series.points;
        points.get(points.len().checked_sub(self.origin_back + 1)?)
    }

    /// The forecast to ask the document for, as `(as_of, end_date)` — the same pair the CLI
    /// passes as `--as-of` and the scope's planning end.
    ///
    /// `None` when the forecast is off, when there is no covered day to stand on, or when the
    /// effective period declares no end: the caller renders each of those states explicitly
    /// rather than asking for a forecast the record cannot bound.
    pub fn projection(&self) -> Option<(String, String)> {
        if !self.forecast {
            return None;
        }
        let origin = self.origin()?;
        let end = self.scope()?.period_end().map(str::to_string)?;
        Some((origin.date.clone(), end))
    }

    /// Switch to the scope `delta` steps away, wrapping — so one key reaches every scope from
    /// either side, exactly as the page's tab strip does.
    pub fn shift_scope(&mut self, delta: isize) {
        if self.choices.is_empty() {
            self.choice = 0;
            return;
        }
        let len = self.choices.len() as isize;
        self.choice = ((self.choice as isize + delta).rem_euclid(len)) as usize;
        // A different scope holds a different series: the other selections are the reader's
        // and stay, but the origin is a *day* of the series and starts from the scope's own
        // end again. The cursor does too — row 12 of one scope is not row 12 of another.
        self.origin_back = 0;
        self.cursor = 0;
    }

    /// The other period source (T030).
    pub fn cycle_period(&mut self) {
        self.period = self.period.next();
    }

    /// The other mode: count ↔ estimate (T030).
    pub fn cycle_mode(&mut self) {
        self.mode = match self.mode {
            Mode::Count => Mode::Estimate,
            Mode::Estimate => Mode::Count,
        };
    }

    /// The next unit the project declares, wrapping; inert when it declares none.
    pub fn cycle_unit(&mut self) {
        if !self.units.is_empty() {
            self.unit = (self.unit + 1) % self.units.len();
        }
    }

    /// Ask for the forecast, or stop asking for it.
    pub fn toggle_forecast(&mut self) {
        self.forecast = !self.forecast;
        if !self.forecast {
            self.origin_back = 0;
        }
    }

    /// Move the forecast origin one covered day earlier, to the series' first day at most.
    pub fn origin_earlier(&mut self) {
        let last = self.days().saturating_sub(1);
        self.origin_back = (self.origin_back + 1).min(last);
    }

    /// Move the forecast origin one covered day later, to the series' last day at most.
    pub fn origin_later(&mut self) {
        self.origin_back = self.origin_back.saturating_sub(1);
    }

    /// Move the daily cursor `delta` rows, clamped into the days the document holds.
    pub fn move_cursor(&mut self, delta: isize) {
        let last = self.days().saturating_sub(1);
        let next = if delta.is_negative() {
            self.cursor.saturating_sub(delta.unsigned_abs())
        } else {
            self.cursor.saturating_add(delta as usize)
        };
        self.cursor = next.min(last);
    }

    /// Keep every index inside the list it indexes (called after every read, so a control
    /// cannot leave a cursor past the end of a document the fold just shrank).
    pub fn clamp(&mut self) {
        if self.choice >= self.choices.len() {
            self.choice = 0;
        }
        if self.unit >= self.units.len() {
            self.unit = 0;
        }
        let last = self.days().saturating_sub(1);
        self.origin_back = self.origin_back.min(last);
        self.cursor = self.cursor.min(last);
    }
}

/// The tab's rendered body: the lines to draw and the line its cursor is on.
///
/// The cursor travels with the lines so the frame can scroll the body to keep the selected
/// day visible without the tab re-deriving where that day landed.
#[derive(Debug, Clone, PartialEq)]
pub struct BurndownFrame {
    /// The body, top to bottom.
    pub lines: Vec<Line<'static>>,
    /// The index in [`Self::lines`] of the selected day's row, or `0` when none is drawn.
    pub cursor_line: usize,
}

/// The Burndown tab's body (T029/T031/T032).
///
/// The scope header, then the fold's own metadata, the daily table with its chart column,
/// the forecast when one was asked for, and every finding with its reason and its remedy —
/// in the order the CLI's report prints them. An empty answer is a sentence that says so,
/// never a blank pane.
pub fn frame(state: &BurndownState) -> BurndownFrame {
    let mut lines: Vec<Line<'static>> = Vec::new();
    let mut cursor_line = 0usize;

    if state.choices.is_empty() {
        lines.extend(no_scope_lines());
        return BurndownFrame { lines, cursor_line };
    }

    lines.extend(scope_lines(state, state.document.as_ref()));
    lines.push(Line::from(""));

    let Some(document) = state.document.as_ref() else {
        lines.extend(problem_lines(state));
        return BurndownFrame { lines, cursor_line };
    };

    lines.extend(fold_lines(document));
    lines.push(Line::from(""));

    if document.is_empty() {
        lines.extend(no_day_lines(document));
    } else {
        lines.push(head_line());
        for (index, point) in document.series.points.iter().enumerate() {
            let selected = index == state.cursor;
            if selected {
                cursor_line = lines.len();
            }
            lines.push(day_line(point, selected));
        }
    }

    lines.push(Line::from(""));
    lines.extend(projection_lines(state, document));
    lines.push(Line::from(""));
    lines.extend(diagnostic_lines(document));
    BurndownFrame { lines, cursor_line }
}

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

fn warning() -> Style {
    Style::default()
        .fg(Color::Yellow)
        .add_modifier(Modifier::BOLD)
}

/// One `label: value` line, in the page's own field style.
fn field(label: &str, value: &str) -> Line<'static> {
    Line::from(vec![
        Span::styled(format!("{label}: "), dim()),
        Span::raw(value.to_string()),
    ])
}

/// The scope lines, in the CLI's own order and spelling (`scope`, `id`, `period`,
/// `snapshot`, `mode`, `unit`), plus the two facts only a *tabbed* surface needs to state:
/// which period source is in force, and where the selection sits in the list.
///
/// The values are the resolved scope's own fields — the same value `tix analytics burndown`
/// prints for the same scope — so the two surfaces cannot disagree about the period or the
/// snapshot binding (NFR-003).
fn scope_lines(state: &BurndownState, document: Option<&ChartExport>) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    let Some(scope) = state.scope() else {
        return lines;
    };
    let period = format!(
        "{}..{}",
        bound_text(scope.period_start()),
        bound_text(scope.period_end())
    );
    lines.push(field("scope", scope.kind.as_str()));
    lines.push(field("id", &scope.id));
    lines.push(field("period", &period));
    lines.push(field(
        "period source",
        &format!("{} ({})", state.period.label(), state.period.description()),
    ));
    lines.push(field(
        "snapshot",
        scope.snapshot_id.as_deref().unwrap_or("-"),
    ));
    lines.push(field("mode", state.mode.as_str()));
    // The document's own unit when there is one — the CLI prints the same field — and
    // the selection otherwise, so the line reads the same before and after a fold.
    let unit = document
        .and_then(|document| document.unit.as_deref())
        .or_else(|| state.unit())
        .unwrap_or("-");
    lines.push(field("unit", unit));
    lines.push(field(
        "selected",
        &format!("{} of {}", state.choice + 1, state.choices.len()),
    ));
    lines
}

/// A period bound as the CLI prints it: the date, or `open` for a bound the record does not
/// declare (which is coverage, not a guess).
fn bound_text(bound: Option<&str>) -> &str {
    bound.unwrap_or("open")
}

/// The fold's own metadata: the formula version, the day count, the covered span and the
/// coverage tally — every value a field or an accessor of the shared document. The finding
/// count is drawn once, above the findings themselves.
fn fold_lines(document: &ChartExport) -> Vec<Line<'static>> {
    let coverage: CoverageSummary = document.coverage;
    let covered = document
        .series
        .points
        .first()
        .zip(document.series.points.last())
        .map_or_else(
            || "-".to_string(),
            |(first, last)| format!("{}..{}", first.date, last.date),
        );
    vec![
        field("formula", &document.formula_version),
        Line::from(vec![
            Span::styled("days: ", dim()),
            Span::raw(document.series.points.len().to_string()),
            Span::styled("   covered: ", dim()),
            Span::raw(covered),
        ]),
        Line::from(vec![
            Span::styled("coverage: ", dim()),
            Span::raw(format!(
                "known={} unknown={} coverage_limited={}",
                coverage.known, coverage.unknown, coverage.coverage_limited
            )),
        ]),
    ]
}

/// How many findings the tab renders: the series' own, the forecast's when one is in the
/// document, then the document's — the same sum, in the same order, as the CLI's.
fn finding_count(document: &ChartExport) -> usize {
    document.series.diagnostics.len()
        + document
            .projection
            .as_ref()
            .map_or(0, |projection| projection.diagnostics.len())
        + document.diagnostics.len()
}

/// The daily table's heading row.
fn head_line() -> Line<'static> {
    let mut text = String::from("  ");
    for (index, column) in DAY_COLUMNS.iter().enumerate() {
        if index > 0 {
            text.push_str("  ");
        }
        let width = DAY_WIDTHS[index];
        if day_text_column(index) {
            text.push_str(&format!("{column:<width$}"));
        } else {
            text.push_str(&format!("{column:>width$}"));
        }
    }
    text.push_str("  CHART");
    Line::from(Span::styled(text, dim()))
}

/// One day as the table's row: the point's own fields, the shared coverage marker beside
/// them, and the chart bar (T031).
///
/// A `None` is `-` through [`dash_number`], the crate's one rendering of "no value", so an
/// unobserved day's additions read as absent rather than as a recorded zero — the `0` an
/// *observed* quiet day carries is right beside it in the same column.
fn day_line(point: &DailyPoint, selected: bool) -> Line<'static> {
    let cells = [
        point.date.clone(),
        point.coverage.as_str().to_string(),
        dash_number(point.remaining),
        dash_number(point.scope_total),
        dash_number(point.completed),
        dash_number(point.scope_added),
        dash_number(point.completions),
    ];
    let mut text = if selected {
        String::from("> ")
    } else {
        String::from("  ")
    };
    for (index, cell) in cells.iter().enumerate() {
        if index > 0 {
            text.push_str("  ");
        }
        let width = DAY_WIDTHS[index];
        if day_text_column(index) {
            text.push_str(&format!("{cell:<width$}"));
        } else {
            text.push_str(&format!("{cell:>width$}"));
        }
    }
    text.push_str("  ");
    text.push_str(&bar_text(point.remaining));
    Line::from(Span::styled(text, day_style(point.coverage, selected)))
}

/// The style one day's row is drawn in: the coverage marker is the day's own warning, and
/// the cursor is the reader's.
fn day_style(coverage: Coverage, selected: bool) -> Style {
    let base = match coverage {
        Coverage::Known => Style::default(),
        Coverage::CoverageLimited => Style::default().fg(Color::Yellow),
        Coverage::Unknown => dim(),
    };
    if selected {
        base.add_modifier(Modifier::BOLD)
    } else {
        base
    }
}

/// The chart column's text for one day: one cell per unit of remaining work, truncated with
/// `…` past [`BAR_CELLS`], `·` for a known zero, and `-` for work the day cannot answer.
fn bar_text(remaining: Option<i64>) -> String {
    let Some(remaining) = remaining else {
        return NO_BAR.to_string();
    };
    let cells = usize::try_from(remaining).unwrap_or(0);
    if cells == 0 {
        return ZERO_BAR.to_string();
    }
    let mut bar = BAR.repeat(cells.min(BAR_CELLS));
    if cells > BAR_CELLS {
        bar.push('…');
    }
    bar
}

/// The forecast block: the projection's own fields when one was drawn, and an explicit
/// statement of *which* state the tab is in when one was not (T032).
fn projection_lines(state: &BurndownState, document: &ChartExport) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    match document.projection.as_ref() {
        Some(projection) => lines.extend(forecast_lines(projection)),
        None if !state.forecast => {
            lines.push(field("projection", "off (press `v` to ask for it)"));
        }
        None => {
            lines.push(field("projection", "unavailable"));
            match state.scope().filter(|scope| scope.period_end().is_none()) {
                Some(scope) => {
                    // The shared service names this state: the scope declares no planning end,
                    // so there is no boundary to draw a forecast against. Pressing `p` cannot
                    // bound a scope that declares none, so the remedy is the record's own.
                    lines.push(Line::from(format!(
                        "  the {} scope `{}` declares no planning end date, so a forecast has \
                         no boundary to be drawn against",
                        scope.kind, scope.id
                    )));
                    lines.push(Line::from(
                        "  remedy: give the scope an end — the cycle's `due_date` or the \
                         milestone's target date",
                    ));
                }
                None => {
                    lines.push(Line::from(
                        "  the record holds no covered day to stand the forecast on",
                    ));
                    lines.push(Line::from(
                        "  remedy: widen the series' period (press `p`) so it covers a \
                         recorded day",
                    ));
                }
            }
        }
    }
    lines
}

/// The forecast's own fields, in the CLI's `projection_block` order.
///
/// The formula version is the **projection's**, not the series' — two different documents of
/// two different formulas — and every unanswerable value is `-`: a forecast that could not be
/// drawn says its `status` and its findings rather than printing a date it did not derive.
fn forecast_lines(projection: &ChartProjection) -> Vec<Line<'static>> {
    vec![
        field("projection", projection.status.as_str()),
        field("  as_of", &projection.as_of),
        field("  end_date", &projection.end_date),
        field("  remaining", &dash_number(projection.remaining)),
        field("  observed_rate", &dash_number(projection.observed_rate)),
        field(
            "  projected_completion",
            projection.projected_completion.as_deref().unwrap_or("-"),
        ),
        field("  meets_end_date", &dash_number(projection.meets_end_date)),
        field("  formula", &projection.formula_version),
    ]
}

/// Every finding the document holds, in the count's own order, each with its reason and its
/// remedy (T031/T032).
///
/// The series' findings lead (they are the fold's), then the forecast's, then the document's
/// own. Each is drawn from its fields, not from a pre-rendered string, so the tab lays out
/// what the CLI prints to stderr — the same kind, scope, day, message and remedy.
fn diagnostic_lines(document: &ChartExport) -> Vec<Line<'static>> {
    let mut lines = vec![field("diagnostics", &finding_count(document).to_string())];
    for diagnostic in &document.series.diagnostics {
        lines.extend(finding_lines(diagnostic));
    }
    if let Some(projection) = document.projection.as_ref() {
        for diagnostic in &projection.diagnostics {
            lines.extend(finding_lines(diagnostic));
        }
    }
    for diagnostic in &document.diagnostics {
        lines.push(Line::from(format!(
            "  {}  {}  {}",
            diagnostic.kind,
            diagnostic
                .scope
                .as_deref()
                .or(diagnostic.target.as_deref())
                .unwrap_or("-"),
            diagnostic.reason
        )));
        if let Some(remedy) = diagnostic.remedy.as_deref() {
            lines.push(Line::from(Span::styled(
                format!("    remedy: {remedy}"),
                dim(),
            )));
        }
    }
    if document.series.diagnostics.is_empty()
        && document.diagnostics.is_empty()
        && document
            .projection
            .as_ref()
            .is_none_or(|projection| projection.diagnostics.is_empty())
    {
        lines.push(Line::from(Span::styled(
            "  none: the fold answered every day it covers",
            dim(),
        )));
    }
    lines
}

/// One shared [`AnalyticsDiagnostic`](crate::analytics::diagnostics::AnalyticsDiagnostic) as
/// the tab draws it: the kind and the scope it is about, its day and event when it has them,
/// the message, and the remedy.
fn finding_lines(
    diagnostic: &crate::analytics::diagnostics::AnalyticsDiagnostic,
) -> Vec<Line<'static>> {
    let mut place = diagnostic.scope.clone();
    if let Some(date) = diagnostic.date.as_deref() {
        place.push_str(&format!("  {date}"));
    }
    if let Some(event_id) = diagnostic.event_id.as_deref() {
        place.push_str(&format!("  {event_id}"));
    }
    let mut lines = vec![Line::from(format!(
        "  {}  {place}  {}",
        diagnostic.kind.as_str(),
        diagnostic.message
    ))];
    if let Some(remedy) = diagnostic.remedy.as_deref() {
        lines.push(Line::from(Span::styled(
            format!("    remedy: {remedy}"),
            dim(),
        )));
    }
    lines
}

/// The tab with no scope to report: an explicit sentence naming how to give it one.
fn no_scope_lines() -> Vec<Line<'static>> {
    vec![
        Line::from(Span::styled(
            "No cycle or milestone is recorded.",
            warning(),
        )),
        Line::from("The fold reports one scope at a time, and the record names none to report."),
        Line::from("Define one with `tix cycle add <name>` or `tix milestone create <name>`,"),
        Line::from("then open this tab again."),
    ]
}

/// The fold's own answer when it covers no day: the sentence, and the findings that say why.
fn no_day_lines(document: &ChartExport) -> Vec<Line<'static>> {
    let findings = document.series.diagnostics.len();
    let mut lines = vec![
        Line::from(Span::styled(
            "The fold answered no day for this scope.",
            warning(),
        )),
        Line::from(format!(
            "It reported {findings} finding(s) — below — rather than an empty series."
        )),
    ];
    if document.series.diagnostics.is_empty() {
        lines.push(Line::from(
            "The period could not be enumerated: press `p` for the period the record's own",
        ));
        lines.push(Line::from(
            "events span, or choose a scope whose record declares its dates.",
        ));
    }
    lines
}

/// The tab when the last fold produced no document: the problem verbatim, then what the
/// reader can do about it.
fn problem_lines(state: &BurndownState) -> Vec<Line<'static>> {
    let mut lines = vec![Line::from(Span::styled(
        "The fold produced no document.",
        warning(),
    ))];
    match state.problem.as_deref() {
        Some(problem) => lines.push(Line::from(problem.to_string())),
        None => lines.push(Line::from(
            "The scope, period, mode or unit selects no series this build can fold.",
        )),
    }
    lines.push(Line::from(""));
    lines.push(Line::from(
        "press `t` for count mode, `p` for the period the record's own events span,",
    ));
    lines.push(Line::from("or `[`/`]` for another scope"));
    lines
}

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

    /// A block of lines as text, one row per line — [`text`] renders a single [`Line`].
    fn render(lines: &[Line<'static>]) -> String {
        lines
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|span| span.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    fn unknown_day() -> DailyPoint {
        DailyPoint {
            date: "2026-01-05".to_string(),
            scope_total: None,
            remaining: None,
            completed: None,
            scope_added: None,
            completions: None,
            coverage: Coverage::Unknown,
            event_ids: Vec::new(),
        }
    }

    fn quiet_day() -> DailyPoint {
        DailyPoint {
            date: "2026-01-06".to_string(),
            scope_total: Some(0),
            remaining: Some(0),
            completed: Some(0),
            scope_added: Some(0),
            completions: Some(0),
            coverage: Coverage::Known,
            event_ids: Vec::new(),
        }
    }

    fn limited_day() -> DailyPoint {
        DailyPoint {
            date: "2026-01-07".to_string(),
            scope_total: Some(2),
            remaining: Some(1),
            completed: None,
            scope_added: None,
            completions: None,
            coverage: Coverage::CoverageLimited,
            event_ids: Vec::new(),
        }
    }

    fn text(line: &Line<'_>) -> String {
        line.spans
            .iter()
            .map(|span| span.content.as_ref())
            .collect::<String>()
    }

    /// A day the record cannot answer prints `-` in every numeric column, never a `0` — and
    /// the day beside it, which *was* read, prints the zero the record holds.
    #[test]
    fn an_unanswerable_day_is_a_dash_and_a_read_quiet_day_is_a_zero() {
        let unobserved = text(&day_line(&unknown_day(), false));
        assert!(unobserved.contains("unknown"), "{unobserved}");
        assert!(
            unobserved.contains("2026-01-05  unknown"),
            "the coverage marker travels beside the values it qualifies: {unobserved}"
        );
        let cells: Vec<&str> = unobserved.split_whitespace().collect();
        assert_eq!(cells[0], "2026-01-05", "{cells:?}");
        assert_eq!(cells[1], "unknown", "{cells:?}");
        assert_eq!(
            cells[2..7].to_vec(),
            vec!["-"; 5],
            "no numeric cell of an unanswerable day reads as a recorded zero: {cells:?}"
        );
        assert_eq!(
            cells[7], "-",
            "and the chart column draws the absent marker, not a zero-length bar: {cells:?}"
        );

        let observed = text(&day_line(&quiet_day(), false));
        assert!(observed.contains("known"), "{observed}");
        assert!(
            observed.contains(" 0"),
            "an observed quiet day's zero is a value: {observed}"
        );
        assert!(
            observed.trim_end().ends_with(ZERO_BAR),
            "and its chart column says a known zero, not an unknown one: {observed}"
        );
    }

    /// A scope that declares no planning end, asked for a forecast, must say *that*: the
    /// shared service names the state (`ProjectionUnknown`), and "press `p`" cannot bound a
    /// scope that declares none. A review found the tab printing "no covered day" while it
    /// was drawing covered days, with that unfollowable remedy.
    #[test]
    fn an_unbounded_scope_under_a_forecast_names_the_missing_planning_end() {
        let unbounded = AnalyticsScope {
            kind: crate::analytics::events::ScopeKind::Cycle,
            id: "Open Cycle".to_string(),
            period: crate::analytics::events::Period {
                start: Some("2026-01-05".to_string()),
                end: None,
            },
            snapshot_id: None,
        };
        let series = crate::analytics::series::BurndownSeries {
            scope: unbounded.clone(),
            mode: Mode::Count,
            unit: None,
            points: vec![quiet_day()],
            diagnostics: Vec::new(),
            formula_version: "burndown.count.v1".to_string(),
        };
        let document = ChartExport::build(&series, None, &[]);
        let mut state = BurndownState::new(vec![unbounded.clone()], Vec::new());
        state.forecast = true;

        let rendered = render(&projection_lines(&state, &document));
        assert!(
            rendered.contains("declares no planning end date"),
            "the missing planning end is named: {rendered}"
        );
        assert!(
            !rendered.contains("no covered day"),
            "the scope has a covered day, so that sentence is false here: {rendered}"
        );
        assert!(
            rendered.contains("due_date"),
            "and the remedy names the record's own field: {rendered}"
        );

        // The other cause keeps its own sentence: a scope that has an end but no covered day.
        let bounded = AnalyticsScope {
            period: crate::analytics::events::Period {
                start: Some("2026-01-05".to_string()),
                end: Some("2026-01-09".to_string()),
            },
            ..unbounded.clone()
        };
        let mut state = BurndownState::new(vec![bounded], Vec::new());
        state.forecast = true;
        let empty = ChartExport::build(
            &crate::analytics::series::BurndownSeries {
                points: Vec::new(),
                ..series
            },
            None,
            &[],
        );
        let rendered = render(&projection_lines(&state, &empty));
        assert!(rendered.contains("no covered day"), "{rendered}");
        assert!(!rendered.contains("planning end date"), "{rendered}");
    }

    /// A coverage-limited day whose level **is** known still draws the level it has, with the
    /// marker beside it: the bar never stands in for a value the day does not hold.
    #[test]
    fn a_coverage_limited_day_draws_the_level_it_holds() {
        let row = text(&day_line(&limited_day(), true));
        assert!(row.starts_with("> "), "the cursor marks the row: {row}");
        assert!(row.contains("coverage_limited"), "{row}");
        assert!(row.contains('█'), "{row}");
    }

    /// The chart column is the value drawn, not a second arithmetic: one cell per unit, a
    /// truncation marker past the cap, and a dash for a value the record does not hold.
    #[test]
    fn the_chart_bar_draws_the_value_it_stands_for() {
        assert_eq!(bar_text(None), "-", "an unanswerable value draws no bar");
        assert_eq!(
            bar_text(Some(0)),
            "·",
            "a known zero is drawn as a zero, not as the absent marker"
        );
        assert_eq!(bar_text(Some(3)), "███");
        assert_eq!(bar_text(Some(20)), "█".repeat(20));
        assert_eq!(bar_text(Some(21)), format!("{}…", "█".repeat(20)));
    }

    /// The Burndown tab lists the actions it really has, and none of the Time tab's.
    #[test]
    fn the_burndown_rows_name_only_this_tabs_keys() {
        let bindings =
            crate::keybindings::KeyBindings::resolve(&crate::keybindings::KeyBindings::default())
                .expect("the built-in bindings resolve");
        let context = crate::keybindings::InputContext::Stats;
        for action in HELP_ACTIONS {
            assert!(
                bindings.bound_actions(context).contains(action),
                "`{}` is not bound in the Stats context",
                action.as_str()
            );
        }
        for absent in [
            TuiAction::TimeAdd,
            TuiAction::TimeEdit,
            TuiAction::TimeDelete,
            TuiAction::TimeFilter,
            TuiAction::TimeBreakdown,
            TuiAction::TimeHistory,
            // `Enter` opens nothing here, so the overlay must not name it.
            TuiAction::Submit,
        ] {
            assert!(
                !HELP_ACTIONS.contains(&absent),
                "`{}` acts on nothing on the Burndown tab",
                absent.as_str()
            );
            assert!(
                !FOOTER_ACTIONS.contains(&absent),
                "`{}` acts on nothing on the Burndown tab",
                absent.as_str()
            );
        }
        let advertised: Vec<&str> = HELP_RAW.iter().map(|(key, _)| *key).collect();
        for key in ["[ / ]", "p", "t", "u", "v", "d / D"] {
            assert!(
                advertised.contains(&key),
                "the tab names `{key}`: {advertised:?}"
            );
        }
    }

    /// A tab with no scope says so rather than drawing nothing.
    #[test]
    fn a_tab_with_no_scope_says_so() {
        let state = BurndownState::new(Vec::new(), Vec::new());
        let frame = frame(&state);
        let text: Vec<String> = frame.lines.iter().map(text).collect();
        assert!(
            text.iter()
                .any(|line| line.contains("No cycle or milestone is recorded")),
            "{text:?}"
        );
        assert_eq!(frame.cursor_line, 0);
    }

    /// The state's own controls are pure session choices: the mode toggle, the unit cycle,
    /// the period source and the scope ring.
    #[test]
    fn the_controls_move_between_the_records_own_choices() {
        let mut state = BurndownState::new(
            vec![
                AnalyticsScope::cycle("Sprint 7", Period::unbounded()).unwrap(),
                AnalyticsScope::milestone("v1", Period::unbounded()).unwrap(),
            ],
            vec!["points".to_string(), "hours".to_string()],
        );
        assert_eq!(state.mode, Mode::Count);
        assert_eq!(state.unit(), None, "a count is unitless");
        state.cycle_mode();
        assert_eq!(state.mode, Mode::Estimate);
        assert_eq!(state.unit(), Some("points"));
        state.cycle_unit();
        assert_eq!(state.unit(), Some("hours"));
        state.cycle_unit();
        assert_eq!(state.unit(), Some("points"), "the unit list wraps");
        state.cycle_period();
        assert_eq!(state.period, BurndownPeriod::Observed);
        assert_eq!(
            state.scope().unwrap().period,
            Period::unbounded(),
            "the observed source releases both bounds"
        );
        state.shift_scope(1);
        assert_eq!(state.selected().unwrap().id, "v1");
        state.shift_scope(1);
        assert_eq!(state.selected().unwrap().id, "Sprint 7", "the ring wraps");
        state.shift_scope(-1);
        assert_eq!(state.selected().unwrap().id, "v1");
    }
}