ftui-core 0.7.0

Terminal lifecycle, capabilities, and event parsing for FrankenTUI.
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
#![forbid(unsafe_code)]

//! Keybinding sequence detection and action mapping.
//!
//! This module implements the keybinding policy specification (bd-2vne.1) for
//! detecting multi-key sequences like Esc Esc and mapping keys to actions based
//! on application state.
//!
//! # Key Concepts
//!
//! - **SequenceDetector**: State machine that detects Esc Esc sequences with
//!   configurable timeout. Single Esc is emitted after timeout or when another
//!   key is pressed.
//!
//! - **SequenceConfig**: Configuration for sequence detection including timeout
//!   windows and debounce settings.
//!
//! - **ActionMapper**: Maps key events to high-level actions based on application
//!   state (input buffer, running tasks, modals, overlays). Integrates with
//!   SequenceDetector to handle Esc sequences.
//!
//! - **AppState**: Runtime state flags that affect action resolution.
//!
//! - **Action**: High-level commands like ClearInput, CancelTask, ToggleTreeView.
//!
//! # State Machine
//!
//! ```text
//!                                     ┌─────────────────────────────────────┐
//!                                     │                                     │
//!                                     ▼                                     │
//! ┌──────────┐   Esc   ┌────────────────────┐  timeout    ┌─────────┐      │
//! │  Idle    │───────▶│  AwaitingSecondEsc  │────────────▶│ Emit(Esc)│      │
//! └──────────┘         └────────────────────┘              └─────────┘      │
//!      ▲                        │                                           │
//!      │                        │ Esc (within timeout)                      │
//!      │                        ▼                                           │
//!      │               ┌─────────────────┐                                  │
//!      │               │ Emit(EscEsc)    │──────────────────────────────────┘
//!      │               └─────────────────┘
//!//!      │  other key
//!      └───────────────────────────────────────────────────────────────────
//! ```
//!
//! # Example
//!
//! ```
//! use std::time::{Duration, Instant};
//! use ftui_core::keybinding::{SequenceDetector, SequenceConfig, SequenceOutput};
//! use ftui_core::event::{KeyCode, KeyEvent, Modifiers, KeyEventKind};
//!
//! let mut detector = SequenceDetector::new(SequenceConfig::default());
//! let now = Instant::now();
//!
//! // First Esc: starts the sequence
//! let esc = KeyEvent::new(KeyCode::Escape);
//! let output = detector.feed(&esc, now);
//! assert!(matches!(output, SequenceOutput::Pending));
//!
//! // Second Esc within timeout: emits EscEsc
//! let later = now + Duration::from_millis(100);
//! let output = detector.feed(&esc, later);
//! assert!(matches!(output, SequenceOutput::EscEsc));
//! ```
//!
//! # Action Mapping Example
//!
//! ```
//! use std::time::Instant;
//! use ftui_core::keybinding::{ActionMapper, ActionConfig, AppState, Action};
//! use ftui_core::event::{KeyCode, KeyEvent, Modifiers};
//!
//! let mut mapper = ActionMapper::new(ActionConfig::default());
//! let now = Instant::now();
//!
//! // Ctrl+C with non-empty input: clears input
//! let state = AppState { input_nonempty: true, ..Default::default() };
//! let ctrl_c = KeyEvent::new(KeyCode::Char('c')).with_modifiers(Modifiers::CTRL);
//! let action = mapper.map(&ctrl_c, &state, now);
//! assert!(matches!(action, Some(Action::ClearInput)));
//!
//! // Ctrl+C with empty input and no task: quits (by default)
//! let idle_state = AppState::default();
//! let action = mapper.map(&ctrl_c, &idle_state, now);
//! assert!(matches!(action, Some(Action::Quit)));
//! ```

use web_time::{Duration, Instant};

use crate::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};

// ---------------------------------------------------------------------------
// Configuration Constants
// ---------------------------------------------------------------------------

/// Default timeout for detecting Esc Esc sequence.
pub const DEFAULT_ESC_SEQ_TIMEOUT_MS: u64 = 250;

/// Minimum allowed value for Esc sequence timeout.
pub const MIN_ESC_SEQ_TIMEOUT_MS: u64 = 150;

/// Maximum allowed value for Esc sequence timeout.
pub const MAX_ESC_SEQ_TIMEOUT_MS: u64 = 400;

/// Default debounce before emitting single Esc.
pub const DEFAULT_ESC_DEBOUNCE_MS: u64 = 50;

/// Minimum allowed value for Esc debounce.
pub const MIN_ESC_DEBOUNCE_MS: u64 = 0;

/// Maximum allowed value for Esc debounce.
pub const MAX_ESC_DEBOUNCE_MS: u64 = 100;

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// Configuration for the sequence detector.
///
/// # Timing Defaults
///
/// | Setting | Default | Range | Description |
/// |---------|---------|-------|-------------|
/// | `esc_seq_timeout` | 250ms | 150-400ms | Window for detecting Esc Esc |
/// | `esc_debounce` | 50ms | 0-100ms | Minimum wait before single Esc |
///
/// # Environment Variables
///
/// | Variable | Type | Default | Description |
/// |----------|------|---------|-------------|
/// | `FTUI_ESC_SEQ_TIMEOUT_MS` | u64 | 250 | Esc Esc detection window |
/// | `FTUI_ESC_DEBOUNCE_MS` | u64 | 50 | Minimum Esc wait |
/// | `FTUI_DISABLE_ESC_SEQ` | bool | false | Disable multi-key sequences |
///
/// # Example
///
/// ```bash
/// # Faster double-tap detection (200ms window)
/// export FTUI_ESC_SEQ_TIMEOUT_MS=200
///
/// # Disable Esc Esc entirely (for strict terminals)
/// export FTUI_DISABLE_ESC_SEQ=1
/// ```
#[derive(Debug, Clone)]
pub struct SequenceConfig {
    /// Maximum gap between Esc presses to detect Esc Esc sequence.
    /// Default: 250ms.
    pub esc_seq_timeout: Duration,

    /// Minimum debounce before emitting single Esc.
    /// Default: 50ms.
    pub esc_debounce: Duration,

    /// Whether to disable multi-key sequences entirely.
    /// When true, all Esc keys are immediately emitted as single Esc.
    /// Default: false.
    pub disable_sequences: bool,
}

impl Default for SequenceConfig {
    fn default() -> Self {
        Self {
            esc_seq_timeout: Duration::from_millis(DEFAULT_ESC_SEQ_TIMEOUT_MS),
            esc_debounce: Duration::from_millis(DEFAULT_ESC_DEBOUNCE_MS),
            disable_sequences: false,
        }
    }
}

impl SequenceConfig {
    /// Create a new config with custom timeout.
    #[must_use]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.esc_seq_timeout = timeout;
        self
    }

    /// Create a new config with custom debounce.
    #[must_use]
    pub fn with_debounce(mut self, debounce: Duration) -> Self {
        self.esc_debounce = debounce;
        self
    }

    /// Disable sequence detection (treat all Esc as single).
    #[must_use]
    pub fn disable_sequences(mut self) -> Self {
        self.disable_sequences = true;
        self
    }

    /// Load config from environment variables.
    ///
    /// Reads:
    /// - `FTUI_ESC_SEQ_TIMEOUT_MS`: Esc Esc detection window in milliseconds
    /// - `FTUI_ESC_DEBOUNCE_MS`: Minimum Esc wait in milliseconds
    /// - `FTUI_DISABLE_ESC_SEQ`: Set to "1" or "true" to disable sequences
    ///
    /// Values are automatically clamped to valid ranges.
    #[must_use]
    pub fn from_env() -> Self {
        let mut config = Self::default();

        if let Ok(val) = std::env::var("FTUI_ESC_SEQ_TIMEOUT_MS")
            && let Ok(ms) = val.parse::<u64>()
        {
            config.esc_seq_timeout = Duration::from_millis(ms);
        }

        if let Ok(val) = std::env::var("FTUI_ESC_DEBOUNCE_MS")
            && let Ok(ms) = val.parse::<u64>()
        {
            config.esc_debounce = Duration::from_millis(ms);
        }

        if let Ok(val) = std::env::var("FTUI_DISABLE_ESC_SEQ") {
            config.disable_sequences = val == "1" || val.eq_ignore_ascii_case("true");
        }

        config.validated()
    }

    /// Validate and clamp values to safe ranges.
    ///
    /// Returns a new config with:
    /// - `esc_seq_timeout` clamped to 150-400ms
    /// - `esc_debounce` clamped to 0-100ms
    /// - `esc_debounce` <= `esc_seq_timeout` (debounce is capped at timeout)
    ///
    /// # Example
    ///
    /// ```
    /// use ftui_core::keybinding::SequenceConfig;
    /// use std::time::Duration;
    ///
    /// let config = SequenceConfig::default()
    ///     .with_timeout(Duration::from_millis(1000))  // Too high
    ///     .validated();
    ///
    /// // Clamped to max 400ms
    /// assert_eq!(config.esc_seq_timeout.as_millis(), 400);
    /// ```
    #[must_use]
    pub fn validated(mut self) -> Self {
        // Clamp timeout to valid range
        let timeout_ms = self.esc_seq_timeout.as_millis() as u64;
        let clamped_timeout = timeout_ms.clamp(MIN_ESC_SEQ_TIMEOUT_MS, MAX_ESC_SEQ_TIMEOUT_MS);
        self.esc_seq_timeout = Duration::from_millis(clamped_timeout);

        // Clamp debounce to valid range
        let debounce_ms = self.esc_debounce.as_millis() as u64;
        let clamped_debounce = debounce_ms.clamp(MIN_ESC_DEBOUNCE_MS, MAX_ESC_DEBOUNCE_MS);

        // Ensure debounce <= timeout (debounce shouldn't exceed the timeout window)
        let final_debounce = clamped_debounce.min(clamped_timeout);
        self.esc_debounce = Duration::from_millis(final_debounce);

        self
    }

    /// Check if values are within valid ranges.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        let timeout_ms = self.esc_seq_timeout.as_millis() as u64;
        let debounce_ms = self.esc_debounce.as_millis() as u64;

        (MIN_ESC_SEQ_TIMEOUT_MS..=MAX_ESC_SEQ_TIMEOUT_MS).contains(&timeout_ms)
            && (MIN_ESC_DEBOUNCE_MS..=MAX_ESC_DEBOUNCE_MS).contains(&debounce_ms)
            && debounce_ms <= timeout_ms
    }
}

// ---------------------------------------------------------------------------
// Sequence Output
// ---------------------------------------------------------------------------

/// Output from the sequence detector after processing a key event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SequenceOutput {
    /// No action yet; waiting for timeout or more input.
    Pending,

    /// Single Escape key was detected.
    Esc,

    /// Double Escape (Esc Esc) sequence was detected.
    EscEsc,

    /// Pass through the original key event (not part of a sequence).
    PassThrough,
}

// ---------------------------------------------------------------------------
// Sequence Detector
// ---------------------------------------------------------------------------

/// Internal state of the sequence detector.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DetectorState {
    /// Idle: waiting for input.
    Idle,

    /// First Esc received; waiting for second or timeout.
    AwaitingSecondEsc { first_esc_time: Instant },
}

/// Stateful detector for multi-key sequences (currently Esc Esc).
///
/// This detector transforms a stream of [`KeyEvent`]s into [`SequenceOutput`]s,
/// detecting Esc Esc sequences with configurable timeout handling.
///
/// # Usage
///
/// Call [`feed`](SequenceDetector::feed) for each key event. The detector returns:
/// - `Pending`: First Esc received, waiting for more input or timeout.
/// - `Esc`: Single Esc was detected (after timeout or other key).
/// - `EscEsc`: Double Esc sequence was detected.
/// - `PassThrough`: Key is not Esc, pass through to normal handling.
///
/// Call [`check_timeout`](SequenceDetector::check_timeout) periodically (e.g., on
/// tick) to emit pending single Esc after timeout expires.
#[derive(Debug)]
pub struct SequenceDetector {
    config: SequenceConfig,
    state: DetectorState,
}

impl SequenceDetector {
    /// Create a new sequence detector with the given configuration.
    #[must_use]
    pub fn new(config: SequenceConfig) -> Self {
        Self {
            config,
            state: DetectorState::Idle,
        }
    }

    /// Create a new sequence detector with default configuration.
    #[must_use]
    pub fn with_defaults() -> Self {
        Self::new(SequenceConfig::default())
    }

    /// Process a key event and return the sequence output.
    ///
    /// Only key press events are considered; repeat and release are ignored.
    pub fn feed(&mut self, event: &KeyEvent, now: Instant) -> SequenceOutput {
        // Only process press events
        if event.kind != KeyEventKind::Press {
            return SequenceOutput::PassThrough;
        }

        // If sequences are disabled, handle Esc immediately
        if self.config.disable_sequences {
            return if event.code == KeyCode::Escape {
                SequenceOutput::Esc
            } else {
                SequenceOutput::PassThrough
            };
        }

        match self.state {
            DetectorState::Idle => {
                if event.code == KeyCode::Escape {
                    // First Esc: transition to awaiting second
                    self.state = DetectorState::AwaitingSecondEsc {
                        first_esc_time: now,
                    };
                    SequenceOutput::Pending
                } else {
                    // Non-Esc key: pass through
                    SequenceOutput::PassThrough
                }
            }

            DetectorState::AwaitingSecondEsc { first_esc_time } => {
                let elapsed = now.saturating_duration_since(first_esc_time);

                if event.code == KeyCode::Escape {
                    // Second Esc received
                    if elapsed <= self.config.esc_seq_timeout {
                        // Within timeout: emit EscEsc
                        self.state = DetectorState::Idle;
                        SequenceOutput::EscEsc
                    } else {
                        // Past timeout: first Esc already timed out, this starts new
                        self.state = DetectorState::AwaitingSecondEsc {
                            first_esc_time: now,
                        };
                        SequenceOutput::Esc
                    }
                } else {
                    // Other key received: emit pending Esc, then pass through
                    // The caller should handle the Esc first, then re-feed this key
                    self.state = DetectorState::Idle;
                    // Return Esc; caller must re-feed the current key
                    SequenceOutput::Esc
                }
            }
        }
    }

    /// Check for timeout and emit pending Esc if expired.
    ///
    /// Call this periodically (e.g., on tick) to handle the case where
    /// the user pressed Esc once and is waiting.
    ///
    /// Returns `Some(SequenceOutput::Esc)` if timeout expired,
    /// `None` otherwise.
    pub fn check_timeout(&mut self, now: Instant) -> Option<SequenceOutput> {
        if let DetectorState::AwaitingSecondEsc { first_esc_time } = self.state {
            let elapsed = now.saturating_duration_since(first_esc_time);
            if elapsed > self.config.esc_seq_timeout {
                self.state = DetectorState::Idle;
                return Some(SequenceOutput::Esc);
            }
        }
        None
    }

    /// Whether the detector is waiting for a second Esc.
    #[must_use]
    pub fn is_pending(&self) -> bool {
        matches!(self.state, DetectorState::AwaitingSecondEsc { .. })
    }

    /// Reset the detector to idle state.
    ///
    /// Any pending Esc is discarded.
    pub fn reset(&mut self) {
        self.state = DetectorState::Idle;
    }

    /// Get a reference to the current configuration.
    #[must_use]
    pub fn config(&self) -> &SequenceConfig {
        &self.config
    }

    /// Update the configuration.
    ///
    /// Does not reset pending state.
    pub fn set_config(&mut self, config: SequenceConfig) {
        self.config = config;
    }
}

// ---------------------------------------------------------------------------
// Application State
// ---------------------------------------------------------------------------

/// Runtime state flags that affect keybinding resolution.
///
/// These flags are queried at the moment a key event is resolved to an action.
/// The priority of actions changes based on these flags per the policy spec.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct AppState {
    /// True if the text input buffer contains characters.
    pub input_nonempty: bool,

    /// True if a background task/command is executing.
    pub task_running: bool,

    /// True if a modal dialog or overlay is visible.
    pub modal_open: bool,

    /// True if a secondary view (tree, debug, HUD) is active.
    pub view_overlay: bool,
}

impl AppState {
    /// Create a new state with all flags false.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            input_nonempty: false,
            task_running: false,
            modal_open: false,
            view_overlay: false,
        }
    }

    /// Set input_nonempty flag.
    #[must_use]
    pub const fn with_input(mut self, nonempty: bool) -> Self {
        self.input_nonempty = nonempty;
        self
    }

    /// Set task_running flag.
    #[must_use]
    pub const fn with_task(mut self, running: bool) -> Self {
        self.task_running = running;
        self
    }

    /// Set modal_open flag.
    #[must_use]
    pub const fn with_modal(mut self, open: bool) -> Self {
        self.modal_open = open;
        self
    }

    /// Set view_overlay flag.
    #[must_use]
    pub const fn with_overlay(mut self, active: bool) -> Self {
        self.view_overlay = active;
        self
    }

    /// Check if in idle state (no input, no task, no modal).
    #[must_use]
    pub const fn is_idle(&self) -> bool {
        !self.input_nonempty && !self.task_running && !self.modal_open
    }
}

// ---------------------------------------------------------------------------
// Actions
// ---------------------------------------------------------------------------

/// High-level actions that can result from keybinding resolution.
///
/// These actions are returned by the [`ActionMapper`] and should be handled
/// by the application's event loop.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Action {
    /// Empty the input buffer, keep cursor at start.
    ClearInput,

    /// Send cancel signal to running task, update status.
    CancelTask,

    /// Close topmost modal, return focus to parent.
    DismissModal,

    /// Deactivate view overlay (tree view, debug HUD).
    CloseOverlay,

    /// Toggle the tree/file view overlay.
    ToggleTreeView,

    /// Clean exit via quit command.
    Quit,

    /// Quit if idle, otherwise cancel current operation.
    SoftQuit,

    /// Immediate quit (bypass confirmation if any).
    HardQuit,

    /// Emit terminal bell (BEL character).
    Bell,

    /// Forward event to focused widget/input.
    ///
    /// This indicates the key should be passed through to normal input handling.
    PassThrough,
}

impl Action {
    /// Check if this action consumes the event (vs passing through).
    #[must_use]
    pub const fn consumes_event(&self) -> bool {
        !matches!(self, Action::PassThrough)
    }

    /// Check if this is a quit-related action.
    #[must_use]
    pub const fn is_quit(&self) -> bool {
        matches!(self, Action::Quit | Action::SoftQuit | Action::HardQuit)
    }
}

// ---------------------------------------------------------------------------
// Ctrl+C Idle Action
// ---------------------------------------------------------------------------

/// Behavior when Ctrl+C is pressed with empty input and no running task.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum CtrlCIdleAction {
    /// Exit the application.
    #[default]
    Quit,

    /// Do nothing.
    Noop,

    /// Emit terminal bell (BEL).
    Bell,
}

impl CtrlCIdleAction {
    /// Parse from string (environment variable value).
    #[must_use]
    pub fn from_str_opt(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "quit" => Some(Self::Quit),
            "noop" | "none" | "ignore" => Some(Self::Noop),
            "bell" | "beep" => Some(Self::Bell),
            _ => None,
        }
    }

    /// Convert to the corresponding Action (or None for Noop).
    #[must_use]
    pub const fn to_action(self) -> Option<Action> {
        match self {
            Self::Quit => Some(Action::Quit),
            Self::Noop => None,
            Self::Bell => Some(Action::Bell),
        }
    }
}

// ---------------------------------------------------------------------------
// Action Configuration
// ---------------------------------------------------------------------------

/// Configuration for action mapping behavior.
///
/// This struct combines sequence detection settings with keybinding behavior
/// configuration. It controls how keys like Ctrl+C, Ctrl+D, Esc, and Esc Esc
/// are interpreted based on application state.
///
/// # Environment Variables
///
/// | Variable | Type | Default | Description |
/// |----------|------|---------|-------------|
/// | `FTUI_CTRL_C_IDLE_ACTION` | string | "quit" | Action when Ctrl+C in idle state |
/// | `FTUI_ESC_SEQ_TIMEOUT_MS` | u64 | 250 | Esc Esc detection window |
/// | `FTUI_ESC_DEBOUNCE_MS` | u64 | 50 | Minimum Esc wait |
/// | `FTUI_DISABLE_ESC_SEQ` | bool | false | Disable Esc Esc sequences |
///
/// # Example: Configure via environment
///
/// ```bash
/// # Make Ctrl+C do nothing when idle (instead of quit)
/// export FTUI_CTRL_C_IDLE_ACTION=noop
///
/// # Or make it beep
/// export FTUI_CTRL_C_IDLE_ACTION=bell
///
/// # Faster double-Esc detection
/// export FTUI_ESC_SEQ_TIMEOUT_MS=200
/// ```
///
/// # Example: Configure in code
///
/// ```
/// use ftui_core::keybinding::{ActionConfig, CtrlCIdleAction, SequenceConfig};
/// use std::time::Duration;
///
/// let config = ActionConfig::default()
///     .with_ctrl_c_idle(CtrlCIdleAction::Bell)
///     .with_sequence_config(
///         SequenceConfig::default()
///             .with_timeout(Duration::from_millis(200))
///     );
/// ```
#[derive(Debug, Clone)]
pub struct ActionConfig {
    /// Sequence detection configuration (timeouts, debounce, disable flag).
    pub sequence_config: SequenceConfig,

    /// Action when Ctrl+C pressed with empty input and no task.
    ///
    /// - `Quit` (default): Exit the application
    /// - `Noop`: Do nothing
    /// - `Bell`: Emit terminal bell
    pub ctrl_c_idle_action: CtrlCIdleAction,
}

impl Default for ActionConfig {
    fn default() -> Self {
        Self {
            sequence_config: SequenceConfig::default(),
            ctrl_c_idle_action: CtrlCIdleAction::Quit,
        }
    }
}

impl ActionConfig {
    /// Create config with custom sequence settings.
    #[must_use]
    pub fn with_sequence_config(mut self, config: SequenceConfig) -> Self {
        self.sequence_config = config;
        self
    }

    /// Set Ctrl+C idle action.
    #[must_use]
    pub fn with_ctrl_c_idle(mut self, action: CtrlCIdleAction) -> Self {
        self.ctrl_c_idle_action = action;
        self
    }

    /// Load config from environment variables.
    ///
    /// Reads:
    /// - `FTUI_CTRL_C_IDLE_ACTION`: "quit", "noop", or "bell"
    /// - Plus all environment variables from [`SequenceConfig::from_env`]
    #[must_use]
    pub fn from_env() -> Self {
        let mut config = Self {
            sequence_config: SequenceConfig::from_env(),
            ctrl_c_idle_action: CtrlCIdleAction::Quit,
        };

        if let Ok(val) = std::env::var("FTUI_CTRL_C_IDLE_ACTION")
            && let Some(action) = CtrlCIdleAction::from_str_opt(&val)
        {
            config.ctrl_c_idle_action = action;
        }

        config
    }

    /// Validate and return a config with clamped sequence values.
    ///
    /// Delegates to [`SequenceConfig::validated`] for timing bounds.
    #[must_use]
    pub fn validated(mut self) -> Self {
        self.sequence_config = self.sequence_config.validated();
        self
    }
}

// ---------------------------------------------------------------------------
// Action Mapper
// ---------------------------------------------------------------------------

/// Maps key events to high-level actions based on application state.
///
/// The `ActionMapper` integrates the sequence detector and implements the
/// priority table from the keybinding policy specification (bd-2vne.1).
///
/// # Priority Order
///
/// Actions are resolved in priority order (first match wins):
///
/// | Priority | Condition | Key | Action |
/// |----------|-----------|-----|--------|
/// | 1 | `modal_open` | Esc | DismissModal |
/// | 2 | `modal_open` | Ctrl+C | DismissModal |
/// | 3 | `input_nonempty` | Ctrl+C | ClearInput |
/// | 4 | `task_running` | Ctrl+C | CancelTask |
/// | 5 | idle | Ctrl+C | Quit (configurable) |
/// | 6 | `view_overlay` | Esc | CloseOverlay |
/// | 7 | `input_nonempty` | Esc | ClearInput |
/// | 8 | `task_running` | Esc | CancelTask |
/// | 9 | always | Esc Esc | ToggleTreeView |
/// | 10 | always | Ctrl+D | SoftQuit |
/// | 11 | always | Ctrl+Q | HardQuit |
///
/// # Usage
///
/// ```
/// use std::time::Instant;
/// use ftui_core::keybinding::{ActionMapper, ActionConfig, AppState, Action};
/// use ftui_core::event::{KeyCode, KeyEvent, Modifiers};
///
/// let mut mapper = ActionMapper::new(ActionConfig::default());
/// let now = Instant::now();
/// let state = AppState::default();
///
/// let key = KeyEvent::new(KeyCode::Char('q')).with_modifiers(Modifiers::CTRL);
/// let action = mapper.map(&key, &state, now);
/// assert!(matches!(action, Some(Action::HardQuit)));
/// ```
#[derive(Debug)]
pub struct ActionMapper {
    config: ActionConfig,
    sequence_detector: SequenceDetector,
}

impl ActionMapper {
    /// Create a new action mapper with the given configuration.
    #[must_use]
    pub fn new(config: ActionConfig) -> Self {
        let sequence_detector = SequenceDetector::new(config.sequence_config.clone());
        Self {
            config,
            sequence_detector,
        }
    }

    /// Create a new action mapper with default configuration.
    #[must_use]
    pub fn with_defaults() -> Self {
        Self::new(ActionConfig::default())
    }

    /// Create a new action mapper loading config from environment.
    #[must_use]
    pub fn from_env() -> Self {
        Self::new(ActionConfig::from_env())
    }

    /// Map a key event to an action based on current application state.
    ///
    /// Returns `Some(action)` if the key resolves to an action, or `None`
    /// if the event should be ignored (e.g., Noop on Ctrl+C when idle).
    ///
    /// # Arguments
    ///
    /// * `event` - The key event to process
    /// * `state` - Current application state flags
    /// * `now` - Current timestamp for sequence detection
    pub fn map(&mut self, event: &KeyEvent, state: &AppState, now: Instant) -> Option<Action> {
        // Only process press events
        if event.kind != KeyEventKind::Press {
            return Some(Action::PassThrough);
        }

        // Check for Ctrl+C, Ctrl+D, Ctrl+Q first (they don't participate in sequences)
        if event.modifiers.contains(Modifiers::CTRL)
            && let KeyCode::Char(c) = event.code
        {
            match c.to_ascii_lowercase() {
                'c' => return self.resolve_ctrl_c(state),
                'd' => return Some(Action::SoftQuit),
                'q' => return Some(Action::HardQuit),
                _ => {}
            }
        }

        // Handle Escape through sequence detector
        if event.code == KeyCode::Escape && event.modifiers == Modifiers::NONE {
            return self.handle_esc_sequence(state, now);
        }

        // For non-Esc keys, check if we have a pending Esc
        let seq_output = self.sequence_detector.feed(event, now);
        match seq_output {
            SequenceOutput::Esc => {
                // Pending Esc was interrupted; resolve it and note the key is consumed
                // The caller should re-feed the current key after handling Esc
                // For now we return the Esc action; the current key is lost
                // This matches the spec: "emit pending Esc first, then process"
                self.resolve_single_esc(state)
            }
            SequenceOutput::Pending => {
                // Should not happen for non-Esc keys
                Some(Action::PassThrough)
            }
            SequenceOutput::EscEsc => {
                // Should not happen for non-Esc keys
                Some(Action::ToggleTreeView)
            }
            SequenceOutput::PassThrough => Some(Action::PassThrough),
        }
    }

    /// Handle Escape key through the sequence detector.
    fn handle_esc_sequence(&mut self, state: &AppState, now: Instant) -> Option<Action> {
        let esc_event = KeyEvent::new(KeyCode::Escape);
        let output = self.sequence_detector.feed(&esc_event, now);

        match output {
            SequenceOutput::Pending => {
                // First Esc received, waiting for second
                // Don't emit action yet; the event loop should call check_timeout
                None
            }
            SequenceOutput::Esc => {
                // Single Esc detected (either timeout or past timeout second Esc)
                self.resolve_single_esc(state)
            }
            SequenceOutput::EscEsc => {
                // Double Esc sequence detected
                Some(Action::ToggleTreeView)
            }
            SequenceOutput::PassThrough => {
                // Should not happen for Esc
                Some(Action::PassThrough)
            }
        }
    }

    /// Resolve Ctrl+C based on state.
    fn resolve_ctrl_c(&self, state: &AppState) -> Option<Action> {
        // Priority 2: modal_open -> DismissModal
        if state.modal_open {
            return Some(Action::DismissModal);
        }

        // Priority 3: input_nonempty -> ClearInput
        if state.input_nonempty {
            return Some(Action::ClearInput);
        }

        // Priority 4: task_running -> CancelTask
        if state.task_running {
            return Some(Action::CancelTask);
        }

        // Priority 5: idle -> configurable action
        self.config.ctrl_c_idle_action.to_action()
    }

    /// Resolve single Esc based on state.
    fn resolve_single_esc(&self, state: &AppState) -> Option<Action> {
        // Priority 1: modal_open -> DismissModal
        if state.modal_open {
            return Some(Action::DismissModal);
        }

        // Priority 6: view_overlay -> CloseOverlay
        if state.view_overlay {
            return Some(Action::CloseOverlay);
        }

        // Priority 7: input_nonempty -> ClearInput
        if state.input_nonempty {
            return Some(Action::ClearInput);
        }

        // Priority 8: task_running -> CancelTask
        if state.task_running {
            return Some(Action::CancelTask);
        }

        // No action for Esc in idle state
        Some(Action::PassThrough)
    }

    /// Check for sequence timeout and return pending action if expired.
    ///
    /// Call this periodically (e.g., on tick) to handle single Esc after
    /// the timeout window closes.
    ///
    /// # Arguments
    ///
    /// * `state` - Current application state flags
    /// * `now` - Current timestamp
    pub fn check_timeout(&mut self, state: &AppState, now: Instant) -> Option<Action> {
        if let Some(SequenceOutput::Esc) = self.sequence_detector.check_timeout(now) {
            return self.resolve_single_esc(state);
        }
        None
    }

    /// Whether the mapper is waiting for a second Esc.
    #[must_use]
    pub fn is_pending_esc(&self) -> bool {
        self.sequence_detector.is_pending()
    }

    /// Reset the sequence detector state.
    ///
    /// Any pending Esc is discarded.
    pub fn reset(&mut self) {
        self.sequence_detector.reset();
    }

    /// Get a reference to the current configuration.
    #[must_use]
    pub fn config(&self) -> &ActionConfig {
        &self.config
    }

    /// Update the configuration.
    pub fn set_config(&mut self, config: ActionConfig) {
        self.sequence_detector
            .set_config(config.sequence_config.clone());
        self.config = config;
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

// ===========================================================================
// Declarative keymaps: combos, chords, priorities, contexts, conflict
// detection, and a chord-aware dispatcher
// ===========================================================================
//
// Resolution order, in prose (the keybinding policy spec copies this):
//
// 1. A key press extends the pending prefix. If the extended chord is bound
//    and no longer bound chord starts with it, the binding fires at once.
//    If a longer bound chord starts with it (`g` while `g g` is bound), the
//    dispatcher waits: the exact binding fires on the chord timeout or when a
//    key arrives that cannot extend the chord, so single-key shortcuts are
//    never blocked, only delayed while a real chord is possible.
// 2. A key that cannot extend the pending prefix flushes it (the prefix
//    fires if it is bound, otherwise it is reported as expired) and is then
//    processed on its own.
// 3. Among bindings for the same chord, one attached to an active context
//    beats a context-free one, then the higher `Priority` wins, then the most
//    recently bound. `KeyMap::conflicts` reports every case that needs the
//    tie-break so shadowing is visible instead of silent.
// 4. `Repeat` events re-fire a single-key binding but never extend a chord;
//    `Release` events are reported as unbound.
// 5. `Esc` goes through the embedded `SequenceDetector` (one Esc timer per
//    dispatcher); `Esc` and `Esc Esc` can be bound like any chord.

use std::fmt;
use std::str::FromStr;

/// Why a key, combo, or chord string could not be parsed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyParseError {
    /// The key name (or the whole chord) was empty.
    EmptyKey,
    /// A key name that matches no [`KeyCode`].
    UnknownKey(String),
    /// A modifier name other than `Ctrl`, `Alt`, `Shift`, `Super`.
    UnknownModifier(String),
    /// More than [`Chord::MAX_LEN`] combos in one chord.
    TooManyKeys(usize),
}

impl fmt::Display for KeyParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyKey => f.write_str("empty key"),
            Self::UnknownKey(name) => write!(f, "unknown key `{name}`"),
            Self::UnknownModifier(name) => write!(f, "unknown modifier `{name}`"),
            Self::TooManyKeys(n) => {
                write!(f, "chord has {n} keys; the maximum is {}", Chord::MAX_LEN)
            }
        }
    }
}

impl std::error::Error for KeyParseError {}

/// A single key press with its modifiers (`Ctrl+x`, `Shift+Tab`, `F12`, `g`).
///
/// Combos are normalized so that `Shift+a`, `A`, and a terminal that reports
/// `Char('A')` with the Shift bit all compare equal: alphabetic characters
/// are stored lowercase with [`Modifiers::SHIFT`] set.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct KeyCombo {
    /// The key.
    pub code: KeyCode,
    /// Modifier keys held.
    pub modifiers: Modifiers,
}

impl KeyCombo {
    /// Build a normalized combo.
    #[must_use]
    pub fn new(code: KeyCode, modifiers: Modifiers) -> Self {
        match code {
            KeyCode::Char(c) if c.is_alphabetic() && c.is_uppercase() => Self {
                code: KeyCode::Char(c.to_lowercase().next().unwrap_or(c)),
                modifiers: modifiers | Modifiers::SHIFT,
            },
            _ => Self { code, modifiers },
        }
    }

    /// A combo without modifiers.
    #[must_use]
    pub fn key(code: KeyCode) -> Self {
        Self::new(code, Modifiers::NONE)
    }

    /// The combo a key event represents (its kind is ignored).
    #[must_use]
    pub fn from_event(event: &KeyEvent) -> Self {
        Self::new(event.code, event.modifiers)
    }

    /// Whether `event` presses this combo (any kind).
    #[must_use]
    pub fn matches(&self, event: &KeyEvent) -> bool {
        Self::from_event(event) == *self
    }
}

impl fmt::Display for KeyCombo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut modifiers = self.modifiers;
        let key = match self.code {
            KeyCode::Char(c) if c.is_alphabetic() && modifiers.contains(Modifiers::SHIFT) => {
                modifiers.remove(Modifiers::SHIFT);
                c.to_uppercase().collect::<String>()
            }
            KeyCode::Char(' ') => "Space".to_string(),
            KeyCode::Char(c) => c.to_string(),
            KeyCode::Enter => "Enter".to_string(),
            KeyCode::Escape => "Esc".to_string(),
            KeyCode::Backspace => "Backspace".to_string(),
            KeyCode::Tab => "Tab".to_string(),
            KeyCode::BackTab => "BackTab".to_string(),
            KeyCode::Delete => "Delete".to_string(),
            KeyCode::Insert => "Insert".to_string(),
            KeyCode::Home => "Home".to_string(),
            KeyCode::End => "End".to_string(),
            KeyCode::PageUp => "PageUp".to_string(),
            KeyCode::PageDown => "PageDown".to_string(),
            KeyCode::Up => "Up".to_string(),
            KeyCode::Down => "Down".to_string(),
            KeyCode::Left => "Left".to_string(),
            KeyCode::Right => "Right".to_string(),
            KeyCode::F(n) => format!("F{n}"),
            KeyCode::Null => "Null".to_string(),
            KeyCode::MediaPlayPause => "MediaPlayPause".to_string(),
            KeyCode::MediaStop => "MediaStop".to_string(),
            KeyCode::MediaNextTrack => "MediaNextTrack".to_string(),
            KeyCode::MediaPrevTrack => "MediaPrevTrack".to_string(),
        };
        for (flag, name) in [
            (Modifiers::CTRL, "Ctrl"),
            (Modifiers::ALT, "Alt"),
            (Modifiers::SHIFT, "Shift"),
            (Modifiers::SUPER, "Super"),
        ] {
            if modifiers.contains(flag) {
                write!(f, "{name}+")?;
            }
        }
        f.write_str(&key)
    }
}

/// Parse a key name: a single character, or a named key (case-insensitive:
/// `Enter`, `Esc`, `Tab`, `BackTab`, `Backspace`, `Delete`, `Insert`, `Home`,
/// `End`, `PageUp`, `PageDown`, `Up`, `Down`, `Left`, `Right`, `Space`,
/// `F1`..`F24`, media keys).
fn parse_key_name(name: &str) -> Result<KeyCode, KeyParseError> {
    let mut chars = name.chars();
    if let (Some(c), None) = (chars.next(), chars.next()) {
        return Ok(KeyCode::Char(c));
    }
    let lower = name.to_ascii_lowercase();
    let code = match lower.as_str() {
        "enter" | "return" => KeyCode::Enter,
        "esc" | "escape" => KeyCode::Escape,
        "backspace" => KeyCode::Backspace,
        "tab" => KeyCode::Tab,
        "backtab" => KeyCode::BackTab,
        "delete" | "del" => KeyCode::Delete,
        "insert" | "ins" => KeyCode::Insert,
        "home" => KeyCode::Home,
        "end" => KeyCode::End,
        "pageup" | "pgup" => KeyCode::PageUp,
        "pagedown" | "pgdn" => KeyCode::PageDown,
        "up" => KeyCode::Up,
        "down" => KeyCode::Down,
        "left" => KeyCode::Left,
        "right" => KeyCode::Right,
        "space" => KeyCode::Char(' '),
        "null" => KeyCode::Null,
        "mediaplaypause" => KeyCode::MediaPlayPause,
        "mediastop" => KeyCode::MediaStop,
        "medianexttrack" => KeyCode::MediaNextTrack,
        "mediaprevtrack" => KeyCode::MediaPrevTrack,
        other => {
            if let Some(digits) = other.strip_prefix('f')
                && let Ok(n) = digits.parse::<u8>()
                && (1..=24).contains(&n)
            {
                KeyCode::F(n)
            } else {
                return Err(KeyParseError::UnknownKey(name.to_string()));
            }
        }
    };
    Ok(code)
}

impl FromStr for KeyCombo {
    type Err = KeyParseError;

    /// Parse `Ctrl+x`, `Shift+Tab`, `F12`, `g`, `Ctrl++` (the plus key).
    /// Modifier names are case-insensitive (`Ctrl`/`Control`, `Alt`/`Opt`/
    /// `Option`, `Shift`, `Super`/`Cmd`/`Meta`/`Win`).
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();
        if s.is_empty() {
            return Err(KeyParseError::EmptyKey);
        }
        let (modifier_part, key_part) = if s == "+" {
            ("", "+")
        } else if let Some(stripped) = s.strip_suffix('+') {
            (stripped.trim_end_matches('+'), "+")
        } else if let Some((modifiers, key)) = s.rsplit_once('+') {
            (modifiers, key)
        } else {
            ("", s)
        };
        let mut modifiers = Modifiers::NONE;
        for part in modifier_part.split('+').filter(|p| !p.is_empty()) {
            modifiers |= match part.to_ascii_lowercase().as_str() {
                "ctrl" | "control" => Modifiers::CTRL,
                "alt" | "opt" | "option" => Modifiers::ALT,
                "shift" => Modifiers::SHIFT,
                "super" | "cmd" | "meta" | "win" => Modifiers::SUPER,
                _ => return Err(KeyParseError::UnknownModifier(part.to_string())),
            };
        }
        if key_part.is_empty() {
            return Err(KeyParseError::EmptyKey);
        }
        Ok(Self::new(parse_key_name(key_part)?, modifiers))
    }
}

/// One to [`Chord::MAX_LEN`] combos pressed in sequence (`g g`, `Ctrl+x Ctrl+s`).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Chord(Vec<KeyCombo>);

impl Chord {
    /// Longest supported chord.
    pub const MAX_LEN: usize = 4;

    /// A one-combo chord.
    #[must_use]
    pub fn single(combo: KeyCombo) -> Self {
        Self(vec![combo])
    }

    /// Build a chord from combos (1..=[`Chord::MAX_LEN`]).
    pub fn new(combos: Vec<KeyCombo>) -> Result<Self, KeyParseError> {
        if combos.is_empty() {
            Err(KeyParseError::EmptyKey)
        } else if combos.len() > Self::MAX_LEN {
            Err(KeyParseError::TooManyKeys(combos.len()))
        } else {
            Ok(Self(combos))
        }
    }

    /// Parse a whitespace-separated chord such as `"g g"` or `"Ctrl+x Ctrl+s"`.
    pub fn parse(s: &str) -> Result<Self, KeyParseError> {
        s.parse()
    }

    /// The combos in order.
    #[must_use]
    pub fn combos(&self) -> &[KeyCombo] {
        &self.0
    }

    /// Number of combos.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Never true for a chord built through the constructors; provided for
    /// API completeness.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Whether this chord is a strict prefix of `other` (`g` of `g g`).
    #[must_use]
    pub fn is_prefix_of(&self, other: &Self) -> bool {
        self.0.len() < other.0.len() && other.0.starts_with(&self.0)
    }
}

impl FromStr for Chord {
    type Err = KeyParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let combos = s
            .split_whitespace()
            .map(str::parse)
            .collect::<Result<Vec<KeyCombo>, _>>()?;
        Self::new(combos)
    }
}

impl fmt::Display for Chord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, combo) in self.0.iter().enumerate() {
            if i > 0 {
                f.write_str(" ")?;
            }
            write!(f, "{combo}")?;
        }
        Ok(())
    }
}

/// Binding priority level; higher wins for the same chord.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Priority {
    /// Application-wide default.
    #[default]
    Global = 0,
    /// Active when the app is in a particular mode.
    Mode = 1,
    /// Owned by the focused widget.
    Widget = 2,
}

/// An interned context name (see [`KeyMap::context`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ContextId(pub u32);

/// Identifier of one binding inside a [`KeyMap`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BindingId(pub u32);

impl fmt::Display for BindingId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "#{}", self.0)
    }
}

/// One chord bound to an action.
#[derive(Debug, Clone)]
pub struct Binding<A> {
    /// Identifier assigned by the map.
    pub id: BindingId,
    /// The chord that triggers the action.
    pub chord: Chord,
    /// The action to dispatch.
    pub action: A,
    /// Priority level.
    pub priority: Priority,
    /// Context the binding is limited to (`None` = always applicable).
    pub context: Option<ContextId>,
    /// Human-readable label for help bars and conflict reports.
    pub label: Option<String>,
}

/// Lower bound of the chord timeout (ms).
pub const MIN_CHORD_TIMEOUT_MS: u64 = 200;
/// Upper bound of the chord timeout (ms).
pub const MAX_CHORD_TIMEOUT_MS: u64 = 5000;
/// Default chord timeout (ms).
pub const DEFAULT_CHORD_TIMEOUT_MS: u64 = 1000;

/// Timing configuration of a [`KeyMap`].
#[derive(Debug, Clone)]
pub struct KeyMapConfig {
    /// How long a pending chord prefix waits for its next key.
    pub chord_timeout: Duration,
    /// Esc / Esc Esc detection settings for the dispatcher's detector.
    pub esc: SequenceConfig,
}

impl Default for KeyMapConfig {
    fn default() -> Self {
        Self {
            chord_timeout: Duration::from_millis(DEFAULT_CHORD_TIMEOUT_MS),
            esc: SequenceConfig::default(),
        }
    }
}

impl KeyMapConfig {
    /// Set the chord timeout, clamped to `200..=5000` ms.
    #[must_use]
    pub fn with_chord_timeout(mut self, timeout: Duration) -> Self {
        let ms = timeout.as_millis().clamp(
            u128::from(MIN_CHORD_TIMEOUT_MS),
            u128::from(MAX_CHORD_TIMEOUT_MS),
        );
        self.chord_timeout = Duration::from_millis(ms as u64);
        self
    }

    /// Set the Esc sequence configuration.
    #[must_use]
    pub fn with_esc(mut self, esc: SequenceConfig) -> Self {
        self.esc = esc;
        self
    }
}

/// Result of [`KeyMap::lookup`].
#[derive(Debug, Clone, Copy)]
pub struct Lookup<'a, A> {
    /// The winning binding for exactly this chord, if any.
    pub exact: Option<&'a Binding<A>>,
    /// Number of applicable bindings whose chord starts with this chord and
    /// is longer (a pending prefix must wait for them).
    pub longer: usize,
}

impl<A> Lookup<'_, A> {
    /// Neither an exact binding nor a longer chord.
    #[must_use]
    pub fn is_none(&self) -> bool {
        self.exact.is_none() && self.longer == 0
    }
}

/// A binding conflict found by [`KeyMap::conflicts`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Conflict {
    /// Same chord, same context, different priority: `winner` hides `loser`.
    Shadowed {
        winner: BindingId,
        loser: BindingId,
        chord: Chord,
    },
    /// `short` is a strict prefix of `long`, so `short` fires only after the
    /// chord timeout or a non-extending key.
    PrefixCollision {
        short: BindingId,
        long: BindingId,
        short_chord: Chord,
        long_chord: Chord,
    },
    /// Same chord, context and priority: the later binding wins.
    Duplicate {
        first: BindingId,
        second: BindingId,
        chord: Chord,
    },
}

/// Every conflict in a map, with a one-line warning per item.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConflictReport {
    /// The conflicts, in map order.
    pub items: Vec<Conflict>,
}

impl ConflictReport {
    /// No conflicts.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Number of conflicts.
    #[must_use]
    pub fn len(&self) -> usize {
        self.items.len()
    }
}

impl fmt::Display for ConflictReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for item in &self.items {
            match item {
                Conflict::Shadowed {
                    winner,
                    loser,
                    chord,
                } => writeln!(
                    f,
                    "warning: binding {winner} shadows binding {loser} on `{chord}` (higher priority)"
                )?,
                Conflict::PrefixCollision {
                    short,
                    long,
                    short_chord,
                    long_chord,
                } => writeln!(
                    f,
                    "warning: binding {short} (`{short_chord}`) is a prefix of binding {long} (`{long_chord}`); it fires only after the chord timeout or a non-extending key"
                )?,
                Conflict::Duplicate {
                    first,
                    second,
                    chord,
                } => writeln!(
                    f,
                    "warning: bindings {first} and {second} both bind `{chord}` at the same priority; the later one wins"
                )?,
            }
        }
        Ok(())
    }
}

/// A declarative binding map: chords to actions with priorities and
/// contexts. Actions are any `Clone` type (usually an app enum).
#[derive(Debug, Clone)]
pub struct KeyMap<A> {
    bindings: Vec<Binding<A>>,
    contexts: Vec<String>,
    config: KeyMapConfig,
    next_id: u32,
}

impl<A> Default for KeyMap<A> {
    fn default() -> Self {
        Self::new()
    }
}

impl<A> KeyMap<A> {
    /// An empty map with default timing.
    #[must_use]
    pub fn new() -> Self {
        Self::with_config(KeyMapConfig::default())
    }

    /// An empty map with the given timing.
    #[must_use]
    pub fn with_config(config: KeyMapConfig) -> Self {
        Self {
            bindings: Vec::new(),
            contexts: Vec::new(),
            config,
            next_id: 0,
        }
    }

    /// Timing configuration.
    #[must_use]
    pub fn config(&self) -> &KeyMapConfig {
        &self.config
    }

    /// Intern a context name; the same name always yields the same id.
    pub fn context(&mut self, name: &str) -> ContextId {
        if let Some(index) = self.contexts.iter().position(|n| n == name) {
            return ContextId(index as u32);
        }
        self.contexts.push(name.to_string());
        ContextId((self.contexts.len() - 1) as u32)
    }

    /// Name of an interned context.
    #[must_use]
    pub fn context_name(&self, id: ContextId) -> Option<&str> {
        self.contexts.get(id.0 as usize).map(String::as_str)
    }

    /// Bind a chord at [`Priority::Global`] with no context.
    pub fn bind(&mut self, chord: Chord, action: A) -> BindingId {
        self.bind_in(chord, action, Priority::Global, None)
    }

    /// Bind a chord with an explicit priority and optional context.
    pub fn bind_in(
        &mut self,
        chord: Chord,
        action: A,
        priority: Priority,
        context: Option<ContextId>,
    ) -> BindingId {
        let id = BindingId(self.next_id);
        self.next_id += 1;
        self.bindings.push(Binding {
            id,
            chord,
            action,
            priority,
            context,
            label: None,
        });
        id
    }

    /// Attach a label to a binding; `false` if the id is unknown.
    pub fn set_label(&mut self, id: BindingId, label: impl Into<String>) -> bool {
        match self.bindings.iter_mut().find(|b| b.id == id) {
            Some(binding) => {
                binding.label = Some(label.into());
                true
            }
            None => false,
        }
    }

    /// Remove a binding.
    pub fn unbind(&mut self, id: BindingId) -> Option<Binding<A>> {
        let index = self.bindings.iter().position(|b| b.id == id)?;
        Some(self.bindings.remove(index))
    }

    /// All bindings in bind order.
    #[must_use]
    pub fn bindings(&self) -> &[Binding<A>] {
        &self.bindings
    }

    /// A binding by id.
    #[must_use]
    pub fn get(&self, id: BindingId) -> Option<&Binding<A>> {
        self.bindings.iter().find(|b| b.id == id)
    }

    /// Number of bindings.
    #[must_use]
    pub fn len(&self) -> usize {
        self.bindings.len()
    }

    /// Whether the map has no bindings.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.bindings.is_empty()
    }

    fn applies(binding: &Binding<A>, active: &[ContextId]) -> bool {
        binding
            .context
            .is_none_or(|context| active.contains(&context))
    }

    /// Ranking used to pick a winner among bindings for the same chord:
    /// active context beats none, then priority, then recency.
    fn rank(binding: &Binding<A>) -> (bool, Priority, BindingId) {
        (binding.context.is_some(), binding.priority, binding.id)
    }

    /// Resolve `chord` against the bindings applicable under `active`
    /// contexts: the winning exact binding and how many longer bound chords
    /// start with it.
    #[must_use]
    pub fn lookup(&self, chord: &Chord, active: &[ContextId]) -> Lookup<'_, A> {
        let mut exact: Option<&Binding<A>> = None;
        let mut longer = 0;
        for binding in &self.bindings {
            if !Self::applies(binding, active) {
                continue;
            }
            if binding.chord == *chord {
                if exact.is_none_or(|current| Self::rank(binding) > Self::rank(current)) {
                    exact = Some(binding);
                }
            } else if chord.is_prefix_of(&binding.chord) {
                longer += 1;
            }
        }
        Lookup { exact, longer }
    }

    /// Report shadowed, duplicate, and prefix-colliding bindings.
    #[must_use]
    pub fn conflicts(&self) -> ConflictReport {
        let mut items = Vec::new();
        for (i, a) in self.bindings.iter().enumerate() {
            for b in &self.bindings[i + 1..] {
                if a.chord == b.chord {
                    if a.context != b.context {
                        // A context-specific override is the intended use.
                        continue;
                    }
                    if a.priority == b.priority {
                        items.push(Conflict::Duplicate {
                            first: a.id,
                            second: b.id,
                            chord: a.chord.clone(),
                        });
                    } else {
                        let (winner, loser) = if a.priority > b.priority {
                            (a.id, b.id)
                        } else {
                            (b.id, a.id)
                        };
                        items.push(Conflict::Shadowed {
                            winner,
                            loser,
                            chord: a.chord.clone(),
                        });
                    }
                } else if a.chord.is_prefix_of(&b.chord) {
                    items.push(Conflict::PrefixCollision {
                        short: a.id,
                        long: b.id,
                        short_chord: a.chord.clone(),
                        long_chord: b.chord.clone(),
                    });
                } else if b.chord.is_prefix_of(&a.chord) {
                    items.push(Conflict::PrefixCollision {
                        short: b.id,
                        long: a.id,
                        short_chord: b.chord.clone(),
                        long_chord: a.chord.clone(),
                    });
                }
            }
        }
        ConflictReport { items }
    }
}

/// What the dispatcher decided for one key event or tick.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Dispatch<A> {
    /// A binding fired.
    Action {
        action: A,
        binding: BindingId,
        chord: Chord,
    },
    /// The key extended a chord prefix; waiting for more keys or the timeout.
    Pending { prefix: Chord },
    /// The key matched nothing (and could not extend a chord).
    Unbound(KeyEvent),
    /// A pending prefix was abandoned (timeout or a non-extending key).
    Expired { prefix: Chord },
    /// Esc sequence detector output for an unbound Esc / Esc Esc.
    Esc(SequenceOutput),
}

/// Counters for evidence rows and hint-usage feedback.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DispatchStats {
    /// Bindings fired.
    pub dispatched: u64,
    /// Keys that entered a chord prefix.
    pub pending: u64,
    /// Prefixes abandoned.
    pub expired: u64,
    /// Keys that matched nothing.
    pub unbound: u64,
    /// Esc / Esc Esc verdicts handed back unbound (see [`Dispatch::Esc`]).
    pub esc: u64,
}

fn action_dispatch<A: Clone>(binding: &Binding<A>, chord: Chord) -> Dispatch<A> {
    Dispatch::Action {
        action: binding.action.clone(),
        binding: binding.id,
        chord,
    }
}

/// Chord-aware dispatcher over a [`KeyMap`].
///
/// Feed every key event through [`feed`](Self::feed) and call
/// [`tick`](Self::tick) once per frame so pending chords and the Esc timer
/// expire; every call returns the decisions to act on. See the module
/// section header for the resolution rules.
#[derive(Debug)]
pub struct KeyDispatcher<A> {
    map: KeyMap<A>,
    pending: Vec<KeyCombo>,
    pending_since: Option<Instant>,
    esc: SequenceDetector,
    active_contexts: Vec<ContextId>,
    stats: DispatchStats,
}

impl<A: Clone> KeyDispatcher<A> {
    /// A dispatcher over `map` with no active contexts.
    #[must_use]
    pub fn new(map: KeyMap<A>) -> Self {
        let esc = SequenceDetector::new(map.config().esc.clone());
        Self {
            map,
            pending: Vec::new(),
            pending_since: None,
            esc,
            active_contexts: Vec::new(),
            stats: DispatchStats::default(),
        }
    }

    /// The underlying map.
    #[must_use]
    pub fn map(&self) -> &KeyMap<A> {
        &self.map
    }

    /// Mutable access to the map (rebinding at runtime).
    pub fn map_mut(&mut self) -> &mut KeyMap<A> {
        &mut self.map
    }

    /// Replace the set of active contexts (focused widget, mode, ...).
    pub fn set_active_contexts(&mut self, contexts: &[ContextId]) {
        self.active_contexts.clear();
        self.active_contexts.extend_from_slice(contexts);
    }

    /// Currently active contexts.
    #[must_use]
    pub fn active_contexts(&self) -> &[ContextId] {
        &self.active_contexts
    }

    /// The chord prefix currently waiting for more keys.
    #[must_use]
    pub fn pending_prefix(&self) -> Option<Chord> {
        Chord::new(self.pending.clone()).ok()
    }

    /// Counters so far.
    #[must_use]
    pub fn stats(&self) -> DispatchStats {
        self.stats
    }

    /// Drop any pending prefix and Esc state.
    pub fn reset(&mut self) {
        self.pending.clear();
        self.pending_since = None;
        self.esc.reset();
    }

    /// Process one key event.
    pub fn feed(&mut self, key: &KeyEvent, now: Instant) -> Vec<Dispatch<A>> {
        let mut out = Vec::with_capacity(2);

        if key.code == KeyCode::Escape {
            if key.kind == KeyEventKind::Press {
                self.flush_pending(&mut out, false);
            }
            match self.esc.feed(key, now) {
                // Repeat / release of Esc: nothing sequence-related to do.
                SequenceOutput::PassThrough => {}
                output => {
                    self.dispatch_esc(output, &mut out);
                    return out;
                }
            }
        }

        match key.kind {
            KeyEventKind::Release => {
                self.stats.unbound += 1;
                out.push(Dispatch::Unbound(*key));
                return out;
            }
            KeyEventKind::Repeat => {
                // A held key re-fires its own single-key binding, never a chord.
                let single = Chord::single(KeyCombo::from_event(key));
                let fired = if self.pending.is_empty() {
                    self.map
                        .lookup(&single, &self.active_contexts)
                        .exact
                        .map(|binding| action_dispatch(binding, single))
                } else {
                    None
                };
                match fired {
                    Some(dispatch) => {
                        self.stats.dispatched += 1;
                        out.push(dispatch);
                    }
                    None => {
                        self.stats.unbound += 1;
                        out.push(Dispatch::Unbound(*key));
                    }
                }
                return out;
            }
            KeyEventKind::Press => {}
        }

        let combo = KeyCombo::from_event(key);
        if self.try_extend(combo, now, &mut out) {
            return out;
        }

        // The key cannot extend the prefix: flush it, then start over with the
        // key on its own so it can fire or begin a new chord.
        if !self.pending.is_empty() {
            self.flush_pending(&mut out, false);
            if self.try_extend(combo, now, &mut out) {
                return out;
            }
        }

        self.stats.unbound += 1;
        out.push(Dispatch::Unbound(*key));
        out
    }

    /// Expire a pending prefix past the chord timeout and drive the Esc timer.
    pub fn tick(&mut self, now: Instant) -> Vec<Dispatch<A>> {
        let mut out = Vec::new();
        if let Some(since) = self.pending_since
            && now.saturating_duration_since(since) >= self.map.config.chord_timeout
        {
            self.flush_pending(&mut out, true);
        }
        if let Some(output) = self.esc.check_timeout(now) {
            self.dispatch_esc(output, &mut out);
        }
        out
    }

    /// Try to treat `combo` as the next key of the pending prefix. Returns
    /// `false` when the extended chord matches nothing (nothing is emitted).
    fn try_extend(&mut self, combo: KeyCombo, now: Instant, out: &mut Vec<Dispatch<A>>) -> bool {
        if self.pending.len() >= Chord::MAX_LEN {
            return false;
        }
        let mut candidate = self.pending.clone();
        candidate.push(combo);
        let chord = Chord(candidate);
        let lookup = self.map.lookup(&chord, &self.active_contexts);
        if let Some(binding) = lookup.exact
            && lookup.longer == 0
        {
            let dispatch = action_dispatch(binding, chord);
            self.pending.clear();
            self.pending_since = None;
            self.stats.dispatched += 1;
            out.push(dispatch);
            return true;
        }
        if lookup.exact.is_some() || lookup.longer > 0 {
            self.pending.clone_from(&chord.0);
            self.pending_since = Some(now);
            self.stats.pending += 1;
            out.push(Dispatch::Pending { prefix: chord });
            return true;
        }
        false
    }

    /// Fire the pending prefix if it is bound, otherwise report it expired;
    /// on a timeout the expiry is reported first so the delay is visible.
    fn flush_pending(&mut self, out: &mut Vec<Dispatch<A>>, timed_out: bool) {
        if self.pending.is_empty() {
            return;
        }
        let prefix = Chord(std::mem::take(&mut self.pending));
        self.pending_since = None;
        let fired = self
            .map
            .lookup(&prefix, &self.active_contexts)
            .exact
            .map(|binding| action_dispatch(binding, prefix.clone()));
        match fired {
            Some(dispatch) => {
                if timed_out {
                    self.stats.expired += 1;
                    out.push(Dispatch::Expired { prefix });
                }
                self.stats.dispatched += 1;
                out.push(dispatch);
            }
            None => {
                self.stats.expired += 1;
                out.push(Dispatch::Expired { prefix });
            }
        }
    }

    /// Route a detector verdict: a bound `Esc` / `Esc Esc` fires its binding,
    /// anything else is handed back as [`Dispatch::Esc`].
    fn dispatch_esc(&mut self, output: SequenceOutput, out: &mut Vec<Dispatch<A>>) {
        let esc = KeyCombo::key(KeyCode::Escape);
        let bound = match output {
            SequenceOutput::Esc => Some(Chord::single(esc)),
            SequenceOutput::EscEsc => Chord::new(vec![esc, esc]).ok(),
            SequenceOutput::Pending | SequenceOutput::PassThrough => None,
        };
        let fired = bound.and_then(|chord| {
            self.map
                .lookup(&chord, &self.active_contexts)
                .exact
                .map(|binding| action_dispatch(binding, chord.clone()))
        });
        match fired {
            Some(dispatch) => {
                self.stats.dispatched += 1;
                out.push(dispatch);
            }
            None => {
                self.stats.esc += 1;
                out.push(Dispatch::Esc(output));
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Serialization (feature `serde`): human-editable keymap files
// ---------------------------------------------------------------------------

/// On-disk shape of a [`KeyMap`] (feature `serde`): chords as text, contexts
/// by name, the chord timeout in milliseconds. Esc timing is not part of the
/// file; it follows [`SequenceConfig`] (defaults and `FTUI_DISABLE_ESC_SEQ`).
///
/// ```toml
/// chord_timeout_ms = 750
///
/// [[bindings]]
/// chord = "Ctrl+x Ctrl+s"
/// action = "Save"
/// priority = "Mode"
/// label = "save"
///
/// [[bindings]]
/// chord = "Enter"
/// action = "Newline"
/// priority = "Widget"
/// context = "editor"
/// ```
#[cfg(feature = "serde")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct KeyMapFile<A> {
    /// Chord timeout in milliseconds (clamped to `200..=5000` on load).
    #[serde(default = "default_chord_timeout_ms")]
    pub chord_timeout_ms: u64,
    /// Bindings in bind order.
    #[serde(default = "Vec::new")]
    pub bindings: Vec<BindingFile<A>>,
}

#[cfg(feature = "serde")]
fn default_chord_timeout_ms() -> u64 {
    DEFAULT_CHORD_TIMEOUT_MS
}

/// One binding in a [`KeyMapFile`].
#[cfg(feature = "serde")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BindingFile<A> {
    /// Chord text, e.g. `"g g"` or `"Ctrl+x Ctrl+s"`.
    pub chord: String,
    /// The action (any serde type; usually a unit-variant enum).
    pub action: A,
    /// Priority level (default `Global`).
    #[serde(default)]
    pub priority: Priority,
    /// Context name (default: none).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context: Option<String>,
    /// Help label (default: none).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

/// Why a [`KeyMapFile`] could not become a [`KeyMap`].
#[cfg(feature = "serde")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyMapFileError {
    /// A binding's chord text did not parse.
    Chord {
        /// Index of the binding in the file.
        index: usize,
        /// The offending chord text.
        chord: String,
        /// Parse error.
        source: KeyParseError,
    },
}

#[cfg(feature = "serde")]
impl fmt::Display for KeyMapFileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Chord {
                index,
                chord,
                source,
            } => write!(f, "binding {index} (`{chord}`): {source}"),
        }
    }
}

#[cfg(feature = "serde")]
impl std::error::Error for KeyMapFileError {}

#[cfg(feature = "serde")]
impl<A: Clone> KeyMap<A> {
    /// The file representation (contexts by name, chords as text).
    #[must_use]
    pub fn to_file(&self) -> KeyMapFile<A> {
        KeyMapFile {
            chord_timeout_ms: self.config.chord_timeout.as_millis() as u64,
            bindings: self
                .bindings
                .iter()
                .map(|binding| BindingFile {
                    chord: binding.chord.to_string(),
                    action: binding.action.clone(),
                    priority: binding.priority,
                    context: binding
                        .context
                        .and_then(|id| self.context_name(id))
                        .map(str::to_string),
                    label: binding.label.clone(),
                })
                .collect(),
        }
    }

    /// Build a map from its file representation, interning context names and
    /// parsing chords; a bad chord names the offending binding.
    pub fn from_file(file: KeyMapFile<A>) -> Result<Self, KeyMapFileError> {
        let config = KeyMapConfig::default()
            .with_chord_timeout(Duration::from_millis(file.chord_timeout_ms));
        let mut map = Self::with_config(config);
        for (index, entry) in file.bindings.into_iter().enumerate() {
            let chord = Chord::parse(&entry.chord).map_err(|source| KeyMapFileError::Chord {
                index,
                chord: entry.chord.clone(),
                source,
            })?;
            let context = entry.context.as_deref().map(|name| map.context(name));
            let id = map.bind_in(chord, entry.action, entry.priority, context);
            if let Some(label) = entry.label {
                map.set_label(id, label);
            }
        }
        Ok(map)
    }
}

#[cfg(feature = "serde")]
impl<A: Clone + serde::Serialize> serde::Serialize for KeyMap<A> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.to_file().serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de, A: Clone + serde::Deserialize<'de>> serde::Deserialize<'de> for KeyMap<A> {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let file = KeyMapFile::<A>::deserialize(deserializer)?;
        Self::from_file(file).map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
mod keymap_tests {
    use super::*;
    use proptest::prelude::*;

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Act {
        GoTop,
        Help,
        Save,
        Quit,
        Submit,
        Newline,
        Global,
        Mode,
        Widget,
        Down,
    }

    fn press(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c))
    }

    fn kind(mut event: KeyEvent, kind: KeyEventKind) -> KeyEvent {
        event.kind = kind;
        event
    }

    fn ms(n: u64) -> Duration {
        Duration::from_millis(n)
    }

    fn chord(s: &str) -> Chord {
        Chord::parse(s).unwrap_or_else(|e| panic!("{s}: {e}"))
    }

    fn actions<A: Clone>(dispatches: &[Dispatch<A>]) -> Vec<A> {
        dispatches
            .iter()
            .filter_map(|d| match d {
                Dispatch::Action { action, .. } => Some(action.clone()),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn combo_parse_display_and_normalization() {
        let ctrl_x: KeyCombo = "Ctrl+x".parse().unwrap();
        assert_eq!(ctrl_x, KeyCombo::new(KeyCode::Char('x'), Modifiers::CTRL));
        assert_eq!(ctrl_x.to_string(), "Ctrl+x");

        // Shift+a, A and a terminal reporting Char('A')+SHIFT are one combo.
        let shift_a: KeyCombo = "shift+a".parse().unwrap();
        assert_eq!(shift_a, "A".parse().unwrap());
        assert_eq!(shift_a, KeyCombo::new(KeyCode::Char('A'), Modifiers::SHIFT));
        assert_eq!(shift_a.to_string(), "A");

        assert_eq!("F12".parse::<KeyCombo>().unwrap().code, KeyCode::F(12));
        assert_eq!(
            "Space".parse::<KeyCombo>().unwrap().code,
            KeyCode::Char(' ')
        );
        assert_eq!(
            "Ctrl+Alt+Delete".parse::<KeyCombo>().unwrap().to_string(),
            "Ctrl+Alt+Delete"
        );
        assert_eq!(
            "Shift+Tab".parse::<KeyCombo>().unwrap().to_string(),
            "Shift+Tab"
        );
        // The plus key itself.
        assert_eq!("+".parse::<KeyCombo>().unwrap().code, KeyCode::Char('+'));
        let ctrl_plus: KeyCombo = "Ctrl++".parse().unwrap();
        assert_eq!(
            ctrl_plus,
            KeyCombo::new(KeyCode::Char('+'), Modifiers::CTRL)
        );

        assert_eq!(
            "Hyper+x".parse::<KeyCombo>(),
            Err(KeyParseError::UnknownModifier("Hyper".into()))
        );
        assert_eq!(
            "Banana".parse::<KeyCombo>(),
            Err(KeyParseError::UnknownKey("Banana".into()))
        );
        assert_eq!("".parse::<KeyCombo>(), Err(KeyParseError::EmptyKey));
        assert_eq!(
            "F0".parse::<KeyCombo>(),
            Err(KeyParseError::UnknownKey("F0".into()))
        );
    }

    #[test]
    fn chord_parse_prefix_and_limits() {
        let gg = chord("g g");
        let g = chord("g");
        assert_eq!(gg.len(), 2);
        assert_eq!(gg.to_string(), "g g");
        assert!(g.is_prefix_of(&gg));
        assert!(!gg.is_prefix_of(&g));
        assert!(!g.is_prefix_of(&g), "a chord is not its own prefix");
        assert_eq!(chord("Ctrl+x Ctrl+s").to_string(), "Ctrl+x Ctrl+s");
        assert_eq!(Chord::parse(""), Err(KeyParseError::EmptyKey));
        assert_eq!(
            Chord::parse("a b c d e"),
            Err(KeyParseError::TooManyKeys(5))
        );
    }

    #[test]
    fn chord_completes_within_timeout() {
        let mut map = KeyMap::new();
        map.bind(chord("g g"), Act::GoTop);
        map.bind(chord("x"), Act::Save);
        let mut dispatcher = KeyDispatcher::new(map);
        let t0 = Instant::now();

        let first = dispatcher.feed(&press('g'), t0);
        assert_eq!(first, vec![Dispatch::Pending { prefix: chord("g") }]);
        assert_eq!(dispatcher.pending_prefix(), Some(chord("g")));
        assert!(
            dispatcher.tick(t0 + ms(300)).is_empty(),
            "still inside the timeout"
        );

        let second = dispatcher.feed(&press('g'), t0 + ms(300));
        assert_eq!(actions(&second), vec![Act::GoTop]);
        assert_eq!(dispatcher.pending_prefix(), None);
        assert_eq!(dispatcher.stats().dispatched, 1);
        assert_eq!(dispatcher.stats().pending, 1);
    }

    #[test]
    fn chord_expires_after_timeout() {
        // Prefix that is itself bound: expiry fires it.
        let mut map = KeyMap::new();
        map.bind(chord("g g"), Act::GoTop);
        map.bind(chord("g"), Act::Help);
        let mut dispatcher = KeyDispatcher::new(map);
        let t0 = Instant::now();
        assert_eq!(
            dispatcher.feed(&press('g'), t0),
            vec![Dispatch::Pending { prefix: chord("g") }]
        );
        assert!(dispatcher.tick(t0 + ms(999)).is_empty());
        let expired = dispatcher.tick(t0 + ms(1000));
        assert_eq!(expired[0], Dispatch::Expired { prefix: chord("g") });
        assert_eq!(actions(&expired), vec![Act::Help]);
        assert_eq!(dispatcher.stats().expired, 1);

        // Prefix that is not bound: expiry only.
        let mut map = KeyMap::new();
        map.bind(chord("g g"), Act::GoTop);
        let mut dispatcher = KeyDispatcher::new(map);
        dispatcher.feed(&press('g'), t0);
        assert_eq!(
            dispatcher.tick(t0 + ms(5000)),
            vec![Dispatch::Expired { prefix: chord("g") }]
        );
        assert_eq!(dispatcher.pending_prefix(), None);
    }

    #[test]
    fn single_key_fires_while_chord_pending() {
        let mut map = KeyMap::new();
        map.bind(chord("g g"), Act::GoTop);
        map.bind(chord("x"), Act::Save);
        let mut dispatcher = KeyDispatcher::new(map);
        let t0 = Instant::now();
        dispatcher.feed(&press('g'), t0);
        let out = dispatcher.feed(&press('x'), t0 + ms(10));
        assert_eq!(out[0], Dispatch::Expired { prefix: chord("g") });
        assert_eq!(
            actions(&out),
            vec![Act::Save],
            "x is never blocked by the pending g"
        );

        // Same with a bound prefix: it fires first, then the single key.
        let mut map = KeyMap::new();
        map.bind(chord("g g"), Act::GoTop);
        map.bind(chord("g"), Act::Help);
        map.bind(chord("x"), Act::Save);
        let mut dispatcher = KeyDispatcher::new(map);
        dispatcher.feed(&press('g'), t0);
        let out = dispatcher.feed(&press('x'), t0 + ms(10));
        assert_eq!(actions(&out), vec![Act::Help, Act::Save]);

        // A non-extending key that starts another chord goes pending itself.
        let mut map = KeyMap::new();
        map.bind(chord("g g"), Act::GoTop);
        map.bind(chord("z z"), Act::Quit);
        let mut dispatcher = KeyDispatcher::new(map);
        dispatcher.feed(&press('g'), t0);
        let out = dispatcher.feed(&press('z'), t0 + ms(10));
        assert_eq!(
            out,
            vec![
                Dispatch::Expired { prefix: chord("g") },
                Dispatch::Pending { prefix: chord("z") }
            ]
        );
    }

    #[test]
    fn prefix_with_own_binding_fires_on_flush() {
        // `g` is bound both on its own and as the prefix of `g g`. A following
        // key that cannot extend the prefix flushes it. Because this is not a
        // timeout, the prefix's own binding fires with no `Expired`, and the
        // non-extending key is then reported unbound.
        let mut map = KeyMap::new();
        let one = map.bind(chord("g"), Act::Help);
        map.bind(chord("g g"), Act::GoTop);
        let mut dispatcher = KeyDispatcher::new(map);
        let t0 = Instant::now();

        assert_eq!(
            dispatcher.feed(&press('g'), t0),
            vec![Dispatch::Pending { prefix: chord("g") }]
        );
        let out = dispatcher.feed(&press('x'), t0 + ms(10));
        assert_eq!(
            out,
            vec![
                Dispatch::Action {
                    action: Act::Help,
                    binding: one,
                    chord: chord("g"),
                },
                Dispatch::Unbound(press('x')),
            ]
        );
        assert_eq!(dispatcher.pending_prefix(), None);
        assert_eq!(
            dispatcher.stats().expired,
            0,
            "a bound prefix flushed by a non-extending key does not expire"
        );
        assert_eq!(dispatcher.stats().dispatched, 1);
    }

    #[test]
    fn widget_beats_mode_beats_global() {
        let mut map = KeyMap::new();
        let g = map.bind_in(chord("s"), Act::Global, Priority::Global, None);
        let m = map.bind_in(chord("s"), Act::Mode, Priority::Mode, None);
        let w = map.bind_in(chord("s"), Act::Widget, Priority::Widget, None);
        let lookup = map.lookup(&chord("s"), &[]);
        assert_eq!(lookup.exact.map(|b| b.id), Some(w));
        assert_eq!(lookup.longer, 0);

        let mut dispatcher = KeyDispatcher::new(map);
        assert_eq!(
            actions(&dispatcher.feed(&press('s'), Instant::now())),
            vec![Act::Widget]
        );

        let report = dispatcher.map().conflicts();
        assert_eq!(report.len(), 3, "{report}");
        assert!(report.items.contains(&Conflict::Shadowed {
            winner: w,
            loser: g,
            chord: chord("s")
        }));
        assert!(report.items.contains(&Conflict::Shadowed {
            winner: m,
            loser: g,
            chord: chord("s")
        }));
        assert!(report.items.contains(&Conflict::Shadowed {
            winner: w,
            loser: m,
            chord: chord("s")
        }));
        assert_eq!(report.to_string().lines().count(), 3);

        // Removing the winner promotes the next.
        dispatcher.map_mut().unbind(w);
        assert_eq!(
            actions(&dispatcher.feed(&press('s'), Instant::now())),
            vec![Act::Mode]
        );
    }

    #[test]
    fn active_context_beats_contextless_even_at_lower_priority() {
        let mut map = KeyMap::new();
        let text_input = map.context("text_input");
        assert_eq!(map.context("text_input"), text_input, "interned once");
        assert_eq!(map.context_name(text_input), Some("text_input"));
        map.bind_in(chord("Enter"), Act::Submit, Priority::Widget, None);
        map.bind_in(
            chord("Enter"),
            Act::Newline,
            Priority::Global,
            Some(text_input),
        );
        assert!(
            map.conflicts().is_empty(),
            "a context override is not a conflict"
        );

        let mut dispatcher = KeyDispatcher::new(map);
        let enter = KeyEvent::new(KeyCode::Enter);
        let t0 = Instant::now();
        assert_eq!(actions(&dispatcher.feed(&enter, t0)), vec![Act::Submit]);
        dispatcher.set_active_contexts(&[text_input]);
        assert_eq!(actions(&dispatcher.feed(&enter, t0)), vec![Act::Newline]);
        dispatcher.set_active_contexts(&[]);
        assert_eq!(actions(&dispatcher.feed(&enter, t0)), vec![Act::Submit]);
    }

    #[test]
    fn conflicts_reports_shadowed_prefix_and_duplicate() {
        let mut map = KeyMap::new();
        let long = map.bind(chord("g g"), Act::GoTop);
        let short = map.bind(chord("g"), Act::Help);
        let q1 = map.bind(chord("q"), Act::Quit);
        let q2 = map.bind(chord("q"), Act::Quit);
        map.set_label(q2, "quit");
        assert_eq!(map.get(q2).and_then(|b| b.label.as_deref()), Some("quit"));

        let report = map.conflicts();
        assert_eq!(report.len(), 2, "{report}");
        assert_eq!(
            report.items[0],
            Conflict::PrefixCollision {
                short,
                long,
                short_chord: chord("g"),
                long_chord: chord("g g"),
            }
        );
        assert_eq!(
            report.items[1],
            Conflict::Duplicate {
                first: q1,
                second: q2,
                chord: chord("q")
            }
        );
        let text = report.to_string();
        assert_eq!(text.lines().count(), 2);
        assert!(
            text.contains("warning: binding #1 (`g`) is a prefix of binding #0 (`g g`)"),
            "{text}"
        );
        assert!(text.contains("the later one wins"), "{text}");

        // The later duplicate wins at dispatch.
        assert_eq!(map.lookup(&chord("q"), &[]).exact.map(|b| b.id), Some(q2));
    }

    #[test]
    fn repeat_refires_single_key_binding_but_never_extends_a_chord() {
        let mut map = KeyMap::new();
        map.bind(chord("j"), Act::Down);
        map.bind(chord("g g"), Act::GoTop);
        let mut dispatcher = KeyDispatcher::new(map);
        let t0 = Instant::now();

        let held = kind(press('j'), KeyEventKind::Repeat);
        assert_eq!(actions(&dispatcher.feed(&held, t0)), vec![Act::Down]);

        dispatcher.feed(&press('g'), t0);
        let repeat_g = kind(press('g'), KeyEventKind::Repeat);
        assert_eq!(
            dispatcher.feed(&repeat_g, t0 + ms(10)),
            vec![Dispatch::Unbound(repeat_g)]
        );
        assert_eq!(
            dispatcher.pending_prefix(),
            Some(chord("g")),
            "repeat left the prefix alone"
        );

        let released = kind(press('j'), KeyEventKind::Release);
        assert_eq!(
            dispatcher.feed(&released, t0 + ms(20)),
            vec![Dispatch::Unbound(released)]
        );
    }

    #[test]
    fn esc_goes_through_the_sequence_detector() {
        let mut map = KeyMap::new();
        map.bind(chord("Esc"), Act::Quit);
        map.bind(chord("Esc Esc"), Act::Help);
        map.bind(chord("g g"), Act::GoTop);
        let mut dispatcher = KeyDispatcher::new(map);
        let esc = KeyEvent::new(KeyCode::Escape);
        let t0 = Instant::now();

        // A lone Esc waits for the detector window, then fires its binding.
        assert_eq!(
            dispatcher.feed(&esc, t0),
            vec![Dispatch::Esc(SequenceOutput::Pending)]
        );
        assert_eq!(actions(&dispatcher.tick(t0 + ms(300))), vec![Act::Quit]);

        // Esc Esc inside the window fires the double binding.
        let t1 = t0 + ms(1000);
        dispatcher.feed(&esc, t1);
        assert_eq!(
            actions(&dispatcher.feed(&esc, t1 + ms(100))),
            vec![Act::Help]
        );

        // Esc cancels a pending chord prefix first.
        let t2 = t0 + ms(3000);
        dispatcher.feed(&press('g'), t2);
        let out = dispatcher.feed(&esc, t2 + ms(10));
        assert_eq!(out[0], Dispatch::Expired { prefix: chord("g") });
        assert_eq!(dispatcher.pending_prefix(), None);

        // Unbound Esc surfaces the detector verdict.
        let mut plain = KeyDispatcher::new(KeyMap::<Act>::new());
        plain.feed(&esc, t0);
        assert_eq!(
            plain.tick(t0 + ms(300)),
            vec![Dispatch::Esc(SequenceOutput::Esc)]
        );
    }

    /// A map round-trips through TOML and JSON with chords as text, contexts
    /// by name and the timeout in milliseconds; a bad hand-written chord is
    /// reported with its binding index.
    #[cfg(feature = "serde")]
    #[test]
    fn keymap_round_trips_through_toml_and_json() {
        #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
        enum Action {
            Quit,
            Save,
            Newline,
        }

        let mut map = KeyMap::with_config(KeyMapConfig::default().with_chord_timeout(ms(750)));
        let editor = map.context("editor");
        let quit = map.bind(chord("q"), Action::Quit);
        map.set_label(quit, "quit");
        map.bind_in(chord("Ctrl+x Ctrl+s"), Action::Save, Priority::Mode, None);
        map.bind_in(
            chord("Enter"),
            Action::Newline,
            Priority::Widget,
            Some(editor),
        );

        let text = toml::to_string(&map).expect("serialize to TOML");
        assert!(text.contains("chord_timeout_ms = 750"), "{text}");
        assert!(text.contains("chord = \"Ctrl+x Ctrl+s\""), "{text}");
        assert!(text.contains("context = \"editor\""), "{text}");
        assert!(text.contains("label = \"quit\""), "{text}");

        let back: KeyMap<Action> = toml::from_str(&text).expect("parse TOML");
        assert_eq!(back.config().chord_timeout, ms(750));
        assert_eq!(back.len(), 3);
        assert_eq!(back.bindings()[0].label.as_deref(), Some("quit"));
        assert_eq!(back.bindings()[1].priority, Priority::Mode);
        assert_eq!(back.bindings()[1].chord, chord("Ctrl+x Ctrl+s"));
        let editor_back = back.bindings()[2].context.expect("context restored");
        assert_eq!(back.context_name(editor_back), Some("editor"));
        assert_eq!(
            back.lookup(&chord("Enter"), &[editor_back])
                .exact
                .map(|b| &b.action),
            Some(&Action::Newline)
        );
        assert!(
            back.lookup(&chord("Enter"), &[]).is_none(),
            "the context binding stays inactive outside its context"
        );

        let json = serde_json::to_string(&map).expect("serialize to JSON");
        let back_json: KeyMap<Action> = serde_json::from_str(&json).expect("parse JSON");
        assert_eq!(back_json.len(), 3);
        assert_eq!(back_json.bindings()[2].action, Action::Newline);

        let bad =
            "chord_timeout_ms = 500\n\n[[bindings]]\nchord = \"Hyper+q\"\naction = \"Quit\"\n";
        let err = toml::from_str::<KeyMap<Action>>(bad)
            .expect_err("bad chord must fail")
            .to_string();
        assert!(err.contains("binding 0") && err.contains("Hyper"), "{err}");

        let minimal: KeyMap<Action> =
            toml::from_str("[[bindings]]\nchord = \"q\"\naction = \"Quit\"\n")
                .expect("defaults fill in");
        assert_eq!(minimal.config().chord_timeout, ms(DEFAULT_CHORD_TIMEOUT_MS));
        assert_eq!(minimal.bindings()[0].priority, Priority::Global);
    }

    /// Unknown keys in a keymap file are rejected (the typo names itself), and
    /// a bad chord names its binding index.
    #[cfg(feature = "serde")]
    #[test]
    fn toml_rejects_unknown_field_and_bad_chord() {
        #[derive(Debug, Clone, serde::Deserialize)]
        enum Action {
            Quit,
        }

        let unknown_top =
            toml::from_str::<KeyMap<Action>>("chord_timeout_ms = 500\ntypo_field = 3\n")
                .expect_err("an unknown top-level field must be rejected")
                .to_string();
        assert!(unknown_top.contains("typo_field"), "{unknown_top}");

        let unknown_binding = toml::from_str::<KeyMap<Action>>(
            "[[bindings]]\nchord = \"q\"\naction = \"Quit\"\nchrod = \"x\"\n",
        )
        .expect_err("an unknown binding field must be rejected")
        .to_string();
        assert!(unknown_binding.contains("chrod"), "{unknown_binding}");

        let bad_chord = toml::from_str::<KeyMap<Action>>(
            "[[bindings]]\nchord = \"Nope+q\"\naction = \"Quit\"\n",
        )
        .expect_err("a bad chord must be rejected")
        .to_string();
        assert!(
            bad_chord.contains("binding 0") && bad_chord.contains("Nope"),
            "{bad_chord}"
        );
    }

    /// The keymap example embedded in the keybinding policy doc (and shipped as
    /// a fixture) parses into exactly the map it describes, so the docs and the
    /// parser cannot silently drift apart.
    #[cfg(feature = "serde")]
    #[test]
    fn toml_example_in_docs_parses() {
        #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
        enum Action {
            Save,
            Newline,
            Top,
        }

        const EXAMPLE: &str = include_str!("../tests/fixtures/keymap_example.toml");
        let map: KeyMap<Action> =
            toml::from_str(EXAMPLE).expect("documented keymap example must parse");

        assert_eq!(map.config().chord_timeout, ms(750));
        assert_eq!(map.len(), 3);

        let save = &map.bindings()[0];
        assert_eq!(save.action, Action::Save);
        assert_eq!(save.chord, chord("Ctrl+x Ctrl+s"));
        assert_eq!(save.priority, Priority::Mode);
        assert_eq!(save.label.as_deref(), Some("save"));

        let newline = &map.bindings()[1];
        assert_eq!(newline.action, Action::Newline);
        assert_eq!(newline.priority, Priority::Widget);
        let editor = newline.context.expect("editor context restored");
        assert_eq!(map.context_name(editor), Some("editor"));
        assert_eq!(
            map.lookup(&chord("Enter"), &[editor])
                .exact
                .map(|binding| &binding.action),
            Some(&Action::Newline)
        );
        assert!(
            map.lookup(&chord("Enter"), &[]).is_none(),
            "the editor binding stays inactive outside its context"
        );

        assert_eq!(map.bindings()[2].chord, chord("g g"));
        assert_eq!(map.bindings()[2].action, Action::Top);
        let report = map.conflicts();
        assert!(report.is_empty(), "{report}");
    }

    fn arb_code() -> impl Strategy<Value = KeyCode> {
        prop_oneof![
            prop::sample::select(vec![
                'a', 'b', 'q', 'x', 'z', 'A', 'Q', '1', '9', '+', '-', '.', '/', ' ',
            ])
            .prop_map(KeyCode::Char),
            (1u8..=24).prop_map(KeyCode::F),
            prop::sample::select(vec![
                KeyCode::Enter,
                KeyCode::Escape,
                KeyCode::Backspace,
                KeyCode::Tab,
                KeyCode::BackTab,
                KeyCode::Delete,
                KeyCode::Insert,
                KeyCode::Home,
                KeyCode::End,
                KeyCode::PageUp,
                KeyCode::PageDown,
                KeyCode::Up,
                KeyCode::Down,
                KeyCode::Left,
                KeyCode::Right,
                KeyCode::Null,
                KeyCode::MediaPlayPause,
                KeyCode::MediaStop,
                KeyCode::MediaNextTrack,
                KeyCode::MediaPrevTrack,
            ]),
        ]
    }

    fn arb_mods() -> impl Strategy<Value = Modifiers> {
        (0u8..16).prop_map(|bits| {
            let mut modifiers = Modifiers::NONE;
            if bits & 0b0001 != 0 {
                modifiers |= Modifiers::CTRL;
            }
            if bits & 0b0010 != 0 {
                modifiers |= Modifiers::ALT;
            }
            if bits & 0b0100 != 0 {
                modifiers |= Modifiers::SHIFT;
            }
            if bits & 0b1000 != 0 {
                modifiers |= Modifiers::SUPER;
            }
            modifiers
        })
    }

    fn arb_small_chord() -> impl Strategy<Value = Chord> {
        prop::collection::vec(
            prop::sample::select(vec!['a', 'b', 'c', 'd'])
                .prop_map(|c| KeyCombo::key(KeyCode::Char(c))),
            1..=3usize,
        )
        .prop_map(|combos| Chord::new(combos).expect("1..=3 combos is a valid chord"))
    }

    fn arb_key() -> impl Strategy<Value = KeyEvent> {
        let code = prop_oneof![
            Just(KeyCode::Char('a')),
            Just(KeyCode::Char('b')),
            Just(KeyCode::Char('c')),
            Just(KeyCode::Enter),
            Just(KeyCode::Escape),
        ];
        let kind = prop_oneof![
            Just(KeyEventKind::Press),
            Just(KeyEventKind::Repeat),
            Just(KeyEventKind::Release),
        ];
        (code, kind).prop_map(|(code, kind)| KeyEvent {
            code,
            modifiers: Modifiers::NONE,
            kind,
        })
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(1000))]

        /// No key is ever swallowed: every feed yields at least one dispatch,
        /// and draining the timers afterwards never panics or leaks a prefix.
        #[test]
        fn every_fed_key_yields_a_dispatch(
            keys in proptest::collection::vec(arb_key(), 1..20),
            gaps in proptest::collection::vec(0u64..1500, 1..20),
        ) {
            let mut map = KeyMap::new();
            map.bind(chord("a b"), Act::GoTop);
            map.bind(chord("a"), Act::Help);
            map.bind(chord("c c c"), Act::Save);
            map.bind(chord("Enter"), Act::Submit);
            let mut dispatcher = KeyDispatcher::new(map);
            let mut now = Instant::now();
            for (key, gap) in keys.iter().zip(gaps.iter().cycle()) {
                now += ms(*gap);
                let out = dispatcher.feed(key, now);
                prop_assert!(!out.is_empty(), "{key:?} produced nothing");
                let _ = dispatcher.tick(now);
            }
            let _ = dispatcher.tick(now + ms(10_000));
            prop_assert_eq!(dispatcher.pending_prefix(), None);
            let stats = dispatcher.stats();
            prop_assert!(
                stats.dispatched + stats.pending + stats.expired + stats.unbound + stats.esc > 0
            );
        }

        /// `Display` and `FromStr` are inverse over the normalized combo
        /// domain: parsing a combo's own text yields the same combo back.
        #[test]
        fn combo_display_parse_round_trip(code in arb_code(), mods in arb_mods()) {
            let combo = KeyCombo::new(code, mods);
            let text = combo.to_string();
            let parsed: KeyCombo = text
                .parse()
                .unwrap_or_else(|e| panic!("`{text}` did not re-parse: {e}"));
            prop_assert_eq!(parsed, combo, "text = `{}`", text);
        }

        /// An unambiguous lookup never depends on the order bindings were
        /// inserted; only reported conflicts may change a winner.
        #[test]
        fn lookup_is_deterministic_under_shuffle(
            raw in prop::collection::vec((arb_small_chord(), any::<u64>()), 1..12),
            queries in prop::collection::vec(arb_small_chord(), 1..8),
        ) {
            // Keep only the first occurrence of each chord: a duplicate is a
            // reported conflict, not something lookup must resolve by order.
            let mut seen = std::collections::BTreeSet::new();
            let mut entries: Vec<(Chord, u64)> = Vec::new();
            for (ch, key) in raw {
                if seen.insert(ch.to_string()) {
                    entries.push((ch, key));
                }
            }
            let build = |order: &[(Chord, u64)]| {
                let mut map = KeyMap::new();
                for (ch, _) in order {
                    map.bind(ch.clone(), ch.to_string());
                }
                map
            };
            let in_order = build(&entries);
            let mut shuffled = entries.clone();
            shuffled.sort_by_key(|(_, key)| *key);
            let reordered = build(&shuffled);
            for query in &queries {
                let a = in_order.lookup(query, &[]);
                let b = reordered.lookup(query, &[]);
                prop_assert_eq!(
                    a.exact.map(|binding| binding.action.clone()),
                    b.exact.map(|binding| binding.action.clone()),
                    "winner changed for `{}`",
                    query
                );
                prop_assert_eq!(a.longer, b.longer, "longer count changed for `{}`", query);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn now() -> Instant {
        Instant::now()
    }

    fn esc_press() -> KeyEvent {
        KeyEvent::new(KeyCode::Escape)
    }

    fn key_press(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code)
    }

    fn esc_release() -> KeyEvent {
        KeyEvent::new(KeyCode::Escape).with_kind(KeyEventKind::Release)
    }

    const MS_50: Duration = Duration::from_millis(50);
    const MS_100: Duration = Duration::from_millis(100);
    const MS_200: Duration = Duration::from_millis(200);
    const MS_300: Duration = Duration::from_millis(300);

    // --- Basic sequence tests ---

    #[test]
    fn single_esc_returns_pending() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        let output = detector.feed(&esc_press(), t);
        assert_eq!(output, SequenceOutput::Pending);
        assert!(detector.is_pending());
    }

    #[test]
    fn esc_esc_within_timeout() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        detector.feed(&esc_press(), t);
        let output = detector.feed(&esc_press(), t + MS_100);

        assert_eq!(output, SequenceOutput::EscEsc);
        assert!(!detector.is_pending());
    }

    #[test]
    fn esc_esc_at_timeout_boundary() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        detector.feed(&esc_press(), t);
        // Exactly at 250ms boundary
        let output = detector.feed(&esc_press(), t + Duration::from_millis(250));

        assert_eq!(output, SequenceOutput::EscEsc);
    }

    #[test]
    fn esc_esc_past_timeout() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        detector.feed(&esc_press(), t);
        // Past 250ms timeout (251ms)
        let output = detector.feed(&esc_press(), t + Duration::from_millis(251));

        // First Esc timed out, second Esc starts new sequence
        assert_eq!(output, SequenceOutput::Esc);
        assert!(detector.is_pending()); // New sequence started
    }

    #[test]
    fn timeout_check_emits_pending_esc() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        detector.feed(&esc_press(), t);

        // Before timeout
        assert!(detector.check_timeout(t + MS_200).is_none());
        assert!(detector.is_pending());

        // After timeout (251ms)
        let output = detector.check_timeout(t + Duration::from_millis(251));
        assert_eq!(output, Some(SequenceOutput::Esc));
        assert!(!detector.is_pending());
    }

    #[test]
    fn other_key_interrupts_sequence() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        detector.feed(&esc_press(), t);
        let output = detector.feed(&key_press(KeyCode::Char('a')), t + MS_100);

        // Pending Esc is emitted
        assert_eq!(output, SequenceOutput::Esc);
        assert!(!detector.is_pending());
    }

    #[test]
    fn non_esc_key_passes_through() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        let output = detector.feed(&key_press(KeyCode::Char('x')), t);
        assert_eq!(output, SequenceOutput::PassThrough);
    }

    #[test]
    fn release_event_passes_through() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        let output = detector.feed(&esc_release(), t);
        assert_eq!(output, SequenceOutput::PassThrough);
        assert!(!detector.is_pending());
    }

    #[test]
    fn release_during_pending_passes_through() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        detector.feed(&esc_press(), t);
        let output = detector.feed(&esc_release(), t + MS_50);

        // Release is ignored; still pending
        assert_eq!(output, SequenceOutput::PassThrough);
        assert!(detector.is_pending());
    }

    // --- Config tests ---

    #[test]
    fn custom_timeout() {
        let config = SequenceConfig::default().with_timeout(Duration::from_millis(100));
        let mut detector = SequenceDetector::new(config);
        let t = now();

        detector.feed(&esc_press(), t);
        // 150ms is past 100ms timeout
        let output = detector.feed(&esc_press(), t + Duration::from_millis(150));

        assert_eq!(output, SequenceOutput::Esc);
    }

    #[test]
    fn disabled_sequences() {
        let config = SequenceConfig::default().disable_sequences();
        let mut detector = SequenceDetector::new(config);
        let t = now();

        // First Esc immediately emits Esc
        let output = detector.feed(&esc_press(), t);
        assert_eq!(output, SequenceOutput::Esc);
        assert!(!detector.is_pending());

        // Second Esc also immediately emits Esc
        let output = detector.feed(&esc_press(), t + MS_50);
        assert_eq!(output, SequenceOutput::Esc);
    }

    #[test]
    fn disabled_sequences_passthrough() {
        let config = SequenceConfig::default().disable_sequences();
        let mut detector = SequenceDetector::new(config);
        let t = now();

        let output = detector.feed(&key_press(KeyCode::Char('a')), t);
        assert_eq!(output, SequenceOutput::PassThrough);
    }

    #[test]
    fn config_default_values() {
        let config = SequenceConfig::default();
        assert_eq!(config.esc_seq_timeout, Duration::from_millis(250));
        assert_eq!(config.esc_debounce, Duration::from_millis(50));
        assert!(!config.disable_sequences);
    }

    #[test]
    fn config_builder_chain() {
        let config = SequenceConfig::default()
            .with_timeout(Duration::from_millis(300))
            .with_debounce(Duration::from_millis(100))
            .disable_sequences();

        assert_eq!(config.esc_seq_timeout, Duration::from_millis(300));
        assert_eq!(config.esc_debounce, Duration::from_millis(100));
        assert!(config.disable_sequences);
    }

    // --- Reset tests ---

    #[test]
    fn reset_clears_pending() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        detector.feed(&esc_press(), t);
        assert!(detector.is_pending());

        detector.reset();
        assert!(!detector.is_pending());

        // After reset, new Esc starts fresh
        let output = detector.feed(&esc_press(), t + MS_100);
        assert_eq!(output, SequenceOutput::Pending);
    }

    #[test]
    fn reset_discards_pending_esc() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        detector.feed(&esc_press(), t);
        detector.reset();

        // Timeout check should not emit anything
        assert!(detector.check_timeout(t + MS_300).is_none());
    }

    // --- Edge cases ---

    #[test]
    fn rapid_triple_esc() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        // First Esc
        let out1 = detector.feed(&esc_press(), t);
        assert_eq!(out1, SequenceOutput::Pending);

        // Second Esc -> EscEsc
        let out2 = detector.feed(&esc_press(), t + MS_50);
        assert_eq!(out2, SequenceOutput::EscEsc);

        // Third Esc -> starts new sequence
        let out3 = detector.feed(&esc_press(), t + MS_100);
        assert_eq!(out3, SequenceOutput::Pending);
    }

    #[test]
    fn alternating_esc_and_key() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        // Esc -> pending
        detector.feed(&esc_press(), t);

        // 'a' -> emits Esc
        let out1 = detector.feed(&key_press(KeyCode::Char('a')), t + MS_50);
        assert_eq!(out1, SequenceOutput::Esc);

        // Esc -> pending again
        let out2 = detector.feed(&esc_press(), t + MS_100);
        assert_eq!(out2, SequenceOutput::Pending);

        // 'b' -> emits Esc
        let out3 = detector.feed(&key_press(KeyCode::Char('b')), t + MS_200);
        assert_eq!(out3, SequenceOutput::Esc);
    }

    #[test]
    fn enter_key_interrupts() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        detector.feed(&esc_press(), t);
        let output = detector.feed(&key_press(KeyCode::Enter), t + MS_100);

        assert_eq!(output, SequenceOutput::Esc);
    }

    #[test]
    fn function_key_interrupts() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        detector.feed(&esc_press(), t);
        let output = detector.feed(&key_press(KeyCode::F(1)), t + MS_100);

        assert_eq!(output, SequenceOutput::Esc);
    }

    #[test]
    fn arrow_key_interrupts() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        detector.feed(&esc_press(), t);
        let output = detector.feed(&key_press(KeyCode::Up), t + MS_100);

        assert_eq!(output, SequenceOutput::Esc);
    }

    #[test]
    fn config_getter_and_setter() {
        let mut detector = SequenceDetector::with_defaults();
        assert_eq!(
            detector.config().esc_seq_timeout,
            Duration::from_millis(250)
        );

        let new_config = SequenceConfig::default().with_timeout(Duration::from_millis(500));
        detector.set_config(new_config);

        assert_eq!(
            detector.config().esc_seq_timeout,
            Duration::from_millis(500)
        );
    }

    #[test]
    fn set_config_preserves_pending_state() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        detector.feed(&esc_press(), t);
        assert!(detector.is_pending());

        // Change config while pending
        detector.set_config(SequenceConfig::default().with_timeout(Duration::from_millis(500)));

        // Still pending
        assert!(detector.is_pending());

        // New timeout applies
        let output = detector.feed(&esc_press(), t + MS_300);
        assert_eq!(output, SequenceOutput::EscEsc); // Within new 500ms timeout
    }

    #[test]
    fn debug_format() {
        let detector = SequenceDetector::with_defaults();
        let dbg = format!("{:?}", detector);
        assert!(dbg.contains("SequenceDetector"));
    }

    #[test]
    fn config_debug_format() {
        let config = SequenceConfig::default();
        let dbg = format!("{:?}", config);
        assert!(dbg.contains("SequenceConfig"));
    }

    #[test]
    fn output_debug_and_eq() {
        assert_eq!(SequenceOutput::Pending, SequenceOutput::Pending);
        assert_eq!(SequenceOutput::Esc, SequenceOutput::Esc);
        assert_eq!(SequenceOutput::EscEsc, SequenceOutput::EscEsc);
        assert_eq!(SequenceOutput::PassThrough, SequenceOutput::PassThrough);
        assert_ne!(SequenceOutput::Esc, SequenceOutput::EscEsc);

        let dbg = format!("{:?}", SequenceOutput::EscEsc);
        assert!(dbg.contains("EscEsc"));
    }

    // --- Stress / property-like tests ---

    #[test]
    fn no_stuck_state() {
        let mut detector = SequenceDetector::with_defaults();
        let t = now();

        // Many operations should always return to Idle eventually
        for i in 0..100 {
            let offset = Duration::from_millis(i * 10);
            if i % 3 == 0 {
                detector.feed(&esc_press(), t + offset);
            } else {
                detector.feed(&key_press(KeyCode::Char('x')), t + offset);
            }
        }

        // Force timeout check - must be well past the last event (990ms) + timeout (250ms)
        detector.check_timeout(t + Duration::from_secs(2));

        // Should be idle
        assert!(!detector.is_pending());
    }

    #[test]
    fn deterministic_output() {
        // Same inputs should produce same outputs
        let config = SequenceConfig::default();
        let t = now();

        let mut d1 = SequenceDetector::new(config.clone());
        let mut d2 = SequenceDetector::new(config);

        let events = [
            (esc_press(), t),
            (esc_press(), t + MS_100),
            (key_press(KeyCode::Char('a')), t + MS_200),
            (esc_press(), t + MS_300),
        ];

        for (event, time) in &events {
            let out1 = d1.feed(event, *time);
            let out2 = d2.feed(event, *time);
            assert_eq!(out1, out2);
        }
    }

    // =========================================================================
    // ActionMapper Tests
    // =========================================================================

    mod action_mapper_tests {
        use super::*;
        use crate::event::Modifiers;

        fn ctrl_c() -> KeyEvent {
            KeyEvent::new(KeyCode::Char('c')).with_modifiers(Modifiers::CTRL)
        }

        fn ctrl_d() -> KeyEvent {
            KeyEvent::new(KeyCode::Char('d')).with_modifiers(Modifiers::CTRL)
        }

        fn ctrl_q() -> KeyEvent {
            KeyEvent::new(KeyCode::Char('q')).with_modifiers(Modifiers::CTRL)
        }

        fn idle_state() -> AppState {
            AppState::default()
        }

        fn input_state() -> AppState {
            AppState::new().with_input(true)
        }

        fn task_state() -> AppState {
            AppState::new().with_task(true)
        }

        fn modal_state() -> AppState {
            AppState::new().with_modal(true)
        }

        fn overlay_state() -> AppState {
            AppState::new().with_overlay(true)
        }

        // --- Ctrl+C tests (policy priorities 2-5) ---

        #[test]
        fn test_ctrl_c_clears_nonempty_input() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            let action = mapper.map(&ctrl_c(), &input_state(), t);
            assert_eq!(action, Some(Action::ClearInput));
        }

        #[test]
        fn test_ctrl_c_cancels_running_task() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            let action = mapper.map(&ctrl_c(), &task_state(), t);
            assert_eq!(action, Some(Action::CancelTask));
        }

        #[test]
        fn test_ctrl_c_quits_when_idle() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            let action = mapper.map(&ctrl_c(), &idle_state(), t);
            assert_eq!(action, Some(Action::Quit));
        }

        #[test]
        fn test_ctrl_c_dismisses_modal() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            let action = mapper.map(&ctrl_c(), &modal_state(), t);
            assert_eq!(action, Some(Action::DismissModal));
        }

        #[test]
        fn test_ctrl_c_modal_priority_over_input() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            // Both modal and input are set
            let state = AppState::new().with_modal(true).with_input(true);
            let action = mapper.map(&ctrl_c(), &state, t);
            assert_eq!(action, Some(Action::DismissModal));
        }

        #[test]
        fn test_ctrl_c_input_priority_over_task() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            let state = AppState::new().with_input(true).with_task(true);
            let action = mapper.map(&ctrl_c(), &state, t);
            assert_eq!(action, Some(Action::ClearInput));
        }

        #[test]
        fn test_ctrl_c_idle_config_noop() {
            let config = ActionConfig::default().with_ctrl_c_idle(CtrlCIdleAction::Noop);
            let mut mapper = ActionMapper::new(config);
            let t = now();

            let action = mapper.map(&ctrl_c(), &idle_state(), t);
            assert_eq!(action, None); // Noop returns None
        }

        #[test]
        fn test_ctrl_c_idle_config_bell() {
            let config = ActionConfig::default().with_ctrl_c_idle(CtrlCIdleAction::Bell);
            let mut mapper = ActionMapper::new(config);
            let t = now();

            let action = mapper.map(&ctrl_c(), &idle_state(), t);
            assert_eq!(action, Some(Action::Bell));
        }

        // --- Ctrl+D and Ctrl+Q tests (policy priorities 10-11) ---

        #[test]
        fn test_ctrl_d_soft_quit() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            let action = mapper.map(&ctrl_d(), &idle_state(), t);
            assert_eq!(action, Some(Action::SoftQuit));
        }

        #[test]
        fn test_ctrl_d_ignores_state() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            // Ctrl+D always does SoftQuit regardless of state
            let action = mapper.map(&ctrl_d(), &modal_state(), t);
            assert_eq!(action, Some(Action::SoftQuit));

            let action = mapper.map(&ctrl_d(), &input_state(), t);
            assert_eq!(action, Some(Action::SoftQuit));
        }

        #[test]
        fn test_ctrl_q_hard_quit() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            let action = mapper.map(&ctrl_q(), &idle_state(), t);
            assert_eq!(action, Some(Action::HardQuit));
        }

        #[test]
        fn test_ctrl_q_ignores_state() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            // Ctrl+Q always does HardQuit regardless of state
            let action = mapper.map(&ctrl_q(), &modal_state(), t);
            assert_eq!(action, Some(Action::HardQuit));
        }

        // --- Esc tests (policy priorities 1, 6-8) ---

        #[test]
        fn test_esc_dismisses_modal() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            // First Esc: pending
            let action1 = mapper.map(&esc_press(), &modal_state(), t);
            assert_eq!(action1, None);

            // Timeout: emit Esc action
            let action2 = mapper.check_timeout(&modal_state(), t + MS_300);
            assert_eq!(action2, Some(Action::DismissModal));
        }

        #[test]
        fn test_esc_clears_input_no_modal() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            mapper.map(&esc_press(), &input_state(), t);
            let action = mapper.check_timeout(&input_state(), t + MS_300);
            assert_eq!(action, Some(Action::ClearInput));
        }

        #[test]
        fn test_esc_cancels_task_empty_input() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            mapper.map(&esc_press(), &task_state(), t);
            let action = mapper.check_timeout(&task_state(), t + MS_300);
            assert_eq!(action, Some(Action::CancelTask));
        }

        #[test]
        fn test_esc_closes_overlay() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            mapper.map(&esc_press(), &overlay_state(), t);
            let action = mapper.check_timeout(&overlay_state(), t + MS_300);
            assert_eq!(action, Some(Action::CloseOverlay));
        }

        #[test]
        fn test_esc_modal_priority_over_overlay() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            let state = AppState::new().with_modal(true).with_overlay(true);
            mapper.map(&esc_press(), &state, t);
            let action = mapper.check_timeout(&state, t + MS_300);
            assert_eq!(action, Some(Action::DismissModal));
        }

        #[test]
        fn test_esc_passthrough_when_idle() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            mapper.map(&esc_press(), &idle_state(), t);
            let action = mapper.check_timeout(&idle_state(), t + MS_300);
            assert_eq!(action, Some(Action::PassThrough));
        }

        // --- Esc Esc tests (policy priority 9) ---

        #[test]
        fn test_esc_esc_within_timeout() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            mapper.map(&esc_press(), &idle_state(), t);
            let action = mapper.map(&esc_press(), &idle_state(), t + MS_100);
            assert_eq!(action, Some(Action::ToggleTreeView));
        }

        #[test]
        fn test_esc_esc_ignores_state() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            // Esc Esc always toggles tree view regardless of state
            mapper.map(&esc_press(), &modal_state(), t);
            let action = mapper.map(&esc_press(), &modal_state(), t + MS_100);
            assert_eq!(action, Some(Action::ToggleTreeView));
        }

        #[test]
        fn test_esc_esc_timeout_expired() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            mapper.map(&esc_press(), &input_state(), t);
            // Past 250ms timeout
            let action = mapper.map(&esc_press(), &input_state(), t + MS_300);

            // First Esc timed out -> ClearInput, second starts new pending
            assert_eq!(action, Some(Action::ClearInput));
            assert!(mapper.is_pending_esc());
        }

        // --- Esc then other key ---

        #[test]
        fn test_esc_then_other_key() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            mapper.map(&esc_press(), &input_state(), t);
            let action = mapper.map(&key_press(KeyCode::Char('a')), &input_state(), t + MS_50);

            // Pending Esc is emitted
            assert_eq!(action, Some(Action::ClearInput));
        }

        // --- Other keys passthrough ---

        #[test]
        fn test_regular_key_passthrough() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            let action = mapper.map(&key_press(KeyCode::Char('x')), &idle_state(), t);
            assert_eq!(action, Some(Action::PassThrough));
        }

        #[test]
        fn test_release_event_passthrough() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            let release = KeyEvent::new(KeyCode::Char('x')).with_kind(KeyEventKind::Release);
            let action = mapper.map(&release, &idle_state(), t);
            assert_eq!(action, Some(Action::PassThrough));
        }

        // --- State helper tests ---

        #[test]
        fn test_app_state_builders() {
            let state = AppState::new()
                .with_input(true)
                .with_task(true)
                .with_modal(true)
                .with_overlay(true);

            assert!(state.input_nonempty);
            assert!(state.task_running);
            assert!(state.modal_open);
            assert!(state.view_overlay);
            assert!(!state.is_idle());
        }

        #[test]
        fn test_app_state_is_idle() {
            assert!(AppState::default().is_idle());
            assert!(!AppState::new().with_input(true).is_idle());
            assert!(!AppState::new().with_task(true).is_idle());
            assert!(!AppState::new().with_modal(true).is_idle());
            // view_overlay doesn't affect is_idle
            assert!(AppState::new().with_overlay(true).is_idle());
        }

        // --- Action enum tests ---

        #[test]
        fn test_action_consumes_event() {
            assert!(Action::ClearInput.consumes_event());
            assert!(Action::CancelTask.consumes_event());
            assert!(Action::Quit.consumes_event());
            assert!(!Action::PassThrough.consumes_event());
        }

        #[test]
        fn test_action_is_quit() {
            assert!(Action::Quit.is_quit());
            assert!(Action::SoftQuit.is_quit());
            assert!(Action::HardQuit.is_quit());
            assert!(!Action::ClearInput.is_quit());
            assert!(!Action::PassThrough.is_quit());
        }

        // --- Config tests ---

        #[test]
        fn test_ctrl_c_idle_action_from_str() {
            assert_eq!(
                CtrlCIdleAction::from_str_opt("quit"),
                Some(CtrlCIdleAction::Quit)
            );
            assert_eq!(
                CtrlCIdleAction::from_str_opt("QUIT"),
                Some(CtrlCIdleAction::Quit)
            );
            assert_eq!(
                CtrlCIdleAction::from_str_opt("noop"),
                Some(CtrlCIdleAction::Noop)
            );
            assert_eq!(
                CtrlCIdleAction::from_str_opt("none"),
                Some(CtrlCIdleAction::Noop)
            );
            assert_eq!(
                CtrlCIdleAction::from_str_opt("ignore"),
                Some(CtrlCIdleAction::Noop)
            );
            assert_eq!(
                CtrlCIdleAction::from_str_opt("bell"),
                Some(CtrlCIdleAction::Bell)
            );
            assert_eq!(
                CtrlCIdleAction::from_str_opt("beep"),
                Some(CtrlCIdleAction::Bell)
            );
            assert_eq!(CtrlCIdleAction::from_str_opt("invalid"), None);
        }

        #[test]
        fn test_ctrl_c_idle_action_to_action() {
            assert_eq!(CtrlCIdleAction::Quit.to_action(), Some(Action::Quit));
            assert_eq!(CtrlCIdleAction::Noop.to_action(), None);
            assert_eq!(CtrlCIdleAction::Bell.to_action(), Some(Action::Bell));
        }

        #[test]
        fn test_action_config_builder() {
            let config = ActionConfig::default()
                .with_sequence_config(SequenceConfig::default().with_timeout(MS_100))
                .with_ctrl_c_idle(CtrlCIdleAction::Bell);

            assert_eq!(config.sequence_config.esc_seq_timeout, MS_100);
            assert_eq!(config.ctrl_c_idle_action, CtrlCIdleAction::Bell);
        }

        // --- Reset tests ---

        #[test]
        fn test_mapper_reset() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            mapper.map(&esc_press(), &idle_state(), t);
            assert!(mapper.is_pending_esc());

            mapper.reset();
            assert!(!mapper.is_pending_esc());
        }

        // --- Determinism / property tests ---

        #[test]
        fn test_deterministic_action_mapping() {
            let t = now();

            let mut m1 = ActionMapper::with_defaults();
            let mut m2 = ActionMapper::with_defaults();

            let events = [
                (ctrl_c(), input_state()),
                (ctrl_d(), modal_state()),
                (ctrl_q(), idle_state()),
            ];

            for (event, state) in &events {
                let a1 = m1.map(event, state, t);
                let a2 = m2.map(event, state, t);
                assert_eq!(a1, a2);
            }
        }

        #[test]
        fn test_uppercase_ctrl_keys() {
            let mut mapper = ActionMapper::with_defaults();
            let t = now();

            // Ctrl+C with uppercase 'C' should also work
            let ctrl_c_upper = KeyEvent::new(KeyCode::Char('C')).with_modifiers(Modifiers::CTRL);
            let action = mapper.map(&ctrl_c_upper, &idle_state(), t);
            assert_eq!(action, Some(Action::Quit));
        }

        // --- Validation tests ---

        #[test]
        fn test_sequence_config_validation_clamps_high_timeout() {
            let config = SequenceConfig::default()
                .with_timeout(Duration::from_millis(1000)) // Too high
                .validated();

            // Should clamp to MAX_ESC_SEQ_TIMEOUT_MS (400ms)
            assert_eq!(config.esc_seq_timeout.as_millis(), 400);
        }

        #[test]
        fn test_sequence_config_validation_clamps_low_timeout() {
            let config = SequenceConfig::default()
                .with_timeout(Duration::from_millis(50)) // Too low
                .validated();

            // Should clamp to MIN_ESC_SEQ_TIMEOUT_MS (150ms)
            assert_eq!(config.esc_seq_timeout.as_millis(), 150);
        }

        #[test]
        fn test_sequence_config_validation_clamps_high_debounce() {
            let config = SequenceConfig::default()
                .with_debounce(Duration::from_millis(200)) // Too high
                .validated();

            // Should clamp to MAX_ESC_DEBOUNCE_MS (100ms)
            assert_eq!(config.esc_debounce.as_millis(), 100);
        }

        #[test]
        fn test_sequence_config_validation_debounce_not_exceeds_timeout() {
            let config = SequenceConfig::default()
                .with_timeout(Duration::from_millis(150))
                .with_debounce(Duration::from_millis(200)) // Higher than timeout
                .validated();

            // Debounce should be clamped to min(100, 150) = 100,
            // but also can't exceed timeout (150)
            // Since debounce max is 100 and timeout is 150, debounce = 100
            assert!(config.esc_debounce <= config.esc_seq_timeout);
        }

        #[test]
        fn test_sequence_config_is_valid() {
            assert!(SequenceConfig::default().is_valid());

            // Invalid: timeout too high
            let invalid = SequenceConfig::default().with_timeout(Duration::from_millis(500));
            assert!(!invalid.is_valid());

            // Valid after validation
            assert!(invalid.validated().is_valid());
        }

        #[test]
        fn test_sequence_config_constants() {
            // Verify constants match spec
            assert_eq!(DEFAULT_ESC_SEQ_TIMEOUT_MS, 250);
            assert_eq!(MIN_ESC_SEQ_TIMEOUT_MS, 150);
            assert_eq!(MAX_ESC_SEQ_TIMEOUT_MS, 400);
            assert_eq!(DEFAULT_ESC_DEBOUNCE_MS, 50);
            assert_eq!(MIN_ESC_DEBOUNCE_MS, 0);
            assert_eq!(MAX_ESC_DEBOUNCE_MS, 100);
        }

        #[test]
        fn test_action_config_validated() {
            let config = ActionConfig::default()
                .with_sequence_config(
                    SequenceConfig::default().with_timeout(Duration::from_millis(1000)),
                )
                .validated();

            // Sequence config should be validated
            assert_eq!(config.sequence_config.esc_seq_timeout.as_millis(), 400);
        }
    }
}