logana 0.5.1

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

#[derive(Debug, Default)]
pub struct NormalMode {
    pub count: Option<usize>,
}

#[async_trait]
impl Mode for NormalMode {
    async fn handle_key(
        mut self: Box<Self>,
        tab: &mut TabState,
        key: KeyCode,
        modifiers: KeyModifiers,
    ) -> (Box<dyn Mode>, KeyResult) {
        // Clone the Arc so we can mutate `tab` freely in each branch.
        let kb = tab.interaction.keybindings.clone();

        // ── Digit accumulation for count prefix ─────────────────────────────
        // Digits 1-9 start a count; 0 appends when count is already active.
        if let KeyCode::Char(c @ '1'..='9') = key
            && (modifiers.is_empty() || modifiers == KeyModifiers::SHIFT)
        {
            let digit = (c as u32 - '0' as u32) as usize;
            let n = self
                .count
                .unwrap_or(0)
                .saturating_mul(10)
                .saturating_add(digit);
            self.count = Some(n.min(999_999));
            return (self, KeyResult::Handled);
        }
        if let KeyCode::Char('0') = key
            && self.count.is_some()
            && (modifiers.is_empty() || modifiers == KeyModifiers::SHIFT)
        {
            self.count = Some(self.count.unwrap().saturating_mul(10).min(999_999));
            return (self, KeyResult::Handled);
        }

        if kb.global.quit.matches(key, modifiers) {
            self.count = None;
            return (self, KeyResult::Ignored);
        }
        if kb.global.next_tab.matches(key, modifiers) || kb.global.prev_tab.matches(key, modifiers)
        {
            self.count = None;
            return (self, KeyResult::Ignored);
        }
        if kb.global.close_tab.matches(key, modifiers) {
            self.count = None;
            return (self, KeyResult::Ignored);
        }
        if kb.global.new_tab.matches(key, modifiers) {
            self.count = None;
            return (self, KeyResult::Ignored);
        }

        if kb.navigation.half_page_down.matches(key, modifiers) {
            let half = (tab.scroll.visible_height / 2).max(1);
            let count = self.count.take().unwrap_or(1);
            tab.scroll.scroll_offset = tab
                .scroll
                .scroll_offset
                .saturating_add(half.saturating_mul(count));
            tab.interaction.g_key_pressed = false;
            return (self, KeyResult::Handled);
        }

        if kb.navigation.half_page_up.matches(key, modifiers) {
            let half = (tab.scroll.visible_height / 2).max(1);
            let count = self.count.take().unwrap_or(1);
            tab.scroll.scroll_offset = tab
                .scroll
                .scroll_offset
                .saturating_sub(half.saturating_mul(count));
            tab.interaction.g_key_pressed = false;
            return (self, KeyResult::Handled);
        }

        if kb.navigation.page_down.matches(key, modifiers) {
            let page = tab.scroll.visible_height.max(1);
            let count = self.count.take().unwrap_or(1);
            tab.scroll.scroll_offset = tab
                .scroll
                .scroll_offset
                .saturating_add(page.saturating_mul(count));
            tab.interaction.g_key_pressed = false;
            return (self, KeyResult::Handled);
        }

        if kb.navigation.page_up.matches(key, modifiers) {
            let page = tab.scroll.visible_height.max(1);
            let count = self.count.take().unwrap_or(1);
            tab.scroll.scroll_offset = tab
                .scroll
                .scroll_offset
                .saturating_sub(page.saturating_mul(count));
            tab.interaction.g_key_pressed = false;
            return (self, KeyResult::Handled);
        }

        if kb.normal.command_mode.matches(key, modifiers) {
            let history = tab.interaction.command_history.clone();
            tab.interaction.g_key_pressed = false;
            tab.interaction.command_error = None;
            self.count = None;
            return (
                Box::new(CommandMode::with_history(String::new(), 0, history)),
                KeyResult::Handled,
            );
        }

        if kb.normal.filter_mode.matches(key, modifiers) {
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (
                Box::new(FilterManagementMode {
                    selected_filter_index: 0,
                }),
                KeyResult::Handled,
            );
        }

        if kb.normal.toggle_filtering.matches(key, modifiers) {
            tab.filter.enabled = !tab.filter.enabled;
            tab.begin_filter_refresh();
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.filter_include.matches(key, modifiers) {
            let history = tab.interaction.command_history.clone();
            tab.interaction.g_key_pressed = false;
            tab.interaction.command_error = None;
            self.count = None;
            return (
                Box::new(CommandMode::with_history("filter ".to_string(), 7, history)),
                KeyResult::Handled,
            );
        }

        if kb.normal.filter_exclude.matches(key, modifiers) {
            let history = tab.interaction.command_history.clone();
            tab.interaction.g_key_pressed = false;
            tab.interaction.command_error = None;
            self.count = None;
            return (
                Box::new(CommandMode::with_history(
                    "exclude ".to_string(),
                    8,
                    history,
                )),
                KeyResult::Handled,
            );
        }

        if kb.normal.enter_ui_mode.matches(key, modifiers) {
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (Box::new(UiMode::from_tab(tab)), KeyResult::Handled);
        }

        if kb.navigation.scroll_down.matches(key, modifiers) {
            let count = self.count.take().unwrap_or(1);
            tab.scroll.scroll_offset = tab.scroll.scroll_offset.saturating_add(count);
            tab.interaction.g_key_pressed = false;
            return (self, KeyResult::Handled);
        }

        if kb.navigation.scroll_up.matches(key, modifiers) {
            let count = self.count.take().unwrap_or(1);
            tab.scroll.scroll_offset = tab.scroll.scroll_offset.saturating_sub(count);
            tab.interaction.g_key_pressed = false;
            return (self, KeyResult::Handled);
        }

        if kb.normal.scroll_left.matches(key, modifiers) {
            if !tab.display.wrap {
                tab.scroll.horizontal_scroll = tab.scroll.horizontal_scroll.saturating_sub(1);
            }
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.scroll_right.matches(key, modifiers) {
            if !tab.display.wrap {
                tab.scroll.horizontal_scroll = tab.scroll.horizontal_scroll.saturating_add(1);
            }
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.start_of_line.matches(key, modifiers) {
            tab.scroll.horizontal_scroll = 0;
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.end_of_line.matches(key, modifiers) {
            if let Some(line_idx) = tab.filter.visible_indices.get_opt(tab.scroll.scroll_offset) {
                let text = tab.get_display_text(line_idx);
                let char_count = text.chars().count();
                tab.scroll_char_cursor_into_view(char_count.saturating_sub(1), &text);
            }
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.go_to_bottom.matches(key, modifiers) {
            // With a count, `{count}G` jumps to that line number.
            if let Some(count) = self.count.take() {
                let _ = tab.goto_line(count);
            } else {
                let n = tab.filter.visible_indices.len();
                if n > 0 {
                    tab.scroll.scroll_offset = n - 1;
                }
            }
            tab.interaction.g_key_pressed = false;
            return (self, KeyResult::Handled);
        }

        // gg chord: first press sets the flag; second press jumps to top.
        if kb.normal.go_to_top_chord.matches(key, modifiers) {
            if tab.interaction.g_key_pressed {
                // With a count, `{count}gg` jumps to that line number.
                if let Some(count) = self.count.take() {
                    let _ = tab.goto_line(count);
                } else {
                    tab.scroll.scroll_offset = 0;
                }
                tab.interaction.g_key_pressed = false;
            } else {
                tab.interaction.g_key_pressed = true;
            }
            return (self, KeyResult::Handled);
        }

        if kb.normal.mark_line.matches(key, modifiers) {
            if let Some(line_idx) = tab.filter.visible_indices.get_opt(tab.scroll.scroll_offset) {
                tab.log_manager.toggle_mark(line_idx);
            }
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.toggle_marks_only.matches(key, modifiers) {
            tab.filter.show_marks_only = !tab.filter.show_marks_only;
            tab.begin_filter_refresh();
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.yank_line.matches(key, modifiers) {
            tab.interaction.g_key_pressed = false;
            self.count = None;
            if tab.filter.visible_indices.is_empty() {
                tab.interaction.command_error = Some("No visible lines".to_string());
                return (self, KeyResult::Handled);
            }
            let idx = tab.filter.visible_indices.get(
                tab.scroll
                    .scroll_offset
                    .min(tab.filter.visible_indices.len() - 1),
            );
            let bytes = tab.file_reader.get_line(idx);
            let text = tab
                .display
                .format
                .as_ref()
                .and_then(|parser| parser.parse_line(bytes))
                .map(|parts| {
                    apply_field_layout(
                        &parts,
                        &tab.display.field_layout,
                        &tab.display.hidden_fields,
                        tab.display.show_keys,
                        None,
                    )
                    .join(" ")
                })
                .unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned());
            return (self, KeyResult::CopyToClipboard(text));
        }

        if kb.normal.yank_marked.matches(key, modifiers) {
            let marked = tab.log_manager.get_marked_indices();
            tab.interaction.g_key_pressed = false;
            self.count = None;
            if marked.is_empty() {
                tab.interaction.command_error = Some("No marked lines".to_string());
                return (self, KeyResult::Handled);
            }
            let text: String = marked
                .iter()
                .map(|&idx| {
                    let bytes = tab.file_reader.get_line(idx);
                    tab.display
                        .format
                        .as_ref()
                        .and_then(|parser| parser.parse_line(bytes))
                        .map(|parts| {
                            apply_field_layout(
                                &parts,
                                &tab.display.field_layout,
                                &tab.display.hidden_fields,
                                tab.display.show_keys,
                                None,
                            )
                            .join(" ")
                        })
                        .unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned())
                })
                .collect::<Vec<_>>()
                .join("\n");
            return (self, KeyResult::CopyToClipboard(text));
        }

        if kb.normal.visual_mode.matches(key, modifiers) {
            let anchor = tab.scroll.scroll_offset;
            tab.interaction.g_key_pressed = false;
            return (
                Box::new(VisualLineMode {
                    anchor,
                    count: None,
                }),
                KeyResult::Handled,
            );
        }

        if kb.normal.visual_char.matches(key, modifiers) {
            let line_text = display_line_text(tab);
            let cursor_col = search_match_char_offset(tab, &line_text);
            tab.interaction.g_key_pressed = false;
            self.count = None;
            tab.cancel_search();
            let mut mode = VisualMode::new(line_text);
            mode.cursor_col = cursor_col;
            return (Box::new(mode), KeyResult::Handled);
        }

        if kb.normal.search_forward.matches(key, modifiers) {
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (
                Box::new(SearchMode {
                    input: String::new(),
                    forward: true,
                }),
                KeyResult::Handled,
            );
        }

        if kb.normal.search_backward.matches(key, modifiers) {
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (
                Box::new(SearchMode {
                    input: String::new(),
                    forward: false,
                }),
                KeyResult::Handled,
            );
        }

        if kb.normal.next_match.matches(key, modifiers) {
            // `n` continues in the original search direction (vim semantics).
            if tab.search.query.go_next().is_some() {
                tab.scroll_to_current_search_match();
            }
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.prev_match.matches(key, modifiers) {
            // `N` reverses the original search direction (vim semantics).
            if tab.search.query.go_prev().is_some() {
                tab.scroll_to_current_search_match();
            }
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.clear_search.matches(key, modifiers)
            && (tab.search.query.get_pattern().is_some() || tab.interaction.notification.is_some())
        {
            tab.cancel_search();
            tab.clear_notification();
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.clear_all.matches(key, modifiers) {
            tab.log_manager.clear_all_marks_and_comments();
            tab.interaction.command_error = Some("Cleared all marks and comments".to_string());
            tab.begin_filter_refresh();
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.edit_comment.matches(key, modifiers) {
            if let Some(line_idx) = tab.filter.visible_indices.get_opt(tab.scroll.scroll_offset) {
                let comments = tab.log_manager.get_comments();
                if let Some(idx) = comments
                    .iter()
                    .position(|c| c.line_indices.contains(&line_idx))
                {
                    let c = &comments[idx];
                    tab.interaction.g_key_pressed = false;
                    self.count = None;
                    return (
                        Box::new(CommentMode::edit(
                            idx,
                            c.text.clone(),
                            c.line_indices.clone(),
                        )),
                        KeyResult::Handled,
                    );
                }
                tab.interaction.command_error = Some("No comment on this line".to_string());
            }
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.delete_comment.matches(key, modifiers) {
            if let Some(line_idx) = tab.filter.visible_indices.get_opt(tab.scroll.scroll_offset) {
                let comments = tab.log_manager.get_comments();
                if let Some(idx) = comments
                    .iter()
                    .position(|c| c.line_indices.contains(&line_idx))
                {
                    tab.log_manager.remove_comment(idx);
                    tab.begin_filter_refresh();
                    tab.interaction.g_key_pressed = false;
                    self.count = None;
                    return (self, KeyResult::Handled);
                }
                tab.interaction.command_error = Some("No comment on this line".to_string());
            }
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.comment_line.matches(key, modifiers) {
            tab.interaction.g_key_pressed = false;
            self.count = None;
            if let Some(line_idx) = tab.filter.visible_indices.get_opt(tab.scroll.scroll_offset) {
                return (
                    Box::new(CommentMode::new(vec![line_idx])),
                    KeyResult::Handled,
                );
            }
            return (self, KeyResult::Handled);
        }

        if kb.normal.next_error.matches(key, modifiers) {
            if let Some(pos) = tab.next_error_position(tab.scroll.scroll_offset) {
                tab.scroll.scroll_offset = pos;
            } else {
                tab.interaction.command_error = Some("No more errors".to_string());
            }
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.prev_error.matches(key, modifiers) {
            if let Some(pos) = tab.prev_error_position(tab.scroll.scroll_offset) {
                tab.scroll.scroll_offset = pos;
            } else {
                tab.interaction.command_error = Some("No previous error".to_string());
            }
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.next_warning.matches(key, modifiers) {
            if let Some(pos) = tab.next_warning_position(tab.scroll.scroll_offset) {
                tab.scroll.scroll_offset = pos;
            } else {
                tab.interaction.command_error = Some("No more warnings".to_string());
            }
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.prev_warning.matches(key, modifiers) {
            if let Some(pos) = tab.prev_warning_position(tab.scroll.scroll_offset) {
                tab.scroll.scroll_offset = pos;
            } else {
                tab.interaction.command_error = Some("No previous warning".to_string());
            }
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (self, KeyResult::Handled);
        }

        if kb.normal.show_keybindings.matches(key, modifiers) {
            tab.interaction.g_key_pressed = false;
            self.count = None;
            return (Box::new(KeybindingsHelpMode::new()), KeyResult::Handled);
        }

        // Unrecognised key — consume it, reset the gg-chord state and count.
        tab.interaction.g_key_pressed = false;
        self.count = None;
        (self, KeyResult::Handled)
    }

    fn render_state(&self) -> ModeRenderState {
        ModeRenderState::Normal
    }

    fn mode_bar_content(&self, kb: &Keybindings, theme: &Theme) -> Line<'static> {
        let label = match self.count {
            Some(n) => format!("[NORMAL] {}  ", n),
            None => "[NORMAL]  ".to_string(),
        };
        let mut spans: Vec<Span<'static>> = vec![Span::styled(
            label,
            Style::default()
                .fg(theme.text_highlight_fg)
                .add_modifier(Modifier::BOLD),
        )];
        status_entry(&mut spans, kb.global.quit.display(), "quit", theme);
        status_entry(
            &mut spans,
            kb.normal.filter_include.display(),
            "filter in",
            theme,
        );
        status_entry(
            &mut spans,
            kb.normal.filter_exclude.display(),
            "filter out",
            theme,
        );
        status_entry(
            &mut spans,
            kb.normal.filter_mode.display(),
            "filters",
            theme,
        );
        status_entry(
            &mut spans,
            kb.normal.toggle_filtering.display(),
            "tog.filter",
            theme,
        );
        status_entry(&mut spans, kb.normal.mark_line.display(), "mark", theme);
        status_entry(
            &mut spans,
            kb.normal.toggle_marks_only.display(),
            "marks only",
            theme,
        );
        status_entry(&mut spans, kb.normal.enter_ui_mode.display(), "ui", theme);
        status_entry(&mut spans, kb.normal.visual_mode.display(), "visual", theme);
        status_entry(
            &mut spans,
            kb.normal.comment_line.display(),
            "comment",
            theme,
        );
        status_entry(
            &mut spans,
            kb.normal.show_keybindings.display(),
            "help",
            theme,
        );
        Line::from(spans)
    }
}

fn search_match_char_offset(tab: &TabState, line_text: &str) -> usize {
    let Some(line_idx) = tab.filter.visible_indices.get_opt(tab.scroll.scroll_offset) else {
        return 0;
    };
    let Some(occ_idx) = tab.search.query.get_current_occurrence_for_line(line_idx) else {
        return 0;
    };
    let Some(re) = tab.search.query.get_compiled_pattern() else {
        return 0;
    };
    let Some(m) = re.find_iter(line_text).nth(occ_idx) else {
        return 0;
    };
    line_text[..m.start()].chars().count()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::Database;
    use crate::db::LogManager;
    use crate::ingestion::FileReader;
    use crate::ui::{KeyResult, TabState, VisibleLines};
    use std::sync::Arc;

    async fn make_tab(lines: &[&str]) -> TabState {
        let data = lines.join("\n").into_bytes();
        let file_reader = FileReader::from_bytes(data);
        let db = Arc::new(Database::in_memory().await.unwrap());
        let log_manager = LogManager::new(db, None).await;
        TabState::new(file_reader, log_manager, "test".to_string())
    }

    async fn press(
        tab: &mut TabState,
        code: KeyCode,
        modifiers: KeyModifiers,
    ) -> (Box<dyn Mode>, KeyResult) {
        Box::new(NormalMode::default())
            .handle_key(tab, code, modifiers)
            .await
    }

    #[tokio::test]
    async fn test_j_increments_scroll_offset() {
        let mut tab = make_tab(&["a", "b", "c"]).await;
        press(&mut tab, KeyCode::Char('j'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 1);
    }

    #[tokio::test]
    async fn test_down_increments_scroll_offset() {
        let mut tab = make_tab(&["a", "b"]).await;
        press(&mut tab, KeyCode::Down, KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 1);
    }

    #[tokio::test]
    async fn test_k_saturates_at_zero() {
        let mut tab = make_tab(&["a"]).await;
        press(&mut tab, KeyCode::Char('k'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 0);
    }

    #[tokio::test]
    async fn test_up_saturates_at_zero() {
        let mut tab = make_tab(&["a"]).await;
        press(&mut tab, KeyCode::Up, KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 0);
    }

    #[tokio::test]
    async fn test_capital_g_jumps_to_last_visible_line() {
        let mut tab = make_tab(&["a", "b", "c", "d", "e"]).await;
        press(&mut tab, KeyCode::Char('G'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 4);
    }

    #[tokio::test]
    async fn test_capital_g_on_empty_does_not_panic() {
        let mut tab = make_tab(&[]).await;
        press(&mut tab, KeyCode::Char('G'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 0);
    }

    #[tokio::test]
    async fn test_gg_jumps_to_top() {
        let mut tab = make_tab(&["a", "b", "c"]).await;
        tab.scroll.scroll_offset = 2;
        press(&mut tab, KeyCode::Char('g'), KeyModifiers::NONE).await;
        assert!(tab.interaction.g_key_pressed);
        assert_eq!(tab.scroll.scroll_offset, 2);
        press(&mut tab, KeyCode::Char('g'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 0);
        assert!(!tab.interaction.g_key_pressed);
    }

    #[tokio::test]
    async fn test_ctrl_d_half_page_down() {
        let mut tab = make_tab(&["a", "b", "c", "d", "e", "f"]).await;
        tab.scroll.visible_height = 4;
        press(&mut tab, KeyCode::Char('d'), KeyModifiers::CONTROL).await;
        assert_eq!(tab.scroll.scroll_offset, 2);
    }

    #[tokio::test]
    async fn test_ctrl_u_half_page_up() {
        let mut tab = make_tab(&["a", "b", "c", "d"]).await;
        tab.scroll.visible_height = 4;
        tab.scroll.scroll_offset = 3;
        press(&mut tab, KeyCode::Char('u'), KeyModifiers::CONTROL).await;
        assert_eq!(tab.scroll.scroll_offset, 1);
    }

    #[tokio::test]
    async fn test_page_down() {
        let mut tab = make_tab(&["a", "b", "c", "d", "e"]).await;
        tab.scroll.visible_height = 3;
        press(&mut tab, KeyCode::PageDown, KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 3);
    }

    #[tokio::test]
    async fn test_page_up_saturates_at_zero() {
        let mut tab = make_tab(&["a"]).await;
        tab.scroll.visible_height = 5;
        press(&mut tab, KeyCode::PageUp, KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 0);
    }

    #[tokio::test]
    async fn test_i_opens_filter_include_command() {
        let mut tab = make_tab(&["line"]).await;
        let (mode, result) = press(&mut tab, KeyCode::Char('i'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        match mode.render_state() {
            ModeRenderState::Command { input, .. } => {
                assert_eq!(input, "filter ");
            }
            other => panic!("expected Command, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_o_opens_filter_exclude_command() {
        let mut tab = make_tab(&["line"]).await;
        let (mode, result) = press(&mut tab, KeyCode::Char('o'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        match mode.render_state() {
            ModeRenderState::Command { input, .. } => {
                assert_eq!(input, "exclude ");
            }
            other => panic!("expected Command, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_command_error_cleared_on_filter_include_shortcut() {
        let mut tab = make_tab(&["line"]).await;
        tab.interaction.command_error = Some("previous error".to_string());
        press(&mut tab, KeyCode::Char('i'), KeyModifiers::NONE).await;
        assert!(tab.interaction.command_error.is_none());
    }

    #[tokio::test]
    async fn test_command_error_cleared_on_colon() {
        let mut tab = make_tab(&["line"]).await;
        tab.interaction.command_error = Some("previous error".to_string());
        press(&mut tab, KeyCode::Char(':'), KeyModifiers::NONE).await;
        assert!(tab.interaction.command_error.is_none());
    }

    #[tokio::test]
    async fn test_u_enters_ui_mode() {
        let mut tab = make_tab(&["line"]).await;
        let (mode, result) = press(&mut tab, KeyCode::Char('u'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        assert!(format!("{:?}", mode).contains("UiMode"));
    }

    #[tokio::test]
    async fn test_colon_transitions_to_command_mode() {
        let mut tab = make_tab(&["line"]).await;
        let (mode, result) = press(&mut tab, KeyCode::Char(':'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        assert!(matches!(
            mode.render_state(),
            ModeRenderState::Command { .. }
        ));
        assert!(matches!(
            mode.render_state(),
            ModeRenderState::Command { .. } | ModeRenderState::Search { .. }
        ));
    }

    #[tokio::test]
    async fn test_f_transitions_to_filter_mode() {
        let mut tab = make_tab(&["line"]).await;
        let (mode, result) = press(&mut tab, KeyCode::Char('f'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        assert!(matches!(
            mode.render_state(),
            ModeRenderState::FilterManagement { .. }
        ));
    }

    #[tokio::test]
    async fn test_slash_transitions_to_forward_search() {
        let mut tab = make_tab(&["line"]).await;
        let (mode, _) = press(&mut tab, KeyCode::Char('/'), KeyModifiers::NONE).await;
        assert!(matches!(
            mode.render_state(),
            ModeRenderState::Command { .. } | ModeRenderState::Search { .. }
        ));
        match mode.render_state() {
            ModeRenderState::Search { forward, .. } => assert!(forward),
            other => panic!("expected Search, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_question_mark_transitions_to_backward_search() {
        let mut tab = make_tab(&["line"]).await;
        let (mode, _) = press(&mut tab, KeyCode::Char('?'), KeyModifiers::NONE).await;
        match mode.render_state() {
            ModeRenderState::Search { forward, .. } => assert!(!forward),
            other => panic!("expected Search, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_esc_clears_active_search() {
        let mut tab = make_tab(&["error line", "info line"]).await;
        tab.filter.visible_indices = VisibleLines::Filtered(vec![0, 1]);
        let visible = tab.filter.visible_indices.clone();
        let texts = tab.collect_display_texts(visible.iter());
        tab.search
            .query
            .search("error", visible.iter(), |li| texts.get(&li).cloned())
            .unwrap();
        assert!(tab.search.query.get_pattern().is_some());
        let (_, result) = press(&mut tab, KeyCode::Esc, KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        assert!(tab.search.query.get_pattern().is_none());
        assert!(tab.search.query.get_results().is_empty());
    }

    #[tokio::test]
    async fn test_entering_visual_char_clears_search() {
        let mut tab = make_tab(&["error line", "info line"]).await;
        tab.filter.visible_indices = VisibleLines::Filtered(vec![0, 1]);
        let visible = tab.filter.visible_indices.clone();
        let texts = tab.collect_display_texts(visible.iter());
        tab.search
            .query
            .search("error", visible.iter(), |li| texts.get(&li).cloned())
            .unwrap();
        assert!(tab.search.query.get_pattern().is_some());

        press(&mut tab, KeyCode::Char('v'), KeyModifiers::NONE).await;

        assert!(tab.search.query.get_pattern().is_none());
        assert!(tab.search.query.get_results().is_empty());
    }

    #[tokio::test]
    async fn test_esc_clears_inflight_search_handle() {
        let mut tab = make_tab(&["error line", "info line"]).await;
        tab.filter.visible_indices = VisibleLines::Filtered(vec![0, 1]);
        tab.begin_search("error", true, true);
        assert!(tab.search.handle.is_some());
        assert!(tab.search.query.get_pattern().is_some());
        press(&mut tab, KeyCode::Esc, KeyModifiers::NONE).await;
        assert!(tab.search.handle.is_none());
        assert!(tab.search.query.get_pattern().is_none());
    }

    #[tokio::test]
    async fn test_esc_without_active_search_does_nothing() {
        let mut tab = make_tab(&["line"]).await;
        assert!(tab.search.query.get_pattern().is_none());
        let (_, result) = press(&mut tab, KeyCode::Esc, KeyModifiers::NONE).await;
        // NormalMode consumes all unrecognised keys; no search to clear
        assert!(matches!(result, KeyResult::Handled));
        assert!(tab.search.query.get_pattern().is_none());
    }

    #[tokio::test]
    async fn test_q_returns_ignored() {
        let mut tab = make_tab(&["line"]).await;
        let (_, result) = press(&mut tab, KeyCode::Char('q'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Ignored));
    }

    #[tokio::test]
    async fn test_tab_returns_ignored() {
        let mut tab = make_tab(&["line"]).await;
        let (_, result) = press(&mut tab, KeyCode::Tab, KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Ignored));
    }

    #[tokio::test]
    async fn test_backtab_returns_ignored() {
        let mut tab = make_tab(&["line"]).await;
        let (_, result) = press(&mut tab, KeyCode::BackTab, KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Ignored));
    }

    #[tokio::test]
    async fn test_ctrl_w_returns_ignored() {
        let mut tab = make_tab(&["line"]).await;
        let (_, result) = press(&mut tab, KeyCode::Char('w'), KeyModifiers::CONTROL).await;
        assert!(matches!(result, KeyResult::Ignored));
    }

    #[tokio::test]
    async fn test_ctrl_t_returns_ignored() {
        let mut tab = make_tab(&["line"]).await;
        let (_, result) = press(&mut tab, KeyCode::Char('t'), KeyModifiers::CONTROL).await;
        assert!(matches!(result, KeyResult::Ignored));
    }

    #[tokio::test]
    async fn test_h_decrements_horizontal_scroll_when_not_wrapped() {
        let mut tab = make_tab(&["long line"]).await;
        tab.display.wrap = false;
        tab.scroll.horizontal_scroll = 5;
        press(&mut tab, KeyCode::Char('h'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.horizontal_scroll, 4);
    }

    #[tokio::test]
    async fn test_l_increments_horizontal_scroll_when_not_wrapped() {
        let mut tab = make_tab(&["long line"]).await;
        tab.display.wrap = false;
        press(&mut tab, KeyCode::Char('l'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.horizontal_scroll, 1);
    }

    #[tokio::test]
    async fn test_h_no_horizontal_scroll_when_wrapped() {
        let mut tab = make_tab(&["long line"]).await;
        tab.display.wrap = true;
        tab.scroll.horizontal_scroll = 5;
        press(&mut tab, KeyCode::Char('h'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.horizontal_scroll, 5);
    }

    #[tokio::test]
    async fn test_l_no_horizontal_scroll_when_wrapped() {
        let mut tab = make_tab(&["long line"]).await;
        tab.display.wrap = true;
        press(&mut tab, KeyCode::Char('l'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.horizontal_scroll, 0);
    }

    #[tokio::test]
    async fn test_left_arrow_decrements_horizontal_scroll_when_not_wrapped() {
        let mut tab = make_tab(&["long line"]).await;
        tab.display.wrap = false;
        tab.scroll.horizontal_scroll = 5;
        press(&mut tab, KeyCode::Left, KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.horizontal_scroll, 4);
    }

    #[tokio::test]
    async fn test_right_arrow_increments_horizontal_scroll_when_not_wrapped() {
        let mut tab = make_tab(&["long line"]).await;
        tab.display.wrap = false;
        press(&mut tab, KeyCode::Right, KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.horizontal_scroll, 1);
    }

    #[tokio::test]
    async fn test_left_arrow_no_horizontal_scroll_when_wrapped() {
        let mut tab = make_tab(&["long line"]).await;
        tab.display.wrap = true;
        tab.scroll.horizontal_scroll = 5;
        press(&mut tab, KeyCode::Left, KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.horizontal_scroll, 5);
    }

    #[tokio::test]
    async fn test_right_arrow_no_horizontal_scroll_when_wrapped() {
        let mut tab = make_tab(&["long line"]).await;
        tab.display.wrap = true;
        press(&mut tab, KeyCode::Right, KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.horizontal_scroll, 0);
    }

    #[tokio::test]
    async fn test_zero_resets_horizontal_scroll_to_start() {
        let mut tab = make_tab(&["hello world"]).await;
        tab.display.wrap = false;
        tab.scroll.horizontal_scroll = 7;
        press(&mut tab, KeyCode::Char('0'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.horizontal_scroll, 0);
    }

    #[tokio::test]
    async fn test_zero_as_count_suffix_does_not_reset_scroll() {
        let mut tab = make_tab(&["hello world"]).await;
        tab.display.wrap = false;
        tab.scroll.horizontal_scroll = 7;
        // Prime a count of 1, then press 0 — should build count 10, not reset scroll.
        // We must carry the mode instance between key presses to preserve the count state.
        let (mode, _) = Box::new(NormalMode::default())
            .handle_key(&mut tab, KeyCode::Char('1'), KeyModifiers::NONE)
            .await;
        mode.handle_key(&mut tab, KeyCode::Char('0'), KeyModifiers::NONE)
            .await;
        assert_eq!(
            tab.scroll.horizontal_scroll, 7,
            "scroll must not change while building a count"
        );
    }

    #[tokio::test]
    async fn test_dollar_scrolls_to_end_of_line() {
        let mut tab = make_tab(&["hello world"]).await;
        tab.display.wrap = false;
        tab.scroll.visible_width = 5;
        tab.scroll.horizontal_scroll = 0;
        press(&mut tab, KeyCode::Char('$'), KeyModifiers::NONE).await;
        // "hello world" is 11 chars; cursor at col 10, visible_width=5 → pad=min(3,2)=2 → scroll=13-5=8
        assert_eq!(tab.scroll.horizontal_scroll, 8);
    }

    #[tokio::test]
    async fn test_dollar_leaves_padding_when_viewport_large_enough() {
        let mut tab = make_tab(&["hello world"]).await;
        tab.display.wrap = false;
        tab.scroll.visible_width = 10;
        tab.scroll.horizontal_scroll = 0;
        press(&mut tab, KeyCode::Char('$'), KeyModifiers::NONE).await;
        // "hello world" is 11 chars; cursor at col 10, visible_width=10 → pad=min(3,4)=3 → scroll=14-10=4
        assert_eq!(tab.scroll.horizontal_scroll, 4);
        // last char (col 10) is at viewport position 10-4=6, with 3 empty cols on the right
    }

    #[tokio::test]
    async fn test_dollar_no_scroll_when_line_fits_in_viewport() {
        let mut tab = make_tab(&["hi"]).await;
        tab.display.wrap = false;
        tab.scroll.visible_width = 10;
        tab.scroll.horizontal_scroll = 3;
        press(&mut tab, KeyCode::Char('$'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.horizontal_scroll, 0);
    }

    #[tokio::test]
    async fn test_dollar_no_scroll_when_wrapped() {
        let mut tab = make_tab(&["hello world"]).await;
        tab.display.wrap = true;
        tab.scroll.visible_width = 5;
        tab.scroll.horizontal_scroll = 0;
        press(&mut tab, KeyCode::Char('$'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.horizontal_scroll, 0);
    }

    #[tokio::test]
    async fn test_dollar_no_scroll_when_visible_width_unknown() {
        let mut tab = make_tab(&["hello world"]).await;
        tab.display.wrap = false;
        tab.scroll.visible_width = 0;
        tab.scroll.horizontal_scroll = 0;
        press(&mut tab, KeyCode::Char('$'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.horizontal_scroll, 0);
    }

    #[tokio::test]
    async fn test_m_marks_current_line() {
        let mut tab = make_tab(&["line0", "line1"]).await;
        tab.scroll.scroll_offset = 0;
        press(&mut tab, KeyCode::Char('m'), KeyModifiers::NONE).await;
        assert!(tab.log_manager.get_marked_indices().contains(&0));
    }

    #[tokio::test]
    async fn test_m_unmarks_already_marked_line() {
        let mut tab = make_tab(&["line0"]).await;
        tab.scroll.scroll_offset = 0;
        press(&mut tab, KeyCode::Char('m'), KeyModifiers::NONE).await;
        press(&mut tab, KeyCode::Char('m'), KeyModifiers::NONE).await;
        assert!(!tab.log_manager.get_marked_indices().contains(&0));
    }

    #[tokio::test]
    async fn test_g_key_resets_on_non_g_press() {
        let mut tab = make_tab(&["a"]).await;
        press(&mut tab, KeyCode::Char('g'), KeyModifiers::NONE).await;
        assert!(tab.interaction.g_key_pressed);
        press(&mut tab, KeyCode::Char('j'), KeyModifiers::NONE).await;
        assert!(!tab.interaction.g_key_pressed);
    }

    #[tokio::test]
    async fn test_capital_f_toggles_filtering_enabled() {
        let mut tab = make_tab(&["a", "b", "c"]).await;
        assert!(tab.filter.enabled);
        press(&mut tab, KeyCode::Char('F'), KeyModifiers::NONE).await;
        assert!(!tab.filter.enabled);
        press(&mut tab, KeyCode::Char('F'), KeyModifiers::NONE).await;
        assert!(tab.filter.enabled);
    }

    #[tokio::test]
    async fn test_filtering_disabled_shows_all_lines() {
        let mut tab = make_tab(&["error", "warn", "info"]).await;
        tab.log_manager
            .add_filter_with_color(
                "error".to_string(),
                crate::filters::FilterType::Include,
                crate::filters::FilterOptions::default().line_mode(),
            )
            .await;
        tab.refresh_visible();
        // With filtering on, only "error" line is visible
        assert_eq!(tab.filter.visible_indices.len(), 1);

        press(&mut tab, KeyCode::Char('F'), KeyModifiers::NONE).await;
        // With filtering off, all 3 lines are visible
        assert_eq!(tab.filter.visible_indices.len(), 3);
    }

    #[tokio::test]
    async fn test_capital_m_toggles_marks_only() {
        let mut tab = make_tab(&["a", "b", "c"]).await;
        assert!(!tab.filter.show_marks_only);
        press(&mut tab, KeyCode::Char('M'), KeyModifiers::NONE).await;
        assert!(tab.filter.show_marks_only);
        press(&mut tab, KeyCode::Char('M'), KeyModifiers::NONE).await;
        assert!(!tab.filter.show_marks_only);
    }

    #[tokio::test]
    async fn test_marks_only_shows_only_marked_lines() {
        let mut tab = make_tab(&["line0", "line1", "line2"]).await;
        // Mark lines 0 and 2
        tab.log_manager.toggle_mark(0);
        tab.log_manager.toggle_mark(2);

        press(&mut tab, KeyCode::Char('M'), KeyModifiers::NONE).await;

        assert_eq!(
            tab.filter.visible_indices,
            VisibleLines::Filtered(vec![0, 2])
        );
    }

    #[tokio::test]
    async fn test_marks_only_off_restores_all_lines() {
        let mut tab = make_tab(&["line0", "line1", "line2"]).await;
        tab.log_manager.toggle_mark(1);
        press(&mut tab, KeyCode::Char('M'), KeyModifiers::NONE).await;
        assert_eq!(tab.filter.visible_indices.len(), 1);

        press(&mut tab, KeyCode::Char('M'), KeyModifiers::NONE).await;
        assert_eq!(tab.filter.visible_indices.len(), 3);
    }

    #[tokio::test]
    async fn test_marks_only_empty_when_no_marks() {
        let mut tab = make_tab(&["a", "b"]).await;
        press(&mut tab, KeyCode::Char('M'), KeyModifiers::NONE).await;
        assert!(tab.filter.visible_indices.is_empty());
    }

    #[tokio::test]
    async fn test_y_yanks_current_line() {
        let mut tab = make_tab(&["line0", "line1", "line2"]).await;
        tab.scroll.scroll_offset = 1;
        let (_, result) = press(&mut tab, KeyCode::Char('y'), KeyModifiers::NONE).await;
        match result {
            KeyResult::CopyToClipboard(text) => {
                assert_eq!(text, "line1");
            }
            other => panic!("expected CopyToClipboard, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_y_no_visible_lines_sets_error() {
        let mut tab = make_tab(&[]).await;
        let (_, result) = press(&mut tab, KeyCode::Char('y'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        assert_eq!(
            tab.interaction.command_error.as_deref(),
            Some("No visible lines")
        );
    }

    #[tokio::test]
    async fn test_capital_y_yanks_marked_lines() {
        let mut tab = make_tab(&["line0", "line1", "line2"]).await;
        tab.log_manager.toggle_mark(0);
        tab.log_manager.toggle_mark(2);
        let (_, result) = press(&mut tab, KeyCode::Char('Y'), KeyModifiers::NONE).await;
        match result {
            KeyResult::CopyToClipboard(text) => {
                assert_eq!(text, "line0\nline2");
            }
            other => panic!("expected CopyToClipboard, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_capital_y_no_marks_sets_error() {
        let mut tab = make_tab(&["line0", "line1"]).await;
        let (_, result) = press(&mut tab, KeyCode::Char('Y'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        assert_eq!(
            tab.interaction.command_error.as_deref(),
            Some("No marked lines")
        );
    }

    #[test]
    fn test_mode_bar_content_contains_normal() {
        assert!(matches!(
            NormalMode::default().render_state(),
            ModeRenderState::Normal
        ));
    }

    #[test]
    fn test_mode_bar_content_contains_marks_only_hint() {
        let content =
            NormalMode::default().mode_bar_content(&Keybindings::default(), &Theme::default());
        let text: String = content.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("marks only"));
    }

    // ── Count prefix tests ───────────────────────────────────────────────

    async fn press_mode(
        mode: NormalMode,
        tab: &mut TabState,
        code: KeyCode,
        modifiers: KeyModifiers,
    ) -> (Box<dyn Mode>, KeyResult) {
        Box::new(mode).handle_key(tab, code, modifiers).await
    }

    #[tokio::test]
    async fn test_count_5j_moves_down_5() {
        let lines: Vec<&str> = (0..20).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        let mode = NormalMode { count: Some(5) };
        press_mode(mode, &mut tab, KeyCode::Char('j'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 5);
    }

    #[tokio::test]
    async fn test_count_3k_moves_up_3() {
        let lines: Vec<&str> = (0..20).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.scroll_offset = 10;
        let mode = NormalMode { count: Some(3) };
        press_mode(mode, &mut tab, KeyCode::Char('k'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 7);
    }

    #[tokio::test]
    async fn test_digit_accumulation() {
        let mut tab = make_tab(&["a"]).await;
        let (mode, _) = press(&mut tab, KeyCode::Char('1'), KeyModifiers::NONE).await;
        let (mode, _) = mode
            .handle_key(&mut tab, KeyCode::Char('2'), KeyModifiers::NONE)
            .await;
        let (mode, _) = mode
            .handle_key(&mut tab, KeyCode::Char('3'), KeyModifiers::NONE)
            .await;
        // Verify the count is 123 by checking it goes to line 123 or moves.
        // Since we only have 1 line, check with gg chord.
        // Instead, press Esc to discard and verify it was accumulated by checking mode state.
        assert!(matches!(mode.render_state(), ModeRenderState::Normal));
    }

    #[tokio::test]
    async fn test_count_0_appends_to_existing() {
        let lines: Vec<&str> = (0..200).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        // Type "10" then "j"
        let (mode, _) = press(&mut tab, KeyCode::Char('1'), KeyModifiers::NONE).await;
        let (mode, _) = mode
            .handle_key(&mut tab, KeyCode::Char('0'), KeyModifiers::NONE)
            .await;
        let _ = mode
            .handle_key(&mut tab, KeyCode::Char('j'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 10);
    }

    #[tokio::test]
    async fn test_count_g_goes_to_line() {
        let lines: Vec<&str> = (0..20).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        // 5G should go to line 5 (0-based index 4)
        let mode = NormalMode { count: Some(5) };
        press_mode(mode, &mut tab, KeyCode::Char('G'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 4);
    }

    #[tokio::test]
    async fn test_count_gg_goes_to_line() {
        let lines: Vec<&str> = (0..20).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        // 5gg should go to line 5 (0-based index 4)
        let mode = NormalMode { count: Some(5) };
        // First g sets g_key_pressed
        let (returned_mode, _) =
            press_mode(mode, &mut tab, KeyCode::Char('g'), KeyModifiers::NONE).await;
        // Second g completes the chord
        let _ = returned_mode
            .handle_key(&mut tab, KeyCode::Char('g'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 4);
    }

    #[tokio::test]
    async fn test_count_resets_on_non_motion_key() {
        let mut tab = make_tab(&["a", "b"]).await;
        let (mode, _) = press(&mut tab, KeyCode::Char('5'), KeyModifiers::NONE).await;
        // Press 'm' (mark line) — count should be reset, mode stays Normal
        let (mode_after, _) = mode
            .handle_key(&mut tab, KeyCode::Char('m'), KeyModifiers::NONE)
            .await;
        // NormalMode.count should have been cleared
        match mode_after.render_state() {
            ModeRenderState::Normal => {}
            other => panic!("expected Normal, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_count_half_page_down() {
        let lines: Vec<&str> = (0..100).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.visible_height = 10;
        let mode = NormalMode { count: Some(3) };
        press_mode(mode, &mut tab, KeyCode::Char('d'), KeyModifiers::CONTROL).await;
        // 3 × (10/2) = 15
        assert_eq!(tab.scroll.scroll_offset, 15);
    }

    #[tokio::test]
    async fn test_count_half_page_up() {
        let lines: Vec<&str> = (0..100).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.visible_height = 10;
        tab.scroll.scroll_offset = 50;
        let mode = NormalMode { count: Some(2) };
        press_mode(mode, &mut tab, KeyCode::Char('u'), KeyModifiers::CONTROL).await;
        // 50 - 2 × (10/2) = 40
        assert_eq!(tab.scroll.scroll_offset, 40);
    }

    #[tokio::test]
    async fn test_count_page_down() {
        let lines: Vec<&str> = (0..100).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.visible_height = 10;
        let mode = NormalMode { count: Some(2) };
        press_mode(mode, &mut tab, KeyCode::PageDown, KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 20);
    }

    #[tokio::test]
    async fn test_count_page_up() {
        let lines: Vec<&str> = (0..100).map(|_| "line").collect();
        let mut tab = make_tab(&lines).await;
        tab.scroll.visible_height = 10;
        tab.scroll.scroll_offset = 50;
        let mode = NormalMode { count: Some(3) };
        press_mode(mode, &mut tab, KeyCode::PageUp, KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 20);
    }

    // ── Clear all marks and comments ────────────────────────────────

    #[tokio::test]
    async fn test_shift_c_clears_marks_and_comments() {
        let mut tab = make_tab(&["a", "b", "c"]).await;
        tab.log_manager.toggle_mark(0);
        tab.log_manager.toggle_mark(2);
        tab.log_manager.add_comment("note".into(), vec![1]);
        assert!(!tab.log_manager.get_marked_indices().is_empty());
        assert!(!tab.log_manager.get_comments().is_empty());

        press(&mut tab, KeyCode::Char('C'), KeyModifiers::NONE).await;
        assert!(tab.log_manager.get_marked_indices().is_empty());
        assert!(tab.log_manager.get_comments().is_empty());
        assert_eq!(
            tab.interaction.command_error.as_deref(),
            Some("Cleared all marks and comments")
        );
    }

    // ── Edit comment ────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_r_on_commented_line_opens_edit_mode() {
        let mut tab = make_tab(&["line0", "line1", "line2"]).await;
        tab.log_manager.add_comment("my comment".into(), vec![0]);
        tab.scroll.scroll_offset = 0;

        let (mode, result) = press(&mut tab, KeyCode::Char('r'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        match mode.render_state() {
            ModeRenderState::Comment { lines, .. } => {
                assert_eq!(lines.join("\n"), "my comment");
            }
            other => panic!("expected Comment, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_r_on_non_commented_line_shows_error() {
        let mut tab = make_tab(&["line0", "line1"]).await;
        tab.scroll.scroll_offset = 0;

        let (mode, result) = press(&mut tab, KeyCode::Char('r'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        assert!(matches!(mode.render_state(), ModeRenderState::Normal));
        assert_eq!(
            tab.interaction.command_error.as_deref(),
            Some("No comment on this line")
        );
    }

    // ── Delete comment ──────────────────────────────────────────────────

    #[tokio::test]
    async fn test_d_on_commented_line_deletes_comment() {
        let mut tab = make_tab(&["line0", "line1", "line2"]).await;
        tab.log_manager.add_comment("to delete".into(), vec![0]);
        tab.log_manager.add_comment("keep".into(), vec![2]);
        tab.scroll.scroll_offset = 0;

        let (mode, result) = press(&mut tab, KeyCode::Char('d'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        assert!(matches!(mode.render_state(), ModeRenderState::Normal));
        let comments = tab.log_manager.get_comments();
        assert_eq!(comments.len(), 1);
        assert_eq!(comments[0].text, "keep");
    }

    #[tokio::test]
    async fn test_d_on_non_commented_line_shows_error() {
        let mut tab = make_tab(&["line0", "line1"]).await;
        tab.scroll.scroll_offset = 0;

        let (_mode, result) = press(&mut tab, KeyCode::Char('d'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        assert_eq!(
            tab.interaction.command_error.as_deref(),
            Some("No comment on this line")
        );
        assert!(tab.log_manager.get_comments().is_empty());
    }

    #[tokio::test]
    async fn test_count_capped_at_999999() {
        let mut tab = make_tab(&["a"]).await;
        let mode = NormalMode {
            count: Some(999_999),
        };
        let (mode, _) = press_mode(mode, &mut tab, KeyCode::Char('9'), KeyModifiers::NONE).await;
        // After multiplying 999_999 * 10, it should be capped at 999_999
        // (saturating_mul won't overflow, but min(999_999) caps it)
        // The result of 999_999 * 10 = 9_999_990 + 9 = 9_999_999, capped to 999_999
        assert!(matches!(mode.render_state(), ModeRenderState::Normal));
    }

    // ── Comment line ─────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_c_opens_comment_mode_for_current_line() {
        let mut tab = make_tab(&["line0", "line1", "line2"]).await;
        tab.scroll.scroll_offset = 1;
        let (mode, result) = press(&mut tab, KeyCode::Char('c'), KeyModifiers::NONE).await;
        assert!(matches!(result, KeyResult::Handled));
        match mode.render_state() {
            ModeRenderState::Comment { line_count, .. } => {
                assert_eq!(line_count, 1);
            }
            other => panic!("expected Comment, got {:?}", other),
        }
    }

    // ── Error / warning navigation ────────────────────────────────────────

    #[tokio::test]
    async fn test_e_navigates_to_next_error() {
        let mut tab =
            make_tab(&["INFO normal line", "ERROR something failed", "INFO another"]).await;
        tab.scroll.scroll_offset = 0;
        press(&mut tab, KeyCode::Char('e'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 1);
    }

    #[tokio::test]
    async fn test_capital_e_navigates_to_prev_error() {
        let mut tab = make_tab(&["ERROR first error", "INFO normal line", "INFO another"]).await;
        tab.scroll.scroll_offset = 2;
        press(&mut tab, KeyCode::Char('E'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 0);
    }

    #[tokio::test]
    async fn test_e_at_last_error_sets_command_error() {
        let mut tab = make_tab(&["ERROR only error", "INFO line"]).await;
        tab.scroll.scroll_offset = 0;
        press(&mut tab, KeyCode::Char('e'), KeyModifiers::NONE).await;
        assert_eq!(
            tab.interaction.command_error.as_deref(),
            Some("No more errors")
        );
    }

    #[tokio::test]
    async fn test_capital_e_at_first_error_sets_command_error() {
        let mut tab = make_tab(&["INFO line", "ERROR only error"]).await;
        tab.scroll.scroll_offset = 1;
        press(&mut tab, KeyCode::Char('E'), KeyModifiers::NONE).await;
        assert_eq!(
            tab.interaction.command_error.as_deref(),
            Some("No previous error")
        );
    }

    #[tokio::test]
    async fn test_w_navigates_to_next_warning() {
        let mut tab =
            make_tab(&["INFO normal line", "WARN disk nearly full", "INFO another"]).await;
        tab.scroll.scroll_offset = 0;
        press(&mut tab, KeyCode::Char('w'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 1);
    }

    #[tokio::test]
    async fn test_capital_w_navigates_to_prev_warning() {
        let mut tab = make_tab(&["WARN first warning", "INFO normal line", "INFO another"]).await;
        tab.scroll.scroll_offset = 2;
        press(&mut tab, KeyCode::Char('W'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 0);
    }

    #[tokio::test]
    async fn test_w_no_warnings_sets_command_error() {
        let mut tab = make_tab(&["INFO only", "DEBUG line"]).await;
        tab.scroll.scroll_offset = 0;
        press(&mut tab, KeyCode::Char('w'), KeyModifiers::NONE).await;
        assert_eq!(
            tab.interaction.command_error.as_deref(),
            Some("No more warnings")
        );
    }

    #[tokio::test]
    async fn test_capital_w_no_prev_warning_sets_command_error() {
        let mut tab = make_tab(&["INFO line", "WARN only warning"]).await;
        tab.scroll.scroll_offset = 1;
        press(&mut tab, KeyCode::Char('W'), KeyModifiers::NONE).await;
        assert_eq!(
            tab.interaction.command_error.as_deref(),
            Some("No previous warning")
        );
    }

    #[tokio::test]
    async fn test_e_skips_non_error_levels() {
        let mut tab = make_tab(&[
            "INFO line",
            "WARN warning",
            "DEBUG debug",
            "ERROR error here",
        ])
        .await;
        tab.scroll.scroll_offset = 0;
        press(&mut tab, KeyCode::Char('e'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 3);
    }

    #[tokio::test]
    async fn test_e_navigates_to_fatal_level() {
        let mut tab = make_tab(&["INFO line", "FATAL crash"]).await;
        tab.scroll.scroll_offset = 0;
        press(&mut tab, KeyCode::Char('e'), KeyModifiers::NONE).await;
        assert_eq!(tab.scroll.scroll_offset, 1);
    }
}