vm-curator 0.4.3

A TUI application to manage QEMU VM library
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
use anyhow::Result;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::mpsc::{self, Receiver, Sender};
use std::time::Instant;

use crate::commands::qemu_system::NetworkCapabilities;
use crate::config::Config;
use crate::hardware::{MultiGpuPassthroughStatus, PciDevice, SingleGpuConfig, UsbDevice};
use crate::metadata::{AsciiArtStore, HierarchyConfig, MetadataStore, OsInfo, QemuProfileStore, SettingsHelpStore, SharedFoldersHelpStore};
use crate::ui::widgets::build_visual_order;
use crate::vm::{discover_vms, BootMode, DiscoveredVm, LaunchOptions, QemuProcess, SharedFolder, Snapshot};
use crate::vm::qemu_config::{PortForward, PortProtocol};

/// Application screens/views
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Screen {
    /// Main VM list
    MainMenu,
    /// VM management options
    Management,
    /// Configuration view (planned feature)
    #[allow(dead_code)]
    Configuration,
    /// Raw launch script view
    RawScript,
    /// Detailed info (history, blurbs) - planned feature
    #[allow(dead_code)]
    DetailedInfo,
    /// Snapshot management
    Snapshots,
    /// Boot options
    BootOptions,
    /// Display options
    DisplayOptions,
    /// USB device selection
    UsbDevices,
    /// PCI device selection for passthrough
    PciPassthrough,
    /// Shared folder management (virtio-9p)
    SharedFolders,
    /// Single GPU passthrough setup
    SingleGpuSetup,
    /// Single GPU passthrough instructions dialog
    SingleGpuInstructions,
    /// Multi-GPU passthrough setup (Looking Glass)
    MultiGpuSetup,
    /// Confirmation dialog
    Confirm(ConfirmAction),
    /// Help screen
    Help,
    /// Search/filter
    Search,
    /// File browser (for ISO selection)
    FileBrowser,
    /// Text input dialog
    TextInput(TextInputContext),
    /// Error dialog (scrollable)
    ErrorDialog,
    /// VM Creation wizard (step tracked in wizard_state)
    CreateWizard,
    /// Custom OS metadata entry (secondary form during wizard)
    CreateWizardCustomOs,
    /// ISO download progress screen (planned feature)
    #[allow(dead_code)]
    CreateWizardDownload,
    /// Network settings (backend + port forwarding)
    NetworkSettings,
    /// Application settings
    Settings,
    /// VM Import wizard
    ImportWizard,
    /// Notes editor
    EditNotes,
}

/// Context for text input dialogs
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TextInputContext {
    SnapshotName,
    RenameVm,
}

/// Actions that need confirmation
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfirmAction {
    LaunchVm,
    ResetVm,
    DeleteVm,
    DeleteSnapshot(String),
    RestoreSnapshot(String),
    DiscardScriptChanges,
    DiscardNotesChanges,
    StopVm,
    ForceStopVm,
}

/// Input mode for text entry
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputMode {
    Normal,
    Editing,
}

/// File browser mode (determines file filter and behavior)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FileBrowserMode {
    #[default]
    Iso,
    RecoveryImage,
    Disk,
    Directory,
    ImportConfig,
    Bios,
    Floppy,
}

/// Action to take with an existing disk when using it for a new VM
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DiskAction {
    #[default]
    Copy,
    Move,
}

/// Steps in the VM creation wizard
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum WizardStep {
    /// Step 1: Select name and OS type
    #[default]
    SelectOs,
    /// Step 2: Select ISO file
    SelectIso,
    /// Step 3: Configure disk settings
    ConfigureDisk,
    /// Step 4: Configure QEMU settings
    ConfigureQemu,
    /// Step 5: Review and confirm
    Confirm,
}

impl WizardStep {
    /// Get the step number (1-5)
    pub fn number(&self) -> u8 {
        match self {
            WizardStep::SelectOs => 1,
            WizardStep::SelectIso => 2,
            WizardStep::ConfigureDisk => 3,
            WizardStep::ConfigureQemu => 4,
            WizardStep::Confirm => 5,
        }
    }

    /// Get the step title
    pub fn title(&self) -> &'static str {
        match self {
            WizardStep::SelectOs => "Select Operating System",
            WizardStep::SelectIso => "Select Install Media",
            WizardStep::ConfigureDisk => "Configure Disk",
            WizardStep::ConfigureQemu => "Configure QEMU",
            WizardStep::Confirm => "Review & Create",
        }
    }

    /// Move to the next step
    pub fn next(&self) -> Option<WizardStep> {
        match self {
            WizardStep::SelectOs => Some(WizardStep::SelectIso),
            WizardStep::SelectIso => Some(WizardStep::ConfigureDisk),
            WizardStep::ConfigureDisk => Some(WizardStep::ConfigureQemu),
            WizardStep::ConfigureQemu => Some(WizardStep::Confirm),
            WizardStep::Confirm => None,
        }
    }

    /// Move to the previous step
    pub fn prev(&self) -> Option<WizardStep> {
        match self {
            WizardStep::SelectOs => None,
            WizardStep::SelectIso => Some(WizardStep::SelectOs),
            WizardStep::ConfigureDisk => Some(WizardStep::SelectIso),
            WizardStep::ConfigureQemu => Some(WizardStep::ConfigureDisk),
            WizardStep::Confirm => Some(WizardStep::ConfigureQemu),
        }
    }
}

/// QEMU configuration settings for the wizard
#[derive(Debug, Clone)]
pub struct WizardQemuConfig {
    /// QEMU emulator command
    pub emulator: String,
    /// RAM in megabytes
    pub memory_mb: u32,
    /// CPU cores
    pub cpu_cores: u32,
    /// CPU model (host, qemu64, pentium, etc.)
    pub cpu_model: Option<String>,
    /// Machine type (q35, pc, etc.)
    pub machine: Option<String>,
    /// Graphics adapter
    pub vga: String,
    /// Audio devices
    pub audio: Vec<String>,
    /// Network adapter model
    pub network_model: String,
    /// Disk interface
    pub disk_interface: String,
    /// Enable KVM acceleration
    pub enable_kvm: bool,
    /// Enable 3D/GL acceleration (requires virtio-vga)
    pub gl_acceleration: bool,
    /// UEFI boot mode
    pub uefi: bool,
    /// TPM emulation
    pub tpm: bool,
    /// RTC uses local time (for Windows)
    pub rtc_localtime: bool,
    /// USB tablet for mouse
    pub usb_tablet: bool,
    /// Display output
    pub display: String,
    /// Network backend
    pub network_backend: String,
    /// Port forwarding rules (user & passt backends)
    pub port_forwards: Vec<PortForward>,
    /// Bridge name when backend is "bridge"
    pub bridge_name: Option<String>,
    /// Additional QEMU arguments
    pub extra_args: Vec<String>,
    /// BIOS/ROM file path (for classic Mac and other systems needing custom firmware)
    pub bios_path: Option<PathBuf>,
}

impl Default for WizardQemuConfig {
    fn default() -> Self {
        Self {
            emulator: "qemu-system-x86_64".to_string(),
            memory_mb: 2048,
            cpu_cores: 2,
            cpu_model: Some("host".to_string()),
            machine: Some("q35".to_string()),
            vga: "std".to_string(),
            audio: vec!["intel-hda".to_string(), "hda-duplex".to_string()],
            network_model: "e1000".to_string(),
            disk_interface: "ide".to_string(),
            enable_kvm: true,
            gl_acceleration: false,
            uefi: false,
            tpm: false,
            rtc_localtime: false,
            usb_tablet: true,
            display: "gtk".to_string(),
            network_backend: "user".to_string(),
            port_forwards: Vec::new(),
            bridge_name: None,
            extra_args: Vec::new(),
            bios_path: None,
        }
    }
}

impl WizardQemuConfig {
    /// Create from a QEMU profile
    pub fn from_profile(profile: &crate::metadata::QemuProfile) -> Self {
        // Check if profile has GL acceleration hints in extra_args
        let gl_acceleration = profile.extra_args.iter().any(|arg|
            arg.contains("virtio-vga-gl") || arg.contains("gl=on")
        );

        Self {
            emulator: profile.emulator.clone(),
            memory_mb: profile.memory_mb,
            cpu_cores: profile.cpu_cores,
            cpu_model: profile.cpu_model.clone(),
            machine: profile.machine.clone(),
            vga: profile.vga.clone(),
            audio: profile.audio.clone(),
            network_model: profile.network_model.clone(),
            disk_interface: profile.disk_interface.clone(),
            enable_kvm: profile.enable_kvm,
            gl_acceleration,
            uefi: profile.uefi,
            tpm: profile.tpm,
            rtc_localtime: profile.rtc_localtime,
            usb_tablet: profile.usb_tablet,
            display: profile.display.clone(),
            network_backend: profile.network_backend.clone(),
            port_forwards: Vec::new(),
            bridge_name: None,
            extra_args: profile.extra_args.clone(),
            bios_path: None,
        }
    }
}

/// Custom OS entry for when user selects "Other"
#[derive(Debug, Clone, Default)]
pub struct CustomOsEntry {
    /// OS identifier (e.g., "my-custom-os")
    pub id: String,
    /// Display name
    pub name: String,
    /// Publisher/developer
    pub publisher: String,
    /// Release date (YYYY-MM-DD) - planned for future save feature
    #[allow(dead_code)]
    pub release_date: Option<String>,
    /// Architecture (x86_64, i386, etc.)
    pub architecture: String,
    /// Short description (one line) - planned for future save feature
    #[allow(dead_code)]
    pub short_blurb: String,
    /// Long description (multi-paragraph) - planned for future save feature
    #[allow(dead_code)]
    pub long_blurb: String,
    /// Fun facts - planned for future save feature
    #[allow(dead_code)]
    pub fun_facts: Vec<String>,
    /// Base profile to use for QEMU defaults
    pub base_profile: String,
    /// Save to user metadata for future use - planned feature
    #[allow(dead_code)]
    pub save_to_user: bool,
}

/// State for the VM creation wizard
#[derive(Debug, Clone)]
pub struct CreateWizardState {
    /// Current wizard step
    pub step: WizardStep,
    /// VM display name (user-entered)
    pub vm_name: String,
    /// Folder name (auto-generated from vm_name)
    pub folder_name: String,
    /// Selected OS profile ID (from qemu_profiles)
    pub selected_os: Option<String>,
    /// Custom OS entry (if "Other" selected)
    pub custom_os: Option<CustomOsEntry>,
    /// ISO or recovery image file path
    pub iso_path: Option<PathBuf>,
    /// Whether the selected media is a recovery image (DMG) rather than an ISO
    pub is_recovery_image: bool,
    /// Whether an ISO download is in progress
    pub iso_downloading: bool,
    /// ISO download progress (0.0 - 1.0)
    pub iso_download_progress: f32,
    /// Disk size in gigabytes (for new disk creation)
    pub disk_size_gb: u32,
    /// Whether to use an existing disk instead of creating a new one
    pub use_existing_disk: bool,
    /// Path to an existing disk to use
    pub existing_disk_path: Option<PathBuf>,
    /// Action to take with existing disk (copy or move)
    pub existing_disk_action: DiskAction,
    /// BIOS/ROM file path (for classic Mac and other systems needing custom firmware)
    pub bios_rom_path: Option<PathBuf>,
    /// Floppy disk image path (for OSes that need a boot floppy, e.g., OS/2)
    pub floppy_path: Option<PathBuf>,
    /// QEMU configuration
    pub qemu_config: WizardQemuConfig,
    /// Auto-launch VM after creation
    pub auto_launch: bool,
    /// Currently focused field index (for navigation)
    pub field_focus: usize,
    /// OS list scroll position - reserved for virtual scrolling
    #[allow(dead_code)]
    pub os_list_scroll: usize,
    /// OS filter/search string
    pub os_filter: String,
    /// Selected OS category index - reserved for future use
    #[allow(dead_code)]
    pub selected_category: usize,
    /// Expanded categories (by name)
    pub expanded_categories: Vec<String>,
    /// Selected item within OS list (category header or OS)
    pub os_list_selected: usize,
    /// Error message to display
    pub error_message: Option<String>,
    /// Currently editing field (for text input focus)
    pub editing_field: Option<WizardField>,
    /// Text edit buffer for numeric fields (memory, cpu, disk)
    pub wizard_edit_buffer: String,
}

/// Fields that can be edited in the wizard
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(dead_code)] // Some variants reserved for future inline editing
pub enum WizardField {
    VmName,
    OsFilter,
    DiskSize,
    MemoryMb,
    CpuCores,
    CustomOsId,
    CustomOsName,
    CustomOsPublisher,
    CustomOsReleaseDate,
    CustomOsShortBlurb,
}

impl Default for CreateWizardState {
    fn default() -> Self {
        Self {
            step: WizardStep::SelectOs,
            vm_name: String::new(),
            folder_name: String::new(),
            selected_os: None,
            custom_os: None,
            iso_path: None,
            is_recovery_image: false,
            iso_downloading: false,
            iso_download_progress: 0.0,
            disk_size_gb: 32,
            use_existing_disk: false,
            existing_disk_path: None,
            existing_disk_action: DiskAction::Copy,
            bios_rom_path: None,
            floppy_path: None,
            qemu_config: WizardQemuConfig::default(),
            auto_launch: true,
            field_focus: 0,
            os_list_scroll: 0,
            os_filter: String::new(),
            selected_category: 0,
            expanded_categories: vec![
                "windows".to_string(),
                "linux".to_string(),
            ],
            os_list_selected: 0,
            error_message: None,
            editing_field: None,
            wizard_edit_buffer: String::new(),
        }
    }
}

impl CreateWizardState {
    /// Generate folder name from VM display name
    pub fn generate_folder_name(display_name: &str) -> String {
        display_name
            .to_lowercase()
            .chars()
            .map(|c| {
                if c.is_alphanumeric() {
                    c
                } else {
                    '-'
                }
            })
            .collect::<String>()
            .split('-')
            .filter(|s| !s.is_empty())
            .collect::<Vec<_>>()
            .join("-")
    }

    /// Update folder name based on selected OS profile ID
    /// Uses the profile ID as base (e.g., "linux-endeavouros") for proper hierarchy matching
    /// If a folder with that name already exists, appends -2, -3, etc.
    pub fn update_folder_name(&mut self, library_path: &std::path::Path) {
        let base_name = if let Some(ref os_id) = self.selected_os {
            // Use the profile ID as the folder name for proper categorization
            os_id.clone()
        } else {
            // Fallback to generating from display name for custom OSes
            Self::generate_folder_name(&self.vm_name)
        };

        // Check if folder already exists, and if so, find an available suffix
        self.folder_name = Self::find_available_folder_name(library_path, &base_name);
    }

    /// Find an available folder name by appending numeric suffixes if needed
    /// e.g., "windows-10" -> "windows-10-2" -> "windows-10-3"
    /// Returns the base name with a numeric suffix if needed, or with "-error" suffix
    /// if no available name was found within the limit (indicating a problem).
    pub fn find_available_folder_name(library_path: &std::path::Path, base_name: &str) -> String {
        let first_candidate = library_path.join(base_name);
        if !first_candidate.exists() {
            return base_name.to_string();
        }

        // Folder exists, try with numeric suffixes
        for suffix in 2..=1000 {
            let candidate_name = format!("{}-{}", base_name, suffix);
            let candidate_path = library_path.join(&candidate_name);
            if !candidate_path.exists() {
                return candidate_name;
            }
        }

        // Exhausted all suffixes - this indicates a problem (1000+ VMs with same base name)
        // Return a clearly invalid name that will fail at creation time with a clear error
        format!("{}-error-too-many-vms", base_name)
    }

    /// Apply profile settings to the wizard state
    pub fn apply_profile(&mut self, profile: &crate::metadata::QemuProfile) {
        self.disk_size_gb = profile.disk_size_gb;
        self.qemu_config = WizardQemuConfig::from_profile(profile);
    }

    /// Check if the wizard can proceed to the next step
    pub fn can_proceed(&self) -> Result<(), String> {
        match self.step {
            WizardStep::SelectOs => {
                if self.vm_name.trim().is_empty() {
                    return Err("Please enter a VM name".to_string());
                }
                if self.selected_os.is_none() && self.custom_os.is_none() {
                    return Err("Please select an operating system".to_string());
                }
                Ok(())
            }
            WizardStep::SelectIso => {
                // ISO is optional - user can configure later
                Ok(())
            }
            WizardStep::ConfigureDisk => {
                if self.use_existing_disk {
                    // Validate existing disk path
                    match &self.existing_disk_path {
                        None => return Err("Please select an existing disk".to_string()),
                        Some(path) => {
                            if !path.exists() {
                                return Err(format!("Disk file not found: {}", path.display()));
                            }
                        }
                    }
                } else {
                    // Validate new disk size
                    if self.disk_size_gb == 0 {
                        return Err("Disk size must be greater than 0".to_string());
                    }
                    if self.disk_size_gb > 10000 {
                        return Err("Disk size cannot exceed 10TB".to_string());
                    }
                }
                Ok(())
            }
            WizardStep::ConfigureQemu => {
                if self.qemu_config.memory_mb == 0 {
                    return Err("Memory must be greater than 0".to_string());
                }
                if self.qemu_config.cpu_cores == 0 {
                    return Err("CPU cores must be greater than 0".to_string());
                }
                Ok(())
            }
            WizardStep::Confirm => Ok(()),
        }
    }

    /// Toggle a category's expanded state
    pub fn toggle_category(&mut self, category: &str) {
        if let Some(pos) = self.expanded_categories.iter().position(|c| c == category) {
            self.expanded_categories.remove(pos);
        } else {
            self.expanded_categories.push(category.to_string());
        }
    }

    /// Check if a category is expanded
    pub fn is_category_expanded(&self, category: &str) -> bool {
        self.expanded_categories.iter().any(|c| c == category)
    }
}

/// State for network settings editing screen
#[derive(Debug, Clone)]
pub struct NetworkSettingsState {
    pub model: String,
    pub backend: String,
    pub bridge_name: Option<String>,
    pub port_forwards: Vec<PortForward>,
    pub selected_field: usize,
    pub editing_port_forwards: bool,
    pub pf_selected: usize,
    pub adding_pf: Option<AddingPortForward>,
}

/// State when adding a new port forward rule
#[derive(Debug, Clone)]
pub struct AddingPortForward {
    pub step: AddPfStep,
    pub protocol: PortProtocol,
    pub host_port_input: String,
    pub guest_port_input: String,
}

/// Steps when adding a port forward
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AddPfStep {
    Protocol,
    HostPort,
    GuestPort,
}

// =========================================================================
// VM Import Wizard Types
// =========================================================================

/// Source type for VM import
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImportSource {
    Libvirt,
    Quickemu,
}

/// Disk handling action during import
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ImportDiskAction {
    #[default]
    Symlink,
    Copy,
    Move,
}

/// Steps in the import wizard
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ImportStep {
    #[default]
    SelectSource,
    SelectVm,
    CompatibilityWarnings,
    ConfigureDisk,
    ReviewAndImport,
}

/// A VM discovered from an external source that can be imported
#[derive(Debug, Clone)]
pub struct ImportableVm {
    pub name: String,
    pub config_path: PathBuf,
    pub source: ImportSource,
    pub qemu_config: WizardQemuConfig,
    pub disk_paths: Vec<PathBuf>,
    pub detected_os_profile: Option<String>,
    pub import_notes: Vec<String>,
    pub disks_readable: Vec<bool>,
}

/// State for the VM import wizard
#[derive(Debug, Clone)]
pub struct ImportWizardState {
    pub step: ImportStep,
    pub source: Option<ImportSource>,
    pub discovered_vms: Vec<ImportableVm>,
    pub selected_vm_index: usize,
    pub selected_vm: Option<ImportableVm>,
    pub vm_name: String,
    pub folder_name: String,
    pub disk_action: ImportDiskAction,
    pub field_focus: usize,
    pub error_message: Option<String>,
    pub editing_name: bool,
    pub warnings_acknowledged: bool,
}

impl Default for ImportWizardState {
    fn default() -> Self {
        Self {
            step: ImportStep::SelectSource,
            source: None,
            discovered_vms: Vec::new(),
            selected_vm_index: 0,
            selected_vm: None,
            vm_name: String::new(),
            folder_name: String::new(),
            disk_action: ImportDiskAction::Symlink,
            field_focus: 0,
            error_message: None,
            editing_name: false,
            warnings_acknowledged: false,
        }
    }
}

/// Application state
pub struct App {
    /// Current screen
    pub screen: Screen,
    /// Screen history for back navigation
    pub screen_stack: Vec<Screen>,
    /// Application configuration
    pub config: Config,
    /// Discovered VMs
    pub vms: Vec<DiscoveredVm>,
    /// Currently selected VM index
    pub selected_vm: usize,
    /// OS metadata store
    pub metadata: MetadataStore,
    /// ASCII art store
    pub ascii_art: AsciiArtStore,
    /// Hierarchy configuration for VM categorization
    pub hierarchy: HierarchyConfig,
    /// Snapshots for current VM (cached)
    pub snapshots: Vec<Snapshot>,
    /// Selected snapshot index
    pub selected_snapshot: usize,
    /// USB devices (cached)
    pub usb_devices: Vec<UsbDevice>,
    /// Selected USB devices for passthrough
    pub selected_usb_devices: Vec<usize>,
    /// PCI devices (cached)
    pub pci_devices: Vec<PciDevice>,
    /// Selected PCI devices for passthrough
    pub selected_pci_devices: Vec<usize>,
    /// Shared folders for the current VM
    pub shared_folders: Vec<SharedFolder>,
    /// Selected shared folder index
    pub shared_folder_selected: usize,
    /// Multi-GPU passthrough status (prerequisites)
    pub multi_gpu_status: Option<MultiGpuPassthroughStatus>,
    /// Selected management menu item
    pub selected_menu_item: usize,
    /// Current boot mode
    pub boot_mode: BootMode,
    /// Search query
    pub search_query: String,
    /// Input mode
    pub input_mode: InputMode,
    /// Filtered VM indices (for search)
    pub filtered_indices: Vec<usize>,
    /// Visual order of VMs (maps visual position to filtered_idx for hierarchy navigation)
    pub visual_order: Vec<usize>,
    /// Status message
    pub status_message: Option<String>,
    /// When status message was set (for auto-clearing)
    pub status_time: Option<Instant>,
    /// Whether the app should quit
    pub should_quit: bool,
    /// File browser current directory
    pub file_browser_dir: PathBuf,
    /// File browser entries (directories first, then files)
    pub file_browser_entries: Vec<FileBrowserEntry>,
    /// File browser selected index
    pub file_browser_selected: usize,
    /// File browser mode (determines file filter and behavior)
    pub file_browser_mode: FileBrowserMode,
    /// Text input buffer (for dialogs)
    pub text_input_buffer: String,
    /// Channel for background operation results
    pub background_rx: Receiver<BackgroundResult>,
    /// Sender for background operations (clone this for threads)
    pub background_tx: Sender<BackgroundResult>,
    /// Whether a background operation is in progress
    pub loading: bool,
    /// Error dialog content (for detailed errors)
    pub error_detail: Option<String>,
    /// Error dialog scroll position
    pub error_scroll: u16,
    /// Right panel scroll position (for info panel)
    pub info_scroll: u16,
    /// Raw script view scroll position
    pub raw_script_scroll: u16,
    /// Script editor buffer (lines of text)
    pub script_editor_lines: Vec<String>,
    /// Script editor cursor position (line, column)
    pub script_editor_cursor: (usize, usize),
    /// Whether the script has been modified
    pub script_editor_modified: bool,
    /// Horizontal scroll offset for the editor
    pub script_editor_h_scroll: usize,
    /// QEMU profiles for VM creation
    pub qemu_profiles: QemuProfileStore,
    /// Settings help text store
    pub settings_help: SettingsHelpStore,
    /// Shared folders help text store
    pub shared_folders_help: SharedFoldersHelpStore,
    /// VM creation wizard state
    pub wizard_state: Option<CreateWizardState>,
    /// VM import wizard state
    pub import_state: Option<ImportWizardState>,
    /// Settings screen selected item
    pub settings_selected: usize,
    /// Settings screen editing mode
    pub settings_editing: bool,
    /// Settings screen edit buffer (for text fields)
    pub settings_edit_buffer: String,
    /// GPU passthrough validation result for settings screen
    pub settings_gpu_validation: Option<crate::ui::screens::settings::GpuValidationResult>,
    /// Cached display capabilities per emulator (populated at startup)
    pub display_capabilities: HashMap<String, Vec<String>>,

    // === VM Process Monitoring ===
    /// Receives QEMU process info from background detection thread
    pub vm_status_rx: Receiver<Vec<QemuProcess>>,
    /// Map of vm_id -> PID for currently running VMs
    pub running_vms: HashMap<String, u32>,
    /// Map of vm_id -> when SIGTERM was sent (for force-stop timeout)
    pub stopping_vms: HashMap<String, Instant>,

    // === Single GPU Passthrough ===
    /// Single GPU passthrough configuration
    pub single_gpu_config: Option<SingleGpuConfig>,
    /// Selected field in single GPU setup screen
    pub single_gpu_selected_field: usize,
    /// Whether to show the instructions dialog
    pub single_gpu_show_instructions: bool,

    // === Networking ===
    /// Detected network capabilities (passt, bridge helper, etc.)
    pub network_caps: NetworkCapabilities,
    /// Network settings editing state
    pub network_settings_state: Option<NetworkSettingsState>,
    /// Whether the wizard port forward editor is active
    pub wizard_editing_port_forwards: bool,
    /// Wizard port forward editor selection index
    pub wizard_pf_selected: usize,
    /// Wizard port forward adding state
    pub wizard_adding_pf: Option<AddingPortForward>,
}

/// Entry in file browser
#[derive(Debug, Clone)]
pub struct FileBrowserEntry {
    pub name: String,
    pub path: PathBuf,
    pub is_dir: bool,
}

/// Background operation result
pub enum BackgroundResult {
    SnapshotCreated { name: String, success: bool, error: Option<String> },
    SnapshotRestored { name: String, success: bool, error: Option<String> },
    SnapshotDeleted { name: String, success: bool, error: Option<String> },
    /// Reserved for async snapshot loading
    #[allow(dead_code)]
    SnapshotsLoaded { snapshots: Vec<Snapshot>, error: Option<String> },
}

impl App {
    /// Create a new application instance with progress callback
    pub fn new_with_progress<F>(config: Config, progress: F) -> Result<Self>
    where
        F: Fn(usize, usize, &str),
    {
        const TOTAL_STEPS: usize = 6;

        // Step 1: Discover VMs
        progress(1, TOTAL_STEPS, "Discovering VMs...");
        let vms = discover_vms(&config.vm_library_path)?;
        progress(1, TOTAL_STEPS, &format!("Found {} VMs", vms.len()));

        // Step 2: Load metadata
        progress(2, TOTAL_STEPS, "Loading OS metadata...");
        let mut metadata = MetadataStore::load_embedded();
        if let Ok(user_metadata) = MetadataStore::load_from_dir(&config.metadata_path) {
            metadata.merge(user_metadata);
        }

        // Step 3: Load ASCII art
        progress(3, TOTAL_STEPS, "Loading ASCII art...");
        let mut ascii_art = AsciiArtStore::load_embedded();
        let user_art = AsciiArtStore::load_from_dir(&config.ascii_art_path);
        ascii_art.merge(user_art);

        // Step 4: Load hierarchy config
        progress(4, TOTAL_STEPS, "Loading hierarchy...");
        let hierarchy = HierarchyConfig::load_embedded();

        // Step 5: Load QEMU profiles
        progress(5, TOTAL_STEPS, "Loading QEMU profiles...");
        let mut qemu_profiles = QemuProfileStore::load_embedded();
        let config_dir = Config::config_file_path()
            .parent()
            .map(|p| p.to_path_buf())
            .unwrap_or_else(|| PathBuf::from("."));
        let user_profiles_path = config_dir.join("qemu_profiles.toml");
        qemu_profiles.load_user_overrides(&user_profiles_path);

        // Load settings help text
        let mut settings_help = SettingsHelpStore::load_embedded();
        let user_help_path = config_dir.join("settings_help.toml");
        settings_help.load_user_overrides(&user_help_path);

        // Load shared folders help text
        let mut shared_folders_help = SharedFoldersHelpStore::load_embedded();
        shared_folders_help.load_user_overrides(&config_dir.join("shared_folders_help.toml"));

        // Step 6: Build visual order and detect display capabilities
        progress(6, TOTAL_STEPS, "Building VM list...");
        let filtered_indices: Vec<usize> = (0..vms.len()).collect();
        let visual_order = build_visual_order(&vms, &filtered_indices, &hierarchy, &metadata);
        let (background_tx, background_rx) = mpsc::channel();

        // Detect network capabilities
        let network_caps = crate::commands::qemu_system::detect_network_capabilities();

        // Detect display capabilities for each available emulator
        let mut display_capabilities = HashMap::new();
        for emulator in crate::commands::qemu_system::list_available_emulators() {
            let displays = crate::commands::qemu_system::get_supported_displays(&emulator);
            if !displays.is_empty() {
                display_capabilities.insert(emulator, displays);
            }
        }

        // Spawn background VM status detection thread
        let (vm_status_tx, vm_status_rx) = mpsc::channel();
        std::thread::spawn(move || {
            loop {
                std::thread::sleep(std::time::Duration::from_secs(3));
                let processes = crate::vm::detect_qemu_processes();
                if vm_status_tx.send(processes).is_err() {
                    break; // Receiver dropped (app exited)
                }
            }
        });

        Ok(Self {
            screen: Screen::MainMenu,
            screen_stack: Vec::new(),
            config,
            vms,
            selected_vm: 0,
            metadata,
            ascii_art,
            hierarchy,
            snapshots: Vec::new(),
            selected_snapshot: 0,
            usb_devices: Vec::new(),
            selected_usb_devices: Vec::new(),
            pci_devices: Vec::new(),
            selected_pci_devices: Vec::new(),
            shared_folders: Vec::new(),
            shared_folder_selected: 0,
            multi_gpu_status: None,
            selected_menu_item: 0,
            boot_mode: BootMode::Normal,
            search_query: String::new(),
            input_mode: InputMode::Normal,
            filtered_indices,
            visual_order,
            status_message: None,
            status_time: None,
            should_quit: false,
            file_browser_dir: dirs::home_dir().unwrap_or_else(|| PathBuf::from("/")),
            file_browser_entries: Vec::new(),
            file_browser_selected: 0,
            file_browser_mode: FileBrowserMode::Iso,
            text_input_buffer: String::new(),
            background_rx,
            background_tx,
            loading: false,
            error_detail: None,
            error_scroll: 0,
            info_scroll: 0,
            raw_script_scroll: 0,
            script_editor_lines: Vec::new(),
            script_editor_cursor: (0, 0),
            script_editor_modified: false,
            script_editor_h_scroll: 0,
            qemu_profiles,
            settings_help,
            shared_folders_help,
            wizard_state: None,
            import_state: None,
            settings_selected: 0,
            settings_editing: false,
            settings_edit_buffer: String::new(),
            settings_gpu_validation: None,
            display_capabilities,

            // VM Process Monitoring
            vm_status_rx,
            running_vms: HashMap::new(),
            stopping_vms: HashMap::new(),

            // Single GPU Passthrough
            single_gpu_config: None,
            single_gpu_selected_field: 0,
            single_gpu_show_instructions: false,

            // Networking
            network_caps,
            network_settings_state: None,
            wizard_editing_port_forwards: false,
            wizard_pf_selected: 0,
            wizard_adding_pf: None,
        })
    }

    /// Get display options for an emulator, filtered and ordered.
    ///
    /// Returns detected display backends for the emulator, preferring `spice-app`
    /// over `spice`. Falls back to a default list if detection returned nothing.
    pub fn get_display_options_for_emulator(&self, emulator: &str) -> Vec<String> {
        // Preferred order of display backends
        let preferred_order = ["gtk", "sdl", "spice-app", "vnc", "none"];

        if let Some(detected) = self.display_capabilities.get(emulator) {
            let mut result = Vec::new();
            // Add backends in preferred order if they were detected
            for &pref in &preferred_order {
                if detected.iter().any(|d| d == pref) {
                    result.push(pref.to_string());
                }
            }
            // Add any remaining detected backends not in preferred order
            for d in detected {
                if !result.iter().any(|r| r == d) && d != "spice" {
                    result.push(d.clone());
                }
            }
            if !result.is_empty() {
                return result;
            }
        }

        // Fallback: default list
        preferred_order.iter().map(|s| s.to_string()).collect()
    }

    /// Get available network backend options based on detected capabilities
    pub fn get_network_backend_options(&self) -> Vec<(&str, &str)> {
        let mut options = vec![
            ("user", "User/SLIRP (NAT) - Default, works everywhere"),
        ];
        if self.network_caps.passt_available {
            options.push(("passt", "passt - Fast NAT, ping works"));
        }
        if self.network_caps.bridge_helper_path.is_some() {
            if !self.network_caps.system_bridges.is_empty() && self.network_caps.bridge_helper_configured {
                options.push(("bridge", "Bridge - Full network, own IP"));
            } else {
                options.push(("bridge", "Bridge - Requires one-time setup"));
            }
        }
        options.push(("none", "None - No networking"));
        options
    }

    /// Get the currently selected VM
    pub fn selected_vm(&self) -> Option<&DiscoveredVm> {
        if self.visual_order.is_empty() {
            return None;
        }
        // selected_vm is an index into visual_order
        // visual_order[selected_vm] gives the filtered_idx
        // filtered_indices[filtered_idx] gives the actual vm index
        let filtered_idx = self.visual_order.get(self.selected_vm)?;
        let actual_idx = self.filtered_indices.get(*filtered_idx)?;
        self.vms.get(*actual_idx)
    }

    /// Get OS info for the selected VM
    pub fn selected_vm_info(&self) -> Option<OsInfo> {
        let vm = self.selected_vm()?;
        self.metadata
            .get(&vm.id)
            .cloned()
            .or_else(|| Some(crate::metadata::default_os_info(&vm.id)))
    }

    /// Get ASCII art for the selected VM
    pub fn selected_vm_ascii(&self) -> &str {
        self.selected_vm()
            .map(|vm| self.ascii_art.get_or_fallback(&vm.id))
            .unwrap_or("")
    }

    /// Navigate to a new screen
    pub fn push_screen(&mut self, screen: Screen) {
        self.screen_stack.push(self.screen.clone());
        self.screen = screen;
        self.selected_menu_item = 0;
    }

    /// Go back to the previous screen
    pub fn pop_screen(&mut self) {
        if let Some(prev) = self.screen_stack.pop() {
            self.screen = prev;
        }
    }

    /// Move selection up in VM list (follows visual/hierarchy order)
    pub fn select_prev(&mut self) {
        if !self.visual_order.is_empty() && self.selected_vm > 0 {
            self.selected_vm -= 1;
            self.info_scroll = 0; // Reset scroll when VM changes
        }
    }

    /// Move selection down in VM list (follows visual/hierarchy order)
    pub fn select_next(&mut self) {
        if !self.visual_order.is_empty() && self.selected_vm < self.visual_order.len() - 1 {
            self.selected_vm += 1;
            self.info_scroll = 0; // Reset scroll when VM changes
        }
    }

    /// Move selection up in menu
    pub fn menu_prev(&mut self) {
        if self.selected_menu_item > 0 {
            self.selected_menu_item -= 1;
        }
    }

    /// Move selection down in menu
    pub fn menu_next(&mut self, max_items: usize) {
        if self.selected_menu_item < max_items.saturating_sub(1) {
            self.selected_menu_item += 1;
        }
    }

    /// Update search filter
    pub fn update_filter(&mut self) {
        if self.search_query.is_empty() {
            self.filtered_indices = (0..self.vms.len()).collect();
        } else {
            let query = self.search_query.to_lowercase();
            self.filtered_indices = self
                .vms
                .iter()
                .enumerate()
                .filter(|(_, vm)| {
                    vm.display_name().to_lowercase().contains(&query)
                        || vm.id.to_lowercase().contains(&query)
                })
                .map(|(i, _)| i)
                .collect();
        }

        // Rebuild visual order for hierarchy navigation
        self.visual_order = build_visual_order(&self.vms, &self.filtered_indices, &self.hierarchy, &self.metadata);

        // Reset selection if out of bounds
        if self.selected_vm >= self.visual_order.len() {
            self.selected_vm = self.visual_order.len().saturating_sub(1);
        }
    }

    /// Refresh VM list
    pub fn refresh_vms(&mut self) -> Result<()> {
        self.vms = discover_vms(&self.config.vm_library_path)?;
        self.update_filter();
        Ok(())
    }

    /// Load snapshots for the current VM
    pub fn load_snapshots(&mut self) -> Result<()> {
        self.snapshots.clear();
        self.selected_snapshot = 0;

        if let Some(vm) = self.selected_vm() {
            if let Some(disk) = vm.config.primary_disk() {
                if disk.format.supports_snapshots() {
                    self.snapshots = crate::vm::list_snapshots(&disk.path)?;
                }
            }
        }

        Ok(())
    }

    /// Load USB devices
    pub fn load_usb_devices(&mut self) -> Result<()> {
        self.usb_devices = crate::hardware::enumerate_usb_devices()?;
        self.selected_usb_devices.clear();
        Ok(())
    }

    /// Toggle USB device selection
    pub fn toggle_usb_device(&mut self, index: usize) {
        if let Some(pos) = self.selected_usb_devices.iter().position(|&i| i == index) {
            self.selected_usb_devices.remove(pos);
        } else {
            self.selected_usb_devices.push(index);
        }
    }

    /// Load PCI devices
    pub fn load_pci_devices(&mut self) -> Result<()> {
        self.pci_devices = crate::hardware::enumerate_pci_devices()?;
        self.selected_pci_devices.clear();
        self.multi_gpu_status = Some(crate::hardware::check_multi_gpu_passthrough_status());
        Ok(())
    }

    /// Load shared folders for the current VM
    pub fn load_shared_folders(&mut self) {
        self.shared_folders.clear();
        self.shared_folder_selected = 0;

        if let Some(vm) = self.selected_vm() {
            self.shared_folders = crate::vm::load_shared_folders(vm);
        }
    }

    /// Add a shared folder, generating a unique mount tag
    pub fn add_shared_folder(&mut self, host_path: String) {
        // Reject duplicate paths
        if self.shared_folders.iter().any(|f| f.host_path == host_path) {
            return;
        }

        let mut mount_tag = generate_mount_tag(&host_path);

        // Ensure unique mount tag
        let base_tag = mount_tag.clone();
        let mut suffix = 2;
        while self.shared_folders.iter().any(|f| f.mount_tag == mount_tag) {
            mount_tag = format!("{}_{}", base_tag, suffix);
            suffix += 1;
        }

        self.shared_folders.push(SharedFolder {
            host_path,
            mount_tag,
        });
    }

    /// Remove the currently selected shared folder
    pub fn remove_shared_folder(&mut self) {
        if !self.shared_folders.is_empty() && self.shared_folder_selected < self.shared_folders.len()
        {
            self.shared_folders.remove(self.shared_folder_selected);
            if self.shared_folder_selected >= self.shared_folders.len()
                && self.shared_folder_selected > 0
            {
                self.shared_folder_selected -= 1;
            }
        }
    }

    /// Toggle PCI device selection
    pub fn toggle_pci_device(&mut self, index: usize) {
        // Don't allow selecting boot VGA
        if let Some(device) = self.pci_devices.get(index) {
            if device.is_boot_vga {
                return;
            }
        }

        if let Some(pos) = self.selected_pci_devices.iter().position(|&i| i == index) {
            self.selected_pci_devices.remove(pos);
        } else {
            self.selected_pci_devices.push(index);
        }
    }

    /// Auto-select a GPU and its paired audio device
    pub fn auto_select_gpu(&mut self, gpu_index: usize) {
        // Clear existing selection
        self.selected_pci_devices.clear();

        if let Some(gpu) = self.pci_devices.get(gpu_index) {
            if gpu.is_boot_vga {
                return;
            }

            // Select the GPU
            self.selected_pci_devices.push(gpu_index);

            // Try to find and select the paired audio device
            if let Some(audio) = crate::hardware::find_gpu_audio_pair(gpu, &self.pci_devices) {
                if let Some(audio_idx) = self.pci_devices.iter().position(|d| d.address == audio.address) {
                    self.selected_pci_devices.push(audio_idx);
                }
            }
        }
    }

    /// Reload the selected VM's raw script from disk
    pub fn reload_selected_vm_script(&mut self) {
        if self.visual_order.is_empty() {
            return;
        }
        if let Some(filtered_idx) = self.visual_order.get(self.selected_vm) {
            if let Some(actual_idx) = self.filtered_indices.get(*filtered_idx) {
                if let Some(vm) = self.vms.get_mut(*actual_idx) {
                    if let Ok(content) = std::fs::read_to_string(&vm.launch_script) {
                        vm.config.raw_script = content;
                    }
                }
            }
        }
    }

    /// Get launch options based on current state
    pub fn get_launch_options(&self) -> LaunchOptions {
        let usb_devices = self
            .selected_usb_devices
            .iter()
            .filter_map(|&i| self.usb_devices.get(i))
            .map(|d| crate::vm::UsbPassthrough {
                vendor_id: d.vendor_id,
                product_id: d.product_id,
                usb_version: d.usb_version,
            })
            .collect();

        LaunchOptions {
            boot_mode: self.boot_mode.clone(),
            extra_args: Vec::new(),
            usb_devices,
        }
    }

    /// Set a status message (auto-clears after 5 seconds)
    pub fn set_status(&mut self, msg: impl Into<String>) {
        self.status_message = Some(msg.into());
        self.status_time = Some(Instant::now());
    }

    /// Show a detailed error in a scrollable dialog
    pub fn show_error(&mut self, error: impl Into<String>) {
        self.error_detail = Some(error.into());
        self.error_scroll = 0;
        self.push_screen(Screen::ErrorDialog);
    }

    /// Clear status message
    pub fn clear_status(&mut self) {
        self.status_message = None;
        self.status_time = None;
    }

    /// Check and clear status if expired (call in event loop)
    pub fn check_status_expiry(&mut self) {
        if let Some(time) = self.status_time {
            if time.elapsed().as_secs() >= 5 {
                self.clear_status();
            }
        }
    }

    /// Check for background operation results (call in event loop)
    pub fn check_background_results(&mut self) {
        // Non-blocking check for results
        while let Ok(result) = self.background_rx.try_recv() {
            self.loading = false;
            match result {
                BackgroundResult::SnapshotCreated { name, success, error } => {
                    if success {
                        self.set_status(format!("Created snapshot: {}", name));
                        // Reload snapshots
                        let _ = self.load_snapshots();
                    } else if let Some(e) = error {
                        self.set_status(format!("Error creating snapshot: {}", e));
                    }
                }
                BackgroundResult::SnapshotRestored { name, success, error } => {
                    if success {
                        self.set_status(format!("Restored snapshot: {}", name));
                    } else if let Some(e) = error {
                        self.set_status(format!("Error restoring snapshot: {}", e));
                    }
                }
                BackgroundResult::SnapshotDeleted { name, success, error } => {
                    if success {
                        self.set_status(format!("Deleted snapshot: {}", name));
                        let _ = self.load_snapshots();
                    } else if let Some(e) = error {
                        self.set_status(format!("Error deleting snapshot: {}", e));
                    }
                }
                BackgroundResult::SnapshotsLoaded { snapshots, error } => {
                    if let Some(e) = error {
                        self.set_status(format!("Error loading snapshots: {}", e));
                    } else {
                        self.snapshots = snapshots;
                        self.selected_snapshot = 0;
                    }
                }
            }
        }
    }

    /// Non-blocking check for VM status updates from background thread.
    /// Consumes all pending messages, keeping only the latest result.
    pub fn check_vm_status(&mut self) {
        let mut latest = None;
        while let Ok(processes) = self.vm_status_rx.try_recv() {
            latest = Some(processes);
        }
        if let Some(processes) = latest {
            self.running_vms = self.match_running_vms(&processes);
            // Clean up stopping_vms for VMs that have actually stopped
            self.stopping_vms.retain(|id, _| self.running_vms.contains_key(id));
        }
    }

    /// Match QEMU processes against known VMs using the process working directory.
    ///
    /// Launch scripts run QEMU from the VM's directory, so /proc/<pid>/cwd
    /// reliably identifies which VM a process belongs to — unlike disk filenames
    /// which are often generic (e.g., "disk.qcow2").
    fn match_running_vms(&self, processes: &[QemuProcess]) -> HashMap<String, u32> {
        let mut result = HashMap::new();
        for vm in &self.vms {
            for proc in processes {
                if let Some(ref cwd) = proc.cwd {
                    // cwd is available — use it as the authoritative match
                    if cwd == &vm.path {
                        result.insert(vm.id.clone(), proc.pid);
                        break;
                    }
                } else {
                    // No cwd available (permissions?) — fall back to full disk path in cmdline
                    if let Some(disk) = vm.config.primary_disk() {
                        if let Some(disk_path_str) = disk.path.to_str() {
                            if !disk_path_str.is_empty() && proc.cmdline.contains(disk_path_str) {
                                result.insert(vm.id.clone(), proc.pid);
                                break;
                            }
                        }
                    }
                }
            }
        }
        result
    }

    /// Get PID of the currently selected VM if it's running.
    pub fn selected_vm_pid(&self) -> Option<u32> {
        let vm = self.selected_vm()?;
        self.running_vms.get(&vm.id).copied()
    }

    /// Load file browser entries for current directory
    pub fn load_file_browser(&mut self, mode: FileBrowserMode) {
        self.file_browser_mode = mode;
        self.file_browser_entries.clear();
        self.file_browser_selected = 0;

        // Determine file extensions to filter by based on mode
        let extensions: &[&str] = match mode {
            FileBrowserMode::Iso => &[".iso", ".ISO"],
            FileBrowserMode::RecoveryImage => &[".dmg", ".DMG", ".qcow2", ".QCOW2"],
            FileBrowserMode::Disk => &[".qcow2", ".QCOW2", ".qcow", ".QCOW"],
            FileBrowserMode::Directory => &[],
            FileBrowserMode::ImportConfig => &[".xml", ".XML", ".conf"],
            FileBrowserMode::Bios => &[".bin", ".BIN", ".rom", ".ROM", ".qcow2", ".QCOW2", ".fd", ".FD"],
            FileBrowserMode::Floppy => &[".img", ".IMG", ".ima", ".IMA", ".flp", ".FLP", ".vfd", ".VFD"],
        };

        // For Directory mode, add a [Select This Directory] sentinel entry first
        if mode == FileBrowserMode::Directory {
            self.file_browser_entries.push(FileBrowserEntry {
                name: "[Select This Directory]".to_string(),
                path: self.file_browser_dir.clone(),
                is_dir: false, // So Enter returns it as a selection
            });
        }

        // Add parent directory entry if not at root
        if let Some(parent) = self.file_browser_dir.parent() {
            self.file_browser_entries.push(FileBrowserEntry {
                name: "..".to_string(),
                path: parent.to_path_buf(),
                is_dir: true,
            });
        }

        // Read directory entries
        if let Ok(entries) = std::fs::read_dir(&self.file_browser_dir) {
            let mut dirs = Vec::new();
            let mut files = Vec::new();

            for entry in entries.flatten() {
                if let Ok(metadata) = entry.metadata() {
                    let name = entry.file_name().to_string_lossy().to_string();
                    // Skip hidden files
                    if name.starts_with('.') {
                        continue;
                    }
                    let entry = FileBrowserEntry {
                        name,
                        path: entry.path(),
                        is_dir: metadata.is_dir(),
                    };
                    if metadata.is_dir() {
                        dirs.push(entry);
                    } else if mode != FileBrowserMode::Directory
                        && extensions.iter().any(|ext| entry.name.ends_with(ext))
                    {
                        files.push(entry);
                    }
                }
            }

            // Sort alphabetically
            dirs.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
            files.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));

            self.file_browser_entries.extend(dirs);
            self.file_browser_entries.extend(files);
        }
    }

    /// Navigate into directory or select file in file browser
    pub fn file_browser_enter(&mut self) -> Option<PathBuf> {
        if let Some(entry) = self.file_browser_entries.get(self.file_browser_selected) {
            if entry.is_dir {
                self.file_browser_dir = entry.path.clone();
                // Preserve the current mode when navigating directories
                let mode = self.file_browser_mode;
                self.load_file_browser(mode);
                None
            } else {
                // Return selected file
                Some(entry.path.clone())
            }
        } else {
            None
        }
    }

    /// Move selection up in file browser
    pub fn file_browser_prev(&mut self) {
        if self.file_browser_selected > 0 {
            self.file_browser_selected -= 1;
        }
    }

    /// Move selection down in file browser
    pub fn file_browser_next(&mut self) {
        if self.file_browser_selected < self.file_browser_entries.len().saturating_sub(1) {
            self.file_browser_selected += 1;
        }
    }

    /// Load the selected VM's script into the editor
    pub fn load_script_into_editor(&mut self) {
        if let Some(vm) = self.selected_vm() {
            self.script_editor_lines = vm.config.raw_script.lines().map(String::from).collect();
            // Ensure at least one line exists
            if self.script_editor_lines.is_empty() {
                self.script_editor_lines.push(String::new());
            }
            self.script_editor_cursor = (0, 0);
            self.script_editor_modified = false;
            self.script_editor_h_scroll = 0;
            self.raw_script_scroll = 0;
        }
    }

    /// Save the editor content back to the launch.sh file
    pub fn save_script_from_editor(&mut self) -> Result<()> {
        // Get the launch script path before we need mutable access
        let launch_script_path = self.selected_vm()
            .map(|vm| vm.launch_script.clone())
            .ok_or_else(|| anyhow::anyhow!("No VM selected"))?;

        let content = self.script_editor_lines.join("\n");
        // Ensure the file ends with a newline
        let content = if content.ends_with('\n') {
            content
        } else {
            format!("{}\n", content)
        };

        std::fs::write(&launch_script_path, &content)?;

        // Update the cached raw_script in the VM
        self.reload_selected_vm_script();
        self.script_editor_modified = false;

        // Re-parse the VM config since the script changed
        if let Ok(vms) = discover_vms(&self.config.vm_library_path) {
            self.vms = vms;
            self.update_filter();
        }

        // Regenerate single-GPU scripts if they exist
        if let Some(vm) = self.selected_vm() {
            if crate::hardware::scripts_exist(&vm.path) {
                // Try with in-memory config first, fall back to saved config
                // Ignore errors - the main save succeeded
                let _ = if let Some(config) = self.single_gpu_config.as_ref() {
                    crate::vm::single_gpu_scripts::regenerate_if_exists(vm, config)
                } else {
                    crate::vm::single_gpu_scripts::regenerate_from_saved_config(vm)
                };
            }
        }

        Ok(())
    }

    // =========================================================================
    // Notes Editor Methods
    // =========================================================================

    /// Load the selected VM's notes into the editor
    pub fn load_notes_into_editor(&mut self) {
        if let Some(vm) = self.selected_vm() {
            let notes_text = vm.notes.as_deref().unwrap_or("");
            self.script_editor_lines = notes_text.lines().map(String::from).collect();
            if self.script_editor_lines.is_empty() {
                self.script_editor_lines.push(String::new());
            }
            self.script_editor_cursor = (0, 0);
            self.script_editor_modified = false;
            self.script_editor_h_scroll = 0;
            self.raw_script_scroll = 0;
        }
    }

    /// Save the editor content as notes to vm-curator.toml
    pub fn save_notes_from_editor(&mut self) -> Result<()> {
        let vm = self.selected_vm()
            .ok_or_else(|| anyhow::anyhow!("No VM selected"))?;

        let vm_path = vm.path.clone();
        let display_name = vm.display_name();
        let os_profile = vm.os_profile.clone();

        let notes_text = self.script_editor_lines.join("\n");
        // Trim trailing whitespace/newlines
        let notes_text = notes_text.trim_end().to_string();
        let notes = if notes_text.is_empty() { None } else { Some(notes_text.as_str()) };

        crate::vm::create::write_vm_metadata(
            &vm_path,
            &display_name,
            os_profile.as_deref(),
            notes,
        )?;

        // Update the in-memory VM's notes
        if let Some(filtered_idx) = self.visual_order.get(self.selected_vm) {
            if let Some(actual_idx) = self.filtered_indices.get(*filtered_idx) {
                if let Some(vm) = self.vms.get_mut(*actual_idx) {
                    vm.notes = notes.map(String::from);
                }
            }
        }

        self.script_editor_modified = false;
        Ok(())
    }

    // =========================================================================
    // VM Creation Wizard Methods
    // =========================================================================

    /// Start the VM creation wizard
    pub fn start_create_wizard(&mut self) {
        let state = CreateWizardState {
            disk_size_gb: self.config.default_disk_size_gb,
            qemu_config: WizardQemuConfig {
                memory_mb: self.config.default_memory_mb,
                cpu_cores: self.config.default_cpu_cores,
                enable_kvm: self.config.default_enable_kvm,
                display: self.config.default_display.clone(),
                ..WizardQemuConfig::default()
            },
            ..CreateWizardState::default()
        };

        self.wizard_state = Some(state);
        self.push_screen(Screen::CreateWizard);
    }

    /// Cancel the wizard and return to main menu
    pub fn cancel_wizard(&mut self) {
        self.wizard_state = None;
        // Pop all wizard-related screens
        while matches!(
            self.screen,
            Screen::CreateWizard | Screen::CreateWizardCustomOs | Screen::CreateWizardDownload
        ) {
            self.pop_screen();
        }
    }

    /// Move to the next wizard step
    pub fn wizard_next_step(&mut self) -> Result<(), String> {
        if let Some(ref mut state) = self.wizard_state {
            // Validate current step
            state.can_proceed()?;

            // Move to next step
            if let Some(next) = state.step.next() {
                state.step = next;
                state.field_focus = 0;
                state.error_message = None;
                Ok(())
            } else {
                Err("Already at final step".to_string())
            }
        } else {
            Err("Wizard not active".to_string())
        }
    }

    /// Move to the previous wizard step
    pub fn wizard_prev_step(&mut self) {
        if let Some(ref mut state) = self.wizard_state {
            if let Some(prev) = state.step.prev() {
                state.step = prev;
                state.field_focus = 0;
                state.error_message = None;
            }
        }
    }

    /// Select an OS profile in the wizard
    pub fn wizard_select_os(&mut self, os_id: &str) {
        let library_path = self.config.vm_library_path.clone();

        // Get full display name from metadata (e.g., "CachyOS (rolling)")
        // Fall back to profile's display_name if not in metadata
        let new_display_name = self.metadata.get(os_id)
            .and_then(|info| info.display_name.clone())
            .or_else(|| self.qemu_profiles.get(os_id).map(|p| p.display_name.clone()))
            .unwrap_or_else(|| os_id.to_string());

        // Get the previous OS's display name (if any) to check if user customized the name
        let previous_default_name = self.wizard_state.as_ref()
            .and_then(|s| s.selected_os.as_ref())
            .and_then(|prev_id| {
                self.metadata.get(prev_id)
                    .and_then(|info| info.display_name.clone())
                    .or_else(|| self.qemu_profiles.get(prev_id).map(|p| p.display_name.clone()))
            });

        if let Some(ref mut state) = self.wizard_state {
            state.selected_os = Some(os_id.to_string());
            state.custom_os = None;

            // Apply profile settings
            if let Some(profile) = self.qemu_profiles.get(os_id) {
                state.apply_profile(profile);

                // Only update VM name if:
                // 1. Name is empty, OR
                // 2. Name matches the previous OS's default (user hasn't customized it)
                let should_update_name = state.vm_name.is_empty()
                    || previous_default_name.as_ref().map(|n| n == &state.vm_name).unwrap_or(false);

                if should_update_name {
                    state.vm_name = new_display_name;
                }
                state.update_folder_name(&library_path);
            }
        }
    }

    /// Set the wizard to use a custom OS
    pub fn wizard_use_custom_os(&mut self) {
        if let Some(ref mut state) = self.wizard_state {
            state.selected_os = None;
            state.custom_os = Some(CustomOsEntry {
                base_profile: "generic-other".to_string(),
                architecture: "x86_64".to_string(),
                ..Default::default()
            });
            self.push_screen(Screen::CreateWizardCustomOs);
        }
    }

    /// Get the full path where the new VM will be created
    pub fn wizard_vm_path(&self) -> Option<PathBuf> {
        self.wizard_state
            .as_ref()
            .filter(|s| !s.folder_name.is_empty())
            .map(|s| self.config.vm_library_path.join(&s.folder_name))
    }

    // =========================================================================
    // VM Import Wizard Methods
    // =========================================================================

    /// Start the VM import wizard
    pub fn start_import_wizard(&mut self) {
        self.import_state = Some(ImportWizardState::default());
        self.push_screen(Screen::ImportWizard);
    }

    /// Cancel the import wizard and return to main menu
    pub fn cancel_import_wizard(&mut self) {
        self.import_state = None;
        while self.screen == Screen::ImportWizard {
            self.pop_screen();
        }
    }

    /// Get the selected OS profile in the wizard
    pub fn wizard_selected_profile(&self) -> Option<&crate::metadata::QemuProfile> {
        self.wizard_state
            .as_ref()
            .and_then(|s| s.selected_os.as_ref())
            .and_then(|os_id| self.qemu_profiles.get(os_id))
    }
}

/// Generate a mount tag from a host directory path
fn generate_mount_tag(path: &str) -> String {
    let folder_name = std::path::Path::new(path)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("shared");
    let sanitized: String = folder_name
        .to_lowercase()
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '_' })
        .collect();
    let tag = sanitized
        .split('_')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("_");
    format!(
        "host_{}",
        if tag.is_empty() {
            "shared".to_string()
        } else {
            tag
        }
    )
}