ferro-json-ui 0.2.56

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
//! Container renderers.
//!
//! Each function takes `(el, spec, data, depth)` and emits the container's
//! HTML wrapper plus the concatenated rendering of each child ID. Child
//! rendering is routed through [`super::render_element`] for ID-keyed lookup.
//!
//! Single-slot containers (`Grid`, `Collapsible`, `FormSection`,
//! `ButtonGroup`) read their children from `Element.children`. Multi-slot
//! containers (`Card`, `Modal`, `Tabs`, `KanbanBoard`, `PageHeader`) read
//! slot IDs from typed Props fields.

use serde_json::Value;

use crate::component::{
    ButtonGroupProps, CardProps, CardVariant, CollapsibleProps, DetailPageProps, FormMaxWidth,
    FormSectionLayout, FormSectionProps, GapSize, GridProps, KanbanBoardProps, ModalProps,
    PageHeaderProps, TabsProps,
};
use crate::data::resolve_path;
use crate::spec::{Element, Spec};

use super::data::{render_inline_dropdown, resolve_row_key, template_actions};
use super::{html_escape, render_element};

// ── Multi-slot containers ────────────────────────────────────────────────

/// Renders a `Card`. Reads `CardProps` (title, description, footer,
/// max_width, variant) and wraps the rendering of each ID in `el.children`
/// in a bordered or elevated container per `variant`. Footer IDs come from
/// `CardProps.footer`. `Narrow` and `Wide` variants of `max_width` apply an
/// outer `mx-auto` width wrapper.
pub(crate) fn render_card(el: &Element, spec: &Spec, data: &Value, depth: usize) -> String {
    let props: CardProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode Card props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    // Body: rendered from `Element.children`.
    let body: String = el
        .children
        .iter()
        .map(|cid| render_element(cid, spec, data, depth + 1))
        .collect();

    // Footer: rendered from `CardProps.footer`. Missing IDs surface via the
    // walker's missing-id diagnostic comment.
    let footer: String = props
        .footer
        .iter()
        .map(|cid| render_element(cid, spec, data, depth + 1))
        .collect();

    let (outer_class, inner_pad) = match props.variant {
        CardVariant::Bordered => (
            "rounded-lg border border-border bg-card shadow-sm overflow-visible",
            "p-4",
        ),
        CardVariant::Elevated => ("rounded-lg bg-card shadow-md overflow-visible", "p-8"),
    };

    let mut html = format!("<div class=\"{outer_class}\"><div class=\"{inner_pad}\">");
    if let Some(ref badge) = props.badge {
        html.push_str("<div class=\"flex items-start justify-between gap-2\">");
        html.push_str(&format!(
            "<h3 class=\"text-base font-semibold leading-snug text-text\">{}</h3>",
            html_escape(&props.title)
        ));
        html.push_str(&format!(
            "<span class=\"inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-secondary/10 text-secondary-foreground shrink-0\">{}</span>",
            html_escape(badge)
        ));
        html.push_str("</div>");
    } else {
        html.push_str(&format!(
            "<h3 class=\"text-base font-semibold leading-snug text-text\">{}</h3>",
            html_escape(&props.title)
        ));
    }
    if let Some(ref subtitle) = props.subtitle {
        html.push_str(&format!(
            "<p class=\"mt-0.5 text-sm text-text-muted\">{}</p>",
            html_escape(subtitle)
        ));
    }
    if let Some(ref desc) = props.description {
        html.push_str(&format!(
            "<p class=\"mt-1 text-sm text-text-muted\">{}</p>",
            html_escape(desc)
        ));
    }
    // Body wrapper is omitted when there are no children to render. Keyed
    // on the slot list, not the rendered string — invisible children render
    // to "" but the wrapper is still emitted so the empty space is
    // structurally consistent.
    if !el.children.is_empty() {
        html.push_str(
            "<div class=\"mt-3 flex flex-wrap gap-3 [&>*]:w-full [&>button]:w-auto [&>a]:w-auto overflow-visible\">",
        );
        html.push_str(&body);
        html.push_str("</div>");
    }
    html.push_str("</div>"); // close inner p-4 region
    if !props.footer.is_empty() {
        html.push_str(
            "<div class=\"border-t border-border px-6 py-4 flex items-center justify-between gap-2\">",
        );
        html.push_str(&footer);
        html.push_str("</div>");
    }
    html.push_str("</div>"); // close outer card

    match props.max_width.as_ref().unwrap_or(&FormMaxWidth::Default) {
        FormMaxWidth::Default => {}
        FormMaxWidth::Narrow => {
            html = format!("<div class=\"max-w-2xl mx-auto\">{html}</div>");
        }
        FormMaxWidth::Wide => {
            html = format!("<div class=\"max-w-4xl mx-auto\">{html}</div>");
        }
    }

    html
}

/// Renders a `Modal` as a native `<dialog>` element with an external trigger
/// button. Body is rendered from `Element.children`; footer is rendered from
/// `ModalProps.footer`. The trigger uses `data-modal-open="{id}"`; the close
/// button uses `data-modal-close`.
pub(crate) fn render_modal(el: &Element, spec: &Spec, data: &Value, depth: usize) -> String {
    let props: ModalProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode Modal props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    let body: String = el
        .children
        .iter()
        .map(|cid| render_element(cid, spec, data, depth + 1))
        .collect();
    let footer: String = props
        .footer
        .iter()
        .map(|cid| render_element(cid, spec, data, depth + 1))
        .collect();

    let trigger = props.trigger_label.as_deref().unwrap_or("Open");
    let mut html = String::new();
    // Trigger button (sibling of dialog, not inside it)
    html.push_str(&format!(
        "<button type=\"button\" class=\"inline-flex items-center justify-center rounded-md bg-primary text-primary-foreground px-4 py-2 text-sm font-medium cursor-pointer\" data-modal-open=\"{}\">{}</button>",
        html_escape(&props.id),
        html_escape(trigger)
    ));
    // Native <dialog> element
    html.push_str(&format!(
        "<dialog id=\"{}\" aria-modal=\"true\" aria-labelledby=\"{}-title\" class=\"bg-card rounded-lg shadow-lg max-w-lg w-full mx-4 p-6 backdrop:bg-black/50\">",
        html_escape(&props.id),
        html_escape(&props.id)
    ));
    // Header row: title + close button
    html.push_str("<div class=\"flex items-center justify-between mb-4\">");
    html.push_str(&format!(
        "<h3 id=\"{}-title\" class=\"text-lg font-semibold leading-snug text-text\">{}</h3>",
        html_escape(&props.id),
        html_escape(&props.title)
    ));
    html.push_str(
        "<button type=\"button\" data-modal-close aria-label=\"Chiudi\" class=\"text-text-muted hover:text-text p-2 rounded transition-colors duration-150\">\u{00d7}</button>",
    );
    html.push_str("</div>");
    if let Some(ref desc) = props.description {
        html.push_str(&format!(
            "<p class=\"text-sm text-text-muted mb-4\">{}</p>",
            html_escape(desc)
        ));
    }
    html.push_str(
        "<div class=\"flex flex-wrap gap-4 [&>*]:w-full [&>button]:w-auto [&>a]:w-auto\">",
    );
    html.push_str(&body);
    html.push_str("</div>");
    if !props.footer.is_empty() {
        html.push_str("<div class=\"mt-6 flex items-center justify-end gap-2\">");
        html.push_str(&footer);
        html.push_str("</div>");
    }
    html.push_str("</dialog>");
    html
}

/// Renders a `Tabs` container. Per-tab children come from
/// `Tab.children: Vec<String>`.
///
/// Two behaviors worth flagging for plugin authors:
/// 1. **Single-tab auto-hide:** when `props.tabs.len() == 1` the tab bar is
///    elided entirely and the single panel renders directly.
/// 2. **Server-driven fallback:** when no tab in the spec carries children
///    (`has_any_content == false`), or when a specific tab has empty children
///    while another has content, that tab's trigger renders as
///    `<a href="?tab=X">` instead of `<button data-tab="X">` — supporting
///    full-page reloads for SSR-only specs.
pub(crate) fn render_tabs(el: &Element, spec: &Spec, data: &Value, depth: usize) -> String {
    let props: TabsProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode Tabs props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    // Single-tab specs render body-only (no tab strip).
    if props.tabs.len() == 1 {
        let tab = &props.tabs[0];
        let mut html = String::from(
            "<div class=\"flex flex-wrap gap-4 [&>*]:w-full [&>button]:w-auto [&>a]:w-auto\">",
        );
        for cid in &tab.children {
            html.push_str(&render_element(cid, spec, data, depth + 1));
        }
        html.push_str("</div>");
        return html;
    }

    let has_any_content = props.tabs.iter().any(|t| !t.children.is_empty());

    let mut html = String::from("<div data-tabs>");
    html.push_str("<div class=\"border-b border-border\">");
    html.push_str("<nav class=\"flex -mb-px space-x-4\" role=\"tablist\">");

    for tab in &props.tabs {
        let is_active = tab.value == props.default_tab;
        let border = if is_active {
            "border-primary"
        } else {
            "border-transparent"
        };
        let text = if is_active {
            "text-primary font-semibold"
        } else {
            "text-text-muted hover:text-text"
        };

        if has_any_content && (is_active || !tab.children.is_empty()) {
            // Client-side tab trigger
            html.push_str(&format!(
                "<button type=\"button\" role=\"tab\" id=\"tab-btn-{}\" aria-controls=\"tab-panel-{}\" data-tab=\"{}\" \
                 class=\"border-b-2 {} {} px-3 py-2 text-sm font-medium cursor-pointer transition-colors duration-150 motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2\" \
                 aria-selected=\"{}\">{}</button>",
                html_escape(&tab.value),
                html_escape(&tab.value),
                html_escape(&tab.value),
                border,
                text,
                is_active,
                html_escape(&tab.label),
            ));
        } else {
            // Server-driven tab: link with ?tab= query param
            html.push_str(&format!(
                "<a href=\"?tab={}\" role=\"tab\" id=\"tab-btn-{}\" aria-controls=\"tab-panel-{}\" \
                 class=\"border-b-2 {} {} px-3 py-2 text-sm font-medium transition-colors duration-150 motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2\" \
                 aria-selected=\"{}\">{}</a>",
                html_escape(&tab.value),
                html_escape(&tab.value),
                html_escape(&tab.value),
                border,
                text,
                is_active,
                html_escape(&tab.label),
            ));
        }
    }

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

    // Render all tab panels — inactive panels are hidden via CSS.
    for tab in &props.tabs {
        if tab.children.is_empty() && tab.value != props.default_tab {
            continue;
        }
        let hidden = if tab.value != props.default_tab {
            " hidden"
        } else {
            ""
        };
        html.push_str(&format!(
            "<div role=\"tabpanel\" id=\"tab-panel-{}\" aria-labelledby=\"tab-btn-{}\" data-tab-panel=\"{}\" class=\"pt-4 flex flex-wrap gap-4 [&>*]:w-full [&>button]:w-auto [&>a]:w-auto{}\">",
            html_escape(&tab.value),
            html_escape(&tab.value),
            html_escape(&tab.value),
            hidden,
        ));
        for cid in &tab.children {
            html.push_str(&render_element(cid, spec, data, depth + 1));
        }
        html.push_str("</div>");
    }

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

/// Stringifies a JSON scalar for `group_by` matching and card field bindings.
/// Objects, arrays, and null yield `None`.
fn json_scalar_string(v: &Value) -> Option<String> {
    match v {
        Value::String(s) => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        Value::Bool(b) => Some(b.to_string()),
        _ => None,
    }
}

/// Renders one data-bound card from a kanban item using the `card_*` / `row_*`
/// field bindings — the prescribed kanban card shape (title, optional
/// description, optional dropdown of `row_actions`). Mirrors `MediaCardGrid`.
fn render_kanban_card(item: &Value, props: &KanbanBoardProps, index: usize) -> String {
    let title = props
        .card_title_key
        .as_deref()
        .and_then(|k| item.get(k))
        .and_then(json_scalar_string)
        .unwrap_or_default();
    let description = props
        .card_description_key
        .as_deref()
        .and_then(|k| item.get(k))
        .and_then(json_scalar_string);

    let mut card = String::from(
        "<div data-kanban-card class=\"cursor-pointer rounded-lg border border-border bg-card p-3 flex flex-col gap-1\">",
    );
    card.push_str("<div class=\"flex items-start justify-between gap-2\">");
    card.push_str(&format!(
        "<div class=\"text-sm font-medium text-text\">{}</div>",
        html_escape(&title)
    ));
    if let Some(ref actions) = props.row_actions {
        let row_key_value = resolve_row_key(item, props.row_key.as_deref(), index);
        let templated = template_actions(actions, item, &row_key_value);
        if !templated.is_empty() {
            card.push_str(&render_inline_dropdown(
                &format!("kanban-card-{row_key_value}"),
                &templated,
            ));
        }
    }
    card.push_str("</div>");
    if let Some(desc) = description {
        card.push_str(&format!(
            "<div class=\"text-xs text-text-muted\">{}</div>",
            html_escape(&desc)
        ));
    }
    card.push_str("</div>");
    card
}

/// Pre-rendered content for a single kanban lane: header count plus the
/// concatenated card HTML, computed once and consumed by both the desktop and
/// mobile layouts.
struct LaneRender {
    id: String,
    title: String,
    count: u32,
    cards_html: String,
}

/// Renders a `KanbanBoard`. `columns` is lane structure (always rendered);
/// card content is data-bound from `items_path` + `group_by` — each item is
/// bucketed into the column whose `id` equals the item's `group_by` value and
/// rendered as a card via the `card_*` / `row_*` bindings. Static specs that
/// set neither `items_path` nor `group_by` fall back to rendering each
/// column's `children` element IDs.
///
/// Responsive: horizontally-scrollable columns on desktop
/// (`hidden md:block`), tab-based column switching on mobile
/// (`block md:hidden`). Mobile default column honors
/// `props.mobile_default_column` when set; otherwise falls back to the first
/// column's id.
pub(crate) fn render_kanban_board(el: &Element, spec: &Spec, data: &Value, depth: usize) -> String {
    let props: KanbanBoardProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode KanbanBoard props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    if props.columns.is_empty() {
        return String::new();
    }

    // Data-bound path: bucket a flat array of items into lanes by `group_by`.
    // Falls back to static `children` rendering when no `group_by` is set.
    let lanes: Vec<LaneRender> = match props.group_by.as_deref() {
        Some(group_by) => {
            let items: Vec<Value> = props
                .items_path
                .as_deref()
                .and_then(|p| resolve_path(data, p))
                .and_then(|v| v.as_array().cloned())
                .unwrap_or_default();
            props
                .columns
                .iter()
                .map(|col| {
                    let cards: Vec<String> = items
                        .iter()
                        .enumerate()
                        .filter(|(_, item)| {
                            item.get(group_by).and_then(json_scalar_string).as_deref()
                                == Some(col.id.as_str())
                        })
                        .map(|(i, item)| render_kanban_card(item, &props, i))
                        .collect();
                    LaneRender {
                        id: col.id.clone(),
                        title: col.title.clone(),
                        count: cards.len() as u32,
                        cards_html: cards.concat(),
                    }
                })
                .collect()
        }
        None => props
            .columns
            .iter()
            .map(|col| {
                let cards_html: String = col
                    .children
                    .iter()
                    .map(|cid| {
                        format!(
                            "<div data-kanban-card class=\"cursor-pointer\">{}</div>",
                            render_element(cid, spec, data, depth + 1)
                        )
                    })
                    .collect();
                LaneRender {
                    id: col.id.clone(),
                    title: col.title.clone(),
                    count: col.count,
                    cards_html,
                }
            })
            .collect(),
    };

    let default_id = props
        .mobile_default_column
        .as_deref()
        .unwrap_or_else(|| &lanes[0].id);

    let mut html = String::new();

    // Desktop view: horizontal scrollable columns. The negative
    // horizontal margin cancels the parent main's `md:p-6` padding so the
    // scroller spans full content width; the matching padding restores the
    // inset for the first/last column so cards don't touch the page edge.
    // Inline styles are used because consumer Tailwind builds typically
    // only generate the literal utilities ferro renders elsewhere (no `mx-*`
    // or `md:` variants for margin/padding).
    html.push_str(
        "<div class=\"hidden md:block overflow-x-auto\" \
         style=\"margin-left: -1.5rem; margin-right: -1.5rem; padding-left: 1.5rem; padding-right: 1.5rem;\">",
    );
    html.push_str("<div class=\"flex gap-4\" style=\"min-width: min-content;\">");

    for lane in &lanes {
        // Column is a flex-column capped at viewport height. Padding lives on
        // the inner sections (header + scroll viewport) instead of the outer
        // wrapper, so the scroll clip rectangle reaches the column's rounded
        // border — card hover shadows and focus rings extend cleanly into the
        // padding zone instead of being clipped at an inner box. Scrollbars
        // are hidden via `ferro-kanban-scroll` (CSS injected by the runtime)
        // plus inline `scrollbar-width: none` for Firefox.
        // The 12rem subtraction reserves room for dashboard header + page
        // header + main padding — adjust if chrome height changes.
        html.push_str(
            "<div class=\"min-w-[260px] flex-1 flex-shrink-0 rounded-lg border border-border bg-card/50 flex flex-col\" \
             style=\"max-height: calc(100vh - 12rem);\">",
        );
        html.push_str("<div class=\"flex items-center justify-between p-3 shrink-0\">");
        html.push_str(&format!(
            "<h3 class=\"text-sm font-semibold text-text\">{}</h3>",
            html_escape(&lane.title),
        ));
        let badge_class = if lane.count > 0 {
            "inline-flex items-center rounded-full px-2 py-0.5 text-xs font-semibold bg-primary text-primary-foreground"
        } else {
            "inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium text-text-muted bg-surface"
        };
        html.push_str(&format!(
            "<span class=\"{}\">{}</span>",
            badge_class, lane.count,
        ));
        html.push_str("</div>");
        html.push_str(
            "<div class=\"ferro-kanban-scroll space-y-2 flex-1 overflow-y-auto px-3 pb-3\" \
             style=\"scrollbar-width: none;\">",
        );
        if lane.cards_html.is_empty() {
            if let Some(ref label) = props.empty_label {
                html.push_str(&format!(
                    "<div class=\"flex items-center justify-center h-full min-h-40 text-sm text-text-muted text-center px-3\">{}</div>",
                    html_escape(label)
                ));
            }
        } else {
            html.push_str(&lane.cards_html);
        }
        html.push_str("</div>");
        html.push_str("</div>");
    }

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

    // Mobile view: tab-based column switching.
    html.push_str("<div class=\"block md:hidden\" data-tabs>");
    html.push_str("<div class=\"flex border-b border-border mb-4\">");

    for lane in &lanes {
        let is_default = lane.id == default_id;
        let (border, text) = if is_default {
            ("border-primary", "text-primary font-semibold")
        } else {
            ("border-transparent", "text-text-muted hover:text-text")
        };
        html.push_str(&format!(
            "<button type=\"button\" data-tab=\"{}\" class=\"flex-1 px-3 py-2 text-sm border-b-2 {} {}\" aria-selected=\"{}\">{} <span class=\"ml-1 text-xs text-text-muted\">({})</span></button>",
            html_escape(&lane.id),
            border,
            text,
            is_default,
            html_escape(&lane.title),
            lane.count,
        ));
    }

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

    for lane in &lanes {
        let is_default = lane.id == default_id;
        let hidden = if is_default { "" } else { " hidden" };
        // Same viewport cap as desktop columns — single column scrolls
        // vertically rather than growing the page. Scrollbars hidden via
        // `ferro-kanban-scroll` + inline scrollbar-width: none.
        html.push_str(&format!(
            "<div data-tab-panel=\"{}\" class=\"ferro-kanban-scroll space-y-3 overflow-y-auto{hidden}\" \
             style=\"max-height: calc(100vh - 14rem); scrollbar-width: none;\">",
            html_escape(&lane.id),
        ));
        if lane.cards_html.is_empty() {
            if let Some(ref label) = props.empty_label {
                html.push_str(&format!(
                    "<div class=\"flex items-center justify-center min-h-40 text-sm text-text-muted text-center px-3\">{}</div>",
                    html_escape(label)
                ));
            }
        } else {
            html.push_str(&lane.cards_html);
        }
        html.push_str("</div>");
    }

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

    html
}

/// Renders a `PageHeader`. Emits the title, optional breadcrumb trail with
/// chevron separators, and right-aligned action buttons.
/// `PageHeaderProps.actions: Vec<String>` lists IDs of elements (typically
/// `Button` atoms) rendered into the actions slot.
///
/// Phase 165 F11: any `Element.children` are rendered as page body below
/// the header chrome. This closes the silent-drop pathology that bit
/// JsonUi::render_file consumers using `root: PageHeader` with children —
/// previously the chrome rendered fine but the body never appeared in DOM.
pub(crate) fn render_page_header(el: &Element, spec: &Spec, data: &Value, depth: usize) -> String {
    let props: PageHeaderProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode PageHeader props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    // Actions: IDs from `props.actions` — typically Button elements.
    let actions_html: String = props
        .actions
        .iter()
        .map(|cid| render_element(cid, spec, data, depth + 1))
        .collect();

    let mut html =
        String::from("<div class=\"flex flex-wrap items-center justify-between gap-3 pb-4\">");

    // Title block — breadcrumb and title fused into one inline flow
    html.push_str("<div class=\"flex items-center gap-2 min-w-0\">");

    if !props.breadcrumb.is_empty() {
        for item in &props.breadcrumb {
            if let Some(ref url) = item.url {
                html.push_str(&format!(
                    "<a href=\"{}\" class=\"text-sm text-text-muted hover:text-text whitespace-nowrap\">{}</a>",
                    html_escape(url),
                    html_escape(&item.label)
                ));
            } else {
                html.push_str(&format!(
                    "<span class=\"text-sm text-text-muted whitespace-nowrap\">{}</span>",
                    html_escape(&item.label)
                ));
            }
            // Chevron separator between breadcrumb and title
            html.push_str(
                "<span aria-hidden=\"true\" class=\"text-text-muted flex-shrink-0\">\
                 <svg class=\"h-4 w-4\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" fill=\"currentColor\">\
                 <path fill-rule=\"evenodd\" d=\"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z\" clip-rule=\"evenodd\"/>\
                 </svg></span>"
            );
        }
    }

    html.push_str(&format!(
        "<h2 class=\"text-2xl font-semibold leading-tight tracking-tight text-text truncate\">{}</h2>",
        html_escape(&props.title)
    ));
    html.push_str("</div>");

    // Actions (optional)
    if !props.actions.is_empty() {
        html.push_str("<div class=\"flex flex-wrap items-center gap-2\">");
        html.push_str(&actions_html);
        html.push_str("</div>");
    }

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

    // F11: render Element.children as page body sections below the chrome.
    // The chrome's `pb-4` provides visual separation; children stack as
    // block-level siblings. Empty children list is a no-op (back-compat).
    if !el.children.is_empty() {
        let body_html: String = el
            .children
            .iter()
            .map(|cid| render_element(cid, spec, data, depth + 1))
            .collect();
        html.push_str("<div class=\"flex flex-col gap-4\">");
        html.push_str(&body_html);
        html.push_str("</div>");
    }

    html
}

/// Renders a `DetailPage`. Emits the canonical resource-detail layout:
/// PageHeader chrome (title + breadcrumb + actions), then an info Card
/// (rendered only when `info` is non-empty) wrapping the listed slot IDs,
/// then `Element.children` stacked below the card as page sections
/// (Tabs, related-resource Cards, etc.). The HTML matches what a
/// hand-composed `PageHeader + Card + Tabs` triple would emit, so the
/// component centralizes the contract without changing the visual output
/// downstream pages were already producing.
pub(crate) fn render_detail_page(el: &Element, spec: &Spec, data: &Value, depth: usize) -> String {
    let props: DetailPageProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode DetailPage props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    let mut html = String::new();

    // Header chrome — mirrors render_page_header's structure verbatim so the
    // DetailPage skeleton stays visually identical to manually-composed pages.
    html.push_str("<div class=\"flex flex-wrap items-center justify-between gap-3 pb-4\">");
    html.push_str("<div class=\"flex items-center gap-2 min-w-0\">");
    if !props.breadcrumb.is_empty() {
        for item in &props.breadcrumb {
            if let Some(ref url) = item.url {
                html.push_str(&format!(
                    "<a href=\"{}\" class=\"text-sm text-text-muted hover:text-text whitespace-nowrap\">{}</a>",
                    html_escape(url),
                    html_escape(&item.label)
                ));
            } else {
                html.push_str(&format!(
                    "<span class=\"text-sm text-text-muted whitespace-nowrap\">{}</span>",
                    html_escape(&item.label)
                ));
            }
            html.push_str(
                "<span aria-hidden=\"true\" class=\"text-text-muted flex-shrink-0\">\
                 <svg class=\"h-4 w-4\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" fill=\"currentColor\">\
                 <path fill-rule=\"evenodd\" d=\"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z\" clip-rule=\"evenodd\"/>\
                 </svg></span>"
            );
        }
    }
    html.push_str(&format!(
        "<h2 class=\"text-2xl font-semibold leading-tight tracking-tight text-text truncate\">{}</h2>",
        html_escape(&props.title)
    ));
    html.push_str("</div>");

    if !props.actions.is_empty() {
        let actions_html: String = props
            .actions
            .iter()
            .map(|cid| render_element(cid, spec, data, depth + 1))
            .collect();
        html.push_str("<div class=\"flex flex-wrap items-center gap-2\">");
        html.push_str(&actions_html);
        html.push_str("</div>");
    }
    html.push_str("</div>");

    // Body: info Card + children sections, stacked vertically with gap-4.
    let has_body = !props.info.is_empty() || !el.children.is_empty();
    if has_body {
        html.push_str("<div class=\"flex flex-col gap-4\">");

        // Info Card — mirrors render_card's Bordered+Default output with an
        // empty title (suppressed via the same path as Card uses for empty
        // titles in practice). The wrapper is omitted entirely when `info`
        // is empty so pages without a primary info block get just the
        // header + children.
        if !props.info.is_empty() {
            let info_body: String = props
                .info
                .iter()
                .map(|cid| render_element(cid, spec, data, depth + 1))
                .collect();
            html.push_str(
                "<div class=\"rounded-lg border border-border bg-card shadow-sm overflow-visible\">\
                 <div class=\"p-4\">",
            );
            html.push_str(
                "<div class=\"flex flex-wrap gap-3 [&>*]:w-full [&>button]:w-auto [&>a]:w-auto overflow-visible\">",
            );
            html.push_str(&info_body);
            html.push_str("</div></div></div>");
        }

        // Element.children render as below-the-fold sections (Tabs,
        // related-resource Cards, action panels).
        if !el.children.is_empty() {
            let body_html: String = el
                .children
                .iter()
                .map(|cid| render_element(cid, spec, data, depth + 1))
                .collect();
            html.push_str(&body_html);
        }

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

    html
}

// ── Single-slot containers ────────────────────────────────────────────────

/// Renders a `Grid` container. Emits a CSS-grid `<div>` whose column count
/// comes from `GridProps.columns` (clamped to `1..=12`), with optional
/// `md_columns` / `lg_columns` breakpoint overrides. When `scrollable` is
/// set, emits a horizontally-scrollable `grid-flow-col` layout instead.
/// Children are rendered from `Element.children`.
pub(crate) fn render_grid(el: &Element, spec: &Spec, data: &Value, depth: usize) -> String {
    let props: GridProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode Grid props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    let gap = match props.gap {
        GapSize::None => "gap-0",
        GapSize::Sm => "gap-2",
        GapSize::Md => "gap-4",
        GapSize::Lg => "gap-6",
        GapSize::Xl => "gap-8",
    };

    // Children body via `render_element`.
    let body: String = el
        .children
        .iter()
        .map(|cid| render_element(cid, spec, data, depth + 1))
        .collect();

    if props.scrollable == Some(true) {
        return format!(
            "<div class=\"overflow-x-auto\"><div class=\"grid grid-flow-col auto-cols-[minmax(280px,1fr)] {gap}\">{body}</div></div>"
        );
    }

    let cols = props.columns.clamp(1, 12);
    let mut col_classes = format!("grid-cols-{cols}");
    if let Some(md) = props.md_columns {
        col_classes.push_str(&format!(" md:grid-cols-{}", md.clamp(1, 12)));
    }
    if let Some(lg) = props.lg_columns {
        col_classes.push_str(&format!(" lg:grid-cols-{}", lg.clamp(1, 12)));
    }
    format!("<div class=\"grid w-full {col_classes} {gap}\">{body}</div>")
}

// SVG chevron used to indicate the collapsed/expanded state.
const CHEVRON_DOWN: &str = concat!(
    "<svg class=\"h-4 w-4\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" fill=\"currentColor\">",
    "<path fill-rule=\"evenodd\" d=\"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z\" clip-rule=\"evenodd\"/>",
    "</svg>"
);

/// Renders a `Collapsible` section as a `<details>`/`<summary>` pair. The
/// title sits in `<summary>`; the body is rendered from `Element.children`.
/// `expanded = true` adds the HTML `open` attribute.
pub(crate) fn render_collapsible(el: &Element, spec: &Spec, data: &Value, depth: usize) -> String {
    let props: CollapsibleProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode Collapsible props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    let body: String = el
        .children
        .iter()
        .map(|cid| render_element(cid, spec, data, depth + 1))
        .collect();

    let mut html = String::from("<details class=\"group\"");
    if props.expanded {
        html.push_str(" open");
    }
    html.push('>');
    let aria_expanded = if props.expanded { "true" } else { "false" };
    html.push_str(&format!(
        "<summary class=\"flex items-center justify-between cursor-pointer px-4 py-3 text-sm font-medium text-text bg-surface rounded-lg hover:bg-card\" aria-expanded=\"{}\">{}<span class=\"text-text-muted group-open:rotate-180 transition-transform\">{CHEVRON_DOWN}</span></summary>",
        aria_expanded,
        html_escape(&props.title)
    ));
    html.push_str("<div class=\"px-4 py-3 flex flex-wrap gap-4 [&>*]:w-full [&>button]:w-auto [&>a]:w-auto\">");
    html.push_str(&body);
    html.push_str("</div></details>");
    html
}

/// Renders a `FormSection` as a `<fieldset>` with an optional legend and
/// description. Two layout variants are supported: stacked (single column)
/// and `TwoColumn` (5-column grid with the title/description in the first 2
/// and the body in the remaining 3). The body is rendered from
/// `Element.children`.
pub(crate) fn render_form_section(el: &Element, spec: &Spec, data: &Value, depth: usize) -> String {
    let props: FormSectionProps = match serde_json::from_value(el.props.clone()) {
        Ok(p) => p,
        Err(e) => {
            return format!(
                "<!-- ferro-json-ui: failed to decode FormSection props: {} -->",
                html_escape(&e.to_string())
            );
        }
    };

    let body: String = el
        .children
        .iter()
        .map(|cid| render_element(cid, spec, data, depth + 1))
        .collect();

    let is_two_column = matches!(props.layout.as_ref(), Some(FormSectionLayout::TwoColumn));

    if is_two_column {
        let mut html = String::from("<fieldset class=\"md:grid md:grid-cols-5 md:gap-8\">");
        html.push_str(&format!(
            "<div class=\"md:col-span-2\"><legend class=\"text-base font-semibold text-text\">{}</legend>",
            html_escape(&props.title)
        ));
        if let Some(ref desc) = props.description {
            html.push_str(&format!(
                "<p class=\"text-sm text-text-muted mt-1\">{}</p>",
                html_escape(desc)
            ));
        }
        html.push_str("</div>");
        html.push_str("<div class=\"md:col-span-3 space-y-4 mt-4 md:mt-0\">");
        html.push_str(&body);
        html.push_str("</div></fieldset>");
        html
    } else {
        let mut html = String::from(
            "<fieldset class=\"flex flex-wrap gap-4 [&>*]:w-full [&>button]:w-auto [&>a]:w-auto\">",
        );
        html.push_str(&format!(
            "<legend class=\"text-base font-semibold text-text\">{}</legend>",
            html_escape(&props.title)
        ));
        if let Some(ref desc) = props.description {
            html.push_str(&format!(
                "<p class=\"text-sm text-text-muted\">{}</p>",
                html_escape(desc)
            ));
        }
        html.push_str("<div class=\"space-y-4\">");
        html.push_str(&body);
        html.push_str("</div></fieldset>");
        html
    }
}

/// Horizontal button row. Renders each child ID in `el.children` and wraps
/// the resulting HTML in a `<div class="flex items-center gap-2 flex-wrap">`
/// container. `ButtonGroupProps.gap` is decoded for prop-shape diagnostics
/// but does not influence the emitted CSS (the gap is fixed at `gap-2`).
pub(crate) fn render_button_group(el: &Element, spec: &Spec, data: &Value, depth: usize) -> String {
    // Decode-check: malformed props surface via HTML comment rather than crash.
    if !el.props.is_null() {
        if let Err(e) = serde_json::from_value::<ButtonGroupProps>(el.props.clone()) {
            return format!(
                "<!-- ferro-json-ui: failed to decode ButtonGroup props: {} -->",
                html_escape(&e.to_string())
            );
        }
    }

    let body: String = el
        .children
        .iter()
        .map(|cid| render_element(cid, spec, data, depth + 1))
        .collect();

    format!("<div class=\"flex items-center gap-2 flex-wrap\">{body}</div>")
}

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

    fn build_spec(elements: Vec<(&str, ElementBuilder)>) -> Spec {
        let mut b = Spec::builder();
        for (id, el) in elements {
            b = b.element(id, el);
        }
        b.build().expect("ok")
    }

    #[test]
    fn grid_recurses_children() {
        let spec = build_spec(vec![
            (
                "root",
                Element::new("Grid")
                    .prop("columns", 2)
                    .child("a")
                    .child("b"),
            ),
            ("a", Element::new("Text").prop("content", "AAA")),
            ("b", Element::new("Text").prop("content", "BBB")),
        ]);
        let el = spec.elements.get("root").unwrap();
        let html = render_grid(el, &spec, &json!({}), 1);
        assert!(html.contains("grid-cols-2"), "got: {html}");
        assert!(html.starts_with("<div class=\"grid"), "got: {html}");
    }

    #[test]
    fn grid_scrollable_emits_flow_col() {
        let spec = build_spec(vec![(
            "root",
            Element::new("Grid").prop("scrollable", true),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_grid(el, &spec, &json!({}), 1);
        assert!(html.contains("grid-flow-col"), "got: {html}");
        assert!(html.contains("overflow-x-auto"), "got: {html}");
    }

    #[test]
    fn grid_renders_when_visible_true() {
        use crate::visibility::{Visibility, VisibilityCondition, VisibilityOperator};
        let spec = build_spec(vec![(
            "root",
            Element::new("Grid")
                .prop("columns", 1)
                .visible(Visibility::Condition(VisibilityCondition {
                    path: "/flag".into(),
                    operator: VisibilityOperator::Eq,
                    value: Some(json!(true)),
                })),
        )]);
        let html = crate::render::render_spec_to_html(&spec, &json!({"flag": true}));
        assert!(
            html.contains("<div class=\"grid"),
            "Grid must render when visible-true; got: {html}"
        );
    }

    #[test]
    fn grid_hidden_when_visible_false() {
        use crate::visibility::{Visibility, VisibilityCondition, VisibilityOperator};
        let spec = build_spec(vec![(
            "root",
            Element::new("Grid")
                .prop("columns", 1)
                .visible(Visibility::Condition(VisibilityCondition {
                    path: "/flag".into(),
                    operator: VisibilityOperator::Eq,
                    value: Some(json!(true)),
                })),
        )]);
        let html = crate::render::render_spec_to_html(&spec, &json!({"flag": false}));
        assert!(
            !html.contains("<div class=\"grid"),
            "Grid must be absent when visible-false; got: {html}"
        );
    }

    #[test]
    fn grid_visible_consumer_reproduction() {
        // Mirrors the consumer's chip-strip spec from
        // gestiscilo-it/app/src/views/calendario/calendar_day.json:73-85.
        // The chip-strip Grid is nested inside a root Grid, with visibility gated
        // on `/has_staff`. The consumer reports the inner Grid does not render
        // when has_staff=true; RESEARCH predicts this fails to reproduce against
        // current ferro master (the visibility evaluator architecture is correct).
        //
        // Outcome A (predicted): both branches pass — F9 closes as no-repro.
        // Outcome B (alternate): one or both branches fail — Task 3 investigates.
        use crate::visibility::{Visibility, VisibilityCondition, VisibilityOperator};
        let chip_strip_visible = Visibility::Condition(VisibilityCondition {
            path: "/has_staff".into(),
            operator: VisibilityOperator::Eq,
            value: Some(json!(true)),
        });
        let spec = build_spec(vec![
            (
                "root",
                Element::new("Grid")
                    .prop("columns", 1)
                    .child("staff_chips_row"),
            ),
            (
                "staff_chips_row",
                Element::new("Grid")
                    .prop("columns", 1)
                    .prop("gap", "sm")
                    .visible(chip_strip_visible.clone()),
            ),
        ]);

        let html_visible = crate::render::render_spec_to_html(&spec, &json!({"has_staff": true}));
        assert!(
            html_visible.matches("<div class=\"grid").count() >= 2,
            "inner Grid must render when has_staff=true (outer + inner = at least 2 grid divs); got: {html_visible}"
        );

        let html_hidden = crate::render::render_spec_to_html(&spec, &json!({"has_staff": false}));
        assert_eq!(
            html_hidden.matches("<div class=\"grid").count(),
            1,
            "only outer Grid renders when has_staff=false (inner Grid hidden, leaving exactly 1 grid div); got: {html_hidden}"
        );
    }

    #[test]
    fn collapsible_emits_details_summary() {
        let spec = build_spec(vec![(
            "root",
            Element::new("Collapsible").prop("title", "More"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_collapsible(el, &spec, &json!({}), 1);
        assert!(html.starts_with("<details"), "got: {html}");
        assert!(html.contains("<summary"), "got: {html}");
        assert!(html.contains("More"), "title missing; got: {html}");
        assert!(html.contains("aria-expanded=\"false\""), "got: {html}");
    }

    #[test]
    fn collapsible_expanded_sets_open_attribute() {
        let spec = build_spec(vec![(
            "root",
            Element::new("Collapsible")
                .prop("title", "Open me")
                .prop("expanded", true),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_collapsible(el, &spec, &json!({}), 1);
        assert!(
            html.starts_with("<details class=\"group\" open>"),
            "got: {html}"
        );
        assert!(html.contains("aria-expanded=\"true\""), "got: {html}");
    }

    #[test]
    fn form_section_emits_title_escaped() {
        let spec = build_spec(vec![(
            "root",
            Element::new("FormSection").prop("title", "<b>X</b>"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_form_section(el, &spec, &json!({}), 1);
        assert!(
            html.contains("&lt;b&gt;X&lt;/b&gt;"),
            "title must be escaped; got: {html}"
        );
        assert!(
            !html.contains("<b>X</b>"),
            "raw HTML must not appear; got: {html}"
        );
    }

    #[test]
    fn form_section_two_column_layout() {
        let spec = build_spec(vec![(
            "root",
            Element::new("FormSection")
                .prop("title", "Profile")
                .prop("description", "Update your info")
                .prop("layout", "two_column"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_form_section(el, &spec, &json!({}), 1);
        assert!(html.contains("md:grid-cols-5"), "got: {html}");
        assert!(html.contains("md:col-span-2"), "got: {html}");
        assert!(html.contains("md:col-span-3"), "got: {html}");
        assert!(html.contains("Update your info"), "got: {html}");
    }

    #[test]
    fn button_group_wraps_in_flex_row() {
        let spec = build_spec(vec![(
            "root",
            Element::new("ButtonGroup").prop("gap", "sm"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_button_group(el, &spec, &json!({}), 1);
        assert_eq!(
            html, "<div class=\"flex items-center gap-2 flex-wrap\"></div>",
            "got: {html}"
        );
    }

    // ── Multi-slot container tests ──────────────────────────────────────
    //
    // These tests check the container's wrapper markup, slot recursion
    // sites, and diagnostic behavior rather than the atom child content.

    #[test]
    fn card_emits_wrapper_and_title_escaped() {
        let spec = build_spec(vec![(
            "root",
            Element::new("Card").prop("title", "<b>T</b>"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_card(el, &spec, &json!({}), 1);
        assert!(
            html.contains("rounded-lg border border-border bg-card"),
            "got: {html}"
        );
        assert!(
            html.contains("&lt;b&gt;T&lt;/b&gt;"),
            "title must be escaped; got: {html}"
        );
        assert!(
            !html.contains("<b>T</b>"),
            "raw HTML must not appear; got: {html}"
        );
    }

    #[test]
    fn card_renders_body_wrapper_when_children_present() {
        // With child IDs in Element.children, Card emits the body wrapper div.
        // Verifies Element.children is the body slot.
        let spec = build_spec(vec![
            (
                "root",
                Element::new("Card").prop("title", "Hi").child("body1"),
            ),
            ("body1", Element::new("Text").prop("content", "BODY")),
        ]);
        let el = spec.elements.get("root").unwrap();
        let html = render_card(el, &spec, &json!({}), 1);
        assert!(
            html.contains("<div class=\"mt-3 flex flex-wrap gap-3"),
            "body wrapper missing; got: {html}"
        );
    }

    #[test]
    fn card_renders_footer_wrapper_from_props() {
        // Footer slot lives in CardProps.footer. Footer wrapper is emitted
        // whenever props.footer is non-empty, regardless of whether the
        // referenced atoms resolve.
        let spec = build_spec(vec![
            (
                "root",
                Element::new("Card")
                    .prop("title", "Hi")
                    .prop("footer", json!(["foot1"])),
            ),
            ("foot1", Element::new("Button").prop("label", "FOOT")),
        ]);
        let el = spec.elements.get("root").unwrap();
        let html = render_card(el, &spec, &json!({}), 1);
        assert!(
            html.contains("border-t border-border px-6 py-4"),
            "footer wrapper missing; got: {html}"
        );
    }

    #[test]
    fn card_missing_footer_id_rejected_at_parse_time() {
        // Dangling footer IDs are caught at spec build/parse time rather
        // than at render time; `SpecError::FooterMissing` is the parse-time
        // rejection variant.
        let err = Spec::builder()
            .element(
                "root",
                Element::new("Card")
                    .prop("title", "T")
                    .prop("footer", json!(["ghost"])),
            )
            .build()
            .unwrap_err();
        match err {
            crate::spec::SpecError::FooterMissing {
                element_id,
                footer_id,
            } => {
                assert_eq!(element_id, "root");
                assert_eq!(footer_id, "ghost");
            }
            other => panic!("expected FooterMissing, got {other:?}"),
        }
    }

    #[test]
    fn render_card_bordered_default() {
        let spec = build_spec(vec![("root", Element::new("Card").prop("title", "X"))]);
        let el = spec.elements.get("root").unwrap();
        let html = render_card(el, &spec, &json!({}), 0);
        assert!(
            html.contains("border border-border"),
            "expected Bordered class, got: {html}"
        );
        assert!(
            html.contains("shadow-sm"),
            "expected shadow-sm, got: {html}"
        );
        assert!(html.contains("p-4"), "expected p-4, got: {html}");
    }

    #[test]
    fn render_card_elevated_no_border() {
        let spec = build_spec(vec![(
            "root",
            Element::new("Card")
                .prop("title", "X")
                .prop("variant", "elevated"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_card(el, &spec, &json!({}), 0);
        assert!(
            html.contains("shadow-md"),
            "expected shadow-md, got: {html}"
        );
        assert!(html.contains("p-8"), "expected p-8, got: {html}");
        assert!(
            !html.contains("border-border"),
            "Elevated must NOT contain border-border, got: {html}"
        );
    }

    #[test]
    fn render_card_omitted_variant_is_bordered() {
        let spec = build_spec(vec![("root", Element::new("Card").prop("title", "X"))]);
        let el = spec.elements.get("root").unwrap();
        let html = render_card(el, &spec, &json!({}), 0);
        assert!(
            html.contains("border border-border"),
            "missing variant defaults to Bordered, got: {html}"
        );
    }

    #[test]
    fn card_max_width_narrow_wraps_in_mx_auto() {
        let spec = build_spec(vec![(
            "root",
            Element::new("Card")
                .prop("title", "T")
                .prop("max_width", "narrow"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_card(el, &spec, &json!({}), 1);
        assert!(
            html.starts_with("<div class=\"max-w-2xl mx-auto\">"),
            "narrow wrapper missing; got: {html}"
        );
    }

    #[test]
    fn render_card_emits_badge_when_present() {
        let spec = build_spec(vec![(
            "root",
            Element::new("Card")
                .prop("title", "Booking")
                .prop("badge", "Scade tra 9m"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_card(el, &spec, &json!({}), 0);
        assert!(
            html.contains("Scade tra 9m"),
            "badge label must appear in DOM; got: {html}"
        );
        assert!(
            html.contains("bg-secondary/10"),
            "badge must use Secondary chrome; got: {html}"
        );
        assert!(
            html.contains("flex items-start justify-between"),
            "title-row wrapper must be emitted when badge present; got: {html}"
        );
    }

    #[test]
    fn render_card_omits_badge_when_absent() {
        let spec = build_spec(vec![("root", Element::new("Card").prop("title", "X"))]);
        let el = spec.elements.get("root").unwrap();
        let html = render_card(el, &spec, &json!({}), 0);
        assert!(
            !html.contains("bg-secondary/10"),
            "no badge chrome when badge absent; got: {html}"
        );
        assert!(
            !html.contains("flex items-start justify-between"),
            "no title-row wrapper when badge absent; got: {html}"
        );
    }

    #[test]
    fn render_card_emits_subtitle_when_present() {
        let spec = build_spec(vec![(
            "root",
            Element::new("Card")
                .prop("title", "Booking")
                .prop("subtitle", "Marco Rossi"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_card(el, &spec, &json!({}), 0);
        assert!(
            html.contains("Marco Rossi"),
            "subtitle text must appear in DOM; got: {html}"
        );
        assert!(
            html.contains("mt-0.5 text-sm text-text-muted"),
            "subtitle must use muted styling with mt-0.5 spacing; got: {html}"
        );
    }

    #[test]
    fn render_card_omits_subtitle_when_absent() {
        let spec = build_spec(vec![("root", Element::new("Card").prop("title", "X"))]);
        let el = spec.elements.get("root").unwrap();
        let html = render_card(el, &spec, &json!({}), 0);
        // The description block uses `mt-1 text-sm text-text-muted`; the subtitle
        // would use `mt-0.5 text-sm text-text-muted`. With neither subtitle nor
        // description, no muted-text paragraph should emit at all.
        assert!(
            !html.contains("text-sm text-text-muted"),
            "no muted text when both subtitle and description absent; got: {html}"
        );
    }

    #[test]
    fn render_card_emits_title_subtitle_description_badge_together() {
        let spec = build_spec(vec![(
            "root",
            Element::new("Card")
                .prop("title", "Booking #1")
                .prop("subtitle", "Marco Rossi")
                .prop("description", "Customer detail")
                .prop("badge", "Scade tra 9m"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_card(el, &spec, &json!({}), 0);
        assert!(html.contains("Booking #1"), "title; got: {html}");
        assert!(html.contains("Marco Rossi"), "subtitle; got: {html}");
        assert!(html.contains("Customer detail"), "description; got: {html}");
        assert!(html.contains("Scade tra 9m"), "badge; got: {html}");
        // Slot order: title-row (with badge) → subtitle → description.
        let title_pos = html.find("Booking #1").expect("title present");
        let subtitle_pos = html.find("Marco Rossi").expect("subtitle present");
        let desc_pos = html.find("Customer detail").expect("description present");
        assert!(
            title_pos < subtitle_pos,
            "title must precede subtitle; got: {html}"
        );
        assert!(
            subtitle_pos < desc_pos,
            "subtitle must precede description; got: {html}"
        );
    }

    #[test]
    fn modal_emits_trigger_and_dialog() {
        let spec = build_spec(vec![(
            "root",
            Element::new("Modal")
                .prop("id", "m1")
                .prop("title", "Confirm"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_modal(el, &spec, &json!({}), 1);
        assert!(html.contains("data-modal-open=\"m1\""), "got: {html}");
        assert!(html.contains("<dialog id=\"m1\""), "got: {html}");
        assert!(html.contains("aria-labelledby=\"m1-title\""), "got: {html}");
        assert!(html.contains("Confirm"), "title missing; got: {html}");
    }

    #[test]
    fn modal_renders_footer_wrapper_from_props() {
        let spec = build_spec(vec![
            (
                "root",
                Element::new("Modal")
                    .prop("id", "m1")
                    .prop("title", "Confirm")
                    .prop("footer", json!(["f1"])),
            ),
            ("f1", Element::new("Button").prop("label", "Yes")),
        ]);
        let el = spec.elements.get("root").unwrap();
        let html = render_modal(el, &spec, &json!({}), 1);
        assert!(
            html.contains("mt-6 flex items-center justify-end gap-2"),
            "footer wrapper missing; got: {html}"
        );
    }

    #[test]
    fn tabs_renders_per_tab_panels() {
        // Both tabs carry children → both tabpanels render. Children come
        // from Tab.children.
        let spec = build_spec(vec![
            (
                "root",
                Element::new("Tabs").prop("default_tab", "a").prop(
                    "tabs",
                    json!([
                        {"value": "a", "label": "A", "children": ["t1"]},
                        {"value": "b", "label": "B", "children": ["t2"]},
                    ]),
                ),
            ),
            ("t1", Element::new("Text").prop("content", "PANEL_A")),
            ("t2", Element::new("Text").prop("content", "PANEL_B")),
        ]);
        let el = spec.elements.get("root").unwrap();
        let html = render_tabs(el, &spec, &json!({}), 1);
        assert!(
            html.contains("data-tabs"),
            "tab container missing; got: {html}"
        );
        assert!(
            html.contains("data-tab-panel=\"a\""),
            "panel a missing; got: {html}"
        );
        assert!(
            html.contains("data-tab-panel=\"b\""),
            "panel b missing; got: {html}"
        );
        assert!(
            html.contains("data-tab=\"a\""),
            "client-side tab trigger a missing; got: {html}"
        );
        assert!(
            html.contains("data-tab=\"b\""),
            "client-side tab trigger b missing; got: {html}"
        );
    }

    #[test]
    fn tabs_single_tab_auto_hides_bar() {
        let spec = build_spec(vec![
            (
                "root",
                Element::new("Tabs").prop("default_tab", "a").prop(
                    "tabs",
                    json!([{"value": "a", "label": "A", "children": ["t1"]}]),
                ),
            ),
            ("t1", Element::new("Text").prop("content", "ONLY")),
        ]);
        let el = spec.elements.get("root").unwrap();
        let html = render_tabs(el, &spec, &json!({}), 1);
        // Single-tab auto-hide: no tab bar markup, no data-tab attribute.
        assert!(
            !html.contains("data-tab=\"a\""),
            "tab bar should be hidden for single-tab; got: {html}"
        );
        assert!(
            !html.contains("data-tabs"),
            "tab container wrapper should be skipped; got: {html}"
        );
        // Single-tab still emits the panel wrapper div.
        assert!(
            html.starts_with("<div class=\"flex flex-wrap gap-4"),
            "got: {html}"
        );
    }

    #[test]
    fn tabs_empty_children_uses_server_driven_link() {
        // All tabs have empty children → has_any_content is false → every tab
        // renders as <a href="?tab=X"> (server-driven fallback, CONTEXT
        // non-obvious behavior).
        let spec = build_spec(vec![(
            "root",
            Element::new("Tabs").prop("default_tab", "a").prop(
                "tabs",
                json!([
                    {"value": "a", "label": "A", "children": []},
                    {"value": "b", "label": "B", "children": []},
                ]),
            ),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_tabs(el, &spec, &json!({}), 1);
        assert!(
            html.contains("href=\"?tab=a\""),
            "expected server-driven link for tab a; got: {html}"
        );
        assert!(
            html.contains("href=\"?tab=b\""),
            "expected server-driven link for tab b; got: {html}"
        );
        // No client-side data-tab attributes on the triggers.
        assert!(
            !html.contains("data-tab=\"a\""),
            "server-driven fallback must not emit data-tab; got: {html}"
        );
    }

    #[test]
    fn kanban_renders_columns_desktop_and_mobile() {
        let spec = build_spec(vec![
            (
                "root",
                Element::new("KanbanBoard").prop(
                    "columns",
                    json!([
                        {"id": "todo", "title": "Todo", "count": 1, "children": ["c1"]},
                        {"id": "done", "title": "Done", "count": 0, "children": ["c2"]},
                    ]),
                ),
            ),
            ("c1", Element::new("Text").prop("content", "FIRST_CARD")),
            ("c2", Element::new("Text").prop("content", "SECOND_CARD")),
        ]);
        let el = spec.elements.get("root").unwrap();
        let html = render_kanban_board(el, &spec, &json!({}), 1);
        // Desktop horizontal-scroll wrapper.
        assert!(
            html.contains("hidden md:block overflow-x-auto"),
            "desktop wrapper missing; got: {html}"
        );
        // Mobile tab-based wrapper.
        assert!(
            html.contains("block md:hidden"),
            "mobile wrapper missing; got: {html}"
        );
        // Column titles escaped and present.
        assert!(html.contains("Todo"), "got: {html}");
        assert!(html.contains("Done"), "got: {html}");
        // Per-column data-tab-panel markers.
        assert!(
            html.contains("data-tab-panel=\"todo\""),
            "todo panel missing; got: {html}"
        );
        assert!(
            html.contains("data-tab-panel=\"done\""),
            "done panel missing; got: {html}"
        );
        // Active count badge vs. zero count badge.
        assert!(
            html.contains("bg-primary text-primary-foreground"),
            "active count badge class missing; got: {html}"
        );
    }

    #[test]
    fn kanban_honors_mobile_default_column() {
        let spec = build_spec(vec![(
            "root",
            Element::new("KanbanBoard")
                .prop("mobile_default_column", "done")
                .prop(
                    "columns",
                    json!([
                        {"id": "todo", "title": "Todo", "count": 0, "children": []},
                        {"id": "done", "title": "Done", "count": 0, "children": []},
                    ]),
                ),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_kanban_board(el, &spec, &json!({}), 1);
        // The "done" mobile panel is the visible one (no " hidden" suffix);
        // "todo" is hidden on mobile. Panels are scrollable so the kanban
        // never grows the page past the viewport.
        assert!(
            html.contains(
                "data-tab-panel=\"done\" class=\"ferro-kanban-scroll space-y-3 overflow-y-auto\""
            ),
            "done should be the visible mobile panel; got: {html}"
        );
        assert!(
            html.contains(
                "data-tab-panel=\"todo\" class=\"ferro-kanban-scroll space-y-3 overflow-y-auto hidden\""
            ),
            "todo should be hidden on mobile; got: {html}"
        );
    }

    #[test]
    fn kanban_empty_columns_returns_empty() {
        let spec = build_spec(vec![(
            "root",
            Element::new("KanbanBoard").prop("columns", json!([])),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_kanban_board(el, &spec, &json!({}), 1);
        assert_eq!(html, "", "empty columns must render empty; got: {html}");
    }

    #[test]
    fn page_header_renders_title_and_breadcrumb() {
        let spec = build_spec(vec![(
            "root",
            Element::new("PageHeader").prop("title", "Dashboard").prop(
                "breadcrumb",
                json!([
                    {"label": "Home", "url": "/"},
                    {"label": "Reports"},
                ]),
            ),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_page_header(el, &spec, &json!({}), 1);
        assert!(html.contains("Dashboard"), "title missing; got: {html}");
        assert!(
            html.contains("<a href=\"/\""),
            "first breadcrumb should be an anchor; got: {html}"
        );
        assert!(html.contains("Home"), "got: {html}");
        assert!(html.contains("Reports"), "got: {html}");
        // Second breadcrumb has no URL → rendered as <span>.
        assert!(
            html.contains(
                "<span class=\"text-sm text-text-muted whitespace-nowrap\">Reports</span>"
            ),
            "urlless breadcrumb should be a span; got: {html}"
        );
    }

    #[test]
    fn page_header_renders_actions_wrapper_from_props() {
        let spec = build_spec(vec![
            (
                "root",
                Element::new("PageHeader")
                    .prop("title", "Dashboard")
                    .prop("actions", json!(["b1"])),
            ),
            ("b1", Element::new("Button").prop("label", "Create")),
        ]);
        let el = spec.elements.get("root").unwrap();
        let html = render_page_header(el, &spec, &json!({}), 1);
        assert!(html.contains("Dashboard"), "got: {html}");
        assert!(
            html.contains("flex flex-wrap items-center gap-2"),
            "actions wrapper missing; got: {html}"
        );
    }

    #[test]
    fn page_header_renders_children_as_body_below_chrome() {
        // Phase 165 F11: previously PageHeader silently dropped
        // Element.children. The body block now renders below the chrome.
        let spec = build_spec(vec![
            (
                "root",
                Element::new("PageHeader")
                    .prop("title", "Customers")
                    .child("body_card"),
            ),
            (
                "body_card",
                Element::new("Card").prop("title", "Customer list"),
            ),
        ]);
        let el = spec.elements.get("root").unwrap();
        let html = render_page_header(el, &spec, &json!({}), 1);
        assert!(
            html.contains("Customers"),
            "header title missing; got: {html}"
        );
        assert!(
            html.contains("Customer list"),
            "child Card body missing — F11 regression; got: {html}"
        );
        // Chrome closes before body container opens.
        let chrome_close = html
            .find("</div><div class=\"flex flex-col gap-4\">")
            .or_else(|| html.find("</div>\n<div class=\"flex flex-col gap-4\">"));
        assert!(
            chrome_close.is_some(),
            "body wrapper must follow the chrome div; got: {html}"
        );
    }

    #[test]
    fn page_header_with_empty_children_is_unchanged() {
        // Back-compat: no children → no body wrapper, same HTML shape as before.
        let spec = build_spec(vec![(
            "root",
            Element::new("PageHeader").prop("title", "Static"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_page_header(el, &spec, &json!({}), 1);
        assert!(html.contains("Static"));
        assert!(
            !html.contains("flex flex-col gap-4"),
            "body wrapper must not appear when children list is empty; got: {html}"
        );
    }

    #[test]
    fn page_header_missing_action_id_emits_diagnostic() {
        // Parallel to Card.footer: PageHeader.actions IDs are not
        // graph-validated at parse time. The walker's missing-id diagnostic
        // catches them at render time.
        let spec = build_spec(vec![(
            "root",
            Element::new("PageHeader")
                .prop("title", "T")
                .prop("actions", json!(["ghost"])),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_page_header(el, &spec, &json!({}), 1);
        assert!(
            html.contains("<!-- ferro-json-ui: element references missing id 'ghost' -->"),
            "got: {html}"
        );
    }

    // ── KanbanBoard structure/content tests ─────────────────────────────

    fn kanban_data_bound(extra: Vec<(&str, Value)>) -> ElementBuilder {
        let mut el = Element::new("KanbanBoard")
            .prop(
                "columns",
                json!([
                    {"title": "Open", "id": "open"},
                    {"title": "Done", "id": "done"}
                ]),
            )
            .prop("items_path", "/items")
            .prop("group_by", "status")
            .prop("card_title_key", "name");
        for (k, v) in extra {
            el = el.prop(k, v);
        }
        el
    }

    #[test]
    fn render_kanban_board_buckets_items_into_columns() {
        let spec = build_spec(vec![("root", kanban_data_bound(vec![]))]);
        let el = spec.elements.get("root").unwrap();
        let data = json!({"items": [
            {"id": 1, "name": "Alpha", "status": "open"},
            {"id": 2, "name": "Beta", "status": "done"},
            {"id": 3, "name": "Gamma", "status": "open"}
        ]});
        let html = render_kanban_board(el, &spec, &data, 0);
        // Both lanes render (structure always present).
        assert!(html.contains(">Open<"), "lane Open missing: {html}");
        assert!(html.contains(">Done<"), "lane Done missing: {html}");
        // Cards land in their lanes.
        assert!(html.contains("Alpha"), "Alpha card missing: {html}");
        assert!(html.contains("Beta"), "Beta card missing: {html}");
        assert!(html.contains("Gamma"), "Gamma card missing: {html}");
        // Per-lane count badge: Open has 2 (desktop + mobile = 2 occurrences each).
        assert_eq!(
            html.matches(">2<").count(),
            1,
            "Open lane desktop count badge should read 2: {html}"
        );
    }

    #[test]
    fn render_kanban_board_static_columns_always_render() {
        // Columns present but no matching items → lanes still render (not blank).
        let spec = build_spec(vec![("root", kanban_data_bound(vec![]))]);
        let el = spec.elements.get("root").unwrap();
        let data = json!({"items": []});
        let html = render_kanban_board(el, &spec, &data, 0);
        assert!(
            html.contains(">Open<"),
            "empty lane Open must render: {html}"
        );
        assert!(
            html.contains(">Done<"),
            "empty lane Done must render: {html}"
        );
    }

    #[test]
    fn render_kanban_board_empty_columns_renders_empty() {
        let spec = build_spec(vec![(
            "root",
            Element::new("KanbanBoard").prop("items_path", "/items"),
        )]);
        let el = spec.elements.get("root").unwrap();
        let html = render_kanban_board(el, &spec, &json!({"items": []}), 0);
        assert_eq!(html, "", "no columns → empty board; got: {html}");
    }

    #[test]
    fn render_kanban_board_card_description_and_actions() {
        let spec = build_spec(vec![(
            "root",
            kanban_data_bound(vec![
                ("card_description_key", json!("customer")),
                (
                    "row_actions",
                    json!([{"label": "View", "action": {"handler": "/orders/{row_key}"}}]),
                ),
                ("row_key", json!("id")),
            ]),
        )]);
        let el = spec.elements.get("root").unwrap();
        let data = json!({"items": [
            {"id": 7, "name": "Alpha", "status": "open", "customer": "Acme"}
        ]});
        let html = render_kanban_board(el, &spec, &data, 0);
        assert!(html.contains("Acme"), "card description missing: {html}");
        assert!(html.contains("View"), "row action missing: {html}");
        assert!(
            html.contains("/orders/7"),
            "row_key interpolation missing: {html}"
        );
    }
}