tix-tracker 0.3.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, List, ListItem, ListState, Paragraph};

use crate::config::BoardConfiguration;
use crate::model::Priority;
use crate::search::{Corpus, StructuredFilter};
use crate::storage::Store;

use super::widgets;

#[derive(Debug, Clone)]
pub struct Card {
    pub number: u32,
    pub title: String,
    pub priority: Priority,
    pub labels: Vec<String>,
    pub assignee: Option<String>,
    pub filename: String,
    pub commit: Option<String>,
    pub created: String,
}

impl crate::config::OrderBy {
    /// Sort cards in place per the board's `order_by` setting. `none` is a
    /// no-op. `sort_by` is stable, so equal creation dates keep the
    /// underlying store order (relative filename ascending) — deterministic
    /// ties with no extra key. Dates are zero-padded `YYYY-MM-DD`, so
    /// lexicographic comparison is chronological.
    pub fn sort(&self, cards: &mut [Card]) {
        match self {
            crate::config::OrderBy::CreatedAtDesc => {
                cards.sort_by(|a, b| b.created.cmp(&a.created))
            }
            crate::config::OrderBy::CreatedAtAsc => cards.sort_by(|a, b| a.created.cmp(&b.created)),
            crate::config::OrderBy::None => {}
        }
    }
}

#[derive(Debug, Clone)]
pub struct BoardColumn {
    pub name: String,
    pub cards: Vec<Card>,
}

#[derive(Debug, Clone)]
pub struct BoardState {
    /// Visible columns only — configured columns not listed in the active
    /// board's `hidden_columns`, in declaration order (FR-002/FR-003). Hidden
    /// columns live in [`BoardState::hidden`].
    pub columns: Vec<BoardColumn>,
    /// Columns hidden from the active board configuration. Their cards stay
    /// in board state (keyed by column name) and remain reachable via
    /// filters/search (DM-01M2MHJB884WCTVCDHPD2T3GE7); they never render.
    pub hidden: Vec<BoardColumn>,
    pub mismatch: BoardColumn,
    /// Whether the computed "Mismatched" pseudo-column is part of the
    /// navigation/render surface (C-002 / FR-003). Cards in unknown statuses
    /// are always collected into [`BoardState::mismatch`]; the column is only
    /// shown when the effective configuration sets `show_mismatch`.
    pub show_mismatch: bool,
    pub active_col: usize,
    pub selected: usize,
    pub filter: Option<String>,
}

impl BoardState {
    pub fn build(store: &Store, board_config: &BoardConfiguration) -> Self {
        let issues = store.list().unwrap_or_default();
        let show_mismatch = board_config.show_mismatch;
        let hidden_names: Vec<&str> = board_config
            .hidden_columns
            .iter()
            .map(String::as_str)
            .collect();
        let mut column_map: Vec<Vec<Card>> =
            board_config.columns.iter().map(|_| Vec::new()).collect();
        let mut mismatch_cards = Vec::new();

        for issue in issues {
            let card = Card {
                number: issue.number,
                title: issue.title.clone(),
                priority: issue.priority.clone(),
                labels: issue.labels.clone(),
                assignee: issue.assignee.clone(),
                filename: issue.filename.clone(),
                commit: issue.commit.clone(),
                created: issue.created.clone(),
            };
            if let Some(idx) = board_config
                .columns
                .iter()
                .position(|c| c == issue.status.display())
            {
                column_map[idx].push(card);
            } else {
                mismatch_cards.push(card);
            }
        }

        for cards in column_map.iter_mut() {
            board_config.order_by.sort(cards);
        }
        board_config.order_by.sort(&mut mismatch_cards);

        let mut columns: Vec<BoardColumn> = Vec::new();
        let mut hidden: Vec<BoardColumn> = Vec::new();
        for (cards, name) in column_map.into_iter().zip(board_config.columns.iter()) {
            let col = BoardColumn {
                name: name.clone(),
                cards,
            };
            if hidden_names.contains(&name.as_str()) {
                hidden.push(col);
            } else {
                columns.push(col);
            }
        }

        let mismatch = BoardColumn {
            name: "Mismatched".to_string(),
            cards: mismatch_cards,
        };

        BoardState {
            columns,
            hidden,
            mismatch,
            show_mismatch,
            active_col: 0,
            selected: 0,
            filter: None,
        }
    }

    /// Build a board from the search corpus, keeping only cards whose full
    /// serialized text matches **both** the fuzzy `query` layer and the
    /// structured `filter` layer (FR-012/FR-013). Both predicates run in a
    /// single pass over the corpus via [`crate::search::matches`] (NFR-001).
    ///
    /// When a filter is active (non-empty query or structured criteria set),
    /// hidden columns' matching cards are **revealed** in the rendered surface
    /// (DM-01M2MHJB884WCTVCDHPD2T3GE7: hidden-column cards reachable via
    /// filters/search). When no filter is active, matching cards from hidden
    /// columns are stashed in [`BoardState::hidden`] (no visual presence).
    pub fn build_filtered(
        board_config: &BoardConfiguration,
        corpus: &Corpus,
        query: &str,
        filter: &StructuredFilter,
    ) -> Self {
        let show_mismatch = board_config.show_mismatch;
        let filtering = !query.is_empty() || filter.has_active_criteria();
        // A bare-number query (all-ASCII-digit after trim) is an exact issue
        // number match, not a fuzzy digit search: only the issue whose
        // `number` equals it survives, still ANDed with the structured
        // filter (board-filtering FR-02 / FR-03). Any other query keeps the
        // fuzzy-text path.
        let number = crate::search::number_query(query);
        let hidden_names: Vec<&str> = board_config
            .hidden_columns
            .iter()
            .map(String::as_str)
            .collect();
        let mut column_map: Vec<Vec<Card>> =
            board_config.columns.iter().map(|_| Vec::new()).collect();
        let mut mismatch_cards = Vec::new();

        for (issue, text) in corpus.issues.iter().zip(corpus.texts.iter()) {
            // Bare-number query: exact issue-number match replaces the fuzzy
            // text layer (board-filtering FR-02); the structured filter still
            // runs (FR-03). Otherwise the composite fuzzy+structured
            // predicate applies unchanged.
            let keep = if let Some(n) = number {
                issue.number == n && filter.evaluate(text)
            } else {
                crate::search::matches(query, filter, text)
            };
            if !keep {
                continue;
            }
            let card = Card {
                number: issue.number,
                title: issue.title.clone(),
                priority: issue.priority.clone(),
                labels: issue.labels.clone(),
                assignee: issue.assignee.clone(),
                filename: issue.filename.clone(),
                commit: issue.commit.clone(),
                created: issue.created.clone(),
            };
            if let Some(idx) = board_config
                .columns
                .iter()
                .position(|c| c == issue.status.display())
            {
                column_map[idx].push(card);
            } else {
                mismatch_cards.push(card);
            }
        }

        for cards in column_map.iter_mut() {
            board_config.order_by.sort(cards);
        }
        board_config.order_by.sort(&mut mismatch_cards);

        let mut columns: Vec<BoardColumn> = Vec::new();
        let mut hidden: Vec<BoardColumn> = Vec::new();
        for (cards, name) in column_map.into_iter().zip(board_config.columns.iter()) {
            let col = BoardColumn {
                name: name.clone(),
                cards,
            };
            if hidden_names.contains(&name.as_str()) {
                if filtering {
                    // Reveal hidden column when a filter is active so
                    // matching cards appear in the rendered surface
                    // (DM-01M2MHJB884WCTVCDHPD2T3GE7).
                    columns.push(col);
                } else {
                    hidden.push(col);
                }
            } else {
                columns.push(col);
            }
        }

        BoardState {
            columns,
            hidden,
            mismatch: BoardColumn {
                name: "Mismatched".to_string(),
                cards: mismatch_cards,
            },
            show_mismatch,
            active_col: 0,
            selected: 0,
            filter: Some(query.to_string()),
        }
    }

    /// True when no card anywhere is visible (used for zero-match feedback).
    pub fn is_empty(&self) -> bool {
        self.columns.iter().all(|c| c.cards.is_empty())
            && (!self.show_mismatch || self.mismatch.cards.is_empty())
    }

    pub fn total_cols(&self) -> usize {
        if self.show_mismatch {
            self.columns.len() + 1
        } else {
            self.columns.len()
        }
    }

    /// Columns a card can be moved into: the configured columns plus (when
    /// shown) the "Mismatched" sentinel, which is never a move target. The
    /// `</>` move keys navigate *among movable columns* only.
    pub fn real_cols(&self) -> usize {
        self.columns.len()
    }

    pub fn column_name(&self, idx: usize) -> &str {
        if idx < self.columns.len() {
            &self.columns[idx].name
        } else if idx == self.columns.len() && self.show_mismatch {
            &self.mismatch.name
        } else {
            "Unknown"
        }
    }

    /// The name under the active cursor, resolving **hidden** columns too
    /// (visible region first, then hidden, then Unknown). Lets `toggle` keep a
    /// logical cursor on a just-hidden column so a second press re-shows it
    /// (T017: "a second press on the same column re-shows it").
    pub fn active_column_name(&self) -> &str {
        let visible = self.columns.len();
        if self.active_col < visible {
            &self.columns[self.active_col].name
        } else {
            let hidden_idx = self.active_col - visible;
            if hidden_idx < self.hidden.len() {
                &self.hidden[hidden_idx].name
            } else {
                "Unknown"
            }
        }
    }

    pub fn column_cards(&self, idx: usize) -> &[Card] {
        if idx < self.columns.len() {
            &self.columns[idx].cards
        } else if idx == self.columns.len() && self.show_mismatch {
            &self.mismatch.cards
        } else {
            &[]
        }
    }

    pub fn get_selected_card(&self) -> Option<&Card> {
        self.column_cards(self.active_col).get(self.selected)
    }

    pub fn move_left(&mut self) {
        let total = self.real_cols();
        self.active_col = if total == 0 {
            0
        } else if self.active_col >= total {
            total - 1
        } else {
            (self.active_col + total - 1) % total
        };
        self.clamp_selection();
    }

    pub fn move_right(&mut self) {
        let total = self.real_cols();
        self.active_col = if total == 0 || self.active_col >= total {
            0
        } else {
            (self.active_col + 1) % total
        };
        self.clamp_selection();
    }

    pub fn move_up(&mut self) {
        if self.selected > 0 {
            self.selected -= 1;
        }
    }

    pub fn move_down(&mut self) {
        let cards = self.column_cards(self.active_col);
        if self.selected + 1 < cards.len() {
            self.selected += 1;
        }
    }

    pub fn clamp_selection(&mut self) {
        let cards = self.column_cards(self.active_col);
        if cards.is_empty() {
            self.selected = 0;
        } else if self.selected >= cards.len() {
            self.selected = cards.len() - 1;
        }
    }

    pub fn select_column(&mut self, col: usize) {
        let total = self.real_cols();
        if total > 0 {
            self.active_col = col % total;
        }
        self.clamp_selection();
    }
}

/// Render options carried from the active board configuration into the board
/// draw. Kept tiny and copyable so tests and call sites stay light.
#[derive(Debug, Clone, Copy)]
pub struct BoardDisplay {
    pub wrap_titles: bool,
    pub title_lines: usize,
}

impl Default for BoardDisplay {
    fn default() -> Self {
        BoardDisplay {
            wrap_titles: true,
            title_lines: 3,
        }
    }
}

impl From<&crate::config::BoardConfiguration> for BoardDisplay {
    fn from(config: &crate::config::BoardConfiguration) -> Self {
        BoardDisplay {
            wrap_titles: config.wrap_titles,
            title_lines: config.title_lines,
        }
    }
}

pub fn render(
    board: &BoardState,
    f: &mut Frame,
    area: Rect,
    status_msg: &Option<String>,
    display: BoardDisplay,
) {
    if area.height < 2 || area.width < 4 {
        return;
    }

    let status_height: u16 = if status_msg.is_some() { 1 } else { 0 };
    let board_height = area.height.saturating_sub(status_height);
    let board_area = Rect {
        height: board_height,
        ..area
    };
    let status_area = Rect {
        y: area.y + board_height,
        height: status_height,
        ..area
    };

    let total = board.total_cols();
    if total == 0 {
        return;
    }

    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints(vec![Constraint::Ratio(1, total as u32); total])
        .split(board_area);

    for i in 0..total {
        let col = if i < board.columns.len() {
            &board.columns[i]
        } else {
            &board.mismatch
        };

        let is_active = i == board.active_col;
        let is_mismatch_col = i == board.columns.len();
        let is_mismatch_highlight = is_mismatch_col && !col.cards.is_empty();

        let items: Vec<ListItem> = col
            .cards
            .iter()
            .enumerate()
            .map(|(j, card)| {
                let lines = widgets::card_lines(
                    card,
                    chunks[i].width as usize,
                    display.wrap_titles,
                    display.title_lines,
                );
                let style = if is_active && j == board.selected {
                    Style::default()
                        .bg(Color::DarkGray)
                        .add_modifier(Modifier::BOLD)
                } else if is_mismatch_highlight {
                    Style::default().fg(Color::Red)
                } else {
                    Style::default()
                };
                ListItem::new(lines).style(style)
            })
            .collect();

        let title = format!("{} ({})", col.name, col.cards.len());
        let border_style = if is_active {
            Style::default().fg(Color::Cyan)
        } else if is_mismatch_highlight {
            Style::default().fg(Color::Red)
        } else {
            Style::default()
        };

        let block = Block::default()
            .borders(Borders::ALL)
            .title(title)
            .border_style(border_style);

        let list = List::new(items).block(block);

        if is_active {
            let mut state = ListState::default();
            if !col.cards.is_empty() {
                state.select(Some(board.selected));
            }
            f.render_stateful_widget(list, chunks[i], &mut state);
        } else {
            f.render_widget(list, chunks[i]);
        }
    }

    if let Some(msg) = status_msg {
        let para = Paragraph::new(Line::from(Span::raw(msg.clone())))
            .style(Style::default().fg(Color::Yellow));
        f.render_widget(para, status_area);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;

    #[test]
    fn total_cols_includes_mismatch() {
        let board = BoardState {
            columns: vec![
                BoardColumn {
                    name: "a".into(),
                    cards: vec![],
                },
                BoardColumn {
                    name: "b".into(),
                    cards: vec![],
                },
            ],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hidden: vec![],
            show_mismatch: true,
        };
        assert_eq!(board.total_cols(), 3);
    }

    #[test]
    fn column_name_mismatch_index() {
        let board = BoardState {
            columns: vec![BoardColumn {
                name: "todo".into(),
                cards: vec![],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hidden: vec![],
            show_mismatch: true,
        };
        assert_eq!(board.column_name(0), "todo");
        assert_eq!(board.column_name(1), "Mismatched");
    }

    #[test]
    fn move_left_wraps_around() {
        let mut board = BoardState {
            columns: vec![
                BoardColumn {
                    name: "a".into(),
                    cards: vec![],
                },
                BoardColumn {
                    name: "b".into(),
                    cards: vec![],
                },
            ],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            show_mismatch: true,
        };
        board.move_left();
        assert_eq!(board.active_col, 1);
    }

    #[test]
    fn move_right_wraps_around() {
        let mut board = BoardState {
            columns: vec![
                BoardColumn {
                    name: "a".into(),
                    cards: vec![],
                },
                BoardColumn {
                    name: "b".into(),
                    cards: vec![],
                },
            ],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 2,
            selected: 0,
            filter: None,
            hidden: vec![],
            show_mismatch: true,
        };
        board.move_right();
        assert_eq!(board.active_col, 0);
    }

    #[test]
    fn clamp_selection_empty_column() {
        let mut board = BoardState {
            columns: vec![BoardColumn {
                name: "a".into(),
                cards: vec![],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 5,
            filter: None,
            hidden: vec![],
            show_mismatch: true,
        };
        board.clamp_selection();
        assert_eq!(board.selected, 0);
    }

    #[test]
    fn clamp_selection_single_card() {
        let mut board = BoardState {
            columns: vec![BoardColumn {
                name: "a".into(),
                cards: vec![Card {
                    number: 1,
                    title: "X".into(),
                    priority: crate::model::Priority::Medium,
                    labels: vec![],
                    assignee: None,
                    filename: "x.md".into(),
                    commit: None,
                    created: "2026-01-01".into(),
                }],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 5,
            filter: None,
            hidden: vec![],
            show_mismatch: true,
        };
        board.clamp_selection();
        assert_eq!(board.selected, 0);
    }

    #[test]
    fn move_up_clamps_at_top() {
        let mut board = BoardState {
            columns: vec![BoardColumn {
                name: "a".into(),
                cards: vec![Card {
                    number: 1,
                    title: "X".into(),
                    priority: crate::model::Priority::Medium,
                    labels: vec![],
                    assignee: None,
                    filename: "x.md".into(),
                    commit: None,
                    created: "2026-01-01".into(),
                }],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hidden: vec![],
            show_mismatch: true,
        };
        board.move_up();
        assert_eq!(board.selected, 0);
    }

    #[test]
    fn move_down_clamps_at_bottom() {
        let mut board = BoardState {
            columns: vec![BoardColumn {
                name: "a".into(),
                cards: vec![Card {
                    number: 1,
                    title: "X".into(),
                    priority: crate::model::Priority::Medium,
                    labels: vec![],
                    assignee: None,
                    filename: "x.md".into(),
                    commit: None,
                    created: "2026-01-01".into(),
                }],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hidden: vec![],
            show_mismatch: true,
        };
        board.move_down();
        assert_eq!(board.selected, 0);
    }

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

        let backend = TestBackend::new(5, 3);
        let mut terminal = Terminal::new(backend).unwrap();
        let board = BoardState {
            columns: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hidden: vec![],
            show_mismatch: true,
        };
        terminal
            .draw(|f| render(&board, f, f.area(), &None, BoardDisplay::default()))
            .unwrap();
    }

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

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let board = BoardState {
            columns: vec![
                BoardColumn {
                    name: "todo".into(),
                    cards: vec![],
                },
                BoardColumn {
                    name: "done".into(),
                    cards: vec![],
                },
            ],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hidden: vec![],
            show_mismatch: true,
        };
        terminal
            .draw(|f| {
                render(
                    &board,
                    f,
                    f.area(),
                    &Some("test msg".into()),
                    BoardDisplay::default(),
                )
            })
            .unwrap();
    }

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

        let title = "This is a deliberately long card title that will not fit on a single line inside the column and must wrap more than once";
        let card = crate::ui::board::Card {
            number: 7,
            title: title.into(),
            priority: crate::model::Priority::Medium,
            labels: vec![],
            assignee: None,
            filename: "x.md".into(),
            commit: None,
            created: "2026-01-01".into(),
        };
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let board = BoardState {
            columns: vec![BoardColumn {
                name: "todo".into(),
                cards: vec![card],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hidden: vec![],
            show_mismatch: false,
        };
        let display = BoardDisplay {
            wrap_titles: true,
            title_lines: 3,
        };
        terminal
            .draw(|f| render(&board, f, f.area(), &None, display))
            .unwrap();
        let buffer = terminal.backend().buffer();

        // The card is the only item in the only column; its block top border
        // sits on y=0, so the ListItem starts at y=1 and each wrapped line
        // must carry the selected-card highlight (DarkGray bg + BOLD).
        let mut highlighted = 0;
        for y in 1..buffer.area().height - 1 {
            let cell = &buffer[(2, y)];
            if cell.bg != Color::DarkGray {
                break;
            }
            assert!(
                cell.modifier.contains(Modifier::BOLD),
                "highlighted continuation line must stay bold: {cell:?}"
            );
            highlighted += 1;
        }
        assert!(
            highlighted >= 2,
            "wrapped card highlights every line, got {highlighted}"
        );
        assert!(
            highlighted <= display.title_lines,
            "highlight never exceeds the line limit: {highlighted}"
        );
    }

    #[test]
    fn build_filtered_keeps_only_fuzzy_matches() {
        use crate::model::Issue;
        use crate::search::Corpus;

        let to_issue = |number: u32, title: &str| Issue {
            number,
            title: title.to_string(),
            status: crate::model::Status::new("todo"),
            labels: vec![],
            priority: crate::model::Priority::Medium,
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            links: vec![],
            files: vec![],
            created: "2026-01-01".into(),
            updated: "2026-01-01".into(),
            filename: format!("2026-01-01-{number}.md"),
            body: String::new(),
        };
        let corpus = Corpus {
            issues: vec![to_issue(1, "Fix login bug"), to_issue(2, "Polish exports")],
            texts: vec!["Fix login bug".to_string(), "Polish exports".to_string()],
        };
        let config = Config::default();
        let board_config = config.default_config();

        let board =
            BoardState::build_filtered(board_config, &corpus, "log", &StructuredFilter::default());
        assert_eq!(board.columns.len(), board_config.columns.len());
        assert_eq!(board.column_cards(0).len(), 1);
        assert_eq!(board.column_cards(0)[0].title, "Fix login bug");
        assert_eq!(board.filter.as_deref(), Some("log"));

        let none =
            BoardState::build_filtered(board_config, &corpus, "zzw", &StructuredFilter::default());
        assert!(none.is_empty());

        let empty =
            BoardState::build_filtered(board_config, &corpus, "", &StructuredFilter::default());
        assert_eq!(empty.column_cards(0).len(), 2, "empty query keeps all");
        assert!(empty.filter.is_some());
    }

    #[test]
    fn build_filtered_bare_number_matches_exact_issue_only() {
        use crate::model::Issue;
        use crate::search::Corpus;

        let to_issue = |number: u32, title: &str, status: &str| Issue {
            number,
            title: title.to_string(),
            status: crate::model::Status::new(status),
            labels: vec![],
            priority: crate::model::Priority::Medium,
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            links: vec![],
            files: vec![],
            created: "2026-01-01".into(),
            updated: "2026-01-01".into(),
            filename: format!("2026-01-01-{number}.md"),
            body: String::new(),
        };
        let corpus = Corpus {
            issues: vec![
                to_issue(55, "Concrete target", "todo"),
                to_issue(155, "Digit-rich title", "todo"),
                to_issue(3, "Login bug", "todo"),
            ],
            texts: vec![
                "Concrete target".to_string(),
                "Digit-rich title".to_string(),
                "Login bug".to_string(),
            ],
        };
        let config = Config::default();
        let board_config = config.default_config();

        let exact =
            BoardState::build_filtered(board_config, &corpus, "55", &StructuredFilter::default());
        assert_eq!(exact.column_cards(0).len(), 1, "only issue 55 matches");
        assert_eq!(exact.column_cards(0)[0].title, "Concrete target");
        assert_eq!(
            exact.column_cards(0)[0].number,
            55,
            "issue 155's digit sequence must not qualify"
        );
        assert_eq!(exact.filter.as_deref(), Some("55"));

        // Number miss -> empty board.
        let miss =
            BoardState::build_filtered(board_config, &corpus, "999", &StructuredFilter::default());
        assert!(miss.is_empty(), "no issue 999 => zero matches");

        // Non-numeric query keeps fuzzy behavior (login finds issue 3 only).
        let fuzzy = BoardState::build_filtered(
            board_config,
            &corpus,
            "login",
            &StructuredFilter::default(),
        );
        assert_eq!(fuzzy.column_cards(0).len(), 1);
        assert_eq!(fuzzy.column_cards(0)[0].title, "Login bug");
    }

    #[test]
    fn build_filtered_mixed_query_keeps_fuzzy_not_number() {
        use crate::model::Issue;
        use crate::search::Corpus;

        let to_issue = |number: u32, title: &str| Issue {
            number,
            title: title.to_string(),
            status: crate::model::Status::new("todo"),
            labels: vec![],
            priority: crate::model::Priority::Medium,
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            links: vec![],
            files: vec![],
            created: "2026-01-01".into(),
            updated: "2026-01-01".into(),
            filename: format!("2026-01-01-{number}.md"),
            body: String::new(),
        };
        let corpus = Corpus {
            issues: vec![
                to_issue(55, "Concrete target"),
                to_issue(155, "Digit-rich title"),
            ],
            texts: vec![
                "Concrete target".to_string(),
                "Digit-rich title".to_string(),
            ],
        };
        let config = Config::default();
        let board_config = config.default_config();

        // "55bug" is not a bare number: fuzzy path applies (no such text, so
        // zero matches rather than exact issue 55).
        let mixed = BoardState::build_filtered(
            board_config,
            &corpus,
            "55bug",
            &StructuredFilter::default(),
        );
        assert!(mixed.is_empty(), "mixed query is not an exact-number query");
    }

    #[test]
    fn build_filtered_number_composes_with_structured_filter_and() {
        use crate::model::Issue;
        use crate::search::Corpus;

        let cases = [
            (55u32, "Issue 55 todo", "todo"),
            (156u32, "Issue 156 todo", "todo"),
            (57u32, "Issue 57 done", "done"),
        ];
        let corpus = Corpus {
            issues: cases
                .iter()
                .map(|&(number, title, status)| Issue {
                    number,
                    title: title.to_string(),
                    status: crate::model::Status::new(status),
                    labels: vec![],
                    priority: crate::model::Priority::Medium,
                    assignee: None,
                    estimate: None,
                    commit: None,
                    gitlab_id: None,
                    linear_id: None,
                    mission: None,
                    task: None,
                    links: vec![],
                    files: vec![],
                    created: "2026-01-01".into(),
                    updated: "2026-01-01".into(),
                    filename: format!("2026-01-01-{}.md", number),
                    body: String::new(),
                })
                .collect(),
            texts: cases
                .iter()
                .map(|(_, title, _)| title.to_string())
                .collect(),
        };
        let config = Config::default();
        let board_config = config.default_config();
        let status_todo = StructuredFilter {
            status: Some("todo".to_string()),
            ..Default::default()
        };
        let status_done = StructuredFilter {
            status: Some("done".to_string()),
            ..Default::default()
        };

        // AND holds on the positive side: 55 must match number AND todo;
        // 156 matches the criteria but is dropped by the number gate.
        let matches = BoardState::build_filtered(board_config, &corpus, "55", &status_todo);
        assert_eq!(matches.column_cards(0).len(), 1);
        assert_eq!(matches.column_cards(0)[0].title, "Issue 55 todo");

        // Requirement scenario: number matches but the criterion fails
        // (issue 55 is "todo" here) => board shows nothing.
        let done_criteria = BoardState::build_filtered(board_config, &corpus, "55", &status_done);
        assert!(done_criteria.is_empty(), "criteria failure hides issue 55");
    }

    #[test]
    fn is_empty_true_only_with_no_cards_anywhere() {
        let board = BoardState {
            columns: vec![BoardColumn {
                name: "a".into(),
                cards: vec![],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hidden: vec![],
            show_mismatch: true,
        };
        assert!(board.is_empty());

        let populated = BoardState {
            columns: vec![BoardColumn {
                name: "a".into(),
                cards: vec![Card {
                    number: 1,
                    title: "X".into(),
                    priority: crate::model::Priority::Medium,
                    labels: vec![],
                    assignee: None,
                    filename: "x.md".into(),
                    commit: None,
                    created: "2026-01-01".into(),
                }],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hidden: vec![],
            show_mismatch: true,
        };
        assert!(!populated.is_empty());
    }

    #[test]
    fn build_splits_hidden_columns_out_of_visible_surface() {
        use crate::config::{BoardConfiguration, Config};

        let mut config = Config::default();
        config.kanban.configurations.insert(
            "default".to_string(),
            BoardConfiguration {
                columns: vec!["todo".into(), "done".into()],
                hidden_columns: vec!["done".into()],
                ..BoardConfiguration::default()
            },
        );
        let store = crate::storage::Store::open(&config).unwrap();
        let board = BoardState::build(&store, config.default_config());
        assert_eq!(board.columns.len(), 1);
        assert_eq!(board.columns[0].name, "todo");
        assert_eq!(board.hidden.len(), 1);
        assert_eq!(board.hidden[0].name, "done");
        assert_eq!(board.total_cols(), 1);
    }

    #[test]
    fn move_left_skips_hidden_column() {
        let mut board = BoardState {
            columns: vec![BoardColumn {
                name: "visible-a".into(),
                cards: vec![],
            }],
            hidden: vec![BoardColumn {
                name: "hidden-b".into(),
                cards: vec![],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            show_mismatch: true,
        };
        board.move_left();
        assert_eq!(board.active_col, 0, "single visible column wraps to itself");
    }

    #[test]
    fn move_right_skips_hidden_column() {
        let mut board = BoardState {
            columns: vec![BoardColumn {
                name: "visible-a".into(),
                cards: vec![],
            }],
            hidden: vec![BoardColumn {
                name: "hidden-b".into(),
                cards: vec![],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            show_mismatch: true,
        };
        board.move_right();
        assert_eq!(board.active_col, 0, "single visible column wraps to itself");
    }

    #[test]
    fn all_columns_hidden_board_is_displayable_and_navigation_safe() {
        let mut board = BoardState {
            columns: vec![],
            hidden: vec![BoardColumn {
                name: "only-hidden".into(),
                cards: vec![],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            show_mismatch: false,
        };
        assert_eq!(board.total_cols(), 0);
        board.move_left();
        board.move_right();
        assert_eq!(board.active_col, 0, "zero-column board must not panic");
        let board2 = BoardState {
            columns: vec![],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            show_mismatch: false,
        };
        assert_eq!(board2.total_cols(), 0);
    }

    fn write_issue_md(
        dir: &std::path::Path,
        name: &str,
        number: u32,
        title: &str,
        status: &str,
        created: &str,
    ) {
        let contents = format!(
            "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"{status}\"\nlabels: []\npriority: \"medium\"\ncreated: \"{created}\"\nupdated: \"{created}\"\n---\n\nBody text."
        );
        std::fs::write(dir.join(name), contents).unwrap();
    }

    #[test]
    fn order_by_sort_desc_asc_none() {
        let mk = |created: &str| Card {
            number: 1,
            title: created.to_string(),
            priority: crate::model::Priority::Medium,
            labels: vec![],
            assignee: None,
            filename: "x.md".into(),
            commit: None,
            created: created.to_string(),
        };
        let dates =
            |cards: &[Card]| -> Vec<String> { cards.iter().map(|c| c.created.clone()).collect() };

        let mut cards = vec![mk("2026-01-01"), mk("2026-03-01"), mk("2026-02-01")];
        crate::config::OrderBy::CreatedAtDesc.sort(&mut cards);
        assert_eq!(dates(&cards), ["2026-03-01", "2026-02-01", "2026-01-01"]);

        let mut cards = vec![mk("2026-01-01"), mk("2026-03-01"), mk("2026-02-01")];
        crate::config::OrderBy::CreatedAtAsc.sort(&mut cards);
        assert_eq!(dates(&cards), ["2026-01-01", "2026-02-01", "2026-03-01"]);

        let mut cards = vec![mk("2026-03-01"), mk("2026-01-01")];
        crate::config::OrderBy::None.sort(&mut cards);
        assert_eq!(
            dates(&cards),
            ["2026-03-01", "2026-01-01"],
            "none is a no-op"
        );
    }

    #[test]
    fn build_orders_most_recent_first_by_default() {
        use crate::config::Config;
        use std::path::PathBuf;
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        std::fs::create_dir_all(&dir).unwrap();
        write_issue_md(&dir, "2026-01-01-old.md", 1, "old", "todo", "2026-01-01");
        write_issue_md(&dir, "2026-02-01-mid.md", 2, "mid", "todo", "2026-02-01");
        write_issue_md(&dir, "2026-03-01-new.md", 3, "new", "todo", "2026-03-01");
        let config = Config {
            issues_dir: PathBuf::from(&dir),
            ..Config::default()
        };
        let store = crate::storage::Store::open(&config).unwrap();
        let board = BoardState::build(&store, config.default_config());
        let titles: Vec<&str> = board
            .column_cards(0)
            .iter()
            .map(|c| c.title.as_str())
            .collect();
        assert_eq!(titles, ["new", "mid", "old"], "default desc: newest first");
    }

    #[test]
    fn build_applies_created_at_asc_and_none() {
        use crate::config::OrderBy;
        use std::path::PathBuf;
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        std::fs::create_dir_all(&dir).unwrap();
        write_issue_md(&dir, "2026-01-01-old.md", 1, "old", "todo", "2026-01-01");
        write_issue_md(&dir, "2026-02-01-mid.md", 2, "mid", "todo", "2026-02-01");
        write_issue_md(&dir, "2026-03-01-new.md", 3, "new", "todo", "2026-03-01");
        let config = crate::config::Config {
            issues_dir: PathBuf::from(&dir),
            ..crate::config::Config::default()
        };
        let store = crate::storage::Store::open(&config).unwrap();

        let mut cfg_asc = config.clone();
        cfg_asc
            .kanban
            .configurations
            .get_mut("default")
            .unwrap()
            .order_by = OrderBy::CreatedAtAsc;
        let board_asc = BoardState::build(&store, cfg_asc.default_config());
        let titles: Vec<&str> = board_asc
            .column_cards(0)
            .iter()
            .map(|c| c.title.as_str())
            .collect();
        assert_eq!(titles, ["old", "mid", "new"]);

        let mut cfg_none = config;
        cfg_none
            .kanban
            .configurations
            .get_mut("default")
            .unwrap()
            .order_by = OrderBy::None;
        let board_none = BoardState::build(&store, cfg_none.default_config());
        let titles: Vec<&str> = board_none
            .column_cards(0)
            .iter()
            .map(|c| c.title.as_str())
            .collect();
        assert_eq!(
            titles,
            ["old", "mid", "new"],
            "none keeps the store's filename-ascending order"
        );
    }

    #[test]
    fn build_filtered_applies_order_by() {
        use crate::model::Issue;
        use crate::search::{Corpus, StructuredFilter};

        let to_issue = |number: u32, title: &str, created: &str| Issue {
            number,
            title: title.to_string(),
            status: crate::model::Status::new("todo"),
            labels: vec![],
            priority: crate::model::Priority::Medium,
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            links: vec![],
            files: vec![],
            created: created.into(),
            updated: "2026-01-01".into(),
            filename: format!("2026-01-01-{number}.md"),
            body: String::new(),
        };
        let corpus = Corpus {
            issues: vec![
                to_issue(1, "old", "2026-01-01"),
                to_issue(2, "new", "2026-03-01"),
                to_issue(3, "mid", "2026-02-01"),
            ],
            texts: vec!["old".into(), "new".into(), "mid".into()],
        };
        let config = crate::config::Config::default();
        let board = BoardState::build_filtered(
            config.default_config(),
            &corpus,
            "",
            &StructuredFilter::default(),
        );
        let titles: Vec<&str> = board
            .column_cards(0)
            .iter()
            .map(|c| c.title.as_str())
            .collect();
        assert_eq!(
            titles,
            ["new", "mid", "old"],
            "default desc applies to filtered results too"
        );
    }
}