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
//! Core scene-graph data model for FD documents.
//!
//! The document is a DAG (Directed Acyclic Graph) where nodes represent
//! visual elements (shapes, text, groups) and edges represent parent→child
//! containment. Styles and animations are attached to nodes. Layout is
//! constraint-based — relationships are preferred over raw positions.
//! `Position { x, y }` is the escape hatch for drag-placed or pinned nodes.

use crate::id::NodeId;
use petgraph::graph::NodeIndex;
use petgraph::stable_graph::StableDiGraph;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use std::collections::HashMap;

// ─── Colors & Paint ──────────────────────────────────────────────────────

/// RGBA color. Stored as 4 × f32 [0.0, 1.0].
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Color {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

/// Compile-time lookup table for fast hex character parsing.
/// Maps ASCII bytes to their 0-15 hex value, or 255 if invalid.
/// This avoids branching (match statement) in the hot parsing path.
const HEX_LUT: [u8; 256] = {
    let mut lut = [255; 256];
    let mut i = 0;
    while i < 10 {
        lut[(b'0' + i) as usize] = i;
        i += 1;
    }
    let mut i = 0;
    while i < 6 {
        lut[(b'a' + i) as usize] = i + 10;
        lut[(b'A' + i) as usize] = i + 10;
        i += 1;
    }
    lut
};

/// Helper to parse a single hex digit.
#[inline(always)]
pub fn hex_val(c: u8) -> Option<u8> {
    let val = HEX_LUT[c as usize];
    if val != 255 { Some(val) } else { None }
}

impl Color {
    /// Create a new color from RGBA components.
    pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
        Self { r, g, b, a }
    }

    /// Parse a hex color string: `#RGB`, `#RGBA`, `#RRGGBB`, `#RRGGBBAA`.
    /// The string may optionally start with `#`.
    pub fn from_hex(hex: &str) -> Option<Self> {
        let hex = hex.strip_prefix('#').unwrap_or(hex);
        let bytes = hex.as_bytes();

        match bytes.len() {
            3 => {
                let r = hex_val(bytes[0])?;
                let g = hex_val(bytes[1])?;
                let b = hex_val(bytes[2])?;
                Some(Self::rgba(
                    (r * 17) as f32 / 255.0,
                    (g * 17) as f32 / 255.0,
                    (b * 17) as f32 / 255.0,
                    1.0,
                ))
            }
            4 => {
                let r = hex_val(bytes[0])?;
                let g = hex_val(bytes[1])?;
                let b = hex_val(bytes[2])?;
                let a = hex_val(bytes[3])?;
                Some(Self::rgba(
                    (r * 17) as f32 / 255.0,
                    (g * 17) as f32 / 255.0,
                    (b * 17) as f32 / 255.0,
                    (a * 17) as f32 / 255.0,
                ))
            }
            6 => {
                let r = hex_val(bytes[0])? << 4 | hex_val(bytes[1])?;
                let g = hex_val(bytes[2])? << 4 | hex_val(bytes[3])?;
                let b = hex_val(bytes[4])? << 4 | hex_val(bytes[5])?;
                Some(Self::rgba(
                    r as f32 / 255.0,
                    g as f32 / 255.0,
                    b as f32 / 255.0,
                    1.0,
                ))
            }
            8 => {
                let r = hex_val(bytes[0])? << 4 | hex_val(bytes[1])?;
                let g = hex_val(bytes[2])? << 4 | hex_val(bytes[3])?;
                let b = hex_val(bytes[4])? << 4 | hex_val(bytes[5])?;
                let a = hex_val(bytes[6])? << 4 | hex_val(bytes[7])?;
                Some(Self::rgba(
                    r as f32 / 255.0,
                    g as f32 / 255.0,
                    b as f32 / 255.0,
                    a as f32 / 255.0,
                ))
            }
            _ => None,
        }
    }

    /// Emit as shortest valid hex string.
    pub fn to_hex(&self) -> String {
        let r = (self.r * 255.0).round() as u8;
        let g = (self.g * 255.0).round() as u8;
        let b = (self.b * 255.0).round() as u8;
        let a = (self.a * 255.0).round() as u8;
        if a == 255 {
            format!("#{r:02X}{g:02X}{b:02X}")
        } else {
            format!("#{r:02X}{g:02X}{b:02X}{a:02X}")
        }
    }
}

/// A gradient stop.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GradientStop {
    pub offset: f32, // 0.0 .. 1.0
    pub color: Color,
}

/// Fill or stroke paint.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Paint {
    Solid(Color),
    LinearGradient {
        angle: f32, // degrees
        stops: Vec<GradientStop>,
    },
    RadialGradient {
        stops: Vec<GradientStop>,
    },
}

// ─── Stroke ──────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Stroke {
    pub paint: Paint,
    pub width: f32,
    pub cap: StrokeCap,
    pub join: StrokeJoin,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StrokeCap {
    Butt,
    Round,
    Square,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StrokeJoin {
    Miter,
    Round,
    Bevel,
}

impl Default for Stroke {
    fn default() -> Self {
        Self {
            paint: Paint::Solid(Color::rgba(0.0, 0.0, 0.0, 1.0)),
            width: 1.0,
            cap: StrokeCap::Butt,
            join: StrokeJoin::Miter,
        }
    }
}

// ─── Font / Text ─────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FontSpec {
    pub family: String,
    pub weight: u16, // 100..900
    pub size: f32,
}

impl Default for FontSpec {
    fn default() -> Self {
        Self {
            family: "Inter".into(),
            weight: 400,
            size: 14.0,
        }
    }
}

// ─── Path data ───────────────────────────────────────────────────────────

/// A single path command (SVG-like but simplified).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PathCmd {
    MoveTo(f32, f32),
    LineTo(f32, f32),
    QuadTo(f32, f32, f32, f32),            // control, end
    CubicTo(f32, f32, f32, f32, f32, f32), // c1, c2, end
    Close,
}

// ─── Image data ──────────────────────────────────────────────────────────

/// Source for an embedded image.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ImageSource {
    /// Relative file path: `src: "assets/hero.png"`.
    File(String),
}

/// How an image fits within its declared dimensions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ImageFit {
    /// Scale to cover bounds, crop overflow.
    #[default]
    Cover,
    /// Scale to fit within bounds, letterbox.
    Contain,
    /// Stretch to exact dimensions.
    Fill,
    /// Natural size, no scaling.
    None,
}

// ─── Shadow ──────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Shadow {
    pub offset_x: f32,
    pub offset_y: f32,
    pub blur: f32,
    pub color: Color,
}

// ─── Styling ─────────────────────────────────────────────────────────────

/// Horizontal text alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum TextAlign {
    Left,
    #[default]
    Center,
    Right,
}

/// Vertical text alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum TextVAlign {
    Top,
    #[default]
    Middle,
    Bottom,
}

/// Horizontal placement of a child within its parent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum HPlace {
    Left,
    #[default]
    Center,
    Right,
}

/// Vertical placement of a child within its parent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum VPlace {
    Top,
    #[default]
    Middle,
    Bottom,
}

/// A reusable style set that nodes can reference via `use: style_name`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Properties {
    pub fill: Option<Paint>,
    pub stroke: Option<Stroke>,
    pub font: Option<FontSpec>,
    pub corner_radius: Option<f32>,
    pub opacity: Option<f32>,
    pub shadow: Option<Shadow>,

    /// Horizontal text alignment (default: Center).
    pub text_align: Option<TextAlign>,
    /// Vertical text alignment (default: Middle).
    pub text_valign: Option<TextVAlign>,

    /// Scale factor applied during rendering (from animations).
    pub scale: Option<f32>,
}

// ─── Animation ───────────────────────────────────────────────────────────

/// The trigger for an animation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnimTrigger {
    Hover,
    Press,
    Enter, // viewport enter
    Custom(String),
}

/// Easing function.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Easing {
    Linear,
    EaseIn,
    EaseOut,
    EaseInOut,
    Spring,
    CubicBezier(f32, f32, f32, f32),
}

/// A property animation keyframe.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnimKeyframe {
    pub trigger: AnimTrigger,
    pub duration_ms: u32,
    pub easing: Easing,
    pub properties: AnimProperties,
    /// Optional post-revert cooldown (ms) before re-triggerable.
    /// `None` = no cooldown (default).
    pub delay_ms: Option<u32>,
}

/// Animatable property overrides.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AnimProperties {
    pub fill: Option<Paint>,
    pub opacity: Option<f32>,
    pub scale: Option<f32>,
    pub rotate: Option<f32>, // degrees
    pub translate: Option<(f32, f32)>,
}

// ─── Imports ─────────────────────────────────────────────────────────────

/// A file import declaration: `import "path.fd" as namespace`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Import {
    /// Relative file path, e.g. "components/buttons.fd".
    pub path: String,
    /// Namespace alias, e.g. "buttons".
    pub namespace: String,
}

// ─── Layout Constraints ──────────────────────────────────────────────────

/// Constraint-based layout — no absolute coordinates in the format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Constraint {
    /// Center this node within a target (e.g. `canvas` or another node).
    CenterIn(NodeId),
    /// Position relative: dx, dy from a reference node.
    Offset { from: NodeId, dx: f32, dy: f32 },
    /// Fill the parent with optional padding.
    FillParent { pad: f32 },
    /// Parent-relative position (used for drag-placed or pinned nodes).
    /// Resolved as `parent.x + x`, `parent.y + y` by the layout solver.
    Position { x: f32, y: f32 },
}

// ─── Edges (connections between nodes) ───────────────────────────────────

/// Arrow head placement on an edge.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ArrowKind {
    #[default]
    None,
    Start,
    End,
    Both,
}

/// How the edge path is drawn between two nodes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum CurveKind {
    #[default]
    Straight,
    Smooth,
    Step,
}

/// An edge endpoint — either connected to a node or a free point in scene-space.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum EdgeAnchor {
    /// Connected to a node center.
    Node(NodeId),
    /// Fixed position in scene-space (standalone arrow).
    Point(f32, f32),
}

impl EdgeAnchor {
    /// Return the NodeId if this is a Node anchor.
    pub fn node_id(&self) -> Option<NodeId> {
        match self {
            Self::Node(id) => Some(*id),
            Self::Point(_, _) => None,
        }
    }
}

/// Document-level default styles for edges.
///
/// When an `edge_defaults` block is present, individual edges omit
/// properties that match the defaults — saving tokens for documents
/// with many similarly styled edges.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct EdgeDefaults {
    pub props: Properties,
    pub arrow: Option<ArrowKind>,
    pub curve: Option<CurveKind>,
}

/// A visual connection between two endpoints.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Edge {
    pub id: NodeId,
    pub from: EdgeAnchor,
    pub to: EdgeAnchor,
    /// Optional text child node (max 1). The node lives in the SceneGraph.
    pub text_child: Option<NodeId>,
    pub props: Properties,
    pub use_styles: SmallVec<[NodeId; 2]>,
    pub arrow: ArrowKind,
    pub curve: CurveKind,
    pub spec: Option<String>,
    pub animations: SmallVec<[AnimKeyframe; 2]>,
    pub flow: Option<FlowAnim>,
    /// Offset of the edge text from the midpoint, set when label is dragged.
    pub label_offset: Option<(f32, f32)>,
}

/// Flow animation kind — continuous motion along the edge path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FlowKind {
    /// A glowing dot traveling from → to on a loop.
    Pulse,
    /// Marching dashes along the edge (stroke-dashoffset animation).
    Dash,
}

/// A flow animation attached to an edge.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct FlowAnim {
    pub kind: FlowKind,
    pub duration_ms: u32,
}

/// Group layout mode (for children arrangement).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LayoutMode {
    /// Free / absolute positioning of children.
    /// Optional padding insets the content area (default 0).
    Free { pad: f32 },
    /// Column (vertical stack).
    Column { gap: f32, pad: f32 },
    /// Row (horizontal stack).
    Row { gap: f32, pad: f32 },
    /// Grid layout.
    Grid { cols: u32, gap: f32, pad: f32 },
}

impl Default for LayoutMode {
    fn default() -> Self {
        LayoutMode::Free { pad: 0.0 }
    }
}

// ─── Scene Graph Nodes ───────────────────────────────────────────────────

/// The node kinds in the scene DAG.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum NodeKind {
    /// Root of the document.
    Root,

    /// Generic placeholder — no visual shape assigned yet.
    /// Used for spec-only nodes: `@login_btn { spec "CTA" }`
    Generic,

    /// Organizational container (like Figma Group).
    /// Auto-sizes to children, no own styles or layout modes.
    Group,

    /// Frame — visible container with explicit size and optional clipping.
    /// Like a Figma frame: has fill/stroke, declared dimensions, clips overflow.
    Frame {
        width: f32,
        height: f32,
        clip: bool,
        layout: LayoutMode,
    },

    /// Rectangle.
    Rect { width: f32, height: f32 },

    /// Ellipse / circle.
    Ellipse { rx: f32, ry: f32 },

    /// Freeform path (pen tool output).
    Path { commands: Vec<PathCmd> },

    /// Embedded image (R3.32).
    Image {
        source: ImageSource,
        width: f32,
        height: f32,
        fit: ImageFit,
    },

    /// Text label. Optional `max_width` constrains horizontal extent
    /// for word wrapping (set via resize handle drag).
    Text {
        content: String,
        max_width: Option<f32>,
    },
}

impl NodeKind {
    /// Return the FD format keyword for this node kind.
    pub fn kind_name(&self) -> &'static str {
        match self {
            Self::Root => "root",
            Self::Generic => "generic",
            Self::Group => "group",
            Self::Frame { .. } => "frame",
            Self::Rect { .. } => "rect",
            Self::Ellipse { .. } => "ellipse",
            Self::Path { .. } => "path",
            Self::Image { .. } => "image",
            Self::Text { .. } => "text",
        }
    }
}

/// A single node in the scene graph.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SceneNode {
    /// The node's ID (e.g. `@login_form`). Anonymous nodes get auto-IDs.
    pub id: NodeId,

    /// What kind of element this is.
    pub kind: NodeKind,

    /// Inline style overrides on this node.
    pub props: Properties,

    /// Named style references (`use: base_text`).
    pub use_styles: SmallVec<[NodeId; 2]>,

    /// Constraint-based positioning.
    pub constraints: SmallVec<[Constraint; 2]>,

    /// Animations attached to this node.
    pub animations: SmallVec<[AnimKeyframe; 2]>,

    /// Markdown spec content (`spec { ... }` block, also accepts legacy `note`).
    pub spec: Option<String>,

    /// Line comments (`# text`) that appeared before this node in the source.
    /// Preserved across parse/emit round-trips so format passes don't delete them.
    pub comments: Vec<String>,

    /// 9-position placement of this child within its parent.
    /// `None` = default positioning (auto-center for text, origin for others).
    pub place: Option<(HPlace, VPlace)>,

    /// Whether this node is locked (prevents move, resize, delete on canvas).
    /// Parsed from `locked: true` in the FD format.
    pub locked: bool,
}

impl SceneNode {
    /// Create a new SceneNode with a given ID and kind.
    pub fn new(id: NodeId, kind: NodeKind) -> Self {
        Self {
            id,
            kind,
            props: Properties::default(),
            use_styles: SmallVec::new(),
            constraints: SmallVec::new(),
            animations: SmallVec::new(),
            spec: None,
            comments: Vec::new(),
            place: None,
            locked: false,
        }
    }
}

// ─── Graph Snapshot (for ReadMode::Diff) ─────────────────────────────────

/// A lightweight snapshot of graph state for diff computation.
///
/// Stores per-node and per-edge hashes so that changes can be detected
/// by comparing hashes rather than storing full copies of the graph.
#[derive(Debug, Clone, Default)]
pub struct GraphSnapshot {
    /// Hash of each node's emitted text, keyed by NodeId.
    pub node_hashes: HashMap<NodeId, u64>,
    /// Hash of each edge's emitted text, keyed by edge id.
    pub edge_hashes: HashMap<NodeId, u64>,
}

// ─── Scene Graph ─────────────────────────────────────────────────────────

/// The complete FD document — a DAG of `SceneNode` values.
///
/// Edges go from parent → child. Style definitions are stored separately
/// in a hashmap for lookup by name.
#[derive(Debug, Clone)]
pub struct SceneGraph {
    /// The underlying directed graph.
    pub graph: StableDiGraph<SceneNode, ()>,

    /// The root node index.
    pub root: NodeIndex,

    /// Named style definitions (`style base_text { ... }`).
    pub styles: HashMap<NodeId, Properties>,

    /// Index from NodeId → NodeIndex for fast lookup.
    pub id_index: HashMap<NodeId, NodeIndex>,

    /// Visual edges (connections between nodes).
    pub edges: Vec<Edge>,

    /// File imports with namespace aliases.
    pub imports: Vec<Import>,

    /// Explicit child ordering set by `sort_nodes`.
    /// When present for a parent, `children()` returns this order
    /// instead of the default `NodeIndex` sort.
    pub sorted_child_order: HashMap<NodeIndex, Vec<NodeIndex>>,

    /// Document-level default styles for edges.
    /// When present, individual edge properties matching the defaults are omitted.
    pub edge_defaults: Option<EdgeDefaults>,
}

impl SceneGraph {
    /// Create a new empty scene graph with a root node.
    #[must_use]
    pub fn new() -> Self {
        let mut graph = StableDiGraph::new();
        let root_node = SceneNode::new(NodeId::intern("root"), NodeKind::Root);
        let root = graph.add_node(root_node);

        let mut id_index = HashMap::new();
        id_index.insert(NodeId::intern("root"), root);

        Self {
            graph,
            root,
            styles: HashMap::new(),
            id_index,
            edges: Vec::new(),
            imports: Vec::new(),
            sorted_child_order: HashMap::new(),
            edge_defaults: None,
        }
    }

    /// Add a node as a child of `parent`. Returns the new node's index.
    pub fn add_node(&mut self, parent: NodeIndex, node: SceneNode) -> NodeIndex {
        let id = node.id;
        let idx = self.graph.add_node(node);
        self.graph.add_edge(parent, idx, ());
        self.id_index.insert(id, idx);
        idx
    }

    /// Remove a node safely, keeping the `id_index` synchronized.
    pub fn remove_node(&mut self, idx: NodeIndex) -> Option<SceneNode> {
        let removed = self.graph.remove_node(idx);
        if let Some(removed_node) = &removed {
            self.id_index.remove(&removed_node.id);
        }
        removed
    }

    /// Look up a node by its `@id`.
    pub fn get_by_id(&self, id: NodeId) -> Option<&SceneNode> {
        self.id_index.get(&id).map(|idx| &self.graph[*idx])
    }

    /// Look up a node mutably by its `@id`.
    pub fn get_by_id_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
        self.id_index
            .get(&id)
            .copied()
            .map(|idx| &mut self.graph[idx])
    }

    /// Get the index for a NodeId.
    pub fn index_of(&self, id: NodeId) -> Option<NodeIndex> {
        self.id_index.get(&id).copied()
    }

    /// Get the parent index of a node.
    pub fn parent(&self, idx: NodeIndex) -> Option<NodeIndex> {
        self.graph
            .neighbors_directed(idx, petgraph::Direction::Incoming)
            .next()
    }

    /// Reparent a node to a new parent.
    pub fn reparent_node(&mut self, child: NodeIndex, new_parent: NodeIndex) {
        if let Some(old_parent) = self.parent(child)
            && let Some(edge) = self.graph.find_edge(old_parent, child)
        {
            self.graph.remove_edge(edge);
            // Clean up stale sorted_child_order for the old parent
            // to prevent ghost children in the emitter.
            if let Some(order) = self.sorted_child_order.get_mut(&old_parent) {
                order.retain(|&idx| idx != child);
            }
        }
        self.graph.add_edge(new_parent, child, ());
    }

    /// Get children of a node in document (insertion) order.
    ///
    /// Sorts by `NodeIndex` so the result is deterministic regardless of
    /// how `petgraph` iterates its adjacency list on different targets
    /// (native vs WASM).
    pub fn children(&self, idx: NodeIndex) -> Vec<NodeIndex> {
        // If an explicit sort order was set (by sort_nodes), use it.
        // Filter out stale entries whose edge was removed (e.g. by reparent_node)
        // as a defensive guard against sorted_child_order desync.
        if let Some(order) = self.sorted_child_order.get(&idx) {
            return order
                .iter()
                .copied()
                .filter(|&c| self.graph.find_edge(idx, c).is_some())
                .collect();
        }

        let mut children: Vec<NodeIndex> = self
            .graph
            .neighbors_directed(idx, petgraph::Direction::Outgoing)
            .collect();
        children.sort();
        children
    }

    /// Move a child one step backward in z-order (swap with previous sibling).
    /// Returns true if the z-order changed.
    pub fn send_backward(&mut self, child: NodeIndex) -> bool {
        let parent = match self.parent(child) {
            Some(p) => p,
            None => return false,
        };
        let siblings = self.children(parent);
        let pos = match siblings.iter().position(|&s| s == child) {
            Some(p) => p,
            None => return false,
        };
        if pos == 0 {
            return false; // already at back
        }
        // Rebuild edges in swapped order
        self.rebuild_child_order(parent, &siblings, pos, pos - 1)
    }

    /// Move a child one step forward in z-order (swap with next sibling).
    /// Returns true if the z-order changed.
    pub fn bring_forward(&mut self, child: NodeIndex) -> bool {
        let parent = match self.parent(child) {
            Some(p) => p,
            None => return false,
        };
        let siblings = self.children(parent);
        let pos = match siblings.iter().position(|&s| s == child) {
            Some(p) => p,
            None => return false,
        };
        if pos >= siblings.len() - 1 {
            return false; // already at front
        }
        self.rebuild_child_order(parent, &siblings, pos, pos + 1)
    }

    /// Move a child to the back of z-order (first child).
    pub fn send_to_back(&mut self, child: NodeIndex) -> bool {
        let parent = match self.parent(child) {
            Some(p) => p,
            None => return false,
        };
        let siblings = self.children(parent);
        let pos = match siblings.iter().position(|&s| s == child) {
            Some(p) => p,
            None => return false,
        };
        if pos == 0 {
            return false;
        }
        self.rebuild_child_order(parent, &siblings, pos, 0)
    }

    /// Move a child to the front of z-order (last child).
    pub fn bring_to_front(&mut self, child: NodeIndex) -> bool {
        let parent = match self.parent(child) {
            Some(p) => p,
            None => return false,
        };
        let siblings = self.children(parent);
        let pos = match siblings.iter().position(|&s| s == child) {
            Some(p) => p,
            None => return false,
        };
        let last = siblings.len() - 1;
        if pos == last {
            return false;
        }
        self.rebuild_child_order(parent, &siblings, pos, last)
    }

    /// Move a child to a specific index within its parent's children.
    /// Clamps `target_index` to `[0, sibling_count - 1]`.
    /// Returns true if the order changed.
    pub fn move_child_to_index(&mut self, child: NodeIndex, target_index: usize) -> bool {
        let parent = match self.parent(child) {
            Some(p) => p,
            None => return false,
        };
        let siblings = self.children(parent);
        let from = match siblings.iter().position(|&s| s == child) {
            Some(p) => p,
            None => return false,
        };
        let to = target_index.min(siblings.len().saturating_sub(1));
        if from == to {
            return false;
        }
        self.rebuild_child_order(parent, &siblings, from, to)
    }

    /// Rebuild child edges, moving child at `from` to `to` position.
    fn rebuild_child_order(
        &mut self,
        parent: NodeIndex,
        siblings: &[NodeIndex],
        from: usize,
        to: usize,
    ) -> bool {
        // Remove all edges from parent to children
        for &sib in siblings {
            if let Some(edge) = self.graph.find_edge(parent, sib) {
                self.graph.remove_edge(edge);
            }
        }
        // Build new order
        let mut new_order: Vec<NodeIndex> = siblings.to_vec();
        let child = new_order.remove(from);
        new_order.insert(to, child);
        // Re-add edges in new order
        for &sib in &new_order {
            self.graph.add_edge(parent, sib, ());
        }
        // Store explicit child order so children() returns z-order, not NodeIndex order
        self.sorted_child_order.insert(parent, new_order);
        true
    }

    /// Define a named style.
    pub fn define_style(&mut self, name: NodeId, style: Properties) {
        self.styles.insert(name, style);
    }

    /// Resolve a node's effective style (merging `use` references + inline overrides + active animations).
    pub fn resolve_style(&self, node: &SceneNode, active_triggers: &[AnimTrigger]) -> Properties {
        let mut resolved = Properties::default();

        // Apply referenced styles in order
        for style_id in &node.use_styles {
            if let Some(base) = self.styles.get(style_id) {
                merge_style(&mut resolved, base);
            }
        }

        // Apply inline overrides (take precedence)
        merge_style(&mut resolved, &node.props);

        // Apply active animation state overrides
        for anim in &node.animations {
            if active_triggers.contains(&anim.trigger) {
                if anim.properties.fill.is_some() {
                    resolved.fill = anim.properties.fill.clone();
                }
                if anim.properties.opacity.is_some() {
                    resolved.opacity = anim.properties.opacity;
                }
                if anim.properties.scale.is_some() {
                    resolved.scale = anim.properties.scale;
                }
            }
        }

        resolved
    }

    /// Rebuild the `id_index` (needed after deserialization).
    pub fn rebuild_index(&mut self) {
        self.id_index.clear();
        for idx in self.graph.node_indices() {
            let id = self.graph[idx].id;
            self.id_index.insert(id, idx);
        }
    }

    /// Resolve an edge's effective style (merging `use` references + inline overrides + active animations).
    pub fn resolve_style_for_edge(
        &self,
        edge: &Edge,
        active_triggers: &[AnimTrigger],
    ) -> Properties {
        let mut resolved = Properties::default();
        for style_id in &edge.use_styles {
            if let Some(base) = self.styles.get(style_id) {
                merge_style(&mut resolved, base);
            }
        }
        merge_style(&mut resolved, &edge.props);

        for anim in &edge.animations {
            if active_triggers.contains(&anim.trigger) {
                if anim.properties.fill.is_some() {
                    resolved.fill = anim.properties.fill.clone();
                }
                if anim.properties.opacity.is_some() {
                    resolved.opacity = anim.properties.opacity;
                }
                if anim.properties.scale.is_some() {
                    resolved.scale = anim.properties.scale;
                }
            }
        }

        resolved
    }

    /// Resolve the effective click target for a leaf node.
    ///
    /// Figma-style group selection with progressive drill-down:
    /// - **First click** → selects the topmost group ancestor (below root).
    /// - **Click again** (topmost group already selected) → next-level group.
    /// - **Click again** (all group ancestors selected) → the leaf itself.
    pub fn effective_target(&self, leaf_id: NodeId, selected: &[NodeId]) -> NodeId {
        let leaf_idx = match self.index_of(leaf_id) {
            Some(idx) => idx,
            None => return leaf_id,
        };

        // Walk up from the leaf, collecting group ancestors below root
        // in bottom-up order.
        let mut groups_bottom_up: Vec<NodeId> = Vec::new();
        let mut cursor = self.parent(leaf_idx);
        while let Some(parent_idx) = cursor {
            if parent_idx == self.root {
                break;
            }
            if matches!(self.graph[parent_idx].kind, NodeKind::Group) {
                groups_bottom_up.push(self.graph[parent_idx].id);
            }
            cursor = self.parent(parent_idx);
        }

        // Reverse to get top-down order (topmost group first).
        groups_bottom_up.reverse();

        // Find the deepest selected group in the ancestor chain.
        // If a selected node is in the chain, advance to the next level down.
        let deepest_selected_pos = groups_bottom_up
            .iter()
            .rposition(|gid| selected.contains(gid));

        match deepest_selected_pos {
            None => {
                // Nothing in the chain is selected → return topmost group
                if let Some(top) = groups_bottom_up.first() {
                    return *top;
                }
            }
            Some(pos) if pos + 1 < groups_bottom_up.len() => {
                // Selected group is not the deepest → advance one level
                return groups_bottom_up[pos + 1];
            }
            Some(_) => {
                // Deepest group is already selected → drill to leaf
            }
        }

        leaf_id
    }

    /// Check if `ancestor_id` is a parent/grandparent/etc. of `descendant_id`.
    pub fn is_ancestor_of(&self, ancestor_id: NodeId, descendant_id: NodeId) -> bool {
        if ancestor_id == descendant_id {
            return false;
        }
        let mut current_idx = match self.index_of(descendant_id) {
            Some(idx) => idx,
            None => return false,
        };
        while let Some(parent_idx) = self.parent(current_idx) {
            if self.graph[parent_idx].id == ancestor_id {
                return true;
            }
            if matches!(self.graph[parent_idx].kind, NodeKind::Root) {
                break;
            }
            current_idx = parent_idx;
        }
        false
    }
}

impl Default for SceneGraph {
    fn default() -> Self {
        Self::new()
    }
}

/// Merge `src` style into `dst`, overwriting only `Some` fields.
fn merge_style(dst: &mut Properties, src: &Properties) {
    if src.fill.is_some() {
        dst.fill = src.fill.clone();
    }
    if src.stroke.is_some() {
        dst.stroke = src.stroke.clone();
    }
    if src.font.is_some() {
        dst.font = src.font.clone();
    }
    if src.corner_radius.is_some() {
        dst.corner_radius = src.corner_radius;
    }
    if src.opacity.is_some() {
        dst.opacity = src.opacity;
    }
    if src.shadow.is_some() {
        dst.shadow = src.shadow.clone();
    }

    if src.text_align.is_some() {
        dst.text_align = src.text_align;
    }
    if src.text_valign.is_some() {
        dst.text_valign = src.text_valign;
    }
    if src.scale.is_some() {
        dst.scale = src.scale;
    }
}

// ─── Resolved positions (output of layout solver) ────────────────────────

/// Resolved absolute bounding box after constraint solving.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct ResolvedBounds {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

impl ResolvedBounds {
    /// Check if a point (px, py) is inside these bounds.
    pub fn contains(&self, px: f32, py: f32) -> bool {
        px >= self.x && px <= self.x + self.width && py >= self.y && py <= self.y + self.height
    }

    /// Return the center point of these bounds.
    pub fn center(&self) -> (f32, f32) {
        (self.x + self.width / 2.0, self.y + self.height / 2.0)
    }

    /// Check if this bounds intersects with a rectangle (AABB overlap).
    pub fn intersects_rect(&self, rx: f32, ry: f32, rw: f32, rh: f32) -> bool {
        self.x < rx + rw
            && self.x + self.width > rx
            && self.y < ry + rh
            && self.y + self.height > ry
    }
}

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

    #[test]
    fn scene_graph_basics() {
        let mut sg = SceneGraph::new();
        let rect = SceneNode::new(
            NodeId::intern("box1"),
            NodeKind::Rect {
                width: 100.0,
                height: 50.0,
            },
        );
        let idx = sg.add_node(sg.root, rect);

        assert!(sg.get_by_id(NodeId::intern("box1")).is_some());
        assert_eq!(sg.children(sg.root).len(), 1);
        assert_eq!(sg.children(sg.root)[0], idx);
    }

    #[test]
    fn color_hex_roundtrip() {
        let c = Color::from_hex("#6C5CE7").unwrap();
        assert_eq!(c.to_hex(), "#6C5CE7");

        let c2 = Color::from_hex("#FF000080").unwrap();
        assert!((c2.a - 128.0 / 255.0).abs() < 0.01);
        assert!(c2.to_hex().len() == 9); // #RRGGBBAA
    }

    #[test]
    fn style_merging() {
        let mut sg = SceneGraph::new();
        sg.define_style(
            NodeId::intern("base"),
            Properties {
                fill: Some(Paint::Solid(Color::rgba(0.0, 0.0, 0.0, 1.0))),
                font: Some(FontSpec {
                    family: "Inter".into(),
                    weight: 400,
                    size: 14.0,
                }),
                ..Default::default()
            },
        );

        let mut node = SceneNode::new(
            NodeId::intern("txt"),
            NodeKind::Text {
                content: "hi".into(),
                max_width: None,
            },
        );
        node.use_styles.push(NodeId::intern("base"));
        node.props.font = Some(FontSpec {
            family: "Inter".into(),
            weight: 700,
            size: 24.0,
        });

        let resolved = sg.resolve_style(&node, &[]);
        // Fill comes from base style
        assert!(resolved.fill.is_some());
        // Font comes from inline override
        let f = resolved.font.unwrap();
        assert_eq!(f.weight, 700);
        assert_eq!(f.size, 24.0);
    }

    #[test]
    fn style_merging_align() {
        let mut sg = SceneGraph::new();
        sg.define_style(
            NodeId::intern("centered"),
            Properties {
                text_align: Some(TextAlign::Center),
                text_valign: Some(TextVAlign::Middle),
                ..Default::default()
            },
        );

        // Node with use: centered + inline override of text_align to Right
        let mut node = SceneNode::new(
            NodeId::intern("overridden"),
            NodeKind::Text {
                content: "hello".into(),
                max_width: None,
            },
        );
        node.use_styles.push(NodeId::intern("centered"));
        node.props.text_align = Some(TextAlign::Right);

        let resolved = sg.resolve_style(&node, &[]);
        // Horizontal should be overridden to Right
        assert_eq!(resolved.text_align, Some(TextAlign::Right));
        // Vertical should come from base style (Middle)
        assert_eq!(resolved.text_valign, Some(TextVAlign::Middle));
    }

    #[test]
    fn test_effective_target_group_selects_group_first() {
        let mut sg = SceneGraph::new();

        // Root -> Group -> Rect
        let group_id = NodeId::intern("my_group");
        let rect_id = NodeId::intern("my_rect");

        let group = SceneNode::new(group_id, NodeKind::Group);
        let rect = SceneNode::new(
            rect_id,
            NodeKind::Rect {
                width: 10.0,
                height: 10.0,
            },
        );

        let group_idx = sg.add_node(sg.root, group);
        sg.add_node(group_idx, rect);

        // Single click (nothing selected): should select the group
        assert_eq!(sg.effective_target(rect_id, &[]), group_id);
        // Double click (group already selected): drill down to leaf
        assert_eq!(sg.effective_target(rect_id, &[group_id]), rect_id);
        // Group itself → returns group (it IS the leaf in this call)
        assert_eq!(sg.effective_target(group_id, &[]), group_id);
    }

    #[test]
    fn test_effective_target_nested_groups_selects_topmost() {
        let mut sg = SceneGraph::new();

        // Root -> group_outer -> group_inner -> rect_leaf
        let outer_id = NodeId::intern("group_outer");
        let inner_id = NodeId::intern("group_inner");
        let leaf_id = NodeId::intern("rect_leaf");

        let outer = SceneNode::new(outer_id, NodeKind::Group);
        let inner = SceneNode::new(inner_id, NodeKind::Group);
        let leaf = SceneNode::new(
            leaf_id,
            NodeKind::Rect {
                width: 50.0,
                height: 50.0,
            },
        );

        let outer_idx = sg.add_node(sg.root, outer);
        let inner_idx = sg.add_node(outer_idx, inner);
        sg.add_node(inner_idx, leaf);

        // Single click (nothing selected): topmost group
        assert_eq!(sg.effective_target(leaf_id, &[]), outer_id);
        // Outer selected → drill to inner group
        assert_eq!(sg.effective_target(leaf_id, &[outer_id]), inner_id);
        // Both outer+inner selected → drill to leaf
        assert_eq!(sg.effective_target(leaf_id, &[outer_id, inner_id]), leaf_id);
        // Non-cumulative: only inner selected (SelectTool replaces, not accumulates)
        // Must drill to leaf — NOT loop back to outer
        assert_eq!(sg.effective_target(leaf_id, &[inner_id]), leaf_id);
    }

    #[test]
    fn test_effective_target_nested_drill_down_three_levels() {
        let mut sg = SceneGraph::new();

        // Root -> group_a -> group_b -> group_c -> rect_leaf
        let a_id = NodeId::intern("group_a");
        let b_id = NodeId::intern("group_b");
        let c_id = NodeId::intern("group_c");
        let leaf_id = NodeId::intern("deep_leaf");

        let a = SceneNode::new(a_id, NodeKind::Group);
        let b = SceneNode::new(b_id, NodeKind::Group);
        let c = SceneNode::new(c_id, NodeKind::Group);
        let leaf = SceneNode::new(
            leaf_id,
            NodeKind::Rect {
                width: 10.0,
                height: 10.0,
            },
        );

        let a_idx = sg.add_node(sg.root, a);
        let b_idx = sg.add_node(a_idx, b);
        let c_idx = sg.add_node(b_idx, c);
        sg.add_node(c_idx, leaf);

        // Progressive drill-down (non-cumulative — SelectTool replaces selection)
        assert_eq!(sg.effective_target(leaf_id, &[]), a_id);
        assert_eq!(sg.effective_target(leaf_id, &[a_id]), b_id);
        assert_eq!(sg.effective_target(leaf_id, &[b_id]), c_id);
        assert_eq!(sg.effective_target(leaf_id, &[c_id]), leaf_id);
    }

    #[test]
    fn test_visual_highlight_differs_from_selected() {
        // Visual highlight contract: when effective_target returns a group,
        // the UI should highlight the raw hit (leaf) not the group.
        let mut sg = SceneGraph::new();

        let group_id = NodeId::intern("card");
        let child_id = NodeId::intern("card_title");

        let group = SceneNode::new(group_id, NodeKind::Group);
        let child = SceneNode::new(
            child_id,
            NodeKind::Text {
                content: "Title".into(),
                max_width: None,
            },
        );

        let group_idx = sg.add_node(sg.root, group);
        sg.add_node(group_idx, child);

        // Raw hit = child_id, nothing selected
        let logical_target = sg.effective_target(child_id, &[]);
        // Logical selection should be the group
        assert_eq!(logical_target, group_id);
        // Visual highlight should be the child (raw hit != logical_target)
        assert_ne!(child_id, logical_target);
        // After drilling (group selected), both converge
        let drilled = sg.effective_target(child_id, &[group_id]);
        assert_eq!(drilled, child_id);
    }

    #[test]
    fn test_effective_target_no_group() {
        let mut sg = SceneGraph::new();

        // Root -> Rect (no group)
        let rect_id = NodeId::intern("standalone_rect");
        let rect = SceneNode::new(
            rect_id,
            NodeKind::Rect {
                width: 10.0,
                height: 10.0,
            },
        );
        sg.add_node(sg.root, rect);

        // No group parent → returns leaf directly
        assert_eq!(sg.effective_target(rect_id, &[]), rect_id);
    }

    #[test]
    fn test_is_ancestor_of() {
        let mut sg = SceneGraph::new();

        // Root -> Group -> Rect
        let group_id = NodeId::intern("grp");
        let rect_id = NodeId::intern("r1");
        let other_id = NodeId::intern("other");

        let group = SceneNode::new(group_id, NodeKind::Group);
        let rect = SceneNode::new(
            rect_id,
            NodeKind::Rect {
                width: 10.0,
                height: 10.0,
            },
        );
        let other = SceneNode::new(
            other_id,
            NodeKind::Rect {
                width: 5.0,
                height: 5.0,
            },
        );

        let group_idx = sg.add_node(sg.root, group);
        sg.add_node(group_idx, rect);
        sg.add_node(sg.root, other);

        // Group is ancestor of rect
        assert!(sg.is_ancestor_of(group_id, rect_id));
        // Root is ancestor of rect (grandparent)
        assert!(sg.is_ancestor_of(NodeId::intern("root"), rect_id));
        // Rect is NOT ancestor of group
        assert!(!sg.is_ancestor_of(rect_id, group_id));
        // Self is NOT ancestor of self
        assert!(!sg.is_ancestor_of(group_id, group_id));
        // Other is not ancestor of rect (sibling)
        assert!(!sg.is_ancestor_of(other_id, rect_id));
    }

    #[test]
    fn test_resolve_style_scale_animation() {
        let sg = SceneGraph::new();

        let mut node = SceneNode::new(
            NodeId::intern("btn"),
            NodeKind::Rect {
                width: 100.0,
                height: 40.0,
            },
        );
        node.props.fill = Some(Paint::Solid(Color::rgba(1.0, 0.0, 0.0, 1.0)));
        node.animations.push(AnimKeyframe {
            trigger: AnimTrigger::Press,
            duration_ms: 100,
            easing: Easing::EaseOut,
            properties: AnimProperties {
                scale: Some(0.97),
                ..Default::default()
            },
            delay_ms: None,
        });

        // Without press trigger: scale should be None
        let resolved = sg.resolve_style(&node, &[]);
        assert!(resolved.scale.is_none());

        // With press trigger: scale should be 0.97
        let resolved = sg.resolve_style(&node, &[AnimTrigger::Press]);
        assert_eq!(resolved.scale, Some(0.97));
        // Fill should still be present
        assert!(resolved.fill.is_some());
    }

    #[test]
    fn z_order_bring_forward() {
        let mut sg = SceneGraph::new();
        let a = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("a"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );
        let _b = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("b"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );
        let _c = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("c"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );

        // Initial: [a, b, c]
        let ids: Vec<&str> = sg
            .children(sg.root)
            .iter()
            .map(|&i| sg.graph[i].id.as_str())
            .collect();
        assert_eq!(ids, vec!["a", "b", "c"]);

        // Bring @a forward → should swap a and b → [b, a, c]
        let changed = sg.bring_forward(a);
        assert!(changed);
        let ids: Vec<&str> = sg
            .children(sg.root)
            .iter()
            .map(|&i| sg.graph[i].id.as_str())
            .collect();
        assert_eq!(ids, vec!["b", "a", "c"]);
    }

    #[test]
    fn z_order_send_backward() {
        let mut sg = SceneGraph::new();
        let _a = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("a"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );
        let _b = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("b"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );
        let c = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("c"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );

        // Send @c backward → should swap c and b → [a, c, b]
        let changed = sg.send_backward(c);
        assert!(changed);
        let ids: Vec<&str> = sg
            .children(sg.root)
            .iter()
            .map(|&i| sg.graph[i].id.as_str())
            .collect();
        assert_eq!(ids, vec!["a", "c", "b"]);
    }

    #[test]
    fn z_order_bring_to_front() {
        let mut sg = SceneGraph::new();
        let a = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("a"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );
        let _b = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("b"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );
        let _c = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("c"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );

        // Bring @a to front → [b, c, a]
        let changed = sg.bring_to_front(a);
        assert!(changed);
        let ids: Vec<&str> = sg
            .children(sg.root)
            .iter()
            .map(|&i| sg.graph[i].id.as_str())
            .collect();
        assert_eq!(ids, vec!["b", "c", "a"]);
    }

    #[test]
    fn z_order_send_to_back() {
        let mut sg = SceneGraph::new();
        let _a = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("a"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );
        let _b = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("b"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );
        let c = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("c"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );

        // Send @c to back → [c, a, b]
        let changed = sg.send_to_back(c);
        assert!(changed);
        let ids: Vec<&str> = sg
            .children(sg.root)
            .iter()
            .map(|&i| sg.graph[i].id.as_str())
            .collect();
        assert_eq!(ids, vec!["c", "a", "b"]);
    }

    #[test]
    fn z_order_emitter_roundtrip() {
        use crate::emitter::emit_document;
        use crate::parser::parse_document;

        let mut sg = SceneGraph::new();
        let a = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("a"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );
        let _b = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("b"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );
        let _c = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("c"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );

        // Bring @a to front → [b, c, a]
        sg.bring_to_front(a);

        // Emit and re-parse
        let text = emit_document(&sg);
        let reparsed = parse_document(&text).unwrap();
        let ids: Vec<&str> = reparsed
            .children(reparsed.root)
            .iter()
            .map(|&i| reparsed.graph[i].id.as_str())
            .collect();
        assert_eq!(
            ids,
            vec!["b", "c", "a"],
            "Z-order should survive emit→parse roundtrip. Emitted:\n{}",
            text
        );
    }

    #[test]
    fn move_child_to_index_basic() {
        let mut sg = SceneGraph::new();
        let a = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("a"),
                NodeKind::Rect {
                    width: 10.0,
                    height: 10.0,
                },
            ),
        );
        let _b = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("b"),
                NodeKind::Rect {
                    width: 10.0,
                    height: 10.0,
                },
            ),
        );
        let _c = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("c"),
                NodeKind::Rect {
                    width: 10.0,
                    height: 10.0,
                },
            ),
        );
        // Move "a" from index 0 to index 2 (last)
        assert!(sg.move_child_to_index(a, 2));
        let ids: Vec<&str> = sg
            .children(sg.root)
            .iter()
            .map(|&i| sg.graph[i].id.as_str())
            .collect();
        assert_eq!(ids, vec!["b", "c", "a"]);
    }

    #[test]
    fn move_child_to_index_out_of_bounds() {
        let mut sg = SceneGraph::new();
        let a = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("a"),
                NodeKind::Rect {
                    width: 10.0,
                    height: 10.0,
                },
            ),
        );
        let _b = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("b"),
                NodeKind::Rect {
                    width: 10.0,
                    height: 10.0,
                },
            ),
        );
        // Index 999 should clamp to last position (1)
        assert!(sg.move_child_to_index(a, 999));
        let ids: Vec<&str> = sg
            .children(sg.root)
            .iter()
            .map(|&i| sg.graph[i].id.as_str())
            .collect();
        assert_eq!(ids, vec!["b", "a"]);
    }

    #[test]
    fn move_child_to_index_noop() {
        let mut sg = SceneGraph::new();
        let a = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("a"),
                NodeKind::Rect {
                    width: 10.0,
                    height: 10.0,
                },
            ),
        );
        // Move to same index → no change
        assert!(!sg.move_child_to_index(a, 0));
    }

    #[test]
    fn reparent_then_children_correct() {
        let mut sg = SceneGraph::new();
        let group = sg.add_node(
            sg.root,
            SceneNode::new(NodeId::intern("g"), NodeKind::Group),
        );
        let rect = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("r"),
                NodeKind::Rect {
                    width: 10.0,
                    height: 10.0,
                },
            ),
        );
        // rect is child of root initially
        assert_eq!(sg.children(sg.root).len(), 2);
        // Reparent rect into group
        sg.reparent_node(rect, group);
        assert_eq!(sg.children(sg.root).len(), 1);
        assert_eq!(sg.children(group).len(), 1);
        assert_eq!(sg.children(group)[0], rect);
        // Reparent back to root
        sg.reparent_node(rect, sg.root);
        assert_eq!(sg.children(sg.root).len(), 2);
        assert_eq!(sg.children(group).len(), 0);
    }

    /// Regression test: reorder creates sorted_child_order, then reparent
    /// must not leave ghost entries in the old parent's children().
    #[test]
    fn reparent_after_reorder_no_ghost_children() {
        let mut sg = SceneGraph::new();
        let parent = sg.add_node(
            sg.root,
            SceneNode::new(
                NodeId::intern("parent"),
                NodeKind::Rect {
                    width: 200.0,
                    height: 200.0,
                },
            ),
        );
        let child_a = sg.add_node(
            parent,
            SceneNode::new(
                NodeId::intern("a"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );
        let child_b = sg.add_node(
            parent,
            SceneNode::new(
                NodeId::intern("b"),
                NodeKind::Rect {
                    width: 50.0,
                    height: 50.0,
                },
            ),
        );

        // Reorder children to create a sorted_child_order entry
        assert!(sg.move_child_to_index(child_b, 0));
        assert!(sg.sorted_child_order.contains_key(&parent));
        assert_eq!(sg.children(parent), vec![child_b, child_a]);

        // Now reparent child_b out to root (simulates drag-above-parent)
        sg.reparent_node(child_b, sg.root);

        // Old parent must NOT have ghost children
        let parent_children = sg.children(parent);
        assert_eq!(
            parent_children.len(),
            1,
            "parent should have exactly 1 child after reparent, got {:?}",
            parent_children
        );
        assert_eq!(parent_children[0], child_a);

        // New parent (root) should now contain both parent and child_b
        let root_children = sg.children(sg.root);
        assert_eq!(root_children.len(), 2);
        assert!(root_children.contains(&parent));
        assert!(root_children.contains(&child_b));

        // Emit document should not duplicate child_b
        let emitted = crate::emitter::emit_document(&sg);
        let count = emitted.matches("@b").count();
        assert_eq!(
            count, 1,
            "@b should appear exactly once in emitted text, found {count} times:\n{emitted}"
        );
    }
}