ferro-json-ui 0.3.4

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
//! Data-display renderers: `Table` and `DataTable`.
//!
//! Each function reads typed props, escapes and substitutes cell values, and
//! emits HTML. Per-row actions resolve URL placeholders against the row's
//! data at render time. Data resolution is routed through
//! [`crate::data::resolve_path`].
//!
//! Behaviors worth flagging for spec authors:
//! - **DataTable `row_key` / `id` URL templating** — row-action URLs have
//!   the placeholders `{row_key}` and `{id}` substituted against the row's
//!   data before emission. When the `row_key` prop is unset, the fallback
//!   is the row index.
//! - **Table empty-state** — when `data_path` resolves to an array but it
//!   is empty, `props.empty_message` is emitted as a single spanning
//!   `<td>`.

use serde_json::Value;

use crate::component::{
    Column, ColumnAlign, ColumnFormat, DataTableProps, DropdownMenuAction, MediaCardGridProps,
    TableProps, Tone,
};
use crate::data::resolve_path;
use crate::spec::{Element, Spec};

use super::atoms::{badge_inline_html, render_menu_item};
use super::classes::INTERACTIVE_BASE;
use super::html_escape;

/// Renders a simple `Table` element. Reads `TableProps.columns` and
/// resolves rows from `TableProps.data_path`. When `row_actions` is set,
/// an `Azioni` header column is appended and each row receives one
/// `<a href="...">` per action.
pub(crate) fn render_table(el: &Element, _spec: &Spec, data: &Value, _depth: usize) -> String {
    let props: TableProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode Table props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    let mut html = String::from(
        "<div class=\"overflow-x-auto\"><table class=\"min-w-full divide-y divide-border\">",
    );

    // Header.
    html.push_str("<thead class=\"bg-surface\"><tr>");
    for col in &props.columns {
        html.push_str(&format!(
            "<th class=\"px-4 py-2 text-left text-xs font-medium uppercase tracking-wider text-text-muted\">{}</th>",
            html_escape(&col.label)
        ));
    }
    if props.row_actions.is_some() {
        html.push_str(
            "<th class=\"px-4 py-2 text-right text-xs font-medium uppercase tracking-wider text-text-muted\">Azioni</th>"
        );
    }
    html.push_str("</tr></thead>");

    // Body.
    html.push_str("<tbody class=\"divide-y divide-border bg-background\">");

    let rows = resolve_path(data, &props.data_path);
    let row_array = rows.and_then(|v| v.as_array());

    if let Some(items) = row_array {
        if items.is_empty() {
            if let Some(ref msg) = props.empty_message {
                let col_count =
                    props.columns.len() + if props.row_actions.is_some() { 1 } else { 0 };
                html.push_str(&format!(
                    "<tr><td colspan=\"{}\" class=\"px-4 py-4 text-center text-sm text-text-muted\">{}</td></tr>",
                    col_count,
                    html_escape(msg)
                ));
            }
        } else {
            for row in items {
                html.push_str("<tr class=\"hover:bg-surface\">");
                for col in &props.columns {
                    let cell_text = cell_string(row.get(&col.key));
                    html.push_str(&format!(
                        "<td class=\"px-4 py-2 text-sm text-text whitespace-nowrap\">{}</td>",
                        html_escape(&cell_text)
                    ));
                }
                if let Some(ref actions) = props.row_actions {
                    html.push_str("<td class=\"px-4 py-2 text-right text-sm space-x-2\">");
                    for action in actions {
                        let url = action.url.as_deref().unwrap_or("#");
                        let handler_str = action.handler.as_str();
                        let label = handler_str.split('.').next_back().unwrap_or(handler_str);
                        html.push_str(&format!(
                            "<a href=\"{}\" class=\"text-primary hover:text-primary/80 {INTERACTIVE_BASE}\">{}</a>",
                            html_escape(url),
                            html_escape(label)
                        ));
                    }
                    html.push_str("</td>");
                }
                html.push_str("</tr>");
            }
        }
    } else if let Some(ref msg) = props.empty_message {
        let col_count = props.columns.len() + if props.row_actions.is_some() { 1 } else { 0 };
        html.push_str(&format!(
            "<tr><td colspan=\"{}\" class=\"px-4 py-4 text-center text-sm text-text-muted\">{}</td></tr>",
            col_count,
            html_escape(msg)
        ));
    }

    html.push_str("</tbody></table></div>");
    html
}

/// Renders a `DataTable`. Supports declarative columns with formatters,
/// per-row actions wrapped in a portal-mode dropdown (positioned with
/// `position: fixed` so it escapes the table wrapper's overflow), optional search
/// bar, and per-row visibility filters. Emits a stripe-style desktop table
/// with alternating rows plus a mobile card fallback.
///
/// URL templating: row-action URLs containing `{row_key}` or `{id}` are
/// substituted against the row's value for `props.row_key` (default: row
/// index) and the row's `id` field respectively. Any other `{column_key}`
/// placeholder is substituted against the matching column value on each
/// row before emission.
/// Tailwind text-alignment class for a column. Defaults to left.
fn col_align_class(align: Option<ColumnAlign>) -> &'static str {
    match align {
        Some(ColumnAlign::Right) => "text-right",
        Some(ColumnAlign::Center) => "text-center",
        _ => "text-left",
    }
}

pub(crate) fn render_data_table(el: &Element, _spec: &Spec, data: &Value, _depth: usize) -> String {
    let props: DataTableProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode DataTable props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    let rows = resolve_path(data, &props.data_path);
    let items: Vec<Value> = rows.and_then(|v| v.as_array().cloned()).unwrap_or_default();
    let has_actions = props.row_actions.is_some();
    let col_count = props.columns.len() + if has_actions { 1 } else { 0 };
    let empty_msg = props
        .empty_message
        .as_deref()
        .unwrap_or("Nessun elemento trovato");

    let mut html = String::new();

    // Empty short-circuit: emit a single centered card with the description
    // text. Replaces the prior empty-table-row + mobile-empty-div split with
    // one shared, table-less visual so the empty state reads as a deliberate
    // placeholder rather than a degenerate table.
    if items.is_empty() {
        let _ = col_count; // silence unused — column count irrelevant when empty
        return format!(
            "<div class=\"fjui-empty-state\">\
             <p class=\"fjui-empty-state__title\">{}</p>\
             </div>",
            html_escape(empty_msg)
        );
    }

    // Desktop table (hidden on mobile).
    // D-08 migration Plan 07: TABLE SHELL uses fjui-table, fjui-table__header,
    // fjui-table__header-cell. Row/cell classes are Plan 08 scope (data.rs body).
    // The outer wrapper is a flat container (fjui-card border-only, LANG-04).
    html.push_str("<div class=\"hidden md:block fjui-card overflow-hidden\">");

    {
        if props.bulk_select.unwrap_or(false) {
            html.push_str("<table class=\"fjui-table\" data-bulk-select-table>");
        } else {
            html.push_str("<table class=\"fjui-table\">");
        }

        // Header shell — Plan 07 scope.
        html.push_str("<thead class=\"fjui-table__header\"><tr>");
        if props.bulk_select.unwrap_or(false) {
            html.push_str(
                "<th class=\"fjui-table__header-cell fjui-table__bulk-select-checkbox\">\
                 <input type=\"checkbox\" aria-label=\"Seleziona tutti\" class=\"cursor-pointer\" />\
                 </th>",
            );
        }
        for col in &props.columns {
            html.push_str(&format!(
                "<th class=\"fjui-table__header-cell {}\">{}",
                col_align_class(col.align),
                html_escape(&col.label)
            ));
            html.push_str("</th>");
        }
        if has_actions {
            html.push_str("<th class=\"fjui-table__header-cell text-right\">Azioni</th>");
        }
        html.push_str("</tr></thead>");

        // Body rows — Plan 08: fjui-table__body + fjui-table__row + fjui-table__cell (D-08).
        // Zebra striping removed (RSK-01); hairline separator + hover surface in skin layer.
        html.push_str("<tbody class=\"fjui-table__body\">");
        for (index, row) in items.iter().enumerate() {
            let row_key_value = resolve_row_key(row, props.row_key.as_deref(), index);
            let row_href = props
                .row_href
                .as_deref()
                .map(|tmpl| template_url(tmpl, row, &row_key_value));
            let (extra_class, click_attrs) = if let Some(ref href) = row_href {
                let onclick = format!(
                    " onclick=\"if(!event.target.closest('button,a,input,label,[popovertarget],[popover]'))window.location.assign(this.dataset.rowHref)\" data-row-href=\"{}\"",
                    html_escape(href)
                );
                (" cursor-pointer", onclick)
            } else if props.row_actions.is_some() {
                let onclick = format!(
                    " onclick=\"if(!event.target.closest('button,a,input,label,[popovertarget],[popover]'))document.getElementById('dt-{}').showPopover()\"",
                    html_escape(&row_key_value)
                );
                (" cursor-pointer", onclick)
            } else {
                ("", String::new())
            };
            // fjui-table__row: skin owns hover surface + hairline separator + transition.
            // Layout-only utilities (cursor-pointer) remain inline per D-02 allowlist.
            html.push_str(&format!(
                "<tr class=\"fjui-table__row{extra_class}\"{click_attrs}>"
            ));
            if props.bulk_select.unwrap_or(false) {
                html.push_str(&format!(
                    "<td class=\"fjui-table__cell fjui-table__bulk-select-checkbox\">\
                     <input type=\"checkbox\" data-row-key=\"{}\" class=\"cursor-pointer\" />\
                     </td>",
                    html_escape(&row_key_value)
                ));
            }
            // Resolve the row id for peek-card data-peek-id attribute (when any column
            // opts into peek via peek_entity). Falls back to row_key_value when no id field.
            let row_id_str = row
                .get("id")
                .and_then(|v| match v {
                    Value::String(s) => Some(s.clone()),
                    Value::Number(n) => Some(n.to_string()),
                    _ => None,
                })
                .unwrap_or_else(|| row_key_value.clone());
            for col in &props.columns {
                // Numeric columns (currency, date, datetime) get the --numeric modifier for
                // font-variant-numeric: tabular-nums + right-align (LANG-03).
                // Boolean columns get the --boolean modifier and render a status dot.
                let cell_class = match col.format {
                    Some(ColumnFormat::Currency | ColumnFormat::Date | ColumnFormat::DateTime) => {
                        "fjui-table__cell fjui-table__cell--numeric"
                    }
                    Some(ColumnFormat::Boolean) => "fjui-table__cell fjui-table__cell--boolean",
                    _ => "fjui-table__cell",
                };
                // When peek_entity is set AND the row has a href, wrap the cell content in
                // an <a> with data-peek-entity + data-peek-id so the peek overlay fires.
                // Full-literal class name per D-01 (246 lock).
                let cell_content =
                    if let (Some(ref entity), Some(ref href)) = (&col.peek_entity, &row_href) {
                        format!(
                            "<a href=\"{}\" class=\"fjui-table__link\" \
                         data-peek-entity=\"{}\" data-peek-id=\"{}\">{}</a>",
                            html_escape(href),
                            html_escape(entity),
                            html_escape(&row_id_str),
                            render_cell(col, row.get(&col.key))
                        )
                    } else {
                        render_cell(col, row.get(&col.key))
                    };
                html.push_str(&format!(
                    "<td class=\"{} {}\">{}</td>",
                    cell_class,
                    col_align_class(col.align),
                    cell_content
                ));
            }
            if let Some(ref actions) = props.row_actions {
                let templated = template_actions(actions, row, &row_key_value);
                html.push_str("<td class=\"fjui-table__cell text-right\">");
                html.push_str(&render_inline_dropdown(
                    &format!("dt-{row_key_value}"),
                    &templated,
                ));
                html.push_str("</td>");
            }
            html.push_str("</tr>");
        }
        html.push_str("</tbody></table>");
    }
    html.push_str("</div>");

    // Mobile cards (visible on mobile). Empty is handled by the early
    // short-circuit above; reaching here implies at least one row.
    // Mobile card rows use fjui-card (flat surface, border-only, LANG-04).
    html.push_str("<div class=\"block md:hidden space-y-3\">");
    {
        for (index, row) in items.iter().enumerate() {
            let row_key_value = resolve_row_key(row, props.row_key.as_deref(), index);
            let row_href = props
                .row_href
                .as_deref()
                .map(|tmpl| template_url(tmpl, row, &row_key_value));
            let (open_tag, close_tag) = if let Some(ref href) = row_href {
                // Navigate via a div + onclick (mirrors the desktop <tr>), NOT an
                // <a> wrapper: the row-actions dropdown emits a <button>, and a
                // <button> nested inside an <a> is invalid HTML. The browser's
                // parser splits the anchor and re-applies the card classes to each
                // fragment, shattering the mobile card (empty box + title-in-a-box
                // + kebab-in-a-box). A div carries the same click-navigation and
                // legally contains the button.
                (
                    format!(
                        "<div class=\"fjui-card p-4 space-y-2 hover:bg-surface/60 cursor-pointer {INTERACTIVE_BASE}\" onclick=\"if(!event.target.closest('button,a,input,label,[popovertarget],[popover]'))window.location.assign(this.dataset.rowHref)\" data-row-href=\"{}\">",
                        html_escape(href)
                    ),
                    "</div>".to_string(),
                )
            } else if props.row_actions.is_some() {
                (
                    format!(
                        "<div class=\"fjui-card p-4 space-y-2 cursor-pointer\" onclick=\"if(!event.target.closest('button,a,input,label,[popovertarget],[popover]'))document.getElementById('dt-m-{}').showPopover()\">",
                        html_escape(&row_key_value)
                    ),
                    "</div>".to_string(),
                )
            } else {
                (
                    "<div class=\"fjui-card p-4 space-y-2\">".to_string(),
                    "</div>".to_string(),
                )
            };
            html.push_str(&open_tag);
            // Mobile list-item: the first column is the prominent title (with
            // the row action on the same line); the remaining columns form a
            // compact muted meta block beneath it. This replaces the prior
            // fully-transposed label/value stack, which gave the entity name no
            // more weight than its metadata and produced tall, low-scannability
            // cards.
            html.push_str("<div class=\"flex items-start justify-between gap-3\">");
            if let Some(first) = props.columns.first() {
                html.push_str(&format!(
                    "<div class=\"min-w-0 flex-1 fjui-text--body font-semibold truncate\">{}</div>",
                    render_cell(first, row.get(&first.key))
                ));
            }
            if let Some(ref actions) = props.row_actions {
                let templated = template_actions(actions, row, &row_key_value);
                html.push_str("<div class=\"shrink-0 -mt-1 -mr-1\">");
                html.push_str(&render_inline_dropdown(
                    &format!("dt-m-{row_key_value}"),
                    &templated,
                ));
                html.push_str("</div>");
            }
            html.push_str("</div>");
            if props.columns.len() > 1 {
                html.push_str("<div class=\"mt-2 space-y-1\">");
                for col in props.columns.iter().skip(1) {
                    html.push_str(&format!(
                        "<div class=\"flex justify-between gap-3 fjui-text--micro\"><span class=\"fjui-text--meta\">{}</span><span class=\"text-right\">{}</span></div>",
                        html_escape(&col.label),
                        render_cell(col, row.get(&col.key))
                    ));
                }
                html.push_str("</div>");
            }
            html.push_str(&close_tag);
        }
    }
    html.push_str("</div>");

    html
}

/// Renders a single cell's value as a plain string. Handles strings,
/// numbers, booleans, and nulls directly; arrays and objects round-trip
/// through `serde_json::to_string`.
fn cell_string(v: Option<&Value>) -> String {
    match v {
        Some(Value::String(s)) => s.clone(),
        Some(Value::Number(n)) => n.to_string(),
        Some(Value::Bool(b)) => b.to_string(),
        Some(Value::Null) | None => String::new(),
        Some(v @ Value::Array(_)) | Some(v @ Value::Object(_)) => {
            serde_json::to_string(v).unwrap_or_default()
        }
    }
}

/// Render a single DataTable cell. Dispatches on `col.format`:
///
/// - `Some(ColumnFormat::Badge)` reads the cell as `{tone, label}` and
///   emits a Badge `<span>` (shared shape with the standalone `Badge`
///   component via [`badge_inline_html`]). Invalid values emit an HTML
///   comment diagnostic instead of falling back to text — a typed column
///   that silently rendered raw JSON would hide real spec bugs.
/// - All other formats (including absent) emit the existing
///   `html_escape(cell_string(...))` text.
///
/// The Badge cell intentionally bypasses `html_escape` on the wrapper markup
/// because the markup is server-controlled (no caller input flows through
/// the class names or `<span>` chrome). The `label` itself IS html-escaped
/// inside `badge_inline_html`.
fn render_cell(col: &Column, value: Option<&Value>) -> String {
    if let Some(ColumnFormat::Badge) = col.format {
        // Cell must be an object `{tone, label}` (or absent — empty cell).
        match value {
            None | Some(Value::Null) => return String::new(),
            Some(v @ Value::Object(_)) => {
                #[derive(serde::Deserialize)]
                struct BadgeCell {
                    tone: Tone,
                    label: String,
                }
                match serde_json::from_value::<BadgeCell>(v.clone()) {
                    Ok(cell) => return badge_inline_html(cell.tone, &cell.label),
                    Err(e) => {
                        return format!(
                            "<!-- ferro-json-ui: invalid Badge cell value: {} -->",
                            html_escape(&e.to_string())
                        );
                    }
                }
            }
            Some(_) => {
                return format!(
                    "<!-- ferro-json-ui: invalid Badge cell value: expected object {{tone, label}}, got {} -->",
                    html_escape(&cell_string(value))
                );
            }
        }
    }
    if let Some(ColumnFormat::Image) = col.format {
        // Cell value is an image URL string. Null or empty → empty cell (no broken img).
        // The URL is html-escaped before interpolation to prevent src attribute injection
        // (T-213-09).
        match value {
            None | Some(Value::Null) => return String::new(),
            Some(_) => {
                let url = cell_string(value);
                if url.is_empty() {
                    return String::new();
                }
                return format!(
                    "<img src=\"{}\" alt=\"\" class=\"w-8 h-8 rounded-full object-cover\" />",
                    html_escape(&url)
                );
            }
        }
    }
    if let Some(ColumnFormat::Icon) = col.format {
        // Cell value is a built-in icon name; rendered as an inline outline SVG
        // that inherits currentColor. Unknown/empty names render nothing (no
        // raw HTML from the cell value — the name only selects a fixed SVG, so
        // there is no injection surface).
        let name = cell_string(value);
        return match builtin_icon_svg(&name) {
            Some(svg) => format!(
                "<span class=\"inline-flex items-center text-text-muted\" aria-hidden=\"true\">{svg}</span>"
            ),
            None => String::new(),
        };
    }
    if let Some(ColumnFormat::Boolean) = col.format {
        // true → success dot + label_true; false/null → muted dot + label_false.
        // Full-literal class strings per D-01 (no dynamic class assembly).
        // label_true/label_false are html-escaped (T-247-02-01).
        let label_true = col.label_true.as_deref().unwrap_or("");
        let label_false = col.label_false.as_deref().unwrap_or("No");
        let is_true = match value {
            Some(Value::Bool(b)) => *b,
            Some(Value::Number(n)) => n.as_i64() == Some(1),
            _ => false,
        };
        return if is_true {
            format!(
                "<span class=\"fjui-status-dot fjui-status-dot--true\">{}</span>",
                html_escape(label_true)
            )
        } else {
            format!(
                "<span class=\"fjui-status-dot fjui-status-dot--false\">{}</span>",
                html_escape(label_false)
            )
        };
    }
    html_escape(&cell_string(value))
}

/// Built-in outline icons for `ColumnFormat::Icon`. Lucide-derived, 20×20,
/// `currentColor` stroke so they match the surrounding text color. Returns
/// `None` for unknown names (renders an empty cell). The cell value selects an
/// entry by name — it is never interpolated as markup, so this is injection-safe.
fn builtin_icon_svg(name: &str) -> Option<&'static str> {
    match name {
        "folder" => Some(
            "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z\"/></svg>",
        ),
        "file" => Some(
            "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z\"/><path d=\"M14 2v4a2 2 0 0 0 2 2h4\"/></svg>",
        ),
        "image" => Some(
            "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" ry=\"2\"/><circle cx=\"9\" cy=\"9\" r=\"2\"/><path d=\"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21\"/></svg>",
        ),
        _ => None,
    }
}

/// Substitute placeholders in a URL template against a row.
///
/// Mirrors the placeholder resolution of `template_actions` so the row-level
/// `props.row_href` URL is computed with the same rules as
/// `row_actions[].action.url`:
///
/// 1. `{col_key}` — every key in the row object substitutes its value.
/// 2. `{row_key}` — resolved against `row_key_value`.
/// 3. `{id}` — resolved against `row["id"]` when present.
///
/// Missing placeholders are left unsubstituted.
fn template_url(template: &str, row: &Value, row_key_value: &str) -> String {
    let mut url = template.to_string();
    if let Some(obj) = row.as_object() {
        for (col_key, col_val) in obj {
            let val_str = match col_val {
                Value::String(s) => s.clone(),
                Value::Number(n) => n.to_string(),
                _ => continue,
            };
            url = url.replace(&format!("{{{col_key}}}"), &val_str);
            url = url.replace(&format!("{{row.{col_key}}}"), &val_str);
        }
    }
    url = url.replace("{row_key}", row_key_value);
    if let Some(id) = row.get("id").and_then(|v| match v {
        Value::String(s) => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        _ => None,
    }) {
        url = url.replace("{id}", &id);
    }
    url
}

/// Resolves the row key for a single row. Reads the value at
/// `props.row_key` from the row when present and stringifiable, otherwise
/// falls back to the row index.
pub(crate) fn resolve_row_key(row: &Value, row_key_prop: Option<&str>, index: usize) -> String {
    if let Some(rk) = row_key_prop {
        if let Some(v) = row.get(rk) {
            match v {
                Value::String(s) => return s.clone(),
                Value::Number(n) => return n.to_string(),
                _ => {}
            }
        }
    }
    index.to_string()
}

/// Templates row-action URLs for a single row.
///
/// Substitution order:
/// 1. All column keys present in the row object (`{label}`, `{slug_path}`,
///    …). Only `String` and `Number` values are substituted; booleans,
///    nulls, arrays, and objects are skipped.
/// 2. `{row_key}` — resolved against `row_key_value`.
/// 3. `{id}` — resolved against `row["id"]` when present.
///
/// Missing placeholders (no matching column, and not `{row_key}` / `{id}`)
/// are left unsubstituted — no panic, no silent removal.
/// Returns `true` iff a row-action item should appear for this row.
///
/// - No `visible_if` declared → always visible (backwards compat).
/// - `visible_if = Some(field)` and `row[field]` is truthy → visible.
///   Truthy = `true` / non-zero number / non-empty string / non-empty array
///   or object.
/// - `visible_if = Some(field)` and `row[field]` is missing, null, false,
///   `0`, or empty → hidden. **Fail-closed** so a typo in the field name
///   cannot leak an action onto every row.
fn action_visible_for_row(action: &DropdownMenuAction, row: &Value) -> bool {
    let Some(field) = action.visible_if.as_deref() else {
        return true;
    };
    match row.get(field) {
        None | Some(Value::Null) => false,
        Some(Value::Bool(b)) => *b,
        Some(Value::Number(n)) => {
            if let Some(i) = n.as_i64() {
                i != 0
            } else if let Some(f) = n.as_f64() {
                f != 0.0
            } else {
                false
            }
        }
        Some(Value::String(s)) => !s.is_empty(),
        Some(Value::Array(a)) => !a.is_empty(),
        Some(Value::Object(o)) => !o.is_empty(),
    }
}

pub(crate) fn template_actions(
    actions: &[DropdownMenuAction],
    row: &Value,
    row_key_value: &str,
) -> Vec<DropdownMenuAction> {
    let id_value: Option<String> = row.get("id").and_then(|v| match v {
        Value::String(s) => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        _ => None,
    });

    actions
        .iter()
        .filter(|a| action_visible_for_row(a, row))
        .map(|a| {
            let mut cloned = a.clone();
            // URL fallback: when the action has no explicit `url`, use the
            // handler name as the base.
            let base_url = cloned
                .action
                .url
                .clone()
                .or_else(|| Some(cloned.action.handler.as_str().to_string()));
            if let Some(mut url) = base_url {
                // Substitute all row column keys first.
                if let Some(obj) = row.as_object() {
                    for (col_key, col_val) in obj {
                        let val_str = match col_val {
                            Value::String(s) => s.clone(),
                            Value::Number(n) => n.to_string(),
                            _ => continue,
                        };
                        url = url.replace(&format!("{{{col_key}}}"), &val_str);
                        url = url.replace(&format!("{{row.{col_key}}}"), &val_str);
                    }
                }
                // `{row_key}` substitutes against the value at `props.row_key`.
                url = url.replace("{row_key}", row_key_value);
                if let Some(ref id) = id_value {
                    url = url.replace("{id}", id);
                }
                cloned.action.url = Some(url);
            }
            cloned
        })
        .collect()
}

/// Minimal self-contained dropdown used for row actions. Emits HTML popover
/// markup (`popovertarget` + `popover`); `runtime/dropdowns.rs` anchors the
/// panel under its trigger on open. The browser handles dismiss and lifts
/// the panel into the top layer, so the surrounding DataTable overflow
/// context cannot clip it.
pub(crate) fn render_inline_dropdown(menu_id: &str, items: &[DropdownMenuAction]) -> String {
    let id = html_escape(menu_id);
    let mut html = String::new();
    html.push_str(&format!(
        "<button type=\"button\" popovertarget=\"{id}\" aria-haspopup=\"menu\" aria-label=\"Azioni\" class=\"cursor-pointer select-none inline-flex h-5 items-center justify-center px-2 rounded-md text-text-muted hover:text-text {INTERACTIVE_BASE}\">\u{22EE}</button>"
    ));
    html.push_str(&format!(
        "<div popover id=\"{id}\" data-popover-menu class=\"min-w-[10rem] rounded-md border border-border bg-card shadow-md text-left p-0\" role=\"menu\">"
    ));
    for item in items {
        // D-01: fjui-menu-item full literals. Appearance moved to skin layer.
        html.push_str(&render_menu_item(
            item,
            "fjui-menu-item",
            "fjui-menu-item fjui-menu-item--destructive",
            " role=\"menuitem\"",
        ));
    }
    html.push_str("</div>");
    html
}

/// Renders a `MediaCardGrid`. Each item in `data_path` becomes a card with
/// an optional screenshot image, title, description, status badge, and
/// per-row dropdown actions. URL placeholders follow the same `{row_key}`
/// / `{id}` interpolation rules as `DataTable`.
pub(crate) fn render_media_card_grid(
    el: &Element,
    _spec: &Spec,
    data: &Value,
    _depth: usize,
) -> String {
    let props: MediaCardGridProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode MediaCardGrid props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    let rows = resolve_path(data, &props.data_path);
    let items: Vec<Value> = rows.and_then(|v| v.as_array().cloned()).unwrap_or_default();
    let empty_msg = props
        .empty_message
        .as_deref()
        .unwrap_or("Nessun elemento trovato");

    if items.is_empty() {
        return format!(
            "<div class=\"fjui-empty-state\">\
             <p class=\"fjui-empty-state__title\">{}</p>\
             </div>",
            html_escape(empty_msg)
        );
    }

    let col_class = match props.columns.unwrap_or(3) {
        2 => "grid-cols-1 md:grid-cols-2",
        4 => "grid-cols-1 md:grid-cols-2 lg:grid-cols-4",
        _ => "grid-cols-1 md:grid-cols-2 lg:grid-cols-3",
    };

    let mut html = format!("<div class=\"grid {col_class} gap-4\">");

    let aspect_ratio = props.image_aspect_ratio.as_deref().unwrap_or("4/5");
    let image_position = props.image_position.as_deref().unwrap_or("center");

    for (index, row) in items.iter().enumerate() {
        let row_key_value = resolve_row_key(row, props.row_key.as_deref(), index);

        let title = row
            .get(props.title_key.as_str())
            .and_then(|v| v.as_str())
            .unwrap_or("");

        let description = props
            .description_key
            .as_deref()
            .and_then(|k| row.get(k))
            .and_then(|v| v.as_str());

        let image_url = props
            .image_key
            .as_deref()
            .and_then(|k| row.get(k))
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty());

        let image_href = props
            .image_href_key
            .as_deref()
            .and_then(|k| row.get(k))
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty());

        let badge_label = props
            .badge_key
            .as_deref()
            .and_then(|k| row.get(k))
            .and_then(|v| v.as_str());

        // Parse the row value through the typed `Tone` enum so MediaCardGrid
        // and `badge_inline_html` cannot drift (T-251-01: the raw row value
        // never reaches a class attribute — invalid tones fall back to
        // `neutral`, and classes come from the shared exhaustive match).
        let badge_tone = props
            .badge_tone_key
            .as_deref()
            .and_then(|k| row.get(k))
            .and_then(|v| serde_json::from_value::<Tone>(v.clone()).ok())
            .unwrap_or_default();

        html.push_str("<div class=\"fjui-card overflow-hidden flex flex-col\">");

        // Image section. If image_key resolves to null/empty, render a blank
        // placeholder slot with the same aspect ratio so card heights stay
        // consistent across the grid.
        if props.image_key.is_some() {
            if let Some(img_src) = image_url {
                let img_tag = format!(
                    "<img src=\"{}\" alt=\"{}\" class=\"w-full object-cover\" style=\"aspect-ratio: {}; object-position: {};\" loading=\"lazy\">",
                    html_escape(img_src),
                    html_escape(title),
                    html_escape(aspect_ratio),
                    html_escape(image_position),
                );
                if let Some(href) = image_href {
                    html.push_str(&format!(
                        "<a href=\"{}\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"block overflow-hidden bg-surface shrink-0\">{}</a>",
                        html_escape(href),
                        img_tag
                    ));
                } else {
                    html.push_str(&format!(
                        "<div class=\"overflow-hidden bg-surface shrink-0\">{img_tag}</div>"
                    ));
                }
            } else {
                html.push_str(&format!(
                    "<div class=\"w-full bg-surface shrink-0\" style=\"aspect-ratio: {};\" aria-hidden=\"true\"></div>",
                    html_escape(aspect_ratio),
                ));
            }
        }

        // Body
        html.push_str("<div class=\"p-4 flex flex-col gap-1 flex-1\">");
        html.push_str(&format!(
            "<div class=\"text-sm font-semibold text-text\">{}</div>",
            html_escape(title)
        ));
        if let Some(desc) = description {
            html.push_str(&format!(
                "<div class=\"text-xs text-text-muted truncate\">{}</div>",
                html_escape(desc)
            ));
        }
        html.push_str("</div>");

        // Footer: badge + dropdown
        let has_badge = badge_label.is_some();
        let has_actions = props.row_actions.is_some();
        if has_badge || has_actions {
            html.push_str("<div class=\"px-4 pb-4 flex items-center justify-between gap-2\">");

            if let Some(label) = badge_label {
                html.push_str(&badge_inline_html(badge_tone, label));
            } else if has_actions {
                html.push_str("<span></span>");
            }

            if let Some(ref actions) = props.row_actions {
                let templated = template_actions(actions, row, &row_key_value);
                html.push_str(&render_inline_dropdown(
                    &format!("mcg-{row_key_value}"),
                    &templated,
                ));
            }

            html.push_str("</div>");
        }

        html.push_str("</div>"); // card
    }

    html.push_str("</div>"); // grid
    html
}

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

    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,
        }
    }

    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
    }

    // ── Table ────────────────────────────────────────────────────────────

    #[test]
    fn table_renders_rows_from_data_path() {
        let el = mk_element(
            "Table",
            json!({
                "data_path": "/users",
                "columns": [{"key": "name", "label": "Name"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"users": [{"name": "Alice"}, {"name": "Bob"}]});
        let html = render_table(&el, &spec, &data, 1);
        assert!(html.contains("Alice"), "got: {html}");
        assert!(html.contains("Bob"), "got: {html}");
        assert!(html.contains("<thead"), "got: {html}");
    }

    #[test]
    fn table_empty_rows_emits_empty_message() {
        let el = mk_element(
            "Table",
            json!({
                "data_path": "/users",
                "columns": [{"key": "name", "label": "Name"}],
                "empty_message": "No users found",
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"users": []});
        let html = render_table(&el, &spec, &data, 1);
        assert!(html.contains("No users found"), "got: {html}");
    }

    #[test]
    fn table_missing_path_emits_empty_message_when_provided() {
        let el = mk_element(
            "Table",
            json!({
                "data_path": "/absent",
                "columns": [{"key": "name", "label": "Name"}],
                "empty_message": "Nothing here",
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({});
        let html = render_table(&el, &spec, &data, 1);
        assert!(html.contains("Nothing here"), "got: {html}");
    }

    #[test]
    fn table_cell_value_is_html_escaped() {
        let el = mk_element(
            "Table",
            json!({
                "data_path": "/users",
                "columns": [{"key": "name", "label": "Name"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"users": [{"name": "<script>x</script>"}]});
        let html = render_table(&el, &spec, &data, 1);
        assert!(!html.contains("<script>x</script>"), "got: {html}");
        assert!(
            html.contains("&lt;script&gt;x&lt;/script&gt;"),
            "got: {html}"
        );
    }

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

    // ── DataTable ────────────────────────────────────────────────────────

    #[test]
    fn data_table_url_template_replaces_id() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/users",
                "columns": [{"key": "name", "label": "Name"}],
                "row_actions": [
                    {"label": "Edit", "action": {"handler": "edit", "url": "/users/{id}/edit", "method": "GET"}}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"users": [
            {"id": "1", "name": "Alice"},
            {"id": "2", "name": "Bob"},
        ]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("/users/1/edit"),
            "row 1 URL missing; got: {html}"
        );
        assert!(
            html.contains("/users/2/edit"),
            "row 2 URL missing; got: {html}"
        );
        assert!(
            !html.contains("/users/{id}/edit"),
            "{{id}} placeholder must be replaced; got: {html}"
        );
    }

    #[test]
    fn data_table_url_template_replaces_row_key() {
        // `{row_key}` substitutes against the value at `props.row_key` on
        // each row (falls back to the row index).
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/users",
                "row_key": "slug",
                "columns": [{"key": "slug", "label": "Slug"}],
                "row_actions": [
                    {"label": "Open", "action": {"handler": "show", "url": "/u/{row_key}", "method": "GET"}}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"users": [
            {"slug": "alice"},
            {"slug": "bob"},
        ]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(html.contains("/u/alice"), "got: {html}");
        assert!(html.contains("/u/bob"), "got: {html}");
    }

    #[test]
    fn data_table_empty_renders_empty_message() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/users",
                "columns": [{"key": "name", "label": "Name"}],
                "empty_message": "No rows",
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"users": []});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(html.contains("No rows"), "got: {html}");
    }

    #[test]
    fn data_table_default_empty_message_used_when_absent() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/users",
                "columns": [{"key": "name", "label": "Name"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"users": []});
        let html = render_data_table(&el, &spec, &data, 1);
        // The default empty message is "Nessun elemento trovato".
        assert!(html.contains("Nessun elemento trovato"), "got: {html}");
    }

    #[test]
    fn data_table_url_template_substitution_is_escaped() {
        // Attribute-breakout via a row's id field — the templated URL must
        // pass through html_escape before emission.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/users",
                "columns": [{"key": "name", "label": "Name"}],
                "row_actions": [
                    {"label": "Edit", "action": {"handler": "edit", "url": "/u/{id}", "method": "GET"}}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"users": [{"id": "\"><script>", "name": "x"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            !html.contains("><script>"),
            "attribute breakout; got: {html}"
        );
        assert!(html.contains("&quot;"), "got: {html}");
    }

    #[test]
    fn data_table_renders_desktop_and_mobile_markup() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/users",
                "columns": [{"key": "name", "label": "Name"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"users": [{"name": "Alice"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("hidden md:block"),
            "desktop wrapper; got: {html}"
        );
        assert!(
            html.contains("block md:hidden"),
            "mobile wrapper; got: {html}"
        );
    }

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

    // Extended placeholder interpolation tests.

    #[test]
    fn data_table_url_template_replaces_column_key() {
        // Any column key bound at render time is substituted in action URLs.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/pages",
                "columns": [{"key": "label", "label": "Label"}],
                "row_actions": [
                    {"label": "Edit", "action": {"handler": "edit", "url": "/p/{slug_path}/edit", "method": "GET"}}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"pages": [
            {"id": "7", "label": "Home", "slug_path": "/home"},
        ]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("/p//home/edit"),
            "expected /p//home/edit in output; got: {html}"
        );
        assert!(
            !html.contains("{slug_path}"),
            "{{slug_path}} placeholder must be replaced; got: {html}"
        );
    }

    #[test]
    fn data_table_url_template_replaces_multiple_keys() {
        // Multiple column keys in a single URL are all substituted.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/pages",
                "columns": [{"key": "label", "label": "Label"}],
                "row_actions": [
                    {"label": "View", "action": {"handler": "view", "url": "/p/{slug_path}/{status}", "method": "GET"}}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"pages": [
            {"id": "1", "label": "Home", "slug_path": "/home", "status": "draft"},
        ]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("/p//home/draft"),
            "expected /p//home/draft in output; got: {html}"
        );
    }

    #[test]
    fn data_table_post_row_action_emits_form_not_anchor() {
        // A row_action declaring `method: POST` must render as a real
        // `<form method="post">` with a submit `<button>`, not as an
        // `<a href>` that issues a GET request. Regression for the
        // dropped-method bug in `render_inline_dropdown`.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/items",
                "columns": [{"key": "name", "label": "Name"}],
                "row_actions": [{
                    "label": "Delete",
                    "action": {"handler": "destroy", "url": "/items/{id}", "method": "POST"},
                    "destructive": true,
                }],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"items": [{"id": "9", "name": "x"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("<form action=\"/items/9\" method=\"post\">"),
            "POST row_action must render a form; got: {html}"
        );
        assert!(
            html.contains("<button type=\"submit\""),
            "POST row_action must include a submit button; got: {html}"
        );
        assert!(
            !html.contains("<a href=\"/items/9\""),
            "POST row_action must not render an anchor (which would GET); got: {html}"
        );
    }

    #[test]
    fn data_table_delete_row_action_spoofs_method() {
        // PUT/PATCH/DELETE row_actions use POST + a `_method` hidden input
        // for HTTP method spoofing through the form submission.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/items",
                "columns": [{"key": "name", "label": "Name"}],
                "row_actions": [{
                    "label": "Delete",
                    "action": {"handler": "destroy", "url": "/items/{id}", "method": "DELETE"},
                }],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"items": [{"id": "9", "name": "x"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("<form action=\"/items/9\" method=\"post\">"),
            "DELETE row_action must render a POST form; got: {html}"
        );
        assert!(
            html.contains("name=\"_method\" value=\"DELETE\""),
            "DELETE row_action must spoof method via hidden input; got: {html}"
        );
    }

    #[test]
    fn data_table_get_row_action_still_emits_anchor() {
        // GET row_actions (the most common case — edit links) continue
        // to render as plain `<a href>` for navigation.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/items",
                "columns": [{"key": "name", "label": "Name"}],
                "row_actions": [{
                    "label": "Edit",
                    "action": {"handler": "edit", "url": "/items/{id}/edit", "method": "GET"},
                }],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"items": [{"id": "9", "name": "x"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("<a href=\"/items/9/edit\""),
            "GET row_action must render an anchor; got: {html}"
        );
        assert!(
            !html.contains("<form action=\"/items/9/edit\""),
            "GET row_action must not render a form; got: {html}"
        );
    }

    #[test]
    fn data_table_url_template_missing_key_leaves_placeholder() {
        // A placeholder with no matching column key is left as-is (no panic, no silent removal).
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/pages",
                "columns": [{"key": "label", "label": "Label"}],
                "row_actions": [
                    {"label": "Edit", "action": {"handler": "edit", "url": "/p/{nonexistent}/edit", "method": "GET"}}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"pages": [
            {"id": "1", "label": "Home"},
        ]});
        let html = render_data_table(&el, &spec, &data, 1);
        // {nonexistent} has no matching column — must remain literal in the URL.
        assert!(
            html.contains("{nonexistent}"),
            "missing-key placeholder must be left unsubstituted; got: {html}"
        );
    }

    // F6 — {row.X} prefix alias tests.

    #[test]
    fn data_table_row_prefix_placeholder_resolved() {
        // {row.delete_url} must resolve to the row's `delete_url` field value.
        // No literal curly braces or URL-encoded form must survive into the
        // rendered HTML.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/items",
                "columns": [{"key": "name", "label": "Name"}],
                "row_actions": [{
                    "label": "Delete",
                    "action": {
                        "handler": "destroy",
                        "url": "{row.delete_url}",
                        "method": "POST"
                    },
                    "destructive": true,
                }],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"items": [
            {"name": "Absence", "delete_url": "/dashboard/staff/1/assenze/3/elimina"},
        ]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("/dashboard/staff/1/assenze/3/elimina"),
            "resolved URL must appear in rendered HTML; got: {html}"
        );
        assert!(
            !html.contains("{row.delete_url}"),
            "literal {{row.delete_url}} must not appear in rendered HTML; got: {html}"
        );
        assert!(
            !html.contains("%7Brow.delete_url%7D"),
            "URL-encoded form must not appear in rendered HTML; got: {html}"
        );
    }

    #[test]
    fn data_table_bare_placeholder_resolved() {
        // Back-compat regression guard: the bare {delete_url} form (no row.
        // prefix) must continue to resolve after the F6 alias is added.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/items",
                "columns": [{"key": "name", "label": "Name"}],
                "row_actions": [{
                    "label": "Delete",
                    "action": {
                        "handler": "destroy",
                        "url": "{delete_url}",
                        "method": "POST"
                    },
                    "destructive": true,
                }],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"items": [
            {"name": "Absence", "delete_url": "/dashboard/staff/1/assenze/3/elimina"},
        ]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("/dashboard/staff/1/assenze/3/elimina"),
            "bare {{delete_url}} must still resolve; got: {html}"
        );
        assert!(
            !html.contains("{delete_url}"),
            "literal {{delete_url}} must not appear in rendered HTML; got: {html}"
        );
    }

    #[test]
    fn data_table_row_prefix_missing_key_leaves_placeholder() {
        // Pitfall 4 guard: when the row has no `nonexistent` field,
        // {row.nonexistent} must be left literal — not silently stripped.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/items",
                "columns": [{"key": "name", "label": "Name"}],
                "row_actions": [{
                    "label": "Action",
                    "action": {
                        "handler": "act",
                        "url": "/items/{row.nonexistent}",
                        "method": "GET"
                    },
                }],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"items": [
            {"name": "Item", "delete_url": "/items/1/delete"},
        ]});
        let html = render_data_table(&el, &spec, &data, 1);
        // The {row.nonexistent} placeholder has no matching key in the row;
        // it must survive unsubstituted (or HTML-escaped, which is also acceptable).
        assert!(
            html.contains("{row.nonexistent}") || html.contains("&#123;row.nonexistent&#125;"),
            "missing-key {{row.nonexistent}} must be left unsubstituted; got: {html}"
        );
    }

    #[test]
    fn data_table_row_href_legacy_placeholders() {
        // Regression guard: `{row_key}` and `{id}` still resolve alongside
        // the general column-key substitution.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/pages",
                "row_key": "slug",
                "columns": [{"key": "slug", "label": "Slug"}],
                "row_actions": [
                    {"label": "View", "action": {"handler": "view", "url": "/p/{row_key}/{id}", "method": "GET"}}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"pages": [
            {"id": "7", "slug": "row-3"},
        ]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("/p/row-3/7"),
            "legacy {{row_key}} and {{id}} must still be substituted; got: {html}"
        );
    }

    #[test]
    fn data_table_mobile_card_with_row_href_wraps_in_div_not_anchor() {
        // A clickable row (row_href) that also carries a row-actions dropdown
        // must render the mobile card as <div onclick> holding data-row-href,
        // NOT an <a> wrapper. The kebab emits a <button>, and <button> inside
        // <a> is invalid HTML the browser splits — re-applying the card
        // classes to each fragment and shattering the card. Regression guard.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/items",
                "row_href": "/items/{id}/detail",
                "columns": [{"key": "name", "label": "Name"}],
                "row_actions": [
                    {"label": "Edit", "action": {"handler": "edit", "url": "/items/{id}/edit", "method": "GET"}}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"items": [{"id": "9", "name": "x"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        // Row navigation is carried by data-row-href; the card is never an
        // anchor wrapping the kebab button.
        assert!(
            !html.contains("<a href=\"/items/9/detail\""),
            "mobile card must not wrap the row in an <a>; got: {html}"
        );
        assert!(
            html.contains("data-row-href=\"/items/9/detail\""),
            "row navigation must be carried by data-row-href; got: {html}"
        );
        // The kebab dropdown button renders — the reason an <a> wrapper would
        // be invalid in the first place.
        assert!(
            html.contains("<button"),
            "row-actions kebab button must render; got: {html}"
        );
    }

    // ── MediaCardGrid ────────────────────────────────────────────────────

    #[test]
    fn media_card_grid_empty_state() {
        let el = mk_element(
            "MediaCardGrid",
            json!({
                "data_path": "/items",
                "title_key": "name"
            }),
        );
        let spec = mk_spec("root", el.clone());
        let html = render_media_card_grid(&el, &spec, &json!({"items": []}), 1);
        assert!(html.contains("Nessun elemento trovato"), "got: {html}");
        assert!(
            !html.contains("<img"),
            "should not render image in empty state"
        );
    }

    #[test]
    fn media_card_grid_renders_title() {
        let el = mk_element(
            "MediaCardGrid",
            json!({
                "data_path": "/items",
                "title_key": "name"
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"items": [{"name": "Hair Factory", "id": 1}]});
        let html = render_media_card_grid(&el, &spec, &data, 1);
        assert!(html.contains("Hair Factory"), "got: {html}");
    }

    #[test]
    fn media_card_grid_renders_image_with_link() {
        let el = mk_element(
            "MediaCardGrid",
            json!({
                "data_path": "/items",
                "title_key": "name",
                "image_key": "screenshot_url",
                "image_href_key": "preview_url"
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"items": [{"name": "HF3", "id": 1, "screenshot_url": "/dashboard/pagine/1/screenshot.png", "preview_url": "/s/amaris-experience/hf3/"}]});
        let html = render_media_card_grid(&el, &spec, &data, 1);
        assert!(html.contains("<img"), "expected img tag, got: {html}");
        assert!(
            html.contains("/dashboard/pagine/1/screenshot.png"),
            "got: {html}"
        );
        assert!(
            html.contains("target=\"_blank\""),
            "expected new-tab link, got: {html}"
        );
        assert!(html.contains("/s/amaris-experience/hf3/"), "got: {html}");
    }

    #[test]
    fn media_card_grid_no_image_when_key_absent() {
        let el = mk_element(
            "MediaCardGrid",
            json!({
                "data_path": "/items",
                "title_key": "name"
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"items": [{"name": "HF3", "id": 1}]});
        let html = render_media_card_grid(&el, &spec, &data, 1);
        assert!(!html.contains("<img"), "got: {html}");
    }

    #[test]
    fn media_card_grid_badge_destructive() {
        let el = mk_element(
            "MediaCardGrid",
            json!({
                "data_path": "/items",
                "title_key": "name",
                "badge_key": "status",
                "badge_tone_key": "tone"
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data =
            json!({"items": [{"name": "HF", "status": "Non visibile", "tone": "destructive"}]});
        let html = render_media_card_grid(&el, &spec, &data, 1);
        assert!(html.contains("Non visibile"), "got: {html}");
        // Plan 05 migration: Badge now emits fjui-badge--destructive (skin owns appearance).
        assert!(html.contains("fjui-badge--destructive"), "got: {html}");
    }

    #[test]
    fn media_card_grid_invalid_tone_falls_back_to_neutral() {
        // T-251-01: an invalid row tone never reaches a class attribute — it
        // falls back to the neutral treatment from the shared badge renderer.
        let el = mk_element(
            "MediaCardGrid",
            json!({
                "data_path": "/items",
                "title_key": "name",
                "badge_key": "status",
                "badge_tone_key": "tone"
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"items": [{"name": "HF", "status": "Attivo", "tone": "not-a-tone"}]});
        let html = render_media_card_grid(&el, &spec, &data, 1);
        assert!(html.contains("Attivo"), "got: {html}");
        // Plan 05 migration: Badge now emits fjui-badge--neutral (skin owns appearance).
        assert!(
            html.contains("fjui-badge--neutral"),
            "expected neutral badge treatment; got: {html}"
        );
        assert!(!html.contains("not-a-tone"), "got: {html}");
    }

    #[test]
    fn media_card_grid_row_actions_interpolated() {
        let el = mk_element(
            "MediaCardGrid",
            json!({
                "data_path": "/items",
                "title_key": "name",
                "row_key": "id",
                "row_actions": [{"label": "Elimina", "action": {"handler": "/dashboard/pagine/{row_key}/delete", "method": "POST"}, "destructive": true}]
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"items": [{"name": "HF", "id": 42}]});
        let html = render_media_card_grid(&el, &spec, &data, 1);
        assert!(html.contains("/dashboard/pagine/42/delete"), "got: {html}");
    }

    // ── ColumnFormat::Badge ──────────────────────────────────────────────

    #[test]
    fn data_table_badge_column_format_renders_pill() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "status", "label": "Status", "format": "badge"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"status": {"tone": "destructive", "label": "Mancante"}}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(html.contains("Mancante"), "label missing; got: {html}");
        // Plan 05 migration: Badge now emits fjui-badge--destructive (skin owns appearance).
        assert!(
            html.contains("fjui-badge--destructive"),
            "missing fjui destructive class; got: {html}"
        );
        assert!(
            html.contains("fjui-badge"),
            "missing fjui-badge base class; got: {html}"
        );
        assert!(
            !html.contains("{&quot;tone&quot;"),
            "raw json leaked into cell; got: {html}"
        );
    }

    #[test]
    fn data_table_badge_column_format_invalid_value_emits_diagnostic() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "status", "label": "Status", "format": "badge"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        // String instead of {variant, label}
        let data = json!({"rows": [{"status": "Mancante"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("<!-- ferro-json-ui: invalid Badge cell value"),
            "expected diagnostic; got: {html}"
        );
        // The bad value itself should NOT be rendered as live UI.
        assert!(!html.contains(">Mancante<"), "got: {html}");
    }

    #[test]
    fn data_table_badge_column_format_null_value_renders_empty_cell() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "status", "label": "Status", "format": "badge"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"status": null}]});
        let html = render_data_table(&el, &spec, &data, 1);
        // No diagnostic, no badge — just an empty cell. Confirms null is a
        // first-class "this row has no status" rather than an error.
        assert!(
            !html.contains("<!-- ferro-json-ui: invalid"),
            "null should be valid; got: {html}"
        );
        assert!(!html.contains("rounded-full"), "got: {html}");
    }

    // ── DropdownMenuAction::visible_if ────────────────────────────────────

    #[test]
    fn data_table_visible_if_keeps_action_when_truthy() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "id", "label": "Id"}],
                "row_actions": [
                    {"label": "Scarica", "action": {"handler": "download", "url": "/d/{id}", "method": "GET"}, "visible_if": "can_download"}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"id": "1", "can_download": true}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(html.contains("Scarica"), "got: {html}");
    }

    #[test]
    fn data_table_visible_if_drops_action_when_falsy() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "id", "label": "Id"}],
                "row_actions": [
                    {"label": "Scarica", "action": {"handler": "download", "url": "/d/{id}", "method": "GET"}, "visible_if": "can_download"}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"id": "1", "can_download": false}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            !html.contains("Scarica"),
            "action should be hidden; got: {html}"
        );
    }

    #[test]
    fn data_table_visible_if_drops_action_when_field_missing() {
        // Fail-closed: missing field = hide. A typo in the spec must NOT show
        // the action everywhere (would expose privileged actions on every row).
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "id", "label": "Id"}],
                "row_actions": [
                    {"label": "Scarica", "action": {"handler": "download", "url": "/d/{id}", "method": "GET"}, "visible_if": "can_download_typo"}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"id": "1", "can_download": true}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            !html.contains("Scarica"),
            "missing field must hide action; got: {html}"
        );
    }

    #[test]
    fn data_table_visible_if_absent_keeps_action() {
        // Backwards-compat: actions with no visible_if always show.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "id", "label": "Id"}],
                "row_actions": [
                    {"label": "Open", "action": {"handler": "open", "url": "/o/{id}", "method": "GET"}}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"id": "1"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("Open"),
            "action without visible_if should always show; got: {html}"
        );
    }

    #[test]
    fn data_table_visible_if_filters_per_row_independently() {
        // Two rows, one declared action with visible_if — the action shows on
        // the row whose gate is true and hides on the row whose gate is false.
        // This is the load-bearing scenario for heterogeneous-row tables.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "id", "label": "Id"}],
                "row_actions": [
                    {"label": "Send link", "action": {"handler": "send", "url": "/s/{id}", "method": "POST"}, "visible_if": "can_send"},
                    {"label": "Download", "action": {"handler": "dl", "url": "/d/{id}", "method": "GET"}, "visible_if": "can_dl"}
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [
            {"id": "1", "can_send": true,  "can_dl": false},
            {"id": "2", "can_send": false, "can_dl": true},
        ]});
        let html = render_data_table(&el, &spec, &data, 1);
        // Both labels present in the full HTML (one per row).
        assert!(
            html.contains("Send link"),
            "row 1 action missing; got: {html}"
        );
        assert!(
            html.contains("Download"),
            "row 2 action missing; got: {html}"
        );
        // Each row's dropdown menu has its own popover id, so this asserts the
        // filter ran per-row by checking action urls land on the right rows.
        // Row 1's dropdown should contain /s/1 (send) but not /d/1 (download).
        // Row 2's dropdown should contain /d/2 (download) but not /s/2 (send).
        assert!(html.contains("/s/1"), "row 1 send url missing; got: {html}");
        assert!(
            !html.contains("/d/1"),
            "row 1 should not show download; got: {html}"
        );
        assert!(
            html.contains("/d/2"),
            "row 2 download url missing; got: {html}"
        );
        assert!(
            !html.contains("/s/2"),
            "row 2 should not show send; got: {html}"
        );
    }

    // ── ColumnFormat::Image ──────────────────────────────────────────────

    #[test]
    fn data_table_image_column_format_renders_img_tag() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "avatar_url", "label": "Avatar", "format": "image"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"avatar_url": "https://cdn.example/a.png"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(html.contains("<img"), "expected <img tag; got: {html}");
        assert!(
            html.contains("https://cdn.example/a.png"),
            "expected URL in src; got: {html}"
        );
    }

    #[test]
    fn data_table_image_column_format_xss_escaped() {
        // T-213-09: a URL containing `"` must not break out of the src attribute.
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "avatar_url", "label": "Avatar", "format": "image"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"avatar_url": "https://x.com/a.png\" onload=\"alert(1)"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            !html.contains("\" onload=\""),
            "unescaped quote must not break src attribute; got: {html}"
        );
        assert!(
            html.contains("&quot;"),
            "quote must be html-escaped; got: {html}"
        );
    }

    #[test]
    fn data_table_image_column_format_null_renders_empty_cell() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "avatar_url", "label": "Avatar", "format": "image"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"avatar_url": null}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            !html.contains("<img"),
            "null must render empty cell, no <img; got: {html}"
        );
    }

    // ── Plan 08: fjui-table__ row/cell/numeric/boolean classes ───────────

    /// D-08 migration: body wrapper emits fjui-table__body; rows emit fjui-table__row.
    #[test]
    fn data_table_row_emits_fjui_table_row_class() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "name", "label": "Name"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"name": "Alice"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("fjui-table__row"),
            "desktop row must emit fjui-table__row; got: {html}"
        );
        assert!(
            html.contains("fjui-table__body"),
            "tbody must emit fjui-table__body; got: {html}"
        );
    }

    /// D-08 migration: default cells emit fjui-table__cell.
    #[test]
    fn data_table_cell_emits_fjui_table_cell_class() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "name", "label": "Name"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"name": "Alice"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("fjui-table__cell"),
            "desktop cell must emit fjui-table__cell; got: {html}"
        );
    }

    /// D-08 migration: numeric columns (currency, date) emit fjui-table__cell--numeric (LANG-03).
    #[test]
    fn data_table_numeric_column_emits_fjui_cell_numeric_modifier() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [
                    {"key": "name", "label": "Name"},
                    {"key": "total", "label": "Total", "format": "currency"},
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"name": "Alice", "total": "€10.00"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("fjui-table__cell--numeric"),
            "currency column must emit fjui-table__cell--numeric; got: {html}"
        );
        // The base cell class must still be present alongside the modifier.
        assert!(
            html.contains("fjui-table__cell"),
            "cell must carry base fjui-table__cell; got: {html}"
        );
    }

    /// D-08 migration: boolean columns emit fjui-table__cell--boolean.
    #[test]
    fn data_table_boolean_column_emits_fjui_cell_boolean_modifier() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [
                    {"key": "name", "label": "Name"},
                    {"key": "active", "label": "Active", "format": "boolean"},
                ],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"name": "Alice", "active": true}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("fjui-table__cell--boolean"),
            "boolean column must emit fjui-table__cell--boolean; got: {html}"
        );
    }

    // ── Plan 247-02: boolean status-dot + bulk-select ────────────────────

    /// Boolean column renders fjui-status-dot with configurable labels (RSK-01).
    #[test]
    fn boolean_column_renders_status_dot() {
        use crate::component::{Column, ColumnFormat};
        let col = Column {
            key: "active".to_string(),
            label: "Stato".to_string(),
            format: Some(ColumnFormat::Boolean),
            align: None,
            label_true: Some("Attivo".to_string()),
            label_false: Some("Non attivo".to_string()),
            peek_entity: None,
        };
        let true_html = render_cell(&col, Some(&Value::Bool(true)));
        assert!(
            true_html.contains("fjui-status-dot--true"),
            "true → success dot; got: {true_html}"
        );
        assert!(true_html.contains("Attivo"), "true label; got: {true_html}");
        let false_html = render_cell(&col, Some(&Value::Bool(false)));
        assert!(
            false_html.contains("fjui-status-dot--false"),
            "false → muted dot; got: {false_html}"
        );
        assert!(
            false_html.contains("Non attivo"),
            "false label; got: {false_html}"
        );
        // integer boolean
        let int_true = render_cell(&col, Some(&Value::Number(serde_json::Number::from(1))));
        assert!(
            int_true.contains("fjui-status-dot--true"),
            "Number(1) → true; got: {int_true}"
        );
    }

    /// Bulk-select column emits checkbox th+td when bulk_select=Some(true).
    #[test]
    fn bulk_select_column_present_when_enabled() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "bulk_select": true,
                "columns": [{"key": "name", "label": "Name"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"name": "Alice"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("fjui-table__bulk-select-checkbox"),
            "bulk_select=true must emit fjui-table__bulk-select-checkbox; got: {html}"
        );
        assert!(
            html.contains("type=\"checkbox\""),
            "bulk-select must include checkbox input; got: {html}"
        );
    }

    /// T-249-04-01: bulk-select td must emit html-escaped data-row-key (no attribute break-out).
    #[test]
    fn bulk_select_emits_html_escaped_data_row_key() {
        // row_key value contains a double-quote — must be escaped to &#34; or &quot;
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "bulk_select": true,
                "row_key": "id",
                "columns": [{"key": "name", "label": "Name"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        // The id value contains a double-quote which would break an HTML attribute if unescaped.
        let data = json!({"rows": [{"id": "42\"xss", "name": "Alice"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("data-row-key="),
            "bulk_select=true must emit data-row-key; got: {html}"
        );
        // The raw quote must NOT appear inside an attribute context.
        assert!(
            !html.contains("data-row-key=\"42\""),
            "double-quote in row key must be html-escaped in attribute; got: {html}"
        );
        // The escaped form must be present.
        assert!(
            html.contains("42&quot;xss") || html.contains("42&#"),
            "escaped quote must appear in html; got: {html}"
        );
    }

    /// data-bulk-select-table attribute must be present on the table root when bulk_select enabled.
    #[test]
    fn bulk_select_table_root_has_data_bulk_select_table() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "bulk_select": true,
                "columns": [{"key": "name", "label": "Name"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"name": "Alice"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            html.contains("data-bulk-select-table"),
            "bulk_select=true must emit data-bulk-select-table on the table wrapper; got: {html}"
        );
    }

    /// D-08 migration: zebra-striping utilities must NOT be present (RSK-01).
    #[test]
    fn data_table_no_zebra_striping_in_rows() {
        let el = mk_element(
            "DataTable",
            json!({
                "data_path": "/rows",
                "columns": [{"key": "name", "label": "Name"}],
            }),
        );
        let spec = mk_spec("root", el.clone());
        let data = json!({"rows": [{"name": "Alice"}, {"name": "Bob"}]});
        let html = render_data_table(&el, &spec, &data, 1);
        assert!(
            !html.contains("even:bg-"),
            "no even: zebra utility; got: {html}"
        );
        assert!(
            !html.contains("odd:bg-"),
            "no odd: zebra utility; got: {html}"
        );
    }
}