vm-curator 0.4.9

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
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
//! VM Creation Wizard screens
//!
//! A 5-step wizard for creating new VMs with OS-specific QEMU defaults.

use anyhow::Result;
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    prelude::*,
    widgets::{Block, Borders, Clear, Paragraph, Wrap},
};

use crate::app::{App, WizardStep, WizardField, WizardQemuConfig};
use crate::metadata::QemuProfileStore;
use crate::vm::create_vm;

/// Parse a size string with optional suffix (KB, MB, GB, case-insensitive)
/// Returns value normalized to target unit.
///
/// For memory (target="MB"): "8GB" -> 8192, "8192" -> 8192
/// For disk (target="GB"): "500GB" -> 500, "512000MB" -> 500
fn parse_size_with_suffix(input: &str, target_unit: &str) -> Option<u32> {
    let input = input.trim().to_uppercase();
    if input.is_empty() {
        return None;
    }

    let (num_str, suffix) = if input.ends_with("GB") {
        (&input[..input.len()-2], "GB")
    } else if input.ends_with("MB") {
        (&input[..input.len()-2], "MB")
    } else if input.ends_with("KB") {
        (&input[..input.len()-2], "KB")
    } else {
        (input.as_str(), target_unit)
    };

    let value: f64 = num_str.trim().parse().ok()?;
    if value < 0.0 {
        return None;
    }

    let result = match (suffix, target_unit) {
        ("GB", "MB") => value * 1024.0,
        ("MB", "MB") => value,
        ("KB", "MB") => value / 1024.0,
        ("GB", "GB") => value,
        ("MB", "GB") => value / 1024.0,
        ("KB", "GB") => value / (1024.0 * 1024.0),
        _ => value,
    };

    if result >= 0.0 && result <= u32::MAX as f64 {
        Some(result.round() as u32)
    } else {
        None
    }
}

/// Render the create wizard based on current step
pub fn render(app: &App, frame: &mut Frame) {
    let area = frame.area();

    // Wizard dialog size
    let dialog_width = 80.min(area.width.saturating_sub(4));
    let dialog_height = 40.min(area.height.saturating_sub(4));

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

    let Some(ref state) = app.wizard_state else {
        return;
    };

    // Render the appropriate step
    match state.step {
        WizardStep::SelectOs => render_step_select_os(app, frame, dialog_area),
        WizardStep::SelectIso => render_step_select_iso(app, frame, dialog_area),
        WizardStep::ConfigureDisk => render_step_configure_disk(app, frame, dialog_area),
        WizardStep::ConfigureQemu => render_step_configure_qemu(app, frame, dialog_area),
        WizardStep::Confirm => render_step_confirm(app, frame, dialog_area),
    }

    // Port-forward editor draws on top of step 4 when active.
    if app.wizard_editing_port_forwards {
        render_wizard_port_forward_editor(app, frame, dialog_area);
    }
}

/// Render custom OS entry form
pub fn render_custom_os(app: &App, frame: &mut Frame) {
    let area = frame.area();
    let dialog_width = 70.min(area.width.saturating_sub(4));
    let dialog_height = 28.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(" Custom OS Entry ")
        .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 Some(ref state) = app.wizard_state else {
        return;
    };

    let custom_os = state.custom_os.as_ref();

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([
            Constraint::Length(1),   // Intro text
            Constraint::Length(1),   // Spacer
            Constraint::Length(3),   // OS Name
            Constraint::Length(3),   // Publisher
            Constraint::Length(3),   // Architecture
            Constraint::Length(1),   // Spacer
            Constraint::Length(5),   // Base profile selection
            Constraint::Length(1),   // Spacer
            Constraint::Min(3),      // Tips
            Constraint::Length(2),   // Help
        ])
        .split(inner);

    // Intro text
    let intro = Paragraph::new("Define your custom operating system:")
        .style(Style::default().fg(Color::Yellow));
    frame.render_widget(intro, chunks[0]);

    // OS Name input
    let os_name = custom_os.map(|c| c.name.as_str()).unwrap_or("");
    let name_focus = state.field_focus == 0;
    let name_editing = matches!(state.editing_field, Some(WizardField::CustomOsName));

    render_input_field(
        frame, chunks[2],
        "OS Name",
        if os_name.is_empty() { "e.g., My Custom Linux" } else { os_name },
        os_name.is_empty(),
        name_focus,
        name_editing,
    );

    if name_editing {
        let cursor_x = chunks[2].x + 1 + os_name.len() as u16;
        let cursor_y = chunks[2].y + 1;
        frame.set_cursor_position((cursor_x, cursor_y));
    }

    // Publisher input
    let publisher = custom_os.map(|c| c.publisher.as_str()).unwrap_or("");
    let pub_focus = state.field_focus == 1;
    let pub_editing = matches!(state.editing_field, Some(WizardField::CustomOsPublisher));

    render_input_field(
        frame, chunks[3],
        "Publisher",
        if publisher.is_empty() { "e.g., Open Source Community" } else { publisher },
        publisher.is_empty(),
        pub_focus,
        pub_editing,
    );

    if pub_editing {
        let cursor_x = chunks[3].x + 1 + publisher.len() as u16;
        let cursor_y = chunks[3].y + 1;
        frame.set_cursor_position((cursor_x, cursor_y));
    }

    // Architecture selection (cycle)
    let arch = custom_os.map(|c| c.architecture.as_str()).unwrap_or("x86_64");
    let arch_focus = state.field_focus == 2;
    render_select_field(
        frame, chunks[4],
        "Architecture",
        arch,
        arch_focus,
        "[←/→] to change",
    );

    // Base profile selection
    let base_profile = custom_os.map(|c| c.base_profile.as_str()).unwrap_or("generic-other");
    let base_focus = state.field_focus == 3;

    let base_block = Block::default()
        .title(" Base QEMU Profile ")
        .borders(Borders::ALL)
        .border_style(if base_focus {
            Style::default().fg(Color::Yellow)
        } else {
            Style::default().fg(Color::Gray)
        });

    let base_inner = base_block.inner(chunks[6]);
    frame.render_widget(base_block, chunks[6]);

    let base_display = get_base_profile_display(base_profile);
    let mut base_lines = Vec::new();
    base_lines.push(Line::from(vec![
        Span::styled("Profile: ", Style::default().fg(Color::Yellow)),
        Span::styled(base_display, if base_focus { Style::default().fg(Color::White).add_modifier(Modifier::BOLD) } else { Style::default().fg(Color::White) }),
    ]));
    base_lines.push(Line::from(Span::styled(
        if base_focus { "[←/→] Change profile" } else { "" },
        Style::default().fg(Color::DarkGray),
    )));

    let base_text = Paragraph::new(base_lines);
    frame.render_widget(base_text, base_inner);

    // Tips
    let tips_block = Block::default()
        .title(" Tip ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::DarkGray));

    let tips_inner = tips_block.inner(chunks[8]);
    frame.render_widget(tips_block, chunks[8]);

    let tips_text = Paragraph::new(
        "You can adjust QEMU settings in step 4.\n\
         Consider contributing new OS profiles to the project!"
    )
    .style(Style::default().fg(Color::DarkGray))
    .wrap(Wrap { trim: false });
    frame.render_widget(tips_text, tips_inner);

    // Help
    let help = Paragraph::new("[Tab] Next field  [Enter] Continue  [Esc] Cancel")
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Center);
    frame.render_widget(help, chunks[9]);
}

fn render_input_field(
    frame: &mut Frame,
    area: Rect,
    label: &str,
    value: &str,
    is_placeholder: bool,
    is_focused: bool,
    is_editing: bool,
) {
    let border_style = if is_editing {
        Style::default().fg(Color::Yellow)
    } else if is_focused {
        Style::default().fg(Color::Cyan)
    } else {
        Style::default().fg(Color::Gray)
    };

    let block = Block::default()
        .title(format!(" {} ", label))
        .borders(Borders::ALL)
        .border_style(border_style);

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

    let text_style = if is_placeholder {
        Style::default().fg(Color::DarkGray)
    } else if is_editing {
        Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::White)
    };

    let text = Paragraph::new(value).style(text_style);
    frame.render_widget(text, inner);
}

fn render_select_field(
    frame: &mut Frame,
    area: Rect,
    label: &str,
    value: &str,
    is_focused: bool,
    hint: &str,
) {
    let border_style = if is_focused {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::Gray)
    };

    let block = Block::default()
        .title(format!(" {} ", label))
        .borders(Borders::ALL)
        .border_style(border_style);

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

    let mut spans = vec![
        Span::styled(value, if is_focused {
            Style::default().fg(Color::White).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::White)
        }),
    ];

    if is_focused {
        spans.push(Span::raw("  "));
        spans.push(Span::styled(hint, Style::default().fg(Color::DarkGray)));
    }

    let text = Paragraph::new(Line::from(spans));
    frame.render_widget(text, inner);
}

fn get_base_profile_display(profile_id: &str) -> &'static str {
    match profile_id {
        "generic-linux" => "Generic Linux (modern, virtio)",
        "generic-windows" => "Generic Windows (SATA, e1000)",
        "generic-bsd" => "Generic BSD (IDE, pcnet)",
        "linux-debian" => "Debian-based Linux",
        "linux-fedora" => "Fedora/RHEL-based Linux",
        "linux-arch" => "Arch Linux",
        _ => "Generic (safe defaults)",
    }
}

const ARCH_OPTIONS: &[&str] = &["x86_64", "i386", "arm64", "ppc64", "mips64", "riscv64"];
const BASE_PROFILE_OPTIONS: &[&str] = &[
    "generic-other",
    "generic-linux",
    "generic-windows",
    "generic-bsd",
    "linux-debian",
    "linux-fedora",
    "linux-arch",
];

/// Render ISO download progress
pub fn render_download(app: &App, frame: &mut Frame) {
    let area = frame.area();
    let dialog_width = 60.min(area.width.saturating_sub(4));
    let dialog_height = 10.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(" Downloading ISO ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Yellow))
        .style(Style::default().bg(Color::Black));

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

    let progress = app.wizard_state.as_ref()
        .map(|s| s.iso_download_progress)
        .unwrap_or(0.0);

    let text = Paragraph::new(format!("Downloading... {:.0}%\n\n[Esc] Cancel", progress * 100.0))
        .style(Style::default().fg(Color::White))
        .alignment(Alignment::Center);
    frame.render_widget(text, inner);
}

/// Handle key input for wizard
pub fn handle_key(app: &mut App, key: KeyEvent) -> Result<()> {
    let Some(ref state) = app.wizard_state else {
        return Ok(());
    };

    // Handle step-specific keys
    match state.step {
        WizardStep::SelectOs => handle_step_select_os(app, key),
        WizardStep::SelectIso => handle_step_select_iso(app, key),
        WizardStep::ConfigureDisk => handle_step_configure_disk(app, key),
        WizardStep::ConfigureQemu => handle_step_configure_qemu(app, key),
        WizardStep::Confirm => handle_step_confirm(app, key),
    }
}

/// Handle key input for custom OS form
pub fn handle_custom_os_key(app: &mut App, key: KeyEvent) -> Result<()> {
    let editing = app.wizard_state.as_ref()
        .map(|s| s.editing_field.is_some())
        .unwrap_or(false);

    if editing {
        // Text input mode
        match key.code {
            KeyCode::Esc | KeyCode::Enter | KeyCode::Tab => {
                if let Some(ref mut state) = app.wizard_state {
                    state.editing_field = None;
                    if key.code == KeyCode::Tab {
                        // Move to next field
                        state.field_focus = (state.field_focus + 1) % 4;
                    }
                }
            }
            KeyCode::Char(c) => {
                if let Some(ref mut state) = app.wizard_state {
                    if let Some(ref mut custom) = state.custom_os {
                        match state.editing_field {
                            Some(WizardField::CustomOsName) => custom.name.push(c),
                            Some(WizardField::CustomOsPublisher) => custom.publisher.push(c),
                            _ => {}
                        }
                    }
                }
            }
            KeyCode::Backspace => {
                if let Some(ref mut state) = app.wizard_state {
                    if let Some(ref mut custom) = state.custom_os {
                        match state.editing_field {
                            Some(WizardField::CustomOsName) => { custom.name.pop(); }
                            Some(WizardField::CustomOsPublisher) => { custom.publisher.pop(); }
                            _ => {}
                        }
                    }
                }
            }
            _ => {}
        }
    } else {
        // Navigation mode
        match key.code {
            KeyCode::Esc => {
                // Cancel custom OS and return to wizard
                if let Some(ref mut state) = app.wizard_state {
                    state.custom_os = None;
                }
                app.pop_screen();
            }
            KeyCode::Tab | KeyCode::Char('j') | KeyCode::Down => {
                if let Some(ref mut state) = app.wizard_state {
                    state.field_focus = (state.field_focus + 1) % 4;
                }
            }
            KeyCode::BackTab | KeyCode::Char('k') | KeyCode::Up => {
                if let Some(ref mut state) = app.wizard_state {
                    state.field_focus = if state.field_focus == 0 { 3 } else { state.field_focus - 1 };
                }
            }
            KeyCode::Left | KeyCode::Right => {
                let delta = if key.code == KeyCode::Right { 1i32 } else { -1i32 };
                if let Some(ref mut state) = app.wizard_state {
                    if let Some(ref mut custom) = state.custom_os {
                        match state.field_focus {
                            2 => {
                                // Architecture
                                let current_idx = ARCH_OPTIONS.iter()
                                    .position(|&a| a == custom.architecture)
                                    .unwrap_or(0);
                                let new_idx = (current_idx as i32 + delta)
                                    .rem_euclid(ARCH_OPTIONS.len() as i32) as usize;
                                custom.architecture = ARCH_OPTIONS[new_idx].to_string();
                            }
                            3 => {
                                // Base profile
                                let current_idx = BASE_PROFILE_OPTIONS.iter()
                                    .position(|&p| p == custom.base_profile)
                                    .unwrap_or(0);
                                let new_idx = (current_idx as i32 + delta)
                                    .rem_euclid(BASE_PROFILE_OPTIONS.len() as i32) as usize;
                                custom.base_profile = BASE_PROFILE_OPTIONS[new_idx].to_string();
                            }
                            _ => {}
                        }
                    }
                }
            }
            KeyCode::Char(' ') => {
                // Enter edit mode for text fields
                if let Some(ref mut state) = app.wizard_state {
                    match state.field_focus {
                        0 => state.editing_field = Some(WizardField::CustomOsName),
                        1 => state.editing_field = Some(WizardField::CustomOsPublisher),
                        _ => {}
                    }
                }
            }
            KeyCode::Enter => {
                // Validate and continue
                let valid = app.wizard_state.as_ref()
                    .and_then(|s| s.custom_os.as_ref())
                    .map(|c| !c.name.trim().is_empty())
                    .unwrap_or(false);

                if valid {
                    // Extract needed data first
                    let (base_profile_id, custom_name, vm_name_empty) = {
                        let state = app.wizard_state.as_ref().unwrap();
                        let custom = state.custom_os.as_ref().unwrap();
                        (
                            custom.base_profile.clone(),
                            custom.name.clone(),
                            state.vm_name.is_empty(),
                        )
                    };

                    // Get profile settings
                    let profile_settings = app.qemu_profiles.get(&base_profile_id).cloned();

                    // Now apply changes
                    if let Some(ref mut state) = app.wizard_state {
                        // Apply profile settings
                        if let Some(profile) = profile_settings {
                            state.qemu_config = WizardQemuConfig::from_profile(&profile);
                            state.disk_size_gb = profile.disk_size_gb;
                        }

                        // Set VM name if empty
                        if vm_name_empty {
                            state.vm_name = custom_name.clone();
                            state.update_folder_name(&app.config.vm_library_path);
                        }

                        // Generate ID from name
                        let id = custom_name.to_lowercase()
                            .chars()
                            .map(|c| if c.is_alphanumeric() { c } else { '-' })
                            .collect::<String>()
                            .split('-')
                            .filter(|s| !s.is_empty())
                            .collect::<Vec<_>>()
                            .join("-");

                        if let Some(ref mut custom) = state.custom_os {
                            custom.id = id;
                        }
                    }

                    app.pop_screen(); // Return to wizard
                } else if let Some(ref mut state) = app.wizard_state {
                    state.error_message = Some("Please enter an OS name".to_string());
                }
            }
            _ => {}
        }
    }
    Ok(())
}

/// Handle key input for download screen
pub fn handle_download_key(app: &mut App, key: KeyEvent) -> Result<()> {
    if key.code == KeyCode::Esc {
        // Cancel download
        if let Some(ref mut state) = app.wizard_state {
            state.iso_downloading = false;
            state.iso_download_progress = 0.0;
        }
        app.pop_screen();
    }
    Ok(())
}

// =============================================================================
// Step 1: Select OS
// =============================================================================

fn render_step_select_os(app: &App, frame: &mut Frame, area: Rect) {
    let state = app.wizard_state.as_ref().unwrap();

    let block = Block::default()
        .title(format!(" Create New VM ({}/5) - {} ", state.step.number(), state.step.title()))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan))
        .style(Style::default().bg(Color::Black));

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

    // Layout: OS list first, then VM name field below
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([
            Constraint::Length(1),   // OS list header
            Constraint::Min(10),     // OS list
            Constraint::Length(1),   // Spacer
            Constraint::Length(3),   // VM Name field
            Constraint::Length(1),   // Error message
            Constraint::Length(2),   // Help text
        ])
        .split(inner);

    // OS list header
    let header = Paragraph::new("Select Operating System:")
        .style(Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD));
    frame.render_widget(header, chunks[0]);

    // OS list (grouped by category)
    render_os_list(app, frame, chunks[1]);

    // VM Name input (below OS list)
    let name_editing = matches!(state.editing_field, Some(WizardField::VmName));
    let name_style = if name_editing {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::White)
    };
    let name_border = if name_editing {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::Gray)
    };

    let name_block = Block::default()
        .title(" VM Name (Tab to edit) ")
        .borders(Borders::ALL)
        .border_style(name_border);

    let name_text = if state.vm_name.is_empty() {
        Paragraph::new("Select an OS above...")
            .style(Style::default().fg(Color::DarkGray))
            .block(name_block)
    } else {
        Paragraph::new(state.vm_name.as_str())
            .style(name_style)
            .block(name_block)
    };
    frame.render_widget(name_text, chunks[3]);

    // Set cursor position when editing
    if name_editing {
        let cursor_x = chunks[3].x + 1 + state.vm_name.len() as u16;
        let cursor_y = chunks[3].y + 1;
        frame.set_cursor_position((cursor_x, cursor_y));
    }

    // Error message
    if let Some(ref error) = state.error_message {
        let error_text = Paragraph::new(error.as_str())
            .style(Style::default().fg(Color::Red));
        frame.render_widget(error_text, chunks[4]);
    }

    // Help text
    let help_text = if name_editing {
        "[Enter] Done editing  [Esc] Cancel"
    } else {
        "[j/k] Select OS  [Tab] Edit name  [Enter] Next  [Esc] Cancel"
    };
    let help = Paragraph::new(help_text)
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Center);
    frame.render_widget(help, chunks[5]);
}

fn render_os_list(app: &App, frame: &mut Frame, area: Rect) {
    let state = app.wizard_state.as_ref().unwrap();

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Gray));

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

    // Build the list of items (categories and OSes)
    let mut lines: Vec<Line> = Vec::new();
    let mut item_index = 0;

    // Get categories in display order
    let category_order = ["windows", "linux", "bsd", "unix", "macos", "mobile", "infrastructure", "utilities", "alternative", "retro", "classic-mac"];

    for category in &category_order {
        let profiles = app.qemu_profiles.list_by_category(category);
        if profiles.is_empty() {
            continue;
        }

        let is_expanded = state.is_category_expanded(category);
        let is_selected = item_index == state.os_list_selected;

        // Category header
        let expand_icon = if is_expanded { "v" } else { ">" };
        let category_name = QemuProfileStore::category_display_name(category);
        let category_style = if is_selected {
            Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)
        };

        let prefix = if is_selected { "> " } else { "  " };
        lines.push(Line::from(vec![
            Span::styled(prefix, category_style),
            Span::styled(expand_icon, category_style),
            Span::styled(format!(" {}", category_name), category_style),
        ]));

        item_index += 1;

        // OS items (if expanded)
        if is_expanded {
            for (os_id, profile) in &profiles {
                // Filter by search query
                if !state.os_filter.is_empty() {
                    let filter_lower = state.os_filter.to_lowercase();
                    if !profile.display_name.to_lowercase().contains(&filter_lower)
                        && !os_id.to_lowercase().contains(&filter_lower)
                    {
                        continue;
                    }
                }

                let is_os_selected = item_index == state.os_list_selected;
                let is_chosen = state.selected_os.as_ref() == Some(*os_id);

                let os_style = if is_os_selected {
                    Style::default().fg(Color::Yellow)
                } else if is_chosen {
                    Style::default().fg(Color::Green)
                } else {
                    Style::default().fg(Color::White)
                };

                let prefix = if is_os_selected { "> " } else { "  " };
                let chosen_marker = if is_chosen { "*" } else { " " };
                let summary = profile.summary();

                lines.push(Line::from(vec![
                    Span::styled(prefix, os_style),
                    Span::styled(format!("   {}", chosen_marker), os_style),
                    Span::styled(profile.display_name.to_string(), os_style),
                    Span::styled(format!("  ({})", summary), Style::default().fg(Color::DarkGray)),
                ]));

                item_index += 1;
            }
        }
    }

    // Add "Custom OS" option at the end
    let is_custom_selected = item_index == state.os_list_selected;
    let custom_style = if is_custom_selected {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::Magenta)
    };
    let prefix = if is_custom_selected { "> " } else { "  " };
    lines.push(Line::from(vec![
        Span::styled(prefix, custom_style),
        Span::styled("   Custom OS...", custom_style),
        Span::styled("  (Define your own)", Style::default().fg(Color::DarkGray)),
    ]));

    // Calculate scroll offset
    let visible_height = inner.height as usize;
    let scroll_offset = if state.os_list_selected >= visible_height {
        state.os_list_selected - visible_height + 1
    } else {
        0
    };

    // Render visible portion
    let visible_lines: Vec<Line> = lines
        .into_iter()
        .skip(scroll_offset)
        .take(visible_height)
        .collect();

    let list = Paragraph::new(visible_lines);
    frame.render_widget(list, inner);
}

fn handle_step_select_os(app: &mut App, key: KeyEvent) -> Result<()> {
    let editing_name = app.wizard_state.as_ref()
        .map(|s| matches!(s.editing_field, Some(WizardField::VmName)))
        .unwrap_or(false);

    if editing_name {
        // Text input mode for VM name
        match key.code {
            KeyCode::Esc | KeyCode::Enter | KeyCode::Tab => {
                if let Some(ref mut state) = app.wizard_state {
                    state.editing_field = None;
                    state.update_folder_name(&app.config.vm_library_path);
                }
            }
            KeyCode::Char(c) => {
                if let Some(ref mut state) = app.wizard_state {
                    state.vm_name.push(c);
                }
            }
            KeyCode::Backspace => {
                if let Some(ref mut state) = app.wizard_state {
                    state.vm_name.pop();
                }
            }
            _ => {}
        }
    } else {
        // Normal navigation mode
        match key.code {
            KeyCode::Esc => {
                app.cancel_wizard();
            }
            KeyCode::Tab => {
                // Toggle to name editing
                if let Some(ref mut state) = app.wizard_state {
                    state.editing_field = Some(WizardField::VmName);
                }
            }
            KeyCode::Char('j') | KeyCode::Down => {
                // Count total items first (immutable borrow)
                let total = count_os_list_items(app);
                // Then mutate
                if let Some(ref mut state) = app.wizard_state {
                    if state.os_list_selected < total.saturating_sub(1) {
                        state.os_list_selected += 1;
                    }
                }
            }
            KeyCode::Char('k') | KeyCode::Up => {
                if let Some(ref mut state) = app.wizard_state {
                    if state.os_list_selected > 0 {
                        state.os_list_selected -= 1;
                    }
                }
            }
            KeyCode::Char(' ') => {
                // Toggle category expansion or select OS
                handle_os_list_action(app, false);
            }
            KeyCode::Enter => {
                // Select OS or expand category, then proceed if valid
                handle_os_list_action(app, true);
            }
            _ => {}
        }
    }
    Ok(())
}

/// Count total items in the OS list (categories + visible OSes + custom)
fn count_os_list_items(app: &App) -> usize {
    let state = app.wizard_state.as_ref().unwrap();
    let category_order = ["windows", "linux", "bsd", "unix", "macos", "mobile", "infrastructure", "utilities", "alternative", "retro", "classic-mac"];

    let mut count = 0;
    for category in &category_order {
        let profiles = app.qemu_profiles.list_by_category(category);
        if profiles.is_empty() {
            continue;
        }
        count += 1; // Category header
        if state.is_category_expanded(category) {
            // Count visible profiles (with filter)
            for (os_id, profile) in &profiles {
                if !state.os_filter.is_empty() {
                    let filter_lower = state.os_filter.to_lowercase();
                    if !profile.display_name.to_lowercase().contains(&filter_lower)
                        && !os_id.to_lowercase().contains(&filter_lower)
                    {
                        continue;
                    }
                }
                count += 1;
            }
        }
    }
    count += 1; // Custom OS option
    count
}

/// Handle action on OS list item (space to toggle, enter to select and proceed)
fn handle_os_list_action(app: &mut App, proceed: bool) {
    // First, collect all the information we need without holding borrows
    let Some(ref state) = app.wizard_state else {
        return;
    };
    let selected = state.os_list_selected;
    let os_filter = state.os_filter.clone();
    let expanded_categories: Vec<String> = state.expanded_categories.clone();

    let category_order = ["windows", "linux", "bsd", "unix", "macos", "mobile", "infrastructure", "utilities", "alternative", "retro", "classic-mac"];

    let mut item_index = 0;
    let mut action: Option<OsListAction> = None;

    for category in &category_order {
        let profiles = app.qemu_profiles.list_by_category(category);
        if profiles.is_empty() {
            continue;
        }

        // Category header
        if item_index == selected {
            action = Some(OsListAction::ToggleCategory(category.to_string()));
            break;
        }
        item_index += 1;

        // OS items (if expanded)
        let is_expanded = expanded_categories.iter().any(|c| c == *category);
        if is_expanded {
            for (os_id, profile) in &profiles {
                if !os_filter.is_empty() {
                    let filter_lower = os_filter.to_lowercase();
                    if !profile.display_name.to_lowercase().contains(&filter_lower)
                        && !os_id.to_lowercase().contains(&filter_lower)
                    {
                        continue;
                    }
                }

                if item_index == selected {
                    action = Some(OsListAction::SelectOs(os_id.to_string()));
                    break;
                }
                item_index += 1;
            }
        }

        if action.is_some() {
            break;
        }
    }

    // Check if custom OS was selected (at the end)
    if action.is_none() && item_index == selected {
        action = Some(OsListAction::CustomOs);
    }

    // Now execute the action
    match action {
        Some(OsListAction::ToggleCategory(cat)) => {
            if let Some(ref mut state) = app.wizard_state {
                state.toggle_category(&cat);
            }
        }
        Some(OsListAction::SelectOs(os_id)) => {
            app.wizard_select_os(&os_id);
            if proceed {
                if let Err(e) = app.wizard_next_step() {
                    if let Some(ref mut state) = app.wizard_state {
                        state.error_message = Some(e);
                    }
                }
            }
        }
        Some(OsListAction::CustomOs) => {
            app.wizard_use_custom_os();
        }
        None => {}
    }
}

/// Actions that can be taken on the OS list
enum OsListAction {
    ToggleCategory(String),
    SelectOs(String),
    CustomOs,
}

// =============================================================================
// Step 2: Select ISO
// =============================================================================

fn render_step_select_iso(app: &App, frame: &mut Frame, area: Rect) {
    let state = app.wizard_state.as_ref().unwrap();

    let block = Block::default()
        .title(format!(" Create New VM ({}/5) - {} ", state.step.number(), state.step.title()))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan))
        .style(Style::default().bg(Color::Black));

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

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([
            Constraint::Length(2),   // OS info
            Constraint::Length(1),   // Spacer
            Constraint::Length(1),   // Header
            Constraint::Min(10),     // Options
            Constraint::Length(1),   // Selected path
            Constraint::Length(2),   // Help
        ])
        .split(inner);

    // OS info
    let os_name = state.selected_os.as_ref()
        .and_then(|id| app.qemu_profiles.get(id))
        .map(|p| p.display_name.as_str())
        .unwrap_or("Custom OS");

    let os_info = Paragraph::new(format!("Operating System: {}", os_name))
        .style(Style::default().fg(Color::White));
    frame.render_widget(os_info, chunks[0]);

    // Header
    let header = Paragraph::new("Install Media:")
        .style(Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD));
    frame.render_widget(header, chunks[2]);

    // Options
    let mut lines = Vec::new();
    let mut option_idx = 0;

    // BIOS/ROM option first (if the selected profile has bios_rom config)
    let bios_rom_config = state.selected_os.as_ref()
        .and_then(|id| app.qemu_profiles.get(id))
        .and_then(|p| p.bios_rom.as_ref());

    if let Some(bios_config) = bios_rom_config {
        let req_label = if bios_config.required { " (REQUIRED)" } else { " (optional)" };
        let is_rom_selected = state.field_focus == option_idx;
        let rom_style = if is_rom_selected {
            Style::default().fg(Color::Yellow)
        } else {
            Style::default().fg(Color::White)
        };
        let rom_prefix = if is_rom_selected { "> " } else { "  " };
        lines.push(Line::styled(
            format!("{}( ) Browse for {} file...{}", rom_prefix, bios_config.label, req_label),
            rom_style,
        ));

        if let Some(ref hint) = bios_config.hint {
            lines.push(Line::styled(format!("       {}", hint), Style::default().fg(Color::DarkGray)));
        }

        if let Some(ref rom_path) = state.bios_rom_path {
            lines.push(Line::styled(
                format!("       ROM: {}", rom_path.display()),
                Style::default().fg(Color::Green),
            ));
        }

        lines.push(Line::from(""));
        option_idx += 1;
    }

    // Check if this OS has a free ISO URL
    let has_download = state.selected_os.as_ref()
        .and_then(|id| app.qemu_profiles.get(id))
        .and_then(|p| p.iso_url.as_ref())
        .is_some();

    if has_download {
        let is_selected = state.field_focus == option_idx;
        let style = if is_selected {
            Style::default().fg(Color::Yellow)
        } else {
            Style::default().fg(Color::White)
        };
        let prefix = if is_selected { "> " } else { "  " };
        lines.push(Line::styled(format!("{}( ) Open download page in browser", prefix), style));
        option_idx += 1;
    }

    // Floppy image option (for OSes that need a boot floppy, e.g., OS/2)
    let is_floppy_selected = state.field_focus == option_idx;
    let floppy_style = if is_floppy_selected {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::White)
    };
    let floppy_prefix = if is_floppy_selected { "> " } else { "  " };
    lines.push(Line::styled(format!("{}( ) Browse for boot floppy image...", floppy_prefix), floppy_style));
    if let Some(ref floppy_path) = state.floppy_path {
        lines.push(Line::styled(
            format!("       Floppy: {}", floppy_path.display()),
            Style::default().fg(Color::Green),
        ));
    }
    option_idx += 1;

    let is_browse_selected = state.field_focus == option_idx;
    let browse_style = if is_browse_selected {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::White)
    };
    let browse_prefix = if is_browse_selected { "> " } else { "  " };
    lines.push(Line::styled(format!("{}( ) Browse for local ISO file...", browse_prefix), browse_style));
    option_idx += 1;

    let is_recovery_selected = state.field_focus == option_idx;
    let recovery_style = if is_recovery_selected {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::White)
    };
    let recovery_prefix = if is_recovery_selected { "> " } else { "  " };
    lines.push(Line::styled(format!("{}( ) Browse for recovery image (DMG)...", recovery_prefix), recovery_style));
    option_idx += 1;

    let is_none_selected = state.field_focus == option_idx;
    let none_style = if is_none_selected {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::White)
    };
    let none_prefix = if is_none_selected { "> " } else { "  " };
    lines.push(Line::styled(format!("{}( ) Skip (configure later)", none_prefix), none_style));

    let options = Paragraph::new(lines)
        .wrap(Wrap { trim: false });
    frame.render_widget(options, chunks[3]);

    // Selected path
    if let Some(ref path) = state.iso_path {
        let label = if state.is_recovery_image { "Selected recovery image" } else { "Selected ISO" };
        let path_text = Paragraph::new(format!("{}: {}", label, path.display()))
            .style(Style::default().fg(Color::Green));
        frame.render_widget(path_text, chunks[4]);
    }

    // Help
    let help = Paragraph::new("[j/k] Select  [Enter] Choose  [Esc] Back")
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Center);
    frame.render_widget(help, chunks[5]);
}

fn handle_step_select_iso(app: &mut App, key: KeyEvent) -> Result<()> {
    let has_download = app.wizard_state.as_ref()
        .and_then(|s| s.selected_os.as_ref())
        .and_then(|id| app.qemu_profiles.get(id))
        .and_then(|p| p.iso_url.as_ref())
        .is_some();

    let has_bios_rom = app.wizard_state.as_ref()
        .and_then(|s| s.selected_os.as_ref())
        .and_then(|id| app.qemu_profiles.get(id))
        .and_then(|p| p.bios_rom.as_ref())
        .is_some();

    // Compute option indices matching the render order: ROM, download, floppy, browse, recovery, skip
    let mut idx = 0;
    let rom_idx = if has_bios_rom { let i = idx; idx += 1; Some(i) } else { None };
    let download_idx = if has_download { let i = idx; idx += 1; Some(i) } else { None };
    let floppy_idx = idx; idx += 1;
    let browse_idx = idx; idx += 1;
    let recovery_browse_idx = idx; idx += 1;
    let no_iso_idx = idx; idx += 1;
    let max_options = idx;

    match key.code {
        KeyCode::Esc => {
            app.wizard_prev_step();
        }
        KeyCode::Char('j') | KeyCode::Down => {
            if let Some(ref mut state) = app.wizard_state {
                if state.field_focus < max_options - 1 {
                    state.field_focus += 1;
                }
            }
        }
        KeyCode::Char('k') | KeyCode::Up => {
            if let Some(ref mut state) = app.wizard_state {
                if state.field_focus > 0 {
                    state.field_focus -= 1;
                }
            }
        }
        KeyCode::Enter => {
            let focus = app.wizard_state.as_ref().map(|s| s.field_focus).unwrap_or(0);

            if Some(focus) == rom_idx {
                // Browse for ROM/BIOS file
                app.load_file_browser(crate::app::FileBrowserMode::Bios);
                app.push_screen(crate::app::Screen::FileBrowser);
            } else if Some(focus) == download_idx {
                // Open download page in browser
                if let Some(url) = app.wizard_state.as_ref()
                    .and_then(|s| s.selected_os.as_ref())
                    .and_then(|id| app.qemu_profiles.get(id))
                    .and_then(|p| p.iso_url.as_ref())
                {
                    let url = url.clone();
                    if let Err(e) = open_url_in_browser(&url) {
                        app.set_status(format!("Failed to open browser: {}", e));
                    } else {
                        app.set_status("Opened download page in browser. Use 'Browse for ISO' after downloading.");
                    }
                }
            } else if focus == floppy_idx {
                // Browse for floppy image - open file browser
                app.load_file_browser(crate::app::FileBrowserMode::Floppy);
                app.push_screen(crate::app::Screen::FileBrowser);
            } else if focus == browse_idx {
                // Browse for ISO - open file browser
                app.seed_iso_browser_dir();
                app.load_file_browser(crate::app::FileBrowserMode::Iso);
                app.push_screen(crate::app::Screen::FileBrowser);
            } else if focus == recovery_browse_idx {
                // Browse for recovery image (DMG) - open file browser
                app.load_file_browser(crate::app::FileBrowserMode::RecoveryImage);
                app.push_screen(crate::app::Screen::FileBrowser);
            } else if focus == no_iso_idx {
                // Skip - check if ROM is required but missing
                let rom_required_but_missing = app.wizard_state.as_ref()
                    .and_then(|s| s.selected_os.as_ref())
                    .and_then(|id| app.qemu_profiles.get(id))
                    .and_then(|p| p.bios_rom.as_ref())
                    .map(|b| b.required)
                    .unwrap_or(false)
                    && app.wizard_state.as_ref()
                        .map(|s| s.bios_rom_path.is_none())
                        .unwrap_or(false);

                if rom_required_but_missing {
                    if let Some(ref mut state) = app.wizard_state {
                        state.error_message = Some("Warning: ROM file is required for this OS but not selected. Proceeding anyway.".to_string());
                    }
                }

                if let Some(ref mut state) = app.wizard_state {
                    state.iso_path = None;
                    state.is_recovery_image = false;
                }
                let _ = app.wizard_next_step();
            }
        }
        _ => {}
    }
    Ok(())
}

// =============================================================================
// Step 3: Configure Disk
// =============================================================================

fn render_step_configure_disk(app: &App, frame: &mut Frame, area: Rect) {
    let state = app.wizard_state.as_ref().unwrap();

    let block = Block::default()
        .title(format!(" Create New VM ({}/5) - {} ", state.step.number(), state.step.title()))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan))
        .style(Style::default().bg(Color::Black));

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

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([
            Constraint::Length(1),   // Header
            Constraint::Length(1),   // Spacer
            Constraint::Length(1),   // Disk source toggle
            Constraint::Length(1),   // Spacer
            Constraint::Min(10),     // Mode-specific content
            Constraint::Length(2),   // Help
        ])
        .split(inner);

    // Header
    let header = Paragraph::new("Disk Configuration")
        .style(Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD));
    frame.render_widget(header, chunks[0]);

    // Disk source toggle (field_focus == 0)
    let source_focused = state.field_focus == 0;
    let create_style = if !state.use_existing_disk {
        Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::DarkGray)
    };
    let existing_style = if state.use_existing_disk {
        Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::DarkGray)
    };
    let prefix = if source_focused { "> " } else { "  " };

    let source_line = Line::from(vec![
        Span::styled(prefix, if source_focused { Style::default().fg(Color::Yellow) } else { Style::default() }),
        Span::styled("Disk Source: ", Style::default().fg(Color::Yellow)),
        Span::styled("[ ", Style::default()),
        Span::styled("Create New", create_style),
        Span::styled(" ] [ ", Style::default()),
        Span::styled("Use Existing", existing_style),
        Span::styled(" ]", Style::default()),
        if source_focused {
            Span::styled("  [←/→] toggle", Style::default().fg(Color::DarkGray))
        } else {
            Span::raw("")
        },
    ]);
    let source_toggle = Paragraph::new(source_line);
    frame.render_widget(source_toggle, chunks[2]);

    // Mode-specific content area
    let content_area = chunks[4];

    if state.use_existing_disk {
        // "Use Existing" mode
        render_existing_disk_mode(app, frame, content_area);
    } else {
        // "Create New" mode (existing behavior)
        render_new_disk_mode(app, frame, content_area);
    }

    // Help
    let help_text = if state.use_existing_disk {
        if state.field_focus == 0 {
            "[←/→] Toggle mode  [j/k] Navigate  [Enter] Next  [Esc] Back"
        } else if state.field_focus == 1 {
            "[Enter] Browse  [j/k] Navigate  [Esc] Back"
        } else {
            "[←/→] Toggle action  [j/k] Navigate  [Enter] Next  [Esc] Back"
        }
    } else {
        let editing = matches!(state.editing_field, Some(WizardField::DiskSize));
        if editing {
            "[Enter] Done  [Backspace] Delete  [0-9] Enter size"
        } else if state.field_focus == 0 {
            "[←/→] Toggle mode  [j/k] Navigate  [Enter] Next  [Esc] Back"
        } else {
            "[Tab] Edit size  [←/→] Adjust  [Enter] Next  [Esc] Back"
        }
    };
    let help = Paragraph::new(help_text)
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Center);
    frame.render_widget(help, chunks[5]);
}

/// Render the "Create New" disk mode content
fn render_new_disk_mode(app: &App, frame: &mut Frame, area: Rect) {
    let state = app.wizard_state.as_ref().unwrap();

    let sub_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),   // Disk size input
            Constraint::Length(1),   // Spacer
            Constraint::Min(5),      // Disk info
        ])
        .split(area);

    // Disk size input (field_focus == 1 when in new disk mode)
    let size_focused = state.field_focus == 1;
    let editing = matches!(state.editing_field, Some(WizardField::DiskSize));
    let size_style = if editing {
        Style::default().fg(Color::Yellow)
    } else if size_focused {
        Style::default().fg(Color::White).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::White)
    };
    let border_style = if editing || size_focused {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::Gray)
    };

    let recommended = app.wizard_selected_profile()
        .map(|p| p.disk_size_gb)
        .unwrap_or(32);

    let size_block = Block::default()
        .title(format!(" Disk Size (Recommended: {} GB) ", recommended))
        .borders(Borders::ALL)
        .border_style(border_style);

    // Show edit buffer when editing, otherwise show current value
    let size_display = if editing {
        format!("{}|  (e.g., 500, 500GB, 512000MB)", state.wizard_edit_buffer)
    } else {
        format!("{} GB", state.disk_size_gb)
    };

    let size_text = Paragraph::new(size_display)
        .style(size_style)
        .block(size_block);
    frame.render_widget(size_text, sub_chunks[0]);

    // Disk info box
    let info_block = Block::default()
        .title(" Disk Info ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Gray));

    let disk_path = app.wizard_vm_path()
        .map(|p| p.join(format!("{}.qcow2", state.folder_name)))
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "~/vm-space/<vm-name>/<vm-name>.qcow2".to_string());

    let info_text = vec![
        Line::from(vec![
            Span::styled("Format: ", Style::default().fg(Color::Yellow)),
            Span::raw("qcow2 (copy-on-write, snapshots supported)"),
        ]),
        Line::from(vec![
            Span::styled("Type: ", Style::default().fg(Color::Yellow)),
            Span::raw("Expandable (only uses space as needed)"),
        ]),
        Line::from(vec![
            Span::styled("Location: ", Style::default().fg(Color::Yellow)),
            Span::raw(disk_path),
        ]),
    ];

    let info = Paragraph::new(info_text)
        .block(info_block)
        .wrap(Wrap { trim: false });
    frame.render_widget(info, sub_chunks[2]);
}

/// Render the "Use Existing" disk mode content
fn render_existing_disk_mode(app: &App, frame: &mut Frame, area: Rect) {
    use crate::app::DiskAction;

    let state = app.wizard_state.as_ref().unwrap();

    let sub_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),   // Browse / selected path
            Constraint::Length(1),   // Spacer
            Constraint::Length(1),   // Action toggle
            Constraint::Length(1),   // Spacer
            Constraint::Min(3),      // Note
        ])
        .split(area);

    // Browse button / selected path (field_focus == 1)
    let browse_focused = state.field_focus == 1;
    let browse_border = if browse_focused {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::Gray)
    };

    let browse_block = Block::default()
        .title(" Disk Image ")
        .borders(Borders::ALL)
        .border_style(browse_border);

    let browse_inner = browse_block.inner(sub_chunks[0]);
    frame.render_widget(browse_block, sub_chunks[0]);

    let browse_text = if let Some(ref path) = state.existing_disk_path {
        let path_str = path.display().to_string();
        // Truncate path if too long
        let max_len = browse_inner.width as usize - 2;
        let display = if path_str.len() > max_len {
            format!("...{}", &path_str[path_str.len() - max_len + 3..])
        } else {
            path_str
        };
        Paragraph::new(display).style(Style::default().fg(Color::Green))
    } else {
        let prefix = if browse_focused { "> " } else { "  " };
        Paragraph::new(format!("{}( ) Browse for qcow2 disk file...", prefix))
            .style(if browse_focused {
                Style::default().fg(Color::Yellow)
            } else {
                Style::default().fg(Color::White)
            })
    };
    frame.render_widget(browse_text, browse_inner);

    // Action toggle (field_focus == 2)
    let action_focused = state.field_focus == 2;
    let copy_style = if matches!(state.existing_disk_action, DiskAction::Copy) {
        Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::DarkGray)
    };
    let move_style = if matches!(state.existing_disk_action, DiskAction::Move) {
        Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::DarkGray)
    };
    let prefix = if action_focused { "> " } else { "  " };

    let action_line = Line::from(vec![
        Span::styled(prefix, if action_focused { Style::default().fg(Color::Yellow) } else { Style::default() }),
        Span::styled("Action: ", Style::default().fg(Color::Yellow)),
        Span::styled("[ ", Style::default()),
        Span::styled("Copy to VM folder", copy_style),
        Span::styled(" ] [ ", Style::default()),
        Span::styled("Move to VM folder", move_style),
        Span::styled(" ]", Style::default()),
    ]);
    let action_toggle = Paragraph::new(action_line);
    frame.render_widget(action_toggle, sub_chunks[2]);

    // Note about renaming
    let note_text = format!(
        "Note: The disk will be renamed to {}.qcow2",
        state.folder_name
    );
    let note = Paragraph::new(note_text)
        .style(Style::default().fg(Color::DarkGray));
    frame.render_widget(note, sub_chunks[4]);
}

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

    let (editing, use_existing, field_focus) = app.wizard_state.as_ref()
        .map(|s| (
            matches!(s.editing_field, Some(WizardField::DiskSize)),
            s.use_existing_disk,
            s.field_focus,
        ))
        .unwrap_or((false, false, 0));

    // Handle disk size editing mode (only in "Create New" mode)
    if editing && !use_existing {
        match key.code {
            KeyCode::Esc => {
                // Cancel edit, restore original value (clear buffer)
                if let Some(ref mut state) = app.wizard_state {
                    state.editing_field = None;
                    state.wizard_edit_buffer.clear();
                }
            }
            KeyCode::Enter | KeyCode::Tab => {
                // Apply the edit with suffix support
                if let Some(ref mut state) = app.wizard_state {
                    let buffer = state.wizard_edit_buffer.clone();
                    if let Some(value) = parse_size_with_suffix(&buffer, "GB") {
                        state.disk_size_gb = value.clamp(1, 10000);
                    }
                    state.editing_field = None;
                    state.wizard_edit_buffer.clear();
                }
            }
            KeyCode::Char(c) if c.is_ascii_alphanumeric() => {
                if let Some(ref mut state) = app.wizard_state {
                    state.wizard_edit_buffer.push(c);
                }
            }
            KeyCode::Backspace => {
                if let Some(ref mut state) = app.wizard_state {
                    state.wizard_edit_buffer.pop();
                }
            }
            KeyCode::Left | KeyCode::Right => {
                // Allow arrow keys to still adjust while editing
                if let Some(ref mut state) = app.wizard_state {
                    if key.code == KeyCode::Left {
                        state.disk_size_gb = state.disk_size_gb.saturating_sub(8).max(1);
                    } else {
                        state.disk_size_gb = (state.disk_size_gb + 8).min(10000);
                    }
                    // Update buffer to reflect new value
                    state.wizard_edit_buffer = state.disk_size_gb.to_string();
                }
            }
            _ => {}
        }
        return Ok(());
    }

    // Normal navigation mode
    match key.code {
        KeyCode::Esc => {
            app.wizard_prev_step();
        }
        KeyCode::Char('j') | KeyCode::Down => {
            if let Some(ref mut state) = app.wizard_state {
                let max_focus = if state.use_existing_disk { 2 } else { 1 };
                if state.field_focus < max_focus {
                    state.field_focus += 1;
                }
            }
        }
        KeyCode::Char('k') | KeyCode::Up => {
            if let Some(ref mut state) = app.wizard_state {
                if state.field_focus > 0 {
                    state.field_focus -= 1;
                }
            }
        }
        KeyCode::Left | KeyCode::Right => {
            if let Some(ref mut state) = app.wizard_state {
                match state.field_focus {
                    0 => {
                        // Toggle disk source mode
                        state.use_existing_disk = !state.use_existing_disk;
                    }
                    1 if !state.use_existing_disk => {
                        // Adjust disk size (Create New mode)
                        if key.code == KeyCode::Left {
                            state.disk_size_gb = state.disk_size_gb.saturating_sub(8).max(1);
                        } else {
                            state.disk_size_gb = (state.disk_size_gb + 8).min(10000);
                        }
                    }
                    2 if state.use_existing_disk => {
                        // Toggle copy/move action
                        state.existing_disk_action = match state.existing_disk_action {
                            DiskAction::Copy => DiskAction::Move,
                            DiskAction::Move => DiskAction::Copy,
                        };
                    }
                    _ => {}
                }
            }
        }
        KeyCode::Tab => {
            // Enter edit mode for disk size (Create New mode only)
            if !use_existing && field_focus == 1 {
                if let Some(ref mut state) = app.wizard_state {
                    state.editing_field = Some(WizardField::DiskSize);
                    state.wizard_edit_buffer = state.disk_size_gb.to_string();
                }
            }
        }
        KeyCode::Enter => {
            // If on browse button in existing mode, open file browser
            if use_existing && field_focus == 1 {
                app.load_file_browser(FileBrowserMode::Disk);
                app.push_screen(crate::app::Screen::FileBrowser);
            } else {
                // Try to proceed to next step
                if let Err(e) = app.wizard_next_step() {
                    if let Some(ref mut state) = app.wizard_state {
                        state.error_message = Some(e);
                    }
                }
            }
        }
        _ => {}
    }
    Ok(())
}

// =============================================================================
// Step 4: Configure QEMU
// =============================================================================

/// QEMU field options for cycling through values
const VGA_OPTIONS: &[&str] = &["std", "virtio", "qxl", "cirrus", "vmware", "none"];
const NETWORK_OPTIONS: &[&str] = &["virtio", "e1000", "rtl8139", "ne2k_pci", "pcnet", "none"];
const DISK_INTERFACE_OPTIONS: &[&str] = &["virtio", "ide", "scsi"];
const DISPLAY_OPTIONS: &[&str] = &["gtk", "sdl", "spice-app", "vnc", "none"];
const AUDIO_OPTIONS: &[(&str, &[&str])] = &[
    ("Intel HDA", &["intel-hda", "hda-duplex"]),
    ("AC97", &["ac97"]),
    ("Sound Blaster 16", &["sb16"]),
    ("None", &[]),
];

/// Fields in the QEMU config screen
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum QemuField {
    Memory,
    CpuCores,
    Vga,
    Audio,
    Network,
    NetBackend,
    BridgeName,
    PortForwards,
    MacAddress,
    DiskInterface,
    Display,
    Kvm,
    GlAccel,
    Uefi,
    Tpm,
    UsbTablet,
    RtcLocal,
}

impl QemuField {
    fn from_index(idx: usize) -> Self {
        match idx {
            0 => Self::Memory,
            1 => Self::CpuCores,
            2 => Self::Vga,
            3 => Self::Audio,
            4 => Self::Network,
            5 => Self::NetBackend,
            6 => Self::BridgeName,
            7 => Self::PortForwards,
            8 => Self::MacAddress,
            9 => Self::DiskInterface,
            10 => Self::Display,
            11 => Self::Kvm,
            12 => Self::GlAccel,
            13 => Self::Uefi,
            14 => Self::Tpm,
            15 => Self::UsbTablet,
            _ => Self::RtcLocal,
        }
    }

    fn count() -> usize {
        17
    }
}

fn render_step_configure_qemu(app: &App, frame: &mut Frame, area: Rect) {
    let state = app.wizard_state.as_ref().unwrap();

    let block = Block::default()
        .title(format!(" Create New VM ({}/5) - {} ", state.step.number(), state.step.title()))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan))
        .style(Style::default().bg(Color::Black));

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

    // Split into left (settings) and right (notes) panels
    let h_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(55), Constraint::Percentage(45)])
        .split(inner);

    let left_chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([
            Constraint::Length(1),   // Header
            Constraint::Min(18),     // Settings
            Constraint::Length(2),   // Help
        ])
        .split(h_chunks[0]);

    let right_chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([
            Constraint::Length(1),   // Header
            Constraint::Min(18),     // Notes
        ])
        .split(h_chunks[1]);

    // Left side: Settings header
    let header = Paragraph::new("QEMU Settings")
        .style(Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD));
    frame.render_widget(header, left_chunks[0]);

    // Settings list (editable)
    let config = &state.qemu_config;
    let focus = state.field_focus;
    let editing = state.editing_field.is_some();
    let mut lines = Vec::new();

    // Memory (editable)
    let mem_selected = focus == 0;
    let mem_editing = matches!(state.editing_field, Some(WizardField::MemoryMb));
    let mem_value = if mem_editing {
        format!("{}|", state.wizard_edit_buffer)
    } else {
        format!("{} MB", config.memory_mb)
    };
    let mem_hint = if mem_editing {
        "[Enter] Done  [Esc] Cancel"
    } else if mem_selected {
        "[Tab] Edit  [←/→] ±256MB"
    } else {
        ""
    };
    lines.push(render_field_line(
        "Memory:",
        &mem_value,
        mem_selected,
        mem_editing,
        mem_hint,
    ));

    // CPU Cores (editable)
    let cpu_selected = focus == 1;
    let cpu_editing = matches!(state.editing_field, Some(WizardField::CpuCores));
    let cpu_value = if cpu_editing {
        format!("{}|", state.wizard_edit_buffer)
    } else {
        format!("{}", config.cpu_cores)
    };
    let cpu_hint = if cpu_editing {
        "[Enter] Done  [Esc] Cancel"
    } else if cpu_selected {
        "[Tab] Edit  [←/→] ±1"
    } else {
        ""
    };
    lines.push(render_field_line(
        "CPU Cores:",
        &cpu_value,
        cpu_selected,
        cpu_editing,
        cpu_hint,
    ));

    // VGA (cycle)
    let vga_selected = focus == 2;
    lines.push(render_field_line(
        "Graphics:",
        &config.vga,
        vga_selected,
        false,
        "[←/→] cycle",
    ));

    // Audio (cycle)
    let audio_selected = focus == 3;
    let audio_label = get_audio_label(&config.audio);
    lines.push(render_field_line(
        "Audio:",
        audio_label,
        audio_selected,
        false,
        "[←/→] cycle",
    ));

    // Network adapter (cycle)
    let net_selected = focus == 4;
    lines.push(render_field_line(
        "Network:",
        &config.network_model,
        net_selected,
        false,
        "[←/→] cycle",
    ));

    // Network backend (cycle) - hidden if network model is "none"
    if config.network_model != "none" {
        let backend_selected = focus == 5;
        let backend_display = match config.network_backend.as_str() {
            "user" => "user/SLIRP (NAT)".to_string(),
            "passt" => "passt".to_string(),
            "bridge" => format!("bridge ({})", config.bridge_name.as_deref().unwrap_or("qemubr0")),
            "none" => "none".to_string(),
            other => other.to_string(),
        };
        lines.push(render_field_line(
            "Net Backend:",
            &backend_display,
            backend_selected,
            false,
            "[←/→] cycle",
        ));

        // Bridge name (only for bridge backend)
        if config.network_backend == "bridge" {
            let bridge_selected = focus == 6;
            let bridge_display = config.bridge_name.as_deref().unwrap_or("qemubr0");
            lines.push(render_field_line(
                "Bridge:",
                bridge_display,
                bridge_selected,
                false,
                "[←/→] cycle",
            ));
        }

        // Port forwards (only for user/passt)
        if config.network_backend == "user" || config.network_backend == "passt" {
            let pf_selected = focus == 7;
            let pf_display = if config.port_forwards.is_empty() {
                "none".to_string()
            } else {
                format!("{} rule(s)", config.port_forwards.len())
            };
            lines.push(render_field_line(
                "Forwards:",
                &pf_display,
                pf_selected,
                false,
                "[Enter] edit",
            ));
        }

        // MAC address (text input, hidden when network model is "none")
        let mac_selected = focus == 8;
        let mac_editing = matches!(state.editing_field, Some(WizardField::MacAddress));
        let mac_value = if mac_editing {
            format!("{}|", state.wizard_edit_buffer)
        } else if let Some(mac) = config.mac_address.as_deref() {
            mac.to_string()
        } else {
            "(auto)".to_string()
        };
        let mac_hint = if mac_editing {
            "[Enter] Done  [Esc] Cancel"
        } else if mac_selected {
            "[Tab] Edit  [g] Generate  [c] Clear"
        } else {
            ""
        };
        lines.push(render_field_line(
            "MAC:",
            &mac_value,
            mac_selected,
            mac_editing,
            mac_hint,
        ));
    }

    // Disk Interface (cycle)
    let disk_selected = focus == 9;
    lines.push(render_field_line(
        "Disk I/F:",
        &config.disk_interface,
        disk_selected,
        false,
        "[←/→] cycle",
    ));

    // Display (cycle)
    let disp_selected = focus == 10;
    lines.push(render_field_line(
        "Display:",
        &config.display,
        disp_selected,
        false,
        "[←/→] cycle",
    ));

    lines.push(Line::from(""));
    lines.push(Line::styled("  Features (toggle with Space):", Style::default().fg(Color::DarkGray)));

    // KVM toggle
    let kvm_selected = focus == 11;
    lines.push(render_toggle_line("KVM Accel:", config.enable_kvm, kvm_selected));

    // 3D/GL acceleration toggle
    let gl_selected = focus == 12;
    lines.push(render_toggle_line("3D Accel:", config.gl_acceleration, gl_selected));

    // UEFI toggle
    let uefi_selected = focus == 13;
    lines.push(render_toggle_line("UEFI Boot:", config.uefi, uefi_selected));

    // TPM toggle
    let tpm_selected = focus == 14;
    lines.push(render_toggle_line("TPM 2.0:", config.tpm, tpm_selected));

    // USB Tablet toggle
    let usb_selected = focus == 15;
    lines.push(render_toggle_line("USB Tablet:", config.usb_tablet, usb_selected));

    // RTC Local toggle
    let rtc_selected = focus == 16;
    lines.push(render_toggle_line("RTC Local:", config.rtc_localtime, rtc_selected));

    let settings = Paragraph::new(lines);
    frame.render_widget(settings, left_chunks[1]);

    // Help text
    let help_text = if editing {
        "[Enter] Done  [Esc] Cancel  [←/→] Adjust"
    } else {
        "[j/k] Navigate  [Tab] Edit  [←/→] Change  [Space] Toggle  [Enter] Next"
    };
    let help = Paragraph::new(help_text)
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Center);
    frame.render_widget(help, left_chunks[2]);

    // Right side: Notes header
    let notes_header = Paragraph::new("Why These Defaults?")
        .style(Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD));
    frame.render_widget(notes_header, right_chunks[0]);

    // Right side: Explanation notes
    let notes_block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::DarkGray));

    let notes_inner = notes_block.inner(right_chunks[1]);
    frame.render_widget(notes_block, right_chunks[1]);

    // Build notes based on selected field and profile
    let notes_text = get_field_notes(app, focus);
    let notes = Paragraph::new(notes_text)
        .style(Style::default().fg(Color::Gray))
        .wrap(Wrap { trim: false });
    frame.render_widget(notes, notes_inner);
}

fn render_field_line(label: &str, value: &str, selected: bool, editing: bool, hint: &str) -> Line<'static> {
    let prefix = if selected { "> " } else { "  " };
    let label_style = Style::default().fg(Color::Yellow);
    let value_style = if editing {
        Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)
    } else if selected {
        Style::default().fg(Color::White).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::White)
    };
    let hint_style = Style::default().fg(Color::DarkGray);

    Line::from(vec![
        Span::styled(prefix.to_string(), if selected { Style::default().fg(Color::Yellow) } else { Style::default() }),
        Span::styled(format!("{:12}", label), label_style),
        Span::styled(format!("{:15}", value), value_style),
        Span::styled(if selected { hint.to_string() } else { String::new() }, hint_style),
    ])
}

fn render_toggle_line(label: &str, enabled: bool, selected: bool) -> Line<'static> {
    let prefix = if selected { "> " } else { "  " };
    let checkbox = if enabled { "[x]" } else { "[ ]" };
    let label_style = Style::default().fg(Color::Yellow);
    let value_style = if selected {
        Style::default().fg(if enabled { Color::Green } else { Color::Red }).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(if enabled { Color::Green } else { Color::DarkGray })
    };

    Line::from(vec![
        Span::styled(prefix.to_string(), if selected { Style::default().fg(Color::Yellow) } else { Style::default() }),
        Span::styled(format!("{:12}", label), label_style),
        Span::styled(checkbox.to_string(), value_style),
    ])
}

fn get_audio_label(audio: &[String]) -> &'static str {
    if audio.is_empty() {
        "None"
    } else if audio.iter().any(|a| a.contains("intel-hda")) {
        "Intel HDA"
    } else if audio.iter().any(|a| a.contains("ac97")) {
        "AC97"
    } else if audio.iter().any(|a| a.contains("sb16")) {
        "Sound Blaster 16"
    } else {
        "Custom"
    }
}

fn get_field_notes(app: &App, focus: usize) -> String {
    let profile = app.wizard_selected_profile();
    let profile_notes = profile.and_then(|p| p.notes.as_ref()).cloned().unwrap_or_default();
    let os_name = profile.map(|p| p.display_name.as_str()).unwrap_or("this OS");

    let field = QemuField::from_index(focus);

    let explanation = match field {
        QemuField::Memory => format!(
            "RAM for {}.\n\n\
            Modern OSes need 4GB+. Older systems may crash with too much RAM.\n\n\
            Windows 95: max 480MB\n\
            Windows 98/ME: max 512MB\n\
            Windows XP: 512MB-1GB\n\
            Linux GUI: 2GB minimum",
            os_name
        ),
        QemuField::CpuCores => format!(
            "CPU cores for {}.\n\n\
            More cores = faster for multi-threaded tasks.\n\n\
            Old OSes (pre-2000) may not support multiple CPUs.\n\
            Don't exceed your host's core count.",
            os_name
        ),
        QemuField::Vga => format!(
            "Graphics adapter for {}.\n\n\
            std: Safe, universal\n\
            virtio: Best Linux perf\n\
            qxl: Best for Windows/Spice\n\
            cirrus: Old OS compat\n\
            vmware: macOS guest\n\
            none: Headless server",
            os_name
        ),
        QemuField::Audio => format!(
            "Audio device for {}.\n\n\
            Intel HDA: Modern (Win Vista+)\n\
            AC97: Win 2000/XP era\n\
            SB16: DOS/Win 9x games\n\
            None: Server/headless",
            os_name
        ),
        QemuField::Network => format!(
            "Network adapter for {}.\n\n\
            virtio: Best perf (needs driver)\n\
            e1000: Wide compat (Intel)\n\
            rtl8139: Win XP built-in\n\
            ne2k_pci: DOS/old Linux\n\
            pcnet: BSD compatible",
            os_name
        ),
        QemuField::NetBackend => format!(
            "Network backend for {}.\n\n\
            user: NAT via SLIRP (default)\n  Works everywhere, no setup needed\n\n\
            passt: Fast NAT, ping works\n  Requires passt package\n\n\
            bridge: Full network access\n  VM gets own IP on LAN\n  One-time setup needed\n\n\
            none: No networking",
            os_name
        ),
        QemuField::BridgeName => {
            let bridges = &app.network_caps.system_bridges;
            let bridges_str = if bridges.is_empty() {
                "No bridges detected on system.".to_string()
            } else {
                format!("Available: {}", bridges.join(", "))
            };
            format!(
                "Network bridge for {}.\n\n\
                {}\n\n\
                The VM will get its own IP on the bridge network, \
                providing full LAN access.\n\n\
                Requires qemu-bridge-helper with proper permissions.",
                os_name, bridges_str
            )
        },
        QemuField::PortForwards => format!(
            "Port forwarding for {}.\n\n\
            Forward host ports to the VM for \
            services like SSH, HTTP, RDP.\n\n\
            Only available with user (NAT) and \
            passt backends.\n\n\
            Press Enter to edit forwarding rules.",
            os_name
        ),
        QemuField::MacAddress => format!(
            "MAC address for {}.\n\n\
            Leave empty for QEMU to pick one. \
            Set explicitly when you need a stable MAC \
            (DHCP reservations, license-bound guests, \
            host firewall rules).\n\n\
            Format: aa:bb:cc:dd:ee:ff\n\
            Press [g] to generate a random MAC \
            with QEMU's safe 52:54:00 prefix.",
            os_name
        ),
        QemuField::DiskInterface => format!(
            "Disk interface for {}.\n\n\
            virtio: Best perf (needs driver)\n\
            ide: Universal compat\n\
            scsi: Server workloads",
            os_name
        ),
        QemuField::Display => format!(
            "Display output for {}.\n\n\
            gtk: Native Linux window\n\
            sdl: Cross-platform\n\
            spice-app: SPICE protocol (needs virt-viewer)\n\
            vnc: Remote access only\n\
            none: Headless, no graphical output",
            os_name
        ),
        QemuField::Kvm => "KVM hardware acceleration.\n\n\
            Enables near-native speed using CPU virtualization.\n\n\
            Requires: Linux host with Intel VT-x or AMD-V.\n\
            Disable for: Non-x86 guests, nested virt issues.".to_string(),
        QemuField::GlAccel => "3D/OpenGL acceleration.\n\n\
            Hardware-accelerated 3D graphics via virtio-gpu.\n\n\
            Requires: virtio VGA (auto-set when enabled)\n\
            Best for: Linux guests, Android x86\n\
            Not for: Windows (no virtio 3D), retro OSes".to_string(),
        QemuField::Uefi => format!(
            "UEFI boot mode for {}.\n\n\
            Modern boot firmware (vs legacy BIOS).\n\n\
            Required: Windows 11, some Linux installs\n\
            Optional: Windows 8+, modern Linux\n\
            Incompatible: DOS, Win 9x, old systems",
            os_name
        ),
        QemuField::Tpm => "TPM 2.0 emulation.\n\n\
            Trusted Platform Module for security features.\n\n\
            Required: Windows 11\n\
            Optional: BitLocker, Secure Boot\n\
            Not needed: Most other OSes".to_string(),
        QemuField::UsbTablet => "USB tablet device.\n\n\
            Provides seamless mouse integration (no capture).\n\n\
            Recommended: Most modern systems\n\
            Disable: Old OSes with USB issues".to_string(),
        QemuField::RtcLocal => "RTC in local time.\n\n\
            Sets hardware clock to local timezone.\n\n\
            Enable: Windows (expects local time)\n\
            Disable: Linux/Unix (expects UTC)".to_string(),
    };

    if profile_notes.is_empty() {
        explanation
    } else {
        format!("{}\n\n---\nProfile note:\n{}", explanation, profile_notes)
    }
}

fn handle_step_configure_qemu(app: &mut App, key: KeyEvent) -> Result<()> {
    let field_count = QemuField::count();

    // Handle wizard port forward editing
    if app.wizard_editing_port_forwards {
        return handle_wizard_port_forward_editor(app, key);
    }

    // Check if we're in edit mode for Memory or CPU
    let editing_memory = app.wizard_state.as_ref()
        .map(|s| matches!(s.editing_field, Some(WizardField::MemoryMb)))
        .unwrap_or(false);
    let editing_cpu = app.wizard_state.as_ref()
        .map(|s| matches!(s.editing_field, Some(WizardField::CpuCores)))
        .unwrap_or(false);
    let editing_mac = app.wizard_state.as_ref()
        .map(|s| matches!(s.editing_field, Some(WizardField::MacAddress)))
        .unwrap_or(false);

    if editing_mac {
        let mut bad_mac: Option<String> = None;
        if let Some(ref mut state) = app.wizard_state {
            match key.code {
                KeyCode::Esc => {
                    state.editing_field = None;
                    state.wizard_edit_buffer.clear();
                }
                KeyCode::Enter | KeyCode::Tab => {
                    let trimmed = state.wizard_edit_buffer.trim().to_string();
                    if trimmed.is_empty() {
                        state.qemu_config.mac_address = None;
                        state.editing_field = None;
                        state.wizard_edit_buffer.clear();
                    } else if crate::vm::mac::is_valid_mac(&trimmed) {
                        state.qemu_config.mac_address = Some(trimmed.to_lowercase());
                        state.editing_field = None;
                        state.wizard_edit_buffer.clear();
                    } else {
                        bad_mac = Some(trimmed);
                    }
                }
                KeyCode::Char(c) if c.is_ascii_hexdigit() || c == ':' => {
                    if state.wizard_edit_buffer.len() < 17 {
                        state.wizard_edit_buffer.push(c);
                    }
                }
                KeyCode::Backspace => {
                    state.wizard_edit_buffer.pop();
                }
                _ => {}
            }
        }
        if let Some(bad) = bad_mac {
            app.set_status(format!("Invalid MAC address: {}", bad));
        }
        return Ok(());
    }

    if editing_memory || editing_cpu {
        // Text input mode for Memory or CPU
        match key.code {
            KeyCode::Esc => {
                // Cancel edit, restore original value
                if let Some(ref mut state) = app.wizard_state {
                    state.editing_field = None;
                    state.wizard_edit_buffer.clear();
                }
            }
            KeyCode::Enter | KeyCode::Tab => {
                // Apply the edit
                if let Some(ref mut state) = app.wizard_state {
                    let buffer = state.wizard_edit_buffer.clone();
                    if editing_memory {
                        // Parse with suffix support (target: MB)
                        if let Some(value) = parse_size_with_suffix(&buffer, "MB") {
                            state.qemu_config.memory_mb = value.clamp(128, 1048576);
                        }
                    } else if editing_cpu {
                        // Parse as plain number
                        if let Ok(value) = buffer.trim().parse::<u32>() {
                            state.qemu_config.cpu_cores = value.clamp(1, 256);
                        }
                    }
                    state.editing_field = None;
                    state.wizard_edit_buffer.clear();
                }
            }
            KeyCode::Char(c) if c.is_ascii_alphanumeric() => {
                if let Some(ref mut state) = app.wizard_state {
                    state.wizard_edit_buffer.push(c);
                }
            }
            KeyCode::Backspace => {
                if let Some(ref mut state) = app.wizard_state {
                    state.wizard_edit_buffer.pop();
                }
            }
            KeyCode::Left | KeyCode::Right => {
                // Allow arrow keys to still adjust while editing
                let delta = if key.code == KeyCode::Right { 1i32 } else { -1i32 };
                handle_qemu_field_change(app, delta);
                // Update buffer to reflect new value
                if let Some(ref mut state) = app.wizard_state {
                    if editing_memory {
                        state.wizard_edit_buffer = state.qemu_config.memory_mb.to_string();
                    } else if editing_cpu {
                        state.wizard_edit_buffer = state.qemu_config.cpu_cores.to_string();
                    }
                }
            }
            _ => {}
        }
        return Ok(());
    }

    match key.code {
        KeyCode::Esc => {
            app.wizard_prev_step();
        }
        KeyCode::Enter => {
            // Check if on PortForwards field
            let on_pf = app.wizard_state.as_ref()
                .map(|s| QemuField::from_index(s.field_focus) == QemuField::PortForwards)
                .unwrap_or(false);
            if on_pf {
                app.wizard_editing_port_forwards = true;
                app.wizard_pf_selected = 0;
                app.wizard_adding_pf = None;
            } else {
                let _ = app.wizard_next_step();
            }
        }
        KeyCode::Tab => {
            // Enter edit mode for Memory, CPU, or MAC fields
            if let Some(ref mut state) = app.wizard_state {
                let field = QemuField::from_index(state.field_focus);
                match field {
                    QemuField::Memory => {
                        state.editing_field = Some(WizardField::MemoryMb);
                        state.wizard_edit_buffer = state.qemu_config.memory_mb.to_string();
                    }
                    QemuField::CpuCores => {
                        state.editing_field = Some(WizardField::CpuCores);
                        state.wizard_edit_buffer = state.qemu_config.cpu_cores.to_string();
                    }
                    QemuField::MacAddress if state.qemu_config.network_model != "none" => {
                        state.editing_field = Some(WizardField::MacAddress);
                        state.wizard_edit_buffer = state
                            .qemu_config
                            .mac_address
                            .clone()
                            .unwrap_or_default();
                    }
                    _ => {}
                }
            }
        }
        KeyCode::Char('g') => {
            if let Some(ref mut state) = app.wizard_state {
                let field = QemuField::from_index(state.field_focus);
                if field == QemuField::MacAddress && state.qemu_config.network_model != "none" {
                    state.qemu_config.mac_address = Some(crate::vm::mac::generate_random_mac());
                }
            }
        }
        KeyCode::Char('c') => {
            if let Some(ref mut state) = app.wizard_state {
                let field = QemuField::from_index(state.field_focus);
                if field == QemuField::MacAddress {
                    state.qemu_config.mac_address = None;
                }
            }
        }
        KeyCode::Char('j') | KeyCode::Down => {
            if let Some(ref mut state) = app.wizard_state {
                if state.field_focus < field_count - 1 {
                    state.field_focus += 1;
                }
            }
        }
        KeyCode::Char('k') | KeyCode::Up => {
            if let Some(ref mut state) = app.wizard_state {
                if state.field_focus > 0 {
                    state.field_focus -= 1;
                }
            }
        }
        KeyCode::Left | KeyCode::Right => {
            let delta = if key.code == KeyCode::Right { 1i32 } else { -1i32 };
            handle_qemu_field_change(app, delta);
            // Show warning if spice-app selected without viewer
            if let Some(ref state) = app.wizard_state {
                if state.qemu_config.display.contains("spice")
                    && !crate::commands::qemu_system::is_spice_viewer_available()
                {
                    app.set_status("Warning: spice-app requires virt-viewer/remote-viewer to be installed");
                }
            }
        }
        KeyCode::Char(' ') => {
            // Toggle for boolean fields
            if let Some(ref mut state) = app.wizard_state {
                let field = QemuField::from_index(state.field_focus);
                match field {
                    QemuField::Kvm => state.qemu_config.enable_kvm = !state.qemu_config.enable_kvm,
                    QemuField::GlAccel => {
                        state.qemu_config.gl_acceleration = !state.qemu_config.gl_acceleration;
                        // Enabling GL acceleration requires virtio VGA and works best with SDL
                        if state.qemu_config.gl_acceleration {
                            if state.qemu_config.vga != "virtio" {
                                state.qemu_config.vga = "virtio".to_string();
                            }
                            // SDL has better performance for 3D acceleration than GTK
                            if state.qemu_config.display == "gtk" {
                                state.qemu_config.display = "sdl".to_string();
                            }
                        }
                    }
                    QemuField::Uefi => state.qemu_config.uefi = !state.qemu_config.uefi,
                    QemuField::Tpm => state.qemu_config.tpm = !state.qemu_config.tpm,
                    QemuField::UsbTablet => state.qemu_config.usb_tablet = !state.qemu_config.usb_tablet,
                    QemuField::RtcLocal => state.qemu_config.rtc_localtime = !state.qemu_config.rtc_localtime,
                    _ => {}
                }
            }
        }
        KeyCode::Char('r') | KeyCode::Char('R') => {
            // Reset to profile defaults
            if let Some(profile) = app.wizard_selected_profile().cloned() {
                if let Some(ref mut state) = app.wizard_state {
                    state.qemu_config = WizardQemuConfig::from_profile(&profile);
                }
            }
        }
        _ => {}
    }
    Ok(())
}

fn handle_wizard_port_forward_editor(app: &mut App, key: KeyEvent) -> Result<()> {
    use crate::app::{AddPfStep, AddingPortForward};
    use crate::vm::qemu_config::{PortForward, PortProtocol};

    // Handle adding mode
    if let Some(ref mut adding) = app.wizard_adding_pf {
        match key.code {
            KeyCode::Esc => {
                app.wizard_adding_pf = None;
            }
            KeyCode::Enter => {
                match adding.step {
                    AddPfStep::Protocol => {
                        adding.step = AddPfStep::HostPort;
                    }
                    AddPfStep::HostPort => {
                        if adding.host_port_input.parse::<u16>().is_ok() {
                            adding.step = AddPfStep::GuestPort;
                        }
                    }
                    AddPfStep::GuestPort => {
                        if let (Ok(host), Ok(guest)) = (
                            adding.host_port_input.parse::<u16>(),
                            adding.guest_port_input.parse::<u16>(),
                        ) {
                            let pf = PortForward {
                                protocol: adding.protocol,
                                host_port: host,
                                guest_port: guest,
                            };
                            if let Some(ref mut state) = app.wizard_state {
                                state.qemu_config.port_forwards.push(pf);
                            }
                            app.wizard_adding_pf = None;
                        }
                    }
                }
            }
            KeyCode::Left | KeyCode::Right => {
                if adding.step == AddPfStep::Protocol {
                    adding.protocol = match adding.protocol {
                        PortProtocol::Tcp => PortProtocol::Udp,
                        PortProtocol::Udp => PortProtocol::Tcp,
                    };
                }
            }
            KeyCode::Char(c) if c.is_ascii_digit() => {
                match adding.step {
                    AddPfStep::HostPort => adding.host_port_input.push(c),
                    AddPfStep::GuestPort => adding.guest_port_input.push(c),
                    _ => {}
                }
            }
            KeyCode::Backspace => {
                match adding.step {
                    AddPfStep::HostPort => { adding.host_port_input.pop(); }
                    AddPfStep::GuestPort => { adding.guest_port_input.pop(); }
                    _ => {}
                }
            }
            _ => {}
        }
        return Ok(());
    }

    // Normal port forward list mode
    match key.code {
        KeyCode::Esc => {
            app.wizard_editing_port_forwards = false;
        }
        KeyCode::Char('j') | KeyCode::Down => {
            let pf_len = app.wizard_state.as_ref()
                .map(|s| s.qemu_config.port_forwards.len())
                .unwrap_or(0);
            if app.wizard_pf_selected < pf_len.saturating_sub(1) {
                app.wizard_pf_selected += 1;
            }
        }
        KeyCode::Char('k') | KeyCode::Up => {
            if app.wizard_pf_selected > 0 {
                app.wizard_pf_selected -= 1;
            }
        }
        KeyCode::Char('a') | KeyCode::Enter => {
            app.wizard_adding_pf = Some(AddingPortForward {
                step: AddPfStep::Protocol,
                protocol: PortProtocol::Tcp,
                host_port_input: String::new(),
                guest_port_input: String::new(),
            });
        }
        KeyCode::Char('d') | KeyCode::Delete => {
            if let Some(ref mut state) = app.wizard_state {
                if !state.qemu_config.port_forwards.is_empty()
                    && app.wizard_pf_selected < state.qemu_config.port_forwards.len()
                {
                    state.qemu_config.port_forwards.remove(app.wizard_pf_selected);
                    if app.wizard_pf_selected >= state.qemu_config.port_forwards.len()
                        && app.wizard_pf_selected > 0
                    {
                        app.wizard_pf_selected -= 1;
                    }
                }
            }
        }
        // Presets
        KeyCode::Char('1') => add_wizard_preset(app, PortProtocol::Tcp, 2222, 22),
        KeyCode::Char('2') => add_wizard_preset(app, PortProtocol::Tcp, 13389, 3389),
        KeyCode::Char('3') => add_wizard_preset(app, PortProtocol::Tcp, 8080, 80),
        KeyCode::Char('4') => add_wizard_preset(app, PortProtocol::Tcp, 8443, 443),
        KeyCode::Char('5') => add_wizard_preset(app, PortProtocol::Tcp, 15900, 5900),
        _ => {}
    }
    Ok(())
}

fn add_wizard_preset(app: &mut App, protocol: crate::vm::qemu_config::PortProtocol, host_port: u16, guest_port: u16) {
    if let Some(ref mut state) = app.wizard_state {
        if !state.qemu_config.port_forwards.iter().any(|pf| pf.host_port == host_port && pf.guest_port == guest_port) {
            state.qemu_config.port_forwards.push(crate::vm::qemu_config::PortForward {
                protocol,
                host_port,
                guest_port,
            });
        }
    }
}

/// Render the port-forward editor as a popup over the wizard dialog.
fn render_wizard_port_forward_editor(app: &App, frame: &mut Frame, parent: Rect) {
    let Some(state) = app.wizard_state.as_ref() else { return };

    // Centered popup, sized to the parent dialog.
    let width = parent.width.saturating_sub(8).min(64);
    let height = parent.height.saturating_sub(6).min(16);
    let x = parent.x + (parent.width.saturating_sub(width)) / 2;
    let y = parent.y + (parent.height.saturating_sub(height)) / 2;
    let area = Rect { x, y, width, height };

    frame.render_widget(Clear, area);

    let block = Block::default()
        .title(" Port Forwarding ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Yellow))
        .style(Style::default().bg(Color::Black));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    // Add-rule sub-dialog takes over the whole popup when active.
    if let Some(adding) = app.wizard_adding_pf.as_ref() {
        render_wizard_adding_pf(adding, frame, inner);
        return;
    }

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([
            Constraint::Min(3),       // Rules list
            Constraint::Length(1),    // Spacer
            Constraint::Length(1),    // Presets
            Constraint::Length(1),    // Help
        ])
        .split(inner);

    // Rules list
    let pfs = &state.qemu_config.port_forwards;
    if pfs.is_empty() {
        let msg = Paragraph::new("  No port forwarding rules configured.")
            .style(Style::default().fg(Color::DarkGray));
        frame.render_widget(msg, chunks[0]);
    } else {
        let mut lines = Vec::new();
        for (i, pf) in pfs.iter().enumerate() {
            let is_selected = i == app.wizard_pf_selected;
            let prefix = if is_selected { "> " } else { "  " };
            let style = if is_selected {
                Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::White)
            };
            lines.push(Line::styled(
                format!("{}{}  {} -> {}", prefix, pf.protocol, pf.host_port, pf.guest_port),
                style,
            ));
        }
        frame.render_widget(Paragraph::new(lines), chunks[0]);
    }

    let presets = Paragraph::new("  Presets: [1] SSH  [2] RDP  [3] HTTP  [4] HTTPS  [5] VNC")
        .style(Style::default().fg(Color::DarkGray));
    frame.render_widget(presets, chunks[2]);

    let help = Paragraph::new("[a] Add  [d] Delete  [1-5] Preset  [Esc] Done")
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Center);
    frame.render_widget(help, chunks[3]);
}

/// Render the "add a port forward rule" prompt inside the editor popup.
fn render_wizard_adding_pf(adding: &crate::app::AddingPortForward, frame: &mut Frame, area: Rect) {
    use crate::app::AddPfStep;

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([
            Constraint::Length(1),    // Header
            Constraint::Length(1),    // Spacer
            Constraint::Length(1),    // Protocol
            Constraint::Length(1),    // Host port
            Constraint::Length(1),    // Guest port
            Constraint::Min(1),       // Spacer
            Constraint::Length(1),    // Help
        ])
        .split(area);

    let header = Paragraph::new("Add Port Forward Rule")
        .style(Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD));
    frame.render_widget(header, chunks[0]);

    let active_style = Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD);
    let idle_style = Style::default().fg(Color::White);
    let hint_style = Style::default().fg(Color::DarkGray);

    // Protocol
    let proto_active = adding.step == AddPfStep::Protocol;
    let proto_line = Line::from(vec![
        Span::styled("  Protocol:   ", Style::default().fg(Color::Yellow)),
        Span::styled(
            format!("{}", adding.protocol),
            if proto_active { active_style } else { idle_style },
        ),
        Span::styled(
            if proto_active { "  [←/→] toggle" } else { "" },
            hint_style,
        ),
    ]);
    frame.render_widget(Paragraph::new(proto_line), chunks[2]);

    // Host port
    let host_active = adding.step == AddPfStep::HostPort;
    let host_value = if adding.host_port_input.is_empty() {
        "_".to_string()
    } else if host_active {
        format!("{}|", adding.host_port_input)
    } else {
        adding.host_port_input.clone()
    };
    let host_line = Line::from(vec![
        Span::styled("  Host Port:  ", Style::default().fg(Color::Yellow)),
        Span::styled(host_value, if host_active { active_style } else { idle_style }),
    ]);
    frame.render_widget(Paragraph::new(host_line), chunks[3]);

    // Guest port
    let guest_active = adding.step == AddPfStep::GuestPort;
    let guest_value = if adding.guest_port_input.is_empty() {
        "_".to_string()
    } else if guest_active {
        format!("{}|", adding.guest_port_input)
    } else {
        adding.guest_port_input.clone()
    };
    let guest_line = Line::from(vec![
        Span::styled("  Guest Port: ", Style::default().fg(Color::Yellow)),
        Span::styled(guest_value, if guest_active { active_style } else { idle_style }),
    ]);
    frame.render_widget(Paragraph::new(guest_line), chunks[4]);

    let help = Paragraph::new("[Enter] Next/Confirm  [Esc] Cancel")
        .style(hint_style)
        .alignment(Alignment::Center);
    frame.render_widget(help, chunks[6]);
}

fn handle_qemu_field_change(app: &mut App, delta: i32) {
    // Get dynamic display options based on the current emulator
    let emulator = app.wizard_state.as_ref()
        .map(|s| s.qemu_config.emulator.clone())
        .unwrap_or_else(|| "qemu-system-x86_64".to_string());
    let dynamic_display_options = app.get_display_options_for_emulator(&emulator);

    // Collect network backend options before mutable borrow
    let backend_options: Vec<String> = app.get_network_backend_options()
        .iter()
        .map(|(id, _)| id.to_string())
        .collect();
    let system_bridges = app.network_caps.system_bridges.clone();
    let default_bridge = system_bridges.first().cloned()
        .or_else(|| Some("qemubr0".to_string()));

    let Some(ref mut state) = app.wizard_state else { return };
    let field = QemuField::from_index(state.field_focus);

    match field {
        QemuField::Memory => {
            let change = 256 * delta;
            state.qemu_config.memory_mb = (state.qemu_config.memory_mb as i32 + change).clamp(128, 1048576) as u32;
        }
        QemuField::CpuCores => {
            state.qemu_config.cpu_cores = (state.qemu_config.cpu_cores as i32 + delta).clamp(1, 256) as u32;
        }
        QemuField::Vga => {
            cycle_option(&mut state.qemu_config.vga, VGA_OPTIONS, delta);
        }
        QemuField::Audio => {
            cycle_audio(&mut state.qemu_config.audio, delta);
        }
        QemuField::Network => {
            cycle_option(&mut state.qemu_config.network_model, NETWORK_OPTIONS, delta);
        }
        QemuField::NetBackend => {
            let backend_strs: Vec<&str> = backend_options.iter().map(|s| s.as_str()).collect();
            cycle_option(&mut state.qemu_config.network_backend, &backend_strs, delta);

            // Set default bridge name when switching to bridge
            if state.qemu_config.network_backend == "bridge" && state.qemu_config.bridge_name.is_none() {
                state.qemu_config.bridge_name = default_bridge.clone();
            }
        }
        QemuField::BridgeName => {
            // Cycle through available system bridges
            if !system_bridges.is_empty() {
                let current_bridge = state.qemu_config.bridge_name.as_deref().unwrap_or("");
                let current_idx = system_bridges.iter()
                    .position(|b| b == current_bridge)
                    .unwrap_or(0);
                let new_idx = (current_idx as i32 + delta)
                    .rem_euclid(system_bridges.len() as i32) as usize;
                state.qemu_config.bridge_name = Some(system_bridges[new_idx].clone());
            }
        }
        QemuField::PortForwards => {
            // Handled via Enter key, not left/right
        }
        QemuField::DiskInterface => {
            cycle_option(&mut state.qemu_config.disk_interface, DISK_INTERFACE_OPTIONS, delta);
        }
        QemuField::Display => {
            // Use dynamic options from detected capabilities
            let display_strs: Vec<&str> = dynamic_display_options.iter().map(|s| s.as_str()).collect();
            if !display_strs.is_empty() {
                cycle_option(&mut state.qemu_config.display, &display_strs, delta);
            } else {
                cycle_option(&mut state.qemu_config.display, DISPLAY_OPTIONS, delta);
            }
        }
        // Toggles use space, not left/right
        _ => {}
    }
}

fn cycle_option(current: &mut String, options: &[&str], delta: i32) {
    let current_idx = options.iter().position(|&o| o == current.as_str()).unwrap_or(0);
    let new_idx = (current_idx as i32 + delta).rem_euclid(options.len() as i32) as usize;
    *current = options[new_idx].to_string();
}

fn cycle_audio(current: &mut Vec<String>, delta: i32) {
    // Find current audio preset
    let current_idx = AUDIO_OPTIONS.iter().position(|(_, devices)| {
        if devices.is_empty() && current.is_empty() {
            true
        } else if !devices.is_empty() && !current.is_empty() {
            current.iter().any(|c| devices.iter().any(|d| c.contains(d)))
        } else {
            false
        }
    }).unwrap_or(0);

    let new_idx = (current_idx as i32 + delta).rem_euclid(AUDIO_OPTIONS.len() as i32) as usize;
    let (_, devices) = AUDIO_OPTIONS[new_idx];
    *current = devices.iter().map(|&s| s.to_string()).collect();
}

// =============================================================================
// Step 5: Confirm
// =============================================================================

fn render_step_confirm(app: &App, frame: &mut Frame, area: Rect) {
    let state = app.wizard_state.as_ref().unwrap();

    let block = Block::default()
        .title(format!(" Create New VM ({}/5) - {} ", state.step.number(), state.step.title()))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Green))
        .style(Style::default().bg(Color::Black));

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

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([
            Constraint::Length(1),   // Header
            Constraint::Length(1),   // Spacer
            Constraint::Min(15),     // Summary
            Constraint::Length(3),   // Auto-launch toggle
            Constraint::Length(1),   // Error
            Constraint::Length(2),   // Help
        ])
        .split(inner);

    // Header
    let header = Paragraph::new("Summary")
        .style(Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD));
    frame.render_widget(header, chunks[0]);

    // Summary
    let os_name = state.selected_os.as_ref()
        .and_then(|id| app.qemu_profiles.get(id))
        .map(|p| p.display_name.as_str())
        .unwrap_or("Custom OS");

    let vm_path = app.wizard_vm_path()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "Unknown".to_string());

    let iso_str = state.iso_path.as_ref()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "None".to_string());

    let config = &state.qemu_config;

    let mut lines = Vec::new();
    lines.push(Line::from(vec![
        Span::styled("VM Name:        ", Style::default().fg(Color::Yellow)),
        Span::raw(&state.vm_name),
    ]));
    lines.push(Line::from(vec![
        Span::styled("Folder:         ", Style::default().fg(Color::Yellow)),
        Span::raw(vm_path),
    ]));
    lines.push(Line::from(vec![
        Span::styled("OS Type:        ", Style::default().fg(Color::Yellow)),
        Span::raw(os_name),
    ]));
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("Disk:           ", Style::default().fg(Color::Yellow)),
        Span::raw(format!("{} GB qcow2 (expandable)", state.disk_size_gb)),
    ]));
    lines.push(Line::from(vec![
        Span::styled("ISO:            ", Style::default().fg(Color::Yellow)),
        Span::raw(iso_str),
    ]));
    if let Some(ref floppy_path) = state.floppy_path {
        lines.push(Line::from(vec![
            Span::styled("Floppy:         ", Style::default().fg(Color::Yellow)),
            Span::raw(floppy_path.display().to_string()),
        ]));
    }
    if let Some(ref rom_path) = state.bios_rom_path {
        lines.push(Line::from(vec![
            Span::styled("BIOS/ROM:       ", Style::default().fg(Color::Yellow)),
            Span::raw(rom_path.display().to_string()),
        ]));
    }
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("Hardware:       ", Style::default().fg(Color::Yellow)),
        Span::raw(format!("{} cores, {} MB RAM", config.cpu_cores, config.memory_mb)),
    ]));
    lines.push(Line::from(vec![
        Span::styled("Graphics:       ", Style::default().fg(Color::Yellow)),
        Span::raw(&config.vga),
    ]));
    lines.push(Line::from(vec![
        Span::styled("Audio:          ", Style::default().fg(Color::Yellow)),
        Span::raw(config.audio.first().cloned().unwrap_or_else(|| "None".to_string())),
    ]));
    let net_display = if config.network_model == "none" {
        "none".to_string()
    } else {
        let backend_str = match config.network_backend.as_str() {
            "passt" => "passt".to_string(),
            "bridge" => format!("bridge ({})", config.bridge_name.as_deref().unwrap_or("qemubr0")),
            "none" => "disabled".to_string(),
            _ => "user/SLIRP (NAT)".to_string(),
        };
        format!("{} ({})", config.network_model, backend_str)
    };
    lines.push(Line::from(vec![
        Span::styled("Network:        ", Style::default().fg(Color::Yellow)),
        Span::raw(net_display),
    ]));
    if !config.port_forwards.is_empty() {
        for pf in &config.port_forwards {
            lines.push(Line::from(format!("                {} {} -> {}", pf.protocol, pf.host_port, pf.guest_port)));
        }
    }

    let accel = if config.enable_kvm { "KVM enabled" } else { "No acceleration" };
    lines.push(Line::from(vec![
        Span::styled("Acceleration:   ", Style::default().fg(Color::Yellow)),
        Span::raw(accel),
    ]));

    let summary = Paragraph::new(lines)
        .wrap(Wrap { trim: false });
    frame.render_widget(summary, chunks[2]);

    // Auto-launch toggle
    let launch_box = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Gray));
    let checkbox = if state.auto_launch { "[x]" } else { "[ ]" };
    let launch_text = Paragraph::new(format!("{} Launch VM in install mode after creation", checkbox))
        .style(Style::default().fg(Color::White))
        .block(launch_box);
    frame.render_widget(launch_text, chunks[3]);

    // Error
    if let Some(ref error) = state.error_message {
        let error_text = Paragraph::new(error.as_str())
            .style(Style::default().fg(Color::Red));
        frame.render_widget(error_text, chunks[4]);
    }

    // Help
    let help = Paragraph::new("[Enter] Create VM  [Space] Toggle launch  [Esc] Back")
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Center);
    frame.render_widget(help, chunks[5]);
}

fn handle_step_confirm(app: &mut App, key: KeyEvent) -> Result<()> {
    match key.code {
        KeyCode::Esc => {
            app.wizard_prev_step();
        }
        KeyCode::Char(' ') => {
            if let Some(ref mut state) = app.wizard_state {
                state.auto_launch = !state.auto_launch;
            }
        }
        KeyCode::Enter => {
            // Create the VM
            let (library_path, auto_launch) = {
                let state = app.wizard_state.as_ref().unwrap();
                let path = app.config.vm_library_path.clone();
                let launch = state.auto_launch;
                (path, launch)
            };

            // Clone the state for creation
            let state = app.wizard_state.as_ref().unwrap().clone();
            let vm_name = state.vm_name.clone();

            match create_vm(&library_path, &state) {
                Ok(created) => {
                    // Cancel wizard first (closes screens)
                    app.cancel_wizard();

                    // Refresh VM list to include the new VM
                    match app.refresh_vms() {
                        Ok(()) => {
                            app.set_status(format!("VM created: {}", vm_name));
                        }
                        Err(e) => {
                            app.set_status(format!("VM created but refresh failed: {}", e));
                        }
                    }

                    // If auto_launch is enabled, find and launch the new VM
                    if auto_launch {
                        // Find the newly created VM and select it
                        if let Some(idx) = app.vms.iter().position(|vm| {
                            vm.launch_script == created.launch_script
                        }) {
                            // Find in visual order
                            if let Some(visual_idx) = app.visual_order.iter().position(|&filtered_idx| {
                                app.filtered_indices.get(filtered_idx) == Some(&idx)
                            }) {
                                app.selected_vm = visual_idx;

                                // Set boot mode to install
                                app.boot_mode = crate::vm::BootMode::Install;

                                // Launch the VM
                                match launch_created_vm(app) {
                                    Ok(()) => {
                                        app.set_status(format!("Launched: {}", vm_name));
                                    }
                                    Err(e) => {
                                        app.set_status(format!("VM created but launch failed: {}", e));
                                    }
                                }
                            }
                        }
                    }
                }
                Err(e) => {
                    if let Some(ref mut state) = app.wizard_state {
                        state.error_message = Some(format!("Failed to create VM: {}", e));
                    }
                }
            }
        }
        _ => {}
    }
    Ok(())
}

/// Launch a newly created VM
fn launch_created_vm(app: &mut App) -> Result<()> {
    if let Some(vm) = app.selected_vm() {
        let options = app.get_launch_options();
        crate::vm::launch_vm_sync(vm, &options)?;
    }
    Ok(())
}

/// Open a URL in the default browser
fn open_url_in_browser(url: &str) -> Result<()> {
    use std::process::Command;

    // Try xdg-open first (standard on Linux)
    let result = Command::new("xdg-open")
        .arg(url)
        .spawn();

    match result {
        Ok(_) => Ok(()),
        Err(_) => {
            // Fallback to other openers
            for opener in &["firefox", "chromium", "google-chrome", "open"] {
                if Command::new(opener).arg(url).spawn().is_ok() {
                    return Ok(());
                }
            }
            anyhow::bail!("No browser found. Please visit: {}", url)
        }
    }
}

// =============================================================================
// Utility
// =============================================================================

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)
}

#[cfg(test)]
#[path = "tests/create_wizard.rs"]
mod tests;