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
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
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
pub mod screens;
pub mod widgets;

use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind};
use ratatui::prelude::*;
use ratatui::backend::CrosstermBackend;
use regex::Regex;
use std::io::Stdout;
use std::time::{Duration, Instant};

use crate::app::{App, BackgroundResult, ConfirmAction, InputMode, Screen, TextInputContext};
use crate::vm::{launch_vm_with_error_check, BootMode};
use std::thread;

/// Run the TUI application
pub fn run(terminal: &mut Terminal<CrosstermBackend<Stdout>>, app: &mut App) -> Result<()> {
    loop {
        terminal.draw(|frame| render(app, frame))?;

        // Check for status message expiry
        app.check_status_expiry();

        // Check for background operation results
        app.check_background_results();

        // Check for VM status updates from background thread
        app.check_vm_status();

        // Poll with timeout to allow periodic checks
        if event::poll(Duration::from_millis(100))? {
            match event::read()? {
                Event::Key(key) => {
                    // Ignore input while loading
                    if !app.loading {
                        handle_key(app, key)?;
                    }
                }
                Event::Mouse(mouse) => {
                    if !app.loading {
                        handle_mouse(app, mouse)?;
                    }
                }
                _ => {}
            }
        }

        if app.should_quit {
            break;
        }
    }

    Ok(())
}

/// Handle mouse input
fn handle_mouse(app: &mut App, mouse: MouseEvent) -> Result<()> {
    match mouse.kind {
        MouseEventKind::ScrollUp => {
            if app.screen == Screen::MainMenu {
                app.select_prev();
            }
        }
        MouseEventKind::ScrollDown => {
            if app.screen == Screen::MainMenu {
                app.select_next();
            }
        }
        MouseEventKind::Down(crossterm::event::MouseButton::Left) => {
            match &app.screen {
                Screen::MainMenu => {
                    handle_main_menu_click(app, mouse.column, mouse.row)?;
                }
                Screen::Confirm(action) => {
                    handle_confirm_click(app, action.clone(), mouse.column, mouse.row)?;
                }
                _ => {}
            }
        }
        _ => {}
    }
    Ok(())
}

/// Handle mouse click in the main menu
fn handle_main_menu_click(app: &mut App, click_x: u16, click_y: u16) -> Result<()> {
    if let Ok((term_width, term_height)) = crossterm::terminal::size() {
        // Main layout: title (3), content (rest), help (3)
        let title_height = 3u16;
        let help_height = 3u16;
        let content_y = title_height;
        let content_height = term_height.saturating_sub(title_height + help_height);

        // VM list is 40% of content width on the left
        let list_width = (term_width * 40) / 100;

        // List area with borders: inner area starts at +1 from each edge
        let list_inner_x = 1u16;
        let list_inner_y = content_y + 1; // +1 for block border
        let list_inner_width = list_width.saturating_sub(2);
        let list_inner_height = content_height.saturating_sub(2);

        // Check if click is within the list inner area
        if click_x >= list_inner_x
            && click_x < list_inner_x + list_inner_width
            && click_y >= list_inner_y
            && click_y < list_inner_y + list_inner_height
        {
            // Calculate which row was clicked
            let clicked_row = (click_y - list_inner_y) as usize;

            // Map clicked row to visual_order index (accounting for header rows)
            if let Some(visual_idx) = widgets::click_row_to_visual_index(
                &app.vms,
                &app.filtered_indices,
                &app.hierarchy,
                &app.metadata,
                &app.visual_order,
                clicked_row,
            ) {
                // If clicking on already-selected VM, show launch confirmation
                if visual_idx == app.selected_vm && app.selected_vm().is_some() {
                    app.push_screen(Screen::Confirm(ConfirmAction::LaunchVm));
                } else {
                    // Otherwise, just select the VM
                    app.selected_vm = visual_idx;
                    app.info_scroll = 0; // Reset scroll when VM changes
                }
            }
        }
    }
    Ok(())
}

/// Handle mouse click in the confirmation dialog
fn handle_confirm_click(app: &mut App, action: ConfirmAction, click_x: u16, click_y: u16) -> Result<()> {
    if let Ok((term_width, term_height)) = crossterm::terminal::size() {
        let area = Rect::new(0, 0, term_width, term_height);

        // Calculate dialog dimensions (same as ConfirmDialog::render)
        let dialog_width = 50.min(area.width.saturating_sub(4));
        let dialog_height = 8.min(area.height.saturating_sub(4));

        // Calculate centered position
        let dialog_x = area.x + (area.width.saturating_sub(dialog_width)) / 2;
        let dialog_y = area.y + (area.height.saturating_sub(dialog_height)) / 2;

        // Inner area after borders (1 pixel each side)
        let inner_x = dialog_x + 1;
        let inner_y = dialog_y + 1;
        let inner_width = dialog_width.saturating_sub(2);
        let inner_height = dialog_height.saturating_sub(2);

        // Buttons are in the bottom 2 rows of the inner area
        let buttons_y = inner_y + inner_height.saturating_sub(2);

        // Check if click is in the buttons row
        if click_y >= buttons_y && click_y < buttons_y + 2 {
            // Buttons are centered: " Yes (y) "  "  "  " No (n) "
            // Yes button is roughly in the left half, No in the right half
            let center_x = inner_x + inner_width / 2;

            if click_x >= inner_x && click_x < center_x {
                // Clicked on Yes - execute the action
                execute_confirm_action(app, action)?;
            } else if click_x >= center_x && click_x < inner_x + inner_width {
                // Clicked on No - cancel
                app.pop_screen();
            }
        }

        // Allow clicking outside the dialog to cancel
        if click_x < dialog_x || click_x >= dialog_x + dialog_width
            || click_y < dialog_y || click_y >= dialog_y + dialog_height
        {
            app.pop_screen();
        }
    }
    Ok(())
}

/// Execute a confirmed action (extracted from handle_confirm for reuse)
fn execute_confirm_action(app: &mut App, action: ConfirmAction) -> Result<()> {
    match action {
        ConfirmAction::LaunchVm => {
            // Pop the confirm dialog first
            app.pop_screen();

            if let Some(vm) = app.selected_vm().cloned() {
                if app.running_vms.contains_key(&vm.id) {
                    app.set_status(format!("{} is already running", vm.display_name()));
                } else {
                    let options = app.get_launch_options();
                    let result = launch_vm_with_error_check(&vm, &options);

                    if result.success {
                        app.set_status(format!("Launched: {}", result.vm_name));
                    } else {
                        // Show error in the error dialog for better visibility
                        let error_msg = result.error.unwrap_or_else(|| "Unknown error".to_string());
                        app.show_error(format!(
                            "Failed to launch {}\n\n{}",
                            result.vm_name, error_msg
                        ));
                    }
                }
            }
        }
        ConfirmAction::ResetVm => {
            if let Some(vm) = app.selected_vm() {
                if app.running_vms.contains_key(&vm.id) {
                    app.set_status("Error: Cannot reset VM while it is running. Please shut down the VM first.");
                } else if let Err(e) = crate::vm::lifecycle::reset_vm(vm) {
                    app.set_status(format!("Error: {}", e));
                } else {
                    app.set_status("VM reset to fresh state");
                }
            }
            app.pop_screen();
            app.pop_screen();
        }
        ConfirmAction::DeleteVm => {
            if let Some(vm) = app.selected_vm().cloned() {
                if let Err(e) = crate::vm::lifecycle::delete_vm(&vm, false) {
                    app.set_status(format!("Error: {}", e));
                } else {
                    app.set_status(format!("Deleted: {}", vm.display_name()));
                    app.refresh_vms()?;
                }
            }
            app.pop_screen();
            app.pop_screen();
        }
        ConfirmAction::RestoreSnapshot(name) => {
            if let Some(vm) = app.selected_vm() {
                if app.running_vms.contains_key(&vm.id) {
                    app.set_status("Error: Cannot restore snapshot while VM is running. Please shut down the VM first.");
                } else if let Some(disk) = vm.config.primary_disk() {
                    let disk_path = disk.path.clone();
                    let snap_name = name.clone();
                    let tx = app.background_tx.clone();
                    app.loading = true;
                    app.set_status(format!("Restoring snapshot: {}...", name));

                    thread::spawn(move || {
                        let result = crate::vm::restore_snapshot(&disk_path, &snap_name);
                        let _ = tx.send(BackgroundResult::SnapshotRestored {
                            name: snap_name,
                            success: result.is_ok(),
                            error: result.err().map(|e| e.to_string()),
                        });
                    });
                }
            }
            app.pop_screen();
        }
        ConfirmAction::DeleteSnapshot(name) => {
            if let Some(vm) = app.selected_vm() {
                if app.running_vms.contains_key(&vm.id) {
                    app.set_status("Error: Cannot delete snapshot while VM is running. Please shut down the VM first.");
                } else if let Some(disk) = vm.config.primary_disk() {
                    let disk_path = disk.path.clone();
                    let snap_name = name.clone();
                    let tx = app.background_tx.clone();
                    app.loading = true;
                    app.set_status(format!("Deleting snapshot: {}...", name));

                    thread::spawn(move || {
                        let result = crate::vm::delete_snapshot(&disk_path, &snap_name);
                        let _ = tx.send(BackgroundResult::SnapshotDeleted {
                            name: snap_name,
                            success: result.is_ok(),
                            error: result.err().map(|e| e.to_string()),
                        });
                    });
                }
            }
            app.pop_screen();
        }
        ConfirmAction::DiscardScriptChanges => {
            // Discard changes and exit editor
            app.raw_script_scroll = 0;
            app.script_editor_lines.clear();
            app.script_editor_modified = false;
            app.pop_screen(); // Close confirm dialog
            app.pop_screen(); // Close editor
        }
        ConfirmAction::DiscardNotesChanges => {
            // Discard changes and exit notes editor
            app.raw_script_scroll = 0;
            app.script_editor_lines.clear();
            app.script_editor_modified = false;
            app.pop_screen(); // Close confirm dialog
            app.pop_screen(); // Close editor
        }
        ConfirmAction::StopVm => {
            app.pop_screen();
            if let Some(vm) = app.selected_vm().cloned() {
                if let Some(pid) = app.running_vms.get(&vm.id).copied() {
                    match crate::vm::stop_vm_by_pid(pid) {
                        Ok(()) => {
                            app.stopping_vms.insert(vm.id.clone(), Instant::now());
                            app.set_status(format!("Stopping {}...", vm.display_name()));
                        }
                        Err(e) => {
                            app.set_status(format!("Failed to stop {}: {}", vm.display_name(), e));
                        }
                    }
                } else {
                    app.set_status(format!("{} is not running", vm.display_name()));
                }
            }
        }
        ConfirmAction::ForceStopVm => {
            app.pop_screen();
            if let Some(vm) = app.selected_vm().cloned() {
                if let Some(pid) = app.running_vms.get(&vm.id).copied() {
                    match crate::vm::force_stop_vm(pid) {
                        Ok(()) => {
                            app.stopping_vms.remove(&vm.id);
                            app.set_status(format!("Force stopped {}", vm.display_name()));
                        }
                        Err(e) => {
                            app.set_status(format!("Failed to force stop {}: {}", vm.display_name(), e));
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

/// Render a dimming overlay over the entire screen
/// Uses a dark background that the popup's Clear widget will cut through
fn render_dim_overlay(_frame: &mut Frame) {
    // Dimming disabled - causing rendering issues
    // The popup's Clear widget and borders provide sufficient contrast
}

/// Render the current screen
fn render(app: &App, frame: &mut Frame) {
    match &app.screen {
        Screen::MainMenu => screens::main_menu::render(app, frame),
        Screen::Management => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::management::render(app, frame);
        }
        Screen::Configuration => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::configuration::render(app, frame);
        }
        Screen::RawScript => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::configuration::render_raw_script(app, frame);
        }
        Screen::EditNotes => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::configuration::render_edit_notes(app, frame);
        }
        Screen::DetailedInfo => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            render_detailed_info(app, frame);
        }
        Screen::Snapshots => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::management::render_snapshots(app, frame);
        }
        Screen::BootOptions => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::management::render_boot_options(app, frame);
        }
        Screen::DisplayOptions => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::management::render_display_options(app, frame);
        }
        Screen::UsbDevices => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            render_usb_devices(app, frame);
        }
        Screen::PciPassthrough => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::pci_passthrough::render(app, frame);
        }
        Screen::SharedFolders => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::shared_folders::render(app, frame);
        }
        Screen::SingleGpuSetup => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::single_gpu_setup::render(app, frame);
        }
        Screen::SingleGpuInstructions => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::single_gpu_setup::render_instructions(app, frame);
        }
        Screen::MultiGpuSetup => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::multi_gpu_setup::render(app, frame);
        }
        Screen::Confirm(action) => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            render_confirm(app, action, frame);
        }
        Screen::Help => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::help::render(frame);
        }
        Screen::Search => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            render_search(app, frame);
        }
        Screen::FileBrowser => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            render_file_browser(app, frame);
        }
        Screen::TextInput(context) => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            render_text_input(app, context, frame);
        }
        Screen::ErrorDialog => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            render_error_dialog(app, frame);
        }
        Screen::CreateWizard => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::create_wizard::render(app, frame);
        }
        Screen::CreateWizardCustomOs => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::create_wizard::render_custom_os(app, frame);
        }
        Screen::CreateWizardDownload => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::create_wizard::render_download(app, frame);
        }
        Screen::NetworkSettings => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::network_settings::render(app, frame);
        }
        Screen::Settings => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::settings::render(app, frame);
        }
        Screen::ImportWizard => {
            screens::main_menu::render(app, frame);
            render_dim_overlay(frame);
            screens::import_wizard::render(app, frame);
        }
    }
}

/// Handle key input
fn handle_key(app: &mut App, key: KeyEvent) -> Result<()> {
    // Global quit with Ctrl+C
    if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
        app.should_quit = true;
        return Ok(());
    }

    // Global quit with q/Q (except in text input modes where q might be typed)
    if (key.code == KeyCode::Char('q') || key.code == KeyCode::Char('Q'))
        && !matches!(app.screen, Screen::Search | Screen::TextInput(_) | Screen::RawScript | Screen::EditNotes | Screen::CreateWizard | Screen::CreateWizardCustomOs | Screen::NetworkSettings | Screen::ImportWizard)
    {
        app.should_quit = true;
        return Ok(());
    }

    match &app.screen {
        Screen::MainMenu => handle_main_menu(app, key)?,
        Screen::Management => handle_management(app, key)?,
        Screen::Configuration => handle_configuration(app, key)?,
        Screen::RawScript => handle_raw_script(app, key)?,
        Screen::EditNotes => handle_edit_notes(app, key)?,
        Screen::DetailedInfo => handle_detailed_info(app, key)?,
        Screen::Snapshots => handle_snapshots(app, key)?,
        Screen::BootOptions => handle_boot_options(app, key)?,
        Screen::DisplayOptions => handle_display_options(app, key)?,
        Screen::UsbDevices => handle_usb_devices(app, key)?,
        Screen::PciPassthrough => screens::pci_passthrough::handle_key(app, key)?,
        Screen::SharedFolders => screens::shared_folders::handle_key(app, key)?,
        Screen::SingleGpuSetup => screens::single_gpu_setup::handle_key(app, key)?,
        Screen::SingleGpuInstructions => handle_single_gpu_instructions(app, key)?,
        Screen::MultiGpuSetup => screens::multi_gpu_setup::handle_input(app, key)?,
        Screen::Confirm(action) => handle_confirm(app, action.clone(), key)?,
        Screen::Help => handle_help(app, key)?,
        Screen::Search => handle_search(app, key)?,
        Screen::FileBrowser => handle_file_browser(app, key)?,
        Screen::TextInput(context) => handle_text_input(app, context.clone(), key)?,
        Screen::ErrorDialog => handle_error_dialog(app, key)?,
        Screen::CreateWizard => screens::create_wizard::handle_key(app, key)?,
        Screen::CreateWizardCustomOs => screens::create_wizard::handle_custom_os_key(app, key)?,
        Screen::CreateWizardDownload => screens::create_wizard::handle_download_key(app, key)?,
        Screen::NetworkSettings => screens::network_settings::handle_key(app, key)?,
        Screen::Settings => { screens::settings::handle_input(app, key)?; }
        Screen::ImportWizard => screens::import_wizard::handle_key(app, key)?,
    }

    Ok(())
}

fn handle_main_menu(app: &mut App, key: KeyEvent) -> Result<()> {
    match key.code {
        KeyCode::Char('j') | KeyCode::Down => app.select_next(),
        KeyCode::Char('k') | KeyCode::Up => app.select_prev(),
        KeyCode::PageDown => {
            app.info_scroll = app.info_scroll.saturating_add(5);
        }
        KeyCode::PageUp => {
            app.info_scroll = app.info_scroll.saturating_sub(5);
        }
        KeyCode::Enter => {
            if app.selected_vm().is_some() {
                if app.config.confirm_before_launch {
                    app.push_screen(Screen::Confirm(ConfirmAction::LaunchVm));
                } else {
                    // Launch directly without confirmation
                    execute_confirm_action(app, ConfirmAction::LaunchVm)?;
                }
            }
        }
        KeyCode::Char('m') | KeyCode::Char('M') => {
            if app.selected_vm().is_some() {
                app.push_screen(Screen::Management);
            }
        }
        KeyCode::Char('/') => {
            app.input_mode = InputMode::Editing;
            app.push_screen(Screen::Search);
        }
        KeyCode::Char('?') => app.push_screen(Screen::Help),
        KeyCode::Char('c') | KeyCode::Char('C') => {
            app.start_create_wizard();
        }
        KeyCode::Char('i') | KeyCode::Char('I') => {
            app.start_import_wizard();
        }
        KeyCode::Char('s') | KeyCode::Char('S') => {
            app.push_screen(Screen::Settings);
        }
        KeyCode::Char('x') | KeyCode::Char('X') => {
            if let Some(vm) = app.selected_vm().cloned() {
                if app.selected_vm_pid().is_some() {
                    if let Some(sent_at) = app.stopping_vms.get(&vm.id) {
                        if sent_at.elapsed() > Duration::from_secs(10) {
                            app.push_screen(Screen::Confirm(ConfirmAction::ForceStopVm));
                        } else {
                            app.set_status(format!(
                                "Waiting for {} to shut down... (press x again after 10s to force)",
                                vm.display_name()
                            ));
                        }
                    } else {
                        app.push_screen(Screen::Confirm(ConfirmAction::StopVm));
                    }
                } else {
                    app.set_status("VM is not running");
                }
            }
        }
        _ => {}
    }
    Ok(())
}

fn handle_management(app: &mut App, key: KeyEvent) -> Result<()> {
    use screens::management::{get_menu_items, menu_item_count, MenuAction};

    let item_count = menu_item_count(app);

    match key.code {
        KeyCode::Esc => app.pop_screen(),
        KeyCode::Char('j') | KeyCode::Down => app.menu_next(item_count),
        KeyCode::Char('k') | KeyCode::Up => app.menu_prev(),
        KeyCode::Enter | KeyCode::Char('1') | KeyCode::Char('2') | KeyCode::Char('3') | KeyCode::Char('4') | KeyCode::Char('5') | KeyCode::Char('6') | KeyCode::Char('7') | KeyCode::Char('8') | KeyCode::Char('9') => {
            // Map number keys to menu index
            let selected_idx = match key.code {
                KeyCode::Char('1') => 0,
                KeyCode::Char('2') => 1,
                KeyCode::Char('3') => 2,
                KeyCode::Char('4') => 3,
                KeyCode::Char('5') => 4,
                KeyCode::Char('6') => 5,
                KeyCode::Char('7') => 6,
                KeyCode::Char('8') => 7,
                KeyCode::Char('9') => 8,
                _ => app.selected_menu_item,
            };

            // Get the menu items and find the action
            if let Some(vm) = app.selected_vm() {
                let menu_items = get_menu_items(vm, &app.config);
                if let Some(item) = menu_items.get(selected_idx) {
                    match item.action {
                        MenuAction::StopVm => {
                            if let Some(vm) = app.selected_vm().cloned() {
                                if app.selected_vm_pid().is_some() {
                                    if let Some(sent_at) = app.stopping_vms.get(&vm.id) {
                                        if sent_at.elapsed() > Duration::from_secs(10) {
                                            app.push_screen(Screen::Confirm(ConfirmAction::ForceStopVm));
                                        } else {
                                            app.set_status(format!(
                                                "Waiting for {} to shut down...",
                                                vm.display_name()
                                            ));
                                        }
                                    } else {
                                        app.push_screen(Screen::Confirm(ConfirmAction::StopVm));
                                    }
                                } else {
                                    app.set_status("VM is not running");
                                }
                            }
                        }
                        MenuAction::BootOptions => {
                            app.selected_menu_item = 0;
                            app.push_screen(Screen::BootOptions);
                        }
                        MenuAction::Snapshots => {
                            app.load_snapshots()?;
                            app.push_screen(Screen::Snapshots);
                        }
                        MenuAction::UsbPassthrough => {
                            app.load_usb_devices()?;
                            // Load saved USB passthrough config and pre-select matching devices
                            if let Some(vm) = app.selected_vm() {
                                let saved = crate::vm::load_usb_passthrough(vm);
                                app.selected_usb_devices.clear();
                                for saved_dev in &saved {
                                    // Find matching device by vendor/product ID
                                    for (i, dev) in app.usb_devices.iter().enumerate() {
                                        if dev.vendor_id == saved_dev.vendor_id
                                            && dev.product_id == saved_dev.product_id
                                        {
                                            app.selected_usb_devices.push(i);
                                            break;
                                        }
                                    }
                                }
                            }
                            app.selected_menu_item = 0;
                            app.push_screen(Screen::UsbDevices);
                        }
                        MenuAction::PciPassthrough => {
                            app.load_pci_devices()?;
                            // Load saved PCI passthrough config and pre-select matching devices
                            if let Some(vm) = app.selected_vm() {
                                let saved_args = crate::vm::load_pci_passthrough(vm);
                                app.selected_pci_devices.clear();
                                for arg in &saved_args {
                                    // Extract address from "-device vfio-pci,host=0000:01:00.0"
                                    if let Some(host_start) = arg.find("host=") {
                                        let addr_start = host_start + 5;
                                        let addr = arg[addr_start..]
                                            .split(|c: char| c == ',' || c.is_whitespace())
                                            .next()
                                            .unwrap_or("");
                                        // Find matching device by address
                                        for (i, dev) in app.pci_devices.iter().enumerate() {
                                            if dev.address == addr {
                                                app.selected_pci_devices.push(i);
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            app.selected_menu_item = 0;
                            app.push_screen(Screen::PciPassthrough);
                        }
                        MenuAction::SharedFolders => {
                            app.load_shared_folders();
                            app.selected_menu_item = 0;
                            app.push_screen(Screen::SharedFolders);
                        }
                        MenuAction::NetworkSettings => {
                            // Initialize network settings state from current VM config
                            if let Some(vm) = app.selected_vm() {
                                let net = vm.config.network.as_ref();
                                let model = net.map(|n| n.model.clone()).unwrap_or_else(|| "e1000".to_string());
                                let (backend, bridge_name) = net.map(|n| {
                                    match &n.backend {
                                        crate::vm::qemu_config::NetworkBackend::User => ("user".to_string(), None),
                                        crate::vm::qemu_config::NetworkBackend::Passt => ("passt".to_string(), None),
                                        crate::vm::qemu_config::NetworkBackend::Bridge(name) => ("bridge".to_string(), Some(name.clone())),
                                        crate::vm::qemu_config::NetworkBackend::None => ("none".to_string(), None),
                                    }
                                }).unwrap_or_else(|| ("user".to_string(), None));
                                let port_forwards = net.map(|n| n.port_forwards.clone()).unwrap_or_default();

                                app.network_settings_state = Some(crate::app::NetworkSettingsState {
                                    model,
                                    backend,
                                    bridge_name,
                                    port_forwards,
                                    selected_field: 0,
                                    editing_port_forwards: false,
                                    pf_selected: 0,
                                    adding_pf: None,
                                });
                                app.push_screen(Screen::NetworkSettings);
                            }
                        }
                        MenuAction::MultiGpuPassthrough => {
                            // Load PCI devices for multi-GPU setup
                            app.load_pci_devices()?;
                            app.push_screen(Screen::MultiGpuSetup);
                        }
                        MenuAction::SingleGpuPassthrough => {
                            // Load PCI devices and initialize single GPU config
                            app.load_pci_devices()?;
                            screens::single_gpu_setup::init_single_gpu_config(app);
                            app.single_gpu_selected_field = 0;
                            app.push_screen(Screen::SingleGpuSetup);
                        }
                        MenuAction::ChangeDisplay => {
                            app.selected_menu_item = 0;
                            app.push_screen(Screen::DisplayOptions);
                        }
                        MenuAction::EditNotes => {
                            app.load_notes_into_editor();
                            app.push_screen(Screen::EditNotes);
                        }
                        MenuAction::RenameVm => {
                            if let Some(vm) = app.selected_vm() {
                                app.text_input_buffer = vm.display_name();
                            }
                            app.push_screen(Screen::TextInput(TextInputContext::RenameVm));
                        }
                        MenuAction::ResetVm => {
                            app.push_screen(Screen::Confirm(ConfirmAction::ResetVm));
                        }
                        MenuAction::DeleteVm => {
                            app.push_screen(Screen::Confirm(ConfirmAction::DeleteVm));
                        }
                        MenuAction::EditRawConfig => {
                            app.load_script_into_editor();
                            app.push_screen(Screen::RawScript);
                        }
                    }
                }
            }
        }
        _ => {}
    }
    Ok(())
}

fn handle_configuration(app: &mut App, key: KeyEvent) -> Result<()> {
    match key.code {
        KeyCode::Esc => app.pop_screen(),
        KeyCode::Char('r') | KeyCode::Char('R') => {
            app.push_screen(Screen::RawScript);
        }
        _ => {}
    }
    Ok(())
}

fn handle_raw_script(app: &mut App, key: KeyEvent) -> Result<()> {
    let total_lines = app.script_editor_lines.len();

    match (key.code, key.modifiers) {
        // Save with Ctrl+S
        (KeyCode::Char('s'), m) if m.contains(KeyModifiers::CONTROL) => {
            match app.save_script_from_editor() {
                Ok(()) => app.set_status("Script saved successfully"),
                Err(e) => app.set_status(format!("Error saving script: {}", e)),
            }
        }

        // Cancel/Exit with Esc
        (KeyCode::Esc, _) => {
            if app.script_editor_modified {
                // Show confirmation if modified
                app.push_screen(Screen::Confirm(ConfirmAction::DiscardScriptChanges));
            } else {
                app.raw_script_scroll = 0;
                app.script_editor_lines.clear();
                app.pop_screen();
            }
        }

        // Navigation
        (KeyCode::Up, _) => {
            if app.script_editor_cursor.0 > 0 {
                app.script_editor_cursor.0 -= 1;
                // Adjust column if new line is shorter
                let line_len = app.script_editor_lines.get(app.script_editor_cursor.0)
                    .map(|l| l.len()).unwrap_or(0);
                if app.script_editor_cursor.1 > line_len {
                    app.script_editor_cursor.1 = line_len;
                }
                // Scroll up if cursor goes above visible area
                if app.script_editor_cursor.0 < app.raw_script_scroll as usize {
                    app.raw_script_scroll = app.script_editor_cursor.0 as u16;
                }
            }
        }
        (KeyCode::Down, _) => {
            if app.script_editor_cursor.0 < total_lines.saturating_sub(1) {
                app.script_editor_cursor.0 += 1;
                // Adjust column if new line is shorter
                let line_len = app.script_editor_lines.get(app.script_editor_cursor.0)
                    .map(|l| l.len()).unwrap_or(0);
                if app.script_editor_cursor.1 > line_len {
                    app.script_editor_cursor.1 = line_len;
                }
                // Scroll down if needed (assuming ~35 visible lines)
                let visible_height = 35usize;
                if app.script_editor_cursor.0 >= app.raw_script_scroll as usize + visible_height {
                    app.raw_script_scroll = (app.script_editor_cursor.0 - visible_height + 1) as u16;
                }
            }
        }
        (KeyCode::Left, _) => {
            if app.script_editor_cursor.1 > 0 {
                app.script_editor_cursor.1 -= 1;
            } else if app.script_editor_cursor.0 > 0 {
                // Move to end of previous line
                app.script_editor_cursor.0 -= 1;
                app.script_editor_cursor.1 = app.script_editor_lines.get(app.script_editor_cursor.0)
                    .map(|l| l.len()).unwrap_or(0);
            }
            // Adjust horizontal scroll
            if app.script_editor_cursor.1 < app.script_editor_h_scroll {
                app.script_editor_h_scroll = app.script_editor_cursor.1;
            }
        }
        (KeyCode::Right, _) => {
            let line_len = app.script_editor_lines.get(app.script_editor_cursor.0)
                .map(|l| l.len()).unwrap_or(0);
            if app.script_editor_cursor.1 < line_len {
                app.script_editor_cursor.1 += 1;
            } else if app.script_editor_cursor.0 < total_lines.saturating_sub(1) {
                // Move to start of next line
                app.script_editor_cursor.0 += 1;
                app.script_editor_cursor.1 = 0;
            }
            // Adjust horizontal scroll (assuming ~80 visible columns)
            let visible_width = 80usize;
            if app.script_editor_cursor.1 >= app.script_editor_h_scroll + visible_width {
                app.script_editor_h_scroll = app.script_editor_cursor.1 - visible_width + 1;
            }
        }
        (KeyCode::Home, _) => {
            app.script_editor_cursor.1 = 0;
            app.script_editor_h_scroll = 0;
        }
        (KeyCode::End, _) => {
            let line_len = app.script_editor_lines.get(app.script_editor_cursor.0)
                .map(|l| l.len()).unwrap_or(0);
            app.script_editor_cursor.1 = line_len;
        }
        (KeyCode::PageUp, _) => {
            let jump = 20;
            app.script_editor_cursor.0 = app.script_editor_cursor.0.saturating_sub(jump);
            app.raw_script_scroll = app.raw_script_scroll.saturating_sub(jump as u16);
            // Adjust column
            let line_len = app.script_editor_lines.get(app.script_editor_cursor.0)
                .map(|l| l.len()).unwrap_or(0);
            if app.script_editor_cursor.1 > line_len {
                app.script_editor_cursor.1 = line_len;
            }
        }
        (KeyCode::PageDown, _) => {
            let jump = 20;
            app.script_editor_cursor.0 = (app.script_editor_cursor.0 + jump).min(total_lines.saturating_sub(1));
            app.raw_script_scroll = (app.raw_script_scroll + jump as u16).min(total_lines.saturating_sub(1) as u16);
            // Adjust column
            let line_len = app.script_editor_lines.get(app.script_editor_cursor.0)
                .map(|l| l.len()).unwrap_or(0);
            if app.script_editor_cursor.1 > line_len {
                app.script_editor_cursor.1 = line_len;
            }
        }

        // Editing - Enter (new line)
        (KeyCode::Enter, _) => {
            let (line_idx, col) = app.script_editor_cursor;
            if let Some(line) = app.script_editor_lines.get_mut(line_idx) {
                let remainder = line[col..].to_string();
                line.truncate(col);
                app.script_editor_lines.insert(line_idx + 1, remainder);
                app.script_editor_cursor = (line_idx + 1, 0);
                app.script_editor_modified = true;
            }
        }

        // Editing - Backspace
        (KeyCode::Backspace, _) => {
            let (line_idx, col) = app.script_editor_cursor;
            if col > 0 {
                if let Some(line) = app.script_editor_lines.get_mut(line_idx) {
                    line.remove(col - 1);
                    app.script_editor_cursor.1 -= 1;
                    app.script_editor_modified = true;
                }
            } else if line_idx > 0 {
                // Join with previous line
                let current_line = app.script_editor_lines.remove(line_idx);
                if let Some(prev_line) = app.script_editor_lines.get_mut(line_idx - 1) {
                    let prev_len = prev_line.len();
                    prev_line.push_str(&current_line);
                    app.script_editor_cursor = (line_idx - 1, prev_len);
                    app.script_editor_modified = true;
                }
            }
        }

        // Editing - Delete
        (KeyCode::Delete, _) => {
            let (line_idx, col) = app.script_editor_cursor;
            if let Some(line) = app.script_editor_lines.get_mut(line_idx) {
                if col < line.len() {
                    line.remove(col);
                    app.script_editor_modified = true;
                } else if line_idx < total_lines - 1 {
                    // Join with next line
                    let next_line = app.script_editor_lines.remove(line_idx + 1);
                    app.script_editor_lines.get_mut(line_idx).unwrap().push_str(&next_line);
                    app.script_editor_modified = true;
                }
            }
        }

        // Editing - Tab (insert 4 spaces)
        (KeyCode::Tab, _) => {
            let (line_idx, col) = app.script_editor_cursor;
            if let Some(line) = app.script_editor_lines.get_mut(line_idx) {
                line.insert_str(col, "    ");
                app.script_editor_cursor.1 += 4;
                app.script_editor_modified = true;
            }
        }

        // Typing characters
        (KeyCode::Char(c), m) if !m.contains(KeyModifiers::CONTROL) => {
            let (line_idx, col) = app.script_editor_cursor;
            if let Some(line) = app.script_editor_lines.get_mut(line_idx) {
                line.insert(col, c);
                app.script_editor_cursor.1 += 1;
                app.script_editor_modified = true;
            }
        }

        _ => {}
    }
    Ok(())
}

fn handle_edit_notes(app: &mut App, key: KeyEvent) -> Result<()> {
    let total_lines = app.script_editor_lines.len();

    match (key.code, key.modifiers) {
        // Save with Ctrl+S
        (KeyCode::Char('s'), m) if m.contains(KeyModifiers::CONTROL) => {
            match app.save_notes_from_editor() {
                Ok(()) => app.set_status("Notes saved"),
                Err(e) => app.set_status(format!("Error saving notes: {}", e)),
            }
        }

        // Cancel/Exit with Esc
        (KeyCode::Esc, _) => {
            if app.script_editor_modified {
                app.push_screen(Screen::Confirm(ConfirmAction::DiscardNotesChanges));
            } else {
                app.raw_script_scroll = 0;
                app.script_editor_lines.clear();
                app.pop_screen();
            }
        }

        // Navigation
        (KeyCode::Up, _) => {
            if app.script_editor_cursor.0 > 0 {
                app.script_editor_cursor.0 -= 1;
                let line_len = app.script_editor_lines.get(app.script_editor_cursor.0)
                    .map(|l| l.len()).unwrap_or(0);
                if app.script_editor_cursor.1 > line_len {
                    app.script_editor_cursor.1 = line_len;
                }
                if app.script_editor_cursor.0 < app.raw_script_scroll as usize {
                    app.raw_script_scroll = app.script_editor_cursor.0 as u16;
                }
            }
        }
        (KeyCode::Down, _) => {
            if app.script_editor_cursor.0 < total_lines.saturating_sub(1) {
                app.script_editor_cursor.0 += 1;
                let line_len = app.script_editor_lines.get(app.script_editor_cursor.0)
                    .map(|l| l.len()).unwrap_or(0);
                if app.script_editor_cursor.1 > line_len {
                    app.script_editor_cursor.1 = line_len;
                }
                let visible_height = 35usize;
                if app.script_editor_cursor.0 >= app.raw_script_scroll as usize + visible_height {
                    app.raw_script_scroll = (app.script_editor_cursor.0 - visible_height + 1) as u16;
                }
            }
        }
        (KeyCode::Left, _) => {
            if app.script_editor_cursor.1 > 0 {
                app.script_editor_cursor.1 -= 1;
            } else if app.script_editor_cursor.0 > 0 {
                app.script_editor_cursor.0 -= 1;
                app.script_editor_cursor.1 = app.script_editor_lines.get(app.script_editor_cursor.0)
                    .map(|l| l.len()).unwrap_or(0);
            }
            if app.script_editor_cursor.1 < app.script_editor_h_scroll {
                app.script_editor_h_scroll = app.script_editor_cursor.1;
            }
        }
        (KeyCode::Right, _) => {
            let line_len = app.script_editor_lines.get(app.script_editor_cursor.0)
                .map(|l| l.len()).unwrap_or(0);
            if app.script_editor_cursor.1 < line_len {
                app.script_editor_cursor.1 += 1;
            } else if app.script_editor_cursor.0 < total_lines.saturating_sub(1) {
                app.script_editor_cursor.0 += 1;
                app.script_editor_cursor.1 = 0;
            }
            let visible_width = 80usize;
            if app.script_editor_cursor.1 >= app.script_editor_h_scroll + visible_width {
                app.script_editor_h_scroll = app.script_editor_cursor.1 - visible_width + 1;
            }
        }
        (KeyCode::Home, _) => {
            app.script_editor_cursor.1 = 0;
            app.script_editor_h_scroll = 0;
        }
        (KeyCode::End, _) => {
            let line_len = app.script_editor_lines.get(app.script_editor_cursor.0)
                .map(|l| l.len()).unwrap_or(0);
            app.script_editor_cursor.1 = line_len;
        }
        (KeyCode::PageUp, _) => {
            let jump = 20;
            app.script_editor_cursor.0 = app.script_editor_cursor.0.saturating_sub(jump);
            app.raw_script_scroll = app.raw_script_scroll.saturating_sub(jump as u16);
            let line_len = app.script_editor_lines.get(app.script_editor_cursor.0)
                .map(|l| l.len()).unwrap_or(0);
            if app.script_editor_cursor.1 > line_len {
                app.script_editor_cursor.1 = line_len;
            }
        }
        (KeyCode::PageDown, _) => {
            let jump = 20;
            app.script_editor_cursor.0 = (app.script_editor_cursor.0 + jump).min(total_lines.saturating_sub(1));
            app.raw_script_scroll = (app.raw_script_scroll + jump as u16).min(total_lines.saturating_sub(1) as u16);
            let line_len = app.script_editor_lines.get(app.script_editor_cursor.0)
                .map(|l| l.len()).unwrap_or(0);
            if app.script_editor_cursor.1 > line_len {
                app.script_editor_cursor.1 = line_len;
            }
        }

        // Editing - Enter (new line)
        (KeyCode::Enter, _) => {
            let (line_idx, col) = app.script_editor_cursor;
            if let Some(line) = app.script_editor_lines.get_mut(line_idx) {
                let remainder = line[col..].to_string();
                line.truncate(col);
                app.script_editor_lines.insert(line_idx + 1, remainder);
                app.script_editor_cursor = (line_idx + 1, 0);
                app.script_editor_modified = true;
            }
        }

        // Editing - Backspace
        (KeyCode::Backspace, _) => {
            let (line_idx, col) = app.script_editor_cursor;
            if col > 0 {
                if let Some(line) = app.script_editor_lines.get_mut(line_idx) {
                    line.remove(col - 1);
                    app.script_editor_cursor.1 -= 1;
                    app.script_editor_modified = true;
                }
            } else if line_idx > 0 {
                let current_line = app.script_editor_lines.remove(line_idx);
                if let Some(prev_line) = app.script_editor_lines.get_mut(line_idx - 1) {
                    let prev_len = prev_line.len();
                    prev_line.push_str(&current_line);
                    app.script_editor_cursor = (line_idx - 1, prev_len);
                    app.script_editor_modified = true;
                }
            }
        }

        // Editing - Delete
        (KeyCode::Delete, _) => {
            let (line_idx, col) = app.script_editor_cursor;
            if let Some(line) = app.script_editor_lines.get_mut(line_idx) {
                if col < line.len() {
                    line.remove(col);
                    app.script_editor_modified = true;
                } else if line_idx < total_lines - 1 {
                    let next_line = app.script_editor_lines.remove(line_idx + 1);
                    app.script_editor_lines.get_mut(line_idx).unwrap().push_str(&next_line);
                    app.script_editor_modified = true;
                }
            }
        }

        // Editing - Tab (insert 4 spaces)
        (KeyCode::Tab, _) => {
            let (line_idx, col) = app.script_editor_cursor;
            if let Some(line) = app.script_editor_lines.get_mut(line_idx) {
                line.insert_str(col, "    ");
                app.script_editor_cursor.1 += 4;
                app.script_editor_modified = true;
            }
        }

        // Typing characters
        (KeyCode::Char(c), m) if !m.contains(KeyModifiers::CONTROL) => {
            let (line_idx, col) = app.script_editor_cursor;
            if let Some(line) = app.script_editor_lines.get_mut(line_idx) {
                line.insert(col, c);
                app.script_editor_cursor.1 += 1;
                app.script_editor_modified = true;
            }
        }

        _ => {}
    }
    Ok(())
}

fn handle_detailed_info(app: &mut App, key: KeyEvent) -> Result<()> {
    if key.code == KeyCode::Esc {
        app.pop_screen();
    }
    Ok(())
}

fn handle_snapshots(app: &mut App, key: KeyEvent) -> Result<()> {
    match key.code {
        KeyCode::Esc => {
            app.selected_menu_item = 0; // Reset for management menu
            app.pop_screen();
        }
        KeyCode::Char('j') | KeyCode::Down => {
            if app.selected_snapshot < app.snapshots.len().saturating_sub(1) {
                app.selected_snapshot += 1;
            }
        }
        KeyCode::Char('k') | KeyCode::Up => {
            if app.selected_snapshot > 0 {
                app.selected_snapshot -= 1;
            }
        }
        KeyCode::Char('c') => {
            // Create snapshot - open text input for name
            if let Some(vm) = app.selected_vm() {
                // Warn if VM is running - snapshot operations on running VMs can cause corruption
                if app.running_vms.contains_key(&vm.id) {
                    app.set_status("Warning: VM is running. Snapshot may be inconsistent.");
                }
                // Pre-fill with timestamp-based suggestion
                app.text_input_buffer = format!("snapshot-{}", chrono::Local::now().format("%Y%m%d-%H%M%S"));
                app.push_screen(Screen::TextInput(TextInputContext::SnapshotName));
            }
        }
        KeyCode::Char('r') => {
            if let Some(snap) = app.snapshots.get(app.selected_snapshot) {
                app.push_screen(Screen::Confirm(ConfirmAction::RestoreSnapshot(snap.name.clone())));
            }
        }
        KeyCode::Char('d') => {
            if let Some(snap) = app.snapshots.get(app.selected_snapshot) {
                app.push_screen(Screen::Confirm(ConfirmAction::DeleteSnapshot(snap.name.clone())));
            }
        }
        _ => {}
    }
    Ok(())
}

fn handle_boot_options(app: &mut App, key: KeyEvent) -> Result<()> {
    use crate::app::FileBrowserMode;

    match key.code {
        KeyCode::Esc => app.pop_screen(),
        KeyCode::Char('j') | KeyCode::Down => app.menu_next(5),
        KeyCode::Char('k') | KeyCode::Up => app.menu_prev(),
        KeyCode::Enter | KeyCode::Char('1') | KeyCode::Char('2') | KeyCode::Char('3') | KeyCode::Char('4') | KeyCode::Char('5') => {
            let item = match key.code {
                KeyCode::Char('1') => 0,
                KeyCode::Char('2') => 1,
                KeyCode::Char('3') => 2,
                KeyCode::Char('4') => 3,
                KeyCode::Char('5') => 4,
                _ => app.selected_menu_item,
            };

            match item {
                0 => {
                    app.boot_mode = BootMode::Normal;
                    app.pop_screen();
                    app.push_screen(Screen::Confirm(ConfirmAction::LaunchVm));
                }
                1 => {
                    app.boot_mode = BootMode::Install;
                    app.pop_screen();
                    app.push_screen(Screen::Confirm(ConfirmAction::LaunchVm));
                }
                2 => {
                    // Open file browser for ISO selection
                    app.load_file_browser(FileBrowserMode::Iso);
                    app.push_screen(Screen::FileBrowser);
                }
                3 => {
                    // Open file browser for recovery image (DMG) selection
                    app.load_file_browser(FileBrowserMode::RecoveryImage);
                    app.push_screen(Screen::FileBrowser);
                }
                4 => {
                    // Open file browser for floppy image selection
                    app.load_file_browser(FileBrowserMode::Floppy);
                    app.push_screen(Screen::FileBrowser);
                }
                _ => {}
            }
        }
        _ => {}
    }
    Ok(())
}

fn handle_display_options(app: &mut App, key: KeyEvent) -> Result<()> {
    let display_options = screens::management::get_display_options(app);
    let option_count = display_options.len();

    match key.code {
        KeyCode::Esc => {
            app.selected_menu_item = 3; // Reset to Change Display position in management menu
            app.pop_screen();
        }
        KeyCode::Char('j') | KeyCode::Down => app.menu_next(option_count),
        KeyCode::Char('k') | KeyCode::Up => app.menu_prev(),
        KeyCode::Enter | KeyCode::Char('1') | KeyCode::Char('2') | KeyCode::Char('3') | KeyCode::Char('4') => {
            let item = match key.code {
                KeyCode::Char('1') => 0,
                KeyCode::Char('2') => 1,
                KeyCode::Char('3') => 2,
                KeyCode::Char('4') => 3,
                _ => app.selected_menu_item,
            };

            if let Some((display_name, _)) = display_options.get(item) {
                let display_name = display_name.clone();
                // Update the display setting in launch.sh
                if let Some(vm) = app.selected_vm() {
                    match update_vm_display(&vm.launch_script, &display_name) {
                        Ok(()) => {
                            // Show spice-app warning if viewer not installed
                            if display_name.contains("spice") && !crate::commands::qemu_system::is_spice_viewer_available() {
                                app.set_status(format!("Display changed to {}. Warning: virt-viewer/remote-viewer not found!", display_name));
                            } else {
                                app.set_status(format!("Display changed to {}", display_name));
                            }
                            // Reload the script to reflect changes
                            app.reload_selected_vm_script();
                        }
                        Err(e) => {
                            app.set_status(format!("Failed to change display: {}", e));
                        }
                    }
                }
                app.selected_menu_item = 3;
                app.pop_screen();
            }
        }
        _ => {}
    }
    Ok(())
}

/// Update the display setting in a VM's launch script
fn update_vm_display(script_path: &std::path::Path, new_display: &str) -> Result<()> {
    let content = std::fs::read_to_string(script_path)?;

    // Regex to match -display with optional gl=on suffix
    // Uses [\w-]+ to match hyphenated backends like spice-app
    let display_re = Regex::new(r"-display\s+([\w-]+)(,gl=on)?")?;

    let new_content = if display_re.is_match(&content) {
        // Replace existing -display setting, preserving gl=on if present
        display_re.replace_all(&content, |caps: &regex::Captures| {
            if caps.get(2).is_some() {
                format!("-display {},gl=on", new_display)
            } else {
                format!("-display {}", new_display)
            }
        }).to_string()
    } else {
        // No -display found, this shouldn't happen for wizard-generated scripts
        // but handle gracefully
        content
    };

    std::fs::write(script_path, new_content)?;
    Ok(())
}

fn handle_usb_devices(app: &mut App, key: KeyEvent) -> Result<()> {
    match key.code {
        KeyCode::Esc => {
            app.selected_menu_item = 2; // Reset to USB Passthrough position in management menu
            app.pop_screen();
        }
        KeyCode::Char('j') | KeyCode::Down => {
            app.selected_menu_item = (app.selected_menu_item + 1).min(app.usb_devices.len().saturating_sub(1));
        }
        KeyCode::Char('k') | KeyCode::Up => {
            if app.selected_menu_item > 0 {
                app.selected_menu_item -= 1;
            }
        }
        KeyCode::Char(' ') | KeyCode::Enter => {
            app.toggle_usb_device(app.selected_menu_item);
        }
        KeyCode::Char('s') | KeyCode::Char('S') => {
            // Save USB passthrough configuration to launch.sh
            let save_result = if let Some(vm) = app.selected_vm() {
                let devices: Vec<crate::vm::UsbPassthrough> = app
                    .selected_usb_devices
                    .iter()
                    .filter_map(|&i| app.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();

                let result = crate::vm::save_usb_passthrough(vm, &devices);
                Some((result, devices.len()))
            } else {
                None
            };

            if let Some((result, count)) = save_result {
                match result {
                    Ok(()) => {
                        // Reload the script so changes are visible in raw script viewer
                        app.reload_selected_vm_script();

                        let mut status_msg = if count > 0 {
                            format!("Saved {} USB device(s) to launch.sh", count)
                        } else {
                            "Cleared USB passthrough from launch.sh".to_string()
                        };

                        // Regenerate single-GPU scripts if they exist
                        // USB devices are important for single-GPU since there's no graphical session
                        if let Some(vm) = app.selected_vm() {
                            if crate::hardware::scripts_exist(&vm.path) {
                                // Try with in-memory config first, fall back to saved config
                                let regen_result = if let Some(config) = app.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)
                                };

                                match regen_result {
                                    Ok(true) => {
                                        status_msg.push_str("; single-GPU scripts regenerated");
                                    }
                                    Ok(false) => {} // Scripts don't exist, nothing to regenerate
                                    Err(e) => {
                                        status_msg.push_str(&format!("; warning: failed to regenerate single-GPU scripts: {}", e));
                                    }
                                }
                            }
                        }

                        app.set_status(status_msg);
                    }
                    Err(e) => {
                        app.set_status(format!("Error saving USB config: {}", e));
                    }
                }
            }
        }
        KeyCode::Char('u') | KeyCode::Char('U') => {
            // Install udev rules for selected USB devices
            if app.selected_usb_devices.is_empty() {
                app.set_status("Select USB devices first, then press 'u' to install permissions");
            } else {
                let selected_devices: Vec<_> = app
                    .selected_usb_devices
                    .iter()
                    .filter_map(|&i| app.usb_devices.get(i).cloned())
                    .collect();

                app.set_status("Installing udev rules (you may be prompted for your password)...");

                // We need to drop the terminal temporarily for the password prompt
                // The install function will handle elevation
                match crate::hardware::install_udev_rules(&selected_devices) {
                    crate::hardware::UdevInstallResult::Success => {
                        app.set_status("USB permissions installed! Devices should now work without sudo.");
                    }
                    crate::hardware::UdevInstallResult::NeedsReboot => {
                        app.set_status("Rules installed. Please unplug/replug devices or reboot.");
                    }
                    crate::hardware::UdevInstallResult::PermissionDenied => {
                        app.set_status("Permission denied. Authentication cancelled or failed.");
                    }
                    crate::hardware::UdevInstallResult::Error(e) => {
                        app.set_status(format!("Error installing rules: {}", e));
                    }
                }
            }
        }
        _ => {}
    }
    Ok(())
}

fn handle_confirm(app: &mut App, action: ConfirmAction, key: KeyEvent) -> Result<()> {
    match key.code {
        KeyCode::Esc | KeyCode::Char('n') => app.pop_screen(),
        KeyCode::Char('y') | KeyCode::Enter => {
            execute_confirm_action(app, action)?;
        }
        _ => {}
    }
    Ok(())
}

fn handle_help(app: &mut App, _key: KeyEvent) -> Result<()> {
    // Any key closes help
    app.pop_screen();
    Ok(())
}

fn handle_search(app: &mut App, key: KeyEvent) -> Result<()> {
    match key.code {
        KeyCode::Esc => {
            app.input_mode = InputMode::Normal;
            app.search_query.clear();
            app.update_filter();
            app.pop_screen();
        }
        KeyCode::Enter => {
            app.input_mode = InputMode::Normal;
            app.pop_screen();
        }
        KeyCode::Backspace => {
            app.search_query.pop();
            app.update_filter();
        }
        KeyCode::Char(c) => {
            app.search_query.push(c);
            app.update_filter();
        }
        _ => {}
    }
    Ok(())
}

fn render_detailed_info(app: &App, frame: &mut Frame) {
    use crate::ui::widgets::DetailedInfoWidget;

    let area = frame.area();
    let dialog_width = 60.min(area.width.saturating_sub(4));
    let dialog_height = 20.min(area.height.saturating_sub(4));

    let dialog_area = centered_rect(dialog_width, dialog_height, area);
    frame.render_widget(ratatui::widgets::Clear, dialog_area);

    let vm_name = app.selected_vm()
        .map(|vm| vm.display_name())
        .unwrap_or_else(|| "Unknown".to_string());

    let os_info = app.selected_vm_info();

    DetailedInfoWidget {
        os_info: os_info.as_ref(),
        vm_name: &vm_name,
    }
    .render(dialog_area, frame.buffer_mut());
}

fn render_confirm(app: &App, action: &ConfirmAction, frame: &mut Frame) {
    use crate::ui::widgets::ConfirmDialog;

    let (title, message) = match action {
        ConfirmAction::LaunchVm => {
            let name = app.selected_vm()
                .map(|vm| vm.display_name())
                .unwrap_or_else(|| "VM".to_string());
            ("Launch VM", format!("Launch {}?", name))
        }
        ConfirmAction::ResetVm => {
            ("Reset VM", "This will reset the VM to its initial state. All changes will be lost. Continue?".to_string())
        }
        ConfirmAction::DeleteVm => {
            let name = app.selected_vm()
                .map(|vm| vm.display_name())
                .unwrap_or_else(|| "VM".to_string());
            ("Delete VM", format!("Delete {}? This will move the VM to trash.", name))
        }
        ConfirmAction::RestoreSnapshot(name) => {
            ("Restore Snapshot", format!("Restore snapshot '{}'? Current state will be lost.", name))
        }
        ConfirmAction::DeleteSnapshot(name) => {
            ("Delete Snapshot", format!("Delete snapshot '{}'? This cannot be undone.", name))
        }
        ConfirmAction::DiscardScriptChanges | ConfirmAction::DiscardNotesChanges => {
            ("Discard Changes", "You have unsaved changes. Discard them?".to_string())
        }
        ConfirmAction::StopVm => {
            let name = app.selected_vm()
                .map(|vm| vm.display_name())
                .unwrap_or_else(|| "VM".to_string());
            ("Stop VM", format!("Stop {}?", name))
        }
        ConfirmAction::ForceStopVm => {
            let name = app.selected_vm()
                .map(|vm| vm.display_name())
                .unwrap_or_else(|| "VM".to_string());
            ("Force Stop VM", format!("Force stop {}? This may cause data loss.", name))
        }
    };

    ConfirmDialog::new(title, &message).render(frame.area(), frame.buffer_mut());
}

fn render_usb_devices(app: &App, frame: &mut Frame) {
    use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph};
    use ratatui::layout::{Layout, Direction, Constraint};

    let area = frame.area();
    let dialog_width = 80.min(area.width.saturating_sub(4));
    let dialog_height = 20.min(area.height.saturating_sub(4));

    let dialog_area = centered_rect(dialog_width, dialog_height, area);
    frame.render_widget(Clear, dialog_area);

    let selected_count = app.selected_usb_devices.len();
    let title = if selected_count > 0 {
        format!(" USB Passthrough ({} selected) ", selected_count)
    } else {
        " USB Passthrough ".to_string()
    };

    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan))
        .style(Style::default().bg(Color::Black));

    let inner = block.inner(dialog_area);
    frame.render_widget(block, dialog_area);

    // Add horizontal margins
    let h_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Length(2),  // Left margin
            Constraint::Min(1),     // Content
            Constraint::Length(2),  // Right margin
        ])
        .split(inner);

    // Split into padding, content, and help
    let v_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),  // Top padding
            Constraint::Min(4),     // Device list
            Constraint::Length(2),  // Help text
        ])
        .split(h_chunks[1]);

    let content_area = v_chunks[1];
    let help_area = v_chunks[2];

    if app.usb_devices.is_empty() {
        let msg = Paragraph::new("No USB devices found.\n\nConnect a USB device and reopen this screen.")
            .style(Style::default().fg(Color::DarkGray))
            .alignment(Alignment::Center);
        frame.render_widget(msg, content_area);
    } else {
        let items: Vec<ListItem> = app.usb_devices
            .iter()
            .enumerate()
            .map(|(i, device)| {
                let selected = app.selected_usb_devices.contains(&i);
                let checkbox = if selected { "[✓]" } else { "[ ]" };
                let style = if i == app.selected_menu_item {
                    Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)
                } else if selected {
                    Style::default().fg(Color::Green)
                } else {
                    Style::default().fg(Color::White)
                };

                ListItem::new(format!(
                    "{} {} ({:04x}:{:04x})",
                    checkbox,
                    device.display_name(),
                    device.vendor_id,
                    device.product_id
                ))
                .style(style)
            })
            .collect();

        let mut state = ListState::default();
        state.select(Some(app.selected_menu_item));

        let list = List::new(items)
            .highlight_symbol("> ");
        frame.render_stateful_widget(list, content_area, &mut state);
    }

    // Help text
    let help = Paragraph::new("[Space] Toggle  [s] Save  [u] Install USB permissions  [Esc] Back")
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Center);
    frame.render_widget(help, help_area);
}

fn render_search(app: &App, frame: &mut Frame) {
    use ratatui::widgets::{Block, Borders, Clear, Paragraph};

    let area = frame.area();
    let dialog_width = 40.min(area.width.saturating_sub(4));
    let dialog_height = 5;

    let dialog_area = centered_rect(dialog_width, dialog_height, area);
    frame.render_widget(Clear, dialog_area);

    let block = Block::default()
        .title(" Search ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan))
        .style(Style::default().bg(Color::Black));

    let inner = block.inner(dialog_area);
    frame.render_widget(block, dialog_area);

    let input = Paragraph::new(format!("/{}", app.search_query))
        .style(Style::default().fg(Color::White));
    frame.render_widget(input, inner);
}

fn render_file_browser(app: &App, frame: &mut Frame) {
    use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState};
    use ratatui::layout::{Layout, Direction, Constraint};
    use crate::app::FileBrowserMode;

    let area = frame.area();
    let dialog_width = 60.min(area.width.saturating_sub(4));
    let dialog_height = 20.min(area.height.saturating_sub(4));

    let dialog_area = centered_rect(dialog_width, dialog_height, area);
    frame.render_widget(Clear, dialog_area);

    let title_prefix = match app.file_browser_mode {
        FileBrowserMode::Iso => "Select ISO",
        FileBrowserMode::RecoveryImage => "Select Recovery Image",
        FileBrowserMode::Disk => "Select Disk Image",
        FileBrowserMode::Directory => "Select Directory",
        FileBrowserMode::ImportConfig => "Select Config File",
        FileBrowserMode::Bios => "Select BIOS/ROM File",
        FileBrowserMode::Floppy => "Select Floppy Image",
    };
    let title = format!(" {} - {} ", title_prefix, app.file_browser_dir.display());
    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan))
        .style(Style::default().bg(Color::Black));

    let inner = block.inner(dialog_area);
    frame.render_widget(block, dialog_area);

    // Add horizontal margins
    let h_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Length(2),  // Left margin
            Constraint::Min(1),     // Content
            Constraint::Length(2),  // Right margin
        ])
        .split(inner);

    // Add top padding
    let v_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),  // Top padding
            Constraint::Min(1),     // Content
        ])
        .split(h_chunks[1]);

    let content_area = v_chunks[1];

    if app.file_browser_entries.is_empty() {
        let msg_text = match app.file_browser_mode {
            FileBrowserMode::Iso => "No ISO files found in this directory.",
            FileBrowserMode::RecoveryImage => "No recovery images (.dmg, .qcow2) found in this directory.",
            FileBrowserMode::Disk => "No disk images found in this directory.",
            FileBrowserMode::Directory => "No subdirectories in this directory.",
            FileBrowserMode::ImportConfig => "No config files (.xml, .conf) found in this directory.",
            FileBrowserMode::Bios => "No firmware files (.bin, .rom, .qcow2, .fd) found in this directory.",
            FileBrowserMode::Floppy => "No floppy images (.img, .ima, .flp, .vfd) found in this directory.",
        };
        let msg = ratatui::widgets::Paragraph::new(msg_text)
            .style(Style::default().fg(Color::DarkGray))
            .alignment(Alignment::Center);
        frame.render_widget(msg, content_area);
        return;
    }

    let items: Vec<ListItem> = app.file_browser_entries
        .iter()
        .map(|entry| {
            let prefix = if entry.name == "[Select This Directory]" {
                ">> "
            } else if entry.is_dir {
                "📁 "
            } else {
                "💿 "
            };
            ListItem::new(format!("{}{}", prefix, entry.name))
        })
        .collect();

    let mut state = ListState::default();
    state.select(Some(app.file_browser_selected));

    let list = List::new(items)
        .highlight_style(
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD)
                .bg(Color::DarkGray),
        )
        .highlight_symbol("> ");
    frame.render_stateful_widget(list, content_area, &mut state);
}

fn handle_file_browser(app: &mut App, key: KeyEvent) -> Result<()> {
    use crate::app::FileBrowserMode;

    match key.code {
        KeyCode::Esc => app.pop_screen(),
        KeyCode::Char('j') | KeyCode::Down => app.file_browser_next(),
        KeyCode::Char('k') | KeyCode::Up => app.file_browser_prev(),
        KeyCode::Enter => {
            if let Some(selected_path) = app.file_browser_enter() {
                match app.file_browser_mode {
                    FileBrowserMode::Iso => {
                        // Check if we're in wizard mode
                        if app.wizard_state.is_some() {
                            // Set the ISO path in wizard state
                            if let Some(ref mut state) = app.wizard_state {
                                state.iso_path = Some(selected_path);
                                state.is_recovery_image = false;
                            }
                            app.pop_screen(); // Close file browser

                            // Proceed to next step
                            let _ = app.wizard_next_step();
                        } else {
                            // Normal boot mode - selected an ISO file
                            app.boot_mode = BootMode::Cdrom(selected_path);
                            app.pop_screen(); // Close file browser
                            app.pop_screen(); // Close boot options
                            app.push_screen(Screen::Confirm(ConfirmAction::LaunchVm));
                        }
                    }
                    FileBrowserMode::RecoveryImage => {
                        if app.wizard_state.is_some() {
                            if let Some(ref mut state) = app.wizard_state {
                                state.iso_path = Some(selected_path);
                                state.is_recovery_image = true;
                            }
                            app.pop_screen();
                            let _ = app.wizard_next_step();
                        } else {
                            // Boot options mode
                            app.boot_mode = BootMode::Recovery(selected_path);
                            app.pop_screen(); // Close file browser
                            app.pop_screen(); // Close boot options
                            app.push_screen(Screen::Confirm(ConfirmAction::LaunchVm));
                        }
                    }
                    FileBrowserMode::Disk => {
                        // Selected a disk file - must be in wizard mode
                        if let Some(ref mut state) = app.wizard_state {
                            state.existing_disk_path = Some(selected_path);
                        }
                        app.pop_screen(); // Close file browser, return to disk config step
                    }
                    FileBrowserMode::Bios => {
                        // Selected a ROM/BIOS file - must be in wizard mode
                        if let Some(ref mut state) = app.wizard_state {
                            state.bios_rom_path = Some(selected_path.clone());
                            state.qemu_config.bios_path = Some(selected_path);
                        }
                        app.pop_screen(); // Close file browser, return to ISO step
                    }
                    FileBrowserMode::Floppy => {
                        if app.wizard_state.is_some() {
                            if let Some(ref mut state) = app.wizard_state {
                                state.floppy_path = Some(selected_path);
                            }
                            app.pop_screen(); // Close file browser, return to ISO step (don't advance)
                        } else {
                            // Boot options mode
                            app.boot_mode = BootMode::Floppy(selected_path);
                            app.pop_screen(); // Close file browser
                            app.pop_screen(); // Close boot options
                            app.push_screen(Screen::Confirm(ConfirmAction::LaunchVm));
                        }
                    }
                    FileBrowserMode::Directory => {
                        // Directory selected (from [Select This Directory] entry)
                        app.add_shared_folder(selected_path.to_string_lossy().to_string());
                        app.pop_screen(); // Return to SharedFolders screen
                    }
                    FileBrowserMode::ImportConfig => {
                        // Selected a config file for import
                        match crate::vm::import::parse_config_file(&selected_path) {
                            Ok(vm) => {
                                app.pop_screen(); // Close file browser

                                let library_path = app.config.vm_library_path.clone();
                                if let Some(ref mut state) = app.import_state {
                                    state.vm_name = vm.name.clone();
                                    state.folder_name =
                                        crate::app::CreateWizardState::find_available_folder_name(
                                            &library_path,
                                            &crate::app::CreateWizardState::generate_folder_name(&vm.name),
                                        );
                                    let has_notes = !vm.import_notes.is_empty();
                                    state.selected_vm = Some(vm);
                                    state.error_message = None;
                                    state.field_focus = 0;

                                    if has_notes {
                                        state.warnings_acknowledged = false;
                                        state.step = crate::app::ImportStep::CompatibilityWarnings;
                                    } else {
                                        state.warnings_acknowledged = true;
                                        state.step = crate::app::ImportStep::ConfigureDisk;
                                    }
                                } else {
                                    // No import state - start fresh
                                    let has_notes = !vm.import_notes.is_empty();
                                    let source = vm.source.clone();
                                    let folder_name =
                                        crate::app::CreateWizardState::find_available_folder_name(
                                            &library_path,
                                            &crate::app::CreateWizardState::generate_folder_name(&vm.name),
                                        );
                                    let vm_name = vm.name.clone();
                                    let (step, warnings_acknowledged) = if has_notes {
                                        (crate::app::ImportStep::CompatibilityWarnings, false)
                                    } else {
                                        (crate::app::ImportStep::ConfigureDisk, true)
                                    };

                                    app.import_state = Some(crate::app::ImportWizardState {
                                        source: Some(source),
                                        vm_name,
                                        folder_name,
                                        selected_vm: Some(vm),
                                        step,
                                        warnings_acknowledged,
                                        ..crate::app::ImportWizardState::default()
                                    });
                                    app.push_screen(crate::app::Screen::ImportWizard);
                                }
                            }
                            Err(e) => {
                                if let Some(ref mut state) = app.import_state {
                                    state.error_message = Some(format!("Failed to parse: {}", e));
                                }
                                app.pop_screen(); // Close file browser
                            }
                        }
                    }
                }
            }
            // If it was a directory, file_browser_enter already navigated
        }
        _ => {}
    }
    Ok(())
}

fn render_text_input(app: &App, context: &TextInputContext, frame: &mut Frame) {
    use ratatui::widgets::{Block, Borders, Clear, Paragraph};

    let title = match context {
        TextInputContext::SnapshotName => " Enter Snapshot Name ",
        TextInputContext::RenameVm => " Enter New VM Name ",
    };

    let area = frame.area();
    let dialog_width = 50.min(area.width.saturating_sub(4));
    let dialog_height = 5;

    let dialog_area = centered_rect(dialog_width, dialog_height, area);
    frame.render_widget(Clear, dialog_area);

    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan))
        .style(Style::default().bg(Color::Black));

    let inner = block.inner(dialog_area);
    frame.render_widget(block, dialog_area);

    let input = Paragraph::new(format!("{}_", app.text_input_buffer))
        .style(Style::default().fg(Color::White));
    frame.render_widget(input, inner);
}

fn handle_text_input(app: &mut App, context: TextInputContext, key: KeyEvent) -> Result<()> {
    match key.code {
        KeyCode::Esc => {
            app.text_input_buffer.clear();
            app.pop_screen();
        }
        KeyCode::Enter => {
            let input = app.text_input_buffer.clone();
            app.text_input_buffer.clear();
            app.pop_screen();

            match context {
                TextInputContext::SnapshotName => {
                    if !input.is_empty() {
                        if let Some(vm) = app.selected_vm() {
                            if let Some(disk) = vm.config.primary_disk() {
                                // Spawn background thread for snapshot creation
                                let disk_path = disk.path.clone();
                                let name = input.clone();
                                let tx = app.background_tx.clone();
                                app.loading = true;
                                app.set_status(format!("Creating snapshot: {}...", name));

                                thread::spawn(move || {
                                    let result = crate::vm::create_snapshot(&disk_path, &name);
                                    let _ = tx.send(BackgroundResult::SnapshotCreated {
                                        name,
                                        success: result.is_ok(),
                                        error: result.err().map(|e| e.to_string()),
                                    });
                                });
                            }
                        }
                    }
                }
                TextInputContext::RenameVm => {
                    if !input.is_empty() {
                        if let Some(vm) = app.selected_vm().cloned() {
                            match crate::vm::lifecycle::rename_vm(&vm, &input) {
                                Ok(()) => {
                                    app.set_status(format!("Renamed to: {}", input));
                                    // Refresh to pick up the new name
                                    let _ = app.refresh_vms();
                                }
                                Err(e) => {
                                    app.set_status(format!("Error renaming: {}", e));
                                }
                            }
                        }
                    }
                }
            }
        }
        KeyCode::Backspace => {
            app.text_input_buffer.pop();
        }
        KeyCode::Char(c) => {
            // Allow different characters based on context
            let allowed = match context {
                TextInputContext::SnapshotName => {
                    // Only safe characters for snapshot names
                    c.is_alphanumeric() || c == '-' || c == '_' || c == '.'
                }
                TextInputContext::RenameVm => {
                    // Allow more characters for VM display names
                    c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == ' ' || c == '(' || c == ')'
                }
            };
            if allowed {
                app.text_input_buffer.push(c);
            }
        }
        _ => {}
    }
    Ok(())
}

fn render_error_dialog(app: &App, frame: &mut Frame) {
    use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};

    let area = frame.area();
    // Make error dialog larger and more prominent
    let dialog_width = 80.min(area.width.saturating_sub(4));
    let dialog_height = 20.min(area.height.saturating_sub(4));

    let dialog_area = centered_rect(dialog_width, dialog_height, area);
    frame.render_widget(Clear, dialog_area);

    let block = Block::default()
        .title(" ⚠ Error ")
        .title_bottom(" [↑/↓ or j/k] Scroll  [Enter/Esc] Close ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Red).add_modifier(Modifier::BOLD))
        .style(Style::default().bg(Color::Black));

    let inner = block.inner(dialog_area);
    frame.render_widget(block, dialog_area);

    let error_text = app.error_detail.as_deref().unwrap_or("No error details");

    // Add visual separator and formatting
    let formatted_error = format!("{}\n\n─────────────────────────────────────────\nCheck the QEMU configuration or launch.sh script for issues.", error_text);

    let paragraph = Paragraph::new(formatted_error)
        .style(Style::default().fg(Color::White))
        .wrap(Wrap { trim: false })
        .scroll((app.error_scroll, 0));
    frame.render_widget(paragraph, inner);
}

fn handle_error_dialog(app: &mut App, key: KeyEvent) -> Result<()> {
    match key.code {
        KeyCode::Esc | KeyCode::Enter => {
            app.error_detail = None;
            app.error_scroll = 0;
            app.pop_screen();
        }
        KeyCode::Char('j') | KeyCode::Down => {
            app.error_scroll = app.error_scroll.saturating_add(1);
        }
        KeyCode::Char('k') | KeyCode::Up => {
            app.error_scroll = app.error_scroll.saturating_sub(1);
        }
        _ => {}
    }
    Ok(())
}

fn handle_single_gpu_instructions(app: &mut App, key: KeyEvent) -> Result<()> {
    match key.code {
        KeyCode::Esc | KeyCode::Enter => {
            app.single_gpu_show_instructions = false;
            app.pop_screen();
        }
        _ => {}
    }
    Ok(())
}

fn centered_rect(width: u16, height: u16, area: Rect) -> Rect {
    let x = area.x + (area.width.saturating_sub(width)) / 2;
    let y = area.y + (area.height.saturating_sub(height)) / 2;
    Rect::new(x, y, width, height)
}