stagecrew 0.4.1

Disk usage management for shared or staging filesystems with automatic cleanup policies
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
//! TUI application state and main loop.

pub(crate) mod dispatcher;
mod input;
mod ui;

use std::collections::HashSet;
use std::io::{self, Stdout};
use std::path::{Path, PathBuf};

use crossterm::ExecutableCommand;
use crossterm::event::{
    DisableMouseCapture, EnableMouseCapture, Event, EventStream, MouseEvent, MouseEventKind,
};
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use futures::StreamExt;
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use ratatui::layout::Rect;
use ratatui::widgets::{ScrollbarState, TableState};

use crate::audit::{AuditEntry, AuditExportFormat};
use crate::config::{AppConfig, AppPaths};
use crate::db::{Database, Entry, Root};
use crate::error::Result;
use crate::removal::{DryRunResult, RemovalMethod};
use crate::scanner::{Scanner, refresh};

use input::InputHandler;

/// Shared immutable references available to all TUI operations within a single
/// frame or event. Constructed once in the event loop and passed to render and
/// input handlers, replacing the previous pattern of threading `&Config` and
/// `&Database` as separate parameters through every function.
pub(crate) struct TuiContext<'a> {
    /// Full application config including per-root overrides.
    pub(crate) app_config: &'a AppConfig,
    /// Async DB dispatcher for non-blocking reads and writes.
    pub(crate) db_dispatcher: &'a dispatcher::DbDispatcher,
}

impl TuiContext<'_> {
    /// Returns the effective config for the currently selected root, falling
    /// back to the global config if no root is selected or the root has no
    /// local override. Looks up the root from the cached `app.roots` list
    /// rather than querying the database.
    pub fn config(&self, app: &App) -> &crate::config::Config {
        let root = app
            .current_root_id
            .and_then(|id| app.roots.iter().find(|r| r.id == id));
        root.map_or(&self.app_config.global, |r| {
            self.app_config.for_root(&r.path)
        })
    }
}

/// A single reversible status change that can be undone.
#[derive(Debug, Clone)]
pub(crate) struct UndoEntry {
    /// Database entry ID.
    pub entry_id: i64,
    /// Status before the action was applied.
    pub status_before: String,
    /// The `deferred_until` value before the action, if any.
    pub deferred_until_before: Option<i64>,
    /// The `countdown_start` value before the action, if any.
    pub countdown_start_before: Option<i64>,
}

/// A reversible action that can be undone as a single unit.
#[derive(Debug, Clone)]
pub(crate) struct UndoAction {
    /// Human-readable description of what was done.
    pub description: String,
    /// The individual entry changes to reverse.
    pub entries: Vec<UndoEntry>,
}

/// An entry awaiting user confirmation for a pending action (delete, ignore, approve, etc.).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PendingEntry {
    /// Database row ID.
    pub id: i64,
    /// Absolute filesystem path.
    pub path: PathBuf,
    /// Whether this entry is a directory (affects propagation to children).
    pub is_dir: bool,
}

/// State for an in-progress deletion action.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PendingDeletion {
    /// Entries to be deleted.
    pub entries: Vec<PendingEntry>,
    /// How to remove the files (trash or permanent delete).
    pub method: RemovalMethod,
}

/// State for an in-progress deferral action.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PendingDeferral {
    /// Entries being deferred.
    pub entries: Vec<PendingEntry>,

    /// Accumulated input buffer for days to defer.
    pub input: String,

    /// Default number of days to defer (from config).
    pub default_days: u32,
}

/// Byte unit for quota target input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum ByteUnit {
    MB,
    #[default]
    GB,
    TB,
}

impl ByteUnit {
    /// Convert a value in this unit to bytes.
    ///
    /// Returns the byte count as `i64` for `SQLite` compatibility. Values that
    /// would overflow `i64::MAX` are clamped.
    pub fn to_bytes(self, value: u64) -> i64 {
        let multiplier: u64 = match self {
            Self::MB => 1_000_000,
            Self::GB => 1_000_000_000,
            Self::TB => 1_000_000_000_000,
        };
        // Saturating multiply, then clamp to i64 range
        let bytes = value.saturating_mul(multiplier);
        // i64::MAX as u64 is safe because i64::MAX is positive
        #[allow(clippy::cast_sign_loss)]
        let max_i64 = i64::MAX as u64;
        if bytes > max_i64 {
            i64::MAX
        } else {
            // Safe: we just checked bytes <= i64::MAX
            #[allow(clippy::cast_possible_wrap)]
            let result = bytes as i64;
            result
        }
    }

    /// Cycle to the next unit.
    pub fn next(self) -> Self {
        match self {
            Self::MB => Self::GB,
            Self::GB => Self::TB,
            Self::TB => Self::MB,
        }
    }

    /// Cycle to the previous unit.
    pub fn prev(self) -> Self {
        match self {
            Self::MB => Self::TB,
            Self::GB => Self::MB,
            Self::TB => Self::GB,
        }
    }
}

impl std::fmt::Display for ByteUnit {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MB => write!(f, "MB"),
            Self::GB => write!(f, "GB"),
            Self::TB => write!(f, "TB"),
        }
    }
}

/// Which field is focused in the quota target dialog.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum QuotaTargetFocus {
    #[default]
    Size,
    Unit,
}

/// Request to open files in an external application.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ExternalOpenRequest {
    /// Open in $VISUAL or $EDITOR (suspends TUI, waits for exit, then rescans).
    Editor(Vec<PathBuf>),
    /// Open with system viewer (fire-and-forget, no TUI interruption).
    SystemViewer(Vec<PathBuf>),
}

/// State for an in-progress quota target edit.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PendingQuotaTarget {
    /// The root being edited.
    pub root_id: i64,

    /// The root's path (for display).
    pub root_path: PathBuf,

    /// Accumulated input buffer for the size value.
    pub input: String,

    /// Selected byte unit.
    pub unit: ByteUnit,

    /// Which field is currently focused.
    pub focus: QuotaTargetFocus,

    /// Current target value in bytes (if any), for display.
    pub current_target: Option<i64>,
}

/// State for an in-progress audit log export.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PendingAuditExport {
    /// Output path input buffer.
    pub path_input: String,
    /// Selected output format.
    pub format: AuditExportFormat,
}

/// Tracks which async data fetches are currently in flight.
/// Used by render to show loading indicators and by the dispatcher
/// to debounce redundant requests.
#[derive(Default)]
#[allow(clippy::struct_excessive_bools)]
pub(crate) struct LoadingState {
    /// True while a roots query is in flight.
    pub roots: bool,
    /// True while a root-entries query is in flight.
    pub root_entries: bool,
    /// True while a dir-entries query is in flight.
    pub dir_entries: bool,
    /// True while a stats query is in flight.
    pub stats: bool,
    /// True while an audit-entries query is in flight.
    pub audit_entries: bool,
}

/// Main TUI application state.
// Allow: The bools represent independent flags (quit, sidebar visibility, scan state,
// search input) that don't naturally form a state machine. Each has distinct semantics.
#[allow(clippy::struct_excessive_bools)]
pub struct App {
    /// Whether the app should quit.
    pub(crate) should_quit: bool,

    /// Current view mode.
    pub(crate) view: View,

    /// Which panel is focused (sidebar or main panel) in `FileList` view.
    pub(crate) focus_panel: FocusPanel,

    /// Currently selected index in the sidebar (tracked roots).
    pub(crate) sidebar_selected_index: usize,

    /// Currently selected index in the main panel (entries).
    pub(crate) entry_selected_index: usize,

    /// Current sort mode for entries.
    pub(crate) sort_mode: SortMode,

    /// Filter for days until expiration.
    // Allow: Planned feature for filtering entry list by expiration days.
    // Reserved for future implementation.
    #[allow(dead_code)]
    pub(crate) filter_days: Option<u32>,

    /// Length of the sidebar list (updated by render, used for navigation bounds).
    pub(crate) sidebar_len: usize,

    /// Length of the entry list (updated by render, used for navigation bounds).
    pub(crate) entry_list_len: usize,

    /// The root ID currently selected in sidebar for viewing entries.
    pub(crate) current_root_id: Option<i64>,

    /// Table state for the entries panel (tracks scroll offset and selection).
    pub(crate) entry_table_state: TableState,

    /// Scrollbar state for the entries panel.
    pub(crate) entry_scrollbar_state: ScrollbarState,

    /// Table state for the audit log view (tracks scroll offset and selection).
    pub(crate) audit_table_state: TableState,

    /// Scrollbar state for the audit log view.
    pub(crate) audit_scrollbar_state: ScrollbarState,

    /// Bounding rectangle of the entries table (for mouse hit-testing).
    pub(crate) entry_table_area: Rect,

    /// Bounding rectangle of the audit log table (for mouse hit-testing).
    pub(crate) audit_table_area: Rect,

    /// The current path being browsed within the selected root.
    /// This enables hierarchical navigation within a root.
    pub(crate) current_path: PathBuf,

    /// Pending entry deletion confirmation state.
    pub(crate) pending_entry_delete: Option<PendingDeletion>,

    /// Pending entry deferral input state.
    pub(crate) pending_entry_deferral: Option<PendingDeferral>,

    /// Pending entry ignore confirmation state.
    pub(crate) pending_entry_ignore: Option<Vec<PendingEntry>>,

    /// Pending entry approval confirmation state.
    pub(crate) pending_entry_approval: Option<Vec<PendingEntry>>,

    /// Set of selected entry IDs for multi-select operations.
    pub(crate) selected_entries: HashSet<i64>,

    /// Visual mode anchor index. `Some(idx)` means visual mode is active,
    /// anchored at position `idx` in the sorted entry list. `None` means
    /// normal mode.
    pub(crate) visual_anchor: Option<usize>,

    /// Snapshot of selected entries taken when visual mode was entered.
    /// Preserves pre-existing Space selections so the visual range is
    /// additive rather than replacing them.
    pub(crate) pre_visual_selection: HashSet<i64>,

    /// Pending add path text input state.
    /// Contains the accumulated input buffer for the new path to add.
    pub(crate) pending_add_path: Option<String>,

    /// Pending remove path confirmation state.
    /// Contains the path awaiting user confirmation for removal from config.
    pub(crate) pending_remove_path: Option<PathBuf>,

    /// Pending quota target edit state.
    /// Contains the input state for setting a root's byte quota target.
    pub(crate) pending_quota_target: Option<PendingQuotaTarget>,

    /// Pending audit export modal state.
    pub(crate) pending_audit_export: Option<PendingAuditExport>,

    /// Dry run preflight check result for display in a modal.
    pub(crate) pending_dry_run: Option<DryRunResult>,

    /// Whether the sidebar is visible.
    pub(crate) sidebar_visible: bool,

    /// Whether a refresh has been requested (set by R keybind, cleared by main loop).
    pub(crate) scan_requested: bool,

    /// Whether a refresh is currently in progress.
    pub(crate) scan_in_progress: bool,

    /// Status message to display (e.g., "Scanning...", "Scan complete").
    pub(crate) status_message: Option<String>,

    /// When the status message was set (for auto-clearing after timeout).
    pub(crate) status_message_time: Option<std::time::Instant>,

    /// Cached header stats, updated after actions and refreshes.
    pub(crate) cached_stats: crate::db::Stats,

    /// Active search query. `Some` means a search is active (either typing or
    /// navigating matches). `None` means normal mode with no search.
    pub(crate) search_query: Option<String>,

    /// Whether the user is currently typing into the search input.
    /// When true, keystrokes go to the search buffer. When false (but
    /// `search_query` is `Some`), the user can navigate matches with n/N.
    pub(crate) search_input_active: bool,

    /// Whether to scroll the viewport to ensure the cursor is visible.
    /// Set by keyboard navigation, cleared after render adjusts the offset.
    /// This allows mouse scrolling to move the viewport independently of
    /// the cursor position.
    pub(crate) ensure_cursor_visible: bool,

    /// Pending request to open files in an external application.
    /// Set by input handler, consumed by main loop.
    pub(crate) external_open_request: Option<ExternalOpenRequest>,

    /// Cached nearest expiration unix timestamp for the countdown widget.
    /// Refreshed on scan completion and status changes.
    pub(crate) nearest_expiration: Option<i64>,

    /// Cached list of tracked roots. Updated on startup, add/remove root,
    /// and scan completion. Render reads this instead of querying the DB.
    pub(crate) roots: Vec<Root>,

    /// Cached entries for the currently selected root. Feeds lifecycle widget,
    /// expiration timeline, and quota pie chart. Updated on root selection
    /// change, user action, and scan completion.
    pub(crate) root_entries: Vec<Entry>,

    /// Cached + sorted entries for the current directory. Feeds the main entry
    /// panel. Updated on navigation, user action, scan completion, and sort
    /// change. Each element is `(entry, days_remaining)`.
    pub(crate) dir_entries: Vec<(Entry, i64)>,

    /// Cached audit log entries for the audit log view. Updated on view
    /// switch to audit log and after user actions that write audit records.
    pub(crate) audit_entries: Vec<AuditEntry>,

    /// Tracks which async data fetches are currently in flight.
    pub(crate) loading: LoadingState,

    /// Path to restore cursor to when `dir_entries` arrives. Set by
    /// `navigate_up` so the cursor lands on the directory we just left.
    pub(crate) pending_cursor_restore: Option<PathBuf>,

    /// In-memory stack of reversible actions for undo.
    pub(crate) undo_stack: Vec<UndoAction>,
}

impl App {
    /// Get the current view.
    pub fn view(&self) -> View {
        self.view
    }

    /// Get which panel is focused.
    pub fn focus_panel(&self) -> FocusPanel {
        self.focus_panel
    }

    /// Get the currently selected index in sidebar.
    pub fn sidebar_selected_index(&self) -> usize {
        self.sidebar_selected_index
    }

    /// Get the currently selected index in entry list.
    pub fn entry_selected_index(&self) -> usize {
        self.entry_selected_index
    }

    /// Get the current sort mode.
    pub fn sort_mode(&self) -> SortMode {
        self.sort_mode
    }

    /// Get the filter for days until expiration.
    // Allow: Getter for filter_days field which is planned for future implementation.
    #[allow(dead_code)]
    pub fn filter_days(&self) -> Option<u32> {
        self.filter_days
    }

    /// Get the current root ID selected in sidebar.
    // Allow: Will be used by TUI-014 directory navigation to determine root boundaries.
    #[allow(dead_code)]
    pub fn current_root_id(&self) -> Option<i64> {
        self.current_root_id
    }

    /// Get the current path being browsed.
    pub fn current_path(&self) -> &Path {
        &self.current_path
    }

    /// Get the pending entry deletion confirmation state.
    pub fn pending_entry_delete(&self) -> Option<&PendingDeletion> {
        self.pending_entry_delete.as_ref()
    }

    /// Get the pending entry deferral input state.
    pub fn pending_entry_deferral(&self) -> Option<&PendingDeferral> {
        self.pending_entry_deferral.as_ref()
    }

    /// Get the pending entry ignore confirmation state.
    pub fn pending_entry_ignore(&self) -> Option<&Vec<PendingEntry>> {
        self.pending_entry_ignore.as_ref()
    }

    /// Get the pending entry approval confirmation state.
    pub fn pending_entry_approval(&self) -> Option<&Vec<PendingEntry>> {
        self.pending_entry_approval.as_ref()
    }

    /// Get the set of selected entry IDs.
    pub fn selected_entries(&self) -> &HashSet<i64> {
        &self.selected_entries
    }

    /// Get the pending add path input state.
    pub fn pending_add_path(&self) -> Option<&str> {
        self.pending_add_path.as_deref()
    }

    /// Get the pending remove path confirmation state.
    pub fn pending_remove_path(&self) -> Option<&Path> {
        self.pending_remove_path.as_deref()
    }

    /// Get the pending quota target edit state.
    pub fn pending_quota_target(&self) -> Option<&PendingQuotaTarget> {
        self.pending_quota_target.as_ref()
    }

    /// Get the pending audit export state.
    pub fn pending_audit_export(&self) -> Option<&PendingAuditExport> {
        self.pending_audit_export.as_ref()
    }

    /// Get the dry run result for modal display.
    pub fn pending_dry_run(&self) -> Option<&DryRunResult> {
        self.pending_dry_run.as_ref()
    }

    /// Check if the sidebar is visible.
    pub fn sidebar_visible(&self) -> bool {
        self.sidebar_visible
    }

    /// Clear all entry selections.
    pub(crate) fn clear_selection(&mut self) {
        self.selected_entries.clear();
    }

    /// Toggle selection of an entry ID.
    pub(crate) fn toggle_entry_selection(&mut self, entry_id: i64) {
        if self.selected_entries.contains(&entry_id) {
            self.selected_entries.remove(&entry_id);
        } else {
            self.selected_entries.insert(entry_id);
        }
    }

    /// Whether visual mode is active.
    pub fn is_visual_mode(&self) -> bool {
        self.visual_anchor.is_some()
    }

    /// Exit visual mode, keeping the current selection intact.
    pub(crate) fn exit_visual_mode(&mut self) {
        self.visual_anchor = None;
        self.pre_visual_selection.clear();
    }

    /// Recompute `selected_entries` from the visual range plus the pre-visual snapshot.
    ///
    /// The visual range spans from the anchor to the cursor (inclusive) in the
    /// sorted entry list. The result is the union of that range with whatever
    /// was selected before visual mode was entered.
    pub(crate) fn recompute_visual_selection(&mut self, entry_ids: &[i64]) {
        let Some(anchor) = self.visual_anchor else {
            return;
        };
        let cursor = self.entry_selected_index;
        let lo = anchor.min(cursor);
        let hi = anchor.max(cursor).min(entry_ids.len().saturating_sub(1));

        self.selected_entries = self.pre_visual_selection.clone();
        for &id in &entry_ids[lo..=hi] {
            self.selected_entries.insert(id);
        }
    }

    /// Select the last item in the sidebar.
    ///
    /// Sets `sidebar_selected_index` to `len - 1`, or 0 if the list is empty.
    pub(crate) fn select_last_sidebar(&mut self, len: usize) {
        self.sidebar_selected_index = len.saturating_sub(1);
    }

    /// Select the last item in the entry list.
    ///
    /// Sets `entry_selected_index` to `len - 1`, or 0 if the list is empty.
    pub(crate) fn select_last_entry(&mut self, len: usize) {
        self.entry_selected_index = len.saturating_sub(1);
    }

    /// Clear any active search state.
    pub(crate) fn clear_search(&mut self) {
        self.search_query = None;
        self.search_input_active = false;
    }

    /// Navigate into a directory entry.
    ///
    /// Sets the current path to the given directory path and resets entry selection.
    /// Also clears any active search since results are directory-specific.
    pub(crate) fn navigate_into(&mut self, path: PathBuf) {
        self.current_path = path;
        self.entry_selected_index = 0;
        self.ensure_cursor_visible = true;
        self.clear_search();
    }

    /// Auto-enter the first root if no root is currently entered.
    ///
    /// Called at startup and after refresh completion so the user sees files
    /// immediately instead of the empty "Select a root" prompt. This is a
    /// no-op when a root is already entered (i.e., `current_path` is non-empty).
    pub(crate) fn auto_enter_first_root(&mut self) {
        if !self.current_path.as_os_str().is_empty() {
            return;
        }
        if let Some(root) = self.roots.first() {
            let path = root.path.clone();
            let id = root.id;
            self.navigate_into(path);
            self.current_root_id = Some(id);
        }
    }

    /// Sync the main panel to show the currently selected sidebar root.
    ///
    /// Looks up the root at `sidebar_selected_index` in the cached roots list
    /// and updates `current_path` and `current_root_id` to match. This ensures
    /// the main panel immediately reflects sidebar navigation rather than
    /// requiring an explicit "enter".
    pub(crate) fn sync_to_sidebar_selection(&mut self) {
        let Some(root) = self.roots.get(self.sidebar_selected_index) else {
            return;
        };
        let path = root.path.clone();
        let id = root.id;
        self.navigate_into(path);
        self.current_root_id = Some(id);
    }

    /// Navigate up to the parent directory.
    ///
    /// If already at a root level, this is a no-op.
    /// Clears any active search since results are directory-specific.
    /// Attempts to restore cursor position to the directory we came from.
    pub(crate) fn navigate_up(&mut self) {
        let Some(parent) = self.current_path.parent() else {
            return;
        };

        // Remember where we came from so the cursor can be restored
        // when the async dir_entries load completes.
        self.pending_cursor_restore = Some(self.current_path.clone());

        self.current_path = parent.to_path_buf();
        self.entry_selected_index = 0;
        self.ensure_cursor_visible = true;
        self.clear_search();
    }
}

/// Terminal manager that ensures proper cleanup.
///
/// This struct handles terminal setup and teardown, guaranteeing cleanup
/// even if the program panics through its Drop implementation.
struct TerminalManager {
    terminal: Terminal<CrosstermBackend<Stdout>>,
}

impl TerminalManager {
    /// Set up the terminal for TUI mode.
    ///
    /// # Errors
    ///
    /// Returns an error if terminal setup fails (raw mode, alternate screen, mouse capture, or backend creation).
    fn setup() -> io::Result<Self> {
        enable_raw_mode()?;
        io::stdout()
            .execute(EnterAlternateScreen)?
            .execute(EnableMouseCapture)?;

        let backend = CrosstermBackend::new(io::stdout());
        let terminal = Terminal::new(backend)?;

        Ok(Self { terminal })
    }

    /// Get a mutable reference to the terminal.
    fn terminal_mut(&mut self) -> &mut Terminal<CrosstermBackend<Stdout>> {
        &mut self.terminal
    }

    /// Temporarily suspend the TUI to allow an external program to use the terminal.
    ///
    /// Returns the terminal to normal mode (disables raw mode, leaves alternate screen,
    /// disables mouse capture). Call `restore()` after the external program exits.
    fn suspend() -> io::Result<()> {
        disable_raw_mode()?;
        io::stdout()
            .execute(LeaveAlternateScreen)?
            .execute(DisableMouseCapture)?;
        Ok(())
    }

    /// Restore the TUI after suspending for an external program.
    ///
    /// Re-enables raw mode, enters alternate screen, enables mouse capture,
    /// and clears the given terminal for a fresh redraw.
    fn restore(terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> io::Result<()> {
        enable_raw_mode()?;
        io::stdout()
            .execute(EnterAlternateScreen)?
            .execute(EnableMouseCapture)?;
        terminal.clear()?;
        Ok(())
    }
}

impl Drop for TerminalManager {
    fn drop(&mut self) {
        // Ensure terminal is restored even on panic.
        // Ignore errors during cleanup - best effort restoration.
        let _ = disable_raw_mode();
        let _ = io::stdout()
            .execute(LeaveAlternateScreen)
            .and_then(|out| out.execute(DisableMouseCapture));
    }
}

/// Available views in the TUI.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum View {
    /// Main file list view with sidebar for directory navigation.
    #[default]
    FileList,

    /// Audit log view.
    AuditLog,

    /// Help/keybindings view.
    Help,
}

/// Focus panel in the file list view.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FocusPanel {
    /// Sidebar panel with tracked directories.
    Sidebar,

    /// Main panel with file list.
    #[default]
    MainPanel,
}

/// Sort modes for the directory list.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortMode {
    /// Sort by time until expiration (default, most urgent first).
    #[default]
    Expiration,

    /// Sort by size (largest first).
    Size,

    /// Sort by path name.
    Name,

    /// Sort by modification time (most recent first).
    Modified,
}

impl App {
    /// Create a new TUI application.
    pub fn new() -> Self {
        Self {
            should_quit: false,
            view: View::default(),
            focus_panel: FocusPanel::default(),
            sidebar_selected_index: 0,
            entry_selected_index: 0,
            sort_mode: SortMode::default(),
            filter_days: None,
            sidebar_len: 0,
            entry_list_len: 0,
            current_root_id: None,
            entry_table_state: TableState::default(),
            entry_scrollbar_state: ScrollbarState::default(),
            audit_table_state: TableState::default(),
            audit_scrollbar_state: ScrollbarState::default(),
            entry_table_area: Rect::default(),
            audit_table_area: Rect::default(),
            current_path: PathBuf::new(),
            pending_entry_delete: None,
            pending_entry_deferral: None,
            pending_entry_ignore: None,
            pending_entry_approval: None,
            selected_entries: HashSet::new(),
            visual_anchor: None,
            pre_visual_selection: HashSet::new(),
            pending_add_path: None,
            pending_remove_path: None,
            pending_quota_target: None,
            pending_audit_export: None,
            pending_dry_run: None,
            sidebar_visible: true,
            scan_requested: false,
            scan_in_progress: false,
            status_message: None,
            status_message_time: None,
            cached_stats: crate::db::Stats {
                total_files: 0,
                total_size_bytes: 0,
                files_within_warning: 0,
                files_pending_approval: 0,
                files_overdue: 0,
                last_scan_completed: None,
                files_healthy: 0,
                bytes_healthy: 0,
                bytes_within_warning: 0,
                bytes_pending_approval: 0,
                bytes_overdue: 0,
                files_ignored: 0,
                bytes_ignored: 0,
            },
            search_query: None,
            search_input_active: false,
            ensure_cursor_visible: false,
            external_open_request: None,
            nearest_expiration: None,
            roots: Vec::new(),
            root_entries: Vec::new(),
            dir_entries: Vec::new(),
            audit_entries: Vec::new(),
            loading: LoadingState::default(),
            pending_cursor_restore: None,
            undo_stack: Vec::new(),
        }
    }

    /// Dispatch async read requests to refresh all cached view data.
    ///
    /// This is the async counterpart to `refresh_view_data`. Instead of
    /// blocking on DB queries, it sends requests to the DB worker and sets
    /// loading flags. Results arrive via the `db_result_rx` channel and
    /// are applied to App state in the event loop.
    pub(crate) fn dispatch_refresh(
        &mut self,
        db_dispatcher: &dispatcher::DbDispatcher,
        ctx: &TuiContext,
    ) {
        let config = ctx.config(self);
        let root_configs = self
            .roots
            .iter()
            .map(|root| {
                let root_config = ctx.app_config.for_root(&root.path);
                crate::db::RootStatConfig {
                    root_id: root.id,
                    expiration_days: root_config.expiration_days,
                    warning_days: root_config.warning_days,
                }
            })
            .collect::<Vec<_>>();
        self.loading.roots = true;
        self.loading.root_entries = self.current_root_id.is_some();
        self.loading.dir_entries = !self.current_path.as_os_str().is_empty();
        self.loading.stats = true;
        self.loading.audit_entries = true;
        db_dispatcher.dispatch_refresh_all(
            self.current_root_id,
            self.current_path(),
            config.expiration_days,
            root_configs,
            self.sort_mode(),
        );
    }

    /// Apply a `DbResult` received from the worker to the cached App state.
    ///
    /// Clears the corresponding loading flag and updates the relevant field.
    pub(crate) fn apply_db_result(&mut self, result: dispatcher::DbResult) {
        match result {
            dispatcher::DbResult::Roots(roots) => {
                self.loading.roots = false;
                self.roots = roots;
                self.sidebar_len = self.roots.len();
                self.auto_enter_first_root();
            }
            dispatcher::DbResult::RootEntries(entries) => {
                self.loading.root_entries = false;
                self.root_entries = entries;
            }
            dispatcher::DbResult::DirEntries(entries) => {
                self.loading.dir_entries = false;
                // If we have a pending cursor restore (from navigate_up),
                // find the directory we came from and place the cursor there.
                if let Some(restore_path) = self.pending_cursor_restore.take()
                    && let Some(idx) = entries.iter().position(|(e, _)| e.path == restore_path)
                {
                    self.entry_selected_index = idx;
                    self.ensure_cursor_visible = true;
                }
                self.dir_entries = entries;
            }
            dispatcher::DbResult::Stats {
                stats,
                nearest_expiration,
            } => {
                self.loading.stats = false;
                self.cached_stats = stats;
                self.nearest_expiration = nearest_expiration;
            }
            dispatcher::DbResult::AuditEntries(entries) => {
                self.loading.audit_entries = false;
                self.audit_entries = entries;
            }
            dispatcher::DbResult::WriteOk => {
                // Optimistic state was correct — nothing to do.
            }
            dispatcher::DbResult::WritePartial { message } => {
                self.status_message = Some(message);
                self.status_message_time = Some(std::time::Instant::now());
            }
            dispatcher::DbResult::WriteFailed { message } => {
                // TODO(phase3): revert optimistic state. For now, just
                // show the error and let the next refresh correct the UI.
                self.status_message = Some(message);
                self.status_message_time = Some(std::time::Instant::now());
            }
            dispatcher::DbResult::Error { context, message } => {
                tracing::warn!("DB worker error in {context}: {message}");
            }
        }
    }

    /// Run the TUI main loop.
    ///
    /// This sets up the terminal in raw mode with an alternate screen, then enters
    /// the main event loop. The loop uses `tokio::select!` to handle both keyboard
    /// events and background task completion without blocking.
    ///
    /// The terminal is guaranteed to be restored to its original state on exit,
    /// even if a panic occurs, through the `TerminalManager`'s Drop implementation.
    ///
    /// # Errors
    ///
    /// Returns an error if terminal setup fails or if rendering encounters an I/O error.
    pub async fn run(
        &mut self,
        app_config: &AppConfig,
        db: &Database,
        db_path: &std::path::Path,
        _paths: &AppPaths,
    ) -> Result<()> {
        // Detect terminal theme before taking over the screen, since the
        // detection uses escape sequences that require normal terminal mode.
        ui::detect_terminal_theme();

        let mut terminal_manager = TerminalManager::setup().map_err(crate::error::Error::Io)?;
        let mut event_stream = EventStream::new();

        // Synchronously load roots so auto_enter_first_root can work.
        // This is the only synchronous DB read remaining in the event loop.
        if let Ok(roots) = db.list_roots() {
            self.roots = roots;
            self.sidebar_len = self.roots.len();
        }
        self.auto_enter_first_root();

        // Channel for receiving scan completion results
        let (scan_tx, mut scan_rx) =
            tokio::sync::mpsc::channel::<std::result::Result<(), String>>(1);

        // Track the scan task handle so we can await it properly
        let mut scan_handle: Option<tokio::task::JoinHandle<()>> = None;

        // Spawn the async DB worker with its own connection
        let (db_dispatcher, mut db_result_rx) = dispatcher::spawn_db_worker(db_path);

        let ctx = TuiContext {
            app_config,
            db_dispatcher: &db_dispatcher,
        };

        // Dispatch initial data load asynchronously
        self.dispatch_refresh(&db_dispatcher, &ctx);

        // Main event loop
        loop {
            // Render the current state
            terminal_manager
                .terminal_mut()
                .draw(|frame| ui::render(self, &ctx, frame))
                .map_err(crate::error::Error::Io)?;

            // Check if we should quit (after rendering final state)
            if self.should_quit {
                break;
            }

            // Clear status message after 3 seconds
            if let Some(time) = self.status_message_time
                && time.elapsed() > std::time::Duration::from_secs(3)
            {
                self.status_message = None;
                self.status_message_time = None;
            }

            // Check if a refresh was requested and none is in progress
            if self.scan_requested && !self.scan_in_progress {
                self.scan_requested = false;
                self.scan_in_progress = true;
                self.status_message = Some("Refreshing...".to_string());
                // Don't set timestamp for "Refreshing..." - we want it to persist until done

                // Clone what we need for the background task
                let scanner = Scanner::new();
                let task_app_config = ctx.app_config.clone();
                let task_db_path = db_path.to_path_buf();
                let tx = scan_tx.clone();

                // Spawn the refresh as a background task.
                // Scans the filesystem then transitions expired files using per-root configs.
                scan_handle = Some(tokio::spawn(async move {
                    let scan_result = tokio::task::spawn_blocking(move || {
                        let rt = tokio::runtime::Handle::current();
                        rt.block_on(async {
                            match Database::open(&task_db_path) {
                                Ok(task_db) => refresh(&task_db, &scanner, &task_app_config)
                                    .await
                                    .map(|_| ())
                                    .map_err(|e| e.to_string()),
                                Err(e) => Err(format!("Failed to open database: {e}")),
                            }
                        })
                    })
                    .await
                    .unwrap_or_else(|e| Err(format!("Refresh task panicked: {e}")));

                    let _ = tx.send(scan_result).await;
                }));
            }

            // Handle external open requests (editor or system viewer)
            self.handle_external_open_request(&mut terminal_manager);

            // Use select! to handle events and scan completion concurrently
            tokio::select! {
                // Handle keyboard/mouse events
                maybe_event = event_stream.next() => {
                    match maybe_event {
                        Some(Ok(Event::Key(key))) => {
                            InputHandler::handle(self, &ctx, key);
                        }
                        Some(Ok(Event::Mouse(mouse))) => {
                            Self::handle_mouse_event(self, mouse);
                        }
                        _ => {}
                    }
                }

                // Handle async DB results
                Some(result) = db_result_rx.recv() => {
                    self.apply_db_result(result);
                }

                // Handle refresh completion
                Some(result) = scan_rx.recv() => {
                    self.scan_in_progress = false;
                    scan_handle = None;
                    self.status_message_time = Some(std::time::Instant::now());
                    match result {
                        Ok(()) => {
                            self.status_message = Some("Refresh complete".to_string());
                            self.dispatch_refresh(&db_dispatcher, &ctx);
                        }
                        Err(e) => {
                            self.status_message = Some(format!("Refresh failed: {e}"));
                        }
                    }
                }

                // Tick once per second for the countdown timer and status message clearing.
                // No DB queries happen here — render reads from cached App state.
                () = tokio::time::sleep(tokio::time::Duration::from_secs(1)) => {}
            }
        }

        // Clean up any running scan task
        if let Some(handle) = scan_handle {
            handle.abort();
        }

        // Terminal cleanup happens automatically via Drop
        Ok(())
    }

    /// Handle mouse events (scroll wheel navigation).
    ///
    /// Mouse scroll adjusts the viewport offset without changing the selection,
    /// but only when the cursor is over the relevant table area.
    fn handle_mouse_event(&mut self, event: MouseEvent) {
        const SCROLL_AMOUNT: usize = 3;
        // Table chrome: 2 for borders + 1 for header row + 1 for header bottom margin
        const TABLE_CHROME: u16 = 4;

        let mouse_pos = (event.column, event.row);

        // Check if mouse is within a rect
        let in_rect = |rect: Rect| {
            mouse_pos.0 >= rect.x
                && mouse_pos.0 < rect.x + rect.width
                && mouse_pos.1 >= rect.y
                && mouse_pos.1 < rect.y + rect.height
        };

        match event.kind {
            MouseEventKind::ScrollDown => {
                if self.view == View::AuditLog && in_rect(self.audit_table_area) {
                    // Scroll audit log viewport down (increase offset)
                    // Clamp so the last items fill the viewport (no empty space at bottom)
                    let viewport_height =
                        self.audit_table_area.height.saturating_sub(TABLE_CHROME) as usize;
                    let max_offset = self.sidebar_len.saturating_sub(viewport_height);
                    let new_offset = self
                        .audit_table_state
                        .offset()
                        .saturating_add(SCROLL_AMOUNT)
                        .min(max_offset);
                    *self.audit_table_state.offset_mut() = new_offset;
                } else if self.view == View::FileList && in_rect(self.entry_table_area) {
                    // Scroll entries viewport down (increase offset)
                    let viewport_height =
                        self.entry_table_area.height.saturating_sub(TABLE_CHROME) as usize;
                    let max_offset = self.entry_list_len.saturating_sub(viewport_height);
                    let new_offset = self
                        .entry_table_state
                        .offset()
                        .saturating_add(SCROLL_AMOUNT)
                        .min(max_offset);
                    *self.entry_table_state.offset_mut() = new_offset;
                }
                // Ignore scroll events outside table areas
            }
            MouseEventKind::ScrollUp => {
                if self.view == View::AuditLog && in_rect(self.audit_table_area) {
                    // Scroll audit log viewport up (decrease offset)
                    *self.audit_table_state.offset_mut() = self
                        .audit_table_state
                        .offset()
                        .saturating_sub(SCROLL_AMOUNT);
                } else if self.view == View::FileList && in_rect(self.entry_table_area) {
                    // Scroll entries viewport up (decrease offset)
                    *self.entry_table_state.offset_mut() = self
                        .entry_table_state
                        .offset()
                        .saturating_sub(SCROLL_AMOUNT);
                }
                // Ignore scroll events outside table areas
            }
            _ => {
                // Ignore other mouse events (clicks, drags, etc.)
            }
        }
    }

    /// Run an editor on the given paths, suspending the TUI while the editor runs.
    ///
    /// Checks `$VISUAL` first, then `$EDITOR`, then falls back to `vi`.
    /// Handle a pending external open request (editor or system viewer).
    ///
    /// Consumes the request from `self.external_open_request` and executes it.
    fn handle_external_open_request(&mut self, terminal_manager: &mut TerminalManager) {
        let Some(request) = self.external_open_request.take() else {
            return;
        };

        match request {
            ExternalOpenRequest::Editor(paths) => {
                // Suspend TUI, run editor, restore TUI, trigger rescan
                if let Err(e) = Self::run_editor(terminal_manager, &paths) {
                    self.status_message = Some(format!("Editor failed: {e}"));
                    self.status_message_time = Some(std::time::Instant::now());
                } else {
                    // Trigger rescan to pick up any mtime changes
                    self.scan_requested = true;
                }
            }
            ExternalOpenRequest::SystemViewer(paths) => {
                // Fire-and-forget, no TUI interruption
                if let Err(e) = Self::open_with_system_viewer(&paths) {
                    self.status_message = Some(format!("Open failed: {e}"));
                    self.status_message_time = Some(std::time::Instant::now());
                }
            }
        }
    }

    /// Run an editor on the given paths, suspending the TUI while the editor runs.
    ///
    /// Checks `$VISUAL` first, then `$EDITOR`, then falls back to `vi`.
    /// Suspends the terminal, spawns the editor, waits for it to exit, then restores.
    fn run_editor(terminal_manager: &mut TerminalManager, paths: &[PathBuf]) -> io::Result<()> {
        let editor = std::env::var("VISUAL")
            .or_else(|_| std::env::var("EDITOR"))
            .unwrap_or_else(|_| "vi".to_string());

        TerminalManager::suspend()?;

        let status = std::process::Command::new(&editor).args(paths).status();

        // Always try to restore, even if the editor failed
        TerminalManager::restore(terminal_manager.terminal_mut())?;

        match status {
            Ok(exit_status) if exit_status.success() => Ok(()),
            Ok(exit_status) => Err(io::Error::other(format!(
                "Editor exited with status: {exit_status}"
            ))),
            Err(e) => Err(e),
        }
    }

    /// Open paths with the system default viewer (fire-and-forget).
    ///
    /// Uses `open` on macOS and `xdg-open` on Linux. Spawns detached processes
    /// that don't block the TUI.
    fn open_with_system_viewer(paths: &[PathBuf]) -> io::Result<()> {
        #[cfg(target_os = "macos")]
        let opener = "open";
        #[cfg(target_os = "linux")]
        let opener = "xdg-open";
        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
        let opener = "xdg-open"; // Best guess for other Unix-likes

        for path in paths {
            std::process::Command::new(opener)
                .arg(path)
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()?;
        }
        Ok(())
    }
}

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

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

    #[test]
    fn sort_mode_default_is_expiration() {
        let mode = SortMode::default();
        assert_eq!(
            mode,
            SortMode::Expiration,
            "Default sort mode should be Expiration"
        );
    }

    #[test]
    fn app_new_has_correct_defaults() {
        let app = App::new();
        assert!(!app.should_quit, "App should not start in quit state");
        assert_eq!(
            app.view,
            View::FileList,
            "App should start in FileList view"
        );
        assert_eq!(
            app.focus_panel,
            FocusPanel::MainPanel,
            "App should start with main panel focused for immediate file interaction"
        );
        assert_eq!(
            app.sidebar_selected_index, 0,
            "App should start with sidebar index 0"
        );
        assert_eq!(
            app.entry_selected_index, 0,
            "App should start with entry index 0"
        );
        assert_eq!(
            app.sort_mode,
            SortMode::Expiration,
            "App should start with Expiration sort mode"
        );
        assert_eq!(app.filter_days, None, "App should start with no filter");
        assert_eq!(app.sidebar_len, 0, "App should start with sidebar_len 0");
        assert_eq!(
            app.entry_list_len, 0,
            "App should start with entry_list_len 0"
        );
        assert_eq!(
            app.current_root_id, None,
            "App should start with no root selected"
        );
        assert!(
            app.current_path.as_os_str().is_empty(),
            "App should start with empty current_path"
        );
        assert_eq!(
            app.pending_entry_delete, None,
            "App should start with no pending entry delete"
        );
        assert_eq!(
            app.pending_entry_deferral, None,
            "App should start with no pending entry deferral"
        );
        assert_eq!(
            app.pending_entry_ignore, None,
            "App should start with no pending entry ignore"
        );
        assert_eq!(
            app.pending_entry_approval, None,
            "App should start with no pending entry approval"
        );
        assert!(
            app.selected_entries.is_empty(),
            "App should start with no selected entries"
        );
        assert_eq!(
            app.pending_add_path, None,
            "App should start with no pending add path"
        );
        assert_eq!(
            app.pending_remove_path, None,
            "App should start with no pending remove path"
        );
        assert_eq!(
            app.pending_audit_export, None,
            "App should start with no pending audit export"
        );
        assert!(
            app.pending_dry_run.is_none(),
            "App should start with no pending dry run"
        );
        assert_eq!(
            app.nearest_expiration, None,
            "App should start with no cached expiration"
        );
        assert_eq!(
            app.search_query, None,
            "App should start with no search query"
        );
        assert!(
            !app.search_input_active,
            "App should start with search input inactive"
        );
    }

    #[test]
    fn app_select_last_sidebar_with_empty_list() {
        let mut app = App::new();
        app.select_last_sidebar(0);
        assert_eq!(
            app.sidebar_selected_index, 0,
            "Selecting last in empty sidebar should set index to 0"
        );
    }

    #[test]
    fn app_select_last_sidebar_with_nonempty_list() {
        let mut app = App::new();
        app.select_last_sidebar(10);
        assert_eq!(
            app.sidebar_selected_index, 9,
            "Selecting last in sidebar of 10 should set index to 9"
        );
    }

    #[test]
    fn app_select_last_entry_with_empty_list() {
        let mut app = App::new();
        app.select_last_entry(0);
        assert_eq!(
            app.entry_selected_index, 0,
            "Selecting last in empty entry list should set index to 0"
        );
    }

    #[test]
    fn app_select_last_entry_with_nonempty_list() {
        let mut app = App::new();
        app.select_last_entry(10);
        assert_eq!(
            app.entry_selected_index, 9,
            "Selecting last in entry list of 10 should set index to 9"
        );
    }

    #[test]
    fn app_getters_return_correct_values() {
        let mut app = App::new();
        app.view = View::Help;
        app.focus_panel = FocusPanel::MainPanel;
        app.sidebar_selected_index = 3;
        app.entry_selected_index = 5;
        app.sort_mode = SortMode::Size;
        app.filter_days = Some(30);
        app.current_root_id = Some(42);

        assert_eq!(app.view(), View::Help);
        assert_eq!(app.focus_panel(), FocusPanel::MainPanel);
        assert_eq!(app.sidebar_selected_index(), 3);
        assert_eq!(app.entry_selected_index(), 5);
        assert_eq!(app.sort_mode(), SortMode::Size);
        assert_eq!(app.filter_days(), Some(30));
        assert_eq!(app.current_root_id(), Some(42));
    }

    #[test]
    fn app_navigate_into_sets_path_and_resets_index() {
        let mut app = App::new();
        app.entry_selected_index = 5;
        app.navigate_into(PathBuf::from("/test/path"));
        assert_eq!(app.current_path, PathBuf::from("/test/path"));
        assert_eq!(app.entry_selected_index, 0);
    }

    #[test]
    fn app_navigate_up_goes_to_parent() {
        let mut app = App::new();
        app.current_path = PathBuf::from("/test/path/child");
        app.entry_selected_index = 5;
        app.navigate_up();
        assert_eq!(app.current_path, PathBuf::from("/test/path"));
        assert_eq!(app.entry_selected_index, 0);
    }

    #[test]
    fn app_navigate_up_at_root_is_noop() {
        let mut app = App::new();
        app.current_path = PathBuf::from("/");
        app.entry_selected_index = 5;
        app.navigate_up();
        // "/" has no parent, so navigate_up is a no-op (path and index unchanged).
        assert_eq!(app.current_path, PathBuf::from("/"));
        assert_eq!(app.entry_selected_index, 5);
    }
}