autumn-web 0.6.0

An opinionated, convention-over-configuration web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
//! Changeset-style form helpers with validation and Maud rendering.
//!
//! # Overview
//!
//! [`Changeset<T>`] captures submitted form values together with per-field
//! validation errors, enabling the create/edit/validate-failure round-trip
//! in a single route handler — no manual flash-carrying, no conditional
//! error-threading.
//!
//! [`ChangesetForm<T>`] is the **default server-rendered HTML form validation
//! path** for any `T: DeserializeOwned + Serialize + Validate`.  It is the
//! axum extractor that decodes the request body (URL-encoded **or**
//! multipart), runs [`validator::Validate`], captures the CSRF token, and
//! hands the handler a ready-to-use changeset — CSRF is emitted
//! automatically when you call [`ChangesetForm::form_tag`].
//!
//! # htmx inline field validation
//!
//! Use [`text_input_htmx`] to wire up per-field inline validation with htmx.
//! The rendered input POSTs to a validation endpoint when its value changes,
//! and htmx swaps the returned field wrapper in place with `outerHTML`.
//!
//! A minimal inline-validation endpoint:
//!
//! ```rust,ignore
//! #[post("/users/validate/email")]
//! async fn validate_email(form: ChangesetForm<UserForm>) -> Markup {
//!     text_input_htmx(&form.changeset, "email", "Email", "/users/validate/email")
//! }
//! ```
//!
//! No-JavaScript fallback is automatic: when htmx is absent the browser
//! falls through to the standard full-form `POST` handler, which returns
//! 422 with inline errors via the same `text_input_htmx` partial.
//!
//! # Model vs custom form structs
//!
//! ## Pattern A — `NewModel` direct
//!
//! When the model struct already has `#[derive(Validate)]` and the form
//! shape matches, use `ChangesetForm<NewModel>` directly:
//!
//! ```rust,ignore
//! #[post("/todos")]
//! async fn create(db: Db, form: ChangesetForm<NewTodo>) -> impl IntoResponse {
//!     match form.into_valid() {
//!         Ok(new_todo) => { /* insert new_todo directly */ }
//!         Err(form) => (StatusCode::UNPROCESSABLE_ENTITY, render(&form)).into_response(),
//!     }
//! }
//! ```
//!
//! ## Pattern B — Custom workflow struct
//!
//! Define a separate form struct when the form needs extra fields (e.g.
//! `confirm_password`), different validation rules, or UI-specific derives.
//! Convert to the model type on successful validation:
//!
//! ```rust,ignore
//! #[post("/users")]
//! async fn create_user(form: ChangesetForm<RegistrationForm>) -> impl IntoResponse {
//!     match form.into_valid() {
//!         Ok(f) => { let user = NewUser::from(f); /* persist */ }
//!         Err(form) => (StatusCode::UNPROCESSABLE_ENTITY, render(&form)).into_response(),
//!     }
//! }
//! ```
//!
//! # Framework comparison
//!
//! | Framework | Changeset type | Rendering helper |
//! |-----------|---------------|-----------------|
//! | Phoenix (Elixir) | `Ecto.Changeset` | `<.input field={@form[:name]} />` |
//! | Rails (Ruby) | `errors[:field]` | `f.text_field :name` |
//! | Django (Python) | `forms.Form` | `{{ form.name.errors }}` |
//! | Autumn (Rust) | `Changeset<T>` | `form.text_input("name", "Name")` |
//!
//! # Happy-path + validation-failure in ≤ 40 `LoC`
//!
//! ```rust,ignore
//! use autumn_web::prelude::*;
//! use autumn_web::form::{ChangesetForm, Changeset, submit_button};
//! use serde::{Deserialize, Serialize};
//! use validator::Validate;
//! use axum::{http::StatusCode, response::IntoResponse};
//!
//! #[derive(Deserialize, Serialize, Validate)]
//! struct GreetForm {
//!     #[validate(length(min = 3, message = "Name must be at least 3 characters"))]
//!     name: String,
//!     #[validate(email(message = "Must be a valid email address"))]
//!     email: String,
//! }
//!
//! fn greet_form_partial(form: &ChangesetForm<GreetForm>, action: &str) -> Markup {
//!     form.form_tag(action, "post", html! {
//!         (form.text_input("name", "Full name"))
//!         (form.text_input("email", "Email"))
//!         (form.submit_button("Submit"))
//!     })
//! }
//!
//! #[get("/greet/new")]
//! async fn new_greet(csrf: CsrfToken) -> Markup {
//!     let blank = ChangesetForm::blank(GreetForm { name: String::new(), email: String::new() },
//!                                     csrf.token());
//!     greet_form_partial(&blank, "/greet")
//! }
//!
//! #[post("/greet")]
//! async fn create_greet(form: ChangesetForm<GreetForm>) -> impl IntoResponse {
//!     match form.into_valid() {
//!         Ok(f) => html! { p { "Hello, " (f.name) "!" } }.into_response(),
//!         Err(form) => (StatusCode::UNPROCESSABLE_ENTITY,
//!                       greet_form_partial(&form, "/greet")).into_response(),
//!     }
//! }
//! ```
//!
//! # CSRF
//!
//! The CSRF token is captured automatically by the [`ChangesetForm`] extractor
//! from the request extensions set by [`crate::security::CsrfLayer`].
//! Calling [`ChangesetForm::form_tag`] emits the hidden `_csrf` input with no
//! additional developer action in POST handlers.
//!
//! For GET handlers (new/edit forms), construct the form context via
//! [`ChangesetForm::blank`], passing `csrf.token()` from a [`crate::security::CsrfToken`]
//! extractor — the only extra line needed is the parameter itself.
//!
//! # Multipart
//!
//! When the `multipart` feature is enabled, [`ChangesetForm`] also decodes
//! `multipart/form-data` bodies.  File fields are skipped; only text fields
//! are decoded.  File upload storage is out of scope here (see issue #494).
//!
//! # Non-htmx fallback
//!
//! When JavaScript is disabled htmx falls back to a standard form POST.
//! The handler pattern above still works: browsers display the 422 page
//! inline.  For a redirect-after-post pattern, serialise `cs.errors()` into
//! the flash store and redirect; restore on the next GET.

// autumn-panic-gate: request-path module — production code path must be panic-free.
// See CONTRIBUTING.md "Request-path panic gate". Justify exceptions with
// #[allow(clippy::<lint>, reason = "…")] at the narrowest scope.
#![cfg_attr(
    not(test),
    deny(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        clippy::unreachable,
        clippy::todo,
        clippy::unimplemented,
        clippy::indexing_slicing,
    )
)]

use std::collections::HashMap;

use axum::extract::{FromRequest, Request};
use axum::response::IntoResponse;
use serde::Serialize;

// ── Changeset<T> ───────────────────────────────────────────────────

/// Carries submitted form values and per-field validation errors.
///
/// Analogous to `Ecto.Changeset` in Phoenix or `errors[:field]` in Rails.
///
/// Obtain a `Changeset` from:
/// - [`Changeset::new`] for a blank/valid changeset
/// - [`IntoChangeset::into_changeset`] after manual construction
/// - The [`ChangesetForm`] axum extractor (preferred)
#[derive(Debug)]
pub struct Changeset<T> {
    data: T,
    errors: HashMap<String, Vec<String>>,
}

impl<T> Changeset<T> {
    /// Create a changeset with no errors (valid state).
    pub fn new(data: T) -> Self {
        Self {
            data,
            errors: HashMap::new(),
        }
    }

    /// Create a changeset pre-loaded with field-level errors.
    pub const fn from_errors(data: T, errors: HashMap<String, Vec<String>>) -> Self {
        Self { data, errors }
    }

    /// Returns `true` when there are no field-level errors.
    pub fn is_valid(&self) -> bool {
        self.errors.is_empty()
    }

    /// Returns the validation messages for `field`, or an empty slice.
    pub fn errors_for(&self, field: &str) -> &[String] {
        self.errors.get(field).map_or(&[], Vec::as_slice)
    }

    /// Returns every field-level error keyed by field name.
    ///
    /// Iteration order is unspecified (it is a [`HashMap`]); callers that render
    /// a stable list (e.g. [`crate::widgets::error_summary`]) should sort. Used
    /// by the error-summary widget to enumerate all messages without the caller
    /// needing to know the field set in advance.
    #[must_use]
    pub const fn all_errors(&self) -> &HashMap<String, Vec<String>> {
        &self.errors
    }

    /// Unwrap the inner data regardless of validity.
    pub fn into_inner(self) -> T {
        self.data
    }

    /// Consume the changeset, returning `Ok(T)` if valid or `Err(self)` if not.
    ///
    /// # Errors
    ///
    /// Returns `Err(self)` when there are field-level validation errors.
    pub fn into_valid(self) -> Result<T, Self> {
        if self.is_valid() {
            Ok(self.data)
        } else {
            Err(self)
        }
    }

    /// Shared reference to the inner data.
    pub const fn data(&self) -> &T {
        &self.data
    }

    /// All field errors as a map (field name → list of messages).
    pub const fn errors(&self) -> &HashMap<String, Vec<String>> {
        &self.errors
    }
}

impl<T: Serialize> Changeset<T> {
    /// Serialize the value of `field` from the inner data to a `String`.
    ///
    /// Used by rendering helpers to re-populate `<input value="…">` after a
    /// failed submission.  Returns `None` for missing or non-scalar fields.
    pub fn field_value(&self, field: &str) -> Option<String> {
        let json = serde_json::to_value(&self.data).ok()?;
        match json.get(field)? {
            serde_json::Value::String(s) => Some(s.clone()),
            serde_json::Value::Number(n) => Some(n.to_string()),
            serde_json::Value::Bool(b) => Some(b.to_string()),
            _ => None,
        }
    }
}

// ── IntoChangeset ──────────────────────────────────────────────────

/// Validate `self` and wrap in a [`Changeset`].
///
/// Blanket-implemented for every type that implements [`validator::Validate`].
pub trait IntoChangeset: Sized {
    /// Run validation and produce a `Changeset<Self>`.
    fn into_changeset(self) -> Changeset<Self>;
}

impl<T: validator::Validate> IntoChangeset for T {
    fn into_changeset(self) -> Changeset<Self> {
        match validator::Validate::validate(&self) {
            Ok(()) => Changeset::new(self),
            Err(errors) => Changeset::from_errors(self, validation_errors_to_map(&errors)),
        }
    }
}

// ── ChangesetForm<T> ───────────────────────────────────────────────

/// Axum extractor that decodes a form body, runs validation, and captures the
/// CSRF token — all in one step.
///
/// Supports both `application/x-www-form-urlencoded` (always) and
/// `multipart/form-data` (when the `multipart` feature is enabled).
///
/// Unlike [`crate::validation::Valid`], this extractor **never** rejects with
/// 422 — errors live in the [`Changeset`] and the handler decides how to
/// respond.  Fails with 400 only when the body cannot be decoded into `T` at
/// all.
///
/// # CSRF — no extra developer action in POST handlers
///
/// The extractor reads the `CsrfToken` from request extensions (placed there
/// by [`crate::security::CsrfLayer`]).  Calling
/// [`ChangesetForm::form_tag`] then emits the hidden `_csrf` input
/// automatically — no separate `CsrfToken` parameter needed.
///
/// For GET handlers (new/edit), use [`ChangesetForm::blank`] and pass
/// `csrf.token()` from a `CsrfToken` extractor.
///
/// # Example
///
/// ```rust,ignore
/// #[post("/users")]
/// async fn create(form: ChangesetForm<NewUser>) -> impl IntoResponse {
///     match form.into_valid() {
///         Ok(user) => { /* persist & redirect */ }
///         Err(form) => (StatusCode::UNPROCESSABLE_ENTITY,
///                       form.form_tag("/users", "post", html! {
///                           (form.text_input("name", "Name"))
///                           (form.submit_button("Save"))
///                       })).into_response()
///     }
/// }
/// ```
pub struct ChangesetForm<T> {
    /// The validated (or invalid) changeset.
    pub changeset: Changeset<T>,
    pub(crate) csrf_token: Option<String>,
    pub(crate) csrf_field: String,
}

impl<T> ChangesetForm<T> {
    /// Build a blank form context for GET handlers (new / edit).
    ///
    /// Wraps `data` in a valid [`Changeset`] and stores `csrf_token` so that
    /// [`ChangesetForm::form_tag`] can emit the hidden input automatically.
    ///
    /// ```rust,ignore
    /// #[get("/users/new")]
    /// async fn new_user(csrf: CsrfToken) -> Markup {
    ///     let ctx = ChangesetForm::blank(UserForm::default(), csrf.token());
    ///     ctx.form_tag("/users", "post", html! { (ctx.text_input("name", "Name")) })
    /// }
    /// ```
    pub fn blank(data: T, csrf_token: &str) -> Self {
        Self {
            changeset: Changeset::new(data),
            csrf_token: Some(csrf_token.to_owned()),
            csrf_field: "_csrf".to_owned(),
        }
    }

    /// Construct a display-only `ChangesetForm` with no CSRF token.
    ///
    /// Use this on GET handlers where CSRF middleware is not active, or when
    /// the form will be re-rendered purely for display (e.g. an initial blank
    /// form on a page that does not enforce CSRF).  [`form_tag`](Self::form_tag)
    /// will omit the hidden CSRF input when no token is stored.
    #[must_use]
    pub fn without_csrf(data: T) -> Self {
        Self {
            changeset: Changeset::new(data),
            csrf_token: None,
            csrf_field: "_csrf".to_owned(),
        }
    }

    /// Wrap a pre-built [`Changeset`] (which may already carry validation errors)
    /// in a `ChangesetForm` without a CSRF token.
    ///
    /// Useful in tests and cases where a `Changeset` was produced externally
    /// (e.g. via [`IntoChangeset`]) before constructing a form for rendering.
    #[must_use]
    pub fn from_changeset(changeset: Changeset<T>) -> Self {
        Self {
            changeset,
            csrf_token: None,
            csrf_field: "_csrf".to_owned(),
        }
    }

    /// Override the CSRF form-field name used by [`ChangesetForm::form_tag`].
    ///
    /// Call this when `security.csrf.form_field` is set to something other than
    /// `"_csrf"` (e.g. `"authenticity_token"`).  The `CsrfFormField` extension
    /// populated by [`from_request`](Self::from_request) sets this automatically
    /// for POST handlers; use this builder on GET handlers that construct a blank
    /// form with [`blank`](Self::blank).
    #[must_use]
    pub fn with_csrf_field(mut self, field: impl Into<String>) -> Self {
        self.csrf_field = field.into();
        self
    }

    /// The CSRF token captured from the request, if the CSRF middleware is active.
    pub fn csrf_token(&self) -> Option<&str> {
        self.csrf_token.as_deref()
    }

    /// Consume and return only the inner [`Changeset`].
    pub fn into_changeset(self) -> Changeset<T> {
        self.changeset
    }

    /// Return `Ok(T)` if the changeset is valid, `Err(self)` if not.
    ///
    /// The `Err` branch returns the whole `ChangesetForm` (with its CSRF
    /// token) so the handler can immediately call `form.form_tag()` to
    /// re-render with inline errors.
    ///
    /// # Errors
    ///
    /// Returns `Err(self)` when the inner changeset has field-level validation errors.
    pub fn into_valid(self) -> Result<T, Self> {
        if self.changeset.is_valid() {
            Ok(self.changeset.into_inner())
        } else {
            Err(self)
        }
    }
}

/// Dereferences to [`Changeset<T>`] so all changeset methods are available
/// directly on `ChangesetForm<T>` — `form.is_valid()`, `form.errors_for(…)`,
/// etc.
impl<T> std::ops::Deref for ChangesetForm<T> {
    type Target = Changeset<T>;
    fn deref(&self) -> &Self::Target {
        &self.changeset
    }
}

/// Maud rendering methods — emit form HTML with automatic CSRF injection.
#[cfg(feature = "maud")]
impl<T: Serialize> ChangesetForm<T> {
    /// Render a `<form>` element with the stored CSRF token injected as a
    /// hidden input — the field name honours `security.csrf.form_field` from
    /// config, so no developer action is required even for non-default names.
    #[must_use]
    #[allow(clippy::needless_pass_by_value)]
    pub fn form_tag(&self, action: &str, method: &str, content: maud::Markup) -> maud::Markup {
        form_tag_inner(
            action,
            method,
            &self.csrf_field,
            self.csrf_token.as_deref(),
            None,
            content,
        )
    }

    /// Render a labeled `<input type="text">` for `field` using the stored
    /// changeset (value + errors).
    pub fn text_input(&self, field: &str, label: &str) -> maud::Markup {
        text_input(&self.changeset, field, label)
    }

    /// Render a labeled `<input type="text">` with htmx inline-validation
    /// attributes for `field`.
    ///
    /// Delegates to [`text_input_htmx`]; see that function for full docs.
    pub fn text_input_htmx(&self, field: &str, label: &str, validate_url: &str) -> maud::Markup {
        text_input_htmx(&self.changeset, field, label, validate_url)
    }

    /// Render a labeled `<input type="text">` with htmx inline-validation
    /// attributes for `field`, excluding the configured submit-token field
    /// `token_field` from the validation POST.
    ///
    /// Delegates to [`text_input_htmx_with_token_field`]; use this when the app
    /// customizes `[security.submit_token].field_name` (issue #1843). Source the
    /// name from the [`SubmitFormField`](crate::security::SubmitFormField)
    /// extractor.
    pub fn text_input_htmx_with_token_field(
        &self,
        field: &str,
        label: &str,
        validate_url: &str,
        token_field: &str,
    ) -> maud::Markup {
        text_input_htmx_with_token_field(&self.changeset, field, label, validate_url, token_field)
    }

    /// Render a `<button type="submit">` with `label`.
    pub fn submit_button(&self, label: &str) -> maud::Markup {
        submit_button(label)
    }
}

impl<S, T> FromRequest<S> for ChangesetForm<T>
where
    S: Send + Sync,
    T: serde::de::DeserializeOwned + validator::Validate + Send,
{
    type Rejection = axum::response::Response;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        // Capture CSRF token and field name before the body is consumed.
        let csrf_token = req
            .extensions()
            .get::<crate::security::CsrfToken>()
            .map(|t| t.token().to_string());
        let csrf_field = req
            .extensions()
            .get::<crate::security::csrf::CsrfFormField>()
            .map_or_else(|| "_csrf".to_owned(), |f| f.0.clone());

        let data: T = decode_form_body(req, state).await?;

        Ok(Self {
            changeset: data.into_changeset(),
            csrf_token,
            csrf_field,
        })
    }
}

/// Decode a form body — URL-encoded always, multipart when that feature is on.
async fn decode_form_body<T, S>(req: Request, state: &S) -> Result<T, axum::response::Response>
where
    T: serde::de::DeserializeOwned + validator::Validate + Send,
    S: Send + Sync,
{
    let content_type = req
        .headers()
        .get(http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or_default()
        .to_string();

    #[cfg(feature = "multipart")]
    if content_type.starts_with("multipart/form-data") {
        return decode_multipart(req, state).await;
    }

    // Same content-type gate axum's own `Form`/`RawForm` extractors apply: a
    // POST whose Content-Type isn't (or doesn't start with) the form-urlencoded
    // mime type is rejected outright, rather than being decoded anyway. `Bytes`
    // alone has no opinion on Content-Type, so this must be checked explicitly
    // now that we no longer route through `axum::extract::Form`.
    if !content_type.starts_with("application/x-www-form-urlencoded") {
        return Err((
            axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
            "Form requests must have `Content-Type: application/x-www-form-urlencoded`",
        )
            .into_response());
    }

    // Buffer the body through axum's own `Bytes` extractor so the configured
    // `DefaultBodyLimit` is enforced exactly as it would be for a single-shot
    // `Form` extraction (a bare `to_bytes(.., usize::MAX)` would accept an
    // unbounded body and defeat that protection).
    let (parts, body) = req.into_parts();
    let bytes_req = Request::from_parts(parts, body);
    let bytes = axum::body::Bytes::from_request(bytes_req, state)
        .await
        .map_err(IntoResponse::into_response)?;

    decode_urlencoded_dropping_blank_optional_fields::<T>(&bytes)
        .map_err(|e| (axum::http::StatusCode::BAD_REQUEST, e.to_string()).into_response())
}

/// Deserialize `T` from `application/x-www-form-urlencoded` bytes, tolerating
/// blank values for non-string `Option<T>` fields (a number/date/uuid input
/// the user left empty submits `field=`, which `serde_urlencoded` otherwise
/// rejects outright — an empty string is not a valid `i32`/`Uuid`/etc., so it
/// never gets the chance to become "missing" and deserialize as `None`).
///
/// [`serde_path_to_error`] pinpoints exactly which field a decode failure
/// came from; if that field's submitted value is blank, drop just that one
/// pair and retry. This converges within (number of blank fields) iterations
/// and never touches a field that decoded successfully — critically, it
/// leaves a blank *required* `String` field's pair alone (an empty string
/// already deserializes fine for `String`, so that field never appears as
/// the error path), letting it flow into the `Changeset` as a real
/// validation error instead of being dropped into a spurious "missing
/// field" decode failure. A genuinely malformed (non-blank) value still
/// fails immediately, matching the "undecodable body is a hard 400" contract.
///
/// # Scope: any field that already tolerates a missing key
///
/// This helper can only observe "decoding this field's blank value failed,
/// and removing the key fixes it" — it cannot see the target type, so it
/// cannot distinguish `Option<T>` from a required `#[serde(default)]` field
/// (e.g. [`checkbox_input`]'s documented `#[serde(default)] published: bool`
/// convention for an unchecked box). Dropping the key makes both resolve to
/// whatever that field already treats a *missing* key as — `None` or the
/// `#[serde(default)]` value respectively. This is intentionally consistent
/// rather than a leak: a field with no such tolerance (no `Option`, no
/// `#[serde(default)]`) still hard-fails, because removing its key surfaces
/// a *missing field* error next iteration instead of resolving — see
/// `blank_required_field_without_default_still_fails_to_decode` for the
/// guarantee. And nothing new is reachable through this leniency: a client
/// that wants a `#[serde(default)]` field to take its default value could
/// already get that by omitting the key entirely.
pub(crate) fn decode_urlencoded_dropping_blank_optional_fields<T: serde::de::DeserializeOwned>(
    bytes: &[u8],
) -> Result<T, serde_path_to_error::Error<serde_urlencoded::de::Error>> {
    let mut pairs: Vec<(String, String)> = url::form_urlencoded::parse(bytes)
        .map(|(k, v)| (k.into_owned(), v.into_owned()))
        .collect();

    loop {
        let encoded = url::form_urlencoded::Serializer::new(String::new())
            .extend_pairs(pairs.iter().map(|(k, v)| (k.as_str(), v.as_str())))
            .finish();
        let deserializer =
            serde_urlencoded::Deserializer::new(url::form_urlencoded::parse(encoded.as_bytes()));
        match serde_path_to_error::deserialize(deserializer) {
            Ok(data) => return Ok(data),
            Err(err) => {
                let field = err.path().to_string();
                let Some(pos) = pairs.iter().position(|(k, v)| *k == field && v.is_empty()) else {
                    return Err(err);
                };
                pairs.remove(pos);
            }
        }
    }
}

/// Fuzzing seam: run the `application/x-www-form-urlencoded` body decoder
/// (including the blank-optional-field retry loop) over arbitrary bytes.
/// Deserializes into a permissive `HashMap` so any well-formed pair shape is
/// accepted and only panics (not decode errors) are of interest.
///
/// Compiled only under `--cfg fuzzing`; the published crate is unaffected.
/// See `fuzz/fuzz_targets/body.rs`.
#[cfg(fuzzing)]
pub fn __fuzz_decode_urlencoded(bytes: &[u8]) {
    let _ = decode_urlencoded_dropping_blank_optional_fields::<
        std::collections::HashMap<String, String>,
    >(bytes);
}

/// Decode `multipart/form-data` text fields and deserialize into `T`.
///
/// File-upload fields are skipped (file storage is out of scope here).
/// The collected text pairs are re-encoded as URL-encoded so that
/// `serde_urlencoded` handles the same type coercions axum's `Form` does.
#[cfg(feature = "multipart")]
async fn decode_multipart<T, S>(req: Request, state: &S) -> Result<T, axum::response::Response>
where
    T: serde::de::DeserializeOwned,
    S: Send + Sync,
{
    let mut multipart = axum::extract::Multipart::from_request(req, state)
        .await
        .map_err(IntoResponse::into_response)?;

    let mut pairs: Vec<(String, String)> = Vec::new();

    loop {
        let field = multipart
            .next_field()
            .await
            .map_err(|e| (axum::http::StatusCode::BAD_REQUEST, e.to_string()).into_response())?;

        let Some(field) = field else { break };

        let name = match field.name() {
            Some(n) => n.to_string(),
            None => continue,
        };

        // Skip file-upload fields; text-only decoding is in scope.
        if field.file_name().is_some() {
            continue;
        }

        let value = field
            .text()
            .await
            .map_err(|e| (axum::http::StatusCode::BAD_REQUEST, e.to_string()).into_response())?;

        pairs.push((name, value));
    }

    // Re-encode as URL-encoded so serde_urlencoded handles type coercions
    // ("30" → u32, "true" → bool, etc.) consistently with the Form extractor.
    let encoded = url::form_urlencoded::Serializer::new(String::new())
        .extend_pairs(pairs.iter().map(|(k, v)| (k.as_str(), v.as_str())))
        .finish();

    match serde_urlencoded::from_str::<T>(&encoded) {
        Ok(data) => Ok(data),
        Err(first_err) => {
            // Same blank-optional-field accommodation as `decode_form_body`:
            // a number/date/uuid field left empty submits an empty text
            // value, which `serde_urlencoded` rejects for non-string
            // `Option<T>` fields — retry with those fields dropped entirely
            // so they deserialize as `None`.
            let (blank, non_blank): (Vec<_>, Vec<_>) =
                pairs.iter().partition(|(_, v)| v.is_empty());
            if blank.is_empty() {
                return Err(
                    (axum::http::StatusCode::BAD_REQUEST, first_err.to_string()).into_response()
                );
            }
            let filtered = url::form_urlencoded::Serializer::new(String::new())
                .extend_pairs(non_blank.iter().map(|(k, v)| (k.as_str(), v.as_str())))
                .finish();
            serde_urlencoded::from_str::<T>(&filtered).map_err(|_| {
                (axum::http::StatusCode::BAD_REQUEST, first_err.to_string()).into_response()
            })
        }
    }
}

// ── Internal helpers ───────────────────────────────────────────────

pub(crate) fn validation_errors_to_map(
    errors: &validator::ValidationErrors,
) -> HashMap<String, Vec<String>> {
    let mut map = HashMap::new();
    collect_errors(errors, "", &mut map);
    map
}

fn collect_errors(
    errors: &validator::ValidationErrors,
    prefix: &str,
    map: &mut HashMap<String, Vec<String>>,
) {
    for (field, kind) in errors.errors() {
        let key = if prefix.is_empty() {
            (*field).to_string()
        } else {
            format!("{prefix}.{field}")
        };
        match kind {
            validator::ValidationErrorsKind::Field(errs) => {
                let messages: Vec<String> = errs
                    .iter()
                    .map(|e| {
                        e.message.as_ref().map_or_else(
                            || format!("validation failed: {}", e.code),
                            ToString::to_string,
                        )
                    })
                    .collect();
                map.entry(key).or_default().extend(messages);
            }
            validator::ValidationErrorsKind::Struct(nested) => {
                collect_errors(nested, &key, map);
            }
            validator::ValidationErrorsKind::List(list) => {
                for (idx, nested) in list {
                    let indexed_key = format!("{key}[{idx}]");
                    collect_errors(nested, &indexed_key, map);
                }
            }
        }
    }
}

// ── Standalone Maud helpers ─────────────────────────────────────────
//
// These are the building blocks used by `ChangesetForm` methods.
// They are also public so GET handlers can use them with a bare `Changeset`.

/// Render a `<form>` element wrapping `content`.
///
/// When `csrf_token` is `Some(token)`, a hidden `<input name="_csrf">` is
/// emitted automatically — compatible with [`crate::security::CsrfLayer`]
/// using the default field name `_csrf`.
///
/// In **POST** handlers, prefer [`ChangesetForm::form_tag`] which injects
/// the token **and** honours any custom `security.csrf.form_field` from config.
#[cfg(feature = "maud")]
#[must_use]
#[allow(clippy::needless_pass_by_value)]
pub fn form_tag(
    action: &str,
    method: &str,
    csrf_token: Option<&str>,
    content: maud::Markup,
) -> maud::Markup {
    form_tag_inner(action, method, "_csrf", csrf_token, None, content)
}

/// Internal: render a `<form>` element using an explicit CSRF field name.
///
/// When `method` is `PUT`, `PATCH`, or `DELETE` (case-insensitive), the
/// browser-facing form method is rewritten to `POST` and a hidden
/// `<input name="_method" value="...">` is emitted so the autumn
/// [`MethodOverrideLayer`](crate::middleware::MethodOverrideLayer) can
/// rewrite the request back to the declared method before route matching.
/// This lets server-rendered HTML target `#[put]` / `#[patch]` /
/// `#[delete]` routes without any client JavaScript.
///
/// `enctype` is emitted verbatim when `Some` (e.g.
/// `Some("multipart/form-data")` for [`FormFor`] forms containing a file
/// input) so every `<form>` — whatever its encoding — flows through this one
/// audited CSRF/method-override path.
#[cfg(feature = "maud")]
#[allow(clippy::needless_pass_by_value)]
pub(crate) fn form_tag_inner(
    action: &str,
    method: &str,
    csrf_field: &str,
    csrf_token: Option<&str>,
    enctype: Option<&str>,
    content: maud::Markup,
) -> maud::Markup {
    let (browser_method, override_value) = browser_method_and_override(method);
    maud::html! {
        form action=(action) method=(browser_method) enctype=[enctype] {
            @if let Some(override_method) = override_value {
                input
                    type="hidden"
                    name=(crate::middleware::DEFAULT_METHOD_OVERRIDE_FIELD)
                    value=(override_method);
            }
            @if let Some(token) = csrf_token {
                input type="hidden" name=(csrf_field) value=(token);
            }
            (content)
        }
    }
}

/// Translate a declared form method into the browser transport method and
/// any required `_method` override value.
///
/// Returns `(transport, override)` where `override` is `Some(value)` only
/// when the declared method needs a hidden `_method` field.
#[cfg(feature = "maud")]
fn browser_method_and_override(method: &str) -> (&'static str, Option<&'static str>) {
    let trimmed = method.trim();
    if trimmed.eq_ignore_ascii_case("PUT") {
        ("post", Some("PUT"))
    } else if trimmed.eq_ignore_ascii_case("PATCH") {
        ("post", Some("PATCH"))
    } else if trimmed.eq_ignore_ascii_case("DELETE") {
        ("post", Some("DELETE"))
    } else if trimmed.eq_ignore_ascii_case("GET") {
        ("get", None)
    } else {
        ("post", None)
    }
}

/// Render a hidden `<input name="_method" value="...">` field for the
/// declared HTTP method.
///
/// Use this directly when constructing a form by hand (without
/// [`ChangesetForm`] or [`form_tag`]) targeting a `#[put]`, `#[patch]`,
/// or `#[delete]` route from a plain HTML browser submission.
///
/// ```rust,ignore
/// use autumn_web::form::method_input;
///
/// maud::html! {
///     form method="post" action="/posts/42" {
///         (method_input("DELETE"))
///         button { "Delete post" }
///     }
/// }
/// ```
#[cfg(feature = "maud")]
#[must_use]
pub fn method_input(method: &str) -> maud::Markup {
    let normalized = method.trim();
    let value = if normalized.eq_ignore_ascii_case("PUT") {
        "PUT"
    } else if normalized.eq_ignore_ascii_case("PATCH") {
        "PATCH"
    } else if normalized.eq_ignore_ascii_case("DELETE") {
        "DELETE"
    } else {
        // `GET`/`POST` (and anything else) don't need an override — emit
        // nothing rather than producing an invalid override field.
        return maud::html! {};
    };
    maud::html! {
        input
            type="hidden"
            name=(crate::middleware::DEFAULT_METHOD_OVERRIDE_FIELD)
            value=(value);
    }
}

/// Render a labeled `<input type="text">` tied to a changeset field.
///
/// - Sets `name` and `id` to `field`
/// - Wraps in a `<div id="{field}-field">` for stable htmx targeting
/// - Populates `value` from the changeset's serialized data
/// - Adds `aria-invalid="true"` + `aria-describedby` when errors exist
/// - Emits a `<div role="alert">` with per-message `<p>` error elements
///
/// Use [`text_input_htmx`] to add htmx inline-validation attributes.
#[cfg(feature = "maud")]
#[must_use]
pub fn text_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let value = changeset.field_value(field).unwrap_or_default();
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            label for=(field) class="autumn-field__label" { (label) }
            input
                type="text"
                id=(field)
                name=(field)
                value=(value)
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" });
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Render a labeled `<input type="text">` with htmx inline-validation attributes.
///
/// Like [`text_input`] but adds `hx-post`, `hx-trigger="change"`,
/// `hx-target="closest [data-autumn-field-wrapper]"`, `hx-swap="outerHTML"`,
/// `hx-include="closest form"`, and `hx-params="not _submit_token"` to the input
/// element so htmx POSTs the whole form to `validate_url` after a changed value
/// is committed and swaps the returned field wrapper in place — no JavaScript
/// required.
///
/// The `hx-params="not _submit_token"` filter drops the hidden one-time
/// submit-token field (issue #1360) from the inline-validation POST: `SubmitTokenLayer`
/// consumes any `_submit_token` a mutating POST carries, so without this filter
/// the first field validation would spend the token and the real create/update
/// submit would replay the validation fragment instead of running the mutation.
///
/// # Custom `field_name` limitation
///
/// This helper hardcodes the **default** submit-token field name
/// `_submit_token` in its `hx-params` filter, so it excludes only that default
/// from inline htmx validation posts. If you customize
/// `[security.submit_token].field_name` **and** hand-write a live-validation
/// form using these helpers, the filter will not exclude your custom field, so
/// the token leaks into the validation POST and `SubmitTokenLayer` consumes it.
///
/// The proper resolution is [`text_input_htmx_with_token_field`], which takes
/// the configured field name and filters `not <field_name>` instead. Source
/// the name at request time from the [`SubmitFormField`](crate::security::SubmitFormField)
/// extractor. Alternatively, add your validation route(s) to
/// `[security.submit_token].exempt_paths` so the one-time token is not consumed
/// by validation requests. Generated scaffolds keep the default field name and
/// wire their validation routes into `exempt_paths` automatically, so this only
/// affects hand-written forms with a customized `field_name`.
///
/// The inline-validation handler should extract [`ChangesetForm<T>`],
/// validate, and return `text_input_htmx(...)` for just the single field.
///
/// # Example
///
/// ```rust,ignore
/// // Render:
/// form.text_input_htmx("email", "Email", "/users/validate/email")
///
/// // Inline-validation handler:
/// #[post("/users/validate/email")]
/// async fn validate_email(form: ChangesetForm<UserForm>) -> Markup {
///     text_input_htmx(&form.changeset, "email", "Email", "/users/validate/email")
/// }
/// ```
#[cfg(feature = "maud")]
#[must_use]
pub fn text_input_htmx<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
    validate_url: &str,
) -> maud::Markup {
    text_input_htmx_with_token_field(
        changeset,
        field,
        label,
        validate_url,
        DEFAULT_SUBMIT_TOKEN_FIELD,
    )
}

/// The default `[security.submit_token].field_name`, matching
/// `default_submit_token_field()` in [`crate::security`]. Used by
/// [`text_input_htmx`] / [`required_text_input_htmx`] to preserve their original
/// hardcoded `hx-params="not _submit_token"` behaviour when delegating to the
/// `*_with_token_field` variants.
#[cfg(feature = "maud")]
const DEFAULT_SUBMIT_TOKEN_FIELD: &str = "_submit_token";

/// Like [`text_input_htmx`] but excludes the caller-supplied submit-token field
/// name (`token_field`) from the inline-validation POST instead of the hardcoded
/// default `_submit_token`.
///
/// Use this when the app customizes `[security.submit_token].field_name` and
/// hand-writes a live-validation form: pass the configured field name so the
/// emitted `hx-params="not <token_field>"` filter drops the actual one-time
/// submit-token field. Without this, the token leaks into the validation POST,
/// `SubmitTokenLayer` consumes it, and the real create/update submit replays the
/// validation fragment instead of running the mutation (issue #1843).
///
/// Callers obtain the configured field name at request time from the
/// [`SubmitFormField`](crate::security::SubmitFormField) extractor. Passing
/// `"_submit_token"` here is equivalent to calling [`text_input_htmx`].
///
/// # Example
///
/// ```rust,ignore
/// async fn validate_email(
///     form: ChangesetForm<UserForm>,
///     SubmitFormField(token_field): SubmitFormField,
/// ) -> Markup {
///     text_input_htmx_with_token_field(
///         &form.changeset, "email", "Email", "/users/validate/email", &token_field,
///     )
/// }
/// ```
#[cfg(feature = "maud")]
#[must_use]
pub fn text_input_htmx_with_token_field<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
    validate_url: &str,
    token_field: &str,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let value = changeset.field_value(field).unwrap_or_default();
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");
    let target = "closest [data-autumn-field-wrapper]";
    let hx_params = format!("not {token_field}");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" data-autumn-field-wrapper=(field) {
            label for=(field) class="autumn-field__label" { (label) }
            input
                type="text"
                id=(field)
                name=(field)
                value=(value)
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" })
                hx-post=(validate_url)
                hx-trigger="change"
                hx-target=(target)
                hx-swap="outerHTML"
                hx-include="closest form"
                hx-params=(hx_params);
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Like [`text_input_htmx`] but for a required field: adds `required` and
/// `aria-required="true"` on the `<input>`, exactly like
/// [`required_text_input`] does for the non-htmx variant.
///
/// Without this, a required field wired up with `text_input_htmx` has no
/// client-side "must fill this in" signal, and a server-side rule that
/// happens to permit an empty string (e.g. a max-only `length` rule) would
/// let a blank required field through silently.
///
/// Like [`text_input_htmx`], this helper hardcodes the **default** submit-token
/// field name in its `hx-params="not _submit_token"` filter. See
/// [`text_input_htmx`](text_input_htmx#custom-field_name-limitation) for the
/// custom `[security.submit_token].field_name` caveat. When you customize the
/// field name, use [`required_text_input_htmx_with_token_field`] (the proper
/// resolution) or add the validation route(s) to
/// `[security.submit_token].exempt_paths` (the alternative) for hand-written
/// live-validation forms.
#[cfg(feature = "maud")]
#[must_use]
pub fn required_text_input_htmx<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
    validate_url: &str,
) -> maud::Markup {
    required_text_input_htmx_with_token_field(
        changeset,
        field,
        label,
        validate_url,
        DEFAULT_SUBMIT_TOKEN_FIELD,
    )
}

/// Like [`required_text_input_htmx`] but excludes the caller-supplied
/// submit-token field name (`token_field`) from the inline-validation POST
/// instead of the hardcoded default `_submit_token`.
///
/// This is the required-field counterpart of
/// [`text_input_htmx_with_token_field`]; see that function for the full
/// rationale (issue #1843) and how to source the configured field name from the
/// [`SubmitFormField`](crate::security::SubmitFormField) extractor. Passing
/// `"_submit_token"` here is equivalent to calling [`required_text_input_htmx`].
#[cfg(feature = "maud")]
#[must_use]
pub fn required_text_input_htmx_with_token_field<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
    validate_url: &str,
    token_field: &str,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let value = changeset.field_value(field).unwrap_or_default();
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");
    let target = "closest [data-autumn-field-wrapper]";
    let hx_params = format!("not {token_field}");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" data-autumn-field-wrapper=(field) {
            label for=(field) class="autumn-field__label" { (label) }
            input
                type="text"
                id=(field)
                name=(field)
                value=(value)
                required
                aria-required="true"
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" })
                hx-post=(validate_url)
                hx-trigger="change"
                hx-target=(target)
                hx-swap="outerHTML"
                hx-include="closest form"
                hx-params=(hx_params);
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Render a `<button type="submit">` with `label`.
#[cfg(feature = "maud")]
#[must_use]
pub fn submit_button(label: &str) -> maud::Markup {
    maud::html! {
        button type="submit" class="autumn-submit" { (label) }
    }
}

/// Render a labeled `<input type="password">` tied to a changeset field.
///
/// Like [`text_input`] but uses `type="password"` and never populates the
/// `value` attribute — browsers must not auto-fill passwords into the markup
/// and screen readers must not announce the value.
///
/// Wraps in `<div id="{field}-field">` for stable htmx targeting.
/// ARIA annotations (`aria-invalid`, `aria-describedby`, error block) behave
/// identically to [`text_input`].
#[cfg(feature = "maud")]
#[must_use]
pub fn password_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            label for=(field) class="autumn-field__label" { (label) }
            input
                type="password"
                id=(field)
                name=(field)
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" });
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Render a labeled `<textarea>` tied to a changeset field.
///
/// The current field value is emitted as the textarea body (not a `value`
/// attribute). Wraps in `<div id="{field}-field">` for stable htmx targeting.
/// ARIA annotations behave identically to [`text_input`].
#[cfg(feature = "maud")]
#[must_use]
pub fn textarea_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let value = changeset.field_value(field).unwrap_or_default();
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            label for=(field) class="autumn-field__label" { (label) }
            textarea
                id=(field)
                name=(field)
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" })
                { (value) }
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Render a labeled `<input type="text">` for a required field.
///
/// Identical to [`text_input`] but adds `aria-required="true"` and the HTML
/// `required` attribute, giving both AT users and browser-native validation
/// the required-field signal without relying solely on color.
/// Wraps in `<div id="{field}-field">` for stable htmx targeting.
#[cfg(feature = "maud")]
#[must_use]
pub fn required_text_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let value = changeset.field_value(field).unwrap_or_default();
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) {
            label for=(field) { (label) }
            input
                type="text"
                id=(field)
                name=(field)
                value=(value)
                required
                aria-required="true"
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" });
            @if has_errors {
                div id=(error_id) role="alert" {
                    @for error in errors {
                        p { (error) }
                    }
                }
            }
        }
    }
}

/// Render a labeled `<input type="checkbox">` tied to a `bool` changeset field.
///
/// # Required: `#[serde(default)]` on the target field
///
/// HTML checkboxes are omitted from submitted form data entirely when
/// unchecked — there is no way to distinguish "unchecked" from "field not
/// present" on the wire. **Do not** pair this with a hidden `<input
/// type="hidden" value="false">` sibling sharing the same `name`: a checked
/// box then submits the key *twice* (`field=false` from the hidden input,
/// `field=true` from the checkbox), and `serde_urlencoded` (used by both
/// axum's `Form` extractor and [`ChangesetForm`]) rejects duplicate keys
/// with a "duplicate field" deserialize error instead of taking the last
/// value — every checked submission would 400.
///
/// Instead, mark the target `bool` field `#[serde(default)]` so a missing
/// key decodes as `false`:
///
/// ```rust,ignore
/// #[derive(serde::Deserialize)]
/// struct PostForm {
///     #[serde(default)]
///     published: bool,
/// }
/// ```
///
/// For a nullable `Option<bool>` field where `None` is a meaningful third
/// state (distinct from `Some(false)`), a checkbox cannot represent it
/// losslessly — use [`select_input`] with three options instead.
///
/// The `checked` attribute reflects the changeset's current value via
/// [`Changeset::field_value`], which serializes `bool` as `"true"`/`"false"`.
/// Wraps in `<div id="{field}-field">` for stable htmx targeting. ARIA
/// annotations behave identically to [`text_input`].
#[cfg(feature = "maud")]
#[must_use]
pub fn checkbox_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let checked = changeset.field_value(field).as_deref() == Some("true");
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            label for=(field) class="autumn-field__label" { (label) }
            input
                type="checkbox"
                id=(field)
                name=(field)
                value="true"
                checked[checked]
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" });
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Render a labeled `<input type="number">` tied to a numeric changeset field
/// (`i32`, `i64`, `f32`, `f64`).
///
/// `step` sets the HTML `step` attribute — pass `Some("1")` for integer
/// fields, `Some("0.01")` or `Some("any")` for floating-point fields, or
/// `None` to leave the browser default (`step="1"`, whole numbers only).
/// Wraps in `<div id="{field}-field">` for stable htmx targeting. ARIA
/// annotations behave identically to [`text_input`].
#[cfg(feature = "maud")]
#[must_use]
pub fn number_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
    step: Option<&str>,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let value = changeset.field_value(field).unwrap_or_default();
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            label for=(field) class="autumn-field__label" { (label) }
            input
                type="number"
                id=(field)
                name=(field)
                value=(value)
                step=[step]
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" });
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Render a labeled `<input type="number">` for a required numeric field.
///
/// Identical to [`number_input`] but adds `aria-required="true"` and the HTML
/// `required` attribute, giving both AT users and browser-native validation
/// the required-field signal without relying solely on color.
#[cfg(feature = "maud")]
#[must_use]
pub fn required_number_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
    step: Option<&str>,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let value = changeset.field_value(field).unwrap_or_default();
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            label for=(field) class="autumn-field__label" { (label) }
            input
                type="number"
                id=(field)
                name=(field)
                value=(value)
                step=[step]
                required
                aria-required="true"
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" });
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Normalize a stored date/datetime string into `YYYY-MM-DD`, the shape the
/// HTML `<input type="date">` control requires.
///
/// Accepts a bare date, a full RFC 3339 timestamp (with offset/`Z`), or a
/// naive datetime, and keeps just the date component. Falls back to the
/// input unchanged when none of those shapes match (e.g. an empty string).
#[cfg(feature = "maud")]
fn normalize_date_value(raw: &str) -> String {
    if raw.is_empty() {
        return String::new();
    }
    // `NaiveDateTime`'s `Display` (as opposed to its serde serialization,
    // which uses `T`) separates date and time with a space, e.g. from a raw
    // `.to_string()` or some database drivers. Normalize defensively so
    // those still parse instead of falling through to the raw string.
    let normalized = raw.replace(' ', "T");
    if let Ok(date) = chrono::NaiveDate::parse_from_str(&normalized, "%Y-%m-%d") {
        return date.to_string();
    }
    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&normalized) {
        return dt.format("%Y-%m-%d").to_string();
    }
    if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(&normalized, "%Y-%m-%dT%H:%M:%S%.f") {
        return ndt.format("%Y-%m-%d").to_string();
    }
    raw.to_owned()
}

/// Normalize a stored datetime string into a shape the HTML `<input
/// type="datetime-local">` control accepts (`YYYY-MM-DDTHH:MM[:SS[.fff]]`).
/// Browsers silently reject RFC 3339 timestamps carrying a `Z`/offset
/// suffix.
///
/// **Seconds/fractional-seconds preserved when present.** `chrono`'s default
/// `serde::Deserialize` for `NaiveDateTime`/`DateTime<Utc>` requires the
/// seconds component — truncating to `YYYY-MM-DDTHH:MM` here would make
/// [`ChangesetForm`] fail to decode the *pre-filled* value on any
/// submission where the user doesn't manually retype it (chrono's parser
/// returns "premature end of input"). `%.f` omits the fractional part
/// cleanly when it's zero, so whole-second values still render without a
/// trailing dot.
///
/// **Wall-clock preserved.** For RFC 3339 input with an explicit offset, the
/// offset is dropped but the local clock components are kept as-is (no
/// conversion to UTC) — the datetime-local input has no timezone concept, so
/// shifting the clock would mutate the value on a no-op save.
#[cfg(feature = "maud")]
fn normalize_datetime_local_value(raw: &str) -> String {
    if raw.is_empty() {
        return String::new();
    }
    // See `normalize_date_value`'s comment on space-separated input.
    let normalized = raw.replace(' ', "T");
    if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(&normalized, "%Y-%m-%dT%H:%M:%S%.f") {
        return ndt.format("%Y-%m-%dT%H:%M:%S%.f").to_string();
    }
    if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(&normalized, "%Y-%m-%dT%H:%M") {
        return ndt.format("%Y-%m-%dT%H:%M:%S%.f").to_string();
    }
    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&normalized) {
        return dt.naive_local().format("%Y-%m-%dT%H:%M:%S%.f").to_string();
    }
    raw.to_owned()
}

/// Pad an HTML `datetime-local` submission (`YYYY-MM-DDTHH:MM`, seconds
/// omitted by the browser at minute granularity) to `YYYY-MM-DDTHH:MM:00` so
/// chrono's parser — which requires the seconds component — accepts it.
fn pad_datetime_local_seconds(raw: &str) -> String {
    if raw.chars().count() == 16 {
        format!("{raw}:00")
    } else {
        raw.to_owned()
    }
}

/// Parse a submitted datetime string into `chrono::DateTime<Utc>`, accepting
/// both wire shapes the same struct has to serve:
///
/// - RFC 3339 with an explicit offset (JSON API bodies) — the offset is
///   honored and the instant converted to UTC;
/// - the offsetless HTML `datetime-local` shape `YYYY-MM-DDTHH:MM[:SS[.f]]`
///   (browser form posts) — interpreted as UTC wall-clock time.
fn parse_datetime_local_or_rfc3339_utc(
    raw: &str,
) -> Result<chrono::DateTime<chrono::Utc>, chrono::ParseError> {
    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(raw) {
        return Ok(dt.with_timezone(&chrono::Utc));
    }
    chrono::NaiveDateTime::parse_from_str(&pad_datetime_local_seconds(raw), "%Y-%m-%dT%H:%M:%S%.f")
        .map(|ndt| ndt.and_utc())
}

/// Parse a submitted datetime string into `chrono::DateTime<Local>`,
/// accepting both wire shapes the same struct has to serve:
///
/// - RFC 3339 with an explicit offset (JSON API bodies) — the offset is
///   honored and the instant converted to the server's local zone;
/// - the offsetless HTML `datetime-local` shape `YYYY-MM-DDTHH:MM[:SS[.f]]`
///   (browser form posts) — interpreted as wall-clock time in the server's
///   local zone. A wall clock repeated by a DST fall-back transition maps to
///   the **earlier** of the two instants (deterministic rather than
///   rejected); a wall clock skipped by a spring-forward transition has no
///   corresponding instant and errors.
fn parse_datetime_local_or_rfc3339_local(
    raw: &str,
) -> Result<chrono::DateTime<chrono::Local>, String> {
    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(raw) {
        return Ok(dt.with_timezone(&chrono::Local));
    }
    let ndt = chrono::NaiveDateTime::parse_from_str(
        &pad_datetime_local_seconds(raw),
        "%Y-%m-%dT%H:%M:%S%.f",
    )
    .map_err(|e| e.to_string())?;
    match ndt.and_local_timezone(chrono::Local) {
        chrono::LocalResult::Single(dt) => Ok(dt),
        chrono::LocalResult::Ambiguous(earliest, _) => Ok(earliest),
        chrono::LocalResult::None => Err(format!(
            "local time {ndt} does not exist in the server's timezone (skipped by a DST transition)"
        )),
    }
}

/// Deserialize an HTML `datetime-local` submission into `chrono::DateTime<Utc>`,
/// treating an offsetless submitted wall-clock value as UTC.
///
/// RFC 3339 input with an explicit offset is also accepted (converted to
/// UTC), so a struct that doubles as a JSON API body keeps decoding.
///
/// `<input type="datetime-local">` has no timezone concept, so [`datetime_input`]
/// necessarily strips any offset when rendering a `DateTime<Utc>` field's
/// current value — the browser then posts back an offsetless string (e.g.
/// `2024-03-15T10:30:56`). Chrono's *default* `Deserialize` for
/// `DateTime<Utc>` requires an RFC 3339 offset and rejects that string with
/// "premature end of input" on every submission. The `#[model]`-generated
/// `NewX` insert struct attaches this deserializer to non-nullable
/// `DateTime<Utc>` columns automatically (and
/// [`deserialize_datetime_local_utc_option`] to nullable ones); attach it
/// yourself on any hand-written form struct with a `DateTime<Utc>` field
/// rendered via `datetime_input`:
///
/// ```rust,ignore
/// #[derive(serde::Deserialize)]
/// struct EventForm {
///     #[serde(deserialize_with = "autumn_web::form::deserialize_datetime_local_utc")]
///     starts_at: chrono::DateTime<chrono::Utc>,
/// }
/// ```
///
/// `chrono::NaiveDateTime` fields don't need an offset, but still benefit
/// from [`deserialize_naive_datetime_local`] as a defensive measure — see
/// its doc comment.
///
/// # Errors
///
/// Returns a deserializer error when the submitted value is neither a valid
/// `YYYY-MM-DDTHH:MM[:SS[.f]]` local datetime string nor a valid RFC 3339
/// timestamp.
pub fn deserialize_datetime_local_utc<'de, D>(
    deserializer: D,
) -> Result<chrono::DateTime<chrono::Utc>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = <String as serde::Deserialize>::deserialize(deserializer)?;
    parse_datetime_local_or_rfc3339_utc(&raw).map_err(serde::de::Error::custom)
}

/// `Option<chrono::DateTime<Utc>>` counterpart to
/// [`deserialize_datetime_local_utc`], for a nullable field — an absent,
/// `null`, or empty submitted value decodes as `None`.
///
/// Like the required variant, both the offsetless `datetime-local` shape
/// (interpreted as UTC) and RFC 3339 (offset converted to UTC) are accepted.
///
/// Pair it with `#[serde(default)]`: `deserialize_with` disables serde's
/// implicit missing-`Option`-field-is-`None` handling, and `default` restores
/// it (the `#[model]`-generated `NewX` struct emits both).
///
/// # Errors
///
/// Returns a deserializer error when a non-empty submitted value is neither
/// a valid `YYYY-MM-DDTHH:MM[:SS[.f]]` local datetime string nor a valid
/// RFC 3339 timestamp.
pub fn deserialize_datetime_local_utc_option<'de, D>(
    deserializer: D,
) -> Result<Option<chrono::DateTime<chrono::Utc>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = <Option<String> as serde::Deserialize>::deserialize(deserializer)?;
    match raw {
        Some(s) if !s.is_empty() => parse_datetime_local_or_rfc3339_utc(&s)
            .map(Some)
            .map_err(serde::de::Error::custom),
        _ => Ok(None),
    }
}

/// Deserialize an HTML `datetime-local` submission into
/// `chrono::DateTime<Local>`, treating an offsetless submitted wall-clock
/// value as the server's local time.
///
/// RFC 3339 input with an explicit offset is also accepted (the instant is
/// converted to the local zone), so a struct that doubles as a JSON API body
/// keeps decoding.
///
/// This is the `DateTime<chrono::Local>` counterpart to
/// [`deserialize_datetime_local_utc`] — see its doc comment for why derived
/// forms need a datetime-local-tolerant deserializer at all. The
/// `#[model]`-generated `NewX` insert struct attaches this deserializer to
/// non-nullable `DateTime<Local>` columns automatically (and
/// [`deserialize_datetime_local_local_option`] to nullable ones); attach it
/// yourself on any hand-written form struct with a `DateTime<Local>` field
/// rendered via [`datetime_input`].
///
/// **DST edge cases** (the submitted wall clock has no offset, so the local
/// zone decides which instant it names): a wall clock that occurs twice
/// because of a fall-back transition maps to the **earlier** of the two
/// instants — deterministic, rather than rejecting the submission; a wall
/// clock skipped by a spring-forward transition names no instant at all and
/// is rejected as a decode error.
///
/// # Errors
///
/// Returns a deserializer error when the submitted value is neither a valid
/// `YYYY-MM-DDTHH:MM[:SS[.f]]` local datetime string nor a valid RFC 3339
/// timestamp, or when the offsetless wall clock falls in a DST gap of the
/// server's local zone.
pub fn deserialize_datetime_local_local<'de, D>(
    deserializer: D,
) -> Result<chrono::DateTime<chrono::Local>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = <String as serde::Deserialize>::deserialize(deserializer)?;
    parse_datetime_local_or_rfc3339_local(&raw).map_err(serde::de::Error::custom)
}

/// `Option<chrono::DateTime<Local>>` counterpart to
/// [`deserialize_datetime_local_local`], for a nullable field — an absent,
/// `null`, or empty submitted value decodes as `None`.
///
/// Like the required variant, both the offsetless `datetime-local` shape
/// (interpreted as the server's local wall clock; DST-ambiguous values map
/// to the earlier instant, DST-skipped values error) and RFC 3339 (offset
/// converted to the local zone) are accepted.
///
/// Pair it with `#[serde(default)]`: `deserialize_with` disables serde's
/// implicit missing-`Option`-field-is-`None` handling, and `default` restores
/// it (the `#[model]`-generated `NewX` struct emits both).
///
/// # Errors
///
/// Returns a deserializer error when a non-empty submitted value is neither
/// a valid `YYYY-MM-DDTHH:MM[:SS[.f]]` local datetime string nor a valid
/// RFC 3339 timestamp, or when the offsetless wall clock falls in a DST gap
/// of the server's local zone.
pub fn deserialize_datetime_local_local_option<'de, D>(
    deserializer: D,
) -> Result<Option<chrono::DateTime<chrono::Local>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = <Option<String> as serde::Deserialize>::deserialize(deserializer)?;
    match raw {
        Some(s) if !s.is_empty() => parse_datetime_local_or_rfc3339_local(&s)
            .map(Some)
            .map_err(serde::de::Error::custom),
        _ => Ok(None),
    }
}

/// Deserialize an HTML `datetime-local` submission into `chrono::NaiveDateTime`.
///
/// The *pre-filled* value [`datetime_input`] renders always includes seconds
/// (see `normalize_datetime_local_value`), so chrono's default `Deserialize`
/// — which requires the seconds component — decodes an untouched submission
/// fine on its own. But a value the user actively edits through the
/// browser's native picker isn't guaranteed to include seconds (`step="any"`
/// only requests that the control *allow* seconds; it doesn't guarantee
/// every browser's UI captures them), which would otherwise 400 with
/// "premature end of input". The `#[model]`-generated `NewX` insert struct
/// attaches this deserializer to non-nullable `NaiveDateTime` columns
/// automatically (and [`deserialize_naive_datetime_local_option`] to nullable
/// ones); attach it yourself on hand-written form structs to defend against
/// that:
///
/// ```rust,ignore
/// #[derive(serde::Deserialize)]
/// struct EventForm {
///     #[serde(deserialize_with = "autumn_web::form::deserialize_naive_datetime_local")]
///     starts_at: chrono::NaiveDateTime,
/// }
/// ```
///
/// # Errors
///
/// Returns a deserializer error when the submitted value isn't a valid
/// `YYYY-MM-DDTHH:MM[:SS[.f]]` local datetime string.
pub fn deserialize_naive_datetime_local<'de, D>(
    deserializer: D,
) -> Result<chrono::NaiveDateTime, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = <String as serde::Deserialize>::deserialize(deserializer)?;
    chrono::NaiveDateTime::parse_from_str(&pad_datetime_local_seconds(&raw), "%Y-%m-%dT%H:%M:%S%.f")
        .map_err(serde::de::Error::custom)
}

/// `Option<chrono::NaiveDateTime>` counterpart to
/// [`deserialize_naive_datetime_local`], for a nullable field — an absent,
/// `null`, or empty submitted value decodes as `None`.
///
/// Pair it with `#[serde(default)]`: `deserialize_with` disables serde's
/// implicit missing-`Option`-field-is-`None` handling, and `default` restores
/// it (the `#[model]`-generated `NewX` struct emits both).
///
/// # Errors
///
/// Returns a deserializer error when a non-empty submitted value isn't a
/// valid `YYYY-MM-DDTHH:MM[:SS[.f]]` local datetime string.
pub fn deserialize_naive_datetime_local_option<'de, D>(
    deserializer: D,
) -> Result<Option<chrono::NaiveDateTime>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = <Option<String> as serde::Deserialize>::deserialize(deserializer)?;
    match raw {
        Some(s) if !s.is_empty() => chrono::NaiveDateTime::parse_from_str(
            &pad_datetime_local_seconds(&s),
            "%Y-%m-%dT%H:%M:%S%.f",
        )
        .map(Some)
        .map_err(serde::de::Error::custom),
        _ => Ok(None),
    }
}

/// Render a labeled `<input type="date">` tied to a changeset field.
///
/// The current value is normalized via `normalize_date_value` to the
/// `YYYY-MM-DD` shape HTML5 date pickers require, regardless of whether the
/// underlying field serializes as a bare date or a full timestamp. Wraps in
/// `<div id="{field}-field">` for stable htmx targeting. ARIA annotations
/// behave identically to [`text_input`].
#[cfg(feature = "maud")]
#[must_use]
pub fn date_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let value = normalize_date_value(&changeset.field_value(field).unwrap_or_default());
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            label for=(field) class="autumn-field__label" { (label) }
            input
                type="date"
                id=(field)
                name=(field)
                value=(value)
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" });
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Render a labeled `<input type="date">` for a required field.
///
/// Identical to [`date_input`] but adds `aria-required="true"` and the HTML
/// `required` attribute, giving both AT users and browser-native validation
/// the required-field signal without relying solely on color.
#[cfg(feature = "maud")]
#[must_use]
pub fn required_date_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let value = normalize_date_value(&changeset.field_value(field).unwrap_or_default());
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            label for=(field) class="autumn-field__label" { (label) }
            input
                type="date"
                id=(field)
                name=(field)
                value=(value)
                required
                aria-required="true"
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" });
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Render a labeled `<input type="datetime-local">` tied to a changeset
/// field (`NaiveDateTime` or `DateTime`).
///
/// The current value is normalized via `normalize_datetime_local_value` to
/// the shape HTML5 datetime pickers require, preserving seconds/fractional
/// seconds when present — `chrono`'s default `Deserialize` requires the
/// seconds component, so truncating to minutes would break decoding the
/// pre-filled value on any untouched submission. Renders `step="any"` so a
/// value carrying seconds doesn't fail the browser's step-mismatch
/// constraint validation (the default step is minute-granularity). Wraps in
/// `<div id="{field}-field">` for stable htmx targeting. ARIA annotations
/// behave identically to [`text_input`].
///
/// # Attach a `deserialize_with` matching the field's chrono type
///
/// `<input type="datetime-local">` has no timezone concept, so the value
/// this renders for a `DateTime<Utc>` field never carries an offset —
/// chrono's default `Deserialize` for `DateTime<Utc>` requires one and
/// rejects the submission. Attach [`deserialize_datetime_local_utc`] (or
/// [`deserialize_datetime_local_utc_option`] for `Option<DateTime<Utc>>`)
/// via `#[serde(deserialize_with = "...")]` on that field. `DateTime<Local>`
/// fields have the same problem and take
/// [`deserialize_datetime_local_local`] (or its `_option` variant), which
/// interprets the offsetless wall clock in the server's local zone. Other
/// zone parameters (e.g. `DateTime<FixedOffset>`) have **no** sound
/// interpretation of an offsetless value — don't render them through this
/// control; use a text input carrying the RFC 3339 string instead (which is
/// what a derived `form_for` does).
///
/// `NaiveDateTime` fields don't hit that offset problem, but a value the
/// user actively edits through the browser's native picker isn't guaranteed
/// to include seconds (unlike the always-seconds-inclusive pre-filled
/// value), which chrono's default `Deserialize` also rejects. Attach
/// [`deserialize_naive_datetime_local`] (or
/// [`deserialize_naive_datetime_local_option`] for `Option<NaiveDateTime>`)
/// as a defensive measure.
#[cfg(feature = "maud")]
#[must_use]
pub fn datetime_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let value = normalize_datetime_local_value(&changeset.field_value(field).unwrap_or_default());
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            label for=(field) class="autumn-field__label" { (label) }
            input
                type="datetime-local"
                id=(field)
                name=(field)
                value=(value)
                step="any"
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" });
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Render a labeled `<input type="datetime-local">` for a required field.
///
/// Identical to [`datetime_input`] but adds `aria-required="true"` and the
/// HTML `required` attribute, giving both AT users and browser-native
/// validation the required-field signal without relying solely on color.
#[cfg(feature = "maud")]
#[must_use]
pub fn required_datetime_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let value = normalize_datetime_local_value(&changeset.field_value(field).unwrap_or_default());
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            label for=(field) class="autumn-field__label" { (label) }
            input
                type="datetime-local"
                id=(field)
                name=(field)
                value=(value)
                step="any"
                required
                aria-required="true"
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" });
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Render a labeled `<select>` tied to a closed-set changeset field, with
/// `options` given as `(value, label)` pairs.
///
/// The option whose `value` matches the changeset's current field value
/// (via [`Changeset::field_value`]) is marked `selected`. This is the
/// control the enum ([#1030]) and references ([#1026]) field types render
/// once those field kinds ship — this slice ships the widget, not the DSL
/// tokens that will target it.
/// Wraps in `<div id="{field}-field">` for stable htmx targeting. ARIA
/// annotations behave identically to [`text_input`].
///
/// [#1030]: https://github.com/madmax983/autumn/issues/1030
/// [#1026]: https://github.com/madmax983/autumn/issues/1026
#[cfg(feature = "maud")]
#[must_use]
pub fn select_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
    options: &[(&str, &str)],
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let current = changeset.field_value(field).unwrap_or_default();
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            label for=(field) class="autumn-field__label" { (label) }
            select
                id=(field)
                name=(field)
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" }) {
                @for (option_value, option_label) in options {
                    option value=(option_value) selected[*option_value == current] { (option_label) }
                }
            }
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Render a labeled `<select>` for a required closed-set field.
///
/// Identical to [`select_input`] but adds `aria-required="true"` and the HTML
/// `required` attribute — combined with a blank placeholder option (an empty
/// `value=""`), this blocks submission until the user picks a real option,
/// giving both AT users and browser-native validation the required-field
/// signal without relying solely on color.
#[cfg(feature = "maud")]
#[must_use]
pub fn required_select_input<T: Serialize>(
    changeset: &Changeset<T>,
    field: &str,
    label: &str,
    options: &[(&str, &str)],
) -> maud::Markup {
    let errors = changeset.errors_for(field);
    let has_errors = !errors.is_empty();
    let current = changeset.field_value(field).unwrap_or_default();
    let error_id = format!("{field}-error");
    let wrapper_id = format!("{field}-field");

    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            label for=(field) class="autumn-field__label" { (label) }
            select
                id=(field)
                name=(field)
                required
                aria-required="true"
                class=(if has_errors { "autumn-field__input autumn-field__input--invalid" } else { "autumn-field__input" })
                aria-invalid=(if has_errors { "true" } else { "false" })
                aria-describedby=(if has_errors { error_id.as_str() } else { "" }) {
                @for (option_value, option_label) in options {
                    option value=(option_value) selected[*option_value == current] { (option_label) }
                }
            }
            @if has_errors {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// Render an ARIA live region for htmx swap announcements.
///
/// Emits `<div id="…" role="status" aria-live="polite" aria-atomic="true">`.
/// Place this element in your page layout and update its content via
/// `hx-swap-oob` to announce htmx-driven changes to screen readers without
/// moving keyboard focus.
///
/// # Example
///
/// ```rust,ignore
/// // In your page layout:
/// (aria_live_region("htmx-status", ""))
///
/// // In an htmx response fragment (announces to screen readers):
/// div id="htmx-status" role="status" aria-live="polite" aria-atomic="true"
///     hx-swap-oob="true" {
///     "Post submitted successfully"
/// }
/// ```
#[cfg(feature = "maud")]
#[must_use]
pub fn aria_live_region(id: &str, message: &str) -> maud::Markup {
    maud::html! {
        div id=(id) role="status" aria-live="polite" aria-atomic="true" {
            (message)
        }
    }
}

/// Render a visually-hidden skip-to-content link that becomes visible on focus.
///
/// Place this as the **first element inside `<body>`** so keyboard users can
/// bypass repeated navigation and jump directly to main content.
///
/// The link carries the `skip-link` CSS class; pair it with the bundled
/// Tailwind config's `skip-link` utility or add your own:
///
/// ```css
/// .skip-link { position: absolute; top: -9999px; }
/// .skip-link:focus { position: static; }
/// ```
#[cfg(feature = "maud")]
#[must_use]
pub fn skip_link(target: &str, label: &str) -> maud::Markup {
    maud::html! {
        a href=(target) class="skip-link" { (label) }
    }
}

// ── form_for (issue #1135 phase 2) ──────────────────────────────────

/// The HTML control a model field renders as inside [`form_for`].
///
/// This is plain data (no `maud` dependency) so the `#[model]`-derived
/// [`FormModel`] implementation is always available; only the rendering side
/// ([`form_for`]) is gated behind the `maud` feature.
/// The enum is `#[non_exhaustive]`: new control kinds will be added without
/// a semver-major bump, so external `match`es need a wildcard arm. All
/// existing variants remain freely constructible.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FieldControl {
    /// `<input type="text">`.
    Text,
    /// `<textarea>`.
    Textarea,
    /// `<input type="password">`.
    Password,
    /// `<input type="number">`, with an optional HTML `step` attribute.
    Number {
        /// The HTML `step` attribute, e.g. `Some("0.01")`, or `None` to use
        /// the browser default.
        step: Option<String>,
    },
    /// `<input type="checkbox">`.
    Checkbox,
    /// `<input type="date">`.
    Date,
    /// `<input type="datetime-local">`.
    DateTime,
    /// `<select>` with `(value, label)` option pairs, e.g. enum variants or
    /// a nullable-bool tri-state.
    Select {
        /// The `(value, label)` option pairs rendered as `<option>` elements.
        options: Vec<(String, String)>,
    },
    /// `<input type="file">`. The presence of any `File` field makes
    /// [`FormFor::render`] emit `enctype="multipart/form-data"`.
    File,
}

/// One field descriptor consumed by [`form_for`].
///
/// Typically produced by a `#[model]`-derived [`FormModel::form_fields`]
/// implementation, one entry per persisted column that should render as a
/// form control.
#[derive(Debug, Clone)]
pub struct FormField {
    /// The field's `name`/`id` attribute — i.e. the key the browser POSTs
    /// this control under, which must match what the form's decode target
    /// (e.g. the `#[model]`-generated `NewX` insert struct) expects. Also
    /// the key [`Changeset::errors_for`] messages are looked up by, and the
    /// key [`FormFor::exclude`]/[`FormFor::override_field`]/
    /// [`FormFor::override_label`] match on.
    ///
    /// When the changeset's data type serializes this field under a
    /// *different* key (a serde rename), set [`FormField::value_name`] so the
    /// pre-filled value is still found — `name` itself deliberately stays the
    /// POST key, not the serialized key.
    pub name: String,
    /// The human-readable `<label>` text.
    pub label: String,
    /// Which HTML control renders this field.
    pub control: FieldControl,
    /// Whether the rendered control should be marked required (`required`
    /// attribute + `aria-required="true"`), where a required variant of the
    /// control exists.
    pub required: bool,
    /// The serde-effective *serialized* key of this field on the changeset's
    /// data type, when it differs from [`FormField::name`] (e.g.
    /// `#[serde(rename = "headline")]` or a struct-level
    /// `#[serde(rename_all = "camelCase")]`). Used **only** to look up the
    /// pre-filled value via [`Changeset::field_value`]; the rendered
    /// `name`/`id` attributes, error lookup, and builder matching all keep
    /// using [`FormField::name`]. `None` means the serialized key equals
    /// `name` (the common case).
    ///
    /// The `#[model]`-derived [`FormModel`] sets this automatically for
    /// serde-renamed columns; hand-written descriptors use
    /// [`FormField::with_value_name`].
    pub value_name: Option<String>,
}

impl FormField {
    /// Construct a new field descriptor.
    ///
    /// The pre-fill lookup key ([`FormField::value_name`]) defaults to
    /// `name`; use [`FormField::with_value_name`] when the changeset's data
    /// type serializes the field under a different (serde-renamed) key.
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        label: impl Into<String>,
        control: FieldControl,
        required: bool,
    ) -> Self {
        Self {
            name: name.into(),
            label: label.into(),
            control,
            required,
            value_name: None,
        }
    }

    /// Set the serialized key used to pre-fill this field's value from the
    /// changeset (see [`FormField::value_name`]), returning `self` for
    /// chaining after [`FormField::new`].
    #[must_use]
    pub fn with_value_name(mut self, value_name: impl Into<String>) -> Self {
        self.value_name = Some(value_name.into());
        self
    }
}

/// Implemented by model types (typically via `#[model]`) to drive
/// [`form_for`].
///
/// Returns the ordered list of fields to render — one [`FormField`] per
/// column that should appear as a control in the generated form.
pub trait FormModel {
    /// The ordered list of fields [`form_for`] should render.
    fn form_fields() -> Vec<FormField>;
}

/// Render a full `<form>` for `T` from `changeset`, deriving one control per
/// [`FormModel::form_fields`] entry.
///
/// This is the "one call renders the whole form" counterpart to composing
/// the individual typed-input helpers (e.g. [`text_input`], [`select_input`])
/// by hand: `form_for` walks `T::form_fields()`, dispatches each field to the
/// matching helper based on its [`FieldControl`], and wraps the result in a
/// `<form>` via the same audited CSRF/method-override path as [`form_tag`].
///
/// Use the [`FormFor`] builder methods to exclude fields, override a field's
/// control or label, inject a CSRF token, append extra markup before the
/// submit button, or force a `multipart/form-data` encoding.
///
/// # Checkboxes and `bool` fields
///
/// A [`FieldControl::Checkbox`] field renders via [`checkbox_input`], which
/// deliberately emits **no** hidden `false` fallback (`serde_urlencoded` — used
/// by axum's `Form` and [`ChangesetForm`] — rejects duplicate keys, so a
/// hidden sibling would 400 every *checked* submission). An unchecked box
/// therefore submits no key at all, and the struct the form posts into must
/// decode a missing key as `false` via `#[serde(default)]` on the `bool`
/// field. The `#[model]`-generated `NewX` insert struct already does this for
/// non-nullable `bool` columns (matching the scaffold's `{Model}Form`
/// convention); hand-written form targets must add the attribute themselves —
/// see [`checkbox_input`]'s documentation.
///
/// # Datetime fields and `datetime-local` values
///
/// A [`FieldControl::DateTime`] field renders via [`datetime_input`], whose
/// `<input type="datetime-local">` has no timezone concept: the pre-filled
/// value is offsetless (`YYYY-MM-DDTHH:MM:SS`) and the browser posts back an
/// offsetless string — not always with seconds. Chrono's default
/// `Deserialize` for `DateTime<Utc>` demands an RFC 3339 offset, so a plain
/// field would reject even an *untouched* submission as a 400 before
/// validation. The `#[model]`-generated `NewX` insert struct therefore
/// attaches [`deserialize_datetime_local_utc`] (or the `_option` variant) to
/// `DateTime<Utc>` columns, [`deserialize_datetime_local_local`] (or its
/// `_option` variant) to `DateTime<Local>` columns, and
/// [`deserialize_naive_datetime_local`] (or its `_option` variant) to
/// `NaiveDateTime` columns: the offsetless value is interpreted as UTC or
/// the server's local zone respectively (see
/// [`deserialize_datetime_local_local`] for the DST edge cases), and
/// RFC 3339 JSON API bodies posted to the same struct keep decoding (an
/// explicit offset is converted to the field's zone).
///
/// A `DateTime` column with any **other** zone parameter (e.g.
/// `DateTime<FixedOffset>`, or a bare `DateTime` alias whose zone the derive
/// can't see) does *not* get the `datetime-local` picker: an offsetless
/// wall clock is genuinely ambiguous for such a zone, so inventing an
/// interpretation would silently shift instants. The derived [`FormModel`]
/// falls back to [`FieldControl::Text`] for those columns — the pre-filled
/// value is the field's serialized RFC 3339 string, which chrono's default
/// `Deserialize` round-trips as-is.
///
/// A required [`FieldControl::Date`] needs no such treatment — the browser's
/// `YYYY-MM-DD` wire shape is exactly what chrono's `NaiveDate`
/// `Deserialize` accepts. Hand-written form targets must attach the
/// deserializers themselves — see each helper's documentation.
///
/// # Serde-renamed fields
///
/// A model column carrying `#[serde(rename = "...")]` (or covered by a
/// struct-level `#[serde(rename_all = "...")]`) serializes under a key that
/// differs from its Rust identifier, and [`Changeset::field_value`] — which
/// pre-fills every control by serializing the changeset's data — indexes by
/// that *serialized* key. The rendered input `name`, however, must stay the
/// Rust identifier: the `#[model]`-generated `NewX`/`UpdateX` structs the
/// form posts into do **not** propagate serde renames, so they decode by
/// identifier. [`FormField`] therefore carries the two keys separately:
/// [`FormField::name`] is the input `name`/`id`/error-lookup key, and
/// [`FormField::value_name`] is the serde-effective serialized key used only
/// for the pre-fill lookup. The `#[model]`-derived [`FormModel`] resolves
/// field-level `rename`/`rename(serialize = ...)` and struct-level
/// `rename_all` automatically; hand-written [`FormModel`] impls whose data
/// type renames fields must call [`FormField::with_value_name`] themselves.
/// Validation errors stay keyed by the Rust identifier (the `validator`
/// crate reports the field ident, and the generated `NewX` has no renames).
///
/// # Example
///
/// ```rust
/// use autumn_web::form::{Changeset, FieldControl, FormField, FormModel, form_for};
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Post {
///     title: String,
///     views: i32,
///     published: bool,
/// }
///
/// impl FormModel for Post {
///     fn form_fields() -> Vec<FormField> {
///         vec![
///             FormField::new("title", "Title", FieldControl::Text, true),
///             FormField::new("views", "Views", FieldControl::Number { step: None }, false),
///             FormField::new("published", "Published", FieldControl::Checkbox, false),
///         ]
///     }
/// }
///
/// let changeset = Changeset::new(Post { title: "Hello".into(), views: 0, published: false });
/// let html = form_for(&changeset, "/posts", "post")
///     .csrf("tok")
///     .render()
///     .into_string();
///
/// assert!(html.contains("<form"));
/// assert!(html.contains(r#"name="_csrf""#));
/// assert!(html.contains(r#"name="title""#));
/// assert!(html.contains(r#"name="views""#));
/// assert!(html.contains(r#"name="published""#));
/// assert!(html.contains(r#"type="submit""#));
/// ```
#[cfg(feature = "maud")]
#[must_use]
pub fn form_for<T>(
    changeset: &Changeset<T>,
    action: impl Into<String>,
    method: impl Into<String>,
) -> FormFor<'_, T>
where
    T: Serialize + FormModel,
{
    FormFor {
        changeset,
        action: action.into(),
        method: method.into(),
        csrf_token: None,
        csrf_field_name: "_csrf".to_string(),
        excluded: Vec::new(),
        field_overrides: Vec::new(),
        label_overrides: Vec::new(),
        prepended: Vec::new(),
        appended: Vec::new(),
        submit_label: "Save".to_string(),
        force_multipart: false,
    }
}

/// Builder returned by [`form_for`]; call [`FormFor::render`] to produce the
/// final `<form>` markup.
#[cfg(feature = "maud")]
pub struct FormFor<'a, T: Serialize + FormModel> {
    changeset: &'a Changeset<T>,
    action: String,
    method: String,
    csrf_token: Option<String>,
    csrf_field_name: String,
    excluded: Vec<String>,
    field_overrides: Vec<(String, FieldControl)>,
    label_overrides: Vec<(String, String)>,
    prepended: Vec<maud::Markup>,
    appended: Vec<maud::Markup>,
    submit_label: String,
    force_multipart: bool,
}

#[cfg(feature = "maud")]
impl<T: Serialize + FormModel> FormFor<'_, T> {
    /// Inject a hidden CSRF input carrying `token`.
    #[must_use]
    pub fn csrf(mut self, token: impl Into<String>) -> Self {
        self.csrf_token = Some(token.into());
        self
    }

    /// Override the hidden CSRF field name (default `"_csrf"`).
    #[must_use]
    pub fn csrf_field_name(mut self, name: impl Into<String>) -> Self {
        self.csrf_field_name = name.into();
        self
    }

    /// Drop `field` from the rendered form.
    #[must_use]
    pub fn exclude(mut self, field: impl Into<String>) -> Self {
        self.excluded.push(field.into());
        self
    }

    /// Replace the derived control for `field`. Calling this again for the
    /// same field replaces the earlier override (last call wins).
    #[must_use]
    pub fn override_field(mut self, field: impl Into<String>, control: FieldControl) -> Self {
        self.field_overrides.push((field.into(), control));
        self
    }

    /// Replace the label for `field`. Calling this again for the same field
    /// replaces the earlier override (last call wins).
    #[must_use]
    pub fn override_label(mut self, field: impl Into<String>, label: impl Into<String>) -> Self {
        self.label_overrides.push((field.into(), label.into()));
        self
    }

    /// Insert extra markup before the submit button.
    #[must_use]
    pub fn append(mut self, markup: maud::Markup) -> Self {
        self.appended.push(markup);
        self
    }

    /// Insert extra markup at the front of the form, immediately after the
    /// hidden CSRF/method-override inputs and before every derived field.
    ///
    /// Use this for hidden control fields — such as a one-time
    /// `_submit_token` — that a body-scanning middleware must find near the
    /// start of the URL-encoded body. A large earlier field (e.g. a long
    /// `<textarea>`) would otherwise push an appended token past the scan cap,
    /// leaving the request effectively token-less.
    #[must_use]
    pub fn prepend(mut self, markup: maud::Markup) -> Self {
        self.prepended.push(markup);
        self
    }

    /// Override the submit button label (default `"Save"`).
    #[must_use]
    pub fn submit_label(mut self, label: impl Into<String>) -> Self {
        self.submit_label = label.into();
        self
    }

    /// Force `enctype="multipart/form-data"` even when no field is a
    /// [`FieldControl::File`].
    #[must_use]
    pub const fn multipart(mut self) -> Self {
        self.force_multipart = true;
        self
    }

    /// Render the full `<form>` markup.
    #[must_use]
    pub fn render(self) -> maud::Markup {
        let Self {
            changeset,
            action,
            method,
            csrf_token,
            csrf_field_name,
            excluded,
            field_overrides,
            label_overrides,
            prepended,
            appended,
            submit_label,
            force_multipart,
        } = self;

        let fields = effective_form_fields::<T>(&excluded, &field_overrides, &label_overrides);
        let is_multipart = force_multipart
            || fields
                .iter()
                .any(|f| matches!(f.control, FieldControl::File));

        let inner = maud::html! {
            @for markup in prepended {
                (markup)
            }
            @for field in &fields {
                (render_form_field(changeset, field))
            }
            @for markup in appended {
                (markup)
            }
            button type="submit" { (submit_label) }
        };

        form_tag_inner(
            &action,
            &method,
            &csrf_field_name,
            csrf_token.as_deref(),
            is_multipart.then_some("multipart/form-data"),
            inner,
        )
    }
}

/// Compute the effective field list for a [`FormFor::render`] call: start
/// from `T::form_fields()`, drop excluded fields, then apply control/label
/// overrides in place. Overrides apply in registration order, so when the
/// same field is overridden twice the **last** call wins — conventional
/// builder semantics.
#[cfg(feature = "maud")]
fn effective_form_fields<T: FormModel>(
    excluded: &[String],
    field_overrides: &[(String, FieldControl)],
    label_overrides: &[(String, String)],
) -> Vec<FormField> {
    T::form_fields()
        .into_iter()
        .filter(|field| !excluded.contains(&field.name))
        .map(|mut field| {
            if let Some((_, control)) = field_overrides
                .iter()
                .rev()
                .find(|(name, _)| *name == field.name)
            {
                field.control = control.clone();
            }
            if let Some((_, label)) = label_overrides
                .iter()
                .rev()
                .find(|(name, _)| *name == field.name)
            {
                field.label = label.clone();
            }
            field
        })
        .collect()
}

/// Serialize adapter that re-exposes one serde-renamed field of `data`
/// under the descriptor's [`FormField::name`], so the typed-input helpers'
/// [`Changeset::field_value`] lookup (keyed by the rendered input name)
/// finds the value that `data` actually serializes under
/// [`FormField::value_name`].
///
/// Serializes as a single-entry map `{ exposed_name: data.serialized_name }`
/// (`null` when the serialized key is absent, which [`Changeset::field_value`]
/// renders as an empty value — same as any missing field today).
#[cfg(feature = "maud")]
struct PrefillAlias<'a, T> {
    /// The changeset's inner data (serialized in full, then re-keyed).
    data: &'a T,
    /// The serde-effective key `data` serializes the field under.
    serialized_name: &'a str,
    /// The key the rendering helpers look the value up by (`FormField::name`).
    exposed_name: &'a str,
}

#[cfg(feature = "maud")]
impl<T: Serialize> Serialize for PrefillAlias<'_, T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::{Error as _, SerializeMap as _};
        let value = serde_json::to_value(self.data).map_err(S::Error::custom)?;
        let field_value = value
            .get(self.serialized_name)
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        let mut map = serializer.serialize_map(Some(1))?;
        map.serialize_entry(self.exposed_name, &field_value)?;
        map.end()
    }
}

/// Wrap a primitive-rendered control (its own `<label>` + input) in the
/// changeset field skeleton shared by every routed control: the stable
/// `<div id="{field}-field" class="autumn-field">` htmx target and, when the
/// field has errors, the `role="alert"` inline-error block keyed to
/// `{field}-error`. This is the same wrapper/error markup the hand-written
/// `*_input` helpers emit; only the inner control now comes from an
/// `a11y` primitive.
#[cfg(feature = "maud")]
fn wrap_field_control(
    field_name: &str,
    control: impl maud::Render,
    errors: &[String],
) -> maud::Markup {
    let error_id = format!("{field_name}-error");
    let wrapper_id = format!("{field_name}-field");
    maud::html! {
        div id=(wrapper_id) class="autumn-field" {
            (control)
            @if !errors.is_empty() {
                div id=(error_id) role="alert" class="autumn-field__errors" {
                    @for error in errors {
                        p class="autumn-field__error" { (error) }
                    }
                }
            }
        }
    }
}

/// The `class` a routed control carries, mirroring the `*_input` helpers:
/// `autumn-field__input`, plus the `--invalid` modifier when the field errored.
#[cfg(feature = "maud")]
const fn field_control_class(has_errors: bool) -> &'static str {
    if has_errors {
        "autumn-field__input autumn-field__input--invalid"
    } else {
        "autumn-field__input"
    }
}

/// Render a single [`FormField`], routing the pre-fill lookup through the
/// field's serialized key ([`FormField::value_name`]) when it differs from
/// the rendered input name — see [`PrefillAlias`]. Everything else (input
/// `name`/`id`, error lookup) stays keyed by [`FormField::name`].
#[cfg(feature = "maud")]
fn render_form_field<T: Serialize>(changeset: &Changeset<T>, field: &FormField) -> maud::Markup {
    if let Some(value_name) = field
        .value_name
        .as_deref()
        .filter(|value_name| *value_name != field.name)
    {
        let aliased = Changeset::from_errors(
            PrefillAlias {
                data: changeset.data(),
                serialized_name: value_name,
                exposed_name: &field.name,
            },
            changeset.errors().clone(),
        );
        return render_form_control(&aliased, field);
    }
    render_form_control(changeset, field)
}

/// Dispatch a single [`FormField`] to the matching typed-input helper.
#[cfg(feature = "maud")]
fn render_form_control<T: Serialize>(changeset: &Changeset<T>, field: &FormField) -> maud::Markup {
    match &field.control {
        FieldControl::Text => {
            if field.required {
                required_text_input(changeset, &field.name, &field.label)
            } else {
                text_input(changeset, &field.name, &field.label)
            }
        }
        FieldControl::Textarea => {
            let errors = changeset.errors_for(&field.name);
            let has_errors = !errors.is_empty();
            let value = changeset.field_value(&field.name).unwrap_or_default();
            let mut control = crate::a11y::TextArea::new(field.name.as_str())
                .label(field.label.as_str())
                .label_class("autumn-field__label")
                .value(value)
                .class(field_control_class(has_errors))
                .aria_invalid(has_errors);
            if has_errors {
                control = control.described_by(format!("{}-error", field.name));
            }
            wrap_field_control(&field.name, control, errors)
        }
        FieldControl::Password => password_input(changeset, &field.name, &field.label),
        FieldControl::Number { step } => {
            if field.required {
                required_number_input(changeset, &field.name, &field.label, step.as_deref())
            } else {
                number_input(changeset, &field.name, &field.label, step.as_deref())
            }
        }
        FieldControl::Checkbox => {
            let errors = changeset.errors_for(&field.name);
            let has_errors = !errors.is_empty();
            let checked = changeset.field_value(&field.name).as_deref() == Some("true");
            let mut control = crate::a11y::Checkbox::new(field.name.as_str())
                .label(field.label.as_str())
                .label_class("autumn-field__label")
                .value("true")
                .checked(checked)
                .class(field_control_class(has_errors))
                .aria_invalid(has_errors);
            if has_errors {
                control = control.described_by(format!("{}-error", field.name));
            }
            wrap_field_control(&field.name, control, errors)
        }
        FieldControl::Date => {
            if field.required {
                required_date_input(changeset, &field.name, &field.label)
            } else {
                date_input(changeset, &field.name, &field.label)
            }
        }
        FieldControl::DateTime => {
            if field.required {
                required_datetime_input(changeset, &field.name, &field.label)
            } else {
                datetime_input(changeset, &field.name, &field.label)
            }
        }
        FieldControl::Select { options } => {
            let errors = changeset.errors_for(&field.name);
            let has_errors = !errors.is_empty();
            let current = changeset.field_value(&field.name).unwrap_or_default();
            let mut control = crate::a11y::Select::new(field.name.as_str())
                .label(field.label.as_str())
                .label_class("autumn-field__label")
                .options(options.iter().map(|(value, label)| {
                    crate::a11y::SelectOption::new(value.as_str(), label.as_str())
                }))
                .selected_value(current)
                .class(field_control_class(has_errors))
                .aria_invalid(has_errors);
            if field.required {
                control = control.required().aria_required();
            }
            if has_errors {
                control = control.described_by(format!("{}-error", field.name));
            }
            wrap_field_control(&field.name, control, errors)
        }
        FieldControl::File => {
            // A file input can't be value-prefilled (browser security), so the
            // typed [`crate::a11y::FileField`] primitive — which deliberately
            // carries no `value` — is a natural fit; it also drops the
            // competing derived `aria-label` in favour of the visible
            // `<label for=…>`. Multipart encoding is unchanged: the
            // `FieldControl::File` variant (not its rendering) still drives the
            // `is_multipart` gate on the parent form.
            let errors = changeset.errors_for(&field.name);
            let has_errors = !errors.is_empty();
            let mut control = crate::a11y::FileField::new(field.name.as_str())
                .label(field.label.as_str())
                .label_class("autumn-field__label")
                .class(field_control_class(has_errors))
                .aria_invalid(has_errors);
            if field.required {
                control = control.required().aria_required();
            }
            if has_errors {
                control = control.described_by(format!("{}-error", field.name));
            }
            wrap_field_control(&field.name, control, errors)
        }
    }
}

// ── Tests ──────────────────────────────────────────────────────────

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

    // ── Changeset::new ─────────────────────────────────────────────

    #[test]
    fn new_changeset_is_valid() {
        let cs = Changeset::new(42_i32);
        assert!(cs.is_valid());
    }

    #[test]
    fn new_changeset_has_no_errors() {
        let cs = Changeset::new("hello");
        assert!(cs.errors().is_empty());
    }

    #[test]
    fn new_changeset_into_inner() {
        let cs = Changeset::new(99_u8);
        assert_eq!(cs.into_inner(), 99);
    }

    #[test]
    fn new_changeset_data_ref() {
        let cs = Changeset::new(vec![1, 2, 3]);
        assert_eq!(cs.data(), &vec![1, 2, 3]);
    }

    // ── Changeset::from_errors ─────────────────────────────────────

    #[test]
    fn from_errors_changeset_is_invalid() {
        let mut errors = HashMap::new();
        errors.insert("name".to_string(), vec!["too short".to_string()]);
        let cs = Changeset::from_errors("data", errors);
        assert!(!cs.is_valid());
    }

    #[test]
    fn from_errors_returns_correct_field_errors() {
        let mut errors = HashMap::new();
        errors.insert("email".to_string(), vec!["invalid email".to_string()]);
        let cs = Changeset::from_errors("data", errors);
        assert_eq!(cs.errors_for("email"), &["invalid email"]);
    }

    #[test]
    fn errors_for_unknown_field_returns_empty_slice() {
        let cs = Changeset::new("data");
        assert!(cs.errors_for("nonexistent").is_empty());
    }

    #[test]
    fn from_errors_multiple_messages_per_field() {
        let mut errors = HashMap::new();
        errors.insert(
            "password".to_string(),
            vec!["too short".to_string(), "must contain a digit".to_string()],
        );
        let cs = Changeset::from_errors("data", errors);
        let msgs = cs.errors_for("password");
        assert_eq!(msgs.len(), 2);
        assert!(msgs.contains(&"too short".to_string()));
        assert!(msgs.contains(&"must contain a digit".to_string()));
    }

    // ── Changeset::into_valid ──────────────────────────────────────

    #[test]
    fn into_valid_returns_ok_when_valid() {
        let cs = Changeset::new(42_i32);
        assert_eq!(cs.into_valid().unwrap(), 42);
    }

    #[test]
    fn into_valid_returns_err_when_invalid() {
        let mut errors = HashMap::new();
        errors.insert("x".to_string(), vec!["err".to_string()]);
        let cs = Changeset::from_errors(42_i32, errors);
        assert!(cs.into_valid().is_err());
    }

    #[test]
    fn into_valid_err_preserves_changeset() {
        let mut errors = HashMap::new();
        errors.insert("name".to_string(), vec!["required".to_string()]);
        let cs = Changeset::from_errors(7_i32, errors);
        let err_cs = cs.into_valid().unwrap_err();
        assert_eq!(err_cs.into_inner(), 7);
    }

    // ── Changeset::field_value ─────────────────────────────────────

    #[test]
    fn field_value_returns_string_field() {
        #[derive(serde::Serialize)]
        struct Form {
            name: String,
        }
        let cs = Changeset::new(Form {
            name: "Alice".into(),
        });
        assert_eq!(cs.field_value("name"), Some("Alice".to_string()));
    }

    #[test]
    fn field_value_returns_number_as_string() {
        #[derive(serde::Serialize)]
        struct Form {
            age: u32,
        }
        let cs = Changeset::new(Form { age: 30 });
        assert_eq!(cs.field_value("age"), Some("30".to_string()));
    }

    #[test]
    fn field_value_returns_bool_as_string() {
        #[derive(serde::Serialize)]
        struct Form {
            active: bool,
        }
        let cs = Changeset::new(Form { active: true });
        assert_eq!(cs.field_value("active"), Some("true".to_string()));
    }

    #[test]
    fn field_value_returns_none_for_missing_field() {
        #[derive(serde::Serialize)]
        struct Form {
            name: String,
        }
        let cs = Changeset::new(Form {
            name: "Alice".into(),
        });
        assert_eq!(cs.field_value("email"), None);
    }

    #[test]
    fn field_value_after_errors_uses_submitted_data() {
        #[derive(serde::Serialize)]
        struct Form {
            name: String,
        }
        let mut errors = HashMap::new();
        errors.insert("name".to_string(), vec!["too short".to_string()]);
        let cs = Changeset::from_errors(Form { name: "ab".into() }, errors);
        assert_eq!(cs.field_value("name"), Some("ab".to_string()));
    }

    // ── IntoChangeset ──────────────────────────────────────────────

    #[test]
    fn into_changeset_valid_input_produces_no_errors() {
        #[derive(validator::Validate)]
        struct F {
            #[validate(length(min = 3))]
            name: String,
        }
        let cs = F {
            name: "Alice".into(),
        }
        .into_changeset();
        assert!(cs.is_valid());
        assert!(cs.errors_for("name").is_empty());
    }

    #[test]
    fn into_changeset_invalid_input_populates_errors() {
        #[derive(validator::Validate)]
        struct F {
            #[validate(length(min = 5))]
            name: String,
        }
        let cs = F { name: "ab".into() }.into_changeset();
        assert!(!cs.is_valid());
        assert!(!cs.errors_for("name").is_empty());
    }

    #[test]
    fn into_changeset_preserves_data_on_failure() {
        #[derive(validator::Validate)]
        struct F {
            #[validate(length(min = 5))]
            name: String,
        }
        let cs = F { name: "ab".into() }.into_changeset();
        assert_eq!(cs.data().name, "ab");
    }

    #[test]
    fn into_changeset_multiple_fields_errors() {
        #[derive(validator::Validate)]
        struct F {
            #[validate(length(min = 3))]
            name: String,
            #[validate(email)]
            email: String,
        }
        let cs = F {
            name: "a".into(),
            email: "not-email".into(),
        }
        .into_changeset();
        assert!(!cs.is_valid());
        assert!(!cs.errors_for("name").is_empty());
        assert!(!cs.errors_for("email").is_empty());
    }

    mod nested_validation {
        use super::*;
        use validator::Validate as _;

        #[derive(validator::Validate)]
        struct NestedAddress {
            #[validate(length(min = 3, message = "street too short"))]
            street: String,
        }

        #[derive(validator::Validate)]
        struct PersonWithAddress {
            #[validate(nested)]
            address: NestedAddress,
        }

        #[test]
        fn nested_struct_errors_are_flattened_with_dot_notation() {
            let cs = PersonWithAddress {
                address: NestedAddress { street: "x".into() },
            }
            .into_changeset();
            assert!(!cs.is_valid());
            assert!(!cs.errors_for("address.street").is_empty());
        }
    }

    // ── ChangesetForm helpers ──────────────────────────────────────

    #[test]
    fn changeset_form_blank_is_valid() {
        #[derive(validator::Validate, serde::Serialize)]
        struct F {
            #[validate(length(min = 1))]
            name: String,
        }
        let form = ChangesetForm::blank(F { name: "ok".into() }, "tok");
        assert!(form.is_valid()); // via Deref
        assert_eq!(form.csrf_token(), Some("tok"));
    }

    #[test]
    fn changeset_form_deref_exposes_changeset_methods() {
        #[derive(validator::Validate)]
        struct F {
            #[validate(length(min = 3))]
            name: String,
        }
        let changeset = F { name: "ab".into() }.into_changeset();
        let form = ChangesetForm {
            changeset,
            csrf_token: None,
            csrf_field: "_csrf".into(),
        };
        // Deref gives access to Changeset methods
        assert!(!form.is_valid());
        assert!(!form.errors_for("name").is_empty());
    }

    #[test]
    fn changeset_form_into_valid_ok() {
        #[derive(validator::Validate)]
        struct F {
            #[validate(length(min = 1))]
            name: String,
        }
        let form = ChangesetForm {
            changeset: F { name: "ok".into() }.into_changeset(),
            csrf_token: None,
            csrf_field: "_csrf".into(),
        };
        assert!(form.into_valid().is_ok());
    }

    #[test]
    fn changeset_form_into_valid_err_preserves_csrf() {
        #[derive(Debug, validator::Validate)]
        struct F {
            #[validate(length(min = 5))]
            name: String,
        }
        let form = ChangesetForm {
            changeset: F { name: "ab".into() }.into_changeset(),
            csrf_token: Some("tok123".into()),
            csrf_field: "_csrf".into(),
        };
        let err_form = form.into_valid().unwrap_err();
        assert_eq!(err_form.csrf_token(), Some("tok123"));
    }

    // ── Maud helpers ───────────────────────────────────────────────

    #[cfg(feature = "maud")]
    #[test]
    fn form_tag_renders_action_and_method() {
        let html = form_tag("/users", "post", None, maud::html! { "" }).into_string();
        assert!(html.contains(r#"action="/users""#), "{html}");
        assert!(html.contains(r#"method="post""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_tag_emits_csrf_hidden_input_when_token_provided() {
        let html = form_tag("/users", "post", Some("tok123"), maud::html! { "" }).into_string();
        assert!(html.contains(r#"name="_csrf""#), "{html}");
        assert!(html.contains(r#"value="tok123""#), "{html}");
        assert!(html.contains(r#"type="hidden""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_tag_omits_csrf_input_when_none() {
        let html = form_tag("/users", "post", None, maud::html! { "" }).into_string();
        assert!(!html.contains("_csrf"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_tag_includes_content() {
        let html = form_tag("/x", "post", None, maud::html! { span { "inner" } }).into_string();
        assert!(html.contains("inner"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_tag_emits_method_override_for_delete() {
        let html = form_tag("/posts/42", "delete", None, maud::html! { "" }).into_string();
        // Browser-facing method must be POST so native form submission works.
        assert!(html.contains(r#"method="post""#), "{html}");
        assert!(!html.contains(r#"method="delete""#), "{html}");
        // Hidden override field tells the autumn middleware to rewrite to DELETE.
        assert!(html.contains(r#"name="_method""#), "{html}");
        assert!(html.contains(r#"value="DELETE""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_tag_emits_method_override_for_put_and_patch() {
        let put_html = form_tag("/p/1", "put", None, maud::html! { "" }).into_string();
        assert!(put_html.contains(r#"method="post""#));
        assert!(put_html.contains(r#"value="PUT""#));

        let patch_html = form_tag("/p/1", "PATCH", None, maud::html! { "" }).into_string();
        assert!(patch_html.contains(r#"method="post""#));
        assert!(patch_html.contains(r#"value="PATCH""#));
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_tag_no_override_for_get_or_post() {
        let get_html = form_tag("/p", "get", None, maud::html! { "" }).into_string();
        assert!(!get_html.contains("_method"), "{get_html}");
        let post_html = form_tag("/p", "post", None, maud::html! { "" }).into_string();
        assert!(!post_html.contains("_method"), "{post_html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn method_input_emits_hidden_field_for_mutating_methods() {
        for method in ["PUT", "PATCH", "DELETE", "delete"] {
            let html = method_input(method).into_string();
            assert!(html.contains(r#"name="_method""#), "{html}");
            assert!(html.contains(r#"type="hidden""#), "{html}");
        }
    }

    #[cfg(feature = "maud")]
    #[test]
    fn method_input_is_empty_for_safe_or_unknown_methods() {
        assert_eq!(method_input("GET").into_string(), "");
        assert_eq!(method_input("POST").into_string(), "");
        assert_eq!(method_input("BREW").into_string(), "");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn changeset_form_form_tag_injects_stored_csrf() {
        #[derive(validator::Validate, serde::Serialize)]
        struct F {
            name: String,
        }
        let form = ChangesetForm::blank(
            F {
                name: String::new(),
            },
            "secret-token",
        );
        let html = form
            .form_tag("/x", "post", maud::html! { "" })
            .into_string();
        assert!(html.contains(r#"value="secret-token""#), "{html}");
        assert!(html.contains(r#"name="_csrf""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn changeset_form_form_tag_honours_custom_csrf_field_name() {
        #[derive(validator::Validate, serde::Serialize)]
        struct F {
            name: String,
        }
        let form = ChangesetForm {
            changeset: Changeset::new(F {
                name: String::new(),
            }),
            csrf_token: Some("tok".into()),
            csrf_field: "authenticity_token".into(),
        };
        let html = form
            .form_tag("/x", "post", maud::html! { "" })
            .into_string();
        assert!(html.contains(r#"name="authenticity_token""#), "{html}");
        assert!(!html.contains(r#"name="_csrf""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_renders_label_name_and_value() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: "Alice".into(),
        });
        let html = text_input(&cs, "name", "Full Name").into_string();
        assert!(html.contains(r#"name="name""#), "{html}");
        assert!(html.contains(r#"value="Alice""#), "{html}");
        assert!(html.contains("Full Name"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_aria_invalid_false_when_no_errors() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: "Alice".into(),
        });
        let html = text_input(&cs, "name", "Name").into_string();
        assert!(html.contains(r#"aria-invalid="false""#), "{html}");
        assert!(!html.contains(r#"role="alert""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_aria_invalid_true_and_error_block_on_failure() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let mut errors = HashMap::new();
        errors.insert("name".to_string(), vec!["too short".to_string()]);
        let cs = Changeset::from_errors(F { name: "ab".into() }, errors);
        let html = text_input(&cs, "name", "Name").into_string();
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains("too short"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_error_block_has_describedby_link() {
        #[derive(serde::Serialize)]
        struct F {
            email: String,
        }
        let mut errors = HashMap::new();
        errors.insert("email".to_string(), vec!["invalid".to_string()]);
        let cs = Changeset::from_errors(F { email: "x".into() }, errors);
        let html = text_input(&cs, "email", "Email").into_string();
        assert!(html.contains("email-error"), "{html}");
        assert!(html.contains(r#"aria-describedby="email-error""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_multiple_errors_all_rendered() {
        #[derive(serde::Serialize)]
        struct F {
            password: String,
        }
        let mut errors = HashMap::new();
        errors.insert(
            "password".to_string(),
            vec!["too short".to_string(), "needs digit".to_string()],
        );
        let cs = Changeset::from_errors(
            F {
                password: "x".into(),
            },
            errors,
        );
        let html = text_input(&cs, "password", "Password").into_string();
        assert!(html.contains("too short"), "{html}");
        assert!(html.contains("needs digit"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn submit_button_renders_button_with_label() {
        let html = submit_button("Save").into_string();
        assert!(html.contains(r#"type="submit""#), "{html}");
        assert!(html.contains("Save"), "{html}");
    }

    // ── RED: accessible form helpers ───────────────────────────────

    #[cfg(feature = "maud")]
    #[test]
    fn password_input_renders_type_password() {
        #[derive(serde::Serialize)]
        struct F {
            password: String,
        }
        let cs = Changeset::new(F {
            password: String::new(),
        });
        let html = password_input(&cs, "password", "Password").into_string();
        assert!(html.contains(r#"type="password""#), "{html}");
        assert!(html.contains(r#"name="password""#), "{html}");
        assert!(html.contains("Password"), "{html}");
        // Must NOT expose the value in the rendered HTML
        assert!(!html.contains(r#"value=""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn password_input_emits_aria_invalid_on_error() {
        #[derive(serde::Serialize)]
        struct F {
            password: String,
        }
        let mut errors = HashMap::new();
        errors.insert("password".to_string(), vec!["too short".to_string()]);
        let cs = Changeset::from_errors(
            F {
                password: "x".into(),
            },
            errors,
        );
        let html = password_input(&cs, "password", "Password").into_string();
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains("too short"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn textarea_input_renders_textarea_element() {
        #[derive(serde::Serialize)]
        struct F {
            bio: String,
        }
        let cs = Changeset::new(F {
            bio: "Hello world".into(),
        });
        let html = textarea_input(&cs, "bio", "Bio").into_string();
        assert!(html.contains("<textarea"), "{html}");
        assert!(html.contains(r#"name="bio""#), "{html}");
        assert!(html.contains(r#"id="bio""#), "{html}");
        assert!(html.contains("Bio"), "{html}");
        assert!(html.contains("Hello world"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn textarea_input_aria_invalid_on_error() {
        #[derive(serde::Serialize)]
        struct F {
            bio: String,
        }
        let mut errors = HashMap::new();
        errors.insert("bio".to_string(), vec!["required".to_string()]);
        let cs = Changeset::from_errors(F { bio: String::new() }, errors);
        let html = textarea_input(&cs, "bio", "Bio").into_string();
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains("required"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn required_text_input_emits_aria_required() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: "Alice".into(),
        });
        let html = required_text_input(&cs, "name", "Name").into_string();
        assert!(html.contains(r#"aria-required="true""#), "{html}");
        assert!(html.contains("required"), "{html}");
        assert!(html.contains(r#"name="name""#), "{html}");
        assert!(html.contains("Name"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn required_text_input_preserves_error_handling() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let mut errors = HashMap::new();
        errors.insert("name".to_string(), vec!["required".to_string()]);
        let cs = Changeset::from_errors(
            F {
                name: String::new(),
            },
            errors,
        );
        let html = required_text_input(&cs, "name", "Name").into_string();
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"aria-required="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn aria_live_region_renders_role_status() {
        let html = aria_live_region("status-msg", "").into_string();
        assert!(html.contains(r#"role="status""#), "{html}");
        assert!(html.contains(r#"aria-live="polite""#), "{html}");
        assert!(html.contains(r#"id="status-msg""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn aria_live_region_renders_message_content() {
        let html = aria_live_region("status-msg", "Form submitted").into_string();
        assert!(html.contains("Form submitted"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn skip_link_renders_anchor_with_href() {
        let html = skip_link("#main-content", "Skip to main content").into_string();
        assert!(html.contains(r##"href="#main-content""##), "{html}");
        assert!(html.contains("Skip to main content"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn skip_link_has_visually_hidden_class_for_focus_reveal() {
        let html = skip_link("#main", "Skip").into_string();
        assert!(html.contains("skip-link"), "{html}");
    }

    // ── AC2: Stable wrapper IDs ────────────────────────────────────

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_wrapper_div_has_stable_id() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: "Alice".into(),
        });
        let html = text_input(&cs, "name", "Name").into_string();
        assert!(html.contains(r#"id="name-field""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn password_input_wrapper_div_has_stable_id() {
        #[derive(serde::Serialize)]
        struct F {
            password: String,
        }
        let cs = Changeset::new(F {
            password: String::new(),
        });
        let html = password_input(&cs, "password", "Password").into_string();
        assert!(html.contains(r#"id="password-field""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn textarea_input_wrapper_div_has_stable_id() {
        #[derive(serde::Serialize)]
        struct F {
            bio: String,
        }
        let cs = Changeset::new(F {
            bio: "Hello".into(),
        });
        let html = textarea_input(&cs, "bio", "Bio").into_string();
        assert!(html.contains(r#"id="bio-field""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn required_text_input_wrapper_div_has_stable_id() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: "Alice".into(),
        });
        let html = required_text_input(&cs, "name", "Name").into_string();
        assert!(html.contains(r#"id="name-field""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn required_number_input_emits_aria_required() {
        #[derive(serde::Serialize)]
        struct F {
            age: i32,
        }
        let cs = Changeset::new(F { age: 30 });
        let html = required_number_input(&cs, "age", "Age", Some("1")).into_string();
        assert!(html.contains(r#"aria-required="true""#), "{html}");
        assert!(html.contains("required"), "{html}");
        assert!(html.contains(r#"type="number""#), "{html}");
        assert!(html.contains(r#"name="age""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn required_number_input_preserves_error_handling() {
        #[derive(serde::Serialize)]
        struct F {
            age: i32,
        }
        let mut errors = HashMap::new();
        errors.insert("age".to_string(), vec!["must be positive".to_string()]);
        let cs = Changeset::from_errors(F { age: -1 }, errors);
        let html = required_number_input(&cs, "age", "Age", Some("1")).into_string();
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains("must be positive"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn required_datetime_input_emits_aria_required() {
        #[derive(serde::Serialize)]
        struct F {
            scheduled_at: String,
        }
        let cs = Changeset::new(F {
            scheduled_at: "2026-01-01T12:00:00".into(),
        });
        let html = required_datetime_input(&cs, "scheduled_at", "Scheduled at").into_string();
        assert!(html.contains(r#"aria-required="true""#), "{html}");
        assert!(html.contains("required"), "{html}");
        assert!(html.contains(r#"type="datetime-local""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn required_select_input_emits_aria_required() {
        #[derive(serde::Serialize)]
        struct F {
            status: String,
        }
        let cs = Changeset::new(F {
            status: "draft".into(),
        });
        let html = required_select_input(
            &cs,
            "status",
            "Status",
            &[("draft", "Draft"), ("published", "Published")],
        )
        .into_string();
        assert!(html.contains(r#"aria-required="true""#), "{html}");
        assert!(html.contains("required"), "{html}");
        assert!(html.contains("<select"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn required_select_input_preserves_error_handling() {
        #[derive(serde::Serialize)]
        struct F {
            status: String,
        }
        let mut errors = HashMap::new();
        errors.insert("status".to_string(), vec!["is required".to_string()]);
        let cs = Changeset::from_errors(
            F {
                status: String::new(),
            },
            errors,
        );
        let html =
            required_select_input(&cs, "status", "Status", &[("draft", "Draft")]).into_string();
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains("is required"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn required_text_input_htmx_emits_aria_required() {
        #[derive(serde::Serialize)]
        struct F {
            title: String,
        }
        let cs = Changeset::new(F {
            title: "Hello".into(),
        });
        let html =
            required_text_input_htmx(&cs, "title", "Title", "/posts/validate/title").into_string();
        assert!(html.contains(r#"aria-required="true""#), "{html}");
        assert!(html.contains("required"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn required_text_input_htmx_preserves_htmx_attributes() {
        #[derive(serde::Serialize)]
        struct F {
            title: String,
        }
        let cs = Changeset::new(F {
            title: String::new(),
        });
        let html =
            required_text_input_htmx(&cs, "title", "Title", "/posts/validate/title").into_string();
        assert!(
            html.contains(r#"hx-post="/posts/validate/title""#),
            "{html}"
        );
        assert!(html.contains(r#"hx-trigger="change""#), "{html}");
        assert!(
            html.contains(r#"hx-target="closest [data-autumn-field-wrapper]""#),
            "{html}"
        );
        assert!(html.contains(r#"hx-swap="outerHTML""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn required_text_input_htmx_preserves_error_handling() {
        #[derive(serde::Serialize)]
        struct F {
            title: String,
        }
        let mut errors = HashMap::new();
        errors.insert("title".to_string(), vec!["is required".to_string()]);
        let cs = Changeset::from_errors(
            F {
                title: String::new(),
            },
            errors,
        );
        let html =
            required_text_input_htmx(&cs, "title", "Title", "/posts/validate/title").into_string();
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains("is required"), "{html}");
    }

    // ── AC2 + AC3: text_input_htmx ────────────────────────────────

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_htmx_wrapper_has_stable_id() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: "Alice".into(),
        });
        let html = text_input_htmx(&cs, "name", "Name", "/validate/name").into_string();
        assert!(html.contains(r#"id="name-field""#), "{html}");
        assert!(
            html.contains(r#"data-autumn-field-wrapper="name""#),
            "{html}"
        );
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_htmx_renders_hx_post() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: "Alice".into(),
        });
        let html = text_input_htmx(&cs, "name", "Name", "/validate/name").into_string();
        assert!(html.contains(r#"hx-post="/validate/name""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_htmx_renders_hx_trigger_change() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: String::new(),
        });
        let html = text_input_htmx(&cs, "name", "Name", "/validate/name").into_string();
        assert!(html.contains(r#"hx-trigger="change""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_htmx_renders_hx_target_and_swap() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: String::new(),
        });
        let html = text_input_htmx(&cs, "name", "Name", "/validate/name").into_string();
        assert!(
            html.contains(r#"hx-target="closest [data-autumn-field-wrapper]""#),
            "{html}"
        );
        assert!(html.contains(r#"hx-swap="outerHTML""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_htmx_target_is_safe_for_nested_field_names() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: String::new(),
        });
        let html =
            text_input_htmx(&cs, "address.street", "Street", "/validate/street").into_string();
        assert!(html.contains(r#"id="address.street-field""#), "{html}");
        assert!(
            html.contains(r#"hx-target="closest [data-autumn-field-wrapper]""#),
            "{html}"
        );
        assert!(
            !html.contains("hx-target=\"#address.street-field\""),
            "{html}"
        );
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_htmx_includes_all_form_fields() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: String::new(),
        });
        let html = text_input_htmx(&cs, "name", "Name", "/validate/name").into_string();
        assert!(html.contains(r#"hx-include="closest form""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_htmx_drops_submit_token_param() {
        // The inline-validation POST `hx-include`s the whole form, which carries
        // the hidden one-time `_submit_token` (issue #1360). `SubmitTokenLayer`
        // consumes any `_submit_token` a mutating POST carries, so validation
        // must filter it out via `hx-params` — otherwise the first field
        // validation spends the token and the real submit replays the fragment.
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: String::new(),
        });
        let plain = text_input_htmx(&cs, "name", "Name", "/validate/name").into_string();
        assert!(
            plain.contains(r#"hx-params="not _submit_token""#),
            "{plain}"
        );
        let required =
            required_text_input_htmx(&cs, "name", "Name", "/validate/name").into_string();
        assert!(
            required.contains(r#"hx-params="not _submit_token""#),
            "{required}"
        );
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_htmx_with_token_field_filters_custom_field() {
        // When the app customizes `[security.submit_token].field_name`, the
        // `*_with_token_field` variants must exclude the configured field name
        // from the inline-validation POST (issue #1843), not the default.
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: String::new(),
        });
        let plain =
            text_input_htmx_with_token_field(&cs, "name", "Name", "/validate/name", "csrf_tok")
                .into_string();
        assert!(plain.contains(r#"hx-params="not csrf_tok""#), "{plain}");
        assert!(!plain.contains("_submit_token"), "{plain}");

        let required = required_text_input_htmx_with_token_field(
            &cs,
            "name",
            "Name",
            "/validate/name",
            "csrf_tok",
        )
        .into_string();
        assert!(
            required.contains(r#"hx-params="not csrf_tok""#),
            "{required}"
        );
        assert!(!required.contains("_submit_token"), "{required}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn with_token_field_default_matches_legacy_helpers() {
        // Passing the default field name reproduces the original hardcoded
        // `hx-params="not _submit_token"` behaviour, guarding backward compat.
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: String::new(),
        });
        assert_eq!(
            text_input_htmx_with_token_field(
                &cs,
                "name",
                "Name",
                "/validate/name",
                "_submit_token"
            )
            .into_string(),
            text_input_htmx(&cs, "name", "Name", "/validate/name").into_string(),
        );
        assert_eq!(
            required_text_input_htmx_with_token_field(
                &cs,
                "name",
                "Name",
                "/validate/name",
                "_submit_token",
            )
            .into_string(),
            required_text_input_htmx(&cs, "name", "Name", "/validate/name").into_string(),
        );
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_htmx_valid_state_no_error_markup() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let cs = Changeset::new(F {
            name: "Alice".into(),
        });
        let html = text_input_htmx(&cs, "name", "Name", "/v").into_string();
        assert!(!html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains(r#"aria-invalid="false""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_htmx_invalid_preserves_value_and_shows_errors() {
        #[derive(serde::Serialize)]
        struct F {
            name: String,
        }
        let mut errors = HashMap::new();
        errors.insert("name".to_string(), vec!["too short".to_string()]);
        let cs = Changeset::from_errors(F { name: "ab".into() }, errors);
        let html = text_input_htmx(&cs, "name", "Name", "/v").into_string();
        assert!(html.contains(r#"value="ab""#), "{html}");
        assert!(html.contains("too short"), "{html}");
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn text_input_htmx_invalid_has_describedby_link() {
        #[derive(serde::Serialize)]
        struct F {
            email: String,
        }
        let mut errors = HashMap::new();
        errors.insert("email".to_string(), vec!["invalid".to_string()]);
        let cs = Changeset::from_errors(F { email: "x".into() }, errors);
        let html = text_input_htmx(&cs, "email", "Email", "/v").into_string();
        assert!(html.contains("email-error"), "{html}");
        assert!(html.contains(r#"aria-describedby="email-error""#), "{html}");
    }

    // ── Typed inputs: checkbox_input / number_input / date_input /
    //    datetime_input / select_input (issue #1131) ────────────────

    #[cfg(feature = "maud")]
    #[test]
    fn checkbox_input_renders_type_checkbox() {
        #[derive(serde::Serialize)]
        struct F {
            active: bool,
        }
        let cs = Changeset::new(F { active: false });
        let html = checkbox_input(&cs, "active", "Active").into_string();
        assert!(html.contains(r#"type="checkbox""#), "{html}");
        assert!(html.contains(r#"name="active""#), "{html}");
        assert!(html.contains("Active"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn checkbox_input_unchecked_when_value_false() {
        #[derive(serde::Serialize)]
        struct F {
            active: bool,
        }
        let cs = Changeset::new(F { active: false });
        let html = checkbox_input(&cs, "active", "Active").into_string();
        assert!(!html.contains("checked"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn checkbox_input_checked_when_value_true() {
        #[derive(serde::Serialize)]
        struct F {
            active: bool,
        }
        let cs = Changeset::new(F { active: true });
        let html = checkbox_input(&cs, "active", "Active").into_string();
        assert!(html.contains("checked"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn checkbox_input_never_emits_a_hidden_fallback() {
        // A hidden "false" sibling sharing the checkbox's `name` would make a
        // *checked* submission send the key twice (`field=false&field=true`).
        // serde_urlencoded rejects duplicate keys outright rather than taking
        // the last value, so every checked submission would 400. Unchecked
        // state must be recovered via `#[serde(default)]` on the target
        // field instead (see the function's doc comment) — never via a
        // hidden fallback input.
        #[derive(serde::Serialize)]
        struct F {
            active: bool,
        }
        let cs = Changeset::new(F { active: false });
        let html = checkbox_input(&cs, "active", "Active").into_string();
        assert!(!html.contains(r#"type="hidden""#), "{html}");
        assert_eq!(
            html.matches(r#"name="active""#).count(),
            1,
            "checkbox_input must emit exactly one input named `active` \
             (a second `name=\"active\"` sibling would duplicate the key \
             on submission): {html}"
        );
    }

    #[cfg(feature = "maud")]
    #[test]
    fn checkbox_input_round_trips_through_real_url_decode_when_checked() {
        // Regression test for the duplicate-key 400: decode the *exact*
        // query string a browser sends for a CHECKED box rendered by
        // checkbox_input (i.e. only the fields checkbox_input itself
        // renders — no hidden sibling), through the same serde_urlencoded
        // machinery axum's `Form` extractor and ChangesetForm use.
        #[derive(serde::Serialize)]
        struct F {
            active: bool,
        }
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(default)]
            active: bool,
        }
        let cs = Changeset::new(F { active: true });
        let html = checkbox_input(&cs, "active", "Active").into_string();
        assert!(html.contains("checked"), "{html}");

        // A checked box submits `active=true` and nothing else.
        let decoded: Decoded = serde_urlencoded::from_str("active=true").unwrap();
        assert!(decoded.active);
    }

    #[cfg(feature = "maud")]
    #[test]
    fn checkbox_input_round_trips_through_real_url_decode_when_unchecked() {
        // An unchecked box submits no `active` key at all; `#[serde(default)]`
        // must recover `false` rather than erroring "missing field".
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(default)]
            active: bool,
        }
        let decoded: Decoded = serde_urlencoded::from_str("").unwrap();
        assert!(!decoded.active);
    }

    #[cfg(feature = "maud")]
    #[test]
    fn checkbox_input_wrapper_div_has_stable_id() {
        #[derive(serde::Serialize)]
        struct F {
            active: bool,
        }
        let cs = Changeset::new(F { active: false });
        let html = checkbox_input(&cs, "active", "Active").into_string();
        assert!(html.contains(r#"id="active-field""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn checkbox_input_emits_aria_invalid_and_errors() {
        #[derive(serde::Serialize)]
        struct F {
            active: bool,
        }
        let mut errors = HashMap::new();
        errors.insert("active".to_string(), vec!["must be true".to_string()]);
        let cs = Changeset::from_errors(F { active: false }, errors);
        let html = checkbox_input(&cs, "active", "Active").into_string();
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains("must be true"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn number_input_renders_type_number() {
        #[derive(serde::Serialize)]
        struct F {
            age: i32,
        }
        let cs = Changeset::new(F { age: 30 });
        let html = number_input(&cs, "age", "Age", Some("1")).into_string();
        assert!(html.contains(r#"type="number""#), "{html}");
        assert!(html.contains(r#"name="age""#), "{html}");
        assert!(html.contains(r#"value="30""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn number_input_renders_step_when_provided() {
        #[derive(serde::Serialize)]
        struct F {
            price: f64,
        }
        let cs = Changeset::new(F { price: 9.99 });
        let html = number_input(&cs, "price", "Price", Some("0.01")).into_string();
        assert!(html.contains(r#"step="0.01""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn number_input_omits_step_when_none() {
        #[derive(serde::Serialize)]
        struct F {
            age: i32,
        }
        let cs = Changeset::new(F { age: 30 });
        let html = number_input(&cs, "age", "Age", None).into_string();
        assert!(!html.contains("step="), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn number_input_emits_aria_invalid_and_errors() {
        #[derive(serde::Serialize)]
        struct F {
            age: i32,
        }
        let mut errors = HashMap::new();
        errors.insert("age".to_string(), vec!["must be positive".to_string()]);
        let cs = Changeset::from_errors(F { age: -1 }, errors);
        let html = number_input(&cs, "age", "Age", None).into_string();
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains("must be positive"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn number_input_wrapper_div_has_stable_id() {
        #[derive(serde::Serialize)]
        struct F {
            age: i32,
        }
        let cs = Changeset::new(F { age: 30 });
        let html = number_input(&cs, "age", "Age", None).into_string();
        assert!(html.contains(r#"id="age-field""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn date_input_renders_type_date() {
        #[derive(serde::Serialize)]
        struct F {
            born_on: String,
        }
        let cs = Changeset::new(F {
            born_on: "2024-03-15".into(),
        });
        let html = date_input(&cs, "born_on", "Born on").into_string();
        assert!(html.contains(r#"type="date""#), "{html}");
        assert!(html.contains(r#"value="2024-03-15""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn date_input_normalizes_full_timestamp_to_date_only() {
        #[derive(serde::Serialize)]
        struct F {
            born_on: String,
        }
        let cs = Changeset::new(F {
            born_on: "2024-03-15T10:30:00Z".into(),
        });
        let html = date_input(&cs, "born_on", "Born on").into_string();
        assert!(html.contains(r#"value="2024-03-15""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn date_input_normalizes_space_separated_datetime_to_date_only() {
        // `NaiveDateTime`'s `Display` (as opposed to its serde
        // serialization) uses a space separator, e.g. from a raw
        // `.to_string()` or some database drivers — accept it defensively
        // rather than falling through to the raw (browser-rejected) string.
        #[derive(serde::Serialize)]
        struct F {
            born_on: String,
        }
        let cs = Changeset::new(F {
            born_on: "2024-03-15 10:30:00".into(),
        });
        let html = date_input(&cs, "born_on", "Born on").into_string();
        assert!(html.contains(r#"value="2024-03-15""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn date_input_emits_aria_invalid_and_errors() {
        #[derive(serde::Serialize)]
        struct F {
            born_on: String,
        }
        let mut errors = HashMap::new();
        errors.insert("born_on".to_string(), vec!["required".to_string()]);
        let cs = Changeset::from_errors(
            F {
                born_on: String::new(),
            },
            errors,
        );
        let html = date_input(&cs, "born_on", "Born on").into_string();
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains("required"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn datetime_input_renders_type_datetime_local() {
        #[derive(serde::Serialize)]
        struct F {
            starts_at: String,
        }
        let cs = Changeset::new(F {
            starts_at: "2024-03-15T10:30:00".into(),
        });
        let html = datetime_input(&cs, "starts_at", "Starts at").into_string();
        assert!(html.contains(r#"type="datetime-local""#), "{html}");
        // Seconds must be preserved, not truncated to minutes: chrono's
        // default Deserialize requires the seconds component, so a
        // minute-only value would fail to decode on an untouched submission.
        assert!(html.contains(r#"value="2024-03-15T10:30:00""#), "{html}");
        // `step="any"` so that value doesn't fail step-mismatch validation
        // (default step is minute-granularity) and block submission.
        assert!(html.contains(r#"step="any""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn datetime_input_normalizes_rfc3339_with_offset_to_local_shape() {
        #[derive(serde::Serialize)]
        struct F {
            starts_at: String,
        }
        let cs = Changeset::new(F {
            starts_at: "2024-03-15T10:30:00Z".into(),
        });
        let html = datetime_input(&cs, "starts_at", "Starts at").into_string();
        // Browsers reject a trailing `Z`/offset in a `datetime-local` value;
        // must be reduced to the bare local-shaped `YYYY-MM-DDTHH:MM:SS`.
        assert!(html.contains(r#"value="2024-03-15T10:30:00""#), "{html}");
        assert!(!html.contains(r#"value="2024-03-15T10:30:00Z""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn datetime_input_normalizes_space_separated_datetime() {
        // `NaiveDateTime`'s `Display` uses a space separator, e.g. from a
        // raw `.to_string()` or some database drivers — accept it
        // defensively rather than falling through to the raw string, which
        // `<input type="datetime-local">` (strictly requiring `T`) rejects.
        #[derive(serde::Serialize)]
        struct F {
            starts_at: String,
        }
        let cs = Changeset::new(F {
            starts_at: "2024-03-15 10:30:00".into(),
        });
        let html = datetime_input(&cs, "starts_at", "Starts at").into_string();
        assert!(html.contains(r#"value="2024-03-15T10:30:00""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn datetime_input_emits_aria_invalid_and_errors() {
        #[derive(serde::Serialize)]
        struct F {
            starts_at: String,
        }
        let mut errors = HashMap::new();
        errors.insert("starts_at".to_string(), vec!["required".to_string()]);
        let cs = Changeset::from_errors(
            F {
                starts_at: String::new(),
            },
            errors,
        );
        let html = datetime_input(&cs, "starts_at", "Starts at").into_string();
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains("required"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn datetime_input_value_round_trips_through_chronos_default_deserialize() {
        // Regression test: chrono's default `serde::Deserialize` for
        // `NaiveDateTime` requires the seconds component ("premature end of
        // input" otherwise). A hand-written form using `datetime_input` with
        // a plain `chrono::NaiveDateTime` changeset field must be able to
        // submit the *pre-filled, untouched* value and have it decode
        // successfully — not just render without visible truncation.
        #[derive(serde::Serialize)]
        struct F {
            starts_at: chrono::NaiveDateTime,
        }
        #[derive(serde::Deserialize)]
        struct Decoded {
            starts_at: chrono::NaiveDateTime,
        }
        let stored = chrono::NaiveDate::from_ymd_opt(2024, 3, 15)
            .unwrap()
            .and_hms_opt(10, 30, 56)
            .unwrap();
        let cs = Changeset::new(F { starts_at: stored });
        let html = datetime_input(&cs, "starts_at", "Starts at").into_string();

        // Extract the rendered value attribute and submit it exactly as a
        // browser would on a no-op edit (field untouched).
        let value = html
            .split("value=\"")
            .nth(1)
            .and_then(|s| s.split('"').next())
            .expect("value attribute present");
        let body = format!("starts_at={value}");
        let decoded: Decoded =
            serde_urlencoded::from_str(&body).expect("pre-filled value must decode");
        assert_eq!(decoded.starts_at, stored);
    }

    #[cfg(feature = "maud")]
    #[test]
    fn datetime_input_value_round_trips_for_utc_datetime_with_deserialize_helper() {
        // Regression test: a DateTime<Utc> field's datetime_input value has
        // no offset (datetime-local has no timezone concept), which chrono's
        // *default* Deserialize for DateTime<Utc> rejects. Confirm the
        // pre-filled value decodes successfully when the field is annotated
        // with deserialize_datetime_local_utc, as documented on
        // datetime_input.
        #[derive(serde::Serialize)]
        struct F {
            starts_at: chrono::DateTime<chrono::Utc>,
        }
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(deserialize_with = "deserialize_datetime_local_utc")]
            starts_at: chrono::DateTime<chrono::Utc>,
        }
        let stored = chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
            chrono::NaiveDate::from_ymd_opt(2024, 3, 15)
                .unwrap()
                .and_hms_opt(10, 30, 56)
                .unwrap(),
            chrono::Utc,
        );
        let cs = Changeset::new(F { starts_at: stored });
        let html = datetime_input(&cs, "starts_at", "Starts at").into_string();
        // The rendered value must not carry an offset/Z (would break the
        // datetime-local input); confirm that first.
        let value = html
            .split("value=\"")
            .nth(1)
            .and_then(|s| s.split('"').next())
            .expect("value attribute present");
        assert!(!value.contains('Z') && !value.contains('+'), "{value}");

        let body = format!("starts_at={value}");
        let decoded: Decoded =
            serde_urlencoded::from_str(&body).expect("pre-filled value must decode");
        assert_eq!(decoded.starts_at, stored);
    }

    #[cfg(feature = "maud")]
    #[test]
    fn deserialize_datetime_local_utc_pads_missing_seconds() {
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(deserialize_with = "deserialize_datetime_local_utc")]
            starts_at: chrono::DateTime<chrono::Utc>,
        }
        let decoded: Decoded = serde_urlencoded::from_str("starts_at=2024-03-15T10:30").unwrap();
        assert_eq!(
            decoded.starts_at,
            chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
                chrono::NaiveDate::from_ymd_opt(2024, 3, 15)
                    .unwrap()
                    .and_hms_opt(10, 30, 0)
                    .unwrap(),
                chrono::Utc,
            )
        );
    }

    #[test]
    fn deserialize_datetime_local_utc_accepts_rfc3339_with_offset() {
        // The same struct often serves JSON API create bodies — the helper
        // must keep accepting RFC 3339, honoring an explicit offset by
        // converting to UTC.
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(deserialize_with = "deserialize_datetime_local_utc")]
            starts_at: chrono::DateTime<chrono::Utc>,
        }
        let expected = chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
            chrono::NaiveDate::from_ymd_opt(2024, 3, 15)
                .unwrap()
                .and_hms_opt(10, 30, 56)
                .unwrap(),
            chrono::Utc,
        );
        let decoded: Decoded =
            serde_json::from_str(r#"{"starts_at":"2024-03-15T10:30:56Z"}"#).unwrap();
        assert_eq!(decoded.starts_at, expected);
        // +09:00 wall clock 19:30:56 is the same instant.
        let decoded: Decoded =
            serde_json::from_str(r#"{"starts_at":"2024-03-15T19:30:56+09:00"}"#).unwrap();
        assert_eq!(decoded.starts_at, expected);
    }

    #[cfg(feature = "maud")]
    #[test]
    fn deserialize_datetime_local_utc_option_absent_key_is_none() {
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(default, deserialize_with = "deserialize_datetime_local_utc_option")]
            starts_at: Option<chrono::DateTime<chrono::Utc>>,
        }
        let decoded: Decoded = serde_urlencoded::from_str("").unwrap();
        assert_eq!(decoded.starts_at, None);
    }

    #[cfg(feature = "maud")]
    #[test]
    fn deserialize_datetime_local_utc_option_present_key_is_some() {
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(default, deserialize_with = "deserialize_datetime_local_utc_option")]
            starts_at: Option<chrono::DateTime<chrono::Utc>>,
        }
        let decoded: Decoded = serde_urlencoded::from_str("starts_at=2024-03-15T10:30:56").unwrap();
        assert_eq!(
            decoded.starts_at,
            Some(chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
                chrono::NaiveDate::from_ymd_opt(2024, 3, 15)
                    .unwrap()
                    .and_hms_opt(10, 30, 56)
                    .unwrap(),
                chrono::Utc,
            ))
        );
    }

    #[test]
    fn deserialize_datetime_local_local_interprets_offsetless_as_local_wall_clock() {
        // The offsetless datetime-local shape names a wall clock in the
        // server's local zone; the decoded instant's local wall clock must
        // match it regardless of what TZ the test host runs in. Midday is
        // safely outside every real zone's DST transition window, so this is
        // deterministic without pinning `TZ`.
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(deserialize_with = "deserialize_datetime_local_local")]
            starts_at: chrono::DateTime<chrono::Local>,
        }
        let expected_wall_clock = chrono::NaiveDate::from_ymd_opt(2024, 3, 15)
            .unwrap()
            .and_hms_opt(12, 30, 56)
            .unwrap();
        let decoded: Decoded =
            serde_json::from_str(r#"{"starts_at":"2024-03-15T12:30:56"}"#).unwrap();
        assert_eq!(decoded.starts_at.naive_local(), expected_wall_clock);

        // Seconds dropped by a minute-granularity picker are padded.
        let decoded: Decoded = serde_json::from_str(r#"{"starts_at":"2024-03-15T12:30"}"#).unwrap();
        assert_eq!(
            decoded.starts_at.naive_local(),
            chrono::NaiveDate::from_ymd_opt(2024, 3, 15)
                .unwrap()
                .and_hms_opt(12, 30, 0)
                .unwrap()
        );
    }

    #[test]
    fn deserialize_datetime_local_local_accepts_rfc3339_with_offset() {
        // The same struct often serves JSON API create bodies — the helper
        // must keep accepting RFC 3339, honoring an explicit offset by
        // converting the instant to the local zone.
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(deserialize_with = "deserialize_datetime_local_local")]
            starts_at: chrono::DateTime<chrono::Local>,
        }
        let expected = chrono::DateTime::parse_from_rfc3339("2024-03-15T10:30:56Z")
            .unwrap()
            .with_timezone(&chrono::Local);
        let decoded: Decoded =
            serde_json::from_str(r#"{"starts_at":"2024-03-15T10:30:56Z"}"#).unwrap();
        assert_eq!(decoded.starts_at, expected);
        // +09:00 wall clock 19:30:56 is the same instant.
        let decoded: Decoded =
            serde_json::from_str(r#"{"starts_at":"2024-03-15T19:30:56+09:00"}"#).unwrap();
        assert_eq!(decoded.starts_at, expected);
    }

    #[cfg(feature = "maud")]
    #[test]
    fn deserialize_datetime_local_local_option_absent_and_empty_are_none() {
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(default, deserialize_with = "deserialize_datetime_local_local_option")]
            starts_at: Option<chrono::DateTime<chrono::Local>>,
        }
        let decoded: Decoded = serde_urlencoded::from_str("").unwrap();
        assert_eq!(decoded.starts_at, None);
        let decoded: Decoded = serde_urlencoded::from_str("starts_at=").unwrap();
        assert_eq!(decoded.starts_at, None);
        let decoded: Decoded = serde_urlencoded::from_str("starts_at=2024-03-15T12:30:56").unwrap();
        assert_eq!(
            decoded.starts_at.map(|dt| dt.naive_local()),
            Some(
                chrono::NaiveDate::from_ymd_opt(2024, 3, 15)
                    .unwrap()
                    .and_hms_opt(12, 30, 56)
                    .unwrap()
            )
        );
    }

    #[cfg(feature = "maud")]
    #[test]
    fn deserialize_naive_datetime_local_pads_missing_seconds() {
        // Regression test: a value the user actively edits through the
        // native picker isn't guaranteed to include seconds, unlike the
        // always-seconds-inclusive pre-filled value — this must not 400.
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(deserialize_with = "deserialize_naive_datetime_local")]
            starts_at: chrono::NaiveDateTime,
        }
        let decoded: Decoded = serde_urlencoded::from_str("starts_at=2024-03-15T10:30").unwrap();
        assert_eq!(
            decoded.starts_at,
            chrono::NaiveDate::from_ymd_opt(2024, 3, 15)
                .unwrap()
                .and_hms_opt(10, 30, 0)
                .unwrap()
        );
    }

    #[cfg(feature = "maud")]
    #[test]
    fn deserialize_naive_datetime_local_preserves_seconds_when_present() {
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(deserialize_with = "deserialize_naive_datetime_local")]
            starts_at: chrono::NaiveDateTime,
        }
        let decoded: Decoded = serde_urlencoded::from_str("starts_at=2024-03-15T10:30:56").unwrap();
        assert_eq!(
            decoded.starts_at,
            chrono::NaiveDate::from_ymd_opt(2024, 3, 15)
                .unwrap()
                .and_hms_opt(10, 30, 56)
                .unwrap()
        );
    }

    #[cfg(feature = "maud")]
    #[test]
    fn deserialize_naive_datetime_local_option_absent_key_is_none() {
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(default, deserialize_with = "deserialize_naive_datetime_local_option")]
            starts_at: Option<chrono::NaiveDateTime>,
        }
        let decoded: Decoded = serde_urlencoded::from_str("").unwrap();
        assert_eq!(decoded.starts_at, None);
    }

    #[cfg(feature = "maud")]
    #[test]
    fn deserialize_naive_datetime_local_option_present_key_is_some() {
        #[derive(serde::Deserialize)]
        struct Decoded {
            #[serde(default, deserialize_with = "deserialize_naive_datetime_local_option")]
            starts_at: Option<chrono::NaiveDateTime>,
        }
        let decoded: Decoded = serde_urlencoded::from_str("starts_at=2024-03-15T10:30").unwrap();
        assert_eq!(
            decoded.starts_at,
            Some(
                chrono::NaiveDate::from_ymd_opt(2024, 3, 15)
                    .unwrap()
                    .and_hms_opt(10, 30, 0)
                    .unwrap()
            )
        );
    }

    #[cfg(feature = "maud")]
    #[test]
    fn datetime_input_wrapper_div_has_stable_id() {
        #[derive(serde::Serialize)]
        struct F {
            starts_at: String,
        }
        let cs = Changeset::new(F {
            starts_at: "2024-03-15T10:30:00".into(),
        });
        let html = datetime_input(&cs, "starts_at", "Starts at").into_string();
        assert!(html.contains(r#"id="starts_at-field""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn select_input_renders_select_element_with_options() {
        #[derive(serde::Serialize)]
        struct F {
            status: String,
        }
        let cs = Changeset::new(F {
            status: "draft".into(),
        });
        let options = [("draft", "Draft"), ("published", "Published")];
        let html = select_input(&cs, "status", "Status", &options).into_string();
        assert!(html.contains("<select"), "{html}");
        assert!(html.contains(r#"name="status""#), "{html}");
        assert!(html.contains(r#"value="draft""#), "{html}");
        assert!(html.contains("Draft"), "{html}");
        assert!(html.contains(r#"value="published""#), "{html}");
        assert!(html.contains("Published"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn select_input_marks_current_value_selected() {
        #[derive(serde::Serialize)]
        struct F {
            status: String,
        }
        let cs = Changeset::new(F {
            status: "published".into(),
        });
        let options = [("draft", "Draft"), ("published", "Published")];
        let html = select_input(&cs, "status", "Status", &options).into_string();
        assert!(html.contains(r#"value="published" selected"#), "{html}");
        assert!(!html.contains(r#"value="draft" selected"#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn select_input_emits_aria_invalid_and_errors() {
        #[derive(serde::Serialize)]
        struct F {
            status: String,
        }
        let mut errors = HashMap::new();
        errors.insert("status".to_string(), vec!["required".to_string()]);
        let cs = Changeset::from_errors(
            F {
                status: String::new(),
            },
            errors,
        );
        let options = [("draft", "Draft"), ("published", "Published")];
        let html = select_input(&cs, "status", "Status", &options).into_string();
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains("required"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn select_input_wrapper_div_has_stable_id() {
        #[derive(serde::Serialize)]
        struct F {
            status: String,
        }
        let cs = Changeset::new(F {
            status: "draft".into(),
        });
        let options = [("draft", "Draft"), ("published", "Published")];
        let html = select_input(&cs, "status", "Status", &options).into_string();
        assert!(html.contains(r#"id="status-field""#), "{html}");
    }

    // ── form_for (issue #1135 phase 2) ──────────────────────────────

    #[cfg(feature = "maud")]
    #[derive(serde::Serialize)]
    struct FormForTestModel {
        title: String,
        views: i32,
        published: bool,
    }

    #[cfg(feature = "maud")]
    impl FormModel for FormForTestModel {
        fn form_fields() -> Vec<FormField> {
            vec![
                FormField::new("title", "Title", FieldControl::Text, true),
                FormField::new("views", "Views", FieldControl::Number { step: None }, false),
                FormField::new("published", "Published", FieldControl::Checkbox, false),
            ]
        }
    }

    #[cfg(feature = "maud")]
    fn blank_form_for_model() -> FormForTestModel {
        FormForTestModel {
            title: String::new(),
            views: 0,
            published: false,
        }
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_prefills_serde_renamed_field_via_value_name() {
        // The data type serializes `title` under "headline" — field_value
        // indexes serialized output, so without value_name routing the
        // pre-fill would come back blank even though the data is present.
        #[derive(serde::Serialize)]
        struct RenamedModel {
            #[serde(rename = "headline")]
            title: String,
        }
        impl FormModel for RenamedModel {
            fn form_fields() -> Vec<FormField> {
                vec![
                    FormField::new("title", "Title", FieldControl::Text, true)
                        .with_value_name("headline"),
                ]
            }
        }

        let mut errors = HashMap::new();
        errors.insert("title".to_string(), vec!["too short".to_string()]);
        let cs = Changeset::from_errors(
            RenamedModel {
                title: "Hello".into(),
            },
            errors,
        );
        let html = form_for(&cs, "/posts", "post").render().into_string();

        // The POST key / id stays the Rust identifier…
        assert!(html.contains(r#"name="title""#), "{html}");
        assert!(!html.contains(r#"name="headline""#), "{html}");
        // …the value is pre-filled through the serialized key…
        assert!(html.contains(r#"value="Hello""#), "{html}");
        // …and errors stay keyed by the identifier.
        assert!(html.contains("too short"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_renders_form_tag_csrf_and_submit() {
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts", "post")
            .csrf("tok123")
            .render()
            .into_string();
        assert!(html.contains("<form"), "{html}");
        assert!(html.contains(r#"name="_csrf""#), "{html}");
        assert!(html.contains(r#"value="tok123""#), "{html}");
        assert!(html.contains(r#"type="submit""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_method_override_emits_hidden_input() {
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts/1", "PUT").render().into_string();
        assert!(html.contains(r#"name="_method""#), "{html}");
        assert!(html.contains(r#"value="PUT""#), "{html}");
        assert!(html.contains(r#"method="post""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_renders_one_control_per_field() {
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts", "post").render().into_string();
        assert!(html.contains(r#"name="title""#), "{html}");
        assert!(html.contains(r#"name="views""#), "{html}");
        assert!(html.contains(r#"name="published""#), "{html}");
        assert!(html.contains(r#"type="checkbox""#), "{html}");
        assert!(html.contains(r#"type="number""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_prefills_values() {
        let cs = Changeset::new(FormForTestModel {
            title: "Hello".into(),
            ..blank_form_for_model()
        });
        let html = form_for(&cs, "/posts", "post").render().into_string();
        assert!(html.contains(r#"value="Hello""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_renders_inline_error_adjacent() {
        let mut errors = HashMap::new();
        errors.insert("title".to_string(), vec!["can't be blank".to_string()]);
        let cs = Changeset::from_errors(blank_form_for_model(), errors);
        let html = form_for(&cs, "/posts", "post").render().into_string();
        assert!(html.contains("can't be blank"), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_exclude_drops_field() {
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts", "post")
            .exclude("published")
            .render()
            .into_string();
        assert!(!html.contains(r#"name="published""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_override_field_changes_control() {
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts", "post")
            .override_field(
                "title",
                FieldControl::Select {
                    options: vec![("a".into(), "A".into())],
                },
            )
            .render()
            .into_string();
        assert!(html.contains("<select"), "{html}");
        assert!(html.contains(r#"name="title""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_override_label() {
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts", "post")
            .override_label("title", "Headline")
            .render()
            .into_string();
        assert!(html.contains("Headline"), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_append_inserts_before_submit() {
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts", "post")
            .append(
                maud::html! { input type="password" name="confirm" aria-label="Confirm password"; },
            )
            .render()
            .into_string();
        let append_idx = html
            .find(r#"name="confirm""#)
            .expect("append markup missing");
        let submit_idx = html
            .find(r#"type="submit""#)
            .expect("submit button missing");
        assert!(append_idx < submit_idx, "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_prepend_inserts_before_fields() {
        // A prepended hidden field (e.g. a one-time submit token, issue #1360)
        // must render at the FRONT of the form — after the CSRF input but before
        // every derived field — so a body-scanning middleware finds it even when
        // an earlier field carries a large value.
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts", "post")
            .csrf("tok")
            .prepend(maud::html! { input type="hidden" name="_submit_token" value="st"; })
            .render()
            .into_string();
        let csrf_idx = html.find(r#"name="_csrf""#).expect("csrf input missing");
        let prepend_idx = html
            .find(r#"name="_submit_token""#)
            .expect("prepend markup missing");
        let first_field_idx = html.find(r#"name="title""#).expect("derived field missing");
        assert!(
            csrf_idx < prepend_idx && prepend_idx < first_field_idx,
            "prepended token must sit after csrf and before the first derived field: {html}"
        );
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_required_date_field_renders_required_attribute() {
        let cs = Changeset::new(blank_form_for_model());
        // `title` is a required field; promoted to a Date control it must
        // keep the required signal (issue #1135 audit: `required` used to be
        // silently dropped for `FieldControl::Date`).
        let html = form_for(&cs, "/posts", "post")
            .override_field("title", FieldControl::Date)
            .render()
            .into_string();
        assert!(html.contains(r#"type="date""#), "{html}");
        assert!(html.contains(r#"aria-required="true""#), "{html}");
    }

    #[cfg(feature = "maud")]
    #[test]
    fn form_for_file_field_sets_multipart() {
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts", "post")
            .override_field("title", FieldControl::File)
            .render()
            .into_string();
        assert!(html.contains(r#"enctype="multipart/form-data""#), "{html}");
    }

    /// A multipart `PUT` form must carry the method-override hidden input,
    /// the CSRF hidden input, AND the `enctype` in the *same* rendered output
    /// — the multipart path flows through the same audited `form_tag_inner`
    /// as every other form, so none of the three can drift apart.
    #[cfg(feature = "maud")]
    #[test]
    fn form_for_multipart_put_emits_method_override_and_csrf_together() {
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts/1", "PUT")
            .csrf("tok456")
            .multipart()
            .render()
            .into_string();
        assert!(html.contains(r#"enctype="multipart/form-data""#), "{html}");
        assert!(html.contains(r#"method="post""#), "{html}");
        assert!(html.contains(r#"name="_method""#), "{html}");
        assert!(html.contains(r#"value="PUT""#), "{html}");
        assert!(html.contains(r#"name="_csrf""#), "{html}");
        assert!(html.contains(r#"value="tok456""#), "{html}");

        // The non-multipart sibling keeps the same combined contract.
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts/1", "PUT")
            .csrf("tok456")
            .render()
            .into_string();
        assert!(!html.contains("enctype"), "{html}");
        assert!(html.contains(r#"name="_method""#), "{html}");
        assert!(html.contains(r#"name="_csrf""#), "{html}");
    }

    /// `FieldControl::File` renders the same inline-error/ARIA/wrapper
    /// skeleton as the changeset-aware helpers: `{field}-field` wrapper id,
    /// `aria-invalid`/`aria-describedby`, a `role="alert"` error block, and
    /// the required signal.
    #[cfg(feature = "maud")]
    #[test]
    fn form_for_file_field_renders_errors_aria_and_required() {
        let mut errors = HashMap::new();
        errors.insert("title".to_string(), vec!["must be a PDF".to_string()]);
        let cs = Changeset::from_errors(blank_form_for_model(), errors);
        // `title` is required in the test model.
        let html = form_for(&cs, "/posts", "post")
            .override_field("title", FieldControl::File)
            .render()
            .into_string();
        assert!(html.contains(r#"type="file""#), "{html}");
        assert!(html.contains(r#"id="title-field""#), "{html}");
        assert!(html.contains(r#"aria-invalid="true""#), "{html}");
        assert!(html.contains(r#"aria-describedby="title-error""#), "{html}");
        assert!(html.contains(r#"role="alert""#), "{html}");
        assert!(html.contains("must be a PDF"), "{html}");
        assert!(html.contains(r#"aria-required="true""#), "{html}");
        assert!(html.contains("required"), "{html}");

        // Error-free, non-required file field: no required signal, no alert.
        // (`title` — the only required field — is excluded so any
        // `aria-required` in the output could only come from the file arm.)
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts", "post")
            .exclude("title")
            .override_field("published", FieldControl::File)
            .render()
            .into_string();
        assert!(html.contains(r#"id="published-field""#), "{html}");
        assert!(html.contains(r#"aria-invalid="false""#), "{html}");
        assert!(!html.contains(r#"aria-required="true""#), "{html}");
    }

    /// Slice 3b (issue #1933): `render_form_control` routes the Textarea,
    /// Checkbox, Select, and File arms through the typed `a11y` primitives
    /// while preserving the `{field}-field` wrapper + `role="alert"` error
    /// skeleton. This pins the two intentional accessibility improvements the
    /// primitives introduce over the hand-written `*_input` helpers: (1) an
    /// error-free control omits the old empty `aria-describedby=""` (an IDREF
    /// referencing nothing), and (2) a visible-label checkbox emits the
    /// `<input>` before its `<label for=…>` (the conventional checkbox layout;
    /// the `for`/`id` association is unchanged).
    #[cfg(feature = "maud")]
    #[test]
    fn form_for_routes_controls_through_a11y_primitives() {
        // Error-free controls drop the empty `aria-describedby=""` no-op.
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts", "post")
            .exclude("views")
            .exclude("published")
            .override_field("title", FieldControl::Textarea)
            .render()
            .into_string();
        assert!(html.contains("<textarea"), "{html}");
        assert!(html.contains(r#"aria-invalid="false""#), "{html}");
        assert!(
            !html.contains(r#"aria-describedby="""#),
            "error-free textarea must not emit an empty aria-describedby: {html}"
        );

        // Checkbox: the visible label's `for`/`id` association is preserved and
        // the `<input>` precedes the `<label>`.
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts", "post")
            .exclude("views")
            .exclude("title")
            .render()
            .into_string();
        assert!(html.contains(r#"type="checkbox""#), "{html}");
        assert!(html.contains(r#"<label for="published""#), "{html}");
        let input_idx = html
            .find(r#"type="checkbox""#)
            .expect("checkbox input missing");
        let label_idx = html
            .find(r#"<label for="published""#)
            .expect("checkbox label missing");
        assert!(
            input_idx < label_idx,
            "checkbox input must precede its label (conventional layout): {html}"
        );
        assert!(
            !html.contains(r#"aria-describedby="""#),
            "error-free checkbox must not emit an empty aria-describedby: {html}"
        );
    }

    /// Duplicate `.override_field`/`.override_label` calls on the same field
    /// resolve last-wins (conventional builder semantics).
    #[cfg(feature = "maud")]
    #[test]
    fn form_for_duplicate_overrides_last_wins() {
        let cs = Changeset::new(blank_form_for_model());
        let html = form_for(&cs, "/posts", "post")
            .override_field("title", FieldControl::Date)
            .override_field("title", FieldControl::Textarea)
            .override_label("title", "First")
            .override_label("title", "Second")
            .render()
            .into_string();
        assert!(html.contains("<textarea"), "{html}");
        assert!(!html.contains(r#"type="date""#), "{html}");
        assert!(html.contains("Second"), "{html}");
        assert!(!html.contains("First"), "{html}");
    }

    // ── ChangesetForm extractor (axum integration) ─────────────────

    mod extractor_tests {
        use super::*;
        use axum::{Router, body::Body, routing::post};
        use tower::ServiceExt;

        #[derive(serde::Deserialize, validator::Validate)]
        struct TestForm {
            #[validate(length(min = 3))]
            name: String,
        }

        #[tokio::test]
        async fn valid_form_body_produces_valid_changeset() {
            async fn handler(form: ChangesetForm<TestForm>) -> String {
                format!("valid={}", form.is_valid())
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(urlencoded_req("/test", "name=Alice"))
                .await
                .unwrap();
            assert_body(resp, "valid=true").await;
        }

        #[tokio::test]
        async fn invalid_form_body_produces_invalid_changeset() {
            async fn handler(form: ChangesetForm<TestForm>) -> String {
                format!("valid={}", form.is_valid())
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(urlencoded_req("/test", "name=ab"))
                .await
                .unwrap();
            assert_body(resp, "valid=false").await;
        }

        #[tokio::test]
        async fn invalid_form_exposes_field_errors() {
            async fn handler(form: ChangesetForm<TestForm>) -> String {
                form.errors_for("name").join("|")
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(urlencoded_req("/test", "name=ab"))
                .await
                .unwrap();
            let body = body_text(resp).await;
            assert!(!body.is_empty(), "expected errors, got empty string");
        }

        #[tokio::test]
        async fn missing_required_field_returns_non_200() {
            async fn handler(form: ChangesetForm<TestForm>) -> String {
                format!("valid={}", form.is_valid())
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(urlencoded_req("/test", "other=value"))
                .await
                .unwrap();
            assert_ne!(resp.status(), axum::http::StatusCode::OK);
        }

        #[derive(serde::Deserialize, validator::Validate)]
        struct OptionalNumericForm {
            #[validate(length(min = 3))]
            name: String,
            age: Option<i32>,
        }

        #[tokio::test]
        async fn blank_optional_numeric_field_decodes_as_none_not_400() {
            // A number input the user left empty submits `age=` — an empty
            // string is not a valid `i32`, so `serde_urlencoded` rejects it
            // outright unless the extractor retries with the blank pair
            // dropped (falling back to `None`) instead of surfacing a
            // spurious decode failure that bypasses the Changeset entirely.
            async fn handler(form: ChangesetForm<OptionalNumericForm>) -> String {
                format!("valid={} age={:?}", form.is_valid(), form.data().age)
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(urlencoded_req("/test", "name=Alice&age="))
                .await
                .unwrap();
            assert_eq!(resp.status(), axum::http::StatusCode::OK);
            assert_body(resp, "valid=true age=None").await;
        }

        #[tokio::test]
        async fn filled_optional_numeric_field_still_decodes() {
            async fn handler(form: ChangesetForm<OptionalNumericForm>) -> String {
                format!("valid={} age={:?}", form.is_valid(), form.data().age)
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(urlencoded_req("/test", "name=Alice&age=30"))
                .await
                .unwrap();
            assert_eq!(resp.status(), axum::http::StatusCode::OK);
            assert_body(resp, "valid=true age=Some(30)").await;
        }

        #[tokio::test]
        async fn garbage_numeric_field_still_fails_decode() {
            // A genuinely undecodable value (not blank) must still 400/422 —
            // the blank-retry accommodation must not paper over real garbage.
            async fn handler(_form: ChangesetForm<OptionalNumericForm>) -> String {
                "unreachable".to_string()
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(urlencoded_req("/test", "name=Alice&age=not-a-number"))
                .await
                .unwrap();
            assert_ne!(resp.status(), axum::http::StatusCode::OK);
        }

        #[tokio::test]
        async fn blank_required_string_survives_alongside_blank_optional_numeric() {
            // A submission with *both* a blank optional numeric field and a
            // blank required/validated `String` field (`name=&age=`) must not
            // have the blank-optional-field retry drop the string pair too —
            // that would turn a real validation error (name too short) into a
            // spurious decode failure. `name` must reach the Changeset as an
            // empty string so `is_valid()` reports the actual length-rule
            // violation, not a 400/422 that hides it.
            async fn handler(form: ChangesetForm<OptionalNumericForm>) -> String {
                format!(
                    "valid={} name={:?} age={:?}",
                    form.is_valid(),
                    form.data().name,
                    form.data().age
                )
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(urlencoded_req("/test", "name=&age="))
                .await
                .unwrap();
            assert_eq!(resp.status(), axum::http::StatusCode::OK);
            assert_body(resp, "valid=false name=\"\" age=None").await;
        }

        #[derive(serde::Deserialize, validator::Validate)]
        struct CheckboxForm {
            #[serde(default)]
            published: bool,
        }

        #[tokio::test]
        async fn blank_defaulted_checkbox_field_decodes_to_its_default() {
            // Documented, intended behavior (see
            // `decode_urlencoded_dropping_blank_optional_fields`'s "Scope"
            // doc section): a `#[serde(default)] bool` field explicitly
            // submitted blank (as opposed to omitted, which is what a real
            // unchecked `<input type="checkbox">` actually sends) resolves
            // to the same default a client could already get by omitting
            // the key entirely — no new capability, just consistent with
            // the field's own declared tolerance for a missing key.
            async fn handler(form: ChangesetForm<CheckboxForm>) -> String {
                format!("published={}", form.data().published)
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(urlencoded_req("/test", "published="))
                .await
                .unwrap();
            assert_eq!(resp.status(), axum::http::StatusCode::OK);
            assert_body(resp, "published=false").await;
        }

        #[derive(serde::Deserialize, validator::Validate)]
        struct RequiredBoolForm {
            #[allow(
                dead_code,
                reason = "decode is expected to fail before this is ever read"
            )]
            accepted_terms: bool,
        }

        #[tokio::test]
        async fn blank_required_field_without_default_still_fails_to_decode() {
            // The boundary the "Scope" doc section on
            // `decode_urlencoded_dropping_blank_optional_fields` promises:
            // a field with *no* tolerance for a missing key at all (no
            // `Option`, no `#[serde(default)]`) must still hard-fail on a
            // blank submission — dropping its key surfaces a "missing
            // field" error on the next attempt instead of resolving, so
            // the function gives up and returns that error rather than
            // silently accepting a bogus value.
            async fn handler(_form: ChangesetForm<RequiredBoolForm>) -> String {
                "unreachable".to_string()
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(urlencoded_req("/test", "accepted_terms="))
                .await
                .unwrap();
            assert_ne!(resp.status(), axum::http::StatusCode::OK);
        }

        #[tokio::test]
        async fn oversized_body_is_rejected_not_fully_buffered() {
            // The blank-optional-field retry must not come at the cost of
            // bypassing axum's `DefaultBodyLimit` (2MB by default) — a body
            // larger than the configured limit must still be rejected rather
            // than fully buffered into memory.
            async fn handler(_form: ChangesetForm<TestForm>) -> String {
                "unreachable".to_string()
            }
            let oversized = format!("name={}", "a".repeat(3 * 1024 * 1024));
            let req = axum::http::Request::builder()
                .method("POST")
                .uri("/test")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body(Body::from(oversized))
                .unwrap();
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(req)
                .await
                .unwrap();
            assert_eq!(resp.status(), axum::http::StatusCode::PAYLOAD_TOO_LARGE);
        }

        #[tokio::test]
        async fn wrong_content_type_is_rejected_not_decoded_anyway() {
            // `Bytes` alone has no opinion on Content-Type, so a `text/plain`
            // (or missing-Content-Type) POST whose body happens to look like
            // `name=Alice` must still be rejected outright — matching axum's
            // own `Form`/`RawForm` extractors — rather than silently decoded.
            async fn handler(_form: ChangesetForm<TestForm>) -> String {
                "unreachable".to_string()
            }
            let req = axum::http::Request::builder()
                .method("POST")
                .uri("/test")
                .header("Content-Type", "text/plain")
                .body(Body::from("name=Alice"))
                .unwrap();
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(req)
                .await
                .unwrap();
            assert_eq!(
                resp.status(),
                axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE
            );
        }

        #[tokio::test]
        async fn missing_content_type_is_rejected_not_decoded_anyway() {
            async fn handler(_form: ChangesetForm<TestForm>) -> String {
                "unreachable".to_string()
            }
            let req = axum::http::Request::builder()
                .method("POST")
                .uri("/test")
                .body(Body::from("name=Alice"))
                .unwrap();
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(req)
                .await
                .unwrap();
            assert_eq!(
                resp.status(),
                axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE
            );
        }

        #[tokio::test]
        async fn csrf_token_is_none_without_csrf_middleware() {
            async fn handler(form: ChangesetForm<TestForm>) -> String {
                form.csrf_token().unwrap_or("none").to_string()
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(urlencoded_req("/test", "name=Alice"))
                .await
                .unwrap();
            assert_body(resp, "none").await;
        }

        #[tokio::test]
        async fn csrf_token_captured_from_request_extensions() {
            // Build a request with CsrfToken pre-inserted in extensions,
            // simulating what CsrfLayer does, then call from_request directly.
            use crate::security::CsrfToken;

            let mut req = axum::http::Request::builder()
                .method("POST")
                .uri("/test")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body(Body::from("name=Alice"))
                .unwrap();
            req.extensions_mut()
                .insert(CsrfToken::new("secret-tok".to_string()));

            let form = ChangesetForm::<TestForm>::from_request(req, &())
                .await
                .expect("extraction should succeed");

            assert_eq!(form.csrf_token(), Some("secret-tok"));
        }

        #[cfg(feature = "multipart")]
        #[tokio::test]
        async fn multipart_form_decodes_text_fields() {
            async fn handler(form: ChangesetForm<TestForm>) -> String {
                format!("valid={} name={}", form.is_valid(), form.data().name)
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(multipart_req("/test", "name", "Alice"))
                .await
                .unwrap();
            assert_body(resp, "valid=true name=Alice").await;
        }

        #[cfg(feature = "multipart")]
        #[tokio::test]
        async fn multipart_blank_optional_numeric_field_decodes_as_none_not_400() {
            async fn handler(form: ChangesetForm<OptionalNumericForm>) -> String {
                format!("valid={} age={:?}", form.is_valid(), form.data().age)
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(multipart_req_multi(
                    "/test",
                    &[("name", "Alice"), ("age", "")],
                ))
                .await
                .unwrap();
            assert_eq!(resp.status(), axum::http::StatusCode::OK);
            assert_body(resp, "valid=true age=None").await;
        }

        #[cfg(feature = "multipart")]
        #[tokio::test]
        async fn multipart_form_validates_fields() {
            async fn handler(form: ChangesetForm<TestForm>) -> String {
                format!("valid={}", form.is_valid())
            }
            let resp = Router::new()
                .route("/test", post(handler))
                .oneshot(multipart_req("/test", "name", "ab"))
                .await
                .unwrap();
            assert_body(resp, "valid=false").await;
        }

        // ── AC3: Inline field validation (htmx partial response) ──

        #[derive(serde::Deserialize, validator::Validate, serde::Serialize)]
        struct InlineTestForm {
            #[validate(length(min = 3, message = "Name must be at least 3 characters"))]
            name: String,
        }

        #[cfg(feature = "maud")]
        #[tokio::test]
        async fn inline_valid_field_returns_field_partial_without_errors() {
            async fn handler(form: ChangesetForm<InlineTestForm>) -> maud::Markup {
                text_input_htmx(&form.changeset, "name", "Name", "/validate/name")
            }
            let resp = Router::new()
                .route("/validate/name", post(handler))
                .oneshot(urlencoded_req("/validate/name", "name=Alice"))
                .await
                .unwrap();
            assert_eq!(resp.status(), axum::http::StatusCode::OK);
            let body = body_text(resp).await;
            assert!(body.contains(r#"aria-invalid="false""#), "{body}");
            assert!(!body.contains(r#"role="alert""#), "{body}");
            assert!(body.contains(r#"value="Alice""#), "{body}");
        }

        #[cfg(feature = "maud")]
        #[tokio::test]
        async fn inline_invalid_field_returns_field_partial_with_errors() {
            async fn handler(form: ChangesetForm<InlineTestForm>) -> maud::Markup {
                text_input_htmx(&form.changeset, "name", "Name", "/validate/name")
            }
            let resp = Router::new()
                .route("/validate/name", post(handler))
                .oneshot(urlencoded_req("/validate/name", "name=ab"))
                .await
                .unwrap();
            assert_eq!(resp.status(), axum::http::StatusCode::OK);
            let body = body_text(resp).await;
            assert!(body.contains(r#"aria-invalid="true""#), "{body}");
            assert!(body.contains(r#"role="alert""#), "{body}");
            assert!(
                body.contains("Name must be at least 3 characters"),
                "{body}"
            );
            // Value preserved after failed validation
            assert!(body.contains(r#"value="ab""#), "{body}");
        }

        #[cfg(feature = "maud")]
        #[tokio::test]
        async fn inline_invalid_field_partial_is_htmx_swappable() {
            async fn handler(form: ChangesetForm<InlineTestForm>) -> maud::Markup {
                text_input_htmx(&form.changeset, "name", "Name", "/validate/name")
            }
            let resp = Router::new()
                .route("/validate/name", post(handler))
                .oneshot(urlencoded_req("/validate/name", "name=ab"))
                .await
                .unwrap();
            let body = body_text(resp).await;
            // Wrapper must have stable id for hx-swap="outerHTML" targeting
            assert!(body.contains(r#"id="name-field""#), "{body}");
        }

        #[cfg(feature = "maud")]
        #[tokio::test]
        async fn full_form_submit_invalid_returns_422() {
            async fn handler(form: ChangesetForm<InlineTestForm>) -> impl IntoResponse {
                match form.into_valid() {
                    Ok(_) => axum::http::StatusCode::OK.into_response(),
                    Err(form) => (
                        axum::http::StatusCode::UNPROCESSABLE_ENTITY,
                        text_input_htmx(&form.changeset, "name", "Name", "/validate/name"),
                    )
                        .into_response(),
                }
            }
            let resp = Router::new()
                .route("/submit", post(handler))
                .oneshot(urlencoded_req("/submit", "name=ab"))
                .await
                .unwrap();
            assert_eq!(
                resp.status(),
                axum::http::StatusCode::UNPROCESSABLE_ENTITY,
                "full-form invalid submit must return 422"
            );
            let body = body_text(resp).await;
            assert!(
                body.contains("Name must be at least 3 characters"),
                "{body}"
            );
        }

        #[cfg(feature = "maud")]
        #[tokio::test]
        async fn full_form_submit_valid_returns_200() {
            async fn handler(form: ChangesetForm<InlineTestForm>) -> impl IntoResponse {
                match form.into_valid() {
                    Ok(_) => axum::http::StatusCode::OK.into_response(),
                    Err(form) => (
                        axum::http::StatusCode::UNPROCESSABLE_ENTITY,
                        text_input_htmx(&form.changeset, "name", "Name", "/validate/name"),
                    )
                        .into_response(),
                }
            }
            let resp = Router::new()
                .route("/submit", post(handler))
                .oneshot(urlencoded_req("/submit", "name=Alice"))
                .await
                .unwrap();
            assert_eq!(resp.status(), axum::http::StatusCode::OK);
        }

        // ── Helpers ────────────────────────────────────────────────

        fn urlencoded_req(uri: &str, body: &'static str) -> axum::http::Request<Body> {
            axum::http::Request::builder()
                .method("POST")
                .uri(uri)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body(Body::from(body))
                .unwrap()
        }

        #[cfg(feature = "multipart")]
        fn multipart_req(uri: &str, field: &str, value: &str) -> axum::http::Request<Body> {
            multipart_req_multi(uri, &[(field, value)])
        }

        #[cfg(feature = "multipart")]
        fn multipart_req_multi(uri: &str, fields: &[(&str, &str)]) -> axum::http::Request<Body> {
            use std::fmt::Write as _;

            let boundary = "----FormBoundary7MA4YWxkTrZu0gW";
            let mut body = String::new();
            for (field, value) in fields {
                let _ = write!(
                    body,
                    "--{boundary}\r\n\
                     Content-Disposition: form-data; name=\"{field}\"\r\n\r\n\
                     {value}\r\n"
                );
            }
            let _ = write!(body, "--{boundary}--\r\n");
            axum::http::Request::builder()
                .method("POST")
                .uri(uri)
                .header(
                    "Content-Type",
                    format!("multipart/form-data; boundary={boundary}"),
                )
                .body(Body::from(body))
                .unwrap()
        }

        async fn body_text(resp: axum::response::Response) -> String {
            let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap();
            String::from_utf8(bytes.to_vec()).unwrap()
        }

        async fn assert_body(resp: axum::response::Response, expected: &str) {
            assert_eq!(body_text(resp).await, expected);
        }
    }
}