edirstat 2.0.1

A fast, cross-platform disk usage analyzer and deduplicator—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
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
use std::sync::{Arc, atomic::Ordering};

use eframe::egui;

use super::{GuiApp, theme};
use crate::arena::{FileArenaSnapshot, NodeStorage, precompute_dir_counts};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActiveModal {
    Delete,
    Trash,
    About,
    DeleteDuplicates,
    TrashDuplicates,
    HardlinkDuplicates,
    SoftlinkDuplicates,
    HowItWorks,
    AdminWarning,
}

fn count_nested_stats(
    nodes: &[crate::arena::FileNode],
    idx: u32,
    files: &mut usize,
    dirs: &mut usize,
) {
    if idx as usize >= nodes.len() {
        return;
    }
    let node = &nodes[idx as usize];
    if node.is_directory() {
        *dirs += 1;
        let mut curr = node.first_child;
        while curr != crate::arena::NO_INDEX {
            count_nested_stats(nodes, curr, files, dirs);
            curr = nodes[curr as usize].next_sibling;
        }
    } else {
        *files += 1;
    }
}

fn collect_descendants(nodes: &[crate::arena::FileNode], idx: u32, out: &mut Vec<u32>) {
    if idx as usize >= nodes.len() {
        return;
    }
    let mut curr = nodes[idx as usize].first_child;
    while curr != crate::arena::NO_INDEX {
        out.push(curr);
        collect_descendants(nodes, curr, out);
        curr = nodes[curr as usize].next_sibling;
    }
}

struct WalkCtx<'a> {
    cloned_nodes: &'a mut Vec<crate::arena::FileNode>,
    string_pool: &'a mut crate::arena::StringPool,
    last_child_map: &'a mut Vec<u32>,
    traversal_stats: &'a crate::engine::traversal::TraversalStats,
    ancestors: &'a mut smallvec::SmallVec<[(u64, u64); 16]>,
}

fn walk_dir(dir_path: &std::path::Path, parent_idx: u32, dir_idx: u32, ctx: &mut WalkCtx<'_>) {
    let Ok(entries) = std::fs::read_dir(dir_path) else {
        return;
    };
    ctx.traversal_stats
        .dirs_scanned
        .fetch_add(1, Ordering::SeqCst);

    for entry_res in entries {
        let Ok(entry) = entry_res else {
            continue;
        };
        let Some(meta) = crate::arena::EntryMetadata::from_dir_entry(&entry) else {
            continue;
        };

        // Cycle Detection
        if meta.file_id != (0, 0) && ctx.ancestors.contains(&meta.file_id) {
            continue;
        }

        let name_id = ctx.string_pool.get_or_insert(meta.name.as_bytes());
        let child_idx = ctx.cloned_nodes.len() as u32;

        let node = crate::arena::FileNode::from_metadata(name_id, Some(parent_idx), &meta);
        ctx.cloned_nodes.push(node);
        ctx.last_child_map.push(crate::arena::NO_INDEX);

        // Connect to parent sibling chain
        let p_idx = parent_idx as usize;
        let last_child = ctx.last_child_map[p_idx];
        if last_child == crate::arena::NO_INDEX {
            ctx.cloned_nodes[p_idx].first_child = child_idx;
        } else {
            ctx.cloned_nodes[last_child as usize].next_sibling = child_idx;
        }
        ctx.last_child_map[p_idx] = child_idx;

        if meta.is_dir {
            if meta.file_id != (0, 0) {
                ctx.ancestors.push(meta.file_id);
            }
            walk_dir(&entry.path(), child_idx, dir_idx, ctx);
            if meta.file_id != (0, 0) {
                ctx.ancestors.pop();
            }
        } else {
            ctx.traversal_stats
                .files_scanned
                .fetch_add(1, Ordering::SeqCst);
            ctx.traversal_stats
                .bytes_scanned
                .fetch_add(meta.len as usize, Ordering::SeqCst);

            // Propagate size and count upwards through parent indices up to dir_idx
            let mut current_idx = Some(parent_idx);
            while let Some(idx) = current_idx {
                ctx.cloned_nodes[idx as usize].size += meta.len;
                ctx.cloned_nodes[idx as usize].file_count += 1;
                if idx == dir_idx {
                    break;
                }
                current_idx = ctx.cloned_nodes[idx as usize].parent_opt();
            }
        }
    }
}

impl GuiApp {
    /// Performs a zero-copy update to the active snapshot by unlinking deleted nodes,
    /// backtracking size weights up to the root, and swapping the updated tree structure.
    pub(crate) fn remove_nodes_from_snapshot(&mut self, target_indices: &[u32]) {
        if target_indices.is_empty() {
            return;
        }

        let current_snap = self.shared_state.current_snapshot.load();
        let mut cloned_nodes = current_snap.nodes.to_vec();

        let mut files_to_remove = 0;
        let mut dirs_to_remove = 0;
        let mut bytes_to_remove = 0u64;

        for &node_idx in target_indices {
            let idx = node_idx as usize;
            if idx >= cloned_nodes.len() {
                continue;
            }
            bytes_to_remove += cloned_nodes[idx].size;
            count_nested_stats(
                &cloned_nodes,
                node_idx,
                &mut files_to_remove,
                &mut dirs_to_remove,
            );
        }

        self.traversal_engine
            .stats()
            .files_scanned
            .fetch_sub(files_to_remove, Ordering::SeqCst);
        self.traversal_engine
            .stats()
            .dirs_scanned
            .fetch_sub(dirs_to_remove, Ordering::SeqCst);
        self.traversal_engine
            .stats()
            .bytes_scanned
            .fetch_sub(bytes_to_remove as usize, Ordering::SeqCst);

        // Clear chart caches to force re-computation
        self.size_dist_chart.cached_counts = None;
        self.dir_comp_chart.children_composition.clear();

        for &node_idx in target_indices {
            let node_idx = node_idx as usize;
            if node_idx >= cloned_nodes.len() {
                continue;
            }

            let node_size = cloned_nodes[node_idx].size;
            let parent_idx = cloned_nodes[node_idx].parent;
            let is_dir = cloned_nodes[node_idx].is_directory();

            // 1. Unlink the deleted item from its parent's sibling chain
            if parent_idx != crate::arena::NO_INDEX {
                let p_idx = parent_idx as usize;
                let mut prev_sibling: Option<u32> = None;
                let mut curr_sibling = cloned_nodes[p_idx].first_child;

                while curr_sibling != crate::arena::NO_INDEX {
                    if curr_sibling == node_idx as u32 {
                        let next_sib = cloned_nodes[node_idx].next_sibling;
                        if let Some(prev) = prev_sibling {
                            cloned_nodes[prev as usize].next_sibling = next_sib;
                        } else {
                            cloned_nodes[p_idx].first_child = next_sib;
                        }
                        break;
                    }
                    // Explicitly advance the pointer
                    prev_sibling = Some(curr_sibling);
                    curr_sibling = cloned_nodes[curr_sibling as usize].next_sibling;
                }
            }

            // 2. Roll back size metrics and file count up the ancestral line
            let mut current_parent = if parent_idx == crate::arena::NO_INDEX {
                None
            } else {
                Some(parent_idx)
            };
            while let Some(p_idx) = current_parent {
                let p_node = &mut cloned_nodes[p_idx as usize];
                p_node.size = p_node.size.saturating_sub(node_size);
                if !is_dir {
                    p_node.file_count = p_node.file_count.saturating_sub(1);
                }
                current_parent = p_node.parent_opt();
            }

            // 3. Isolate the node
            cloned_nodes[node_idx].size = 0;
            cloned_nodes[node_idx].file_count = 0;
            cloned_nodes[node_idx].first_child = crate::arena::NO_INDEX;
            cloned_nodes[node_idx].next_sibling = crate::arena::NO_INDEX;
        }

        let dir_counts = Arc::new(precompute_dir_counts(&cloned_nodes));
        let new_snapshot = crate::arena::FileArenaSnapshot {
            nodes: std::sync::Arc::new(NodeStorage::Owned(cloned_nodes)),
            string_pool: current_snap.string_pool.clone(),
            dir_counts,
        };
        self.shared_state
            .current_snapshot
            .store(std::sync::Arc::new(new_snapshot));
    }

    pub(crate) fn execute_deletion(
        &mut self,
        target_indices: &[u32],
        to_trash: bool,
        snapshot: &FileArenaSnapshot,
    ) {
        let mut successfully_deleted = Vec::new();
        let mut failures = Vec::new();
        for &idx in target_indices {
            let path_str = snapshot.get_full_path(idx);
            let path = std::path::Path::new(&path_str);
            if path.exists() {
                let result = if to_trash {
                    trash::delete(path).map_err(|e| (e.to_string(), is_permission_denied_trash(&e)))
                } else if path.is_dir() {
                    std::fs::remove_dir_all(path)
                        .map_err(|e| (e.to_string(), is_permission_denied_io(&e)))
                } else {
                    std::fs::remove_file(path)
                        .map_err(|e| (e.to_string(), is_permission_denied_io(&e)))
                };

                if let Err((err_msg, is_perm)) = result {
                    println!(
                        "Failed to delete/trash path {}: {}",
                        path.display(),
                        err_msg
                    );
                    failures.push((path_str, err_msg, is_perm));
                } else {
                    successfully_deleted.push(idx);
                }
            } else {
                successfully_deleted.push(idx);
            }
        }

        if to_trash {
            if !successfully_deleted.is_empty() {
                crate::gui::toast_success(format!(
                    "Moved {} item(s) to trash",
                    successfully_deleted.len()
                ));
            }
            if !failures.is_empty() {
                let perm_count = failures.iter().filter(|&(_, _, is_perm)| *is_perm).count();
                if perm_count == failures.len() {
                    crate::gui::toast_error(format!(
                        "Failed to move {} item(s) to trash (Permission Denied). Try running with elevated privileges.",
                        failures.len()
                    ));
                } else if perm_count > 0 {
                    crate::gui::toast_error(format!(
                        "Failed to move {} item(s) to trash ({} due to Permission Denied).",
                        failures.len(),
                        perm_count
                    ));
                } else {
                    crate::gui::toast_error(format!(
                        "Failed to move {} item(s) to trash",
                        failures.len()
                    ));
                }
            }
        } else {
            if !successfully_deleted.is_empty() {
                crate::gui::toast_success(format!(
                    "Permanently deleted {} item(s)",
                    successfully_deleted.len()
                ));
            }
            if !failures.is_empty() {
                let perm_count = failures.iter().filter(|&(_, _, is_perm)| *is_perm).count();
                if perm_count == failures.len() {
                    crate::gui::toast_error(format!(
                        "Failed to delete {} item(s) (Permission Denied). Try running with elevated privileges.",
                        failures.len()
                    ));
                } else if perm_count > 0 {
                    crate::gui::toast_error(format!(
                        "Failed to delete {} item(s) ({} due to Permission Denied).",
                        failures.len(),
                        perm_count
                    ));
                } else {
                    crate::gui::toast_error(format!("Failed to delete {} item(s)", failures.len()));
                }
            }
        }

        if !successfully_deleted.is_empty() {
            {
                let mut results = self.deduplicator_results.write();
                for group in &mut results.groups {
                    let mut i = 0;
                    while i < group.nodes.len() {
                        if successfully_deleted.contains(&group.nodes[i]) {
                            group.nodes.remove(i);
                            if i < group.file_ids.len() {
                                group.file_ids.remove(i);
                            }
                        } else {
                            i += 1;
                        }
                    }
                }
                results.groups.retain(|group| group.nodes.len() >= 2);
                results.rebuild_flat_rows(snapshot);
            }

            self.selected_duplicates
                .retain(|idx| !successfully_deleted.contains(idx));

            // Clean up selections inside RoaringBitmap
            for &idx in &successfully_deleted {
                self.table_state.selected_rows.remove(idx);
            }

            self.remove_nodes_from_snapshot(&successfully_deleted);
        }
    }

    pub(crate) fn execute_hardlinking(
        &mut self,
        target_indices: &[u32],
        snapshot: &FileArenaSnapshot,
    ) {
        let mut successfully_linked = Vec::new();
        let mut failures = Vec::new();
        let results_guard = self.deduplicator_results.read();

        for &idx in target_indices {
            let Some(group) = results_guard.groups.iter().find(|g| g.nodes.contains(&idx)) else {
                failures.push((
                    format!("Index {idx}"),
                    "Not found in any duplicate group".to_string(),
                    false,
                ));
                continue;
            };

            // Find a source node in the group that is NOT being replaced to link against
            let Some(&src_idx) = group.nodes.iter().find(|&&n| !target_indices.contains(&n)) else {
                failures.push((
                    format!("Index {idx}"),
                    "No remaining source file in group".to_string(),
                    false,
                ));
                continue;
            };

            let src_path_str = snapshot.get_full_path(src_idx);
            let dst_path_str = snapshot.get_full_path(idx);
            let src_path = std::path::Path::new(&src_path_str);
            let dst_path = std::path::Path::new(&dst_path_str);

            if src_path.exists() && dst_path.exists() {
                let temp_dst = dst_path.with_extension("tmp_hl_bak");
                match std::fs::rename(dst_path, &temp_dst) {
                    Err(e) => {
                        failures.push((dst_path_str, e.to_string(), is_permission_denied_io(&e)));
                    }
                    Ok(()) => {
                        match std::fs::hard_link(src_path, dst_path) {
                            Ok(()) => {
                                let _ = std::fs::remove_file(&temp_dst);
                                successfully_linked.push(idx);
                            }
                            Err(e) => {
                                // Restore backup on failure
                                let _ = std::fs::rename(&temp_dst, dst_path);
                                failures.push((
                                    dst_path_str,
                                    format!("Failed to create hard link: {e}"),
                                    is_permission_denied_io(&e),
                                ));
                            }
                        }
                    }
                }
            } else {
                failures.push((
                    dst_path_str,
                    "Source or destination path does not exist".to_string(),
                    false,
                ));
            }
        }

        if !successfully_linked.is_empty() {
            crate::gui::toast_success(format!(
                "Successfully replaced {} duplicate(s) with hardlinks",
                successfully_linked.len()
            ));
        }
        if !failures.is_empty() {
            let perm_count = failures.iter().filter(|&(_, _, is_perm)| *is_perm).count();
            if perm_count == failures.len() {
                crate::gui::toast_error(format!(
                    "Failed to hardlink {} duplicate(s) (Permission Denied).",
                    failures.len()
                ));
            } else if perm_count > 0 {
                crate::gui::toast_error(format!(
                    "Failed to hardlink {} duplicate(s) ({} due to Permission Denied).",
                    failures.len(),
                    perm_count
                ));
            } else {
                crate::gui::toast_error(format!(
                    "Failed to hardlink {} duplicate(s)",
                    failures.len()
                ));
            }
        }

        if !successfully_linked.is_empty() {
            drop(results_guard);
            {
                let mut results = self.deduplicator_results.write();
                for group in &mut results.groups {
                    let has_any = group.nodes.iter().any(|n| successfully_linked.contains(n));
                    if has_any {
                        for (i, &node_idx) in group.nodes.iter().enumerate() {
                            let path_str = snapshot.get_full_path(node_idx);
                            if let Ok(meta) = std::fs::metadata(path_str) {
                                let file_id = crate::engine::traversal::get_file_id(&meta);
                                if i < group.file_ids.len() {
                                    group.file_ids[i] = file_id;
                                }
                            }
                        }
                    }
                }
                results.rebuild_flat_rows(snapshot);
            }

            self.selected_duplicates
                .retain(|idx| !successfully_linked.contains(idx));
        }
    }

    pub(crate) fn execute_softlinking(
        &mut self,
        target_indices: &[u32],
        snapshot: &FileArenaSnapshot,
    ) {
        let mut successfully_linked = Vec::new();
        let mut failures = Vec::new();
        let results_guard = self.deduplicator_results.read();

        for &idx in target_indices {
            let Some(group) = results_guard.groups.iter().find(|g| g.nodes.contains(&idx)) else {
                failures.push((
                    format!("Index {idx}"),
                    "Not found in any duplicate group".to_string(),
                    false,
                ));
                continue;
            };

            // Find a source node in the group that is NOT being replaced to link against
            let Some(&src_idx) = group.nodes.iter().find(|&&n| !target_indices.contains(&n)) else {
                failures.push((
                    format!("Index {idx}"),
                    "No remaining source file in group".to_string(),
                    false,
                ));
                continue;
            };

            let src_path_str = snapshot.get_full_path(src_idx);
            let dst_path_str = snapshot.get_full_path(idx);
            let src_path = std::path::Path::new(&src_path_str);
            let dst_path = std::path::Path::new(&dst_path_str);

            if src_path.exists() && dst_path.exists() {
                let temp_dst = dst_path.with_extension("tmp_sl_bak");
                if let Err(e) = std::fs::rename(dst_path, &temp_dst) {
                    failures.push((dst_path_str, e.to_string(), is_permission_denied_io(&e)));
                } else {
                    let symlink_result = {
                        #[cfg(unix)]
                        {
                            std::os::unix::fs::symlink(src_path, dst_path)
                        }
                        #[cfg(windows)]
                        {
                            std::os::windows::fs::symlink_file(src_path, dst_path)
                        }
                        #[cfg(not(any(unix, windows)))]
                        {
                            Err(std::io::Error::new(
                                std::io::ErrorKind::Unsupported,
                                "Symlinks not supported on this platform",
                            ))
                        }
                    };

                    match symlink_result {
                        Ok(()) => {
                            let _ = std::fs::remove_file(&temp_dst);
                            successfully_linked.push(idx);
                        }
                        Err(e) => {
                            // Restore backup on failure
                            let _ = std::fs::rename(&temp_dst, dst_path);
                            failures.push((
                                dst_path_str,
                                format!("Failed to create symlink: {e}"),
                                is_permission_denied_io(&e),
                            ));
                        }
                    }
                }
            } else {
                failures.push((
                    dst_path_str,
                    "Source or destination path does not exist".to_string(),
                    false,
                ));
            }
        }

        if !successfully_linked.is_empty() {
            crate::gui::toast_success(format!(
                "Successfully replaced {} duplicate(s) with softlinks",
                successfully_linked.len()
            ));
        }
        if !failures.is_empty() {
            let perm_count = failures.iter().filter(|&(_, _, is_perm)| *is_perm).count();
            if perm_count == failures.len() {
                crate::gui::toast_error(format!(
                    "Failed to softlink {} duplicate(s) (Permission Denied).",
                    failures.len()
                ));
            } else if perm_count > 0 {
                crate::gui::toast_error(format!(
                    "Failed to softlink {} duplicate(s) ({} due to Permission Denied).",
                    failures.len(),
                    perm_count
                ));
            } else {
                crate::gui::toast_error(format!(
                    "Failed to softlink {} duplicate(s)",
                    failures.len()
                ));
            }
        }

        if !successfully_linked.is_empty() {
            drop(results_guard);
            {
                let mut results = self.deduplicator_results.write();
                for group in &mut results.groups {
                    let mut i = 0;
                    while i < group.nodes.len() {
                        if successfully_linked.contains(&group.nodes[i]) {
                            group.nodes.remove(i);
                            if i < group.file_ids.len() {
                                group.file_ids.remove(i);
                            }
                        } else {
                            i += 1;
                        }
                    }
                }
                results.groups.retain(|group| group.nodes.len() >= 2);
                results.rebuild_flat_rows(snapshot);
            }

            self.selected_duplicates
                .retain(|idx| !successfully_linked.contains(idx));

            // Clean up selections inside RoaringBitmap
            for &idx in &successfully_linked {
                self.table_state.selected_rows.remove(idx);
            }

            self.remove_nodes_from_snapshot(&successfully_linked);
        }
    }

    pub fn render_modals(&mut self, ctx: &egui::Context, snapshot: &FileArenaSnapshot) {
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        enum DeletionAction {
            DeleteMultiple,
            TrashMultiple,
            DeleteDuplicates,
            TrashDuplicates,
            HardlinkDuplicates,
            SoftlinkDuplicates,
        }

        struct ModalConfig {
            title: &'static str,
            border_color: egui::Color32,
            warning_color: egui::Color32,
            header: String,
            info_msg: String,
            warning_msg: &'static str,
            checkbox_label: &'static str,
            confirm_button_text: &'static str,
            paths: Vec<String>,
            action: DeletionAction,
        }

        let modal_config = match self.active_modal {
            Some(ActiveModal::Delete) => {
                let idxs = &self.delete_node_indices;
                if idxs.is_empty() {
                    None
                } else {
                    let total_size: u64 = idxs
                        .iter()
                        .map(|&idx| snapshot.nodes[idx as usize].size)
                        .sum();
                    let size_str = prettier_bytes::ByteFormatter::new()
                        .format(total_size)
                        .to_string();
                    let paths: Vec<String> = idxs
                        .iter()
                        .map(|&idx| {
                            crate::model::arena::clean_unc_path(&snapshot.get_full_path(idx))
                                .into_owned()
                        })
                        .collect();
                    Some(ModalConfig {
                        title: "⚠ PERMANENT DELETION WARNING",
                        border_color: theme::DELETION_BORDER,
                        warning_color: theme::DELETION_WARNING,
                        header: "⚠ Permanent Deletion Warning!".to_string(),
                        info_msg: format!("Total Size: {size_str}"),
                        warning_msg: "This is a recursive deletion. All files, folders, and subdirectories under the selected path(s) will be permanently deleted and cannot be recovered (bypassing the recycle/trash bin).",
                        checkbox_label: "I understand that files will be permanently deleted and cannot be recovered.",
                        confirm_button_text: "🗑 Yes, Delete Permanently",
                        paths,
                        action: DeletionAction::DeleteMultiple,
                    })
                }
            }
            Some(ActiveModal::Trash) => {
                let idxs = &self.delete_node_indices;
                if idxs.is_empty() {
                    None
                } else {
                    let total_size: u64 = idxs
                        .iter()
                        .map(|&idx| snapshot.nodes[idx as usize].size)
                        .sum();
                    let size_str = prettier_bytes::ByteFormatter::new()
                        .format(total_size)
                        .to_string();
                    let paths: Vec<String> = idxs
                        .iter()
                        .map(|&idx| {
                            crate::model::arena::clean_unc_path(&snapshot.get_full_path(idx))
                                .into_owned()
                        })
                        .collect();
                    Some(ModalConfig {
                        title: "♻ MOVE TO TRASH",
                        border_color: theme::TRASH_BORDER,
                        warning_color: theme::TRASH_WARNING,
                        header: "♻ Move to Trash".to_string(),
                        info_msg: format!("Total Size: {size_str}"),
                        warning_msg: "This will move the selected path(s) and all their contents to your system recycle bin/trash, where they can be recovered or permanently deleted later.",
                        checkbox_label: "I confirm that I want to move this to the trash.",
                        confirm_button_text: "♻ Yes, Move to Trash",
                        paths,
                        action: DeletionAction::TrashMultiple,
                    })
                }
            }
            Some(ActiveModal::DeleteDuplicates) => {
                let idxs = &self.delete_duplicates_indices;
                if idxs.is_empty() {
                    None
                } else {
                    let total_size: u64 = idxs
                        .iter()
                        .map(|&idx| snapshot.nodes[idx as usize].size)
                        .sum();
                    let size_str = prettier_bytes::ByteFormatter::new()
                        .format(total_size)
                        .to_string();
                    let paths = idxs
                        .iter()
                        .map(|&idx| {
                            crate::model::arena::clean_unc_path(&snapshot.get_full_path(idx))
                                .into_owned()
                        })
                        .collect();
                    Some(ModalConfig {
                        title: "⚠ PERMANENT DEDUPLICATION WARNING",
                        border_color: theme::DELETION_BORDER,
                        warning_color: theme::DELETION_WARNING,
                        header: "⚠ Permanent Duplicate Deletion Warning!".to_string(),
                        info_msg: format!("Total space to be reclaimed: {size_str}"),
                        warning_msg: "All selected files will be permanently deleted and cannot be recovered (bypassing the recycle/trash bin).",
                        checkbox_label: "I understand that files will be permanently deleted and cannot be recovered.",
                        confirm_button_text: "🗑 Yes, Delete Selected Permanently",
                        paths,
                        action: DeletionAction::DeleteDuplicates,
                    })
                }
            }
            Some(ActiveModal::TrashDuplicates) => {
                let idxs = &self.delete_duplicates_indices;
                if idxs.is_empty() {
                    None
                } else {
                    let total_size: u64 = idxs
                        .iter()
                        .map(|&idx| snapshot.nodes[idx as usize].size)
                        .sum();
                    let size_str = prettier_bytes::ByteFormatter::new()
                        .format(total_size)
                        .to_string();
                    let paths = idxs
                        .iter()
                        .map(|&idx| {
                            crate::model::arena::clean_unc_path(&snapshot.get_full_path(idx))
                                .into_owned()
                        })
                        .collect();
                    Some(ModalConfig {
                        title: "♻ MOVE DUPLICATES TO TRASH",
                        border_color: theme::TRASH_BORDER,
                        warning_color: theme::TRASH_WARNING,
                        header: "♻ Move Duplicates to Trash".to_string(),
                        info_msg: format!("Total space to be reclaimed: {size_str}"),
                        warning_msg: "All selected files will be moved to the recycle bin/trash.",
                        checkbox_label: "I confirm that I want to move these files to the trash.",
                        confirm_button_text: "♻ Yes, Move Selected to Trash",
                        paths,
                        action: DeletionAction::TrashDuplicates,
                    })
                }
            }
            Some(ActiveModal::HardlinkDuplicates) => {
                let idxs = &self.delete_duplicates_indices;
                if idxs.is_empty() {
                    None
                } else {
                    let total_size: u64 = idxs
                        .iter()
                        .map(|&idx| snapshot.nodes[idx as usize].size)
                        .sum();
                    let size_str = prettier_bytes::ByteFormatter::new()
                        .format(total_size)
                        .to_string();
                    let paths = idxs
                        .iter()
                        .map(|&idx| {
                            crate::model::arena::clean_unc_path(&snapshot.get_full_path(idx))
                                .into_owned()
                        })
                        .collect();
                    Some(ModalConfig {
                        title: "🔗 REPLACE DUPLICATES WITH HARDLINKS",
                        border_color: theme::BUTTON_ORANGE,
                        warning_color: theme::BUTTON_ORANGE_HOVER,
                        header: "🔗 Replace Duplicates with Hardlinks".to_string(),
                        info_msg: format!(
                            "Total files to process: {}. Cumulative virtual size: {}",
                            idxs.len(),
                            size_str
                        ),
                        warning_msg: "This will delete the selected duplicate files and replace them with filesystem-level hardlinks pointing to the remaining original file in each group. This retains files visually while freeing up actual physical storage.",
                        checkbox_label: "I confirm that I want to replace selected files with hardlinks.",
                        confirm_button_text: "🔗 Yes, Replace with Hardlinks",
                        paths,
                        action: DeletionAction::HardlinkDuplicates,
                    })
                }
            }
            Some(ActiveModal::SoftlinkDuplicates) => {
                let idxs = &self.delete_duplicates_indices;
                if idxs.is_empty() {
                    None
                } else {
                    let total_size: u64 = idxs
                        .iter()
                        .map(|&idx| snapshot.nodes[idx as usize].size)
                        .sum();
                    let size_str = prettier_bytes::ByteFormatter::new()
                        .format(total_size)
                        .to_string();
                    let paths = idxs
                        .iter()
                        .map(|&idx| {
                            crate::model::arena::clean_unc_path(&snapshot.get_full_path(idx))
                                .into_owned()
                        })
                        .collect();
                    Some(ModalConfig {
                        title: "🔗 REPLACE DUPLICATES WITH SOFTLINKS",
                        border_color: theme::BUTTON_ORANGE,
                        warning_color: theme::BUTTON_ORANGE_HOVER,
                        header: "🔗 Replace Duplicates with Softlinks".to_string(),
                        info_msg: format!(
                            "Total files to process: {}. Cumulative virtual size: {}",
                            idxs.len(),
                            size_str
                        ),
                        warning_msg: "This will delete the selected duplicate files and replace them with filesystem-level softlinks (symbolic links) pointing to the remaining original file in each group. This retains files visually while freeing up actual physical storage.",
                        checkbox_label: "I confirm that I want to replace selected files with softlinks.",
                        confirm_button_text: "🔗 Yes, Replace with Softlinks",
                        paths,
                        action: DeletionAction::SoftlinkDuplicates,
                    })
                }
            }
            _ => None,
        };

        if let Some(cfg) = modal_config {
            let mut open = true;
            egui::Window::new(cfg.title)
                .anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0))
                .collapsible(false)
                .resizable(!cfg.paths.is_empty())
                .default_width(550.0)
                .open(&mut open)
                .title_bar(false) // Disable default system title bar for uniform styling
                .frame(
                    egui::Frame::window(&ctx.global_style())
                        .fill(theme::BG_WINDOW_SLATE)
                        .stroke(egui::Stroke::new(1.2f32, egui::Color32::from_rgb(74, 85, 104))) // Bright, crisp slate border
                        .inner_margin(egui::Margin::ZERO) // Fill header completely to the borders
                        .corner_radius(8.0),
                )
                .show(ctx, |ui| {
                    // Custom Header Area
                    egui::Frame::new()
                        .inner_margin(egui::Margin::symmetric(16, 12))
                        .show(ui, |ui| {
                            ui.horizontal(|ui| {
                                ui.heading(
                                    egui::RichText::new(&cfg.header)
                                        .color(ui.visuals().strong_text_color())
                                        .strong(),
                                );
                                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                                    let close_btn = ui.button("");
                                    if close_btn.clicked() {
                                        self.active_modal = None;
                                    }
                                });
                            });
                        });

                    // Thin, subtle separator line matching normal panels
                    let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 1.0), egui::Sense::hover());
                    ui.painter().hline(rect.left()..=rect.right(), rect.center().y, egui::Stroke::new(1.0f32, theme::STROKE_BORDER_SLATE));

                    // Modal Content Frame
                    egui::Frame::new()
                        .inner_margin(egui::Margin::same(16))
                        .show(ui, |ui| {
                            ui.vertical(|ui| {
                                let path_exists = if cfg.paths.len() == 1 {
                                    let raw_path = match self.active_modal {
                                        Some(ActiveModal::Delete | ActiveModal::Trash) => {
                                            self.delete_node_indices.first().map_or_else(|| cfg.paths[0].clone(), |&idx| snapshot.get_full_path(idx))
                                        }
                                        Some(
                                            ActiveModal::DeleteDuplicates
                                            | ActiveModal::TrashDuplicates
                                            | ActiveModal::HardlinkDuplicates
                                            | ActiveModal::SoftlinkDuplicates,
                                        ) => {
                                            self.delete_duplicates_indices.first().map_or_else(|| cfg.paths[0].clone(), |&idx| snapshot.get_full_path(idx))
                                        }
                                        _ => cfg.paths[0].clone(),
                                    };
                                    std::path::Path::new(&raw_path).exists()
                                } else {
                                    true
                                };

                                if path_exists {
                                    ui.label(if cfg.paths.len() > 1 {
                                        format!(
                                            "You are about to process {} duplicate files/items:",
                                            cfg.paths.len()
                                        )
                                    } else {
                                        "You are about to process the following path:".to_string()
                                    });

                                    ui.add_space(8.0);

                                    // Display list of selected items inside a high-contrast container
                                    let path_bg = theme::BG_PANEL_SLATE;
                                    egui::Frame::new()
                                        .fill(path_bg)
                                        .stroke(egui::Stroke::new(1.0f32, theme::STROKE_BORDER_SLATE))
                                        .inner_margin(egui::Margin::same(12))
                                        .corner_radius(4.0)
                                        .show(ui, |ui| {
                                            ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);
                                            ui.colored_label(ui.visuals().strong_text_color(), &cfg.paths[0]);
                                            if cfg.paths.len() > 1 {
                                                ui.add_space(4.0);
                                                egui::ScrollArea::vertical()
                                                    .max_height(150.0)
                                                    .show(ui, |ui| {
                                                        for path in &cfg.paths[1..] {
                                                            ui.small(path);
                                                        }
                                                    });
                                            }
                                        });

                                    ui.add_space(8.0);

                                    ui.horizontal(|ui| {
                                        ui.label("Details: ");
                                        ui.label(egui::RichText::new(&cfg.info_msg).strong());
                                    });

                                    ui.add_space(8.0);
                                    ui.separator();
                                    ui.add_space(8.0);

                                    // Warning explanation text area
                                    ui.horizontal(|ui| {
                                        ui.colored_label(cfg.warning_color, "");
                                        ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);
                                        ui.label(egui::RichText::new(cfg.warning_msg));
                                    });

                                    ui.add_space(12.0);

                                    // Checkbox alignment
                                    ui.checkbox(&mut self.delete_confirm_checked, cfg.checkbox_label);
                                    ui.add_space(16.0);

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

                                        let confirm_btn = egui::Button::new(
                                            egui::RichText::new(cfg.confirm_button_text)
                                                .color(theme::COLOR_WHITE)
                                                .strong(),
                                        )
                                        .fill(cfg.border_color);

                                        let confirm_res =
                                            ui.add_enabled(self.delete_confirm_checked, confirm_btn);
                                        if confirm_res.clicked() {
                                            match cfg.action {
                                                DeletionAction::DeleteMultiple => {
                                                    self.execute_deletion(
                                                        &self.delete_node_indices.clone(),
                                                        false,
                                                        snapshot,
                                                    );
                                                    self.delete_node_indices.clear();
                                                }
                                                DeletionAction::TrashMultiple => {
                                                    self.execute_deletion(
                                                        &self.delete_node_indices.clone(),
                                                        true,
                                                        snapshot,
                                                    );
                                                    self.delete_node_indices.clear();
                                                }
                                                DeletionAction::DeleteDuplicates => {
                                                    self.execute_deletion(
                                                        &self.delete_duplicates_indices.clone(),
                                                        false,
                                                        snapshot,
                                                    );
                                                    self.delete_duplicates_indices.clear();
                                                }
                                                DeletionAction::TrashDuplicates => {
                                                    self.execute_deletion(
                                                        &self.delete_duplicates_indices.clone(),
                                                        true,
                                                        snapshot,
                                                    );
                                                    self.delete_duplicates_indices.clear();
                                                }
                                                DeletionAction::HardlinkDuplicates => {
                                                    self.execute_hardlinking(
                                                        &self.delete_duplicates_indices.clone(),
                                                        snapshot,
                                                    );
                                                    self.delete_duplicates_indices.clear();
                                                }
                                                DeletionAction::SoftlinkDuplicates => {
                                                    self.execute_softlinking(
                                                        &self.delete_duplicates_indices.clone(),
                                                        snapshot,
                                                    );
                                                    self.delete_duplicates_indices.clear();
                                                }
                                            }
                                            self.active_modal = None;
                                        }
                                    });
                                } else {
                                    ui.heading(
                                        egui::RichText::new("❌ Path Does Not Exist!")
                                            .color(theme::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(), &cfg.paths[0]);
                                    ui.add_space(16.0);
                                    if ui.button("Close").clicked() {
                                        self.active_modal = None;
                                    }
                                }
                            });
                        });
                });
            if !open {
                self.active_modal = None;
            }
        }

        // Render the Admin Access Recommendation Modal
        if self.active_modal == Some(ActiveModal::AdminWarning) {
            let mut open = true;
            egui::Window::new("⚠ Elevation Recommended")
                .anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0))
                .collapsible(false)
                .resizable(false)
                .open(&mut open)
                .title_bar(false) // Disable default system title bar to match custom styles
                .frame(
                    egui::Frame::window(&ctx.global_style())
                        .fill(theme::BG_WINDOW_SLATE)
                        .stroke(egui::Stroke::new(1.2f32, egui::Color32::from_rgb(74, 85, 104)))
                        .inner_margin(egui::Margin::ZERO)
                        .corner_radius(8.0),
                )
                .show(ctx, |ui| {
                    // Header Area
                    egui::Frame::new()
                        .inner_margin(egui::Margin::symmetric(16, 12))
                        .show(ui, |ui| {
                            ui.horizontal(|ui| {
                                ui.heading(
                                    egui::RichText::new("⚠ Elevation Recommended")
                                        .color(ui.visuals().strong_text_color())
                                        .strong(),
                                );
                                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                                    let close_btn = ui.button("");
                                    if close_btn.clicked() {
                                        self.active_modal = None;
                                    }
                                });
                            });
                        });

                    // Separator line
                    let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 1.0), egui::Sense::hover());
                    ui.painter().hline(rect.left()..=rect.right(), rect.center().y, egui::Stroke::new(1.0f32, theme::STROKE_BORDER_SLATE));

                    // Content Area
                    egui::Frame::new()
                        .inner_margin(egui::Margin::same(16))
                        .show(ui, |ui| {
                            ui.vertical(|ui| {
                                ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);
                                ui.label("eDirStat runs with standard user privileges by default. However, Windows strictly restricts raw physical disk handle access to administrator accounts.");
                                ui.add_space(10.0);

                                // Warning highlight box
                                egui::Frame::new()
                                    .fill(theme::BG_PANEL_SLATE)
                                    .stroke(egui::Stroke::new(1.0f32, theme::STROKE_BORDER_SLATE))
                                    .inner_margin(egui::Margin::same(12))
                                    .corner_radius(4.0)
                                    .show(ui, |ui| {
                                        ui.set_min_width(ui.available_width());
                                        ui.horizontal(|ui| {
                                            ui.colored_label(theme::WARNING_RED, "");
                                            ui.vertical(|ui| {
                                                ui.strong("Windows NTFS MFT Driver Disabled");
                                                ui.small("Without administrative privileges, the direct-to-disk MFT scanner cannot initialize. File analysis will use the fallback standard traversal driver, reducing scan performance by as much as 20x.");
                                            });
                                        });
                                    });

                                ui.add_space(12.0);
                                ui.label("Would you like to relaunch the application with Administrator privileges now?");
                                ui.add_space(16.0);

                                // Modal actions footer
                                ui.horizontal(|ui| {
                                    if ui.button("Continue as Standard User").clicked() {
                                        self.active_modal = None;
                                    }

                                    let relaunch_btn = egui::Button::new(
                                        egui::RichText::new("🛡 Relaunch as Admin")
                                            .color(theme::COLOR_WHITE)
                                            .strong(),
                                    )
                                    .fill(theme::BUTTON_ORANGE);

                                    if ui.add(relaunch_btn).clicked() {
                                        #[cfg(target_os = "windows")]
                                        {
                                            let _ = cli_or_gui::relaunch_as_elevated();
                                        }
                                    }
                                });
                            });
                        });
                });
            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)
                .title_bar(false) // Disable default system title bar
                .frame(
                    egui::Frame::window(&ctx.global_style())
                        .fill(theme::BG_WINDOW_SLATE)
                        .stroke(egui::Stroke::new(1.2f32, egui::Color32::from_rgb(74, 85, 104))) // Matching bright slate border
                        .inner_margin(egui::Margin::ZERO)
                        .corner_radius(8.0),
                )
                .show(ctx, |ui| {
                    // Custom Header Area
                    egui::Frame::new()
                        .inner_margin(egui::Margin::symmetric(16, 12))
                        .show(ui, |ui| {
                            ui.horizontal(|ui| {
                                ui.heading(
                                    egui::RichText::new("ℹ About eDirStat")
                                        .color(ui.visuals().strong_text_color())
                                        .strong(),
                                );
                                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                                    let close_btn = ui.button("");
                                    if close_btn.clicked() {
                                        self.active_modal = None;
                                    }
                                });
                            });
                        });

                    // Thin, subtle separator line
                    let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 1.0), egui::Sense::hover());
                    ui.painter().hline(rect.left()..=rect.right(), rect.center().y, egui::Stroke::new(1.0f32, theme::STROKE_BORDER_SLATE));

                    // Content Area
                    egui::Frame::new()
                        .inner_margin(egui::Margin::same(16))
                        .show(ui, |ui| {
                            ui.vertical_centered(|ui| {
                                ui.add(
                                    egui::Image::new(egui::include_image!("../../assets/img/logo-nosubtext-transparent.svg"))
                                        .max_height(100.0)
                                );
                                ui.add_space(8.0);

                                ui.label(egui::RichText::new(concat!("v", env!("CARGO_PKG_VERSION"))).strong().color(ui.visuals().strong_text_color()));
                                #[cfg(feature = "online")]
                                {
                                    ui.add_space(4.0);
                                    self.draw_update_check_ui(ui);
                                }
                                ui.add_space(8.0);
                                ui.separator();
                                ui.add_space(8.0);

                                ui.label(egui::RichText::new("By: Cody Wyatt Neiman (xangelix) <neiman@cody.to>"));
                                ui.add_space(12.0);

                                let info_bg = theme::BG_PANEL_SLATE;
                                egui::Frame::new()
                                    .fill(info_bg)
                                    .stroke(egui::Stroke::new(1.0f32, theme::STROKE_BORDER_SLATE))
                                    .inner_margin(egui::Margin::same(12))
                                    .corner_radius(4.0)
                                    .show(ui, |ui| {
                                        ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);
                                        ui.label("A high-performance disk space analyzer and deduplication toolkit built in Rust.");
                                        ui.add_space(6.0);
                                        ui.label("Features parallel, work-stealing directory traversal, compressed snapshots with zero-parsing layout deserialization, and responsive, interactive treemaps.");
                                        ui.add_space(6.0);
                                        ui.label("The integrated deduplicator runs a multi-stage cryptographic hashing pipeline to safely isolate duplicate groups, calculate reclaimable space, and respect system-level hardlinks.");
                                    });

                                ui.add_space(16.0);

                                if ui.button("View Open Source Licenses").clicked() {
                                    self.show_licenses = true;
                                }
                            });
                        });
                });
            if !open {
                self.active_modal = None;
            }
        }

        // Render "How Deduplication Works" Modal
        if self.active_modal == Some(ActiveModal::HowItWorks) {
            let mut open = true;
            egui::Window::new("ℹ How Deduplication Works")
                .anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0))
                .collapsible(false)
                .resizable(false)
                .open(&mut open)
                .title_bar(false) // Disable default system title bar
                .frame(
                    egui::Frame::window(&ctx.global_style())
                        .fill(theme::BG_WINDOW_SLATE)
                        .stroke(egui::Stroke::new(1.2f32, egui::Color32::from_rgb(74, 85, 104)))
                        .inner_margin(egui::Margin::ZERO)
                        .corner_radius(8.0),
                )
                .show(ctx, |ui| {
                    // Custom Header Area
                    egui::Frame::new()
                        .inner_margin(egui::Margin::symmetric(16, 12))
                        .show(ui, |ui| {
                            ui.horizontal(|ui| {
                                ui.heading(
                                    egui::RichText::new("ℹ How Deduplication Works")
                                        .color(ui.visuals().strong_text_color())
                                        .strong(),
                                );
                                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                                    let close_btn = ui.button("");
                                    if close_btn.clicked() {
                                        self.active_modal = None;
                                    }
                                });
                            });
                        });

                    // Thin, subtle separator line
                    let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 1.0), egui::Sense::hover());
                    ui.painter().hline(rect.left()..=rect.right(), rect.center().y, egui::Stroke::new(1.0f32, theme::STROKE_BORDER_SLATE));

                    // Content Area
                    egui::Frame::new()
                        .inner_margin(egui::Margin::same(16))
                        .show(ui, |ui| {
                            ui.vertical(|ui| {
                                egui::ScrollArea::vertical()
                                    .max_height(450.0)
                                    .auto_shrink([false, true]) // Lock scrollbar against the right edge
                                    .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible)
                                    .content_margin(egui::Margin {
                                        left: 0,
                                        right: 14, // Clean separation padding before the scrollbar
                                        top: 0,
                                        bottom: 0,
                                    })
                                    .show(ui, |ui| {
                                        ui.vertical(|ui| {
                                            ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);

                                            ui.label(
                                                "Rather than comparing every file's bytes directly (which requires slow, pairwise O(N²) scans), this system utilizes a highly optimized 7-stage pipeline to identify identical content safely and efficiently."
                                            );
                                            ui.add_space(10.0);

                                            ui.strong("The 7-Stage Pipeline:");
                                            ui.add_space(6.0);

                                            let steps = [
                                                ("1. Size Partitioning", "Files are grouped by their exact size in bytes. Any file with a unique size is discarded immediately, bypassing disk I/O entirely."),
                                                ("2. Prefix Hashing", "The first 4KB of remaining candidates are hashed. This quickly filters out files with different headers or metadata formats."),
                                                ("3. Midpoint Hashing", "A 4KB block from the center of the remaining files is hashed, catching internal structural differences."),
                                                ("4. Suffix Hashing", "The last 4KB of data is hashed. This is highly effective at identifying differences in trailing contents or metadata."),
                                                ("5. Multi-Range Hashing", "Large files (over 100MB) undergo periodic block sampling across their entire length to verify content consistency without reading the entire file."),
                                                ("6. Full BLAKE3 Hashing", "For remaining candidates, a full BLAKE3 cryptographic hash is computed. Due to the high collision resistance of a 256-bit space, matching hashes indicate an astronomical unlikeliness that the files differ, providing a highly reliable proof of identity without requiring pairwise comparisons."),
                                                ("7. Timestamp Validation", "Right before displaying or executing any deduplication action, the application verifies the files' timestamps on disk to protect against changes that occurred since snapshot generation.")
                                            ];

                                            for (title, desc) in steps {
                                                egui::Frame::new()
                                                    .fill(theme::BG_PANEL_SLATE)
                                                    .stroke(egui::Stroke::new(1.0f32, theme::STROKE_BORDER_SLATE))
                                                    .inner_margin(egui::Margin::same(10))
                                                    .corner_radius(4.0)
                                                    .show(ui, |ui| {
                                                        // Stretch step frame to align perfectly with content bounds
                                                        ui.set_min_width(ui.available_width());
                                                        ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);
                                                        ui.strong(title);
                                                        ui.add_space(2.0);
                                                        ui.small(desc);
                                                    });
                                                ui.add_space(6.0);
                                            }

                                            ui.add_space(10.0);
                                            ui.strong("Why is this sufficient?");
                                            ui.add_space(4.0);
                                            ui.label(
                                                "This multi-stage filter ensures that only files with identical size, prefix, midpoint, suffix, and distributed block samples are read in full. Finally, comparing a 256-bit BLAKE3 cryptographic hash offers a safety profile on par with industry-grade secure transfer protocols, eliminating the need for slow, pairwise byte-by-byte comparisons."
                                            );
                                        });
                                    });

                                ui.add_space(16.0);
                                ui.vertical_centered(|ui| {
                                    if ui.button("Close").clicked() {
                                        self.active_modal = None;
                                    }
                                });
                            });
                        });
                });
            if !open {
                self.active_modal = None;
            }
        }

        if self.show_licenses {
            let mut open = true;
            egui::Window::new("📜 Open Source Licenses")
                .anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0))
                .collapsible(false)
                .resizable(true)
                .default_width(650.0)
                .default_height(500.0)
                .open(&mut open)
                .title_bar(false)
                .frame(
                    egui::Frame::window(&ctx.global_style())
                        .fill(theme::BG_WINDOW_SLATE)
                        .stroke(egui::Stroke::new(1.2f32, egui::Color32::from_rgb(74, 85, 104)))
                        .inner_margin(egui::Margin::ZERO)
                        .corner_radius(8.0),
                )
                .show(ctx, |ui| {
                    // Custom Header Area
                    egui::Frame::new()
                        .inner_margin(egui::Margin::symmetric(16, 12))
                        .show(ui, |ui| {
                            ui.horizontal(|ui| {
                                ui.heading(
                                    egui::RichText::new("📜 Open Source Licenses")
                                        .color(ui.visuals().strong_text_color())
                                        .strong(),
                                );
                                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                                    let close_btn = ui.button("");
                                    if close_btn.clicked() {
                                        self.show_licenses = false;
                                    }
                                });
                            });
                        });

                    // Thin, subtle separator line matching normal panels
                    let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 1.0), egui::Sense::hover());
                    ui.painter().hline(rect.left()..=rect.right(), rect.center().y, egui::Stroke::new(1.0f32, theme::STROKE_BORDER_SLATE));

                    // Modal Content Frame
                    egui::Frame::new()
                        .inner_margin(egui::Margin::same(16))
                        .show(ui, |ui| {
                            ui.vertical(|ui| {
                                ui.label("The following third-party libraries and crates are used in this application:");
                                ui.add_space(8.0);

                                let mut licenses_text = {
                                    #[cfg(target_os = "linux")]
                                    let bytes = include_packed::include_packed!("assets/licenses/linux.md");
                                    #[cfg(target_os = "windows")]
                                    let bytes = include_packed::include_packed!("assets/licenses/windows.md");
                                    #[cfg(target_os = "macos")]
                                    let bytes = include_packed::include_packed!("assets/licenses/macos.md");
                                    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
                                    let bytes = include_packed::include_packed!("assets/licenses/linux.md");

                                    String::from_utf8(bytes).unwrap_or_default()
                                };

                                egui::ScrollArea::vertical()
                                    .max_height(350.0)
                                    .show(ui, |ui| {
                                        ui.add(
                                            egui::TextEdit::multiline(&mut licenses_text)
                                                .font(egui::TextStyle::Monospace)
                                                .desired_width(f32::INFINITY)
                                                .desired_rows(18)
                                                .interactive(true)
                                        );
                                    });

                                ui.add_space(16.0);
                                ui.horizontal(|ui| {
                                    if ui.button("Close").clicked() {
                                        self.show_licenses = false;
                                    }
                                });
                            });
                        });
                });
            if !open {
                self.show_licenses = false;
            }
        }
    }

    pub(crate) fn refresh_directory_subtree(&mut self, dir_idx: u32) {
        self.refresh_directory_subtrees(&[dir_idx]);
    }

    pub(crate) fn refresh_directory_subtrees(&mut self, dir_indices: &[u32]) {
        if dir_indices.is_empty() {
            return;
        }
        self.scan_start_time = Some(std::time::Instant::now());
        self.total_scan_duration = None;
        let current_snap = self.shared_state.current_snapshot.load();
        let mut valid_indices = Vec::new();
        for &idx in dir_indices {
            let path_str = current_snap.get_full_path(idx);
            let path = std::path::PathBuf::from(path_str);
            if path.exists() && path.is_dir() {
                valid_indices.push((idx, path));
            }
        }
        if valid_indices.is_empty() {
            return;
        }

        let state = self.shared_state.clone();
        let traversal_stats = self.traversal_engine.stats().clone();

        state.is_scanning.store(true, Ordering::SeqCst);

        std::thread::spawn(move || {
            let current_snap = state.current_snapshot.load();
            let mut cloned_nodes = current_snap.nodes.to_vec();
            let mut string_pool = (*current_snap.string_pool).clone();

            for (dir_idx, path) in valid_indices {
                // 1. Collect and delete old descendants of dir_idx
                let mut descendants = Vec::new();
                collect_descendants(&cloned_nodes, dir_idx, &mut descendants);

                let old_size = cloned_nodes[dir_idx as usize].size;
                let old_file_count = cloned_nodes[dir_idx as usize].file_count;

                // Roll back ancestors size/counts
                let mut current_parent = cloned_nodes[dir_idx as usize].parent_opt();
                while let Some(p_idx) = current_parent {
                    let p_node = &mut cloned_nodes[p_idx as usize];
                    p_node.size = p_node.size.saturating_sub(old_size);
                    p_node.file_count = p_node.file_count.saturating_sub(old_file_count);
                    current_parent = p_node.parent_opt();
                }

                let mut files_removed = 0;
                let mut dirs_removed = 0;
                for &idx in &descendants {
                    let node = &cloned_nodes[idx as usize];
                    if node.is_directory() {
                        dirs_removed += 1;
                    } else {
                        files_removed += 1;
                    }
                }

                traversal_stats
                    .files_scanned
                    .fetch_sub(files_removed, Ordering::SeqCst);
                traversal_stats
                    .dirs_scanned
                    .fetch_sub(dirs_removed, Ordering::SeqCst);
                traversal_stats
                    .bytes_scanned
                    .fetch_sub(old_size as usize, Ordering::SeqCst);

                // Isolate old descendants
                for &idx in &descendants {
                    let idx = idx as usize;
                    cloned_nodes[idx].size = 0;
                    cloned_nodes[idx].file_count = 0;
                    cloned_nodes[idx].first_child = crate::arena::NO_INDEX;
                    cloned_nodes[idx].next_sibling = crate::arena::NO_INDEX;
                    // Do NOT set parent to NO_INDEX to avoid them being treated as ghost root nodes
                }

                cloned_nodes[dir_idx as usize].first_child = crate::arena::NO_INDEX;
                cloned_nodes[dir_idx as usize].size = 0;
                cloned_nodes[dir_idx as usize].file_count = 0;

                // 2. Scan the directory recursively on disk and append new nodes
                let mut last_child_map = vec![crate::arena::NO_INDEX; cloned_nodes.len()];

                // --- BUILD ANCESTORS FOR CYCLE DETECTION ---
                let mut ancestors: smallvec::SmallVec<[(u64, u64); 16]> = smallvec::smallvec![];
                for ancestor_path in path.ancestors() {
                    if let Ok(meta) = std::fs::metadata(ancestor_path) {
                        ancestors.push(crate::engine::traversal::get_file_id(&meta));
                    }
                }
                // Reverse so that the root ancestor is first and the target path is last
                ancestors.reverse();

                let mut walk_ctx = WalkCtx {
                    cloned_nodes: &mut cloned_nodes,
                    string_pool: &mut string_pool,
                    last_child_map: &mut last_child_map,
                    traversal_stats: &traversal_stats,
                    ancestors: &mut ancestors,
                };
                walk_dir(&path, dir_idx, dir_idx, &mut walk_ctx);

                // 3. Now propagate the new size/counts of dir_idx to all its ancestors!
                let new_size = cloned_nodes[dir_idx as usize].size;
                let new_file_count = cloned_nodes[dir_idx as usize].file_count;

                let mut current_parent = cloned_nodes[dir_idx as usize].parent_opt();
                while let Some(p_idx) = current_parent {
                    let p_node = &mut cloned_nodes[p_idx as usize];
                    p_node.size += new_size;
                    p_node.file_count += new_file_count;
                    current_parent = p_node.parent_opt();
                }
            }

            // 4. Swap snapshot
            let dir_counts = Arc::new(precompute_dir_counts(&cloned_nodes));
            let new_snapshot = FileArenaSnapshot {
                nodes: Arc::new(NodeStorage::Owned(cloned_nodes)),
                string_pool: Arc::new(string_pool),
                dir_counts,
            };
            state.current_snapshot.store(Arc::new(new_snapshot));

            state.is_scanning.store(false, Ordering::SeqCst);
        });
    }
}

#[cfg(feature = "online")]
impl GuiApp {
    fn draw_update_check_ui(&mut self, ui: &mut egui::Ui) {
        let check_result = self.update_checker.read_or_request(|| async {
            let client = reqwest::Client::builder()
                .user_agent("edirstat-update-checker")
                .build()
                .map_err(|e| e.to_string())?;

            let response = client
                .get("https://github.com/xangelix/edirstat/releases/latest")
                .send()
                .await
                .map_err(|e| e.to_string())?;

            let final_url = response.url();
            let tag = final_url
                .path_segments()
                .and_then(|mut segments| segments.next_back())
                .ok_or_else(|| "Invalid release URL structure".to_string())?;

            let latest_version_str = tag.trim_start_matches('v');
            let latest_version = semver::Version::parse(latest_version_str)
                .map_err(|e| format!("Failed to parse latest version '{tag}': {e}"))?;

            let current_version_str = env!("CARGO_PKG_VERSION");
            let current_version = semver::Version::parse(current_version_str).map_err(|e| {
                format!("Failed to parse current version '{current_version_str}': {e}")
            })?;

            if latest_version > current_version && latest_version.pre.is_empty() {
                Ok(Some(tag.to_string()))
            } else {
                Ok(None)
            }
        });

        match check_result {
            None => {
                ui.horizontal(|ui| {
                    ui.spinner();
                    ui.small("Checking for updates...");
                });
            }
            Some(Ok(Some(new_version))) => {
                ui.horizontal(|ui| {
                    ui.colored_label(theme::BUTTON_ORANGE, "");
                    ui.hyperlink_to(
                        egui::RichText::new(format!("New version {new_version} available!"))
                            .color(theme::BUTTON_ORANGE)
                            .strong(),
                        "https://github.com/xangelix/edirstat/releases/latest",
                    );
                });
            }
            Some(Ok(None)) => {
                ui.weak("You are up to date");
            }
            Some(Err(err)) => {
                ui.weak(format!("Update check failed: {err}"));
            }
        }
    }
}

fn is_permission_denied_io(err: &std::io::Error) -> bool {
    err.kind() == std::io::ErrorKind::PermissionDenied
}

fn is_permission_denied_trash(err: &trash::Error) -> bool {
    match err {
        trash::Error::CouldNotAccess { .. } => true,
        #[cfg(all(
            unix,
            not(target_os = "macos"),
            not(target_os = "ios"),
            not(target_os = "android")
        ))]
        trash::Error::FileSystem { source, .. } => {
            source.kind() == std::io::ErrorKind::PermissionDenied
        }
        trash::Error::Os { description, .. } | trash::Error::Unknown { description } => {
            let desc_lower = description.to_lowercase();
            desc_lower.contains("permission")
                || desc_lower.contains("access is denied")
                || desc_lower.contains("denied")
        }
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use crate::coordinator::{Coordinator, SharedState};
    use crate::engine::traversal::TraversalEngine;

    #[test]
    fn test_execute_softlinking() -> Result<(), crate::EdirstatError> {
        let temp_dir = std::env::current_dir()?
            .join("target")
            .join("test_gui_softlinking");
        let _ = std::fs::remove_dir_all(&temp_dir); // Clean old
        std::fs::create_dir_all(&temp_dir)?;

        let file1_path = temp_dir.join("file1.txt");
        let file2_path = temp_dir.join("file2.txt");

        let content = b"hello identical softlink content! hello identical softlink content!";
        std::fs::write(&file1_path, content)?;
        std::fs::write(&file2_path, content)?;

        let shared_state = Arc::new(SharedState::new());
        let engine = Arc::new(TraversalEngine::new());
        let (tx, rx) = crossbeam::channel::unbounded();

        let handle = engine.start_traversal(temp_dir.clone(), tx)?;
        let mut coordinator = Coordinator::new(rx, shared_state.clone());
        coordinator.run_coordinator_loop(&temp_dir.to_string_lossy());
        let _ = handle.join();

        let snapshot = shared_state.current_snapshot.load();
        assert!(!snapshot.nodes.is_empty());

        let mut app = GuiApp::new(shared_state, engine, None);

        // Scan duplicates using run_deduplication
        let progress = atomic_progress::Progress::new_spinner("Deduplicator");
        let config = crate::stats::deduplicator::DeduplicatorConfig {
            min_size: 1,
            ignore_system: false,
            ignore_hidden: false,
        };
        crate::stats::deduplicator::run_deduplication(
            snapshot.clone(),
            progress,
            app.deduplicator_results.clone(),
            app.deduplicator_cancel.clone(),
            config,
        );

        // Verify we found a duplicate group
        assert_eq!(app.deduplicator_results.read().groups.len(), 1);
        assert_eq!(app.deduplicator_results.read().groups[0].nodes.len(), 2);

        // We want to replace the second file (node index 2 or 1, let's find the one that is not original/first)
        let target_node_idx = {
            let results_guard = app.deduplicator_results.read();
            // The flat_rows sorted items: first is original, second is duplicate to be replaced.
            assert_eq!(results_guard.flat_rows.len(), 2);
            assert!(!results_guard.flat_rows[1].is_original);
            results_guard.flat_rows[1].node_idx
        };

        // Execute softlinking
        app.execute_softlinking(&[target_node_idx], &snapshot);

        // Verify the softlink exists and points to the first file
        let target_path = snapshot.get_full_path(target_node_idx);
        let link_path = std::path::Path::new(&target_path);
        assert!(link_path.exists());
        assert!(link_path.is_symlink());

        // Verify that the softlinked node has been removed from the results
        assert!(app.deduplicator_results.read().groups.is_empty());
        assert!(app.deduplicator_results.read().flat_rows.is_empty());

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_dir);
        Ok(())
    }

    #[test]
    fn test_gui_app_new_with_initial_path() -> Result<(), crate::EdirstatError> {
        let temp_dir = std::env::current_dir()?
            .join("target")
            .join("test_gui_app_initial_path");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir)?;

        let test_file = temp_dir.join("test.txt");
        std::fs::write(&test_file, b"hello world")?;

        let shared_state = Arc::new(SharedState::new());
        let engine = Arc::new(TraversalEngine::new());

        // Test scanning a directory
        let app = GuiApp::new(shared_state.clone(), engine, Some(temp_dir.clone()));

        // Wait for the background scan to start
        let mut attempts = 0;
        while !shared_state.is_scanning.load(Ordering::SeqCst) && attempts < 200 {
            std::thread::sleep(std::time::Duration::from_millis(10));
            attempts += 1;
        }

        // Wait for the background scan to complete
        attempts = 0;
        while shared_state.is_scanning.load(Ordering::SeqCst) && attempts < 200 {
            std::thread::sleep(std::time::Duration::from_millis(10));
            attempts += 1;
        }

        let snapshot = shared_state.current_snapshot.load();
        assert!(!snapshot.nodes.is_empty());
        assert_eq!(app.current_scan_path, Some(temp_dir.clone()));

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_dir);
        Ok(())
    }

    #[test]
    fn test_gui_app_new_with_snapshot_file() -> Result<(), crate::EdirstatError> {
        let temp_dir = std::env::current_dir()?
            .join("target")
            .join("test_gui_app_snapshot_file");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir)?;

        let mut pool = crate::arena::StringPool::new();
        let name_root = pool.get_or_insert(b"/");
        let nodes = vec![crate::arena::FileNode::new(
            name_root, None, true, false, 0, 0, 0,
        )];
        let test_file = temp_dir.join("test_snapshot.edst");
        crate::persistence::save_snapshot(&nodes, &pool, &test_file)?;

        let shared_state = Arc::new(SharedState::new());
        let engine = Arc::new(TraversalEngine::new());

        // Test loading snapshot file
        let app = GuiApp::new(shared_state.clone(), engine, Some(test_file.clone()));

        let snapshot = shared_state.current_snapshot.load();
        assert!(!snapshot.nodes.is_empty());
        assert_eq!(app.current_scan_path, Some(test_file));

        // Clean up
        let _ = std::fs::remove_dir_all(&temp_dir);
        Ok(())
    }

    #[test]
    fn test_gui_root_name_clean_unc() -> Result<(), egui_table_kit::error::TableError> {
        use egui_table_kit::operations::TableProvider as _;

        let mut pool = crate::arena::StringPool::new();
        // A Windows UNC path as the root node name
        let name_root = pool.get_or_insert(b"\\\\?\\C:\\TestFolder");
        let nodes = vec![crate::arena::FileNode::new(
            name_root, None, true, false, 0, 0, 0,
        )];
        let dir_counts = crate::arena::precompute_dir_counts(&nodes);
        let snapshot = FileArenaSnapshot {
            nodes: Arc::new(crate::arena::NodeStorage::Owned(nodes)),
            string_pool: Arc::new(pool),
            dir_counts: Arc::new(dir_counts),
        };

        // 1. Verify TableProviderWrapper for_selected_rows and for_all_rows
        let provider = crate::gui::explorer::TableProviderWrapper::new(&snapshot);
        let mut state = egui_table_kit::state::TableState::new("test_table", 0);
        state.selected_rows.insert(0);

        let mut row_names = Vec::new();
        provider.for_selected_rows(&state, &mut |row| {
            row_names.push(row[0].0.to_string());
            Ok(())
        })?;
        assert_eq!(row_names, vec!["C:\\TestFolder"]);

        let mut all_row_names = Vec::new();
        provider.for_all_rows(&mut |row| {
            all_row_names.push(row[0].0.to_string());
            Ok(())
        })?;
        assert_eq!(all_row_names, vec!["C:\\TestFolder"]);

        // 2. Verify row_matches
        let mut filter = egui_table_kit::filter::Filter::default();
        filter.search.set_text("Folder");
        filter.search.open();
        assert!(provider.row_matches(&state, 0, &[(0, filter.clone())], None));

        // Searching for the UNC prefix should not match if it's stripped
        let mut filter_unc = egui_table_kit::filter::Filter::default();
        filter_unc.search.set_text(r"\\?\");
        filter_unc.search.open();
        assert!(!provider.row_matches(&state, 0, &[(0, filter_unc)], None));

        Ok(())
    }
}