aethermap-gui 1.4.3

GUI client for aethermap input remapper
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
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
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
use iced::{
    widget::{
        button, checkbox, column, container, row, text, text_input, scrollable,
        horizontal_rule, vertical_rule, pick_list, slider, Column, Space,
    },
    Element, Length, Subscription, Theme, Application, Command, Color,
    Alignment,
};
use std::sync::Arc;
use crate::theme::{aether_dark, aether_light, container_styles};

// Import custom widgets
use crate::widgets::{AnalogVisualizer, CurveGraph, analog_visualizer::DeadzoneShape as WidgetDeadzoneShape};
use aethermap_common::{DeviceInfo, DeviceCapabilities, DeviceType, LayerConfigInfo, LayerMode, LedPattern, LedZone, MacroEntry, MacroSettings, RemapProfileInfo, RemapEntry, Action, AnalogMode, CameraOutputMode, Request, Response, AutoSwitchRule as CommonAutoSwitchRule};
use aethermap_common::HotkeyBinding as CommonHotkeyBinding;
use aethermap_common::ipc_client::IpcClient;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::collections::{VecDeque, HashMap, HashSet};
use std::time::{Duration, Instant};

// Import focus_tracker types - need to use path from lib.rs root
// Since we're in gui.rs (a module of aethermap_gui library),
// we access sibling modules via super:: or direct path when in closures

// Razer brand colors (for future custom theming)
// const RAZER_GREEN: Color = Color::from_rgb(0.267, 0.839, 0.173); // #44D62C
// const RAZER_GREEN_DIM: Color = Color::from_rgb(0.176, 0.561, 0.118); // #2D8F1E
// const BG_DEEP: Color = Color::from_rgb(0.051, 0.051, 0.051); // #0D0D0D
// const BG_SURFACE: Color = Color::from_rgb(0.102, 0.102, 0.102); // #1A1A1A
// const BG_ELEVATED: Color = Color::from_rgb(0.141, 0.141, 0.141); // #242424
// const TEXT_PRIMARY: Color = Color::WHITE;
// const TEXT_SECONDARY: Color = Color::from_rgb(0.702, 0.702, 0.702); // #B3B3B3
// const TEXT_MUTED: Color = Color::from_rgb(0.400, 0.400, 0.400); // #666666
// const DANGER_RED: Color = Color::from_rgb(1.0, 0.231, 0.188); // #FF3B30
// const WARNING_YELLOW: Color = Color::from_rgb(1.0, 0.722, 0.0); // #FFB800

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tab {
    Devices,
    Macros,
    Profiles,
}

#[derive(Debug, Clone)]
pub struct Notification {
    pub message: String,
    pub is_error: bool,
    pub timestamp: Instant,
}

/// A button in the visual keypad layout
///
/// Represents the physical layout of a button on devices like the Azeron Cyborg.
/// Coordinates are in a 10x10 grid for layout positioning.
#[derive(Debug, Clone)]
pub struct KeypadButton {
    /// Button identifier (e.g., "JOY_BTN_0" through "JOY_BTN_25")
    pub id: String,
    /// Display label for the button
    pub label: String,
    /// Grid row (0-9) for layout positioning
    pub row: usize,
    /// Grid column (0-9) for layout positioning - reserved for future 2D layout use
    #[allow(dead_code)]
    pub col: usize,
    /// Current remapping target (if any)
    pub current_remap: Option<String>,
}

/// Azeron Cyborg keypad layout definition
///
/// Returns the button layout for the Azeron Cyborg keypad with all 26 joystick buttons.
/// The layout positions buttons in a grid approximating the physical device.
pub fn azeron_keypad_layout() -> Vec<KeypadButton> {
    vec![
        // Top function row (5 buttons)
        KeypadButton { id: "JOY_BTN_0".to_string(), label: "1".to_string(), row: 0, col: 0, current_remap: None },
        KeypadButton { id: "JOY_BTN_1".to_string(), label: "2".to_string(), row: 0, col: 1, current_remap: None },
        KeypadButton { id: "JOY_BTN_2".to_string(), label: "3".to_string(), row: 0, col: 2, current_remap: None },
        KeypadButton { id: "JOY_BTN_3".to_string(), label: "4".to_string(), row: 0, col: 3, current_remap: None },
        KeypadButton { id: "JOY_BTN_4".to_string(), label: "5".to_string(), row: 0, col: 4, current_remap: None },

        // Main keyboard area (QWERTY-style layout, 12 buttons)
        KeypadButton { id: "JOY_BTN_5".to_string(), label: "Q".to_string(), row: 2, col: 0, current_remap: None },
        KeypadButton { id: "JOY_BTN_6".to_string(), label: "W".to_string(), row: 2, col: 1, current_remap: None },
        KeypadButton { id: "JOY_BTN_7".to_string(), label: "E".to_string(), row: 2, col: 2, current_remap: None },
        KeypadButton { id: "JOY_BTN_8".to_string(), label: "R".to_string(), row: 2, col: 3, current_remap: None },
        KeypadButton { id: "JOY_BTN_9".to_string(), label: "A".to_string(), row: 3, col: 0, current_remap: None },
        KeypadButton { id: "JOY_BTN_10".to_string(), label: "S".to_string(), row: 3, col: 1, current_remap: None },
        KeypadButton { id: "JOY_BTN_11".to_string(), label: "D".to_string(), row: 3, col: 2, current_remap: None },
        KeypadButton { id: "JOY_BTN_12".to_string(), label: "F".to_string(), row: 3, col: 3, current_remap: None },
        KeypadButton { id: "JOY_BTN_13".to_string(), label: "Z".to_string(), row: 4, col: 0, current_remap: None },
        KeypadButton { id: "JOY_BTN_14".to_string(), label: "X".to_string(), row: 4, col: 1, current_remap: None },
        KeypadButton { id: "JOY_BTN_15".to_string(), label: "C".to_string(), row: 4, col: 2, current_remap: None },
        KeypadButton { id: "JOY_BTN_16".to_string(), label: "V".to_string(), row: 4, col: 3, current_remap: None },

        // Number/extra keys (5 buttons)
        KeypadButton { id: "JOY_BTN_17".to_string(), label: "6".to_string(), row: 0, col: 5, current_remap: None },
        KeypadButton { id: "JOY_BTN_18".to_string(), label: "7".to_string(), row: 1, col: 5, current_remap: None },
        KeypadButton { id: "JOY_BTN_19".to_string(), label: "8".to_string(), row: 2, col: 5, current_remap: None },
        KeypadButton { id: "JOY_BTN_20".to_string(), label: "9".to_string(), row: 3, col: 5, current_remap: None },
        KeypadButton { id: "JOY_BTN_21".to_string(), label: "0".to_string(), row: 4, col: 5, current_remap: None },

        // Thumb cluster (5 buttons)
        KeypadButton { id: "JOY_BTN_22".to_string(), label: "TL".to_string(), row: 6, col: 0, current_remap: None },
        KeypadButton { id: "JOY_BTN_23".to_string(), label: "TM".to_string(), row: 6, col: 1, current_remap: None },
        KeypadButton { id: "JOY_BTN_24".to_string(), label: "TR".to_string(), row: 6, col: 2, current_remap: None },
        KeypadButton { id: "JOY_BTN_25".to_string(), label: "BL".to_string(), row: 7, col: 0, current_remap: None },
        KeypadButton { id: "JOY_BTN_26".to_string(), label: "BR".to_string(), row: 7, col: 1, current_remap: None },
    ]
}

/// Auto-switch rule for profile switching based on focused window
///
/// GUI representation of AutoSwitchRule from the daemon config.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoSwitchRule {
    /// Application identifier to match (e.g., "org.alacritty", "firefox", "*")
    pub app_id: String,
    /// Profile name to activate when this app has focus
    pub profile_name: String,
    /// Device ID to apply profile to (None = all devices)
    pub device_id: Option<String>,
    /// Layer ID to activate (None = profile default)
    pub layer_id: Option<usize>,
}

/// Auto-switch rules view state
///
/// Manages the UI for configuring auto-profile switching rules.
#[derive(Debug, Clone, Default)]
pub struct AutoSwitchRulesView {
    /// Device ID being configured
    pub device_id: String,
    /// List of configured rules
    pub rules: Vec<AutoSwitchRule>,
    /// Currently editing rule index (None = adding new)
    pub editing_rule: Option<usize>,
    /// New rule app_id input
    pub new_app_id: String,
    /// New rule profile_name input
    pub new_profile_name: String,
    /// New rule layer_id input
    pub new_layer_id: String,
}

/// Hotkey binding for manual profile switching
///
/// GUI representation of HotkeyBinding from the daemon config.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HotkeyBinding {
    /// Modifier keys (Ctrl, Alt, Shift, Super)
    pub modifiers: Vec<String>,
    /// Trigger key (number 1-9 for profile switching)
    pub key: String,
    /// Profile to activate when hotkey pressed
    pub profile_name: String,
    /// Device to apply to (None = all devices)
    pub device_id: Option<String>,
    /// Layer to activate (None = profile default)
    pub layer_id: Option<usize>,
}

/// Hotkey bindings view state
///
/// Manages the UI for configuring global hotkey bindings.
#[derive(Debug, Clone, Default)]
pub struct HotkeyBindingsView {
    /// Device ID being configured
    pub device_id: String,
    /// List of configured bindings
    pub bindings: Vec<HotkeyBinding>,
    /// Currently editing binding index (None = adding new)
    pub editing_binding: Option<usize>,
    /// New binding modifiers (checkboxes)
    pub new_modifiers: Vec<String>,
    /// New binding key input
    pub new_key: String,
    /// New binding profile_name input
    pub new_profile_name: String,
    /// New binding layer_id input
    pub new_layer_id: String,
}

/// Deadzone shape for analog calibration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeadzoneShape {
    Circular,
    Square,
}

impl std::fmt::Display for DeadzoneShape {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DeadzoneShape::Circular => write!(f, "Circular"),
            DeadzoneShape::Square => write!(f, "Square"),
        }
    }
}

impl DeadzoneShape {
    pub const ALL: [DeadzoneShape; 2] = [DeadzoneShape::Circular, DeadzoneShape::Square];
}

impl Default for DeadzoneShape {
    fn default() -> Self {
        Self::Circular
    }
}

/// Sensitivity curve for analog calibration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SensitivityCurve {
    Linear,
    Quadratic,
    Exponential,
}

impl std::fmt::Display for SensitivityCurve {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SensitivityCurve::Linear => write!(f, "Linear"),
            SensitivityCurve::Quadratic => write!(f, "Quadratic"),
            SensitivityCurve::Exponential => write!(f, "Exponential"),
        }
    }
}

impl SensitivityCurve {
    pub const ALL: [SensitivityCurve; 3] = [
        SensitivityCurve::Linear,
        SensitivityCurve::Quadratic,
        SensitivityCurve::Exponential,
    ];
}

impl Default for SensitivityCurve {
    fn default() -> Self {
        Self::Linear
    }
}

/// Analog calibration configuration state (GUI version)
///
/// Tracks the calibration settings for analog stick processing.
/// This wraps the common type with Display conversion helpers.
#[derive(Debug, Clone)]
pub struct CalibrationConfig {
    pub deadzone: f32,
    pub deadzone_shape: String,
    pub sensitivity: String,
    pub sensitivity_multiplier: f32,
    pub range_min: i32,
    pub range_max: i32,
    pub invert_x: bool,
    pub invert_y: bool,
    pub exponent: f32,
}

impl Default for CalibrationConfig {
    fn default() -> Self {
        Self {
            deadzone: 0.15,
            deadzone_shape: "circular".to_string(),
            sensitivity: "linear".to_string(),
            sensitivity_multiplier: 1.0,
            range_min: -32768,
            range_max: 32767,
            invert_x: false,
            invert_y: false,
            exponent: 2.0,
        }
    }
}

/// Analog calibration view state
///
/// Manages the UI for configuring analog stick calibration settings.
#[derive(Debug)]
pub struct AnalogCalibrationView {
    /// Device ID being configured
    pub device_id: String,
    /// Layer ID being configured
    pub layer_id: usize,
    /// Current calibration settings
    pub calibration: CalibrationConfig,

    /// Deadzone shape selection
    pub deadzone_shape_selected: DeadzoneShape,
    /// Sensitivity curve selection
    pub sensitivity_curve_selected: SensitivityCurve,

    /// Analog mode selection
    pub analog_mode_selected: AnalogMode,
    /// Camera output mode selection (when analog_mode is Camera)
    pub camera_mode_selected: CameraOutputMode,

    /// Inversion checkboxes
    pub invert_x_checked: bool,
    pub invert_y_checked: bool,

    /// Current stick position for visualization (-1.0 to 1.0)
    pub stick_x: f32,
    /// Current stick position for visualization (-1.0 to 1.0)
    pub stick_y: f32,

    /// Loading state
    pub loading: bool,
    /// Error message if any
    pub error: Option<String>,

    /// Last time visualizer was updated (for throttling to ~30 FPS)
    /// Not cloned - reset to Instant::now() on clone
    pub last_visualizer_update: Instant,

    /// Canvas cache for visualizer static elements (deadzone, axes)
    /// Cleared when deadzone or shape changes.
    /// Wrapped in Arc for sharing across widget instances.
    pub visualizer_cache: Arc<iced::widget::canvas::Cache>,
}

// Manual Clone implementation since Instant doesn't implement Clone
// Cache is wrapped in Arc so it can be cloned (shared)
impl Clone for AnalogCalibrationView {
    fn clone(&self) -> Self {
        Self {
            device_id: self.device_id.clone(),
            layer_id: self.layer_id,
            calibration: self.calibration.clone(),
            deadzone_shape_selected: self.deadzone_shape_selected,
            sensitivity_curve_selected: self.sensitivity_curve_selected,
            analog_mode_selected: self.analog_mode_selected,
            camera_mode_selected: self.camera_mode_selected,
            invert_x_checked: self.invert_x_checked,
            invert_y_checked: self.invert_y_checked,
            stick_x: self.stick_x,
            stick_y: self.stick_y,
            loading: self.loading,
            error: self.error.clone(),
            // Reset to now for cloned instances - throttling will work correctly
            last_visualizer_update: Instant::now(),
            // Arc allows cloning the cache reference
            visualizer_cache: Arc::clone(&self.visualizer_cache),
        }
    }
}

impl Default for AnalogCalibrationView {
    fn default() -> Self {
        Self {
            device_id: String::new(),
            layer_id: 0,
            calibration: CalibrationConfig::default(),
            deadzone_shape_selected: DeadzoneShape::Circular,
            sensitivity_curve_selected: SensitivityCurve::Linear,
            analog_mode_selected: AnalogMode::Disabled,
            camera_mode_selected: CameraOutputMode::Scroll,
            invert_x_checked: false,
            invert_y_checked: false,
            stick_x: 0.0,
            stick_y: 0.0,
            loading: false,
            error: None,
            last_visualizer_update: Instant::now(),
            visualizer_cache: Arc::new(iced::widget::canvas::Cache::default()),
        }
    }
}

/// LED configuration state for a device
///
/// Tracks current LED settings including per-zone colors,
/// brightness levels, and active pattern.
#[derive(Debug, Clone)]
pub struct LedState {
    /// Per-zone RGB colors (Logo, Keys, Thumbstick, etc.)
    pub zone_colors: HashMap<LedZone, (u8, u8, u8)>,
    /// Global brightness (0-100)
    pub global_brightness: u8,
    /// Per-zone brightness (0-100)
    pub zone_brightness: HashMap<LedZone, u8>,
    /// Active LED pattern
    pub active_pattern: LedPattern,
}

impl Default for LedState {
    fn default() -> Self {
        Self {
            zone_colors: HashMap::new(),
            global_brightness: 100,
            zone_brightness: HashMap::new(),
            active_pattern: LedPattern::Static,
        }
    }
}

pub struct State {
    pub devices: Vec<DeviceInfo>,
    pub macros: Vec<MacroEntry>,
    pub selected_device: Option<usize>,
    pub status: String,
    pub status_history: VecDeque<String>,
    pub loading: bool,
    pub recording: bool,
    pub recording_macro_name: Option<String>,
    pub daemon_connected: bool,
    pub new_macro_name: String,
    pub socket_path: PathBuf,
    pub recently_updated_macros: HashMap<String, Instant>,
    pub grabbed_devices: HashSet<String>,
    pub profile_name: String,
    pub active_tab: Tab,
    pub notifications: VecDeque<Notification>,
    pub recording_pulse: bool,
    /// Available profiles per device (device_id -> profile names)
    pub device_profiles: HashMap<String, Vec<String>>,
    /// Active profile per device (device_id -> profile name)
    pub active_profiles: HashMap<String, String>,
    /// Available remap profiles per device (device_path -> profile info)
    pub remap_profiles: HashMap<String, Vec<RemapProfileInfo>>,
    /// Active remap profile per device (device_path -> profile name)
    pub active_remap_profiles: HashMap<String, String>,
    /// Active remaps per device (device_path -> remap entries)
    pub active_remaps: HashMap<String, (String, Vec<RemapEntry>)>,
    /// Azeron keypad layout for selected device
    pub keypad_layout: Vec<KeypadButton>,
    /// Current device path being viewed in keypad layout
    pub keypad_view_device: Option<String>,
    /// Selected button for remapping (index into keypad_layout)
    pub selected_button: Option<usize>,
    /// Device capabilities for current selection
    pub device_capabilities: Option<DeviceCapabilities>,
    /// Active layer per device (device_id -> active_layer_id)
    pub active_layers: HashMap<String, usize>,
    /// Layer configurations per device (device_id -> layers)
    pub layer_configs: HashMap<String, Vec<LayerConfigInfo>>,
    /// Layer configuration dialog state (device_id, layer_id, name, mode)
    pub layer_config_dialog: Option<(String, usize, String, LayerMode)>,
    /// D-pad mode per device (device_id -> mode)
    pub analog_dpad_modes: HashMap<String, String>,
    /// Per-axis deadzone values (device_id -> (x_percentage, y_percentage))
    pub analog_deadzones_xy: HashMap<String, (u8, u8)>,
    /// Per-axis outer deadzone values (device_id -> (x_percentage, y_percentage))
    pub analog_outer_deadzones_xy: HashMap<String, (u8, u8)>,
    /// LED configuration state per device (device_id -> LedState)
    pub led_states: HashMap<String, LedState>,
    /// LED configuration dialog open for device
    pub led_config_device: Option<String>,
    /// Currently selected LED zone for color editing
    pub selected_led_zone: Option<LedZone>,
    /// Pending color picker values (r, g, b) before application
    pub pending_led_color: Option<(u8, u8, u8)>,
    /// Current focused application ID (for auto-switch rule creation)
    pub current_focus: Option<String>,
    /// Focus tracking is active
    pub focus_tracking_active: bool,
    /// Auto-switch rules view (open when configuring auto-profile switching)
    pub auto_switch_view: Option<AutoSwitchRulesView>,
    /// Hotkey bindings view (open when configuring hotkeys)
    pub hotkey_view: Option<HotkeyBindingsView>,
    /// Analog calibration view (open when configuring analog stick)
    pub analog_calibration_view: Option<AnalogCalibrationView>,
    /// Global macro timing and jitter settings
    pub macro_settings: MacroSettings,
    /// Current UI theme (Adaptive COSMIC)
    pub current_theme: Theme,
}

impl Default for State {
    fn default() -> Self {
        let socket_path = if cfg!(target_os = "linux") {
            PathBuf::from("/run/aethermap/aethermap.sock")
        } else if cfg!(target_os = "macos") {
            PathBuf::from("/tmp/aethermap.sock")
        } else {
            std::env::temp_dir().join("aethermap.sock")
        };
        State {
            devices: Vec::new(),
            macros: Vec::new(),
            selected_device: None,
            status: "Initializing...".to_string(),
            status_history: VecDeque::with_capacity(10),
            loading: false,
            recording: false,
            recording_macro_name: None,
            daemon_connected: false,
            new_macro_name: String::new(),
            socket_path,
            recently_updated_macros: HashMap::new(),
            grabbed_devices: HashSet::new(),
            profile_name: "default".to_string(),
            active_tab: Tab::Devices,
            notifications: VecDeque::with_capacity(5),
            recording_pulse: false,
            device_profiles: HashMap::new(),
            active_profiles: HashMap::new(),
            remap_profiles: HashMap::new(),
            active_remap_profiles: HashMap::new(),
            active_remaps: HashMap::new(),
            keypad_layout: Vec::new(),
            keypad_view_device: None,
            selected_button: None,
            device_capabilities: None,
            active_layers: HashMap::new(),
            layer_configs: HashMap::new(),
            layer_config_dialog: None,
            analog_dpad_modes: HashMap::new(),
            analog_deadzones_xy: HashMap::new(),
            analog_outer_deadzones_xy: HashMap::new(),
            led_states: HashMap::new(),
            led_config_device: None,
            selected_led_zone: None,
            pending_led_color: None,
            current_focus: None,
            focus_tracking_active: false,
            auto_switch_view: None,
            hotkey_view: None,
            analog_calibration_view: None,
            macro_settings: MacroSettings {
                latency_offset_ms: 0,
                jitter_pct: 0.0,
                capture_mouse: false,
            },
            current_theme: aether_dark(),
        }
    }
}

#[derive(Debug, Clone)]
pub enum Message {
    // Navigation
    SwitchTab(Tab),
    ThemeChanged(iced::Theme),

    // Device Management
    LoadDevices,
    DevicesLoaded(Result<Vec<DeviceInfo>, String>),
    GrabDevice(String),
    UngrabDevice(String),
    DeviceGrabbed(Result<String, String>),
    DeviceUngrabbed(Result<String, String>),
    SelectDevice(usize),

    // Macro Recording
    UpdateMacroName(String),
    StartRecording,
    StopRecording,
    RecordingStarted(Result<String, String>),
    RecordingStopped(Result<MacroEntry, String>),

    // Macro Management
    LoadMacros,
    MacrosLoaded(Result<Vec<MacroEntry>, String>),
    LoadMacroSettings,
    MacroSettingsLoaded(Result<MacroSettings, String>),
    SetMacroSettings(MacroSettings),
    LatencyChanged(u32),
    JitterChanged(f32),
    CaptureMouseToggled(bool),
    PlayMacro(String),
    MacroPlayed(Result<String, String>),
    DeleteMacro(String),
    MacroDeleted(Result<String, String>),

    // Profile Management
    UpdateProfileName(String),
    SaveProfile,
    ProfileSaved(Result<(String, usize), String>),
    LoadProfile,
    ProfileLoaded(Result<(String, usize), String>),

    // Device Profile Management
    LoadDeviceProfiles(String),
    DeviceProfilesLoaded(String, Result<Vec<String>, String>),
    ActivateProfile(String, String),
    ProfileActivated(String, String),
    DeactivateProfile(String),
    ProfileDeactivated(String),
    ProfileError(String),

    // Remap Profile Management
    LoadRemapProfiles(String),
    RemapProfilesLoaded(String, Result<Vec<RemapProfileInfo>, String>),
    ActivateRemapProfile(String, String),
    RemapProfileActivated(String, String),
    DeactivateRemapProfile(String),
    RemapProfileDeactivated(String),
    LoadActiveRemaps(String),
    ActiveRemapsLoaded(String, Result<Option<(String, Vec<RemapEntry>)>, String>),

    // Status
    CheckDaemonConnection,
    DaemonStatusChanged(bool),

    // UI
    TickAnimations,
    ShowNotification(String, bool), // (message, is_error)

    // Mouse Event Recording
    RecordMouseEvent {
        event_type: String,
        button: Option<u16>,
        x: i32,
        y: i32,
        delta: i32,
    },

    // Keypad Remapping
    /// Show keypad remapping view for a device
    ShowKeypadView(String),
    /// Select a keypad button for remapping
    SelectKeypadButton(String),
    /// Load device capabilities for keypad view
    DeviceCapabilitiesLoaded(String, Result<DeviceCapabilities, String>),

    // Layer Management
    /// Layer state changed (device_id, layer_id)
    LayerStateChanged(String, usize),
    /// Request layer configuration for a device
    LayerConfigRequested(String),
    /// Request activation of a layer (device_id, layer_id, mode)
    LayerActivateRequested(String, usize, LayerMode),
    /// Layer configuration updated (device_id, config)
    LayerConfigUpdated(String, LayerConfigInfo),
    /// Open layer config dialog for editing
    OpenLayerConfigDialog(String, usize),
    /// Update layer name in dialog
    LayerConfigNameChanged(String),
    /// Update layer mode in dialog
    LayerConfigModeChanged(LayerMode),
    /// Save layer config from dialog
    SaveLayerConfig,
    /// Cancel layer config dialog
    CancelLayerConfig,
    /// Periodic refresh of layer states
    RefreshLayers,
    /// Layer list loaded from daemon (device_id, layers)
    LayerListLoaded(String, Vec<LayerConfigInfo>),

    // D-pad Mode Management
    /// Request D-pad mode for a device
    AnalogDpadModeRequested(String),
    /// D-pad mode loaded (device_id, mode)
    AnalogDpadModeLoaded(String, String),
    /// Set D-pad mode (device_id, mode)
    SetAnalogDpadMode(String, String),
    /// D-pad mode set result
    AnalogDpadModeSet(Result<(), String>),

    // Per-Axis Deadzone Management
    /// Request per-axis deadzone for a device
    AnalogDeadzoneXYRequested(String),
    /// Per-axis deadzone loaded (device_id, (x_pct, y_pct))
    AnalogDeadzoneXYLoaded(String, (u8, u8)),
    /// Set per-axis deadzone (device_id, x_pct, y_pct)
    SetAnalogDeadzoneXY(String, u8, u8),
    /// Per-axis deadzone set result
    AnalogDeadzoneXYSet(Result<(), String>),
    /// Request per-axis outer deadzone for a device
    AnalogOuterDeadzoneXYRequested(String),
    /// Per-axis outer deadzone loaded (device_id, (x_pct, y_pct))
    AnalogOuterDeadzoneXYLoaded(String, (u8, u8)),
    /// Set per-axis outer deadzone (device_id, x_pct, y_pct)
    SetAnalogOuterDeadzoneXY(String, u8, u8),
    /// Per-axis outer deadzone set result
    AnalogOuterDeadzoneXYSet(Result<(), String>),

    // LED Configuration Management
    /// Open LED configuration dialog for device
    OpenLedConfig(String),
    /// Close LED configuration dialog
    CloseLedConfig,
    /// Select LED zone for color editing
    SelectLedZone(LedZone),
    /// Set LED color (device_id, zone, red, green, blue)
    SetLedColor(String, LedZone, u8, u8, u8),
    /// LED color set result
    LedColorSet(Result<(), String>),
    /// Set LED brightness (device_id, zone_opt, brightness)
    SetLedBrightness(String, Option<LedZone>, u8),
    /// LED brightness set result
    LedBrightnessSet(Result<(), String>),
    /// Set LED pattern (device_id, pattern)
    SetLedPattern(String, LedPattern),
    /// LED pattern set result
    LedPatternSet(Result<(), String>),
    /// Request LED state refresh for device
    RefreshLedState(String),
    /// LED state loaded (device_id, colors)
    LedStateLoaded(String, Result<HashMap<LedZone, (u8, u8, u8)>, String>),
    /// RGB slider changed (red, green, blue)
    LedSliderChanged(u8, u8, u8),

    // Focus Tracking
    /// Start focus tracking after daemon connection confirmed
    StartFocusTracking,
    /// Focus tracking started successfully
    FocusTrackingStarted(Result<bool, String>),
    /// Focus change event received from tracker
    FocusChanged(String, Option<String>), // (app_id, window_title)

    // Auto-Switch Rules Management
    /// Open auto-switch rules view for a device
    ShowAutoSwitchRules(String),
    /// Close auto-switch rules view
    CloseAutoSwitchRules,
    /// Load auto-switch rules for a device
    LoadAutoSwitchRules(String),
    /// Auto-switch rules loaded (device_id, rules)
    AutoSwitchRulesLoaded(Result<Vec<AutoSwitchRule>, String>),
    /// Start editing a rule (index in list)
    EditAutoSwitchRule(usize),
    /// Update new rule app_id input
    AutoSwitchAppIdChanged(String),
    /// Update new rule profile_name input
    AutoSwitchProfileNameChanged(String),
    /// Update new rule layer_id input
    AutoSwitchLayerIdChanged(String),
    /// Use current focused app as app_id
    AutoSwitchUseCurrentApp,
    /// Save the current rule (add or update)
    SaveAutoSwitchRule,
    /// Delete a rule
    DeleteAutoSwitchRule(usize),

    // Hotkey Bindings Management
    /// Open hotkey bindings view for a device
    ShowHotkeyBindings(String),
    /// Close hotkey bindings view
    CloseHotkeyBindings,
    /// Load hotkey bindings for a device
    LoadHotkeyBindings(String),
    /// Hotkey bindings loaded result
    HotkeyBindingsLoaded(Result<Vec<HotkeyBinding>, String>),
    /// Start editing a binding (index in list)
    EditHotkeyBinding(usize),
    /// Toggle modifier checkbox (modifier_name)
    ToggleHotkeyModifier(String),
    /// Update new binding key input
    HotkeyKeyChanged(String),
    /// Update new binding profile_name input
    HotkeyProfileNameChanged(String),
    /// Update new binding layer_id input
    HotkeyLayerIdChanged(String),
    /// Save the current binding (add or update)
    SaveHotkeyBinding,
    /// Delete a binding
    DeleteHotkeyBinding(usize),
    /// Hotkey bindings updated after delete
    HotkeyBindingsUpdated(Vec<HotkeyBinding>),

    // Analog Calibration Management
    /// Open analog calibration view for a device and layer
    OpenAnalogCalibration {
        device_id: String,
        layer_id: usize,
    },
    /// Analog calibration field changed
    AnalogDeadzoneChanged(f32),
    AnalogDeadzoneShapeChanged(DeadzoneShape),
    AnalogSensitivityChanged(f32),
    AnalogSensitivityCurveChanged(SensitivityCurve),
    AnalogRangeMinChanged(i32),
    AnalogRangeMaxChanged(i32),
    AnalogInvertXToggled(bool),
    AnalogInvertYToggled(bool),
    /// Analog mode changed
    AnalogModeChanged(AnalogMode),
    /// Camera output mode changed
    CameraModeChanged(CameraOutputMode),
    /// Apply calibration changes
    ApplyAnalogCalibration,
    /// Analog calibration loaded
    AnalogCalibrationLoaded(Result<aethermap_common::AnalogCalibrationConfig, String>),
    /// Analog calibration applied
    AnalogCalibrationApplied(Result<(), String>),
    /// Close analog calibration view
    CloseAnalogCalibration,
    /// Analog input updated (streaming from daemon)
    AnalogInputUpdated(f32, f32), // (x, y)
}

// Reserved for future use
#[allow(dead_code)]
pub enum _FutureMessage {
    DismissNotification,
}

impl Application for State {
    type Message = Message;
    type Theme = Theme;
    type Executor = iced::executor::Default;
    type Flags = ();

    fn new(_flags: ()) -> (Self, Command<Message>) {
        let initial_state = State::default();
        let initial_commands = Command::batch([
            Command::perform(async { Message::CheckDaemonConnection }, |msg| msg),
            Command::perform(async { Message::LoadDevices }, |msg| msg),
            Command::perform(async { Message::LoadMacroSettings }, |msg| msg),
        ]);
        (initial_state, initial_commands)
    }

    fn title(&self) -> String {
        String::from("Aethermap")
    }

    fn theme(&self) -> Theme {
        self.current_theme.clone()
    }

    fn update(&mut self, message: Message) -> Command<Message> {
        match message {
            Message::ThemeChanged(theme) => {
                self.current_theme = theme;
                Command::none()
            }
            Message::SwitchTab(tab) => {
                self.active_tab = tab;
                Command::none()
            }
            Message::SelectDevice(idx) => {
                self.selected_device = Some(idx);
                // Load analog settings for the selected device if it has analog stick
                if let Some(device) = self.devices.get(idx) {
                    let device_id = format!("{:04x}:{:04x}", device.vendor_id, device.product_id);
                    if device.device_type == DeviceType::Gamepad || device.device_type == DeviceType::Keypad {
                        let device_id_clone1 = device_id.clone();
                        let device_id_clone2 = device_id.clone();
                        let device_id_clone3 = device_id.clone();
                        return Command::batch(vec![
                            Command::none(),
                            Command::perform(async move { device_id_clone1 }, |id| Message::AnalogDpadModeRequested(id)),
                            Command::perform(async move { device_id_clone2 }, |id| Message::AnalogDeadzoneXYRequested(id)),
                            Command::perform(async move { device_id_clone3 }, |id| Message::AnalogOuterDeadzoneXYRequested(id)),
                        ]);
                    }
                }
                Command::none()
            }
            Message::CheckDaemonConnection => {
                let socket_path = self.socket_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.connect().await.is_ok()
                    },
                    Message::DaemonStatusChanged,
                )
            }
            Message::DaemonStatusChanged(connected) => {
                self.daemon_connected = connected;
                if connected {
                    self.add_notification("Connected to daemon", false);
                    // Start focus tracking after successful daemon connection
                    Command::perform(async { Message::StartFocusTracking }, |msg| msg)
                } else {
                    self.add_notification("Daemon not running - start aethermapd", true);
                    Command::none()
                }
            }
            Message::StartFocusTracking => {
                // Spawn async task to initialize and start focus tracking
                // We create a simple check for portal availability
                Command::perform(
                    async move {
                        // Check if WAYLAND_DISPLAY is set (basic portal check)
                        let wayland_available = std::env::var("WAYLAND_DISPLAY").is_ok();
                        if wayland_available {
                            tracing::info!("Focus tracking available (Wayland detected)");
                        } else {
                            tracing::warn!("Focus tracking unavailable (not on Wayland)");
                        }
                        wayland_available
                    },
                    |available| Message::FocusTrackingStarted(Ok(available)),
                )
            }
            Message::FocusTrackingStarted(Ok(available)) => {
                self.focus_tracking_active = available;
                if available {
                    self.add_notification("Focus tracking enabled", false);
                } else {
                    self.add_notification("Focus tracking unavailable (portal not connected)", true);
                }
                Command::none()
            }
            Message::FocusTrackingStarted(Err(e)) => {
                self.add_notification(&format!("Focus tracking error: {}", e), true);
                self.focus_tracking_active = false;
                Command::none()
            }
            Message::FocusChanged(app_id, window_title) => {
                // Update current focus for auto-switch rule creation UI
                self.current_focus = Some(app_id.clone());
                // Send focus change to daemon for auto-profile switching
                let socket_path = self.socket_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.send_focus_change(app_id, window_title).await
                    },
                    |result| match result {
                        Ok(()) => Message::TickAnimations, // Silent success
                        Err(e) => Message::ProfileError(format!("Focus change failed: {}", e)),
                    },
                )
            }

            // Auto-Switch Rules Management
            Message::ShowAutoSwitchRules(device_id) => {
                self.auto_switch_view = Some(AutoSwitchRulesView {
                    device_id: device_id.clone(),
                    rules: Vec::new(),
                    editing_rule: None,
                    new_app_id: String::new(),
                    new_profile_name: String::new(),
                    new_layer_id: String::new(),
                });
                // Load rules from daemon
                let device_id_clone = device_id.clone();
                Command::perform(
                    async move { device_id_clone },
                    |id| Message::LoadAutoSwitchRules(id)
                )
            }
            Message::CloseAutoSwitchRules => {
                self.auto_switch_view = None;
                Command::none()
            }
            Message::LoadAutoSwitchRules(_device_id) => {
                let socket_path = self.socket_path.clone();
                Command::perform(
                    async move {
                        let client = IpcClient::with_socket_path(&socket_path);
                        let request = Request::GetAutoSwitchRules;
                        match client.send(&request).await {
                            Ok(Response::AutoSwitchRules { rules }) => {
                                // Convert common::AutoSwitchRule to gui::AutoSwitchRule
                                Ok(rules.into_iter().map(|r| AutoSwitchRule {
                                    app_id: r.app_id,
                                    profile_name: r.profile_name,
                                    device_id: r.device_id,
                                    layer_id: r.layer_id,
                                }).collect())
                            }
                            Ok(Response::Error(msg)) => Err(msg),
                            Err(e) => Err(format!("IPC error: {}", e)),
                            _ => Err("Unexpected response".to_string()),
                        }
                    },
                    Message::AutoSwitchRulesLoaded,
                )
            }
            Message::AutoSwitchRulesLoaded(Ok(rules)) => {
                self.auto_switch_view.as_mut().map(|view| {
                    view.rules = rules;
                });
                Command::none()
            }
            Message::AutoSwitchRulesLoaded(Err(error)) => {
                self.add_notification(&format!("Failed to load auto-switch rules: {}", error), true);
                Command::none()
            }
            Message::EditAutoSwitchRule(index) => {
                if let Some(view) = &self.auto_switch_view {
                    if let Some(rule) = view.rules.get(index) {
                        self.auto_switch_view = Some(AutoSwitchRulesView {
                            device_id: view.device_id.clone(),
                            rules: view.rules.clone(),
                            editing_rule: Some(index),
                            new_app_id: rule.app_id.clone(),
                            new_profile_name: rule.profile_name.clone(),
                            new_layer_id: rule.layer_id.map(|id| id.to_string()).unwrap_or_default(),
                        });
                    }
                }
                Command::none()
            }
            Message::AutoSwitchAppIdChanged(value) => {
                self.auto_switch_view.as_mut().map(|view| {
                    view.new_app_id = value;
                });
                Command::none()
            }
            Message::AutoSwitchProfileNameChanged(value) => {
                self.auto_switch_view.as_mut().map(|view| {
                    view.new_profile_name = value;
                });
                Command::none()
            }
            Message::AutoSwitchLayerIdChanged(value) => {
                self.auto_switch_view.as_mut().map(|view| {
                    view.new_layer_id = value;
                });
                Command::none()
            }
            Message::AutoSwitchUseCurrentApp => {
                if let Some(ref focus) = self.current_focus {
                    self.auto_switch_view.as_mut().map(|view| {
                        view.new_app_id = focus.clone();
                    });
                }
                Command::none()
            }
            Message::SaveAutoSwitchRule => {
                if let Some(mut view) = self.auto_switch_view.clone() {
                    let rule = AutoSwitchRule {
                        app_id: view.new_app_id.clone(),
                        profile_name: view.new_profile_name.clone(),
                        device_id: Some(view.device_id.clone()),
                        layer_id: view.new_layer_id.parse().ok(),
                    };

                    if let Some(editing) = view.editing_rule {
                        if editing < view.rules.len() {
                            view.rules[editing] = rule.clone();
                        }
                    } else {
                        view.rules.push(rule.clone());
                    }

                    view.editing_rule = None;
                    view.new_app_id = String::new();
                    view.new_profile_name = String::new();
                    view.new_layer_id = String::new();

                    let rules = view.rules.clone();
                    let socket_path = self.socket_path.clone();

                    // Update local state immediately
                    self.auto_switch_view = Some(view);

                    // Sync to daemon
                    Command::perform(
                        async move {
                            // Convert GUI AutoSwitchRule to common AutoSwitchRule
                            let common_rules: Vec<CommonAutoSwitchRule> = rules.into_iter()
                                .map(|r| CommonAutoSwitchRule {
                                    app_id: r.app_id,
                                    profile_name: r.profile_name,
                                    device_id: r.device_id,
                                    layer_id: r.layer_id,
                                })
                                .collect();

                            let client = IpcClient::with_socket_path(socket_path);
                            let request = Request::SetAutoSwitchRules { rules: common_rules };
                            match client.send(&request).await {
                                Ok(Response::AutoSwitchRulesAck) => Ok(()),
                                Ok(Response::Error(msg)) => Err(msg),
                                Err(e) => Err(format!("IPC error: {}", e)),
                                _ => Err("Unexpected response".to_string()),
                            }
                        },
                        |result| match result {
                            Ok(()) => Message::ShowNotification("Auto-switch rules saved".to_string(), false),
                            Err(e) => Message::ShowNotification(format!("Failed to save rules: {}", e), true),
                        }
                    )
                } else {
                    Command::none()
                }
            }
            Message::DeleteAutoSwitchRule(index) => {
                if let Some(view) = self.auto_switch_view.clone() {
                    if index < view.rules.len() {
                        let mut rules = view.rules.clone();
                        rules.remove(index);
                        let socket_path = self.socket_path.clone();

                        // Update local state immediately
                        self.auto_switch_view.as_mut().map(|v| v.rules = rules.clone());

                        // Sync to daemon
                        return Command::perform(
                            async move {
                                // Convert GUI AutoSwitchRule to common AutoSwitchRule
                                let common_rules: Vec<CommonAutoSwitchRule> = rules.into_iter()
                                    .map(|r| CommonAutoSwitchRule {
                                        app_id: r.app_id,
                                        profile_name: r.profile_name,
                                        device_id: r.device_id,
                                        layer_id: r.layer_id,
                                    })
                                    .collect();

                                let client = IpcClient::with_socket_path(&socket_path);
                                let request = Request::SetAutoSwitchRules { rules: common_rules };
                                match client.send(&request).await {
                                    Ok(Response::AutoSwitchRulesAck) => Ok(()),
                                    Ok(Response::Error(msg)) => Err(msg),
                                    Err(e) => Err(format!("IPC error: {}", e)),
                                    _ => Err("Unexpected response".to_string()),
                                }
                            },
                            |result| match result {
                                Ok(()) => Message::ShowNotification("Rule deleted".to_string(), false),
                                Err(e) => Message::ShowNotification(format!("Failed to delete rule: {}", e), true),
                            }
                        );
                    }
                }
                Command::none()
            }

            // Hotkey Bindings Management
            Message::ShowHotkeyBindings(device_id) => {
                self.hotkey_view = Some(HotkeyBindingsView {
                    device_id: device_id.clone(),
                    bindings: Vec::new(),
                    editing_binding: None,
                    new_modifiers: Vec::new(),
                    new_key: String::new(),
                    new_profile_name: String::new(),
                    new_layer_id: String::new(),
                });
                // Load bindings from daemon
                let device_id_clone = device_id.clone();
                Command::perform(
                    async move { device_id_clone },
                    |id| Message::LoadHotkeyBindings(id)
                )
            }
            Message::CloseHotkeyBindings => {
                self.hotkey_view = None;
                Command::none()
            }
            Message::LoadHotkeyBindings(device_id) => {
                let socket_path = self.socket_path.clone();
                Command::perform(
                    async move {
                        let client = IpcClient::with_socket_path(&socket_path);
                        let request = Request::ListHotkeys { device_id };
                        match client.send(&request).await {
                            Ok(Response::HotkeyList { bindings, .. }) => {
                                // Convert common::HotkeyBinding to gui::HotkeyBinding
                                Ok(bindings.into_iter().map(|b| HotkeyBinding {
                                    modifiers: b.modifiers,
                                    key: b.key,
                                    profile_name: b.profile_name,
                                    device_id: b.device_id,
                                    layer_id: b.layer_id,
                                }).collect())
                            }
                            Ok(Response::Error(msg)) => Err(msg),
                            Err(e) => Err(format!("IPC error: {}", e)),
                            _ => Err("Unexpected response".to_string()),
                        }
                    },
                    Message::HotkeyBindingsLoaded,
                )
            }
            Message::HotkeyBindingsLoaded(Ok(bindings)) => {
                if let Some(view) = &mut self.hotkey_view {
                    view.bindings = bindings;
                }
                Command::none()
            }
            Message::HotkeyBindingsLoaded(Err(error)) => {
                self.add_notification(&format!("Failed to load hotkey bindings: {}", error), true);
                Command::none()
            }
            Message::EditHotkeyBinding(index) => {
                if let Some(view) = &self.hotkey_view {
                    if let Some(binding) = view.bindings.get(index) {
                        self.hotkey_view = Some(HotkeyBindingsView {
                            device_id: view.device_id.clone(),
                            bindings: view.bindings.clone(),
                            editing_binding: Some(index),
                            new_modifiers: binding.modifiers.clone(),
                            new_key: binding.key.clone(),
                            new_profile_name: binding.profile_name.clone(),
                            new_layer_id: binding.layer_id.map(|id| id.to_string()).unwrap_or_default(),
                        });
                    }
                }
                Command::none()
            }
            Message::ToggleHotkeyModifier(modifier) => {
                self.hotkey_view.as_mut().map(|view| {
                    if view.new_modifiers.contains(&modifier) {
                        view.new_modifiers.retain(|m| m != &modifier);
                    } else {
                        view.new_modifiers.push(modifier);
                    }
                });
                Command::none()
            }
            Message::HotkeyKeyChanged(value) => {
                self.hotkey_view.as_mut().map(|view| {
                    view.new_key = value;
                });
                Command::none()
            }
            Message::HotkeyProfileNameChanged(value) => {
                self.hotkey_view.as_mut().map(|view| {
                    view.new_profile_name = value;
                });
                Command::none()
            }
            Message::HotkeyLayerIdChanged(value) => {
                self.hotkey_view.as_mut().map(|view| {
                    view.new_layer_id = value;
                });
                Command::none()
            }
            Message::SaveHotkeyBinding => {
                if let Some(view) = &self.hotkey_view {
                    let device_id = view.device_id.clone();
                    let binding = CommonHotkeyBinding {
                        modifiers: view.new_modifiers.clone(),
                        key: view.new_key.clone(),
                        profile_name: view.new_profile_name.clone(),
                        device_id: Some(view.device_id.clone()),
                        layer_id: if view.new_layer_id.is_empty() { None } else { view.new_layer_id.parse().ok() },
                    };
                    let socket_path = self.socket_path.clone();

                    // Update local state immediately
                    if let Some(local_view) = &self.hotkey_view {
                        let gui_binding = HotkeyBinding {
                            modifiers: binding.modifiers.clone(),
                            key: binding.key.clone(),
                            profile_name: binding.profile_name.clone(),
                            device_id: binding.device_id.clone(),
                            layer_id: binding.layer_id,
                        };
                        let mut updated_view = local_view.clone();
                        if let Some(editing) = local_view.editing_binding {
                            if editing < local_view.bindings.len() {
                                updated_view.bindings[editing] = gui_binding;
                            }
                        } else {
                            updated_view.bindings.push(gui_binding);
                        }
                        updated_view.editing_binding = None;
                        updated_view.new_modifiers = Vec::new();
                        updated_view.new_key = String::new();
                        updated_view.new_profile_name = String::new();
                        updated_view.new_layer_id = String::new();
                        self.hotkey_view = Some(updated_view);
                    }

                    return Command::perform(
                        async move {
                            let client = IpcClient::with_socket_path(&socket_path);
                            let request = Request::RegisterHotkey { device_id, binding };
                            match client.send(&request).await {
                                Ok(Response::HotkeyRegistered { .. }) => Ok(()),
                                Ok(Response::Error(msg)) => Err(msg),
                                Err(e) => Err(format!("IPC error: {}", e)),
                                _ => Err("Unexpected response".to_string()),
                            }
                        },
                        |result| match result {
                            Ok(()) => Message::ShowNotification("Hotkey saved".to_string(), false),
                            Err(e) => Message::ShowNotification(format!("Failed to save hotkey: {}", e), true),
                        }
                    );
                }
                Command::none()
            }
            Message::DeleteHotkeyBinding(index) => {
                if let Some(view) = &self.hotkey_view {
                    if index < view.bindings.len() {
                        let device_id = view.device_id.clone();
                        let binding = view.bindings[index].clone();
                        let socket_path = self.socket_path.clone();

                        // Update local state immediately
                        let updated_bindings = view.bindings.iter()
                            .enumerate()
                            .filter(|(i, _)| *i != index)
                            .map(|(_, b)| b.clone())
                            .collect();

                        return Command::perform(
                            async move {
                                let client = IpcClient::with_socket_path(&socket_path);
                                let request = Request::RemoveHotkey {
                                    device_id,
                                    key: binding.key.clone(),
                                    modifiers: binding.modifiers.clone(),
                                };
                                match client.send(&request).await {
                                    Ok(Response::HotkeyRemoved { .. }) => Ok(()),
                                    Ok(Response::Error(msg)) => Err(msg),
                                    Err(e) => Err(format!("IPC error: {}", e)),
                                    _ => Err("Unexpected response".to_string()),
                                }
                            },
                            move |result| {
                                if result.is_ok() {
                                    Message::HotkeyBindingsUpdated(updated_bindings)
                                } else {
                                    let err_msg = result.unwrap_err();
                                    Message::ShowNotification(format!("Failed to delete hotkey: {}", err_msg), true)
                                }
                            }
                        );
                    }
                }
                Command::none()
            }
            Message::HotkeyBindingsUpdated(bindings) => {
                if let Some(view) = &mut self.hotkey_view {
                    view.bindings = bindings;
                }
                self.add_notification("Hotkey deleted", false);
                Command::none()
            }

            // Analog Calibration Management
            Message::OpenAnalogCalibration { device_id, layer_id } => {
                // Create the view with loading state
                self.analog_calibration_view = Some(AnalogCalibrationView {
                    device_id: device_id.clone(),
                    layer_id,
                    calibration: CalibrationConfig::default(),
                    deadzone_shape_selected: DeadzoneShape::Circular,
                    sensitivity_curve_selected: SensitivityCurve::Linear,
                    analog_mode_selected: AnalogMode::Disabled,
                    camera_mode_selected: CameraOutputMode::Scroll,
                    invert_x_checked: false,
                    invert_y_checked: false,
                    stick_x: 0.0,
                    stick_y: 0.0,
                    loading: true,
                    error: None,
                    last_visualizer_update: Instant::now(),
                    visualizer_cache: Arc::new(iced::widget::canvas::Cache::default()),
                });

                // Load calibration from daemon
                let device_id_clone = device_id.clone();
                let socket_path = self.socket_path.clone();

                // Subscribe to analog input updates
                let device_id_subscribe = device_id.clone();
                let socket_path_subscribe = self.socket_path.clone();

                Command::batch(vec![
                    // Subscribe to analog input updates
                    Command::perform(
                        async move {
                            let client = crate::ipc::IpcClient::new(socket_path_subscribe);
                            client.subscribe_analog_input(&device_id_subscribe).await
                        },
                        |result| match result {
                            Ok(_) => Message::ShowNotification("Subscribed to analog input".to_string(), false),
                            Err(e) => Message::ShowNotification(format!("Subscription failed: {}", e), true),
                        },
                    ),
                    // Load calibration data
                    Command::perform(
                        async move {
                            let client = crate::ipc::IpcClient::new(socket_path);
                            client.get_analog_calibration(&device_id_clone, layer_id).await
                        },
                        Message::AnalogCalibrationLoaded,
                    ),
                ])
            }
            Message::AnalogCalibrationLoaded(Ok(calibration)) => {
                if let Some(view) = &mut self.analog_calibration_view {
                    // Convert common config to local CalibrationConfig
                    view.calibration = CalibrationConfig {
                        deadzone: calibration.deadzone,
                        deadzone_shape: calibration.deadzone_shape.clone(),
                        sensitivity: calibration.sensitivity.clone(),
                        sensitivity_multiplier: calibration.sensitivity_multiplier,
                        range_min: calibration.range_min,
                        range_max: calibration.range_max,
                        invert_x: calibration.invert_x,
                        invert_y: calibration.invert_y,
                        exponent: calibration.exponent,
                    };
                    view.loading = false;

                    // Update selections from loaded calibration
                    view.deadzone_shape_selected = match calibration.deadzone_shape.as_str() {
                        "circular" => DeadzoneShape::Circular,
                        "square" => DeadzoneShape::Square,
                        _ => DeadzoneShape::Circular,
                    };
                    view.sensitivity_curve_selected = match calibration.sensitivity.as_str() {
                        "linear" => SensitivityCurve::Linear,
                        "quadratic" => SensitivityCurve::Quadratic,
                        "exponential" => SensitivityCurve::Exponential,
                        _ => SensitivityCurve::Linear,
                    };
                    view.invert_x_checked = calibration.invert_x;
                    view.invert_y_checked = calibration.invert_y;
                }
                Command::none()
            }
            Message::AnalogCalibrationLoaded(Err(error)) => {
                if let Some(view) = &mut self.analog_calibration_view {
                    view.error = Some(error);
                    view.loading = false;
                }
                Command::none()
            }
            Message::AnalogDeadzoneChanged(value) => {
                if let Some(view) = &mut self.analog_calibration_view {
                    view.calibration.deadzone = value;
                    // Clear cache so deadzone redraws with new size
                    view.visualizer_cache.clear();
                }
                Command::none()
            }
            Message::AnalogDeadzoneShapeChanged(shape) => {
                if let Some(view) = &mut self.analog_calibration_view {
                    view.deadzone_shape_selected = shape;
                    view.calibration.deadzone_shape = shape.to_string().to_lowercase();
                    // Clear cache so deadzone redraws with new shape
                    view.visualizer_cache.clear();
                }
                Command::none()
            }
            Message::AnalogSensitivityChanged(value) => {
                if let Some(view) = &mut self.analog_calibration_view {
                    view.calibration.sensitivity_multiplier = value;
                }
                Command::none()
            }
            Message::AnalogSensitivityCurveChanged(curve) => {
                if let Some(view) = &mut self.analog_calibration_view {
                    view.sensitivity_curve_selected = curve;
                    view.calibration.sensitivity = curve.to_string().to_lowercase();
                }
                Command::none()
            }
            Message::AnalogRangeMinChanged(value) => {
                if let Some(view) = &mut self.analog_calibration_view {
                    view.calibration.range_min = value;
                }
                Command::none()
            }
            Message::AnalogRangeMaxChanged(value) => {
                if let Some(view) = &mut self.analog_calibration_view {
                    view.calibration.range_max = value;
                }
                Command::none()
            }
            Message::AnalogInvertXToggled(checked) => {
                if let Some(view) = &mut self.analog_calibration_view {
                    view.invert_x_checked = checked;
                    view.calibration.invert_x = checked;
                }
                Command::none()
            }
            Message::AnalogInvertYToggled(checked) => {
                if let Some(view) = &mut self.analog_calibration_view {
                    view.invert_y_checked = checked;
                    view.calibration.invert_y = checked;
                }
                Command::none()
            }
            Message::AnalogModeChanged(mode) => {
                if let Some(view) = &mut self.analog_calibration_view {
                    view.analog_mode_selected = mode;
                }
                Command::none()
            }
            Message::CameraModeChanged(mode) => {
                if let Some(view) = &mut self.analog_calibration_view {
                    view.camera_mode_selected = mode;
                }
                Command::none()
            }
            Message::ApplyAnalogCalibration => {
                if let Some(view) = self.analog_calibration_view.clone() {
                    let device_id = view.device_id.clone();
                    let layer_id = view.layer_id;
                    let calibration = aethermap_common::AnalogCalibrationConfig {
                        deadzone: view.calibration.deadzone,
                        deadzone_shape: view.calibration.deadzone_shape.clone(),
                        sensitivity: view.calibration.sensitivity.clone(),
                        sensitivity_multiplier: view.calibration.sensitivity_multiplier,
                        range_min: view.calibration.range_min,
                        range_max: view.calibration.range_max,
                        invert_x: view.calibration.invert_x,
                        invert_y: view.calibration.invert_y,
                        exponent: view.calibration.exponent,
                        analog_mode: view.analog_mode_selected,
                        camera_output_mode: if view.analog_mode_selected == aethermap_common::AnalogMode::Camera {
                            Some(view.camera_mode_selected)
                        } else {
                            None
                        },
                    };
                    let socket_path = self.socket_path.clone();

                    return Command::perform(
                        async move {
                            let client = crate::ipc::IpcClient::new(socket_path);
                            client.set_analog_calibration(&device_id, layer_id, calibration).await
                                .map_err(|e| e.to_string())
                        },
                        Message::AnalogCalibrationApplied,
                    );
                }
                Command::none()
            }
            Message::AnalogCalibrationApplied(Ok(())) => {
                self.add_notification("Calibration saved successfully", false);
                Command::none()
            }
            Message::AnalogCalibrationApplied(Err(error)) => {
                self.add_notification(&format!("Failed to save calibration: {}", error), true);
                if let Some(view) = &mut self.analog_calibration_view {
                    let mut view = view.clone();
                    view.error = Some(error);
                    self.analog_calibration_view = Some(view);
                }
                Command::none()
            }
            Message::CloseAnalogCalibration => {
                // Unsubscribe from analog input updates
                let device_id = self.analog_calibration_view.as_ref()
                    .map(|v| v.device_id.clone())
                    .unwrap_or_default();
                let socket_path = self.socket_path.clone();

                self.analog_calibration_view = None;

                // Unsubscribe is fire-and-forget - we don't need to wait for result
                // Spawn a background task to handle it
                let _ = std::thread::spawn(move || {
                    let rt = tokio::runtime::Runtime::new().unwrap();
                    rt.block_on(async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        if let Err(e) = client.unsubscribe_analog_input(&device_id).await {
                            eprintln!("Failed to unsubscribe: {}", e);
                        }
                    });
                });

                Command::none()
            }
            Message::AnalogInputUpdated(x, y) => {
                // Update analog calibration view stick position with throttling
                // Throttle to ~30 FPS (33ms between updates) to prevent overwhelming the GUI
                if let Some(view) = &mut self.analog_calibration_view {
                    if view.last_visualizer_update.elapsed() >= Duration::from_millis(33) {
                        view.stick_x = x;
                        view.stick_y = y;
                        view.last_visualizer_update = Instant::now();
                        Command::none() // Triggers redraw
                    } else {
                        Command::none() // Skip redraw, no state change
                    }
                } else {
                    Command::none()
                }
            }

            Message::LoadDevices => {
                let socket_path = self.socket_path.clone();
                self.loading = true;
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.get_devices().await.map_err(|e| e.to_string())
                    },
                    Message::DevicesLoaded,
                )
            }
            Message::DevicesLoaded(Ok(devices)) => {
                let count = devices.len();
                self.devices = devices;
                self.loading = false;
                self.add_notification(&format!("Found {} devices", count), false);
                Command::perform(async { Message::LoadMacros }, |msg| msg)
            }
            Message::DevicesLoaded(Err(e)) => {
                self.loading = false;
                self.add_notification(&format!("Error: {}", e), true);
                Command::none()
            }
            Message::LoadMacros => {
                let socket_path = self.socket_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.list_macros().await.map_err(|e| e.to_string())
                    },
                    Message::MacrosLoaded,
                )
            }
            Message::MacrosLoaded(Ok(macros)) => {
                let count = macros.len();
                self.macros = macros;
                self.add_notification(&format!("Loaded {} macros", count), false);
                Command::none()
            }
            Message::MacrosLoaded(Err(e)) => {
                self.add_notification(&format!("Error loading macros: {}", e), true);
                Command::none()
            }
            Message::LoadMacroSettings => {
                let socket_path = self.socket_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.get_macro_settings().await.map_err(|e| e.to_string())
                    },
                    Message::MacroSettingsLoaded,
                )
            }
            Message::MacroSettingsLoaded(Ok(settings)) => {
                self.macro_settings = settings;
                Command::none()
            }
            Message::MacroSettingsLoaded(Err(e)) => {
                self.add_notification(&format!("Error loading macro settings: {}", e), true);
                Command::none()
            }
            Message::SetMacroSettings(settings) => {
                let socket_path = self.socket_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.set_macro_settings(settings).await.map_err(|e| e.to_string())
                    },
                    |result| match result {
                        Ok(_) => Message::TickAnimations, // Silent success
                        Err(e) => Message::ShowNotification(format!("Failed to save settings: {}", e), true),
                    }
                )
            }
            Message::LatencyChanged(ms) => {
                self.macro_settings.latency_offset_ms = ms;
                let settings = self.macro_settings.clone();
                Command::perform(async move { Message::SetMacroSettings(settings) }, |msg| msg)
            }
            Message::JitterChanged(pct) => {
                self.macro_settings.jitter_pct = pct;
                let settings = self.macro_settings.clone();
                Command::perform(async move { Message::SetMacroSettings(settings) }, |msg| msg)
            }
            Message::CaptureMouseToggled(enabled) => {
                self.macro_settings.capture_mouse = enabled;
                let settings = self.macro_settings.clone();
                Command::perform(async move { Message::SetMacroSettings(settings) }, |msg| msg)
            }
            Message::PlayMacro(macro_name) => {
                let socket_path = self.socket_path.clone();
                let name = macro_name.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.test_macro(&name).await.map(|_| name).map_err(|e| e.to_string())
                    },
                    Message::MacroPlayed,
                )
            }
            Message::MacroPlayed(Ok(name)) => {
                self.add_notification(&format!("Played macro: {}", name), false);
                Command::none()
            }
            Message::MacroPlayed(Err(e)) => {
                self.add_notification(&format!("Failed to play: {}", e), true);
                Command::none()
            }
            Message::UpdateMacroName(name) => {
                self.new_macro_name = name;
                Command::none()
            }
            Message::UpdateProfileName(name) => {
                self.profile_name = name;
                Command::none()
            }
            Message::StartRecording => {
                if self.new_macro_name.trim().is_empty() {
                    self.add_notification("Enter a macro name first", true);
                    return Command::none();
                }
                if self.grabbed_devices.is_empty() {
                    self.add_notification("Grab a device first", true);
                    return Command::none();
                }

                let device_path = self.grabbed_devices.iter().next().unwrap().clone();
                let socket_path = self.socket_path.clone();
                let macro_name = self.new_macro_name.clone();
                let capture_mouse = self.macro_settings.capture_mouse;
                self.recording = true;
                self.recording_macro_name = Some(macro_name.clone());

                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.start_recording_macro(&device_path, &macro_name, capture_mouse)
                            .await
                            .map(|_| macro_name)
                            .map_err(|e| e.to_string())
                    },
                    Message::RecordingStarted,
                )
            }
            Message::RecordingStarted(Ok(name)) => {
                self.add_notification(&format!("Recording '{}' - Press keys now!", name), false);
                Command::none()
            }
            Message::RecordingStarted(Err(e)) => {
                self.recording = false;
                self.recording_macro_name = None;
                self.add_notification(&format!("Failed to start recording: {}", e), true);
                Command::none()
            }
            Message::StopRecording => {
                let socket_path = self.socket_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.stop_recording_macro().await.map_err(|e| e.to_string())
                    },
                    Message::RecordingStopped,
                )
            }
            Message::RecordingStopped(Ok(macro_entry)) => {
                let name = macro_entry.name.clone();
                self.macros.push(macro_entry);
                self.recording = false;
                self.recording_macro_name = None;
                self.recently_updated_macros.insert(name.clone(), Instant::now());
                self.new_macro_name.clear();
                self.add_notification(&format!("Recorded macro: {}", name), false);
                Command::none()
            }
            Message::RecordingStopped(Err(e)) => {
                self.recording = false;
                self.recording_macro_name = None;
                self.add_notification(&format!("Recording failed: {}", e), true);
                Command::none()
            }
            Message::DeleteMacro(macro_name) => {
                let socket_path = self.socket_path.clone();
                let name = macro_name.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.delete_macro(&name).await.map(|_| name).map_err(|e| e.to_string())
                    },
                    Message::MacroDeleted,
                )
            }
            Message::MacroDeleted(Ok(name)) => {
                self.macros.retain(|m| m.name != name);
                self.add_notification(&format!("Deleted: {}", name), false);
                Command::none()
            }
            Message::MacroDeleted(Err(e)) => {
                self.add_notification(&format!("Delete failed: {}", e), true);
                Command::none()
            }
            Message::SaveProfile => {
                if self.profile_name.trim().is_empty() {
                    self.add_notification("Enter a profile name", true);
                    return Command::none();
                }
                let socket_path = self.socket_path.clone();
                let name = self.profile_name.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.save_profile(&name).await.map_err(|e| e.to_string())
                    },
                    Message::ProfileSaved,
                )
            }
            Message::ProfileSaved(Ok((name, count))) => {
                self.add_notification(&format!("Saved '{}' ({} macros)", name, count), false);
                Command::none()
            }
            Message::ProfileSaved(Err(e)) => {
                self.add_notification(&format!("Save failed: {}", e), true);
                Command::none()
            }
            Message::LoadProfile => {
                if self.profile_name.trim().is_empty() {
                    self.add_notification("Enter a profile name to load", true);
                    return Command::none();
                }
                let socket_path = self.socket_path.clone();
                let name = self.profile_name.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.load_profile(&name).await.map_err(|e| e.to_string())
                    },
                    Message::ProfileLoaded,
                )
            }
            Message::ProfileLoaded(Ok((name, count))) => {
                self.add_notification(&format!("Loaded '{}' ({} macros)", name, count), false);
                Command::perform(async { Message::LoadMacros }, |msg| msg)
            }
            Message::ProfileLoaded(Err(e)) => {
                self.add_notification(&format!("Load failed: {}", e), true);
                Command::none()
            }
            Message::TickAnimations => {
                let now = Instant::now();
                self.recently_updated_macros.retain(|_, timestamp| {
                    now.duration_since(*timestamp) < Duration::from_secs(3)
                });
                self.recording_pulse = !self.recording_pulse;
                // Auto-dismiss old notifications
                while let Some(notif) = self.notifications.front() {
                    if now.duration_since(notif.timestamp) > Duration::from_secs(5) {
                        self.notifications.pop_front();
                    } else {
                        break;
                    }
                }
                Command::none()
            }
            Message::ShowNotification(message, is_error) => {
                self.add_notification(&message, is_error);
                Command::none()
            }
            Message::GrabDevice(device_path) => {
                let socket_path = self.socket_path.clone();
                let path_clone = device_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.grab_device(&path_clone).await.map(|_| path_clone).map_err(|e| e.to_string())
                    },
                    Message::DeviceGrabbed,
                )
            }
            Message::UngrabDevice(device_path) => {
                let socket_path = self.socket_path.clone();
                let path_clone = device_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.ungrab_device(&path_clone).await.map(|_| path_clone).map_err(|e| e.to_string())
                    },
                    Message::DeviceUngrabbed,
                )
            }
            Message::DeviceGrabbed(Ok(device_path)) => {
                self.grabbed_devices.insert(device_path.clone());
                if let Some(idx) = self.devices.iter().position(|d| d.path.to_string_lossy() == device_path) {
                    self.selected_device = Some(idx);
                }
                self.add_notification("Device grabbed - ready for recording", false);
                Command::none()
            }
            Message::DeviceGrabbed(Err(e)) => {
                self.add_notification(&format!("Grab failed: {}", e), true);
                Command::none()
            }
            Message::DeviceUngrabbed(Ok(device_path)) => {
                self.grabbed_devices.remove(&device_path);
                self.add_notification("Device released", false);
                Command::none()
            }
            Message::DeviceUngrabbed(Err(e)) => {
                self.add_notification(&format!("Release failed: {}", e), true);
                Command::none()
            }
            Message::LoadDeviceProfiles(device_id) => {
                let socket_path = self.socket_path.clone();
                let id = device_id.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        (id.clone(), client.get_device_profiles(id).await)
                    },
                    |(device_id, result)| Message::DeviceProfilesLoaded(
                        device_id,
                        result.map_err(|e| e.to_string())
                    )
                )
            }
            Message::DeviceProfilesLoaded(device_id, Ok(profiles)) => {
                self.device_profiles.insert(device_id.clone(), profiles);
                self.add_notification(&format!("Loaded {} profiles for {}", self.device_profiles.get(&device_id).map(|p| p.len()).unwrap_or(0), device_id), false);
                Command::none()
            }
            Message::DeviceProfilesLoaded(_device_id, Err(e)) => {
                self.add_notification(&format!("Failed to load device profiles: {}", e), true);
                Command::none()
            }
            Message::ActivateProfile(device_id, profile_name) => {
                let socket_path = self.socket_path.clone();
                let id = device_id.clone();
                let name = profile_name.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.activate_profile(id.clone(), name.clone()).await
                    },
                    move |result| match result {
                        Ok(()) => Message::ProfileActivated(device_id, profile_name),
                        Err(e) => Message::ProfileError(format!("Failed to activate profile: {}", e)),
                    }
                )
            }
            Message::ProfileActivated(device_id, profile_name) => {
                self.active_profiles.insert(device_id.clone(), profile_name.clone());
                self.add_notification(&format!("Activated profile '{}' on {}", profile_name, device_id), false);
                Command::none()
            }
            Message::DeactivateProfile(device_id) => {
                let socket_path = self.socket_path.clone();
                let id = device_id.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.deactivate_profile(id.clone()).await
                    },
                    move |result| match result {
                        Ok(()) => Message::ProfileDeactivated(device_id),
                        Err(e) => Message::ProfileError(format!("Failed to deactivate profile: {}", e)),
                    }
                )
            }
            Message::ProfileDeactivated(device_id) => {
                self.active_profiles.remove(&device_id);
                self.add_notification(&format!("Deactivated profile on {}", device_id), false);
                Command::none()
            }
            Message::ProfileError(msg) => {
                self.add_notification(&msg, true);
                Command::none()
            }
            Message::LoadRemapProfiles(device_path) => {
                let socket_path = self.socket_path.clone();
                let path = device_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        (path.clone(), client.list_remap_profiles(&path).await)
                    },
                    |(device_path, result)| Message::RemapProfilesLoaded(
                        device_path,
                        result.map_err(|e| e.to_string())
                    )
                )
            }
            Message::RemapProfilesLoaded(device_path, Ok(profiles)) => {
                self.remap_profiles.insert(device_path.clone(), profiles);
                self.add_notification(&format!("Loaded {} remap profiles for {}", self.remap_profiles.get(&device_path).map(|p| p.len()).unwrap_or(0), device_path), false);
                Command::none()
            }
            Message::RemapProfilesLoaded(_device_path, Err(e)) => {
                self.add_notification(&format!("Failed to load remap profiles: {}", e), true);
                Command::none()
            }
            Message::ActivateRemapProfile(device_path, profile_name) => {
                let socket_path = self.socket_path.clone();
                let path = device_path.clone();
                let name = profile_name.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.activate_remap_profile(&path, &name).await
                    },
                    move |result| match result {
                        Ok(()) => Message::RemapProfileActivated(device_path, profile_name),
                        Err(e) => Message::ProfileError(format!("Failed to activate remap profile: {}", e)),
                    }
                )
            }
            Message::RemapProfileActivated(device_path, profile_name) => {
                self.active_remap_profiles.insert(device_path.clone(), profile_name.clone());
                self.add_notification(&format!("Activated remap profile '{}' on {}", profile_name, device_path), false);
                // Refresh active remaps after activation
                Command::perform(
                    async move { device_path.clone() },
                    |path| Message::LoadActiveRemaps(path)
                )
            }
            Message::DeactivateRemapProfile(device_path) => {
                let socket_path = self.socket_path.clone();
                let path = device_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.deactivate_remap_profile(&path).await
                    },
                    move |result| match result {
                        Ok(()) => Message::RemapProfileDeactivated(device_path),
                        Err(e) => Message::ProfileError(format!("Failed to deactivate remap profile: {}", e)),
                    }
                )
            }
            Message::RemapProfileDeactivated(device_path) => {
                self.active_remap_profiles.remove(&device_path);
                self.active_remaps.remove(&device_path);
                self.add_notification(&format!("Deactivated remap profile on {}", device_path), false);
                Command::none()
            }
            Message::LoadActiveRemaps(device_path) => {
                let socket_path = self.socket_path.clone();
                let path = device_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        (path.clone(), client.get_active_remaps(&path).await)
                    },
                    |(device_path, result)| Message::ActiveRemapsLoaded(
                        device_path,
                        result.map_err(|e| e.to_string())
                    )
                )
            }
            Message::ActiveRemapsLoaded(device_path, Ok(Some((profile_name, remaps)))) => {
                self.active_remaps.insert(device_path.clone(), (profile_name, remaps));
                Command::none()
            }
            Message::ActiveRemapsLoaded(device_path, Ok(None)) => {
                self.active_remaps.remove(&device_path);
                Command::none()
            }
            Message::ActiveRemapsLoaded(_device_path, Err(e)) => {
                self.add_notification(&format!("Failed to load active remaps: {}", e), true);
                Command::none()
            }
            Message::RecordMouseEvent { event_type, button, x, y, delta } => {
                // Mouse events are captured by daemon during recording via device grab
                // This handler is for GUI-side mouse event logging
                if self.recording {
                    // Log the mouse event for debugging/confirmation
                    let event_desc = match event_type.as_str() {
                        "button_press" => format!("Mouse button {} pressed", button.unwrap_or(0)),
                        "button_release" => format!("Mouse button {} released", button.unwrap_or(0)),
                        "movement" => format!("Mouse moved to ({}, {})", x, y),
                        "scroll" => format!("Mouse scrolled {}", delta),
                        _ => format!("Unknown mouse event: {}", event_type),
                    };
                    // Update status to show mouse event was captured
                    self.status = event_desc;
                }
                Command::none()
            }
            Message::ShowKeypadView(device_path) => {
                // Empty string means back button was pressed - clear keypad view
                if device_path.is_empty() {
                    self.device_capabilities = None;
                    self.keypad_layout.clear();
                    self.keypad_view_device = None;
                    self.selected_button = None;
                    return Command::none();
                }
                // Store the device path for keypad view
                self.keypad_view_device = Some(device_path.clone());
                // Query device capabilities and load keypad layout
                let socket_path = self.socket_path.clone();
                let path_clone = device_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        (path_clone.clone(), client.get_device_capabilities(&path_clone).await)
                    },
                    |(device_path, result)| Message::DeviceCapabilitiesLoaded(
                        device_path,
                        result.map_err(|e| e.to_string())
                    )
                )
            }
            Message::DeviceCapabilitiesLoaded(device_path, Ok(capabilities)) => {
                self.device_capabilities = Some(capabilities);
                self.keypad_layout = azeron_keypad_layout();
                // Load current remappings and update button.current_remap
                if let Some((profile_name, remaps)) = self.active_remaps.get(&device_path) {
                    for remap in remaps {
                        if let Some(button) = self.keypad_layout.iter_mut().find(|b| b.id == remap.from_key) {
                            button.current_remap = Some(remap.to_key.clone());
                        }
                    }
                    self.add_notification(&format!("Loaded remaps from profile '{}'", profile_name), false);
                }
                // Switch to Devices tab to show keypad view
                self.active_tab = Tab::Devices;
                Command::none()
            }
            Message::DeviceCapabilitiesLoaded(_device_path, Err(e)) => {
                self.add_notification(&format!("Failed to load device capabilities: {}", e), true);
                Command::none()
            }
            Message::SelectKeypadButton(button_id) => {
                self.selected_button = self.keypad_layout.iter().position(|b| b.id == button_id);
                self.status = format!("Selected button: {} - Configure remapping in device profile", button_id);
                Command::none()
            }
            Message::LayerStateChanged(device_id, layer_id) => {
                self.active_layers.insert(device_id, layer_id);
                Command::none()
            }
            Message::LayerConfigRequested(device_id) => {
                let socket_path = self.socket_path.clone();
                let id = device_id.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        (id.clone(), client.list_layers(&id).await)
                    },
                    |(device_id, result)| match result {
                        Ok(layers) => {
                            // Store layers and trigger UI refresh
                            // We'll emit LayerStateChanged for the active layer
                            if let Some(active_layer) = layers.first() {
                                Message::LayerStateChanged(device_id, active_layer.layer_id)
                            } else {
                                Message::TickAnimations // No-op refresh
                            }
                        }
                        Err(e) => Message::ProfileError(format!("Failed to load layers: {}", e)),
                    }
                )
            }
            Message::LayerActivateRequested(device_id, layer_id, mode) => {
                let socket_path = self.socket_path.clone();
                let id = device_id.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.activate_layer(&id, layer_id, mode).await
                    },
                    move |result| match result {
                        Ok(()) => Message::LayerStateChanged(device_id, layer_id),
                        Err(e) => Message::ProfileError(format!("Failed to activate layer: {}", e)),
                    }
                )
            }
            Message::LayerConfigUpdated(device_id, config) => {
                let socket_path = self.socket_path.clone();
                let id = device_id.clone();
                let layer_id = config.layer_id;
                let name = config.name.clone();
                let mode = config.mode;
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.set_layer_config(&id, layer_id, name, mode).await
                    },
                    move |result| match result {
                        Ok(()) => {
                            // Refresh layer list after config update
                            Message::LayerConfigRequested(device_id)
                        }
                        Err(e) => Message::ProfileError(format!("Failed to update layer config: {}", e)),
                    }
                )
            }
            Message::OpenLayerConfigDialog(device_id, layer_id) => {
                // Get current layer config if available
                let current_name = self.layer_configs
                    .get(&device_id)
                    .and_then(|layers| layers.iter().find(|l| l.layer_id == layer_id))
                    .map(|l| l.name.clone())
                    .unwrap_or_else(|| format!("Layer {}", layer_id));

                let current_mode = self.layer_configs
                    .get(&device_id)
                    .and_then(|layers| layers.iter().find(|l| l.layer_id == layer_id))
                    .map(|l| l.mode)
                    .unwrap_or(LayerMode::Hold);

                self.layer_config_dialog = Some((device_id, layer_id, current_name, current_mode));
                Command::none()
            }
            Message::LayerConfigNameChanged(name) => {
                if let Some((device_id, layer_id, _, mode)) = self.layer_config_dialog.take() {
                    self.layer_config_dialog = Some((device_id, layer_id, name, mode));
                }
                Command::none()
            }
            Message::LayerConfigModeChanged(mode) => {
                if let Some((device_id, layer_id, name, _)) = self.layer_config_dialog.take() {
                    self.layer_config_dialog = Some((device_id, layer_id, name, mode));
                }
                Command::none()
            }
            Message::SaveLayerConfig => {
                if let Some((device_id, layer_id, name, mode)) = self.layer_config_dialog.take() {
                    let config = LayerConfigInfo {
                        layer_id,
                        name: name.clone(),
                        mode,
                        remap_count: 0,
                        led_color: (0, 0, 255), // Default blue - TODO: allow GUI configuration
                        led_zone: None, // Default zone - TODO: allow GUI configuration
                    };
                    // Return LayerConfigUpdated message to handle the async save
                    Command::perform(
                        async move { (device_id, config) },
                        |(device_id, config)| Message::LayerConfigUpdated(device_id, config)
                    )
                } else {
                    Command::none()
                }
            }
            Message::CancelLayerConfig => {
                self.layer_config_dialog = None;
                Command::none()
            }
            Message::RefreshLayers => {
                // Periodic refresh of layer states for all devices
                let mut commands = Vec::new();

                // Request layer configuration refresh for devices that have profiles loaded
                for device_id in self.device_profiles.keys() {
                    let device_id = device_id.clone();
                    let socket_path = self.socket_path.clone();
                    commands.push(Command::perform(
                        async move {
                            let client = crate::ipc::IpcClient::new(socket_path);
                            (device_id.clone(), client.list_layers(&device_id).await)
                        },
                        |(device_id, result)| match result {
                            Ok(layers) => {
                                // Store layers and update active layer
                                Message::LayerListLoaded(device_id, layers)
                            }
                            Err(_) => Message::TickAnimations, // Silent fail on refresh
                        }
                    ));
                }

                // Also refresh active layer states
                for device_id in self.active_layers.keys().cloned().collect::<Vec<_>>() {
                    let device_id = device_id.clone();
                    let socket_path = self.socket_path.clone();
                    commands.push(Command::perform(
                        async move {
                            let client = crate::ipc::IpcClient::new(socket_path);
                            (device_id.clone(), client.get_active_layer(&device_id).await)
                        },
                        |(device_id, result)| match result {
                            Ok(Some(layer_id)) => {
                                Message::LayerStateChanged(device_id, layer_id)
                            }
                            _ => Message::TickAnimations,
                        }
                    ));
                }

                Command::batch(commands)
            }
            Message::LayerListLoaded(device_id, layers) => {
                self.layer_configs.insert(device_id.clone(), layers);
                Command::none()
            }

            Message::AnalogDpadModeRequested(device_id) => {
                let socket_path = self.socket_path.clone();
                let device_id_clone = device_id.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.get_analog_dpad_mode(&device_id_clone).await
                    },
                    move |result| match result {
                        Ok(mode) => Message::AnalogDpadModeLoaded(device_id, mode),
                        Err(e) => {
                            eprintln!("Failed to get D-pad mode: {}", e);
                            Message::TickAnimations // Silent fail
                        }
                    },
                )
            }

            Message::AnalogDpadModeLoaded(device_id, mode) => {
                self.analog_dpad_modes.insert(device_id, mode);
                Command::none()
            }

            Message::SetAnalogDpadMode(device_id, mode) => {
                let socket_path = self.socket_path.clone();
                let device_id_clone = device_id.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.set_analog_dpad_mode(&device_id_clone, &mode).await
                    },
                    |result| match result {
                        Ok(_) => Message::AnalogDpadModeSet(Ok(())),
                        Err(e) => Message::AnalogDpadModeSet(Err(e)),
                    },
                )
            }

            Message::AnalogDpadModeSet(result) => {
                match result {
                    Ok(_) => {
                        // Success - D-pad mode updated
                        Command::none()
                    }
                    Err(e) => {
                        eprintln!("Failed to set D-pad mode: {}", e);
                        // Could show a toast notification here
                        Command::none()
                    }
                }
            }

            // Per-Axis Deadzone handlers
            Message::AnalogDeadzoneXYRequested(device_id) => {
                let socket_path = self.socket_path.clone();
                let device_id_clone = device_id.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.get_analog_deadzone_xy(&device_id_clone).await
                    },
                    move |result| match result {
                        Ok((x_pct, y_pct)) => Message::AnalogDeadzoneXYLoaded(device_id, (x_pct, y_pct)),
                        Err(e) => {
                            eprintln!("Failed to get per-axis deadzone: {}", e);
                            Message::TickAnimations // Silent fail
                        }
                    },
                )
            }

            Message::AnalogDeadzoneXYLoaded(device_id, (x_pct, y_pct)) => {
                self.analog_deadzones_xy.insert(device_id, (x_pct, y_pct));
                Command::none()
            }

            Message::SetAnalogDeadzoneXY(device_id, x_pct, y_pct) => {
                let socket_path = self.socket_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.set_analog_deadzone_xy(&device_id, x_pct, y_pct).await
                    },
                    |result| match result {
                        Ok(_) => Message::AnalogDeadzoneXYSet(Ok(())),
                        Err(e) => Message::AnalogDeadzoneXYSet(Err(e)),
                    },
                )
            }

            Message::AnalogDeadzoneXYSet(result) => {
                match result {
                    Ok(_) => {
                        // Success - per-axis deadzone updated
                        Command::none()
                    }
                    Err(e) => {
                        eprintln!("Failed to set per-axis deadzone: {}", e);
                        self.add_notification(&format!("Failed to set deadzone: {}", e), true);
                        Command::none()
                    }
                }
            }

            // Per-Axis Outer Deadzone handlers
            Message::AnalogOuterDeadzoneXYRequested(device_id) => {
                let socket_path = self.socket_path.clone();
                let device_id_clone = device_id.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.get_analog_outer_deadzone_xy(&device_id_clone).await
                    },
                    move |result| match result {
                        Ok((x_pct, y_pct)) => Message::AnalogOuterDeadzoneXYLoaded(device_id, (x_pct, y_pct)),
                        Err(e) => {
                            eprintln!("Failed to get per-axis outer deadzone: {}", e);
                            Message::TickAnimations // Silent fail
                        }
                    },
                )
            }

            Message::AnalogOuterDeadzoneXYLoaded(device_id, (x_pct, y_pct)) => {
                self.analog_outer_deadzones_xy.insert(device_id, (x_pct, y_pct));
                Command::none()
            }

            Message::SetAnalogOuterDeadzoneXY(device_id, x_pct, y_pct) => {
                let socket_path = self.socket_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.set_analog_outer_deadzone_xy(&device_id, x_pct, y_pct).await
                    },
                    |result| match result {
                        Ok(_) => Message::AnalogOuterDeadzoneXYSet(Ok(())),
                        Err(e) => Message::AnalogOuterDeadzoneXYSet(Err(e)),
                    },
                )
            }

            Message::AnalogOuterDeadzoneXYSet(result) => {
                match result {
                    Ok(_) => {
                        // Success - per-axis outer deadzone updated
                        Command::none()
                    }
                    Err(e) => {
                        eprintln!("Failed to set per-axis outer deadzone: {}", e);
                        self.add_notification(&format!("Failed to set outer deadzone: {}", e), true);
                        Command::none()
                    }
                }
            }

            // LED Configuration handlers
            Message::OpenLedConfig(device_id) => {
                self.led_config_device = Some(device_id.clone());
                self.selected_led_zone = Some(LedZone::Logo); // Default to Logo zone
                return Command::batch([
                    Command::none(),
                    Command::perform(
                        async move { device_id },
                        |device_id| Message::RefreshLedState(device_id)
                    ),
                ]);
            }

            Message::CloseLedConfig => {
                self.led_config_device = None;
                self.selected_led_zone = None;
                self.pending_led_color = None;
                Command::none()
            }

            Message::SelectLedZone(zone) => {
                self.selected_led_zone = Some(zone);
                Command::none()
            }

            Message::RefreshLedState(device_id) => {
                let socket_path = self.socket_path.clone();
                let device_id_clone = device_id.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.get_all_led_colors(&device_id_clone).await
                    },
                    move |result| match result {
                        Ok(colors) => Message::LedStateLoaded(device_id, Ok(colors)),
                        Err(e) => Message::LedStateLoaded(device_id, Err(e)),
                    },
                )
            }

            Message::LedStateLoaded(device_id, result) => {
                match result {
                    Ok(colors) => {
                        // Initialize LED state for device if not exists
                        let led_state = self.led_states.entry(device_id.clone()).or_default();
                        led_state.zone_colors = colors;
                        Command::none()
                    }
                    Err(e) => {
                        eprintln!("Failed to load LED state: {}", e);
                        // Silent fail - LED may not be supported
                        Command::none()
                    }
                }
            }

            Message::SetLedColor(device_id, zone, red, green, blue) => {
                let socket_path = self.socket_path.clone();
                let device_id_clone = device_id.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.set_led_color(&device_id_clone, zone, red, green, blue).await
                    },
                    move |result| match result {
                        Ok(_) => Message::LedColorSet(Ok(())),
                        Err(e) => Message::LedColorSet(Err(e)),
                    },
                )
            }

            Message::LedColorSet(result) => {
                match result {
                    Ok(_) => {
                        // Success - color updated
                        Command::none()
                    }
                    Err(e) => {
                        eprintln!("Failed to set LED color: {}", e);
                        self.add_notification(&format!("Failed to set LED color: {}", e), true);
                        Command::none()
                    }
                }
            }

            Message::SetLedBrightness(device_id, zone, brightness) => {
                let socket_path = self.socket_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.set_led_brightness(&device_id, zone, brightness).await
                    },
                    |result| match result {
                        Ok(_) => Message::LedBrightnessSet(Ok(())),
                        Err(e) => Message::LedBrightnessSet(Err(e)),
                    },
                )
            }

            Message::LedBrightnessSet(result) => {
                match result {
                    Ok(_) => {
                        // Success - brightness updated
                        Command::none()
                    }
                    Err(e) => {
                        eprintln!("Failed to set LED brightness: {}", e);
                        self.add_notification(&format!("Failed to set LED brightness: {}", e), true);
                        Command::none()
                    }
                }
            }

            Message::SetLedPattern(device_id, pattern) => {
                let socket_path = self.socket_path.clone();
                Command::perform(
                    async move {
                        let client = crate::ipc::IpcClient::new(socket_path);
                        client.set_led_pattern(&device_id, pattern).await
                    },
                    |result| match result {
                        Ok(_) => Message::LedPatternSet(Ok(())),
                        Err(e) => Message::LedPatternSet(Err(e)),
                    },
                )
            }

            Message::LedPatternSet(result) => {
                match result {
                    Ok(_) => {
                        // Success - pattern updated
                        Command::none()
                    }
                    Err(e) => {
                        eprintln!("Failed to set LED pattern: {}", e);
                        self.add_notification(&format!("Failed to set LED pattern: {}", e), true);
                        Command::none()
                    }
                }
            }

            Message::LedSliderChanged(red, green, blue) => {
                self.pending_led_color = Some((red, green, blue));
                // If a device and zone are selected, apply the color immediately
                if let (Some(ref device_id), Some(zone)) = (&self.led_config_device, self.selected_led_zone) {
                    let device_id = device_id.clone();
                    return Command::perform(
                        async move { (device_id, zone, red, green, blue) },
                        |(device_id, zone, red, green, blue)| {
                            Message::SetLedColor(device_id, zone, red, green, blue)
                        },
                    );
                }
                Command::none()
            }
        }
    }

    fn view(&self) -> Element<'_, Message> {
        let sidebar = self.view_sidebar();
        let main_content = self.view_main_content();
        let status_bar = self.view_status_bar();

        let main_layout = row![
            sidebar,
            vertical_rule(1),
            column![
                main_content,
                horizontal_rule(1),
                status_bar,
            ]
            .height(Length::Fill)
        ];

        let base: Element<'_, Message> = container(main_layout)
            .width(Length::Fill)
            .height(Length::Fill)
            .into();

        // Show layer config dialog overlay if active
        if let Some(dialog) = self.layer_config_dialog() {
            container(
                column![
                    base,
                    dialog,
                ]
                .height(Length::Fill)
            )
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
        } else if let Some(led_dialog) = self.view_led_config() {
            // Show LED config dialog overlay if active
            container(
                column![
                    base,
                    led_dialog,
                ]
                .height(Length::Fill)
            )
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
        } else if let Some(calib_dialog) = self.view_analog_calibration() {
            // Show analog calibration dialog overlay if active
            container(
                column![
                    base,
                    calib_dialog,
                ]
                .height(Length::Fill)
            )
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
        } else {
            base
        }
    }

    fn subscription(&self) -> Subscription<Message> {
        let timer = iced::time::every(Duration::from_millis(500)).map(|_| Message::TickAnimations);

        // Periodic layer state refresh (every 2 seconds)
        let layer_refresh = iced::time::every(Duration::from_secs(2))
            .map(|_| Message::RefreshLayers);

        // Subscribe to mouse events only when recording
        // Note: In iced 0.12, mouse events are handled via the runtime event stream
        // The actual mouse event capture for macros happens at the daemon level via evdev
        // This subscription tracks recording state for UI updates only
        let mouse_events = iced::event::listen_with(|event, _status| {
            match event {
                iced::Event::Mouse(iced::mouse::Event::ButtonPressed(iced::mouse::Button::Left)) => {
                    Some(Message::RecordMouseEvent {
                        event_type: "button_press".to_string(),
                        button: Some(0x110), // BTN_LEFT in evdev
                        x: 0,
                        y: 0,
                        delta: 0,
                    })
                }
                iced::Event::Mouse(iced::mouse::Event::ButtonPressed(iced::mouse::Button::Right)) => {
                    Some(Message::RecordMouseEvent {
                        event_type: "button_press".to_string(),
                        button: Some(0x111), // BTN_RIGHT in evdev
                        x: 0,
                        y: 0,
                        delta: 0,
                    })
                }
                iced::Event::Mouse(iced::mouse::Event::ButtonPressed(iced::mouse::Button::Middle)) => {
                    Some(Message::RecordMouseEvent {
                        event_type: "button_press".to_string(),
                        button: Some(0x112), // BTN_MIDDLE in evdev
                        x: 0,
                        y: 0,
                        delta: 0,
                    })
                }
                iced::Event::Mouse(iced::mouse::Event::ButtonReleased(_)) => {
                    Some(Message::RecordMouseEvent {
                        event_type: "button_release".to_string(),
                        button: Some(0),
                        x: 0,
                        y: 0,
                        delta: 0,
                    })
                }
                iced::Event::Mouse(iced::mouse::Event::WheelScrolled { delta }) => {
                    let scroll_delta = match delta {
                        iced::mouse::ScrollDelta::Lines { y, .. } => y as i32,
                        iced::mouse::ScrollDelta::Pixels { y, .. } => y as i32,
                    };
                    Some(Message::RecordMouseEvent {
                        event_type: "scroll".to_string(),
                        button: None,
                        x: 0,
                        y: 0,
                        delta: scroll_delta,
                    })
                }
                iced::Event::Mouse(iced::mouse::Event::CursorMoved { .. }) => {
                    // Note: Cursor movement is tracked but may be sampled at reduced rate
                    Some(Message::RecordMouseEvent {
                        event_type: "movement".to_string(),
                        button: None,
                        x: 0,
                        y: 0,
                        delta: 0,
                    })
                }
                _ => None,
            }
        });

        // Only enable mouse event subscription during recording
        let mouse_subscription = if self.recording {
            mouse_events
        } else {
            Subscription::none()
        };

        let theme_subscription = iced::subscription::unfold(
            "ashpd-theme",
            None,
            |state: Option<iced::futures::stream::BoxStream<'static, ashpd::desktop::settings::ColorScheme>>| async move {
                use ashpd::desktop::settings::{ColorScheme, Settings};
                use iced::futures::StreamExt;

                let mut stream = match state {
                    Some(s) => s,
                    None => {
                        let settings = match Settings::new().await {
                            Ok(s) => s,
                            Err(_) => return iced::futures::future::pending().await,
                        };
                        let initial = settings.color_scheme().await.unwrap_or(ColorScheme::NoPreference);
                        let theme = match initial {
                            ColorScheme::PreferDark => aether_dark(),
                            ColorScheme::PreferLight => aether_light(),
                            ColorScheme::NoPreference => aether_dark(),
                        };
                        
                        let s = match settings.receive_color_scheme_changed().await {
                            Ok(s) => s,
                            Err(_) => return (Message::ThemeChanged(theme), None),
                        };
                        return (Message::ThemeChanged(theme), Some(s.boxed()));
                    }
                };

                if let Some(scheme) = stream.next().await {
                    let theme = match scheme {
                        ColorScheme::PreferDark => aether_dark(),
                        ColorScheme::PreferLight => aether_light(),
                        ColorScheme::NoPreference => aether_dark(),
                    };
                    (Message::ThemeChanged(theme), Some(stream))
                } else {
                    iced::futures::future::pending().await
                }
            }
        );

        Subscription::batch(vec![timer, layer_refresh, mouse_subscription, theme_subscription])
    }
}

impl State {
    fn add_notification(&mut self, message: &str, is_error: bool) {
        self.notifications.push_back(Notification {
            message: message.to_string(),
            is_error,
            timestamp: Instant::now(),
        });
        self.status = message.to_string();
        self.status_history.push_back(message.to_string());
        if self.status_history.len() > 10 {
            self.status_history.pop_front();
        }
        if self.notifications.len() > 5 {
            self.notifications.pop_front();
        }
    }

    fn view_sidebar(&self) -> Element<'_, Message> {
        let logo = column![
            text("").size(40),
            text("AETHERMAP").size(16),
            text("v1.4.1").size(10),
        ]
        .spacing(2)
        .align_items(Alignment::Center)
        .width(Length::Fill);

        let nav_button = |label: &str, icon: &str, tab: Tab| {
            let is_active = self.active_tab == tab;
            let btn_style = if is_active {
                iced::theme::Button::Primary
            } else {
                iced::theme::Button::Text
            };

            button(
                row![
                    text(icon).size(18),
                    Space::with_width(10),
                    text(label).size(14),
                ]
                .align_items(Alignment::Center)
            )
            .on_press(Message::SwitchTab(tab))
            .style(btn_style)
            .padding([12, 20])
            .width(Length::Fill)
        };

        let connection_status = if self.daemon_connected {
            row![
                text("").size(12),
                Space::with_width(8),
                text("Connected").size(11),
            ]
        } else {
            row![
                text("").size(12),
                Space::with_width(8),
                text("Disconnected").size(11),
            ]
        }
        .align_items(Alignment::Center);

        let sidebar_content = column![
            logo,
            Space::with_height(30),
            nav_button("Devices", "🎮", Tab::Devices),
            nav_button("Macros", "", Tab::Macros),
            nav_button("Profiles", "📁", Tab::Profiles),
            Space::with_height(Length::Fill),
            horizontal_rule(1),
            Space::with_height(10),
            connection_status,
            Space::with_height(5),
            button("Refresh")
                .on_press(Message::CheckDaemonConnection)
                .style(iced::theme::Button::Text)
                .width(Length::Fill),
        ]
        .spacing(4)
        .padding(16)
        .align_items(Alignment::Center);

        container(sidebar_content)
            .width(180)
            .height(Length::Fill)
            .into()
    }

    fn view_main_content(&self) -> Element<'_, Message> {
        let content = match self.active_tab {
            Tab::Devices => self.view_devices_tab(),
            Tab::Macros => self.view_macros_tab(),
            Tab::Profiles => self.view_profiles_tab(),
        };

        container(scrollable(content))
            .width(Length::Fill)
            .height(Length::Fill)
            .padding(24)
            .into()
    }

    fn view_devices_tab(&self) -> Element<'_, Message> {
        let header = row![
            text("DEVICES").size(24),
            Space::with_width(Length::Fill),
            button("Reload")
                .on_press(Message::LoadDevices)
                .style(iced::theme::Button::Secondary),
        ]
        .align_items(Alignment::Center);

        // Show auto-switch rules view when open
        if let Some(ref view) = self.auto_switch_view {
            return column![
                header,
                Space::with_height(20),
                row![
                    button("← Back to Devices")
                        .on_press(Message::CloseAutoSwitchRules)
                        .style(iced::theme::Button::Text),
                    Space::with_width(Length::Fill),
                    text(format!("Auto-Switch Rules: {}", view.device_id)).size(18),
                ]
                .align_items(Alignment::Center),
                Space::with_height(20),
                self.view_auto_switch_rules(),
            ]
            .spacing(10)
            .into();
        }

        // Show hotkey bindings view when open
        if let Some(ref view) = self.hotkey_view {
            return column![
                header,
                Space::with_height(20),
                row![
                    button("← Back to Devices")
                        .on_press(Message::CloseHotkeyBindings)
                        .style(iced::theme::Button::Text),
                    Space::with_width(Length::Fill),
                    text(format!("Hotkey Bindings: {}", view.device_id)).size(18),
                ]
                .align_items(Alignment::Center),
                Space::with_height(20),
                self.view_hotkey_bindings(),
            ]
            .spacing(10)
            .into();
        }

        // Show keypad view when capabilities are loaded
        if self.device_capabilities.is_some() && !self.keypad_layout.is_empty() {
            // Build keypad view content
            let mut keypad_content = vec![
                header.into(),
                Space::with_height(20).into(),
                row![
                    button("← Back to Devices")
                        .on_press(Message::ShowKeypadView("".to_string()))
                        .style(iced::theme::Button::Text),
                    Space::with_width(Length::Fill),
                ]
                .align_items(Alignment::Center)
                .into(),
                Space::with_height(20).into(),
                self.view_azeron_keypad().into(),
            ];

            // Add profile quick toggles at the bottom if device path is available
            if let Some(ref device_path) = self.keypad_view_device {
                keypad_content.push(Space::with_height(20).into());
                keypad_content.push(
                    container(
                        column![
                            text("Quick Profile Switch").size(14),
                            Space::with_height(8),
                            self.profile_quick_toggles(device_path),
                        ]
                        .spacing(4)
                    )
                    .padding(16)
                    .width(Length::Fill)
                    .style(container_styles::card)
                    .into()
                );
            }

            return column(keypad_content)
                .spacing(10)
                .into();
        }

        let device_list = if self.devices.is_empty() {
            column![
                Space::with_height(40),
                text("No devices found").size(16),
                Space::with_height(10),
                text("Click 'Reload' to scan for input devices").size(12),
            ]
            .align_items(Alignment::Center)
            .width(Length::Fill)
        } else {
            let mut list: Column<Message> = column![].spacing(12);
            for (idx, device) in self.devices.iter().enumerate() {
                list = list.push(self.view_device_card(device, idx));
            }
            list
        };

        column![
            header,
            Space::with_height(20),
            device_list,
        ]
        .spacing(10)
        .into()
    }

    fn view_device_card(&self, device: &DeviceInfo, idx: usize) -> Element<'_, Message> {
        let device_path = device.path.to_string_lossy().to_string();
        let is_grabbed = self.grabbed_devices.contains(&device_path);
        let is_selected = self.selected_device == Some(idx);

        // Use device_type from capability detection (not name heuristics)
        let icon = match device.device_type {
            DeviceType::Keyboard => "⌨️",
            DeviceType::Mouse => "🖱️",
            DeviceType::Gamepad => "🎮",
            DeviceType::Keypad => "🎹",
            DeviceType::Other => "📱",
        };

        let status_badge = if is_grabbed {
            container(
                text("GRABBED").size(10)
            )
            .padding([4, 8])
            .style(container_styles::card)
        } else {
            container(text("").size(10))
        };

        let action_button = if is_grabbed {
            button("Release")
                .on_press(Message::UngrabDevice(device_path.clone()))
                .style(iced::theme::Button::Destructive)
        } else {
            button("Grab Device")
                .on_press(Message::GrabDevice(device_path.clone()))
                .style(iced::theme::Button::Primary)
        };

        let select_indicator = if is_selected { "" } else { "" };

        // Get device_id for layer operations
        let device_id = format!("{:04x}:{:04x}", device.vendor_id, device.product_id);

        // Add "Configure Keypad" button for keypad devices
        let keypad_button = if device.device_type == DeviceType::Keypad {
            Some(
                button("Configure Keypad")
                    .on_press(Message::ShowKeypadView(device_path.clone()))
                    .style(iced::theme::Button::Secondary)
            )
        } else {
            None
        };

        // Add "Configure LEDs" button for LED-capable devices (keypad/gamepad)
        let led_button = if device.device_type == DeviceType::Keypad || device.device_type == DeviceType::Gamepad {
            Some(
                button("Configure LEDs")
                    .on_press(Message::OpenLedConfig(device_id.clone()))
                    .style(iced::theme::Button::Secondary)
            )
        } else {
            None
        };

        // Add "Auto-Switch Rules" button for all devices
        let auto_switch_button = Some(
            button("Auto-Switch Rules")
                .on_press(Message::ShowAutoSwitchRules(device_id.clone()))
                .style(iced::theme::Button::Secondary)
        );

        // Add "Hotkey Bindings" button for all devices
        let hotkey_button = Some(
            button("Hotkey Bindings")
                .on_press(Message::ShowHotkeyBindings(device_id.clone()))
                .style(iced::theme::Button::Secondary)
        );

        // Add "Analog Calibration" button for devices with analog support
        let analog_button = if device.device_type == DeviceType::Keypad ||
                             device.device_type == DeviceType::Gamepad {
            Some(
                button("Analog Calibration")
                    .on_press(Message::OpenAnalogCalibration {
                        device_id: device_id.clone(),
                        layer_id: self.active_layers.get(&device_id).copied().unwrap_or(0),
                    })
                    .style(iced::theme::Button::Secondary)
            )
        } else {
            None
        };

        let card_content = column![
            row![
                text(icon).size(28),
                Space::with_width(12),
                column![
                    row![
                        text(format!("{}{}", select_indicator, device.name)).size(16),
                        Space::with_width(8),
                        text(match device.device_type {
                            DeviceType::Keyboard => "Keyboard",
                            DeviceType::Mouse => "Mouse",
                            DeviceType::Gamepad => "Gamepad",
                            DeviceType::Keypad => "Keypad",
                            DeviceType::Other => "Other",
                        }).size(12).style(iced::theme::Text::Color(iced::Color::from_rgb(0.6, 0.6, 0.6))),
                    ],
                    text(format!(
                        "VID:{:04X} PID:{:04X} | {}",
                        device.vendor_id, device.product_id, device_path
                    )).size(11),
                ],
                Space::with_width(Length::Fill),
                status_badge,
            ]
            .align_items(Alignment::Center),
            Space::with_height(12),
            row![
                button("Select")
                    .on_press(Message::SelectDevice(idx))
                    .style(iced::theme::Button::Text),
                Space::with_width(Length::Fill),
                action_button,
            ],
            Space::with_height(8),
            self.view_profile_selector(device),
            self.view_remap_profile_switcher(&device_path),
            Space::with_height(4),
            // Profile quick toggles - horizontal row of profile buttons
            container(
                column![
                    text("Profiles").size(11).style(iced::theme::Text::Color(iced::Color::from_rgb(0.5, 0.5, 0.5))),
                    Space::with_height(4),
                    self.profile_quick_toggles(&device_path),
                ]
                .spacing(4)
            )
            .padding([8, 0])
            .width(Length::Fill),
            Space::with_height(8),
            row![
                text("Layer:").size(12),
                Space::with_width(8),
                self.layer_indicator(&device_id),
                Space::with_width(Length::Fill),
                self.layer_activation_buttons(&device_id),
            ]
            .spacing(4)
            .align_items(Alignment::Center),
        ]
        .spacing(8);

        // Build card content with optional D-pad mode selector
        let mut card_elements: Vec<Element<'_, Message>> = vec![card_content.into()];

        // Add D-pad mode selector for devices with analog sticks
        if device.device_type == DeviceType::Gamepad || device.device_type == DeviceType::Keypad {
            let current_mode = self.analog_dpad_modes.get(&device_id).cloned().unwrap_or_else(|| "disabled".to_string());

            card_elements.push(Space::with_height(4).into());
            card_elements.push(
                row![
                    text("D-pad:").size(12),
                    Space::with_width(4),
                    button("Off")
                        .on_press(Message::SetAnalogDpadMode(device_id.clone(), "disabled".to_string()))
                        .style(if current_mode == "disabled" {
                            iced::theme::Button::Primary
                        } else {
                            iced::theme::Button::Text
                        }),
                    button("8-Way")
                        .on_press(Message::SetAnalogDpadMode(device_id.clone(), "eight_way".to_string()))
                        .style(if current_mode == "eight_way" {
                            iced::theme::Button::Primary
                        } else {
                            iced::theme::Button::Text
                        }),
                    button("4-Way")
                        .on_press(Message::SetAnalogDpadMode(device_id.clone(), "four_way".to_string()))
                        .style(if current_mode == "four_way" {
                            iced::theme::Button::Primary
                        } else {
                            iced::theme::Button::Text
                        }),
                ]
                .spacing(4)
                .align_items(Alignment::Center)
                .into()
            );

            // Add per-axis deadzone controls
            let (deadzone_x, deadzone_y) = self.analog_deadzones_xy.get(&device_id).cloned().unwrap_or((43, 43));
            let (outer_deadzone_x, outer_deadzone_y) = self.analog_outer_deadzones_xy.get(&device_id).cloned().unwrap_or((100, 100));

            card_elements.push(Space::with_height(8).into());

            // Inner deadzone controls
            card_elements.push(
                column![
                    text("Deadzone (noise filter)").size(11),
                    row![
                        text("X:").size(11),
                        Space::with_width(4),
                        self.deadzone_buttons(&device_id, false, deadzone_x),
                        Space::with_width(8),
                        text(format!("{}%", deadzone_x)).size(11),
                    ]
                    .spacing(2)
                    .align_items(Alignment::Center),
                    row![
                        text("Y:").size(11),
                        Space::with_width(4),
                        self.deadzone_buttons(&device_id, true, deadzone_y),
                        Space::with_width(8),
                        text(format!("{}%", deadzone_y)).size(11),
                    ]
                    .spacing(2)
                    .align_items(Alignment::Center),
                ]
                .spacing(4)
                .into()
            );

            // Outer deadzone controls
            card_elements.push(Space::with_height(4).into());
            card_elements.push(
                column![
                    text("Max Range (input clamp)").size(11),
                    row![
                        text("X:").size(11),
                        Space::with_width(4),
                        self.outer_deadzone_buttons(&device_id, false, outer_deadzone_x),
                        Space::with_width(8),
                        text(format!("{}%", outer_deadzone_x)).size(11),
                    ]
                    .spacing(2)
                    .align_items(Alignment::Center),
                    row![
                        text("Y:").size(11),
                        Space::with_width(4),
                        self.outer_deadzone_buttons(&device_id, true, outer_deadzone_y),
                        Space::with_width(8),
                        text(format!("{}%", outer_deadzone_y)).size(11),
                    ]
                    .spacing(2)
                    .align_items(Alignment::Center),
                ]
                .spacing(4)
                .into()
            );
        }

        // Add keypad button if applicable
        if let Some(keypad_btn) = keypad_button {
            card_elements.push(Space::with_height(4).into());
            card_elements.push(
                row![Space::with_width(Length::Fill), keypad_btn,]
                    .spacing(4)
                    .into()
            );
        }

        // Add LED configuration button if applicable
        if let Some(led_btn) = led_button {
            card_elements.push(Space::with_height(4).into());
            card_elements.push(
                row![Space::with_width(Length::Fill), led_btn,]
                    .spacing(4)
                    .into()
            );
        }

        // Add auto-switch rules button
        if let Some(auto_btn) = auto_switch_button {
            card_elements.push(Space::with_height(4).into());
            card_elements.push(
                row![Space::with_width(Length::Fill), auto_btn,]
                    .spacing(4)
                    .into()
            );
        }

        // Add hotkey bindings button
        if let Some(hotkey_btn) = hotkey_button {
            card_elements.push(Space::with_height(4).into());
            card_elements.push(
                row![Space::with_width(Length::Fill), hotkey_btn,]
                    .spacing(4)
                    .into()
            );
        }

        // Add analog calibration button
        if let Some(analog_btn) = analog_button {
            card_elements.push(Space::with_height(4).into());
            card_elements.push(
                row![Space::with_width(Length::Fill), analog_btn,]
                    .spacing(4)
                    .into()
            );
        }

        let card_content = column(card_elements).spacing(4);

        container(card_content)
            .padding(16)
            .width(Length::Fill)
            .style(container_styles::card)
            .into()
    }

    fn view_macros_tab(&self) -> Element<'_, Message> {
        let header = row![
            text("MACROS").size(24),
            Space::with_width(Length::Fill),
            text(format!("{} total", self.macros.len())).size(14),
        ]
        .align_items(Alignment::Center);

        let recording_section = self.view_recording_panel();
        let settings_section = self.view_macro_settings_panel();
        let macro_list = self.view_macro_list();

        column![
            header,
            Space::with_height(20),
            row![
                recording_section,
                settings_section,
            ].spacing(20),
            Space::with_height(20),
            text("MACRO LIBRARY").size(18),
            Space::with_height(10),
            macro_list,
        ]
        .spacing(10)
        .into()
    }

    fn view_recording_panel(&self) -> Element<'_, Message> {
        let name_input = text_input("Enter macro name (e.g., 'Quick Reload')", &self.new_macro_name)
            .on_input(Message::UpdateMacroName)
            .padding(12)
            .size(14);

        let record_button = if self.recording {
            let indicator = if self.recording_pulse { "" } else { "" };
            button(
                row![
                    text(indicator).size(18),
                    Space::with_width(8),
                    text("STOP RECORDING").size(14),
                ]
                .align_items(Alignment::Center)
            )
            .on_press(Message::StopRecording)
            .style(iced::theme::Button::Destructive)
            .padding([14, 24])
        } else {
            button(
                row![
                    text("").size(18),
                    Space::with_width(8),
                    text("START RECORDING").size(14),
                ]
                .align_items(Alignment::Center)
            )
            .on_press(Message::StartRecording)
            .style(iced::theme::Button::Primary)
            .padding([14, 24])
        };

        let instructions = column![
            text("Recording Instructions").size(14),
            Space::with_height(8),
            text("1. Go to Devices tab and grab a device").size(12),
            text("2. Enter a descriptive macro name above").size(12),
            text("3. Click 'Start Recording' and press keys").size(12),
            text("4. Click 'Stop Recording' when finished").size(12),
        ]
        .spacing(4);

        let recording_status = if self.recording {
            container(
                row![
                    text("").size(14),
                    Space::with_width(8),
                    text(format!(
                        "Recording '{}' - Press keys on grabbed device...",
                        self.recording_macro_name.as_deref().unwrap_or("")
                    )).size(13),
                ]
                .align_items(Alignment::Center)
            )
            .padding(12)
            .width(Length::Fill)
            .style(container_styles::card)
        } else {
            container(text(""))
        };

        let panel_content = column![
            text("MACRO RECORDING").size(16),
            Space::with_height(16),
            name_input,
            Space::with_height(16),
            instructions,
            Space::with_height(16),
            recording_status,
            Space::with_height(16),
            container(record_button).center_x(),
        ];

        container(panel_content)
            .padding(20)
            .width(Length::Fill)
            .style(container_styles::card)
            .into()
    }

    fn view_macro_settings_panel(&self) -> Element<'_, Message> {
        let latency_label = text(format!("Latency Offset: {}ms", self.macro_settings.latency_offset_ms)).size(14);
        let latency_slider = slider(
            0..=200,
            self.macro_settings.latency_offset_ms,
            Message::LatencyChanged,
        );

        let jitter_label = text(format!("Jitter: {:.0}%", self.macro_settings.jitter_pct * 100.0)).size(14);
        let jitter_slider = slider(
            0.0..=0.5,
            self.macro_settings.jitter_pct,
            Message::JitterChanged,
        ).step(0.01);

        let capture_mouse_checkbox = checkbox(
            "Capture Mouse (Macro playback moves mouse)",
            self.macro_settings.capture_mouse,
        )
        .on_toggle(Message::CaptureMouseToggled)
        .size(14);

        let content = column![
            text("GLOBAL MACRO SETTINGS").size(16),
            Space::with_height(16),
            latency_label,
            latency_slider,
            Space::with_height(12),
            jitter_label,
            jitter_slider,
            Space::with_height(16),
            capture_mouse_checkbox,
        ]
        .spacing(4);

        container(content)
            .padding(20)
            .width(Length::Fill)
            .style(container_styles::card)
            .into()
    }

    /// View a single macro action with icon formatting
    fn view_macro_action(&self, action: &Action) -> Element<'_, Message> {
        let action_text = Self::format_action_with_icon(action);
        text(action_text).size(11).into()
    }

    fn view_macro_list(&self) -> Element<'_, Message> {
        if self.macros.is_empty() {
            return container(
                column![
                    text("No macros yet").size(14),
                    text("Record your first macro above").size(12),
                ]
                .spacing(8)
                .align_items(Alignment::Center)
            )
            .padding(20)
            .width(Length::Fill)
            .center_x()
            .into();
        }

        let mut list: Column<Message> = column![].spacing(8);

        for macro_entry in &self.macros {
            let is_recent = self.recently_updated_macros.contains_key(&macro_entry.name);
            let name_prefix = if is_recent { "" } else { "" };

            // Create action preview list (show first 3 actions)
            let action_preview: Vec<Element<'_, Message>> = macro_entry.actions
                .iter()
                .take(3)
                .map(|action| self.view_macro_action(action))
                .collect();

            let more_indicator = if macro_entry.actions.len() > 3 {
                Some(text(format!("+ {} more actions...", macro_entry.actions.len() - 3)).size(10))
            } else {
                None
            };

            let macro_card = container(
                row![
                    column![
                        text(format!("{}{}", name_prefix, macro_entry.name)).size(15),
                        text(format!(
                            "{} actions | {} trigger keys | {}",
                            macro_entry.actions.len(),
                            macro_entry.trigger.keys.len(),
                            if macro_entry.enabled { "enabled" } else { "disabled" }
                        )).size(11),
                        // Show action previews
                        column(action_preview)
                            .spacing(2)
                            .padding([4, 0]),
                        more_indicator.unwrap_or_else(|| text("").size(10)),
                    ]
                    .spacing(4),
                    Space::with_width(Length::Fill),
                    button("▶ Test")
                        .on_press(Message::PlayMacro(macro_entry.name.clone()))
                        .style(iced::theme::Button::Secondary),
                    button("🗑")
                        .on_press(Message::DeleteMacro(macro_entry.name.clone()))
                        .style(iced::theme::Button::Destructive),
                ]
                .spacing(8)
                .align_items(Alignment::Center)
            )
            .padding(12)
            .width(Length::Fill)
            .style(container_styles::card);

            list = list.push(macro_card);
        }

        scrollable(list).height(300).into()
    }

    fn view_profiles_tab(&self) -> Element<'_, Message> {
        let header = text("PROFILES").size(24);

        let profile_input = text_input("Profile name...", &self.profile_name)
            .on_input(Message::UpdateProfileName)
            .padding(12)
            .size(14);

        let save_button = button(
            row![
                text("💾").size(16),
                Space::with_width(8),
                text("Save Profile").size(14),
            ]
            .align_items(Alignment::Center)
        )
        .on_press(Message::SaveProfile)
        .style(iced::theme::Button::Primary)
        .padding([12, 20]);

        let load_button = button(
            row![
                text("📂").size(16),
                Space::with_width(8),
                text("Load Profile").size(14),
            ]
            .align_items(Alignment::Center)
        )
        .on_press(Message::LoadProfile)
        .style(iced::theme::Button::Secondary)
        .padding([12, 20]);

        let profile_info = column![
            text("Current Configuration").size(16),
            Space::with_height(10),
            text(format!("{} devices detected", self.devices.len())).size(12),
            text(format!("{} devices grabbed", self.grabbed_devices.len())).size(12),
            text(format!("{} macros configured", self.macros.len())).size(12),
        ]
        .spacing(4);

        let panel_content = column![
            text("SAVE / LOAD CONFIGURATION").size(16),
            Space::with_height(16),
            profile_input,
            Space::with_height(16),
            row![
                save_button,
                Space::with_width(10),
                load_button,
            ],
            Space::with_height(20),
            profile_info,
        ];

        column![
            header,
            Space::with_height(20),
            container(panel_content)
                .padding(20)
                .width(Length::Fill)
                .style(container_styles::card),
        ]
        .spacing(10)
        .into()
    }

    /// Render profile selection dropdown for a device
    fn view_profile_selector(&self, device: &DeviceInfo) -> Element<'_, Message> {
        let device_id = format!("{:04x}:{:04x}", device.vendor_id, device.product_id);
        let profiles = self.device_profiles.get(&device_id);
        let active_profile = self.active_profiles.get(&device_id);

        let profile_row: Element<'_, Message> = if let Some(profiles) = profiles {
            if profiles.is_empty() {
                row![
                    text("Profile: ").size(12),
                    text("No profiles configured").size(12),
                ]
                .spacing(10)
                .align_items(Alignment::Center)
                .into()
            } else {
                let device_id_for_closure = device_id.clone();
                let picker = pick_list(
                    profiles.clone(),
                    active_profile.cloned(),
                    move |profile_name| Message::ActivateProfile(device_id_for_closure.clone(), profile_name),
                )
                .placeholder("Select profile")
                .width(Length::Fixed(150.0));

                let mut row_content = row![
                    text("Profile: ").size(12),
                    picker,
                ]
                .spacing(10)
                .align_items(Alignment::Center);

                // Add deactivate button if profile is active
                if let Some(_active) = active_profile {
                    row_content = row_content.push(
                        button(text("Deactivate").size(11))
                            .on_press(Message::DeactivateProfile(device_id.clone()))
                            .padding(5)
                            .style(iced::theme::Button::Text)
                    );
                }

                row_content.into()
            }
        } else {
            row![
                text("Profile: ").size(12),
                button(text("Load Profiles").size(11))
                    .on_press(Message::LoadDeviceProfiles(device_id.clone()))
                    .padding([4, 8])
                    .style(iced::theme::Button::Text),
            ]
            .spacing(10)
            .align_items(Alignment::Center)
            .into()
        };

        container(profile_row)
            .padding([4, 0])
            .into()
    }

    /// Render remap profile switcher for a device
    fn view_remap_profile_switcher(&self, device_path: &str) -> Element<'_, Message> {
        let profiles = self.remap_profiles.get(device_path);
        let active_profile = self.active_remap_profiles.get(device_path);

        let profile_row: Element<'_, Message> = if let Some(profiles) = profiles {
            if profiles.is_empty() {
                row![
                    text("Remap: ").size(12),
                    text("No remap profiles").size(12),
                ]
                .spacing(10)
                .align_items(Alignment::Center)
                .into()
            } else {
                let profile_names: Vec<String> = profiles.iter().map(|p| p.name.clone()).collect();
                let device_path_for_closure = device_path.to_string();
                let picker = pick_list(
                    profile_names,
                    active_profile.cloned(),
                    move |profile_name| Message::ActivateRemapProfile(device_path_for_closure.clone(), profile_name),
                )
                .placeholder("Select remap profile")
                .width(Length::Fixed(150.0));

                let mut row_content = row![
                    text("Remap: ").size(12),
                    picker,
                ]
                .spacing(10)
                .align_items(Alignment::Center);

                // Add deactivate button if profile is active
                if let Some(_active) = active_profile {
                    row_content = row_content.push(
                        button(text("Off").size(11))
                            .on_press(Message::DeactivateRemapProfile(device_path.to_string()))
                            .padding(5)
                            .style(iced::theme::Button::Text)
                    );
                }

                // Add refresh button
                row_content = row_content.push(
                    button(text("").size(11))
                        .on_press(Message::LoadRemapProfiles(device_path.to_string()))
                        .padding(5)
                        .style(iced::theme::Button::Text)
                );

                row_content.into()
            }
        } else {
            row![
                text("Remap: ").size(12),
                button(text("Load Remaps").size(11))
                    .on_press(Message::LoadRemapProfiles(device_path.to_string()))
                    .padding([4, 8])
                    .style(iced::theme::Button::Text),
            ]
            .spacing(10)
            .align_items(Alignment::Center)
            .into()
        };

        let remap_content = column![
            profile_row,
            self.view_active_remaps_display(device_path),
        ]
        .spacing(4);

        container(remap_content)
            .padding([4, 0])
            .into()
    }

    /// Render active remaps display for a device
    fn view_active_remaps_display(&self, device_path: &str) -> Element<'_, Message> {
        if let Some((profile_name, remaps)) = self.active_remaps.get(device_path) {
            if remaps.is_empty() {
                return text(format!("Profile: {} (no remaps)", profile_name))
                    .size(10)
                    .into();
            }

            let remap_rows: Vec<Element<'_, Message>> = remaps.iter().map(|remap| {
                row![
                    text(format!("{}{}", remap.from_key, remap.to_key))
                        .size(10)
                ]
                .into()
            }).collect();

            let remap_list = scrollable(
                column(remap_rows).spacing(2)
            )
            .height(Length::Fixed(60.0));

            column![
                text(format!("Active: {} ({} remaps)", profile_name, remaps.len())).size(10),
                remap_list,
            ]
            .spacing(2)
            .into()
        } else {
            text("").size(10).into()
        }
    }

    /// Format an action with an appropriate icon for display
    fn format_action_with_icon(action: &Action) -> String {
        match action {
            Action::KeyPress(key) => format!("⌨️ Press Key {}", key),
            Action::KeyRelease(key) => format!("⌨️ Release Key {}", key),
            Action::Delay(ms) => format!("⏱️ Wait {}ms", ms),
            Action::MousePress(btn) => format!("🖱️ Click Button {}", btn),
            Action::MouseRelease(btn) => format!("🖱️ Release Button {}", btn),
            Action::MouseMove(x, y) => format!("↕️ Move X={} Y={}", x, y),
            Action::MouseScroll(amount) => format!("🔄 Scroll {}", amount),
            Action::Execute(cmd) => format!("▶️ Execute {}", cmd),
            Action::Type(text) => format!("⌨️ Type {}", text),
            Action::AnalogMove { axis_code, normalized } => {
                // Convert axis code to human-readable name
                let axis_name = match axis_code {
                    61000 => "X",
                    61001 => "Y",
                    61002 => "Z",
                    61003 => "RX",
                    61004 => "RY",
                    61005 => "RZ",
                    _ => "UNKNOWN",
                };
                format!("🕹️ Analog({}, {:.2})", axis_name, normalized)
            }
        }
    }

    /// View for auto-switch rules configuration
    ///
    /// Displays the current focus, list of rules, and controls for adding/editing rules.
    fn view_auto_switch_rules(&self) -> Element<'_, Message> {
        let view = self.auto_switch_view.as_ref().unwrap();

        // Current focus display
        let focus_display = row![
            text("Current Focus:").size(14),
            Space::with_width(8),
            if let Some(ref focus) = self.current_focus {
                container(text(focus).size(14))
                    .padding([4, 12])
                    .style(container_styles::card)
            } else {
                container(text("Unknown").size(14).style(iced::theme::Text::Color(iced::Color::from_rgb(0.6, 0.6, 0.6))))
                    .padding([4, 12])
            },
        ]
        .spacing(4)
        .align_items(Alignment::Center);

        // Rules list header
        let rules_header = row![
            text("Auto-Switch Rules").size(18),
            Space::with_width(Length::Fill),
            if view.editing_rule.is_some() {
                button("Cancel")
                    .on_press(Message::EditAutoSwitchRule(usize::MAX))
                    .style(iced::theme::Button::Text)
            } else {
                button("Add Rule")
                    .on_press(Message::EditAutoSwitchRule(usize::MAX))
                    .style(iced::theme::Button::Primary)
            },
        ]
        .align_items(Alignment::Center);

        // Rules list
        let rules_list = if view.rules.is_empty() {
            column![
                Space::with_height(20),
                text("No rules configured").size(14).style(iced::theme::Text::Color(iced::Color::from_rgb(0.6, 0.6, 0.6))),
                Space::with_height(8),
                text("Add a rule to automatically switch profiles when windows gain focus").size(12).style(iced::theme::Text::Color(iced::Color::from_rgb(0.5, 0.5, 0.5))),
            ]
            .align_items(Alignment::Center)
        } else {
            let mut list = column![].spacing(8);
            for (idx, rule) in view.rules.iter().enumerate() {
                let is_editing = view.editing_rule == Some(idx);
                let indicator: Element<'_, Message> = if is_editing {
                    container(text("")).padding([0, 8]).into()
                } else {
                    Space::with_width(20).into()
                };
                let row = row![
                    indicator,
                    column![
                        text(format!("App: {}", rule.app_id)).size(14),
                        text(format!("Profile: {}{}", rule.profile_name,
                            rule.layer_id.map(|l| format!(" + Layer {}", l)).unwrap_or_default())).size(12),
                    ]
                    .spacing(2),
                    Space::with_width(Length::Fill),
                    button("Edit")
                        .on_press(Message::EditAutoSwitchRule(idx))
                        .style(iced::theme::Button::Text),
                    button("Delete")
                        .on_press(Message::DeleteAutoSwitchRule(idx))
                        .style(iced::theme::Button::Destructive),
                ]
                .spacing(8)
                .align_items(Alignment::Center);
                list = list.push(row);
            }
            list
        };

        // Edit form (shown when editing or adding)
        let edit_form = if view.editing_rule.is_some() {
            Some(column![
                Space::with_height(20),
                text(if view.editing_rule.unwrap_or(0) < view.rules.len() {
                    "Edit Rule"
                } else {
                    "Add New Rule"
                }).size(16),
                Space::with_height(12),
                row![
                    text("App ID:").size(14),
                    Space::with_width(8),
                    text_input("org.alacritty", &view.new_app_id)
                        .on_input(Message::AutoSwitchAppIdChanged)
                        .padding(8)
                        .size(14),
                    Space::with_width(8),
                    button("Use Current")
                        .on_press(Message::AutoSwitchUseCurrentApp)
                        .style(iced::theme::Button::Secondary),
                ]
                .spacing(4)
                .align_items(Alignment::Center),
                Space::with_height(8),
                row![
                    text("Profile:").size(14),
                    Space::with_width(8),
                    text_input("default", &view.new_profile_name)
                        .on_input(Message::AutoSwitchProfileNameChanged)
                        .padding(8)
                        .size(14),
                ]
                .spacing(4)
                .align_items(Alignment::Center),
                Space::with_height(8),
                row![
                    text("Layer (optional):").size(14),
                    Space::with_width(8),
                    text_input("0", &view.new_layer_id)
                        .on_input(Message::AutoSwitchLayerIdChanged)
                        .padding(8)
                        .size(14),
                ]
                .spacing(4)
                .align_items(Alignment::Center),
                Space::with_height(12),
                row![
                    Space::with_width(Length::Fill),
                    button("Save Rule")
                        .on_press(Message::SaveAutoSwitchRule)
                        .style(iced::theme::Button::Primary),
                ]
                .align_items(Alignment::Center),
            ]
            .spacing(4))
        } else {
            None
        };

        let mut content = column![
            focus_display,
            Space::with_height(20),
            rules_header,
            Space::with_height(12),
            scrollable(rules_list).height(Length::Fixed(200.0)),
        ]
        .spacing(4);

        if let Some(form) = edit_form {
            content = content.push(form);
        }

        container(content)
            .padding(20)
            .width(Length::Fill)
            .style(container_styles::card)
            .into()
    }

    /// View for hotkey bindings configuration
    ///
    /// Displays list of hotkey bindings and controls for adding/editing bindings.
    fn view_hotkey_bindings(&self) -> Element<'_, Message> {
        let view = self.hotkey_view.as_ref().unwrap();

        // Bindings list header
        let bindings_header = row![
            text("Hotkey Bindings").size(18),
            Space::with_width(Length::Fill),
            if view.editing_binding.is_some() {
                button("Cancel")
                    .on_press(Message::EditHotkeyBinding(usize::MAX))
                    .style(iced::theme::Button::Text)
            } else {
                button("Add Binding")
                    .on_press(Message::EditHotkeyBinding(usize::MAX))
                    .style(iced::theme::Button::Primary)
            },
        ]
        .align_items(Alignment::Center);

        // Bindings list
        let bindings_list = if view.bindings.is_empty() {
            column![
                Space::with_height(20),
                text("No bindings configured").size(14).style(iced::theme::Text::Color(iced::Color::from_rgb(0.6, 0.6, 0.6))),
                Space::with_height(8),
                text("Add a binding to switch profiles using keyboard shortcuts").size(12).style(iced::theme::Text::Color(iced::Color::from_rgb(0.5, 0.5, 0.5))),
            ]
            .align_items(Alignment::Center)
        } else {
            let mut list = column![].spacing(8);
            for (idx, binding) in view.bindings.iter().enumerate() {
                let is_editing = view.editing_binding == Some(idx);
                let modifiers_str = binding.modifiers.join("+");
                let indicator: Element<'_, Message> = if is_editing {
                    container(text("")).padding([0, 8]).into()
                } else {
                    Space::with_width(20).into()
                };
                let row = row![
                    indicator,
                    column![
                        text(format!("{}+{}{}", modifiers_str, binding.key, binding.profile_name)).size(14),
                        text(format!("Layer: {}",
                            binding.layer_id.map(|l| l.to_string()).unwrap_or_else(|| "default".to_string()))).size(12),
                    ]
                    .spacing(2),
                    Space::with_width(Length::Fill),
                    button("Edit")
                        .on_press(Message::EditHotkeyBinding(idx))
                        .style(iced::theme::Button::Text),
                    button("Delete")
                        .on_press(Message::DeleteHotkeyBinding(idx))
                        .style(iced::theme::Button::Destructive),
                ]
                .spacing(8)
                .align_items(Alignment::Center);
                list = list.push(row);
            }
            list
        };

        // Edit form (shown when editing or adding)
        let edit_form = if view.editing_binding.is_some() {
            Some(column![
                Space::with_height(20),
                text(if view.editing_binding.unwrap_or(0) < view.bindings.len() {
                    "Edit Binding"
                } else {
                    "Add New Binding"
                }).size(16),
                Space::with_height(12),
                text("Modifiers:").size(14),
                row![
                    self.modifier_checkbox("Ctrl", "ctrl", &view.new_modifiers),
                    self.modifier_checkbox("Alt", "alt", &view.new_modifiers),
                    self.modifier_checkbox("Shift", "shift", &view.new_modifiers),
                    self.modifier_checkbox("Super", "super", &view.new_modifiers),
                ]
                .spacing(8),
                Space::with_height(8),
                row![
                    text("Key:").size(14),
                    Space::with_width(8),
                    text_input("1", &view.new_key)
                        .on_input(Message::HotkeyKeyChanged)
                        .padding(8)
                        .size(14),
                ]
                .spacing(4)
                .align_items(Alignment::Center),
                Space::with_height(8),
                row![
                    text("Profile:").size(14),
                    Space::with_width(8),
                    text_input("default", &view.new_profile_name)
                        .on_input(Message::HotkeyProfileNameChanged)
                        .padding(8)
                        .size(14),
                ]
                .spacing(4)
                .align_items(Alignment::Center),
                Space::with_height(8),
                row![
                    text("Layer (optional):").size(14),
                    Space::with_width(8),
                    text_input("0", &view.new_layer_id)
                        .on_input(Message::HotkeyLayerIdChanged)
                        .padding(8)
                        .size(14),
                ]
                .spacing(4)
                .align_items(Alignment::Center),
                Space::with_height(12),
                row![
                    Space::with_width(Length::Fill),
                    button("Save Binding")
                        .on_press(Message::SaveHotkeyBinding)
                        .style(iced::theme::Button::Primary),
                ]
                .align_items(Alignment::Center),
            ]
            .spacing(4))
        } else {
            None
        };

        let mut content = column![
            bindings_header,
            Space::with_height(12),
            scrollable(bindings_list).height(Length::Fixed(200.0)),
        ]
        .spacing(4);

        if let Some(form) = edit_form {
            content = content.push(form);
        }

        container(content)
            .padding(20)
            .width(Length::Fill)
            .style(container_styles::card)
            .into()
    }

    /// Helper function to create a modifier checkbox
    fn modifier_checkbox<'a>(&'a self, label: &str, modifier: &str, selected: &[String]) -> Element<'a, Message> {
        let is_checked = selected.iter().any(|m| m.to_lowercase() == modifier);
        let btn = if is_checked {
            button(text(format!("[{}] ", label)).size(12))
        } else {
            button(text(format!("[ ] {}", label)).size(12))
        };
        btn.on_press(Message::ToggleHotkeyModifier(modifier.to_string()))
            .style(iced::theme::Button::Text)
            .into()
    }

    /// Format a remap target key name for display
    ///
    /// Converts internal key names like "KEY_A", "BTN_LEFT", etc.
    /// into user-friendly display names like "A", "LMB", etc.
    fn format_remap_target(target: &str) -> String {
        // Handle common key prefixes
        if let Some(rest) = target.strip_prefix("KEY_") {
            // Convert KEY_A -> A, KEY_LEFTCTRL -> LCtrl, etc.
            match rest {
                "LEFTCTRL" => "LCtrl".to_string(),
                "RIGHTCTRL" => "RCtrl".to_string(),
                "LEFTSHIFT" => "LShft".to_string(),
                "RIGHTSHIFT" => "RShft".to_string(),
                "LEFTALT" => "LAlt".to_string(),
                "RIGHTALT" => "RAlt".to_string(),
                "LEFTMETA" => "LMeta".to_string(),
                "RIGHTMETA" => "RMeta".to_string(),
                "SPACE" => "Space".to_string(),
                "TAB" => "Tab".to_string(),
                "ENTER" => "Enter".to_string(),
                "ESC" => "Esc".to_string(),
                "BACKSPACE" => "Bksp".to_string(),
                "DELETE" => "Del".to_string(),
                "INSERT" => "Ins".to_string(),
                "HOME" => "Home".to_string(),
                "END" => "End".to_string(),
                "PAGEUP" => "PgUp".to_string(),
                "PAGEDOWN" => "PgDn".to_string(),
                "UP" => "".to_string(),
                "DOWN" => "".to_string(),
                "LEFT" => "".to_string(),
                "RIGHT" => "".to_string(),
                // Single character keys
                s if s.len() == 1 => s.to_uppercase(),
                // F-keys
                s if s.starts_with('F') => format!("F{}", &s[1..]),
                _ => rest.to_string(),
            }
        } else if let Some(rest) = target.strip_prefix("BTN_") {
            // Mouse buttons
            match rest {
                "LEFT" => "LMB".to_string(),
                "RIGHT" => "RMB".to_string(),
                "MIDDLE" => "Mid".to_string(),
                "SIDE" => "Side".to_string(),
                "EXTRA" => "Extra".to_string(),
                "FORWARD" => "Fwd".to_string(),
                "BACK" => "Back".to_string(),
                _ => rest.to_string(),
            }
        } else if let Some(rest) = target.strip_prefix("REL_") {
            // Relative axes (wheel)
            match rest {
                "WHEEL" => "Wheel".to_string(),
                "HWHEEL" => "HWheel".to_string(),
                _ => rest.to_string(),
            }
        } else {
            // Return as-is for unknown formats (truncate if too long)
            if target.len() > 6 {
                format!("{}...", &target[..6])
            } else {
                target.to_string()
            }
        }
    }

    /// View for Azeron keypad remapping interface
    ///
    /// Displays a visual representation of the Azeron Cyborg keypad with
    /// clickable buttons for remapping configuration.
    /// Shows the current mapping for each button in a clean, readable format.
    ///
    /// Format: Unmapped buttons show the button label (1, 2, Q, W, etc.).
    /// Mapped buttons show the original label small at top, mapped key below.
    fn view_azeron_keypad(&self) -> Element<'_, Message> {
        let layout = azeron_keypad_layout();

        // Create grid of buttons organized by row
        let mut rows: Vec<Vec<Element<'_, Message>>> = Vec::with_capacity(10);
        for _ in 0..10 {
            rows.push(Vec::new());
        }

        for keypad_button in &layout {
            let button_id = keypad_button.id.clone();
            let label = keypad_button.label.clone();
            let remap = keypad_button.current_remap.clone();
            let is_selected = self.selected_button == Some(
                layout.iter().position(|b| b.id == keypad_button.id).unwrap_or(usize::MAX)
            );

            // Button styling based on remap state and selection
            let button_style = if is_selected {
                iced::theme::Button::Primary
            } else if remap.is_some() {
                iced::theme::Button::Secondary
            } else {
                iced::theme::Button::Text
            };

            // Format the button content to show mapping clearly
            // If remapped, show the mapped key name prominently
            let button_content: Element<'_, Message> = if let Some(ref target) = remap {
                // Parse the target to get a readable key name
                let display_name = Self::format_remap_target(target);
                // Create a column with original label small on top, mapped key below
                container(
                    column![
                        text(label).size(8).style(iced::theme::Text::Color(iced::Color::from_rgb(0.5, 0.5, 0.5))),
                        text(display_name).size(11).width(Length::Fixed(45.0)),
                    ]
                    .spacing(2)
                    .align_items(Alignment::Center)
                )
                .center_x()
                .center_y()
                .into()
            } else {
                // Unmapped button - show the label centered
                container(text(label).size(12))
                    .center_x()
                    .center_y()
                    .into()
            };

            let btn = button(button_content)
                .on_press(Message::SelectKeypadButton(button_id.clone()))
                .style(button_style)
                .padding([6, 8])
                .width(iced::Length::Fixed(54.0))
                .height(iced::Length::Fixed(54.0))
                .into();

            if rows.get_mut(keypad_button.row).is_some() {
                rows[keypad_button.row].push(btn);
            }
        }

        // Add hat switch indicator in center
        let hat_switch = container(
            text("HAT\n").size(10)
        )
        .width(iced::Length::Fixed(54.0))
        .height(iced::Length::Fixed(54.0))
        .center_x()
        .center_y()
        .style(container_styles::card)
        .into();

        // Insert hat switch at center position (row 5, col 2)
        if rows.get_mut(5).is_some() {
            rows[5].push(hat_switch);
        }

        // Build the keypad layout
        let keypad_rows: Vec<Element<'_, Message>> = rows
            .into_iter()
            .filter(|r| !r.is_empty())
            .map(|row_elements| row(row_elements).spacing(4).align_items(Alignment::Center).into())
            .collect();

        let keypad_content = column![
            text("Azeron Keypad Layout").size(20),
            Space::with_height(10),
            text("Click a button to configure remapping").size(12),
            Space::with_height(20),
        ]
        .spacing(10)
        .align_items(Alignment::Center)
        .push(column(keypad_rows).spacing(4).align_items(Alignment::Center));

        container(keypad_content)
            .padding(24)
            .width(Length::Fill)
            .center_x()
            .into()
    }

    fn view_status_bar(&self) -> Element<'_, Message> {
        let connection_indicator = if self.daemon_connected {
            text("● Connected").size(12)
        } else {
            text("○ Disconnected").size(12)
        };

        let latest_notification = if let Some(notif) = self.notifications.back() {
            if notif.is_error {
                text(&notif.message).size(12)
            } else {
                text(&notif.message).size(12)
            }
        } else {
            text("Ready").size(12)
        };

        container(
            row![
                connection_indicator,
                text(" | ").size(12),
                latest_notification,
                Space::with_width(Length::Fill),
                text(format!("{} macros", self.macros.len())).size(12),
            ]
            .spacing(5)
            .align_items(Alignment::Center)
        )
        .padding([8, 16])
        .width(Length::Fill)
        .into()
    }

    /// View layer indicator for a device
    ///
    /// Displays the active layer name/ID for the given device.
    /// Shows "Layer N: {name}" format with Primary style for visibility.
    fn layer_indicator(&self, device_id: &str) -> Element<'_, Message> {
        if let Some(&layer_id) = self.active_layers.get(device_id) {
            // Get layer name from configs if available
            let layer_name = self.layer_configs
                .get(device_id)
                .and_then(|layers| layers.iter().find(|l| l.layer_id == layer_id))
                .map(|l| l.name.as_str())
                .unwrap_or("Unknown");

            container(
                text(format!("Layer {}: {}", layer_id, layer_name))
                    .size(12)
            )
            .padding([4, 8])
            .style(container_styles::card)
            .into()
        } else {
            // No active layer - show default base layer
            container(
                text("Layer 0: Base").size(12)
            )
            .padding([4, 8])
            .style(container_styles::card)
            .into()
        }
    }

    /// View profile quick toggle buttons for a device
    ///
    /// Shows horizontal row of toggle buttons for each available remap profile.
    /// Highlights the active profile with Primary style.
    /// Similar to the official Azeron software's profile toggle interface.
    fn profile_quick_toggles(&self, device_path: &str) -> Element<'_, Message> {
        let profiles = self.remap_profiles.get(device_path);
        let active_profile = self.active_remap_profiles.get(device_path);

        if let Some(profile_list) = profiles {
            if profile_list.is_empty() {
                return row![].into(); // Empty row when no profiles
            }

            let buttons: Vec<Element<'_, Message>> = profile_list
                .iter()
                .map(|profile| {
                    let is_active = active_profile.as_ref().map(|s| s.as_str()) == Some(profile.name.as_str());
                    let button_style = if is_active {
                        iced::theme::Button::Primary
                    } else {
                        iced::theme::Button::Secondary
                    };

                    button(
                        text(&profile.name).size(11)
                    )
                    .on_press(Message::ActivateRemapProfile(device_path.to_string(), profile.name.clone()))
                    .style(button_style)
                    .padding([6, 10])
                    .into()
                })
                .collect();

            // If there's an active profile, add a deactivate button at the end
            let mut final_buttons = buttons;
            if active_profile.is_some() {
                final_buttons.push(
                    button(
                        text("Off").size(11)
                    )
                    .on_press(Message::DeactivateRemapProfile(device_path.to_string()))
                    .style(iced::theme::Button::Text)
                    .padding([6, 10])
                    .into()
                );
            }

            row(final_buttons).spacing(6).into()
        } else {
            row![].into() // Empty row when profiles not loaded
        }
    }

    /// View layer activation buttons for a device
    ///
    /// Shows buttons for each toggle layer available for the device.
    /// Highlights active toggle layers with Secondary style.
    fn layer_activation_buttons(&self, device_id: &str) -> Element<'_, Message> {
        let layers = self.layer_configs.get(device_id);

        if let Some(layer_list) = layers {
            // Filter for toggle layers only
            let toggle_layers: Vec<_> = layer_list
                .iter()
                .filter(|l| l.mode == LayerMode::Toggle && l.layer_id > 0)
                .collect();

            if toggle_layers.is_empty() {
                return text("No toggle layers configured").size(11).into();
            }

            let active_layer_id = self.active_layers.get(device_id).copied().unwrap_or(0);

            let buttons: Vec<Element<'_, Message>> = toggle_layers
                .iter()
                .map(|layer| {
                    let is_active = active_layer_id == layer.layer_id;
                    let button_style = if is_active {
                        iced::theme::Button::Secondary
                    } else {
                        iced::theme::Button::Text
                    };

                    button(
                        text(format!("L{}", layer.layer_id)).size(11)
                    )
                    .on_press(Message::LayerActivateRequested(
                        device_id.to_string(),
                        layer.layer_id,
                        LayerMode::Toggle,
                    ))
                    .style(button_style)
                    .padding([4, 8])
                    .into()
                })
                .collect();

            row(buttons).spacing(4).into()
        } else {
            text("Load layers to see toggle buttons").size(11).into()
        }
    }

    /// Deadzone quick-select buttons
    ///
    /// Provides buttons for common deadzone percentages.
    fn deadzone_buttons(&self, device_id: &str, is_y_axis: bool, current: u8) -> Element<'_, Message> {
        let percentages = [0, 10, 20, 30, 40, 50];
        let buttons: Vec<Element<'_, Message>> = percentages
            .iter()
            .map(|&pct| {
                let is_current = current == pct;
                button(text(format!("{}%", pct)).size(10))
                    .on_press(if is_y_axis {
                        Message::SetAnalogDeadzoneXY(device_id.to_string(), current, pct)
                    } else {
                        Message::SetAnalogDeadzoneXY(device_id.to_string(), pct, current)
                    })
                    .style(if is_current {
                        iced::theme::Button::Primary
                    } else {
                        iced::theme::Button::Text
                    })
                    .padding([2, 6])
                    .into()
            })
            .collect();

        row(buttons).spacing(2).into()
    }

    /// Outer deadzone quick-select buttons
    ///
    /// Provides buttons for common outer deadzone percentages.
    fn outer_deadzone_buttons(&self, device_id: &str, is_y_axis: bool, current: u8) -> Element<'_, Message> {
        let percentages = [80, 85, 90, 95, 100];
        let buttons: Vec<Element<'_, Message>> = percentages
            .iter()
            .map(|&pct| {
                let is_current = current == pct;
                button(text(format!("{}%", pct)).size(10))
                    .on_press(if is_y_axis {
                        Message::SetAnalogOuterDeadzoneXY(device_id.to_string(), current, pct)
                    } else {
                        Message::SetAnalogOuterDeadzoneXY(device_id.to_string(), pct, current)
                    })
                    .style(if is_current {
                        iced::theme::Button::Primary
                    } else {
                        iced::theme::Button::Text
                    })
                    .padding([2, 6])
                    .into()
            })
            .collect();

        row(buttons).spacing(2).into()
    }

    /// View layer settings for a device
    ///
    /// Displays a table/list of all layers for the device with edit buttons.
    fn layer_settings_view(&self, device_id: &str) -> Element<'_, Message> {
        let layers = self.layer_configs.get(device_id);

        if let Some(layer_list) = layers {
            if layer_list.is_empty() {
                return column![
                    text("No layers configured").size(14),
                    text("Default base layer will be created automatically").size(11),
                ]
                .spacing(4)
                .into();
            }

            let mut rows: Vec<Element<'_, Message>> = layer_list
                .iter()
                .map(|layer| {
                    let mode_text = match layer.mode {
                        LayerMode::Hold => "Hold",
                        LayerMode::Toggle => "Toggle",
                    };

                    row![
                        text(format!("L{}", layer.layer_id)).size(12).width(Length::Fixed(30.0)),
                        text(&layer.name).size(12).width(Length::Fixed(100.0)),
                        text(mode_text).size(12).width(Length::Fixed(60.0)),
                        text(format!("{} remaps", layer.remap_count)).size(11),
                        Space::with_width(Length::Fill),
                        button(text("Edit").size(11))
                            .on_press(Message::OpenLayerConfigDialog(device_id.to_string(), layer.layer_id))
                            .style(iced::theme::Button::Text)
                            .padding([4, 8]),
                    ]
                    .spacing(8)
                    .align_items(Alignment::Center)
                    .into()
                })
                .collect();

            // Add "Add Layer" button if less than 8 layers
            let add_button = if layer_list.len() < 8 {
                Some(
                    button(
                        row![
                            text("+").size(14),
                            text("Add Layer").size(12),
                        ]
                        .spacing(4)
                    )
                    .on_press(Message::OpenLayerConfigDialog(
                        device_id.to_string(),
                        layer_list.len(),
                    ))
                    .style(iced::theme::Button::Secondary)
                    .padding([6, 12])
                    .into()
                )
            } else {
                None
            };

            if let Some(btn) = add_button {
                rows.push(btn);
            }

            column(rows).spacing(8).into()
        } else {
            column![
                text("Load layers to see settings").size(12),
                button("Load Layers")
                    .on_press(Message::LayerConfigRequested(device_id.to_string()))
                    .style(iced::theme::Button::Secondary),
            ]
            .spacing(8)
            .into()
        }
    }

    /// View layer configuration dialog
    ///
    /// Modal dialog for editing layer name and mode.
    fn layer_config_dialog(&self) -> Option<Element<'_, Message>> {
        if let Some((_device_id, layer_id, name, mode)) = &self.layer_config_dialog {
            let mode_options = vec!["Hold".to_string(), "Toggle".to_string()];
            let current_mode_str = match mode {
                LayerMode::Hold => "Hold",
                LayerMode::Toggle => "Toggle",
            };

            let dialog = container(
                column![
                    text(format!("Configure Layer {}", layer_id)).size(18),
                    Space::with_height(20),
                    text("Layer Name:").size(12),
                    text_input("Enter layer name...", name)
                        .on_input(Message::LayerConfigNameChanged)
                        .padding(8)
                        .size(14)
                        .width(Length::Fixed(250.0)),
                    Space::with_height(12),
                    text("Activation Mode:").size(12),
                    pick_list(mode_options, Some(current_mode_str.to_string()), |selected| {
                        let new_mode = match selected.as_str() {
                            "Toggle" => LayerMode::Toggle,
                            _ => LayerMode::Hold,
                        };
                        Message::LayerConfigModeChanged(new_mode)
                    })
                    .width(Length::Fixed(250.0))
                    .padding(8),
                    Space::with_height(20),
                    row![
                        button("Cancel")
                            .on_press(Message::CancelLayerConfig)
                            .style(iced::theme::Button::Text)
                            .padding([8, 16]),
                        Space::with_width(Length::Fill),
                        button("Save")
                            .on_press(Message::SaveLayerConfig)
                            .style(iced::theme::Button::Primary)
                            .padding([8, 16]),
                    ]
                    .spacing(8),
                ]
                .spacing(4)
            )
            .padding(24)
            .width(Length::Fixed(300.0))
            .style(container_styles::card);

            // Overlay dialog on semi-transparent background
            Some(
                container(
                    container(dialog)
                        .width(Length::Fill)
                        .center_x()
                        .center_y()
                )
                .width(Length::Fill)
                .height(Length::Fill)
                .style(iced::theme::Container::Transparent)
                .into()
            )
        } else {
            None
        }
    }

    /// Get current color for a zone, with default fallback
    fn get_zone_color(&self, zone: LedZone) -> (u8, u8, u8) {
        if let Some(device_id) = &self.led_config_device {
            if let Some(led_state) = self.led_states.get(device_id) {
                if let Some(&color) = led_state.zone_colors.get(&zone) {
                    return color;
                }
            }
        }
        // Default to white if not set
        (255, 255, 255)
    }

    /// View LED RGB sliders for color adjustment
    fn view_led_rgb_sliders(&self) -> Element<'_, Message> {
        let zone = self.selected_led_zone.unwrap_or(LedZone::Logo);
        let (r, g, b) = self.pending_led_color.unwrap_or_else(|| self.get_zone_color(zone));

        Column::new()
            .spacing(8)
            .push(
                row![
                    text("Red:").size(12).width(Length::Fixed(40.0)),
                    text(format!("{}", r)).size(12).width(Length::Fixed(30.0)),
                    slider(0..=255, r, move |v| {
                        let (_, g, b) = (v as u8, g, b);
                        Message::LedSliderChanged(v as u8, g, b)
                    })
                    .width(Length::Fill)
                ]
                .spacing(8)
                .align_items(Alignment::Center)
            )
            .push(
                row![
                    text("Green:").size(12).width(Length::Fixed(40.0)),
                    text(format!("{}", g)).size(12).width(Length::Fixed(30.0)),
                    slider(0..=255, g, move |v| {
                        let (r, _, b) = (r, v as u8, b);
                        Message::LedSliderChanged(r, v as u8, b)
                    })
                    .width(Length::Fill)
                ]
                .spacing(8)
                .align_items(Alignment::Center)
            )
            .push(
                row![
                    text("Blue:").size(12).width(Length::Fixed(40.0)),
                    text(format!("{}", b)).size(12).width(Length::Fixed(30.0)),
                    slider(0..=255, b, move |v| {
                        let (r, g, _) = (r, g, v as u8);
                        Message::LedSliderChanged(r, g, v as u8)
                    })
                    .width(Length::Fill)
                ]
                .spacing(8)
                .align_items(Alignment::Center)
            )
            .into()
    }

    /// Get color style for LED preview container
    fn led_color_style(zone: Option<LedZone>, zone_colors: &std::collections::HashMap<LedZone, (u8, u8, u8)>) -> iced::theme::Container {
        let (r, g, b) = zone
            .and_then(|z| zone_colors.get(&z))
            .copied()
            .unwrap_or((255, 255, 255));

        struct LedColorStyle {
            r: u8,
            g: u8,
            b: u8,
        }

        impl iced::widget::container::StyleSheet for LedColorStyle {
            type Style = Theme;

            fn appearance(&self, _style: &Self::Style) -> iced::widget::container::Appearance {
                iced::widget::container::Appearance {
                    background: Some(Color::from_rgb8(self.r, self.g, self.b).into()),
                    ..Default::default()
                }
            }
        }

        iced::theme::Container::Custom(Box::new(LedColorStyle { r, g, b }))
    }

    /// View LED configuration dialog
    ///
    /// Displays modal dialog for LED configuration with zone selection,
    /// RGB sliders, brightness control, and pattern selection.
    pub fn view_led_config(&self) -> Option<Element<'_, Message>> {
        if let Some(ref device_id) = self.led_config_device {
            let selected_zone = self.selected_led_zone.unwrap_or(LedZone::Logo);
            let led_state = self.led_states.get(device_id);
            let zone_colors = led_state.map(|s| &s.zone_colors);
            let current_color = self.get_zone_color(selected_zone);

            // Zone buttons
            let zones = vec![
                (LedZone::Logo, "Logo"),
                (LedZone::Keys, "Keys"),
                (LedZone::Thumbstick, "Thumbstick"),
            ];

            let zone_buttons: Vec<Element<'_, Message>> = zones
                .into_iter()
                .map(|(zone, label)| {
                    let is_selected = self.selected_led_zone == Some(zone);
                    button(text(label).size(12))
                        .on_press(Message::SelectLedZone(zone))
                        .style(if is_selected {
                            iced::theme::Button::Primary
                        } else {
                            iced::theme::Button::Secondary
                        })
                        .padding([6, 12])
                        .into()
                })
                .collect();

            // Color preview
            let preview = container(
                container(
                    text(format!("RGB({}, {}, {})", current_color.0, current_color.1, current_color.2))
                        .size(11)
                        .horizontal_alignment(iced::alignment::Horizontal::Center)
                )
                .width(Length::Fill)
                .height(Length::Fill)
                .align_x(iced::alignment::Horizontal::Center)
                .align_y(iced::alignment::Vertical::Center)
            )
            .width(Length::Fixed(120.0))
            .height(Length::Fixed(60.0))
            .style(if let Some(colors) = zone_colors {
                Self::led_color_style(self.selected_led_zone, colors)
            } else {
                iced::theme::Container::Transparent
            });

            // Pattern buttons
            let patterns = vec![
                (LedPattern::Static, "Static"),
                (LedPattern::Breathing, "Breathing"),
                (LedPattern::Rainbow, "Rainbow"),
            ];

            let current_pattern = led_state.map(|s| s.active_pattern).unwrap_or(LedPattern::Static);

            let pattern_buttons: Vec<Element<'_, Message>> = patterns
                .into_iter()
                .map(|(pattern, label)| {
                    let is_active = current_pattern == pattern;
                    button(text(label).size(11))
                        .on_press(Message::SetLedPattern(device_id.clone(), pattern))
                        .style(if is_active {
                            iced::theme::Button::Primary
                        } else {
                            iced::theme::Button::Secondary
                        })
                        .padding([4, 10])
                        .into()
                })
                .collect();

            let brightness = led_state.map(|s| s.global_brightness as f32).unwrap_or(100.0);

            let dialog = container(
                column![
                    // Header
                    row![
                        text("LED Configuration").size(18),
                        Space::with_width(Length::Fill),
                        button(text("×").size(20))
                            .on_press(Message::CloseLedConfig)
                            .style(iced::theme::Button::Text)
                            .padding([0, 8])
                    ]
                    .spacing(8)
                    .align_items(Alignment::Center),

                    horizontal_rule(1),

                    // Device ID
                    text(device_id).size(11).width(Length::Fill),

                    // Zone selection
                    text("Zone:").size(13),
                    row(zone_buttons).spacing(8),

                    horizontal_rule(1),

                    // Color preview
                    text("Color:").size(13),
                    row![
                        preview,
                        column![
                            text("Adjust RGB sliders below").size(11),
                            text("to change color").size(11),
                        ]
                        .spacing(4)
                    ]
                    .spacing(12)
                    .align_items(Alignment::Center),

                    // RGB sliders
                    self.view_led_rgb_sliders(),

                    horizontal_rule(1),

                    // Brightness control
                    text(format!("Brightness: {}%", brightness as u8)).size(13),
                    slider(0.0..=100.0, brightness, move |v| {
                        Message::SetLedBrightness(device_id.clone(), None, v as u8)
                    })
                    .width(Length::Fill),

                    horizontal_rule(1),

                    // Pattern selection
                    text("Pattern:").size(13),
                    row(pattern_buttons).spacing(8),

                    horizontal_rule(1),

                    // Close button
                    row![
                        Space::with_width(Length::Fill),
                        button(text("Close").size(13))
                            .on_press(Message::CloseLedConfig)
                            .style(iced::theme::Button::Secondary)
                            .padding([6, 16])
                    ]
                    .spacing(8)
                ]
                .spacing(12)
                .padding(20)
            )
            .max_width(500)
            .style(container_styles::card);

            // Modal overlay
            Some(
                container(dialog)
                    .width(Length::Fill)
                    .height(Length::Fill)
                    .align_x(iced::alignment::Horizontal::Center)
                    .align_y(iced::alignment::Vertical::Center)
                    .padding(40)
                    .style(iced::theme::Container::Transparent)
                    .into(),
            )
        } else {
            None
        }
    }

    /// View analog calibration dialog
    ///
    /// Displays modal dialog for analog stick calibration with deadzone,
    /// sensitivity, range, and inversion controls.
    pub fn view_analog_calibration(&self) -> Option<Element<'_, Message>> {
        if let Some(ref view) = self.analog_calibration_view {
            let dialog = container(view.view())
                .max_width(600)
                .max_height(800)
                .style(container_styles::card);

            // Modal overlay
            Some(
                container(dialog)
                    .width(Length::Fill)
                    .height(Length::Fill)
                    .align_x(iced::alignment::Horizontal::Center)
                    .align_y(iced::alignment::Vertical::Center)
                    .padding(40)
                    .style(iced::theme::Container::Transparent)
                    .into(),
            )
        } else {
            None
        }
    }
}

impl AnalogCalibrationView {
    fn checkbox_button<'a>(&'a self, label: &str, is_checked: bool, msg: fn(bool) -> Message) -> Element<'a, Message> {
        let btn = if is_checked {
            button(text(format!("[X] {}", label)).size(14))
        } else {
            button(text(format!("[ ] {}", label)).size(14))
        };
        btn.on_press(msg(is_checked))
            .style(iced::theme::Button::Text)
            .into()
    }

    pub fn view(&self) -> Element<Message> {
        use iced::widget::{horizontal_rule as rule, Row, Column, container, Canvas};

        let title = text("Analog Calibration").size(24);

        // Device and layer info
        let info = Column::new()
            .spacing(5)
            .push(text(format!("Device: {}", self.device_id)).size(14))
            .push(text(format!("Layer: {}", self.layer_id)).size(14));

        // Visualizer section
        let visualizer_section = Column::new()
            .spacing(10)
            .push(text("Stick Position").size(18))
            .push(
                container(
                    Canvas::new(AnalogVisualizer {
                        stick_x: self.stick_x,
                        stick_y: self.stick_y,
                        deadzone: self.calibration.deadzone,
                        deadzone_shape: match self.deadzone_shape_selected {
                            DeadzoneShape::Circular => WidgetDeadzoneShape::Circular,
                            DeadzoneShape::Square => WidgetDeadzoneShape::Square,
                        },
                        range_min: self.calibration.range_min,
                        range_max: self.calibration.range_max,
                        cache: Arc::clone(&self.visualizer_cache),
                    })
                    .width(Length::Fixed(250.0))
                    .height(Length::Fixed(250.0))
                )
                .width(Length::Fixed(270.0))
                .height(Length::Fixed(270.0))
                .center_x()
                .center_y()
            );

        // Mode section
        let mode_section = Column::new()
            .spacing(10)
            .push(text("Output Mode").size(18))
            .push(
                Row::new()
                    .spacing(10)
                    .push(text("Mode:"))
                    .push(pick_list(
                        &AnalogMode::ALL[..],
                        Some(self.analog_mode_selected),
                        Message::AnalogModeChanged,
                    ))
            );

        // Add camera sub-mode selector if camera mode is selected
        let mode_section = if self.analog_mode_selected == AnalogMode::Camera {
            mode_section.push(
                Row::new()
                    .spacing(10)
                    .push(text("Camera:"))
                    .push(pick_list(
                        &CameraOutputMode::ALL[..],
                        Some(self.camera_mode_selected),
                        Message::CameraModeChanged,
                    ))
            )
        } else {
            mode_section
        };

        // Deadzone section
        let deadzone_section = Column::new()
            .spacing(10)
            .push(text("Deadzone").size(18))
            .push(
                Row::new()
                    .spacing(10)
                    .push(text("Size:"))
                    .push(text(format!("{:.0}%", self.calibration.deadzone * 100.0)))
                    .push(slider(0.0..=1.0, self.calibration.deadzone, Message::AnalogDeadzoneChanged).step(0.01))
            )
            .push(
                Row::new()
                    .spacing(10)
                    .push(text("Shape:"))
                    .push(pick_list(
                        &DeadzoneShape::ALL[..],
                        Some(self.deadzone_shape_selected),
                        Message::AnalogDeadzoneShapeChanged,
                    ))
            );

        // Sensitivity section
        let sensitivity_section = Column::new()
            .spacing(10)
            .push(text("Sensitivity").size(18))
            .push(
                Row::new()
                    .spacing(10)
                    .push(text("Multiplier:"))
                    .push(text(format!("{:.1}", self.calibration.sensitivity_multiplier)))
                    .push(slider(0.1..=5.0, self.calibration.sensitivity_multiplier, Message::AnalogSensitivityChanged).step(0.1))
            )
            .push(
                Row::new()
                    .spacing(10)
                    .push(text("Curve:"))
                    .push(pick_list(
                        &SensitivityCurve::ALL[..],
                        Some(self.sensitivity_curve_selected),
                        Message::AnalogSensitivityCurveChanged,
                    ))
            )
            .push(text(format!("Curve: {}", self.sensitivity_curve_selected)).size(14))
            .push(
                container(
                    Canvas::new(CurveGraph {
                        curve: self.sensitivity_curve_selected,
                        multiplier: self.calibration.sensitivity_multiplier,
                    })
                    .width(Length::Fixed(300.0))
                    .height(Length::Fixed(200.0))
                )
                .width(Length::Fixed(320.0))
                .center_x()
            );

        // Range section
        let range_section = Column::new()
            .spacing(10)
            .push(text("Output Range").size(18))
            .push(
                Row::new()
                    .spacing(10)
                    .push(text("Min:"))
                    .push(text(self.calibration.range_min.to_string()))
                    .push(slider(-32768..=0, self.calibration.range_min, Message::AnalogRangeMinChanged))
            )
            .push(
                Row::new()
                    .spacing(10)
                    .push(text("Max:"))
                    .push(text(self.calibration.range_max.to_string()))
                    .push(slider(0..=32767, self.calibration.range_max, Message::AnalogRangeMaxChanged))
            );

        // Inversion section
        let inversion_section = Column::new()
            .spacing(10)
            .push(text("Axis Inversion").size(18))
            .push(
                Row::new()
                    .spacing(20)
                    .push(self.checkbox_button("Invert X", self.invert_x_checked, Message::AnalogInvertXToggled))
                    .push(self.checkbox_button("Invert Y", self.invert_y_checked, Message::AnalogInvertYToggled))
            );

        // Apply and Close buttons
        let buttons = Row::new()
            .spacing(10)
            .push(
                button("Apply")
                    .on_press(Message::ApplyAnalogCalibration)
            )
            .push(
                button("Close")
                    .on_press(Message::CloseAnalogCalibration)
                    .style(iced::theme::Button::Secondary)
            );

        // Error display
        let content = if let Some(error) = &self.error {
            Column::new()
                .spacing(20)
                .push(title)
                .push(info)
                .push(rule(1))
                .push(text(format!("Error: {}", error)).style(Color::from_rgb(1.0, 0.4, 0.4)))
                .push(buttons)
        } else {
            Column::new()
                .spacing(20)
                .push(title)
                .push(info)
                .push(rule(1))
                .push(visualizer_section)
                .push(rule(1))
                .push(mode_section)
                .push(rule(1))
                .push(deadzone_section)
                .push(rule(1))
                .push(sensitivity_section)
                .push(rule(1))
                .push(range_section)
                .push(rule(1))
                .push(inversion_section)
                .push(rule(1))
                .push(buttons)
        };

        scrollable(content).height(Length::Fill).into()
    }
}

#[cfg(test)]
mod calibration_tests {
    use super::*;
    use aethermap_common::{AnalogMode, CameraOutputMode};

    #[test]
    fn test_analog_calibration_view_default() {
        let view = AnalogCalibrationView::default();

        assert_eq!(view.device_id, "");
        assert_eq!(view.layer_id, 0);
        assert_eq!(view.calibration.deadzone, 0.15);
        assert_eq!(view.stick_x, 0.0);
        assert_eq!(view.stick_y, 0.0);
        assert_eq!(view.loading, false);
        assert!(view.error.is_none());
    }

    #[test]
    fn test_analog_calibration_view_with_values() {
        let view = AnalogCalibrationView {
            device_id: "test_device".to_string(),
            layer_id: 1,
            calibration: CalibrationConfig {
                deadzone: 0.2,
                deadzone_shape: "circular".to_string(),
                sensitivity: "quadratic".to_string(),
                sensitivity_multiplier: 1.5,
                range_min: -16384,
                range_max: 16383,
                invert_x: true,
                invert_y: false,
                exponent: 2.0,
            },
            deadzone_shape_selected: DeadzoneShape::Square,
            sensitivity_curve_selected: SensitivityCurve::Quadratic,
            analog_mode_selected: AnalogMode::Mouse,
            camera_mode_selected: CameraOutputMode::Keys,
            invert_x_checked: true,
            invert_y_checked: false,
            stick_x: 0.5,
            stick_y: -0.3,
            loading: false,
            error: None,
            last_visualizer_update: Instant::now(),
            visualizer_cache: Arc::new(iced::widget::canvas::Cache::default()),
        };

        assert_eq!(view.device_id, "test_device");
        assert_eq!(view.layer_id, 1);
        assert_eq!(view.calibration.deadzone, 0.2);
        assert_eq!(view.stick_x, 0.5);
        assert_eq!(view.stick_y, -0.3);
        assert_eq!(view.analog_mode_selected, AnalogMode::Mouse);
        assert_eq!(view.camera_mode_selected, CameraOutputMode::Keys);
        assert_eq!(view.invert_x_checked, true);
        assert_eq!(view.invert_y_checked, false);
    }

    #[test]
    fn test_calibration_config_default() {
        let config = CalibrationConfig::default();

        assert_eq!(config.deadzone, 0.15);
        assert_eq!(config.deadzone_shape, "circular");
        assert_eq!(config.sensitivity, "linear");
        assert_eq!(config.sensitivity_multiplier, 1.0);
        assert_eq!(config.range_min, -32768);
        assert_eq!(config.range_max, 32767);
        assert_eq!(config.invert_x, false);
        assert_eq!(config.invert_y, false);
        assert_eq!(config.exponent, 2.0);
    }

    #[test]
    fn test_deadzone_shape_display() {
        assert_eq!(DeadzoneShape::Circular.to_string(), "Circular");
        assert_eq!(DeadzoneShape::Square.to_string(), "Square");
    }

    #[test]
    fn test_sensitivity_curve_display() {
        assert_eq!(SensitivityCurve::Linear.to_string(), "Linear");
        assert_eq!(SensitivityCurve::Quadratic.to_string(), "Quadratic");
        assert_eq!(SensitivityCurve::Exponential.to_string(), "Exponential");
    }

    #[test]
    fn test_deadzone_shape_default() {
        assert_eq!(DeadzoneShape::default(), DeadzoneShape::Circular);
    }

    #[test]
    fn test_sensitivity_curve_default() {
        assert_eq!(SensitivityCurve::default(), SensitivityCurve::Linear);
    }

    #[test]
    fn test_analog_calibration_view_clone() {
        let view = AnalogCalibrationView {
            device_id: "test_device".to_string(),
            layer_id: 1,
            calibration: CalibrationConfig {
                deadzone: 0.2,
                ..Default::default()
            },
            ..Default::default()
        };

        let cloned = view.clone();
        assert_eq!(cloned.device_id, "test_device");
        assert_eq!(cloned.layer_id, 1);
        assert_eq!(cloned.calibration.deadzone, 0.2);
        // Clone resets last_visualizer_update to Instant::now()
        assert!(cloned.last_visualizer_update.elapsed() < Duration::from_secs(1));
    }

    #[test]
    fn test_throttling_threshold() {
        // Verify the 30 FPS throttling threshold (33ms)
        let view = AnalogCalibrationView {
            device_id: "test".to_string(),
            layer_id: 0,
            calibration: CalibrationConfig::default(),
            deadzone_shape_selected: DeadzoneShape::Circular,
            sensitivity_curve_selected: SensitivityCurve::Linear,
            analog_mode_selected: AnalogMode::Disabled,
            camera_mode_selected: CameraOutputMode::Scroll,
            invert_x_checked: false,
            invert_y_checked: false,
            stick_x: 0.0,
            stick_y: 0.0,
            loading: false,
            error: None,
            last_visualizer_update: Instant::now(),
            visualizer_cache: Arc::new(iced::widget::canvas::Cache::default()),
        };

        // Immediately after update, elapsed time should be small
        assert!(view.last_visualizer_update.elapsed() < Duration::from_millis(33));

        // After 40ms, should definitely exceed the threshold
        std::thread::sleep(Duration::from_millis(40));
        assert!(view.last_visualizer_update.elapsed() >= Duration::from_millis(33));
    }

    #[test]
    fn test_visualizer_cache_arc_sharing() {
        // Verify that Arc<Cache> can be cloned and shared
        let cache = Arc::new(iced::widget::canvas::Cache::default());
        let cache_clone = Arc::clone(&cache);

        // Both Arcs point to the same Cache
        assert!(Arc::ptr_eq(&cache, &cache_clone));
    }

    #[test]
    fn test_analog_mode_selection_states() {
        // Test that all analog modes can be selected
        let modes = [
            AnalogMode::Disabled,
            AnalogMode::Dpad,
            AnalogMode::Gamepad,
            AnalogMode::Camera,
            AnalogMode::Mouse,
            AnalogMode::Wasd,
        ];

        for mode in modes {
            let view = AnalogCalibrationView {
                analog_mode_selected: mode,
                ..Default::default()
            };
            assert_eq!(view.analog_mode_selected, mode);
        }
    }

    #[test]
    fn test_camera_mode_selection_states() {
        // Test that all camera output modes can be selected
        let modes = [CameraOutputMode::Scroll, CameraOutputMode::Keys];

        for mode in modes {
            let view = AnalogCalibrationView {
                camera_mode_selected: mode,
                ..Default::default()
            };
            assert_eq!(view.camera_mode_selected, mode);
        }
    }
}