ghast-inventory 0.4.8

Inventory and container windows for the ghast Minecraft Java Edition client library: vanilla client-side click prediction, the window confirm protocol, hashed 26.1 clicks and lazy NBT / data-component item stacks (1.8.9, 1.12.2, 1.16.5, 26.1 and 26.2)
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
//! The inventory state machine: what the vanilla client holds (player inventory, cursor, the
//! open window), fed by the server's window packets, plus click intents with vanilla's
//! prediction and the window confirm ("transaction") protocol.

use bytestring::ByteString;

use crate::crafting::RecipeBook;
use crate::rules::{Version, VersionNotEnabled};
use crate::sim::{Layout, Loc, Model, OUTSIDE, Screen, Sim};
use crate::stack::Stack;

/// Whether `l` is a crafting grid slot of the layout's screen.
fn is_grid(lay: Layout, l: Loc) -> bool {
    match (lay.screen, l) {
        (Screen::Player, Loc::Craft(_)) => true,
        (Screen::Container(WindowKind::Crafting), Loc::Container(k)) => (1..=9).contains(&k),
        _ => false,
    }
}
use crate::window::{SlotKind, WindowKind};

/// Version tags for loops monomorphised per version ([`Inventory::on_window_items`]).
const V18: u8 = 0;
const V112: u8 = 1;
const V1165: u8 = 2;
const V261: u8 = 3;
const V262: u8 = 4;

/// One incoming `window_items` slot: [`Incoming::settle`] stores it (normalised and clamped
/// like vanilla's handler) and says whether the slot changed.
trait Incoming {
    fn settle<const V: u8>(self, slot: &mut Option<Stack>, clamp: bool) -> bool;
}

impl Incoming for Option<Stack> {
    #[inline(always)]
    fn settle<const V: u8>(self, slot: &mut Option<Stack>, clamp: bool) -> bool {
        let s = normalize_as::<V>(self);
        let s = if clamp { clamp_as::<V>(s) } else { s };
        if same_slot(slot, &s) {
            false
        } else {
            *slot = s;
            true
        }
    }
}

#[cfg(any(feature = "v1_8", feature = "v1_12"))]
impl Incoming for &ghast_protocol::types::slot::legacy::Slot {
    #[inline(always)]
    fn settle<const V: u8>(self, slot: &mut Option<Stack>, clamp: bool) -> bool {
        if legacy_same::<V>(slot, self, clamp) {
            return false;
        }
        crate::stack::from_legacy_slot(self.clone()).settle::<V>(slot, clamp);
        true
    }
}

/// Whether `stored` equals the 1.8 / 1.12 wire slot `w` after normalising and clamping, i.e.
/// what [`Incoming::settle`] of the converted slot would compare.
#[cfg(any(feature = "v1_8", feature = "v1_12"))]
#[inline(always)]
fn legacy_same<const V: u8>(
    stored: &Option<Stack>,
    w: &ghast_protocol::types::slot::legacy::Slot,
    clamp: bool,
) -> bool {
    let Some(ws) = &w.0 else {
        return stored.is_none();
    };
    let id = i32::from(ws.id);
    let mut count = i32::from(ws.count);
    if V != V18 && (count <= 0 || id == 0) {
        return stored.is_none();
    }
    if V == V261 || V == V262 || V == V1165 {
        // legacy slots never reach these versions (see `on_window_items_legacy`)
        return false;
    }
    if clamp && count > 64 {
        count = 64;
    }
    let Some(st) = stored else {
        return false;
    };
    st.id == id
        && st.count == count
        && st.damage == ws.damage
        && match (&st.data, &ws.nbt) {
            (crate::stack::ItemData::None, None) => true,
            (crate::stack::ItemData::Nbt(a), Some(b)) => a == b,
            _ => false,
        }
}

/// [`Inventory::normalize`] with the version as a constant.
#[inline(always)]
fn normalize_as<const V: u8>(s: Option<Stack>) -> Option<Stack> {
    if V == V18 {
        return s;
    }
    let mut s = s.filter(|s| s.count > 0 && s.id != 0);
    if V != V112
        && let Some(st) = &mut s
    {
        st.damage = 0;
    }
    s
}

/// [`crate::sim::clamp_v`] with the version as a constant.
#[inline(always)]
fn clamp_as<const V: u8>(mut s: Option<Stack>) -> Option<Stack> {
    if V == V261 {
        crate::sim::clamp_v(Version::V26_1, &mut s);
    } else if V == V262 {
        crate::sim::clamp_v(Version::V26_2, &mut s);
    } else {
        crate::sim::clamp(&mut s);
    }
    s
}

/// `a == b` for slots, written out so the common equal-NBT case stays a few compares and one
/// `memcmp` whatever variants `ItemData` has.
#[inline(always)]
fn same_slot(a: &Option<Stack>, b: &Option<Stack>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => {
            a.id == b.id && a.count == b.count && a.damage == b.damage && a.data == b.data
        }
        _ => false,
    }
}

/// The `Window::menu` of a 26.1 mount screen (`horse_screen_open`; not a `minecraft:menu` id).
#[cfg(modern)]
const MOUNT_MENU: i32 = 1000;

/// 26.1: ticks without a correcting container packet after which a click counts as accepted
/// (see [`Inventory::set_click_settle_ticks`]).
pub const DEFAULT_CLICK_SETTLE_TICKS: u32 = 4;

/// Ticks a click may wait for its confirm before it is given up ([`ClickOutcome::TimedOut`]).
pub const DEFAULT_CLICK_TIMEOUT_TICKS: u32 = 40;

/// A click intent: the vanilla GUI gestures a bot needs. Slot numbers are the open screen's
/// (window 0 when only the player inventory is open); [`OUTSIDE`] (-999) is a click outside the
/// window.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Click {
    /// Mode 0: left click (`right = false`: pick up / put down / swap the whole stack) or right
    /// click (pick up half / put down one). On [`OUTSIDE`] it drops the cursor stack (left) or
    /// one item of it (right).
    Pickup {
        /// Slot, or [`OUTSIDE`].
        slot: i16,
        /// Right mouse button.
        right: bool,
    },
    /// Mode 1: shift-click (move the stack to the other part of the window).
    QuickMove {
        /// Slot.
        slot: i16,
        /// Right mouse button (same effect).
        right: bool,
    },
    /// Mode 2: number key over a slot: swap it with hotbar slot `hotbar` (0..=8), or on 1.16.5
    /// `40` (the swap-hands key) with the offhand.
    Swap {
        /// Slot.
        slot: i16,
        /// Hotbar index 0..=8, or 40 (offhand, 1.16.5 only).
        hotbar: u8,
    },
    /// Mode 4: drop key over a slot (`all = false`: one item, Q; `all = true`: the stack,
    /// ctrl+Q). With an empty cursor and [`OUTSIDE`] this is what the vanilla GUI sends for a
    /// click outside the window (no effect).
    Drop {
        /// Slot, or [`OUTSIDE`].
        slot: i16,
        /// Whole stack.
        all: bool,
    },
    /// Mode 6: double click: gather items like the cursor stack into it.
    PickupAll {
        /// Slot (normally the now empty slot the stack was picked up from).
        slot: i16,
    },
    /// Mode 3: middle click in creative mode: a full stack of the slot's item onto the empty
    /// cursor (26.1; no effect outside creative mode).
    Clone {
        /// Slot.
        slot: i16,
    },
    /// Mode 5: one packet of a drag ("quick craft"): the GUI sends [`DragStage::Start`] (slot
    /// [`OUTSIDE`]), one [`DragStage::Slot`] per slot the mouse crosses, then
    /// [`DragStage::End`] (slot [`OUTSIDE`]), each its own click (26.1).
    QuickCraft {
        /// Slot ([`OUTSIDE`] for start and end).
        slot: i16,
        /// Which packet of the drag.
        stage: DragStage,
        /// How the carried stack is spread.
        kind: DragKind,
    },
}

/// The packet of a drag ([`Click::QuickCraft`]): vanilla's quick-craft header.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DragStage {
    /// Mouse pressed over the screen (header 0).
    Start,
    /// The mouse crossed a slot (header 1).
    Slot,
    /// Mouse released: the stack is spread (header 2).
    End,
}

/// How a drag spreads the carried stack ([`Click::QuickCraft`]): vanilla's quick-craft type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DragKind {
    /// Left button: split evenly (type 0).
    Split,
    /// Right button: one item per slot (type 1).
    One,
    /// Middle button, creative mode: a full stack per slot (type 2).
    Clone,
}

impl Click {
    /// The wire `(slot, button, mode)`.
    #[must_use]
    pub fn wire(self) -> (i16, u8, u8) {
        match self {
            Click::Pickup { slot, right } => (slot, u8::from(right), 0),
            Click::QuickMove { slot, right } => (slot, u8::from(right), 1),
            Click::Swap { slot, hotbar } => (slot, hotbar, 2),
            Click::Drop { slot, all } => (slot, u8::from(all), 4),
            Click::PickupAll { slot } => (slot, 0, 6),
            Click::Clone { slot } => (slot, 2, 3),
            Click::QuickCraft { slot, stage, kind } => {
                let header = match stage {
                    DragStage::Start => 0,
                    DragStage::Slot => 1,
                    DragStage::End => 2,
                };
                let ty = match kind {
                    DragKind::Split => 0,
                    DragKind::One => 1,
                    DragKind::Clone => 2,
                };
                (slot, header | ty << 2, 5)
            }
        }
    }
}

/// Why a click (or open / close) was refused. Nothing was sent and nothing changed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ClickError {
    /// The previous click's confirm has not arrived yet (one click in flight).
    Pending,
    /// The server rejected a click and its full window resync has not arrived yet.
    Resyncing,
    /// Nothing is open: open the player inventory ([`Inventory::open_inventory`]) or wait for a
    /// container window.
    NoScreen,
    /// A container window is open (the player inventory cannot be opened over it).
    WindowOpen,
    /// Same-tick packet order vanilla never produces (and Grim's PacketOrder checks flag): a
    /// second click this tick, a click / close in the tick the inventory was opened, or the
    /// other way round. Retry next tick.
    SameTick,
    /// The slot does not exist in the open screen (or `OUTSIDE` where not allowed).
    InvalidSlot,
    /// Invalid hotbar index for [`Click::Swap`].
    InvalidButton,
    /// The result depends on data ghast does not model (recipes, fuel, brewing, trading,
    /// enchanting, an unknown crafting result); sending it would desynchronise the inventory.
    Unpredictable,
}

impl std::fmt::Display for ClickError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            ClickError::Pending => "a click is waiting for its confirm",
            ClickError::Resyncing => "waiting for the window resync after a rejected click",
            ClickError::NoScreen => "no inventory screen is open",
            ClickError::WindowOpen => "a container window is open",
            ClickError::SameTick => "not allowed in the same tick",
            ClickError::InvalidSlot => "invalid slot",
            ClickError::InvalidButton => "invalid button",
            ClickError::Unpredictable => "click outcome cannot be predicted",
        })
    }
}

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

/// A window click as sent (`window_click`; 1.8 `ClickWindowC2SPacket`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ClickPacket {
    /// Window id (0 = player inventory).
    pub window_id: u8,
    /// Slot, or -999.
    pub slot: i16,
    /// Mouse button / hotbar key.
    pub button: u8,
    /// Click mode.
    pub mode: u8,
    /// Action number: the window's counter, incremented before each click.
    pub action: i16,
    /// What vanilla's `onSlotClick` returned (the server compares it with its own result).
    pub item: Option<Stack>,
    /// 1.16.5: arm swings (main hand) to send before the click: the client's
    /// `PlayerEntity.dropItem` swings for each stack the click drops (a throw, a click
    /// outside with a carried stack); 0 on the other versions.
    pub swings: u8,
}

/// A packet the inventory wants sent. Write it right away, in call order (before the tick's
/// movement packet when it comes from a behaviour action).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Outgoing {
    /// `window_click`.
    Click(ClickPacket),
    /// `transaction` answer to a rejected confirm (always `accepted = true`, like vanilla).
    Confirm {
        /// Window id as received.
        window_id: i8,
        /// Action number as received.
        action: i16,
    },
    /// `close_window` with this id (0 = player inventory).
    CloseWindow(u8),
    /// 1.8 only: `client_command` "open inventory achievement" (vanilla sends it when E opens
    /// the inventory).
    OpenInventory,
    /// 26.1 `container_click` (no confirm exists: the server applies every click and resends
    /// the slots whose hashes differ from its own result).
    ContainerClick(ContainerClick),
    /// 26.1 creative inventory screen (window 0 in creative mode): the packets the real
    /// client sends, in order (often none). See [`CreativePacket`].
    Creative(Vec<CreativePacket>),
    /// 26.1 `rename_item`: the anvil's name field ([`Inventory::anvil_rename_modern`]).
    RenameItem(String),
    /// 26.1 `container_button_click` (a loom pattern: [`Inventory::select_loom_pattern_modern`]).
    ButtonClick {
        /// Container id.
        window_id: i32,
        /// Button id.
        button: i32,
    },
    /// 26.1 `select_trade` ([`Inventory::select_trade_modern`]).
    SelectTrade(i32),
    /// 1.16.5 `arm_animation` (main hand) outside a click: the client dropped a carried stack
    /// (`PlayerEntity.dropItem` swings), e.g. when a server window replaced the open screen.
    Swing,
}

/// One packet the 26.1 creative inventory screen sends (`Outgoing::Creative`): the server
/// trusts these stacks, so they are exactly what the real client sends.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CreativePacket {
    /// `swing` (main hand): a stack was dropped.
    Swing,
    /// `set_creative_mode_slot`: window 0 slot `slot` now holds `item` (`slot` -1: `item` is
    /// dropped).
    SetSlot {
        /// Window 0 slot, or -1 for a drop.
        slot: i16,
        /// The stack.
        item: Option<Stack>,
    },
}

/// A 26.1 click as sent: what vanilla `MultiPlayerGameMode.handleContainerInput` writes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ContainerClick {
    /// Container id (0 = player inventory).
    pub window_id: i32,
    /// The screen's state id (from the last `container_set_content` / `container_set_slot`).
    pub state_id: i32,
    /// Slot, or -999.
    pub slot: i16,
    /// Mouse button / hotbar key.
    pub button: u8,
    /// Click mode (`ContainerInput`).
    pub mode: u8,
    /// Slots whose stack the prediction changed, with the new stack (vanilla compares every slot
    /// before and after the simulated click).
    pub changed: Vec<(i16, Option<Stack>)>,
    /// The cursor after the click.
    pub carried: Option<Stack>,
    /// `false` when ghast could not predict this click (see [`Inventory::click`]): nothing
    /// changed locally, `changed` is empty, and the server's corrections bring the result.
    pub predicted: bool,
    /// ghast's own number for the click (per screen, like the legacy action number, but never
    /// sent): the [`ClickResult::action`] that resolves it.
    pub action: i16,
    /// How many `swing` (main hand) packets the vanilla client sends right before this click:
    /// every stack the click drops (outside the window, the drop key, a remainder that does not
    /// fit) swings the arm. Send them first, then the click (0 when unpredicted).
    pub swings: u8,
}

/// What became of a click.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ClickOutcome {
    /// The server agreed with the prediction.
    Accepted,
    /// The server disagreed; it resends the window (the inventory waits for it).
    Rejected,
    /// No confirm within the timeout (the server may not have had that window open).
    TimedOut,
}

/// A finished click.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ClickResult {
    /// Window id the click was sent for.
    pub window_id: i32,
    /// Its action number.
    pub action: i16,
    /// The outcome.
    pub outcome: ClickOutcome,
}

impl ClickResult {
    /// A result as [`Inventory::drain_events`] reports it (for tests and replays).
    #[must_use]
    pub fn new(window_id: i32, action: i16, outcome: ClickOutcome) -> ClickResult {
        ClickResult {
            window_id,
            action,
            outcome,
        }
    }
}

/// Changes since the last [`Inventory::drain_events`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Events {
    /// Something in the player's inventory (window 0, incl. crafting grid) changed.
    pub player_changed: bool,
    /// Something in the open window's own slots changed.
    pub window_changed: bool,
    /// The cursor stack changed.
    pub cursor_changed: bool,
    /// The server opened a window (its id).
    pub opened: Option<i32>,
    /// The open window was closed by the server.
    pub closed: bool,
    /// Clicks that were confirmed, rejected or timed out, in order.
    pub clicks: Vec<ClickResult>,
    /// The server sent the full contents of window 0 (`window_items` / 26.x
    /// `container_set_content` for the player inventory): every slot of it, armor and the
    /// crafting grid included, is the server's now. Servers send it at join, at respawn and
    /// after a rejected click; a kit given with single `set_slot`s does not set it.
    pub player_synced: bool,
    /// The server sent the full contents of the open window (its own slots and the player
    /// slots it shows).
    pub window_synced: bool,
}

/// An open container window.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Window {
    id: i32,
    kind: WindowKind,
    title: ByteString,
    action: i16,
    properties: Vec<(i16, i16)>,
    /// 26.1 `minecraft:menu` registry id (-1 for other versions).
    menu: i32,
}

impl Window {
    /// Window id (`syncId`).
    #[must_use]
    pub fn id(&self) -> i32 {
        self.id
    }
    /// Its type.
    #[must_use]
    pub fn kind(&self) -> WindowKind {
        self.kind
    }
    /// The title exactly as sent: a JSON chat component on both versions.
    #[must_use]
    pub fn title(&self) -> &ByteString {
        &self.title
    }
    /// A window property (`craft_progress_bar`: furnace progress, enchanting seeds, …).
    #[must_use]
    pub fn property(&self, id: i16) -> Option<i16> {
        self.properties.iter().find(|p| p.0 == id).map(|p| p.1)
    }
    /// 26.1: the `minecraft:menu` registry id of `open_screen` (`None` for other versions).
    #[must_use]
    pub fn menu_modern(&self) -> Option<i32> {
        (self.menu >= 0).then_some(self.menu)
    }
}

/// Which screen the client has open.
#[derive(Debug, Clone, PartialEq, Eq)]
enum ScreenState {
    None,
    Inventory,
    Window(Window),
}

#[derive(Debug, Clone, Copy)]
struct PendingClick {
    window_id: i32,
    action: i16,
    age: u32,
}

#[derive(Debug, Clone, Copy, Default)]
struct TickFlags {
    clicked: bool,
    opened: bool,
    closed: bool,
}

/// The client's inventory: player inventory, cursor, the open window, click prediction and
/// the confirm protocol. Pure and deterministic: packets in, packets out, no I/O or clock
/// ([`tick`](Inventory::tick) counts time).
#[derive(Debug, Clone)]
pub struct Inventory {
    version: Version,
    m: Model,
    screen: ScreenState,
    player_action: i16,
    pending: Option<PendingClick>,
    resync: Option<(i32, u32)>,
    flags: TickFlags,
    timeout: u32,
    settle: u32,
    events: Events,
    /// Server writes of each hotbar slot and (last) the off hand (`set_slot`,
    /// `window_items`), changed or not.
    hotbar_writes: [u16; 10],
    book: RecipeBook,
    /// 1.16.5: the server's item tags (they belong to the connection, like the recipes).
    tags16: Option<std::sync::Arc<crate::tags16::ItemTags16>>,
    /// 26.1 state ids: window 0 (`inventoryMenu`) and the open container.
    state_player: i32,
    state_window: i32,
    /// 26.1 registry names for click hashes and the binding curse.
    #[cfg(modern)]
    reg26: crate::item26::HashRegistries,
    /// 26.1: recipe item sets, game mode, experience level.
    #[cfg(modern)]
    w26: crate::sim26::World26,
    /// 26.1: window 0's and the open container's per-screen click state (drags, …).
    #[cfg(modern)]
    s26: [crate::sim26::Screen26; 2],
    /// 26.1: window 0's `lastSlots` (what its last `broadcastChanges` saw; the creative
    /// screen's listener sends every slot that differs).
    #[cfg(modern)]
    creative_last: Vec<Option<Stack>>,
    /// 26.1: the creative inventory screen is open (window 0 in creative mode).
    #[cfg(modern)]
    creative_screen: bool,
    /// 26.1: packets the creative screen sends in answer to server packets
    /// ([`Inventory::take_creative_echo_modern`]).
    #[cfg(modern)]
    creative_echo: Vec<CreativePacket>,
    /// 26.1 `LocalPlayer.dropSpamThrottler`: +20 per creative drop, -1 per tick; drops are
    /// refused from 1280 (`canDropItems`).
    #[cfg(modern)]
    drop_throttle: i32,
    /// 26.1 `update_recipes` body, not parsed yet (parsed when a menu needs its item sets).
    #[cfg(modern)]
    recipes_raw: Option<bytes::Bytes>,
    /// 26.1 tags and enchantment definitions (raw until a menu needs them).
    #[cfg(modern)]
    d26: crate::data26::Data26,
    /// 1.8 – 1.16.5: the creative inventory screen, allocated at its first open.
    creative16: Option<Box<creative_legacy::CreativeLegacy>>,
}

#[path = "creative_legacy.rs"]
mod creative_legacy;
pub use creative_legacy::CreativeTab;

/// The write counter of a hotbar slot (0 … 8) or the off hand (9) for a slot location.
#[inline]
fn hand_writes_index(l: Loc) -> Option<usize> {
    match l {
        Loc::Player(k @ 0..9) => Some(k),
        Loc::Player(40) => Some(9),
        _ => None,
    }
}

impl Inventory {
    /// An empty inventory (a fresh player entity).
    ///
    /// # Errors
    /// [`VersionNotEnabled`] when this build of the crate lacks the version's feature
    /// ([`Version::is_enabled`]).
    pub fn new(version: Version) -> Result<Inventory, VersionNotEnabled> {
        if version.is_enabled() {
            Ok(Inventory::empty(version))
        } else {
            Err(VersionNotEnabled(version))
        }
    }

    fn empty(version: Version) -> Inventory {
        Inventory {
            version,
            m: Model::default(),
            screen: ScreenState::None,
            player_action: 0,
            pending: None,
            resync: None,
            flags: TickFlags::default(),
            timeout: DEFAULT_CLICK_TIMEOUT_TICKS,
            settle: DEFAULT_CLICK_SETTLE_TICKS,
            events: Events::default(),
            hotbar_writes: [0; 10],
            book: RecipeBook::default(),
            tags16: None,
            state_player: 0,
            state_window: 0,
            #[cfg(modern)]
            reg26: crate::item26::HashRegistries::default(),
            #[cfg(modern)]
            w26: crate::sim26::World26::default(),
            #[cfg(modern)]
            s26: Default::default(),
            #[cfg(modern)]
            creative_last: Vec::new(),
            #[cfg(modern)]
            creative_screen: false,
            #[cfg(modern)]
            creative_echo: Vec::new(),
            #[cfg(modern)]
            drop_throttle: 0,
            #[cfg(modern)]
            recipes_raw: None,
            #[cfg(modern)]
            d26: Default::default(),
            creative16: None,
        }
    }

    /// Sets how many ticks a click may wait for its confirm.
    pub fn set_click_timeout(&mut self, ticks: u32) {
        self.timeout = ticks.max(1);
    }

    /// 26.1: how many ticks after a click without a correcting container packet make it
    /// [`ClickOutcome::Accepted`]. 26.1 has no confirm: the server applies the click when it
    /// receives it and answers in the same moment, with `container_set_slot` /
    /// `container_set_content` / `set_cursor_item` only for slots its result disagrees with, and
    /// with nothing when the client predicted right. So silence is the acceptance; set this to
    /// cover the round trip (`ceil(rtt / 50 ms) + 1`; default
    /// [`DEFAULT_CLICK_SETTLE_TICKS`]). A correction before that makes the click
    /// [`ClickOutcome::Rejected`] (already applied: no resync wait).
    pub fn set_click_settle_ticks(&mut self, ticks: u32) {
        self.settle = ticks.max(1);
    }

    /// The protocol version.
    #[must_use]
    pub fn version(&self) -> Version {
        self.version
    }

    /// The level of enchantment `name` (`sharpness` or `minecraft:sharpness`) on `stack`, on
    /// every version (1.8 / 1.12 numeric ids, 1.16.5 names, 26.x the server's enchantment
    /// registry from [`Inventory::set_registries_modern`]); 0 when it has none.
    #[must_use]
    pub fn enchantment_level(&self, stack: &crate::Stack, name: &str) -> i32 {
        let want = name.strip_prefix("minecraft:").unwrap_or(name);
        #[cfg(modern)]
        let registry: &[String] = self.reg26.enchantments();
        #[cfg(not(modern))]
        let registry: &[String] = &[];
        stack
            .enchantments(self.version)
            .iter()
            .find(|e| e.id.plain_name(registry) == Some(want))
            .map_or(0, |e| e.level)
    }

    /// The modern table set of this inventory's version (a placeholder for a legacy one: only
    /// modern code paths read it).
    #[cfg(modern)]
    #[inline]
    pub(crate) fn mv(&self) -> crate::tables::Mv {
        crate::tables::Mv::of(self.version).unwrap_or(crate::tables::Mv::ANY)
    }

    /// A new player entity (join, respawn, dimension change): everything is cleared,
    /// including the action counters; the server resends the inventory.
    /// The selected hotbar slot restarts at 0 too (a new `PlayerInventory`).
    pub fn reset(&mut self) {
        // the recipe book belongs to the connection, not to the player entity
        #[cfg(modern)]
        let reg26 = std::mem::take(&mut self.reg26);
        #[cfg(modern)]
        let w26 = std::mem::take(&mut self.w26);
        #[cfg(modern)]
        let recipes_raw = self.recipes_raw.take();
        #[cfg(modern)]
        let d26 = std::mem::take(&mut self.d26);
        *self = Inventory {
            timeout: self.timeout,
            settle: self.settle,
            book: std::mem::take(&mut self.book),
            hotbar_writes: self.hotbar_writes,
            tags16: self.tags16.take(),
            #[cfg(modern)]
            reg26,
            #[cfg(modern)]
            w26,
            #[cfg(modern)]
            recipes_raw,
            #[cfg(modern)]
            d26,
            creative16: self
                .creative16
                .take()
                .map(creative_legacy::CreativeLegacy::respawned),
            ..Inventory::empty(self.version)
        };
        self.events.player_changed = true;
    }

    /// Call once at the start of every client tick: resets the per-tick packet-order guard
    /// and ages the pending click.
    pub fn tick(&mut self) {
        self.flags = TickFlags::default();
        #[cfg(modern)]
        if self.drop_throttle > 0 {
            self.drop_throttle -= 1;
        }
        if let Some(p) = &mut self.pending {
            p.age += 1;
            if self.version.is_modern() && p.age >= self.settle {
                self.events.clicks.push(ClickResult {
                    window_id: p.window_id,
                    action: p.action,
                    outcome: ClickOutcome::Accepted,
                });
                self.pending = None;
            } else if p.age >= self.timeout {
                self.events.clicks.push(ClickResult {
                    window_id: p.window_id,
                    action: p.action,
                    outcome: ClickOutcome::TimedOut,
                });
                self.pending = None;
            }
        }
        if let Some((_, age)) = &mut self.resync {
            *age += 1;
            if *age >= self.timeout {
                self.resync = None;
            }
        }
    }

    /// Takes the accumulated change flags and click results.
    pub fn drain_events(&mut self) -> Events {
        std::mem::take(&mut self.events)
    }

    // ------------------------------------------------------------------ reading

    /// The cursor ("carried") stack.
    #[must_use]
    pub fn cursor(&self) -> Option<&Stack> {
        self.m.cursor.as_ref()
    }

    /// `PlayerInventory` slot by vanilla index: 0..=8 hotbar, 9..=35 main, 36..=39 armor
    /// (feet, legs, chest, head), 40 offhand (1.12 / 1.16.5).
    #[must_use]
    pub fn player(&self, index: usize) -> Option<&Stack> {
        self.m.player.get(index)?.as_ref()
    }

    /// Hotbar slot 0..=8.
    #[must_use]
    pub fn hotbar(&self, k: usize) -> Option<&Stack> {
        if k < 9 { self.player(k) } else { None }
    }

    /// The selected hotbar slot.
    #[must_use]
    pub fn selected(&self) -> u8 {
        self.m.selected
    }

    /// How many times the server wrote the selected hotbar slot (`set_slot`, `window_items`;
    /// 1.8 – 1.16.5), whether the stack changed or not, wrapping. A 1.8 client's item use ends
    /// when the held stack is replaced, even by an equal one.
    #[must_use]
    pub fn held_writes(&self) -> u16 {
        self.hotbar_writes[usize::from(self.m.selected.min(8))]
    }

    /// [`Inventory::held_writes`] for the off-hand slot (1.12 / 1.16.5).
    #[must_use]
    pub fn offhand_writes(&self) -> u16 {
        self.hotbar_writes[9]
    }

    /// The stack in the selected hotbar slot.
    #[must_use]
    pub fn held(&self) -> Option<&Stack> {
        self.player(usize::from(self.m.selected))
    }

    /// Armor piece: 0 head, 1 chest, 2 legs, 3 feet.
    #[must_use]
    pub fn armor(&self, a: usize) -> Option<&Stack> {
        if a < 4 { self.player(39 - a) } else { None }
    }

    /// The offhand stack (1.12 / 1.16.5).
    #[must_use]
    pub fn offhand(&self) -> Option<&Stack> {
        self.player(40)
    }

    /// The open container window, if any.
    #[must_use]
    pub fn window(&self) -> Option<&Window> {
        match &self.screen {
            ScreenState::Window(w) => Some(w),
            _ => None,
        }
    }

    /// Whether a GUI is open (a container window or the player inventory).
    #[must_use]
    pub fn gui_open(&self) -> bool {
        self.screen != ScreenState::None
    }

    /// Whether the player inventory GUI is open (no container window).
    #[must_use]
    pub fn inventory_open(&self) -> bool {
        self.screen == ScreenState::Inventory
    }

    fn layout(&self) -> Layout {
        let screen = match &self.screen {
            ScreenState::Window(w) => Screen::Container(w.kind),
            _ => Screen::Player,
        };
        Layout::new(self.version, screen)
    }

    /// Number of slots of the current screen (window 0 when no container is open: 45 on 1.8,
    /// 46 on 1.12 / 1.16.5).
    #[must_use]
    pub fn slot_count(&self) -> usize {
        self.layout().len
    }

    /// Container slots of the open window (before the player's 36), 0 for window 0.
    #[must_use]
    pub fn container_len(&self) -> usize {
        self.layout().n
    }

    /// Slot `i` of the current screen (window 0 layout when no container is open).
    #[must_use]
    pub fn slot(&self, i: usize) -> Option<&Stack> {
        let l = self.layout().loc(i)?;
        self.m.at(l).as_ref()
    }

    /// Slot `i` of window 0 (`PlayerScreenHandler` numbering), whatever is open.
    #[must_use]
    pub fn window0_slot(&self, i: usize) -> Option<&Stack> {
        let l = Layout::new(self.version, Screen::Player).loc(i)?;
        self.m.at(l).as_ref()
    }

    /// Kind of slot `i` of the current screen.
    #[must_use]
    pub fn slot_kind(&self, i: usize) -> Option<SlotKind> {
        let lay = self.layout();
        (i < lay.len).then(|| lay.kind(i))
    }

    /// The current screen's slot that shows `PlayerInventory` index `k` (e.g. hotbar 0 is
    /// window 0 slot 36 and slot 54 of a 3-row chest).
    #[must_use]
    pub fn slot_of_player(&self, k: usize) -> Option<i16> {
        self.layout().slot_of_player(k).map(|i| i as i16)
    }

    /// First slot of the current screen whose stack matches.
    pub fn find(&self, mut pred: impl FnMut(&Stack) -> bool) -> Option<i16> {
        let lay = self.layout();
        (0..lay.len)
            .find(|&i| {
                lay.loc(i)
                    .and_then(|l| self.m.at(l).as_ref())
                    .is_some_and(&mut pred)
            })
            .map(|i| i as i16)
    }

    /// Total count of matching stacks in the player inventory (hotbar, main, armor, offhand).
    pub fn count(&self, mut pred: impl FnMut(&Stack) -> bool) -> i32 {
        self.m
            .player
            .iter()
            .flatten()
            .filter(|s| pred(s))
            .map(|s| s.count)
            .sum()
    }

    /// Whether the current screen's crafting result (window 0 slot 0, crafting table slot 0)
    /// is what the vanilla client shows. The 1.8 client computes results from its recipe book
    /// (ghast does not) and the server never sends them except in `window_items`; on 1.16.5 the
    /// server sends each new result as `set_slot`. The 1.12 client never computes results: the
    /// slot always holds what the server last sent (taking a result whose grid changed since is
    /// refused, its remainders depend on the recipes). While unknown, result clicks are
    /// [`ClickError::Unpredictable`]. 1.8 – 1.16.5 anvil and grindstone: whether ghast could
    /// compute the output like the client (false for inputs it cannot read, until the server's
    /// `set_slot`).
    #[must_use]
    pub fn result_known(&self) -> bool {
        match &self.screen {
            ScreenState::Window(w) if w.kind == WindowKind::Crafting => {
                self.m.container_result_known
            }
            // 1.8 – 1.16.5 anvil: the output the client computed after an input change
            ScreenState::Window(w)
                if matches!(w.kind, WindowKind::Anvil | WindowKind::Grindstone)
                    && !self.version.is_modern() =>
            {
                self.m.container_result_known
            }
            ScreenState::Window(_) => true,
            _ => self.m.craft_result_known,
        }
    }

    /// Whether the current screen's crafting result belongs to the grid as it is now. 1.12: the
    /// server sent it and the grid has not changed since (a click that changes the grid leaves
    /// the old result in the slot until the server's `set_slot`; taking such a stale result is
    /// [`ClickError::Unpredictable`]). 1.8 / 1.16.5: the same as
    /// [`result_known`](Inventory::result_known).
    #[must_use]
    pub fn result_current(&self) -> bool {
        if self.version != Version::V1_12 {
            return self.result_known();
        }
        match &self.screen {
            ScreenState::Window(w) if w.kind == WindowKind::Crafting => self.m.container_fresh,
            ScreenState::Window(_) => true,
            _ => self.m.craft_fresh,
        }
    }

    /// Whether a click waits for its confirm.
    #[must_use]
    pub fn pending(&self) -> bool {
        self.pending.is_some()
    }

    /// Whether the inventory waits for the server's resync after a rejected click.
    #[must_use]
    pub fn resyncing(&self) -> bool {
        self.resync.is_some()
    }

    /// Whether [`click`](Inventory::click) would currently refuse for a reason other than the
    /// click itself.
    pub fn can_click(&self) -> Result<(), ClickError> {
        if self.pending.is_some() {
            return Err(ClickError::Pending);
        }
        if self.resync.is_some() {
            return Err(ClickError::Resyncing);
        }
        if self.flags.clicked || self.flags.opened {
            return Err(ClickError::SameTick);
        }
        if self.screen == ScreenState::None {
            return Err(ClickError::NoScreen);
        }
        Ok(())
    }

    // ------------------------------------------------------------------ actions

    /// Simulates a click exactly like the vanilla client (`ClientPlayerInteractionManager.clickSlot`:
    /// next action number, `onSlotClick`, packet with its return value) and returns the packet
    /// to send now. The prediction is applied immediately; the click is pending until its
    /// confirm arrives.
    ///
    /// Bots should click only while not turning (the server and anticheats see clicks against
    /// the last sent rotation; vanilla players do not move the camera with a GUI open).
    pub fn click(&mut self, click: Click) -> Result<Outgoing, ClickError> {
        self.can_click()?;
        let lay = self.layout();
        let (slot, button, mode) = click.wire();
        if self.creative_screen_legacy().is_some() {
            return self.creative_click_legacy(slot, button, mode);
        }
        let in_range = usize::try_from(slot).is_ok_and(|i| i < lay.len);
        let slot_ok = match click {
            Click::Pickup { .. } | Click::Drop { .. } => in_range || slot == OUTSIDE,
            Click::QuickMove { .. }
            | Click::Swap { .. }
            | Click::PickupAll { .. }
            | Click::Clone { .. } => in_range,
            Click::QuickCraft { stage, .. } => match stage {
                DragStage::Slot => in_range,
                DragStage::Start | DragStage::End => in_range || slot == OUTSIDE,
            },
        };
        if !slot_ok {
            return Err(ClickError::InvalidSlot);
        }
        if !self.version.is_modern()
            && (matches!(click, Click::QuickCraft { .. })
                || matches!(click, Click::Clone { .. }) && !self.m.creative)
        {
            // the older versions' drags are not modelled; the clone is a creative click
            return Err(ClickError::Unpredictable);
        }
        if let Click::Swap { hotbar, .. } = click {
            let ok = hotbar < 9
                || (hotbar == 40
                    && matches!(
                        self.version,
                        Version::V1_16_5 | Version::V26_1 | Version::V26_2
                    ));
            if !ok {
                return Err(ClickError::InvalidButton);
            }
        }
        #[cfg(modern)]
        if self.version.is_modern() {
            if self.creative_screen {
                return self.creative_click(slot, button, mode);
            }
            return Ok(self.click_26(slot, button, mode));
        }
        let mut m = self.m.clone();
        let simulated = {
            let mut sim = Sim {
                v: self.version,
                lay,
                m: &mut m,
                book: &self.book,
                binding_curse: self.binding_curse(),
                tags: self.tags16.as_deref(),
            };
            sim.click(slot, button, mode)
        };
        let item = simulated.map_err(|_| ClickError::Unpredictable)?;
        let swings = self.drop_swings_1_16(&m, lay, slot, button, mode);
        self.commit(m, lay);
        let (window_id, action) = match &mut self.screen {
            ScreenState::Window(w) => {
                w.action = w.action.wrapping_add(1);
                (w.id, w.action)
            }
            _ => {
                self.player_action = self.player_action.wrapping_add(1);
                (0, self.player_action)
            }
        };
        self.pending = Some(PendingClick {
            window_id,
            action,
            age: 0,
        });
        self.flags.clicked = true;
        Ok(Outgoing::Click(ClickPacket {
            window_id: window_id as u8,
            slot,
            button,
            mode,
            action,
            item,
            swings,
        }))
    }

    fn binding_curse(&self) -> Option<i32> {
        #[cfg(modern)]
        {
            self.reg26
                .enchantments()
                .iter()
                .position(|n| n == "minecraft:binding_curse")
                .map(|i| i as i32)
        }
        #[cfg(not(modern))]
        None
    }

    /// 26.1: the registry names click hashes and the binding curse check need (the
    /// configuration phase's `minecraft:enchantment` keys in order). Without them, clicks with
    /// enchanted items send hashes the server corrects, and taking enchanted armor off is not
    /// predicted.
    #[cfg(modern)]
    ///
    /// Clients of one process that receive the same names share one copy of them.
    pub fn set_registries_modern(&mut self, reg: crate::item26::HashRegistries) {
        self.reg26 = reg.shared();
    }

    /// 26.1: the registry names set with [`Inventory::set_registries_modern`].
    #[cfg(modern)]
    #[must_use]
    pub fn registries_modern(&self) -> &crate::item26::HashRegistries {
        &self.reg26
    }

    /// 26.1: the name of enchantment registry id `id` as the server's `registry_data` keyed it
    /// (`minecraft:sharpness`), from the registries set with
    /// [`Inventory::set_registries_modern`]; `None` for an unknown id.
    #[cfg(modern)]
    #[must_use]
    pub fn enchantment_name_modern(&self, id: i32) -> Option<&str> {
        self.reg26
            .enchantments()
            .get(usize::try_from(id).ok()?)
            .map(String::as_str)
    }

    /// 26.1: the state id the next click of the current screen carries.
    #[must_use]
    pub fn state_id(&self) -> i32 {
        match &self.screen {
            ScreenState::Window(_) => self.state_window,
            _ => self.state_player,
        }
    }

    /// The 26.1 menu the click runs in.
    #[cfg(modern)]
    fn kind_26(&self) -> crate::sim26::Kind {
        match &self.screen {
            ScreenState::Window(w) => match (crate::sim26::Kind::from_menu(w.menu), w.kind) {
                (Some(k), _) => k,
                (None, WindowKind::Horse { slots }) if w.menu == MOUNT_MENU => {
                    crate::sim26::Kind::Mount(slots.saturating_sub(2) / 3)
                }
                (None, WindowKind::Chest { rows }) => crate::sim26::Kind::Chest(rows),
                (None, _) => crate::sim26::Kind::Chest(0),
            },
            _ => crate::sim26::Kind::Player,
        }
    }

    /// The 26.1 click (`MultiPlayerGameMode.handleContainerInput`): vanilla predicts, then lists
    /// every slot whose stack changed (in the order of its `Int2ObjectOpenHashMap`) and the
    /// carried stack. A click ghast cannot predict is sent unpredicted (nothing changes locally;
    /// the server applies it and sends the true slots), never refused.
    #[cfg(modern)]
    fn click_26(&mut self, slot: i16, button: u8, mode: u8) -> Outgoing {
        let kind = self.kind_26();
        if matches!(
            kind,
            crate::sim26::Kind::Furnace(_)
                | crate::sim26::Kind::Smithing
                | crate::sim26::Kind::Stonecutter
        ) {
            self.ensure_recipes_modern();
        }
        if matches!(
            kind,
            crate::sim26::Kind::Anvil
                | crate::sim26::Kind::Grindstone
                | crate::sim26::Kind::Loom
                | crate::sim26::Kind::Mount(_)
        ) {
            self.d26.ensure(self.mv(), self.reg26.enchantments());
        }
        let w = usize::from(matches!(self.screen, ScreenState::Window(_)));
        let mut m = self.m.clone();
        let mut scr = self.s26[w].clone();
        self.w26.binding_curse = self.binding_curse();
        self.w26.can_drop = self.drop_throttle < 1280;
        let (result, swings) = {
            let mut sim = crate::sim26::Sim26 {
                kind,
                m: &mut m,
                s: &mut scr,
                w: &self.w26,
                d: &self.d26,
                reg: &self.reg26,
                mv: self.mv(),
                swings: 0,
                xp_spent: 0,
            };
            let r = sim.click(slot, button as i8, mode);
            (r, (sim.swings, sim.xp_spent))
        };
        let (swings, xp_spent) = swings;
        let predicted = result.is_ok();
        let mut changed = Vec::new();
        let mut swings_out = 0;
        if predicted {
            let mut idx = Vec::new();
            for i in 0..kind.len() {
                let Some(l) = kind.loc(i) else { break };
                let (a, b) = (self.m.at(l), m.at(l));
                let same = match (a, b) {
                    (None, None) => true,
                    (Some(a), Some(b)) => a.count == b.count && a.id == b.id && a.data_eq(b),
                    _ => false,
                };
                if !same {
                    idx.push(i as i32);
                }
            }
            for i in crate::sim26::fastutil_order(&idx) {
                let l = kind.loc(i as usize).unwrap_or(Loc::Player(0));
                changed.push((i as i16, m.at(l).clone()));
            }
            let lay = self.layout();
            self.commit(m, lay);
            self.s26[w] = scr;
            swings_out = swings;
            if xp_spent != 0
                && let Some(x) = &mut self.w26.xp_level
            {
                *x -= xp_spent;
            }
        } else {
            // the outcome is unknown, including how far a drag got: start over
            self.s26[w].drag.reset();
        }
        let (window_id, action) = match &mut self.screen {
            ScreenState::Window(w) => {
                w.action = w.action.wrapping_add(1);
                (w.id, w.action)
            }
            _ => {
                self.player_action = self.player_action.wrapping_add(1);
                (0, self.player_action)
            }
        };
        self.pending = Some(PendingClick {
            window_id,
            action,
            age: 0,
        });
        self.flags.clicked = true;
        Outgoing::ContainerClick(ContainerClick {
            action,
            window_id,
            state_id: self.state_id(),
            slot,
            button,
            mode,
            changed,
            carried: self.m.cursor.clone(),
            predicted,
            swings: swings_out,
        })
    }

    /// 26.1: whether the player is in creative mode (instant build): middle-click clones,
    /// clone drags, armor with the binding curse comes off, overflow vanishes. Set from the
    /// `abilities` packet by [`Inventory::apply_raw_modern`].
    #[cfg(modern)]
    pub fn set_creative_modern(&mut self, creative: bool) {
        self.w26.creative = creative;
    }

    /// 26.1 `update_tags` (configuration `tags` or play `tags`): the body is kept and parsed
    /// at the first click in an anvil, grindstone, loom or mount screen (the item, enchantment,
    /// banner pattern and entity type tags those read). The play packet is also handled by
    /// [`Inventory::apply_raw_modern`].
    #[cfg(modern)]
    pub fn on_update_tags_modern(&mut self, body: bytes::Bytes) {
        self.d26.set_tags_raw(body);
    }

    /// 26.1 configuration `registry_data`: the `minecraft:enchantment` body is kept (parsed
    /// with the tags) for the anvil's rules; other registries are ignored. Entries sent without
    /// data (a server and client sharing the vanilla pack) use the vanilla definitions.
    #[cfg(modern)]
    pub fn on_registry_data_modern(&mut self, body: bytes::Bytes) {
        self.d26.set_registry_raw(body);
    }

    /// 26.1 `horse_screen_open` (`ClientboundMountScreenOpenPacket`): the mount's inventory
    /// screen. The client builds it from the entity, so the caller passes what the screen reads
    /// off it: the entity type (`minecraft:entity_type` registry id), the packet's inventory
    /// columns and `canUseSlot(SADDLE)` / `canUseSlot(BODY)` (horses, donkeys, mules, camels:
    /// saddle when alive, adult and tamed, body always; llamas: both always; nautili: both when
    /// alive, adult and tame).
    #[cfg(modern)]
    pub fn on_mount_screen_modern(
        &mut self,
        window_id: i32,
        columns: i32,
        entity_type: i32,
        can_saddle: bool,
        can_body: bool,
    ) {
        let cols = u8::try_from(columns.clamp(0, 50)).unwrap_or(0);
        self.on_open_window(
            window_id,
            Some(WindowKind::Horse {
                slots: 2 + cols * 3,
            }),
            "".into(),
        );
        if let ScreenState::Window(w) = &mut self.screen
            && w.id == window_id
        {
            w.menu = MOUNT_MENU;
        }
        self.s26[1] = crate::sim26::Screen26 {
            mount_type: entity_type,
            mount_saddle: can_saddle,
            mount_body: can_body,
            ..Default::default()
        };
    }

    /// 26.1 `merchant_offers`: the open villager screen's offers.
    #[cfg(modern)]
    pub fn on_merchant_offers_modern(&mut self, body: &bytes::Bytes) {
        if let Some((window, offers)) = crate::sim26::parse_offers(self.mv(), body)
            && let ScreenState::Window(w) = &self.screen
            && w.id == window
            && w.menu == 19
        {
            self.s26[1].offers = offers;
        }
    }

    /// Runs one 26.1 screen action on the open menu (no container click).
    #[cfg(modern)]
    fn screen_action_modern<T>(
        &mut self,
        f: impl FnOnce(&mut crate::sim26::Sim26<'_>) -> Result<T, crate::sim::Unpredictable>,
    ) -> Result<T, crate::sim::Unpredictable> {
        let kind = self.kind_26();
        let lay = self.layout();
        let mut m = self.m.clone();
        let mut scr = self.s26[1].clone();
        self.w26.binding_curse = self.binding_curse();
        self.w26.can_drop = self.drop_throttle < 1280;
        let r = {
            let mut sim = crate::sim26::Sim26 {
                kind,
                m: &mut m,
                s: &mut scr,
                w: &self.w26,
                d: &self.d26,
                reg: &self.reg26,
                mv: self.mv(),
                swings: 0,
                xp_spent: 0,
            };
            f(&mut sim)
        };
        if r.is_ok() {
            self.commit(m, lay);
            self.s26[1] = scr;
        }
        r
    }

    /// 26.1 anvil: types `name` into the name field (`AnvilMenu.setItemName`; the name is
    /// filtered like vanilla's and limited to 50 characters). Returns the `rename_item` to send
    /// when the name changed (`Ok(None)`: nothing to send). An empty name removes a custom
    /// name. Like the real screen, it does nothing while the input slot is empty.
    ///
    /// # Errors
    /// [`ClickError::NoScreen`] when no anvil is open.
    #[cfg(modern)]
    pub fn anvil_rename_modern(&mut self, name: &str) -> Result<Option<Outgoing>, ClickError> {
        if self.kind_26() != crate::sim26::Kind::Anvil {
            return Err(ClickError::NoScreen);
        }
        if self.m.container.first().is_none_or(Option::is_none) {
            return Ok(None);
        }
        let filtered: String = name
            .chars()
            .filter(|&c| c != '\u{a7}' && c >= ' ' && c != '\u{7f}')
            .collect();
        if filtered.chars().count() > 50 || self.s26[1].anvil_name.as_deref() == Some(&filtered) {
            return Ok(None);
        }
        self.d26.ensure(self.mv(), self.reg26.enchantments());
        let n = filtered.clone();
        let r = self.screen_action_modern(|sim| {
            sim.s.anvil_name = Some(n);
            sim.anvil_create()
        });
        if r.is_err() {
            // the result could not be computed: keep the name, the server sends the result
            self.s26[1].anvil_name = Some(filtered.clone());
        }
        Ok(Some(Outgoing::RenameItem(filtered)))
    }

    /// 26.1 `EnchantmentHelper.getTridentSpinAttackStrength(stack)`: 0 run through the
    /// `minecraft:trident_spin_attack_strength` effect of every enchantment in the stack's
    /// `enchantments` (in their order), as the server's enchantment registry defines it
    /// (`registry_data` with data, else vanilla's definition: riptide adds `1.5 + 0.75 ×
    /// (level - 1)`). `Some(0.0)` without such an enchantment.
    ///
    /// `None` when it cannot be computed: an enchantment whose definition is unknown (not sent
    /// with data and not vanilla), an effect that does not read, or one that draws on the
    /// holder's random (`remove_binomial`). The first call parses the raw registry data and
    /// tags (hence `&mut self`).
    #[cfg(modern)]
    pub fn trident_spin_attack_strength_modern(&mut self, stack: &Stack) -> Option<f32> {
        let list = crate::item26::enchantments(self.mv(), stack, false).unwrap_or_default();
        if list.is_empty() {
            return Some(0.0);
        }
        self.d26.ensure(self.mv(), self.reg26.enchantments());
        let mut v = 0.0f32;
        for (id, level) in list {
            match &self.d26.enchantment(id)?.spin {
                None => {}
                Some(None) => return None,
                Some(Some(fx)) => v = fx.process(level, v)?,
            }
        }
        Some(v)
    }

    /// 26.1 loom: clicks pattern button `index` (`LoomMenu.clickMenuButton`). Returns the
    /// `container_button_click` when the loom accepts it (`Ok(None)`: not a selectable pattern).
    ///
    /// # Errors
    /// [`ClickError::NoScreen`] when no loom is open; [`ClickError::Unpredictable`] when the
    /// patterns are not known.
    #[cfg(modern)]
    pub fn select_loom_pattern_modern(
        &mut self,
        index: i32,
    ) -> Result<Option<Outgoing>, ClickError> {
        if self.kind_26() != crate::sim26::Kind::Loom {
            return Err(ClickError::NoScreen);
        }
        self.d26.ensure(self.mv(), self.reg26.enchantments());
        let ok = self
            .screen_action_modern(|sim| sim.loom_button(index))
            .map_err(|_| ClickError::Unpredictable)?;
        Ok(ok.then(|| Outgoing::ButtonClick {
            window_id: self.open_id(),
            button: index,
        }))
    }

    /// 1.8 – 1.16.5 villager screen: the server's offers for window `window_id` (vanilla
    /// keeps them only while that window's trading screen is open). The output is not looked up
    /// again until the next slot change, like vanilla. [`Inventory::apply_v1_8`] /
    /// [`Inventory::apply_v1_12_2`] (`MC|TrList`) and [`Inventory::apply_v1_16_5`]
    /// (`trade_list`) call this.
    pub fn on_trade_offers(&mut self, window_id: i32, offers: Vec<crate::merchant::TradeOffer>) {
        if self.open_id() == window_id
            && let Some(mer) = self.m.merchant.as_deref_mut()
        {
            mer.offers = Some(offers);
        }
    }

    /// 1.16.5 `open_window` by menu type id ([`WindowKind::from_v1_16_5`]); also remembers
    /// which recipes a furnace, blast furnace or smoker smelts (its shift-click reads them).
    /// [`Inventory::apply_v1_16_5`] calls this.
    pub fn on_open_window_v1_16_5(&mut self, id: i32, menu_type: i32, title: ByteString) {
        self.on_open_window(id, WindowKind::from_v1_16_5(menu_type), title);
        if self.open_id() == id {
            self.m.furnace = match menu_type {
                9 => 1,
                21 => 2,
                _ => 0,
            };
        }
    }

    /// A workstation's `window_items`: vanilla's `updateSlotStacks` sets the slots in order
    /// (`Slot.setStack`, which notifies the menu twice for an input), so each input change sees
    /// the slots before it new and the ones after it old.
    fn station_window_items(&mut self, before: Vec<Option<Stack>>) {
        let Some(st) = self.m.station.as_deref() else {
            return;
        };
        let inputs: Vec<bool> = (0..before.len()).map(|k| st.is_input(k)).collect();
        let new = std::mem::replace(&mut self.m.container, before);
        let lay = self.layout();
        let mut sim = Sim {
            v: self.version,
            lay,
            m: &mut self.m,
            book: &self.book,
            binding_curse: None,
            tags: self.tags16.as_deref(),
        };
        for (k, s) in new.into_iter().enumerate() {
            if k >= sim.m.container.len() {
                break;
            }
            sim.m.container[k] = s;
            if inputs[k] {
                sim.station_touched(Loc::Container(k));
                sim.station_touched(Loc::Container(k));
            }
        }
        self.m.container_result_known = true;
    }

    /// A server `set_slot` of workstation container slot `k` (`None`: all of them): an input
    /// change runs the menu's update; the result slot keeps what the packet set.
    fn station_inbound(&mut self, k: Option<usize>) {
        let Some(st) = self.m.station.as_deref() else {
            return;
        };
        let out = st.output();
        if k.is_some_and(|k| !st.is_input(k)) {
            // the server's result
            self.m.container_result_known = true;
            return;
        }
        let keep = self.m.container.get(out).cloned();
        let lay = self.layout();
        let mut sim = Sim {
            v: self.version,
            lay,
            m: &mut self.m,
            book: &self.book,
            binding_curse: None,
            tags: self.tags16.as_deref(),
        };
        // `Slot.setStack`: twice
        sim.station_touched(Loc::Container(0));
        sim.station_touched(Loc::Container(0));
        if k.is_none()
            && let (Some(slot), Some(keep)) = (self.m.container.get_mut(out), keep)
        {
            *slot = keep;
            self.m.container_result_known = true;
        }
    }

    /// The packets the open screen sent by itself since the last call, to write before
    /// anything else this tick (the 1.16.5 anvil screen's `rename_item` when its first input
    /// changed, also through a server packet). A click's own packet comes after these.
    pub fn take_screen_packets(&mut self) -> Vec<Outgoing> {
        std::mem::take(&mut self.m.screen_out)
    }

    /// The player's experience level (the 1.16.5 anvil's cost check; also the 26.x anvil).
    /// Set from the `experience` packet ([`Inventory::apply_v1_16_5`] does).
    pub fn set_experience_level(&mut self, level: i32) {
        self.m.xp_level = level;
        #[cfg(modern)]
        if self.version.is_modern() {
            self.set_experience_level_modern(level);
        }
    }

    /// The experience level as the client holds it (taking an anvil result lowers it).
    #[must_use]
    pub fn experience_level(&self) -> i32 {
        self.m.xp_level
    }

    /// Creative mode (the 1.16.5 anvil: no level check, every enchantment fits; also 26.x).
    /// Set from the `abilities` packet ([`Inventory::apply_v1_16_5`] does).
    pub fn set_creative(&mut self, creative: bool) {
        self.m.creative = creative;
        #[cfg(modern)]
        if self.version.is_modern() {
            self.set_creative_modern(creative);
        }
    }

    /// The 1.16.5 anvil's level cost as the client holds it (`None`: no 1.16.5 anvil open).
    #[must_use]
    pub fn anvil_cost(&self) -> Option<i32> {
        match self.m.station.as_deref() {
            Some(crate::station::Station::Anvil(a)) => Some(a.cost),
            _ => None,
        }
    }

    /// Anvil: types `name` into the name field like the screen (1.16.5: `onRenamed`; 26.x: as
    /// [`Inventory::anvil_rename_modern`]). Returns the `rename_item` / `MC|ItemName` to send
    /// (`Ok(None)`: nothing is sent: no first input, or an empty name on 1.16.5). The field
    /// takes at most 35 characters (1.8.9: 30), without `§` and control characters. Typing exactly the item's translated
    /// name is not recognised (ghast has no translations): it renames.
    ///
    /// # Errors
    /// [`ClickError::NoScreen`] when no anvil is open; [`ClickError::InvalidSlot`] for a name
    /// the field does not take; [`ClickError::Unpredictable`] when the result cannot be
    /// computed (an item name ghast cannot read).
    pub fn anvil_rename(&mut self, name: &str) -> Result<Option<Outgoing>, ClickError> {
        #[cfg(modern)]
        if self.version.is_modern() {
            return self.anvil_rename_modern(name);
        }
        if !matches!(
            self.m.station.as_deref(),
            Some(crate::station::Station::Anvil(_))
        ) {
            return Err(ClickError::NoScreen);
        }
        let field = if self.version == Version::V1_8 {
            30
        } else {
            35
        };
        if name.chars().count() > field
            || name
                .chars()
                .any(|c| c == '\u{a7}' || c < ' ' || c == '\u{7f}')
        {
            return Err(ClickError::InvalidSlot);
        }
        // the field is editable while the screen last saw an item in slot 0
        let editable = matches!(
            self.m.station.as_deref(),
            Some(crate::station::Station::Anvil(a)) if a.tracked.is_some()
        );
        // 1.16.5 sends nothing for an empty field; 1.12 sends every change
        if (name.is_empty() && self.version == Version::V1_16_5) || !editable {
            return Ok(None);
        }
        let lay = self.layout();
        let mut m = self.m.clone();
        let mut sim = Sim {
            v: self.version,
            lay,
            m: &mut m,
            book: &self.book,
            binding_curse: None,
            tags: self.tags16.as_deref(),
        };
        // onRenamed: the item's own (custom) name typed again keeps it
        sim.anvil_set_name(name.to_owned());
        if !m.container_result_known {
            return Err(ClickError::Unpredictable);
        }
        let out = std::mem::take(&mut m.screen_out);
        self.m = m;
        self.events.window_changed = true;
        Ok(out.into_iter().last())
    }

    /// 1.16.5 menu buttons the client acts on itself (stonecutter recipe `index`, like its
    /// screen; [`Outgoing::ButtonClick`] is the packet to send). `Ok(None)`: the menu does not
    /// take that button (nothing to send).
    ///
    /// # Errors
    /// [`ClickError::NoScreen`] when no such menu is open.
    pub fn click_button(&mut self, index: i32) -> Result<Option<Outgoing>, ClickError> {
        use crate::station::Station;
        let id = self.open_id();
        let lay = self.layout();
        // the lectern screen only sends its buttons (page back 1, forward 2, take book 3,
        // page 100 + n); the server answers
        if matches!(&self.screen, ScreenState::Window(w) if w.kind == WindowKind::Lectern)
            && self.version == Version::V1_16_5
        {
            return Ok(
                matches!(index, 1..=3 | 100..).then_some(Outgoing::ButtonClick {
                    window_id: id,
                    button: index,
                }),
            );
        }
        if let Some(Station::Loom { .. }) = self.m.station.as_deref() {
            let before = self.m.container.clone();
            let mut sim = Sim {
                v: self.version,
                lay,
                m: &mut self.m,
                book: &self.book,
                binding_curse: None,
                tags: self.tags16.as_deref(),
            };
            let ok = sim.loom_button(index);
            if self.m.container != before {
                self.events.window_changed = true;
            }
            return Ok(ok.then_some(Outgoing::ButtonClick {
                window_id: id,
                button: index,
            }));
        }
        let Some(Station::Stonecutter {
            recipes, selected, ..
        }) = self.m.station.as_deref_mut()
        else {
            return Err(ClickError::NoScreen);
        };
        if usize::try_from(index).map_or(true, |k| k >= recipes.len()) {
            return Ok(None);
        }
        *selected = index;
        let before = self.m.container.clone();
        let mut sim = Sim {
            v: self.version,
            lay,
            m: &mut self.m,
            book: &self.book,
            binding_curse: None,
            tags: self.tags16.as_deref(),
        };
        sim.stonecutter_populate();
        if self.m.container != before {
            self.events.window_changed = true;
        }
        Ok(Some(Outgoing::ButtonClick {
            window_id: id,
            button: index,
        }))
    }

    /// 1.8 – 1.16.5 mount screen (a `Horse` window): what its saddle and armor slots take, read
    /// off the entity like vanilla's screen does (`None`: unknown, the default after the window
    /// opens; clicks that would need them are refused). Vanilla: 1.8 `open_window`
    /// `EntityHorse` names the entity; saddle always, horse armor for horse type 0. 1.12: saddle
    /// for all but llamas, horse armor for horses, carpets for llamas. 1.16.5
    /// (`open_horse_window`): saddle for a tame adult (not a llama), horse armor for horses,
    /// carpets for llamas and trader llamas.
    pub fn set_mount_rules(&mut self, rules: Option<crate::mount::MountRules>) {
        if matches!(&self.screen, ScreenState::Window(w) if matches!(w.kind, WindowKind::Horse { .. }))
        {
            self.m.mount = rules;
        }
    }

    /// The open mount screen's rules ([`Inventory::set_mount_rules`]).
    #[must_use]
    pub fn mount_rules(&self) -> Option<crate::mount::MountRules> {
        self.m.mount
    }

    /// 1.8 / 1.12 `MC|TrList` custom payload data (window id, then the offers).
    #[cfg(any(feature = "v1_8", feature = "v1_12"))]
    pub fn on_trade_list_legacy(&mut self, data: &bytes::Bytes) {
        if let Some((w, offers)) = crate::merchant::parse_legacy(data) {
            self.on_trade_offers(w, offers);
        }
    }

    /// 1.16.5 `tags`: the item tags the beacon, furnace and llama slots read (the client uses
    /// the server's; until they arrive those rules are refused as unpredictable). [`Inventory::apply_v1_16_5`]
    /// calls this.
    #[cfg(feature = "v1_16_5")]
    pub fn on_tags_v1_16_5(&mut self, p: &ghast_protocol::v1_16_5::play::clientbound::Tags) {
        self.tags16 = Some(std::sync::Arc::new(
            crate::tags16::ItemTags16::from_item_tags(
                self.version,
                p.item_tags.iter().map(|t| (&*t.tag_name, &t.entries[..])),
            ),
        ));
    }

    /// 1.16.5 `trade_list`.
    #[cfg(feature = "v1_16_5")]
    pub fn on_trade_list_v1_16_5(
        &mut self,
        p: &ghast_protocol::v1_16_5::play::clientbound::TradeList,
    ) {
        self.on_trade_offers(p.window_id, crate::merchant::from_v1_16_5(p));
    }

    /// The open villager screen's offers as the client holds them (uses counted on the client),
    /// `None` when no villager screen is open or the server has not sent them (1.8 – 1.16.5).
    #[must_use]
    pub fn trade_offers(&self) -> Option<&[crate::merchant::TradeOffer]> {
        self.m.merchant.as_ref()?.offers.as_deref()
    }

    /// Villager screen: picks offer `index` like the screen's arrows / trade buttons and
    /// returns the packet to send (1.8 / 1.12 `MC|TrSel`, 1.16.5 / 26.1 `select_trade`).
    /// 1.8 / 1.12: the output is looked up again for that offer (0 = the first offer that
    /// matches). 1.16.5: also the payments go back into the inventory and the offer's own
    /// items come out of it (`switchTo`), as the screen does. 26.1: as
    /// [`Inventory::select_trade_modern`].
    ///
    /// # Errors
    /// [`ClickError::NoScreen`] when no villager screen is open; [`ClickError::InvalidSlot`]
    /// when the offers are not known or `index` is not one of them.
    pub fn select_trade(&mut self, index: i32) -> Result<Outgoing, ClickError> {
        #[cfg(modern)]
        if self.version.is_modern() {
            return self.select_trade_modern(index);
        }
        let v = self.version;
        let Some(mer) = self.m.merchant.as_deref_mut() else {
            return Err(ClickError::NoScreen);
        };
        let n = mer.offers.as_ref().map_or(0, Vec::len);
        if usize::try_from(index).map_or(true, |k| k >= n) {
            return Err(ClickError::InvalidSlot);
        }
        mer.index = index;
        crate::merchant::update(v, &mut self.m);
        if v == Version::V1_16_5 {
            let lay = self.layout();
            let before = self.m.clone();
            let mut sim = Sim {
                v,
                lay,
                m: &mut self.m,
                book: &self.book,
                binding_curse: None,
                tags: self.tags16.as_deref(),
            };
            sim.switch_trade(index as usize);
            if self.m.container != before.container {
                self.events.window_changed = true;
            }
            if self.m.player != before.player {
                self.events.player_changed = true;
            }
        }
        Ok(Outgoing::SelectTrade(index))
    }

    /// 26.1 villager screen: picks trade `index` (`setSelectionHint`, `tryMoveItems`: the
    /// payment goes back to the inventory and the trade's costs come out of it). Returns the
    /// `select_trade` to send.
    ///
    /// # Errors
    /// [`ClickError::NoScreen`] when no villager screen is open.
    #[cfg(modern)]
    pub fn select_trade_modern(&mut self, index: i32) -> Result<Outgoing, ClickError> {
        if self.kind_26() != crate::sim26::Kind::Merchant {
            return Err(ClickError::NoScreen);
        }
        if self
            .screen_action_modern(|sim| sim.select_trade(index))
            .is_err()
        {
            self.s26[1].trade_hint = index;
        }
        Ok(Outgoing::SelectTrade(index))
    }

    /// 26.1: keeps an `update_recipes` body for later parsing.
    #[cfg(modern)]
    pub(crate) fn set_recipes_raw_modern(&mut self, body: bytes::Bytes) {
        self.recipes_raw = Some(body);
    }

    #[cfg(modern)]
    pub(crate) fn take_recipes_raw_modern(&mut self) -> Option<bytes::Bytes> {
        self.recipes_raw.take()
    }

    /// 26.1: the packets the creative inventory screen sent in answer to server packets since
    /// the last call (vanilla echoes every window 0 slot the server sets while the screen is
    /// open); send them right away.
    #[cfg(modern)]
    pub fn take_creative_echo_modern(&mut self) -> Vec<CreativePacket> {
        std::mem::take(&mut self.creative_echo)
    }

    /// Whether the 26.1 creative inventory screen is open (window 0 opened in creative mode):
    /// clicks then return [`Outgoing::Creative`].
    #[cfg(modern)]
    #[must_use]
    pub fn creative_screen_modern(&self) -> bool {
        self.creative_screen
    }

    /// `InventoryMenu.broadcastChanges` with the creative listener: every slot that differs
    /// from the last broadcast is sent.
    #[cfg(modern)]
    fn creative_broadcast(&mut self, out: &mut Vec<CreativePacket>) {
        let lay = Layout::new(self.version, Screen::Player);
        if self.creative_last.is_empty() {
            // allocated on the first broadcast: a bot that never opens it pays nothing
            self.creative_last = vec![None; 46];
        }
        for i in 0..46 {
            let Some(l) = lay.loc(i) else { break };
            let cur = self.m.at(l);
            let same = match (&self.creative_last[i], cur) {
                (None, None) => true,
                (Some(a), Some(b)) => a.count == b.count && a.id == b.id && a.data_eq(b),
                _ => false,
            };
            if !same {
                self.creative_last[i] = cur.clone();
                out.push(CreativePacket::SetSlot {
                    slot: i as i16,
                    item: cur.clone(),
                });
            }
        }
    }

    /// A click in the creative inventory screen (`CreativeModeInventoryScreen.slotClicked`,
    /// inventory tab): Q / drops are the screen's own; everything else runs window 0's click
    /// and broadcasts. Refused as unpredictable when ghast cannot simulate it (the stacks it
    /// sends would be wrong).
    #[cfg(modern)]
    fn creative_click(&mut self, slot: i16, button: u8, mode: u8) -> Result<Outgoing, ClickError> {
        let mode = if slot == OUTSIDE && mode == 0 {
            4
        } else {
            mode
        };
        let lay = Layout::new(self.version, Screen::Player);
        let mut out = Vec::new();
        let idx = usize::try_from(slot).ok();
        if mode == 4 && self.drop_throttle >= 1280 {
            // `canDropItems()` is false: the screen ignores the click
            self.flags.clicked = true;
            return Ok(Outgoing::Creative(out));
        }
        if mode == 4 {
            if let Some(i) = idx
                && let Some(l) = lay.loc(i)
                && let Some(st) = self.m.at(l).clone()
            {
                // slot.remove(button == 0 ? 1 : max stack size): the crafting result is taken
                // whole, other slots split
                let n = if button == 0 {
                    1
                } else {
                    crate::item26::max_stack_size(self.mv(), &st)
                };
                let dropped = if l == Loc::CraftResult {
                    self.m.at_mut(l).take()
                } else {
                    let s = self.m.at_mut(l);
                    let k = n.min(st.count).max(0);
                    let d = (k > 0).then(|| st.with_count(k));
                    if let Some(x) = s {
                        x.count -= k;
                        if x.count <= 0 {
                            *s = None;
                        }
                    }
                    d
                };
                if dropped.is_some() {
                    self.drop_throttle += 20;
                    out.push(CreativePacket::Swing);
                    out.push(CreativePacket::SetSlot {
                        slot: -1,
                        item: dropped,
                    });
                }
                out.push(CreativePacket::SetSlot {
                    slot,
                    item: self.m.at(l).clone(),
                });
                self.events.player_changed = true;
                self.flags.clicked = true;
                return Ok(Outgoing::Creative(out));
            }
            if slot == OUTSIDE
                && let Some(c) = self.m.cursor.take()
            {
                self.drop_throttle += 20;
                out.push(CreativePacket::Swing);
                out.push(CreativePacket::SetSlot {
                    slot: -1,
                    item: Some(c),
                });
                self.events.cursor_changed = true;
                self.flags.clicked = true;
                return Ok(Outgoing::Creative(out));
            }
        }
        let mut m = self.m.clone();
        let mut scr = self.s26[0].clone();
        self.w26.binding_curse = self.binding_curse();
        self.w26.can_drop = self.drop_throttle < 1280;
        let (result, swings) = {
            let mut sim = crate::sim26::Sim26 {
                kind: crate::sim26::Kind::Player,
                m: &mut m,
                s: &mut scr,
                w: &self.w26,
                d: &self.d26,
                reg: &self.reg26,
                mv: self.mv(),
                swings: 0,
                xp_spent: 0,
            };
            let r = sim.click(slot, button as i8, mode);
            (r, sim.swings)
        };
        if result.is_err() {
            return Err(ClickError::Unpredictable);
        }
        for _ in 0..swings {
            out.push(CreativePacket::Swing);
        }
        self.commit(m, lay);
        self.s26[0] = scr;
        self.creative_broadcast(&mut out);
        self.flags.clicked = true;
        Ok(Outgoing::Creative(out))
    }

    /// 26.1: the player's experience level (the anvil's result can only be taken with enough);
    /// set from the `experience` packet by [`Inventory::apply_raw_modern`].
    #[cfg(modern)]
    pub fn set_experience_level_modern(&mut self, level: i32) {
        self.w26.xp_level = Some(level);
    }

    /// 26.1 `update_recipes` (`declare_recipes`): the recipe item sets the furnace, smithing
    /// and stonecutter slot rules read (`(set name, item ids)`, e.g.
    /// `("minecraft:furnace_input", …)`) and the stonecutter recipes' inputs (`None` when one
    /// names a tag: shift-clicks into the stonecutter are then not predicted).
    #[cfg(modern)]
    pub fn on_recipes_modern<'a>(
        &mut self,
        sets: impl IntoIterator<Item = (&'a str, &'a [i32])>,
        stonecutter_inputs: Option<Vec<i32>>,
    ) {
        self.recipes_raw = None;
        let w = &mut self.w26;
        for v in [
            &mut w.furnace_input,
            &mut w.blast_input,
            &mut w.smoker_input,
            &mut w.smithing_base,
            &mut w.smithing_template,
            &mut w.smithing_addition,
        ] {
            v.clear();
        }
        for (name, ids) in sets {
            let target = match name.strip_prefix("minecraft:").unwrap_or(name) {
                "furnace_input" => &mut w.furnace_input,
                "blast_furnace_input" => &mut w.blast_input,
                "smoker_input" => &mut w.smoker_input,
                "smithing_base" => &mut w.smithing_base,
                "smithing_template" => &mut w.smithing_template,
                "smithing_addition" => &mut w.smithing_addition,
                _ => continue,
            };
            target.extend_from_slice(ids);
            target.sort_unstable();
            target.dedup();
        }
        w.cutter_inputs = stonecutter_inputs.map(|mut v| {
            v.sort_unstable();
            v.dedup();
            v
        });
    }

    /// Modern `open_screen`: the menu registry id (`minecraft:menu`) and the title. Menus the
    /// client has no screen for are ignored.
    #[cfg(modern)]
    pub fn on_open_screen_modern(&mut self, id: i32, menu: i32, title: ByteString) {
        self.on_open_window(id, crate::item26::window_kind(self.mv(), menu), title);
        if let ScreenState::Window(w) = &mut self.screen
            && w.id == id
        {
            w.menu = menu;
        }
        self.s26[1] = Default::default();
    }

    /// 26.1: the client-side effects of setting the open menu's container slots from a packet:
    /// vanilla runs each slot's `set` in order (the container caps it and the menu's
    /// `slotsChanged` recomputes results and remembered state: the anvil's cost and repair
    /// counts, the loom's patterns, the trade, the stonecutter input). `old` is the container
    /// before the packet; the packet's slots are replayed one by one from it.
    /// Whether the open 26.1 menu reacts to server slot packets (container caps, result hooks).
    #[cfg(modern)]
    fn hooks_modern(&self) -> bool {
        use crate::sim26::Kind;
        matches!(
            self.kind_26(),
            Kind::Anvil
                | Kind::Beacon
                | Kind::Grindstone
                | Kind::Smithing
                | Kind::Stonecutter
                | Kind::Loom
                | Kind::Cartography
                | Kind::Merchant
        )
    }

    #[cfg(modern)]
    fn inbound_modern(&mut self, old: Vec<Option<Stack>>, slots: std::ops::Range<usize>) {
        use crate::sim26::Kind;
        let kind = self.kind_26();
        if matches!(kind, Kind::Anvil | Kind::Grindstone | Kind::Loom) {
            self.d26.ensure(self.mv(), self.reg26.enchantments());
        }
        let new = std::mem::replace(&mut self.m.container, old);
        let mut scr = self.s26[1].clone();
        let mut m = std::mem::take(&mut self.m);
        let mut ok = true;
        {
            let mut sim = crate::sim26::Sim26 {
                kind,
                m: &mut m,
                s: &mut scr,
                w: &self.w26,
                d: &self.d26,
                reg: &self.reg26,
                mv: self.mv(),
                swings: 0,
                xp_spent: 0,
            };
            for k in slots.clone() {
                if k >= new.len() {
                    break;
                }
                if sim.inbound_set(k, new[k].clone()).is_err() {
                    ok = false;
                    break;
                }
            }
        }
        if !ok {
            // a hook ghast cannot compute: the packet's slots as sent
            for k in slots {
                if let (Some(d), Some(v)) = (m.container.get_mut(k), new.get(k)) {
                    *d = v.clone();
                }
            }
        }
        self.m = m;
        self.s26[1] = scr;
    }

    /// Replaces the model with the simulated one, records which parts changed and marks a
    /// crafting result unknown when its grid changed.
    fn commit(&mut self, new: Model, lay: Layout) {
        let old = std::mem::replace(&mut self.m, new);
        if old.player != self.m.player || old.craft != self.m.craft {
            self.events.player_changed = true;
        }
        if old.craft_result != self.m.craft_result {
            self.events.player_changed = true;
        }
        if old.container != self.m.container {
            self.events.window_changed = true;
        }
        if old.cursor != self.m.cursor {
            self.events.cursor_changed = true;
        }
        // 1.8: the simulation recomputed the result itself; 1.16.5: the server sends it; 1.12:
        // the client keeps the result it has, which no longer belongs to a changed grid.
        if self.version == Version::V1_8 {
            return;
        }
        if self.version == Version::V1_12 {
            if old.craft != self.m.craft {
                self.m.craft_fresh = false;
            }
            if lay.screen == Screen::Container(WindowKind::Crafting)
                && old.container.get(1..10) != self.m.container.get(1..10)
            {
                self.m.container_fresh = false;
            }
            return;
        }
        if old.craft != self.m.craft {
            self.m.craft_result_known = false;
        }
        if lay.screen == Screen::Container(WindowKind::Crafting)
            && old.container.get(1..10) != self.m.container.get(1..10)
        {
            self.m.container_result_known = false;
        }
    }

    /// Opens the player inventory GUI (key E). Returns the packet to send (1.8: the "open
    /// inventory achievement" client command; 1.12 / 1.16.5: nothing). No-op when already open.
    pub fn open_inventory(&mut self) -> Result<Option<Outgoing>, ClickError> {
        match self.screen {
            ScreenState::Inventory => return Ok(None),
            ScreenState::Window(_) => return Err(ClickError::WindowOpen),
            ScreenState::None => {}
        }
        if self.flags.clicked || self.flags.closed {
            return Err(ClickError::SameTick);
        }
        if !self.version.is_modern() && self.m.creative {
            return Ok(self.open_creative_legacy());
        }
        self.screen = ScreenState::Inventory;
        self.flags.opened = true;
        #[cfg(modern)]
        if self.version.is_modern() && self.w26.creative {
            // the creative screen adds its listener: one broadcast
            self.creative_screen = true;
            let mut out = Vec::new();
            self.creative_broadcast(&mut out);
            return Ok((!out.is_empty()).then_some(Outgoing::Creative(out)));
        }
        Ok((self.version == Version::V1_8).then_some(Outgoing::OpenInventory))
    }

    /// Closes the open GUI (Escape / E): `close_window` with its id. The client drops the
    /// cursor stack (the server throws it) and, for the 1.8 player inventory, empties the
    /// crafting grid (the server drops it).
    pub fn close(&mut self) -> Result<Outgoing, ClickError> {
        if self.screen == ScreenState::None {
            return Err(ClickError::NoScreen);
        }
        if self.flags.opened {
            return Err(ClickError::SameTick);
        }
        let id = match &self.screen {
            ScreenState::Window(w) => w.id as u8,
            _ => 0,
        };
        self.close_screen();
        self.flags.closed = true;
        Ok(Outgoing::CloseWindow(id))
    }

    /// The client side of closing the current screen handler (`closeScreen` + `close`).
    fn close_screen(&mut self) {
        #[cfg(modern)]
        {
            self.creative_screen = false;
        }
        // 26.1: only the server empties the cursor (`removed` checks for a ServerPlayer); the
        // client's player inventory menu keeps its own, so closing window 0 keeps the cursor,
        // and closing a container returns to window 0's (empty) one.
        let keep_cursor = self.version.is_modern() && self.screen == ScreenState::Inventory;
        if !keep_cursor && self.m.cursor.take().is_some() {
            self.events.cursor_changed = true;
        }
        let creative = self
            .creative16
            .as_mut()
            .is_some_and(|c| std::mem::take(&mut c.open));
        match std::mem::replace(&mut self.screen, ScreenState::None) {
            // the creative screen's handler only drops the cursor
            ScreenState::Inventory if creative => {}
            ScreenState::Inventory => {
                if self.version == Version::V1_8 {
                    // PlayerScreenHandler.close: grid dropped, result cleared (also on the client)
                    if self.m.craft.iter().any(Option::is_some) {
                        self.events.player_changed = true;
                    }
                    self.m.craft = Default::default();
                }
                self.m.craft_result = None;
                self.m.craft_result_known = !matches!(
                    self.version,
                    Version::V1_16_5 | Version::V26_1 | Version::V26_2
                );
                self.m.craft_fresh = false;
            }
            ScreenState::Window(_) => {
                self.m.container.clear();
                self.m.merchant = None;
                self.m.mount = None;
                self.m.station = None;
                self.m.container_result_known = true;
                self.m.container_fresh = true;
                #[cfg(modern)]
                {
                    self.s26[1] = Default::default();
                }
            }
            ScreenState::None => {}
        }
        if let Some((w, _)) = self.resync
            && w != 0
        {
            self.resync = None;
        }
    }

    /// Client-side use of the held stack (no packet): `n` items off the selected hotbar stack,
    /// the slot emptied when nothing is left. Vanilla does this when a right click places a block
    /// or plants seeds (1.8 `BlockItem` / `SeedItem.use`, 1.16.5 `BlockItem.place`) or
    /// when eating finishes, before the server's `set_slot`; call it then (not in creative,
    /// where vanilla keeps the count). Returns whether there was a stack.
    pub fn consume_held(&mut self, n: u8) -> bool {
        self.consume(usize::from(self.m.selected.min(8)), n)
    }

    /// Client-side durability loss of the held stack (no packet; 1.8 / 1.12 `ItemStack.damage`
    /// without Unbreaking, which rolls a random number): the damage goes up by `amount`; past
    /// the durability the stack breaks (one item less, damage 0). Vanilla does this when a hit
    /// lands on a living entity (a sword 1, a tool 2), before the server's `set_slot`. Returns
    /// whether the stack took the damage (1.16.5 / 26.x keep the damage in NBT / components:
    /// `false`, nothing changes).
    pub fn damage_held(&mut self, amount: u16) -> bool {
        if !matches!(self.version, Version::V1_8 | Version::V1_12) {
            return false;
        }
        let v = self.version;
        let k = usize::from(self.m.selected.min(8));
        let slot = &mut self.m.player[k];
        let Some(s) = slot.as_mut() else {
            return false;
        };
        let Some(max) = s.max_damage(v).filter(|&m| m > 0) else {
            return false;
        };
        if !s.is_damageable(v) {
            return false;
        }
        let d = i32::from(s.damage) + i32::from(amount);
        if d > max {
            s.count -= 1;
            s.damage = 0;
            if s.count <= 0 {
                *slot = None;
            }
        } else {
            s.damage = d as i16;
        }
        self.events.player_changed = true;
        true
    }

    /// [`consume_held`](Inventory::consume_held) for the offhand stack (1.12 / 1.16.5; no-op on
    /// 1.8).
    pub fn consume_offhand(&mut self, n: u8) -> bool {
        self.version != Version::V1_8 && self.consume(40, n)
    }

    /// Client-side end of a drink or a stew (`onItemUseFinish`, no packet): the last item of
    /// the stack in the main hand (or the off hand, 1.12+) becomes `container` (a glass bottle,
    /// a bucket, a bowl; one of it); a stack of more loses one item. Returns whether there
    /// was a stack.
    pub fn finish_into(&mut self, off_hand: bool, container: i32) -> bool {
        if off_hand && self.version == Version::V1_8 {
            return false;
        }
        let k = if off_hand {
            40
        } else {
            usize::from(self.m.selected.min(8))
        };
        let slot = &mut self.m.player[k];
        let Some(s) = slot.as_mut() else {
            return false;
        };
        if s.count > 1 {
            s.count -= 1;
        } else {
            *slot = Some(Stack::new(container, 1, 0));
        }
        self.events.player_changed = true;
        true
    }

    fn consume(&mut self, k: usize, n: u8) -> bool {
        let slot = &mut self.m.player[k];
        let Some(s) = slot.as_mut() else {
            return false;
        };
        s.count -= i32::from(n);
        if s.count <= 0 {
            *slot = None;
        }
        self.events.player_changed = true;
        true
    }

    /// What a right-click use of the stack in the main hand (or the off hand, 1.12+) does to
    /// the armor on the client (no packet; vanilla's item `use`): `true` when it equips the
    /// stack. 1.8 / 1.12.2 / 1.16.5 (`ArmorItem` / `ElytraItem`): only into an empty armor
    /// slot. 26.x (a swappable `equippable`): also swaps with the piece worn, unless that is
    /// the same item with the same components or carries the binding curse outside creative.
    /// `creative` is the game mode.
    #[must_use]
    pub fn use_equips(&self, off_hand: bool, creative: bool) -> bool {
        self.use_equip_plan(off_hand, creative).is_some()
    }

    /// The hand's player index and the armor index its use equips.
    fn use_equip_plan(&self, off_hand: bool, creative: bool) -> Option<(usize, usize)> {
        let hand = if off_hand {
            if self.version == Version::V1_8 {
                return None;
            }
            40
        } else {
            usize::from(self.m.selected.min(8))
        };
        let s = self.m.player[hand].as_ref().filter(|s| s.count > 0)?;
        let a = self.version.use_equip_target(s)?;
        let worn_k = 39 - usize::from(a);
        match &self.m.player[worn_k] {
            None => Some((hand, worn_k)),
            Some(_) if !matches!(self.version, Version::V26_1 | Version::V26_2) => None,
            // Equippable.swapWithEquipmentSlot: FAIL for the same item or a cursed piece.
            Some(w) => (!w.same_item(s)
                && (creative || self.enchantment_level(w, "binding_curse") == 0))
                .then_some((hand, worn_k)),
        }
    }

    /// Applies the right-click equip of [`Inventory::use_equips`] like the vanilla client,
    /// before the server's slot updates: 1.8 – 1.16.5 the stack moves into the armor slot and
    /// the hand empties (creative too); 26.x a single item swaps with the worn piece (in
    /// creative a copy goes on and the hand keeps its stack when the slot was empty), a larger
    /// stack puts one on and keeps the rest (not predicted when a worn piece would have to go
    /// into the inventory). Returns whether the use equips (the server's answer then follows).
    pub fn equip_from_hand(&mut self, off_hand: bool, creative: bool) -> bool {
        let Some((hand, worn_k)) = self.use_equip_plan(off_hand, creative) else {
            return false;
        };
        let modern = matches!(self.version, Version::V26_1 | Version::V26_2);
        let worn = self.m.player[worn_k].take();
        let held = self.m.player[hand].take().expect("planned with a stack");
        if !modern {
            self.m.player[worn_k] = Some(held);
        } else if held.count <= 1 {
            let to_hand = match (&worn, creative) {
                (None, true) => Some(held.clone()),
                _ => worn,
            };
            self.m.player[worn_k] = Some(held);
            self.m.player[hand] = to_hand;
        } else if worn.is_some() {
            // Inventory.add of the old piece: left to the server's updates.
            self.m.player[worn_k] = worn;
            self.m.player[hand] = Some(held);
            return true;
        } else {
            let mut one = held.clone();
            one.count = 1;
            self.m.player[worn_k] = Some(one);
            let mut rest = held;
            if !creative {
                rest.count -= 1;
            }
            self.m.player[hand] = Some(rest);
        }
        self.events.player_changed = true;
        true
    }

    /// Client-side drop of the held stack (no packet): one item off the selected hotbar stack,
    /// or all of it with `whole_stack`, the slot emptied when nothing is left. The 1.16.5 / 26.1
    /// drop key does this before the server's `set_slot` (`ClientPlayerEntity.dropSelectedItem`,
    /// `LocalPlayer.drop`: `removeStack(selected, whole ? count : 1)`); 1.8 / 1.12 do not.
    /// Returns whether there was a stack (vanilla then swings the arm).
    pub fn drop_held(&mut self, whole_stack: bool) -> bool {
        let slot = &mut self.m.player[usize::from(self.m.selected.min(8))];
        let Some(s) = slot.as_mut() else {
            return false;
        };
        if s.count <= 0 {
            return false;
        }
        if whole_stack || s.count == 1 {
            *slot = None;
        } else {
            s.count -= 1;
        }
        self.events.player_changed = true;
        true
    }

    /// Selects a hotbar slot (the behaviour's `select_slot`; vanilla's insertStack prefers it).
    pub fn select(&mut self, slot: u8) {
        if slot < 9 {
            self.m.selected = slot;
        }
    }

    // ------------------------------------------------------------------ inbound

    /// `held_item_slot` from the server.
    pub fn on_held_slot(&mut self, slot: i8) {
        if (0..9).contains(&slot) {
            self.m.selected = slot as u8;
        }
    }

    /// `open_window`: the server opened a window of this kind (`None`: a type the vanilla
    /// client has no screen for; ignored). Any open screen is closed client-side first.
    pub fn on_open_window(&mut self, id: i32, kind: Option<WindowKind>, title: ByteString) {
        let Some(kind) = kind else { return };
        if self.screen != ScreenState::None {
            self.close_screen();
        }
        let n = kind.container_len(self.version);
        self.m.container = vec![None; n];
        self.m.merchant = (kind == WindowKind::Merchant
            && crate::menus::modelled(self.version, kind))
        .then(Box::default);
        self.m.mount = None;
        self.m.furnace = 0;
        self.m.station = crate::station::Station::of(self.version, kind).map(Box::new);
        self.m.container_result_known = true;
        self.m.container_fresh = true;
        self.screen = ScreenState::Window(Window {
            id,
            kind,
            title,
            action: 0,
            properties: Vec::new(),
            menu: -1,
        });
        self.events.opened = Some(id);
        self.events.window_changed = true;
    }

    /// `close_window` from the server (closes whatever is open, whatever the id).
    pub fn on_close_window(&mut self) {
        if self.screen != ScreenState::None {
            let was_window = matches!(self.screen, ScreenState::Window(_));
            self.close_screen();
            if was_window {
                self.events.closed = true;
            }
        }
    }

    fn open_id(&self) -> i32 {
        match &self.screen {
            ScreenState::Window(w) => w.id,
            _ => 0,
        }
    }

    /// `window_items`: replaces the window's slots (`window_id` as received, unsigned byte).
    pub fn on_window_items(
        &mut self,
        window_id: i32,
        items: impl IntoIterator<Item = Option<Stack>>,
    ) {
        // One loop per version: the per-slot normalising and clamping rules are constants
        // inside it, so the legacy hot path carries no version tests.
        let items = items.into_iter();
        match self.version {
            Version::V1_8 => self.window_items_as::<V18, _>(window_id, items),
            Version::V1_12 => self.window_items_as::<V112, _>(window_id, items),
            Version::V1_16_5 => self.window_items_as::<V1165, _>(window_id, items),
            Version::V26_1 => self.window_items_as::<V261, _>(window_id, items),
            #[cfg(feature = "v26_2")]
            Version::V26_2 => self.window_items_as::<V262, _>(window_id, items),
            // no inventory exists for a disabled version
            #[cfg(not(feature = "v26_2"))]
            Version::V26_2 => {}
        }
    }

    /// `window_items` straight from the 1.8 / 1.12 wire slots: a slot equal to the stored stack
    /// is compared without being converted (no NBT refcount traffic for unchanged slots, the
    /// common case of a refreshed shop window).
    #[cfg(any(feature = "v1_8", feature = "v1_12"))]
    pub(crate) fn on_window_items_legacy(
        &mut self,
        window_id: i32,
        items: &[ghast_protocol::types::slot::legacy::Slot],
    ) {
        match self.version {
            Version::V1_8 => self.window_items_as::<V18, _>(window_id, items.iter()),
            Version::V1_12 => self.window_items_as::<V112, _>(window_id, items.iter()),
            // not reached: the legacy packets belong to 1.8 / 1.12 connections
            _ => self.on_window_items(
                window_id,
                items.iter().cloned().map(crate::stack::from_legacy_slot),
            ),
        }
    }

    #[inline]
    fn window_items_as<const V: u8, W: Incoming>(
        &mut self,
        window_id: i32,
        items: impl Iterator<Item = W>,
    ) {
        let lay = if window_id == 0 {
            Layout::new(self.version, Screen::Player)
        } else if window_id == self.open_id() {
            self.layout()
        } else {
            return;
        };
        let mut player = false;
        let mut window = false;
        let mut touched_grid = false;
        // a workstation sees its slots set one by one
        let before = (lay.screen != Screen::Player && self.m.station.is_some())
            .then(|| self.m.container.clone());
        for (i, s) in items.enumerate() {
            let Some(l) = lay.loc(i) else { break };
            if let Some(k) = hand_writes_index(l) {
                self.hotbar_writes[k] = self.hotbar_writes[k].wrapping_add(1);
            }
            touched_grid |= is_grid(lay, l);
            let clamps = if V == V261 || V == V262 {
                lay.clamps_26(l)
            } else {
                lay.clamps(l)
            };
            let slot = self.m.at_mut(l);
            if s.settle::<V>(slot, clamps) {
                match l {
                    Loc::Container(_) => window = true,
                    _ => player = true,
                }
            }
        }
        if lay.screen == Screen::Player {
            self.m.craft_result_known = true;
            self.m.craft_fresh = true;
        } else {
            self.m.container_result_known = true;
            self.m.container_fresh = true;
        }
        // villager screen: every slot set marked the trading inventory dirty
        if lay.screen != Screen::Player && self.m.merchant.is_some() {
            crate::merchant::update(self.version, &mut self.m);
        }
        // workstation: the inputs were set (the menu looked its result up), then the result
        // slot got the packet's stack
        if let Some(before) = before {
            self.station_window_items(before);
        }
        // 1.16.5 beacon: the payment inventory caps at 1 (one check per packet, not per slot)
        if V == V1165 && window && lay.screen == Screen::Container(WindowKind::Beacon) {
            lay.clamp_menu(Loc::Container(0), self.m.at_mut(Loc::Container(0)));
        }
        // 1.8: setting the grid slots made the client compute the result itself
        if V == V18 && touched_grid {
            crate::sim::recompute_1_8(&mut self.m, lay);
        }
        self.events.player_changed |= player;
        self.events.window_changed |= window;
        if lay.screen == Screen::Player {
            self.events.player_synced = true;
        } else {
            self.events.window_synced = true;
        }
        if self.resync.is_some_and(|(w, _)| w == window_id) {
            self.resync = None;
        }
    }

    /// `set_slot` (`window_id` as received, signed byte): -1 sets the cursor, 1.12 / 1.16.5 -2 a
    /// `PlayerInventory` index, window 0 slots 36..45 always reach window 0, others only the
    /// current screen.
    pub fn on_set_slot(&mut self, window_id: i32, slot: i16, item: Option<Stack>) {
        if self.creative_items_ignore_legacy(window_id, slot) {
            return;
        }
        let item = self.normalize(item);
        if window_id == -1 {
            if self.m.cursor != item {
                self.m.cursor = item;
                self.events.cursor_changed = true;
            }
            return;
        }
        let loc = if window_id == -2 && self.version != Version::V1_8 {
            usize::try_from(slot)
                .ok()
                .filter(|&k| k < 41)
                .map(Loc::Player)
        } else if window_id == 0 && (36..45).contains(&slot) {
            Layout::new(self.version, Screen::Player).loc(slot as usize)
        } else if window_id == self.open_id() {
            usize::try_from(slot)
                .ok()
                .and_then(|i| self.layout().loc(i))
        } else {
            None
        };
        let Some(l) = loc else { return };
        if let Some(k) = hand_writes_index(l) {
            self.hotbar_writes[k] = self.hotbar_writes[k].wrapping_add(1);
        }
        let mut item = item;
        if self.layout().clamps(l) {
            crate::sim::clamp_v(self.version, &mut item);
            self.layout().clamp_menu(l, &mut item);
        }
        let crafting_table = matches!(
            self.layout().screen,
            Screen::Container(WindowKind::Crafting)
        );
        let anvil = !self.version.is_modern()
            && !matches!(
                self.version,
                Version::V1_16_5 | Version::V1_12 | Version::V1_8
            )
            && matches!(self.layout().screen, Screen::Container(WindowKind::Anvil));
        match l {
            Loc::CraftResult => {
                self.m.craft_result_known = true;
                self.m.craft_fresh = true;
            }
            Loc::Container(0) if crafting_table => {
                self.m.container_result_known = true;
                self.m.container_fresh = true;
            }
            // the server's anvil output; an input set by the server makes the client compute it
            Loc::Container(2) if anvil => self.m.container_result_known = true,
            Loc::Container(0 | 1) if anvil => {
                let first = if l == Loc::Container(0) {
                    item.is_none()
                } else {
                    self.m.container.first().is_none_or(Option::is_none)
                };
                if first {
                    if let Some(out) = self.m.container.get_mut(2) {
                        *out = None;
                    }
                    self.m.container_result_known = true;
                } else {
                    self.m.container_result_known = false;
                }
            }
            // 1.12: a grid slot changed under the result the client holds
            Loc::Craft(_) if self.version == Version::V1_12 => self.m.craft_fresh = false,
            Loc::Container(1..=9) if crafting_table && self.version == Version::V1_12 => {
                self.m.container_fresh = false;
            }
            _ => {}
        }
        let s = self.m.at_mut(l);
        if *s != item {
            *s = item;
            match l {
                Loc::Container(_) => self.events.window_changed = true,
                _ => self.events.player_changed = true,
            }
        }
        if self.version == Version::V1_8 {
            // the slot's screen: window 0 for its hotbar slots, else the current one
            let lay = if window_id == 0 && (36..45).contains(&slot) {
                Layout::new(self.version, Screen::Player)
            } else {
                self.layout()
            };
            if is_grid(lay, l) {
                crate::sim::recompute_1_8(&mut self.m, lay);
            }
        }
        // villager screen: `Slot.setStack` marks the trading inventory dirty
        if matches!(l, Loc::Container(0..=2)) && self.m.merchant.is_some() {
            crate::merchant::update(self.version, &mut self.m);
        }
        if let Loc::Container(k) = l {
            self.station_inbound(Some(k));
        }
    }

    /// 26.1: a container packet arrived while a click waits to settle: the server disagreed.
    fn correction_modern(&mut self, window_id: Option<i32>) {
        if let Some(p) = self.pending
            && window_id.is_none_or(|w| w == p.window_id || w == 0)
        {
            self.pending = None;
            self.events.clicks.push(ClickResult {
                window_id: p.window_id,
                action: p.action,
                outcome: ClickOutcome::Rejected,
            });
        }
    }

    /// 26.1 `container_set_content` (vanilla `initializeContents`): window 0 or the open
    /// container's slots, its carried stack and its state id. Window 0's carried stack only
    /// shows while no container is open (the client keeps one per menu).
    pub fn on_window_items_modern(
        &mut self,
        window_id: i32,
        state_id: i32,
        items: impl IntoIterator<Item = Option<Stack>>,
        carried: Option<Stack>,
    ) {
        let current = window_id == self.open_id();
        if window_id != 0 && !current {
            return;
        }
        self.correction_modern(Some(window_id));
        #[cfg(modern)]
        let old = (window_id != 0 && self.hooks_modern()).then(|| self.m.container.clone());
        self.on_window_items(window_id, items);
        if window_id == 0 {
            self.state_player = state_id;
        } else {
            self.state_window = state_id;
            #[cfg(modern)]
            if let Some(old) = old {
                let n = old.len();
                self.inbound_modern(old, 0..n);
            }
        }
        if current {
            self.on_set_cursor(carried);
        }
    }

    /// 26.1 `container_set_slot`: window 0 slots always reach window 0 (any slot), the open
    /// container's only that container; the menu's state id follows.
    pub fn on_set_slot_modern(
        &mut self,
        window_id: i32,
        state_id: i32,
        slot: i16,
        item: Option<Stack>,
    ) {
        let item = self.normalize(item);
        let lay = if window_id == 0 {
            Layout::new(self.version, Screen::Player)
        } else if window_id == self.open_id() {
            self.layout()
        } else {
            return;
        };
        if window_id == 0 {
            self.state_player = state_id;
        } else {
            self.state_window = state_id;
        }
        self.correction_modern(Some(window_id));
        let Some(l) = usize::try_from(slot).ok().and_then(|i| lay.loc(i)) else {
            return;
        };
        let mut item = item;
        if lay.clamps_26(l) {
            crate::sim::clamp_v(self.version, &mut item);
        }
        match l {
            Loc::CraftResult => self.m.craft_result_known = true,
            Loc::Container(0) if lay.screen == Screen::Container(WindowKind::Crafting) => {
                self.m.container_result_known = true;
            }
            _ => {}
        }
        #[cfg(modern)]
        let old = (matches!(l, Loc::Container(_)) && self.hooks_modern())
            .then(|| self.m.container.clone());
        let s = self.m.at_mut(l);
        if *s != item {
            *s = item;
            match l {
                Loc::Container(_) => self.events.window_changed = true,
                _ => self.events.player_changed = true,
            }
        }
        #[cfg(modern)]
        if let (Loc::Container(k), Some(old)) = (l, old)
            && window_id != 0
        {
            self.inbound_modern(old, k..k + 1);
        }
        // the creative screen broadcasts window 0 after every server slot
        #[cfg(modern)]
        if window_id == 0 && self.creative_screen {
            let mut out = std::mem::take(&mut self.creative_echo);
            self.creative_broadcast(&mut out);
            self.creative_echo = out;
        }
    }

    /// 26.1 `set_cursor_item`: the open menu's carried stack.
    pub fn on_set_cursor(&mut self, item: Option<Stack>) {
        if self.version.is_modern() {
            self.correction_modern(None);
            // the creative screen keeps its own cursor
            #[cfg(modern)]
            if self.creative_screen {
                return;
            }
        }
        let item = self.normalize(item);
        if self.m.cursor != item {
            self.m.cursor = item;
            self.events.cursor_changed = true;
        }
    }

    /// 26.1 `set_player_inventory`: a `PlayerInventory` index (0..=40; the body armor and saddle
    /// slots 41 and 42 are not kept).
    pub fn on_set_player_inventory(&mut self, slot: i32, item: Option<Stack>) {
        self.correction_modern(None);
        let item = self.normalize(item);
        let Some(k) = usize::try_from(slot).ok().filter(|&k| k < 41) else {
            return;
        };
        if self.m.player[k] != item {
            self.m.player[k] = item;
            self.events.player_changed = true;
        }
    }

    /// The crafting recipes the server declared (1.16.5; 1.8 clients know theirs).
    #[must_use]
    pub fn recipes(&self) -> &RecipeBook {
        &self.book
    }

    /// Forgets the server's recipes and item tags (1.16.5): what reads them is refused again
    /// until they are sent anew (ghast-client calls this when `Interests::RECIPES` is
    /// switched off).
    pub fn clear_server_data(&mut self) {
        self.book = RecipeBook::default();
        self.tags16 = None;
    }

    /// 1.16.5 `declare_recipes`: replaces the client's recipes (the remainders of a taken
    /// crafting result, a furnace's shift-click, the smithing table, the stonecutter; until a
    /// declared book arrives those are refused as unpredictable).
    pub fn on_declare_recipes(&mut self, book: RecipeBook) {
        self.book = book;
    }

    /// `craft_progress_bar` (window property).
    pub fn on_window_property(&mut self, window_id: i32, property: i16, value: i16) {
        if let ScreenState::Window(w) = &mut self.screen
            && w.id == window_id
        {
            match w.properties.iter_mut().find(|p| p.0 == property) {
                Some(p) => p.1 = value,
                None => w.properties.push((property, value)),
            }
            // 1.16.5 anvil: the level cost
            if property == 0
                && let Some(crate::station::Station::Anvil(a)) = self.m.station.as_deref_mut()
            {
                a.cost = i32::from(value);
            }
            // 1.16.5 stonecutter / loom: the selected recipe / pattern (no result update)
            if property == 0
                && let Some(
                    crate::station::Station::Stonecutter { selected, .. }
                    | crate::station::Station::Loom { selected },
                ) = self.m.station.as_deref_mut()
            {
                *selected = i32::from(value);
            }
            #[cfg(modern)]
            match w.menu {
                // anvil: the cost data slot
                8 if property == 0 => self.s26[1].anvil_cost = i32::from(value),
                // loom: the selected pattern
                18 if property == 0 => self.s26[1].loom_selected = i32::from(value),
                // crafter: slot locks
                7 if (0..9).contains(&property) => {
                    let bit = 1u16 << property;
                    if value == 1 {
                        self.s26[1].crafter_locked |= bit;
                    } else {
                        self.s26[1].crafter_locked &= !bit;
                    }
                }
                _ => {}
            }
        }
    }

    /// `transaction` (window confirm) from the server. Returns the answer to send now, exactly
    /// when vanilla answers (not accepted, and the window is 0 or the open one); resolves the
    /// pending click when it is its confirm. Route every confirm through here and answer
    /// nowhere else, so each is answered exactly once.
    pub fn on_transaction(
        &mut self,
        window_id: i8,
        action: i16,
        accepted: bool,
    ) -> Option<Outgoing> {
        let w = i32::from(window_id);
        if let Some(p) = self.pending
            && p.window_id == w
            && p.action == action
        {
            self.pending = None;
            let outcome = if accepted {
                ClickOutcome::Accepted
            } else {
                self.resync = Some((w, 0));
                ClickOutcome::Rejected
            };
            self.events.clicks.push(ClickResult {
                window_id: w,
                action,
                outcome,
            });
        }
        let known = w == 0 || w == self.open_id();
        (known && !accepted).then_some(Outgoing::Confirm { window_id, action })
    }

    /// 1.12 / 1.16.5 drop empty stacks (1.16.5 also has no damage field); 1.8 keeps zero-count
    /// stacks.
    ///
    /// Works in place: moving an `Option<Stack>` through a `match` per slot cost the legacy
    /// `window_items` path measurably once `Stack` grew the 26.1 variant.
    #[inline]
    fn normalize(&self, mut s: Option<Stack>) -> Option<Stack> {
        self.normalize_in_place(&mut s);
        s
    }

    #[inline]
    fn normalize_in_place(&self, s: &mut Option<Stack>) {
        if self.version == Version::V1_8 {
            return;
        }
        if s.as_ref().is_some_and(|s| s.count <= 0 || s.id == 0) {
            *s = None;
        } else if self.version != Version::V1_12
            && let Some(st) = s
        {
            st.damage = 0;
        }
    }
}

/// The 0.4.1 names of the modern methods (26.1 was the only modern version then); each one is
/// the `_modern` method of the same name and works for every modern version.
#[cfg(modern)]
impl Inventory {
    /// Alias of [`Inventory::set_registries_modern`].
    pub fn set_registries_26_1(&mut self, reg: crate::item26::HashRegistries) {
        self.set_registries_modern(reg);
    }
    /// Alias of [`Inventory::registries_modern`].
    #[must_use]
    pub fn registries_26_1(&self) -> &crate::item26::HashRegistries {
        self.registries_modern()
    }
    /// Alias of [`Inventory::enchantment_name_modern`].
    #[must_use]
    pub fn enchantment_name_26_1(&self, id: i32) -> Option<&str> {
        self.enchantment_name_modern(id)
    }
    /// Alias of [`Inventory::set_creative_modern`].
    pub fn set_creative_26_1(&mut self, creative: bool) {
        self.set_creative_modern(creative);
    }
    /// Alias of [`Inventory::on_update_tags_modern`].
    pub fn on_update_tags_26_1(&mut self, body: bytes::Bytes) {
        self.on_update_tags_modern(body);
    }
    /// Alias of [`Inventory::on_registry_data_modern`].
    pub fn on_registry_data_26_1(&mut self, body: bytes::Bytes) {
        self.on_registry_data_modern(body);
    }
    /// Alias of [`Inventory::on_mount_screen_modern`].
    pub fn on_mount_screen_26_1(
        &mut self,
        window_id: i32,
        columns: i32,
        entity_type: i32,
        can_saddle: bool,
        can_body: bool,
    ) {
        self.on_mount_screen_modern(window_id, columns, entity_type, can_saddle, can_body);
    }
    /// Alias of [`Inventory::on_merchant_offers_modern`].
    pub fn on_merchant_offers_26_1(&mut self, body: &bytes::Bytes) {
        self.on_merchant_offers_modern(body);
    }
    /// Alias of [`Inventory::anvil_rename_modern`].
    ///
    /// # Errors
    /// As [`Inventory::anvil_rename_modern`].
    pub fn anvil_rename_26_1(&mut self, name: &str) -> Result<Option<Outgoing>, ClickError> {
        self.anvil_rename_modern(name)
    }
    /// Alias of [`Inventory::trident_spin_attack_strength_modern`].
    pub fn trident_spin_attack_strength_26_1(&mut self, stack: &Stack) -> Option<f32> {
        self.trident_spin_attack_strength_modern(stack)
    }
    /// Alias of [`Inventory::select_loom_pattern_modern`].
    ///
    /// # Errors
    /// As [`Inventory::select_loom_pattern_modern`].
    pub fn select_loom_pattern_26_1(&mut self, index: i32) -> Result<Option<Outgoing>, ClickError> {
        self.select_loom_pattern_modern(index)
    }
    /// Alias of [`Inventory::select_trade_modern`].
    ///
    /// # Errors
    /// As [`Inventory::select_trade_modern`].
    pub fn select_trade_26_1(&mut self, index: i32) -> Result<Outgoing, ClickError> {
        self.select_trade_modern(index)
    }
    /// Alias of [`Inventory::take_creative_echo_modern`].
    pub fn take_creative_echo_26_1(&mut self) -> Vec<CreativePacket> {
        self.take_creative_echo_modern()
    }
    /// Alias of [`Inventory::creative_screen_modern`].
    #[must_use]
    pub fn creative_screen_26_1(&self) -> bool {
        self.creative_screen_modern()
    }
    /// Alias of [`Inventory::set_experience_level_modern`].
    pub fn set_experience_level_26_1(&mut self, level: i32) {
        self.set_experience_level_modern(level);
    }
    /// Alias of [`Inventory::on_recipes_modern`].
    pub fn on_recipes_26_1<'a>(
        &mut self,
        sets: impl IntoIterator<Item = (&'a str, &'a [i32])>,
        stonecutter_inputs: Option<Vec<i32>>,
    ) {
        self.on_recipes_modern(sets, stonecutter_inputs);
    }
    /// Alias of [`Inventory::on_open_screen_modern`].
    pub fn on_open_screen_26_1(&mut self, id: i32, menu: i32, title: ByteString) {
        self.on_open_screen_modern(id, menu, title);
    }
}

/// The 0.4.1 names of the modern slot packets (they exist in every build, like 0.4.1's).
impl Inventory {
    /// Alias of [`Inventory::on_window_items_modern`].
    pub fn on_window_items_26_1(
        &mut self,
        window_id: i32,
        state_id: i32,
        items: impl IntoIterator<Item = Option<Stack>>,
        carried: Option<Stack>,
    ) {
        self.on_window_items_modern(window_id, state_id, items, carried);
    }
    /// Alias of [`Inventory::on_set_slot_modern`].
    pub fn on_set_slot_26_1(
        &mut self,
        window_id: i32,
        state_id: i32,
        slot: i16,
        item: Option<Stack>,
    ) {
        self.on_set_slot_modern(window_id, state_id, slot, item);
    }
}

impl Window {
    /// Alias of [`Window::menu_modern`].
    #[must_use]
    pub fn menu_26_1(&self) -> Option<i32> {
        self.menu_modern()
    }
}