ferro-json-ui 0.3.7

JSON-based server-driven UI schema types for Ferro
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
//! Form-control renderers.
//!
//! Each function emits a single typed form control or the surrounding
//! `<form>` element with signature `(el, spec, data, depth) -> String`.
//! Decode failures surface as HTML diagnostic comments via the shared
//! `decode_diagnostic` helper.
//!
//! Behaviors worth flagging for spec authors:
//! - **Switch auto-form wrap** — when `SwitchProps.action` is `Some`, the
//!   switch is wrapped inside a `<form>` that submits on change via
//!   `onchange="this.closest('form').submit()"`.
//! - **Input / Select / Checkbox / Switch `data_path` pre-fill** — resolves
//!   the path against the render-time `data` via
//!   [`crate::data::resolve_path`] / [`crate::data::resolve_path_string`] to
//!   populate `value=""` or `checked` attributes. `default_value` wins over
//!   `data_path` for `Input` and `Select`.
//! - **Form method spoofing** — `PUT` / `PATCH` / `DELETE` rewrite to
//!   `POST` + a hidden `_method` input.

use serde_json::Value;

use crate::action::HttpMethod;
use crate::component::{
    CheckboxListProps, CheckboxProps, FormMaxWidth, FormProps, InputProps, InputType, SelectOption,
    SelectProps, SwitchProps,
};
use crate::data::{resolve_path, resolve_path_string};
use crate::spec::{Element, Spec};

use super::classes::{DISABLED_BASE, FOCUS_RING, MOTION_FAST};
use super::{html_escape, render_element};

/// Renders a `<form>` element. Child IDs in `el.children` become the form
/// body; `FormProps.action` controls submission target and method (with
/// HTTP-method spoofing for PUT/PATCH/DELETE → POST + hidden `_method`
/// input). When `action.url` is `None`, the form falls back to `action="#"`
/// and emits a diagnostic HTML comment.
pub(crate) fn render_form(el: &Element, spec: &Spec, data: &Value, depth: usize) -> String {
    let props: FormProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode Form props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    // Effective method — `props.method` overrides `props.action.method`.
    let effective_method = props
        .method
        .as_ref()
        .unwrap_or(&props.action.method)
        .clone();

    let (form_method, needs_spoofing) = match effective_method {
        HttpMethod::Get => ("get", false),
        HttpMethod::Post => ("post", false),
        HttpMethod::Put | HttpMethod::Patch | HttpMethod::Delete => ("post", true),
    };

    // Resolve action URL. Priority:
    //   1. `props.action.url` — populated by `resolve_actions` for the
    //      enclosing element. Not populated for FormProps.action because
    //      `resolve_actions` only walks `el.action`, not `el.props.action`.
    //   2. `props.action.handler` literal path — when the handler is a
    //      `/path` string, use it directly. Covers the FormProps case where
    //      authoring code passes either a literal URL or a `{$data}` binding
    //      that `resolve_expressions` materialised into a literal URL.
    //   3. Fall through to "#" with a diagnostic comment.
    let handler_str = props.action.handler.as_str();
    let (action_url, diagnostic) = if let Some(u) = props.action.url.as_deref() {
        (u.to_string(), String::new())
    } else if handler_str.starts_with('/') {
        (handler_str.to_string(), String::new())
    } else {
        (
            "#".to_string(),
            format!(
                "<!-- ferro-json-ui: action '{}' has no resolved url -->",
                html_escape(handler_str)
            ),
        )
    };

    let id_attr = match props.id.as_deref() {
        Some(i) => format!(" id=\"{}\"", html_escape(i)),
        None => String::new(),
    };
    let enctype_attr = match props.enctype.as_deref() {
        Some(e) => format!(" enctype=\"{}\"", html_escape(e)),
        None => String::new(),
    };
    // Fill mode (Register layout, 256 D-15): the Form joins the fill-viewport
    // height chain so the inner panes Grid's `h-full` resolves against a real
    // height and each pane scrolls independently. Full literals for the
    // Tailwind @source scanner (render::classes discipline).
    let form_classes = if props.fill == Some(true) {
        "flex flex-col h-full min-h-0 [&>*]:flex-1 [&>*]:min-h-0"
    } else {
        "flex flex-wrap gap-4 [&>*]:w-full [&>button]:w-auto [&>a]:w-auto"
    };
    let mut html = match &props.guard {
        Some(g) => format!(
            "<form{id_attr} action=\"{}\" method=\"{}\"{enctype_attr} data-form-guard=\"{}\" class=\"{form_classes}\">",
            html_escape(&action_url),
            form_method,
            html_escape(g)
        ),
        None => format!(
            "<form{id_attr} action=\"{}\" method=\"{}\"{enctype_attr} class=\"{form_classes}\">",
            html_escape(&action_url),
            form_method
        ),
    };

    if needs_spoofing {
        let method_value = match effective_method {
            HttpMethod::Put => "PUT",
            HttpMethod::Patch => "PATCH",
            HttpMethod::Delete => "DELETE",
            _ => unreachable!(),
        };
        html.push_str(&format!(
            "<input type=\"hidden\" name=\"_method\" value=\"{method_value}\">"
        ));
    }

    // Form fields come from `el.children`. Each child ID is looked up and
    // rendered via the walker, which applies visibility and depth guards.
    for child_id in &el.children {
        html.push_str(&render_element(child_id, spec, data, depth + 1));
    }

    html.push_str("</form>");

    // Max-width wrapper when specified. Anchors LEFT (no mx-auto) so a
    // constrained form aligns with the page header edge; centering belongs to
    // the layout (AuthLayout centers its whole content area itself).
    let html = match props.max_width.as_ref().unwrap_or(&FormMaxWidth::Default) {
        FormMaxWidth::Default => html,
        FormMaxWidth::Narrow => format!("<div class=\"max-w-2xl\">{html}</div>"),
        FormMaxWidth::Wide => format!("<div class=\"max-w-4xl\">{html}</div>"),
    };

    format!("{diagnostic}{html}")
}

/// Renders an `<input>` (or `<textarea>` for `InputType::Textarea`).
///
/// Value-resolution precedence: explicit `default_value` wins over a
/// `data_path`-resolved string. Hidden inputs skip the label and wrapper
/// `<div>`; all other input types render inside a `space-y-1` wrapper with
/// a `<label>` above and optional description / error `<p>` below.
pub(crate) fn render_input(el: &Element, _spec: &Spec, data: &Value, _depth: usize) -> String {
    let props: InputProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode Input props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    // Effective value: default_value wins, else data_path, else none.
    let resolved_value = if let Some(ref dv) = props.default_value {
        Some(dv.clone())
    } else if let Some(ref dp) = props.data_path {
        resolve_path_string(data, dp)
    } else {
        None
    };

    // Hidden inputs emit no label or wrapper div.
    if matches!(props.input_type, InputType::Hidden) {
        let val = resolved_value.as_deref().unwrap_or("");
        return format!(
            "<input type=\"hidden\" id=\"{}\" name=\"{}\" value=\"{}\">",
            html_escape(&props.field),
            html_escape(&props.field),
            html_escape(val)
        );
    }

    let has_error = props.error.is_some();
    // The error ring is semantic (destructive) and intentionally NOT the
    // `--color-ring` token; only the non-error branch uses the shared ring.
    let focus_ring_class = if has_error {
        "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive focus-visible:ring-offset-2"
    } else {
        FOCUS_RING
    };

    let mut html = String::from("<div class=\"space-y-1\">");
    html.push_str(&format!(
        "<label class=\"block text-sm font-medium text-text\" for=\"{}\">{}</label>",
        html_escape(&props.field),
        html_escape(&props.label)
    ));

    match props.input_type {
        InputType::Hidden => unreachable!("handled by early return above"),
        InputType::Textarea => {
            // fjui-textarea: skin owns border/bg/padding/min-height/font-family/line-height.
            // DISABLED_BASE + FOCUS_RING are D-02 allowlist behavior utilities (kept inline).
            let val = resolved_value.as_deref().unwrap_or("");
            let error_class = if has_error {
                " fjui-textarea--error"
            } else {
                ""
            };
            html.push_str(&format!(
                "<textarea id=\"{}\" name=\"{}\" class=\"fjui-textarea{error_class} w-full {MOTION_FAST} {DISABLED_BASE} {}\"",
                html_escape(&props.field),
                html_escape(&props.field),
                focus_ring_class
            ));
            if let Some(ref placeholder) = props.placeholder {
                html.push_str(&format!(" placeholder=\"{}\"", html_escape(placeholder)));
            }
            if props.required == Some(true) {
                html.push_str(" required");
            }
            if props.disabled == Some(true) {
                html.push_str(" disabled");
            }
            if has_error {
                html.push_str(&format!(
                    " aria-invalid=\"true\" aria-describedby=\"err-{}\"",
                    html_escape(&props.field)
                ));
            }
            html.push_str(&format!(">{}</textarea>", html_escape(val)));
        }
        InputType::File => {
            let file_ring_class = if has_error {
                " ring-1 ring-destructive"
            } else {
                ""
            };
            html.push_str(&format!(
                "<input type=\"file\" id=\"{}\" name=\"{}\" class=\"block w-full text-sm text-text file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-medium file:bg-surface file:text-text hover:file:bg-surface/80{}\"",
                html_escape(&props.field),
                html_escape(&props.field),
                file_ring_class,
            ));
            if let Some(ref accept) = props.accept {
                html.push_str(&format!(" accept=\"{}\"", html_escape(accept)));
            }
            if props.required == Some(true) {
                html.push_str(" required");
            }
            if props.disabled == Some(true) {
                html.push_str(" disabled");
            }
            if has_error {
                html.push_str(&format!(
                    " aria-invalid=\"true\" aria-describedby=\"err-{}\"",
                    html_escape(&props.field)
                ));
            }
            html.push('>');
        }
        _ => {
            let input_type = match props.input_type {
                InputType::Text => "text",
                InputType::Email => "email",
                InputType::Password => "password",
                InputType::Number => "number",
                InputType::Date => "date",
                InputType::Time => "time",
                InputType::Url => "url",
                InputType::Tel => "tel",
                InputType::Search => "search",
                InputType::Textarea | InputType::Hidden | InputType::File => unreachable!(),
            };

            // Date-picker progressive enhancement (ENTRY-02).
            //
            // When `date_picker = true` on a date or time input, wrap the native
            // input in the `[data-date-picker]` contract markup so the client-side
            // calendar runtime (date_picker.rs) can bind to it:
            //
            //   [data-date-picker]             — wrapper
            //   [data-date-picker-native]       — <input> form value carrier (sr-only)
            //   [data-date-picker-trigger]      — <button> that opens the dialog
            //   [data-date-picker-dialog]       — <dialog> element (built by JS)
            //
            // The native input is the sole form value carrier; `class="sr-only"` keeps
            // it accessible but visually hidden so the JS trigger replaces it visually.
            // If `showModal` is unsupported the runtime exits early, leaving the native
            // input functional (no-JS fallback, D-08).
            let use_date_picker = props.date_picker == Some(true)
                && matches!(props.input_type, InputType::Date | InputType::Time);

            if use_date_picker {
                // Wrapper — runtime binds to this attribute.
                html.push_str("<div data-date-picker class=\"fjui-datepicker\">");

                // Native input: sr-only form value carrier.
                let error_attr = if has_error {
                    format!(
                        " aria-invalid=\"true\" aria-describedby=\"err-{}\"",
                        html_escape(&props.field)
                    )
                } else {
                    String::new()
                };
                html.push_str(&format!(
                    "<input type=\"{}\" id=\"{}\" name=\"{}\" class=\"sr-only\" data-date-picker-native",
                    input_type,
                    html_escape(&props.field),
                    html_escape(&props.field),
                ));
                if let Some(ref val) = resolved_value {
                    html.push_str(&format!(" value=\"{}\"", html_escape(val)));
                }
                if props.required == Some(true) {
                    html.push_str(" required");
                }
                if props.disabled == Some(true) {
                    html.push_str(" disabled");
                }
                html.push_str(&error_attr);
                html.push('>');

                // Trigger button — visible, opens the dialog.
                let trigger_label = if input_type == "time" {
                    "Seleziona orario"
                } else {
                    "Seleziona data"
                };
                html.push_str(&format!(
                    "<button type=\"button\" class=\"fjui-datepicker__trigger\" \
                     aria-label=\"{}\" data-date-picker-trigger>{}</button>",
                    html_escape(trigger_label),
                    html_escape(trigger_label),
                ));

                // Dialog shell — JS builds the calendar grid inside on first open.
                html.push_str(
                    "<dialog data-date-picker-dialog class=\"fjui-datepicker__dialog\"></dialog>",
                );

                html.push_str("</div>");
            } else {
                // Standard input (no date picker).
                // fjui-input: skin owns border/bg/padding/border-radius/font-size (incl 16px iOS floor).
                // fjui-input--error: skin owns destructive border color when in error state.
                // DISABLED_BASE + FOCUS_RING are D-02 allowlist behavior utilities (kept inline).
                let error_class = if has_error { " fjui-input--error" } else { "" };
                html.push_str(&format!(
                    "<input type=\"{}\" id=\"{}\" name=\"{}\" class=\"fjui-input{error_class} w-full {MOTION_FAST} {DISABLED_BASE} {}\"",
                    input_type,
                    html_escape(&props.field),
                    html_escape(&props.field),
                    focus_ring_class
                ));
                if let Some(ref placeholder) = props.placeholder {
                    html.push_str(&format!(" placeholder=\"{}\"", html_escape(placeholder)));
                }
                if let Some(ref val) = resolved_value {
                    html.push_str(&format!(" value=\"{}\"", html_escape(val)));
                }
                if let Some(ref step) = props.step {
                    html.push_str(&format!(" step=\"{}\"", html_escape(step)));
                }
                if let Some(ref list_id) = props.list {
                    html.push_str(&format!(" list=\"{}\"", html_escape(list_id)));
                }
                if props.required == Some(true) {
                    html.push_str(" required");
                }
                if props.disabled == Some(true) {
                    html.push_str(" disabled");
                }
                if has_error {
                    html.push_str(&format!(
                        " aria-invalid=\"true\" aria-describedby=\"err-{}\"",
                        html_escape(&props.field)
                    ));
                }
                html.push('>');

                // Optional `<datalist>` companion: looks up `list_id` as a flat
                // key on the root data object and emits one `<option>` per
                // string entry.
                if let Some(ref list_id) = props.list {
                    if let Some(arr) = data.get(list_id).and_then(|v| v.as_array()) {
                        html.push_str(&format!("<datalist id=\"{}\">", html_escape(list_id)));
                        for opt in arr {
                            if let Some(s) = opt.as_str() {
                                html.push_str(&format!("<option value=\"{}\">", html_escape(s)));
                            }
                        }
                        html.push_str("</datalist>");
                    }
                }
            }
        }
    }

    if let Some(ref desc) = props.description {
        html.push_str(&format!(
            "<p class=\"text-sm text-text-muted\">{}</p>",
            html_escape(desc)
        ));
    }

    if let Some(ref error) = props.error {
        html.push_str(&format!(
            "<p id=\"err-{}\" class=\"fjui-form-message--error\">{}</p>",
            html_escape(&props.field),
            html_escape(error)
        ));
    }
    html.push_str("</div>");
    html
}

/// Renders a `<select>` element. Same `default_value` > `data_path`
/// precedence as [`render_input`]. The resolved value marks the matching
/// `<option>` with the `selected` attribute. Optional `placeholder` is
/// emitted as a first `<option value="">` entry.
pub(crate) fn render_select(el: &Element, _spec: &Spec, data: &Value, _depth: usize) -> String {
    let props: SelectProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode Select props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    let selected_value = if let Some(ref dv) = props.default_value {
        Some(dv.clone())
    } else if let Some(ref dp) = props.data_path {
        resolve_path_string(data, dp)
    } else {
        None
    };

    let has_error = props.error.is_some();
    // The error ring is semantic (destructive) and intentionally NOT the
    // `--color-ring` token; only the non-error branch uses the shared ring.
    let focus_ring_class = if has_error {
        "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive focus-visible:ring-offset-2"
    } else {
        FOCUS_RING
    };

    let mut html = String::from("<div class=\"space-y-1\">");
    html.push_str(&format!(
        "<label class=\"block text-sm font-medium text-text\" for=\"{}\">{}</label>",
        html_escape(&props.field),
        html_escape(&props.label)
    ));

    html.push_str("<div class=\"relative\">");
    // fjui-select: skin owns border/bg/padding/border-radius/font-size/appearance.
    // fjui-select--error: skin owns destructive border when in error state.
    // DISABLED_BASE + FOCUS_RING are D-02 allowlist behavior utilities (kept inline).
    //
    // When searchable=true the native <select> is the hidden form value carrier:
    // it gets class="sr-only" and data-combobox-native instead of the visible skin
    // classes. The combobox.rs runtime syncs value back via nativeSelect.value.
    let select_error_class = if has_error { " fjui-select--error" } else { "" };
    if props.searchable == Some(true) {
        html.push_str(&format!(
            "<select id=\"{}\" name=\"{}\" class=\"sr-only\" data-combobox-native",
            html_escape(&props.field),
            html_escape(&props.field),
        ));
    } else {
        html.push_str(&format!(
            "<select id=\"{}\" name=\"{}\" class=\"fjui-select{select_error_class} w-full pr-10 {MOTION_FAST} {DISABLED_BASE} {}\"",
            html_escape(&props.field),
            html_escape(&props.field),
            focus_ring_class
        ));
    }
    if props.required == Some(true) {
        html.push_str(" required");
    }
    if props.disabled == Some(true) {
        html.push_str(" disabled");
    }
    if has_error {
        html.push_str(&format!(
            " aria-invalid=\"true\" aria-describedby=\"err-{}\"",
            html_escape(&props.field)
        ));
    }
    html.push('>');

    if let Some(ref placeholder) = props.placeholder {
        html.push_str(&format!(
            "<option value=\"\">{}</option>",
            html_escape(placeholder)
        ));
    }

    for opt in &props.options {
        let is_selected = selected_value.as_deref() == Some(&opt.value);
        let selected_attr = if is_selected { " selected" } else { "" };
        html.push_str(&format!(
            "<option value=\"{}\"{}>{}</option>",
            html_escape(&opt.value),
            selected_attr,
            html_escape(&opt.label)
        ));
    }

    html.push_str("</select>");

    if props.searchable == Some(true) {
        // Combobox progressive enhancement overlay.
        // The native <select> above becomes the hidden form value carrier
        // (class="sr-only" data-combobox-native). The visible widget is
        // emitted below; the runtime (combobox.rs) binds the two on init.
        //
        // All fjui-* class names are full string literals (D-01 lock — no
        // format! interpolation of class names). Interpolation is only for
        // id/aria/data attribute VALUES, and every user-supplied value goes
        // through html_escape.

        let field_esc = html_escape(&props.field);
        let placeholder = props.placeholder.as_deref().unwrap_or("Cerca\u{2026}");
        let listbox_id = format!("fjui-combo-listbox-{field_esc}");
        let controls_id = html_escape(&listbox_id);

        html.push_str(&format!(
            "<div class=\"fjui-combobox\" data-combobox>\
             <input class=\"fjui-combobox__input\" data-combobox-input \
              type=\"text\" role=\"combobox\" \
              aria-expanded=\"false\" \
              aria-controls=\"{controls_id}\" \
              aria-autocomplete=\"list\" \
              aria-activedescendant \
              placeholder=\"{placeholder_esc}\" \
              autocomplete=\"off\" spellcheck=\"false\">\
             <ul class=\"fjui-combobox__listbox\" id=\"{controls_id}\" role=\"listbox\" hidden>",
            controls_id = controls_id,
            placeholder_esc = html_escape(placeholder),
        ));

        for (i, opt) in props.options.iter().enumerate() {
            let opt_id = format!("fjui-combo-opt-{}-{}", html_escape(&props.field), i);
            html.push_str(&format!(
                "<li class=\"fjui-combobox__option\" role=\"option\"\
                  id=\"{opt_id}\" data-value=\"{val}\" aria-selected=\"false\">{label}</li>",
                opt_id = html_escape(&opt_id),
                val = html_escape(&opt.value),
                label = html_escape(&opt.label),
            ));
        }

        html.push_str("</ul></div>");
    } else {
        html.push_str(concat!(
            "<span class=\"pointer-events-none absolute inset-y-0 right-3 flex items-center\" aria-hidden=\"true\">",
            "<svg class=\"h-4 w-4 text-text-muted\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" fill=\"currentColor\">",
            "<path fill-rule=\"evenodd\" d=\"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z\" clip-rule=\"evenodd\"/>",
            "</svg></span>"
        ));
    }
    html.push_str("</div>");

    if let Some(ref desc) = props.description {
        html.push_str(&format!(
            "<p class=\"text-sm text-text-muted\">{}</p>",
            html_escape(desc)
        ));
    }

    if let Some(ref error) = props.error {
        html.push_str(&format!(
            "<p id=\"err-{}\" class=\"fjui-form-message--error\">{}</p>",
            html_escape(&props.field),
            html_escape(error)
        ));
    }
    html.push_str("</div>");
    html
}

/// Renders a `<input type="checkbox">`.
///
/// `checked` prop wins over `data_path` truthy resolution. When `props.value`
/// is set, the checkbox id is scoped as `"{field}_{value}"` so multiple
/// checkboxes in a group can share the same name without id collisions.
pub(crate) fn render_checkbox(el: &Element, _spec: &Spec, data: &Value, _depth: usize) -> String {
    let props: CheckboxProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode Checkbox props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    let is_checked = resolve_checked(props.checked, props.data_path.as_deref(), data);

    let has_error = props.error.is_some();
    let border_class = if has_error {
        "border-destructive"
    } else {
        "border-border"
    };
    // The error ring is semantic (destructive) and intentionally NOT the
    // `--color-ring` token; only the non-error branch uses the shared ring.
    let focus_ring_class = if has_error {
        "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive focus-visible:ring-offset-2"
    } else {
        FOCUS_RING
    };

    let value_attr = props.value.as_deref().unwrap_or("1");
    let checkbox_id = match &props.value {
        Some(v) => format!("{}_{}", props.field, v),
        None => props.field.clone(),
    };

    let mut html = String::from("<div class=\"space-y-1\">");
    html.push_str("<div class=\"flex items-center gap-2\">");
    html.push_str(&format!(
        "<input type=\"checkbox\" id=\"{}\" name=\"{}\" value=\"{}\" class=\"h-4 w-4 rounded-sm {} text-primary {MOTION_FAST} {DISABLED_BASE} {}\"",
        html_escape(&checkbox_id),
        html_escape(&props.field),
        html_escape(value_attr),
        border_class,
        focus_ring_class,
    ));
    if is_checked {
        html.push_str(" checked");
    }
    if props.required == Some(true) {
        html.push_str(" required");
    }
    if props.disabled == Some(true) {
        html.push_str(" disabled");
    }
    if has_error {
        html.push_str(&format!(
            " aria-invalid=\"true\" aria-describedby=\"err-{}\"",
            html_escape(&props.field)
        ));
    }
    html.push('>');
    html.push_str(&format!(
        "<label class=\"text-sm font-medium text-text\" for=\"{}\">{}</label>",
        html_escape(&checkbox_id),
        html_escape(&props.label)
    ));
    html.push_str("</div>");

    if let Some(ref desc) = props.description {
        html.push_str(&format!(
            "<p class=\"ml-6 text-sm text-text-muted\">{}</p>",
            html_escape(desc)
        ));
    }

    if let Some(ref error) = props.error {
        html.push_str(&format!(
            "<p id=\"err-{}\" class=\"ml-6 text-sm text-destructive\">{}</p>",
            html_escape(&props.field),
            html_escape(error)
        ));
    }
    html.push_str("</div>");
    html
}

/// Renders a multi-select checkbox group from static `options` or a data-driven
/// `options_path`. Pre-checked options are resolved from `selected_path` as a
/// `Vec<String>`. All string interpolations pass through `html_escape`.
pub(crate) fn render_checkbox_list(
    el: &Element,
    _spec: &Spec,
    data: &Value,
    _depth: usize,
) -> String {
    let props: CheckboxListProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode CheckboxList props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    // Resolve options: data-driven path wins when static `options` is empty.
    let options: Vec<SelectOption> = if props.options.is_empty() {
        props
            .options_path
            .as_deref()
            .and_then(|path| resolve_path(data, path))
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| serde_json::from_value::<SelectOption>(v.clone()).ok())
                    .collect()
            })
            .unwrap_or_default()
    } else {
        props.options.clone()
    };

    // Resolve pre-selected values.
    let selected: Vec<String> = props
        .selected_path
        .as_deref()
        .and_then(|path| resolve_path(data, path))
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect()
        })
        .unwrap_or_default();

    let has_error = props.error.is_some();
    let mut html = if has_error {
        format!(
            "<fieldset class=\"space-y-2\" aria-invalid=\"true\" aria-describedby=\"err-{}\">",
            html_escape(&props.field)
        )
    } else {
        String::from("<fieldset class=\"space-y-2\">")
    };
    if let Some(ref label) = props.label {
        html.push_str(&format!(
            "<legend class=\"text-sm font-medium text-text\">{}</legend>",
            html_escape(label)
        ));
    }
    if let Some(ref desc) = props.description {
        html.push_str(&format!(
            "<p class=\"text-sm text-text-muted mb-2\">{}</p>",
            html_escape(desc)
        ));
    }
    let checkbox_border = if has_error {
        "border-destructive"
    } else {
        "border-border"
    };
    for option in &options {
        let is_checked = selected.contains(&option.value);
        let checkbox_id = format!("{}_{}", props.field, option.value);
        html.push_str("<div class=\"flex items-center gap-2\">");
        html.push_str(&format!(
            "<input type=\"checkbox\" id=\"{}\" name=\"{}\" value=\"{}\" \
             class=\"h-4 w-4 rounded-sm {} text-primary {MOTION_FAST} {DISABLED_BASE} {FOCUS_RING}\"",
            html_escape(&checkbox_id),
            html_escape(&props.field),
            html_escape(&option.value),
            checkbox_border,
        ));
        if is_checked {
            html.push_str(" checked");
        }
        if props.disabled == Some(true) {
            html.push_str(" disabled");
        }
        html.push('>');
        html.push_str(&format!(
            "<label class=\"text-sm font-medium text-text\" for=\"{}\">{}</label>",
            html_escape(&checkbox_id),
            html_escape(&option.label)
        ));
        html.push_str("</div>");
    }
    if let Some(ref err) = props.error {
        html.push_str(&format!(
            "<p id=\"err-{}\" class=\"text-sm text-destructive mt-1\">{}</p>",
            html_escape(&props.field),
            html_escape(err)
        ));
    }
    html.push_str("</fieldset>");
    html
}

/// Renders a switch (styled checkbox with `role="switch"`).
///
/// Auto-form wrap: when `props.action` is `Some`, the switch renders inside
/// a minimal `<form>` and fires an `onchange` submit. When `action.url` is
/// `None`, the form falls back to `action="#"` with a diagnostic HTML
/// comment preceding the rendered markup.
pub(crate) fn render_switch(el: &Element, _spec: &Spec, data: &Value, _depth: usize) -> String {
    let props: SwitchProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode Switch props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    let is_checked = resolve_checked(props.checked, props.data_path.as_deref(), data);

    let has_error = props.error.is_some();
    // Error keeps the semantic destructive ring; the non-error ring sources
    // the `--color-ring` token (peer-focus /30 opacity — Switch-specific).
    let peer_ring_class = if has_error {
        "peer-focus:ring-2 peer-focus:ring-destructive/30"
    } else {
        "peer-focus:ring-2 peer-focus:ring-ring/30"
    };

    let compact_class = if props.compact == Some(true) {
        " scale-75 origin-left"
    } else {
        ""
    };

    let auto_submit = props.action.is_some();
    let onchange = if auto_submit {
        " onchange=\"this.closest('form').submit()\""
    } else {
        ""
    };

    let mut diagnostic = String::new();
    let mut html = String::new();

    if let Some(ref action) = props.action {
        let (action_url, diag) = match action.url.as_deref() {
            Some(u) => (u.to_string(), String::new()),
            None => (
                "#".to_string(),
                format!(
                    "<!-- ferro-json-ui: action '{}' has no resolved url -->",
                    html_escape(action.handler.as_str())
                ),
            ),
        };
        diagnostic = diag;

        let (form_method, needs_spoofing) = match action.method {
            HttpMethod::Get => ("get", false),
            HttpMethod::Post => ("post", false),
            HttpMethod::Put | HttpMethod::Patch | HttpMethod::Delete => ("post", true),
        };
        html.push_str(&format!(
            "<form action=\"{}\" method=\"{}\">",
            html_escape(&action_url),
            form_method
        ));
        if needs_spoofing {
            let method_value = match action.method {
                HttpMethod::Put => "PUT",
                HttpMethod::Patch => "PATCH",
                HttpMethod::Delete => "DELETE",
                _ => unreachable!(),
            };
            html.push_str(&format!(
                "<input type=\"hidden\" name=\"_method\" value=\"{method_value}\">"
            ));
        }
    }

    html.push_str(&format!("<div class=\"space-y-1{compact_class}\">"));
    html.push_str("<div class=\"flex items-center justify-between\">");

    // Left side: label + description.
    html.push_str("<div>");
    html.push_str(&format!(
        "<label class=\"text-sm font-medium text-text\" for=\"{}\">{}</label>",
        html_escape(&props.field),
        html_escape(&props.label)
    ));
    if let Some(ref desc) = props.description {
        html.push_str(&format!(
            "<p class=\"text-sm text-text-muted\">{}</p>",
            html_escape(desc)
        ));
    }
    html.push_str("</div>");

    // Right side: toggle.
    html.push_str("<label class=\"relative inline-flex items-center cursor-pointer\">");
    let aria_checked = if is_checked { "true" } else { "false" };
    html.push_str(&format!(
        "<input type=\"checkbox\" id=\"{}\" name=\"{}\" value=\"1\" role=\"switch\" aria-checked=\"{}\" class=\"sr-only peer\"{}",
        html_escape(&props.field),
        html_escape(&props.field),
        aria_checked,
        onchange,
    ));
    if is_checked {
        html.push_str(" checked");
    }
    if props.required == Some(true) {
        html.push_str(" required");
    }
    if props.disabled == Some(true) {
        html.push_str(" disabled");
    }
    if has_error {
        html.push_str(&format!(
            " aria-invalid=\"true\" aria-describedby=\"err-{}\"",
            html_escape(&props.field)
        ));
    }
    html.push('>');
    html.push_str(&format!(
        "<div class=\"w-11 h-6 bg-border rounded-full peer peer-checked:bg-primary {peer_ring_class} after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-background after:rounded-full after:h-5 after:w-5 after:transition-all after:duration-fast after:ease-base peer-checked:after:translate-x-full\"></div>",
    ));
    html.push_str("</label>");
    html.push_str("</div>");

    if let Some(ref error) = props.error {
        html.push_str(&format!(
            "<p id=\"err-{}\" class=\"text-sm text-destructive\">{}</p>",
            html_escape(&props.field),
            html_escape(error)
        ));
    }
    html.push_str("</div>");

    if props.action.is_some() {
        html.push_str("</form>");
    }

    format!("{diagnostic}{html}")
}

/// Shared truthiness rule for `Checkbox.data_path` and `Switch.data_path`.
/// Per-JSON-variant semantics: `Bool` is its own value; `Number` is truthy
/// iff nonzero; `String` is truthy iff non-empty AND not the literal
/// `"false"` / `"0"`; `Null` is always falsy; arrays and objects are always
/// truthy.
fn resolve_checked(explicit: Option<bool>, data_path: Option<&str>, data: &Value) -> bool {
    if let Some(c) = explicit {
        return c;
    }
    match data_path {
        Some(dp) => resolve_path(data, dp)
            .map(|v| match v {
                Value::Bool(b) => *b,
                Value::Number(n) => n.as_f64().map(|f| f != 0.0).unwrap_or(false),
                Value::String(s) => !s.is_empty() && s != "false" && s != "0",
                Value::Null => false,
                _ => true,
            })
            .unwrap_or(false),
        None => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::action::{Action, HttpMethod};
    use crate::spec::{Element, Spec};
    use serde_json::json;

    fn mk_spec(root: &str, el: Element) -> Spec {
        let mut spec = Spec::builder()
            .element("__tmp__", Element::new("Text"))
            .build()
            .expect("builder accepts trivial spec");
        spec.root = root.to_string();
        spec.elements.clear();
        spec.elements.insert(root.to_string(), el);
        spec
    }

    fn mk_element(type_name: &str, props: Value) -> Element {
        Element {
            type_name: type_name.to_string(),
            props,
            children: Vec::new(),
            action: None,
            visible: None,
            each: None,
            if_: None,
        }
    }

    // ── Input ────────────────────────────────────────────────────────────

    #[test]
    fn input_data_path_prefills_value() {
        let el = mk_element(
            "Input",
            json!({"field": "name", "label": "Name", "data_path": "/user/name"}),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"user": {"name": "Alice"}});
        let html = render_input(&el, &spec, &data, 1);
        assert!(html.contains("value=\"Alice\""), "got: {html}");
    }

    #[test]
    fn input_default_value_wins_over_data_path() {
        // Precedence: explicit default_value wins over data_path.
        let el = mk_element(
            "Input",
            json!({
                "field": "name",
                "label": "Name",
                "default_value": "explicit",
                "data_path": "/user/name",
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"user": {"name": "Alice"}});
        let html = render_input(&el, &spec, &data, 1);
        assert!(html.contains("value=\"explicit\""), "got: {html}");
        assert!(!html.contains("value=\"Alice\""), "got: {html}");
    }

    #[test]
    fn input_hidden_emits_no_label() {
        let el = mk_element(
            "Input",
            json!({"field": "token", "label": "t", "input_type": "hidden", "default_value": "abc"}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);
        assert!(html.starts_with("<input type=\"hidden\""), "got: {html}");
        assert!(!html.contains("<label"), "got: {html}");
        assert!(html.contains("value=\"abc\""), "got: {html}");
    }

    #[test]
    fn input_xss_in_value_is_escaped() {
        // Attribute-breakout via data_path — the resolved value must be
        // html-escaped before interpolation into `value=""`.
        let el = mk_element(
            "Input",
            json!({"field": "name", "label": "n", "data_path": "/payload"}),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"payload": "\"><script>x</script>"});
        let html = render_input(&el, &spec, &data, 1);
        assert!(!html.contains("<script>x</script>"), "got: {html}");
        assert!(html.contains("&quot;"), "got: {html}");
    }

    #[test]
    fn input_error_emits_aria_describedby() {
        let el = mk_element(
            "Input",
            json!({"field": "email", "label": "Email", "error": "required"}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);
        assert!(html.contains("aria-invalid=\"true\""), "got: {html}");
        assert!(
            html.contains("aria-describedby=\"err-email\""),
            "got: {html}"
        );
        assert!(
            html.contains("<p id=\"err-email\" class=\"fjui-form-message--error\">required</p>"),
            "got: {html}"
        );
    }

    /// INT-pass (251-02): the non-error focus ring sources the `--color-ring`
    /// token and the disabled treatment is the uniform D-16 pair.
    #[test]
    fn input_non_error_carries_token_ring_and_disabled_base() {
        let el = mk_element("Input", json!({"field": "email", "label": "Email"}));
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("focus-visible:ring-ring"),
            "non-error input must carry the ring token; got: {html}"
        );
        assert!(
            !html.contains("focus-visible:ring-destructive"),
            "no error ring without error; got: {html}"
        );
        assert!(
            html.contains("disabled:pointer-events-none"),
            "uniform disabled treatment (D-16); got: {html}"
        );
        assert!(
            !html.contains("disabled:cursor-not-allowed"),
            "retired disabled cursor class must not survive; got: {html}"
        );
        assert!(
            html.contains("duration-fast"),
            "fast motion tier on form controls; got: {html}"
        );
    }

    /// INT-pass (251-02): Switch non-error peer ring sources the ring token.
    #[test]
    fn switch_non_error_carries_token_peer_ring() {
        let el = mk_element("Switch", json!({"field": "notify", "label": "Notify"}));
        let spec = mk_spec("root", el.clone());
        let html = render_switch(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("peer-focus:ring-ring/30"),
            "non-error Switch must carry peer-focus:ring-ring/30; got: {html}"
        );
        assert!(
            !html.contains("peer-focus:ring-destructive/30"),
            "no error peer ring without error; got: {html}"
        );
    }

    // ── Date picker opt-in ───────────────────────────────────────────────

    /// date_picker=true on a date input emits the [data-date-picker] wrapper,
    /// the sr-only native input as value carrier, the trigger button, and the
    /// dialog shell. No plain fjui-input class must appear (that class belongs
    /// to the un-enhanced path).
    #[test]
    fn input_date_picker_true_emits_wrapper_markup() {
        let el = mk_element(
            "Input",
            json!({
                "field": "date",
                "label": "Data",
                "input_type": "date",
                "date_picker": true,
                "default_value": "2026-07-22"
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);

        // Wrapper attribute present.
        assert!(
            html.contains("data-date-picker"),
            "wrapper attr missing; got: {html}"
        );
        // Native input is the value carrier with data-date-picker-native.
        assert!(
            html.contains("data-date-picker-native"),
            "native value-carrier attr missing; got: {html}"
        );
        // Native input carries sr-only (visually hidden, accessible).
        assert!(
            html.contains("sr-only"),
            "sr-only missing on native input; got: {html}"
        );
        // Native input carries the default value.
        assert!(
            html.contains("value=\"2026-07-22\""),
            "default value missing on native input; got: {html}"
        );
        // Trigger button present.
        assert!(
            html.contains("data-date-picker-trigger"),
            "trigger button attr missing; got: {html}"
        );
        // Dialog shell present.
        assert!(
            html.contains("data-date-picker-dialog"),
            "dialog shell attr missing; got: {html}"
        );
        // No plain fjui-input class — that is the un-enhanced path.
        assert!(
            !html.contains("class=\"fjui-input"),
            "fjui-input class must not appear on the date-picker path; got: {html}"
        );
    }

    /// date_picker=true on a time input emits "Seleziona orario" trigger label.
    #[test]
    fn input_date_picker_true_time_emits_orario_label() {
        let el = mk_element(
            "Input",
            json!({
                "field": "booking_time",
                "label": "Orario",
                "input_type": "time",
                "date_picker": true
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);

        assert!(
            html.contains("data-date-picker"),
            "wrapper attr missing; got: {html}"
        );
        assert!(
            html.contains("Seleziona orario"),
            "time trigger must say 'Seleziona orario'; got: {html}"
        );
        assert!(
            !html.contains("Seleziona data"),
            "time trigger must not say 'Seleziona data'; got: {html}"
        );
    }

    /// date_picker absent (default) on a date input emits the plain fjui-input path.
    /// Regression guard: the enhancement must not alter existing plain date inputs.
    #[test]
    fn input_date_no_picker_emits_plain_input() {
        let el = mk_element(
            "Input",
            json!({"field": "date", "label": "Data", "input_type": "date"}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);

        assert!(
            !html.contains("data-date-picker"),
            "plain date input must not emit data-date-picker; got: {html}"
        );
        assert!(
            html.contains("class=\"fjui-input"),
            "plain date input must emit fjui-input class; got: {html}"
        );
        assert!(
            html.contains("type=\"date\""),
            "plain date input must emit type=\"date\"; got: {html}"
        );
    }

    /// date_picker=true propagates error ARIA to the native sr-only input.
    #[test]
    fn input_date_picker_error_aria_on_native_input() {
        let el = mk_element(
            "Input",
            json!({
                "field": "date",
                "label": "Data",
                "input_type": "date",
                "date_picker": true,
                "error": "obbligatorio"
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);

        assert!(
            html.contains("aria-invalid=\"true\""),
            "aria-invalid missing; got: {html}"
        );
        assert!(
            html.contains("aria-describedby=\"err-date\""),
            "aria-describedby missing; got: {html}"
        );
        // Error message paragraph still rendered.
        assert!(
            html.contains("<p id=\"err-date\""),
            "error <p> missing; got: {html}"
        );
    }

    // ── Checkbox ─────────────────────────────────────────────────────────

    #[test]
    fn checkbox_error_renders_destructive_class_and_aria() {
        let el = mk_element(
            "Checkbox",
            json!({"field": "agreed", "label": "Agree", "error": "required"}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_checkbox(&el, &spec, &json!({}), 1);

        // Pitfall 3 guard: border-destructive must be ON the <input>, not on an outer <div>.
        let input_pos = html
            .find("<input type=\"checkbox\"")
            .expect("<input type=\"checkbox\" not found in rendered output");
        let input_close_rel = html[input_pos..]
            .find('>')
            .expect("closing > for <input> not found");
        let input_tag = &html[input_pos..=(input_pos + input_close_rel)];
        assert!(
            input_tag.contains("border-destructive"),
            "border-destructive must be on the <input> tag itself; input tag: {input_tag}"
        );
        assert!(
            input_tag.contains("focus-visible:ring-destructive"),
            "focus-visible:ring-destructive must be on the <input>; input tag: {input_tag}"
        );
        assert!(
            input_tag.contains("aria-invalid=\"true\""),
            "aria-invalid must be on the <input>; input tag: {input_tag}"
        );
        assert!(
            input_tag.contains("aria-describedby=\"err-agreed\""),
            "aria-describedby must be on the <input>; input tag: {input_tag}"
        );

        // Locked error <p> DOM shape per UI-SPEC.md.
        assert!(
            html.contains(
                "<p id=\"err-agreed\" class=\"ml-6 text-sm text-destructive\">required</p>"
            ),
            "error <p> must have id=\"err-agreed\" and locked class chain; got: {html}"
        );

        // Diagnostic-comment guard (RESEARCH Pattern Map §Decode-Failure).
        assert!(
            !html.contains("<!-- ferro-json-ui:"),
            "no diagnostic comments in happy path; got: {html}"
        );
    }

    #[test]
    fn checkbox_list_error_renders_fieldset_aria() {
        let el = mk_element(
            "CheckboxList",
            json!({
                "field": "topics",
                "label": "Topics",
                "options": [
                    {"value": "a", "label": "A"},
                    {"value": "b", "label": "B"}
                ],
                "error": "pick at least one"
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_checkbox_list(&el, &spec, &json!({}), 1);

        // Fieldset must carry the ARIA pairing.
        let fieldset_pos = html
            .find("<fieldset")
            .expect("<fieldset not found in rendered output");
        let fieldset_close_rel = html[fieldset_pos..]
            .find('>')
            .expect("closing > for <fieldset> not found");
        let fieldset_tag = &html[fieldset_pos..=(fieldset_pos + fieldset_close_rel)];
        assert!(
            fieldset_tag.contains("aria-invalid=\"true\""),
            "aria-invalid must be on <fieldset>; fieldset tag: {fieldset_tag}"
        );
        assert!(
            fieldset_tag.contains("aria-describedby=\"err-topics\""),
            "aria-describedby must be on <fieldset>; fieldset tag: {fieldset_tag}"
        );

        // Each per-option <input type="checkbox"> must carry border-destructive.
        let input_count = html.matches("<input type=\"checkbox\"").count();
        assert_eq!(
            input_count, 2,
            "expected 2 option inputs; got {input_count} in: {html}"
        );
        let destructive_input_count = html
            .split("<input type=\"checkbox\"")
            .skip(1)
            .filter(|chunk| {
                let close_rel = chunk
                    .find('>')
                    .expect(">/closing not found in option input");
                chunk[..close_rel].contains("border-destructive")
            })
            .count();
        assert_eq!(
            destructive_input_count, 2,
            "both option inputs must carry border-destructive; got {destructive_input_count} of 2 in: {html}"
        );

        // Per-option inputs MUST NOT carry their own aria-invalid (group-level ARIA only).
        // The single aria-invalid above on <fieldset> is the only occurrence we expect.
        let aria_count = html.matches("aria-invalid=\"true\"").count();
        assert_eq!(
            aria_count, 1,
            "aria-invalid should appear only on <fieldset> (count=1); got {aria_count} in: {html}"
        );

        // Locked error <p> DOM shape per UI-SPEC.md.
        assert!(
            html.contains("<p id=\"err-topics\" class=\"text-sm text-destructive mt-1\">pick at least one</p>"),
            "error <p> must have id=\"err-topics\" and locked class chain; got: {html}"
        );

        assert!(
            !html.contains("<!-- ferro-json-ui:"),
            "no diagnostic comments; got: {html}"
        );
    }

    #[test]
    fn switch_error_renders_destructive_ring_and_aria() {
        let el = mk_element(
            "Switch",
            json!({"field": "notify", "label": "Notify me", "error": "required"}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_switch(&el, &spec, &json!({}), 1);

        // Hidden checkbox <input> must carry aria-invalid + aria-describedby.
        // We isolate the hidden input (it has class "sr-only peer") to make sure the
        // ARIA is on the form control element, not on a sibling div.
        let input_pos = html
            .find("<input")
            .expect("<input not found in rendered output");
        let input_close_rel = html[input_pos..]
            .find('>')
            .expect("closing > for <input> not found");
        let input_tag = &html[input_pos..=(input_pos + input_close_rel)];
        assert!(
            input_tag.contains("sr-only peer"),
            "the first <input> should be the hidden sr-only peer; tag: {input_tag}"
        );
        assert!(
            input_tag.contains("aria-invalid=\"true\""),
            "aria-invalid must be on the hidden <input>; tag: {input_tag}"
        );
        assert!(
            input_tag.contains("aria-describedby=\"err-notify\""),
            "aria-describedby must be on the hidden <input>; tag: {input_tag}"
        );

        // The visible pill <div> must carry peer-focus:ring-destructive/30,
        // NOT the non-error `--color-ring` token ring.
        assert!(
            html.contains("peer-focus:ring-destructive/30"),
            "pill must carry peer-focus:ring-destructive/30; got: {html}"
        );
        assert!(
            !html.contains("peer-focus:ring-ring/30"),
            "pill must NOT carry peer-focus:ring-ring/30 when has_error; got: {html}"
        );

        // Locked error <p> DOM shape per UI-SPEC.md.
        assert!(
            html.contains("<p id=\"err-notify\" class=\"text-sm text-destructive\">required</p>"),
            "error <p> must have id=\"err-notify\" and locked class chain; got: {html}"
        );

        assert!(
            !html.contains("<!-- ferro-json-ui:"),
            "no diagnostic comments; got: {html}"
        );
    }

    #[test]
    fn input_file_error_renders_destructive_ring_and_aria() {
        let el = mk_element(
            "Input",
            json!({
                "field": "avatar",
                "label": "Avatar",
                "input_type": "file",
                "error": "must be PNG"
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);

        // Isolate the <input type="file"> tag bytes (Pitfall 3 guard).
        let input_pos = html
            .find("<input type=\"file\"")
            .expect("<input type=\"file\" not found in rendered output");
        let input_close_rel = html[input_pos..]
            .find('>')
            .expect("closing > for <input type=\"file\"> not found");
        let input_tag = &html[input_pos..=(input_pos + input_close_rel)];

        assert!(
            input_tag.contains("ring-1 ring-destructive"),
            "ring-1 ring-destructive must be on the <input type=\"file\">; tag: {input_tag}"
        );
        assert!(
            input_tag.contains("aria-invalid=\"true\""),
            "aria-invalid must be on the <input type=\"file\">; tag: {input_tag}"
        );
        assert!(
            input_tag.contains("aria-describedby=\"err-avatar\""),
            "aria-describedby must be on the <input type=\"file\">; tag: {input_tag}"
        );

        // Shared error <p> already has id — confirm it survives with the migrated class.
        assert!(
            html.contains(
                "<p id=\"err-avatar\" class=\"fjui-form-message--error\">must be PNG</p>"
            ),
            "shared error <p> must carry id and fjui-form-message--error class; got: {html}"
        );

        assert!(
            !html.contains("<!-- ferro-json-ui:"),
            "no diagnostic comments; got: {html}"
        );
    }

    // ── Select ───────────────────────────────────────────────────────────

    #[test]
    fn select_data_path_marks_option_selected() {
        let el = mk_element(
            "Select",
            json!({
                "field": "role",
                "label": "Role",
                "data_path": "/role",
                "options": [
                    {"value": "a", "label": "A"},
                    {"value": "b", "label": "B"},
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"role": "b"});
        let html = render_select(&el, &spec, &data, 1);
        assert!(
            html.contains("<option value=\"b\" selected>B</option>"),
            "got: {html}"
        );
        assert!(
            html.contains("<option value=\"a\">A</option>"),
            "got: {html}"
        );
    }

    #[test]
    fn select_default_value_wins_over_data_path() {
        let el = mk_element(
            "Select",
            json!({
                "field": "role",
                "label": "Role",
                "default_value": "a",
                "data_path": "/role",
                "options": [
                    {"value": "a", "label": "A"},
                    {"value": "b", "label": "B"},
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"role": "b"});
        let html = render_select(&el, &spec, &data, 1);
        assert!(
            html.contains("<option value=\"a\" selected>A</option>"),
            "got: {html}"
        );
    }

    // ── Checkbox ─────────────────────────────────────────────────────────

    #[test]
    fn checkbox_data_path_truthy_renders_checked() {
        let el = mk_element(
            "Checkbox",
            json!({"field": "agreed", "label": "Agree", "data_path": "/agreed"}),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"agreed": true});
        let html = render_checkbox(&el, &spec, &data, 1);
        assert!(html.contains(" checked"), "got: {html}");
    }

    #[test]
    fn checkbox_data_path_false_omits_checked() {
        let el = mk_element(
            "Checkbox",
            json!({"field": "agreed", "label": "Agree", "data_path": "/agreed"}),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"agreed": false});
        let html = render_checkbox(&el, &spec, &data, 1);
        assert!(!html.contains(" checked"), "got: {html}");
    }

    #[test]
    fn checkbox_with_value_scopes_id() {
        let el = mk_element(
            "Checkbox",
            json!({"field": "topic", "value": "news", "label": "News"}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_checkbox(&el, &spec, &json!({}), 1);
        assert!(html.contains("id=\"topic_news\""), "got: {html}");
        assert!(html.contains("name=\"topic\""), "got: {html}");
        assert!(html.contains("value=\"news\""), "got: {html}");
    }

    // ── Switch ───────────────────────────────────────────────────────────

    #[test]
    fn switch_with_action_wraps_in_form() {
        let action = Action {
            handler: "users.toggle".into(),
            url: Some("/users/1/toggle".into()),
            method: HttpMethod::Post,
            confirm: None,
            on_success: None,
            on_error: None,
            target: None,
        };
        let el = mk_element(
            "Switch",
            json!({
                "field": "active",
                "label": "Active",
                "action": action,
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_switch(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("<form action=\"/users/1/toggle\" method=\"post\">"),
            "got: {html}"
        );
        assert!(
            html.contains("onchange=\"this.closest('form').submit()\""),
            "got: {html}"
        );
        assert!(html.contains("</form>"), "got: {html}");
    }

    #[test]
    fn switch_without_action_no_form_wrap() {
        let el = mk_element("Switch", json!({"field": "active", "label": "Active"}));
        let spec = mk_spec("root", el.clone());
        let html = render_switch(&el, &spec, &json!({}), 1);
        assert!(
            !html.contains("<form"),
            "switch without action must not wrap in form; got: {html}"
        );
        assert!(
            !html.contains("onchange"),
            "switch without action must not have onchange; got: {html}"
        );
    }

    #[test]
    fn switch_action_without_url_emits_diagnostic() {
        let action = Action {
            handler: "users.toggle".into(),
            url: None,
            method: HttpMethod::Post,
            confirm: None,
            on_success: None,
            on_error: None,
            target: None,
        };
        let el = mk_element(
            "Switch",
            json!({"field": "active", "label": "Active", "action": action}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_switch(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("<!-- ferro-json-ui: action 'users.toggle' has no resolved url -->"),
            "got: {html}"
        );
        assert!(html.contains("<form action=\"#\""), "got: {html}");
    }

    #[test]
    fn switch_put_method_spoofs_post() {
        let action = Action {
            handler: "users.update".into(),
            url: Some("/users/1".into()),
            method: HttpMethod::Put,
            confirm: None,
            on_success: None,
            on_error: None,
            target: None,
        };
        let el = mk_element(
            "Switch",
            json!({"field": "x", "label": "X", "action": action}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_switch(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("<form action=\"/users/1\" method=\"post\">"),
            "got: {html}"
        );
        assert!(
            html.contains("<input type=\"hidden\" name=\"_method\" value=\"PUT\">"),
            "got: {html}"
        );
    }

    // ── Form ─────────────────────────────────────────────────────────────

    #[test]
    fn form_recurses_children_as_fields() {
        // Build with the regular builder so the walker can resolve children.
        let spec = Spec::builder()
            .element(
                "root",
                Element::new("Form")
                    .prop(
                        "action",
                        json!({"handler": "save", "method": "POST", "url": "/save"}),
                    )
                    .child("i1")
                    .child("i2"),
            )
            .element(
                "i1",
                Element::new("Input").prop("field", "a").prop("label", "A"),
            )
            .element(
                "i2",
                Element::new("Input").prop("field", "b").prop("label", "B"),
            )
            .build()
            .expect("spec builds");

        let el = spec.elements.get("root").unwrap();
        let html = render_form(el, &spec, &json!({}), 1);
        assert!(html.contains("<form"), "got: {html}");
        // Both labels appear — confirms recursion into render_element which
        // dispatches to render_input for each child.
        assert!(html.contains(">A</label>"), "got: {html}");
        assert!(html.contains(">B</label>"), "got: {html}");
    }

    #[test]
    fn form_action_url_resolved_in_action_attr() {
        let el = mk_element(
            "Form",
            json!({"action": {"handler": "save", "method": "POST", "url": "/submit"}}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_form(&el, &spec, &json!({}), 1);
        assert!(html.contains("action=\"/submit\""), "got: {html}");
        assert!(!html.contains("<!-- ferro-json-ui: action"), "got: {html}");
    }

    #[test]
    fn form_action_url_unresolved_falls_back_with_diagnostic() {
        let el = mk_element(
            "Form",
            json!({"action": {"handler": "save", "method": "POST"}}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_form(&el, &spec, &json!({}), 1);
        assert!(html.contains("action=\"#\""), "got: {html}");
        assert!(
            html.contains("<!-- ferro-json-ui: action 'save' has no resolved url -->"),
            "got: {html}"
        );
    }

    #[test]
    fn form_put_method_spoofs_post_with_hidden_input() {
        let el = mk_element(
            "Form",
            json!({"action": {"handler": "update", "method": "PUT", "url": "/r/1"}}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_form(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("method=\"post\""),
            "PUT must spoof to POST; got: {html}"
        );
        assert!(
            html.contains("<input type=\"hidden\" name=\"_method\" value=\"PUT\">"),
            "got: {html}"
        );
    }

    // ── Decode-failure diagnostics ───────────────────────────────────────

    #[test]
    fn input_props_decode_failure_emits_diagnostic() {
        let el = mk_element("Input", json!(42));
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("<!-- ferro-json-ui: failed to decode Input props"),
            "got: {html}"
        );
    }

    #[test]
    fn form_props_decode_failure_emits_diagnostic() {
        let el = mk_element("Form", json!(42));
        let spec = mk_spec("root", el.clone());
        let html = render_form(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("<!-- ferro-json-ui: failed to decode Form props"),
            "got: {html}"
        );
    }

    /// Fill mode (256 D-15 / 257-04): a Form with `fill:true` joins the
    /// fill-viewport height chain so the inner panes Grid's `h-full` resolves
    /// against the viewport-constrained cell instead of content height.
    /// Expected class string: `flex flex-col h-full min-h-0 [&>*]:flex-1
    /// [&>*]:min-h-0` — mirrors the SelectionPanel shell pattern.
    #[test]
    fn render_form_fill_true_emits_height_chain() {
        let el = mk_element(
            "Form",
            json!({"action": {"handler": "/x", "method": "POST"}, "fill": true}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_form(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("flex flex-col h-full min-h-0 [&>*]:flex-1 [&>*]:min-h-0"),
            "fill:true form must carry the height-chain class string; got: {html}"
        );
        assert!(
            !html.contains("flex flex-wrap"),
            "fill:true form must NOT emit flex flex-wrap; got: {html}"
        );
    }

    /// Non-fill Form emits the byte-identical default class string.
    /// Proves the fill:absent path is unaffected by the fill feature (every
    /// existing Form render is unchanged — backward-compatibility guard).
    #[test]
    fn render_form_default_class_is_byte_identical() {
        let el = mk_element(
            "Form",
            json!({"action": {"handler": "/x", "method": "POST"}}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_form(&el, &spec, &json!({}), 1);
        assert!(
            html.contains(
                "class=\"flex flex-wrap gap-4 [&>*]:w-full [&>button]:w-auto [&>a]:w-auto\""
            ),
            "default form must carry the byte-identical default class string; got: {html}"
        );
        assert!(
            !html.contains("h-full"),
            "default form must NOT contain h-full; got: {html}"
        );
        assert!(
            !html.contains("min-h-0"),
            "default form must NOT contain min-h-0; got: {html}"
        );
    }

    // ── CheckboxList ─────────────────────────────────────────────────────

    #[test]
    fn checkbox_list_renders_one_checkbox_per_option() {
        let el = mk_element(
            "CheckboxList",
            json!({
                "field": "services",
                "options": [{"value": "a", "label": "A"}, {"value": "b", "label": "B"}]
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_checkbox_list(&el, &spec, &json!({}), 1);
        assert_eq!(
            html.matches("<input type=\"checkbox\"").count(),
            2,
            "expected 2 checkboxes; got: {html}"
        );
        assert!(html.contains("name=\"services\""), "got: {html}");
        assert!(html.contains("value=\"a\""), "got: {html}");
        assert!(html.contains("value=\"b\""), "got: {html}");
    }

    #[test]
    fn checkbox_list_selected_path_prechecks_matching_options() {
        let el = mk_element(
            "CheckboxList",
            json!({
                "field": "services",
                "options": [{"value": "a", "label": "A"}, {"value": "b", "label": "B"}],
                "selected_path": "/sel"
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"sel": ["a"]});
        let html = render_checkbox_list(&el, &spec, &data, 1);
        // Only option "a" should be checked
        let checked_count = html.matches(" checked").count();
        assert_eq!(checked_count, 1, "expected 1 checked; got: {html}");
        // The checked input must be the one with value="a"
        let a_pos = html.find("value=\"a\"").expect("value=a not found");
        let checked_pos = html.find(" checked").expect("checked not found");
        assert!(
            checked_pos > a_pos,
            "checked attribute should follow value=a; got: {html}"
        );
    }

    #[test]
    fn checkbox_list_options_path_resolves_dynamic_options() {
        let el = mk_element(
            "CheckboxList",
            json!({
                "field": "services",
                "options_path": "/opts"
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"opts": [{"value": "x", "label": "X"}]});
        let html = render_checkbox_list(&el, &spec, &data, 1);
        assert!(html.contains("value=\"x\""), "got: {html}");
        assert_eq!(
            html.matches("<input type=\"checkbox\"").count(),
            1,
            "got: {html}"
        );
    }

    #[test]
    fn checkbox_list_escapes_html_in_option_label() {
        let el = mk_element(
            "CheckboxList",
            json!({
                "field": "services",
                "options": [{"value": "a", "label": "<script>alert(1)</script>"}]
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_checkbox_list(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("&lt;script&gt;"),
            "label must be HTML-escaped; got: {html}"
        );
        assert!(
            !html.contains("<script>"),
            "raw <script> must not appear; got: {html}"
        );
    }

    #[test]
    fn checkbox_list_disabled_propagates_to_each_input() {
        let el = mk_element(
            "CheckboxList",
            json!({
                "field": "services",
                "options": [{"value": "a", "label": "A"}, {"value": "b", "label": "B"}],
                "disabled": true
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_checkbox_list(&el, &spec, &json!({}), 1);
        // Match the bare attribute (` disabled>` closes the tag) — the class
        // string legitimately contains `disabled:*` DISABLED_BASE fragments.
        let disabled_count = html.matches(" disabled>").count();
        assert_eq!(
            disabled_count, 2,
            "every input must carry disabled; got: {html}"
        );
    }

    // ── Switch.compact ───────────────────────────────────────────────────

    #[test]
    fn switch_compact_adds_scale_class() {
        // compact=true must produce scale-75 and origin-left in the output
        let el = mk_element(
            "Switch",
            json!({"field": "x", "label": "L", "compact": true}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_switch(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("scale-75"),
            "compact=true must emit scale-75; got: {html}"
        );
        assert!(
            html.contains("origin-left"),
            "compact=true must emit origin-left; got: {html}"
        );

        // compact=false must NOT produce the compact classes
        let el_false = mk_element(
            "Switch",
            json!({"field": "x", "label": "L", "compact": false}),
        );
        let html_false = render_switch(&el_false, &spec, &json!({}), 1);
        assert!(
            !html_false.contains("scale-75"),
            "compact=false must not emit scale-75; got: {html_false}"
        );

        // compact absent must NOT produce the compact classes
        let el_none = mk_element("Switch", json!({"field": "x", "label": "L"}));
        let html_none = render_switch(&el_none, &spec, &json!({}), 1);
        assert!(
            !html_none.contains("scale-75"),
            "compact=None must not emit scale-75; got: {html_none}"
        );
    }

    // ── File input + enctype (F5) ─────────────────────────────────────────

    #[test]
    fn input_file_renders_file_type_and_accept() {
        // Build a spec with a Form root and one file Input child.
        let spec = Spec::builder()
            .element(
                "root",
                Element::new("Form")
                    .prop(
                        "action",
                        json!({"handler": "upload", "method": "POST", "url": "/upload"}),
                    )
                    .child("avatar_input"),
            )
            .element(
                "avatar_input",
                Element::new("Input")
                    .prop("field", json!("avatar"))
                    .prop("label", json!("Avatar"))
                    .prop("input_type", json!("file"))
                    .prop("accept", json!("image/jpeg,image/png,image/webp")),
            )
            .build()
            .expect("spec builds");

        let html = crate::render::render_spec_to_html(&spec, &serde_json::Value::Null);
        assert!(
            html.contains("type=\"file\""),
            "file input must emit type=\"file\"; got: {html}"
        );
        assert!(
            html.contains("accept=\"image/jpeg,image/png,image/webp\""),
            "file input must emit accept attribute; got: {html}"
        );
        // File inputs MUST NOT emit value="" — browser security restriction.
        assert!(
            !html.contains("value=\"\""),
            "file input must not emit value attribute; got: {html}"
        );
        assert!(
            html.contains("<label"),
            "file input must still render a label; got: {html}"
        );
        assert!(
            html.contains("Avatar"),
            "label must contain the label text; got: {html}"
        );
    }

    #[test]
    fn form_enctype_emitted_when_set() {
        // Form with enctype set must emit the attribute on the opening <form> tag.
        let el_with_enctype = mk_element(
            "Form",
            json!({
                "action": {"handler": "upload", "method": "POST", "url": "/upload"},
                "enctype": "multipart/form-data"
            }),
        );
        let spec = mk_spec("root", el_with_enctype.clone());
        let html = render_form(&el_with_enctype, &spec, &json!({}), 1);
        assert!(
            html.contains("enctype=\"multipart/form-data\""),
            "enctype must appear in HTML; got: {html}"
        );
        // enctype attribute must appear on the opening <form> tag (between <form and first >)
        let form_start = html.find("<form").expect("<form not found");
        let tag_end = html[form_start..]
            .find('>')
            .expect("> not found after <form");
        let opening_tag = &html[form_start..form_start + tag_end];
        assert!(
            opening_tag.contains("enctype=\"multipart/form-data\""),
            "enctype must be on the opening <form> tag, not a child; got opening tag: {opening_tag}"
        );

        // Form without enctype must NOT emit the attribute.
        let el_no_enctype = mk_element(
            "Form",
            json!({"action": {"handler": "save", "method": "POST", "url": "/save"}}),
        );
        let spec2 = mk_spec("root", el_no_enctype.clone());
        let html2 = render_form(&el_no_enctype, &spec2, &json!({}), 1);
        assert!(
            !html2.contains("enctype=\""),
            "form without enctype must not emit enctype attribute; got: {html2}"
        );
    }

    #[test]
    fn multipart_form_roundtrip() {
        // End-to-end: staff create form with enctype + file input + text input + submit button.
        let spec = Spec::builder()
            .element(
                "root",
                Element::new("Form")
                    .prop(
                        "action",
                        json!({"handler": "staff.create", "method": "POST", "url": "/staff"}),
                    )
                    .prop("enctype", json!("multipart/form-data"))
                    .child("name_input")
                    .child("avatar_input")
                    .child("submit_btn"),
            )
            .element(
                "name_input",
                Element::new("Input")
                    .prop("field", json!("name"))
                    .prop("label", json!("Nome"))
                    .prop("input_type", json!("text")),
            )
            .element(
                "avatar_input",
                Element::new("Input")
                    .prop("field", json!("avatar"))
                    .prop("label", json!("Avatar"))
                    .prop("input_type", json!("file"))
                    .prop("accept", json!("image/jpeg,image/png,image/webp")),
            )
            .element(
                "submit_btn",
                Element::new("Button")
                    .prop("label", json!("Salva"))
                    .prop("button_type", json!("submit")),
            )
            .build()
            .expect("spec builds");

        let html = crate::render::render_spec_to_html(&spec, &serde_json::Value::Null);
        assert!(
            html.contains("enctype=\"multipart/form-data\""),
            "form must emit enctype; got: {html}"
        );
        assert!(
            html.contains("type=\"file\""),
            "avatar input must emit type=file; got: {html}"
        );
        assert!(
            html.contains("accept=\"image/jpeg,image/png,image/webp\""),
            "avatar input must emit accept; got: {html}"
        );
        assert!(
            html.contains("type=\"text\""),
            "name input must emit type=text; got: {html}"
        );
        assert!(
            html.contains("type=\"submit\""),
            "submit button must emit type=submit; got: {html}"
        );
    }

    // ── Switch depth-8 regression (F1 + F4 closure) ──────────────────────

    #[test]
    fn switch_at_depth_8_renders_role_switch() {
        // Consumer's staff-detail nesting:
        // dashboard (depth 1) → root layout (2) → DetailPage (3) → Tabs (4)
        // → Card (5) → Form (6) → Grid (7, "row") → Switch (8)
        //
        // Before Phase 175-01 (F1): MAX_NESTING_DEPTH = 5 → the walker tripwire
        // fired at depth 7+, emitting a "depth limit exceeded" comment instead of
        // dispatching to render_switch. The consumer's Switch was invisibly stripped.
        //
        // After Phase 175-01: MAX_NESTING_DEPTH = 16 → depth 8 is well within
        // the limit, dispatch reaches render_switch, and the role="switch" markup
        // emerges.
        //
        // This test pins the F1+F4 closure: if a future regression lowers the
        // depth limit below 8 or breaks Switch dispatch, this test fires.
        // Spec::builder() validates structure at build() time — a DepthExceeded
        // error here means MAX_NESTING_DEPTH was reverted below 8.
        let spec = Spec::builder()
            // depth 1: g1 → g2
            .element(
                "g1",
                Element::new("Grid").prop("columns", json!(1)).child("g2"),
            )
            // depth 2: g2 → g3
            .element(
                "g2",
                Element::new("Grid").prop("columns", json!(1)).child("g3"),
            )
            // depth 3: g3 → g4
            .element(
                "g3",
                Element::new("Grid").prop("columns", json!(1)).child("g4"),
            )
            // depth 4: g4 → g5
            .element(
                "g4",
                Element::new("Grid").prop("columns", json!(1)).child("g5"),
            )
            // depth 5: g5 → g6
            .element(
                "g5",
                Element::new("Grid").prop("columns", json!(1)).child("g6"),
            )
            // depth 6: g6 → g7
            .element(
                "g6",
                Element::new("Grid").prop("columns", json!(1)).child("g7"),
            )
            // depth 7: g7 → leaf
            .element(
                "g7",
                Element::new("Grid").prop("columns", json!(1)).child("leaf"),
            )
            // depth 8: Switch leaf (the consumer's per-day open/closed toggle)
            .element(
                "leaf",
                Element::new("Switch")
                    .prop("field", json!("day_1_is_open"))
                    .prop("label", json!("Aperto")),
            )
            .build()
            .expect("depth-8 spec must build after Phase 175-01 raises MAX_NESTING_DEPTH to 16");

        let html = crate::render::render_spec_to_html(&spec, &serde_json::Value::Null);

        assert!(
            html.contains("role=\"switch\""),
            "Switch at depth 8 must render role=\"switch\"; got: {html}"
        );
        assert!(
            !html.contains("depth limit exceeded"),
            "Switch at depth 8 must not be stripped by the walker tripwire; got: {html}"
        );
        assert!(
            !html.contains("cycle guard tripped"),
            "Walker tripwire must not emit the deprecated cycle-guard diagnostic; got: {html}"
        );
    }

    // ── CheckboxGroup (alias for CheckboxList) ────────────────────────────

    #[test]
    fn checkbox_group_renders_fieldset() {
        // CheckboxGroup dispatches to render_checkbox_list — same props, same renderer.
        // A spec with type "CheckboxGroup" must produce a <fieldset> with N
        // <input type="checkbox"> children whose name attributes carry the field name.
        let el = mk_element(
            "CheckboxGroup",
            json!({
                "field": "copy_to",
                "label": "Copia su",
                "options": [
                    {"value": "tue", "label": "Martedì"},
                    {"value": "wed", "label": "Mercoledì"}
                ]
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = crate::render::render_spec_to_html(&spec, &serde_json::Value::Null);
        assert!(
            html.contains("<fieldset"),
            "CheckboxGroup must render a <fieldset>; got: {html}"
        );
        assert!(
            html.contains("type=\"checkbox\""),
            "CheckboxGroup must render <input type=\"checkbox\"> children; got: {html}"
        );
        assert!(
            html.contains("name=\"copy_to\""),
            "CheckboxGroup must emit a name attribute on its children; got: {html}"
        );
        assert_eq!(
            html.matches("<input type=\"checkbox\"").count(),
            2,
            "expected 2 checkboxes for 2 options; got: {html}"
        );
    }

    // ── Plan 08: fjui- classes for Input/Select/Textarea/FormSection/FormGroup ──

    /// D-08 migration: render_input emits fjui-input class.
    #[test]
    fn input_emits_fjui_input_class() {
        let el = mk_element("Input", json!({"field": "email", "label": "Email"}));
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("fjui-input"),
            "render_input must emit fjui-input class; got: {html}"
        );
    }

    /// D-08 migration: render_input with error emits fjui-input--error modifier.
    #[test]
    fn input_with_error_emits_fjui_input_error_modifier() {
        let el = mk_element(
            "Input",
            json!({"field": "email", "label": "Email", "error": "required"}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("fjui-input--error"),
            "input with error must emit fjui-input--error; got: {html}"
        );
    }

    /// D-08 migration: render_select emits fjui-select class.
    #[test]
    fn select_emits_fjui_select_class() {
        let el = mk_element(
            "Select",
            json!({
                "field": "role",
                "label": "Role",
                "options": [{"value": "a", "label": "A"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_select(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("fjui-select"),
            "render_select must emit fjui-select class; got: {html}"
        );
    }

    /// D-08 migration: render_input (textarea) emits fjui-textarea class.
    #[test]
    fn textarea_emits_fjui_textarea_class() {
        let el = mk_element(
            "Input",
            json!({"field": "notes", "label": "Notes", "input_type": "textarea"}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("fjui-textarea"),
            "textarea input must emit fjui-textarea class; got: {html}"
        );
    }

    /// D-08 migration: error message paragraph emits fjui-form-message--error.
    #[test]
    fn input_error_paragraph_emits_fjui_form_message_error() {
        let el = mk_element(
            "Input",
            json!({"field": "email", "label": "Email", "error": "is required"}),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_input(&el, &spec, &json!({}), 1);
        assert!(
            html.contains("fjui-form-message--error"),
            "error paragraph must emit fjui-form-message--error class; got: {html}"
        );
    }

    // ── Select / Combobox ────────────────────────────────────────────────

    /// Searchable=true must produce the combobox overlay markup with the native
    /// select as a hidden form value carrier.
    #[test]
    fn searchable_true_emits_combobox_markup() {
        let el = mk_element(
            "Select",
            json!({
                "field": "customer_id",
                "label": "Cliente",
                "searchable": true,
                "options": [
                    {"value": "1", "label": "Alice"},
                    {"value": "2", "label": "Bob"}
                ]
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_select(&el, &spec, &json!({}), 1);

        // Native select must be hidden as form value carrier.
        assert!(
            html.contains("data-combobox-native"),
            "hidden native select must carry data-combobox-native; got: {html}"
        );
        assert!(
            html.contains("class=\"sr-only\""),
            "native select must have class=sr-only; got: {html}"
        );

        // Combobox wrapper and input ARIA.
        assert!(
            html.contains("data-combobox"),
            "combobox wrapper must carry data-combobox; got: {html}"
        );
        assert!(
            html.contains("role=\"combobox\""),
            "filter input must carry role=combobox; got: {html}"
        );
        assert!(
            html.contains("aria-autocomplete=\"list\""),
            "filter input must carry aria-autocomplete=list; got: {html}"
        );

        // Stable option ids — index-based, never value-based.
        assert!(
            html.contains("id=\"fjui-combo-opt-customer_id-0\""),
            "first option must have stable id fjui-combo-opt-customer_id-0; got: {html}"
        );
        assert!(
            html.contains("id=\"fjui-combo-opt-customer_id-1\""),
            "second option must have stable id fjui-combo-opt-customer_id-1; got: {html}"
        );

        // No diagnostic comments in the happy path.
        assert!(
            !html.contains("<!-- ferro-json-ui:"),
            "no diagnostic comments in happy path; got: {html}"
        );
    }

    /// Searchable=false (or None) must preserve the original native select unchanged.
    #[test]
    fn searchable_false_emits_native_select_only() {
        let el = mk_element(
            "Select",
            json!({
                "field": "status",
                "label": "Stato",
                "options": [{"value": "a", "label": "Active"}]
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_select(&el, &spec, &json!({}), 1);

        assert!(
            !html.contains("data-combobox"),
            "non-searchable select must not emit combobox markup; got: {html}"
        );
        assert!(
            html.contains("class=\"fjui-select"),
            "non-searchable select must keep fjui-select class; got: {html}"
        );
    }
}