dlt-tui 1.1.0

A fast, keyboard-centric TUI viewer for Automotive DLT (Diagnostic Log and Trace) files
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
use crate::explorer::{self, FileEntry};
use crate::parser::DltMessage;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{
    Arc, Mutex,
    atomic::{AtomicUsize, Ordering},
};

#[derive(Debug, PartialEq, Clone)]
pub enum AppScreen {
    Explorer,
    LogViewer,
    LogDetail,
}

use serde::{Deserialize, Serialize};

#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct Filter {
    pub min_level: Option<crate::parser::LogLevel>,
    pub app_id: Option<String>,
    pub ctx_id: Option<String>,
    pub text: Option<String>,
}

#[derive(Debug, PartialEq, Clone)]
pub enum FilterInputMode {
    Text,
    AppId,
    CtxId,
    MinLevel,
}

#[derive(Debug, PartialEq, Clone)]
pub struct LogEntry {
    pub message: DltMessage,
    pub source_file: Option<PathBuf>,
    pub source_index: usize,
}

impl LogEntry {
    pub fn new(message: DltMessage, source_file: Option<PathBuf>, source_index: usize) -> Self {
        Self {
            message,
            source_file,
            source_index,
        }
    }

    pub fn source_name(&self) -> &str {
        self.source_file
            .as_deref()
            .and_then(Path::file_name)
            .and_then(|name| name.to_str())
            .unwrap_or("-")
    }
}

pub struct App {
    pub screen: AppScreen,
    pub explorer_items: Vec<FileEntry>,
    pub explorer_selected_index: usize,
    pub logs: Vec<LogEntry>,
    pub filtered_log_indices: Vec<usize>,
    pub logs_selected_index: usize,
    pub filter: Filter,
    pub filter_input_mode: Option<FilterInputMode>,
    pub filter_input: String,
    pub error_message: Option<String>,
    pub info_message: Option<String>,
    pub should_quit: bool,
    pub log_receiver: Option<std::sync::mpsc::Receiver<LogEntry>>,
    pub is_loading: bool,
    pub connection_info: Option<String>,
    pub auto_scroll: bool,
    pub horizontal_scroll: usize,
    pub show_time_delta: bool,
    pub skipped_bytes: usize,
    skipped_bytes_shared: Option<Arc<AtomicUsize>>,
    tcp_error: Option<Arc<Mutex<Option<String>>>>,
    /// BUG-1: Generation counter incremented on every apply_filter() call.
    /// on_tick() only appends new indices if filter_generation hasn't changed.
    filter_generation: u64,
}

impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}

impl App {
    pub fn new() -> Self {
        Self {
            screen: AppScreen::Explorer,
            explorer_items: vec![],
            explorer_selected_index: 0,
            logs: vec![],
            filtered_log_indices: vec![],
            logs_selected_index: 0,
            filter: Filter::default(),
            filter_input_mode: None,
            filter_input: String::new(),
            error_message: None,
            info_message: None,
            should_quit: false,
            log_receiver: None,
            is_loading: false,
            connection_info: None,
            auto_scroll: false,
            horizontal_scroll: 0,
            show_time_delta: false,
            skipped_bytes: 0,
            skipped_bytes_shared: None,
            tcp_error: None,
            filter_generation: 0,
        }
    }

    pub fn load_filter_config(&mut self) {
        let path = std::path::Path::new(".dlt-tui.toml");
        // SEC-4: check file size before reading (1MB limit)
        if let Ok(meta) = std::fs::metadata(path)
            && meta.len() > 1_048_576
        {
            self.error_message = Some("Config file too large (>1MB)".to_string());
            return;
        }
        if path.exists()
            && let Ok(content) = std::fs::read_to_string(path)
            && let Ok(filter) = toml::from_str::<Filter>(&content)
        {
            self.filter = filter;
            self.info_message = Some("Loaded filter from .dlt-tui.toml".to_string());
        }
    }

    pub fn save_filter_config(&mut self) {
        if let Ok(content) = toml::to_string(&self.filter) {
            if std::fs::write(".dlt-tui.toml", content).is_ok() {
                self.info_message = Some("Saved filter to .dlt-tui.toml".to_string());
            } else {
                self.error_message = Some("Failed to save filter config".to_string());
            }
        } else {
            self.error_message = Some("Failed to serialize filter".to_string());
        }
    }

    pub fn load_directory(&mut self, path: &Path) -> std::io::Result<()> {
        let mut entries = explorer::list_directory(path)?;

        // Sort first: directories first, then alphabetically by name
        entries.sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then(a.name.cmp(&b.name)));

        // Insert ".." AFTER sorting so it always stays at position 0
        if let Some(parent) = path.parent() {
            entries.insert(
                0,
                FileEntry {
                    name: "..".to_string(),
                    is_dir: true,
                    path: parent.to_path_buf(),
                },
            );
        }

        self.explorer_items = entries;
        self.explorer_selected_index = 0;
        Ok(())
    }

    pub fn load_files(&mut self, paths: Vec<PathBuf>) -> std::io::Result<()> {
        self.logs.clear();
        self.filtered_log_indices.clear();
        self.logs_selected_index = 0;
        self.load_filter_config();
        self.is_loading = true;
        self.horizontal_scroll = 0;
        self.show_time_delta = false;
        self.skipped_bytes = 0;

        let (tx, rx) = std::sync::mpsc::channel();
        self.log_receiver = Some(rx);

        let skipped_shared = Arc::new(AtomicUsize::new(0));
        self.skipped_bytes_shared = Some(Arc::clone(&skipped_shared));

        std::thread::spawn(move || {
            for (source_index, path) in paths.into_iter().enumerate() {
                let stream = match crate::fs_reader::open_dlt_stream(&path) {
                    Ok(s) => s,
                    Err(_) => continue,
                };

                let source_file = path.clone();
                let send_result = crate::tcp_client::stream_from_reader_with_handler(
                    stream,
                    Arc::clone(&skipped_shared),
                    |message| {
                        tx.send(LogEntry::new(
                            message,
                            Some(source_file.clone()),
                            source_index,
                        ))
                        .is_ok()
                    },
                )
                .is_err();

                if send_result {
                    continue;
                }
            }
        });

        self.apply_filter();
        self.screen = AppScreen::LogViewer;
        Ok(())
    }

    fn check_log_against_filter(
        log: &DltMessage,
        filter: &Filter,
        regex: Option<&regex::Regex>,
    ) -> bool {
        if let Some(ref min_level) = filter.min_level {
            // Determine if log_level is severe enough or matches
            // Simplification for MVP: We just check exact equality or we can skip for now
            // Actually, let's just do exact matching or implement a partial ord on LogLevel
            // Since LogLevel isn't Ord yet, we will compare them by converting to an integer.
            let level_val = |l: &crate::parser::LogLevel| match l {
                crate::parser::LogLevel::Fatal => 1,
                crate::parser::LogLevel::Error => 2,
                crate::parser::LogLevel::Warn => 3,
                crate::parser::LogLevel::Info => 4,
                crate::parser::LogLevel::Debug => 5,
                crate::parser::LogLevel::Verbose => 6,
                crate::parser::LogLevel::Unknown(_) => 7,
            };

            let target_val = level_val(min_level);
            let current_val = log.log_level.as_ref().map(level_val).unwrap_or(7);

            if current_val > target_val {
                return false;
            }
        }

        if let Some(ref text) = filter.text {
            if let Some(re) = regex {
                if !re.is_match(&log.payload_text) {
                    return false;
                }
            } else if !log
                .payload_text
                .to_lowercase()
                .contains(&text.to_lowercase())
            {
                return false;
            }
        }

        if let Some(ref app_id) = filter.app_id {
            let matches = log
                .apid
                .as_deref()
                .map(|s| s.eq_ignore_ascii_case(app_id))
                .unwrap_or(false);
            if !matches {
                return false;
            }
        }

        if let Some(ref ctx_id) = filter.ctx_id {
            let matches = log
                .ctid
                .as_deref()
                .map(|s| s.eq_ignore_ascii_case(ctx_id))
                .unwrap_or(false);
            if !matches {
                return false;
            }
        }

        true
    }

    pub fn apply_filter(&mut self) {
        self.filtered_log_indices.clear();

        // BUG-1: bump generation so on_tick won't append with stale filter
        self.filter_generation = self.filter_generation.wrapping_add(1);

        // Compile regex once if text filter exists
        // SEC-1: size_limit prevents ReDoS from malicious patterns
        let text_regex = self.filter.text.as_ref().and_then(|text| {
            regex::RegexBuilder::new(text)
                .case_insensitive(true)
                .size_limit(256 * 1024) // 256KB compiled regex limit
                .build()
                .ok() // If invalid regex, we will fallback to plain string search
        });

        for (idx, log) in self.logs.iter().enumerate() {
            if Self::check_log_against_filter(&log.message, &self.filter, text_regex.as_ref()) {
                self.filtered_log_indices.push(idx);
            }
        }

        self.sort_filtered_indices();
        self.logs_selected_index = 0;
    }

    fn sort_filtered_indices(&mut self) {
        self.filtered_log_indices.sort_by_key(|&idx| {
            let entry = &self.logs[idx];
            (
                entry.message.timestamp_us == 0,
                entry.message.timestamp_us,
                entry.source_index,
                idx,
            )
        });
    }

    pub fn source_counts(&self) -> Vec<(String, usize)> {
        let mut counts = BTreeMap::new();
        for &idx in &self.filtered_log_indices {
            let source = self.logs[idx].source_name().to_string();
            *counts.entry(source).or_insert(0) += 1;
        }
        counts.into_iter().collect()
    }

    pub fn ctx_counts(&self) -> Vec<(String, usize)> {
        let mut counts = BTreeMap::new();
        for &idx in &self.filtered_log_indices {
            let ctx = self.logs[idx]
                .message
                .ctid
                .as_deref()
                .unwrap_or("-")
                .to_string();
            *counts.entry(ctx).or_insert(0) += 1;
        }
        counts.into_iter().collect()
    }

    pub fn selected_entry(&self) -> Option<&LogEntry> {
        self.filtered_log_indices
            .get(self.logs_selected_index)
            .map(|&idx| &self.logs[idx])
    }

    pub fn on_home(&mut self) {
        match self.screen {
            AppScreen::Explorer => self.explorer_selected_index = 0,
            AppScreen::LogViewer | AppScreen::LogDetail => self.logs_selected_index = 0,
        }
    }

    pub fn on_end(&mut self) {
        match self.screen {
            AppScreen::Explorer => {
                if !self.explorer_items.is_empty() {
                    self.explorer_selected_index = self.explorer_items.len() - 1;
                }
            }
            AppScreen::LogViewer | AppScreen::LogDetail => {
                if !self.filtered_log_indices.is_empty() {
                    self.logs_selected_index = self.filtered_log_indices.len() - 1;
                }
            }
        }
    }

    pub fn on_right(&mut self, amount: usize) {
        if self.screen == AppScreen::LogViewer {
            self.horizontal_scroll = self.horizontal_scroll.saturating_add(amount);
        }
    }

    pub fn on_left(&mut self, amount: usize) {
        if self.screen == AppScreen::LogViewer {
            self.horizontal_scroll = self.horizontal_scroll.saturating_sub(amount);
        }
    }

    pub fn on_tick(&mut self) {
        if let Some(rx) = &self.log_receiver {
            let mut added = false;
            let current_len = self.logs.len();
            let current_gen = self.filter_generation;

            loop {
                match rx.try_recv() {
                    Ok(msg) => {
                        self.logs.push(msg);
                        added = true;
                    }
                    Err(std::sync::mpsc::TryRecvError::Empty) => {
                        break;
                    }
                    Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                        self.is_loading = false;
                        // BUG-5: Check for TCP connection error from background thread
                        if let Some(ref tcp_err) = self.tcp_error
                            && let Ok(guard) = tcp_err.lock()
                            && let Some(ref err_msg) = *guard
                        {
                            self.error_message =
                                Some(format!("TCP connection failed: {}", err_msg));
                        }
                        self.tcp_error = None;
                        if self.connection_info.is_some() {
                            // If no error was set and no logs received, show a clean disconnect message
                            if self.error_message.is_none() && self.logs.is_empty() {
                                self.error_message =
                                    Some("TCP connection ended with no data".to_string());
                            }
                            self.connection_info = None;
                        }
                        // Read skipped bytes from the shared atomic
                        if let Some(ref shared) = self.skipped_bytes_shared {
                            self.skipped_bytes = shared.load(Ordering::Relaxed);
                        }
                        self.skipped_bytes_shared = None;
                        self.log_receiver = None;
                        break;
                    }
                }
            }

            if added {
                let text_regex = self.filter.text.as_ref().and_then(|text| {
                    regex::RegexBuilder::new(text)
                        .case_insensitive(true)
                        .size_limit(256 * 1024)
                        .build()
                        .ok()
                });

                // BUG-1: Only append incrementally if filter hasn't been reapplied
                // since we captured current_gen. If it changed, apply_filter()
                // already rebuilt the full index, so skip incremental append.
                if self.filter_generation == current_gen {
                    for idx in current_len..self.logs.len() {
                        let log = &self.logs[idx].message;
                        if Self::check_log_against_filter(log, &self.filter, text_regex.as_ref()) {
                            self.filtered_log_indices.push(idx);
                        }
                    }
                    self.sort_filtered_indices();
                }

                // Auto-scroll: keep cursor at the end when in tail mode
                if self.auto_scroll && !self.filtered_log_indices.is_empty() {
                    self.logs_selected_index = self.filtered_log_indices.len() - 1;
                }
            }
        }
    }

    pub fn on_up(&mut self) {
        match self.screen {
            AppScreen::Explorer => {
                if self.explorer_selected_index > 0 {
                    self.explorer_selected_index -= 1;
                }
            }
            AppScreen::LogViewer | AppScreen::LogDetail => {
                if self.logs_selected_index > 0 {
                    self.logs_selected_index -= 1;
                }
            }
        }
    }

    pub fn on_down(&mut self) {
        match self.screen {
            AppScreen::Explorer => {
                if !self.explorer_items.is_empty()
                    && self.explorer_selected_index < self.explorer_items.len() - 1
                {
                    self.explorer_selected_index += 1;
                }
            }
            AppScreen::LogViewer | AppScreen::LogDetail => {
                if !self.filtered_log_indices.is_empty()
                    && self.logs_selected_index < self.filtered_log_indices.len() - 1
                {
                    self.logs_selected_index += 1;
                }
            }
        }
    }

    /// Move selection down by `page_size` rows (full page scroll)
    pub fn on_page_down(&mut self, page_size: usize) {
        if page_size == 0 {
            return;
        }
        match self.screen {
            AppScreen::Explorer => {
                if !self.explorer_items.is_empty() {
                    let max = self.explorer_items.len() - 1;
                    self.explorer_selected_index =
                        (self.explorer_selected_index + page_size).min(max);
                }
            }
            AppScreen::LogViewer | AppScreen::LogDetail => {
                if !self.filtered_log_indices.is_empty() {
                    let max = self.filtered_log_indices.len() - 1;
                    self.logs_selected_index = (self.logs_selected_index + page_size).min(max);
                }
            }
        }
    }

    /// Move selection up by `page_size` rows (full page scroll)
    pub fn on_page_up(&mut self, page_size: usize) {
        if page_size == 0 {
            return;
        }
        match self.screen {
            AppScreen::Explorer => {
                self.explorer_selected_index =
                    self.explorer_selected_index.saturating_sub(page_size);
            }
            AppScreen::LogViewer | AppScreen::LogDetail => {
                self.logs_selected_index = self.logs_selected_index.saturating_sub(page_size);
            }
        }
    }

    /// Move selection down by half a page
    pub fn on_half_page_down(&mut self, page_size: usize) {
        self.on_page_down(page_size / 2);
    }

    /// Move selection up by half a page
    pub fn on_half_page_up(&mut self, page_size: usize) {
        self.on_page_up(page_size / 2);
    }

    pub fn on_key_q(&mut self) {
        self.should_quit = true;
    }

    /// Handle a key event. `page_size` is the number of visible rows (from terminal height).
    pub fn handle_key(&mut self, key: crossterm::event::KeyEvent, page_size: usize) {
        use crossterm::event::{KeyCode, KeyModifiers};

        // Dismiss error or info on any key press
        if self.error_message.is_some() || self.info_message.is_some() {
            self.error_message = None;
            self.info_message = None;
            return;
        }

        // Filter input mode: capture text input for active filter
        if let Some(mode) = self.filter_input_mode.clone() {
            match key.code {
                KeyCode::Enter => {
                    self.filter_input_mode = None;
                    let input = if self.filter_input.is_empty() {
                        None
                    } else {
                        Some(self.filter_input.clone())
                    };
                    // UX-4: feedback when filter is cleared
                    let was_cleared = input.is_none();
                    match mode {
                        FilterInputMode::Text => self.filter.text = input,
                        FilterInputMode::AppId => self.filter.app_id = input,
                        FilterInputMode::CtxId => self.filter.ctx_id = input,
                        FilterInputMode::MinLevel => {
                            self.filter.min_level = match self.filter_input.to_lowercase().as_str()
                            {
                                "f" | "fatal" => Some(crate::parser::LogLevel::Fatal),
                                "e" | "error" => Some(crate::parser::LogLevel::Error),
                                "w" | "warn" => Some(crate::parser::LogLevel::Warn),
                                "i" | "info" => Some(crate::parser::LogLevel::Info),
                                "d" | "debug" => Some(crate::parser::LogLevel::Debug),
                                "v" | "verbose" => Some(crate::parser::LogLevel::Verbose),
                                _ => None,
                            };
                        }
                    }
                    self.apply_filter();
                    if was_cleared {
                        self.info_message = Some("Filter cleared".to_string());
                    }
                }
                KeyCode::Esc => {
                    // Cancel: exit input mode without changing the filter
                    self.filter_input_mode = None;
                    self.filter_input.clear();
                }
                KeyCode::Char(c) if self.filter_input.len() < 1024 => {
                    // SEC-5: limit filter input length to prevent memory abuse
                    self.filter_input.push(c);
                }
                KeyCode::Char(_) => {}
                KeyCode::Backspace => {
                    self.filter_input.pop();
                }
                _ => {}
            }
            return;
        }

        // Normal mode key handling
        match key.code {
            KeyCode::Char('q') => match self.screen {
                AppScreen::Explorer => self.on_key_q(),
                AppScreen::LogViewer => self.screen = AppScreen::Explorer,
                // UX-6: q on LogDetail goes back to LogViewer
                AppScreen::LogDetail => self.screen = AppScreen::LogViewer,
            },
            KeyCode::Char('b') if self.screen == AppScreen::Explorer => {
                // BUG-2: bounds check before accessing explorer_items
                if let Some(selected) = self.explorer_items.get(self.explorer_selected_index) {
                    let dir_path = if selected.is_dir {
                        selected.path.clone()
                    } else {
                        selected
                            .path
                            .parent()
                            .unwrap_or(&selected.path)
                            .to_path_buf()
                    };

                    if let Ok(mut entries) = crate::explorer::list_directory(&dir_path) {
                        entries.sort_by(|a, b| a.name.cmp(&b.name));
                        let files: Vec<PathBuf> = entries
                            .into_iter()
                            .filter(|e| {
                                !e.is_dir
                                    && (e.name.ends_with(".dlt")
                                        || e.name.ends_with(".dlt.gz")
                                        || e.name.ends_with(".dlt.zip"))
                            })
                            .map(|e| e.path)
                            .collect();

                        if files.is_empty() {
                            self.error_message =
                                Some("No DLT files found in directory".to_string());
                        } else {
                            self.info_message =
                                Some(format!("Batch loading {} files...", files.len()));
                            if let Err(e) = self.load_files(files) {
                                self.error_message = Some(format!("Batch load failed: {}", e));
                            }
                        }
                    } else {
                        self.error_message =
                            Some("Failed to read directory for batch load".to_string());
                    }
                }
            }
            KeyCode::Char('E') if self.screen == AppScreen::LogViewer => {
                self.on_export();
            }
            KeyCode::Char('S') if self.screen == AppScreen::LogViewer => {
                self.save_filter_config();
            }
            KeyCode::Char('L') if self.screen == AppScreen::LogViewer => {
                self.load_filter_config();
                self.apply_filter();
            }
            KeyCode::Char('t') if self.screen == AppScreen::LogViewer => {
                self.show_time_delta = !self.show_time_delta;
            }
            KeyCode::Char('j') | KeyCode::Down => self.on_down(),
            KeyCode::Char('k') | KeyCode::Up => self.on_up(),
            KeyCode::Left => {
                if key.modifiers.contains(KeyModifiers::SHIFT) {
                    self.on_left(10);
                } else {
                    self.on_left(1);
                }
            }
            KeyCode::Right => {
                if key.modifiers.contains(KeyModifiers::SHIFT) {
                    self.on_right(10);
                } else {
                    self.on_right(1);
                }
            }
            KeyCode::Char('g') | KeyCode::Home => self.on_home(),
            KeyCode::Char('G') | KeyCode::End => self.on_end(),
            // Page scrolling
            KeyCode::Char('f') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.on_page_down(page_size);
            }
            KeyCode::PageDown => self.on_page_down(page_size),
            KeyCode::Char('b') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.on_page_up(page_size);
            }
            KeyCode::PageUp => self.on_page_up(page_size),
            KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.on_half_page_down(page_size);
            }
            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.on_half_page_up(page_size);
            }
            KeyCode::Char('/') if self.screen == AppScreen::LogViewer => {
                self.filter_input_mode = Some(FilterInputMode::Text);
                self.filter_input.clear();
            }
            KeyCode::Char('l') if self.screen == AppScreen::LogViewer => {
                self.filter_input_mode = Some(FilterInputMode::MinLevel);
                self.filter_input.clear();
            }
            KeyCode::Char('a') if self.screen == AppScreen::LogViewer => {
                self.filter_input_mode = Some(FilterInputMode::AppId);
                self.filter_input.clear();
            }
            KeyCode::Char('c') if self.screen == AppScreen::LogViewer => {
                self.filter_input_mode = Some(FilterInputMode::CtxId);
                self.filter_input.clear();
            }
            KeyCode::Char('C') if self.screen == AppScreen::LogViewer => {
                self.filter = Filter::default();
                self.apply_filter();
            }
            KeyCode::Char('F') if self.screen == AppScreen::LogViewer => {
                self.auto_scroll = !self.auto_scroll;
            }
            KeyCode::Enter => {
                if self.screen == AppScreen::Explorer {
                    // BUG-2: bounds check before accessing explorer_items
                    if let Some(selected) = self.explorer_items.get(self.explorer_selected_index) {
                        if selected.is_dir {
                            let path_clone = selected.path.clone();
                            if let Err(e) = self.load_directory(&path_clone) {
                                self.error_message =
                                    Some(format!("Could not open directory: {}", e));
                            }
                        } else {
                            let path_clone = selected.path.clone();
                            if let Err(e) = self.load_files(vec![path_clone]) {
                                self.error_message = Some(format!("Could not open file: {}", e));
                            }
                        }
                    }
                } else if self.screen == AppScreen::LogViewer
                    && !self.filtered_log_indices.is_empty()
                {
                    self.screen = AppScreen::LogDetail;
                }
            }
            KeyCode::Esc => {
                // UX-1: Esc consistently means "go back" — on Explorer, quit the app
                if self.screen == AppScreen::Explorer {
                    self.on_key_q();
                } else if self.screen == AppScreen::LogViewer {
                    self.screen = AppScreen::Explorer;
                } else if self.screen == AppScreen::LogDetail {
                    self.screen = AppScreen::LogViewer;
                }
            }
            _ => {}
        }
    }

    pub fn connect_tcp(&mut self, addr: &str) {
        self.logs.clear();
        self.filtered_log_indices.clear();
        self.logs_selected_index = 0;
        self.load_filter_config();
        self.is_loading = true;
        self.auto_scroll = true;
        self.horizontal_scroll = 0;
        self.show_time_delta = false;
        self.connection_info = Some(addr.to_string());

        let (tx, rx) = std::sync::mpsc::channel();
        self.log_receiver = Some(rx);

        // BUG-5: shared error state so background thread can report connection failures
        let tcp_error = Arc::new(Mutex::new(None));
        self.tcp_error = Some(Arc::clone(&tcp_error));

        let addr_owned = addr.to_string();
        std::thread::spawn(move || {
            if let Err(e) =
                crate::tcp_client::stream_from_tcp_with_handler(&addr_owned, |message| {
                    tx.send(LogEntry::new(message, None, 0)).is_ok()
                })
                && let Ok(mut guard) = tcp_error.lock()
            {
                *guard = Some(e.to_string());
            }
        });

        self.screen = AppScreen::LogViewer;
    }

    pub fn on_export(&mut self) {
        if self.filtered_log_indices.is_empty() {
            self.error_message = Some("No logs to export".to_string());
            return;
        }

        let now = chrono::Local::now();
        let base = format!("dlt_export_{}", now.format("%Y%m%d_%H%M%S"));

        // SEC-2: avoid overwriting existing files by appending a suffix
        let filename = if !std::path::Path::new(&format!("{}.txt", base)).exists() {
            format!("{}.txt", base)
        } else {
            let mut i = 1;
            loop {
                let candidate = format!("{}_{}.txt", base, i);
                if !std::path::Path::new(&candidate).exists() {
                    break candidate;
                }
                i += 1;
                if i > 999 {
                    self.error_message = Some("Too many export files".to_string());
                    return;
                }
            }
        };

        // Collect references to the currently filtered DltMessages
        let filtered_logs: Vec<&crate::parser::DltMessage> = self
            .filtered_log_indices
            .iter()
            .map(|&i| &self.logs[i].message)
            .collect();

        match crate::exporter::export_to_txt(&filtered_logs, &filename) {
            Ok(_) => {
                self.info_message = Some(format!(
                    "Exported {} logs to {}",
                    filtered_logs.len(),
                    filename
                ));
            }
            Err(e) => {
                self.error_message = Some(format!("Export failed: {}", e));
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use std::path::PathBuf;

    fn build_mock_app_with_explorer_files() -> App {
        App {
            screen: AppScreen::Explorer,
            explorer_items: vec![
                FileEntry {
                    name: "folder1".to_string(),
                    is_dir: true,
                    path: PathBuf::from("folder1"),
                },
                FileEntry {
                    name: "fileA.dlt".to_string(),
                    is_dir: false,
                    path: PathBuf::from("fileA.dlt"),
                },
                FileEntry {
                    name: "fileB.dlt".to_string(),
                    is_dir: false,
                    path: PathBuf::from("fileB.dlt"),
                },
            ],
            ..App::new()
        }
    }

    fn build_mock_app_with_logs(count: usize) -> App {
        let mut app = App::new();
        app.screen = AppScreen::LogViewer;
        for i in 0..count {
            app.logs.push(LogEntry::new(
                DltMessage {
                    timestamp_us: 1000 + i as u64,
                    ecu_id: format!("ECU{}", i),
                    apid: None,
                    ctid: None,
                    log_level: None,
                    payload_text: format!("Log message {}", i),
                    payload_raw: format!("Log message {}", i).into_bytes(),
                },
                None,
                0,
            ));
        }
        app.apply_filter();
        app
    }

    fn mock_entry(
        timestamp_us: u64,
        payload_text: &str,
        source_file: Option<&str>,
        source_index: usize,
    ) -> LogEntry {
        LogEntry::new(
            DltMessage {
                timestamp_us,
                ecu_id: "ECU1".to_string(),
                apid: Some("APP1".to_string()),
                ctid: Some("CTX1".to_string()),
                log_level: Some(crate::parser::LogLevel::Info),
                payload_text: payload_text.to_string(),
                payload_raw: payload_text.as_bytes().to_vec(),
            },
            source_file.map(PathBuf::from),
            source_index,
        )
    }

    #[test]
    fn test_app_initialization() {
        let app = App::new();
        assert_eq!(app.screen, AppScreen::Explorer);
        assert_eq!(app.explorer_selected_index, 0);
        assert_eq!(app.logs_selected_index, 0);
        assert!(!app.should_quit);
    }

    #[test]
    fn test_quit_on_q() {
        let mut app = App::new();
        app.on_key_q();
        assert!(app.should_quit);
    }

    #[test]
    fn test_explorer_up_down_bounds() {
        let mut app = build_mock_app_with_explorer_files();

        // Initial state index: 0. Trying to go UP shouldn't underflow.
        app.on_up();
        assert_eq!(app.explorer_selected_index, 0);

        // Move down within bounds
        app.on_down();
        assert_eq!(app.explorer_selected_index, 1);

        app.on_down();
        assert_eq!(app.explorer_selected_index, 2);

        // Move down out of bounds, should cap at length - 1 (i.e. 2)
        app.on_down();
        assert_eq!(app.explorer_selected_index, 2);

        // Move back up
        app.on_up();
        assert_eq!(app.explorer_selected_index, 1);
    }

    #[test]
    fn test_log_viewer_up_down_bounds() {
        let mut app = build_mock_app_with_logs(5);

        // Test list traversal for logs
        app.on_up();
        assert_eq!(app.logs_selected_index, 0);

        app.on_down();
        assert_eq!(app.logs_selected_index, 1);

        // move multiple down
        app.on_down();
        app.on_down();
        app.on_down();
        app.on_down();
        // Capped at 4
        assert_eq!(app.logs_selected_index, 4);
        // test home and end
        app.on_home();
        assert_eq!(app.logs_selected_index, 0);

        app.on_end();
        assert_eq!(app.logs_selected_index, 4);
    }

    #[test]
    fn test_apply_filter_orders_logs_by_timestamp_across_sources() {
        let mut app = App::new();
        app.screen = AppScreen::LogViewer;
        app.logs
            .push(mock_entry(3_000, "third", Some("ctx_a.dlt"), 0));
        app.logs
            .push(mock_entry(1_000, "first", Some("ctx_b.dlt"), 1));
        app.logs
            .push(mock_entry(2_000, "second", Some("ctx_a.dlt"), 0));

        app.apply_filter();

        let ordered_payloads: Vec<&str> = app
            .filtered_log_indices
            .iter()
            .map(|&idx| app.logs[idx].message.payload_text.as_str())
            .collect();
        assert_eq!(ordered_payloads, vec!["first", "second", "third"]);
    }

    #[test]
    fn test_log_entry_source_name_uses_file_name() {
        let entry = mock_entry(1_000, "payload", Some("/tmp/logs/ctx_a.dlt"), 0);

        assert_eq!(entry.source_name(), "ctx_a.dlt");
    }

    #[test]
    fn test_source_and_ctx_counts_use_filtered_logs() {
        let mut app = App::new();
        app.screen = AppScreen::LogViewer;
        app.logs
            .push(mock_entry(1_000, "keep one", Some("ctx_a.dlt"), 0));
        app.logs
            .push(mock_entry(2_000, "drop me", Some("ctx_b.dlt"), 1));
        app.logs
            .push(mock_entry(3_000, "keep two", Some("ctx_a.dlt"), 0));
        app.filter.text = Some("keep".to_string());

        app.apply_filter();

        assert_eq!(app.source_counts(), vec![("ctx_a.dlt".to_string(), 2)]);
        assert_eq!(app.ctx_counts(), vec![("CTX1".to_string(), 2)]);
    }

    // ==================== Page scrolling tests ====================

    #[test]
    fn test_page_down_log_viewer() {
        let mut app = build_mock_app_with_logs(100);
        assert_eq!(app.logs_selected_index, 0);

        // Full page down
        app.on_page_down(20);
        assert_eq!(app.logs_selected_index, 20);

        // Another page
        app.on_page_down(20);
        assert_eq!(app.logs_selected_index, 40);
    }

    #[test]
    fn test_page_down_clamps_at_end() {
        let mut app = build_mock_app_with_logs(50);
        app.logs_selected_index = 45;

        // Page down should clamp to last item (index 49)
        app.on_page_down(20);
        assert_eq!(app.logs_selected_index, 49);
    }

    #[test]
    fn test_page_up_log_viewer() {
        let mut app = build_mock_app_with_logs(100);
        app.logs_selected_index = 50;

        app.on_page_up(20);
        assert_eq!(app.logs_selected_index, 30);

        app.on_page_up(20);
        assert_eq!(app.logs_selected_index, 10);
    }

    #[test]
    fn test_page_up_clamps_at_start() {
        let mut app = build_mock_app_with_logs(100);
        app.logs_selected_index = 5;

        // Page up should clamp to 0
        app.on_page_up(20);
        assert_eq!(app.logs_selected_index, 0);
    }

    #[test]
    fn test_half_page_scroll() {
        let mut app = build_mock_app_with_logs(100);

        app.on_half_page_down(20); // 20/2 = 10
        assert_eq!(app.logs_selected_index, 10);

        app.on_half_page_down(20);
        assert_eq!(app.logs_selected_index, 20);

        app.on_half_page_up(20);
        assert_eq!(app.logs_selected_index, 10);

        app.on_half_page_up(20);
        assert_eq!(app.logs_selected_index, 0);
    }

    #[test]
    fn test_page_scroll_explorer() {
        let mut app = build_mock_app_with_explorer_files();
        // Explorer has 3 items (indices 0, 1, 2)

        app.on_page_down(10);
        assert_eq!(app.explorer_selected_index, 2); // clamped

        app.on_page_up(10);
        assert_eq!(app.explorer_selected_index, 0); // clamped
    }

    #[test]
    fn test_page_scroll_empty_list() {
        let mut app = App::new();
        app.screen = AppScreen::LogViewer;
        // No logs

        app.on_page_down(20);
        assert_eq!(app.logs_selected_index, 0);

        app.on_page_up(20);
        assert_eq!(app.logs_selected_index, 0);
    }

    #[test]
    fn test_page_scroll_zero_page_size() {
        let mut app = build_mock_app_with_logs(10);
        app.logs_selected_index = 5;

        app.on_page_down(0);
        assert_eq!(app.logs_selected_index, 5); // unchanged

        app.on_page_up(0);
        assert_eq!(app.logs_selected_index, 5); // unchanged
    }

    // ==================== Filter scenario tests ====================

    fn build_mock_app_with_diverse_logs() -> App {
        let mut app = App::new();
        app.screen = AppScreen::LogViewer;

        let entries = vec![
            (
                "ECU1",
                Some("DIAG"),
                Some("CAN1"),
                Some(crate::parser::LogLevel::Error),
                "CAN bus timeout on channel 1",
            ),
            (
                "ECU1",
                Some("DIAG"),
                Some("CAN2"),
                Some(crate::parser::LogLevel::Warn),
                "CAN retransmit count high",
            ),
            (
                "ECU1",
                Some("SYS"),
                Some("BOOT"),
                Some(crate::parser::LogLevel::Info),
                "System boot complete",
            ),
            (
                "ECU2",
                Some("NAV"),
                Some("GPS1"),
                Some(crate::parser::LogLevel::Debug),
                "GPS fix acquired lat=35.6 lon=139.7",
            ),
            (
                "ECU2",
                Some("NAV"),
                Some("MAP1"),
                Some(crate::parser::LogLevel::Info),
                "Map data loaded",
            ),
            (
                "ECU1",
                Some("SYS"),
                Some("BOOT"),
                Some(crate::parser::LogLevel::Fatal),
                "Watchdog reset detected",
            ),
            (
                "ECU1",
                Some("DIAG"),
                Some("UDS1"),
                Some(crate::parser::LogLevel::Info),
                "UDS session started",
            ),
            (
                "ECU2",
                Some("HMI"),
                Some("DISP"),
                Some(crate::parser::LogLevel::Verbose),
                "Frame rendered in 16ms",
            ),
        ];

        for (i, (ecu, apid, ctid, level, text)) in entries.into_iter().enumerate() {
            app.logs.push(LogEntry::new(
                DltMessage {
                    timestamp_us: 1000 + i as u64,
                    ecu_id: ecu.to_string(),
                    apid: apid.map(|s| s.to_string()),
                    ctid: ctid.map(|s| s.to_string()),
                    log_level: level,
                    payload_text: text.to_string(),
                    payload_raw: text.as_bytes().to_vec(),
                },
                None,
                0,
            ));
        }
        app.apply_filter();
        app
    }

    #[test]
    fn test_filter_by_text() {
        let mut app = build_mock_app_with_diverse_logs();
        assert_eq!(app.filtered_log_indices.len(), 8); // all

        app.filter.text = Some("CAN".to_string());
        app.apply_filter();
        assert_eq!(app.filtered_log_indices.len(), 2); // "CAN bus timeout" + "CAN retransmit"
    }

    #[test]
    fn test_filter_by_text_case_insensitive() {
        let mut app = build_mock_app_with_diverse_logs();

        app.filter.text = Some("can".to_string());
        app.apply_filter();
        assert_eq!(app.filtered_log_indices.len(), 2); // case-insensitive
    }

    #[test]
    fn test_filter_by_app_id() {
        let mut app = build_mock_app_with_diverse_logs();

        app.filter.app_id = Some("DIAG".to_string());
        app.apply_filter();
        assert_eq!(app.filtered_log_indices.len(), 3); // CAN1, CAN2, UDS1
    }

    #[test]
    fn test_filter_by_ctx_id() {
        let mut app = build_mock_app_with_diverse_logs();

        app.filter.ctx_id = Some("BOOT".to_string());
        app.apply_filter();
        assert_eq!(app.filtered_log_indices.len(), 2); // boot complete + watchdog reset
    }

    #[test]
    fn test_filter_by_log_level() {
        let mut app = build_mock_app_with_diverse_logs();

        // Warn and above (Fatal, Error, Warn)
        app.filter.min_level = Some(crate::parser::LogLevel::Warn);
        app.apply_filter();
        assert_eq!(app.filtered_log_indices.len(), 3); // Fatal + Error + Warn
    }

    #[test]
    fn test_filter_compound_level_and_app() {
        let mut app = build_mock_app_with_diverse_logs();

        // DIAG logs at Warn or above
        app.filter.app_id = Some("DIAG".to_string());
        app.filter.min_level = Some(crate::parser::LogLevel::Warn);
        app.apply_filter();
        assert_eq!(app.filtered_log_indices.len(), 2); // Error + Warn from DIAG
    }

    #[test]
    fn test_filter_compound_all_criteria() {
        let mut app = build_mock_app_with_diverse_logs();

        // DIAG + Error+ + "timeout"
        app.filter.app_id = Some("DIAG".to_string());
        app.filter.min_level = Some(crate::parser::LogLevel::Error);
        app.filter.text = Some("timeout".to_string());
        app.apply_filter();
        assert_eq!(app.filtered_log_indices.len(), 1); // Only "CAN bus timeout"
        assert_eq!(
            app.logs[app.filtered_log_indices[0]].message.payload_text,
            "CAN bus timeout on channel 1"
        );
    }

    #[test]
    fn test_filter_by_regex() {
        let mut app = build_mock_app_with_diverse_logs();

        // Regex: match "lat=... lon=..."
        app.filter.text = Some(r"lat=\d+\.\d+".to_string());
        app.apply_filter();
        assert_eq!(app.filtered_log_indices.len(), 1); // GPS fix
    }

    #[test]
    fn test_filter_no_match() {
        let mut app = build_mock_app_with_diverse_logs();

        app.filter.text = Some("NONEXISTENT_STRING".to_string());
        app.apply_filter();
        assert_eq!(app.filtered_log_indices.len(), 0);
    }

    #[test]
    fn test_filter_reset() {
        let mut app = build_mock_app_with_diverse_logs();

        app.filter.text = Some("CAN".to_string());
        app.apply_filter();
        assert_eq!(app.filtered_log_indices.len(), 2);

        // Reset
        app.filter = Filter::default();
        app.apply_filter();
        assert_eq!(app.filtered_log_indices.len(), 8); // all restored
    }

    #[test]
    fn test_filter_resets_selected_index() {
        let mut app = build_mock_app_with_diverse_logs();
        app.logs_selected_index = 5;

        app.filter.text = Some("CAN".to_string());
        app.apply_filter();
        // apply_filter should reset index to 0
        assert_eq!(app.logs_selected_index, 0);
    }

    #[test]
    fn test_horizontal_scroll() {
        let mut app = build_mock_app_with_logs(1);
        assert_eq!(app.horizontal_scroll, 0);

        app.on_right(1);
        assert_eq!(app.horizontal_scroll, 1);

        app.on_right(10);
        assert_eq!(app.horizontal_scroll, 11);

        app.on_left(5);
        assert_eq!(app.horizontal_scroll, 6);

        app.on_left(10);
        assert_eq!(app.horizontal_scroll, 0, "Should clamp at 0");
    }

    // ==================== Bug verification tests ====================

    fn make_key(code: KeyCode) -> KeyEvent {
        KeyEvent {
            code,
            modifiers: KeyModifiers::NONE,
            kind: crossterm::event::KeyEventKind::Press,
            state: crossterm::event::KeyEventState::NONE,
        }
    }

    /// FIXED BUG-3: Esc during filter input now preserves previous filter value
    #[test]
    fn test_esc_preserves_previous_filter() {
        let mut app = build_mock_app_with_diverse_logs();

        // Set an initial text filter
        app.filter.text = Some("CAN".to_string());
        app.apply_filter();
        assert_eq!(app.filtered_log_indices.len(), 2);

        // Enter filter input mode for text
        app.handle_key(make_key(KeyCode::Char('/')), 20);
        assert!(app.filter_input_mode.is_some());

        // Type something new
        app.handle_key(make_key(KeyCode::Char('X')), 20);

        // Press Esc to cancel
        app.handle_key(make_key(KeyCode::Esc), 20);

        // Previous "CAN" filter should be preserved
        assert_eq!(
            app.filter.text,
            Some("CAN".to_string()),
            "Esc should preserve the previous filter value"
        );
        assert_eq!(
            app.filtered_log_indices.len(),
            2,
            "Filter results should remain unchanged after Esc"
        );
    }

    /// FIXED BUG-3b: Esc from first-time filter input leaves filter as None
    #[test]
    fn test_esc_first_time_filter_leaves_none() {
        let mut app = build_mock_app_with_diverse_logs();
        assert_eq!(app.filter.text, None);
        assert_eq!(app.filtered_log_indices.len(), 8);

        // Enter filter input mode for text (no previous filter)
        app.handle_key(make_key(KeyCode::Char('/')), 20);
        app.handle_key(make_key(KeyCode::Char('X')), 20);
        app.handle_key(make_key(KeyCode::Esc), 20);

        // Filter should remain None
        assert_eq!(app.filter.text, None);
        assert_eq!(app.filtered_log_indices.len(), 8);
    }

    /// FIXED BUG-4: APP ID filter is now case-insensitive
    #[test]
    fn test_app_id_filter_case_insensitive() {
        let mut app = build_mock_app_with_diverse_logs();

        // Filter with lowercase "diag" should match "DIAG"
        app.filter.app_id = Some("diag".to_string());
        app.apply_filter();
        assert_eq!(
            app.filtered_log_indices.len(),
            3,
            "APP ID filter should be case-insensitive: 'diag' matches 'DIAG'"
        );

        // CTX ID filter should also be case-insensitive
        app.filter.app_id = None;
        app.filter.ctx_id = Some("boot".to_string());
        app.apply_filter();
        assert_eq!(
            app.filtered_log_indices.len(),
            2,
            "CTX ID filter should be case-insensitive: 'boot' matches 'BOOT'"
        );
    }

    // ==================== Phase 1 security/bug fix tests ====================

    /// SEC-1: ReDoS-prone regex should be rejected by size_limit and fall back to plain text
    #[test]
    fn test_redos_regex_rejected() {
        let mut app = build_mock_app_with_diverse_logs();
        // This pattern compiles to a very large NFA; size_limit should reject it
        app.filter.text = Some("(a+)+$".repeat(100));
        app.apply_filter();
        // Should not hang — the regex fails to compile and falls back to plain text search
        // Since no log contains the literal "(a+)+$" repeated, result should be 0
        assert_eq!(app.filtered_log_indices.len(), 0);
    }

    /// SEC-5: Filter input should be bounded at 1024 characters
    #[test]
    fn test_filter_input_length_limit() {
        let mut app = build_mock_app_with_diverse_logs();
        app.screen = AppScreen::LogViewer;

        // Enter filter input mode
        app.handle_key(make_key(KeyCode::Char('/')), 20);

        // Type 1030 characters
        for _ in 0..1030 {
            app.handle_key(make_key(KeyCode::Char('x')), 20);
        }

        assert_eq!(
            app.filter_input.len(),
            1024,
            "Filter input should be capped at 1024"
        );
    }

    /// UX-4: Empty filter submission should show "Filter cleared" feedback
    #[test]
    fn test_empty_filter_shows_cleared_message() {
        let mut app = build_mock_app_with_diverse_logs();
        app.screen = AppScreen::LogViewer;

        // Enter filter input mode and submit empty
        app.handle_key(make_key(KeyCode::Char('/')), 20);
        app.handle_key(make_key(KeyCode::Enter), 20);

        assert_eq!(
            app.info_message,
            Some("Filter cleared".to_string()),
            "Empty filter submission should show feedback"
        );
    }

    /// BUG-2: Accessing explorer with out-of-bounds index should not panic
    #[test]
    fn test_explorer_bounds_safety() {
        let mut app = App::new();
        // Manually set index beyond items (simulates stale index after directory change error)
        app.explorer_selected_index = 999;
        app.explorer_items = vec![]; // empty

        // These should not panic
        app.handle_key(make_key(KeyCode::Enter), 20);
        app.handle_key(make_key(KeyCode::Char('b')), 20);
    }

    /// UX-1: Esc on Explorer should quit the app
    #[test]
    fn test_esc_on_explorer_quits() {
        let mut app = App::new();
        assert_eq!(app.screen, AppScreen::Explorer);
        assert!(!app.should_quit);

        app.handle_key(make_key(KeyCode::Esc), 20);
        assert!(app.should_quit, "Esc on Explorer should quit the app");
    }

    /// UX-1: Esc on LogViewer goes back to Explorer
    #[test]
    fn test_esc_on_log_viewer_goes_back() {
        let mut app = build_mock_app_with_logs(5);
        app.screen = AppScreen::LogViewer;

        app.handle_key(make_key(KeyCode::Esc), 20);
        assert_eq!(app.screen, AppScreen::Explorer);
    }

    /// BUG-1: apply_filter bumps filter_generation
    #[test]
    fn test_filter_generation_increments() {
        let mut app = build_mock_app_with_diverse_logs();
        let gen_before = app.filter_generation;

        app.apply_filter();
        assert_eq!(
            app.filter_generation,
            gen_before + 1,
            "apply_filter should increment filter_generation"
        );
    }
}