strata-style 0.1.2

Pure Rust CSS engine, cascade solver, and Tailwind CSS JIT compiler
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
//! Core CSS style types, layout enums, and ComputedStyle representation.

use std::sync::Arc;
pub use strata_primitives::color::Rgba;
pub use strata_primitives::geom::{EdgeInsets, Matrix4x4};
pub use strata_primitives::AtomId;

pub type Color = Rgba;
pub type CustomPropertyMap = Arc<Vec<(AtomId, AtomId)>>;

/// Box layout display model.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Display {
    #[default]
    Block,
    Inline,
    InlineBlock,
    ListItem,
    Flex,
    InlineFlex,
    Grid,
    InlineGrid,
    Table,
    InlineTable,
    TableRowGroup,
    TableHeaderGroup,
    TableFooterGroup,
    TableRow,
    TableCell,
    TableCaption,
    TableColumnGroup,
    TableColumn,
    None,
}

/// CSS table layout algorithm mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TableLayout {
    #[default]
    Auto,
    Fixed,
}

/// CSS border collapse model for tables.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BorderCollapse {
    #[default]
    Separate,
    Collapse,
}

/// CSS table caption placement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CaptionSide {
    #[default]
    Top,
    Bottom,
}

/// Positioning scheme in CSS box layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Position {
    #[default]
    Static,
    Relative,
    Absolute,
    Fixed,
    Sticky,
}

/// CSS float property defining element lateral drift.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Float {
    #[default]
    None,
    Left,
    Right,
    InlineStart,
    InlineEnd,
}

/// CSS clear property defining clearance below floating boxes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Clear {
    #[default]
    None,
    Left,
    Right,
    Both,
    InlineStart,
    InlineEnd,
}

/// CSS Length and Dimension units.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Dimension {
    #[default]
    Auto,
    Px(f32),
    Percent(f32),
    Vw(f32),
    Vh(f32),
    Rem(f32),
    Em(f32),
    Calc(crate::calc::CalcId),
    MinContent,
    MaxContent,
    FitContent(f32),
}

impl Dimension {
    /// Creates a Dimension variant from an AST calc expression.
    pub fn calc(expr: crate::calc::CalcExpr) -> Self {
        Self::Calc(crate::calc::intern_calc(expr))
    }

    /// Resolves the dimension into concrete pixels given a context.
    pub fn resolve_px(
        &self,
        parent_size: f32,
        root_font_size: f32,
        current_font_size: f32,
    ) -> Option<f32> {
        match *self {
            Self::Auto => None,
            Self::Px(px) => Some(px),
            Self::Percent(pct) => Some(parent_size * (pct / 100.0)),
            Self::Vw(vw) => Some(vw), // Handled by viewport context in layout
            Self::Vh(vh) => Some(vh),
            Self::Rem(rem) => Some(rem * root_font_size),
            Self::Em(em) => Some(em * current_font_size),
            Self::Calc(id) => crate::calc::get_calc(id).map(|expr| {
                let ctx = crate::calc::CalcContext {
                    parent_size,
                    root_font_size,
                    current_font_size,
                    viewport_width: 1920.0,
                    viewport_height: 1080.0,
                };
                expr.eval(&ctx)
            }),
            Self::MinContent | Self::MaxContent | Self::FitContent(_) => None,
        }
    }
}

/// Box sizing model (CSS box-sizing).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BoxSizing {
    #[default]
    BorderBox,
    ContentBox,
}

/// Flex container main axis direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlexDirection {
    #[default]
    Row,
    RowReverse,
    Column,
    ColumnReverse,
}

/// Flex line wrapping behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlexWrap {
    #[default]
    NoWrap,
    Wrap,
    WrapReverse,
}

/// Main-axis alignment within flex containers and grid tracks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum JustifyContent {
    #[default]
    FlexStart,
    FlexEnd,
    Center,
    SpaceBetween,
    SpaceAround,
    SpaceEvenly,
}

/// Cross-axis alignment for items in flex/grid containers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlignItems {
    #[default]
    Stretch,
    FlexStart,
    FlexEnd,
    Center,
    Baseline,
}

/// Self-alignment on the cross-axis overriding container `align-items`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlignSelf {
    #[default]
    Auto,
    Stretch,
    FlexStart,
    FlexEnd,
    Center,
    Baseline,
}

/// Individual track sizing breadth used in CSS minmax() functions.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GridTrackBreadth {
    Auto,
    Px(f32),
    Percent(f32),
    Fr(f32),
    MinContent,
    MaxContent,
}

/// CSS Grid track sizing definition (W3C CSS Grid Layout Level 2).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GridTrack {
    Auto,
    Px(f32),
    Percent(f32),
    Fr(f32),
    MinContent,
    MaxContent,
    Subgrid,
    MinMax(GridTrackBreadth, GridTrackBreadth),
}

/// CSS grid-auto-flow property (W3C CSS Grid Level 2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GridAutoFlow {
    #[default]
    Row,
    Column,
    RowDense,
    ColumnDense,
}

impl GridAutoFlow {
    pub fn is_row(&self) -> bool {
        matches!(self, Self::Row | Self::RowDense)
    }

    pub fn is_dense(&self) -> bool {
        matches!(self, Self::RowDense | Self::ColumnDense)
    }

    pub fn parse(s: &str) -> Option<Self> {
        let s = s.trim().to_ascii_lowercase();
        let tokens: Vec<&str> = s.split_whitespace().collect();
        match tokens.as_slice() {
            ["row"] => Some(Self::Row),
            ["column"] => Some(Self::Column),
            ["dense"] => Some(Self::RowDense),
            ["row", "dense"] | ["dense", "row"] => Some(Self::RowDense),
            ["column", "dense"] | ["dense", "column"] => Some(Self::ColumnDense),
            _ => None,
        }
    }
}

/// 4-corner border radius definition.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct BorderRadius {
    pub top_left: f32,
    pub top_right: f32,
    pub bottom_right: f32,
    pub bottom_left: f32,
}

impl BorderRadius {
    pub const ZERO: Self = Self::all(0.0);

    pub const fn new(top_left: f32, top_right: f32, bottom_right: f32, bottom_left: f32) -> Self {
        Self {
            top_left,
            top_right,
            bottom_right,
            bottom_left,
        }
    }

    pub const fn all(radius: f32) -> Self {
        Self {
            top_left: radius,
            top_right: radius,
            bottom_right: radius,
            bottom_left: radius,
        }
    }
}

/// Standard W3C CSS blend modes for mix-blend-mode and background-blend-mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum BlendMode {
    #[default]
    Normal,
    Multiply,
    Screen,
    Overlay,
    Darken,
    Lighten,
    ColorDodge,
    ColorBurn,
    HardLight,
    SoftLight,
    Difference,
    Exclusion,
    Hue,
    Saturation,
    Color,
    Luminosity,
}

impl BlendMode {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Normal => "normal",
            Self::Multiply => "multiply",
            Self::Screen => "screen",
            Self::Overlay => "overlay",
            Self::Darken => "darken",
            Self::Lighten => "lighten",
            Self::ColorDodge => "color-dodge",
            Self::ColorBurn => "color-burn",
            Self::HardLight => "hard-light",
            Self::SoftLight => "soft-light",
            Self::Difference => "difference",
            Self::Exclusion => "exclusion",
            Self::Hue => "hue",
            Self::Saturation => "saturation",
            Self::Color => "color",
            Self::Luminosity => "luminosity",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "normal" => Some(Self::Normal),
            "multiply" => Some(Self::Multiply),
            "screen" => Some(Self::Screen),
            "overlay" => Some(Self::Overlay),
            "darken" => Some(Self::Darken),
            "lighten" => Some(Self::Lighten),
            "color-dodge" => Some(Self::ColorDodge),
            "color-burn" => Some(Self::ColorBurn),
            "hard-light" => Some(Self::HardLight),
            "soft-light" => Some(Self::SoftLight),
            "difference" => Some(Self::Difference),
            "exclusion" => Some(Self::Exclusion),
            "hue" => Some(Self::Hue),
            "saturation" => Some(Self::Saturation),
            "color" => Some(Self::Color),
            "luminosity" => Some(Self::Luminosity),
            _ => None,
        }
    }

    /// Returns true if this blend mode evaluates color channels independently.
    #[inline]
    pub fn is_separable(&self) -> bool {
        !matches!(
            self,
            Self::Hue | Self::Saturation | Self::Color | Self::Luminosity
        )
    }
}

/// CSS isolation property determining stacking group containment for blend modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Isolation {
    #[default]
    Auto,
    Isolate,
}

impl Isolation {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Isolate => "isolate",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "auto" => Some(Self::Auto),
            "isolate" => Some(Self::Isolate),
            _ => None,
        }
    }
}

/// CSS box-shadow effect definition.
#[derive(Debug, Clone, PartialEq)]
pub struct BoxShadow {
    pub offset_x: f32,
    pub offset_y: f32,
    pub blur_radius: f32,
    pub spread_radius: f32,
    pub color: Color,
    pub inset: bool,
}

/// A color stop in a CSS gradient definition.
#[derive(Debug, Clone, PartialEq)]
pub struct ColorStop {
    pub color: Color,
    /// Stop position as a fraction [0.0, 1.0], or None for automatic distribution.
    pub position: Option<f32>,
}

/// CSS Gradient background specification.
#[derive(Debug, Clone, PartialEq)]
pub enum Gradient {
    Linear {
        /// Gradient orientation in degrees (0 = to top, 90 = to right, 180 = to bottom).
        angle_deg: f32,
        stops: Vec<ColorStop>,
    },
    Radial {
        /// Center origin fraction (cx, cy), typically (0.5, 0.5).
        center: (f32, f32),
        stops: Vec<ColorStop>,
    },
    Conic {
        angle_deg: f32,
        center: (f32, f32),
        stops: Vec<ColorStop>,
    },
}

/// Content overflow clipping behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Overflow {
    #[default]
    Visible,
    Hidden,
    Scroll,
    Auto,
}

/// Typographic font weight.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FontWeight {
    Thin = 100,
    ExtraLight = 200,
    Light = 300,
    #[default]
    Normal = 400,
    Medium = 500,
    SemiBold = 600,
    Bold = 700,
    ExtraBold = 800,
    Black = 900,
}

impl FontWeight {
    pub fn from_u16(weight: u16) -> Self {
        match weight {
            0..=150 => Self::Thin,
            151..=250 => Self::ExtraLight,
            251..=350 => Self::Light,
            351..=450 => Self::Normal,
            451..=550 => Self::Medium,
            551..=650 => Self::SemiBold,
            651..=750 => Self::Bold,
            751..=850 => Self::ExtraBold,
            _ => Self::Black,
        }
    }
}

/// Text horizontal alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextAlign {
    #[default]
    Left,
    Center,
    Right,
    Justify,
}

/// Font style (normal, italic, oblique).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FontStyle {
    #[default]
    Normal,
    Italic,
    Oblique,
}

/// Text overflow behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextOverflow {
    #[default]
    Clip,
    Ellipsis,
}

/// Text decoration line.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextDecoration {
    #[default]
    None,
    Underline,
    LineThrough,
    Overline,
}

/// Text capitalization transform.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextTransform {
    #[default]
    None,
    Uppercase,
    Lowercase,
    Capitalize,
}

/// Whitespace handling behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WhiteSpace {
    #[default]
    Normal,
    NoWrap,
    Pre,
    PreWrap,
    PreLine,
}

/// Vertical alignment within line box or table cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VerticalAlign {
    #[default]
    Baseline,
    Top,
    Middle,
    Bottom,
    TextTop,
    TextBottom,
    Sub,
    Super,
}

/// Mouse pointer cursor style.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Cursor {
    #[default]
    Default,
    Pointer,
    Text,
    Move,
    NotAllowed,
    Crosshair,
    Grab,
    Grabbing,
    ColResize,
    RowResize,
    Wait,
    Help,
    None,
}

/// Text selection behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum UserSelect {
    #[default]
    Auto,
    None,
    Text,
    All,
}

/// Pointer event pass-through behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PointerEvents {
    #[default]
    Auto,
    None,
}

/// Element visibility.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Visibility {
    #[default]
    Visible,
    Hidden,
    Collapse,
}

/// Border and outline stroke style.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BorderStyle {
    #[default]
    Solid,
    Dashed,
    Dotted,
    Double,
    None,
    Hidden,
}

/// Content visibility optimization (W3C CSS Containment Module Level 2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ContentVisibility {
    #[default]
    Visible,
    Auto,
    Hidden,
}

/// CSS Containment specification (W3C CSS Containment Module Level 2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Containment {
    pub size: bool,
    pub inline_size: bool,
    pub layout: bool,
    pub paint: bool,
    pub style: bool,
}

impl Containment {
    pub const NONE: Self = Self {
        size: false,
        inline_size: false,
        layout: false,
        paint: false,
        style: false,
    };

    pub const STRICT: Self = Self {
        size: true,
        inline_size: false,
        layout: true,
        paint: true,
        style: false,
    };

    pub const CONTENT: Self = Self {
        size: false,
        inline_size: false,
        layout: true,
        paint: true,
        style: false,
    };

    #[inline]
    pub fn contains_layout(&self) -> bool {
        self.layout
    }

    #[inline]
    pub fn contains_size(&self) -> bool {
        self.size
    }

    #[inline]
    pub fn contains_paint(&self) -> bool {
        self.paint
    }
}

/// Stepped timing function transition position (W3C CSS Easing Functions Level 1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StepPosition {
    JumpStart,
    #[default]
    JumpEnd,
    JumpNone,
    JumpBoth,
    Start,
    End,
}

/// Animation and transition timing function (easing curve).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum TransitionEasing {
    Linear,
    #[default]
    Ease,
    EaseIn,
    EaseOut,
    EaseInOut,
    StepStart,
    StepEnd,
    Steps(u32, StepPosition),
    CubicBezier(f32, f32, f32, f32),
}

impl TransitionEasing {
    /// Evaluates the easing function at normalized progression `t` in `[0.0, 1.0]`.
    pub fn evaluate(&self, t: f32) -> f32 {
        let t = t.clamp(0.0, 1.0);
        match self {
            Self::Linear => t,
            Self::Ease => cubic_bezier_solve(t, 0.25, 0.1, 0.25, 1.0),
            Self::EaseIn => cubic_bezier_solve(t, 0.42, 0.0, 1.0, 1.0),
            Self::EaseOut => cubic_bezier_solve(t, 0.0, 0.0, 0.58, 1.0),
            Self::EaseInOut => cubic_bezier_solve(t, 0.42, 0.0, 0.58, 1.0),
            Self::StepStart => {
                if t > 0.0 {
                    1.0
                } else {
                    0.0
                }
            }
            Self::StepEnd => {
                if t >= 1.0 {
                    1.0
                } else {
                    0.0
                }
            }
            Self::Steps(n, pos) => evaluate_steps(t, *n, *pos),
            Self::CubicBezier(x1, y1, x2, y2) => cubic_bezier_solve(t, *x1, *y1, *x2, *y2),
        }
    }

    /// Solves the easing function at normalized progression `t` in `[0.0, 1.0]`.
    #[inline(always)]
    pub fn solve(&self, t: f32) -> f32 {
        self.evaluate(t)
    }

    /// Parses a CSS timing function string into a `TransitionEasing`.
    pub fn parse(s: &str) -> Option<Self> {
        let s = s.trim();
        let lower = s.to_ascii_lowercase();
        match lower.as_str() {
            "linear" => return Some(Self::Linear),
            "ease" => return Some(Self::Ease),
            "ease-in" => return Some(Self::EaseIn),
            "ease-out" => return Some(Self::EaseOut),
            "ease-in-out" => return Some(Self::EaseInOut),
            "step-start" => return Some(Self::StepStart),
            "step-end" => return Some(Self::StepEnd),
            _ => {}
        }

        if lower.starts_with("cubic-bezier(") && lower.ends_with(')') {
            let inner = &s[13..s.len() - 1];
            let parts: Vec<&str> = inner.split(',').collect();
            if parts.len() == 4 {
                if let (Ok(x1), Ok(y1), Ok(x2), Ok(y2)) = (
                    parts[0].trim().parse::<f32>(),
                    parts[1].trim().parse::<f32>(),
                    parts[2].trim().parse::<f32>(),
                    parts[3].trim().parse::<f32>(),
                ) {
                    return Some(Self::CubicBezier(x1, y1, x2, y2));
                }
            }
        }

        if lower.starts_with("steps(") && lower.ends_with(')') {
            let inner = &s[6..s.len() - 1];
            let parts: Vec<&str> = inner.split(',').collect();
            if parts.len() == 1 {
                if let Ok(n) = parts[0].trim().parse::<u32>() {
                    return Some(Self::Steps(n, StepPosition::End));
                }
            } else if parts.len() == 2 {
                if let Ok(n) = parts[0].trim().parse::<u32>() {
                    let pos = match parts[1].trim().to_ascii_lowercase().as_str() {
                        "jump-start" | "start" => StepPosition::JumpStart,
                        "jump-end" | "end" => StepPosition::JumpEnd,
                        "jump-none" => StepPosition::JumpNone,
                        "jump-both" => StepPosition::JumpBoth,
                        _ => StepPosition::End,
                    };
                    return Some(Self::Steps(n, pos));
                }
            }
        }

        None
    }
}

/// Solves a cubic Bézier curve for parameter `x` using De Casteljau's algorithm and root finding.
#[inline(always)]
pub fn cubic_bezier_solve(x: f32, x1: f32, y1: f32, x2: f32, y2: f32) -> f32 {
    crate::bezier::cubic_bezier_solve(x, x1, y1, x2, y2)
}

/// Evaluates stepped progress for `steps(n, position)`.
pub fn evaluate_steps(t: f32, n: u32, pos: StepPosition) -> f32 {
    let n = n.max(1) as f32;
    let t = t.clamp(0.0, 1.0);
    match pos {
        StepPosition::JumpStart | StepPosition::Start => ((t * n).floor() + 1.0) / n,
        StepPosition::JumpEnd | StepPosition::End => (t * n).floor() / n,
        StepPosition::JumpNone => {
            if n <= 1.0 {
                t
            } else {
                (t * (n - 1.0)).floor() / (n - 1.0)
            }
        }
        StepPosition::JumpBoth => ((t * (n + 1.0)).floor() + 1.0) / (n + 1.0),
    }
    .clamp(0.0, 1.0)
}

/// Identifies an individual animatable CSS property target for transitions.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum TransitionProperty {
    #[default]
    All,
    None,
    Color,
    BackgroundColor,
    Opacity,
    Transform,
    Width,
    Height,
    MinWidth,
    MaxWidth,
    MinHeight,
    MaxHeight,
    Margin,
    Padding,
    BorderColor,
    BorderWidth,
    BorderRadius,
    Flex,
    FlexGrow,
    FlexShrink,
    FlexBasis,
    Gap,
    GapRow,
    GapCol,
    BoxShadow,
    Filter,
    BackdropFilter,
    ClipPath,
    MixBlendMode,
    Isolation,
    ViewTransitionName,
    Custom(String),
}

impl TransitionProperty {
    /// Parses a property identifier string into a `TransitionProperty`.
    pub fn parse(s: &str) -> Self {
        match s.trim().to_ascii_lowercase().as_str() {
            "all" => Self::All,
            "none" => Self::None,
            "color" => Self::Color,
            "background-color" | "background" => Self::BackgroundColor,
            "opacity" => Self::Opacity,
            "transform" => Self::Transform,
            "width" => Self::Width,
            "height" => Self::Height,
            "min-width" => Self::MinWidth,
            "max-width" => Self::MaxWidth,
            "min-height" => Self::MinHeight,
            "max-height" => Self::MaxHeight,
            "margin" => Self::Margin,
            "padding" => Self::Padding,
            "border-color" => Self::BorderColor,
            "border-width" => Self::BorderWidth,
            "border-radius" => Self::BorderRadius,
            "flex" => Self::Flex,
            "flex-grow" => Self::FlexGrow,
            "flex-shrink" => Self::FlexShrink,
            "flex-basis" => Self::FlexBasis,
            "gap" => Self::Gap,
            "row-gap" | "gap-row" => Self::GapRow,
            "column-gap" | "gap-col" => Self::GapCol,
            "box-shadow" => Self::BoxShadow,
            "filter" => Self::Filter,
            "backdrop-filter" => Self::BackdropFilter,
            "clip-path" => Self::ClipPath,
            "mix-blend-mode" => Self::MixBlendMode,
            "isolation" => Self::Isolation,
            "view-transition-name" => Self::ViewTransitionName,
            other => Self::Custom(other.to_string()),
        }
    }

    /// Evaluates if this transition property matches a specific target CSS property.
    pub fn matches(&self, target: &str) -> bool {
        match self {
            Self::All => true,
            Self::None => false,
            Self::Color => target == "color",
            Self::BackgroundColor => target == "background-color" || target == "background",
            Self::Opacity => target == "opacity",
            Self::Transform => target == "transform",
            Self::Width => target == "width",
            Self::Height => target == "height",
            Self::MinWidth => target == "min-width",
            Self::MaxWidth => target == "max-width",
            Self::MinHeight => target == "min-height",
            Self::MaxHeight => target == "max-height",
            Self::Margin => target.starts_with("margin"),
            Self::Padding => target.starts_with("padding"),
            Self::BorderColor => target.starts_with("border-color"),
            Self::BorderWidth => target.starts_with("border-width"),
            Self::BorderRadius => target.starts_with("border-radius"),
            Self::Flex => {
                target == "flex"
                    || target == "flex-grow"
                    || target == "flex-shrink"
                    || target == "flex-basis"
            }
            Self::FlexGrow => target == "flex-grow",
            Self::FlexShrink => target == "flex-shrink",
            Self::FlexBasis => target == "flex-basis",
            Self::Gap => target == "gap" || target == "row-gap" || target == "column-gap",
            Self::GapRow => target == "row-gap",
            Self::GapCol => target == "column-gap",
            Self::BoxShadow => target == "box-shadow",
            Self::Filter => target == "filter",
            Self::BackdropFilter => target == "backdrop-filter",
            Self::ClipPath => target == "clip-path",
            Self::MixBlendMode => target == "mix-blend-mode",
            Self::Isolation => target == "isolation",
            Self::ViewTransitionName => target == "view-transition-name",
            Self::Custom(c) => c.eq_ignore_ascii_case(target),
        }
    }

    /// Returns `true` when animating or transitioning this property affects box layout/reflow.
    #[inline]
    pub fn is_layout_affecting(&self) -> bool {
        matches!(
            self,
            Self::Width
                | Self::Height
                | Self::MinWidth
                | Self::MaxWidth
                | Self::MinHeight
                | Self::MaxHeight
                | Self::Margin
                | Self::Padding
                | Self::BorderWidth
                | Self::Flex
                | Self::FlexGrow
                | Self::FlexShrink
                | Self::FlexBasis
                | Self::Gap
                | Self::GapRow
                | Self::GapCol
        )
    }

    /// Returns the canonical CSS property name string.
    pub fn as_str(&self) -> &str {
        match self {
            Self::All => "all",
            Self::None => "none",
            Self::Color => "color",
            Self::BackgroundColor => "background-color",
            Self::Opacity => "opacity",
            Self::Transform => "transform",
            Self::Width => "width",
            Self::Height => "height",
            Self::MinWidth => "min-width",
            Self::MaxWidth => "max-width",
            Self::MinHeight => "min-height",
            Self::MaxHeight => "max-height",
            Self::Margin => "margin",
            Self::Padding => "padding",
            Self::BorderColor => "border-color",
            Self::BorderWidth => "border-width",
            Self::BorderRadius => "border-radius",
            Self::Flex => "flex",
            Self::FlexGrow => "flex-grow",
            Self::FlexShrink => "flex-shrink",
            Self::FlexBasis => "flex-basis",
            Self::Gap => "gap",
            Self::GapRow => "row-gap",
            Self::GapCol => "column-gap",
            Self::BoxShadow => "box-shadow",
            Self::Filter => "filter",
            Self::BackdropFilter => "backdrop-filter",
            Self::ClipPath => "clip-path",
            Self::MixBlendMode => "mix-blend-mode",
            Self::Isolation => "isolation",
            Self::ViewTransitionName => "view-transition-name",
            Self::Custom(s) => s.as_str(),
        }
    }
}

/// Transition behavior for discrete animatable properties (W3C CSS Transitions Level 2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TransitionBehavior {
    #[default]
    Normal,
    AllowDiscrete,
}

impl TransitionBehavior {
    /// Parses a CSS transition-behavior string.
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "normal" => Some(Self::Normal),
            "allow-discrete" => Some(Self::AllowDiscrete),
            _ => None,
        }
    }
}

/// Complete transition descriptor specifying timing, delay, easing, and behavior.
#[derive(Debug, Clone, PartialEq)]
pub struct TransitionSpec {
    pub property: TransitionProperty,
    pub duration_ms: f32,
    pub timing_function: TransitionEasing,
    pub delay_ms: f32,
    pub behavior: TransitionBehavior,
}

impl Default for TransitionSpec {
    fn default() -> Self {
        Self {
            property: TransitionProperty::All,
            duration_ms: 0.0,
            timing_function: TransitionEasing::Ease,
            delay_ms: 0.0,
            behavior: TransitionBehavior::Normal,
        }
    }
}

/// CSS animation-direction property (W3C CSS Animations Level 1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AnimationDirection {
    #[default]
    Normal,
    Reverse,
    Alternate,
    AlternateReverse,
}

impl AnimationDirection {
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "normal" => Some(Self::Normal),
            "reverse" => Some(Self::Reverse),
            "alternate" => Some(Self::Alternate),
            "alternate-reverse" => Some(Self::AlternateReverse),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Normal => "normal",
            Self::Reverse => "reverse",
            Self::Alternate => "alternate",
            Self::AlternateReverse => "alternate-reverse",
        }
    }
}

/// CSS animation-fill-mode property (W3C CSS Animations Level 1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AnimationFillMode {
    #[default]
    None,
    Forwards,
    Backwards,
    Both,
}

impl AnimationFillMode {
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "none" => Some(Self::None),
            "forwards" => Some(Self::Forwards),
            "backwards" => Some(Self::Backwards),
            "both" => Some(Self::Both),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Forwards => "forwards",
            Self::Backwards => "backwards",
            Self::Both => "both",
        }
    }
}

/// CSS animation-play-state property (W3C CSS Animations Level 1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AnimationPlayState {
    #[default]
    Running,
    Paused,
}

impl AnimationPlayState {
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "running" => Some(Self::Running),
            "paused" => Some(Self::Paused),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Running => "running",
            Self::Paused => "paused",
        }
    }
}

/// CSS animation-iteration-count property (W3C CSS Animations Level 1).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AnimationIterationCount {
    Infinite,
    Count(f32),
}

impl Default for AnimationIterationCount {
    fn default() -> Self {
        Self::Count(1.0)
    }
}

impl AnimationIterationCount {
    pub fn parse(s: &str) -> Option<Self> {
        let s = s.trim();
        if s.eq_ignore_ascii_case("infinite") {
            Some(Self::Infinite)
        } else if let Ok(n) = s.parse::<f32>() {
            if n >= 0.0 {
                Some(Self::Count(n))
            } else {
                None
            }
        } else {
            None
        }
    }
}

/// Target scroll axis for scroll-driven animations (W3C CSS Scroll-Driven Animations Level 1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ScrollAxis {
    #[default]
    Block,
    Inline,
    Vertical,
    Horizontal,
}

/// Target scroller source container for `scroll()` functional timeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ScrollTimelineSource {
    #[default]
    Nearest,
    Root,
    SelfNode,
}

/// CSS animation timeline descriptor per W3C Scroll-Driven Animations Level 1.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum AnimationTimeline {
    /// Traditional wall-clock time timeline.
    #[default]
    Time,
    /// Container scroll-driven timeline with source scroller and axis.
    Scroll(ScrollTimelineSource, ScrollAxis),
    /// Element visibility in scrollport view timeline with axis and start/end insets.
    View(ScrollAxis, f32, f32),
    /// Named timeline referencing a @scroll-timeline or scroll-timeline-name.
    Named(String),
}

/// Named range anchor for scroll-driven animations per W3C specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AnimationRangeName {
    #[default]
    Normal,
    Cover,
    Contain,
    Entry,
    Exit,
}

/// Start and end range boundaries for scroll-driven animations.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AnimationRange {
    pub name: AnimationRangeName,
    pub start_offset: f32,
    pub end_offset: f32,
}

impl Default for AnimationRange {
    fn default() -> Self {
        Self {
            name: AnimationRangeName::Normal,
            start_offset: 0.0,
            end_offset: 1.0,
        }
    }
}

/// Complete CSS animation descriptor specifying name, timing, delay, iterations, direction, fill mode, timeline, and range.
#[derive(Debug, Clone, PartialEq)]
pub struct AnimationSpec {
    pub name: String,
    pub duration_ms: f32,
    pub timing_function: TransitionEasing,
    pub delay_ms: f32,
    pub iteration_count: AnimationIterationCount,
    pub direction: AnimationDirection,
    pub fill_mode: AnimationFillMode,
    pub play_state: AnimationPlayState,
    pub timeline: AnimationTimeline,
    pub range: AnimationRange,
}

impl Default for AnimationSpec {
    fn default() -> Self {
        Self {
            name: String::new(),
            duration_ms: 0.0,
            timing_function: TransitionEasing::Ease,
            delay_ms: 0.0,
            iteration_count: AnimationIterationCount::Count(1.0),
            direction: AnimationDirection::Normal,
            fill_mode: AnimationFillMode::None,
            play_state: AnimationPlayState::Running,
            timeline: AnimationTimeline::Time,
            range: AnimationRange::default(),
        }
    }
}

/// An individual CSS 2D or 3D transform operation.
#[derive(Debug, Clone, PartialEq)]
pub enum TransformOp {
    Translate(Dimension, Dimension),
    Translate3d(Dimension, Dimension, Dimension),
    Scale(f32, f32),
    Scale3d(f32, f32, f32),
    Rotate(f32), // Radians (around Z)
    RotateX(f32),
    RotateY(f32),
    RotateZ(f32),
    Rotate3d(f32, f32, f32, f32), // x, y, z, rad
    Skew(f32, f32),               // Radians (ax, ay)
    Perspective(f32),             // Pixels
    Matrix([f32; 6]),
    Matrix3d([f32; 16]),
}

impl TransformOp {
    /// Computes the 4x4 matrix for this individual transform operation given element size.
    pub fn to_matrix(&self, width: f32, height: f32) -> Matrix4x4 {
        match self {
            Self::Translate(dx, dy) => {
                let tx = match dx {
                    Dimension::Px(px) => *px,
                    Dimension::Percent(pct) => width * (pct / 100.0),
                    Dimension::Rem(rem) => rem * 16.0,
                    Dimension::Em(em) => em * 16.0,
                    _ => 0.0,
                };
                let ty = match dy {
                    Dimension::Px(px) => *px,
                    Dimension::Percent(pct) => height * (pct / 100.0),
                    Dimension::Rem(rem) => rem * 16.0,
                    Dimension::Em(em) => em * 16.0,
                    _ => 0.0,
                };
                Matrix4x4::translation(tx, ty, 0.0)
            }
            Self::Translate3d(dx, dy, dz) => {
                let tx = match dx {
                    Dimension::Px(px) => *px,
                    Dimension::Percent(pct) => width * (pct / 100.0),
                    Dimension::Rem(rem) => rem * 16.0,
                    Dimension::Em(em) => em * 16.0,
                    _ => 0.0,
                };
                let ty = match dy {
                    Dimension::Px(px) => *px,
                    Dimension::Percent(pct) => height * (pct / 100.0),
                    Dimension::Rem(rem) => rem * 16.0,
                    Dimension::Em(em) => em * 16.0,
                    _ => 0.0,
                };
                let tz = match dz {
                    Dimension::Px(px) => *px,
                    Dimension::Rem(rem) => rem * 16.0,
                    Dimension::Em(em) => em * 16.0,
                    _ => 0.0,
                };
                Matrix4x4::translation(tx, ty, tz)
            }
            Self::Scale(sx, sy) => Matrix4x4::scaling(*sx, *sy, 1.0),
            Self::Scale3d(sx, sy, sz) => Matrix4x4::scaling(*sx, *sy, *sz),
            Self::Rotate(rad) | Self::RotateZ(rad) => Matrix4x4::rotation_z(*rad),
            Self::RotateX(rad) => Matrix4x4::rotation_x(*rad),
            Self::RotateY(rad) => Matrix4x4::rotation_y(*rad),
            Self::Rotate3d(x, y, z, rad) => Matrix4x4::rotation_axis(*x, *y, *z, *rad),
            Self::Skew(ax, ay) => Matrix4x4::skew(*ax, *ay),
            Self::Perspective(d) => Matrix4x4::perspective(*d),
            Self::Matrix(m) => Matrix4x4::from_2d(m[0], m[1], m[2], m[3], m[4], m[5]),
            Self::Matrix3d(m) => Matrix4x4::from_array(*m),
        }
    }

    /// Returns the identity equivalent for this operation type per CSS Transitions.
    pub fn to_identity(&self) -> Self {
        match self {
            Self::Translate(..) => Self::Translate(Dimension::Px(0.0), Dimension::Px(0.0)),
            Self::Translate3d(..) => {
                Self::Translate3d(Dimension::Px(0.0), Dimension::Px(0.0), Dimension::Px(0.0))
            }
            Self::Scale(..) => Self::Scale(1.0, 1.0),
            Self::Scale3d(..) => Self::Scale3d(1.0, 1.0, 1.0),
            Self::Rotate(..) => Self::Rotate(0.0),
            Self::RotateX(..) => Self::RotateX(0.0),
            Self::RotateY(..) => Self::RotateY(0.0),
            Self::RotateZ(..) => Self::RotateZ(0.0),
            Self::Rotate3d(x, y, z, _) => Self::Rotate3d(*x, *y, *z, 0.0),
            Self::Skew(..) => Self::Skew(0.0, 0.0),
            Self::Perspective(d) => Self::Perspective(*d),
            Self::Matrix(..) => Self::Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]),
            Self::Matrix3d(..) => Self::Matrix3d([
                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
            ]),
        }
    }
}

/// The origin point around which transforms are applied.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TransformOrigin {
    pub x: Dimension,
    pub y: Dimension,
    pub z: f32,
}

impl Default for TransformOrigin {
    fn default() -> Self {
        Self {
            x: Dimension::Percent(50.0),
            y: Dimension::Percent(50.0),
            z: 0.0,
        }
    }
}

/// CSS transform-style property defining 3D rendering context hierarchy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TransformStyle {
    #[default]
    Flat,
    Preserve3d,
}

/// CSS backface-visibility property determining if reverse side of 3D element is rendered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BackfaceVisibility {
    #[default]
    Visible,
    Hidden,
}

/// Computes the composite 4x4 matrix for a list of transform operations relative to `origin`.
pub fn compute_transform_matrix(
    ops: &[TransformOp],
    width: f32,
    height: f32,
    origin: &TransformOrigin,
) -> Matrix4x4 {
    if ops.is_empty() {
        return Matrix4x4::identity();
    }

    let ox = match origin.x {
        Dimension::Px(px) => px,
        Dimension::Percent(pct) => width * (pct / 100.0),
        Dimension::Rem(rem) => rem * 16.0,
        Dimension::Em(em) => em * 16.0,
        _ => width * 0.5,
    };
    let oy = match origin.y {
        Dimension::Px(px) => px,
        Dimension::Percent(pct) => height * (pct / 100.0),
        Dimension::Rem(rem) => rem * 16.0,
        Dimension::Em(em) => em * 16.0,
        _ => height * 0.5,
    };
    let oz = origin.z;

    let t_origin = Matrix4x4::translation(ox, oy, oz);
    let t_origin_inv = Matrix4x4::translation(-ox, -oy, -oz);

    let mut combined_ops = Matrix4x4::identity();
    for op in ops {
        combined_ops = combined_ops.multiply(&op.to_matrix(width, height));
    }

    t_origin.multiply(&combined_ops).multiply(&t_origin_inv)
}

/// Fully computed and resolved styles for an element node.
#[derive(Debug, Clone, PartialEq)]
pub struct ComputedStyle {
    // Layout Display & Box Model
    pub display: Display,
    pub position: Position,
    pub float: Float,
    pub clear: Clear,
    pub box_sizing: BoxSizing,
    pub content_visibility: ContentVisibility,
    pub contain: Containment,
    pub contain_intrinsic_width: Option<Dimension>,
    pub contain_intrinsic_height: Option<Dimension>,
    pub width: Dimension,
    pub height: Dimension,
    pub min_width: Dimension,
    pub max_width: Dimension,
    pub min_height: Dimension,
    pub max_height: Dimension,
    pub margin: EdgeInsets<f32>,
    pub margin_auto_top: bool,
    pub margin_auto_right: bool,
    pub margin_auto_bottom: bool,
    pub margin_auto_left: bool,
    pub padding: EdgeInsets<f32>,
    pub insets: EdgeInsets<Dimension>, // top, right, bottom, left
    pub z_index: Option<i32>,

    // Flexbox
    pub flex_direction: FlexDirection,
    pub flex_wrap: FlexWrap,
    pub justify_content: JustifyContent,
    pub align_items: AlignItems,
    pub align_self: AlignSelf,
    pub flex_grow: f32,
    pub flex_shrink: f32,
    pub flex_basis: Dimension,
    pub gap: f32,
    pub gap_row: f32,
    pub gap_col: f32,

    // CSS Grid
    pub grid_template_columns: Vec<GridTrack>,
    pub grid_template_rows: Vec<GridTrack>,
    pub grid_template_areas: Vec<Vec<String>>,
    pub grid_auto_flow: GridAutoFlow,
    pub grid_area: Option<String>,
    pub grid_column_start: Option<i32>,
    pub grid_column_end: Option<i32>,
    pub grid_column_span: Option<u32>,
    pub grid_row_start: Option<i32>,
    pub grid_row_end: Option<i32>,
    pub grid_row_span: Option<u32>,

    // CSS Table
    pub table_layout: TableLayout,
    pub border_collapse: BorderCollapse,
    pub border_spacing: (f32, f32),
    pub caption_side: CaptionSide,
    pub colspan: u32,
    pub rowspan: u32,

    // Visuals & Backgrounds
    pub background_color: Option<Color>,
    pub background_gradient: Option<Gradient>,
    pub border_color: Option<Color>,
    pub border_width: EdgeInsets<f32>,
    pub border_radius: BorderRadius,
    pub opacity: f32,
    pub box_shadow: Vec<BoxShadow>,
    pub overflow_x: Overflow,
    pub overflow_y: Overflow,

    // Typography (Inheritable)
    pub color: Color,
    pub font_family: AtomId,
    pub font_size: f32,
    pub root_font_size: f32,
    pub font_weight: FontWeight,
    pub font_style: FontStyle,
    pub text_align: TextAlign,
    pub line_height: f32,
    pub letter_spacing: f32,
    pub text_decoration: TextDecoration,
    pub text_transform: TextTransform,
    pub text_overflow: TextOverflow,
    pub white_space: WhiteSpace,
    pub vertical_align: VerticalAlign,

    // Interaction & Behavior (Inheritable)
    pub cursor: Cursor,
    pub user_select: UserSelect,
    pub pointer_events: PointerEvents,
    pub visibility: Visibility,
    pub caret_color: Option<Color>,

    // Border & Outline Styles
    pub border_style: BorderStyle,
    pub outline_width: f32,
    pub outline_style: BorderStyle,
    pub outline_color: Option<Color>,
    pub outline_offset: f32,

    // Aspect Ratio & Layout
    pub aspect_ratio: Option<f32>,

    // Visual Effects
    pub backdrop_filter: Option<crate::effects::BackdropFilter>,
    pub filter: Option<crate::effects::BackdropFilter>,
    pub clip_path: Option<crate::effects::ClipPath>,
    pub mix_blend_mode: BlendMode,
    pub isolation: Isolation,

    // Transitions (W3C CSS Transitions Level 1 & 2)
    pub transitions: Vec<TransitionSpec>,

    // Animations (W3C CSS Animations Level 1 & 2)
    pub animations: Vec<AnimationSpec>,

    // CSS 2D & 3D Transforms (Level 1 & Level 2)
    pub transform: Vec<TransformOp>,
    pub transform_origin: TransformOrigin,
    pub transform_style: TransformStyle,
    pub perspective: Option<f32>,
    pub perspective_origin: (Dimension, Dimension),
    pub backface_visibility: BackfaceVisibility,

    // CSS Custom Properties (Inheritable - Copy-On-Write Arc)
    pub custom_properties: Option<CustomPropertyMap>,

    // Next-Gen CSS Standards (Milestone 48)
    pub starting_style: Option<Box<ComputedStyle>>,
    pub view_transition_name: Option<String>,
    pub animation_timeline: AnimationTimeline,
    pub animation_range: AnimationRange,
}

impl Default for ComputedStyle {
    fn default() -> Self {
        Self {
            display: Display::Block,
            position: Position::Static,
            float: Float::None,
            clear: Clear::None,
            box_sizing: BoxSizing::BorderBox,
            content_visibility: ContentVisibility::Visible,
            contain: Containment::NONE,
            contain_intrinsic_width: None,
            contain_intrinsic_height: None,
            width: Dimension::Auto,
            height: Dimension::Auto,
            min_width: Dimension::Auto,
            max_width: Dimension::Auto,
            min_height: Dimension::Auto,
            max_height: Dimension::Auto,
            margin: EdgeInsets::ZERO,
            margin_auto_top: false,
            margin_auto_right: false,
            margin_auto_bottom: false,
            margin_auto_left: false,
            padding: EdgeInsets::ZERO,
            insets: EdgeInsets::new(
                Dimension::Auto,
                Dimension::Auto,
                Dimension::Auto,
                Dimension::Auto,
            ),
            z_index: None,

            flex_direction: FlexDirection::Row,
            flex_wrap: FlexWrap::NoWrap,
            justify_content: JustifyContent::FlexStart,
            align_items: AlignItems::Stretch,
            align_self: AlignSelf::Auto,
            flex_grow: 0.0,
            flex_shrink: 1.0,
            flex_basis: Dimension::Auto,
            gap: 0.0,
            gap_row: 0.0,
            gap_col: 0.0,

            grid_template_columns: Vec::new(),
            grid_template_rows: Vec::new(),
            grid_template_areas: Vec::new(),
            grid_auto_flow: GridAutoFlow::Row,
            grid_area: None,
            grid_column_start: None,
            grid_column_end: None,
            grid_column_span: None,
            grid_row_start: None,
            grid_row_end: None,
            grid_row_span: None,

            table_layout: TableLayout::Auto,
            border_collapse: BorderCollapse::Separate,
            border_spacing: (0.0, 0.0),
            caption_side: CaptionSide::Top,
            colspan: 1,
            rowspan: 1,

            background_color: None,
            background_gradient: None,
            border_color: None,
            border_width: EdgeInsets::ZERO,
            border_radius: BorderRadius::ZERO,
            opacity: 1.0,
            box_shadow: Vec::new(),
            overflow_x: Overflow::Visible,
            overflow_y: Overflow::Visible,

            color: Color::BLACK,
            font_family: AtomId::FONT_SANS,
            font_size: 16.0,
            root_font_size: 16.0,
            font_weight: FontWeight::Normal,
            font_style: FontStyle::Normal,
            text_align: TextAlign::Left,
            line_height: 1.2,
            letter_spacing: 0.0,
            text_decoration: TextDecoration::None,
            text_transform: TextTransform::None,
            text_overflow: TextOverflow::Clip,
            white_space: WhiteSpace::Normal,
            vertical_align: VerticalAlign::Baseline,

            cursor: Cursor::Default,
            user_select: UserSelect::Auto,
            pointer_events: PointerEvents::Auto,
            visibility: Visibility::Visible,
            caret_color: None,

            border_style: BorderStyle::Solid,
            outline_width: 0.0,
            outline_style: BorderStyle::None,
            outline_color: None,
            outline_offset: 0.0,

            aspect_ratio: None,

            backdrop_filter: None,
            filter: None,
            clip_path: None,
            mix_blend_mode: BlendMode::Normal,
            isolation: Isolation::Auto,
            transitions: Vec::new(),
            animations: Vec::new(),

            transform: Vec::new(),
            transform_origin: TransformOrigin::default(),
            transform_style: TransformStyle::default(),
            perspective: None,
            perspective_origin: (Dimension::Percent(50.0), Dimension::Percent(50.0)),
            backface_visibility: BackfaceVisibility::default(),

            custom_properties: None,

            starting_style: None,
            view_transition_name: None,
            animation_timeline: AnimationTimeline::Time,
            animation_range: AnimationRange::default(),
        }
    }
}

impl ComputedStyle {
    /// Returns true if this style defines any animations.
    #[inline(always)]
    pub fn has_animations(&self) -> bool {
        !self.animations.is_empty()
    }

    /// Returns true if this style defines any 2D or 3D transform operations.
    #[inline(always)]
    pub fn has_transform(&self) -> bool {
        !self.transform.is_empty()
    }

    /// Returns true if this style defines any visual filters, backdrop filters, clip-paths, or blend modes.
    #[inline(always)]
    pub fn has_visual_effects(&self) -> bool {
        self.mix_blend_mode != BlendMode::Normal
            || self.isolation == Isolation::Isolate
            || self.filter.as_ref().is_some_and(|f| !f.is_empty())
            || self.backdrop_filter.as_ref().is_some_and(|b| !b.is_empty())
            || self.clip_path.as_ref().is_some_and(|c| !c.is_none())
    }

    /// Computes the composite 4x4 matrix for this element's transform given layout width and height.
    #[inline(always)]
    pub fn compute_transform_matrix(&self, width: f32, height: f32) -> Matrix4x4 {
        compute_transform_matrix(&self.transform, width, height, &self.transform_origin)
    }

    /// Evaluates if this element establishes a containing block for `position: fixed`
    /// (and `position: absolute`) descendants per CSS Transforms Level 1 §2 and Filter Effects Level 1 §5.
    #[inline(always)]
    pub fn establishes_fixed_containing_block(&self) -> bool {
        self.has_transform()
            || self.filter.as_ref().is_some_and(|f| !f.is_empty())
            || self.backdrop_filter.as_ref().is_some_and(|b| !b.is_empty())
    }

    /// Evaluates if this element establishes an isolated stacking context per
    /// W3C CSS 2.1 Appendix E, CSS Flexbox §4.3, CSS Grid §5.4, CSS Positioned Layout Level 3 §3.1,
    /// and CSS Compositing Level 1.
    ///
    /// Note: Per CSS 2.1 Appendix E / CSS Overflow Level 3, `overflow != Visible` clips scrollable
    /// content without establishing an atomic stacking context.
    #[inline]
    pub fn establishes_stacking_context_in(
        &self,
        parent_display: Option<Display>,
        is_root: bool,
    ) -> bool {
        if is_root {
            return true;
        }
        let is_positioned = self.position != Position::Static;
        let is_flex_or_grid_item = matches!(
            parent_display,
            Some(Display::Flex | Display::InlineFlex | Display::Grid | Display::InlineGrid)
        );
        let z_index_triggers = self.z_index.is_some() && (is_positioned || is_flex_or_grid_item);
        let fixed_or_sticky = matches!(self.position, Position::Fixed | Position::Sticky);

        z_index_triggers
            || fixed_or_sticky
            || self.opacity < 0.999
            || self.has_transform()
            || self.has_visual_effects()
    }

    /// Evaluates if this element establishes an isolated stacking context without parent display context.
    #[inline]
    pub fn establishes_stacking_context(&self) -> bool {
        self.establishes_stacking_context_in(None, false)
    }
    /// Constructs an unstyled node inheriting inheritable properties from parent with zero heap allocations.
    pub fn inherit_from(parent: &Self) -> Self {
        // Inheritable properties per W3C CSS Cascading and Inheritance Level 4:
        Self {
            color: parent.color,
            font_family: parent.font_family,
            font_size: parent.font_size,
            root_font_size: parent.root_font_size,
            font_weight: parent.font_weight,
            font_style: parent.font_style,
            text_align: parent.text_align,
            line_height: parent.line_height,
            letter_spacing: parent.letter_spacing,
            text_decoration: parent.text_decoration,
            text_transform: parent.text_transform,
            text_overflow: parent.text_overflow,
            white_space: parent.white_space,
            cursor: parent.cursor,
            user_select: parent.user_select,
            pointer_events: parent.pointer_events,
            visibility: parent.visibility,
            caret_color: parent.caret_color,
            border_collapse: parent.border_collapse,
            border_spacing: parent.border_spacing,
            caption_side: parent.caption_side,
            custom_properties: parent.custom_properties.clone(),
            ..Self::default()
        }
    }

    /// Looks up a CSS custom property by AtomId.
    pub fn get_custom_property(&self, key: AtomId) -> Option<AtomId> {
        let map = self.custom_properties.as_ref()?;
        for (k, v) in map.iter().rev() {
            if *k == key {
                return Some(*v);
            }
        }
        None
    }

    /// Sets or overrides a CSS custom property using Copy-On-Write semantics.
    pub fn set_custom_property(&mut self, key: AtomId, value: AtomId) {
        let mut list = match &self.custom_properties {
            Some(arc) => (**arc).clone(),
            None => Vec::with_capacity(4),
        };
        if let Some(pos) = list.iter().position(|(k, _)| *k == key) {
            list[pos].1 = value;
        } else {
            list.push((key, value));
        }
        self.custom_properties = Some(Arc::new(list));
    }
}