fd-core 0.1.18

FD (Fast Draft) — core data model, parser, emitter, and layout solver
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
use super::*;
use crate::parser::parse_document;

#[test]
fn roundtrip_simple() {
    let input = r#"
rect @box {
  w: 100
  h: 50
  fill: #FF0000
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);

    // Re-parse the emitted output
    let graph2 = parse_document(&output).expect("re-parse of emitted output failed");
    let node2 = graph2.get_by_id(NodeId::intern("box")).unwrap();

    match &node2.kind {
        NodeKind::Rect { width, height } => {
            assert_eq!(*width, 100.0);
            assert_eq!(*height, 50.0);
        }
        _ => panic!("expected Rect"),
    }
}

#[test]
fn roundtrip_ellipse() {
    let input = r#"
ellipse @dot {
  w: 40 h: 40
  fill: #00FF00
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of ellipse failed");
    let node = graph2.get_by_id(NodeId::intern("dot")).unwrap();
    match &node.kind {
        NodeKind::Ellipse { rx, ry } => {
            assert_eq!(*rx, 40.0);
            assert_eq!(*ry, 40.0);
        }
        _ => panic!("expected Ellipse"),
    }
}

#[test]
fn roundtrip_text_with_font() {
    let input = r#"
text @title "Hello" {
  font: "Inter" 700 32
  fill: #1A1A2E
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of text failed");
    let node = graph2.get_by_id(NodeId::intern("title")).unwrap();
    match &node.kind {
        NodeKind::Text { content, .. } => assert_eq!(content, "Hello"),
        _ => panic!("expected Text"),
    }
    let font = node.props.font.as_ref().expect("font missing");
    assert_eq!(font.family, "Inter");
    assert_eq!(font.weight, 700);
    assert_eq!(font.size, 32.0);
}

#[test]
fn roundtrip_nested_group() {
    let input = r#"
group @card {
  layout: column gap=16 pad=24

  text @heading "Title" {
font: "Inter" 600 20
fill: #333333
  }

  rect @body {
w: 300 h: 200
fill: #F5F5F5
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of nested group failed");
    let card_idx = graph2.index_of(NodeId::intern("card")).unwrap();
    assert_eq!(graph2.children(card_idx).len(), 2);
}

#[test]
fn roundtrip_animation() {
    let input = r#"
rect @btn {
  w: 200 h: 48
  fill: #6C5CE7

  anim :hover {
fill: #5A4BD1
scale: 1.2
ease: spring 300ms
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of animation failed");
    let btn = graph2.get_by_id(NodeId::intern("btn")).unwrap();
    assert_eq!(btn.animations.len(), 1);
    assert_eq!(btn.animations[0].trigger, AnimTrigger::Hover);
}

#[test]
fn roundtrip_style_and_use() {
    let input = r#"
style accent {
  fill: #6C5CE7
  corner: 10
}

rect @btn {
  w: 200 h: 48
  use: accent
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of style+use failed");
    assert!(graph2.styles.contains_key(&NodeId::intern("accent")));
    let btn = graph2.get_by_id(NodeId::intern("btn")).unwrap();
    assert_eq!(btn.use_styles.len(), 1);
}

#[test]
fn roundtrip_note_inline() {
    let input = r#"
rect @box {
  note "Primary container for content"
  w: 100 h: 50
  fill: #FF0000
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("box")).unwrap();
    assert_eq!(node.spec.as_deref(), Some("Primary container for content"));

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of note failed");
    let node2 = graph2.get_by_id(NodeId::intern("box")).unwrap();
    assert_eq!(node2.spec, node.spec);
}

#[test]
fn roundtrip_note_block_markdown() {
    let input = r#"
rect @login_btn {
  note {
    - [ ] disabled state when fields empty
    - [ ] loading spinner during auth
  }
  w: 280 h: 48
  fill: #6C5CE7
}
"#;
    let graph = parse_document(input).unwrap();
    let btn = graph.get_by_id(NodeId::intern("login_btn")).unwrap();
    let note = btn.spec.as_ref().expect("should have spec");
    assert!(note.contains("disabled state when fields empty"));
    assert!(note.contains("loading spinner during auth"));

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of note block failed");
    let btn2 = graph2.get_by_id(NodeId::intern("login_btn")).unwrap();
    assert_eq!(btn2.spec, btn.spec);
}

#[test]
fn roundtrip_note_multiline_content() {
    // Raw markdown content is preserved through parse → emit → re-parse
    let input = r#"
rect @card {
  note {
    ## Card Features
    - Dark mode support
    - Responsive layout
  }
  w: 300 h: 200
}
"#;
    let graph = parse_document(input).unwrap();
    let card = graph.get_by_id(NodeId::intern("card")).unwrap();
    let note = card.spec.as_ref().expect("should have spec");
    assert!(note.contains("## Card Features"));
    assert!(note.contains("Dark mode support"));

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of multiline note failed");
    let card2 = graph2.get_by_id(NodeId::intern("card")).unwrap();
    assert_eq!(card2.spec, card.spec);
}

#[test]
fn roundtrip_note_nested() {
    let input = r#"
group @form {
  layout: column gap=16 pad=32
  note "User authentication entry point"

  rect @email {
    note {
      Validates email format on blur
    }
    w: 280 h: 44
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let form = graph.get_by_id(NodeId::intern("form")).unwrap();
    assert_eq!(
        form.spec.as_deref(),
        Some("User authentication entry point")
    );
    let email = graph.get_by_id(NodeId::intern("email")).unwrap();
    assert!(email.spec.is_some());

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of nested note failed");
    let form2 = graph2.get_by_id(NodeId::intern("form")).unwrap();
    assert_eq!(form2.spec, form.spec);
    let email2 = graph2.get_by_id(NodeId::intern("email")).unwrap();
    assert_eq!(email2.spec, email.spec);
}

#[test]
fn parse_note_raw_content() {
    let input = r#"
rect @widget {
  note {
    # Widget Notes
    Some description text
    - [ ] criterion one
    - [x] done item
  }
  w: 100 h: 100
}
"#;
    let graph = parse_document(input).unwrap();
    let w = graph.get_by_id(NodeId::intern("widget")).unwrap();
    let note = w.spec.as_ref().expect("should have spec");
    assert!(note.contains("# Widget Notes"));
    assert!(note.contains("criterion one"));
    assert!(note.contains("done item"));
}

#[test]
fn roundtrip_edge_basic() {
    let input = r#"
rect @box_a {
  w: 100 h: 50
}

rect @box_b {
  w: 100 h: 50
}

edge @a_to_b {
  from: @box_a
  to: @box_b
  label: "next step"
  arrow: end
}
"#;
    let graph = parse_document(input).unwrap();
    assert_eq!(graph.edges.len(), 1);
    let edge = &graph.edges[0];
    assert_eq!(edge.id.as_str(), "a_to_b");
    assert_eq!(edge.from, EdgeAnchor::Node(NodeId::intern("box_a")));
    assert_eq!(edge.to, EdgeAnchor::Node(NodeId::intern("box_b")));
    // label: "next step" auto-creates text child
    let text_id = edge.text_child.expect("text_child should be set");
    assert_eq!(text_id.as_str(), "_a_to_b_label");
    let text_node = graph.get_by_id(text_id).expect("text node should exist");
    if let NodeKind::Text { content, .. } = &text_node.kind {
        assert_eq!(content, "next step");
    } else {
        panic!("expected Text node");
    }
    assert_eq!(edge.arrow, ArrowKind::End);

    // Re-parse roundtrip — emitter writes nested text block
    let output = emit_document(&graph);
    assert!(output.contains("text @_a_to_b_label \"next step\" {}"));

    let graph2 = parse_document(&output).expect("roundtrip failed");
    assert_eq!(graph2.edges.len(), 1);
    let edge2 = &graph2.edges[0];
    assert_eq!(edge2.from, EdgeAnchor::Node(NodeId::intern("box_a")));
    assert_eq!(edge2.to, EdgeAnchor::Node(NodeId::intern("box_b")));
    assert!(edge2.text_child.is_some());
    assert_eq!(edge2.arrow, ArrowKind::End);
}

#[test]
fn roundtrip_edge_styled() {
    let input = r#"
rect @s1 { w: 50 h: 50 }
rect @s2 { w: 50 h: 50 }

edge @flow {
  from: @s1
  to: @s2
  stroke: #6C5CE7 2
  arrow: both
  curve: smooth
}
"#;
    let graph = parse_document(input).unwrap();
    assert_eq!(graph.edges.len(), 1);
    let edge = &graph.edges[0];
    assert_eq!(edge.arrow, ArrowKind::Both);
    assert_eq!(edge.curve, CurveKind::Smooth);
    assert!(edge.props.stroke.is_some());

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("styled edge roundtrip failed");
    let edge2 = &graph2.edges[0];
    assert_eq!(edge2.arrow, ArrowKind::Both);
    assert_eq!(edge2.curve, CurveKind::Smooth);
}

#[test]
fn roundtrip_edge_with_note() {
    let input = r#"
rect @login { w: 200 h: 100 }
rect @dashboard { w: 200 h: 100 }

edge @login_flow {
  note {
    Main authentication flow
    Must redirect within 2s
  }
  from: @login
  to: @dashboard
  label: "on success"
  arrow: end
}
"#;
    let graph = parse_document(input).unwrap();
    let edge = &graph.edges[0];
    let note = edge.spec.as_ref().expect("edge should have spec");
    assert!(note.contains("Main authentication flow"));
    assert!(note.contains("redirect within 2s"));

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("noted edge roundtrip failed");
    let edge2 = &graph2.edges[0];
    assert_eq!(edge2.spec, edge.spec);
}

#[test]
fn roundtrip_generic_node() {
    let input = r#"
@login_btn {
  note {
    Primary CTA — triggers login API call
    - [ ] disabled when fields empty
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("login_btn")).unwrap();
    assert!(matches!(node.kind, NodeKind::Generic));
    assert!(node.spec.is_some());

    let output = emit_document(&graph);
    assert!(output.contains("@login_btn {"));
    assert!(!output.contains("rect @login_btn"));
    assert!(!output.contains("group @login_btn"));

    let graph2 = parse_document(&output).expect("re-parse of generic node failed");
    let node2 = graph2.get_by_id(NodeId::intern("login_btn")).unwrap();
    assert!(matches!(node2.kind, NodeKind::Generic));
    assert_eq!(node2.spec, node.spec);
}

#[test]
fn roundtrip_generic_nested() {
    let input = r#"
group @form {
  layout: column gap=16 pad=32

  @email_input {
    note "Email field with validation"
  }

  @password_input {
    note "Password field (min 8 chars)"
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let form_idx = graph.index_of(NodeId::intern("form")).unwrap();
    assert_eq!(graph.children(form_idx).len(), 2);

    let email = graph.get_by_id(NodeId::intern("email_input")).unwrap();
    assert!(matches!(email.kind, NodeKind::Generic));
    assert!(email.spec.is_some());

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of nested generic failed");
    let email2 = graph2.get_by_id(NodeId::intern("email_input")).unwrap();
    assert!(matches!(email2.kind, NodeKind::Generic));
    assert_eq!(email2.spec, email.spec);
}

#[test]
fn parse_generic_with_properties() {
    let input = r#"
@card {
  fill: #FFFFFF
  corner: 8
}
"#;
    let graph = parse_document(input).unwrap();
    let card = graph.get_by_id(NodeId::intern("card")).unwrap();
    assert!(matches!(card.kind, NodeKind::Generic));
    assert!(card.props.fill.is_some());
    assert_eq!(card.props.corner_radius, Some(8.0));
}

#[test]
fn roundtrip_edge_with_trigger_anim() {
    let input = r#"
rect @a { w: 50 h: 50 }
rect @b { w: 50 h: 50 }

edge @hover_edge {
  from: @a
  to: @b
  stroke: #6C5CE7 2
  arrow: end

  anim :hover {
opacity: 0.5
ease: ease_out 200ms
  }
}
"#;
    let graph = parse_document(input).unwrap();
    assert_eq!(graph.edges.len(), 1);
    let edge = &graph.edges[0];
    assert_eq!(edge.animations.len(), 1);
    assert_eq!(edge.animations[0].trigger, AnimTrigger::Hover);
    assert_eq!(edge.animations[0].duration_ms, 200);

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("trigger anim roundtrip failed");
    let edge2 = &graph2.edges[0];
    assert_eq!(edge2.animations.len(), 1);
    assert_eq!(edge2.animations[0].trigger, AnimTrigger::Hover);
}

#[test]
fn roundtrip_edge_with_flow() {
    let input = r#"
rect @src { w: 50 h: 50 }
rect @dst { w: 50 h: 50 }

edge @data {
  from: @src
  to: @dst
  arrow: end
  flow: pulse 800ms
}
"#;
    let graph = parse_document(input).unwrap();
    let edge = &graph.edges[0];
    assert!(edge.flow.is_some());
    let flow = edge.flow.unwrap();
    assert_eq!(flow.kind, FlowKind::Pulse);
    assert_eq!(flow.duration_ms, 800);

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("flow roundtrip failed");
    let edge2 = &graph2.edges[0];
    let flow2 = edge2.flow.unwrap();
    assert_eq!(flow2.kind, FlowKind::Pulse);
    assert_eq!(flow2.duration_ms, 800);
}

#[test]
fn roundtrip_edge_dash_flow() {
    let input = r#"
rect @x { w: 50 h: 50 }
rect @y { w: 50 h: 50 }

edge @dashed {
  from: @x
  to: @y
  stroke: #EF4444 1
  flow: dash 400ms
  arrow: both
  curve: step
}
"#;
    let graph = parse_document(input).unwrap();
    let edge = &graph.edges[0];
    let flow = edge.flow.unwrap();
    assert_eq!(flow.kind, FlowKind::Dash);
    assert_eq!(flow.duration_ms, 400);
    assert_eq!(edge.arrow, ArrowKind::Both);
    assert_eq!(edge.curve, CurveKind::Step);

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("dash flow roundtrip failed");
    let edge2 = &graph2.edges[0];
    let flow2 = edge2.flow.unwrap();
    assert_eq!(flow2.kind, FlowKind::Dash);
    assert_eq!(flow2.duration_ms, 400);
}

#[test]
fn roundtrip_edge_point_anchors() {
    let input = r#"
edge @standalone {
  from: 100 200
  to: 300 150
  arrow: end
}
"#;
    let graph = parse_document(input).unwrap();
    assert_eq!(graph.edges.len(), 1);
    let edge = &graph.edges[0];
    assert_eq!(edge.from, EdgeAnchor::Point(100.0, 200.0));
    assert_eq!(edge.to, EdgeAnchor::Point(300.0, 150.0));
    assert_eq!(edge.arrow, ArrowKind::End);

    let output = emit_document(&graph);
    assert!(output.contains("from: 100 200"));
    assert!(output.contains("to: 300 150"));

    let graph2 = parse_document(&output).expect("point anchor roundtrip failed");
    let edge2 = &graph2.edges[0];
    assert_eq!(edge2.from, EdgeAnchor::Point(100.0, 200.0));
    assert_eq!(edge2.to, EdgeAnchor::Point(300.0, 150.0));
}

#[test]
fn roundtrip_edge_mixed_anchors() {
    let input = r#"
rect @start { w: 50 h: 50 }

edge @dangling {
  from: @start
  to: 400 300
  arrow: end
}
"#;
    let graph = parse_document(input).unwrap();
    assert_eq!(graph.edges.len(), 1);
    let edge = &graph.edges[0];
    assert_eq!(edge.from, EdgeAnchor::Node(NodeId::intern("start")));
    assert_eq!(edge.to, EdgeAnchor::Point(400.0, 300.0));

    let output = emit_document(&graph);
    assert!(output.contains("from: @start"));
    assert!(output.contains("to: 400 300"));

    let graph2 = parse_document(&output).expect("mixed anchor roundtrip failed");
    let edge2 = &graph2.edges[0];
    assert_eq!(edge2.from, EdgeAnchor::Node(NodeId::intern("start")));
    assert_eq!(edge2.to, EdgeAnchor::Point(400.0, 300.0));
}

#[test]
fn parse_edge_omitted_anchors_default() {
    let input = r#"
edge @no_endpoints {
  arrow: end
}
"#;
    let graph = parse_document(input).unwrap();
    assert_eq!(graph.edges.len(), 1);
    let edge = &graph.edges[0];
    assert_eq!(edge.from, EdgeAnchor::Point(0.0, 0.0));
    assert_eq!(edge.to, EdgeAnchor::Point(0.0, 0.0));
}

#[test]
fn test_notes_markdown_basic() {
    let input = r#"
rect @login_btn {
  note {
    ## Login Button
    - [ ] disabled when fields empty
    - [x] styled with brand colors
  }
  w: 280 h: 48
  fill: #6C5CE7
}
"#;
    let graph = parse_document(input).unwrap();
    let md = emit_spec_markdown(&graph, "login.fd");

    assert!(md.starts_with("# Spec: login.fd\n"));
    assert!(md.contains("## @login_btn `rect`"));
    assert!(md.contains("## Login Button"));
    assert!(md.contains("disabled when fields empty"));
    // Visual props must NOT appear
    assert!(!md.contains("280"));
    assert!(!md.contains("6C5CE7"));
}

#[test]
fn test_notes_markdown_nested() {
    let input = r#"
group @form {
  layout: column gap=16 pad=32
  note "Shipping address form"

  rect @email {
    note {
      Email input validation
    }
    w: 280 h: 44
  }

  rect @no_note {
    w: 100 h: 50
    fill: #CCC
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let md = emit_spec_markdown(&graph, "checkout.fd");

    assert!(md.contains("## @form `group`"));
    assert!(md.contains("### @email `rect`"));
    assert!(md.contains("Shipping address form"));
    assert!(md.contains("Email input validation"));
    // Node without note should be skipped
    assert!(!md.contains("no_note"));
}

#[test]
fn test_notes_markdown_with_edges() {
    let input = r#"
rect @login { w: 200 h: 100 }
rect @dashboard {
  note "Main dashboard"
  w: 200 h: 100
}

edge @auth_flow {
  note {
    Authentication flow details
  }
  from: @login
  to: @dashboard
  label: "on success"
  arrow: end
}
"#;
    let graph = parse_document(input).unwrap();
    let md = emit_spec_markdown(&graph, "flow.fd");

    assert!(md.contains("## Flows"));
    assert!(md.contains("**@login** → **@dashboard**"));
    assert!(md.contains("on success"));
    assert!(md.contains("Authentication flow details"));
}

#[test]
fn roundtrip_import_basic() {
    let input = "import \"components/buttons.fd\" as btn\nrect @hero { w: 200 h: 100 }\n";
    let graph = parse_document(input).unwrap();
    assert_eq!(graph.imports.len(), 1);
    assert_eq!(graph.imports[0].path, "components/buttons.fd");
    assert_eq!(graph.imports[0].namespace, "btn");

    let output = emit_document(&graph);
    assert!(output.contains("import \"components/buttons.fd\" as btn"));

    let graph2 = parse_document(&output).expect("re-parse of import failed");
    assert_eq!(graph2.imports.len(), 1);
    assert_eq!(graph2.imports[0].path, "components/buttons.fd");
    assert_eq!(graph2.imports[0].namespace, "btn");
}

#[test]
fn roundtrip_import_multiple() {
    let input =
        "import \"tokens.fd\" as tokens\nimport \"buttons.fd\" as btn\nrect @box { w: 50 h: 50 }\n";
    let graph = parse_document(input).unwrap();
    assert_eq!(graph.imports.len(), 2);
    assert_eq!(graph.imports[0].namespace, "tokens");
    assert_eq!(graph.imports[1].namespace, "btn");

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of multiple imports failed");
    assert_eq!(graph2.imports.len(), 2);
    assert_eq!(graph2.imports[0].namespace, "tokens");
    assert_eq!(graph2.imports[1].namespace, "btn");
}

#[test]
fn parse_import_without_alias_errors() {
    let input = "import \"missing_alias.fd\"\nrect @box { w: 50 h: 50 }\n";
    // This should fail because "as namespace" is missing
    let result = parse_document(input);
    assert!(result.is_err());
}

#[test]
fn roundtrip_comment_preserved() {
    // A `# comment` before a node should survive parse → emit → parse.
    let input = r#"
# This is a section header
rect @box {
  w: 100 h: 50
  fill: #FF0000
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(
        output.contains("# This is a section header"),
        "comment should appear in emitted output: {output}"
    );
    // Re-parse should also preserve it
    let graph2 = parse_document(&output).expect("re-parse of commented document failed");
    let node = graph2.get_by_id(NodeId::intern("box")).unwrap();
    assert_eq!(node.comments, vec!["This is a section header"]);
}

#[test]
fn roundtrip_multiple_comments_preserved() {
    let input = r#"
# Header section
# Subheading
rect @panel {
  w: 300 h: 200
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse failed");
    let node = graph2.get_by_id(NodeId::intern("panel")).unwrap();
    assert_eq!(node.comments.len(), 2);
    assert_eq!(node.comments[0], "Header section");
    assert_eq!(node.comments[1], "Subheading");
}

#[test]
fn roundtrip_inline_position() {
    let input = r#"
rect @placed {
  x: 100
  y: 200
  w: 50 h: 50
  fill: #FF0000
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("placed")).unwrap();

    // Should have a Position constraint from x:/y: parsing
    assert!(
        node.constraints
            .iter()
            .any(|c| matches!(c, Constraint::Position { .. })),
        "should have Position constraint"
    );

    // Emit and verify x:/y: appear inline (not as top-level arrow)
    let output = emit_document(&graph);
    assert!(output.contains("x: 100"), "should emit x: inline");
    assert!(output.contains("y: 200"), "should emit y: inline");
    assert!(
        !output.contains("-> absolute"),
        "should NOT emit old absolute arrow"
    );
    assert!(
        !output.contains("-> position"),
        "should NOT emit position arrow"
    );

    // Round-trip: re-parse emitted output
    let graph2 = parse_document(&output).expect("re-parse of inline position failed");
    let node2 = graph2.get_by_id(NodeId::intern("placed")).unwrap();
    let pos = node2
        .constraints
        .iter()
        .find_map(|c| match c {
            Constraint::Position { x, y } => Some((*x, *y)),
            _ => None,
        })
        .expect("Position constraint missing after roundtrip");
    assert_eq!(pos, (100.0, 200.0));
}

#[test]
fn emit_children_before_styles() {
    let input = r#"
rect @box {
  w: 200 h: 100
  fill: #FF0000
  corner: 10
  text @label "Hello" {
fill: #FFFFFF
font: "Inter" 600 14
  }
  anim :hover {
fill: #CC0000
ease: ease_out 200ms
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);

    // Children should appear before inline appearance properties
    let child_pos = output.find("text @label").expect("child missing");
    let fill_pos = output.find("fill: #FF0000").expect("fill missing");
    let corner_pos = output.find("corner: 10").expect("corner missing");
    let anim_pos = output.find("when :hover").expect("when missing");

    assert!(
        child_pos < fill_pos,
        "children should appear before fill: child_pos={child_pos} fill_pos={fill_pos}"
    );
    assert!(
        child_pos < corner_pos,
        "children should appear before corner"
    );
    assert!(fill_pos < anim_pos, "fill should appear before animations");
}

#[test]
fn emit_section_separators() {
    let input = r#"
style accent {
  fill: #6C5CE7
}

rect @a {
  w: 100 h: 50
}

rect @b {
  w: 100 h: 50
}

edge @flow {
  from: @a
  to: @b
  arrow: end
}

@a -> center_in: canvas
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);

    assert!(
        output.contains("# ─── Styles ───"),
        "should have Styles separator"
    );
    assert!(
        output.contains("# ─── Layout ───"),
        "should have Layout separator"
    );
    assert!(
        output.contains("# ─── Flows ───"),
        "should have Flows separator"
    );
}

#[test]
fn roundtrip_children_before_styles() {
    let input = r#"
group @card {
  layout: column gap=12 pad=20
  text @title "Dashboard" {
font: "Inter" 600 20
fill: #111111
  }
  rect @body {
w: 300 h: 200
fill: #F5F5F5
  }
  fill: #FFFFFF
  corner: 8
  shadow: (0,2,8,#00000011)
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);

    // Re-parse the re-ordered output
    let graph2 = parse_document(&output).expect("re-parse of reordered output failed");
    let card_idx = graph2.index_of(NodeId::intern("card")).unwrap();
    assert_eq!(
        graph2.children(card_idx).len(),
        2,
        "card should still have 2 children after roundtrip"
    );

    // Verify children appear before appearance
    let child_pos = output.find("text @title").expect("child missing");
    let fill_pos = output.find("fill: #FFFFFF").expect("card fill missing");
    assert!(
        child_pos < fill_pos,
        "children should appear before parent fill"
    );
}

#[test]
fn roundtrip_style_keyword() {
    // Verify that `style` keyword parses and emits correctly
    let input = r#"
style accent {
  fill: #6C5CE7
  corner: 12
}

rect @btn {
  w: 120 h: 40
  use: accent
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);

    // Emitter should output `style`, not `theme` (legacy)
    assert!(
        output.contains("style accent"),
        "should emit `style` keyword"
    );
    assert!(
        !output.contains("theme accent"),
        "should NOT emit `theme` keyword"
    );

    // Round-trip: re-parse emitted output
    let graph2 = parse_document(&output).expect("re-parse of style output failed");
    assert!(
        graph2.styles.contains_key(&NodeId::intern("accent")),
        "style definition should survive roundtrip"
    );
}

#[test]
fn roundtrip_when_keyword() {
    // Verify that `when` keyword parses and emits correctly
    let input = r#"
rect @btn {
  w: 120 h: 40
  fill: #6C5CE7
  when :hover {
fill: #5A4BD1
ease: ease_out 200ms
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);

    // Emitter should output `when`, not `anim`
    assert!(output.contains("when :hover"), "should emit `when` keyword");
    assert!(
        !output.contains("anim :hover"),
        "should NOT emit `anim` keyword"
    );

    // Round-trip: re-parse emitted output
    let graph2 = parse_document(&output).expect("re-parse of when output failed");
    let node = graph2.get_by_id(NodeId::intern("btn")).unwrap();
    assert_eq!(
        node.animations.len(),
        1,
        "animation should survive roundtrip"
    );
    assert_eq!(
        node.animations[0].trigger,
        AnimTrigger::Hover,
        "trigger should be Hover"
    );
}

#[test]
fn parse_old_theme_keyword_compat() {
    // Old `theme` keyword must still be accepted by the parser
    let input = r#"
theme accent {
  fill: #6C5CE7
}

rect @btn {
  w: 120 h: 40
  use: accent
}
"#;
    let graph = parse_document(input).unwrap();
    assert!(
        graph.styles.contains_key(&NodeId::intern("accent")),
        "old `theme` keyword should parse into a style definition"
    );

    // Emitter should output `style`
    let output = emit_document(&graph);
    assert!(
        output.contains("style accent"),
        "emitter should output `style` keyword"
    );
}

#[test]
fn parse_old_anim_keyword_compat() {
    // Old `anim` keyword must still be accepted by the parser
    let input = r#"
rect @btn {
  w: 120 h: 40
  fill: #6C5CE7
  anim :press {
scale: 0.9
ease: spring 150ms
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("btn")).unwrap();
    assert_eq!(
        node.animations.len(),
        1,
        "old `anim` keyword should parse into animation"
    );
    assert_eq!(
        node.animations[0].trigger,
        AnimTrigger::Press,
        "trigger should be Press"
    );

    // Emitter should upgrade to `when`
    let output = emit_document(&graph);
    assert!(
        output.contains("when :press"),
        "emitter should upgrade `anim` to `when`"
    );
}

#[test]
fn roundtrip_style_import() {
    // Verify that import + style references work together
    let input = r#"
import "tokens.fd" as tokens

style card_base {
  fill: #FFFFFF
  corner: 16
}

rect @card {
  w: 300 h: 200
  use: card_base
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);

    // Both import and style should appear in output
    assert!(
        output.contains("import \"tokens.fd\" as tokens"),
        "import should survive roundtrip"
    );
    assert!(
        output.contains("style card_base"),
        "style should survive roundtrip"
    );

    // Re-parse
    let graph2 = parse_document(&output).expect("re-parse failed");
    assert_eq!(graph2.imports.len(), 1, "import count should survive");
    assert!(
        graph2.styles.contains_key(&NodeId::intern("card_base")),
        "style def should survive"
    );
}

// ─── Hardening: edge-case round-trip tests ─────────────────────────────

#[test]
fn roundtrip_empty_group() {
    // Empty groups (no children, no styles, no annotations) are stripped on emit.
    let input = "group @empty {\n}\n";
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(
        !output.contains("@empty"),
        "empty group should be stripped on emit, got: {output}"
    );
}

#[test]
fn emit_strips_empty_frame() {
    // Childless frame with no styles should be stripped on emit.
    let input = "frame @lonely {\n  w: 200 h: 100\n}\n";
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(
        !output.contains("@lonely"),
        "empty frame should be stripped on emit, got: {output}"
    );
}

#[test]
fn emit_keeps_styled_empty_frame() {
    // Childless frame WITH styles should be preserved.
    let input = "frame @styled {\n  w: 200 h: 100\n  fill: #FF0000\n}\n";
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(
        output.contains("@styled"),
        "styled empty frame should be preserved, got: {output}"
    );
}

#[test]
fn emit_keeps_group_with_children() {
    // Group with children must NOT be stripped.
    let input = "group @parent {\n  rect @child {\n    w: 40 h: 20\n  }\n}\n";
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(
        output.contains("@parent"),
        "group with children should be preserved, got: {output}"
    );
}

#[test]
fn roundtrip_deeply_nested_groups() {
    let input = r#"
group @outer {
  group @middle {
group @inner {
  rect @leaf {
    w: 40 h: 20
    fill: #FF0000
  }
}
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of nested groups failed");
    let leaf = graph2.get_by_id(NodeId::intern("leaf")).unwrap();
    assert!(matches!(leaf.kind, NodeKind::Rect { .. }));
    // Verify 3-level nesting preserved
    let inner_idx = graph2.index_of(NodeId::intern("inner")).unwrap();
    assert_eq!(graph2.children(inner_idx).len(), 1);
    let middle_idx = graph2.index_of(NodeId::intern("middle")).unwrap();
    assert_eq!(graph2.children(middle_idx).len(), 1);
}

#[test]
fn roundtrip_unicode_text() {
    let input = "text @emoji \"Hello 🎨 café 日本語\" {\n  fill: #333333\n}\n";
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(
        output.contains("Hello 🎨 café 日本語"),
        "unicode should survive emit"
    );
    let graph2 = parse_document(&output).expect("re-parse of unicode failed");
    let node = graph2.get_by_id(NodeId::intern("emoji")).unwrap();
    match &node.kind {
        NodeKind::Text { content, .. } => {
            assert!(content.contains("🎨"));
            assert!(content.contains("café"));
            assert!(content.contains("日本語"));
        }
        _ => panic!("expected Text node"),
    }
}

#[test]
fn roundtrip_note_all_fields() {
    // `spec` keyword still parses and round-trips correctly
    let input = r#"
rect @full_spec {
  spec {
    Full specification node
    - [ ] all fields present
    **Priority:** high
  }
  w: 100 h: 50
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("full_spec")).unwrap();
    assert!(node.spec.is_some());

    let output = emit_document(&graph);
    // Emitter should output `note` keyword (upgraded from `spec`)
    assert!(
        output.contains("spec {"),
        "emitter should output `spec` keyword, got: {output}"
    );
    let graph2 = parse_document(&output).expect("re-parse of full spec failed");
    let node2 = graph2.get_by_id(NodeId::intern("full_spec")).unwrap();
    assert_eq!(node2.spec, node.spec);
}

#[test]
fn roundtrip_path_node() {
    let input = "path @sketch {\n}\n";
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of path failed");
    let node = graph2.get_by_id(NodeId::intern("sketch")).unwrap();
    assert!(matches!(node.kind, NodeKind::Path { .. }));
}

#[test]
fn roundtrip_gradient_linear() {
    let input = r#"
rect @grad {
  w: 200 h: 100
  fill: linear(90deg, #FF0000 0, #0000FF 1)
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("grad")).unwrap();
    assert!(matches!(
        node.props.fill,
        Some(Paint::LinearGradient { .. })
    ));

    let output = emit_document(&graph);
    assert!(output.contains("linear("), "should emit linear gradient");
    let graph2 = parse_document(&output).expect("re-parse of linear gradient failed");
    let node2 = graph2.get_by_id(NodeId::intern("grad")).unwrap();
    assert!(matches!(
        node2.props.fill,
        Some(Paint::LinearGradient { .. })
    ));
}

#[test]
fn roundtrip_gradient_radial() {
    let input = r#"
rect @radial_box {
  w: 100 h: 100
  fill: radial(#FFFFFF 0, #000000 1)
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("radial_box")).unwrap();
    assert!(matches!(
        node.props.fill,
        Some(Paint::RadialGradient { .. })
    ));

    let output = emit_document(&graph);
    assert!(output.contains("radial("), "should emit radial gradient");
    let graph2 = parse_document(&output).expect("re-parse of radial gradient failed");
    let node2 = graph2.get_by_id(NodeId::intern("radial_box")).unwrap();
    assert!(matches!(
        node2.props.fill,
        Some(Paint::RadialGradient { .. })
    ));
}

#[test]
fn roundtrip_shadow_property() {
    let input = r#"
rect @shadowed {
  w: 200 h: 100
  shadow: (0,4,20,#000000)
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("shadowed")).unwrap();
    let shadow = node.props.shadow.as_ref().expect("shadow should exist");
    assert_eq!(shadow.blur, 20.0);

    let output = emit_document(&graph);
    assert!(output.contains("shadow:"), "should emit shadow");
    let graph2 = parse_document(&output).expect("re-parse of shadow failed");
    let node2 = graph2.get_by_id(NodeId::intern("shadowed")).unwrap();
    let shadow2 = node2.props.shadow.as_ref().expect("shadow should survive");
    assert_eq!(shadow2.offset_y, 4.0);
    assert_eq!(shadow2.blur, 20.0);
}

#[test]
fn roundtrip_opacity() {
    let input = r#"
rect @faded {
  w: 100 h: 100
  fill: #6C5CE7
  opacity: 0.5
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("faded")).unwrap();
    assert_eq!(node.props.opacity, Some(0.5));

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of opacity failed");
    let node2 = graph2.get_by_id(NodeId::intern("faded")).unwrap();
    assert_eq!(node2.props.opacity, Some(0.5));
}

#[test]
fn roundtrip_clip_frame() {
    let input = r#"
frame @clipped {
  w: 300 h: 200
  clip: true
  fill: #FFFFFF
  corner: 12
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(output.contains("clip: true"), "should emit clip");
    let graph2 = parse_document(&output).expect("re-parse of clip frame failed");
    let node = graph2.get_by_id(NodeId::intern("clipped")).unwrap();
    match &node.kind {
        NodeKind::Frame { clip, .. } => assert!(clip, "clip should be true"),
        _ => panic!("expected Frame node"),
    }
}

#[test]
fn roundtrip_multiple_animations() {
    let input = r#"
rect @animated {
  w: 120 h: 40
  fill: #6C5CE7
  when :hover {
fill: #5A4BD1
scale: 1.1
ease: ease_out 200ms
  }
  when :press {
scale: 0.9
ease: spring 150ms
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("animated")).unwrap();
    assert_eq!(node.animations.len(), 2, "should have 2 animations");

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of multi-anim failed");
    let node2 = graph2.get_by_id(NodeId::intern("animated")).unwrap();
    assert_eq!(node2.animations.len(), 2);
    assert_eq!(node2.animations[0].trigger, AnimTrigger::Hover);
    assert_eq!(node2.animations[1].trigger, AnimTrigger::Press);
}

#[test]
fn roundtrip_inline_note_shorthand() {
    // `note "..."` shorthand parses as inline note
    let input = r#"
rect @btn {
  note "Primary action button"
  w: 180 h: 48
  fill: #6C5CE7
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("btn")).unwrap();
    assert_eq!(node.spec.as_deref(), Some("Primary action button"));

    let output = emit_document(&graph);
    assert!(
        output.contains("spec \""),
        "emitter should output `spec` keyword: {output}"
    );
    let graph2 = parse_document(&output).expect("re-parse of inline note failed");
    let node2 = graph2.get_by_id(NodeId::intern("btn")).unwrap();
    assert_eq!(node2.spec, node.spec);
}

#[test]
fn roundtrip_note_keyword_block() {
    // `note { ... }` block captures raw markdown
    let input = r#"
rect @card {
  note {
    # Card component
    - [ ] responsive on mobile
    - [ ] dark mode
  }
  w: 200 h: 100
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("card")).unwrap();
    let note = node.spec.as_ref().expect("should have spec");
    assert!(note.contains("responsive on mobile"));

    let output = emit_document(&graph);
    assert!(output.contains("spec {"), "should emit note keyword");
    let graph2 = parse_document(&output).expect("re-parse of note keyword failed");
    let node2 = graph2.get_by_id(NodeId::intern("card")).unwrap();
    assert_eq!(node2.spec, node.spec);
}

#[test]
fn parse_note_checklist() {
    let input = r#"
rect @task {
  note {
    - [x] Pick the color
    - [x] Choose the font
  }
  w: 100 h: 50
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("task")).unwrap();
    let note = node.spec.as_ref().expect("should have spec");
    assert!(note.contains("Pick the color"));
    assert!(note.contains("Choose the font"));
}

#[test]
fn roundtrip_note_checklist() {
    let input = r#"
rect @task {
  note {
    A task card
    - [ ] Add animation
    - [x] Pick the font
  }
  w: 100 h: 50
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);

    assert!(output.contains("spec {"));
    assert!(output.contains("A task card"));

    let graph2 = parse_document(&output).expect("re-parse of checklist note failed");
    let node2 = graph2.get_by_id(NodeId::intern("task")).unwrap();
    let note = node2.spec.as_ref().expect("should have spec");
    assert!(note.contains("Add animation"));
    assert!(note.contains("Pick the font"));
}

#[test]
fn note_content_preserves_all_lines() {
    let input = r#"
rect @widget {
  note {
    Description text
    - [ ] Still need to do
    - [ ] Another todo
    - [x] Already done thing
    - [x] Another done
    **Tag:** important
  }
  w: 100 h: 50
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);

    let graph2 = parse_document(&output).expect("re-parse of note failed");
    let node = graph2.get_by_id(NodeId::intern("widget")).unwrap();
    let note = node.spec.as_ref().expect("should have spec");

    // All lines should be preserved in raw markdown
    assert!(note.contains("Description text"));
    assert!(note.contains("Still need to do"));
    assert!(note.contains("Another todo"));
    assert!(note.contains("Already done thing"));
    assert!(note.contains("important"));
}

#[test]
fn spec_keyword_captured_as_raw_note() {
    // Old `spec { ... }` content is captured as raw markdown
    let input = r#"
rect @old {
  spec {
    Legacy format text
    status: done
    accept: "old criterion"
  }
  w: 100 h: 50
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("old")).unwrap();
    let note = node.spec.as_ref().expect("should have spec");
    // Raw content is captured verbatim
    assert!(note.contains("Legacy format text"));
    assert!(note.contains("status: done"));

    let output = emit_document(&graph);
    // Emitter outputs `spec` (it's now the primary keyword)
    assert!(output.contains("spec {"), "should emit spec keyword");
    // Legacy `note` keyword should NOT appear in output
    assert!(!output.contains("note {"), "should not emit note keyword");
}

#[test]
fn roundtrip_layout_modes() {
    let input = r#"
frame @col {
  w: 400 h: 300
  layout: column gap=16 pad=24
  rect @c1 { w: 100 h: 50 }
}

frame @rw {
  w: 400 h: 300
  layout: row gap=8 pad=12
  rect @r1 { w: 50 h: 50 }
}

frame @grd {
  w: 400 h: 300
  layout: grid cols=2 gap=10 pad=20
  rect @g1 { w: 80 h: 80 }
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(output.contains("layout: column gap=16 pad=24"));
    assert!(output.contains("layout: row gap=8 pad=12"));
    assert!(output.contains("layout: grid cols=2 gap=10 pad=20"));

    let graph2 = parse_document(&output).expect("re-parse of layout modes failed");
    let col = graph2.get_by_id(NodeId::intern("col")).unwrap();
    assert!(matches!(col.kind, NodeKind::Frame { .. }));
    let rw = graph2.get_by_id(NodeId::intern("rw")).unwrap();
    assert!(matches!(rw.kind, NodeKind::Frame { .. }));
    let grd = graph2.get_by_id(NodeId::intern("grd")).unwrap();
    assert!(matches!(grd.kind, NodeKind::Frame { .. }));
}

// ─── emit_filtered tests ─────────────────────────────────────────────

fn make_test_graph() -> SceneGraph {
    // A rich document with styles, layout, anims, specs, and edges
    let input = r#"
style accent {
  fill: #6C5CE7
  font: "Inter" bold 16
}

frame @container {
  w: 600 h: 400
  layout: column gap=16 pad=24

  rect @card {
w: 200 h: 100
use: accent
fill: #FFFFFF
corner: 12
spec {
  "Main card component"
  status: done
}
when :hover {
  fill: #F0EDFF
  scale: 1.1
  ease: ease_out 200ms
}
  }

  text @label "Hello" {
font: "Inter" regular 14
fill: #333333
x: 20
y: 40
  }
}

edge @card_to_label {
  from: @card
  to: @label
  label: "displays"
}
"#;
    parse_document(input).unwrap()
}

#[test]
fn emit_filtered_full_matches_emit_document() {
    let graph = make_test_graph();
    let full = emit_filtered(&graph, ReadMode::Full);
    let doc = emit_document(&graph);
    assert_eq!(full, doc, "Full mode should be identical to emit_document");
}

#[test]
fn emit_filtered_structure() {
    let graph = make_test_graph();
    let out = emit_filtered(&graph, ReadMode::Structure);
    // Should have node declarations
    assert!(out.contains("frame @container"), "should include frame");
    assert!(out.contains("rect @card"), "should include rect");
    assert!(out.contains("text @label"), "should include text");
    // Should NOT have styles, dimensions, specs, or anims
    assert!(!out.contains("fill:"), "no fill in structure mode");
    assert!(!out.contains("spec"), "no spec in structure mode");
    assert!(!out.contains("when"), "no when in structure mode");
    assert!(!out.contains("style"), "no style in structure mode");
    assert!(!out.contains("edge"), "no edges in structure mode");
}

#[test]
fn emit_filtered_layout() {
    let graph = make_test_graph();
    let out = emit_filtered(&graph, ReadMode::Layout);
    // Should have layout + dimensions
    assert!(out.contains("layout: column"), "should include layout");
    assert!(out.contains("w: 200 h: 100"), "should include dims");
    assert!(out.contains("x: 20"), "should include position");
    // Should NOT have styles or anims
    assert!(!out.contains("fill:"), "no fill in layout mode");
    assert!(!out.contains("style"), "no style in layout mode");
    assert!(!out.contains("when :hover"), "no when in layout mode");
}

#[test]
fn emit_filtered_design() {
    let graph = make_test_graph();
    let out = emit_filtered(&graph, ReadMode::Design);
    // Should have style definitions
    assert!(out.contains("style accent"), "should include style");
    assert!(out.contains("use: accent"), "should include use ref");
    assert!(out.contains("fill:"), "should include fill");
    assert!(out.contains("corner: 12"), "should include corner");
    // Should NOT have layout or anims
    assert!(!out.contains("layout:"), "no layout in design mode");
    assert!(!out.contains("w: 200"), "no dims in design mode");
    assert!(!out.contains("when :hover"), "no when in design mode");
}

#[test]
fn emit_filtered_notes() {
    let graph = make_test_graph();
    let out = emit_filtered(&graph, ReadMode::Notes);
    // Should have spec blocks
    assert!(out.contains("spec"), "should include spec");
    assert!(out.contains("Main card component"), "should include desc");
    // Raw spec content is preserved
    assert!(
        out.contains("status: done"),
        "should include raw status line"
    );
    // Should NOT have styles or anims
    assert!(!out.contains("fill:"), "no fill in notes mode");
    assert!(!out.contains("when"), "no when in notes mode");
}

#[test]
fn emit_filtered_spec_alias() {
    // ReadMode::Spec (alias) should produce the same output as ReadMode::Notes
    let graph = make_test_graph();
    let notes_out = emit_filtered(&graph, ReadMode::Notes);
    let spec_out = emit_filtered(&graph, ReadMode::Spec);
    assert_eq!(notes_out, spec_out, "Spec should be alias for Notes");
}

#[test]
fn emit_filtered_visual() {
    let graph = make_test_graph();
    let out = emit_filtered(&graph, ReadMode::Visual);
    // Visual = Layout + Design + When
    assert!(out.contains("style accent"), "should include style");
    assert!(out.contains("layout: column"), "should include layout");
    assert!(out.contains("w: 200 h: 100"), "should include dims");
    assert!(out.contains("fill:"), "should include fill");
    assert!(out.contains("corner: 12"), "should include corner");
    assert!(out.contains("when :hover"), "should include when");
    assert!(out.contains("scale: 1.1"), "should include anim props");
    assert!(out.contains("edge @card_to_label"), "should include edges");
    // Should NOT have spec blocks
    assert!(
        !out.contains("Main card component"),
        "no spec desc in visual mode"
    );
}

#[test]
fn emit_filtered_when() {
    let graph = make_test_graph();
    let out = emit_filtered(&graph, ReadMode::When);
    // Should have when blocks
    assert!(out.contains("when :hover"), "should include when");
    assert!(out.contains("scale: 1.1"), "should include anim props");
    // Should NOT have node-level styles, layout, or spec
    assert!(!out.contains("corner:"), "no corner in when mode");
    assert!(!out.contains("w: 200"), "no dims in when mode");
    assert!(!out.contains("style"), "no style in when mode");
    assert!(!out.contains("spec"), "no spec in when mode");
}

#[test]
fn emit_filtered_edges() {
    let graph = make_test_graph();
    let out = emit_filtered(&graph, ReadMode::Edges);
    // Should have edges
    assert!(out.contains("edge @card_to_label"), "should include edge");
    assert!(out.contains("from: @card"), "should include from");
    assert!(out.contains("to: @label"), "should include to");
    assert!(
        out.contains("text @_card_to_label_label \"displays\" {}"),
        "should include text child"
    );
    // Should NOT have styles or anims
    assert!(!out.contains("fill:"), "no fill in edges mode");
    assert!(!out.contains("when"), "no when in edges mode");
}

#[test]
fn roundtrip_no_duplicate_separators() {
    // Document with styles + nodes + edge triggers section separators.
    // After multiple round-trips, separators must appear exactly once.
    let input = r#"
style accent {
  fill: #A29BFE
}

rect @a {
  w: 100 h: 50
  fill: #FF0000
}

rect @b {
  w: 80 h: 40
}

edge @link {
  from: @a
  to: @b
}
"#;
    let graph = parse_document(input).unwrap();
    let pass1 = emit_document(&graph);

    // Separators should exist
    assert!(
        pass1.contains("# ─── Styles ───"),
        "pass 1 should have Styles separator: {pass1}"
    );
    assert!(
        pass1.contains("# ─── Layout ───"),
        "pass 1 should have Layout separator: {pass1}"
    );

    // Round-trip again
    let graph2 = parse_document(&pass1).expect("re-parse failed");
    let pass2 = emit_document(&graph2);

    // Count occurrences — must be exactly 1 each
    let styles_count = pass2.matches("# ─── Styles ───").count();
    let layout_count = pass2.matches("# ─── Layout ───").count();
    let flows_count = pass2.matches("# ─── Flows ───").count();
    assert_eq!(styles_count, 1, "Styles separator duplicated: {pass2}");
    assert_eq!(layout_count, 1, "Layout separator duplicated: {pass2}");
    assert_eq!(flows_count, 1, "Flows separator duplicated: {pass2}");

    // Third round-trip for good measure
    let graph3 = parse_document(&pass2).expect("third parse failed");
    let pass3 = emit_document(&graph3);
    assert_eq!(
        pass3.matches("# ─── Layout ───").count(),
        1,
        "Layout separator grew after 3 round-trips: {pass3}"
    );
}

#[test]
fn roundtrip_user_comments_not_stripped() {
    // User comments (non-separator) must survive even with separators present.
    let input = r#"
style dark {
  fill: #1A1A2E
}

# Settings panel
rect @settings {
  w: 300 h: 200
}

rect @other {
  w: 50 h: 50
}

edge @link {
  from: @settings
  to: @other
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(
        output.contains("# Settings panel"),
        "user comment should survive: {output}"
    );
    // Separators should not be attached to nodes as comments
    let node = graph.get_by_id(NodeId::intern("settings")).unwrap();
    assert_eq!(
        node.comments,
        vec!["Settings panel"],
        "only user comment should be attached, not separators"
    );
}

// ─── Path d: command roundtrip tests ────────────────────────────────────

#[test]
fn roundtrip_path_with_commands() {
    let input = r#"
path @sketch {
  d: M 10 20 L 100 200 L 300 400
  stroke: #5E5CE6 2
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("sketch")).unwrap();
    match &node.kind {
        NodeKind::Path { commands } => {
            assert_eq!(commands.len(), 3, "should have 3 commands");
            assert!(matches!(commands[0], PathCmd::MoveTo(_, _)));
            assert!(matches!(commands[1], PathCmd::LineTo(_, _)));
        }
        _ => panic!("expected Path node"),
    }

    let output = emit_document(&graph);
    assert!(output.contains("d:"), "should emit d: property");
    assert!(output.contains("M 10 20"), "should emit MoveTo");

    let graph2 = parse_document(&output).expect("re-parse of path with commands failed");
    let node2 = graph2.get_by_id(NodeId::intern("sketch")).unwrap();
    match &node2.kind {
        NodeKind::Path { commands } => {
            assert_eq!(commands.len(), 3, "commands should survive roundtrip");
        }
        _ => panic!("expected Path node after roundtrip"),
    }
}

#[test]
fn roundtrip_path_cubic_and_close() {
    let input = r#"
path @curve {
  d: M 0 0 C 10 20 30 40 50 60 Z
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("curve")).unwrap();
    match &node.kind {
        NodeKind::Path { commands } => {
            assert_eq!(commands.len(), 3);
            assert!(matches!(commands[1], PathCmd::CubicTo(_, _, _, _, _, _)));
            assert!(matches!(commands[2], PathCmd::Close));
        }
        _ => panic!("expected Path"),
    }

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse failed");
    let node2 = graph2.get_by_id(NodeId::intern("curve")).unwrap();
    match &node2.kind {
        NodeKind::Path { commands } => {
            assert_eq!(commands.len(), 3, "cubic + close should survive roundtrip");
        }
        _ => panic!("expected Path"),
    }
}

#[test]
fn roundtrip_path_quad() {
    let input = r#"
path @quad_stroke {
  d: M 0 0 Q 50 100 100 0
  stroke: #FF0000 3
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("quad_stroke")).unwrap();
    match &node.kind {
        NodeKind::Path { commands } => {
            assert_eq!(commands.len(), 2);
            assert!(matches!(commands[1], PathCmd::QuadTo(_, _, _, _)));
        }
        _ => panic!("expected Path"),
    }

    let output = emit_document(&graph);
    assert!(output.contains("Q 50 100 100 0"), "should emit QuadTo");
    let graph2 = parse_document(&output).unwrap();
    let node2 = graph2.get_by_id(NodeId::intern("quad_stroke")).unwrap();
    match &node2.kind {
        NodeKind::Path { commands } => assert_eq!(commands.len(), 2),
        _ => panic!("expected Path"),
    }
}

#[test]
fn roundtrip_path_empty_commands() {
    // Path with no d: property — backward compatibility
    let input = "path @empty_path {\n  stroke: #333333 1\n}\n";
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("empty_path")).unwrap();
    match &node.kind {
        NodeKind::Path { commands } => assert!(commands.is_empty()),
        _ => panic!("expected Path"),
    }
    let output = emit_document(&graph);
    assert!(!output.contains("d:"), "empty commands should not emit d:");
    let graph2 = parse_document(&output).unwrap();
    let node2 = graph2.get_by_id(NodeId::intern("empty_path")).unwrap();
    assert!(matches!(node2.kind, NodeKind::Path { .. }));
}

// ─── Image node roundtrip tests ─────────────────────────────────────────

#[test]
fn roundtrip_image_basic() {
    let input = r#"
image @hero {
  w: 400 h: 300
  src: "assets/hero.png"
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("hero")).unwrap();
    match &node.kind {
        NodeKind::Image {
            source,
            width,
            height,
            fit,
        } => {
            match source {
                ImageSource::File(p) => assert_eq!(p, "assets/hero.png"),
            }
            assert_eq!(*width, 400.0);
            assert_eq!(*height, 300.0);
            assert_eq!(*fit, ImageFit::Cover); // Default
        }
        _ => panic!("expected Image node"),
    }

    let output = emit_document(&graph);
    assert!(output.contains("image @hero"), "should emit image keyword");
    assert!(
        output.contains("src: \"assets/hero.png\""),
        "should emit src"
    );
    assert!(
        !output.contains("fit:"),
        "default fit should not be emitted"
    );

    let graph2 = parse_document(&output).expect("re-parse of image failed");
    let node2 = graph2.get_by_id(NodeId::intern("hero")).unwrap();
    assert!(matches!(node2.kind, NodeKind::Image { .. }));
}

#[test]
fn roundtrip_image_with_fit() {
    let input = r#"
image @bg {
  w: 800 h: 600
  src: "bg.jpg"
  fit: contain
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("bg")).unwrap();
    match &node.kind {
        NodeKind::Image { fit, .. } => assert_eq!(*fit, ImageFit::Contain),
        _ => panic!("expected Image"),
    }

    let output = emit_document(&graph);
    assert!(
        output.contains("fit: contain"),
        "should emit non-default fit"
    );

    let graph2 = parse_document(&output).unwrap();
    let node2 = graph2.get_by_id(NodeId::intern("bg")).unwrap();
    match &node2.kind {
        NodeKind::Image { fit, .. } => assert_eq!(*fit, ImageFit::Contain),
        _ => panic!("expected Image"),
    }
}

#[test]
fn roundtrip_image_in_frame() {
    let input = r#"
frame @card {
  w: 400 h: 300
  clip: true
  image @photo {
    w: 400 h: 200
    src: "photo.png"
  }
  text @caption "Hello" {
    font: "Inter" regular 14
  }
}
"#;
    let graph = parse_document(input).unwrap();
    let card_idx = graph.index_of(NodeId::intern("card")).unwrap();
    assert_eq!(
        graph.children(card_idx).len(),
        2,
        "card should have 2 children"
    );

    let output = emit_document(&graph);
    let graph2 = parse_document(&output).expect("re-parse of image in frame failed");
    let card_idx2 = graph2.index_of(NodeId::intern("card")).unwrap();
    assert_eq!(graph2.children(card_idx2).len(), 2);
    let photo = graph2.get_by_id(NodeId::intern("photo")).unwrap();
    assert!(matches!(photo.kind, NodeKind::Image { .. }));
}

#[test]
fn roundtrip_image_with_styles() {
    let input = r#"
image @styled_img {
  w: 200 h: 150
  src: "icon.svg"
  fit: fill
  corner: 12
  opacity: 0.8
}
"#;
    let graph = parse_document(input).unwrap();
    let node = graph.get_by_id(NodeId::intern("styled_img")).unwrap();
    assert_eq!(node.props.corner_radius, Some(12.0));
    assert_eq!(node.props.opacity, Some(0.8));

    let output = emit_document(&graph);
    assert!(output.contains("corner: 12"));
    assert!(output.contains("opacity: 0.8"));
    assert!(output.contains("fit: fill"));

    let graph2 = parse_document(&output).unwrap();
    let node2 = graph2.get_by_id(NodeId::intern("styled_img")).unwrap();
    assert_eq!(node2.props.corner_radius, Some(12.0));
    assert_eq!(node2.props.opacity, Some(0.8));
    match &node2.kind {
        NodeKind::Image { fit, .. } => assert_eq!(*fit, ImageFit::Fill),
        _ => panic!("expected Image"),
    }
}

// ─── F1: 1-Decimal Precision tests ──────────────────────────────────────

#[test]
fn emit_format_num_one_decimal() {
    use crate::emitter::format_num;
    assert_eq!(format_num(128.57), "128.6");
    assert_eq!(format_num(100.0), "100");
    assert_eq!(format_num(0.5), "0.5");
    assert_eq!(format_num(3.14), "3.1");
    assert_eq!(format_num(42.0), "42");
}

#[test]
fn roundtrip_one_decimal_coords() {
    let input = "rect @box {\n  w: 128.6 h: 64.3\n  x: 10.5\n  y: 20.7\n  fill: #FF0000\n}\n";
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(output.contains("128.6"), "w should be 128.6: {output}");
    assert!(output.contains("64.3"), "h should be 64.3: {output}");
    let graph2 = parse_document(&output).expect("re-parse of 1dp coords failed");
    let node = graph2.get_by_id(NodeId::intern("box")).unwrap();
    match &node.kind {
        NodeKind::Rect { width, height } => {
            assert!((width - 128.6).abs() < 0.1);
            assert!((height - 64.3).abs() < 0.1);
        }
        _ => panic!("expected Rect"),
    }
}

// ─── F2: Edge Defaults tests ────────────────────────────────────────────

#[test]
fn parse_edge_defaults() {
    let input = r#"
edge_defaults {
  stroke: #6B7080 1.5
  arrow: end
  curve: smooth
}

rect @a { w: 50 h: 50 }
rect @b { w: 50 h: 50 }

edge @link {
  from: @a
  to: @b
  stroke: #6B7080 1.5
  arrow: end
  curve: smooth
}
"#;
    let graph = parse_document(input).unwrap();
    let defaults = graph
        .edge_defaults
        .as_ref()
        .expect("should have edge_defaults");
    assert!(defaults.props.stroke.is_some());
    assert_eq!(defaults.arrow, Some(ArrowKind::End));
    assert_eq!(defaults.curve, Some(CurveKind::Smooth));
}

#[test]
fn emit_edge_defaults_suppresses_matching() {
    let input = r#"
edge_defaults {
  stroke: #6B7080 1.5
  arrow: end
}

rect @a { w: 50 h: 50 }
rect @b { w: 50 h: 50 }

edge @link {
  from: @a
  to: @b
  stroke: #6B7080 1.5
  arrow: end
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    // edge_defaults block should be present
    assert!(
        output.contains("edge_defaults"),
        "should emit edge_defaults: {output}"
    );
    // Individual edge should NOT have stroke or arrow (they match defaults)
    let edge_section = output
        .split("edge @link")
        .nth(1)
        .expect("edge block missing");
    assert!(
        !edge_section.contains("stroke:"),
        "matching stroke should be suppressed: {edge_section}"
    );
    assert!(
        !edge_section.contains("arrow:"),
        "matching arrow should be suppressed: {edge_section}"
    );
}

#[test]
fn roundtrip_edge_defaults() {
    let input = r#"
edge_defaults {
  stroke: #6B7080 1.5
  arrow: end
  curve: smooth
}

rect @a { w: 50 h: 50 }
rect @b { w: 50 h: 50 }
rect @c { w: 50 h: 50 }

edge @ab {
  from: @a
  to: @b
  stroke: #6B7080 1.5
  arrow: end
  curve: smooth
}

edge @bc {
  from: @b
  to: @c
  stroke: #FF0000 2
  arrow: both
}
"#;
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);

    // Re-parse
    let graph2 = parse_document(&output).expect("re-parse of edge_defaults failed");
    assert!(graph2.edge_defaults.is_some());
    assert_eq!(graph2.edges.len(), 2);

    // bc edge should still have its own stroke/arrow
    let bc = graph2.edges.iter().find(|e| e.id.as_str() == "bc").unwrap();
    assert_eq!(bc.arrow, ArrowKind::Both);
    assert!(bc.props.stroke.is_some());
}

// ─── F5: ReadMode::Diff tests ───────────────────────────────────────────

#[test]
fn snapshot_and_diff_added_node() {
    use crate::emitter::{emit_diff, snapshot_graph};

    let input = "rect @a {\n  w: 100 h: 50\n  fill: #FF0000\n}\n";
    let graph1 = parse_document(input).unwrap();
    let snap = snapshot_graph(&graph1);

    // Add a node
    let input2 = "rect @a {\n  w: 100 h: 50\n  fill: #FF0000\n}\nrect @b {\n  w: 50 h: 50\n}\n";
    let graph2 = parse_document(input2).unwrap();
    let diff = emit_diff(&graph2, &snap);

    assert!(diff.contains("+ "), "should show added node: {diff}");
    assert!(diff.contains("@b"), "should mention @b: {diff}");
    assert!(!diff.contains("- @"), "no removals expected: {diff}");
}

#[test]
fn snapshot_and_diff_removed_node() {
    use crate::emitter::{emit_diff, snapshot_graph};

    let input = "rect @a {\n  w: 100 h: 50\n}\nrect @b {\n  w: 50 h: 50\n}\n";
    let graph1 = parse_document(input).unwrap();
    let snap = snapshot_graph(&graph1);

    // Remove @b
    let input2 = "rect @a {\n  w: 100 h: 50\n}\n";
    let graph2 = parse_document(input2).unwrap();
    let diff = emit_diff(&graph2, &snap);

    assert!(diff.contains("- @b"), "should show removed node: {diff}");
}

#[test]
fn snapshot_and_diff_modified_style() {
    use crate::emitter::{emit_diff, snapshot_graph};

    let input = "rect @a {\n  w: 100 h: 50\n  fill: #FF0000\n}\n";
    let graph1 = parse_document(input).unwrap();
    let snap = snapshot_graph(&graph1);

    // Change fill
    let input2 = "rect @a {\n  w: 100 h: 50\n  fill: #0000FF\n}\n";
    let graph2 = parse_document(input2).unwrap();
    let diff = emit_diff(&graph2, &snap);

    assert!(diff.contains("~ "), "should show modified node: {diff}");
    assert!(diff.contains("@a"), "should mention @a: {diff}");
}

#[test]
fn snapshot_no_changes() {
    use crate::emitter::{emit_diff, snapshot_graph};

    let input = "rect @a {\n  w: 100 h: 50\n  fill: #FF0000\n}\n";
    let graph = parse_document(input).unwrap();
    let snap = snapshot_graph(&graph);
    let diff = emit_diff(&graph, &snap);

    assert!(diff.contains("# No changes"), "unchanged graph: {diff}");
}

// ─── F6: Inline Doc-Comments tests ──────────────────────────────────────

#[test]
fn emit_no_auto_comment_text_node() {
    let input = "text @title \"Welcome Home\" {\n  fill: #333333\n}\n";
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(
        !output.contains("[auto]"),
        "text node should NOT get auto-comment (self-documenting): {output}"
    );
}

#[test]
fn emit_auto_comment_group_children() {
    let input = "group @panel {\n  rect @a { w: 50 h: 50 }\n  rect @b { w: 50 h: 50 }\n}\n";
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(
        output.contains("[auto] container (2 children)"),
        "group should get child count: {output}"
    );
}

#[test]
fn roundtrip_auto_comments_not_duplicated() {
    // Use a group (which still gets auto-comments) to test duplication
    let input = "group @panel {\n  rect @a { w: 50 h: 50 }\n}\n";
    let graph = parse_document(input).unwrap();
    let pass1 = emit_document(&graph);
    assert!(pass1.contains("[auto]"), "pass1 should have auto-comment");

    // Round-trip: [auto] should be skipped by parser, regenerated by emitter
    let graph2 = parse_document(&pass1).expect("re-parse failed");
    let pass2 = emit_document(&graph2);

    // Should have exactly one [auto] comment
    let auto_count = pass2.matches("[auto]").count();
    assert_eq!(auto_count, 1, "auto-comments should not duplicate: {pass2}");
}

#[test]
fn emit_auto_comment_styled_node() {
    let input =
        "style accent {\n  fill: #6C5CE7\n}\nrect @btn {\n  w: 120 h: 40\n  use: accent\n}\n";
    let graph = parse_document(input).unwrap();
    let output = emit_document(&graph);
    assert!(
        output.contains("[auto] styled: accent"),
        "node with use: should get styled comment: {output}"
    );
}