edirstat 1.0.2

A fast, cross-platform disk usage analyzer with work-stealing multithreading, zero-copy snapshots, and an interactive treemap GUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
use std::{
    collections::{HashMap, HashSet},
    ops::RangeInclusive,
    path::{Path, PathBuf},
    sync::{Arc, atomic::Ordering},
    time::{Duration, Instant},
};

use eframe::egui;
use egui_plot::{AxisHints, GridMark, Line, Plot, PlotResponse, Points};
use rfd::FileDialog;
use smallvec::SmallVec;

use super::{
    arena::{FileArenaSnapshot, NO_EXTENSION, NO_INDEX},
    colors,
    coordinator::SharedState,
    persistence::{load_snapshot, save_snapshot},
    stats::{self, StatsChart as _},
    traversal::TraversalEngine,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ActiveModal {
    Delete,
    About,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VisMode {
    Treemap,
    Plots,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlotType {
    SizeDistribution,
    AgeSizeScatter,
    DirComposition,
    ExtensionBoxplot,
    TemporalTimeline,
}

pub struct GuiApp {
    shared_state: Arc<SharedState>,
    traversal_engine: Arc<TraversalEngine>,

    // UI state
    selected_node_idx: Option<u32>,
    expanded_nodes: HashSet<u32>,
    search_query: String,
    monospace_paths: bool,

    // Visualization tabs
    vis_mode: VisMode,
    plot_type: PlotType,

    // Analytics components
    scatter_chart: stats::scatter_plot::FileAgeSizeScatterChart,
    dir_comp_chart: stats::dir_composition::DirCompositionChart,
    boxplot_chart: stats::extension_boxplot::ExtensionBoxplotChart,
    timeline_chart: stats::temporal_timeline::TemporalTimelineChart,

    // Modal states
    delete_confirm_checked: bool,
    delete_node_idx: Option<u32>,
    active_modal: Option<ActiveModal>,

    // Saved scan parameters
    current_scan_path: Option<PathBuf>,
    scan_start_time: Option<Instant>,
    total_scan_duration: Option<Duration>,

    // Extension breakdown stats
    extension_stats: Vec<ExtensionStat>,
    last_extension_update: Option<Instant>,

    // Layout caching fields
    cached_blocks: Vec<stats::treemap::TreemapBlock>,
    last_snapshot_ptr: usize,
    last_rect: egui::Rect,

    // Single-use trigger to automatically scroll the list view to the target row
    scroll_to_selected: bool,
}

struct ExtensionStat {
    ext: String,
    total_size: u64,
    file_count: u32,
    color: egui::Color32,
}

impl GuiApp {
    pub fn new(shared_state: Arc<SharedState>, traversal_engine: Arc<TraversalEngine>) -> Self {
        Self {
            shared_state,
            traversal_engine,
            selected_node_idx: None,
            expanded_nodes: HashSet::new(),
            search_query: String::new(),
            monospace_paths: false,
            vis_mode: VisMode::Treemap,
            plot_type: PlotType::SizeDistribution,
            scatter_chart: stats::scatter_plot::FileAgeSizeScatterChart::new(),
            dir_comp_chart: stats::dir_composition::DirCompositionChart::new(0),
            boxplot_chart: stats::extension_boxplot::ExtensionBoxplotChart::new(),
            timeline_chart: stats::temporal_timeline::TemporalTimelineChart::new(),
            delete_confirm_checked: false,
            delete_node_idx: None,
            active_modal: None,
            current_scan_path: None,
            scan_start_time: None,
            total_scan_duration: None,
            extension_stats: Vec::new(),
            last_extension_update: None,
            cached_blocks: Vec::new(),
            last_snapshot_ptr: 0,
            last_rect: egui::Rect::NOTHING,
            scroll_to_selected: false,
        }
    }

    fn reset_state(&mut self) {
        self.selected_node_idx = None;
        self.expanded_nodes.clear();
        self.extension_stats.clear();
        self.last_extension_update = None;
        self.delete_confirm_checked = false;
        self.delete_node_idx = None;
        self.active_modal = None;
        self.traversal_engine.stats().reset();
        self.scatter_chart = stats::scatter_plot::FileAgeSizeScatterChart::new();
        self.dir_comp_chart = stats::dir_composition::DirCompositionChart::new(0);
        self.boxplot_chart = stats::extension_boxplot::ExtensionBoxplotChart::new();
        self.timeline_chart = stats::temporal_timeline::TemporalTimelineChart::new();
        self.cached_blocks.clear();
        self.last_snapshot_ptr = 0;
        self.last_rect = egui::Rect::NOTHING;
        self.scroll_to_selected = false;
    }

    /// Renders the shared "File" actions used in both the top toolbar and node context menus.
    fn draw_file_menu_contents(&mut self, ui: &mut egui::Ui, snapshot: &FileArenaSnapshot) {
        let has_selection = self.selected_node_idx.is_some();

        let open_btn = ui.add_enabled(has_selection, egui::Button::new("🗁 Open in File Manager"));
        if open_btn.clicked() {
            let idx_opt = self.selected_node_idx;
            if let Some(idx) = idx_opt {
                let path_str = snapshot.get_full_path(idx);
                let path = std::path::Path::new(&path_str);
                let dir_to_open = if path.is_dir() {
                    path
                } else {
                    path.parent().map_or(path, |p| p)
                };
                let _ = open::that(dir_to_open);
            }
            ui.close_kind(egui::UiKind::Menu); // Closes the active menu/context-menu
        }

        let delete_btn = ui.add_enabled(has_selection, egui::Button::new("🗑 Delete (Permanent)"));
        if delete_btn.clicked() {
            self.active_modal = Some(ActiveModal::Delete);
            self.delete_confirm_checked = false;
            self.delete_node_idx = self.selected_node_idx;
            ui.close_kind(egui::UiKind::Menu); // Closes the active menu/context-menu
        }
    }

    fn render_size_distribution_plot(ui: &mut egui::Ui, snapshot: &FileArenaSnapshot) {
        let mut chart_gen = stats::size_distribution::SizeDistributionChart;
        let bar_chart = chart_gen.compute(snapshot);

        let formatter = |mark: GridMark, _range: &RangeInclusive<f64>| {
            let labels = [
                "< 10 KB",
                "10 KB - 100 KB",
                "100 KB - 1 MB",
                "1 MB - 10 MB",
                "10 MB - 100 MB",
                "100 MB - 1 GB",
                "1 GB - 10 GB",
                "> 10 GB",
            ];
            let val = mark.value.round() as usize;
            if val < labels.len() {
                labels[val].to_string()
            } else {
                String::new()
            }
        };

        let x_grid = |_input: egui_plot::GridInput| {
            let mut marks = vec![];
            for i in 0..8 {
                marks.push(GridMark {
                    value: i as f64,
                    step_size: 1.0,
                });
            }
            marks
        };

        let x_axes = vec![
            AxisHints::new_x()
                .label("File Size Bracket")
                .formatter(formatter),
        ];

        let plot = Plot::new("size_dist_plot")
            .height(ui.available_height() - 10.0)
            .custom_x_axes(x_axes)
            .x_grid_spacer(x_grid)
            .y_axis_label("File Count")
            .allow_zoom(false)
            .allow_drag(false)
            .allow_scroll(false);

        plot.show(ui, |plot_ui| {
            plot_ui.bar_chart(bar_chart);
        });
    }

    fn render_scatter_plot(&mut self, ui: &mut egui::Ui, snapshot: &FileArenaSnapshot) {
        // Recompute parameters if snapshot boundary updates
        let snapshot_ptr = Arc::as_ptr(&snapshot.nodes) as usize;
        if self.last_snapshot_ptr != snapshot_ptr || self.scatter_chart.top_files.is_empty() {
            self.scatter_chart.compute(snapshot);
            self.last_snapshot_ptr = snapshot_ptr;
        }

        if self.scatter_chart.top_files.is_empty() {
            ui.centered_and_justified(|ui| {
                ui.label("No file data available to plot.");
            });
            return;
        }

        let max_time = self.scatter_chart.max_timestamp;

        // Populate log-scale coordinates [Age, Size]
        let plot_points: Vec<[f64; 2]> = self
            .scatter_chart
            .top_files
            .iter()
            .map(|&(idx, size)| {
                let node = &snapshot.nodes[idx as usize];

                #[allow(clippy::cast_precision_loss)]
                let age_days = if max_time > node.modified_timestamp {
                    (max_time - node.modified_timestamp) as f64 / 86400.0
                } else {
                    0.0
                };
                #[allow(clippy::cast_precision_loss)]
                let size_log = (size as f64).log10();

                [age_days, size_log]
            })
            .collect();

        // Format grid boundaries log10 values into pretty byte readouts
        let y_formatter = |mark: egui_plot::GridMark, _range: &RangeInclusive<f64>| {
            let val = mark.value;
            if val < 0.0 {
                return String::new();
            }
            let bytes = 10.0f64.powf(val);
            if bytes >= 1.0 {
                prettier_bytes::ByteFormatter::new()
                    .format(bytes as u64)
                    .to_string()
            } else {
                String::new()
            }
        };

        let x_axes = vec![AxisHints::new_x().label("File Age (Days unmodified)")];
        let y_axes = vec![
            AxisHints::new_y()
                .label("File Size (Logarithmic)")
                .formatter(y_formatter),
        ];

        let points = Points::new("Top 5,000 Space Hogs", plot_points)
            .radius(2.0)
            .color(crate::colors::COLOR_SCANNING);

        let plot = Plot::new("age_size_scatter_plot")
            .height(ui.available_height() - 10.0)
            .custom_x_axes(x_axes)
            .custom_y_axes(y_axes)
            .show_background(true);

        let PlotResponse {
            inner: (pointer_coordinate, bounds),
            ..
        } = plot.show(ui, |plot_ui| {
            plot_ui.points(points);
            (plot_ui.pointer_coordinate(), plot_ui.plot_bounds())
        });

        // Hover coordinates check for rendering on-demand details
        if let Some(coord) = pointer_coordinate {
            let bounds_width = bounds.width();
            let bounds_height = bounds.height();

            if bounds_width > 0.0 && bounds_height > 0.0 {
                let mut closest_node_idx = None;
                let mut min_dist_sq = f64::INFINITY;

                for &(idx, size) in &self.scatter_chart.top_files {
                    let node = &snapshot.nodes[idx as usize];

                    #[allow(clippy::cast_precision_loss)]
                    let age_days = if max_time > node.modified_timestamp {
                        (max_time - node.modified_timestamp) as f64 / 86400.0
                    } else {
                        0.0
                    };

                    #[allow(clippy::cast_precision_loss)]
                    let size_log = (size as f64).log10();

                    // Standardize aspect ratio coordinate scaling
                    let dx = (coord.x - age_days) / bounds_width;
                    let dy = (coord.y - size_log) / bounds_height;
                    let dist_sq = dy.mul_add(dy, dx * dx);

                    if dist_sq < min_dist_sq {
                        min_dist_sq = dist_sq;
                        closest_node_idx = Some(idx);
                    }
                }

                // Tooltip displays if within visual vicinity (0.02 screen-radius bounds)
                if min_dist_sq < 0.0004
                    && let Some(node_idx) = closest_node_idx
                {
                    let node = &snapshot.nodes[node_idx as usize];
                    let path_str = snapshot.get_full_path(node_idx);
                    let size_str = prettier_bytes::ByteFormatter::new()
                        .format(node.size)
                        .to_string();

                    let age_days = if max_time > node.modified_timestamp {
                        (max_time - node.modified_timestamp) / 86400
                    } else {
                        0
                    };

                    egui::Tooltip::always_open(
                        ui.ctx().clone(),
                        ui.layer_id(),
                        egui::Id::new("scatter_tooltip"),
                        egui::PopupAnchor::Pointer,
                    )
                    .show(|ui| {
                        ui.label(format!("📄 Path: {path_str}"));
                        ui.label(format!("💾 Size: {size_str}"));
                        ui.label(format!("⏳ Age: {age_days} days unmodified"));
                    });
                }
            }
        }
    }

    fn render_dir_composition_plot(&mut self, ui: &mut egui::Ui, snapshot: &FileArenaSnapshot) {
        use stats::StatsChart;

        // Bind composition to active tree folder, falling back to root (0)
        let active_dir = self.selected_node_idx.unwrap_or(0);

        let snapshot_ptr = Arc::as_ptr(&snapshot.nodes) as usize;
        let needs_rebuild = self.last_snapshot_ptr != snapshot_ptr
            || self.dir_comp_chart.parent_idx != active_dir
            || self.dir_comp_chart.children_composition.is_empty();

        if needs_rebuild {
            self.dir_comp_chart.parent_idx = active_dir;
            self.dir_comp_chart.compute(snapshot);
            self.last_snapshot_ptr = snapshot_ptr;
        }

        if self.dir_comp_chart.children_composition.is_empty() {
            ui.centered_and_justified(|ui| {
                ui.label(
                    "Selected path has no nested subdirectories or files to display composition.",
                );
            });
            return;
        }

        let parent_name = snapshot
            .string_pool
            .get(snapshot.nodes[active_dir as usize].name_id)
            .unwrap_or("Root");
        ui.strong(format!("📁 Active Directory: {parent_name}"));
        ui.add_space(4.0);

        let children_count = self.dir_comp_chart.children_composition.len();
        let chart_ref = &self.dir_comp_chart;

        let x_formatter = move |mark: GridMark, _range: &RangeInclusive<f64>| {
            let val = mark.value.round() as usize;
            if val < children_count {
                chart_ref.children_composition[val].0.clone()
            } else {
                String::new()
            }
        };

        let y_formatter = |mark: GridMark, _range: &RangeInclusive<f64>| {
            let val = mark.value;
            if val <= 0.0 {
                return String::new();
            }
            prettier_bytes::ByteFormatter::new()
                .format(val as u64)
                .to_string()
        };

        let x_grid = move |_input: egui_plot::GridInput| {
            let mut marks = vec![];
            for i in 0..children_count {
                #[allow(clippy::cast_precision_loss)]
                let value = i as f64;

                marks.push(GridMark {
                    value,
                    step_size: 1.0,
                });
            }
            marks
        };

        let x_axes = vec![
            AxisHints::new_x()
                .label("Direct Children")
                .formatter(x_formatter),
        ];
        let y_axes = vec![
            AxisHints::new_y()
                .label("Cumulative Space")
                .formatter(y_formatter),
        ];

        // Generate stacked bar charts for active configuration
        let mut chart_gen = stats::dir_composition::DirCompositionChart::new(active_dir);
        let stacked_charts = chart_gen.compute(snapshot);

        let plot = Plot::new("dir_composition_plot")
            .height(ui.available_height() - 30.0)
            .custom_x_axes(x_axes)
            .custom_y_axes(y_axes)
            .x_grid_spacer(x_grid)
            .legend(egui_plot::Legend::default().position(egui_plot::Corner::RightTop))
            .allow_zoom(false)
            .allow_drag(false)
            .allow_scroll(false);

        plot.show(ui, |plot_ui| {
            for chart in stacked_charts {
                plot_ui.bar_chart(chart);
            }
        });
    }

    fn render_boxplot_plot(&mut self, ui: &mut egui::Ui, snapshot: &FileArenaSnapshot) {
        let snapshot_ptr = Arc::as_ptr(&snapshot.nodes) as usize;
        let needs_rebuild = self.last_snapshot_ptr != snapshot_ptr
            || self.boxplot_chart.computed_spreads.is_empty();

        if needs_rebuild {
            self.boxplot_chart.compute(snapshot);
            self.last_snapshot_ptr = snapshot_ptr;
        }

        if self.boxplot_chart.computed_spreads.is_empty() {
            ui.centered_and_justified(|ui| {
                ui.label(
                    "Not enough file data in any single extension category to generate box plots.",
                );
            });
            return;
        }

        let spreads_count = self.boxplot_chart.computed_spreads.len();
        let chart_ref = &self.boxplot_chart;

        let x_formatter = move |mark: GridMark, _range: &RangeInclusive<f64>| {
            let val = mark.value.round() as usize;
            if val < spreads_count {
                format!(".{}", chart_ref.computed_spreads[val].0.clone())
            } else {
                String::new()
            }
        };

        let y_formatter = |mark: GridMark, _range: &RangeInclusive<f64>| {
            let val = mark.value;
            if val < 0.0 {
                return String::new();
            }
            let bytes = 10.0f64.powf(val);
            if bytes >= 1.0 {
                prettier_bytes::ByteFormatter::new()
                    .format(bytes as u64)
                    .to_string()
            } else {
                String::new()
            }
        };

        let x_grid = move |_input: egui_plot::GridInput| {
            let mut marks = vec![];
            for i in 0..spreads_count {
                #[allow(clippy::cast_precision_loss)]
                let value = i as f64;

                marks.push(GridMark {
                    value,
                    step_size: 1.0,
                });
            }
            marks
        };

        let x_axes = vec![
            AxisHints::new_x()
                .label("Top Extensions (by file count)")
                .formatter(x_formatter),
        ];
        let y_axes = vec![
            AxisHints::new_y()
                .label("File Size Distribution")
                .formatter(y_formatter),
        ];

        let plot = Plot::new("boxplot_plot")
            .height(ui.available_height() - 10.0)
            .custom_x_axes(x_axes)
            .custom_y_axes(y_axes)
            .x_grid_spacer(x_grid)
            .legend(egui_plot::Legend::default().position(egui_plot::Corner::RightTop))
            .allow_zoom(false)
            .allow_drag(false)
            .allow_scroll(false);

        plot.show(ui, |plot_ui| {
            for (i, (ext, spread)) in self.boxplot_chart.computed_spreads.iter().enumerate() {
                #[allow(clippy::cast_precision_loss)]
                let index = i as f64;

                let elem =
                    egui_plot::BoxElem::new(index, spread.clone()).name(format!(".{ext} sizes"));
                let box_plot = egui_plot::BoxPlot::new(ext.clone(), vec![elem])
                    .color(colors::get_color_for_extension(ext));
                plot_ui.box_plot(box_plot);
            }
        });
    }

    fn render_timeline_plot(&mut self, ui: &mut egui::Ui, snapshot: &FileArenaSnapshot) {
        let snapshot_ptr = Arc::as_ptr(&snapshot.nodes) as usize;
        let needs_rebuild =
            self.last_snapshot_ptr != snapshot_ptr || self.timeline_chart.sorted_days.is_empty();

        if needs_rebuild {
            self.timeline_chart.compute(snapshot);
            self.last_snapshot_ptr = snapshot_ptr;
        }

        if self.timeline_chart.sorted_days.is_empty() {
            ui.centered_and_justified(|ui| {
                ui.label("No file modification metadata available to construct timelines.");
            });
            return;
        }

        // Build Space Points (cumulative) and Activity Points (daily frequency)
        let mut space_points = Vec::new();
        let mut activity_points = Vec::new();

        let mut cumulative_size = 0u64;
        for &day in &self.timeline_chart.sorted_days {
            let (size, count) = self.timeline_chart.daily_totals[&day];
            cumulative_size += size;

            #[allow(clippy::cast_precision_loss)]
            let d = day as f64;
            #[allow(clippy::cast_precision_loss)]
            let count_d = count as f64;
            #[allow(clippy::cast_precision_loss)]
            let cumulative_size_d = cumulative_size as f64;

            space_points.push([d, cumulative_size_d]);
            activity_points.push([d, count_d]);
        }

        // Custom time-axis calendar formatter
        let x_formatter = |mark: GridMark, _range: &RangeInclusive<f64>| {
            let val = mark.value.round() as i64;
            stats::temporal_timeline::format_epoch_to_date(val)
        };

        let y_space_formatter = |mark: GridMark, _range: &RangeInclusive<f64>| {
            let val = mark.value;
            if val <= 0.0 {
                return String::new();
            }
            prettier_bytes::ByteFormatter::new()
                .format(val as u64)
                .to_string()
        };

        // Shared link structures
        let link_group_id = ui.id().with("linked_timeline_plots");
        let link_axis = egui::Vec2b::new(true, false); // link X only, do not scale Y together
        let link_cursor = egui::Vec2b::new(true, false);

        let space_line = Line::new("Space Progress", space_points)
            .color(crate::colors::COLOR_SCANNING)
            .width(2.0);

        let activity_line = Line::new("Activity Frequency", activity_points)
            .color(crate::colors::GLOW_INNER_CORE)
            .width(1.5);

        // Render dual layout
        let half_height = (ui.available_height() - 40.0) / 2.0;

        ui.label(
            "Timeline views are dynamically linked; zooming/panning one will scroll the other.",
        );
        ui.add_space(4.0);

        // 1. Top Plot: Cumulative Storage Growth
        let top_x = vec![AxisHints::new_x().formatter(x_formatter)];
        let top_y = vec![
            AxisHints::new_y()
                .label("Disk Space")
                .formatter(y_space_formatter),
        ];
        let plot_top = Plot::new("timeline_space_plot")
            .height(half_height)
            .custom_x_axes(top_x)
            .custom_y_axes(top_y)
            .link_axis(link_group_id, link_axis)
            .link_cursor(link_group_id, link_cursor)
            .legend(egui_plot::Legend::default().position(egui_plot::Corner::LeftTop));

        plot_top.show(ui, |plot_ui| {
            plot_ui.line(space_line);
        });

        ui.add_space(6.0);

        // 2. Bottom Plot: Activity frequency spikes
        let bottom_x = vec![AxisHints::new_x().formatter(x_formatter)];
        let bottom_y = vec![AxisHints::new_y().label("Files Modified")];
        let plot_bottom = Plot::new("timeline_activity_plot")
            .height(half_height)
            .custom_x_axes(bottom_x)
            .custom_y_axes(bottom_y)
            .link_axis(link_group_id, link_axis)
            .link_cursor(link_group_id, link_cursor)
            .legend(egui_plot::Legend::default().position(egui_plot::Corner::LeftTop));

        plot_bottom.show(ui, |plot_ui| {
            plot_ui.line(activity_line);
        });
    }
}

impl eframe::App for GuiApp {
    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        let ctx = ui.ctx().clone();
        // Fetch current snapshot
        let snapshot = self.shared_state.current_snapshot.load();
        let is_scanning = self.shared_state.is_scanning.load(Ordering::SeqCst);

        // Repaint during scan to show live progress, or continuously while selected to drive the glow animation
        if is_scanning {
            ctx.request_repaint_after(Duration::from_millis(50));
        } else if self.selected_node_idx.is_some() {
            ctx.request_repaint_after(Duration::from_millis(8)); // ~120fps smooth animation loop
        }

        // Apply dark, premium glassmorphism-inspired style
        setup_custom_style(&ctx);

        // Top Control Panel
        egui::Panel::top("top_panel").show_inside(ui, |ui| {
            ui.horizontal(|ui| {
                ui.heading(
                    egui::RichText::new("eDirStat 👷")
                        .strong()
                        .color(ui.visuals().strong_text_color()),
                );
                ui.separator();

                if ui.button("📁 Scan Directory").clicked() {
                    let folder_opt = FileDialog::new().pick_folder();
                    if let Some(path) = folder_opt {
                        self.reset_state();
                        self.current_scan_path = Some(path.clone());
                        self.scan_start_time = Some(Instant::now());
                        self.total_scan_duration = None;

                        // Start traversal and coordinator
                        let (tx, rx) = crossbeam::channel::unbounded();
                        let traversal = self.traversal_engine.clone();
                        let state = self.shared_state.clone();

                        // Launch Traversal Engine in background
                        match traversal.start_traversal(path.clone(), tx) {
                            Ok(_) => {
                                // Launch Coordinator in background
                                let mut coordinator =
                                    crate::coordinator::Coordinator::new(rx, state);
                                std::thread::spawn(move || {
                                    coordinator.run_coordinator_loop(&path.to_string_lossy());
                                });
                            }
                            Err(e) => {
                                println!("Failed to start traversal: {e}");
                            }
                        }
                    }
                }

                if ui.button("💾 Save Snapshot").clicked() && !snapshot.nodes.is_empty() {
                    let file_opt = FileDialog::new()
                        .add_filter("eDirStat Snapshot", &["edst"])
                        .save_file();
                    if let Some(path) = file_opt {
                        match save_snapshot(&snapshot.nodes, &snapshot.string_pool, &path) {
                            Ok(()) => {}
                            Err(e) => {
                                println!("Failed to save snapshot: {e}");
                            }
                        }
                    }
                }

                if ui.button("📖 Load Snapshot").clicked() {
                    let file_opt = FileDialog::new()
                        .add_filter("eDirStat Snapshot", &["edst"])
                        .pick_file();
                    if let Some(path) = file_opt {
                        match load_snapshot(&path) {
                            Ok((arena, string_pool)) => {
                                self.reset_state();
                                let loaded_snapshot = FileArenaSnapshot {
                                    nodes: Arc::new(arena.nodes().to_vec()),
                                    string_pool: Arc::new(string_pool),
                                };
                                self.shared_state
                                    .current_snapshot
                                    .store(Arc::new(loaded_snapshot));
                                self.current_scan_path = Some(path);
                                self.scan_start_time = None;

                                // Rebuild extension stats exactly once in the background upon load
                                let mut ext_map: HashMap<String, (u64, u32)> = HashMap::new();
                                for node in self.shared_state.current_snapshot.load().nodes.iter() {
                                    if node.is_directory() {
                                        continue;
                                    }
                                    if let Some(name) = self
                                        .shared_state
                                        .current_snapshot
                                        .load()
                                        .string_pool
                                        .get(node.name_id)
                                    {
                                        let ext = Path::new(name).extension().map_or_else(
                                            || NO_EXTENSION.to_string(),
                                            |s| s.to_string_lossy().to_ascii_lowercase(),
                                        );
                                        let entry = ext_map.entry(ext).or_insert((0, 0));
                                        entry.0 += node.size;
                                        entry.1 += 1;
                                    }
                                }
                                let mut stats: Vec<(String, u64, u32)> = ext_map
                                    .into_iter()
                                    .map(|(ext, (total_size, file_count))| {
                                        (ext, total_size, file_count)
                                    })
                                    .collect();
                                stats.sort_by_key(|b| std::cmp::Reverse(b.1));
                                self.shared_state.extension_stats.store(Arc::new(stats));
                            }
                            Err(e) => {
                                println!("Failed to load snapshot: {e}");
                            }
                        }
                    }
                }

                ui.separator();

                // Live status display
                if is_scanning {
                    ui.spinner();
                    ui.colored_label(crate::colors::COLOR_SCANNING, "Scanning Disk...");
                } else if self.current_scan_path.is_some() {
                    ui.colored_label(crate::colors::COLOR_SCAN_COMPLETE, "Scan Complete");
                } else {
                    ui.label("Idle");
                }

                if let Some(ref path) = self.current_scan_path {
                    ui.separator();
                    ui.label(format!("Path: {}", path.display()));
                }

                // --- Right-Aligned Concurrency Badge ---
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    let threads = self.traversal_engine.num_threads();
                    let badge_text = format!("{threads} Worker Threads");
                    ui.colored_label(crate::colors::GLOW_INNER_CORE, badge_text)
                        .on_hover_text("The number of parallel, work-stealing CPU cores allocated for directory traversal.");
                });
            });
        });

        // Bottom Stats Panel
        egui::Panel::bottom("bottom_panel").show_inside(ui, |ui| {
            ui.horizontal(|ui| {
                let file_count = self
                    .traversal_engine
                    .stats()
                    .files_scanned
                    .load(Ordering::Relaxed);
                let dir_count = self
                    .traversal_engine
                    .stats()
                    .dirs_scanned
                    .load(Ordering::Relaxed);
                let bytes = self
                    .traversal_engine
                    .stats()
                    .bytes_scanned
                    .load(Ordering::Relaxed);

                ui.label(format!("📁 Directories: {dir_count}"));
                ui.separator();
                ui.label(format!("📄 Files: {file_count}"));
                ui.separator();
                ui.label(format!(
                    "💾 Total Size: {}",
                    prettier_bytes::ByteFormatter::new().format(bytes as u64)
                ));

                if is_scanning && let Some(start) = self.scan_start_time {
                    let elapsed = start.elapsed();

                    #[allow(clippy::cast_precision_loss)]
                    let speed = bytes as f64 / elapsed.as_secs_f64();

                    ui.separator();
                    ui.label(format!("⏱ Time: {:.1}s", elapsed.as_secs_f64()));
                    ui.separator();
                    ui.label(format!(
                        "⚡ Speed: {}/s",
                        prettier_bytes::ByteFormatter::new().format(speed as u64)
                    ));
                }

                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if let Some(idx) = self.selected_node_idx {
                        let size_str = prettier_bytes::ByteFormatter::new()
                            .format(snapshot.nodes[idx as usize].size)
                            .to_string();
                        ui.strong(size_str);
                        let path_str = snapshot.get_full_path(idx);
                        ui.label(format!("Selection: {path_str}"));
                    }
                });
            });
        });

        // Left Panel - Directory Tree Explorer
        egui::Panel::left("left_panel")
            .resizable(true)
            .default_size(450.0)
            .show_inside(ui, |ui| {
                ui.vertical(|ui| {
                    // Toolbar above the root tree
                    egui::MenuBar::new().ui(ui, |ui| {
                        ui.menu_button("File", |ui| {
                            self.draw_file_menu_contents(ui, &snapshot);
                        });
                        ui.menu_button("View", |ui| {
                            ui.checkbox(&mut self.monospace_paths, "🅰 Monospace Paths");
                            ui.separator();
                            if ui.button("🗂 Collapse All").clicked() {
                                self.expanded_nodes.clear();
                                ui.close_kind(egui::UiKind::Menu);
                            }
                        });
                        ui.menu_button("Help", |ui| {
                            if ui.button("ℹ About").clicked() {
                                self.active_modal = Some(ActiveModal::About);
                            }
                        });
                    });
                    ui.separator();

                    ui.horizontal(|ui| {
                        ui.label("🔍 Filter:");
                        ui.text_edit_singleline(&mut self.search_query);
                        if !self.search_query.is_empty() && ui.button("").clicked() {
                            self.search_query.clear();
                        }
                    });
                    ui.separator();

                    if snapshot.nodes.is_empty() {
                        ui.centered_and_justified(|ui| {
                            ui.label("Click 'Scan Directory' to explore disk usage.");
                        });
                    } else {
                        // Auto-expand the root node (0) if expanded_nodes is empty
                        if self.expanded_nodes.is_empty() {
                            self.expanded_nodes.insert(0);
                        }

                        let mut visible_nodes = Vec::new();
                        self.flatten_visible_tree(&snapshot, 0, 0, &mut visible_nodes);

                        // Fetch the exact layout spacing variables
                        let row_height = ui.spacing().interact_size.y;
                        let spacing_y = ui.spacing().item_spacing.y;
                        let row_stride = row_height + spacing_y; // Actual pixel gap per item index
                        let available_height = ui.available_height(); // Height of the left panel

                        // --- Mathematically Correct Programmatic Scrolling ---
                        let mut scroll_area = egui::ScrollArea::vertical();
                        if self.scroll_to_selected {
                            if let Some(selected_idx) = self.selected_node_idx {
                                // Find the index of the selected item in the flat visible list
                                if let Some(row_index) = visible_nodes
                                    .iter()
                                    .position(|&(node_idx, _)| node_idx == selected_idx)
                                {
                                    #[allow(clippy::cast_precision_loss)]
                                    let target_y = (row_index as f32) * row_stride;

                                    // Calculate center offset relative to the available height of the viewport
                                    let center_offset = (available_height - row_height) / 2.0;
                                    let offset = (target_y - center_offset).max(0.0);

                                    scroll_area = scroll_area.vertical_scroll_offset(offset);
                                }
                            }
                            self.scroll_to_selected = false; // Reset the scroll trigger
                        }

                        scroll_area.show_rows(
                            ui,
                            row_height,
                            visible_nodes.len(),
                            |ui, row_range| {
                                for idx in row_range {
                                    let (node_idx, indent) = visible_nodes[idx];
                                    self.render_tree_node_row(ui, &snapshot, node_idx, indent);
                                }
                            },
                        );
                    }
                });
            });

        // Right Panel - Extension statistics
        egui::Panel::right("right_panel")
            .resizable(true)
            .size_range(80.0..=250.0)
            .default_size(210.0)
            .show_inside(ui, |ui| {
                ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
                ui.vertical(|ui| {
                    ui.heading(
                        egui::RichText::new("📂 Extensions")
                            .strong()
                            .color(ui.visuals().strong_text_color()),
                    );
                    ui.separator();

                    // Map the pre-computed/pre-sorted stats vector from our background thread
                    let shared_ext_stats = self.shared_state.extension_stats.load();
                    if !shared_ext_stats.is_empty() {
                        self.extension_stats = shared_ext_stats
                            .iter()
                            .map(|(ext, total_size, file_count)| ExtensionStat {
                                ext: ext.clone(),
                                total_size: *total_size,
                                file_count: *file_count,
                                color: colors::get_color_for_extension(ext),
                            })
                            .collect();
                    }

                    if self.extension_stats.is_empty() {
                        ui.label("No statistics gathered yet.");
                    } else {
                        egui::ScrollArea::vertical().show(ui, |ui| {
                            for stat in &self.extension_stats {
                                ui.horizontal(|ui| {
                                    // Colored dot
                                    let (rect, _) = ui.allocate_exact_size(
                                        egui::vec2(10.0, 10.0),
                                        egui::Sense::hover(),
                                    );
                                    ui.painter().circle_filled(rect.center(), 5.0, stat.color);

                                    // Allocate name width and truncate it
                                    let name_width = (ui.available_width() - 65.0).max(10.0);
                                    ui.allocate_ui(
                                        egui::vec2(name_width, ui.spacing().interact_size.y),
                                        |ui| {
                                            ui.style_mut().wrap_mode =
                                                Some(egui::TextWrapMode::Truncate);

                                            // Render the label and attach a hover tooltip showing file count
                                            ui.label(&stat.ext).on_hover_text(format!(
                                                "Files: {}",
                                                stat.file_count
                                            ));
                                        },
                                    );

                                    ui.with_layout(
                                        egui::Layout::right_to_left(egui::Align::Center),
                                        |ui| {
                                            ui.label(
                                                prettier_bytes::ByteFormatter::new()
                                                    .format(stat.total_size)
                                                    .to_string(),
                                            );
                                        },
                                    );
                                });
                            }
                        });
                    }
                });
            });

        // Central Panel - Canvas visual Treemap / Plot Panel
        egui::CentralPanel::default().show_inside(ui, |ui| {
            ui.vertical(|ui| {
                ui.horizontal(|ui| {
                    ui.selectable_value(&mut self.vis_mode, VisMode::Treemap, "🗺 Treemap");
                    ui.selectable_value(&mut self.vis_mode, VisMode::Plots, "📈 Plots");
                });
                ui.separator();

                if self.vis_mode == VisMode::Treemap {
                    ui.heading(
                        egui::RichText::new("📊 Treemap Visualization")
                            .strong()
                            .color(ui.visuals().strong_text_color()),
                    );
                    ui.separator();

                    if snapshot.nodes.is_empty() {
                        ui.centered_and_justified(|ui| {
                            ui.label("Scanned filesystem will be visualized as a treemap here.");
                        });
                    } else {
                        let available_rect = ui.available_rect_before_wrap();
                        let (rect, response) = ui.allocate_exact_size(
                            egui::vec2(available_rect.width(), available_rect.height() - 20.0),
                            egui::Sense::click_and_drag(),
                        );

                        // --- Layout Cache Check ---
                        let snapshot_ptr = Arc::as_ptr(&snapshot.nodes) as usize;
                        let needs_rebuild = self.cached_blocks.is_empty()
                            || snapshot_ptr != self.last_snapshot_ptr
                            || rect != self.last_rect;

                        if needs_rebuild {
                            let mut chart = stats::treemap::TreemapChart::new(rect);
                            self.cached_blocks = chart.compute(&snapshot);
                            self.last_snapshot_ptr = snapshot_ptr;
                            self.last_rect = rect;
                        }

                        let painter = ui.painter_at(rect);
                        let mut hovered_block = None;
                        let hover_pos = response.hover_pos();

                        // Look up hovered block (O(M) linear search is fast on layout blocks in Rust)
                        if let Some(pos) = hover_pos {
                            for block in &self.cached_blocks {
                                if block.rect.contains(pos) {
                                    hovered_block = Some(block);
                                    break;
                                }
                            }
                        }

                        // GPU Batching: Consolidate static blocks into exactly ONE single mesh submission to the GPU
                        let mut combined_mesh = egui::Mesh::default();
                        for block in &self.cached_blocks {
                            let fill_color = block.color;
                            let color_light = fill_color.linear_multiply(1.15);
                            let color_dark = fill_color.linear_multiply(0.75);

                            let base_vertex_idx = combined_mesh.vertices.len() as u32;

                            combined_mesh.vertices.push(egui::epaint::Vertex {
                                pos: block.rect.left_top(),
                                uv: egui::epaint::WHITE_UV,
                                color: color_light,
                            });
                            combined_mesh.vertices.push(egui::epaint::Vertex {
                                pos: block.rect.right_top(),
                                uv: egui::epaint::WHITE_UV,
                                color: color_light,
                            });
                            combined_mesh.vertices.push(egui::epaint::Vertex {
                                pos: block.rect.right_bottom(),
                                uv: egui::epaint::WHITE_UV,
                                color: color_dark,
                            });
                            combined_mesh.vertices.push(egui::epaint::Vertex {
                                pos: block.rect.left_bottom(),
                                uv: egui::epaint::WHITE_UV,
                                color: color_dark,
                            });

                            combined_mesh.add_triangle(
                                base_vertex_idx,
                                base_vertex_idx + 1,
                                base_vertex_idx + 2,
                            );
                            combined_mesh.add_triangle(
                                base_vertex_idx,
                                base_vertex_idx + 2,
                                base_vertex_idx + 3,
                            );
                        }

                        painter.add(combined_mesh);

                        // Dynamic overlays for highlights
                        if let Some(block) = hovered_block {
                            let stroke = egui::Stroke::new(1.5, egui::Color32::WHITE);
                            painter.rect(
                                block.rect,
                                0.0,
                                egui::Color32::TRANSPARENT,
                                stroke,
                                egui::StrokeKind::Inside,
                            );
                        }

                        if let Some(selected_idx) = self.selected_node_idx {
                            // Reconstruct the bounding box union of all blocks belonging to the selection.
                            // For a file, this yields its individual rect. For a directory, it yields the
                            // exact unified rect of its visible children on-screen.
                            let mut target_rect: Option<egui::Rect> = None;
                            for block in &self.cached_blocks {
                                if stats::treemap::is_descendant(
                                    &snapshot.nodes,
                                    block.node_idx,
                                    selected_idx,
                                ) {
                                    match target_rect {
                                        None => target_rect = Some(block.rect),
                                        Some(ref mut r) => *r = r.union(block.rect),
                                    }
                                }
                            }

                            if let Some(rect) = target_rect {
                                let time = ui.input(|i| i.time);

                                // A wave factor oscillating smoothly between 0.0 and 1.0 (approx. 1Hz frequency)
                                let pulse = 0.5f64.mul_add((time * 6.0).sin(), 0.5);

                                // 1. Draw Outer Expanding Glow (grows and fades)
                                let glow_alpha = 0.20f64.mul_add(pulse, 0.1);
                                let glow_color = crate::colors::GLOW_OUTER_BASE
                                    .linear_multiply(glow_alpha as f32);
                                let glow_thickness = 6.0f32.mul_add(pulse as f32, 4.0); // Oscillates thickness
                                painter.rect(
                                    rect,
                                    0.0,
                                    egui::Color32::TRANSPARENT,
                                    egui::Stroke::new(glow_thickness, glow_color),
                                    egui::StrokeKind::Outside,
                                );

                                // 2. Draw Inner Sharp Contrast Core (stays crisp)
                                let core_color = crate::colors::GLOW_INNER_CORE; // Soft pastel purple/violet
                                let core_thickness = 1.0f32.mul_add(pulse as f32, 1.5);
                                painter.rect(
                                    rect,
                                    0.0,
                                    egui::Color32::TRANSPARENT,
                                    egui::Stroke::new(core_thickness, core_color),
                                    egui::StrokeKind::Inside,
                                );
                            }
                        }

                        // Click event to select node
                        if response.clicked()
                            && let Some(block) = hovered_block
                        {
                            self.selected_node_idx = Some(block.node_idx);
                            self.scroll_to_selected = true; // Raise scroll trigger

                            // Auto expand parents so it shows up in tree view
                            let mut curr = Some(block.node_idx);
                            while let Some(idx) = curr {
                                if let Some(node) = snapshot.nodes.get(idx as usize) {
                                    if node.is_directory() {
                                        self.expanded_nodes.insert(idx);
                                    }
                                    curr = node.parent_opt();
                                } else {
                                    break;
                                }
                            }
                        }

                        // Draw tooltip
                        if let Some(block) = hovered_block {
                            let path_str = snapshot.get_full_path(block.node_idx);
                            let size_str = prettier_bytes::ByteFormatter::new()
                                .format(snapshot.nodes[block.node_idx as usize].size)
                                .to_string();
                            egui::Tooltip::always_open(
                                ctx.clone(),
                                ui.layer_id(),
                                egui::Id::new("treemap_tooltip"),
                                egui::PopupAnchor::Pointer,
                            )
                            .show(|ui| {
                                ui.label(format!("📁 {path_str}"));
                                ui.label(format!("💾 Size: {size_str}"));
                            });
                        }
                    }
                } else {
                    // Plots rendering block
                    ui.horizontal(|ui| {
                        ui.label("Select Plot:");
                        egui::ComboBox::from_id_salt("plot_type_combo")
                            .selected_text(match self.plot_type {
                                PlotType::SizeDistribution => "📊 File Size Distribution",
                                PlotType::AgeSizeScatter => "🌌 File Age vs. File Size",
                                PlotType::DirComposition => "🍰 Directory Composition",
                                PlotType::ExtensionBoxplot => "📦 File Sizes by Extension",
                                PlotType::TemporalTimeline => "⏱ Linked Temporal Timelines",
                            })
                            .show_ui(ui, |ui| {
                                ui.selectable_value(
                                    &mut self.plot_type,
                                    PlotType::SizeDistribution,
                                    "📊 File Size Distribution",
                                );
                                ui.selectable_value(
                                    &mut self.plot_type,
                                    PlotType::AgeSizeScatter,
                                    "🌌 File Age vs. File Size",
                                );
                                ui.selectable_value(
                                    &mut self.plot_type,
                                    PlotType::DirComposition,
                                    "🍰 Directory Composition",
                                );
                                ui.selectable_value(
                                    &mut self.plot_type,
                                    PlotType::ExtensionBoxplot,
                                    "📦 File Sizes by Extension",
                                );
                                ui.selectable_value(
                                    &mut self.plot_type,
                                    PlotType::TemporalTimeline,
                                    "⏱ Linked Temporal Timelines",
                                );
                            });
                    });
                    ui.separator();

                    if snapshot.nodes.is_empty() {
                        ui.centered_and_justified(|ui| {
                            ui.label("Scanned filesystem will be plotted here.");
                        });
                    } else {
                        match self.plot_type {
                            PlotType::SizeDistribution => {
                                Self::render_size_distribution_plot(ui, &snapshot);
                            }
                            PlotType::AgeSizeScatter => {
                                self.render_scatter_plot(ui, &snapshot);
                            }
                            PlotType::DirComposition => {
                                self.render_dir_composition_plot(ui, &snapshot);
                            }
                            PlotType::ExtensionBoxplot => {
                                self.render_boxplot_plot(ui, &snapshot);
                            }
                            PlotType::TemporalTimeline => {
                                self.render_timeline_plot(ui, &snapshot);
                            }
                        }
                    }
                }
            });
        });

        // Render Permanent Deletion Modal Popup
        if self.active_modal == Some(ActiveModal::Delete) {
            let idx_opt = self.delete_node_idx;
            if let Some(idx) = idx_opt {
                let path_str = snapshot.get_full_path(idx);
                let size_str = prettier_bytes::ByteFormatter::new()
                    .format(snapshot.nodes[idx as usize].size)
                    .to_string();

                let mut open = true;
                egui::Window::new("⚠ PERMANENT DELETION WARNING")
                    .anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0))
                    .collapsible(false)
                    .resizable(false)
                    .open(&mut open)
                    .frame(egui::Frame::window(ui.style()).stroke(egui::Stroke::new(2.0, crate::colors::DELETION_BORDER))) // Thick red border outline
                    .show(&ctx, |ui| {
                        ui.vertical(|ui| {
                            let path = std::path::Path::new(&path_str);
                            if path.exists() {
                                ui.heading(
                                    egui::RichText::new("⚠ Permanent Deletion Warning!")
                                        .color(crate::colors::DELETION_WARNING)
                                        .strong()
                                );
                                ui.separator();

                                ui.label("You are about to permanently delete the following path:");
                                ui.colored_label(ui.visuals().strong_text_color(), &path_str);
                                ui.label(format!("Total Size: {size_str}"));
                                ui.separator();

                                ui.label("This is a recursive deletion. All files, folders, and subdirectories under this path will be permanently deleted and cannot be recovered (bypassing the recycle/trash bin).");
                                ui.add_space(8.0);

                                ui.checkbox(&mut self.delete_confirm_checked, "I understand that files will be permanently deleted and cannot be recovered.");
                                ui.add_space(8.0);

                                ui.horizontal(|ui| {
                                    if ui.button("Cancel").clicked() {
                                        self.active_modal = None;
                                    }

                                    // Red confirm button
                                    let confirm_btn = egui::Button::new(
                                        egui::RichText::new("🗑 Yes, Delete Permanently")
                                            .color(egui::Color32::WHITE)
                                            .strong()
                                    ).fill(crate::colors::DELETION_BORDER);

                                    let confirm_res = ui.add_enabled(self.delete_confirm_checked, confirm_btn);
                                    if confirm_res.clicked() {
                                        let path = std::path::Path::new(&path_str);
                                        if path.exists() {
                                            let delete_result = if path.is_dir() {
                                                std::fs::remove_dir_all(path)
                                            } else {
                                                std::fs::remove_file(path)
                                            };

                                            if let Err(e) = delete_result {
                                                println!("Failed to delete path: {e}");
                                            } else {
                                                // Reset selection upon deletion
                                                self.selected_node_idx = None;
                                            }
                                        }
                                        self.active_modal = None;
                                    }
                                });
                            } else {
                                ui.heading(
                                    egui::RichText::new("❌ Path Does Not Exist!")
                                        .color(crate::colors::DELETION_WARNING)
                                        .strong()
                                );
                                ui.separator();
                                ui.label("Error: The path you are trying to delete does not exist on disk.");
                                ui.colored_label(ui.visuals().strong_text_color(), &path_str);
                                ui.add_space(8.0);
                                if ui.button("Close").clicked() {
                                    self.active_modal = None;
                                }
                            }
                        });
                    });
                if !open {
                    self.active_modal = None;
                }
            }
        }

        // Render Help -> About Modal Popup
        if self.active_modal == Some(ActiveModal::About) {
            let mut open = true;
            egui::Window::new("ℹ About eDirStat")
                .anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0))
                .collapsible(false)
                .resizable(false)
                .open(&mut open)
                .show(&ctx, |ui| {
                    ui.vertical_centered(|ui| {
                        ui.heading(
                            egui::RichText::new("eDirStat 👷")
                                .strong()
                                .color(ui.visuals().strong_text_color())
                        );
                        ui.label(concat!("v", env!("CARGO_PKG_VERSION")));
                        ui.separator();
                        ui.label("By: Cody Wyatt Neiman (xangelix) <".to_owned() + "neiman" + "@" + "cody.to>");
                        ui.add_space(8.0);
                        ui.label("A modern, zero-copy, highly performant disk usage analyzer written in Rust.");
                        ui.label("Features dynamic work-stealing multithreaded directory walking, lazy explorer sibling sorting, zero-copy persistent memory mapping, HSL treemap gradients, and instant virtual rendering.");
                        ui.add_space(8.0);
                        if ui.button("Close").clicked() {
                            self.active_modal = None;
                        }
                    });
                });
            if !open {
                self.active_modal = None;
            }
        }
    }
}

impl GuiApp {
    fn flatten_visible_tree(
        &mut self,
        snapshot: &FileArenaSnapshot,
        node_idx: u32,
        indent_level: usize,
        out: &mut Vec<(u32, usize)>,
    ) {
        let node = &snapshot.nodes[node_idx as usize];
        let name = snapshot.string_pool.get(node.name_id).unwrap_or("unknown");

        // Filter search query
        if !self.search_query.is_empty() {
            let matches_query = name
                .to_lowercase()
                .contains(&self.search_query.to_lowercase());
            // If it's a file and doesn't match, skip
            if !node.is_directory() && !matches_query {
                return;
            }
        }

        out.push((node_idx, indent_level));

        let is_expanded = self.expanded_nodes.contains(&node_idx);
        let has_children = node.is_directory() && node.first_child != NO_INDEX;

        if is_expanded && has_children {
            let mut sorted_child_indices = SmallVec::<[u32; 16]>::new();
            let mut curr = node.first_child;
            while curr != NO_INDEX {
                sorted_child_indices.push(curr);
                curr = snapshot.nodes[curr as usize].next_sibling;
            }
            // Sort immediate children by size descending dynamically for 100% correct tree views
            sorted_child_indices.sort_by(|&a, &b| {
                snapshot.nodes[b as usize]
                    .size
                    .cmp(&snapshot.nodes[a as usize].size)
            });

            for &child_idx in &sorted_child_indices {
                self.flatten_visible_tree(snapshot, child_idx, indent_level + 1, out);
            }
        }
    }

    fn render_tree_node_row(
        &mut self,
        ui: &mut egui::Ui,
        snapshot: &FileArenaSnapshot,
        node_idx: u32,
        indent_level: usize,
    ) {
        let node = &snapshot.nodes[node_idx as usize];
        let name = snapshot.string_pool.get(node.name_id).unwrap_or("unknown");

        let is_expanded = self.expanded_nodes.contains(&node_idx);
        let has_children = node.is_directory() && node.first_child != NO_INDEX;
        let is_selected = self.selected_node_idx == Some(node_idx);

        let horizontal_res = ui.horizontal(|ui| {
            // Indent padding
            #[allow(clippy::cast_precision_loss)]
            ui.add_space(indent_level as f32 * 16.0);

            // Icon & Expand Arrow
            let icon_text = if node.is_symlink() {
                "🔗"
            } else if node.is_directory() {
                "📁"
            } else {
                "📄"
            };

            if has_children {
                let arrow = if is_expanded { "[-]" } else { "[+]" };
                let rich_arrow = egui::RichText::new(arrow).monospace();
                let label = ui.selectable_label(is_expanded, rich_arrow);
                if label.clicked() {
                    if is_expanded {
                        self.expanded_nodes.remove(&node_idx);
                    } else {
                        self.expanded_nodes.insert(node_idx);
                    }
                }
            } else {
                ui.add_space(22.0); // Arrow placeholder alignment space matching "[+]"
            }

            ui.label(icon_text);

            // Node Name / Label with automatic left-aligned truncation
            let mut rich_name = egui::RichText::new(name);
            if self.monospace_paths {
                rich_name = rich_name.monospace();
            }
            if is_selected {
                rich_name = rich_name
                    .strong()
                    .color(ui.visuals().selection.stroke.color);
            }

            // Allocate exactly the remaining width minus space for the size column (72px subtracted)
            let name_width = (ui.available_width() - 72.0).max(50.0);

            ui.allocate_ui(egui::vec2(name_width, ui.spacing().interact_size.y), |ui| {
                ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
                ui.label(rich_name);
            });

            // Muted size details (far right aligned)
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                ui.label(
                    prettier_bytes::ByteFormatter::new()
                        .format(node.size)
                        .to_string(),
                );
            });
        });

        // Get the bounding box of the whole row
        let rect = horizontal_res.response.rect;

        // --- Offset the interaction hitbox strictly to the right of the expand button ---
        let mut interactive_rect = rect;
        #[allow(clippy::cast_precision_loss)]
        let expand_button_width = (indent_level as f32).mul_add(16.0, 24.0);
        interactive_rect.min.x += expand_button_width;

        let row_id = ui.id().with(("tree_row", node_idx));
        let response = ui.interact(interactive_rect, row_id, egui::Sense::click());

        // Draw professional background selection / hover highlights over the FULL row (for seamless visual style)
        if is_selected {
            let fill_color = ui.visuals().selection.bg_fill.linear_multiply(0.12);
            ui.painter().rect_filled(rect, 4.0, fill_color);
        } else if response.hovered() {
            let hover_color = ui.visuals().widgets.hovered.bg_fill.linear_multiply(0.04);
            ui.painter().rect_filled(rect, 4.0, hover_color);
        }

        // Handle selection on Left-Click or Right-Click (only outside of the expand button)
        if response.clicked() || response.secondary_clicked() {
            self.selected_node_idx = Some(node_idx);
        }

        // Render the context menu on Right-Click
        response.context_menu(|ui| {
            self.draw_file_menu_contents(ui, snapshot);
        });

        // Draw vertical indentation guidelines to visually track nested guidelines
        let painter = ui.painter();
        let stroke = egui::Stroke::new(1.0, crate::colors::INDENT_GUIDELINE);
        for i in 0..indent_level {
            #[allow(clippy::cast_precision_loss)]
            let x = (i as f32).mul_add(16.0, rect.min.x) + 8.0;

            // Draw a dashed vertical line
            let dash_length = 2.0;
            let gap_length = 2.0;
            let step = dash_length + gap_length;
            let total_height = rect.max.y - rect.min.y;
            if total_height > 0.0 {
                let num_steps = (total_height / step).ceil() as usize;
                for step_idx in 0..num_steps {
                    #[allow(clippy::cast_precision_loss)]
                    let segment_y = (step_idx as f32).mul_add(step, rect.min.y);

                    let next_y = (segment_y + dash_length).min(rect.max.y);
                    painter.line_segment([egui::pos2(x, segment_y), egui::pos2(x, next_y)], stroke);
                }
            }
        }
    }
}

// Custom Glassmorphic Dark styling settings
fn setup_custom_style(ctx: &egui::Context) {
    let mut visuals = egui::Visuals::dark();

    // Background Slate Color
    visuals.panel_fill = crate::colors::BG_PANEL_SLATE;
    visuals.window_fill = crate::colors::BG_WINDOW_SLATE;

    // Borders
    visuals.widgets.noninteractive.bg_fill = crate::colors::BG_WINDOW_SLATE;
    visuals.widgets.noninteractive.bg_stroke =
        egui::Stroke::new(1.0, crate::colors::STROKE_BORDER_SLATE);

    ctx.set_visuals(visuals);
}