cleansys 0.6.7

CleanSys — modern terminal user interface for system cleanup on Linux, macOS, and Windows (Ratatui TUI + CLI)
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
use anyhow::Result;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crossterm::terminal;
use ratatui::widgets::ListState;
use std::time::Instant;

use crate::components::password_prompt::PasswordPrompt;
use cleansys_core::{check_root, format_size, CleanerCategory, CleanerFn, Status};
use std::time::SystemTime;

#[derive(Debug, Clone)]
pub struct DetailedCleanedItem {
    pub path: String,
    pub size: u64,
    pub category: String,
    pub cleaner_name: String,
    pub timestamp: SystemTime,
    pub item_type: CleanedItemType,
}

#[derive(Debug, Clone, PartialEq)]
pub enum CleanedItemType {
    File,
    Directory,
    Log,
}

impl From<cleansys_core::CleanedItemType> for CleanedItemType {
    fn from(value: cleansys_core::CleanedItemType) -> Self {
        match value {
            cleansys_core::CleanedItemType::File => CleanedItemType::File,
            cleansys_core::CleanedItemType::Directory => CleanedItemType::Directory,
            cleansys_core::CleanedItemType::SymLink => CleanedItemType::File,
        }
    }
}

/// Type alias for pending operations: (category_index, item_index, name, function, requires_root)
pub type PendingOperation = (usize, usize, String, CleanerFn, bool);

#[derive(Debug, Clone, PartialEq)]
pub enum ViewMode {
    Standard,
    Compact,
    Detailed,
    Performance,
}

#[derive(Debug, Clone, PartialEq)]
pub enum SortMode {
    Name,
    Size,
    Status,
    Category,
}

#[derive(Debug, Clone, PartialEq)]
pub enum FilterMode {
    All,
    Selected,
    Completed,
    Errors,
    UserOnly,
    SystemOnly,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ChartType {
    Bar,
    PieCount,
    PieSize,
}

// `Status`, `CleanerItem`, and `CleanerCategory` now live in `cleansys-core`
// so the TUI and GUI front-ends share the exact same domain model.

pub struct App {
    pub categories: Vec<CleanerCategory>,
    pub category_index: usize,
    pub item_list_state: ListState,
    pub is_root: bool,
    pub is_running: bool,
    pub operation_start_time: Option<Instant>,
    pub operation_end_time: Option<Instant>,
    pub total_bytes_cleaned: u64,
    pub show_help: bool,
    pub result_messages: Vec<String>,
    pub detailed_view: bool,
    pub current_cleaner_index: usize,
    pub animation_frame: usize,
    pub last_frame_time: Instant,
    pub terminal_width: u16,
    pub terminal_height: u16,
    pub compact_mode: bool,
    pub show_performance_stats: bool,
    pub operation_count: usize,
    pub errors_count: usize,
    pub paused: bool,
    pub confirmation_mode: bool,
    pub selected_cleaners_count: usize,
    pub view_mode: ViewMode,
    pub sort_mode: SortMode,
    pub filter_mode: FilterMode,
    pub detailed_cleaned_items: Vec<DetailedCleanedItem>,
    pub detailed_list_scroll_state: ListState,
    pub search_query: String,
    pub search_active: bool,
    pub detailed_view_filter: String,
    pub demo_operation_timer: Option<Instant>,
    pub demo_operations_completed: usize,
    pub chart_type: ChartType,
    pub operation_logs: Vec<String>,
    pub show_progress_screen: bool,
    pub password_prompt: PasswordPrompt,
    pub needs_sudo: bool,
    pub pending_operations: Vec<PendingOperation>,
    /// Whether the "confirm this run" overlay is currently shown, awaiting
    /// a yes/no answer before `pending_operations` actually executes.
    pub awaiting_run_confirmation: bool,
    /// Whether the preview (dry-run) results overlay is currently shown.
    pub preview_open: bool,
    /// Results of the most recent preview run: `(cleaner_name, result)`.
    pub preview_results: Vec<(String, cleansys_core::CleaningResult)>,
    /// Whether the "needs Administrator" notice is shown (Windows only;
    /// there is no interactive sudo-password flow there).
    pub needs_admin_notice: bool,
    /// Selected cleaners staged while `awaiting_run_confirmation` is true.
    pub pending_run_selection: Vec<PendingOperation>,
}

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

impl App {
    pub fn new() -> Self {
        // Get initial terminal size
        let (width, height) = terminal::size().unwrap_or((80, 24));

        let mut app = App {
            categories: Vec::new(),
            category_index: 0,
            item_list_state: ListState::default(),
            is_root: check_root(),
            is_running: false,
            operation_start_time: None,
            operation_end_time: None,
            total_bytes_cleaned: 0,
            show_help: false,
            result_messages: Vec::new(),
            detailed_view: false,
            current_cleaner_index: 0,
            animation_frame: 0,
            last_frame_time: Instant::now(),
            terminal_width: width,
            terminal_height: height,
            compact_mode: height < 25,
            show_performance_stats: false,
            operation_count: 0,
            errors_count: 0,
            paused: false,
            confirmation_mode: true,
            selected_cleaners_count: 0,
            view_mode: if height < 25 {
                ViewMode::Compact
            } else {
                ViewMode::Standard
            },
            sort_mode: SortMode::Category,
            filter_mode: FilterMode::All,
            detailed_cleaned_items: Vec::new(),
            detailed_list_scroll_state: ListState::default(),
            search_query: String::new(),
            search_active: false,
            detailed_view_filter: String::new(),
            demo_operation_timer: None,
            demo_operations_completed: 0,
            chart_type: ChartType::PieCount,
            operation_logs: Vec::new(),
            show_progress_screen: false,
            password_prompt: PasswordPrompt::new(),
            needs_sudo: false,
            pending_operations: Vec::new(),
            awaiting_run_confirmation: false,
            preview_open: false,
            preview_results: Vec::new(),
            needs_admin_notice: false,
            pending_run_selection: Vec::new(),
        };
        app.item_list_state.select(Some(0));

        app
    }

    pub fn toggle_search(&mut self) {
        self.search_active = !self.search_active;
        if !self.search_active {
            self.search_query.clear();
        }
    }

    pub fn clear_search(&mut self) {
        self.search_active = false;
        self.search_query.clear();
        self.detailed_view_filter.clear();
    }

    pub fn add_search_char(&mut self, c: char) {
        if self.search_active {
            self.search_query.push(c);
        }
    }

    pub fn remove_search_char(&mut self) {
        if self.search_active {
            self.search_query.pop();
        }
    }

    pub fn get_category_distribution(&self) -> Vec<(String, usize, u64)> {
        let mut category_map: std::collections::HashMap<String, (usize, u64)> =
            std::collections::HashMap::new();

        for item in &self.detailed_cleaned_items {
            // Create a unique key that combines cleaner name with category type
            // This differentiates between user and system cleaners with the same name
            let display_name = if item.category.contains("System") {
                format!("{} (System)", item.cleaner_name)
            } else {
                item.cleaner_name.clone()
            };

            let entry = category_map.entry(display_name).or_insert((0, 0));
            entry.0 += 1;
            entry.1 += item.size;
        }

        let mut categories: Vec<(String, usize, u64)> = category_map
            .into_iter()
            .map(|(name, (count, size))| (name, count, size))
            .collect();

        categories.sort_by_key(|b| std::cmp::Reverse(b.2)); // Sort by size descending
        categories
    }

    pub fn next_item(&mut self) {
        let items = &self.categories[self.category_index].items;
        let i = match self.item_list_state.selected() {
            Some(i) => {
                if i >= items.len() - 1 {
                    0
                } else {
                    i + 1
                }
            }
            None => 0,
        };
        self.item_list_state.select(Some(i));
    }

    pub fn previous_item(&mut self) {
        let items = &self.categories[self.category_index].items;
        let i = match self.item_list_state.selected() {
            Some(i) => {
                if i == 0 {
                    items.len() - 1
                } else {
                    i - 1
                }
            }
            None => 0,
        };
        self.item_list_state.select(Some(i));
    }

    pub fn toggle_selected(&mut self) {
        if let Some(i) = self.item_list_state.selected() {
            let item = &mut self.categories[self.category_index].items[i];
            // Allow selection even for root items, will prompt for password later
            item.selected = !item.selected;
        }
    }

    pub fn next_category(&mut self) {
        if self.category_index < self.categories.len() - 1 {
            self.category_index += 1;
        } else {
            self.category_index = 0;
        }
        // Reset selection in new category
        self.item_list_state.select(Some(0));
    }

    pub fn previous_category(&mut self) {
        if self.category_index > 0 {
            self.category_index -= 1;
        } else {
            self.category_index = self.categories.len() - 1;
        }
        // Reset selection in new category
        self.item_list_state.select(Some(0));
    }

    pub fn toggle_help(&mut self) {
        self.show_help = !self.show_help;
    }

    pub fn select_all(&mut self) {
        for item in &mut self.categories[self.category_index].items {
            // Allow selection of all items, will handle root permissions later
            item.selected = true;
        }
    }

    pub fn deselect_all(&mut self) {
        for item in &mut self.categories[self.category_index].items {
            item.selected = false;
        }
    }

    /// Select every item across every category (not just the active tab).
    pub fn select_all_everywhere(&mut self) {
        for category in &mut self.categories {
            for item in &mut category.items {
                item.selected = true;
            }
        }
    }

    /// Deselect every item across every category (not just the active tab).
    pub fn deselect_all_everywhere(&mut self) {
        for category in &mut self.categories {
            for item in &mut category.items {
                item.selected = false;
            }
        }
    }

    /// Gather selected cleaners and either show the confirmation overlay
    /// (when `confirmation_mode` is on) or start execution immediately.
    pub fn request_run(&mut self) -> Result<()> {
        if self.is_running {
            return Ok(());
        }

        let has_selected = self
            .categories
            .iter()
            .any(|c| c.items.iter().any(|i| i.selected));

        if !has_selected {
            self.result_messages
                .push("No items selected. Please select items to clean.".to_string());
            return Ok(());
        }

        let mut selected_cleaners = Vec::new();
        for (cat_idx, category) in self.categories.iter().enumerate() {
            for (item_idx, item) in category.items.iter().enumerate() {
                if item.selected {
                    let name = item.name.clone();
                    let function = item.function;
                    selected_cleaners.push((cat_idx, item_idx, name, function, item.requires_root));
                }
            }
        }

        if selected_cleaners.is_empty() {
            self.operation_logs
                .push("No cleaners selected. Please select at least one cleaner.".to_string());
            return Ok(());
        }

        if self.confirmation_mode {
            self.pending_run_selection = selected_cleaners;
            self.awaiting_run_confirmation = true;
            Ok(())
        } else {
            self.begin_execution(selected_cleaners)
        }
    }

    /// User confirmed the run in the confirmation overlay.
    pub fn confirm_pending_run(&mut self) -> Result<()> {
        self.awaiting_run_confirmation = false;
        let selected_cleaners = std::mem::take(&mut self.pending_run_selection);
        self.begin_execution(selected_cleaners)
    }

    /// User cancelled the confirmation overlay.
    pub fn cancel_run_confirmation(&mut self) {
        self.awaiting_run_confirmation = false;
        self.pending_run_selection.clear();
    }

    /// Preview (dry-run) every selected cleaner synchronously: measures real
    /// sizes/paths without deleting anything or invoking any mutating
    /// external command, and shows the results in an overlay.
    pub fn run_preview(&mut self) {
        if self.is_running {
            return;
        }

        let selected: Vec<(String, cleansys_core::CleanerFn)> = self
            .categories
            .iter()
            .flat_map(|c| c.items.iter())
            .filter(|i| i.selected)
            .map(|i| (i.name.clone(), i.function))
            .collect();

        if selected.is_empty() {
            self.result_messages
                .push("No items selected. Please select items to preview.".to_string());
            return;
        }

        self.preview_results.clear();
        for (name, function) in selected {
            match function(cleansys_core::RunOptions::preview()) {
                Ok(result) => self.preview_results.push((name, result)),
                Err(e) => self
                    .operation_logs
                    .push(format!("⚠️  Preview failed for {name}: {e}")),
            }
        }
        self.preview_open = true;
    }

    /// Close the preview results overlay.
    pub fn close_preview(&mut self) {
        self.preview_open = false;
        self.preview_results.clear();
    }

    /// Actually kick off execution: reset per-run counters/logs, clear all
    /// items' previous status/bytes_cleaned, and mark the given selection as
    /// `Pending`. Shared by both the direct (already-elevated) path in
    /// [`Self::begin_execution`] and the post-password-authentication path in
    /// [`Self::handle_key`] so the two can never drift out of sync again (a
    /// previous copy-pasted duplicate of this omitted the `item.status =
    /// None` reset and the trailing `update_counters()` call, which could
    /// leave stale status/error counts from a prior run visible after
    /// authenticating via the sudo password prompt).
    fn start_operations(&mut self, selected_cleaners: &[PendingOperation]) {
        self.is_running = true;
        self.show_progress_screen = true;
        self.operation_start_time = Some(Instant::now());
        self.operation_end_time = None;
        self.total_bytes_cleaned = 0;
        self.demo_operation_timer = Some(Instant::now());
        self.demo_operations_completed = 0;
        self.result_messages.clear();
        self.operation_logs.clear();
        self.detailed_cleaned_items.clear(); // Clear previous cleaning results
        self.current_cleaner_index = 0;

        // Reset status and bytes_cleaned for all items to start fresh
        for category in &mut self.categories {
            for item in &mut category.items {
                item.bytes_cleaned = 0;
                item.status = None;
            }
        }

        // Set all selected cleaners to Pending
        for (cat_idx, item_idx, _, _, _) in selected_cleaners {
            self.categories[*cat_idx].items[*item_idx].status = Some(Status::Pending);
        }

        self.update_counters();

        // Operations will be processed by update_demo_operations over time.
        // The is_running flag will be automatically turned off when all
        // operations complete.
    }

    /// Test-only public wrapper around the private [`Self::start_operations`],
    /// so integration tests in `tests/` (a separate crate, which can only
    /// see `pub` items) can drive the exact same post-authentication code
    /// path `handle_key` uses. Only compiled into debug builds.
    #[cfg(debug_assertions)]
    pub fn start_operations_for_tests(&mut self, selected_cleaners: &[PendingOperation]) {
        self.start_operations(selected_cleaners);
    }

    /// Actually start execution of the given selected cleaners: prompts for
    /// elevation if needed (sudo password on Unix, an "Administrator
    /// required" notice on Windows), or starts the run directly.
    fn begin_execution(&mut self, selected_cleaners: Vec<PendingOperation>) -> Result<()> {
        let has_root_operations = selected_cleaners.iter().any(|(_, _, _, _, root)| *root);

        // Check if we need elevation. `is_root` reflects whether the process
        // itself was launched with actual root privileges (e.g. `sudo
        // cleansys`) and never changes at runtime; `password_prompt` tracks
        // whether the user has already authenticated via the in-app sudo
        // dialog this session. Both must be considered here, or a user who
        // already authenticated once would be re-prompted for their
        // password on every subsequent run.
        if has_root_operations && !self.is_root && !self.password_prompt.is_authenticated() {
            self.pending_operations.clone_from(&selected_cleaners);
            if cleansys_core::utils::supports_sudo_prompt() {
                self.needs_sudo = true;
                self.password_prompt.show();
            } else {
                self.needs_admin_notice = true;
            }
            return Ok(());
        }

        self.start_operations(&selected_cleaners);

        Ok(())
    }

    pub fn update_animation(&mut self) {
        let now = Instant::now();
        if now.duration_since(self.last_frame_time).as_millis() > 100 {
            self.animation_frame = (self.animation_frame + 1) % 10;
            self.last_frame_time = now;
        }

        // Update demo operations if running
        if self.is_running {
            self.update_demo_operations();
        }
    }

    pub fn update_demo_operations(&mut self) {
        if let Some(start_time) = self.demo_operation_timer {
            let elapsed = start_time.elapsed().as_millis();

            // Find next pending operation to start
            type Operation = (usize, usize, String, CleanerFn, bool);
            let mut pending_operations: Vec<Operation> = Vec::new();
            for (cat_idx, category) in self.categories.iter().enumerate() {
                for (item_idx, item) in category.items.iter().enumerate() {
                    if matches!(item.status, Some(Status::Pending)) {
                        pending_operations.push((
                            cat_idx,
                            item_idx,
                            item.name.to_string(),
                            item.function,
                            item.requires_root,
                        ));
                    }
                }
            }

            // Start next operation every 1.5 seconds (paced so the progress
            // screen shows operations completing one at a time rather than
            // all at once, even though each one runs synchronously).
            let operations_to_start = (elapsed / 1500) as usize;
            if operations_to_start > self.demo_operations_completed
                && !pending_operations.is_empty()
            {
                if let Some((cat_idx, item_idx, _name, _function, _requires_root)) =
                    pending_operations.first()
                {
                    // Set to running
                    self.categories[*cat_idx].items[*item_idx].status = Some(Status::Running);
                    self.demo_operations_completed += 1;
                }
            }

            // Complete running operations after 2 seconds
            let mut running_operations: Vec<Operation> = Vec::new();
            for (cat_idx, category) in self.categories.iter().enumerate() {
                for (item_idx, item) in category.items.iter().enumerate() {
                    if matches!(item.status, Some(Status::Running)) {
                        running_operations.push((
                            cat_idx,
                            item_idx,
                            item.name.to_string(),
                            item.function,
                            item.requires_root,
                        ));
                    }
                }
            }

            // Complete operations that have been running for at least 2 seconds
            for (cat_idx, item_idx, name, function, requires_root) in running_operations {
                self.operation_logs.push(format!("Starting: {}", name));

                // Check if operation requires root and we don't have it
                let result: anyhow::Result<cleansys_core::CleaningResult> =
                    if requires_root && !self.is_root && !self.password_prompt.is_authenticated() {
                        // Show password prompt and pause operations
                        self.needs_sudo = true;
                        self.password_prompt.show();
                        self.is_running = false;
                        self.operation_logs
                            .push(format!("🔒 {}: Waiting for sudo authentication...", name));
                        // Return error to mark this operation as pending
                        Err(anyhow::anyhow!("Waiting for sudo authentication"))
                    } else {
                        self.operation_logs.push(format!("🔄 Executing: {}", name));
                        function(cleansys_core::RunOptions::execute())
                    };

                // Process result
                match result {
                    Ok(cleaning_result) => {
                        let bytes = cleaning_result.total_bytes;
                        let msg = if requires_root {
                            format!(
                                "Cleaned {} (root) ({}, {} item(s))",
                                name,
                                format_size(bytes),
                                cleaning_result.item_count()
                            )
                        } else {
                            format!(
                                "Cleaned {} ({}, {} item(s))",
                                name,
                                format_size(bytes),
                                cleaning_result.item_count()
                            )
                        };
                        self.categories[cat_idx].items[item_idx].status =
                            Some(Status::Success(msg));
                        self.categories[cat_idx].items[item_idx].bytes_cleaned = bytes;
                        self.total_bytes_cleaned += bytes;
                        self.operation_logs.push(format!(
                            "✅ Completed {}: {} freed across {} item(s)",
                            name,
                            format_size(bytes),
                            cleaning_result.item_count()
                        ));

                        // Record real per-item detail (path + size) for the detailed view.
                        let category_name = self.categories[cat_idx].name.clone();
                        for item in &cleaning_result.items {
                            self.operation_logs.push(format!(
                                "{} ({})",
                                item.path_str(),
                                format_size(item.size)
                            ));
                            self.add_detailed_cleaned_item(
                                item.path_str(),
                                item.size,
                                category_name.clone(),
                                name.clone(),
                                item.item_type.clone().into(),
                            );
                        }
                        self.categories[cat_idx].items[item_idx].last_result =
                            Some(cleaning_result);

                        if bytes == 0 {
                            self.operation_logs.push(format!(
                                "ℹ️  {}: nothing to clean (already empty on {})",
                                name,
                                cleansys_core::cleaners::platform::platform_name()
                            ));
                        }
                    }
                    Err(e) => {
                        let error_msg = if requires_root && !self.is_root {
                            "Requires sudo - restart with 'sudo cleansys'".to_string()
                        } else {
                            format!(
                                "Failed: {}",
                                e.to_string()
                                    .split(':')
                                    .next_back()
                                    .unwrap_or("Unknown error")
                                    .trim()
                            )
                        };
                        self.categories[cat_idx].items[item_idx].status =
                            Some(Status::Error(error_msg.clone()));
                        self.operation_logs
                            .push(format!("❌ Failed {}: {}", name, error_msg));

                        // Add helpful message for sudo requirement
                        if requires_root
                            && !self.is_root
                            && !self
                                .result_messages
                                .iter()
                                .any(|msg| msg.contains("sudo cleansys"))
                        {
                            self.result_messages.push(
                                "💡 System cleaners require root privileges. Run 'sudo cleansys' to clean system files.".to_string()
                            );
                        }
                    }
                }
            }
        }
    }

    pub fn cancel_sudo_operations(&mut self) {
        // Mark all operations as cancelled
        for category in &mut self.categories {
            for item in &mut category.items {
                if item.selected && matches!(item.status, Some(Status::Running | Status::Pending)) {
                    item.status = Some(Status::Error("Operation cancelled by user".to_string()));
                    item.selected = false; // Deselect the item
                }
            }
        }

        self.result_messages
            .push("Cleaning operations cancelled by user.".to_string());
    }

    pub fn handle_key(&mut self, key: KeyEvent) -> Result<bool> {
        // If password prompt is visible, handle password input first
        if self.password_prompt.is_visible() {
            match key.code {
                KeyCode::Enter => {
                    // Submit password and authenticate
                    match self.password_prompt.submit() {
                        Ok(true) => {
                            // Authentication successful, proceed with operations
                            self.needs_sudo = false;
                            self.password_prompt.hide();

                            // Now start the actual cleaning operations
                            let selected_cleaners = self.pending_operations.clone();
                            self.pending_operations.clear();

                            if !selected_cleaners.is_empty() {
                                self.start_operations(&selected_cleaners);
                            }
                        }
                        Ok(false) => {
                            // Authentication failed, stay on prompt
                        }
                        Err(e) => {
                            self.operation_logs
                                .push(format!("❌ Authentication error: {}", e));
                            self.password_prompt.hide();
                            self.needs_sudo = false;
                            self.pending_operations.clear();
                        }
                    }
                }
                KeyCode::Esc => {
                    // Cancel password prompt
                    self.password_prompt.cancel();
                    self.needs_sudo = false;
                    self.pending_operations.clear();
                }
                KeyCode::Char(c) => {
                    self.password_prompt.add_char(c);
                }
                KeyCode::Backspace => {
                    self.password_prompt.remove_char();
                }
                _ => {}
            }
            return Ok(false);
        }

        // "Needs Administrator" notice (Windows only — no interactive sudo flow there)
        if self.needs_admin_notice {
            match key.code {
                KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') => {
                    self.needs_admin_notice = false;
                    self.pending_operations.clear();
                }
                _ => {}
            }
            return Ok(false);
        }

        // Run confirmation overlay
        if self.awaiting_run_confirmation {
            match key.code {
                KeyCode::Enter | KeyCode::Char('y') => {
                    self.confirm_pending_run()?;
                }
                KeyCode::Esc | KeyCode::Char('n') => {
                    self.cancel_run_confirmation();
                }
                _ => {}
            }
            return Ok(false);
        }

        // Preview results overlay
        if self.preview_open {
            match key.code {
                KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') => {
                    self.close_preview();
                }
                _ => {}
            }
            return Ok(false);
        }

        match (key.code, key.modifiers) {
            // Quit
            (KeyCode::Char('q'), _) => {
                if self.show_help {
                    self.show_help = false;
                } else if self.is_running {
                    // Cancel current cleaning operations
                    self.is_running = false;
                    self.cancel_sudo_operations();
                } else {
                    return Ok(true);
                }
            }

            // Navigation
            (KeyCode::Down, _) => {
                if !self.show_help {
                    if self.is_running || self.show_progress_screen {
                        self.scroll_detailed_list_down();
                    } else {
                        self.next_item();
                    }
                }
            }
            (KeyCode::Up, _) => {
                if !self.show_help {
                    if self.is_running || self.show_progress_screen {
                        self.scroll_detailed_list_up();
                    } else {
                        self.previous_item();
                    }
                }
            }
            (KeyCode::Tab, _) => {
                if !self.show_help {
                    self.next_category();
                }
            }
            (KeyCode::BackTab, _) => {
                if !self.show_help {
                    self.previous_category();
                }
            }
            // Selection
            (KeyCode::Char(' '), KeyModifiers::NONE) => {
                if !self.show_help {
                    self.toggle_selected();
                }
            }
            // Run cleaners (shows a confirmation overlay first, unless
            // confirmation prompts are disabled via 'y').
            (KeyCode::Enter, _) => {
                if !self.show_help {
                    self.request_run()?;
                }
            }
            // Preview (dry-run) selected cleaners — measures real sizes/paths
            // without deleting anything.
            (KeyCode::Char('d'), _) => {
                if !self.show_help && !self.is_running {
                    self.run_preview();
                }
            }
            // Help dialog
            (KeyCode::Char('?' | 'h'), _) => {
                self.toggle_help();
            }

            // Toggle search in removed items view
            (KeyCode::Char('/'), _) => {
                if !self.show_help {
                    self.toggle_search();
                }
            }
            // Clear search or cancel operations or return to main menu
            (KeyCode::Esc, _) => {
                if self.search_active {
                    self.clear_search();
                } else if self.is_running {
                    self.is_running = false;
                    self.cancel_sudo_operations();
                } else if self.show_progress_screen {
                    // Return to main menu from completed operations screen
                    self.show_progress_screen = false;
                }
            }
            // Scroll removed items list
            (KeyCode::Char('j'), _) => {
                if !self.show_help {
                    self.scroll_detailed_list_down();
                }
            }
            (KeyCode::Char('k'), _) => {
                if !self.show_help {
                    self.scroll_detailed_list_up();
                }
            }
            // Select all in current category
            (KeyCode::Char('a'), _) => {
                if !self.show_help {
                    self.select_all();
                }
            }
            // Deselect all in current category
            (KeyCode::Char('n'), _) => {
                if !self.show_help {
                    self.deselect_all();
                }
            }
            // Select all across every category
            (KeyCode::Char('A'), _) => {
                if !self.show_help {
                    self.select_all_everywhere();
                }
            }
            // Deselect all across every category
            (KeyCode::Char('N'), _) => {
                if !self.show_help {
                    self.deselect_all_everywhere();
                }
            }

            // Toggle compact mode
            (KeyCode::Char('m'), _) => {
                if !self.show_help {
                    self.toggle_compact_mode();
                }
            }
            // Toggle auto scroll log
            (KeyCode::Char('s'), _) => {
                if !self.show_help && self.is_running {
                    self.toggle_auto_scroll();
                }
            }
            // Toggle performance stats
            (KeyCode::Char('p'), _) => {
                if !self.show_help {
                    self.toggle_performance_stats();
                }
            }
            // Cycle view mode
            (KeyCode::Char('v'), _) => {
                if !self.show_help {
                    self.cycle_view_mode();
                }
            }
            // Cycle sort mode
            (KeyCode::Char('o'), _) => {
                if !self.show_help {
                    self.cycle_sort_mode();
                }
            }
            // Cycle filter mode
            (KeyCode::Char('f'), _) => {
                if !self.show_help {
                    self.cycle_filter_mode();
                }
            }
            // Toggle pause/resume operations
            (KeyCode::Char(' '), KeyModifiers::CONTROL) => {
                if self.is_running {
                    self.toggle_pause();
                }
            }
            // Toggle confirmation mode
            (KeyCode::Char('y'), _) => {
                if !self.show_help {
                    self.toggle_confirmation_mode();
                }
            }
            // Toggle chart type
            (KeyCode::Char('c'), _) => {
                if !self.show_help {
                    self.toggle_chart_type();
                }
            }
            // Clear all errors
            (KeyCode::Char('x'), _) => {
                if !self.show_help {
                    self.clear_errors();
                }
            }
            // Handle search input (only when search is active)
            (KeyCode::Char(c), _) => {
                if self.search_active {
                    self.add_search_char(c);
                } else if !self.show_help {
                    self.toggle_selected();
                }
            }
            // Backspace in search
            (KeyCode::Backspace, _) => {
                if self.search_active {
                    self.remove_search_char();
                }
            }
            // Page scrolling for removed items (when in progress view)
            (KeyCode::PageUp, _) => {
                if self.is_running || self.show_progress_screen {
                    // Scroll up by 10 items
                    for _ in 0..10 {
                        self.scroll_detailed_list_up();
                    }
                }
            }
            (KeyCode::PageDown, _) => {
                if self.is_running || self.show_progress_screen {
                    // Scroll down by 10 items
                    for _ in 0..10 {
                        self.scroll_detailed_list_down();
                    }
                }
            }
            // Enhanced navigation with Ctrl modifiers
            (KeyCode::Home, _) => {
                if !self.show_help {
                    if self.is_running || self.show_progress_screen {
                        self.detailed_list_scroll_state.select(Some(0));
                    } else {
                        self.item_list_state.select(Some(0));
                    }
                }
            }
            (KeyCode::End, _) if !self.show_help => {
                if self.is_running || self.show_progress_screen {
                    if !self.detailed_cleaned_items.is_empty() {
                        let last_index = (self.detailed_cleaned_items.len() * 3).saturating_sub(1);
                        self.detailed_list_scroll_state.select(Some(last_index));
                    }
                } else {
                    let len = self.categories[self.category_index].items.len();
                    if len > 0 {
                        self.item_list_state.select(Some(len - 1));
                    }
                }
            }
            _ => {}
        }

        Ok(false)
    }

    pub fn handle_resize(&mut self, width: u16, height: u16) {
        self.terminal_width = width;
        self.terminal_height = height;
    }

    pub fn toggle_compact_mode(&mut self) {
        self.compact_mode = !self.compact_mode;
        self.view_mode = if self.compact_mode {
            ViewMode::Compact
        } else {
            ViewMode::Standard
        };
    }

    pub fn toggle_auto_scroll(&mut self) {
        // Auto scroll functionality for operation logs
    }

    pub fn toggle_performance_stats(&mut self) {
        self.show_performance_stats = !self.show_performance_stats;
    }

    pub fn cycle_view_mode(&mut self) {
        self.view_mode = match self.view_mode {
            ViewMode::Standard => ViewMode::Compact,
            ViewMode::Compact => ViewMode::Detailed,
            ViewMode::Detailed => ViewMode::Performance,
            ViewMode::Performance => ViewMode::Standard,
        };
    }

    pub fn cycle_sort_mode(&mut self) {
        self.sort_mode = match self.sort_mode {
            SortMode::Name => SortMode::Size,
            SortMode::Size => SortMode::Status,
            SortMode::Status => SortMode::Category,
            SortMode::Category => SortMode::Name,
        };
    }

    pub fn cycle_filter_mode(&mut self) {
        self.filter_mode = match self.filter_mode {
            FilterMode::All => FilterMode::Selected,
            FilterMode::Selected => FilterMode::Completed,
            FilterMode::Completed => FilterMode::Errors,
            FilterMode::Errors => FilterMode::UserOnly,
            FilterMode::UserOnly => FilterMode::SystemOnly,
            FilterMode::SystemOnly => FilterMode::All,
        };
    }

    pub fn toggle_pause(&mut self) {
        self.paused = !self.paused;
    }

    pub fn toggle_confirmation_mode(&mut self) {
        self.confirmation_mode = !self.confirmation_mode;
    }

    pub fn update_counters(&mut self) {
        self.selected_cleaners_count = self
            .categories
            .iter()
            .flat_map(|cat| &cat.items)
            .filter(|item| item.selected)
            .count();

        self.errors_count = self
            .categories
            .iter()
            .flat_map(|cat| &cat.items)
            .filter(|item| matches!(item.status, Some(Status::Error(_))))
            .count();

        self.operation_count = self
            .categories
            .iter()
            .flat_map(|cat| &cat.items)
            .filter(|item| item.status.is_some())
            .count();

        // Auto-complete when all operations are finished
        if self.is_running && self.operation_count > 0 {
            let running_count = self
                .categories
                .iter()
                .flat_map(|cat| &cat.items)
                .filter(|item| matches!(item.status, Some(Status::Running)))
                .count();

            let pending_count = self
                .categories
                .iter()
                .flat_map(|cat| &cat.items)
                .filter(|item| matches!(item.status, Some(Status::Pending)))
                .count();

            let selected_count = self
                .categories
                .iter()
                .flat_map(|cat| &cat.items)
                .filter(|item| item.selected)
                .count();

            // If no operations are running or pending, and we have selected items, mark as complete
            if running_count == 0 && pending_count == 0 && selected_count > 0 {
                self.is_running = false;
                self.demo_operation_timer = None;
                self.operation_end_time = Some(Instant::now());

                // Add completion message
                if !self
                    .result_messages
                    .iter()
                    .any(|msg| msg.contains("Completed"))
                {
                    let summary = format!(
                        "Cleaning completed! Total space freed: {}",
                        format_size(self.total_bytes_cleaned)
                    );
                    self.result_messages
                        .push(format!("{summary} (Press ESC to return to main menu)"));
                    crate::notifications::notify_completion(&summary);
                }
                // Keep show_progress_screen true so user stays on details screen
            }
        }
    }

    pub fn clear_errors(&mut self) {
        for category in &mut self.categories {
            for item in &mut category.items {
                if matches!(item.status, Some(Status::Error(_))) {
                    item.status = None;
                }
            }
        }
        self.errors_count = 0;
    }

    pub fn get_elapsed_time(&self) -> String {
        if let Some(start_time) = self.operation_start_time {
            let elapsed = if let Some(end_time) = self.operation_end_time {
                // Operation completed, show total time
                end_time.duration_since(start_time)
            } else {
                // Operation still running, show current elapsed time
                start_time.elapsed()
            };

            if elapsed.as_secs() < 60 {
                format!("{}s", elapsed.as_secs())
            } else {
                format!("{}m {}s", elapsed.as_secs() / 60, elapsed.as_secs() % 60)
            }
        } else {
            "0s".to_string()
        }
    }

    pub fn add_detailed_cleaned_item(
        &mut self,
        path: String,
        size: u64,
        category: String,
        cleaner_name: String,
        item_type: CleanedItemType,
    ) {
        let item = DetailedCleanedItem {
            path,
            size,
            category,
            cleaner_name,
            timestamp: SystemTime::now(),
            item_type,
        };
        self.detailed_cleaned_items.push(item);

        // Keep only last 1000 items to prevent memory issues
        if self.detailed_cleaned_items.len() > 1000 {
            self.detailed_cleaned_items.remove(0);
        }
    }

    pub fn scroll_detailed_list_up(&mut self) {
        if let Some(selected) = self.detailed_list_scroll_state.selected() {
            if selected > 0 {
                self.detailed_list_scroll_state.select(Some(selected - 1));
            }
        } else {
            // Start from the bottom when first navigating
            let total_items = if !self.detailed_cleaned_items.is_empty() {
                self.detailed_cleaned_items.len() * 3 // Account for spacing between items
            } else {
                45 // Sample items count for demo
            };
            if total_items > 0 {
                self.detailed_list_scroll_state
                    .select(Some(total_items - 1));
            }
        }
    }

    pub fn scroll_detailed_list_down(&mut self) {
        let total_items = if !self.detailed_cleaned_items.is_empty() {
            self.detailed_cleaned_items.len() * 3 // Account for spacing between items
        } else {
            45 // Sample items count for demo
        };

        if let Some(selected) = self.detailed_list_scroll_state.selected() {
            if selected < total_items.saturating_sub(1) {
                self.detailed_list_scroll_state.select(Some(selected + 1));
            }
        } else if total_items > 0 {
            self.detailed_list_scroll_state.select(Some(0));
        }
    }

    pub fn get_filtered_detailed_items(&self) -> Vec<&DetailedCleanedItem> {
        let mut items: Vec<&DetailedCleanedItem> = self
            .detailed_cleaned_items
            .iter()
            .filter(|item| {
                // Apply search filter
                if !self.search_query.is_empty() {
                    let query_lower = self.search_query.to_lowercase();
                    return item.path.to_lowercase().contains(&query_lower)
                        || item.category.to_lowercase().contains(&query_lower)
                        || item.cleaner_name.to_lowercase().contains(&query_lower);
                }

                // Apply category filter
                if !self.detailed_view_filter.is_empty() {
                    return item
                        .category
                        .to_lowercase()
                        .contains(&self.detailed_view_filter.to_lowercase());
                }

                true
            })
            .collect();

        // Sort based on current sort mode
        match self.sort_mode {
            SortMode::Name => items.sort_by(|a, b| a.path.cmp(&b.path)),
            SortMode::Size => items.sort_by_key(|b| std::cmp::Reverse(b.size)), // Largest first
            SortMode::Category => items.sort_by(|a, b| a.category.cmp(&b.category)),
            SortMode::Status => items.sort_by_key(|b| std::cmp::Reverse(b.timestamp)), // Most recent first
        }

        items
    }

    pub fn toggle_chart_type(&mut self) {
        self.chart_type = match self.chart_type {
            ChartType::Bar => ChartType::PieCount,
            ChartType::PieCount => ChartType::PieSize,
            ChartType::PieSize => ChartType::Bar,
        };
    }
}