rustdupe 0.1.0

Smart duplicate file finder with interactive TUI
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
//! TUI application state management.
//!
//! # Overview
//!
//! This module manages the application state for the interactive TUI, including:
//! - Current mode (Scanning, Reviewing, Previewing, Confirming, Quitting)
//! - Duplicate groups for display
//! - Navigation state (selected index, scroll offset)
//! - Selection state (files marked for deletion)
//!
//! # Architecture
//!
//! The `App` struct is the central state container for the TUI. It is designed
//! to be accessed only from the main thread (terminal operations are not thread-safe).
//! State transitions are explicit through method calls.
//!
//! # Example
//!
//! ```
//! use rustdupe::tui::app::{App, AppMode};
//! use rustdupe::duplicates::DuplicateGroup;
//! use std::path::PathBuf;
//!
//! // Create a new app instance
//! let mut app = App::new();
//!
//! // Set up with duplicate groups
//! let groups = vec![
//!     DuplicateGroup::new(
//!         [0u8; 32],
//!         1000,
//!         vec![PathBuf::from("/a.txt"), PathBuf::from("/b.txt")],
//!     ),
//! ];
//! app.set_groups(groups);
//! app.set_mode(AppMode::Reviewing);
//!
//! // Navigate and select
//! app.next();
//! app.toggle_select();
//!
//! assert!(app.is_file_selected(&PathBuf::from("/b.txt")));
//! ```

use std::collections::HashSet;
use std::path::PathBuf;

use crate::duplicates::DuplicateGroup;

/// Application mode/state.
///
/// Represents the current state of the TUI application. Modes control
/// what is displayed and which actions are available.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AppMode {
    /// Scanning in progress - shows progress bar and stats
    #[default]
    Scanning,
    /// Reviewing duplicate groups - main navigation mode
    Reviewing,
    /// Previewing a file's content
    Previewing,
    /// Confirming a deletion operation
    Confirming,
    /// Application is quitting
    Quitting,
}

impl AppMode {
    /// Check if the application is in a navigable state.
    #[must_use]
    pub fn is_navigable(&self) -> bool {
        matches!(self, Self::Reviewing)
    }

    /// Check if the application is done (quitting).
    #[must_use]
    pub fn is_done(&self) -> bool {
        matches!(self, Self::Quitting)
    }
}

/// User action triggered by keyboard input.
///
/// Actions are the result of key event processing and represent
/// user intentions that modify application state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    /// Navigate up in the list
    NavigateUp,
    /// Navigate down in the list
    NavigateDown,
    /// Navigate to next group
    NextGroup,
    /// Navigate to previous group
    PreviousGroup,
    /// Toggle selection of current item
    ToggleSelect,
    /// Select all files in current group (except first)
    SelectAllInGroup,
    /// Deselect all files
    DeselectAll,
    /// Preview the selected file
    Preview,
    /// Delete selected files (to trash)
    Delete,
    /// Confirm current action
    Confirm,
    /// Cancel current action
    Cancel,
    /// Quit the application
    Quit,
}

/// Scan summary for display in TUI.
///
/// Contains statistics about the completed scan to display to the user.
#[derive(Debug, Clone, Default)]
pub struct ScanProgress {
    /// Current phase name (e.g., "Walking", "Prehashing", "Full hashing")
    pub phase: String,
    /// Current file being processed
    pub current_path: String,
    /// Number of files processed so far
    pub current: usize,
    /// Total number of files to process (0 if unknown)
    pub total: usize,
    /// Human-readable status message
    pub message: String,
}

impl ScanProgress {
    /// Create a new scan progress.
    ///
    /// # Example
    ///
    /// ```
    /// use rustdupe::tui::app::ScanProgress;
    /// let progress = ScanProgress::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Calculate progress percentage (0-100).
    #[must_use]
    pub fn percentage(&self) -> u16 {
        if self.total == 0 {
            0
        } else {
            ((self.current as f64 / self.total as f64) * 100.0).min(100.0) as u16
        }
    }
}

/// TUI application state.
///
/// The central state container for the TUI application. Manages:
/// - Current mode and navigation state
/// - Duplicate groups to display
/// - User selections for batch operations
///
/// # Thread Safety
///
/// This struct is NOT thread-safe and should only be accessed from the main thread.
/// Terminal operations are not thread-safe, so all TUI state modifications
/// must happen on the main thread.
#[derive(Debug, Clone)]
pub struct App {
    /// Current application mode
    mode: AppMode,
    /// Duplicate groups to display
    groups: Vec<DuplicateGroup>,
    /// Currently selected group index
    group_index: usize,
    /// Currently selected file index within the group
    file_index: usize,
    /// Scroll offset for the group list
    group_scroll: usize,
    /// Scroll offset for the file list within current group
    file_scroll: usize,
    /// Files marked for deletion (PathBuf set for O(1) lookup)
    selected_files: HashSet<PathBuf>,
    /// Scan progress (for Scanning mode)
    scan_progress: ScanProgress,
    /// Error message to display (if any)
    error_message: Option<String>,
    /// Preview content (for Previewing mode)
    preview_content: Option<String>,
    /// Total reclaimable space in bytes
    reclaimable_space: u64,
    /// Number of visible rows in the UI (for scroll calculation)
    visible_rows: usize,
}

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

impl App {
    /// Create a new App instance with empty state.
    ///
    /// The app starts in Scanning mode with no groups loaded.
    ///
    /// # Example
    ///
    /// ```
    /// use rustdupe::tui::app::App;
    /// let app = App::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            mode: AppMode::Scanning,
            groups: Vec::new(),
            group_index: 0,
            file_index: 0,
            group_scroll: 0,
            file_scroll: 0,
            selected_files: HashSet::new(),
            scan_progress: ScanProgress::new(),
            error_message: None,
            preview_content: None,
            reclaimable_space: 0,
            visible_rows: 20, // Default, will be updated by UI
        }
    }

    /// Create an App with pre-loaded duplicate groups.
    ///
    /// The app starts in Reviewing mode if groups are provided.
    ///
    /// # Example
    ///
    /// ```
    /// use rustdupe::tui::app::App;
    /// use rustdupe::duplicates::DuplicateGroup;
    /// let app = App::with_groups(vec![]);
    /// ```
    #[must_use]
    pub fn with_groups(groups: Vec<DuplicateGroup>) -> Self {
        let reclaimable = groups.iter().map(DuplicateGroup::wasted_space).sum();
        let mode = if groups.is_empty() {
            AppMode::Scanning
        } else {
            AppMode::Reviewing
        };

        Self {
            mode,
            groups,
            group_index: 0,
            file_index: 0,
            group_scroll: 0,
            file_scroll: 0,
            selected_files: HashSet::new(),
            scan_progress: ScanProgress::new(),
            error_message: None,
            preview_content: None,
            reclaimable_space: reclaimable,
            visible_rows: 20,
        }
    }

    // ==================== Mode Management ====================

    /// Get the current application mode.
    #[must_use]
    pub fn mode(&self) -> AppMode {
        self.mode
    }

    /// Set the application mode.
    ///
    /// This is the only way to change modes - state transitions are explicit.
    pub fn set_mode(&mut self, mode: AppMode) {
        log::debug!("Mode transition: {:?} -> {:?}", self.mode, mode);
        self.mode = mode;
    }

    /// Check if the application should quit.
    #[must_use]
    pub fn should_quit(&self) -> bool {
        self.mode.is_done()
    }

    // ==================== Group Management ====================

    /// Get the duplicate groups.
    #[must_use]
    pub fn groups(&self) -> &[DuplicateGroup] {
        &self.groups
    }

    /// Set the duplicate groups and recalculate stats.
    ///
    /// This also resets navigation state and calculates reclaimable space.
    pub fn set_groups(&mut self, groups: Vec<DuplicateGroup>) {
        self.reclaimable_space = groups.iter().map(DuplicateGroup::wasted_space).sum();
        self.groups = groups;
        self.group_index = 0;
        self.file_index = 0;
        self.group_scroll = 0;
        self.file_scroll = 0;
        self.selected_files.clear();

        log::info!(
            "Loaded {} duplicate groups, {} bytes reclaimable",
            self.groups.len(),
            self.reclaimable_space
        );
    }

    /// Get the number of duplicate groups.
    #[must_use]
    pub fn group_count(&self) -> usize {
        self.groups.len()
    }

    /// Check if there are any duplicate groups.
    #[must_use]
    pub fn has_groups(&self) -> bool {
        !self.groups.is_empty()
    }

    /// Get the total reclaimable space in bytes.
    #[must_use]
    pub fn reclaimable_space(&self) -> u64 {
        self.reclaimable_space
    }

    /// Get the total number of duplicate files.
    #[must_use]
    pub fn duplicate_file_count(&self) -> usize {
        self.groups.iter().map(|g| g.files.len()).sum()
    }

    // ==================== Navigation ====================

    /// Get the currently selected group index.
    #[must_use]
    pub fn group_index(&self) -> usize {
        self.group_index
    }

    /// Get the currently selected file index within the group.
    #[must_use]
    pub fn file_index(&self) -> usize {
        self.file_index
    }

    /// Get the current group scroll offset.
    #[must_use]
    pub fn group_scroll(&self) -> usize {
        self.group_scroll
    }

    /// Get the current file scroll offset.
    #[must_use]
    pub fn file_scroll(&self) -> usize {
        self.file_scroll
    }

    /// Set the number of visible rows (for scroll calculation).
    pub fn set_visible_rows(&mut self, rows: usize) {
        self.visible_rows = rows.max(1);
    }

    /// Get the currently selected group (if any).
    #[must_use]
    pub fn current_group(&self) -> Option<&DuplicateGroup> {
        self.groups.get(self.group_index)
    }

    /// Get the currently selected file path (if any).
    #[must_use]
    pub fn current_file(&self) -> Option<&PathBuf> {
        self.current_group()
            .and_then(|g| g.files.get(self.file_index))
    }

    /// Navigate to the next file in the current group.
    ///
    /// If at the end of the group, stays at the last file.
    pub fn next(&mut self) {
        if !self.mode.is_navigable() || self.groups.is_empty() {
            return;
        }

        if let Some(group) = self.current_group() {
            if self.file_index + 1 < group.files.len() {
                self.file_index += 1;
                self.update_file_scroll();
                log::trace!("Navigate next: file_index = {}", self.file_index);
            }
        }
    }

    /// Navigate to the previous file in the current group.
    ///
    /// If at the start of the group, stays at the first file.
    pub fn previous(&mut self) {
        if !self.mode.is_navigable() || self.groups.is_empty() {
            return;
        }

        if self.file_index > 0 {
            self.file_index -= 1;
            self.update_file_scroll();
            log::trace!("Navigate previous: file_index = {}", self.file_index);
        }
    }

    /// Navigate to the next duplicate group.
    pub fn next_group(&mut self) {
        if !self.mode.is_navigable() || self.groups.is_empty() {
            return;
        }

        if self.group_index + 1 < self.groups.len() {
            self.group_index += 1;
            self.file_index = 0;
            self.file_scroll = 0;
            self.update_group_scroll();
            log::trace!("Navigate next group: group_index = {}", self.group_index);
        }
    }

    /// Navigate to the previous duplicate group.
    pub fn previous_group(&mut self) {
        if !self.mode.is_navigable() || self.groups.is_empty() {
            return;
        }

        if self.group_index > 0 {
            self.group_index -= 1;
            self.file_index = 0;
            self.file_scroll = 0;
            self.update_group_scroll();
            log::trace!(
                "Navigate previous group: group_index = {}",
                self.group_index
            );
        }
    }

    /// Update file scroll to keep current selection visible.
    fn update_file_scroll(&mut self) {
        // Scroll down if selection is below visible area
        if self.file_index >= self.file_scroll + self.visible_rows {
            self.file_scroll = self.file_index - self.visible_rows + 1;
        }
        // Scroll up if selection is above visible area
        if self.file_index < self.file_scroll {
            self.file_scroll = self.file_index;
        }
    }

    /// Update group scroll to keep current selection visible.
    fn update_group_scroll(&mut self) {
        // Scroll down if selection is below visible area
        if self.group_index >= self.group_scroll + self.visible_rows {
            self.group_scroll = self.group_index - self.visible_rows + 1;
        }
        // Scroll up if selection is above visible area
        if self.group_index < self.group_scroll {
            self.group_scroll = self.group_index;
        }
    }

    // ==================== Selection Management ====================

    /// Get the set of selected file paths.
    #[must_use]
    pub fn selected_files(&self) -> &HashSet<PathBuf> {
        &self.selected_files
    }

    /// Get selected files as a sorted vector (for display/operations).
    #[must_use]
    pub fn selected_files_vec(&self) -> Vec<PathBuf> {
        let mut files: Vec<PathBuf> = self.selected_files.iter().cloned().collect();
        files.sort();
        files
    }

    /// Get the number of selected files.
    #[must_use]
    pub fn selected_count(&self) -> usize {
        self.selected_files.len()
    }

    /// Check if any files are selected.
    #[must_use]
    pub fn has_selections(&self) -> bool {
        !self.selected_files.is_empty()
    }

    /// Check if a specific file is selected.
    #[must_use]
    pub fn is_file_selected(&self, path: &PathBuf) -> bool {
        self.selected_files.contains(path)
    }

    /// Check if the currently highlighted file is selected.
    #[must_use]
    pub fn is_current_selected(&self) -> bool {
        self.current_file()
            .is_some_and(|f| self.selected_files.contains(f))
    }

    /// Toggle selection of the currently highlighted file.
    ///
    /// If the file is selected, it will be deselected, and vice versa.
    pub fn toggle_select(&mut self) {
        if let Some(path) = self.current_file().cloned() {
            if self.selected_files.contains(&path) {
                self.selected_files.remove(&path);
                log::debug!("Deselected: {}", path.display());
            } else {
                self.selected_files.insert(path.clone());
                log::debug!("Selected: {}", path.display());
            }
        }
    }

    /// Select a specific file.
    pub fn select(&mut self, path: PathBuf) {
        self.selected_files.insert(path);
    }

    /// Deselect a specific file.
    pub fn deselect(&mut self, path: &PathBuf) {
        self.selected_files.remove(path);
    }

    /// Select all files in the current group except the first one.
    ///
    /// The first file is preserved as the "original" that should be kept.
    pub fn select_all_in_group(&mut self) {
        // Clone files to avoid borrow conflict
        let files_to_select: Vec<PathBuf> = self
            .current_group()
            .map(|g| g.files.iter().skip(1).cloned().collect())
            .unwrap_or_default();

        let count = files_to_select.len();
        for path in files_to_select {
            self.selected_files.insert(path);
        }

        if count > 0 {
            log::debug!("Selected {} files in group (keeping first)", count);
        }
    }

    /// Deselect all files.
    pub fn deselect_all(&mut self) {
        let count = self.selected_files.len();
        self.selected_files.clear();
        log::debug!("Deselected all {} files", count);
    }

    /// Remove files from groups after successful deletion.
    ///
    /// This updates the internal state to reflect deleted files.
    pub fn remove_deleted_files(&mut self, deleted: &[PathBuf]) {
        let deleted_set: HashSet<&PathBuf> = deleted.iter().collect();

        // Remove from selection
        self.selected_files.retain(|p| !deleted_set.contains(p));

        // Remove from groups and filter empty groups
        for group in &mut self.groups {
            group.files.retain(|p| !deleted_set.contains(p));
        }

        // Remove groups with less than 2 files (no longer duplicates)
        self.groups.retain(|g| g.files.len() >= 2);

        // Recalculate reclaimable space
        self.reclaimable_space = self.groups.iter().map(DuplicateGroup::wasted_space).sum();

        // Fix navigation if needed
        if self.group_index >= self.groups.len() && !self.groups.is_empty() {
            self.group_index = self.groups.len() - 1;
        }
        if let Some(group) = self.current_group() {
            if self.file_index >= group.files.len() && !group.files.is_empty() {
                self.file_index = group.files.len() - 1;
            }
        } else {
            self.file_index = 0;
        }

        log::info!(
            "Removed {} deleted files, {} groups remaining",
            deleted.len(),
            self.groups.len()
        );
    }

    // ==================== Scan Progress ====================

    /// Get the scan progress.
    #[must_use]
    pub fn scan_progress(&self) -> &ScanProgress {
        &self.scan_progress
    }

    /// Update the scan progress.
    pub fn update_scan_progress(&mut self, phase: &str, current: usize, total: usize, path: &str) {
        self.scan_progress.phase = phase.to_string();
        self.scan_progress.current = current;
        self.scan_progress.total = total;
        self.scan_progress.current_path = path.to_string();
    }

    /// Set a status message for the scan progress.
    pub fn set_scan_message(&mut self, message: &str) {
        self.scan_progress.message = message.to_string();
    }

    // ==================== Error Handling ====================

    /// Get the current error message (if any).
    #[must_use]
    pub fn error_message(&self) -> Option<&str> {
        self.error_message.as_deref()
    }

    /// Set an error message to display.
    pub fn set_error(&mut self, message: &str) {
        self.error_message = Some(message.to_string());
        log::error!("App error: {}", message);
    }

    /// Clear the error message.
    pub fn clear_error(&mut self) {
        self.error_message = None;
    }

    // ==================== Preview ====================

    /// Get the preview content (if any).
    #[must_use]
    pub fn preview_content(&self) -> Option<&str> {
        self.preview_content.as_deref()
    }

    /// Set the preview content.
    pub fn set_preview(&mut self, content: String) {
        self.preview_content = Some(content);
    }

    /// Clear the preview content.
    pub fn clear_preview(&mut self) {
        self.preview_content = None;
    }

    // ==================== Action Handling ====================

    /// Handle a user action and update state accordingly.
    ///
    /// Returns true if the action was handled.
    ///
    /// # Example
    ///
    /// ```
    /// use rustdupe::tui::app::{App, Action};
    /// let mut app = App::new();
    /// app.handle_action(Action::Quit);
    /// assert!(app.should_quit());
    /// ```
    pub fn handle_action(&mut self, action: Action) -> bool {
        log::trace!("Handling action: {:?} in mode {:?}", action, self.mode);

        match action {
            Action::NavigateUp => {
                self.previous();
                true
            }
            Action::NavigateDown => {
                self.next();
                true
            }
            Action::NextGroup => {
                self.next_group();
                true
            }
            Action::PreviousGroup => {
                self.previous_group();
                true
            }
            Action::ToggleSelect => {
                self.toggle_select();
                true
            }
            Action::SelectAllInGroup => {
                self.select_all_in_group();
                true
            }
            Action::DeselectAll => {
                self.deselect_all();
                true
            }
            Action::Preview => {
                if self.mode == AppMode::Reviewing && self.current_file().is_some() {
                    self.set_mode(AppMode::Previewing);
                    true
                } else {
                    false
                }
            }
            Action::Delete => {
                if self.mode == AppMode::Reviewing && self.has_selections() {
                    self.set_mode(AppMode::Confirming);
                    true
                } else {
                    false
                }
            }
            Action::Confirm => {
                // Confirmation handling is done by the TUI main loop
                true
            }
            Action::Cancel => {
                match self.mode {
                    AppMode::Previewing => {
                        self.clear_preview();
                        self.set_mode(AppMode::Reviewing);
                    }
                    AppMode::Confirming => {
                        self.set_mode(AppMode::Reviewing);
                    }
                    _ => {}
                }
                true
            }
            Action::Quit => {
                self.set_mode(AppMode::Quitting);
                true
            }
        }
    }
}

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

    fn make_group(size: u64, paths: Vec<&str>) -> DuplicateGroup {
        DuplicateGroup::new(
            [0u8; 32],
            size,
            paths.into_iter().map(PathBuf::from).collect(),
        )
    }

    #[test]
    fn test_app_new() {
        let app = App::new();
        assert_eq!(app.mode(), AppMode::Scanning);
        assert!(app.groups().is_empty());
        assert_eq!(app.group_index(), 0);
        assert_eq!(app.file_index(), 0);
        assert!(!app.has_selections());
    }

    #[test]
    fn test_app_with_groups() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt"])];
        let app = App::with_groups(groups);

        assert_eq!(app.mode(), AppMode::Reviewing);
        assert_eq!(app.group_count(), 1);
        assert_eq!(app.reclaimable_space(), 100); // 1 duplicate = 100 bytes wasted
    }

    #[test]
    fn test_app_with_empty_groups() {
        let app = App::with_groups(vec![]);
        assert_eq!(app.mode(), AppMode::Scanning);
        assert!(!app.has_groups());
    }

    #[test]
    fn test_set_groups() {
        let mut app = App::new();
        let groups = vec![
            make_group(100, vec!["/a.txt", "/b.txt"]),
            make_group(200, vec!["/c.txt", "/d.txt", "/e.txt"]),
        ];
        app.set_groups(groups);

        assert_eq!(app.group_count(), 2);
        assert_eq!(app.reclaimable_space(), 100 + 400); // 1*100 + 2*200
        assert_eq!(app.group_index(), 0);
        assert_eq!(app.file_index(), 0);
    }

    #[test]
    fn test_navigation_next_previous() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt", "/c.txt"])];
        let mut app = App::with_groups(groups);

        assert_eq!(app.file_index(), 0);

        app.next();
        assert_eq!(app.file_index(), 1);

        app.next();
        assert_eq!(app.file_index(), 2);

        // At end, should stay at last
        app.next();
        assert_eq!(app.file_index(), 2);

        app.previous();
        assert_eq!(app.file_index(), 1);

        app.previous();
        assert_eq!(app.file_index(), 0);

        // At start, should stay at first
        app.previous();
        assert_eq!(app.file_index(), 0);
    }

    #[test]
    fn test_navigation_groups() {
        let groups = vec![
            make_group(100, vec!["/a.txt", "/b.txt"]),
            make_group(200, vec!["/c.txt", "/d.txt"]),
            make_group(300, vec!["/e.txt", "/f.txt"]),
        ];
        let mut app = App::with_groups(groups);

        assert_eq!(app.group_index(), 0);

        app.next_group();
        assert_eq!(app.group_index(), 1);
        assert_eq!(app.file_index(), 0); // Reset file index

        app.next_group();
        assert_eq!(app.group_index(), 2);

        // At end, should stay
        app.next_group();
        assert_eq!(app.group_index(), 2);

        app.previous_group();
        assert_eq!(app.group_index(), 1);

        app.previous_group();
        assert_eq!(app.group_index(), 0);

        // At start, should stay
        app.previous_group();
        assert_eq!(app.group_index(), 0);
    }

    #[test]
    fn test_navigation_not_in_reviewing_mode() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt"])];
        let mut app = App::with_groups(groups);
        app.set_mode(AppMode::Scanning);

        app.next();
        assert_eq!(app.file_index(), 0); // Should not move
    }

    #[test]
    fn test_toggle_select() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt"])];
        let mut app = App::with_groups(groups);

        assert!(!app.is_current_selected());

        app.toggle_select();
        assert!(app.is_current_selected());
        assert_eq!(app.selected_count(), 1);

        app.toggle_select();
        assert!(!app.is_current_selected());
        assert_eq!(app.selected_count(), 0);
    }

    #[test]
    fn test_select_all_in_group() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt", "/c.txt"])];
        let mut app = App::with_groups(groups);

        app.select_all_in_group();

        // First file should NOT be selected (preserved as original)
        assert!(!app.is_file_selected(&PathBuf::from("/a.txt")));
        assert!(app.is_file_selected(&PathBuf::from("/b.txt")));
        assert!(app.is_file_selected(&PathBuf::from("/c.txt")));
        assert_eq!(app.selected_count(), 2);
    }

    #[test]
    fn test_deselect_all() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt", "/c.txt"])];
        let mut app = App::with_groups(groups);

        app.select_all_in_group();
        assert_eq!(app.selected_count(), 2);

        app.deselect_all();
        assert_eq!(app.selected_count(), 0);
    }

    #[test]
    fn test_selected_files_vec() {
        let groups = vec![make_group(100, vec!["/z.txt", "/a.txt", "/m.txt"])];
        let mut app = App::with_groups(groups);

        app.select_all_in_group();
        let selected = app.selected_files_vec();

        // Should be sorted
        assert_eq!(
            selected,
            vec![PathBuf::from("/a.txt"), PathBuf::from("/m.txt")]
        );
    }

    #[test]
    fn test_remove_deleted_files() {
        let groups = vec![
            make_group(100, vec!["/a.txt", "/b.txt", "/c.txt"]),
            make_group(200, vec!["/d.txt", "/e.txt"]),
        ];
        let mut app = App::with_groups(groups);
        app.select(PathBuf::from("/b.txt"));
        app.select(PathBuf::from("/e.txt"));

        // Delete /b.txt and /e.txt
        app.remove_deleted_files(&[PathBuf::from("/b.txt"), PathBuf::from("/e.txt")]);

        // /b.txt should be removed from first group
        assert_eq!(app.groups()[0].files.len(), 2);
        assert!(!app.groups()[0].files.contains(&PathBuf::from("/b.txt")));

        // Second group now has only 1 file, so it's removed (not duplicates anymore)
        assert_eq!(app.group_count(), 1);

        // Selections should be cleared for deleted files
        assert!(!app.is_file_selected(&PathBuf::from("/b.txt")));
        assert!(!app.is_file_selected(&PathBuf::from("/e.txt")));
    }

    #[test]
    fn test_current_file() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt"])];
        let mut app = App::with_groups(groups);

        assert_eq!(app.current_file(), Some(&PathBuf::from("/a.txt")));

        app.next();
        assert_eq!(app.current_file(), Some(&PathBuf::from("/b.txt")));
    }

    #[test]
    fn test_current_group() {
        let groups = vec![
            make_group(100, vec!["/a.txt", "/b.txt"]),
            make_group(200, vec!["/c.txt", "/d.txt"]),
        ];
        let mut app = App::with_groups(groups);

        let group = app.current_group().unwrap();
        assert_eq!(group.size, 100);

        app.next_group();
        let group = app.current_group().unwrap();
        assert_eq!(group.size, 200);
    }

    #[test]
    fn test_mode_transitions() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt"])];
        let mut app = App::with_groups(groups);

        assert_eq!(app.mode(), AppMode::Reviewing);

        app.set_mode(AppMode::Previewing);
        assert_eq!(app.mode(), AppMode::Previewing);

        app.set_mode(AppMode::Confirming);
        assert_eq!(app.mode(), AppMode::Confirming);

        app.set_mode(AppMode::Quitting);
        assert!(app.should_quit());
    }

    #[test]
    fn test_handle_action_navigate() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt", "/c.txt"])];
        let mut app = App::with_groups(groups);

        assert!(app.handle_action(Action::NavigateDown));
        assert_eq!(app.file_index(), 1);

        assert!(app.handle_action(Action::NavigateUp));
        assert_eq!(app.file_index(), 0);
    }

    #[test]
    fn test_handle_action_toggle_select() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt"])];
        let mut app = App::with_groups(groups);

        assert!(app.handle_action(Action::ToggleSelect));
        assert!(app.is_current_selected());
    }

    #[test]
    fn test_handle_action_preview() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt"])];
        let mut app = App::with_groups(groups);

        assert!(app.handle_action(Action::Preview));
        assert_eq!(app.mode(), AppMode::Previewing);
    }

    #[test]
    fn test_handle_action_delete_requires_selection() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt"])];
        let mut app = App::with_groups(groups);

        // Without selection, delete should not work
        assert!(!app.handle_action(Action::Delete));
        assert_eq!(app.mode(), AppMode::Reviewing);

        // With selection, delete should transition to Confirming
        app.toggle_select();
        assert!(app.handle_action(Action::Delete));
        assert_eq!(app.mode(), AppMode::Confirming);
    }

    #[test]
    fn test_handle_action_cancel() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt"])];
        let mut app = App::with_groups(groups);

        app.set_mode(AppMode::Previewing);
        assert!(app.handle_action(Action::Cancel));
        assert_eq!(app.mode(), AppMode::Reviewing);

        app.toggle_select();
        app.set_mode(AppMode::Confirming);
        assert!(app.handle_action(Action::Cancel));
        assert_eq!(app.mode(), AppMode::Reviewing);
    }

    #[test]
    fn test_handle_action_quit() {
        let groups = vec![make_group(100, vec!["/a.txt", "/b.txt"])];
        let mut app = App::with_groups(groups);

        assert!(app.handle_action(Action::Quit));
        assert!(app.should_quit());
    }

    #[test]
    fn test_scan_progress() {
        let mut app = App::new();

        app.update_scan_progress("Walking", 50, 100, "/some/path/file.txt");

        let progress = app.scan_progress();
        assert_eq!(progress.phase, "Walking");
        assert_eq!(progress.current, 50);
        assert_eq!(progress.total, 100);
        assert_eq!(progress.percentage(), 50);
    }

    #[test]
    fn test_scan_progress_percentage() {
        let mut progress = ScanProgress::new();

        // 0 total should return 0%
        assert_eq!(progress.percentage(), 0);

        progress.total = 100;
        progress.current = 25;
        assert_eq!(progress.percentage(), 25);

        progress.current = 100;
        assert_eq!(progress.percentage(), 100);

        // Over 100% should cap at 100
        progress.current = 150;
        assert_eq!(progress.percentage(), 100);
    }

    #[test]
    fn test_error_handling() {
        let mut app = App::new();

        assert!(app.error_message().is_none());

        app.set_error("Something went wrong");
        assert_eq!(app.error_message(), Some("Something went wrong"));

        app.clear_error();
        assert!(app.error_message().is_none());
    }

    #[test]
    fn test_preview_handling() {
        let mut app = App::new();

        assert!(app.preview_content().is_none());

        app.set_preview("File content here".to_string());
        assert_eq!(app.preview_content(), Some("File content here"));

        app.clear_preview();
        assert!(app.preview_content().is_none());
    }

    #[test]
    fn test_app_mode_is_navigable() {
        assert!(!AppMode::Scanning.is_navigable());
        assert!(AppMode::Reviewing.is_navigable());
        assert!(!AppMode::Previewing.is_navigable());
        assert!(!AppMode::Confirming.is_navigable());
        assert!(!AppMode::Quitting.is_navigable());
    }

    #[test]
    fn test_app_mode_is_done() {
        assert!(!AppMode::Scanning.is_done());
        assert!(!AppMode::Reviewing.is_done());
        assert!(!AppMode::Previewing.is_done());
        assert!(!AppMode::Confirming.is_done());
        assert!(AppMode::Quitting.is_done());
    }

    #[test]
    fn test_duplicate_file_count() {
        let groups = vec![
            make_group(100, vec!["/a.txt", "/b.txt"]), // 2 files
            make_group(200, vec!["/c.txt", "/d.txt", "/e.txt"]), // 3 files
        ];
        let app = App::with_groups(groups);

        assert_eq!(app.duplicate_file_count(), 5);
    }

    #[test]
    fn test_scroll_update_on_navigation() {
        let paths: Vec<&str> = (0..30)
            .map(|i| Box::leak(format!("/file{}.txt", i).into_boxed_str()) as &str)
            .collect();
        let groups = vec![make_group(100, paths)];
        let mut app = App::with_groups(groups);
        app.set_visible_rows(10);

        // Navigate past visible area
        for _ in 0..15 {
            app.next();
        }

        // Scroll should have adjusted
        assert!(app.file_scroll() > 0);
        assert!(app.file_index() >= app.file_scroll());
        assert!(app.file_index() < app.file_scroll() + app.visible_rows);
    }
}