blinc_core 0.4.0

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

use std::collections::HashMap;

// ─────────────────────────────────────────────────────────────────────────────
// Core Geometry Types
// ─────────────────────────────────────────────────────────────────────────────

/// 2D point
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Point {
    pub x: f32,
    pub y: f32,
}

impl Point {
    pub const ZERO: Point = Point { x: 0.0, y: 0.0 };

    pub const fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
}

/// 2D size
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Size {
    pub width: f32,
    pub height: f32,
}

impl Size {
    pub const ZERO: Size = Size {
        width: 0.0,
        height: 0.0,
    };

    pub const fn new(width: f32, height: f32) -> Self {
        Self { width, height }
    }

    /// Convert to a Rect at the origin (0, 0)
    pub const fn to_rect(self) -> Rect {
        Rect {
            origin: Point::ZERO,
            size: self,
        }
    }
}

impl From<Size> for Rect {
    /// Convert Size to Rect at origin (0, 0)
    fn from(size: Size) -> Self {
        Rect {
            origin: Point::ZERO,
            size,
        }
    }
}

/// 2D rectangle
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Rect {
    pub origin: Point,
    pub size: Size,
}

impl Rect {
    pub const ZERO: Rect = Rect {
        origin: Point::ZERO,
        size: Size::ZERO,
    };

    pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
        Self {
            origin: Point::new(x, y),
            size: Size::new(width, height),
        }
    }

    pub fn from_origin_size(origin: Point, size: Size) -> Self {
        Self { origin, size }
    }

    pub fn x(&self) -> f32 {
        self.origin.x
    }

    pub fn y(&self) -> f32 {
        self.origin.y
    }

    pub fn width(&self) -> f32 {
        self.size.width
    }

    pub fn height(&self) -> f32 {
        self.size.height
    }

    pub fn center(&self) -> Point {
        Point::new(
            self.origin.x + self.size.width / 2.0,
            self.origin.y + self.size.height / 2.0,
        )
    }

    pub fn contains(&self, point: Point) -> bool {
        point.x >= self.origin.x
            && point.x <= self.origin.x + self.size.width
            && point.y >= self.origin.y
            && point.y <= self.origin.y + self.size.height
    }

    /// Get the size of this rect
    pub fn size(&self) -> Size {
        self.size
    }

    /// Offset the rect by a delta
    pub fn offset(&self, dx: f32, dy: f32) -> Self {
        Rect {
            origin: Point::new(self.origin.x + dx, self.origin.y + dy),
            size: self.size,
        }
    }

    /// Inset the rect by a delta (shrink from all sides)
    pub fn inset(&self, dx: f32, dy: f32) -> Self {
        Rect {
            origin: Point::new(self.origin.x + dx, self.origin.y + dy),
            size: Size::new(
                (self.size.width - 2.0 * dx).max(0.0),
                (self.size.height - 2.0 * dy).max(0.0),
            ),
        }
    }

    /// Create a rect from center point and size
    pub fn from_center(center: Point, size: Size) -> Self {
        Rect {
            origin: Point::new(center.x - size.width / 2.0, center.y - size.height / 2.0),
            size,
        }
    }

    /// Create a rect from two corner points
    pub fn from_points(p1: Point, p2: Point) -> Self {
        let min_x = p1.x.min(p2.x);
        let min_y = p1.y.min(p2.y);
        let max_x = p1.x.max(p2.x);
        let max_y = p1.y.max(p2.y);
        Rect {
            origin: Point::new(min_x, min_y),
            size: Size::new(max_x - min_x, max_y - min_y),
        }
    }

    /// Get the union of two rects (smallest rect containing both)
    pub fn union(&self, other: &Rect) -> Self {
        let min_x = self.origin.x.min(other.origin.x);
        let min_y = self.origin.y.min(other.origin.y);
        let max_x = (self.origin.x + self.size.width).max(other.origin.x + other.size.width);
        let max_y = (self.origin.y + self.size.height).max(other.origin.y + other.size.height);
        Rect {
            origin: Point::new(min_x, min_y),
            size: Size::new(max_x - min_x, max_y - min_y),
        }
    }

    /// Expand rect to include a point
    pub fn expand_to_include(&self, point: Point) -> Self {
        let min_x = self.origin.x.min(point.x);
        let min_y = self.origin.y.min(point.y);
        let max_x = (self.origin.x + self.size.width).max(point.x);
        let max_y = (self.origin.y + self.size.height).max(point.y);
        Rect {
            origin: Point::new(min_x, min_y),
            size: Size::new(max_x - min_x, max_y - min_y),
        }
    }

    /// Check if this rect intersects with another
    ///
    /// Returns true if the two rects overlap at any point.
    pub fn intersects(&self, other: &Rect) -> bool {
        let self_right = self.origin.x + self.size.width;
        let self_bottom = self.origin.y + self.size.height;
        let other_right = other.origin.x + other.size.width;
        let other_bottom = other.origin.y + other.size.height;

        self.origin.x < other_right
            && self_right > other.origin.x
            && self.origin.y < other_bottom
            && self_bottom > other.origin.y
    }

    /// Get the intersection of two rects (if they overlap)
    ///
    /// Returns None if the rects don't overlap.
    pub fn intersection(&self, other: &Rect) -> Option<Self> {
        if !self.intersects(other) {
            return None;
        }

        let x = self.origin.x.max(other.origin.x);
        let y = self.origin.y.max(other.origin.y);
        let right = (self.origin.x + self.size.width).min(other.origin.x + other.size.width);
        let bottom = (self.origin.y + self.size.height).min(other.origin.y + other.size.height);

        Some(Rect {
            origin: Point::new(x, y),
            size: Size::new(right - x, bottom - y),
        })
    }
}

/// 2D vector
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Vec2 {
    pub x: f32,
    pub y: f32,
}

impl Vec2 {
    pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };
    pub const ONE: Vec2 = Vec2 { x: 1.0, y: 1.0 };

    pub const fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }

    pub fn length(&self) -> f32 {
        (self.x * self.x + self.y * self.y).sqrt()
    }

    pub fn normalize(&self) -> Self {
        let len = self.length();
        if len > 0.0 {
            Self::new(self.x / len, self.y / len)
        } else {
            Self::ZERO
        }
    }
}

/// 3D vector
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Vec3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

impl Vec3 {
    pub const ZERO: Vec3 = Vec3 {
        x: 0.0,
        y: 0.0,
        z: 0.0,
    };
    pub const ONE: Vec3 = Vec3 {
        x: 1.0,
        y: 1.0,
        z: 1.0,
    };
    pub const UP: Vec3 = Vec3 {
        x: 0.0,
        y: 1.0,
        z: 0.0,
    };
    pub const FORWARD: Vec3 = Vec3 {
        x: 0.0,
        y: 0.0,
        z: -1.0,
    };

    pub const fn new(x: f32, y: f32, z: f32) -> Self {
        Self { x, y, z }
    }

    pub fn length(&self) -> f32 {
        (self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
    }

    pub fn normalize(&self) -> Self {
        let len = self.length();
        if len > 0.0 {
            Self::new(self.x / len, self.y / len, self.z / len)
        } else {
            Self::ZERO
        }
    }

    pub fn dot(&self, other: Vec3) -> f32 {
        self.x * other.x + self.y * other.y + self.z * other.z
    }

    pub fn cross(&self, other: Vec3) -> Vec3 {
        Vec3::new(
            self.y * other.z - self.z * other.y,
            self.z * other.x - self.x * other.z,
            self.x * other.y - self.y * other.x,
        )
    }
}

/// 4x4 transformation matrix (column-major)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Mat4 {
    pub cols: [[f32; 4]; 4],
}

impl Default for Mat4 {
    fn default() -> Self {
        Self::IDENTITY
    }
}

impl Mat4 {
    pub const IDENTITY: Mat4 = Mat4 {
        cols: [
            [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],
        ],
    };

    pub fn translation(x: f32, y: f32, z: f32) -> Self {
        Self {
            cols: [
                [1.0, 0.0, 0.0, 0.0],
                [0.0, 1.0, 0.0, 0.0],
                [0.0, 0.0, 1.0, 0.0],
                [x, y, z, 1.0],
            ],
        }
    }

    pub fn scale(x: f32, y: f32, z: f32) -> Self {
        Self {
            cols: [
                [x, 0.0, 0.0, 0.0],
                [0.0, y, 0.0, 0.0],
                [0.0, 0.0, z, 0.0],
                [0.0, 0.0, 0.0, 1.0],
            ],
        }
    }

    pub fn rotation_y(angle: f32) -> Self {
        let c = angle.cos();
        let s = angle.sin();
        Self {
            cols: [
                [c, 0.0, -s, 0.0],
                [0.0, 1.0, 0.0, 0.0],
                [s, 0.0, c, 0.0],
                [0.0, 0.0, 0.0, 1.0],
            ],
        }
    }

    /// Multiply two matrices
    pub fn mul(&self, other: &Mat4) -> Mat4 {
        let mut result = [[0.0f32; 4]; 4];
        for (i, result_col) in result.iter_mut().enumerate() {
            for (j, result_elem) in result_col.iter_mut().enumerate() {
                for k in 0..4 {
                    *result_elem += self.cols[k][j] * other.cols[i][k];
                }
            }
        }
        Mat4 { cols: result }
    }
}

/// 2D affine transformation
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Affine2D {
    /// Matrix elements [a, b, c, d, tx, ty]
    /// | a  c  tx |
    /// | b  d  ty |
    /// | 0  0   1 |
    pub elements: [f32; 6],
}

impl Default for Affine2D {
    fn default() -> Self {
        Self::IDENTITY
    }
}

impl Affine2D {
    pub const IDENTITY: Affine2D = Affine2D {
        elements: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
    };

    pub fn translation(x: f32, y: f32) -> Self {
        Self {
            elements: [1.0, 0.0, 0.0, 1.0, x, y],
        }
    }

    pub fn scale(sx: f32, sy: f32) -> Self {
        Self {
            elements: [sx, 0.0, 0.0, sy, 0.0, 0.0],
        }
    }

    pub fn rotation(angle: f32) -> Self {
        let c = angle.cos();
        let s = angle.sin();
        Self {
            elements: [c, s, -s, c, 0.0, 0.0],
        }
    }

    /// Create a skew-X transform (shear along X axis)
    /// `angle` is in radians
    pub fn skew_x(angle: f32) -> Self {
        Self {
            elements: [1.0, 0.0, angle.tan(), 1.0, 0.0, 0.0],
        }
    }

    /// Create a skew-Y transform (shear along Y axis)
    /// `angle` is in radians
    pub fn skew_y(angle: f32) -> Self {
        Self {
            elements: [1.0, angle.tan(), 0.0, 1.0, 0.0, 0.0],
        }
    }

    pub fn transform_point(&self, point: Point) -> Point {
        let [a, b, c, d, tx, ty] = self.elements;
        Point::new(
            a * point.x + c * point.y + tx,
            b * point.x + d * point.y + ty,
        )
    }

    /// Concatenate this transform with another (self * other)
    /// The resulting transform first applies `other`, then `self`.
    pub fn then(&self, other: &Affine2D) -> Affine2D {
        let [a1, b1, c1, d1, tx1, ty1] = self.elements;
        let [a2, b2, c2, d2, tx2, ty2] = other.elements;

        // Matrix multiplication for 2D affine transforms:
        // [a1 c1 tx1]   [a2 c2 tx2]
        // [b1 d1 ty1] * [b2 d2 ty2]
        // [0  0  1  ]   [0  0  1  ]
        Affine2D {
            elements: [
                a1 * a2 + c1 * b2,         // a
                b1 * a2 + d1 * b2,         // b
                a1 * c2 + c1 * d2,         // c
                b1 * c2 + d1 * d2,         // d
                a1 * tx2 + c1 * ty2 + tx1, // tx
                b1 * tx2 + d1 * ty2 + ty1, // ty
            ],
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Color and Visual Types
// ─────────────────────────────────────────────────────────────────────────────

/// RGBA color (linear space)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Color {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

impl Color {
    pub const WHITE: Color = Color::rgb(1.0, 1.0, 1.0);
    pub const BLACK: Color = Color::rgb(0.0, 0.0, 0.0);
    pub const RED: Color = Color::rgb(1.0, 0.0, 0.0);
    pub const GREEN: Color = Color::rgb(0.0, 1.0, 0.0);
    pub const BLUE: Color = Color::rgb(0.0, 0.0, 1.0);
    pub const YELLOW: Color = Color::rgb(1.0, 1.0, 0.0);
    pub const CYAN: Color = Color::rgb(0.0, 1.0, 1.0);
    pub const MAGENTA: Color = Color::rgb(1.0, 0.0, 1.0);
    pub const PURPLE: Color = Color::rgb(0.5, 0.0, 0.5);
    pub const ORANGE: Color = Color::rgb(1.0, 0.5, 0.0);
    pub const GRAY: Color = Color::rgb(0.5, 0.5, 0.5);
    pub const TRANSPARENT: Color = Color::rgba(0.0, 0.0, 0.0, 0.0);

    pub const fn rgb(r: f32, g: f32, b: f32) -> Self {
        Self { r, g, b, a: 1.0 }
    }

    pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
        Self { r, g, b, a }
    }

    pub fn from_hex(hex: u32) -> Self {
        let r = ((hex >> 16) & 0xFF) as f32 / 255.0;
        let g = ((hex >> 8) & 0xFF) as f32 / 255.0;
        let b = (hex & 0xFF) as f32 / 255.0;
        Self::rgb(r, g, b)
    }

    pub fn with_alpha(mut self, alpha: f32) -> Self {
        self.a = alpha;
        self
    }

    pub fn to_array(&self) -> [f32; 4] {
        [self.r, self.g, self.b, self.a]
    }

    /// Linear interpolation between two colors
    pub fn lerp(a: &Color, b: &Color, t: f32) -> Color {
        let t = t.clamp(0.0, 1.0);
        Color {
            r: a.r + (b.r - a.r) * t,
            g: a.g + (b.g - a.g) * t,
            b: a.b + (b.b - a.b) * t,
            a: a.a + (b.a - a.a) * t,
        }
    }
}

impl Default for Color {
    fn default() -> Self {
        Self::BLACK
    }
}

/// Gradient stop
#[derive(Clone, Copy, Debug)]
pub struct GradientStop {
    /// Position along the gradient (0.0 to 1.0)
    pub offset: f32,
    /// Color at this stop
    pub color: Color,
}

impl GradientStop {
    /// Create a new gradient stop
    pub fn new(offset: f32, color: Color) -> Self {
        Self {
            offset: offset.clamp(0.0, 1.0),
            color,
        }
    }
}

/// Gradient coordinate space
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GradientSpace {
    /// Coordinates are in user/world space (absolute pixels)
    #[default]
    UserSpace,
    /// Coordinates are relative to the bounding box (0.0-1.0)
    ObjectBoundingBox,
}

/// Gradient spread method for areas outside the gradient
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GradientSpread {
    /// Pad with the end colors
    #[default]
    Pad,
    /// Reflect the gradient
    Reflect,
    /// Repeat the gradient
    Repeat,
}

/// Gradient type
#[derive(Clone, Debug)]
pub enum Gradient {
    /// Linear gradient between two points
    Linear {
        /// Start point
        start: Point,
        /// End point
        end: Point,
        /// Color stops (should be sorted by offset)
        stops: Vec<GradientStop>,
        /// Coordinate space interpretation
        space: GradientSpace,
        /// Spread method
        spread: GradientSpread,
    },
    /// Radial gradient from center outward
    Radial {
        /// Center point
        center: Point,
        /// Radius
        radius: f32,
        /// Optional focal point (if None, same as center)
        focal: Option<Point>,
        /// Color stops (should be sorted by offset)
        stops: Vec<GradientStop>,
        /// Coordinate space interpretation
        space: GradientSpace,
        /// Spread method
        spread: GradientSpread,
    },
    /// Conic/angular gradient around a center point
    Conic {
        /// Center point
        center: Point,
        /// Start angle in radians
        start_angle: f32,
        /// Color stops (should be sorted by offset)
        stops: Vec<GradientStop>,
        /// Coordinate space interpretation
        space: GradientSpace,
    },
}

impl Gradient {
    /// Create a simple linear gradient with two colors
    pub fn linear(start: Point, end: Point, from: Color, to: Color) -> Self {
        Gradient::Linear {
            start,
            end,
            stops: vec![GradientStop::new(0.0, from), GradientStop::new(1.0, to)],
            space: GradientSpace::UserSpace,
            spread: GradientSpread::Pad,
        }
    }

    /// Create a linear gradient with multiple stops
    pub fn linear_with_stops(start: Point, end: Point, stops: Vec<GradientStop>) -> Self {
        Gradient::Linear {
            start,
            end,
            stops,
            space: GradientSpace::UserSpace,
            spread: GradientSpread::Pad,
        }
    }

    /// Create a simple radial gradient with two colors
    pub fn radial(center: Point, radius: f32, from: Color, to: Color) -> Self {
        Gradient::Radial {
            center,
            radius,
            focal: None,
            stops: vec![GradientStop::new(0.0, from), GradientStop::new(1.0, to)],
            space: GradientSpace::UserSpace,
            spread: GradientSpread::Pad,
        }
    }

    /// Create a radial gradient with multiple stops
    pub fn radial_with_stops(center: Point, radius: f32, stops: Vec<GradientStop>) -> Self {
        Gradient::Radial {
            center,
            radius,
            focal: None,
            stops,
            space: GradientSpace::UserSpace,
            spread: GradientSpread::Pad,
        }
    }

    /// Create a conic gradient with two colors
    pub fn conic(center: Point, from: Color, to: Color) -> Self {
        Gradient::Conic {
            center,
            start_angle: 0.0,
            stops: vec![GradientStop::new(0.0, from), GradientStop::new(1.0, to)],
            space: GradientSpace::UserSpace,
        }
    }

    /// Get the gradient stops
    pub fn stops(&self) -> &[GradientStop] {
        match self {
            Gradient::Linear { stops, .. } => stops,
            Gradient::Radial { stops, .. } => stops,
            Gradient::Conic { stops, .. } => stops,
        }
    }

    /// Get the first color in the gradient (or BLACK if no stops)
    pub fn first_color(&self) -> Color {
        self.stops()
            .first()
            .map(|s| s.color)
            .unwrap_or(Color::BLACK)
    }

    /// Get the last color in the gradient (or BLACK if no stops)
    pub fn last_color(&self) -> Color {
        self.stops().last().map(|s| s.color).unwrap_or(Color::BLACK)
    }
}

/// Image fill mode for background images
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ImageFit {
    /// Scale image to fill container, cropping if necessary (CSS: cover)
    #[default]
    Cover,
    /// Scale image to fit within container (CSS: contain)
    Contain,
    /// Stretch image to fill container exactly (CSS: fill)
    Fill,
    /// Tile the image to fill the container
    Tile,
}

/// Image alignment within container
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ImagePosition {
    /// Horizontal position (0.0 = left, 0.5 = center, 1.0 = right)
    pub x: f32,
    /// Vertical position (0.0 = top, 0.5 = center, 1.0 = bottom)
    pub y: f32,
}

impl ImagePosition {
    pub const CENTER: Self = Self { x: 0.5, y: 0.5 };
    pub const TOP_LEFT: Self = Self { x: 0.0, y: 0.0 };
    pub const TOP_CENTER: Self = Self { x: 0.5, y: 0.0 };
    pub const TOP_RIGHT: Self = Self { x: 1.0, y: 0.0 };
    pub const CENTER_LEFT: Self = Self { x: 0.0, y: 0.5 };
    pub const CENTER_RIGHT: Self = Self { x: 1.0, y: 0.5 };
    pub const BOTTOM_LEFT: Self = Self { x: 0.0, y: 1.0 };
    pub const BOTTOM_CENTER: Self = Self { x: 0.5, y: 1.0 };
    pub const BOTTOM_RIGHT: Self = Self { x: 1.0, y: 1.0 };

    pub fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
}

/// Image brush for background fills
#[derive(Clone, Debug)]
pub struct ImageBrush {
    /// Path to the image (relative to assets root or absolute)
    pub source: String,
    /// How to fit the image in the container
    pub fit: ImageFit,
    /// Position of the image within the container
    pub position: ImagePosition,
    /// Opacity (0.0 = transparent, 1.0 = opaque)
    pub opacity: f32,
    /// Tint color (multiplied with image)
    pub tint: Color,
}

impl ImageBrush {
    /// Create a new image brush with default settings
    pub fn new(source: impl Into<String>) -> Self {
        Self {
            source: source.into(),
            fit: ImageFit::Cover,
            position: ImagePosition::CENTER,
            opacity: 1.0,
            tint: Color::WHITE,
        }
    }

    /// Set the fit mode
    pub fn fit(mut self, fit: ImageFit) -> Self {
        self.fit = fit;
        self
    }

    /// Set cover fit (scales to fill, may crop)
    pub fn cover(self) -> Self {
        self.fit(ImageFit::Cover)
    }

    /// Set contain fit (scales to fit, may letterbox)
    pub fn contain(self) -> Self {
        self.fit(ImageFit::Contain)
    }

    /// Set fill fit (stretches to fill exactly)
    pub fn fill(self) -> Self {
        self.fit(ImageFit::Fill)
    }

    /// Set tile fit (repeats the image)
    pub fn tile(self) -> Self {
        self.fit(ImageFit::Tile)
    }

    /// Set the position
    pub fn position(mut self, position: ImagePosition) -> Self {
        self.position = position;
        self
    }

    /// Center the image
    pub fn center(self) -> Self {
        self.position(ImagePosition::CENTER)
    }

    /// Set opacity
    pub fn opacity(mut self, opacity: f32) -> Self {
        self.opacity = opacity;
        self
    }

    /// Set tint color
    pub fn tint(mut self, color: Color) -> Self {
        self.tint = color;
        self
    }
}

/// Brush for filling shapes
#[derive(Clone, Debug)]
pub enum Brush {
    Solid(Color),
    Gradient(Gradient),
    /// Glass/frosted blur effect - blurs content behind the shape
    Glass(GlassStyle),
    /// Pure backdrop blur effect - blurs content behind without glass styling
    Blur(BlurStyle),
    /// Image fill for backgrounds
    Image(ImageBrush),
}

impl From<Color> for Brush {
    fn from(color: Color) -> Self {
        Brush::Solid(color)
    }
}

impl From<GlassStyle> for Brush {
    fn from(style: GlassStyle) -> Self {
        Brush::Glass(style)
    }
}

impl From<ImageBrush> for Brush {
    fn from(brush: ImageBrush) -> Self {
        Brush::Image(brush)
    }
}

impl From<BlurStyle> for Brush {
    fn from(style: BlurStyle) -> Self {
        Brush::Blur(style)
    }
}

/// Blend mode for layer composition
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BlendMode {
    #[default]
    Normal,
    Multiply,
    Screen,
    Overlay,
    Darken,
    Lighten,
    ColorDodge,
    ColorBurn,
    HardLight,
    SoftLight,
    Difference,
    Exclusion,
}

/// Corner radii for rounded rectangles
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct CornerRadius {
    pub top_left: f32,
    pub top_right: f32,
    pub bottom_right: f32,
    pub bottom_left: f32,
}

impl CornerRadius {
    pub const ZERO: CornerRadius = CornerRadius {
        top_left: 0.0,
        top_right: 0.0,
        bottom_right: 0.0,
        bottom_left: 0.0,
    };

    /// Create a corner radius with different values for each corner.
    /// Order: top_left, top_right, bottom_right, bottom_left (clockwise from top-left)
    pub 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 fn uniform(radius: f32) -> Self {
        Self {
            top_left: radius,
            top_right: radius,
            bottom_right: radius,
            bottom_left: radius,
        }
    }

    pub fn to_array(&self) -> [f32; 4] {
        [
            self.top_left,
            self.top_right,
            self.bottom_right,
            self.bottom_left,
        ]
    }

    /// Check if all corner radii are the same
    pub fn is_uniform(&self) -> bool {
        self.top_left == self.top_right
            && self.top_right == self.bottom_right
            && self.bottom_right == self.bottom_left
    }
}

impl From<f32> for CornerRadius {
    fn from(radius: f32) -> Self {
        Self::uniform(radius)
    }
}

/// Corner shape parameters for superellipse-based corners.
///
/// Each value is the CSS `superellipse(n)` parameter controlling corner curvature:
/// - `1.0` = round (standard circular arc, default)
/// - `0.0` = bevel (straight diagonal cut)
/// - `2.0` = squircle (smoother than circular)
/// - `-1.0` = scoop (concave inward curve)
/// - `100.0` = square (sharp corner, ignores border-radius)
/// - `-100.0` = notch (sharp 90° inward notch)
///
/// The CSS `n` value maps to Lamé exponent `p = 2^n`:
/// `n=0→p=1 (L1/bevel)`, `n=1→p=2 (L2/circle)`, `n=2→p=4 (squircle)`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CornerShape {
    pub top_left: f32,
    pub top_right: f32,
    pub bottom_right: f32,
    pub bottom_left: f32,
}

impl Default for CornerShape {
    fn default() -> Self {
        Self::ROUND
    }
}

impl CornerShape {
    /// Standard circular corners (default)
    pub const ROUND: CornerShape = CornerShape {
        top_left: 1.0,
        top_right: 1.0,
        bottom_right: 1.0,
        bottom_left: 1.0,
    };

    /// Straight diagonal cut corners
    pub const BEVEL: CornerShape = CornerShape {
        top_left: 0.0,
        top_right: 0.0,
        bottom_right: 0.0,
        bottom_left: 0.0,
    };

    /// Smoother-than-circular corners
    pub const SQUIRCLE: CornerShape = CornerShape {
        top_left: 2.0,
        top_right: 2.0,
        bottom_right: 2.0,
        bottom_left: 2.0,
    };

    /// Concave inward-curving corners
    pub const SCOOP: CornerShape = CornerShape {
        top_left: -1.0,
        top_right: -1.0,
        bottom_right: -1.0,
        bottom_left: -1.0,
    };

    /// Sharp 90° inward notch corners
    pub const NOTCH: CornerShape = CornerShape {
        top_left: -100.0,
        top_right: -100.0,
        bottom_right: -100.0,
        bottom_left: -100.0,
    };

    /// Sharp square corners (no rounding even with border-radius)
    pub const SQUARE: CornerShape = CornerShape {
        top_left: 100.0,
        top_right: 100.0,
        bottom_right: 100.0,
        bottom_left: 100.0,
    };

    pub 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 fn uniform(n: f32) -> Self {
        Self {
            top_left: n,
            top_right: n,
            bottom_right: n,
            bottom_left: n,
        }
    }

    pub fn to_array(&self) -> [f32; 4] {
        [
            self.top_left,
            self.top_right,
            self.bottom_right,
            self.bottom_left,
        ]
    }

    /// Check if all corners are standard round (n=1.0)
    pub fn is_round(&self) -> bool {
        (self.top_left - 1.0).abs() < 0.001
            && (self.top_right - 1.0).abs() < 0.001
            && (self.bottom_right - 1.0).abs() < 0.001
            && (self.bottom_left - 1.0).abs() < 0.001
    }
}

impl From<f32> for CornerShape {
    fn from(n: f32) -> Self {
        Self::uniform(n)
    }
}

/// Per-edge fade distances for smooth overflow clipping.
///
/// Instead of hard-clipping at the overflow boundary, each edge can have a
/// pixel distance over which content fades to transparent via a linear ramp.
/// Zero means hard clip (default).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct OverflowFade {
    pub top: f32,
    pub right: f32,
    pub bottom: f32,
    pub left: f32,
}

impl OverflowFade {
    pub const NONE: OverflowFade = OverflowFade {
        top: 0.0,
        right: 0.0,
        bottom: 0.0,
        left: 0.0,
    };

    pub fn uniform(distance: f32) -> Self {
        Self {
            top: distance,
            right: distance,
            bottom: distance,
            left: distance,
        }
    }

    pub fn vertical(distance: f32) -> Self {
        Self {
            top: distance,
            right: 0.0,
            bottom: distance,
            left: 0.0,
        }
    }

    pub fn horizontal(distance: f32) -> Self {
        Self {
            top: 0.0,
            right: distance,
            bottom: 0.0,
            left: distance,
        }
    }

    pub fn new(top: f32, right: f32, bottom: f32, left: f32) -> Self {
        Self {
            top,
            right,
            bottom,
            left,
        }
    }

    pub fn to_array(&self) -> [f32; 4] {
        [self.top, self.right, self.bottom, self.left]
    }

    pub fn is_none(&self) -> bool {
        self.top == 0.0 && self.right == 0.0 && self.bottom == 0.0 && self.left == 0.0
    }
}

impl From<f32> for OverflowFade {
    fn from(distance: f32) -> Self {
        Self::uniform(distance)
    }
}

/// Shadow configuration
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Shadow {
    pub offset_x: f32,
    pub offset_y: f32,
    pub blur: f32,
    pub spread: f32,
    pub color: Color,
}

impl Shadow {
    pub fn new(offset_x: f32, offset_y: f32, blur: f32, color: Color) -> Self {
        Self {
            offset_x,
            offset_y,
            blur,
            spread: 0.0,
            color,
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Glass Style
// ─────────────────────────────────────────────────────────────────────────────

/// Glass/frosted glass effect configuration
///
/// Creates a backdrop blur effect similar to macOS vibrancy or iOS blur.
/// Used with `DrawContext::fill_glass()` to render glass panels.
#[derive(Clone, Copy, Debug)]
pub struct GlassStyle {
    /// Blur intensity (0-50, default 20)
    pub blur: f32,
    /// Tint color applied over the blur
    pub tint: Color,
    /// Color saturation (1.0 = normal, 0.0 = grayscale)
    pub saturation: f32,
    /// Brightness multiplier (1.0 = normal)
    pub brightness: f32,
    /// Noise/grain amount for frosted texture (0.0-0.1)
    pub noise: f32,
    /// Border highlight thickness
    pub border_thickness: f32,
    /// Optional drop shadow
    pub shadow: Option<Shadow>,
    /// Use simple frosted glass mode (no liquid glass effects)
    ///
    /// When true, renders pure frosted glass without edge refraction,
    /// light reflections, or bevel effects. More performant and suitable
    /// for subtle UI backgrounds.
    pub simple: bool,
    /// Glass nesting depth (0 = top-level, 1+ = nested inside another glass element).
    /// Nested glass requires multi-pass rendering: parent glass renders first,
    /// then the result becomes the backdrop for child glass.
    pub depth: u32,
    /// Border color (when set with alpha > 0, renders a solid border instead of light-based highlights)
    pub border_color: Option<Color>,
}

impl Default for GlassStyle {
    fn default() -> Self {
        Self {
            blur: 20.0,
            tint: Color::rgba(1.0, 1.0, 1.0, 0.1),
            saturation: 1.0,
            brightness: 1.0,
            noise: 0.0,
            border_thickness: 0.8,
            shadow: None,
            simple: false,
            depth: 0,
            border_color: None,
        }
    }
}

impl GlassStyle {
    /// Create a new glass style with default settings
    pub fn new() -> Self {
        Self::default()
    }

    /// Set blur intensity
    pub fn blur(mut self, blur: f32) -> Self {
        self.blur = blur;
        self
    }

    /// Set tint color
    pub fn tint(mut self, color: Color) -> Self {
        self.tint = color;
        self
    }

    /// Set saturation
    pub fn saturation(mut self, saturation: f32) -> Self {
        self.saturation = saturation;
        self
    }

    /// Set brightness
    pub fn brightness(mut self, brightness: f32) -> Self {
        self.brightness = brightness;
        self
    }

    /// Set noise amount
    pub fn noise(mut self, noise: f32) -> Self {
        self.noise = noise;
        self
    }

    /// Set border thickness
    pub fn border(mut self, thickness: f32) -> Self {
        self.border_thickness = thickness;
        self
    }

    /// Set drop shadow
    pub fn shadow(mut self, shadow: Shadow) -> Self {
        self.shadow = Some(shadow);
        self
    }

    // Presets

    /// Ultra-thin glass (subtle blur)
    pub fn ultra_thin() -> Self {
        Self::new().blur(10.0)
    }

    /// Thin glass
    pub fn thin() -> Self {
        Self::new().blur(15.0)
    }

    /// Regular glass (default)
    pub fn regular() -> Self {
        Self::new()
    }

    /// Thick glass (heavy blur)
    pub fn thick() -> Self {
        Self::new().blur(30.0)
    }

    /// Frosted glass with grain texture
    pub fn frosted() -> Self {
        Self::new().noise(0.03)
    }

    /// Simple frosted glass - pure blur without liquid glass effects
    ///
    /// Creates a clean backdrop blur effect without edge refraction,
    /// light reflections, or bevel effects. More performant and ideal
    /// for subtle UI backgrounds where you want pure frosted glass.
    pub fn simple() -> Self {
        Self {
            blur: 15.0,
            tint: Color::rgba(1.0, 1.0, 1.0, 0.15),
            saturation: 1.1,
            brightness: 1.0,
            noise: 0.0,
            border_thickness: 0.0,
            shadow: None,
            simple: true,
            depth: 0,
            border_color: None,
        }
    }

    /// Enable/disable simple mode (no liquid glass effects)
    pub fn with_simple(mut self, simple: bool) -> Self {
        self.simple = simple;
        self
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Blur Style
// ─────────────────────────────────────────────────────────────────────────────

/// Pure backdrop blur effect configuration
///
/// Unlike `GlassStyle`, this provides just blur without tinting, noise, or other
/// glass-specific effects. Use this when you want a simple blur effect on the
/// content behind an element.
#[derive(Clone, Copy, Debug)]
pub struct BlurStyle {
    /// Blur radius in pixels (0-50, default 10)
    pub radius: f32,
    /// Blur quality setting
    pub quality: crate::draw::BlurQuality,
    /// Optional tint color (applied after blur)
    pub tint: Option<Color>,
    /// Opacity of the blur effect (0.0-1.0, default 1.0)
    pub opacity: f32,
}

impl Default for BlurStyle {
    fn default() -> Self {
        Self {
            radius: 10.0,
            quality: crate::draw::BlurQuality::Medium,
            tint: None,
            opacity: 1.0,
        }
    }
}

impl BlurStyle {
    /// Create a new blur style with default settings
    pub fn new() -> Self {
        Self::default()
    }

    /// Create blur with specified radius
    pub fn with_radius(radius: f32) -> Self {
        Self {
            radius,
            ..Default::default()
        }
    }

    /// Set blur radius
    pub fn radius(mut self, radius: f32) -> Self {
        self.radius = radius;
        self
    }

    /// Set blur quality
    pub fn quality(mut self, quality: crate::draw::BlurQuality) -> Self {
        self.quality = quality;
        self
    }

    /// Set optional tint color
    pub fn tint(mut self, color: Color) -> Self {
        self.tint = Some(color);
        self
    }

    /// Set opacity
    pub fn opacity(mut self, opacity: f32) -> Self {
        self.opacity = opacity;
        self
    }

    // Presets

    /// Light blur (subtle, 5px)
    pub fn light() -> Self {
        Self::with_radius(5.0)
    }

    /// Medium blur (default, 10px)
    pub fn medium() -> Self {
        Self::with_radius(10.0)
    }

    /// Heavy blur (20px)
    pub fn heavy() -> Self {
        Self::with_radius(20.0)
    }

    /// Maximum blur (50px)
    pub fn max() -> Self {
        Self::with_radius(50.0)
    }

    /// High quality blur (Kawase multi-pass)
    pub fn high_quality(mut self) -> Self {
        self.quality = crate::draw::BlurQuality::High;
        self
    }

    /// Low quality blur (fast box blur)
    pub fn low_quality(mut self) -> Self {
        self.quality = crate::draw::BlurQuality::Low;
        self
    }
}

impl From<f32> for BlurStyle {
    fn from(radius: f32) -> Self {
        Self::with_radius(radius)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Layer Identifiers
// ─────────────────────────────────────────────────────────────────────────────

/// Unique identifier for a layer
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct LayerId(pub u64);

impl LayerId {
    pub fn new(id: u64) -> Self {
        Self(id)
    }
}

/// Generator for unique layer IDs
#[derive(Debug, Default)]
pub struct LayerIdGenerator {
    next: u64,
}

impl LayerIdGenerator {
    pub fn new() -> Self {
        Self { next: 1 }
    }

    pub fn next_id(&mut self) -> LayerId {
        let id = LayerId(self.next);
        self.next += 1;
        id
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Layer Properties
// ─────────────────────────────────────────────────────────────────────────────

/// Pointer event behavior
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PointerEvents {
    /// Normal hit testing
    #[default]
    Auto,
    /// Transparent to input
    None,
    /// Receive events but don't block
    PassThrough,
}

/// Billboard facing mode for 2D content in 3D space
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BillboardFacing {
    /// Always faces camera
    #[default]
    Camera,
    /// Faces camera but stays upright
    CameraY,
    /// Uses transform rotation
    Fixed,
}

/// Layer cache policy
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CachePolicy {
    /// Always re-render
    #[default]
    None,
    /// Cache until content changes
    Content,
    /// Cache with explicit invalidation
    Manual,
}

/// Post-processing effect
#[derive(Clone, Debug)]
pub enum PostEffect {
    Blur { radius: f32 },
    Saturation { factor: f32 },
    Brightness { factor: f32 },
    Contrast { factor: f32 },
    GlassBlur { radius: f32, tint: Color },
}

/// Texture format for offscreen layers
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextureFormat {
    #[default]
    Bgra8Unorm,
    Rgba8Unorm,
    Rgba16Float,
    Rgba32Float,
}

/// Properties common to all layers
#[derive(Clone, Debug, Default)]
pub struct LayerProperties {
    /// Unique identifier for referencing
    pub id: Option<LayerId>,

    /// Visibility (skips render entirely when false)
    pub visible: bool,

    /// Pointer event behavior
    pub pointer_events: PointerEvents,

    /// Render order hint (within same Z-level)
    pub order: i32,

    /// Optional name for debugging
    pub name: Option<String>,
}

impl LayerProperties {
    pub fn new() -> Self {
        Self {
            visible: true,
            ..Default::default()
        }
    }

    pub fn with_id(mut self, id: LayerId) -> Self {
        self.id = Some(id);
        self
    }

    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    pub fn hidden(mut self) -> Self {
        self.visible = false;
        self
    }

    pub fn with_order(mut self, order: i32) -> Self {
        self.order = order;
        self
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Clip Shape
// ─────────────────────────────────────────────────────────────────────────────

/// Shape used for clipping
#[derive(Clone, Debug)]
pub enum ClipShape {
    /// Axis-aligned rectangle clip
    Rect(Rect),
    /// Rounded rectangle clip
    RoundedRect {
        rect: Rect,
        corner_radius: CornerRadius,
    },
    /// Circular clip
    Circle { center: Point, radius: f32 },
    /// Elliptical clip
    Ellipse { center: Point, radii: Vec2 },
    /// Arbitrary path clip (requires tessellation or stencil buffer)
    Path(crate::draw::Path),
    /// Polygon clip with pre-resolved vertices (absolute pixel coordinates)
    Polygon(Vec<Point>),
}

impl ClipShape {
    /// Create a rectangular clip
    pub fn rect(rect: Rect) -> Self {
        ClipShape::Rect(rect)
    }

    /// Create a rounded rectangle clip
    pub fn rounded_rect(rect: Rect, corner_radius: impl Into<CornerRadius>) -> Self {
        ClipShape::RoundedRect {
            rect,
            corner_radius: corner_radius.into(),
        }
    }

    /// Create a circular clip
    pub fn circle(center: Point, radius: f32) -> Self {
        ClipShape::Circle { center, radius }
    }

    /// Create an elliptical clip
    pub fn ellipse(center: Point, radii: Vec2) -> Self {
        ClipShape::Ellipse { center, radii }
    }

    /// Create a path-based clip
    pub fn path(path: crate::draw::Path) -> Self {
        ClipShape::Path(path)
    }

    /// Get the bounding rect of this clip shape
    pub fn bounds(&self) -> Rect {
        match self {
            ClipShape::Rect(rect) => *rect,
            ClipShape::RoundedRect { rect, .. } => *rect,
            ClipShape::Circle { center, radius } => {
                Rect::from_center(*center, Size::new(*radius * 2.0, *radius * 2.0))
            }
            ClipShape::Ellipse { center, radii } => {
                Rect::from_center(*center, Size::new(radii.x * 2.0, radii.y * 2.0))
            }
            ClipShape::Path(path) => path.bounds(),
            ClipShape::Polygon(pts) => {
                if pts.is_empty() {
                    return Rect::new(0.0, 0.0, 0.0, 0.0);
                }
                let min_x = pts.iter().map(|p| p.x).fold(f32::MAX, f32::min);
                let min_y = pts.iter().map(|p| p.y).fold(f32::MAX, f32::min);
                let max_x = pts.iter().map(|p| p.x).fold(f32::MIN, f32::max);
                let max_y = pts.iter().map(|p| p.y).fold(f32::MIN, f32::max);
                Rect::new(min_x, min_y, max_x - min_x, max_y - min_y)
            }
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// CSS clip-path Types
// ─────────────────────────────────────────────────────────────────────────────

/// A length value that can be pixels or a percentage
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ClipLength {
    /// Absolute length in pixels
    Px(f32),
    /// Percentage of the reference dimension (0.0 - 100.0)
    Percent(f32),
}

impl ClipLength {
    /// Resolve this length against a reference dimension in pixels
    pub fn resolve(&self, reference: f32) -> f32 {
        match self {
            ClipLength::Px(v) => *v,
            ClipLength::Percent(pct) => reference * pct / 100.0,
        }
    }
}

impl Default for ClipLength {
    fn default() -> Self {
        ClipLength::Px(0.0)
    }
}

/// CSS `clip-path` shape function
///
/// Supports the full CSS clip-path specification:
/// - `circle()`, `ellipse()` — basic shape functions
/// - `inset()` — inset rectangle with optional rounding
/// - `rect()`, `xywh()` — CSS basic shape box functions
/// - `polygon()` — arbitrary polygon vertices
/// - `path()` — SVG path data (pre-flattened to polygon vertices)
#[derive(Clone, Debug)]
pub enum ClipPath {
    /// `circle(radius at cx cy)`
    Circle {
        radius: Option<ClipLength>,
        center: (ClipLength, ClipLength),
    },
    /// `ellipse(rx ry at cx cy)`
    Ellipse {
        rx: Option<ClipLength>,
        ry: Option<ClipLength>,
        center: (ClipLength, ClipLength),
    },
    /// `inset(top right bottom left round radius)`
    Inset {
        top: ClipLength,
        right: ClipLength,
        bottom: ClipLength,
        left: ClipLength,
        round: Option<f32>,
    },
    /// `rect(top right bottom left round radius)` — same as inset but absolute coords
    Rect {
        top: ClipLength,
        right: ClipLength,
        bottom: ClipLength,
        left: ClipLength,
        round: Option<f32>,
    },
    /// `xywh(x y w h round radius)`
    Xywh {
        x: ClipLength,
        y: ClipLength,
        w: ClipLength,
        h: ClipLength,
        round: Option<f32>,
    },
    /// `polygon(x1 y1, x2 y2, ...)`
    Polygon {
        points: Vec<(ClipLength, ClipLength)>,
    },
    /// `path("M 0 0 L ...")` — pre-flattened from SVG path commands to polygon vertices
    Path { vertices: Vec<(f32, f32)> },
}

// ─────────────────────────────────────────────────────────────────────────────
// 3D Scene Types
// ─────────────────────────────────────────────────────────────────────────────

/// Camera projection type
#[derive(Clone, Copy, Debug)]
pub enum CameraProjection {
    Perspective {
        fov_y: f32,
        aspect: f32,
        near: f32,
        far: f32,
    },
    Orthographic {
        left: f32,
        right: f32,
        bottom: f32,
        top: f32,
        near: f32,
        far: f32,
    },
}

impl Default for CameraProjection {
    fn default() -> Self {
        CameraProjection::Perspective {
            fov_y: std::f32::consts::FRAC_PI_4,
            aspect: 16.0 / 9.0,
            near: 0.1,
            far: 1000.0,
        }
    }
}

/// Camera for 3D scenes
#[derive(Clone, Debug, Default)]
pub struct Camera {
    pub position: Vec3,
    pub target: Vec3,
    pub up: Vec3,
    pub projection: CameraProjection,
}

impl Camera {
    pub fn perspective(position: Vec3, target: Vec3, fov_y: f32) -> Self {
        Self {
            position,
            target,
            up: Vec3::UP,
            projection: CameraProjection::Perspective {
                fov_y,
                aspect: 16.0 / 9.0,
                near: 0.1,
                far: 1000.0,
            },
        }
    }

    pub fn orthographic(position: Vec3, target: Vec3, scale: f32) -> Self {
        Self {
            position,
            target,
            up: Vec3::UP,
            projection: CameraProjection::Orthographic {
                left: -scale,
                right: scale,
                bottom: -scale,
                top: scale,
                near: 0.1,
                far: 1000.0,
            },
        }
    }
}

/// Light type for 3D scenes
#[derive(Clone, Debug)]
pub enum Light {
    Directional {
        direction: Vec3,
        color: Color,
        intensity: f32,
        cast_shadows: bool,
    },
    Point {
        position: Vec3,
        color: Color,
        intensity: f32,
        range: f32,
    },
    Spot {
        position: Vec3,
        direction: Vec3,
        color: Color,
        intensity: f32,
        range: f32,
        inner_angle: f32,
        outer_angle: f32,
    },
    Ambient {
        color: Color,
        intensity: f32,
    },
}

/// Environment settings for 3D scenes (skybox, IBL)
#[derive(Clone, Debug, Default)]
pub struct Environment {
    /// HDRI texture path (if any)
    pub hdri: Option<String>,
    /// Environment intensity
    pub intensity: f32,
    /// Background blur amount
    pub blur: f32,
    /// Solid background color (used if no HDRI)
    pub background_color: Option<Color>,
}

/// Parameters for 3D SDF raymarching viewport
///
/// This struct contains all the information needed to render an SDF scene
/// using GPU raymarching.
#[derive(Clone, Debug)]
pub struct Sdf3DViewport {
    /// The generated WGSL shader code containing the SDF scene definition
    pub shader_wgsl: String,
    /// Camera position in world space
    pub camera_pos: Vec3,
    /// Camera look direction (normalized)
    pub camera_dir: Vec3,
    /// Camera up vector (normalized)
    pub camera_up: Vec3,
    /// Camera right vector (normalized)
    pub camera_right: Vec3,
    /// Field of view in radians
    pub fov: f32,
    /// Animation time for time-based effects
    pub time: f32,
    /// Maximum raymarch steps
    pub max_steps: u32,
    /// Maximum ray distance
    pub max_distance: f32,
    /// Surface hit epsilon
    pub epsilon: f32,
    /// Lights in the scene
    pub lights: Vec<Light>,
}

impl Default for Sdf3DViewport {
    fn default() -> Self {
        Self {
            shader_wgsl: String::new(),
            camera_pos: Vec3::new(0.0, 2.0, 5.0),
            camera_dir: Vec3::new(0.0, 0.0, -1.0),
            camera_up: Vec3::new(0.0, 1.0, 0.0),
            camera_right: Vec3::new(1.0, 0.0, 0.0),
            fov: 0.8,
            time: 0.0,
            max_steps: 128,
            max_distance: 100.0,
            epsilon: 0.001,
            lights: Vec::new(),
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// GPU Particle System Types
// ─────────────────────────────────────────────────────────────────────────────

/// Emitter shape for GPU particle systems
#[derive(Clone, Debug, Default, PartialEq)]
pub enum ParticleEmitterShape {
    /// Single point emitter
    #[default]
    Point,
    /// Sphere volume/surface
    Sphere { radius: f32 },
    /// Upper hemisphere
    Hemisphere { radius: f32 },
    /// Cone shape
    Cone { angle: f32, radius: f32 },
    /// Box volume
    Box { half_extents: Vec3 },
    /// Circle (XZ plane)
    Circle { radius: f32 },
}

/// Force affector for GPU particles
#[derive(Clone, Debug, PartialEq)]
pub enum ParticleForce {
    /// Constant directional force (gravity)
    Gravity(Vec3),
    /// Wind with turbulence
    Wind {
        direction: Vec3,
        strength: f32,
        turbulence: f32,
    },
    /// Vortex/swirl
    Vortex {
        axis: Vec3,
        center: Vec3,
        strength: f32,
    },
    /// Velocity damping
    Drag(f32),
    /// Noise-based force
    Turbulence { strength: f32, frequency: f32 },
    /// Point attractor/repeller
    Attractor { position: Vec3, strength: f32 },
}

/// Particle render mode
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ParticleRenderMode {
    /// Camera-facing billboards
    #[default]
    Billboard,
    /// Stretched in velocity direction
    Stretched,
    /// Horizontal billboards
    Horizontal,
    /// Vertical billboards
    Vertical,
}

/// Particle blend mode
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ParticleBlendMode {
    /// Standard alpha blending
    #[default]
    Alpha,
    /// Additive blending (for glowing effects)
    Additive,
    /// Multiplicative blending
    Multiply,
}

/// GPU particle system data for rendering
///
/// This structure contains all the data needed to simulate and render
/// a particle system on the GPU. It's created from blinc_3d's ParticleSystem
/// component for submission to the GPU renderer.
#[derive(Clone, Debug)]
pub struct ParticleSystemData {
    /// Maximum number of particles
    pub max_particles: u32,
    /// Emitter shape
    pub emitter: ParticleEmitterShape,
    /// Emitter world position
    pub emitter_position: Vec3,
    /// Emission rate (particles per second)
    pub emission_rate: f32,
    /// Burst count (particles to spawn in a burst, decrements each frame)
    pub burst_count: f32,
    /// Emission direction
    pub direction: Vec3,
    /// Direction randomness (0 = straight, 1 = fully random)
    pub direction_randomness: f32,
    /// Particle lifetime range (min, max)
    pub lifetime: (f32, f32),
    /// Start speed range (min, max)
    pub start_speed: (f32, f32),
    /// Start size range (min, max)
    pub start_size: (f32, f32),
    /// End size range (min, max)
    pub end_size: (f32, f32),
    /// Start color (base - young particles)
    pub start_color: Color,
    /// Mid color (middle - mid-life particles)
    pub mid_color: Color,
    /// End color (tip - old/dying particles)
    pub end_color: Color,
    /// Force affectors
    pub forces: Vec<ParticleForce>,
    /// Gravity scale
    pub gravity_scale: f32,
    /// Render mode
    pub render_mode: ParticleRenderMode,
    /// Blend mode
    pub blend_mode: ParticleBlendMode,
    /// Current time for simulation
    pub time: f32,
    /// Delta time for this frame
    pub delta_time: f32,
    /// Camera position (for billboarding)
    pub camera_pos: Vec3,
    /// Camera direction (for billboarding)
    pub camera_dir: Vec3,
    /// Camera up vector
    pub camera_up: Vec3,
    /// Camera right vector
    pub camera_right: Vec3,
    /// Whether system is playing
    pub playing: bool,
}

impl Default for ParticleSystemData {
    fn default() -> Self {
        Self {
            max_particles: 10000,
            emitter: ParticleEmitterShape::Point,
            emitter_position: Vec3::ZERO,
            emission_rate: 100.0,
            burst_count: 0.0,
            direction: Vec3::new(0.0, 1.0, 0.0),
            direction_randomness: 0.0,
            lifetime: (1.0, 2.0),
            start_speed: (1.0, 2.0),
            start_size: (0.1, 0.2),
            end_size: (0.0, 0.1),
            start_color: Color::WHITE,
            mid_color: Color::rgba(1.0, 1.0, 1.0, 0.5),
            end_color: Color::rgba(1.0, 1.0, 1.0, 0.0),
            forces: Vec::new(),
            gravity_scale: 1.0,
            render_mode: ParticleRenderMode::Billboard,
            blend_mode: ParticleBlendMode::Alpha,
            time: 0.0,
            delta_time: 0.016,
            camera_pos: Vec3::new(0.0, 2.0, 5.0),
            camera_dir: Vec3::new(0.0, 0.0, -1.0),
            camera_up: Vec3::new(0.0, 1.0, 0.0),
            camera_right: Vec3::new(1.0, 0.0, 0.0),
            playing: true,
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Layer Command Types (for Canvas2D and Scene3D)
// ─────────────────────────────────────────────────────────────────────────────

/// Commands for 2D canvas drawing
/// These are recorded and then executed by the Canvas2D renderer
#[derive(Clone, Debug, Default)]
pub struct Canvas2DCommands {
    commands: Vec<Canvas2DCommand>,
}

/// Individual canvas drawing command
#[derive(Clone, Debug)]
pub enum Canvas2DCommand {
    /// Clear the canvas with a color
    Clear(Color),

    /// Save the current state (transform, clip, opacity)
    Save,

    /// Restore the previously saved state
    Restore,

    /// Push a 2D transform
    Transform(Affine2D),

    /// Set the global opacity
    SetOpacity(f32),

    /// Set the blend mode
    SetBlendMode(BlendMode),

    /// Push a clipping shape
    PushClip(ClipShape),

    /// Pop the last clipping shape
    PopClip,

    /// Fill a path with a brush
    FillPath {
        path: crate::draw::Path,
        brush: Brush,
    },

    /// Stroke a path
    StrokePath {
        path: crate::draw::Path,
        stroke: crate::draw::Stroke,
        brush: Brush,
    },

    /// Fill a rectangle (optimized primitive)
    FillRect {
        rect: Rect,
        corner_radius: CornerRadius,
        brush: Brush,
    },

    /// Stroke a rectangle (optimized primitive)
    StrokeRect {
        rect: Rect,
        corner_radius: CornerRadius,
        stroke: crate::draw::Stroke,
        brush: Brush,
    },

    /// Fill a circle (optimized primitive)
    FillCircle {
        center: Point,
        radius: f32,
        brush: Brush,
    },

    /// Stroke a circle (optimized primitive)
    StrokeCircle {
        center: Point,
        radius: f32,
        stroke: crate::draw::Stroke,
        brush: Brush,
    },

    /// Draw text
    DrawText {
        text: String,
        origin: Point,
        style: crate::draw::TextStyle,
    },

    /// Draw an image
    DrawImage {
        image: crate::draw::ImageId,
        rect: Rect,
        options: crate::draw::ImageOptions,
    },

    /// Draw a shadow
    DrawShadow {
        rect: Rect,
        corner_radius: CornerRadius,
        shadow: Shadow,
    },
}

impl Canvas2DCommands {
    pub fn new() -> Self {
        Self {
            commands: Vec::new(),
        }
    }

    pub fn push(&mut self, command: Canvas2DCommand) {
        self.commands.push(command);
    }

    pub fn commands(&self) -> &[Canvas2DCommand] {
        &self.commands
    }

    pub fn clear(&mut self) {
        self.commands.clear();
    }

    pub fn len(&self) -> usize {
        self.commands.len()
    }

    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }
}

/// Commands for 3D scene
#[derive(Clone, Debug, Default)]
pub struct Scene3DCommands {
    commands: Vec<Scene3DCommand>,
}

/// Individual 3D scene command
#[derive(Clone, Debug)]
pub enum Scene3DCommand {
    /// Clear the scene with a color
    Clear(Color),

    /// Set the active camera
    SetCamera(Camera),

    /// Push a 3D transform matrix
    PushTransform(Mat4),

    /// Pop the last transform
    PopTransform,

    /// Draw a mesh with a material
    DrawMesh {
        mesh: crate::draw::MeshId,
        material: crate::draw::MaterialId,
        transform: Mat4,
    },

    /// Draw multiple instances of a mesh
    DrawMeshInstanced {
        mesh: crate::draw::MeshId,
        instances: Vec<crate::draw::MeshInstance>,
    },

    /// Add a light to the scene
    AddLight(Light),

    /// Set the environment (skybox, ambient, etc.)
    SetEnvironment(Environment),

    /// Draw a billboard (2D content in 3D space)
    DrawBillboard {
        /// Size of the billboard in world units
        size: Size,
        /// Transform in world space
        transform: Mat4,
        /// How the billboard faces the camera
        facing: BillboardFacing,
        /// The 2D content to render
        content: Canvas2DCommands,
    },
}

impl Scene3DCommands {
    pub fn new() -> Self {
        Self {
            commands: Vec::new(),
        }
    }

    pub fn push(&mut self, command: Scene3DCommand) {
        self.commands.push(command);
    }

    pub fn commands(&self) -> &[Scene3DCommand] {
        &self.commands
    }

    pub fn clear(&mut self) {
        self.commands.clear();
    }

    pub fn len(&self) -> usize {
        self.commands.len()
    }

    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// UI Node (placeholder for full UI system)
// ─────────────────────────────────────────────────────────────────────────────

/// Reference to a UI node in the layout tree
#[derive(Clone, Copy, Debug)]
pub struct UiNode {
    /// Node identifier
    pub id: u64,
}

impl UiNode {
    pub fn new(id: u64) -> Self {
        Self { id }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Layer Enum - The Core Abstraction
// ─────────────────────────────────────────────────────────────────────────────

/// All visual content is represented as a `Layer`.
///
/// Layers can be 2D UI primitives, 2D canvas drawings, 3D scenes, or
/// composition/transformation of other layers.
#[derive(Clone, Debug)]
pub enum Layer {
    // ─────────────────────────────────────────────────────────────────────────
    // 2D Primitives (SDF Rendered)
    // ─────────────────────────────────────────────────────────────────────────
    /// UI node tree (SDF rendered)
    Ui {
        node: UiNode,
        props: LayerProperties,
    },

    // ─────────────────────────────────────────────────────────────────────────
    // 2D Vector Drawing
    // ─────────────────────────────────────────────────────────────────────────
    /// 2D canvas with vector drawing commands
    Canvas2D {
        size: Size,
        commands: Canvas2DCommands,
        cache_policy: CachePolicy,
        props: LayerProperties,
    },

    // ─────────────────────────────────────────────────────────────────────────
    // 3D Scene
    // ─────────────────────────────────────────────────────────────────────────
    /// 3D scene with meshes, materials, and lighting
    Scene3D {
        viewport: Rect,
        commands: Scene3DCommands,
        camera: Camera,
        environment: Option<Environment>,
        props: LayerProperties,
    },

    // ─────────────────────────────────────────────────────────────────────────
    // Composition
    // ─────────────────────────────────────────────────────────────────────────
    /// Stack of layers composited together
    Stack {
        layers: Vec<Layer>,
        blend_mode: BlendMode,
        props: LayerProperties,
    },

    /// 2D transform applied to a layer
    Transform2D {
        transform: Affine2D,
        layer: Box<Layer>,
        props: LayerProperties,
    },

    /// 3D transform applied to a layer
    Transform3D {
        transform: Mat4,
        layer: Box<Layer>,
        props: LayerProperties,
    },

    /// Clip mask applied to a layer
    Clip {
        shape: ClipShape,
        layer: Box<Layer>,
        props: LayerProperties,
    },

    /// Opacity applied to a layer
    Opacity {
        value: f32,
        layer: Box<Layer>,
        props: LayerProperties,
    },

    // ─────────────────────────────────────────────────────────────────────────
    // Render Target Indirection
    // ─────────────────────────────────────────────────────────────────────────
    /// Layer rendered to an offscreen texture with optional effects
    Offscreen {
        size: Size,
        format: TextureFormat,
        layer: Box<Layer>,
        effects: Vec<PostEffect>,
        props: LayerProperties,
    },

    // ─────────────────────────────────────────────────────────────────────────
    // Dimension Bridging
    // ─────────────────────────────────────────────────────────────────────────
    /// 2D layer placed in 3D space
    Billboard {
        layer: Box<Layer>,
        transform: Mat4,
        facing: BillboardFacing,
        props: LayerProperties,
    },

    /// 3D scene embedded in 2D layout
    Viewport3D {
        rect: Rect,
        scene: Box<Layer>, // Must be Scene3D
        props: LayerProperties,
    },

    /// Reference to another layer's render output
    Portal {
        source: LayerId,
        sample_rect: Rect,
        dest_rect: Rect,
        props: LayerProperties,
    },

    /// Empty layer (useful as placeholder)
    Empty { props: LayerProperties },
}

impl Layer {
    /// Get the layer properties
    pub fn props(&self) -> &LayerProperties {
        match self {
            Layer::Ui { props, .. } => props,
            Layer::Canvas2D { props, .. } => props,
            Layer::Scene3D { props, .. } => props,
            Layer::Stack { props, .. } => props,
            Layer::Transform2D { props, .. } => props,
            Layer::Transform3D { props, .. } => props,
            Layer::Clip { props, .. } => props,
            Layer::Opacity { props, .. } => props,
            Layer::Offscreen { props, .. } => props,
            Layer::Billboard { props, .. } => props,
            Layer::Viewport3D { props, .. } => props,
            Layer::Portal { props, .. } => props,
            Layer::Empty { props } => props,
        }
    }

    /// Get mutable layer properties
    pub fn props_mut(&mut self) -> &mut LayerProperties {
        match self {
            Layer::Ui { props, .. } => props,
            Layer::Canvas2D { props, .. } => props,
            Layer::Scene3D { props, .. } => props,
            Layer::Stack { props, .. } => props,
            Layer::Transform2D { props, .. } => props,
            Layer::Transform3D { props, .. } => props,
            Layer::Clip { props, .. } => props,
            Layer::Opacity { props, .. } => props,
            Layer::Offscreen { props, .. } => props,
            Layer::Billboard { props, .. } => props,
            Layer::Viewport3D { props, .. } => props,
            Layer::Portal { props, .. } => props,
            Layer::Empty { props } => props,
        }
    }

    /// Get the layer ID if set
    pub fn id(&self) -> Option<LayerId> {
        self.props().id
    }

    /// Check if the layer is visible
    pub fn is_visible(&self) -> bool {
        self.props().visible
    }

    /// Create an empty layer
    pub fn empty() -> Self {
        Layer::Empty {
            props: LayerProperties::new(),
        }
    }

    /// Create a stack of layers
    pub fn stack(layers: Vec<Layer>) -> Self {
        Layer::Stack {
            layers,
            blend_mode: BlendMode::Normal,
            props: LayerProperties::new(),
        }
    }

    /// Wrap this layer with a 2D transform
    pub fn with_transform_2d(self, transform: Affine2D) -> Self {
        Layer::Transform2D {
            transform,
            layer: Box::new(self),
            props: LayerProperties::new(),
        }
    }

    /// Wrap this layer with a 3D transform
    pub fn with_transform_3d(self, transform: Mat4) -> Self {
        Layer::Transform3D {
            transform,
            layer: Box::new(self),
            props: LayerProperties::new(),
        }
    }

    /// Wrap this layer with a clip shape
    pub fn with_clip(self, shape: ClipShape) -> Self {
        Layer::Clip {
            shape,
            layer: Box::new(self),
            props: LayerProperties::new(),
        }
    }

    /// Wrap this layer with opacity
    pub fn with_opacity(self, value: f32) -> Self {
        Layer::Opacity {
            value,
            layer: Box::new(self),
            props: LayerProperties::new(),
        }
    }

    /// Check if this is a 3D layer
    pub fn is_3d(&self) -> bool {
        matches!(
            self,
            Layer::Scene3D { .. } | Layer::Billboard { .. } | Layer::Transform3D { .. }
        )
    }

    /// Check if this is a 2D layer
    pub fn is_2d(&self) -> bool {
        matches!(
            self,
            Layer::Ui { .. }
                | Layer::Canvas2D { .. }
                | Layer::Transform2D { .. }
                | Layer::Viewport3D { .. }
        )
    }

    /// Visit all child layers
    pub fn visit_children<F: FnMut(&Layer)>(&self, mut f: F) {
        match self {
            Layer::Stack { layers, .. } => {
                for layer in layers {
                    f(layer);
                }
            }
            Layer::Transform2D { layer, .. }
            | Layer::Transform3D { layer, .. }
            | Layer::Clip { layer, .. }
            | Layer::Opacity { layer, .. }
            | Layer::Offscreen { layer, .. }
            | Layer::Billboard { layer, .. }
            | Layer::Viewport3D { scene: layer, .. } => {
                f(layer);
            }
            _ => {}
        }
    }

    /// Visit all child layers mutably
    pub fn visit_children_mut<F: FnMut(&mut Layer)>(&mut self, mut f: F) {
        match self {
            Layer::Stack { layers, .. } => {
                for layer in layers {
                    f(layer);
                }
            }
            Layer::Transform2D { layer, .. }
            | Layer::Transform3D { layer, .. }
            | Layer::Clip { layer, .. }
            | Layer::Opacity { layer, .. }
            | Layer::Offscreen { layer, .. }
            | Layer::Billboard { layer, .. }
            | Layer::Viewport3D { scene: layer, .. } => {
                f(layer);
            }
            _ => {}
        }
    }
}

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

/// Scene graph containing the root layer and layer index
#[derive(Debug, Default)]
pub struct SceneGraph {
    /// Root layer of the scene
    pub root: Option<Layer>,

    /// Index for fast layer lookup by ID
    layer_index: HashMap<LayerId, usize>,

    /// ID generator
    id_generator: LayerIdGenerator,
}

impl SceneGraph {
    pub fn new() -> Self {
        Self {
            root: None,
            layer_index: HashMap::new(),
            id_generator: LayerIdGenerator::new(),
        }
    }

    /// Set the root layer
    pub fn set_root(&mut self, layer: Layer) {
        self.root = Some(layer);
        self.rebuild_index();
    }

    /// Generate a new unique layer ID
    pub fn new_layer_id(&mut self) -> LayerId {
        self.id_generator.next_id()
    }

    /// Find a layer by ID (traverses the tree)
    pub fn find_layer(&self, id: LayerId) -> Option<&Layer> {
        fn find_in_layer(layer: &Layer, target_id: LayerId) -> Option<&Layer> {
            if layer.id() == Some(target_id) {
                return Some(layer);
            }

            match layer {
                Layer::Stack { layers, .. } => {
                    for child in layers {
                        if let Some(found) = find_in_layer(child, target_id) {
                            return Some(found);
                        }
                    }
                }
                Layer::Transform2D { layer: child, .. }
                | Layer::Transform3D { layer: child, .. }
                | Layer::Clip { layer: child, .. }
                | Layer::Opacity { layer: child, .. }
                | Layer::Offscreen { layer: child, .. }
                | Layer::Billboard { layer: child, .. }
                | Layer::Viewport3D { scene: child, .. } => {
                    if let Some(found) = find_in_layer(child, target_id) {
                        return Some(found);
                    }
                }
                _ => {}
            }

            None
        }

        self.root.as_ref().and_then(|root| find_in_layer(root, id))
    }

    /// Rebuild the layer index
    fn rebuild_index(&mut self) {
        self.layer_index.clear();
        // Future: implement full index rebuilding
    }

    /// Traverse all layers in depth-first order
    pub fn traverse<F: FnMut(&Layer, usize)>(&self, mut f: F) {
        fn traverse_layer<F: FnMut(&Layer, usize)>(layer: &Layer, depth: usize, f: &mut F) {
            f(layer, depth);
            layer.visit_children(|child| traverse_layer(child, depth + 1, f));
        }

        if let Some(root) = &self.root {
            traverse_layer(root, 0, &mut f);
        }
    }

    /// Count total number of layers
    pub fn layer_count(&self) -> usize {
        let mut count = 0;
        self.traverse(|_, _| count += 1);
        count
    }

    /// Check if the scene contains any 3D layers
    pub fn has_3d(&self) -> bool {
        let mut has_3d = false;
        self.traverse(|layer, _| {
            if layer.is_3d() {
                has_3d = true;
            }
        });
        has_3d
    }

    /// Count all visible layers
    pub fn visible_layer_count(&self) -> usize {
        let mut count = 0;
        self.traverse(|layer, _| {
            if layer.is_visible() {
                count += 1;
            }
        });
        count
    }
}

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

    #[test]
    fn test_layer_creation() {
        let layer = Layer::empty();
        assert!(layer.is_visible());
        assert!(layer.id().is_none());
    }

    #[test]
    fn test_layer_stack() {
        let stack = Layer::stack(vec![Layer::empty(), Layer::empty(), Layer::empty()]);

        let mut count = 0;
        stack.visit_children(|_| count += 1);
        assert_eq!(count, 3);
    }

    #[test]
    fn test_layer_transforms() {
        let layer = Layer::empty()
            .with_transform_2d(Affine2D::translation(10.0, 20.0))
            .with_opacity(0.5);

        assert!(matches!(layer, Layer::Opacity { .. }));
    }

    #[test]
    fn test_scene_graph() {
        let mut scene = SceneGraph::new();

        let id1 = scene.new_layer_id();
        let id2 = scene.new_layer_id();

        assert_ne!(id1, id2);

        scene.set_root(Layer::stack(vec![
            Layer::Empty {
                props: LayerProperties::new().with_id(id1),
            },
            Layer::Empty {
                props: LayerProperties::new().with_id(id2),
            },
        ]));

        assert_eq!(scene.layer_count(), 3); // stack + 2 empty

        let found = scene.find_layer(id1);
        assert!(found.is_some());
    }

    #[test]
    fn test_geometry_types() {
        let p = Point::new(1.0, 2.0);
        let s = Size::new(100.0, 50.0);
        let r = Rect::from_origin_size(p, s);

        assert_eq!(r.center(), Point::new(51.0, 27.0));
        assert!(r.contains(Point::new(50.0, 25.0)));
        assert!(!r.contains(Point::new(200.0, 100.0)));

        // Test Size to Rect conversion
        let size = Size::new(200.0, 100.0);
        let rect: Rect = size.into();
        assert_eq!(rect.x(), 0.0);
        assert_eq!(rect.y(), 0.0);
        assert_eq!(rect.width(), 200.0);
        assert_eq!(rect.height(), 100.0);

        // Test to_rect() method
        let rect2 = size.to_rect();
        assert_eq!(rect, rect2);

        // Test offset and inset
        let offset_rect = rect.offset(10.0, 20.0);
        assert_eq!(offset_rect.x(), 10.0);
        assert_eq!(offset_rect.y(), 20.0);

        let inset_rect = rect.inset(5.0, 10.0);
        assert_eq!(inset_rect.x(), 5.0);
        assert_eq!(inset_rect.y(), 10.0);
        assert_eq!(inset_rect.width(), 190.0);
        assert_eq!(inset_rect.height(), 80.0);
    }

    #[test]
    fn test_color() {
        let c = Color::from_hex(0xFF5500);
        assert_eq!(c.r, 1.0);
        assert!((c.g - 85.0 / 255.0).abs() < 0.001);
        assert_eq!(c.b, 0.0);

        let c2 = c.with_alpha(0.5);
        assert_eq!(c2.a, 0.5);
    }

    #[test]
    fn test_mat4_operations() {
        let t = Mat4::translation(1.0, 2.0, 3.0);
        let s = Mat4::scale(2.0, 2.0, 2.0);
        let result = t.mul(&s);

        // Verify it's a valid combined transform
        assert_eq!(result.cols[3][0], 1.0); // translation preserved
    }
}