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
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
use crate::{
    config::Keybindings,
    mode::app_mode::{Mode, ModeRenderState, status_entry},
    mode::command_mode::CommandMode,
    mode::normal_mode::NormalMode,
    mode::search_mode::SearchMode,
    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};

/// A character-search motion waiting for the target character.
#[derive(Debug, Clone)]
pub enum PendingMotion {
    FindForward,
    FindBackward,
    TillForward,
    TillBackward,
}

#[derive(Debug)]
pub struct VisualMode {
    /// Column where the selection was anchored (None = cursor-only, no active selection).
    pub anchor_col: Option<usize>,
    /// Column (char index) of the moving cursor.
    pub cursor_col: usize,
    /// Snapshot of the displayed line text captured on entry.
    pub line_text: String,
    /// A pending `f/F/t/T` motion waiting for a target character.
    pub pending_motion: Option<PendingMotion>,
    /// Last `f/F/t/T` motion for `;`/`,` repeat.
    pub last_char_motion: Option<(PendingMotion, char)>,
}

impl VisualMode {
    pub fn new(line_text: String) -> Self {
        Self {
            anchor_col: None,
            cursor_col: 0,
            line_text,
            pending_motion: None,
            last_char_motion: None,
        }
    }

    /// Refreshes `line_text` from the current scroll position, clamps `cursor_col`
    /// to the new line length, and resets selection state.
    /// Called after any motion that changes the active line.
    fn on_line_change(&mut self, tab: &TabState) {
        self.line_text = display_line_text(tab);
        let n = self.line_text.chars().count();
        self.cursor_col = if n == 0 {
            0
        } else {
            self.cursor_col.min(n - 1)
        };
        self.anchor_col = None;
        self.pending_motion = None;
    }

    /// Returns the currently selected text.
    /// Without an anchor, returns the single character under the cursor.
    fn selected_text(&self) -> String {
        let (lo, hi) = self.selection_range();
        self.line_text.chars().skip(lo).take(hi - lo + 1).collect()
    }

    /// Returns (lo, hi) char indices of the active selection (inclusive).
    /// Falls back to (cursor, cursor) when no anchor is set.
    pub fn selection_range(&self) -> (usize, usize) {
        let anchor = self.anchor_col.unwrap_or(self.cursor_col);
        let lo = anchor.min(self.cursor_col);
        let hi = anchor.max(self.cursor_col);
        (lo, hi)
    }
}

// ---------------------------------------------------------------------------
// Mode impl
// ---------------------------------------------------------------------------

#[async_trait]
impl Mode for VisualMode {
    async fn handle_key(
        mut self: Box<Self>,
        tab: &mut TabState,
        key: KeyCode,
        modifiers: KeyModifiers,
    ) -> (Box<dyn Mode>, KeyResult) {
        let kb = tab.interaction.keybindings.clone();

        if let Some(pending) = self.pending_motion.take() {
            if let KeyCode::Char(c) = key {
                self.cursor_col = apply_char_motion(&self.line_text, self.cursor_col, &pending, c);
                self.last_char_motion = Some((pending, c));
                tab.scroll_char_cursor_into_view(self.cursor_col, &self.line_text);
            }
            // Non-char key cancels the pending motion; cursor stays put.
            return (self, KeyResult::Handled);
        }

        let char_count = self.line_text.chars().count();

        // Clear the gg-chord flag for any key that isn't the go-to-top chord.
        if !kb.normal.go_to_top_chord.matches(key, modifiers) {
            tab.interaction.g_key_pressed = false;
        }

        if kb.visual.move_left.matches(key, modifiers) {
            self.cursor_col = char_left(self.cursor_col);
        } else if kb.visual.move_right.matches(key, modifiers) {
            self.cursor_col = char_right(&self.line_text, self.cursor_col);
        } else if kb.visual.word_forward.matches(key, modifiers) {
            self.cursor_col = word_forward(&self.line_text, self.cursor_col);
        } else if kb.visual.word_backward.matches(key, modifiers) {
            self.cursor_col = word_backward(&self.line_text, self.cursor_col);
        } else if kb.visual.word_end.matches(key, modifiers) {
            self.cursor_col = word_end(&self.line_text, self.cursor_col);
        } else if kb.visual.word_forward_big.matches(key, modifiers) {
            self.cursor_col = word_forward_big(&self.line_text, self.cursor_col);
        } else if kb.visual.word_backward_big.matches(key, modifiers) {
            self.cursor_col = word_backward_big(&self.line_text, self.cursor_col);
        } else if kb.visual.word_end_big.matches(key, modifiers) {
            self.cursor_col = word_end_big(&self.line_text, self.cursor_col);
        } else if kb.visual.start_of_line.matches(key, modifiers) {
            self.cursor_col = 0;
        } else if kb.visual.first_nonblank.matches(key, modifiers) {
            self.cursor_col = first_nonblank(&self.line_text);
        } else if kb.visual.end_of_line.matches(key, modifiers) {
            self.cursor_col = char_count.saturating_sub(1);
        } else if kb.visual.find_forward.matches(key, modifiers) {
            self.pending_motion = Some(PendingMotion::FindForward);
        } else if kb.visual.find_backward.matches(key, modifiers) {
            self.pending_motion = Some(PendingMotion::FindBackward);
        } else if kb.visual.till_forward.matches(key, modifiers) {
            self.pending_motion = Some(PendingMotion::TillForward);
        } else if kb.visual.till_backward.matches(key, modifiers) {
            self.pending_motion = Some(PendingMotion::TillBackward);
        } else if kb.visual.repeat_motion.matches(key, modifiers) {
            if let Some((motion, c)) = self.last_char_motion.clone() {
                self.cursor_col = apply_char_motion(&self.line_text, self.cursor_col, &motion, c);
            }
        } else if kb.visual.repeat_motion_rev.matches(key, modifiers) {
            if let Some((motion, c)) = self.last_char_motion.clone() {
                let reversed = reverse_motion(&motion);
                self.cursor_col = apply_char_motion(&self.line_text, self.cursor_col, &reversed, c);
            }
        } else if kb.visual.start_selection.matches(key, modifiers) {
            self.anchor_col = Some(self.cursor_col);
        } else if kb.visual.filter_include.matches(key, modifiers) {
            let selected = quote_for_command(&regex::escape(&self.selected_text()));
            let input = format!("filter {}", selected);
            let cursor = input.len();
            let history = tab.interaction.command_history.clone();
            return (
                Box::new(CommandMode::with_history(input, cursor, history)),
                KeyResult::Handled,
            );
        } else if kb.visual.filter_exclude.matches(key, modifiers) {
            let selected = quote_for_command(&regex::escape(&self.selected_text()));
            let input = format!("exclude {}", selected);
            let cursor = input.len();
            let history = tab.interaction.command_history.clone();
            return (
                Box::new(CommandMode::with_history(input, cursor, history)),
                KeyResult::Handled,
            );
        } else if kb.visual.search.matches(key, modifiers) {
            let selected = regex::escape(&self.selected_text());
            return (
                Box::new(SearchMode {
                    input: selected,
                    forward: true,
                }),
                KeyResult::Handled,
            );
        } else if kb.visual.yank.matches(key, modifiers) {
            let selected = self.selected_text();
            return (
                Box::new(NormalMode::default()),
                KeyResult::CopyToClipboard(selected),
            );
        } else if kb.visual.exit.matches(key, modifiers) {
            return (Box::new(NormalMode::default()), KeyResult::Handled);
        } else if kb.navigation.scroll_down.matches(key, modifiers) {
            tab.scroll.scroll_offset = tab.scroll.scroll_offset.saturating_add(1);
            self.on_line_change(tab);
        } else if kb.navigation.scroll_up.matches(key, modifiers) {
            tab.scroll.scroll_offset = tab.scroll.scroll_offset.saturating_sub(1);
            self.on_line_change(tab);
        } else if kb.navigation.half_page_down.matches(key, modifiers) {
            let half = (tab.scroll.visible_height / 2).max(1);
            tab.scroll.scroll_offset = tab.scroll.scroll_offset.saturating_add(half);
            self.on_line_change(tab);
        } else if kb.navigation.half_page_up.matches(key, modifiers) {
            let half = (tab.scroll.visible_height / 2).max(1);
            tab.scroll.scroll_offset = tab.scroll.scroll_offset.saturating_sub(half);
            self.on_line_change(tab);
        } else if kb.navigation.page_down.matches(key, modifiers) {
            let page = tab.scroll.visible_height.max(1);
            tab.scroll.scroll_offset = tab.scroll.scroll_offset.saturating_add(page);
            self.on_line_change(tab);
        } else if kb.navigation.page_up.matches(key, modifiers) {
            let page = tab.scroll.visible_height.max(1);
            tab.scroll.scroll_offset = tab.scroll.scroll_offset.saturating_sub(page);
            self.on_line_change(tab);
        } else if kb.normal.go_to_bottom.matches(key, modifiers) {
            let n = tab.filter.visible_indices.len();
            if n > 0 {
                tab.scroll.scroll_offset = n - 1;
            }
            self.on_line_change(tab);
        } else if kb.normal.go_to_top_chord.matches(key, modifiers) {
            if tab.interaction.g_key_pressed {
                tab.scroll.scroll_offset = 0;
                tab.interaction.g_key_pressed = false;
                self.on_line_change(tab);
            } else {
                tab.interaction.g_key_pressed = true;
            }
        }

        tab.scroll_char_cursor_into_view(self.cursor_col, &self.line_text);
        (self, KeyResult::Ignored)
    }

    fn mode_bar_content(&self, kb: &Keybindings, theme: &Theme) -> Line<'static> {
        if self.pending_motion.is_some() {
            return Line::from(vec![
                Span::styled(
                    "[VISUAL-CHAR]  ",
                    Style::default()
                        .fg(theme.text_highlight_fg)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(
                    "pending — type a character",
                    Style::default().fg(theme.text),
                ),
            ]);
        }

        let label = if self.anchor_col.is_some() {
            "[VISUAL-CHAR SELECT]  "
        } else {
            "[VISUAL-CHAR]  "
        };
        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.navigation.scroll_down.display(),
            "line↓",
            theme,
        );
        status_entry(
            &mut spans,
            kb.navigation.scroll_up.display(),
            "line↑",
            theme,
        );
        status_entry(&mut spans, kb.visual.move_left.display(), "char←", theme);
        status_entry(&mut spans, kb.visual.move_right.display(), "char→", theme);
        status_entry(&mut spans, kb.visual.word_forward.display(), "word→", theme);
        status_entry(&mut spans, kb.visual.word_end.display(), "end→", theme);
        status_entry(
            &mut spans,
            kb.visual.word_backward.display(),
            "word←",
            theme,
        );
        status_entry(
            &mut spans,
            kb.visual.start_of_line.display(),
            "line-start",
            theme,
        );
        status_entry(
            &mut spans,
            kb.visual.end_of_line.display(),
            "line-end",
            theme,
        );
        status_entry(&mut spans, kb.visual.find_forward.display(), "find→", theme);
        status_entry(
            &mut spans,
            kb.visual.start_selection.display(),
            "select",
            theme,
        );
        status_entry(
            &mut spans,
            kb.visual.filter_include.display(),
            "filter",
            theme,
        );
        status_entry(
            &mut spans,
            kb.visual.filter_exclude.display(),
            "exclude",
            theme,
        );
        status_entry(&mut spans, kb.visual.search.display(), "search", theme);
        status_entry(&mut spans, kb.visual.yank.display(), "yank", theme);
        status_entry(&mut spans, kb.visual.exit.display(), "cancel", theme);
        Line::from(spans)
    }

    fn render_state(&self) -> ModeRenderState {
        ModeRenderState::Visual {
            anchor_col: self.anchor_col,
            cursor_col: self.cursor_col,
            pending_motion: self.pending_motion.is_some(),
        }
    }

    fn on_scroll_line_change(&mut self, tab: &mut TabState) {
        self.on_line_change(tab);
        tab.scroll_char_cursor_into_view(self.cursor_col, &self.line_text);
    }
}

// ---------------------------------------------------------------------------
// Shared helper — also used by normal_mode to capture the line text on entry
// ---------------------------------------------------------------------------

/// Wraps `pattern` in double quotes when it contains whitespace, escaping
/// any embedded `"` as `\"` so that `shell_split` reconstructs the original
/// pattern correctly.
pub fn quote_for_command(pattern: &str) -> String {
    if pattern.chars().any(char::is_whitespace) {
        let escaped = pattern.replace('"', "\\\"");
        format!("\"{}\"", escaped)
    } else {
        pattern.to_string()
    }
}

/// Returns the displayed text for the current scroll line using parsed
/// field-layout (if available) or raw bytes as fallback.
pub fn display_line_text(tab: &TabState) -> String {
    if let Some(idx) = tab.filter.visible_indices.get_opt(tab.scroll.scroll_offset) {
        let bytes = tab.file_reader.get_line(idx);
        if !tab.display.raw_mode
            && let Some(parser) = tab.display.format.as_ref()
            && let Some(parts) = parser.parse_line(bytes)
        {
            return apply_field_layout(
                &parts,
                &tab.display.field_layout,
                &tab.display.hidden_fields,
                tab.display.show_keys,
                None,
            )
            .join(" ");
        }
        String::from_utf8_lossy(bytes).into_owned()
    } else {
        String::new()
    }
}

// ---------------------------------------------------------------------------
// Motion helpers
// ---------------------------------------------------------------------------

fn apply_char_motion(text: &str, col: usize, motion: &PendingMotion, c: char) -> usize {
    match motion {
        PendingMotion::FindForward => find_char_forward(text, col, c),
        PendingMotion::FindBackward => find_char_backward(text, col, c),
        PendingMotion::TillForward => till_char_forward(text, col, c),
        PendingMotion::TillBackward => till_char_backward(text, col, c),
    }
}

fn reverse_motion(motion: &PendingMotion) -> PendingMotion {
    match motion {
        PendingMotion::FindForward => PendingMotion::FindBackward,
        PendingMotion::FindBackward => PendingMotion::FindForward,
        PendingMotion::TillForward => PendingMotion::TillBackward,
        PendingMotion::TillBackward => PendingMotion::TillForward,
    }
}

pub fn char_left(col: usize) -> usize {
    col.saturating_sub(1)
}

pub fn char_right(text: &str, col: usize) -> usize {
    let n = text.chars().count();
    if n == 0 { 0 } else { (col + 1).min(n - 1) }
}

fn is_word_char(c: char) -> bool {
    c.is_alphanumeric() || c == '_' || c == '-'
}

/// Returns the (start, end) inclusive char indices of the word at `col`.
/// Returns `None` if `col` is not on a word character.
pub fn word_bounds_at(text: &str, col: usize) -> Option<(usize, usize)> {
    let chars: Vec<char> = text.chars().collect();
    let n = chars.len();
    if col >= n || !is_word_char(chars[col]) {
        return None;
    }
    let mut start = col;
    while start > 0 && is_word_char(chars[start - 1]) {
        start -= 1;
    }
    let mut end = col;
    while end + 1 < n && is_word_char(chars[end + 1]) {
        end += 1;
    }
    Some((start, end))
}

pub fn word_forward(text: &str, col: usize) -> usize {
    let chars: Vec<char> = text.chars().collect();
    let n = chars.len();
    if col >= n {
        return n.saturating_sub(1);
    }
    let mut pos = col;
    if is_word_char(chars[pos]) {
        while pos < n && is_word_char(chars[pos]) {
            pos += 1;
        }
    } else if !chars[pos].is_whitespace() {
        while pos < n && !is_word_char(chars[pos]) && !chars[pos].is_whitespace() {
            pos += 1;
        }
    }
    while pos < n && chars[pos].is_whitespace() {
        pos += 1;
    }
    pos.min(n.saturating_sub(1))
}

pub fn word_backward(text: &str, col: usize) -> usize {
    if col == 0 {
        return 0;
    }
    let chars: Vec<char> = text.chars().collect();
    let mut pos = col - 1;
    while pos > 0 && chars[pos].is_whitespace() {
        pos -= 1;
    }
    if chars[pos].is_whitespace() {
        return 0;
    }
    if is_word_char(chars[pos]) {
        while pos > 0 && is_word_char(chars[pos - 1]) {
            pos -= 1;
        }
    } else {
        while pos > 0 && !is_word_char(chars[pos - 1]) && !chars[pos - 1].is_whitespace() {
            pos -= 1;
        }
    }
    pos
}

pub fn word_end(text: &str, col: usize) -> usize {
    let chars: Vec<char> = text.chars().collect();
    let n = chars.len();
    if n == 0 {
        return 0;
    }
    let mut pos = col;
    // Step right if already at the end of a word/punct group.
    if pos + 1 < n {
        let at_word_end = is_word_char(chars[pos]) && !is_word_char(chars[pos + 1]);
        let at_punct_end = !is_word_char(chars[pos])
            && !chars[pos].is_whitespace()
            && (is_word_char(chars[pos + 1]) || chars[pos + 1].is_whitespace());
        if at_word_end || at_punct_end {
            pos += 1;
        }
    } else {
        return n - 1;
    }
    while pos < n && chars[pos].is_whitespace() {
        pos += 1;
    }
    if pos >= n {
        return n - 1;
    }
    if is_word_char(chars[pos]) {
        while pos + 1 < n && is_word_char(chars[pos + 1]) {
            pos += 1;
        }
    } else {
        while pos + 1 < n && !is_word_char(chars[pos + 1]) && !chars[pos + 1].is_whitespace() {
            pos += 1;
        }
    }
    pos
}

pub fn word_forward_big(text: &str, col: usize) -> usize {
    let chars: Vec<char> = text.chars().collect();
    let n = chars.len();
    if col >= n {
        return n.saturating_sub(1);
    }
    let mut pos = col;
    while pos < n && !chars[pos].is_whitespace() {
        pos += 1;
    }
    while pos < n && chars[pos].is_whitespace() {
        pos += 1;
    }
    pos.min(n.saturating_sub(1))
}

pub fn word_backward_big(text: &str, col: usize) -> usize {
    if col == 0 {
        return 0;
    }
    let chars: Vec<char> = text.chars().collect();
    let mut pos = col - 1;
    while pos > 0 && chars[pos].is_whitespace() {
        pos -= 1;
    }
    if chars[pos].is_whitespace() {
        return 0;
    }
    while pos > 0 && !chars[pos - 1].is_whitespace() {
        pos -= 1;
    }
    pos
}

pub fn word_end_big(text: &str, col: usize) -> usize {
    let chars: Vec<char> = text.chars().collect();
    let n = chars.len();
    if n == 0 {
        return 0;
    }
    let mut pos = col;
    if pos + 1 < n && !chars[pos].is_whitespace() && chars[pos + 1].is_whitespace() {
        pos += 1;
    } else if pos + 1 >= n {
        return n - 1;
    }
    while pos < n && chars[pos].is_whitespace() {
        pos += 1;
    }
    if pos >= n {
        return n - 1;
    }
    while pos + 1 < n && !chars[pos + 1].is_whitespace() {
        pos += 1;
    }
    pos
}

pub fn first_nonblank(text: &str) -> usize {
    text.chars().position(|c| !c.is_whitespace()).unwrap_or(0)
}

pub fn find_char_forward(text: &str, col: usize, target: char) -> usize {
    text.chars()
        .enumerate()
        .skip(col + 1)
        .find(|&(_, c)| c == target)
        .map(|(i, _)| i)
        .unwrap_or(col)
}

pub fn find_char_backward(text: &str, col: usize, target: char) -> usize {
    if col == 0 {
        return 0;
    }
    let chars: Vec<char> = text.chars().collect();
    for i in (0..col).rev() {
        if chars[i] == target {
            return i;
        }
    }
    col // not found, stay
}

pub fn till_char_forward(text: &str, col: usize, target: char) -> usize {
    let found = find_char_forward(text, col, target);
    if found > col {
        found.saturating_sub(1)
    } else {
        col
    }
}

pub fn till_char_backward(text: &str, col: usize, target: char) -> usize {
    let found = find_char_backward(text, col, target);
    if found < col {
        (found + 1).min(col)
    } else {
        col
    }
}

/// Overlay REVERSED modifier on chars [lo, hi] (inclusive) of a rendered Line.
/// Used by the render layer to show the visual-char selection.
pub fn apply_char_selection(line: Line<'static>, lo: usize, hi: usize) -> Line<'static> {
    let base_style = line.style;
    let mut new_spans: Vec<Span<'static>> = Vec::new();
    let mut char_pos = 0usize;

    for span in line.spans {
        let content = span.content.as_ref().to_owned();
        let style = span.style;
        let span_chars: Vec<char> = content.chars().collect();
        let span_len = span_chars.len();
        let span_end = char_pos + span_len;

        // Compute overlap with [lo, hi] within this span.
        let sel_start = lo.saturating_sub(char_pos).min(span_len);
        let sel_end = (hi + 1).saturating_sub(char_pos).min(span_len);
        let has_overlap = sel_start < sel_end && char_pos <= hi && span_end > lo;

        if !has_overlap {
            new_spans.push(Span::styled(content, style));
        } else {
            if sel_start > 0 {
                let s: String = span_chars[..sel_start].iter().collect();
                new_spans.push(Span::styled(s, style));
            }
            let s: String = span_chars[sel_start..sel_end].iter().collect();
            new_spans.push(Span::styled(s, style.add_modifier(Modifier::REVERSED)));
            if sel_end < span_len {
                let s: String = span_chars[sel_end..].iter().collect();
                new_spans.push(Span::styled(s, style));
            }
        }

        char_pos = span_end;
    }

    Line::from(new_spans).style(base_style)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::Database;
    use crate::db::LogManager;
    use crate::ingestion::FileReader;
    use crate::mode::app_mode::ModeRenderState;
    use crate::ui::TabState;
    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())
    }

    fn make_mode(text: &str) -> VisualMode {
        VisualMode::new(text.to_string())
    }

    async fn press(
        mode: VisualMode,
        tab: &mut TabState,
        key: KeyCode,
    ) -> (Box<dyn Mode>, KeyResult) {
        Box::new(mode)
            .handle_key(tab, key, KeyModifiers::NONE)
            .await
    }

    fn cursor_col(mode: &dyn Mode) -> usize {
        match mode.render_state() {
            ModeRenderState::Visual { cursor_col, .. } => cursor_col,
            other => panic!("expected Visual, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_h_moves_left() {
        let mut tab = make_tab(&["hello"]).await;
        let mut mode = make_mode("hello");
        mode.cursor_col = 3;
        let (m, _) = press(mode, &mut tab, KeyCode::Char('h')).await;
        assert_eq!(cursor_col(m.as_ref()), 2);
    }

    #[tokio::test]
    async fn test_h_saturates_at_zero() {
        let mut tab = make_tab(&["hello"]).await;
        let mode = make_mode("hello");
        let (m, _) = press(mode, &mut tab, KeyCode::Char('h')).await;
        assert_eq!(cursor_col(m.as_ref()), 0);
    }

    #[tokio::test]
    async fn test_l_moves_right() {
        let mut tab = make_tab(&["hello"]).await;
        let mode = make_mode("hello");
        let (m, _) = press(mode, &mut tab, KeyCode::Char('l')).await;
        assert_eq!(cursor_col(m.as_ref()), 1);
    }

    #[tokio::test]
    async fn test_l_saturates_at_end() {
        let mut tab = make_tab(&["hi"]).await;
        let mut mode = make_mode("hi");
        mode.cursor_col = 1;
        let (m, _) = press(mode, &mut tab, KeyCode::Char('l')).await;
        assert_eq!(cursor_col(m.as_ref()), 1);
    }

    #[tokio::test]
    async fn test_zero_moves_to_start() {
        let mut tab = make_tab(&["hello"]).await;
        let mut mode = make_mode("hello");
        mode.cursor_col = 4;
        let (m, _) = press(mode, &mut tab, KeyCode::Char('0')).await;
        assert_eq!(cursor_col(m.as_ref()), 0);
    }

    #[tokio::test]
    async fn test_caret_moves_to_first_nonblank() {
        let mut tab = make_tab(&["  hello"]).await;
        let mut mode = make_mode("  hello");
        mode.cursor_col = 6;
        let (m, _) = press(mode, &mut tab, KeyCode::Char('^')).await;
        assert_eq!(cursor_col(m.as_ref()), 2);
    }

    #[tokio::test]
    async fn test_dollar_moves_to_end() {
        let mut tab = make_tab(&["hello"]).await;
        let mode = make_mode("hello");
        let (m, _) = press(mode, &mut tab, KeyCode::Char('$')).await;
        assert_eq!(cursor_col(m.as_ref()), 4);
    }

    #[tokio::test]
    async fn test_w_moves_to_next_word() {
        let mut tab = make_tab(&["foo bar"]).await;
        let mode = make_mode("foo bar");
        let (m, _) = press(mode, &mut tab, KeyCode::Char('w')).await;
        assert_eq!(cursor_col(m.as_ref()), 4);
    }

    #[tokio::test]
    async fn test_b_moves_to_word_start() {
        let mut tab = make_tab(&["foo bar"]).await;
        let mut mode = make_mode("foo bar");
        mode.cursor_col = 4;
        let (m, _) = press(mode, &mut tab, KeyCode::Char('b')).await;
        assert_eq!(cursor_col(m.as_ref()), 0);
    }

    #[tokio::test]
    async fn test_e_moves_to_word_end() {
        let mut tab = make_tab(&["foo bar"]).await;
        let mode = make_mode("foo bar");
        let (m, _) = press(mode, &mut tab, KeyCode::Char('e')).await;
        assert_eq!(cursor_col(m.as_ref()), 2);
    }

    #[tokio::test]
    async fn test_big_w_skips_whitespace_delimited() {
        let mut tab = make_tab(&["foo.bar baz"]).await;
        let mode = make_mode("foo.bar baz");
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('W'), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(m.as_ref()), 8);
    }

    #[tokio::test]
    async fn test_big_b_skips_whitespace_delimited_backward() {
        let mut tab = make_tab(&["foo bar.baz"]).await;
        let mut mode = make_mode("foo bar.baz");
        mode.cursor_col = 10;
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('B'), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(m.as_ref()), 4);
    }

    #[tokio::test]
    async fn test_big_e_skips_whitespace_delimited_end() {
        let mut tab = make_tab(&["foo bar.baz"]).await;
        let mut mode = make_mode("foo bar.baz");
        mode.cursor_col = 3; // space after "foo"
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('E'), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(m.as_ref()), 10);
    }

    #[tokio::test]
    async fn test_f_enters_pending_then_finds_char() {
        let mut tab = make_tab(&["hello world"]).await;
        let mode = make_mode("hello world");
        // 'f' → pending
        let (mb, _) = press(mode, &mut tab, KeyCode::Char('f')).await;
        assert!(matches!(
            mb.render_state(),
            ModeRenderState::Visual {
                pending_motion: true,
                ..
            }
        ));
        // 'o' → find first 'o' after col 0 → index 4
        let (mc, _) = mb
            .handle_key(&mut tab, KeyCode::Char('o'), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(mc.as_ref()), 4);
    }

    #[tokio::test]
    async fn test_f_no_match_stays_put() {
        let mut tab = make_tab(&["hello"]).await;
        let mode = make_mode("hello");
        let (mb, _) = press(mode, &mut tab, KeyCode::Char('f')).await;
        let (mc, _) = mb
            .handle_key(&mut tab, KeyCode::Char('z'), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(mc.as_ref()), 0);
    }

    #[tokio::test]
    async fn test_big_f_finds_prev_char() {
        let mut tab = make_tab(&["hello world"]).await;
        let mut mode = make_mode("hello world");
        mode.cursor_col = 10;
        let (mb, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('F'), KeyModifiers::NONE)
            .await;
        // 'o' backward from 10 → 'o' in "world" at index 7
        let (mc, _) = mb
            .handle_key(&mut tab, KeyCode::Char('o'), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(mc.as_ref()), 7);
    }

    #[tokio::test]
    async fn test_t_stops_one_before() {
        let mut tab = make_tab(&["hello"]).await;
        let mode = make_mode("hello");
        let (mb, _) = press(mode, &mut tab, KeyCode::Char('t')).await;
        // 'l' found at 2, stop at 1
        let (mc, _) = mb
            .handle_key(&mut tab, KeyCode::Char('l'), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(mc.as_ref()), 1);
    }

    #[tokio::test]
    async fn test_big_t_stops_one_after() {
        let mut tab = make_tab(&["hello"]).await;
        let mut mode = make_mode("hello");
        mode.cursor_col = 4;
        let (mb, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('T'), KeyModifiers::NONE)
            .await;
        // 'e' found at 1, stop at 2
        let (mc, _) = mb
            .handle_key(&mut tab, KeyCode::Char('e'), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(mc.as_ref()), 2);
    }

    #[tokio::test]
    async fn test_semicolon_repeats_last_motion() {
        let mut tab = make_tab(&["aXbXcX"]).await;
        let mode = make_mode("aXbXcX");
        // f X → col=1
        let (mb, _) = press(mode, &mut tab, KeyCode::Char('f')).await;
        let (mb, _) = mb
            .handle_key(&mut tab, KeyCode::Char('X'), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(mb.as_ref()), 1);
        // ; → col=3
        let (mb, _) = mb
            .handle_key(&mut tab, KeyCode::Char(';'), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(mb.as_ref()), 3);
        // ; again → col=5
        let (mb, _) = mb
            .handle_key(&mut tab, KeyCode::Char(';'), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(mb.as_ref()), 5);
    }

    #[tokio::test]
    async fn test_comma_reverses_motion() {
        let mut tab = make_tab(&["aXbXcX"]).await;
        let mut mode = make_mode("aXbXcX");
        mode.cursor_col = 5;
        // F X → col=3
        let (mb, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('F'), KeyModifiers::NONE)
            .await;
        let (mb, _) = mb
            .handle_key(&mut tab, KeyCode::Char('X'), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(mb.as_ref()), 3);
        // , → reverse F = f X → from 3 forward → col=5
        let (mb, _) = mb
            .handle_key(&mut tab, KeyCode::Char(','), KeyModifiers::NONE)
            .await;
        assert_eq!(cursor_col(mb.as_ref()), 5);
    }

    #[tokio::test]
    async fn test_pending_cancelled_by_non_char_key() {
        let mut tab = make_tab(&["hello"]).await;
        let mode = make_mode("hello");
        let (mb, _) = press(mode, &mut tab, KeyCode::Char('f')).await;
        assert!(matches!(
            mb.render_state(),
            ModeRenderState::Visual {
                pending_motion: true,
                ..
            }
        ));
        // Left arrow cancels pending, cursor stays at 0
        let (mb2, _) = mb
            .handle_key(&mut tab, KeyCode::Left, KeyModifiers::NONE)
            .await;
        assert!(matches!(
            mb2.render_state(),
            ModeRenderState::Visual {
                pending_motion: false,
                ..
            }
        ));
        assert_eq!(cursor_col(mb2.as_ref()), 0);
    }

    #[tokio::test]
    async fn test_i_enters_command_mode_with_filter_prefix() {
        let mut tab = make_tab(&["hello world"]).await;
        let mut mode = make_mode("hello world");
        mode.anchor_col = Some(0);
        mode.cursor_col = 4; // selected = "hello"
        let (m, _) = press(mode, &mut tab, KeyCode::Char('i')).await;
        match m.render_state() {
            ModeRenderState::Command { input, .. } => {
                assert!(input.starts_with("filter "), "got: {input}");
                assert!(input.contains("hello"));
            }
            other => panic!("expected Command, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_i_escapes_regex_metacharacters_in_filter() {
        let mut tab = make_tab(&["192.168.1.1 GET /api"]).await;
        let mut mode = make_mode("192.168.1.1 GET /api");
        mode.anchor_col = Some(0);
        mode.cursor_col = 10; // selected = "192.168.1.1"
        let (m, _) = press(mode, &mut tab, KeyCode::Char('i')).await;
        match m.render_state() {
            ModeRenderState::Command { input, .. } => {
                assert_eq!(input, r"filter 192\.168\.1\.1", "got: {input}");
            }
            other => panic!("expected Command, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_o_enters_command_mode_with_exclude_prefix() {
        let mut tab = make_tab(&["hello world"]).await;
        let mut mode = make_mode("hello world");
        mode.anchor_col = Some(0);
        mode.cursor_col = 4; // selected = "hello"
        let (m, _) = press(mode, &mut tab, KeyCode::Char('o')).await;
        match m.render_state() {
            ModeRenderState::Command { input, .. } => {
                assert!(input.starts_with("exclude "), "got: {input}");
                assert!(input.contains("hello"));
            }
            other => panic!("expected Command, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_o_escapes_regex_metacharacters_in_exclude() {
        let mut tab = make_tab(&["error: connection(reset)"]).await;
        let mut mode = make_mode("error: connection(reset)");
        mode.anchor_col = Some(7);
        mode.cursor_col = 23; // selected = "connection(reset)"
        let (m, _) = press(mode, &mut tab, KeyCode::Char('o')).await;
        match m.render_state() {
            ModeRenderState::Command { input, .. } => {
                assert_eq!(input, r"exclude connection\(reset\)", "got: {input}");
            }
            other => panic!("expected Command, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_filter_with_spaces_wraps_in_quotes() {
        let mut tab = make_tab(&["hello world foo"]).await;
        let mut mode = make_mode("hello world foo");
        mode.anchor_col = Some(0);
        mode.cursor_col = 10; // selected = "hello world"
        let (m, _) = press(mode, &mut tab, KeyCode::Char('i')).await;
        match m.render_state() {
            ModeRenderState::Command { input, .. } => {
                assert_eq!(input, r#"filter "hello world""#, "got: {input}");
            }
            other => panic!("expected Command, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_exclude_with_spaces_wraps_in_quotes() {
        let mut tab = make_tab(&["error hello world"]).await;
        let mut mode = make_mode("error hello world");
        mode.anchor_col = Some(6);
        mode.cursor_col = 16; // selected = "hello world"
        let (m, _) = press(mode, &mut tab, KeyCode::Char('o')).await;
        match m.render_state() {
            ModeRenderState::Command { input, .. } => {
                assert_eq!(input, r#"exclude "hello world""#, "got: {input}");
            }
            other => panic!("expected Command, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_filter_with_embedded_quote_escaped() {
        let mut tab = make_tab(&[r#"say "hi" now"#]).await;
        let mut mode = make_mode(r#"say "hi" now"#);
        mode.anchor_col = Some(0);
        mode.cursor_col = 11; // selected = r#"say "hi" now"#
        let (m, _) = press(mode, &mut tab, KeyCode::Char('i')).await;
        match m.render_state() {
            ModeRenderState::Command { input, .. } => {
                assert_eq!(input, r#"filter "say \"hi\" now""#, "got: {input}");
            }
            other => panic!("expected Command, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_filter_no_spaces_no_quotes() {
        let mut tab = make_tab(&["error"]).await;
        let mut mode = make_mode("error");
        mode.anchor_col = Some(0);
        mode.cursor_col = 4;
        let (m, _) = press(mode, &mut tab, KeyCode::Char('i')).await;
        match m.render_state() {
            ModeRenderState::Command { input, .. } => {
                assert_eq!(input, "filter error", "got: {input}");
            }
            other => panic!("expected Command, got {:?}", other),
        }
    }

    // ── quote_for_command unit tests ─────────────────────────────────────────

    #[test]
    fn test_quote_for_command_no_spaces() {
        assert_eq!(quote_for_command("hello"), "hello");
        assert_eq!(quote_for_command(r"192\.168\.1\.1"), r"192\.168\.1\.1");
    }

    #[test]
    fn test_quote_for_command_with_spaces() {
        assert_eq!(quote_for_command("hello world"), r#""hello world""#);
    }

    #[test]
    fn test_quote_for_command_embedded_quote() {
        assert_eq!(quote_for_command(r#"say "hi" now"#), r#""say \"hi\" now""#);
    }

    #[test]
    fn test_quote_for_command_empty() {
        assert_eq!(quote_for_command(""), "");
    }

    #[tokio::test]
    async fn test_slash_enters_search_mode_with_selected_text() {
        let mut tab = make_tab(&["hello world"]).await;
        let mut mode = make_mode("hello world");
        mode.anchor_col = Some(0);
        mode.cursor_col = 4; // selected = "hello"
        let (m, _) = press(mode, &mut tab, KeyCode::Char('/')).await;
        match m.render_state() {
            ModeRenderState::Search { query, forward } => {
                assert!(query.contains("hello"), "got: {query}");
                assert!(forward);
            }
            other => panic!("expected Search, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_slash_escapes_regex_metacharacters_in_search() {
        let mut tab = make_tab(&["GET /api/v1?foo=bar"]).await;
        let mut mode = make_mode("GET /api/v1?foo=bar");
        mode.anchor_col = Some(4);
        mode.cursor_col = 18; // selected = "/api/v1?foo=bar"
        let (m, _) = press(mode, &mut tab, KeyCode::Char('/')).await;
        match m.render_state() {
            ModeRenderState::Search { query, forward } => {
                assert_eq!(query, r"/api/v1\?foo=bar", "got: {query}");
                assert!(forward);
            }
            other => panic!("expected Search, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_y_copies_selected_text_to_clipboard() {
        let mut tab = make_tab(&["hello world"]).await;
        let mut mode = make_mode("hello world");
        mode.anchor_col = Some(0);
        mode.cursor_col = 4;
        let (m, result) = press(mode, &mut tab, KeyCode::Char('y')).await;
        assert!(matches!(m.render_state(), ModeRenderState::Normal));
        match result {
            KeyResult::CopyToClipboard(text) => assert_eq!(text, "hello"),
            other => panic!("expected CopyToClipboard, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_y_anchor_after_cursor_still_selects_correctly() {
        let mut tab = make_tab(&["hello"]).await;
        let mut mode = make_mode("hello");
        mode.anchor_col = Some(4);
        mode.cursor_col = 1;
        let (_, result) = press(mode, &mut tab, KeyCode::Char('y')).await;
        match result {
            KeyResult::CopyToClipboard(text) => assert_eq!(text, "ello"),
            other => panic!("expected CopyToClipboard, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_v_anchors_selection_at_cursor() {
        let mut tab = make_tab(&["hello"]).await;
        let mut mode = make_mode("hello");
        mode.cursor_col = 2;
        assert!(mode.anchor_col.is_none());
        let (m, _) = press(mode, &mut tab, KeyCode::Char('v')).await;
        match m.render_state() {
            ModeRenderState::Visual {
                anchor_col,
                cursor_col,
                ..
            } => {
                assert_eq!(anchor_col, Some(2));
                assert_eq!(cursor_col, 2);
            }
            other => panic!("expected Visual, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_y_without_anchor_copies_single_char_under_cursor() {
        let mut tab = make_tab(&["hello"]).await;
        let mut mode = make_mode("hello");
        mode.cursor_col = 1; // 'e'
        let (_, result) = press(mode, &mut tab, KeyCode::Char('y')).await;
        match result {
            KeyResult::CopyToClipboard(text) => assert_eq!(text, "e"),
            other => panic!("expected CopyToClipboard, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_esc_returns_normal_mode() {
        let mut tab = make_tab(&["hello"]).await;
        let mode = make_mode("hello");
        let (m, result) = press(mode, &mut tab, KeyCode::Esc).await;
        assert!(matches!(result, KeyResult::Handled));
        assert!(matches!(m.render_state(), ModeRenderState::Normal));
    }

    #[test]
    fn test_mode_bar_content_contains_filter_search_yank() {
        let mode = make_mode("hello");
        let content = mode.mode_bar_content(&Keybindings::default(), &Theme::default());
        let text: String = content.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("filter"), "missing filter in: {text}");
        assert!(text.contains("search"), "missing search in: {text}");
        assert!(text.contains("yank"), "missing yank in: {text}");
    }

    #[test]
    fn test_mode_bar_pending_shows_pending_message() {
        let mut mode = make_mode("hello");
        mode.pending_motion = Some(PendingMotion::FindForward);
        let content = mode.mode_bar_content(&Keybindings::default(), &Theme::default());
        let text: String = content.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("pending"), "missing pending in: {text}");
    }

    #[test]
    fn test_word_forward_from_start() {
        assert_eq!(word_forward("foo bar", 0), 4);
    }

    #[test]
    fn test_word_forward_at_end() {
        assert_eq!(word_forward("foo", 2), 2);
    }

    #[test]
    fn test_word_backward_from_second_word() {
        assert_eq!(word_backward("foo bar", 4), 0);
    }

    #[test]
    fn test_word_backward_at_start() {
        assert_eq!(word_backward("foo", 0), 0);
    }

    #[test]
    fn test_word_end_from_start() {
        assert_eq!(word_end("foo bar", 0), 2);
    }

    #[test]
    fn test_first_nonblank_with_leading_spaces() {
        assert_eq!(first_nonblank("  hello"), 2);
    }

    #[test]
    fn test_first_nonblank_no_leading_spaces() {
        assert_eq!(first_nonblank("hello"), 0);
    }

    #[test]
    fn test_first_nonblank_all_spaces() {
        assert_eq!(first_nonblank("   "), 0);
    }

    #[test]
    fn test_find_char_forward_finds_first() {
        assert_eq!(find_char_forward("hello", 0, 'l'), 2);
    }

    #[test]
    fn test_find_char_forward_finds_second() {
        assert_eq!(find_char_forward("hello", 2, 'l'), 3);
    }

    #[test]
    fn test_find_char_forward_not_found() {
        assert_eq!(find_char_forward("hello", 4, 'z'), 4);
    }

    #[test]
    fn test_find_char_backward_finds_last() {
        assert_eq!(find_char_backward("hello", 4, 'l'), 3);
    }

    #[test]
    fn test_find_char_backward_finds_prev() {
        assert_eq!(find_char_backward("hello", 3, 'l'), 2);
    }

    #[test]
    fn test_find_char_backward_not_found() {
        assert_eq!(find_char_backward("hello", 1, 'z'), 1);
    }

    #[test]
    fn test_till_char_forward_stops_before() {
        assert_eq!(till_char_forward("hello", 0, 'l'), 1); // 'l' at 2, stop at 1
    }

    #[test]
    fn test_till_char_forward_not_found() {
        assert_eq!(till_char_forward("hello", 0, 'z'), 0);
    }

    #[test]
    fn test_till_char_backward_stops_after() {
        assert_eq!(till_char_backward("hello", 4, 'e'), 2); // 'e' at 1, one after = 2
    }

    #[test]
    fn test_char_right_empty_string() {
        assert_eq!(char_right("", 0), 0);
    }

    #[test]
    fn test_word_forward_big() {
        assert_eq!(word_forward_big("foo.bar baz", 0), 8);
    }

    #[test]
    fn test_word_backward_big() {
        assert_eq!(word_backward_big("foo bar.baz", 10), 4);
    }

    #[test]
    fn test_apply_char_selection_single_span() {
        let line = Line::from("hello world");
        let result = apply_char_selection(line, 0, 4);
        let text: String = result.spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(text, "hello world");
        // First span should have REVERSED
        assert!(result.spans[0].style.add_modifier == Modifier::REVERSED);
        // Suffix should not have REVERSED
        assert!(
            !result.spans[1]
                .style
                .add_modifier
                .contains(Modifier::REVERSED)
        );
    }

    #[test]
    fn test_apply_char_selection_full_span() {
        let line = Line::from("hi");
        let result = apply_char_selection(line, 0, 1);
        assert_eq!(result.spans.len(), 1);
        assert!(
            result.spans[0]
                .style
                .add_modifier
                .contains(Modifier::REVERSED)
        );
    }

    #[test]
    fn test_apply_char_selection_out_of_range_noop() {
        let line = Line::from("hello");
        let result = apply_char_selection(line, 10, 20);
        // No selection overlap: single span, no REVERSED
        assert_eq!(result.spans.len(), 1);
        assert!(
            !result.spans[0]
                .style
                .add_modifier
                .contains(Modifier::REVERSED)
        );
    }

    // ── Line navigation ──────────────────────────────────────────────────────

    async fn make_multi_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;
        let mut tab = TabState::new(file_reader, log_manager, "test".to_string());
        tab.refresh_visible();
        tab
    }

    #[tokio::test]
    async fn test_j_scrolls_down_and_updates_line_text() {
        let mut tab = make_multi_tab(&["line0", "line1", "line2"]).await;
        tab.scroll.scroll_offset = 0;
        let mode = VisualMode::new("line0".to_string());
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('j'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 1);
        match m.render_state() {
            ModeRenderState::Visual {
                anchor_col,
                cursor_col,
                ..
            } => {
                assert_eq!(anchor_col, None);
                assert_eq!(cursor_col, 0);
            }
            other => panic!("expected Visual, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_k_scrolls_up_and_updates_line_text() {
        let mut tab = make_multi_tab(&["line0", "line1", "line2"]).await;
        tab.scroll.scroll_offset = 2;
        let mode = VisualMode::new("line2".to_string());
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('k'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 1);
        assert!(matches!(m.render_state(), ModeRenderState::Visual { .. }));
    }

    #[tokio::test]
    async fn test_j_clamps_cursor_col_to_new_line_length() {
        let mut tab = make_multi_tab(&["long line here", "hi"]).await;
        tab.scroll.scroll_offset = 0;
        let mut mode = VisualMode::new("long line here".to_string());
        mode.cursor_col = 10;
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('j'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 1);
        // "hi" has 2 chars; col 10 clamps to 1
        assert_eq!(cursor_col(m.as_ref()), 1);
    }

    #[tokio::test]
    async fn test_j_resets_anchor() {
        let mut tab = make_multi_tab(&["line0", "line1"]).await;
        tab.scroll.scroll_offset = 0;
        let mut mode = VisualMode::new("line0".to_string());
        mode.anchor_col = Some(2);
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('j'), KeyModifiers::NONE)
            .await;
        match m.render_state() {
            ModeRenderState::Visual { anchor_col, .. } => assert_eq!(anchor_col, None),
            other => panic!("expected Visual, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_k_at_top_stays_at_zero() {
        let mut tab = make_multi_tab(&["only"]).await;
        tab.scroll.scroll_offset = 0;
        let mode = VisualMode::new("only".to_string());
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('k'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 0);
        assert!(matches!(m.render_state(), ModeRenderState::Visual { .. }));
    }

    #[tokio::test]
    async fn test_capital_g_goes_to_last_line() {
        let mut tab = make_multi_tab(&["a", "b", "c"]).await;
        tab.scroll.scroll_offset = 0;
        let mode = VisualMode::new("a".to_string());
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('G'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 2);
        assert!(matches!(m.render_state(), ModeRenderState::Visual { .. }));
    }

    #[tokio::test]
    async fn test_gg_chord_goes_to_first_line() {
        let mut tab = make_multi_tab(&["a", "b", "c"]).await;
        tab.scroll.scroll_offset = 2;
        let mode = VisualMode::new("c".to_string());
        // first 'g' sets the flag
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('g'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 2); // not moved yet
        assert!(tab.interaction.g_key_pressed);
        // second 'g' jumps to top
        let (m2, _) = m
            .handle_key(&mut tab, KeyCode::Char('g'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 0);
        assert!(!tab.interaction.g_key_pressed);
        assert!(matches!(m2.render_state(), ModeRenderState::Visual { .. }));
    }

    #[tokio::test]
    async fn test_non_g_key_clears_g_flag() {
        let mut tab = make_multi_tab(&["a", "b"]).await;
        tab.scroll.scroll_offset = 1;
        tab.interaction.g_key_pressed = true;
        let mode = VisualMode::new("b".to_string());
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('h'), KeyModifiers::NONE)
            .await;
        assert!(!tab.interaction.g_key_pressed);
        assert!(matches!(m.render_state(), ModeRenderState::Visual { .. }));
    }

    #[tokio::test]
    async fn test_ctrl_d_half_page_down() {
        let mut tab = make_multi_tab(&["a", "b", "c", "d", "e"]).await;
        tab.scroll.scroll_offset = 0;
        tab.scroll.visible_height = 4;
        let mode = VisualMode::new("a".to_string());
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('d'), KeyModifiers::CONTROL)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 2); // half of 4 = 2
        assert!(matches!(m.render_state(), ModeRenderState::Visual { .. }));
    }

    #[tokio::test]
    async fn test_ctrl_u_half_page_up() {
        let mut tab = make_multi_tab(&["a", "b", "c", "d", "e"]).await;
        tab.scroll.scroll_offset = 4;
        tab.scroll.visible_height = 4;
        let mode = VisualMode::new("e".to_string());
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('u'), KeyModifiers::CONTROL)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 2);
        assert!(matches!(m.render_state(), ModeRenderState::Visual { .. }));
    }

    #[tokio::test]
    async fn test_mode_bar_contains_line_nav_hints() {
        let mode = make_mode("hello");
        let content = mode.mode_bar_content(&Keybindings::default(), &Theme::default());
        let text: String = content.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("line↓"), "missing line↓ in: {text}");
        assert!(text.contains("line↑"), "missing line↑ in: {text}");
    }

    #[tokio::test]
    async fn test_unrecognized_key_returns_ignored() {
        let mut tab = make_multi_tab(&["hello"]).await;
        let mode = VisualMode::new("hello".to_string());
        let (_, result) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::F(2), KeyModifiers::NONE)
            .await;
        assert!(matches!(result, KeyResult::Ignored));
    }

    #[tokio::test]
    async fn test_cursor_right_past_viewport_scrolls_right() {
        let line = "abcdefghij"; // 10 chars
        let mut tab = make_tab(&[line]).await;
        tab.display.wrap = false;
        tab.scroll.visible_width = 5;
        tab.scroll.horizontal_scroll = 0;
        let mut mode = make_mode(line);
        mode.cursor_col = 4; // at right edge of visible area
        let (m, _) = press(mode, &mut tab, KeyCode::Char('l')).await;
        assert_eq!(cursor_col(m.as_ref()), 5);
        // pad=min(3,(5-1)/2)=2; padded_right=5+1+2=8 > 0+5 → H=8-5=3
        assert_eq!(
            tab.scroll.horizontal_scroll, 3,
            "scroll should advance with padding"
        );
    }

    #[tokio::test]
    async fn test_cursor_left_past_viewport_scrolls_left() {
        let line = "abcdefghij";
        let mut tab = make_tab(&[line]).await;
        tab.display.wrap = false;
        tab.scroll.visible_width = 5;
        tab.scroll.horizontal_scroll = 3;
        let mut mode = make_mode(line);
        mode.cursor_col = 3; // at left edge of viewport
        let (m, _) = press(mode, &mut tab, KeyCode::Char('h')).await;
        assert_eq!(cursor_col(m.as_ref()), 2);
        // pad=2; 2 < 3+2=5 → H=2-2=0
        assert_eq!(
            tab.scroll.horizontal_scroll, 0,
            "scroll should retreat with padding"
        );
    }

    #[tokio::test]
    async fn test_cursor_within_viewport_does_not_scroll() {
        let line = "abcdefghij";
        let mut tab = make_tab(&[line]).await;
        tab.display.wrap = false;
        tab.scroll.visible_width = 5;
        tab.scroll.horizontal_scroll = 2;
        let mut mode = make_mode(line);
        mode.cursor_col = 3;
        let (m, _) = press(mode, &mut tab, KeyCode::Char('l')).await;
        assert_eq!(cursor_col(m.as_ref()), 4);
        assert_eq!(tab.scroll.horizontal_scroll, 2, "scroll should not change");
    }

    #[tokio::test]
    async fn test_end_of_line_scrolls_viewport_to_show_cursor() {
        let line = "abcdefghij";
        let mut tab = make_tab(&[line]).await;
        tab.display.wrap = false;
        tab.scroll.visible_width = 5;
        tab.scroll.horizontal_scroll = 0;
        let mode = make_mode(line);
        let (m, _) = press(mode, &mut tab, KeyCode::Char('$')).await;
        assert_eq!(cursor_col(m.as_ref()), 9);
        assert!(
            tab.scroll.horizontal_scroll + tab.scroll.visible_width > 9,
            "cursor must be within viewport after $"
        );
    }

    #[tokio::test]
    async fn test_start_of_line_resets_scroll() {
        let line = "abcdefghij";
        let mut tab = make_tab(&[line]).await;
        tab.display.wrap = false;
        tab.scroll.visible_width = 5;
        tab.scroll.horizontal_scroll = 7;
        let mut mode = make_mode(line);
        mode.cursor_col = 9;
        let (_, _) = press(mode, &mut tab, KeyCode::Char('0')).await;
        assert_eq!(
            tab.scroll.horizontal_scroll, 0,
            "scroll should reset to 0 at line start"
        );
    }

    #[tokio::test]
    async fn test_wrap_mode_does_not_adjust_scroll() {
        let line = "abcdefghij";
        let mut tab = make_tab(&[line]).await;
        tab.display.wrap = true;
        tab.scroll.visible_width = 5;
        tab.scroll.horizontal_scroll = 0;
        let mut mode = make_mode(line);
        mode.cursor_col = 4;
        let (m, _) = press(mode, &mut tab, KeyCode::Char('l')).await;
        assert_eq!(cursor_col(m.as_ref()), 5);
        assert_eq!(
            tab.scroll.horizontal_scroll, 0,
            "wrap mode should not adjust scroll"
        );
    }

    #[test]
    fn test_word_bounds_at_middle_of_word() {
        assert_eq!(word_bounds_at("hello world", 3), Some((0, 4)));
    }

    #[test]
    fn test_word_bounds_at_start_of_word() {
        assert_eq!(word_bounds_at("hello world", 0), Some((0, 4)));
    }

    #[test]
    fn test_word_bounds_at_end_of_word() {
        assert_eq!(word_bounds_at("hello world", 4), Some((0, 4)));
    }

    #[test]
    fn test_word_bounds_at_second_word() {
        assert_eq!(word_bounds_at("hello world", 6), Some((6, 10)));
    }

    #[test]
    fn test_word_bounds_at_whitespace_returns_none() {
        assert_eq!(word_bounds_at("hello world", 5), None);
    }

    #[test]
    fn test_word_bounds_at_out_of_range_returns_none() {
        assert_eq!(word_bounds_at("hello", 10), None);
    }

    #[test]
    fn test_word_bounds_at_underscore_included() {
        assert_eq!(word_bounds_at("foo_bar baz", 4), Some((0, 6)));
    }

    #[test]
    fn test_word_bounds_at_dash_included() {
        assert_eq!(word_bounds_at("foo-bar baz", 4), Some((0, 6)));
    }

    #[test]
    fn test_word_bounds_at_uuid() {
        let uuid = "550e8400-e29b-41d4-a716-446655440000";
        let end = uuid.chars().count() - 1;
        assert_eq!(word_bounds_at(uuid, 10), Some((0, end)));
    }

    #[tokio::test]
    async fn test_line_change_scrolls_cursor_into_view() {
        let line0 = "abcdefghijklmno"; // 15 chars
        let line1 = "xyz"; // 3 chars
        let mut tab = make_multi_tab(&[line0, line1]).await;
        tab.scroll.scroll_offset = 0;
        tab.display.wrap = false;
        tab.scroll.visible_width = 5;
        tab.scroll.horizontal_scroll = 10;
        let mut mode = VisualMode::new(line0.to_string());
        mode.cursor_col = 12;
        // move down — cursor clamps to col 2 on "xyz", which is left of h_scroll=10
        let (m, _) = Box::new(mode)
            .handle_key(&mut tab, KeyCode::Char('j'), KeyModifiers::NONE)
            .await;
        assert_eq!(tab.scroll.scroll_offset, 1);
        assert_eq!(cursor_col(m.as_ref()), 2);
        assert!(
            tab.scroll.horizontal_scroll <= 2,
            "scroll should have moved left to show cursor, got {}",
            tab.scroll.horizontal_scroll
        );
    }
}