euv-core 0.53.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
use super::*;

/// Queries browser dark-mode preference using `window.matchMedia("(prefers-color-scheme: dark)")`.
///
/// # Returns
///
/// - `ThemeMode` - Detected browser appearance mode.
#[must_use]
pub fn web_system_theme() -> ThemeMode {
    let Some(win) = window() else {
        return ThemeMode::Light;
    };
    let matches_dark: bool = win
        .match_media(WEB_DARK_MEDIA_QUERY)
        .ok()
        .flatten()
        .map(|mql: MediaQueryList| mql.matches())
        .unwrap_or(false);
    if matches_dark {
        ThemeMode::Dark
    } else {
        ThemeMode::Light
    }
}

/// Queries the browser's `window.devicePixelRatio`, clamped to `[WEB_DPR_MIN, WEB_DPR_MAX]` so mobile/web canvases never downscale below 1x physical pixels.
///
/// # Returns
///
/// - `f32` - Device pixel ratio clamped to `[WEB_DPR_MIN, WEB_DPR_MAX]`.
#[must_use]
pub fn web_device_pixel_ratio() -> f32 {
    window()
        .map(|width_val: Window| {
            let raw: f64 = width_val.device_pixel_ratio();
            if raw.is_finite() && raw > 0.0 {
                (raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
            } else {
                1.0
            }
        })
        .unwrap_or(1.0)
}

/// Opens an external HTTP(S) URL in a new browser tab with `noopener,noreferrer`.
///
/// # Arguments
///
/// - `&str` - Validated `http://` or `https://` URL string.
///
/// # Returns
///
/// - `bool` - `true` when `window.open` succeeded without error.
#[must_use]
pub(crate) fn web_open_external_url(url: &str) -> bool {
    let Some(win) = window() else {
        return false;
    };
    win.open_with_url_and_target_and_features(url, WEB_OPEN_TARGET_BLANK, WEB_OPEN_FEATURES_SAFE)
        .is_ok()
}

/// Mounts or navigates the embedded WebView sheet `<iframe>` inside `document.body` on WebAssembly.
///
/// # Arguments
///
/// - `&str` - Validated `http://` or `https://` URL string.
/// - `&str` - Accessible sheet title for the `<iframe>`.
///
/// # Returns
///
/// - `bool` - `true` when the embedded `<iframe>` was created or updated.
pub(crate) fn web_webview_open(url: &str, title: &str) -> bool {
    let Some(doc) = window().and_then(|win: Window| win.document()) else {
        return false;
    };
    let iframe_el: Element = if let Some(existing) = doc.get_element_by_id(WEB_WEBVIEW_IFRAME_ID) {
        existing
    } else {
        let Ok(created) = doc.create_element(WEB_TAG_IFRAME) else {
            return false;
        };
        drop(created.set_attribute(WEB_ATTR_ID, WEB_WEBVIEW_IFRAME_ID));
        drop(created.set_attribute(WEB_ATTR_REFERRER_POLICY, WEB_REFERRER_POLICY_STRICT));
        drop(created.set_attribute(WEB_ATTR_STYLE, WEB_WEBVIEW_HIDDEN_STYLE));
        let Some(body_el) = doc.body() else {
            return false;
        };
        if body_el.append_child(&created).is_err() {
            return false;
        }
        created
    };
    drop(iframe_el.set_attribute(WEB_ATTR_TITLE, title));
    iframe_el.set_attribute(WEB_ATTR_SRC, url).is_ok()
}

/// Synchronizes the CSS pixel geometry and opacity of the embedded WebView `<iframe>` on WebAssembly.
///
/// # Arguments
///
/// - `f32` - Left coordinate in logical CSS pixels.
/// - `f32` - Top coordinate in logical CSS pixels.
/// - `f32` - Width in logical CSS pixels.
/// - `f32` - Height in logical CSS pixels.
/// - `f32` - Effective opacity in `0.0..=1.0`.
///
/// # Returns
///
/// - `bool` - `true` when the embedded `<iframe>` style updated.
pub(crate) fn web_webview_frame(
    left_px: f32,
    top_px: f32,
    width_px: f32,
    height_px: f32,
    alpha_val: f32,
) -> bool {
    let Some(doc) = window().and_then(|win: Window| win.document()) else {
        return false;
    };
    let Some(iframe_el) = doc.get_element_by_id(WEB_WEBVIEW_IFRAME_ID) else {
        return false;
    };
    let is_empty_rect: bool = width_px < 1.0 || height_px < 1.0;
    if is_empty_rect || alpha_val <= 0.005 {
        return iframe_el
            .set_attribute(WEB_ATTR_STYLE, WEB_WEBVIEW_HIDDEN_STYLE)
            .is_ok();
    }
    let pointer_css: &str = if alpha_val >= 0.98 { "auto" } else { "none" };
    let inline_css: String = format!(
        "position:fixed;left:{left_px:.2}px;top:{top_px:.2}px;width:{width_px:.2}px;height:{height_px:.2}px;border:0;z-index:20;background:#ffffff;display:block;pointer-events:{pointer_css};opacity:{alpha_val:.3};"
    );
    iframe_el.set_attribute(WEB_ATTR_STYLE, &inline_css).is_ok()
}

/// Reloads the active embedded WebView `<iframe>` on WebAssembly by re-assigning its `src` URL.
///
/// # Arguments
///
/// - `&str` - Active URL to reload.
///
/// # Returns
///
/// - `bool` - `true` when the embedded `<iframe>` existed and reloaded.
pub(crate) fn web_webview_reload(url: &str) -> bool {
    let Some(doc) = window().and_then(|win: Window| win.document()) else {
        return false;
    };
    let Some(iframe_el) = doc.get_element_by_id(WEB_WEBVIEW_IFRAME_ID) else {
        return false;
    };
    iframe_el.set_attribute(WEB_ATTR_SRC, url).is_ok()
}

/// Removes the active embedded WebView `<iframe>` overlay from the browser DOM on WebAssembly.
///
/// # Returns
///
/// - `bool` - `true` when an active embedded `<iframe>` was found and removed.
pub(crate) fn web_webview_close() -> bool {
    let Some(doc) = window().and_then(|win: Window| win.document()) else {
        return false;
    };
    let Some(iframe_el) = doc.get_element_by_id(WEB_WEBVIEW_IFRAME_ID) else {
        return false;
    };
    iframe_el.remove();
    true
}

/// Queries the browser's live CSS viewport `(width, height)` preferring `visualViewport` (when not pinch-zoomed) and `documentElement.clientWidth/Height` before `innerWidth/Height`.
///
/// # Arguments
///
/// - `&Window` - Active browser window.
/// - `&Document` - Active browser document.
/// - `f64` - Fallback logical width.
/// - `f64` - Fallback logical height.
///
/// # Returns
///
/// - `(f64, f64)` - Live CSS viewport `(width, height)` in CSS pixels.
#[must_use]
pub(crate) fn web_query_viewport_css_size(
    win: &Window,
    doc: &Document,
    fallback_w: f64,
    fallback_h: f64,
) -> (f64, f64) {
    if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
        && !vv.is_null()
        && !vv.is_undefined()
    {
        let vv_scale: f64 = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_SCALE))
            .ok()
            .and_then(|item_val: JsValue| item_val.as_f64())
            .filter(|tex_v: &f64| tex_v.is_finite() && *tex_v > 0.0)
            .unwrap_or(1.0);
        if vv_scale <= WEB_PINCH_ZOOM_THRESHOLD {
            let vw: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_WIDTH))
                .ok()
                .and_then(|bary_v: JsValue| bary_v.as_f64())
                .filter(|sample_val: &f64| sample_val.is_finite() && *sample_val >= 64.0);
            let vh: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_HEIGHT))
                .ok()
                .and_then(|item_val_primary: JsValue| item_val_primary.as_f64())
                .filter(|item_val_secondary: &f64| {
                    item_val_secondary.is_finite() && *item_val_secondary >= 64.0
                });
            if let (Some(width_val), Some(height_val)) = (vw, vh) {
                return (width_val, height_val);
            }
        }
    }
    if let Some(root) = doc.document_element() {
        let cw: f64 = f64::from(root.client_width());
        let ch: f64 = f64::from(root.client_height());
        if cw >= 64.0 && ch >= 64.0 {
            return (cw, ch);
        }
    }
    let span_width: f64 = win
        .inner_width()
        .ok()
        .and_then(|item_val_next: JsValue| item_val_next.as_f64())
        .filter(|item_val_alt: &f64| item_val_alt.is_finite() && *item_val_alt >= 64.0)
        .unwrap_or(fallback_w.max(64.0));
    let span_height: f64 = win
        .inner_height()
        .ok()
        .and_then(|item_val_inner: JsValue| item_val_inner.as_f64())
        .filter(|item_val_local: &f64| item_val_local.is_finite() && *item_val_local >= 64.0)
        .unwrap_or(fallback_h.max(64.0));
    (span_width, span_height)
}

/// Attempts a synchronous clipboard write using a temporary offscreen `<textarea>` and `document.execCommand("copy")`, restoring prior element focus afterward.
///
/// # Arguments
///
/// - `&Document` - Active browser document.
/// - `&str` - UTF-8 text string to copy.
///
/// # Returns
///
/// - `bool` - `true` when `document.execCommand("copy")` reported success.
fn web_write_clipboard_exec_command(doc: &Document, text: &str) -> bool {
    let Some(body) = doc.body() else {
        return false;
    };
    let prev_active: Option<HtmlElement> = doc
        .active_element()
        .and_then(|el: Element| el.dyn_into::<HtmlElement>().ok());
    let Ok(ta_el) = doc.create_element(WEB_TAG_TEXTAREA) else {
        return false;
    };
    drop(ta_el.set_attribute(WEB_ATTR_READONLY, ""));
    drop(ta_el.set_attribute(WEB_ATTR_COPY_PROXY, WEB_COPY_PROXY_FLAG));
    drop(ta_el.set_attribute(WEB_ATTR_STYLE, WEB_COPY_PROXY_STYLE));
    let _: Result<bool, JsValue> = Reflect::set(
        ta_el.as_ref(),
        &JsValue::from_str(WEB_PROP_VALUE),
        &JsValue::from_str(text),
    );
    if body.append_child(&ta_el).is_err() {
        return false;
    }
    if let Ok(ta_html) = ta_el.clone().dyn_into::<HtmlElement>() {
        drop(ta_html.focus());
    }
    if let Ok(sel_val) = Reflect::get(ta_el.as_ref(), &JsValue::from_str(WEB_METHOD_SELECT))
        && let Ok(sel_fn) = sel_val.dyn_into::<Function>()
    {
        drop(sel_fn.call0(ta_el.as_ref()));
    }
    if let Ok(rng_val) = Reflect::get(
        ta_el.as_ref(),
        &JsValue::from_str(WEB_METHOD_SET_SELECTION_RANGE),
    ) && let Ok(rng_fn) = rng_val.dyn_into::<Function>()
    {
        let utf16_len: f64 = text.encode_utf16().count() as f64;
        drop(rng_fn.call2(
            ta_el.as_ref(),
            &JsValue::from_f64(0.0),
            &JsValue::from_f64(utf16_len),
        ));
    }
    let copied: bool = Reflect::get(doc.as_ref(), &JsValue::from_str(WEB_METHOD_EXEC_COMMAND))
        .ok()
        .and_then(|item_val: JsValue| item_val.dyn_into::<Function>().ok())
        .and_then(|factor_val: Function| {
            factor_val
                .call1(doc.as_ref(), &JsValue::from_str(WEB_CMD_COPY))
                .ok()
        })
        .and_then(|res: JsValue| res.as_bool())
        .unwrap_or(false);
    drop(body.remove_child(&ta_el));
    if let Some(prev) = prev_active {
        drop(prev.focus());
    }
    copied
}

/// Writes `text` to the browser clipboard using both synchronous offscreen `<textarea>` `execCommand("copy")` and async `navigator.clipboard.writeText` so copy works reliably across HTTPS, HTTP, Safari, Firefox, and Chrome.
///
/// # Arguments
///
/// - `&str` - UTF-8 text string to copy.
///
/// # Returns
///
/// - `bool` - `true` when either synchronous or async clipboard copy succeeded/dispatched.
pub(crate) fn web_write_clipboard(text: &str) -> bool {
    let Some(win) = window() else {
        return false;
    };
    let exec_ok: bool = win
        .document()
        .map(|doc: Document| web_write_clipboard_exec_command(&doc, text))
        .unwrap_or(false);
    let nav: Navigator = win.navigator();
    let mut async_ok: bool = false;
    if let Ok(clip) = Reflect::get(nav.as_ref(), &JsValue::from_str(WEB_PROP_CLIPBOARD))
        && !clip.is_null()
        && !clip.is_undefined()
        && let Ok(write_val) = Reflect::get(&clip, &JsValue::from_str(WEB_METHOD_WRITE_TEXT))
        && let Ok(write_fn) = write_val.dyn_into::<Function>()
        && let Ok(promise_val) = write_fn.call1(&clip, &JsValue::from_str(text))
    {
        async_ok = true;
        if let Ok(catch_val) = Reflect::get(&promise_val, &JsValue::from_str(WEB_METHOD_CATCH))
            && let Ok(catch_fn) = catch_val.dyn_into::<Function>()
        {
            let noop: Function = Function::new_no_args(WEB_JS_NOOP_BODY);
            drop(catch_fn.call1(&promise_val, &noop));
        }
    }
    exec_ok || async_ok
}

/// Queries whether the active browser tab is currently hidden (`document.hidden`).
///
/// # Returns
///
/// - `bool` - `true` when the page is in a background tab or minimized.
#[must_use]
pub(crate) fn web_document_hidden() -> bool {
    window()
        .and_then(|width_val: Window| width_val.document())
        .map(|delta_val: Document| delta_val.hidden())
        .unwrap_or(false)
}

/// Queries live browser online connectivity via `navigator.onLine`.
///
/// # Returns
///
/// - `bool` - `true` when the browser reports network availability.
#[must_use]
pub(crate) fn web_navigator_online() -> bool {
    window()
        .map(|width_val: Window| width_val.navigator().on_line())
        .unwrap_or(true)
}

/// Queries the browser's primary BCP-47 locale tag via `navigator.language`.
///
/// # Returns
///
/// - `String` - Locale identifier (fallback `"en-US"`).
#[must_use]
pub(crate) fn web_navigator_locale() -> String {
    window()
        .and_then(|width_val: Window| width_val.navigator().language())
        .filter(|text_value: &String| !text_value.trim().is_empty())
        .unwrap_or_else(|| DEFAULT_SYSTEM_LOCALE.to_string())
}

/// Parses a single CSS property value (e.g. `"0px"`, `"44px"`) from a `CSSStyleDeclaration` via `parse_css_safe_area_px`.
///
/// # Arguments
///
/// - `&JsValue` - `CSSStyleDeclaration` returned by `window.getComputedStyle(...)`.
/// - `&Function` - Bound `getPropertyValue` method.
/// - `&str` - CSS property name (`padding-*` or `--euv-safe-*`).
///
/// # Returns
///
/// - `f32` - Sanitized non-negative inset in logical CSS pixels (`0.0` when unset or zero).
#[must_use]
fn web_read_css_px_prop(style_decl: &JsValue, get_prop_fn: &Function, prop_name: &str) -> f32 {
    let Ok(raw_val) = get_prop_fn.call1(style_decl, &JsValue::from_str(prop_name)) else {
        return 0.0;
    };
    let Some(text) = raw_val.as_string() else {
        return 0.0;
    };
    parse_css_safe_area_px(&text)
}

/// Ensures a reusable zero-size hidden DOM probe element mapping `env(safe-area-inset-*)` onto real `padding-*` CSS lengths exists.
///
/// # Arguments
///
/// - `&Document` - Active browser `Document`.
///
/// # Returns
///
/// - `Option<Element>` - Mounted hidden safe-area probe element.
fn web_ensure_safe_area_probe(doc: &Document) -> Option<Element> {
    if let Some(existing) = doc.get_element_by_id(WEB_SAFE_PROBE_ID) {
        return Some(existing);
    }
    let probe: Element = doc.create_element(WEB_TAG_DIV).ok()?;
    drop(probe.set_attribute(WEB_ATTR_ID, WEB_SAFE_PROBE_ID));
    drop(probe.set_attribute(WEB_ATTR_STYLE, WEB_SAFE_PROBE_STYLE));
    let parent: Element = doc
        .body()
        .map(|blue_val: HtmlElement| blue_val.into())
        .or_else(|| doc.document_element())?;
    drop(parent.append_child(probe.as_ref()));
    Some(probe)
}

/// Reads real browser CSS `env(safe-area-inset-*)` values via computed `padding-*` on a hidden probe, returning `0.0` whenever the browser reports no safe area.
///
/// # Returns
///
/// - `SafeAreaInsets` - Exact browser-reported safe-area insets (`0.0` on every edge without a real safe area).
#[must_use]
pub fn web_query_safe_area_insets() -> SafeAreaInsets {
    let Some(win) = window() else {
        return SafeAreaInsets::default();
    };
    let Some(doc): Option<Document> = win.document() else {
        return SafeAreaInsets::default();
    };
    let Ok(get_style_val) = Reflect::get(
        win.as_ref(),
        &JsValue::from_str(WEB_METHOD_GET_COMPUTED_STYLE),
    ) else {
        return SafeAreaInsets::default();
    };
    let Ok(get_style_fn) = get_style_val.dyn_into::<Function>() else {
        return SafeAreaInsets::default();
    };
    let mut probe_insets: SafeAreaInsets = SafeAreaInsets::default();
    if let Some(probe) = web_ensure_safe_area_probe(&doc)
        && let Ok(style_decl) = get_style_fn.call1(win.as_ref(), probe.as_ref())
        && let Ok(get_prop_val) = Reflect::get(
            &style_decl,
            &JsValue::from_str(WEB_METHOD_GET_PROPERTY_VALUE),
        )
        && let Ok(get_prop_fn) = get_prop_val.dyn_into::<Function>()
    {
        probe_insets = SafeAreaInsets::new(
            web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_PADDING_TOP),
            web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_PADDING_RIGHT),
            web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_PADDING_BOTTOM),
            web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_PADDING_LEFT),
        );
    }
    if probe_insets != SafeAreaInsets::default() {
        return probe_insets;
    }
    let Some(root): Option<Element> = doc.document_element() else {
        return SafeAreaInsets::default();
    };
    let Ok(style_decl) = get_style_fn.call1(win.as_ref(), root.as_ref()) else {
        return SafeAreaInsets::default();
    };
    let Ok(get_prop_val) = Reflect::get(
        &style_decl,
        &JsValue::from_str(WEB_METHOD_GET_PROPERTY_VALUE),
    ) else {
        return SafeAreaInsets::default();
    };
    let Ok(get_prop_fn) = get_prop_val.dyn_into::<Function>() else {
        return SafeAreaInsets::default();
    };
    let top: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_TOP);
    let right: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_RIGHT);
    let bottom: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_BOTTOM);
    let left: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_LEFT);
    SafeAreaInsets::new(top, right, bottom, left)
}

/// Checks whether the browser exposes `navigator.gpu` for WebGPU hardware acceleration.
///
/// # Returns
///
/// - `bool` - `true` when `navigator.gpu` is present and non-null.
#[must_use]
pub fn web_has_webgpu() -> bool {
    let Some(win) = window() else {
        return false;
    };
    let nav: Navigator = win.navigator();
    Reflect::get(nav.as_ref(), &JsValue::from_str(WEB_PROP_GPU))
        .map(|val: JsValue| !val.is_undefined() && !val.is_null())
        .unwrap_or(false)
}

/// Attaches a browser `ResizeObserver` to `canvas` invoking `callback` on layout box changes without polling reflows.
///
/// # Arguments
///
/// - `&HtmlCanvasElement` - Target DOM canvas element.
/// - `&Function` - JavaScript callback invoked when `canvas` resizes.
///
/// # Returns
///
/// - `Option<Object>` - Live `ResizeObserver` instance if supported by the browser.
#[must_use]
pub fn web_attach_resize_observer(
    canvas: &HtmlCanvasElement,
    callback: &Function,
) -> Option<Object> {
    let win: Window = window()?;
    let ctor_val: JsValue =
        Reflect::get(win.as_ref(), &JsValue::from_str(WEB_CTOR_RESIZE_OBSERVER)).ok()?;
    let ctor_fn: Function = ctor_val.dyn_into::<Function>().ok()?;
    let args_obj: Object = Object::new();
    let _: bool = Reflect::set(
        args_obj.as_ref(),
        &JsValue::from_str(WEB_REFLECT_ARG0_KEY),
        callback.as_ref(),
    )
    .ok()?;
    let ro_val: JsValue = Reflect::construct(&ctor_fn, &Object::values(&args_obj)).ok()?;
    let observe_val: JsValue =
        Reflect::get(&ro_val, &JsValue::from_str(WEB_METHOD_OBSERVE)).ok()?;
    let observe_fn: Function = observe_val.dyn_into::<Function>().ok()?;
    let _: JsValue = observe_fn.call1(&ro_val, canvas.as_ref()).ok()?;
    ro_val.dyn_into::<Object>().ok()
}

/// Disconnects a live browser `ResizeObserver` cleanly on window teardown.
///
/// # Arguments
///
/// - `&Object` - Active `ResizeObserver` instance.
pub fn web_disconnect_resize_observer(observer: &Object) {
    if let Ok(disc_val) = Reflect::get(observer.as_ref(), &JsValue::from_str(WEB_METHOD_DISCONNECT))
        && let Ok(disc_fn) = disc_val.dyn_into::<Function>()
    {
        drop(disc_fn.call0(observer.as_ref()));
    }
}

/// Builds the WebGL2 context options dictionary (`alpha: false`, `desynchronized: false`, `preserveDrawingBuffer: false`, `powerPreference: "high-performance"`).
///
/// Keeps `desynchronized: false` to prevent tile tearing and blocky mosaic artifacts on mobile Safari and Android Chrome.
///
/// # Returns
///
/// - `Object` - Populated JS options object for `getContext("webgl2", opts)`.
#[must_use]
fn web_gl2_context_options() -> Object {
    let opts: Object = Object::new();
    let _: Result<bool, JsValue> = Reflect::set(
        opts.as_ref(),
        &JsValue::from_str(WEB_GL_OPT_ALPHA),
        &JsValue::from_bool(false),
    );
    let _: Result<bool, JsValue> = Reflect::set(
        opts.as_ref(),
        &JsValue::from_str(WEB_GL_OPT_ANTIALIAS),
        &JsValue::from_bool(false),
    );
    let _: Result<bool, JsValue> = Reflect::set(
        opts.as_ref(),
        &JsValue::from_str(WEB_GL_OPT_DEPTH),
        &JsValue::from_bool(false),
    );
    let _: Result<bool, JsValue> = Reflect::set(
        opts.as_ref(),
        &JsValue::from_str(WEB_GL_OPT_DESYNCHRONIZED),
        &JsValue::from_bool(false),
    );
    let _: Result<bool, JsValue> = Reflect::set(
        opts.as_ref(),
        &JsValue::from_str(WEB_GL_OPT_POWER_PREF),
        &JsValue::from_str(WEB_GL_OPT_HIGH_PERFORMANCE),
    );
    let _: Result<bool, JsValue> = Reflect::set(
        opts.as_ref(),
        &JsValue::from_str(WEB_GL_OPT_PRESERVE_DRAWING),
        &JsValue::from_bool(false),
    );
    opts
}

/// Applies canonical RGBA8 WebGL2 pixel unpack state (`UNPACK_ALIGNMENT = 4`, no flip-Y, no premultiply, no colorspace conversion).
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
fn web_configure_gl2_unpack_state(gl: &WebGl2RenderingContext) {
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_ALIGNMENT, 4);
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_FLIP_Y_WEBGL, 0);
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
    gl.pixel_storei(
        WebGl2RenderingContext::UNPACK_COLORSPACE_CONVERSION_WEBGL,
        WebGl2RenderingContext::NONE as i32,
    );
}

/// Initializes the WebGL2 direct GPU primitive `WebGlProgram` (`precision highp float`, zero CPU framebuffer upload) on `gl`.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
///
/// # Returns
///
/// - `Option<WebGl2DirectPipeline>` - Compiled direct primitive program and uniform locations.
fn web_init_gl2_direct_pipeline(gl: &WebGl2RenderingContext) -> Option<WebGl2DirectPipeline> {
    let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
    gl.shader_source(&vs, WEB_GL2_DIRECT_VERT_SHADER);
    gl.compile_shader(&vs);
    let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
    gl.shader_source(&fs, WEB_GL2_DIRECT_FRAG_SHADER);
    gl.compile_shader(&fs);
    let prog: WebGlProgram = gl.create_program()?;
    gl.attach_shader(&prog, &vs);
    gl.attach_shader(&prog, &fs);
    gl.link_program(&prog);
    let view_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&prog, WEB_GL2_UNIFORM_VIEW);
    let rect_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&prog, WEB_GL2_DIRECT_UNIFORM_RECT);
    let color_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&prog, WEB_GL2_DIRECT_UNIFORM_COLOR);
    Some(WebGl2DirectPipeline {
        program: prog,
        view_loc,
        rect_loc,
        color_loc,
    })
}

/// Queries `GL_MAX_TEXTURE_SIZE` and `GL_MAX_RENDERBUFFER_SIZE` once when creating a WebGL2 context so hot frames never stall the GPU pipeline.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
///
/// # Returns
///
/// - `u32` - Supported maximum 2D texture and renderbuffer edge length in physical pixels.
#[must_use]
fn web_query_gl2_max_texture_size(gl: &WebGl2RenderingContext) -> u32 {
    let max_tex: u32 = gl
        .get_parameter(WebGl2RenderingContext::MAX_TEXTURE_SIZE)
        .ok()
        .and_then(|val: JsValue| val.as_f64())
        .map(|val: f64| val.max(1024.0) as u32)
        .unwrap_or(WEB_TILED_BLIT_CHUNK_DIM);
    let max_rb: u32 = gl
        .get_parameter(WebGl2RenderingContext::MAX_RENDERBUFFER_SIZE)
        .ok()
        .and_then(|val: JsValue| val.as_f64())
        .map(|val: f64| val.max(1024.0) as u32)
        .unwrap_or(max_tex);
    max_tex.min(max_rb).max(1024)
}

/// Probes whether `navigator.gpu` WebGPU capability is exposed in the current browser context.
///
/// # Arguments
///
/// - `&Window` - Active browser window.
///
/// # Returns
///
/// - `bool` - `true` when `navigator.gpu` is defined and non-null.
#[must_use]
fn web_probe_webgpu_available(win: &Window) -> bool {
    let nav: Navigator = win.navigator();
    Reflect::get(nav.as_ref(), &JsValue::from_str(WEB_PROP_GPU))
        .ok()
        .map(|val: JsValue| !val.is_null() && !val.is_undefined())
        .unwrap_or(false)
}

/// Creates a 2D WebGL2 texture seeded with a `1x1` transparent texel and `LINEAR`/`CLAMP_TO_EDGE` sampling.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
/// - `Option<&Function>` - Cached `gl.bindTexture` function handle.
/// - `i32` - Internal WebGL2 sized format (`R8` or `RGBA8`).
/// - `u32` - Pixel upload format (`RED` or `RGBA`).
/// - `&[u8]` - Initial `1x1` pixel payload.
///
/// # Returns
///
/// - `Option<JsValue>` - Allocated opaque WebGL2 texture handle.
fn web_create_gl2_seeded_texture(
    gl: &WebGl2RenderingContext,
    bind_texture_fn: Option<&Function>,
    internal_format: i32,
    upload_format: u32,
    seed_pixel: &[u8],
) -> Option<JsValue> {
    let tex: JsValue = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_CREATE_TEXTURE))
        .ok()
        .and_then(|item_val: JsValue| item_val.dyn_into::<Function>().ok())
        .and_then(|create_fn: Function| create_fn.call0(gl.as_ref()).ok())
        .filter(|val: &JsValue| !val.is_null() && !val.is_undefined())?;
    let target_val: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
    if let Some(bind_fn) = bind_texture_fn {
        drop(bind_fn.call2(gl.as_ref(), &target_val, &tex));
    }
    gl.tex_parameteri(
        WebGl2RenderingContext::TEXTURE_2D,
        WebGl2RenderingContext::TEXTURE_MIN_FILTER,
        WebGl2RenderingContext::LINEAR as i32,
    );
    gl.tex_parameteri(
        WebGl2RenderingContext::TEXTURE_2D,
        WebGl2RenderingContext::TEXTURE_MAG_FILTER,
        WebGl2RenderingContext::LINEAR as i32,
    );
    gl.tex_parameteri(
        WebGl2RenderingContext::TEXTURE_2D,
        WebGl2RenderingContext::TEXTURE_WRAP_S,
        WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
    );
    gl.tex_parameteri(
        WebGl2RenderingContext::TEXTURE_2D,
        WebGl2RenderingContext::TEXTURE_WRAP_T,
        WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
    );
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_ALIGNMENT, 1);
    // SAFETY: `seed_pixel` stays valid and immovable for the synchronous `texImage2D` call.
    let view: Uint8Array = unsafe { Uint8Array::view(seed_pixel) };
    let _: Result<(), JsValue> = gl
        .tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
            WebGl2RenderingContext::TEXTURE_2D,
            0,
            internal_format,
            1,
            1,
            0,
            upload_format,
            WebGl2RenderingContext::UNSIGNED_BYTE,
            Some(view.as_ref()),
        );
    Some(tex)
}

/// Initializes the WebGL2 64-byte instanced uber-shader pipeline (`draw_arrays_instanced`) using `webgl2_compile_ui_program` and `gles3_ui_instance_attribs`.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 rendering context.
///
/// # Returns
///
/// - `Option<WebGl2InstancedPipeline>` - Ready-to-draw instanced pipeline with persistent VAO, `GL_STREAM_DRAW` instance VBO, and 4 texture slots.
fn web_init_gl2_instanced_pipeline(gl: &WebGl2RenderingContext) -> Option<WebGl2InstancedPipeline> {
    let program: WebGlProgram = webgl2_compile_ui_program(gl)?;
    let linked: bool = gl
        .get_program_parameter(&program, WebGl2RenderingContext::LINK_STATUS)
        .as_bool()
        .unwrap_or(false);
    if !linked {
        return None;
    }
    let vao: WebGlVertexArrayObject = gl.create_vertex_array()?;
    let quad_vbo: WebGlBuffer = gl.create_buffer()?;
    let instance_vbo: WebGlBuffer = gl.create_buffer()?;
    gl.bind_vertex_array(Some(&vao));
    gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&quad_vbo));
    // SAFETY: `WEB_GL2_UNIT_QUAD_VERTS` is a `'static` `[f32; 12]` (48 bytes) read synchronously by WebGL2.
    let quad_bytes: &[u8] = unsafe {
        from_raw_parts(
            WEB_GL2_UNIT_QUAD_VERTS.as_ptr().cast::<u8>(),
            size_of::<[f32; 12]>(),
        )
    };
    // SAFETY: `quad_bytes` lives in static WASM memory for the synchronous `bufferData` upload.
    let quad_view: Uint8Array = unsafe { Uint8Array::view(quad_bytes) };
    gl.buffer_data_with_array_buffer_view(
        WebGl2RenderingContext::ARRAY_BUFFER,
        quad_view.as_ref(),
        WebGl2RenderingContext::STATIC_DRAW,
    );
    gl.enable_vertex_attrib_array(0);
    gl.vertex_attrib_pointer_with_i32(0, 2, WebGl2RenderingContext::FLOAT, false, 8, 0);
    gl.vertex_attrib_divisor(0, 0);
    gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&instance_vbo));
    gl.buffer_data_with_i32(
        WebGl2RenderingContext::ARRAY_BUFFER,
        WEB_GL2_INITIAL_INSTANCE_VBO_BYTES as i32,
        WebGl2RenderingContext::STREAM_DRAW,
    );
    let attribs: [Gles3InstanceAttribSpec; 5] = gles3_ui_instance_attribs();
    for spec in attribs.iter() {
        gl.enable_vertex_attrib_array(spec.get_location());
        if spec.get_is_integer() {
            gl.vertex_attrib_i_pointer_with_i32(
                spec.get_location(),
                spec.get_components(),
                WebGl2RenderingContext::UNSIGNED_INT,
                spec.get_stride(),
                spec.get_byte_offset() as i32,
            );
        } else {
            gl.vertex_attrib_pointer_with_i32(
                spec.get_location(),
                spec.get_components(),
                WebGl2RenderingContext::FLOAT,
                false,
                spec.get_stride(),
                spec.get_byte_offset() as i32,
            );
        }
        gl.vertex_attrib_divisor(spec.get_location(), 1);
    }
    gl.bind_vertex_array(None);
    gl.use_program(Some(&program));
    if let Some(loc) = gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_GLYPH_R8) {
        gl.uniform1i(Some(&loc), 0);
    }
    if let Some(loc) = gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_GLYPH_RGBA8) {
        gl.uniform1i(Some(&loc), 1);
    }
    if let Some(loc) = gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_IMAGE_TEX) {
        gl.uniform1i(Some(&loc), 2);
    }
    if let Some(loc) = gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_EXTERNAL_TEX) {
        gl.uniform1i(Some(&loc), 3);
    }
    let viewport_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_VIEWPORT);
    let scroll_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_SCROLL);
    let tile_origin_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_TILE_ORIGIN);
    let blur_program: Option<WebGlProgram> = web_compile_gl2_program(
        gl,
        GLSL_ES3_BACKDROP_BLUR_VERTEX_SHADER,
        GLSL_ES3_BACKDROP_BLUR_FRAGMENT_SHADER,
    );
    let (blur_texel_loc, blur_offset_loc, blur_mode_loc): (
        Option<WebGlUniformLocation>,
        Option<WebGlUniformLocation>,
        Option<WebGlUniformLocation>,
    ) = if let Some(bprog) = blur_program.as_ref() {
        gl.use_program(Some(bprog));
        if let Some(loc) = gl.get_uniform_location(bprog, WEB_GL2_BLUR_UNIFORM_TEX) {
            gl.uniform1i(Some(&loc), 0);
        }
        (
            gl.get_uniform_location(bprog, WEB_GL2_BLUR_UNIFORM_TEXEL),
            gl.get_uniform_location(bprog, WEB_GL2_BLUR_UNIFORM_OFFSET),
            gl.get_uniform_location(bprog, WEB_GL2_BLUR_UNIFORM_MODE),
        )
    } else {
        (None, None, None)
    };
    gl.use_program(Some(&program));
    let bind_texture_fn: Option<Function> =
        Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_BIND_TEXTURE))
            .ok()
            .and_then(|val: JsValue| val.dyn_into::<Function>().ok());
    let zero_r8: [u8; 1] = [0];
    let zero_rgba8: [u8; 4] = [0, 0, 0, 0];
    gl.active_texture(WebGl2RenderingContext::TEXTURE0);
    let glyph_r8_tex: Option<JsValue> = web_create_gl2_seeded_texture(
        gl,
        bind_texture_fn.as_ref(),
        WebGl2RenderingContext::R8 as i32,
        WebGl2RenderingContext::RED,
        &zero_r8,
    );
    gl.active_texture(WebGl2RenderingContext::TEXTURE1);
    let glyph_rgba8_tex: Option<JsValue> = web_create_gl2_seeded_texture(
        gl,
        bind_texture_fn.as_ref(),
        WebGl2RenderingContext::RGBA8 as i32,
        WebGl2RenderingContext::RGBA,
        &zero_rgba8,
    );
    gl.active_texture(WebGl2RenderingContext::TEXTURE2);
    let image_atlas_tex: Option<JsValue> = web_create_gl2_seeded_texture(
        gl,
        bind_texture_fn.as_ref(),
        WebGl2RenderingContext::RGBA8 as i32,
        WebGl2RenderingContext::RGBA,
        &zero_rgba8,
    );
    gl.active_texture(WebGl2RenderingContext::TEXTURE3);
    let external_tex: Option<JsValue> = web_create_gl2_seeded_texture(
        gl,
        bind_texture_fn.as_ref(),
        WebGl2RenderingContext::RGBA8 as i32,
        WebGl2RenderingContext::RGBA,
        &zero_rgba8,
    );
    let max_tex_dim: u32 = web_query_gl2_max_texture_size(gl);
    Some(WebGl2InstancedPipeline {
        program,
        vao,
        instance_vbo,
        instance_vbo_cap_bytes: WEB_GL2_INITIAL_INSTANCE_VBO_BYTES,
        viewport_loc,
        scroll_loc,
        tile_origin_loc,
        bind_texture_fn,
        glyph_r8_tex,
        glyph_r8_w: 1,
        glyph_r8_h: 1,
        glyph_rgba8_tex,
        image_atlas_tex,
        image_atlas_w: 1,
        image_atlas_h: 1,
        external_tex,
        max_tex_dim,
        blur_program,
        blur_texel_loc,
        blur_offset_loc,
        blur_mode_loc,
        blur_scene_fbo: None,
        blur_scene_tex: None,
        blur_half_fbo: None,
        blur_half_tex: None,
        blur_full_fbo: None,
        blur_full_tex: None,
        blur_dims: (0, 0),
        scene_gl: None,
        synced_glyph_r8_rev: 0,
        synced_image_rgba8_rev: 0,
    })
}

/// Initializes a `highp` fullscreen triangle `WebGlProgram`, resident RGBA8 texture handle, and `u_view` uniform location on `gl`.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
///
/// # Returns
///
/// - `Option<WebGl2BlitPipeline>` - Compiled blit program, allocated WebGL2 texture object, and `u_view` uniform location.
fn web_init_gl2_blit_pipeline(gl: &WebGl2RenderingContext) -> Option<WebGl2BlitPipeline> {
    let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
    gl.shader_source(&vs, WEB_GL2_BLIT_VERT_SHADER);
    gl.compile_shader(&vs);
    let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
    gl.shader_source(&fs, WEB_GL2_BLIT_FRAG_SHADER);
    gl.compile_shader(&fs);
    let prog: WebGlProgram = gl.create_program()?;
    gl.attach_shader(&prog, &vs);
    gl.attach_shader(&prog, &fs);
    gl.link_program(&prog);
    gl.use_program(Some(&prog));
    if let Some(loc) = gl.get_uniform_location(&prog, WEB_GL2_UNIFORM_TEX) {
        gl.uniform1i(Some(&loc), 0);
    }
    let view_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&prog, WEB_GL2_UNIFORM_VIEW);
    web_configure_gl2_unpack_state(gl);
    let bind_texture_fn: Option<Function> =
        Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_BIND_TEXTURE))
            .ok()
            .and_then(|val: JsValue| val.dyn_into::<Function>().ok());
    let texture: Option<JsValue> =
        Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_CREATE_TEXTURE))
            .ok()
            .and_then(|item_val: JsValue| item_val.dyn_into::<Function>().ok())
            .and_then(|factor_val: Function| factor_val.call0(gl.as_ref()).ok())
            .filter(|blend_factor: &JsValue| {
                !blend_factor.is_null() && !blend_factor.is_undefined()
            });
    if let Some(tex) = texture.as_ref() {
        let target: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
        if let Some(bind_fn) = bind_texture_fn.as_ref() {
            drop(bind_fn.call2(gl.as_ref(), &target, tex));
        }
        gl.tex_parameteri(
            WebGl2RenderingContext::TEXTURE_2D,
            WebGl2RenderingContext::TEXTURE_MIN_FILTER,
            WebGl2RenderingContext::LINEAR as i32,
        );
        gl.tex_parameteri(
            WebGl2RenderingContext::TEXTURE_2D,
            WebGl2RenderingContext::TEXTURE_MAG_FILTER,
            WebGl2RenderingContext::LINEAR as i32,
        );
        gl.tex_parameteri(
            WebGl2RenderingContext::TEXTURE_2D,
            WebGl2RenderingContext::TEXTURE_WRAP_S,
            WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
        );
        gl.tex_parameteri(
            WebGl2RenderingContext::TEXTURE_2D,
            WebGl2RenderingContext::TEXTURE_WRAP_T,
            WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
        );
    }
    let max_tex_dim: u32 = web_query_gl2_max_texture_size(gl);
    Some(WebGl2BlitPipeline {
        program: prog,
        texture,
        view_loc,
        bind_texture_fn,
        max_tex_dim,
    })
}

/// Invokes a zero-argument DOM method that may return a JS `Promise`, swallowing rejections so browser consoles stay clean.
///
/// # Arguments
///
/// - `&JsValue` - Target DOM receiver (`Element` or `Document`).
/// - `&str` - Method property name to invoke.
///
/// # Returns
///
/// - `bool` - `true` when the method existed on `target` and was invoked.
fn web_invoke_promise_method(target: &JsValue, method: &str) -> bool {
    let Ok(func_val) = Reflect::get(target, &JsValue::from_str(method)) else {
        return false;
    };
    let Ok(func) = func_val.dyn_into::<Function>() else {
        return false;
    };
    if let Ok(ret) = func.call0(target)
        && let Ok(promise) = ret.dyn_into::<Promise>()
    {
        WEB_PROMISE_NOOP_REJECT.with(|callback_fn: &Closure<dyn FnMut(JsValue)>| {
            let _: Promise = promise.catch(callback_fn);
        });
    }
    true
}

/// Returns `true` when the browser document currently has a standard or WebKit-prefixed fullscreen element active.
///
/// # Arguments
///
/// - `&Document` - Active browser DOM document.
///
/// # Returns
///
/// - `bool` - `true` while browser fullscreen is active.
#[must_use]
fn web_doc_has_fullscreen_element(doc: &Document) -> bool {
    if doc.fullscreen_element().is_some() {
        return true;
    }
    Reflect::get(
        doc.as_ref(),
        &JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
    )
    .ok()
    .map(|item_val: JsValue| !item_val.is_null() && !item_val.is_undefined())
    .unwrap_or(false)
}

/// Requests or exits browser Fullscreen API cleanly on `document.documentElement` with Safari WebKit fallback.
///
/// # Arguments
///
/// - `bool` - `true` to enter fullscreen; `false` to exit fullscreen.
pub fn web_set_fullscreen(enabled: bool) {
    let Some(doc) = window().and_then(|width_val: Window| width_val.document()) else {
        return;
    };
    let is_fs: bool = web_doc_has_fullscreen_element(&doc);
    if enabled {
        if !is_fs
            && let Some(root) = doc.document_element()
            && !web_invoke_promise_method(root.as_ref(), WEB_METHOD_REQUEST_FULLSCREEN)
        {
            let _: bool =
                web_invoke_promise_method(root.as_ref(), WEB_METHOD_WEBKIT_REQUEST_FULLSCREEN);
        }
    } else if is_fs && !web_invoke_promise_method(doc.as_ref(), WEB_METHOD_EXIT_FULLSCREEN) {
        let _: bool = web_invoke_promise_method(doc.as_ref(), WEB_METHOD_WEBKIT_EXIT_FULLSCREEN);
    }
}

/// Injects an idempotent `<style id="euv-web-reset">` stylesheet into `<head>` to disable browser tap-highlight blue overlays and focus outlines.
///
/// # Arguments
///
/// - `&Document` - Active browser DOM document.
fn web_ensure_reset_stylesheet(doc: &Document) {
    if doc.get_element_by_id(WEB_RESET_STYLE_ID).is_some() {
        return;
    }
    let Ok(style_el) = doc.create_element(WEB_STYLE_TAG) else {
        return;
    };
    drop(style_el.set_attribute(WEB_ATTR_ID, WEB_RESET_STYLE_ID));
    style_el.set_text_content(Some(WEB_RESET_STYLE_CSS));
    if let Ok(Some(head)) = doc.query_selector(WEB_HEAD_SELECTOR) {
        drop(head.append_child(&style_el));
    } else if let Some(root) = doc.document_element() {
        drop(root.append_child(&style_el));
    }
}

/// Creates or reuses the mounted `HTMLCanvasElement`, preferring WebGPU / WebGL2 hardware contexts and locking `"2d"` only if GPU contexts fail or `RenderMode::Software` is explicitly requested.
///
/// # Arguments
///
/// - `&WindowConfig` - Declarative window configuration.
/// - `f32` - Browser device pixel ratio.
/// - `bool` - `true` when an existing DOM `<canvas>` may be reused to prevent duplicate stacked canvases.
///
/// # Returns
///
/// - `Result<WebCanvasSurface, PlatformError>` - Mounted canvas and active WebGPU, WebGL2, or 2D context.
pub(crate) fn web_create_canvas(
    config: &WindowConfig,
    dpr: f32,
    reuse_existing: bool,
) -> Result<WebCanvasSurface, PlatformError> {
    let win: Window = window()
        .ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
    let doc: Document = win
        .document()
        .ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
    doc.set_title(config.get_title());
    web_ensure_reset_stylesheet(&doc);
    let mut existing_canvas: Option<HtmlCanvasElement> = None;
    if reuse_existing
        && let Ok(Some(found)) = doc.query_selector(WEB_CANVAS_TAG)
        && let Ok(existing) = found.dyn_into::<HtmlCanvasElement>()
    {
        existing_canvas = Some(existing);
    }
    let (canvas, needs_append): (HtmlCanvasElement, bool) = match existing_canvas {
        Some(existing) => (existing, false),
        None => {
            let el: Element = doc.create_element(WEB_CANVAS_TAG).map_err(|_: JsValue| {
                PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
            })?;
            let created: HtmlCanvasElement =
                el.dyn_into::<HtmlCanvasElement>().map_err(|_: Element| {
                    PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
                })?;
            (created, true)
        }
    };
    let (win_w, win_h): (f64, f64) = web_query_viewport_css_size(
        &win,
        &doc,
        config.get_width() as f64,
        config.get_height() as f64,
    );
    let safe_dpr: f64 = f64::from(dpr.clamp(WEB_DPR_MIN, WEB_DPR_MAX));
    let phys_w: u32 = (win_w * safe_dpr)
        .round()
        .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
    let phys_h: u32 = (win_h * safe_dpr)
        .round()
        .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
    canvas.set_width(phys_w);
    canvas.set_height(phys_h);
    let css_style: String =
        format!("{WEB_CANVAS_STYLE_PREFIX}{WEB_CURSOR_DEFAULT}{WEB_CANVAS_STYLE_SUFFIX}");
    drop(canvas.set_attribute(WEB_ATTR_STYLE, &css_style));
    drop(canvas.set_attribute(WEB_ATTR_CANVAS_ROLE, WEB_CANVAS_ROLE_ACTIVE));
    drop(canvas.set_attribute(WEB_ATTR_TABINDEX, WEB_ATTR_TABINDEX_ZERO));
    if let Some(body) = doc.body() {
        drop(body.set_attribute(WEB_ATTR_STYLE, WEB_BODY_STYLE));
        if needs_append {
            drop(body.append_child(&canvas));
        }
    }
    let render_mode: RenderMode = config.get_render().get_mode();
    let prefer_direct: bool = config.get_render().get_direct_gpu_present();
    let webgpu_available: bool = web_probe_webgpu_available(&win);
    if render_mode != RenderMode::Software {
        let gl_opts: Object = web_gl2_context_options();
        if let Ok(Some(raw_gl)) =
            canvas.get_context_with_context_options(WEB_CONTEXT_WEBGL2, gl_opts.as_ref())
            && let Ok(gl2) = raw_gl.dyn_into::<WebGl2RenderingContext>()
        {
            let gl2_instanced: Option<WebGl2InstancedPipeline> =
                web_init_gl2_instanced_pipeline(&gl2);
            let direct: Option<WebGl2DirectPipeline> = web_init_gl2_direct_pipeline(&gl2);
            let (
                gl2_direct_program,
                gl2_direct_view_loc,
                gl2_direct_rect_loc,
                gl2_direct_color_loc,
            ): (
                Option<WebGlProgram>,
                Option<WebGlUniformLocation>,
                Option<WebGlUniformLocation>,
                Option<WebGlUniformLocation>,
            ) = match direct {
                Some(delta_val) => (
                    Some(delta_val.program),
                    delta_val.view_loc,
                    delta_val.rect_loc,
                    delta_val.color_loc,
                ),
                None => (None, None, None, None),
            };
            let pipeline: Option<WebGl2BlitPipeline> = web_init_gl2_blit_pipeline(&gl2);
            let (gl2_program, gl2_texture, gl2_view_loc, gl2_bind_texture_fn, gl2_max_tex_dim): (
                Option<WebGlProgram>,
                Option<JsValue>,
                Option<WebGlUniformLocation>,
                Option<Function>,
                u32,
            ) = match pipeline {
                Some(point_val) => (
                    Some(point_val.program),
                    point_val.texture,
                    point_val.view_loc,
                    point_val.bind_texture_fn,
                    point_val.max_tex_dim,
                ),
                None => (None, None, None, None, web_query_gl2_max_texture_size(&gl2)),
            };
            let pres_mode: WebPresentationMode = if prefer_direct && gl2_instanced.is_some() {
                WebPresentationMode::GpuDirect
            } else {
                WebPresentationMode::GpuUpload
            };
            return Ok(WebCanvasSurface {
                canvas,
                context_kind: WebCanvasContextKind::WebGl2,
                presentation_mode: pres_mode,
                webgpu_ctx: None,
                webgpu_available,
                gl2: Some(gl2),
                gl2_instanced,
                gl2_direct_program,
                gl2_direct_view_loc,
                gl2_direct_rect_loc,
                gl2_direct_color_loc,
                gl2_program,
                gl2_texture,
                gl2_view_loc,
                gl2_bind_texture_fn,
                gl2_max_tex_dim,
                ctx2d: None,
            });
        }
    }
    let raw_ctx: Object = canvas
        .get_context(WEB_CONTEXT_2D)
        .map_err(|_: JsValue| PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string()))?
        .ok_or_else(|| PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string()))?;
    let ctx2d: CanvasRenderingContext2d = raw_ctx
        .dyn_into::<CanvasRenderingContext2d>()
        .map_err(|_: Object| PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string()))?;
    Ok(WebCanvasSurface {
        canvas,
        context_kind: WebCanvasContextKind::Canvas2d,
        presentation_mode: WebPresentationMode::Software,
        webgpu_ctx: None,
        webgpu_available,
        gl2: None,
        gl2_instanced: None,
        gl2_direct_program: None,
        gl2_direct_view_loc: None,
        gl2_direct_rect_loc: None,
        gl2_direct_color_loc: None,
        gl2_program: None,
        gl2_texture: None,
        gl2_view_loc: None,
        gl2_bind_texture_fn: None,
        gl2_max_tex_dim: WEB_TILED_BLIT_CHUNK_DIM,
        ctx2d: Some(ctx2d),
    })
}

/// Creates a brand-new independent sibling `<canvas>` mounted hidden inside `parent_el` (or `document.body`) for a single locked context family (`WebGl2` or `Canvas2d`).
///
/// NEVER calls `getContext("2d")` and `getContext("webgl2")` on the same `<canvas>`.
///
/// # Arguments
///
/// - `Option<&Element>` - Parent container holding the active `<canvas>` (`None` falls back to `document.body`).
/// - `WebPresentationMode` - Candidate presentation mode determining the locked context family.
/// - `u32` - Physical canvas width in pixels.
/// - `u32` - Physical canvas height in pixels.
///
/// # Returns
///
/// - `Result<WebCanvasSurface, PlatformError>` - Hidden standby `<canvas>` initialized with its independent context.
pub(crate) fn web_create_independent_standby_canvas(
    parent_el: Option<&Element>,
    target_mode: WebPresentationMode,
    phys_w: u32,
    phys_h: u32,
) -> Result<WebCanvasSurface, PlatformError> {
    let win: Window = window()
        .ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
    let doc: Document = win
        .document()
        .ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
    let el: Element = doc.create_element(WEB_CANVAS_TAG).map_err(|_: JsValue| {
        PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
    })?;
    let canvas: HtmlCanvasElement = el.dyn_into::<HtmlCanvasElement>().map_err(|_: Element| {
        PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
    })?;
    canvas.set_width(phys_w.max(1));
    canvas.set_height(phys_h.max(1));
    drop(canvas.set_attribute(WEB_ATTR_STYLE, WEB_STANDBY_CANVAS_STYLE));
    drop(canvas.set_attribute(WEB_ATTR_CANVAS_ROLE, WEB_CANVAS_ROLE_STANDBY));
    drop(canvas.set_attribute(WEB_ATTR_TABINDEX, WEB_ATTR_TABINDEX_ZERO));
    if let Some(container) = parent_el {
        drop(container.append_child(&canvas));
    } else if let Some(body) = doc.body() {
        drop(body.append_child(&canvas));
    }
    match target_mode {
        WebPresentationMode::GpuDirect | WebPresentationMode::GpuUpload => {
            let gl_opts: Object = web_gl2_context_options();
            let raw_gl: Object = canvas
                .get_context_with_context_options(WEB_CONTEXT_WEBGL2, gl_opts.as_ref())
                .map_err(|_: JsValue| {
                    canvas.remove();
                    PlatformError::SurfaceError(ERR_WEB_GL2_CONTEXT_MISSING.to_string())
                })?
                .ok_or_else(|| {
                    canvas.remove();
                    PlatformError::SurfaceError(ERR_WEB_GL2_CONTEXT_MISSING.to_string())
                })?;
            let gl2: WebGl2RenderingContext =
                raw_gl
                    .dyn_into::<WebGl2RenderingContext>()
                    .map_err(|_: Object| {
                        canvas.remove();
                        PlatformError::SurfaceError(ERR_WEB_GL2_CONTEXT_MISSING.to_string())
                    })?;
            let gl2_instanced: Option<WebGl2InstancedPipeline> =
                web_init_gl2_instanced_pipeline(&gl2);
            let direct: Option<WebGl2DirectPipeline> = web_init_gl2_direct_pipeline(&gl2);
            let (
                gl2_direct_program,
                gl2_direct_view_loc,
                gl2_direct_rect_loc,
                gl2_direct_color_loc,
            ): (
                Option<WebGlProgram>,
                Option<WebGlUniformLocation>,
                Option<WebGlUniformLocation>,
                Option<WebGlUniformLocation>,
            ) = match direct {
                Some(delta_val) => (
                    Some(delta_val.program),
                    delta_val.view_loc,
                    delta_val.rect_loc,
                    delta_val.color_loc,
                ),
                None => (None, None, None, None),
            };
            let pipeline: Option<WebGl2BlitPipeline> = web_init_gl2_blit_pipeline(&gl2);
            let (gl2_program, gl2_texture, gl2_view_loc, gl2_bind_texture_fn, gl2_max_tex_dim): (
                Option<WebGlProgram>,
                Option<JsValue>,
                Option<WebGlUniformLocation>,
                Option<Function>,
                u32,
            ) = match pipeline {
                Some(point_val) => (
                    Some(point_val.program),
                    point_val.texture,
                    point_val.view_loc,
                    point_val.bind_texture_fn,
                    point_val.max_tex_dim,
                ),
                None => (None, None, None, None, web_query_gl2_max_texture_size(&gl2)),
            };
            if target_mode == WebPresentationMode::GpuDirect
                && gl2_instanced.is_none()
                && gl2_direct_program.is_none()
            {
                canvas.remove();
                return Err(PlatformError::SurfaceError(
                    ERR_WEB_GL2_DIRECT_MISSING.to_string(),
                ));
            }
            Ok(WebCanvasSurface {
                canvas,
                context_kind: WebCanvasContextKind::WebGl2,
                presentation_mode: target_mode,
                webgpu_ctx: None,
                webgpu_available: web_probe_webgpu_available(&win),
                gl2: Some(gl2),
                gl2_instanced,
                gl2_direct_program,
                gl2_direct_view_loc,
                gl2_direct_rect_loc,
                gl2_direct_color_loc,
                gl2_program,
                gl2_texture,
                gl2_view_loc,
                gl2_bind_texture_fn,
                gl2_max_tex_dim,
                ctx2d: None,
            })
        }
        WebPresentationMode::Software => {
            let raw_ctx: Object = canvas
                .get_context(WEB_CONTEXT_2D)
                .map_err(|_: JsValue| {
                    canvas.remove();
                    PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string())
                })?
                .ok_or_else(|| {
                    canvas.remove();
                    PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string())
                })?;
            let ctx2d: CanvasRenderingContext2d = raw_ctx
                .dyn_into::<CanvasRenderingContext2d>()
                .map_err(|_: Object| {
                    canvas.remove();
                    PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string())
                })?;
            Ok(WebCanvasSurface {
                canvas,
                context_kind: WebCanvasContextKind::Canvas2d,
                presentation_mode: WebPresentationMode::Software,
                webgpu_ctx: None,
                webgpu_available: web_probe_webgpu_available(&win),
                gl2: None,
                gl2_instanced: None,
                gl2_direct_program: None,
                gl2_direct_view_loc: None,
                gl2_direct_rect_loc: None,
                gl2_direct_color_loc: None,
                gl2_program: None,
                gl2_texture: None,
                gl2_view_loc: None,
                gl2_bind_texture_fn: None,
                gl2_max_tex_dim: WEB_TILED_BLIT_CHUNK_DIM,
                ctx2d: Some(ctx2d),
            })
        }
    }
}

/// Returns whether every primitive in `batches` is an unrounded flat rectangle supported by the direct WebGL2 quad shader.
///
/// # Arguments
///
/// - `&[GpuBatch]` - Ordered GPU primitive draw batches.
///
/// # Returns
///
/// - `bool` - `true` when all primitives are unrounded flat rects supported by the direct WebGL2 quad shader.
#[must_use]
pub(crate) fn web_batches_support_gl2_direct(batches: &[GpuBatch]) -> bool {
    for batch_entry in batches.iter() {
        for primitive_item in batch_entry.get_primitives().iter() {
            if primitive_item.prim_kind() != PrimKind::RoundedRect
                || primitive_item.get_radii_border() != [0, 0, 0, 0]
                || primitive_item.get_extra_param() != 0
            {
                return false;
            }
        }
    }
    true
}

/// Draws axis-aligned flat color GPU batches directly through the minimal WebGL2 quad shader.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
/// - `&WebGlProgram` - Direct quad shader program.
/// - `&WebGl2DirectUniforms<'_>` - Viewport, rect, and color uniform locations.
/// - `(u32, u32)` - Physical canvas `(width, height)`.
/// - `Color` - Frame clear color.
/// - `&[GpuBatch]` - GPU batches validated by `web_batches_support_gl2_direct`.
///
/// # Returns
///
/// - `u32` - Count of GPU primitives drawn directly on WebGL2.
pub(crate) fn web_draw_gl2_direct_batches(
    gl: &WebGl2RenderingContext,
    program: &WebGlProgram,
    uniform_locs: &WebGl2DirectUniforms<'_>,
    surface_dims: (u32, u32),
    clear_color: Color,
    batches: &[GpuBatch],
) -> u32 {
    let view_loc: Option<&WebGlUniformLocation> = uniform_locs.view_loc;
    let rect_loc: Option<&WebGlUniformLocation> = uniform_locs.rect_loc;
    let color_loc: Option<&WebGlUniformLocation> = uniform_locs.color_loc;
    let (width, height): (u32, u32) = surface_dims;
    let draw_w: i32 = width.max(1) as i32;
    let draw_h: i32 = height.max(1) as i32;
    gl.viewport(0, 0, draw_w, draw_h);
    gl.enable(WebGl2RenderingContext::BLEND);
    gl.blend_func(
        WebGl2RenderingContext::SRC_ALPHA,
        WebGl2RenderingContext::ONE_MINUS_SRC_ALPHA,
    );
    gl.clear_color(
        f32::from(clear_color.get_red()) / 255.0,
        f32::from(clear_color.get_green()) / 255.0,
        f32::from(clear_color.get_blue()) / 255.0,
        f32::from(clear_color.get_alpha()) / 255.0,
    );
    gl.clear(WebGl2RenderingContext::COLOR_BUFFER_BIT);
    gl.use_program(Some(program));
    if let Some(loc) = view_loc {
        gl.uniform2f(Some(loc), draw_w as f32, draw_h as f32);
    }
    let mut drawn: u32 = 0;
    for batch in batches.iter() {
        for prim in batch.get_primitives().iter() {
            let rect: [f32; 4] = prim.get_rect();
            let packed: u32 = prim.get_color_rgba();
            let red_val: f32 = f32::from((packed & 0xFF) as u8) / 255.0;
            let green_val: f32 = f32::from(((packed >> 8) & 0xFF) as u8) / 255.0;
            let blue_val: f32 = f32::from(((packed >> 16) & 0xFF) as u8) / 255.0;
            let alpha_val: f32 = f32::from(((packed >> 24) & 0xFF) as u8) / 255.0;
            if let Some(loc) = rect_loc {
                gl.uniform4f(Some(loc), rect[0], rect[1], rect[2], rect[3]);
            }
            if let Some(loc) = color_loc {
                gl.uniform4f(Some(loc), red_val, green_val, blue_val, alpha_val);
            }
            gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 6);
            drawn = drawn.saturating_add(1);
        }
    }
    drawn
}

/// Uploads full or dirty sub-rectangle updates of an R8 glyph coverage atlas onto `TEXTURE0` using cached `bindTexture` with zero per-frame `Reflect::get`.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
/// - `&mut WebGl2InstancedPipeline` - Persistent instanced pipeline owning `glyph_r8_tex`.
/// - `&DirectGpuAtlasUpload` - R8 glyph atlas pixels.
/// - `&[PixelDirtyRect]` - Dirty sub-rectangles pending incremental upload.
fn web_sync_gl2_glyph_r8_atlas(
    gl: &WebGl2RenderingContext,
    pipe: &mut WebGl2InstancedPipeline,
    atlas: &DirectGpuAtlasUpload,
    dirty_rects: &[PixelDirtyRect],
) {
    let atlas_w: u32 = atlas.get_width();
    let atlas_h: u32 = atlas.get_height();
    let pixels: &[u8] = atlas.get_pixels().as_slice();
    if atlas_w == 0
        || atlas_h == 0
        || pixels.len() < (atlas_w as usize).saturating_mul(atlas_h as usize)
    {
        return;
    }
    let Some(tex) = pipe.glyph_r8_tex.as_ref() else {
        return;
    };
    let target_val: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
    gl.active_texture(WebGl2RenderingContext::TEXTURE0);
    if let Some(bind_fn) = pipe.bind_texture_fn.as_ref() {
        drop(bind_fn.call2(gl.as_ref(), &target_val, tex));
    }
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_ALIGNMENT, 1);
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_FLIP_Y_WEBGL, 0);
    let dims_changed: bool = pipe.glyph_r8_w != atlas_w || pipe.glyph_r8_h != atlas_h;
    if dims_changed || dirty_rects.is_empty() {
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
        // SAFETY: `pixels` stays valid in WASM linear memory for the synchronous `texImage2D` call.
        let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
        let _: Result<(), JsValue> = gl
            .tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
                WebGl2RenderingContext::TEXTURE_2D,
                0,
                WebGl2RenderingContext::R8 as i32,
                atlas_w as i32,
                atlas_h as i32,
                0,
                WebGl2RenderingContext::RED,
                WebGl2RenderingContext::UNSIGNED_BYTE,
                Some(view.as_ref()),
            );
        pipe.glyph_r8_w = atlas_w;
        pipe.glyph_r8_h = atlas_h;
        return;
    }
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, atlas_w as i32);
    // SAFETY: `pixels` stays valid in WASM linear memory for synchronous `texSubImage2D` calls.
    let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
    for dirty in dirty_rects.iter() {
        let rx: u32 = dirty.get_x().min(atlas_w);
        let ry: u32 = dirty.get_y().min(atlas_h);
        let rw: u32 = dirty.get_width().min(atlas_w.saturating_sub(rx));
        let rh: u32 = dirty.get_height().min(atlas_h.saturating_sub(ry));
        if rw == 0 || rh == 0 {
            continue;
        }
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, rx as i32);
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, ry as i32);
        let _: Result<(), JsValue> = gl
            .tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
                WebGl2RenderingContext::TEXTURE_2D,
                0,
                rx as i32,
                ry as i32,
                rw as i32,
                rh as i32,
                WebGl2RenderingContext::RED,
                WebGl2RenderingContext::UNSIGNED_BYTE,
                Some(view.as_ref()),
            );
    }
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
}

/// Compiles and links a WebGL2 vertex + fragment shader pair, returning `None` on compile or link failure.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
/// - `&str` - GLSL ES 3.00 vertex shader source.
/// - `&str` - GLSL ES 3.00 fragment shader source.
///
/// # Returns
///
/// - `Option<WebGlProgram>` - Linked `WebGlProgram` ready for binding.
fn web_compile_gl2_program(
    gl: &WebGl2RenderingContext,
    vs_src: &str,
    fs_src: &str,
) -> Option<WebGlProgram> {
    let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
    gl.shader_source(&vs, vs_src);
    gl.compile_shader(&vs);
    if !gl
        .get_shader_parameter(&vs, WebGl2RenderingContext::COMPILE_STATUS)
        .as_bool()
        .unwrap_or(false)
    {
        return None;
    }
    let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
    gl.shader_source(&fs, fs_src);
    gl.compile_shader(&fs);
    if !gl
        .get_shader_parameter(&fs, WebGl2RenderingContext::COMPILE_STATUS)
        .as_bool()
        .unwrap_or(false)
    {
        return None;
    }
    let prog: WebGlProgram = gl.create_program()?;
    gl.attach_shader(&prog, &vs);
    gl.attach_shader(&prog, &fs);
    gl.link_program(&prog);
    if !gl
        .get_program_parameter(&prog, WebGl2RenderingContext::LINK_STATUS)
        .as_bool()
        .unwrap_or(false)
    {
        return None;
    }
    Some(prog)
}

/// Allocates a linear-filtered `RGBA8` WebGL2 texture and attaches it to a new `WebGlFramebuffer` sized `(width, height)`.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
/// - `u32` - Target width in physical pixels.
/// - `u32` - Target height in physical pixels.
///
/// # Returns
///
/// - `Option<(WebGlFramebuffer, WebGlTexture)>` - Ready offscreen color FBO and backing texture.
fn web_create_gl2_fbo_target(
    gl: &WebGl2RenderingContext,
    width: u32,
    height: u32,
) -> Option<(WebGlFramebuffer, WebGlTexture)> {
    let fbo: WebGlFramebuffer = gl.create_framebuffer()?;
    let tex: WebGlTexture = gl.create_texture()?;
    gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(&tex));
    gl.tex_parameteri(
        WebGl2RenderingContext::TEXTURE_2D,
        WebGl2RenderingContext::TEXTURE_MIN_FILTER,
        WebGl2RenderingContext::LINEAR as i32,
    );
    gl.tex_parameteri(
        WebGl2RenderingContext::TEXTURE_2D,
        WebGl2RenderingContext::TEXTURE_MAG_FILTER,
        WebGl2RenderingContext::LINEAR as i32,
    );
    gl.tex_parameteri(
        WebGl2RenderingContext::TEXTURE_2D,
        WebGl2RenderingContext::TEXTURE_WRAP_S,
        WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
    );
    gl.tex_parameteri(
        WebGl2RenderingContext::TEXTURE_2D,
        WebGl2RenderingContext::TEXTURE_WRAP_T,
        WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
    );
    let _: Result<(), JsValue> = gl
        .tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
            WebGl2RenderingContext::TEXTURE_2D,
            0,
            WebGl2RenderingContext::RGBA8 as i32,
            width.max(1) as i32,
            height.max(1) as i32,
            0,
            WebGl2RenderingContext::RGBA,
            WebGl2RenderingContext::UNSIGNED_BYTE,
            None,
        );
    gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, Some(&fbo));
    gl.framebuffer_texture_2d(
        WebGl2RenderingContext::FRAMEBUFFER,
        WebGl2RenderingContext::COLOR_ATTACHMENT0,
        WebGl2RenderingContext::TEXTURE_2D,
        Some(&tex),
        0,
    );
    gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, None);
    Some((fbo, tex))
}

/// Ensures the 3 Dual-Kawase blur FBO targets (`scene`, `half`, `full`) exist and match `(width, height)`.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
/// - `&mut WebGl2InstancedPipeline` - Instanced pipeline holding resident blur FBOs.
/// - `u32` - Surface width in physical pixels.
/// - `u32` - Surface height in physical pixels.
///
/// # Returns
///
/// - `bool` - `true` when all 3 blur FBO targets are allocated and ready.
fn web_ensure_gl2_blur_targets(
    gl: &WebGl2RenderingContext,
    pipe: &mut WebGl2InstancedPipeline,
    width: u32,
    height: u32,
) -> bool {
    let w: u32 = width.max(1);
    let h: u32 = height.max(1);
    if pipe.blur_dims == (w, h)
        && pipe.blur_scene_fbo.is_some()
        && pipe.blur_half_fbo.is_some()
        && pipe.blur_full_fbo.is_some()
    {
        return true;
    }
    if let Some(fbo) = pipe.blur_scene_fbo.take() {
        gl.delete_framebuffer(Some(&fbo));
    }
    if let Some(tex) = pipe.blur_scene_tex.take() {
        gl.delete_texture(Some(&tex));
    }
    if let Some(fbo) = pipe.blur_half_fbo.take() {
        gl.delete_framebuffer(Some(&fbo));
    }
    if let Some(tex) = pipe.blur_half_tex.take() {
        gl.delete_texture(Some(&tex));
    }
    if let Some(fbo) = pipe.blur_full_fbo.take() {
        gl.delete_framebuffer(Some(&fbo));
    }
    if let Some(tex) = pipe.blur_full_tex.take() {
        gl.delete_texture(Some(&tex));
    }
    let hw: u32 = (w / 2).max(1);
    let hh: u32 = (h / 2).max(1);
    let (Some((sfbo, stex)), Some((hfbo, htex)), Some((ffbo, ftex))) = (
        web_create_gl2_fbo_target(gl, w, h),
        web_create_gl2_fbo_target(gl, hw, hh),
        web_create_gl2_fbo_target(gl, w, h),
    ) else {
        pipe.blur_dims = (0, 0);
        return false;
    };
    pipe.blur_scene_fbo = Some(sfbo);
    pipe.blur_scene_tex = Some(stex);
    pipe.blur_half_fbo = Some(hfbo);
    pipe.blur_half_tex = Some(htex);
    pipe.blur_full_fbo = Some(ffbo);
    pipe.blur_full_tex = Some(ftex);
    pipe.blur_dims = (w, h);
    true
}

/// Lazily compiles the WebGL2 hardware Ocean + Origami Boat and Instanced Depth-Buffered 3D PBR pipelines.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
///
/// # Returns
///
/// - `Option<WebGl2ScenePipeline>` - Compiled hardware scene pipeline bundle.
fn web_init_gl2_scene_pipeline(gl: &WebGl2RenderingContext) -> Option<WebGl2ScenePipeline> {
    let ocean_program: WebGlProgram =
        web_compile_gl2_program(gl, WEB_GL2_SCENE_FULLSCREEN_VERT, WEB_GL2_SCENE_OCEAN_FRAG)?;
    gl.use_program(Some(&ocean_program));
    if let Some(loc) = gl.get_uniform_location(&ocean_program, WEB_GL2_SCENE_UNIFORM_WAKE_TEX) {
        gl.uniform1i(Some(&loc), 0);
    }
    let ocean_time_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&ocean_program, WEB_GL2_SCENE_UNIFORM_OCEAN_TIME);
    let ocean_roll_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&ocean_program, WEB_GL2_SCENE_UNIFORM_OCEAN_ROLL);
    let ocean_sun_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&ocean_program, WEB_GL2_SCENE_UNIFORM_OCEAN_SUN);
    let boat_program: WebGlProgram =
        web_compile_gl2_program(gl, WEB_GL2_SCENE_BOAT_VERT, WEB_GL2_SCENE_BOAT_FRAG)?;
    let boat_vao: WebGlVertexArrayObject = gl.create_vertex_array()?;
    let boat_vbo: WebGlBuffer = gl.create_buffer()?;
    gl.bind_vertex_array(Some(&boat_vao));
    gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&boat_vbo));
    gl.enable_vertex_attrib_array(0);
    gl.vertex_attrib_pointer_with_i32(0, 4, WebGl2RenderingContext::FLOAT, false, 32, 0);
    gl.enable_vertex_attrib_array(1);
    gl.vertex_attrib_pointer_with_i32(1, 4, WebGl2RenderingContext::FLOAT, false, 32, 16);
    gl.bind_vertex_array(None);
    let sky3d_program: WebGlProgram =
        web_compile_gl2_program(gl, WEB_GL2_SCENE_FULLSCREEN_VERT, WEB_GL2_SCENE_3D_SKY_FRAG)?;
    let sky3d_vp_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&sky3d_program, WEB_GL2_SCENE_UNIFORM_VIEW_PROJ);
    let sky3d_cam_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&sky3d_program, WEB_GL2_SCENE_UNIFORM_CAM_POS);
    let sky3d_sun_dir_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&sky3d_program, WEB_GL2_SCENE_UNIFORM_SUN_FOG);
    let sky3d_sun_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&sky3d_program, WEB_GL2_SCENE_UNIFORM_SUN_COL);
    let sky3d_hor_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&sky3d_program, WEB_GL2_SCENE_UNIFORM_SKY_HOR);
    let sky3d_zen_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&sky3d_program, WEB_GL2_SCENE_UNIFORM_SKY_ZEN);
    let mesh3d_program: WebGlProgram =
        web_compile_gl2_program(gl, WEB_GL2_SCENE_3D_MESH_VERT, WEB_GL2_SCENE_3D_MESH_FRAG)?;
    let mesh3d_vp_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&mesh3d_program, WEB_GL2_SCENE_UNIFORM_VIEW_PROJ);
    let mesh3d_cam_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&mesh3d_program, WEB_GL2_SCENE_UNIFORM_CAM_POS);
    let mesh3d_sun_fog_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&mesh3d_program, WEB_GL2_SCENE_UNIFORM_SUN_FOG);
    let mesh3d_sun_col_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&mesh3d_program, WEB_GL2_SCENE_UNIFORM_SUN_COL);
    let mesh3d_hor_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&mesh3d_program, WEB_GL2_SCENE_UNIFORM_SKY_HOR);
    let mesh3d_zen_loc: Option<WebGlUniformLocation> =
        gl.get_uniform_location(&mesh3d_program, WEB_GL2_SCENE_UNIFORM_SKY_ZEN);
    let mesh3d_vao: WebGlVertexArrayObject = gl.create_vertex_array()?;
    let mesh3d_vert_vbo: WebGlBuffer = gl.create_buffer()?;
    let mesh3d_inst_vbo: WebGlBuffer = gl.create_buffer()?;
    gl.bind_vertex_array(Some(&mesh3d_vao));
    gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&mesh3d_vert_vbo));
    for attr_idx in 0u32..3u32 {
        gl.enable_vertex_attrib_array(attr_idx);
        gl.vertex_attrib_pointer_with_i32(
            attr_idx,
            4,
            WebGl2RenderingContext::FLOAT,
            false,
            48,
            (attr_idx * 16) as i32,
        );
        gl.vertex_attrib_divisor(attr_idx, 0);
    }
    gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&mesh3d_inst_vbo));
    for slot in 0u32..6u32 {
        let loc: u32 = 3 + slot;
        gl.enable_vertex_attrib_array(loc);
        gl.vertex_attrib_pointer_with_i32(
            loc,
            4,
            WebGl2RenderingContext::FLOAT,
            false,
            96,
            (slot * 16) as i32,
        );
        gl.vertex_attrib_divisor(loc, 1);
    }
    gl.bind_vertex_array(None);
    let (scene_fbo, scene_color_tex): (WebGlFramebuffer, WebGlTexture) =
        web_create_gl2_fbo_target(gl, 64, 64)?;
    let scene_depth_rbo: WebGlRenderbuffer = gl.create_renderbuffer()?;
    gl.bind_renderbuffer(WebGl2RenderingContext::RENDERBUFFER, Some(&scene_depth_rbo));
    gl.renderbuffer_storage(
        WebGl2RenderingContext::RENDERBUFFER,
        WebGl2RenderingContext::DEPTH_COMPONENT24,
        64,
        64,
    );
    gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, Some(&scene_fbo));
    gl.framebuffer_renderbuffer(
        WebGl2RenderingContext::FRAMEBUFFER,
        WebGl2RenderingContext::DEPTH_ATTACHMENT,
        WebGl2RenderingContext::RENDERBUFFER,
        Some(&scene_depth_rbo),
    );
    gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, None);
    let wake_tex: WebGlTexture = gl.create_texture()?;
    gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(&wake_tex));
    gl.tex_parameteri(
        WebGl2RenderingContext::TEXTURE_2D,
        WebGl2RenderingContext::TEXTURE_MIN_FILTER,
        WebGl2RenderingContext::LINEAR as i32,
    );
    gl.tex_parameteri(
        WebGl2RenderingContext::TEXTURE_2D,
        WebGl2RenderingContext::TEXTURE_MAG_FILTER,
        WebGl2RenderingContext::LINEAR as i32,
    );
    gl.tex_parameteri(
        WebGl2RenderingContext::TEXTURE_2D,
        WebGl2RenderingContext::TEXTURE_WRAP_S,
        WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
    );
    gl.tex_parameteri(
        WebGl2RenderingContext::TEXTURE_2D,
        WebGl2RenderingContext::TEXTURE_WRAP_T,
        WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
    );
    Some(WebGl2ScenePipeline {
        ocean_program,
        ocean_time_loc,
        ocean_roll_loc,
        ocean_sun_loc,
        boat_program,
        boat_vao,
        boat_vbo,
        boat_vbo_cap: 0,
        sky3d_program,
        sky3d_vp_loc,
        sky3d_cam_loc,
        sky3d_sun_dir_loc,
        sky3d_sun_loc,
        sky3d_hor_loc,
        sky3d_zen_loc,
        mesh3d_program,
        mesh3d_vp_loc,
        mesh3d_cam_loc,
        mesh3d_sun_fog_loc,
        mesh3d_sun_col_loc,
        mesh3d_hor_loc,
        mesh3d_zen_loc,
        mesh3d_vao,
        mesh3d_vert_vbo,
        mesh3d_vert_rev: 0,
        mesh3d_vert_cap: 0,
        mesh3d_inst_vbo,
        mesh3d_inst_cap: 0,
        mesh3d_inst_base_off: 0,
        scene_fbo,
        scene_color_tex,
        scene_depth_rbo,
        scene_dims: (64, 64),
        wake_tex,
        wake_dims: (0, 0),
    })
}

/// Computes the union normalized UV bounds `[u0, v0_top, u1, v1_bot]` of all `PrimKind::ExternalGpuSurface` primitives intersecting one tile surface slice, or `None` when the tile does not touch the scene viewport.
///
/// # Arguments
///
/// - `&GpuFrameSubmission` - Direct-GPU frame payload.
/// - `(f32, f32)` - Physical pixel origin `(tile_origin_x, tile_origin_y)` of this surface slice.
/// - `(i32, i32)` - Active drawing buffer `(draw_w, draw_h)` in physical pixels.
///
/// # Returns
///
/// - `Option<[f32; 4]>` - Normalized top-down UV sub-rect `[u0, v0_top, u1, v1_bot]` in `[0.0, 1.0]`, or `None` when this tile skips the scene pass.
#[must_use]
fn web_scene_pass_tile_uv_bounds(
    submission: &GpuFrameSubmission,
    tile_origin: (f32, f32),
    draw_dims: (i32, i32),
) -> Option<[f32; 4]> {
    let tile_x0: f32 = tile_origin.0;
    let tile_y0: f32 = tile_origin.1;
    let tile_x1: f32 = tile_x0 + (draw_dims.0.max(1) as f32);
    let tile_y1: f32 = tile_y0 + (draw_dims.1.max(1) as f32);
    let mut found: bool = false;
    let mut min_u: f32 = 1.0;
    let mut min_v: f32 = 1.0;
    let mut max_u: f32 = 0.0;
    let mut max_v: f32 = 0.0;
    for batch in submission.get_batches().iter() {
        for prim in batch.get_primitives().iter() {
            if prim.prim_kind() != PrimKind::ExternalGpuSurface {
                continue;
            }
            let rect: [f32; 4] = prim.get_rect();
            let clip: [f32; 4] = prim.get_clip_rect();
            let qw: f32 = rect[2];
            let qh: f32 = rect[3];
            if qw <= 0.0 || qh <= 0.0 {
                continue;
            }
            let qx0: f32 = rect[0];
            let qy0: f32 = rect[1];
            let qx1: f32 = qx0 + qw;
            let qy1: f32 = qy0 + qh;
            let vx0: f32 = qx0.max(clip[0]).max(tile_x0);
            let vy0: f32 = qy0.max(clip[1]).max(tile_y0);
            let vx1: f32 = qx1.min(clip[2]).min(tile_x1);
            let vy1: f32 = qy1.min(clip[3]).min(tile_y1);
            if vx1 <= vx0 || vy1 <= vy0 {
                continue;
            }
            let u0: f32 = ((vx0 - qx0) / qw).clamp(0.0, 1.0);
            let v0: f32 = ((vy0 - qy0) / qh).clamp(0.0, 1.0);
            let u1: f32 = ((vx1 - qx0) / qw).clamp(0.0, 1.0);
            let v1: f32 = ((vy1 - qy0) / qh).clamp(0.0, 1.0);
            if u1 <= u0 || v1 <= v0 {
                continue;
            }
            min_u = min_u.min(u0);
            min_v = min_v.min(v0);
            max_u = max_u.max(u1);
            max_v = max_v.max(v1);
            found = true;
        }
    }
    if found {
        Some([min_u, min_v, max_u, max_v])
    } else {
        None
    }
}

/// Returns whether any visible `PrimKind::BackdropBlur` primitive in `submission` intersects one tile surface slice.
///
/// # Arguments
///
/// - `&GpuFrameSubmission` - Direct-GPU frame payload.
/// - `(f32, f32)` - Physical pixel origin `(tile_origin_x, tile_origin_y)` of this surface slice.
/// - `(i32, i32)` - Active drawing buffer `(draw_w, draw_h)` in physical pixels.
///
/// # Returns
///
/// - `bool` - `true` when at least one `BackdropBlur` primitive intersects this tile.
#[must_use]
fn web_tile_has_backdrop_blur(
    submission: &GpuFrameSubmission,
    tile_origin: (f32, f32),
    draw_dims: (i32, i32),
) -> bool {
    let tile_x0: f32 = tile_origin.0;
    let tile_y0: f32 = tile_origin.1;
    let tile_x1: f32 = tile_x0 + (draw_dims.0.max(1) as f32);
    let tile_y1: f32 = tile_y0 + (draw_dims.1.max(1) as f32);
    for batch in submission.get_batches().iter() {
        for prim in batch.get_primitives().iter() {
            if prim.prim_kind() != PrimKind::BackdropBlur {
                continue;
            }
            let rect: [f32; 4] = prim.get_rect();
            let clip: [f32; 4] = prim.get_clip_rect();
            let vx0: f32 = rect[0].max(clip[0]).max(tile_x0);
            let vy0: f32 = rect[1].max(clip[1]).max(tile_y0);
            let vx1: f32 = (rect[0] + rect[2]).min(clip[2]).min(tile_x1);
            let vy1: f32 = (rect[1] + rect[3]).min(clip[3]).min(tile_y1);
            if vx1 > vx0 && vy1 > vy0 {
                return true;
            }
        }
    }
    false
}

/// Synchronizes the primary canvas `data-euv-tiled` DOM attribute only when the active tile grid `(columns, rows)` transitions, avoiding per-frame DOM writes.
///
/// # Arguments
///
/// - `Option<&HtmlCanvasElement>` - Primary foreground `<canvas>` element.
/// - `&mut (u32, u32)` - Cached previously applied `(columns, rows)` grid state.
/// - `u32` - Active tile column count (`1` when single-canvas untiled).
/// - `u32` - Active tile row count (`1` when single-canvas untiled).
pub(crate) fn web_sync_canvas_tiled_attr(
    canvas: Option<&HtmlCanvasElement>,
    active_tile_grid: &mut (u32, u32),
    columns: u32,
    rows: u32,
) {
    let next_grid: (u32, u32) = (columns.max(1), rows.max(1));
    if *active_tile_grid == next_grid {
        return;
    }
    if let Some(el) = canvas {
        if next_grid.0 > 1 || next_grid.1 > 1 {
            let label: String = format!("{}x{}", next_grid.0, next_grid.1);
            drop(el.set_attribute(WEB_ATTR_DATA_TILED, &label));
        } else {
            drop(el.remove_attribute(WEB_ATTR_DATA_TILED));
        }
    }
    *active_tile_grid = next_grid;
}

/// Executes a hardware WebGL2 `OceanFluid` or `World3d` offscreen scene pass into `scene.scene_color_tex` with optional partial-tile scissoring and zero CPU pixel rasterization.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
/// - `&mut WebGl2ScenePipeline` - Compiled hardware scene pipeline bundle.
/// - `u32` - Active `GL_MAX_TEXTURE_SIZE`.
/// - `&DirectGpuScenePass` - Hardware ocean or 3D scene pass payload.
/// - `[f32; 4]` - Normalized top-down UV bounds `[u0, v0_top, u1, v1_bot]` needed by the active tile.
fn web_execute_gl2_scene_pass(
    gl: &WebGl2RenderingContext,
    scene: &mut WebGl2ScenePipeline,
    max_tex_dim: u32,
    pass: &DirectGpuScenePass,
    uv_bounds: [f32; 4],
) {
    let max_dim: u32 = max_tex_dim.clamp(256, WEB_GL2_MAX_SINGLE_SURFACE_DIM);
    let (req_w, req_h): (u32, u32) = match pass {
        DirectGpuScenePass::OceanFluid(ocean) => (
            ocean.get_target_width().clamp(64, max_dim),
            ocean.get_target_height().clamp(64, max_dim),
        ),
        DirectGpuScenePass::World3d(world) => (
            world.get_target_width().clamp(64, max_dim),
            world.get_target_height().clamp(64, max_dim),
        ),
    };
    if scene.scene_dims != (req_w, req_h) {
        gl.bind_texture(
            WebGl2RenderingContext::TEXTURE_2D,
            Some(&scene.scene_color_tex),
        );
        let _: Result<(), JsValue> = gl
            .tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
                WebGl2RenderingContext::TEXTURE_2D,
                0,
                WebGl2RenderingContext::RGBA8 as i32,
                req_w as i32,
                req_h as i32,
                0,
                WebGl2RenderingContext::RGBA,
                WebGl2RenderingContext::UNSIGNED_BYTE,
                None,
            );
        gl.bind_renderbuffer(
            WebGl2RenderingContext::RENDERBUFFER,
            Some(&scene.scene_depth_rbo),
        );
        gl.renderbuffer_storage(
            WebGl2RenderingContext::RENDERBUFFER,
            WebGl2RenderingContext::DEPTH_COMPONENT24,
            req_w as i32,
            req_h as i32,
        );
        scene.scene_dims = (req_w, req_h);
    }
    gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, Some(&scene.scene_fbo));
    let [u0, v0_top, u1, v1_bot]: [f32; 4] = uv_bounds;
    let has_full_uv: bool = u0 <= 0.0005 && v0_top <= 0.0005 && u1 >= 0.9995 && v1_bot >= 0.9995;
    let use_scissor: bool = !has_full_uv;
    if use_scissor {
        let fbo_w_f: f32 = req_w as f32;
        let fbo_h_f: f32 = req_h as f32;
        let fbo_w_i: i32 = req_w as i32;
        let fbo_h_i: i32 = req_h as i32;
        let sc_x0: i32 =
            ((u0 * fbo_w_f).floor() as i32 - WEB_GL2_SCENE_SCISSOR_PAD_PX).clamp(0, fbo_w_i);
        let sc_x1: i32 =
            ((u1 * fbo_w_f).ceil() as i32 + WEB_GL2_SCENE_SCISSOR_PAD_PX).clamp(0, fbo_w_i);
        let sc_y0: i32 = (((1.0 - v1_bot) * fbo_h_f).floor() as i32 - WEB_GL2_SCENE_SCISSOR_PAD_PX)
            .clamp(0, fbo_h_i);
        let sc_y1: i32 = (((1.0 - v0_top) * fbo_h_f).ceil() as i32 + WEB_GL2_SCENE_SCISSOR_PAD_PX)
            .clamp(0, fbo_h_i);
        let sc_w: i32 = sc_x1 - sc_x0;
        let sc_h: i32 = sc_y1 - sc_y0;
        if sc_w <= 0 || sc_h <= 0 {
            gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, None);
            return;
        }
        gl.enable(WebGl2RenderingContext::SCISSOR_TEST);
        gl.scissor(sc_x0, sc_y0, sc_w, sc_h);
    } else {
        gl.disable(WebGl2RenderingContext::SCISSOR_TEST);
    }
    gl.viewport(0, 0, req_w as i32, req_h as i32);
    match pass {
        DirectGpuScenePass::OceanFluid(ocean) => {
            let wake_w: u32 = ocean.get_wake_width().max(1);
            let wake_h: u32 = ocean.get_wake_height().max(1);
            let wake_bytes: &[u8] = ocean.get_wake_rgba8().as_slice();
            let req_wake: usize = (wake_w as usize)
                .saturating_mul(wake_h as usize)
                .saturating_mul(4);
            if wake_bytes.len() >= req_wake
                && (scene.wake_dims != (wake_w, wake_h) || ocean.get_has_active_wake())
            {
                gl.active_texture(WebGl2RenderingContext::TEXTURE0);
                gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(&scene.wake_tex));
                web_configure_gl2_unpack_state(gl);
                gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
                gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
                gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
                // SAFETY: `wake_bytes` remains valid in WASM linear memory for synchronous upload.
                let view: Uint8Array = unsafe { Uint8Array::view(wake_bytes) };
                if scene.wake_dims != (wake_w, wake_h) {
                    let _: Result<(), JsValue> = gl
                        .tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
                            WebGl2RenderingContext::TEXTURE_2D,
                            0,
                            WebGl2RenderingContext::RGBA8 as i32,
                            wake_w as i32,
                            wake_h as i32,
                            0,
                            WebGl2RenderingContext::RGBA,
                            WebGl2RenderingContext::UNSIGNED_BYTE,
                            Some(view.as_ref()),
                        );
                    scene.wake_dims = (wake_w, wake_h);
                } else {
                    let _: Result<(), JsValue> = gl
                        .tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
                            WebGl2RenderingContext::TEXTURE_2D,
                            0,
                            0,
                            0,
                            wake_w as i32,
                            wake_h as i32,
                            WebGl2RenderingContext::RGBA,
                            WebGl2RenderingContext::UNSIGNED_BYTE,
                            Some(view.as_ref()),
                        );
                }
            }
            gl.disable(WebGl2RenderingContext::DEPTH_TEST);
            gl.disable(WebGl2RenderingContext::BLEND);
            gl.use_program(Some(&scene.ocean_program));
            gl.active_texture(WebGl2RenderingContext::TEXTURE0);
            gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(&scene.wake_tex));
            let boat_uv: [f32; 2] = ocean.get_boat_uv();
            let sun: [f32; 3] = ocean.get_sun_dir();
            if let Some(loc) = scene.ocean_time_loc.as_ref() {
                gl.uniform4f(
                    Some(loc),
                    ocean.get_sim_time(),
                    ocean.get_agitation(),
                    ocean.get_horizon_v(),
                    ocean.get_aspect(),
                );
            }
            if let Some(loc) = scene.ocean_roll_loc.as_ref() {
                gl.uniform4f(
                    Some(loc),
                    ocean.get_roll_cos(),
                    ocean.get_roll_sin(),
                    boat_uv[0],
                    boat_uv[1],
                );
            }
            if let Some(loc) = scene.ocean_sun_loc.as_ref() {
                gl.uniform4f(
                    Some(loc),
                    sun[0],
                    sun[1],
                    sun[2],
                    if ocean.get_has_active_wake() {
                        1.0
                    } else {
                        0.0
                    },
                );
            }
            gl.bind_vertex_array(None);
            gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
            let boat_verts: &[GpuOceanBoatVertex] = ocean.get_boat_vertices().as_slice();
            if !boat_verts.is_empty() {
                let byte_len: usize = size_of_val(boat_verts);
                // SAFETY: `GpuOceanBoatVertex` is `#[repr(C)]` 32 bytes with no padding.
                let raw: &[u8] =
                    unsafe { from_raw_parts(boat_verts.as_ptr().cast::<u8>(), byte_len) };
                // SAFETY: `raw` remains valid during synchronous `bufferSubData`.
                let view: Uint8Array = unsafe { Uint8Array::view(raw) };
                gl.enable(WebGl2RenderingContext::BLEND);
                gl.blend_func_separate(
                    WebGl2RenderingContext::SRC_ALPHA,
                    WebGl2RenderingContext::ONE_MINUS_SRC_ALPHA,
                    WebGl2RenderingContext::ONE,
                    WebGl2RenderingContext::ONE_MINUS_SRC_ALPHA,
                );
                gl.use_program(Some(&scene.boat_program));
                gl.bind_vertex_array(Some(&scene.boat_vao));
                gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&scene.boat_vbo));
                if byte_len > scene.boat_vbo_cap {
                    let cap: usize = byte_len.max(1024).next_power_of_two();
                    gl.buffer_data_with_i32(
                        WebGl2RenderingContext::ARRAY_BUFFER,
                        cap as i32,
                        WebGl2RenderingContext::STREAM_DRAW,
                    );
                    scene.boat_vbo_cap = cap;
                }
                gl.buffer_sub_data_with_i32_and_array_buffer_view(
                    WebGl2RenderingContext::ARRAY_BUFFER,
                    0,
                    view.as_ref(),
                );
                gl.draw_arrays(
                    WebGl2RenderingContext::TRIANGLES,
                    0,
                    boat_verts.len() as i32,
                );
                gl.bind_vertex_array(None);
            }
        }
        DirectGpuScenePass::World3d(world) => {
            let cam: [f32; 4] = world.get_camera_pos();
            let sun_fog: [f32; 4] = world.get_sun_dir_fog();
            let sun_col: [f32; 4] = world.get_sun_color_ambient();
            let sky_hor: [f32; 4] = world.get_sky_horizon_tod();
            let sky_zen: [f32; 4] = world.get_sky_zenith_aspect();
            gl.disable(WebGl2RenderingContext::BLEND);
            gl.depth_mask(true);
            gl.clear_depth(1.0);
            gl.clear_color(0.04, 0.05, 0.09, 1.0);
            gl.clear(
                WebGl2RenderingContext::COLOR_BUFFER_BIT | WebGl2RenderingContext::DEPTH_BUFFER_BIT,
            );
            gl.disable(WebGl2RenderingContext::DEPTH_TEST);
            gl.depth_mask(false);
            gl.use_program(Some(&scene.sky3d_program));
            let sky_vp: [f32; 16] = world.get_view_proj();
            gl.uniform_matrix4fv_with_f32_array(scene.sky3d_vp_loc.as_ref(), false, &sky_vp);
            if let Some(loc) = scene.sky3d_cam_loc.as_ref() {
                gl.uniform4f(Some(loc), cam[0], cam[1], cam[2], cam[3]);
            }
            if let Some(loc) = scene.sky3d_sun_dir_loc.as_ref() {
                gl.uniform4f(Some(loc), sun_fog[0], sun_fog[1], sun_fog[2], sun_fog[3]);
            }
            if let Some(loc) = scene.sky3d_sun_loc.as_ref() {
                gl.uniform4f(Some(loc), sun_col[0], sun_col[1], sun_col[2], sun_col[3]);
            }
            if let Some(loc) = scene.sky3d_hor_loc.as_ref() {
                gl.uniform4f(Some(loc), sky_hor[0], sky_hor[1], sky_hor[2], sky_hor[3]);
            }
            if let Some(loc) = scene.sky3d_zen_loc.as_ref() {
                gl.uniform4f(Some(loc), sky_zen[0], sky_zen[1], sky_zen[2], sky_zen[3]);
            }
            gl.bind_vertex_array(None);
            gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
            let verts: &[GpuWorld3dVertex] = world.get_mesh_buffer().get_vertices().as_slice();
            let insts: &[GpuWorld3dInstance] = world.get_instances().as_slice();
            if !verts.is_empty() && !insts.is_empty() {
                let mesh_rev: u64 = world.get_mesh_buffer().get_revision();
                gl.bind_vertex_array(Some(&scene.mesh3d_vao));
                if scene.mesh3d_vert_rev != mesh_rev || scene.mesh3d_vert_cap == 0 {
                    let vbytes: usize = size_of_val(verts);
                    // SAFETY: `GpuWorld3dVertex` is `#[repr(C)]` 48 bytes with no padding.
                    let raw_v: &[u8] =
                        unsafe { from_raw_parts(verts.as_ptr().cast::<u8>(), vbytes) };
                    // SAFETY: `raw_v` stays valid during synchronous `bufferData`.
                    let vview: Uint8Array = unsafe { Uint8Array::view(raw_v) };
                    gl.bind_buffer(
                        WebGl2RenderingContext::ARRAY_BUFFER,
                        Some(&scene.mesh3d_vert_vbo),
                    );
                    if vbytes > scene.mesh3d_vert_cap {
                        let cap: usize = vbytes.max(4096).next_power_of_two();
                        gl.buffer_data_with_i32(
                            WebGl2RenderingContext::ARRAY_BUFFER,
                            cap as i32,
                            WebGl2RenderingContext::STATIC_DRAW,
                        );
                        scene.mesh3d_vert_cap = cap;
                    }
                    gl.buffer_sub_data_with_i32_and_array_buffer_view(
                        WebGl2RenderingContext::ARRAY_BUFFER,
                        0,
                        vview.as_ref(),
                    );
                    scene.mesh3d_vert_rev = mesh_rev;
                }
                let ibytes: usize = size_of_val(insts);
                // SAFETY: `GpuWorld3dInstance` is `#[repr(C)]` 96 bytes with no padding.
                let raw_i: &[u8] = unsafe { from_raw_parts(insts.as_ptr().cast::<u8>(), ibytes) };
                // SAFETY: `raw_i` stays valid during synchronous `bufferSubData`.
                let iview: Uint8Array = unsafe { Uint8Array::view(raw_i) };
                gl.bind_buffer(
                    WebGl2RenderingContext::ARRAY_BUFFER,
                    Some(&scene.mesh3d_inst_vbo),
                );
                if ibytes > scene.mesh3d_inst_cap {
                    let cap: usize = ibytes.max(4096).next_power_of_two();
                    gl.buffer_data_with_i32(
                        WebGl2RenderingContext::ARRAY_BUFFER,
                        cap as i32,
                        WebGl2RenderingContext::STREAM_DRAW,
                    );
                    scene.mesh3d_inst_cap = cap;
                }
                gl.buffer_sub_data_with_i32_and_array_buffer_view(
                    WebGl2RenderingContext::ARRAY_BUFFER,
                    0,
                    iview.as_ref(),
                );
                gl.enable(WebGl2RenderingContext::DEPTH_TEST);
                gl.depth_func(WebGl2RenderingContext::LESS);
                gl.depth_mask(true);
                gl.use_program(Some(&scene.mesh3d_program));
                let vp: [f32; 16] = world.get_view_proj();
                gl.uniform_matrix4fv_with_f32_array(scene.mesh3d_vp_loc.as_ref(), false, &vp);
                if let Some(loc) = scene.mesh3d_cam_loc.as_ref() {
                    gl.uniform4f(Some(loc), cam[0], cam[1], cam[2], cam[3]);
                }
                if let Some(loc) = scene.mesh3d_sun_fog_loc.as_ref() {
                    gl.uniform4f(Some(loc), sun_fog[0], sun_fog[1], sun_fog[2], sun_fog[3]);
                }
                if let Some(loc) = scene.mesh3d_sun_col_loc.as_ref() {
                    gl.uniform4f(Some(loc), sun_col[0], sun_col[1], sun_col[2], sun_col[3]);
                }
                if let Some(loc) = scene.mesh3d_hor_loc.as_ref() {
                    gl.uniform4f(Some(loc), sky_hor[0], sky_hor[1], sky_hor[2], sky_hor[3]);
                }
                if let Some(loc) = scene.mesh3d_zen_loc.as_ref() {
                    gl.uniform4f(Some(loc), sky_zen[0], sky_zen[1], sky_zen[2], sky_zen[3]);
                }
                for batch in world.get_draw_batches().iter() {
                    if batch.get_vertex_count() == 0 || batch.get_instance_count() == 0 {
                        continue;
                    }
                    let base_byte_off: i32 = (batch.get_instance_start() as i32).saturating_mul(96);
                    if scene.mesh3d_inst_base_off != base_byte_off {
                        for slot in 0u32..6u32 {
                            gl.vertex_attrib_pointer_with_i32(
                                3 + slot,
                                4,
                                WebGl2RenderingContext::FLOAT,
                                false,
                                96,
                                base_byte_off + (slot as i32) * 16,
                            );
                        }
                        scene.mesh3d_inst_base_off = base_byte_off;
                    }
                    gl.draw_arrays_instanced(
                        WebGl2RenderingContext::TRIANGLES,
                        batch.get_vertex_start() as i32,
                        batch.get_vertex_count() as i32,
                        batch.get_instance_count() as i32,
                    );
                }
                gl.bind_vertex_array(None);
                gl.disable(WebGl2RenderingContext::DEPTH_TEST);
            }
        }
    }
    if use_scissor {
        gl.disable(WebGl2RenderingContext::SCISSOR_TEST);
    }
    gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, None);
}

/// Creates a sibling non-interactive WebGL2 tile `<canvas>` mounted alongside `parent_canvas` for tiled presentation above `GL_MAX_TEXTURE_SIZE`.
///
/// # Arguments
///
/// - `Option<&HtmlCanvasElement>` - Main foreground canvas whose parent element hosts sibling tile canvases.
/// - `u32` - Tile physical width in device pixels.
/// - `u32` - Tile physical height in device pixels.
///
/// # Returns
///
/// - `Option<WebGl2TileCanvas>` - Ready tile canvas with compiled instanced WebGL2 pipeline.
fn web_create_gl2_tile_canvas(
    parent_canvas: Option<&HtmlCanvasElement>,
    tile_w: u32,
    tile_h: u32,
) -> Option<WebGl2TileCanvas> {
    let win: Window = window()?;
    let doc: Document = win.document()?;
    let el: Element = doc.create_element(WEB_CANVAS_TAG).ok()?;
    let canvas: HtmlCanvasElement = el.dyn_into::<HtmlCanvasElement>().ok()?;
    canvas.set_width(tile_w.max(1));
    canvas.set_height(tile_h.max(1));
    drop(canvas.set_attribute(WEB_ATTR_CANVAS_ROLE, WEB_CANVAS_ROLE_TILE));
    if let Some(parent) =
        parent_canvas.and_then(|main_el: &HtmlCanvasElement| main_el.parent_element())
    {
        drop(parent.append_child(&canvas));
    } else if let Some(body) = doc.body() {
        drop(body.append_child(&canvas));
    }
    let gl_opts: Object = web_gl2_context_options();
    let raw_gl: Object = canvas
        .get_context_with_context_options(WEB_CONTEXT_WEBGL2, gl_opts.as_ref())
        .ok()
        .flatten()?;
    let gl2: WebGl2RenderingContext = raw_gl.dyn_into::<WebGl2RenderingContext>().ok()?;
    let instanced: WebGl2InstancedPipeline = web_init_gl2_instanced_pipeline(&gl2)?;
    Some(WebGl2TileCanvas {
        canvas,
        gl2,
        instanced,
        last_style_geom: (u32::MAX, u32::MAX, 0, 0, 0, 0),
    })
}

/// Uploads full or dirty sub-rectangle updates of an RGBA8 image atlas onto `TEXTURE2` using cached `bindTexture` with zero per-frame `Reflect::get`.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
/// - `&mut WebGl2InstancedPipeline` - Persistent instanced pipeline owning `image_atlas_tex`.
/// - `&DirectGpuAtlasUpload` - RGBA8 image atlas payload.
/// - `&[PixelDirtyRect]` - Dirty sub-rectangles pending incremental upload.
fn web_sync_gl2_image_rgba8_atlas(
    gl: &WebGl2RenderingContext,
    pipe: &mut WebGl2InstancedPipeline,
    atlas: &DirectGpuAtlasUpload,
    dirty_rects: &[PixelDirtyRect],
) {
    let atlas_w: u32 = atlas.get_width();
    let atlas_h: u32 = atlas.get_height();
    let pixels: &[u8] = atlas.get_pixels().as_slice();
    let required: usize = (atlas_w as usize)
        .saturating_mul(atlas_h as usize)
        .saturating_mul(4);
    if atlas_w == 0 || atlas_h == 0 || pixels.len() < required {
        return;
    }
    let Some(tex) = pipe.image_atlas_tex.as_ref() else {
        return;
    };
    let target_val: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
    gl.active_texture(WebGl2RenderingContext::TEXTURE2);
    if let Some(bind_fn) = pipe.bind_texture_fn.as_ref() {
        drop(bind_fn.call2(gl.as_ref(), &target_val, tex));
    }
    web_configure_gl2_unpack_state(gl);
    let dims_changed: bool = pipe.image_atlas_w != atlas_w || pipe.image_atlas_h != atlas_h;
    if dims_changed || dirty_rects.is_empty() {
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
        // SAFETY: `pixels` stays valid in WASM linear memory for synchronous `texImage2D` upload.
        let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
        let _: Result<(), JsValue> = gl
            .tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
                WebGl2RenderingContext::TEXTURE_2D,
                0,
                WebGl2RenderingContext::RGBA8 as i32,
                atlas_w as i32,
                atlas_h as i32,
                0,
                WebGl2RenderingContext::RGBA,
                WebGl2RenderingContext::UNSIGNED_BYTE,
                Some(view.as_ref()),
            );
        pipe.image_atlas_w = atlas_w;
        pipe.image_atlas_h = atlas_h;
        return;
    }
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, atlas_w as i32);
    // SAFETY: `pixels` stays valid in WASM linear memory for synchronous `texSubImage2D` upload.
    let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
    for dirty in dirty_rects.iter() {
        let rx: u32 = dirty.get_x().min(atlas_w);
        let ry: u32 = dirty.get_y().min(atlas_h);
        let rw: u32 = dirty.get_width().min(atlas_w.saturating_sub(rx));
        let rh: u32 = dirty.get_height().min(atlas_h.saturating_sub(ry));
        if rw == 0 || rh == 0 {
            continue;
        }
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, rx as i32);
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, ry as i32);
        let _: Result<(), JsValue> = gl
            .tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
                WebGl2RenderingContext::TEXTURE_2D,
                0,
                rx as i32,
                ry as i32,
                rw as i32,
                rh as i32,
                WebGl2RenderingContext::RGBA,
                WebGl2RenderingContext::UNSIGNED_BYTE,
                Some(view.as_ref()),
            );
    }
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
    gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
}

/// Renders `submission` onto one WebGL2 drawing buffer (`draw_w x draw_h`) at physical pixel origin `tile_origin`, executing GPU scene passes and Dual-Kawase blur natively on GPU.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Target WebGL2 context.
/// - `&mut WebGl2InstancedPipeline` - Instanced uber-shader pipeline owning atlases, blur FBOs, and lazy scene shaders.
/// - `&GpuFrameSubmission` - Direct-GPU frame payload.
/// - `(i32, i32)` - Active drawing buffer `(draw_w, draw_h)` in physical pixels.
/// - `(f32, f32)` - Physical pixel origin `(tile_origin_x, tile_origin_y)` of this surface slice.
/// - `(Option<&DirectGpuAtlasUpload>, u64, bool)` - Cached window R8 glyph atlas snapshot, revision, and incoming-frame flag.
/// - `(Option<&DirectGpuAtlasUpload>, u64, bool)` - Cached window RGBA8 image atlas snapshot, revision, and incoming-frame flag.
///
/// # Returns
///
/// - `(usize, u32)` - Tuple `(draw_calls, primitive_count)`.
fn web_draw_gl2_instanced_on_surface(
    gl: &WebGl2RenderingContext,
    pipe: &mut WebGl2InstancedPipeline,
    submission: &GpuFrameSubmission,
    draw_dims: (i32, i32),
    tile_origin: (f32, f32),
    glyph_cache: (Option<&DirectGpuAtlasUpload>, u64, bool),
    image_cache: (Option<&DirectGpuAtlasUpload>, u64, bool),
) -> (usize, u32) {
    let (draw_w, draw_h): (i32, i32) = draw_dims;
    let (tile_ox, tile_oy): (f32, f32) = tile_origin;
    let (glyph_snap, glyph_rev, glyph_incoming): (Option<&DirectGpuAtlasUpload>, u64, bool) =
        glyph_cache;
    let (image_snap, image_rev, image_incoming): (Option<&DirectGpuAtlasUpload>, u64, bool) =
        image_cache;
    if glyph_rev > 0
        && pipe.synced_glyph_r8_rev != glyph_rev
        && let Some(glyph_atlas) = glyph_snap
    {
        let incremental_ok: bool = glyph_incoming
            && pipe.synced_glyph_r8_rev > 0
            && pipe.synced_glyph_r8_rev.wrapping_add(1) == glyph_rev;
        let dirty_slice: &[PixelDirtyRect] = if incremental_ok {
            submission.get_glyph_dirty_rects().as_slice()
        } else {
            &[]
        };
        web_sync_gl2_glyph_r8_atlas(gl, pipe, glyph_atlas, dirty_slice);
        pipe.synced_glyph_r8_rev = glyph_rev;
    }
    if image_rev > 0
        && pipe.synced_image_rgba8_rev != image_rev
        && let Some(image_atlas) = image_snap
    {
        let incremental_ok: bool = image_incoming
            && pipe.synced_image_rgba8_rev > 0
            && pipe.synced_image_rgba8_rev.wrapping_add(1) == image_rev;
        let dirty_slice: &[PixelDirtyRect] = if incremental_ok {
            submission.get_image_dirty_rects().as_slice()
        } else {
            &[]
        };
        web_sync_gl2_image_rgba8_atlas(gl, pipe, image_atlas, dirty_slice);
        pipe.synced_image_rgba8_rev = image_rev;
    }
    let mut active_scene_tex: Option<WebGlTexture> = None;
    if let Some(scene_pass) = submission.gpu_scene_pass_ref()
        && let Some(uv_bounds) = web_scene_pass_tile_uv_bounds(submission, tile_origin, draw_dims)
    {
        if pipe.scene_gl.is_none() {
            pipe.scene_gl = web_init_gl2_scene_pipeline(gl);
        }
        if let Some(scene_gl) = pipe.scene_gl.as_mut() {
            web_execute_gl2_scene_pass(gl, scene_gl, pipe.max_tex_dim, scene_pass, uv_bounds);
            active_scene_tex = Some(scene_gl.scene_color_tex.clone());
        }
    }
    let has_blur_batches: bool = pipe.blur_program.is_some()
        && web_tile_has_backdrop_blur(submission, tile_origin, draw_dims);
    let use_blur_fbo: bool =
        has_blur_batches && web_ensure_gl2_blur_targets(gl, pipe, draw_w as u32, draw_h as u32);
    if use_blur_fbo {
        gl.bind_framebuffer(
            WebGl2RenderingContext::FRAMEBUFFER,
            pipe.blur_scene_fbo.as_ref(),
        );
    } else {
        gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, None);
    }
    let target_val: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
    if let Some(bind_fn) = pipe.bind_texture_fn.as_ref() {
        if let Some(tex) = pipe.glyph_r8_tex.as_ref() {
            gl.active_texture(WebGl2RenderingContext::TEXTURE0);
            drop(bind_fn.call2(gl.as_ref(), &target_val, tex));
        }
        if let Some(tex) = pipe.glyph_rgba8_tex.as_ref() {
            gl.active_texture(WebGl2RenderingContext::TEXTURE1);
            drop(bind_fn.call2(gl.as_ref(), &target_val, tex));
        }
        if let Some(tex) = pipe.image_atlas_tex.as_ref() {
            gl.active_texture(WebGl2RenderingContext::TEXTURE2);
            drop(bind_fn.call2(gl.as_ref(), &target_val, tex));
        }
        if let Some(scene_tex) = active_scene_tex.as_ref() {
            gl.active_texture(WebGl2RenderingContext::TEXTURE3);
            gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(scene_tex));
        } else if let Some(tex) = pipe.external_tex.as_ref() {
            gl.active_texture(WebGl2RenderingContext::TEXTURE3);
            drop(bind_fn.call2(gl.as_ref(), &target_val, tex));
        }
    }
    let clear_color: Color = submission.get_clear_color();
    gl.viewport(0, 0, draw_w, draw_h);
    gl.disable(WebGl2RenderingContext::DEPTH_TEST);
    gl.enable(WebGl2RenderingContext::BLEND);
    gl.blend_func_separate(
        WebGl2RenderingContext::SRC_ALPHA,
        WebGl2RenderingContext::ONE_MINUS_SRC_ALPHA,
        WebGl2RenderingContext::ONE,
        WebGl2RenderingContext::ONE_MINUS_SRC_ALPHA,
    );
    gl.clear_color(
        f32::from(clear_color.get_red()) / 255.0,
        f32::from(clear_color.get_green()) / 255.0,
        f32::from(clear_color.get_blue()) / 255.0,
        f32::from(clear_color.get_alpha()) / 255.0,
    );
    gl.clear(WebGl2RenderingContext::COLOR_BUFFER_BIT);
    gl.use_program(Some(&pipe.program));
    if let Some(loc) = pipe.viewport_loc.as_ref() {
        gl.uniform2f(Some(loc), draw_w as f32, draw_h as f32);
    }
    if let Some(loc) = pipe.scroll_loc.as_ref() {
        gl.uniform2f(Some(loc), 0.0, 0.0);
    }
    if let Some(loc) = pipe.tile_origin_loc.as_ref() {
        gl.uniform2f(Some(loc), tile_ox, tile_oy);
    }
    gl.bind_vertex_array(Some(&pipe.vao));
    gl.bind_buffer(
        WebGl2RenderingContext::ARRAY_BUFFER,
        Some(&pipe.instance_vbo),
    );
    let mut draw_calls: usize = 0;
    let mut total_primitives: u32 = 0;
    let half_w: i32 = (draw_w / 2).max(1);
    let half_h: i32 = (draw_h / 2).max(1);
    for batch in submission.get_batches().iter() {
        let prims: &[GpuPrimitiveInstance] = batch.get_primitives().as_slice();
        if prims.is_empty() {
            continue;
        }
        let is_blur_batch: bool = use_blur_fbo
            && prims.iter().any(|prim_item: &GpuPrimitiveInstance| {
                prim_item.prim_kind() == PrimKind::BackdropBlur
            });
        if is_blur_batch
            && let (
                Some(bprog),
                Some(sfbo),
                Some(stex),
                Some(hfbo),
                Some(htex),
                Some(ffbo),
                Some(ftex),
            ) = (
                pipe.blur_program.as_ref(),
                pipe.blur_scene_fbo.as_ref(),
                pipe.blur_scene_tex.as_ref(),
                pipe.blur_half_fbo.as_ref(),
                pipe.blur_half_tex.as_ref(),
                pipe.blur_full_fbo.as_ref(),
                pipe.blur_full_tex.as_ref(),
            )
        {
            gl.disable(WebGl2RenderingContext::BLEND);
            gl.bind_vertex_array(None);
            gl.use_program(Some(bprog));
            gl.active_texture(WebGl2RenderingContext::TEXTURE0);
            gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, Some(hfbo));
            gl.viewport(0, 0, half_w, half_h);
            gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(stex));
            if let Some(loc) = pipe.blur_texel_loc.as_ref() {
                gl.uniform2f(
                    Some(loc),
                    1.0 / (draw_w.max(1) as f32),
                    1.0 / (draw_h.max(1) as f32),
                );
            }
            if let Some(loc) = pipe.blur_offset_loc.as_ref() {
                gl.uniform1f(Some(loc), 2.5);
            }
            if let Some(loc) = pipe.blur_mode_loc.as_ref() {
                gl.uniform1i(Some(loc), 0);
            }
            gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
            gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, Some(ffbo));
            gl.viewport(0, 0, draw_w, draw_h);
            gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(htex));
            if let Some(loc) = pipe.blur_texel_loc.as_ref() {
                gl.uniform2f(Some(loc), 1.0 / (half_w as f32), 1.0 / (half_h as f32));
            }
            if let Some(loc) = pipe.blur_mode_loc.as_ref() {
                gl.uniform1i(Some(loc), 1);
            }
            gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
            draw_calls = draw_calls.saturating_add(2);
            gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, Some(sfbo));
            gl.viewport(0, 0, draw_w, draw_h);
            gl.enable(WebGl2RenderingContext::BLEND);
            if let (Some(bind_fn), Some(r8_tex)) =
                (pipe.bind_texture_fn.as_ref(), pipe.glyph_r8_tex.as_ref())
            {
                gl.active_texture(WebGl2RenderingContext::TEXTURE0);
                drop(bind_fn.call2(gl.as_ref(), &target_val, r8_tex));
            }
            gl.active_texture(WebGl2RenderingContext::TEXTURE3);
            gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(ftex));
            gl.use_program(Some(&pipe.program));
            gl.bind_vertex_array(Some(&pipe.vao));
            gl.bind_buffer(
                WebGl2RenderingContext::ARRAY_BUFFER,
                Some(&pipe.instance_vbo),
            );
        }
        let byte_len: usize = prims.len().saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
        // SAFETY: `GpuPrimitiveInstance` is `#[repr(C)]` 64 bytes with no uninitialized padding.
        let raw_bytes: &[u8] = unsafe { from_raw_parts(prims.as_ptr().cast::<u8>(), byte_len) };
        // SAFETY: `raw_bytes` stays valid and immovable in WASM linear memory for the synchronous buffer upload.
        let view: Uint8Array = unsafe { Uint8Array::view(raw_bytes) };
        if byte_len > pipe.instance_vbo_cap_bytes {
            let next_cap: usize = byte_len.next_power_of_two();
            gl.buffer_data_with_i32(
                WebGl2RenderingContext::ARRAY_BUFFER,
                next_cap as i32,
                WebGl2RenderingContext::STREAM_DRAW,
            );
            pipe.instance_vbo_cap_bytes = next_cap;
        }
        gl.buffer_sub_data_with_i32_and_array_buffer_view(
            WebGl2RenderingContext::ARRAY_BUFFER,
            0,
            view.as_ref(),
        );
        gl.draw_arrays_instanced(WebGl2RenderingContext::TRIANGLES, 0, 6, prims.len() as i32);
        draw_calls = draw_calls.saturating_add(1);
        total_primitives = total_primitives.saturating_add(prims.len() as u32);
        if is_blur_batch {
            gl.active_texture(WebGl2RenderingContext::TEXTURE3);
            if let Some(scene_tex) = active_scene_tex.as_ref() {
                gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(scene_tex));
            } else if let (Some(bind_fn), Some(ext_tex)) =
                (pipe.bind_texture_fn.as_ref(), pipe.external_tex.as_ref())
            {
                drop(bind_fn.call2(gl.as_ref(), &target_val, ext_tex));
            }
        }
    }
    gl.bind_vertex_array(None);
    if use_blur_fbo && let Some(sfbo) = pipe.blur_scene_fbo.as_ref() {
        gl.bind_framebuffer(WebGl2RenderingContext::READ_FRAMEBUFFER, Some(sfbo));
        gl.bind_framebuffer(WebGl2RenderingContext::DRAW_FRAMEBUFFER, None);
        gl.blit_framebuffer(
            0,
            0,
            draw_w,
            draw_h,
            0,
            0,
            draw_w,
            draw_h,
            WebGl2RenderingContext::COLOR_BUFFER_BIT,
            WebGl2RenderingContext::NEAREST,
        );
        gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, None);
    }
    (draw_calls, total_primitives)
}

/// Draws a full `GpuFrameSubmission` directly via WebGL2 `gl.draw_arrays_instanced(TRIANGLES, 0, 6, count)` with hardware blur, GPU scene passes, and multi-canvas tiling above `GL_MAX_TEXTURE_SIZE`.
///
/// # Arguments
///
/// - `&mut WebWindowRecord` - Active browser window record owning the WebGL2 context and `WebGl2InstancedPipeline`.
/// - `&GpuFrameSubmission` - Direct-GPU batches, clear color, scene pass, and incremental glyph/image atlas payloads.
///
/// # Returns
///
/// - `Result<Option<(usize, u32)>, PlatformError>` - `Ok(Some((draw_calls, primitive_count)))` on direct instanced GPU presentation, or `Ok(None)` when unsupported.
pub(crate) fn web_draw_gl2_instanced_submission(
    rec: &mut WebWindowRecord,
    submission: &GpuFrameSubmission,
) -> Result<Option<(usize, u32)>, PlatformError> {
    let WebWindowRecord {
        canvas,
        gl2,
        gl2_instanced,
        tiled_canvases,
        active_tile_grid,
        cached_glyph_r8_atlas,
        cached_glyph_r8_rev,
        cached_image_rgba8_atlas,
        cached_image_rgba8_rev,
        ..
    } = rec;
    let (Some(gl), Some(pipe)) = (gl2.as_ref(), gl2_instanced.as_mut()) else {
        return Ok(None);
    };
    let glyph_incoming: bool = submission.glyph_atlas_r8_ref().is_some();
    if let Some(atlas) = submission.glyph_atlas_r8_ref() {
        *cached_glyph_r8_atlas = Some(atlas.clone());
        *cached_glyph_r8_rev = cached_glyph_r8_rev.wrapping_add(1).max(1);
    }
    let image_incoming: bool = submission.image_atlas_rgba8_ref().is_some();
    if let Some(atlas) = submission.image_atlas_rgba8_ref() {
        *cached_image_rgba8_atlas = Some(atlas.clone());
        *cached_image_rgba8_rev = cached_image_rgba8_rev.wrapping_add(1).max(1);
    }
    let glyph_cache: (Option<&DirectGpuAtlasUpload>, u64, bool) = (
        cached_glyph_r8_atlas.as_ref(),
        *cached_glyph_r8_rev,
        glyph_incoming,
    );
    let image_cache: (Option<&DirectGpuAtlasUpload>, u64, bool) = (
        cached_image_rgba8_atlas.as_ref(),
        *cached_image_rgba8_rev,
        image_incoming,
    );
    let req_w: u32 = submission.get_width().max(1);
    let req_h: u32 = submission.get_height().max(1);
    let max_single_dim: u32 = pipe.max_tex_dim.clamp(256, WEB_GL2_MAX_SINGLE_SURFACE_DIM);
    let max_single_area: u64 = u64::from(max_single_dim)
        .saturating_mul(u64::from(max_single_dim))
        .max(65_536);
    let mut tile_limit: Option<(u32, u64)> = if req_w > max_single_dim || req_h > max_single_dim {
        Some((max_single_dim, max_single_area))
    } else {
        None
    };
    if tile_limit.is_none() {
        if let Some(el) = canvas.as_ref() {
            if el.width() != req_w {
                el.set_width(req_w);
            }
            if el.height() != req_h {
                el.set_height(req_h);
            }
        }
        let draw_w: i32 = gl.drawing_buffer_width();
        let draw_h: i32 = gl.drawing_buffer_height();
        if draw_w == (req_w as i32) && draw_h == (req_h as i32) {
            if !tiled_canvases.is_empty() {
                for tile_rec in tiled_canvases.drain(..) {
                    tile_rec.canvas.remove();
                }
            }
            web_sync_canvas_tiled_attr(canvas.as_ref(), active_tile_grid, 1, 1);
            let (draws, prims): (usize, u32) = web_draw_gl2_instanced_on_surface(
                gl,
                pipe,
                submission,
                (draw_w, draw_h),
                (0.0, 0.0),
                glyph_cache,
                image_cache,
            );
            return Ok(Some((draws, prims)));
        }
        let actual_w: u32 = (draw_w.max(256) as u32).min(max_single_dim);
        let actual_h: u32 = (draw_h.max(256) as u32).min(max_single_dim);
        let clamped_w: bool = draw_w < (req_w as i32);
        let clamped_h: bool = draw_h < (req_h as i32);
        let safe_axis: u32 = if clamped_w && clamped_h {
            actual_w.max(actual_h).min(max_single_dim).max(256)
        } else if clamped_w {
            actual_w.max(256)
        } else if clamped_h {
            actual_h.max(256)
        } else {
            actual_w.min(actual_h).max(256)
        };
        let safe_area: u64 = u64::from(actual_w)
            .saturating_mul(u64::from(actual_h))
            .max(65_536);
        tile_limit = Some((safe_axis, safe_area));
    }
    let (max_tile_axis, max_tile_area): (u32, u64) =
        tile_limit.unwrap_or((max_single_dim, max_single_area));
    let plan: TiledSurfacePlan =
        ViewportMetrics::from_exact(f64::from(req_w), f64::from(req_h), req_w, req_h, 1.0)
            .plan_tiled_surface(SurfaceTileLimit::new(max_tile_axis, max_tile_area));
    let tiles: &[SurfaceTileRect] = plan.get_tiles().as_slice();
    if tiles.is_empty() {
        return Ok(None);
    }
    while tiled_canvases.len() > tiles.len() {
        if let Some(extra) = tiled_canvases.pop() {
            extra.canvas.remove();
        }
    }
    for tile in tiles.iter().skip(tiled_canvases.len()) {
        let Some(created) = web_create_gl2_tile_canvas(
            canvas.as_ref(),
            tile.get_physical_width(),
            tile.get_physical_height(),
        ) else {
            for existing in tiled_canvases.drain(..) {
                existing.canvas.remove();
            }
            web_sync_canvas_tiled_attr(canvas.as_ref(), active_tile_grid, 1, 1);
            return Ok(None);
        };
        tiled_canvases.push(created);
    }
    web_sync_canvas_tiled_attr(
        canvas.as_ref(),
        active_tile_grid,
        plan.get_columns(),
        plan.get_rows(),
    );
    let inv_req_w: f64 = 100.0 / f64::from(req_w);
    let inv_req_h: f64 = 100.0 / f64::from(req_h);
    let mut total_draws: usize = 0;
    let mut total_prims: u32 = 0;
    for (tile, tile_rec) in tiles.iter().zip(tiled_canvases.iter_mut()) {
        let tw: u32 = tile.get_physical_width().max(1);
        let th: u32 = tile.get_physical_height().max(1);
        if tile_rec.canvas.width() != tw {
            tile_rec.canvas.set_width(tw);
        }
        if tile_rec.canvas.height() != th {
            tile_rec.canvas.set_height(th);
        }
        let tile_geom: (u32, u32, u32, u32, u32, u32) = (
            tile.get_physical_x(),
            tile.get_physical_y(),
            tw,
            th,
            req_w,
            req_h,
        );
        if tile_rec.last_style_geom != tile_geom {
            let left_pct: f64 = f64::from(tile.get_physical_x()) * inv_req_w;
            let top_pct: f64 = f64::from(tile.get_physical_y()) * inv_req_h;
            let width_pct: f64 = f64::from(tw) * inv_req_w;
            let height_pct: f64 = f64::from(th) * inv_req_h;
            let tile_style: String = format!(
                "{WEB_TILE_CANVAS_STYLE_PREFIX}left:{left_pct:.4}%;top:{top_pct:.4}%;width:{width_pct:.4}%;height:{height_pct:.4}%;"
            );
            drop(tile_rec.canvas.set_attribute(WEB_ATTR_STYLE, &tile_style));
            tile_rec.last_style_geom = tile_geom;
        }
        let draw_w: i32 = tile_rec.gl2.drawing_buffer_width().max(1);
        let draw_h: i32 = tile_rec.gl2.drawing_buffer_height().max(1);
        let (draws, prims): (usize, u32) = web_draw_gl2_instanced_on_surface(
            &tile_rec.gl2,
            &mut tile_rec.instanced,
            submission,
            (draw_w, draw_h),
            (tile.get_physical_x() as f32, tile.get_physical_y() as f32),
            glyph_cache,
            image_cache,
        );
        total_draws = total_draws.saturating_add(draws);
        total_prims = total_prims.saturating_add(prims);
    }
    Ok(Some((total_draws, total_prims)))
}

/// Packs a partial dirty sub-rectangle of `framebuffer` into tightly contiguous RGBA8 bytes.
///
/// # Arguments
///
/// - `&Framebuffer` - Source RGBA8 framebuffer.
/// - `u32` - Inclusive left pixel coordinate.
/// - `u32` - Inclusive top pixel coordinate.
/// - `u32` - Sub-rectangle width in pixels.
/// - `u32` - Sub-rectangle height in pixels.
/// - `&mut Vec<u8>` - Reusable destination staging buffer cleared and filled in place.
fn web_pack_rgba_subrect_into(
    framebuffer: &Framebuffer,
    x0: u32,
    y0: u32,
    width: u32,
    height: u32,
    out: &mut Vec<u8>,
) {
    let fb_w: usize = framebuffer.get_width() as usize;
    let src: &[u8] = framebuffer.get_pixels().as_slice();
    let row_bytes: usize = (width as usize) * 4;
    let needed: usize = row_bytes * (height as usize);
    out.clear();
    if out.capacity() < needed {
        out.reserve(needed - out.capacity());
    }
    for row in y0..(y0 + height) {
        let start: usize = ((row as usize) * fb_w + (x0 as usize)) * 4;
        let end: usize = start + row_bytes;
        if end <= src.len() {
            out.extend_from_slice(&src[start..end]);
        }
    }
}

/// Uploads full or dirty sub-rectangle RGBA8 pixels directly from WASM linear memory (`precision highp float` + `texelFetch`, `GpuUpload` path with `cpu_mirror_active = true`) and returns the exact uploaded byte count.
///
/// # Arguments
///
/// - `&mut WebWindowRecord` - Browser window record holding the WebGL2 context, program, resident texture, and canvas.
/// - `&Framebuffer` - Source RGBA8 framebuffer.
/// - `DamageRegion` - Damaged physical pixel region.
///
/// # Returns
///
/// - `Result<Option<u64>, PlatformError>` - `Ok(Some(upload_bytes))` when presented via WebGL2 upload; `Ok(None)` when no WebGL2 pipeline is bound.
pub(crate) fn web_present_gl2_region(
    rec: &mut WebWindowRecord,
    framebuffer: &Framebuffer,
    damage: DamageRegion,
) -> Result<Option<u64>, PlatformError> {
    let WebWindowRecord {
        canvas,
        gl2,
        gl2_program,
        gl2_texture,
        gl2_view_loc,
        gl2_bind_texture_fn,
        gl2_max_tex_dim,
        gl2_tex_width,
        gl2_tex_height,
        active_tile_grid,
        ..
    } = rec;
    let (Some(gl), Some(program), Some(texture)) =
        (gl2.as_ref(), gl2_program.as_ref(), gl2_texture.as_ref())
    else {
        return Ok(None);
    };
    let fb_w: u32 = framebuffer.get_width();
    let fb_h: u32 = framebuffer.get_height();
    if fb_w == 0 || fb_h == 0 {
        return Ok(Some(0));
    }
    let pixels: &[u8] = framebuffer.get_pixels().as_slice();
    let required_bytes: usize = (fb_w as usize)
        .saturating_mul(fb_h as usize)
        .saturating_mul(4);
    if pixels.len() < required_bytes {
        return Err(PlatformError::SurfaceError(
            ERR_WEB_PRESENT_FAILED.to_string(),
        ));
    }
    let max_tex_dim: u32 = (*gl2_max_tex_dim).max(1024);
    if fb_w > max_tex_dim || fb_h > max_tex_dim {
        return Ok(None);
    }
    let mut drawing_resized: bool =
        gl.drawing_buffer_width() != (fb_w as i32) || gl.drawing_buffer_height() != (fb_h as i32);
    if drawing_resized && let Some(el) = canvas.as_ref() {
        if el.width() != fb_w {
            el.set_width(fb_w);
        }
        if el.height() != fb_h {
            el.set_height(fb_h);
        }
        drawing_resized = true;
    }
    if gl.drawing_buffer_width() != (fb_w as i32) || gl.drawing_buffer_height() != (fb_h as i32) {
        return Ok(None);
    }
    web_sync_canvas_tiled_attr(canvas.as_ref(), active_tile_grid, 1, 1);
    let tex_dims_changed: bool = *gl2_tex_width != fb_w || *gl2_tex_height != fb_h;
    let resolved_rect: Option<Rect> = damage.resolve(fb_w, fb_h);
    if resolved_rect.is_none() && !drawing_resized && !tex_dims_changed {
        return Ok(Some(0));
    }
    let target_val: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
    gl.active_texture(WebGl2RenderingContext::TEXTURE0);
    if let Some(bind_fn) = gl2_bind_texture_fn.as_ref() {
        drop(bind_fn.call2(gl.as_ref(), &target_val, texture));
    }
    web_configure_gl2_unpack_state(gl);
    let surface_dirty: bool = drawing_resized || tex_dims_changed;
    let needs_full_upload: bool = damage.get_full_damage() || surface_dirty;
    let mut upload_bytes: u64 = 0;
    if needs_full_upload {
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
        gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
        // SAFETY: `pixels` stays valid and immovable in WASM linear memory for the synchronous WebGL2 upload call.
        let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
        if tex_dims_changed {
            gl.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
                WebGl2RenderingContext::TEXTURE_2D,
                0,
                WebGl2RenderingContext::RGBA8 as i32,
                fb_w as i32,
                fb_h as i32,
                0,
                WebGl2RenderingContext::RGBA,
                WebGl2RenderingContext::UNSIGNED_BYTE,
                Some(view.as_ref()),
            )
            .map_err(|_: JsValue| {
                PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
            })?;
            *gl2_tex_width = fb_w;
            *gl2_tex_height = fb_h;
        } else {
            gl.tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
                WebGl2RenderingContext::TEXTURE_2D,
                0,
                0,
                0,
                fb_w as i32,
                fb_h as i32,
                WebGl2RenderingContext::RGBA,
                WebGl2RenderingContext::UNSIGNED_BYTE,
                Some(view.as_ref()),
            )
            .map_err(|_: JsValue| {
                PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
            })?;
        }
        upload_bytes = required_bytes as u64;
    } else if let Some(rect) = resolved_rect {
        let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(fb_w);
        let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(fb_h);
        let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(fb_w);
        let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(fb_h);
        if x1 > x0 && y1 > y0 {
            let rw: u32 = x1 - x0;
            let rh: u32 = y1 - y0;
            gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, fb_w as i32);
            gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, x0 as i32);
            gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, y0 as i32);
            // SAFETY: `pixels` stays valid and immovable in WASM linear memory for the synchronous WebGL2 upload call.
            let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
            let upload_res: Result<(), JsValue> = gl
                .tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
                    WebGl2RenderingContext::TEXTURE_2D,
                    0,
                    x0 as i32,
                    y0 as i32,
                    rw as i32,
                    rh as i32,
                    WebGl2RenderingContext::RGBA,
                    WebGl2RenderingContext::UNSIGNED_BYTE,
                    Some(view.as_ref()),
                );
            gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
            gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
            gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
            upload_res.map_err(|_: JsValue| {
                PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
            })?;
            upload_bytes = u64::from(rw)
                .saturating_mul(u64::from(rh))
                .saturating_mul(4);
        }
    }
    let draw_w: i32 = gl.drawing_buffer_width().max(1);
    let draw_h: i32 = gl.drawing_buffer_height().max(1);
    gl.viewport(0, 0, draw_w, draw_h);
    gl.use_program(Some(program));
    if let Some(loc) = gl2_view_loc.as_ref() {
        gl.uniform2f(Some(loc), draw_w as f32, draw_h as f32);
    }
    gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
    Ok(Some(upload_bytes))
}

/// Blits only the damaged physical rectangle of an RGBA8 `Framebuffer` onto a browser `CanvasRenderingContext2d` (`Software`, `cpu_mirror_active = true`), auto-syncing `<canvas>` backing-store dimensions when resized, and returns exact uploaded bytes.
///
/// # Arguments
///
/// - `Option<&HtmlCanvasElement>` - Backing `<canvas>` element synchronized to `(fb_w, fb_h)` before blitting.
/// - `&CanvasRenderingContext2d` - Browser 2D rendering context.
/// - `&Framebuffer` - Rendered RGBA8 framebuffer.
/// - `DamageRegion` - Damaged pixel region to copy into the canvas.
///
/// # Returns
///
/// - `Result<u64, PlatformError>` - Exact pixel bytes copied via `putImageData`.
pub(crate) fn web_present_image_data_region(
    canvas: Option<&HtmlCanvasElement>,
    ctx2d: &CanvasRenderingContext2d,
    framebuffer: &Framebuffer,
    damage: DamageRegion,
) -> Result<u64, PlatformError> {
    let fb_w: u32 = framebuffer.get_width();
    let fb_h: u32 = framebuffer.get_height();
    let mut backing_resized: bool = false;
    if let Some(el) = canvas {
        if el.width() != fb_w {
            el.set_width(fb_w);
            backing_resized = true;
        }
        if el.height() != fb_h {
            el.set_height(fb_h);
            backing_resized = true;
        }
    }
    let effective_damage: DamageRegion = if backing_resized {
        DamageRegion::full()
    } else {
        damage
    };
    let Some(rect) = effective_damage.resolve(fb_w, fb_h) else {
        return Ok(0);
    };
    if effective_damage.get_full_damage()
        && fb_w <= WEB_TILED_BLIT_CHUNK_DIM
        && fb_h <= WEB_TILED_BLIT_CHUNK_DIM
    {
        let pixels: &[u8] = framebuffer.get_pixels().as_slice();
        let clamped: Clamped<&[u8]> = Clamped(pixels);
        let img: ImageData = ImageData::new_with_u8_clamped_array_and_sh(clamped, fb_w, fb_h)
            .map_err(|_: JsValue| {
                PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
            })?;
        ctx2d.put_image_data(&img, 0.0, 0.0).map_err(|_: JsValue| {
            PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
        })?;
        Ok(pixels.len() as u64)
    } else {
        let (x0, y0, x1, y1): (u32, u32, u32, u32) = if effective_damage.get_full_damage() {
            (0, 0, fb_w, fb_h)
        } else {
            (
                (rect.get_x().floor().max(0.0) as u32).min(fb_w),
                (rect.get_y().floor().max(0.0) as u32).min(fb_h),
                (rect.right().ceil().max(0.0) as u32).min(fb_w),
                (rect.bottom().ceil().max(0.0) as u32).min(fb_h),
            )
        };
        if x1 <= x0 || y1 <= y0 {
            return Ok(0);
        }
        let mut total_copied: u64 = 0;
        let mut tile_y: u32 = y0;
        while tile_y < y1 {
            let tile_h: u32 = (y1 - tile_y).min(WEB_TILED_BLIT_CHUNK_DIM);
            let mut tile_x: u32 = x0;
            while tile_x < x1 {
                let tile_w: u32 = (x1 - tile_x).min(WEB_TILED_BLIT_CHUNK_DIM);
                let (img, copied_bytes): (ImageData, u64) = WEB_SUBRECT_SCRATCH.with(
                    |cell: &RefCell<Vec<u8>>| -> Result<(ImageData, u64), PlatformError> {
                        let Ok(mut sub) = cell.try_borrow_mut() else {
                            return Err(PlatformError::SurfaceError(
                                ERR_WEB_PRESENT_FAILED.to_string(),
                            ));
                        };
                        web_pack_rgba_subrect_into(
                            framebuffer,
                            tile_x,
                            tile_y,
                            tile_w,
                            tile_h,
                            &mut sub,
                        );
                        let copied_bytes: u64 = sub.len() as u64;
                        let clamped: Clamped<&[u8]> = Clamped(sub.as_slice());
                        let img_res: Result<ImageData, JsValue> =
                            ImageData::new_with_u8_clamped_array_and_sh(clamped, tile_w, tile_h);
                        drop(sub);
                        let img: ImageData = img_res.map_err(|_: JsValue| {
                            PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
                        })?;
                        Ok((img, copied_bytes))
                    },
                )?;
                ctx2d
                    .put_image_data(&img, tile_x as f64, tile_y as f64)
                    .map_err(|_: JsValue| {
                        PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
                    })?;
                total_copied = total_copied.saturating_add(copied_bytes);
                tile_x = tile_x.saturating_add(tile_w);
            }
            tile_y = tile_y.saturating_add(tile_h);
        }
        Ok(total_copied)
    }
}

/// Reads an optional finite numeric property from a JS object via `Reflect::get`.
///
/// # Arguments
///
/// - `&JsValue` - Target JS object.
/// - `&str` - Property name.
///
/// # Returns
///
/// - `Option<f32>` - Finite `f32` value when present and numeric.
fn web_read_opt_f32(target: &JsValue, key: &str) -> Option<f32> {
    let val: JsValue = Reflect::get(target, &JsValue::from_str(key)).ok()?;
    let num: f64 = val.as_f64()?;
    if num.is_finite() {
        Some(num as f32)
    } else {
        None
    }
}

/// Reads a 3-component `(x, y, z)` vector from a nested JS property (such as `accelerationIncludingGravity`).
///
/// # Arguments
///
/// - `&JsValue` - Parent DOM event object.
/// - `&str` - Nested vector property name.
///
/// # Returns
///
/// - `Option<[f32; 3]>` - Vector when the nested object is non-null and carries at least one finite axis.
fn web_read_vec3_prop(event_val: &JsValue, prop: &str) -> Option<[f32; 3]> {
    let sub: JsValue = Reflect::get(event_val, &JsValue::from_str(prop)).ok()?;
    if sub.is_null() || sub.is_undefined() {
        return None;
    }
    let ox: Option<f32> = web_read_opt_f32(&sub, WEB_PROP_AXIS_X);
    let oy: Option<f32> = web_read_opt_f32(&sub, WEB_PROP_AXIS_Y);
    let oz: Option<f32> = web_read_opt_f32(&sub, WEB_PROP_AXIS_Z);
    if ox.is_none() && oy.is_none() && oz.is_none() {
        return None;
    }
    Some([ox.unwrap_or(0.0), oy.unwrap_or(0.0), oz.unwrap_or(0.0)])
}

/// Reads `DeviceMotionEvent.rotationRate` (`beta`->X, `gamma`->Y, `alpha`->Z) converted from `deg/s` into `rad/s`.
///
/// # Arguments
///
/// - `&JsValue` - `DeviceMotionEvent` JS object.
///
/// # Returns
///
/// - `[f32; 3]` - Device-frame angular velocity `[wx, wy, wz]` in `rad/s`.
fn web_read_rotation_rate_rad(event_val: &JsValue) -> [f32; 3] {
    let Ok(sub) = Reflect::get(event_val, &JsValue::from_str(WEB_PROP_ROTATION_RATE)) else {
        return [0.0, 0.0, 0.0];
    };
    if sub.is_null() || sub.is_undefined() {
        return [0.0, 0.0, 0.0];
    }
    let alpha_dps: f32 = web_read_opt_f32(&sub, WEB_PROP_ALPHA).unwrap_or(0.0);
    let beta_dps: f32 = web_read_opt_f32(&sub, WEB_PROP_BETA).unwrap_or(0.0);
    let gamma_dps: f32 = web_read_opt_f32(&sub, WEB_PROP_GAMMA).unwrap_or(0.0);
    [
        beta_dps * WEB_DEG_TO_RAD,
        gamma_dps * WEB_DEG_TO_RAD,
        alpha_dps * WEB_DEG_TO_RAD,
    ]
}

/// Queries the active browser screen rotation angle in degrees (`0`, `90`, `180`, `270`) from `screen.orientation.angle` with legacy `window.orientation` fallback.
///
/// # Returns
///
/// - `i32` - Normalized screen rotation angle in degrees.
#[must_use]
pub fn web_screen_orientation_angle_deg() -> i32 {
    let Some(win) = window() else {
        return 0;
    };
    if let Ok(screen_val) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_SCREEN))
        && !screen_val.is_null()
        && !screen_val.is_undefined()
        && let Ok(orient_val) = Reflect::get(&screen_val, &JsValue::from_str(WEB_PROP_ORIENTATION))
        && !orient_val.is_null()
        && !orient_val.is_undefined()
        && let Some(angle) = web_read_opt_f32(&orient_val, WEB_PROP_ANGLE)
    {
        return angle.round() as i32;
    }
    if let Some(legacy_angle) = web_read_opt_f32(win.as_ref(), WEB_PROP_ORIENTATION) {
        return legacy_angle.round() as i32;
    }
    0
}

/// Returns current browser monotonic timestamp in nanoseconds via `window.performance.now()`.
///
/// # Returns
///
/// - `u64` - Monotonic timestamp in nanoseconds (`0` when unavailable).
#[must_use]
fn web_monotonic_now_ns() -> u64 {
    window()
        .and_then(|win: Window| win.performance())
        .map(|perf: Performance| (perf.now().max(0.0) * 1_000_000.0) as u64)
        .unwrap_or(0)
}

/// Processes a browser `deviceorientation` event and updates the thread-local gravity orientation reference.
///
/// # Arguments
///
/// - `&Event` - Incoming DOM `DeviceOrientationEvent`.
fn web_handle_device_orientation(event: &Event) {
    let ev_val: &JsValue = event.as_ref();
    let Some(beta_deg) = web_read_opt_f32(ev_val, WEB_PROP_BETA) else {
        return;
    };
    let Some(gamma_deg) = web_read_opt_f32(ev_val, WEB_PROP_GAMMA) else {
        return;
    };
    let alpha_deg: f32 = web_read_opt_f32(ev_val, WEB_PROP_ALPHA).unwrap_or(0.0);
    let blue_val: f32 = beta_deg * WEB_DEG_TO_RAD;
    let green_val: f32 = gamma_deg * WEB_DEG_TO_RAD;
    let yaw_rad: f32 = alpha_deg * WEB_DEG_TO_RAD;
    let g_dev: [f32; 3] = [
        STANDARD_GRAVITY_MPS2 * blue_val.cos() * green_val.sin(),
        -STANDARD_GRAVITY_MPS2 * blue_val.sin(),
        -STANDARD_GRAVITY_MPS2 * blue_val.cos() * green_val.cos(),
    ];
    let angle_deg: i32 = web_screen_orientation_angle_deg();
    let ts_ns: u64 = web_monotonic_now_ns();
    WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
        if let Ok(mut node_style) = cell.try_borrow_mut() {
            node_style.set_orient_gravity_dev(Some(g_dev));
            node_style.set_last_yaw_rad(yaw_rad);
            if !node_style.get_has_motion_event() {
                let mut sample: DeviceMotionSample = DeviceMotionSample::from_device_axes(
                    g_dev,
                    [0.0, 0.0, 0.0],
                    [0.0, 0.0, 0.0],
                    angle_deg,
                    ts_ns,
                );
                sample.set_yaw_rad(yaw_rad);
                node_style.set_pending_sample(sample);
                node_style.set_has_pending_sample(true);
            }
        }
    });
}

/// Applies a smooth symmetric deadzone `dz` to a single sensor channel so MEMS stationary noise maps cleanly to `0.0`.
///
/// # Arguments
///
/// - `f32` - Raw finite sensor reading.
/// - `f32` - Positive deadzone threshold.
///
/// # Returns
///
/// - `f32` - Deadzone-filtered value preserving sign and smooth continuity above `dz`.
#[inline(always)]
#[must_use]
fn web_apply_sensor_deadzone(item_val: f32, dz: f32) -> f32 {
    if !item_val.is_finite() {
        return 0.0;
    }
    let abs_v: f32 = item_val.abs();
    if abs_v <= dz {
        0.0
    } else {
        item_val.signum() * (abs_v - dz)
    }
}

/// Processes a browser `devicemotion` event, fuses gravity, linear acceleration, and gyroscope rate into screen-aligned coordinates.
///
/// # Arguments
///
/// - `&Event` - Incoming DOM `DeviceMotionEvent`.
fn web_handle_device_motion(event: &Event) {
    let ev_val: &JsValue = event.as_ref();
    let accel_incl: Option<[f32; 3]> = web_read_vec3_prop(ev_val, WEB_PROP_ACCEL_INCLUDING_GRAVITY);
    let accel_lin: Option<[f32; 3]> = web_read_vec3_prop(ev_val, WEB_PROP_ACCELERATION);
    let raw_gyro: [f32; 3] = web_read_rotation_rate_rad(ev_val);
    let gyro_dev: [f32; 3] = [
        web_apply_sensor_deadzone(raw_gyro[0], WEB_GYRO_DEADZONE_RAD_S),
        web_apply_sensor_deadzone(raw_gyro[1], WEB_GYRO_DEADZONE_RAD_S),
        web_apply_sensor_deadzone(raw_gyro[2], WEB_GYRO_DEADZONE_RAD_S),
    ];
    let angle_deg: i32 = web_screen_orientation_angle_deg();
    let ts_ns: u64 = web_monotonic_now_ns();
    WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
        if let Ok(mut node_style) = cell.try_borrow_mut() {
            let first_motion: bool = !node_style.get_has_motion_event();
            let mut g_dev_opt: Option<[f32; 3]> = None;
            let mut lin_dev: [f32; 3] = [0.0, 0.0, 0.0];
            if let Some(ag) = accel_incl {
                node_style.set_has_motion_event(true);
                let (raw_g_unsmoothed, raw_lin): ([f32; 3], [f32; 3]) = if let Some(al) = accel_lin
                {
                    ([ag[0] - al[0], ag[1] - al[1], ag[2] - al[2]], al)
                } else {
                    let prev: [f32; 3] = node_style.get_filtered_gravity_dev().unwrap_or(ag);
                    let alpha_val: f32 = WEB_GRAVITY_LPF_ALPHA;
                    let filt: [f32; 3] = [
                        prev[0] * (1.0 - alpha_val) + ag[0] * alpha_val,
                        prev[1] * (1.0 - alpha_val) + ag[1] * alpha_val,
                        prev[2] * (1.0 - alpha_val) + ag[2] * alpha_val,
                    ];
                    node_style.set_filtered_gravity_dev(Some(filt));
                    (filt, [ag[0] - filt[0], ag[1] - filt[1], ag[2] - filt[2]])
                };
                let prev_g: [f32; 3] = node_style
                    .get_filtered_gravity_dev()
                    .unwrap_or(raw_g_unsmoothed);
                let dg2: f32 = (raw_g_unsmoothed[0] - prev_g[0]).powi(2)
                    + (raw_g_unsmoothed[1] - prev_g[1]).powi(2)
                    + (raw_g_unsmoothed[2] - prev_g[2]).powi(2);
                let lpf_a: f32 = if dg2 < 0.09 { 0.18 } else { 0.65 };
                let raw_g: [f32; 3] = [
                    prev_g[0] * (1.0 - lpf_a) + raw_g_unsmoothed[0] * lpf_a,
                    prev_g[1] * (1.0 - lpf_a) + raw_g_unsmoothed[1] * lpf_a,
                    prev_g[2] * (1.0 - lpf_a) + raw_g_unsmoothed[2] * lpf_a,
                ];
                node_style.set_filtered_gravity_dev(Some(raw_g));
                if let Some(og) = node_style.get_orient_gravity_dev() {
                    let dot: f32 = raw_g[0] * og[0] + raw_g[1] * og[1] + raw_g[2] * og[2];
                    if dot > WEB_GRAVITY_SIGN_DOT_THRESHOLD {
                        node_style.set_gravity_sign(1.0);
                    } else if dot < -WEB_GRAVITY_SIGN_DOT_THRESHOLD {
                        node_style.set_gravity_sign(-1.0);
                    }
                } else if first_motion && raw_g[1].abs() > 4.2 {
                    node_style.set_gravity_sign(if raw_g[1] < 0.0 { 1.0 } else { -1.0 });
                }
                let source_val: f32 = node_style.get_gravity_sign();
                g_dev_opt = Some([
                    raw_g[0] * source_val,
                    raw_g[1] * source_val,
                    raw_g[2] * source_val,
                ]);
                let lin_sign: f32 = if source_val > 0.0 { -1.0 } else { 1.0 };
                lin_dev = [
                    web_apply_sensor_deadzone(
                        raw_lin[0] * lin_sign,
                        WEB_LINEAR_ACCEL_DEADZONE_MPS2,
                    ),
                    web_apply_sensor_deadzone(
                        raw_lin[1] * lin_sign,
                        WEB_LINEAR_ACCEL_DEADZONE_MPS2,
                    ),
                    web_apply_sensor_deadzone(
                        raw_lin[2] * lin_sign,
                        WEB_LINEAR_ACCEL_DEADZONE_MPS2,
                    ),
                ];
            } else if let Some(og) = node_style.get_orient_gravity_dev() {
                g_dev_opt = Some(og);
                if let Some(al) = accel_lin {
                    lin_dev = [
                        web_apply_sensor_deadzone(al[0], WEB_LINEAR_ACCEL_DEADZONE_MPS2),
                        web_apply_sensor_deadzone(al[1], WEB_LINEAR_ACCEL_DEADZONE_MPS2),
                        web_apply_sensor_deadzone(al[2], WEB_LINEAR_ACCEL_DEADZONE_MPS2),
                    ];
                }
            }
            if let Some(g_dev) = g_dev_opt {
                let mut sample: DeviceMotionSample = DeviceMotionSample::from_device_axes(
                    g_dev, lin_dev, gyro_dev, angle_deg, ts_ns,
                );
                sample.set_yaw_rad(node_style.get_last_yaw_rad());
                node_style.set_pending_sample(sample);
                node_style.set_has_pending_sample(true);
            }
        }
    });
}

/// Attaches browser `devicemotion` and `deviceorientation` listeners once onto `window` so `WebPlatform::poll_events` emits screen-aligned `SystemEvent::DeviceMotion` samples.
///
/// # Returns
///
/// - `bool` - `true` when browser motion listeners are attached and ready.
pub fn web_attach_device_motion_listeners() -> bool {
    let already: bool = WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
        cell.try_borrow()
            .map(|node_style: Ref<'_, WebDeviceMotionState>| node_style.get_listeners_attached())
            .unwrap_or(false)
    });
    if already {
        return true;
    }
    let Some(win) = window() else {
        return false;
    };
    let on_motion: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(|ui_event: Event| {
        web_handle_device_motion(&ui_event);
    }) as Box<dyn FnMut(Event)>);
    let motion_ok: bool = win
        .add_event_listener_with_callback(
            WEB_EVENT_DEVICE_MOTION,
            on_motion.as_ref().unchecked_ref(),
        )
        .is_ok();
    on_motion.forget();
    let on_orient: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(|dispatched_event: Event| {
        web_handle_device_orientation(&dispatched_event);
    }) as Box<dyn FnMut(Event)>);
    let orient_ok: bool = win
        .add_event_listener_with_callback(
            WEB_EVENT_DEVICE_ORIENTATION,
            on_orient.as_ref().unchecked_ref(),
        )
        .is_ok();
    on_orient.forget();
    let attached: bool = motion_ok || orient_ok;
    if attached {
        WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
            if let Ok(mut active_style) = cell.try_borrow_mut() {
                active_style.set_listeners_attached(true);
            }
        });
    }
    attached
}

/// Drains the most recent browser-fused `DeviceMotionSample`, if a fresh sensor reading arrived since the previous poll.
///
/// # Returns
///
/// - `Option<DeviceMotionSample>` - Latest screen-aligned sample ready for `SystemEvent::DeviceMotion`.
#[must_use]
pub fn web_take_pending_device_motion() -> Option<DeviceMotionSample> {
    WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
        cell.try_borrow_mut()
            .ok()
            .and_then(|mut node_style: RefMut<'_, WebDeviceMotionState>| {
                if node_style.get_has_pending_sample() {
                    node_style.set_has_pending_sample(false);
                    Some(node_style.get_pending_sample())
                } else {
                    None
                }
            })
    })
}

/// Invokes a static Safari sensor `requestPermission()` method on `ctor_name`, attaching motion listeners if permission resolves as `"granted"`.
///
/// # Arguments
///
/// - `&Window` - Active browser `Window`.
/// - `&str` - Constructor name (`DeviceMotionEvent` or `DeviceOrientationEvent`).
///
/// # Returns
///
/// - `bool` - `true` when the browser exposed and invoked `requestPermission()`.
fn web_try_request_ctor_permission(win: &Window, ctor_name: &str) -> bool {
    let Ok(ctor_val) = Reflect::get(win.as_ref(), &JsValue::from_str(ctor_name)) else {
        return false;
    };
    if ctor_val.is_null() || ctor_val.is_undefined() {
        return false;
    }
    let Ok(req_val) = Reflect::get(&ctor_val, &JsValue::from_str(WEB_METHOD_REQUEST_PERMISSION))
    else {
        return false;
    };
    let Ok(req_fn) = req_val.dyn_into::<Function>() else {
        return false;
    };
    if let Ok(ret) = req_fn.call0(&ctor_val)
        && let Ok(promise) = ret.dyn_into::<Promise>()
    {
        let on_granted: Closure<dyn FnMut(JsValue)> = Closure::wrap(Box::new(|res: JsValue| {
            if res.as_string().as_deref() == Some(WEB_PERMISSION_GRANTED) {
                let _: bool = web_attach_device_motion_listeners();
            }
        })
            as Box<dyn FnMut(JsValue)>);
        let chained: Promise = promise.then(&on_granted);
        on_granted.forget();
        WEB_PROMISE_NOOP_REJECT.with(|callback_fn: &Closure<dyn FnMut(JsValue)>| {
            let _: Promise = chained.catch(callback_fn);
        });
        return true;
    }
    false
}

/// Requests browser device motion/orientation permission (required on iOS 13+ Safari inside a user gesture) and attaches sensor listeners.
///
/// # Returns
///
/// - `bool` - `true` when permission request was dispatched or listeners were immediately attached.
pub(crate) fn web_request_motion_permission_impl() -> bool {
    let Some(win) = window() else {
        return false;
    };
    let motion_req: bool = web_try_request_ctor_permission(&win, WEB_CTOR_DEVICE_MOTION_EVENT);
    let orient_req: bool = web_try_request_ctor_permission(&win, WEB_CTOR_DEVICE_ORIENTATION_EVENT);
    if motion_req || orient_req {
        return true;
    }
    web_attach_device_motion_listeners()
}

/// Rasterizes a loaded DOM `<img>` element onto an offscreen 2D canvas and extracts its RGBA8 pixel buffer, upscaling vector SVGs to the active HiDPI `devicePixelRatio` for crisp Retina rendering.
///
/// # Arguments
///
/// - `&Document` - Active browser `Document`.
/// - `&Element` - Loaded `<img>` DOM element.
/// - `&str` - Source URL or data URI used to identify vector SVG assets.
///
/// # Returns
///
/// - `Option<ImageBuffer>` - Decoded RGBA8 `ImageBuffer`, or `None` if decoding or canvas readback fails.
fn web_rasterize_loaded_img(doc: &Document, img: &Element, url: &str) -> Option<ImageBuffer> {
    let raw_w: u32 = Reflect::get(img.as_ref(), &JsValue::from_str(WEB_PROP_NATURAL_WIDTH))
        .ok()
        .and_then(|item_val: JsValue| item_val.as_f64())
        .map(|item_count: f64| item_count.round().max(0.0) as u32)
        .unwrap_or(0);
    let raw_h: u32 = Reflect::get(img.as_ref(), &JsValue::from_str(WEB_PROP_NATURAL_HEIGHT))
        .ok()
        .and_then(|tex_v: JsValue| tex_v.as_f64())
        .map(|node_entry: f64| node_entry.round().max(0.0) as u32)
        .unwrap_or(0);
    let lower_url: String = url.to_ascii_lowercase();
    let is_svg_url: bool =
        lower_url.contains(WEB_EXT_SVG) || lower_url.starts_with(WEB_DATA_SVG_PREFIX);
    let missing_intrinsic: bool = raw_w == 0 || raw_h == 0;
    let is_vector_svg: bool = is_svg_url || missing_intrinsic;
    let (base_w, base_h): (u32, u32) = if !missing_intrinsic {
        (raw_w, raw_h)
    } else {
        (WEB_SVG_FALLBACK_WIDTH, WEB_SVG_FALLBACK_HEIGHT)
    };
    let (src_w, src_h): (u32, u32) = if is_vector_svg {
        let svg_scale: f64 = f64::from(web_device_pixel_ratio().clamp(1.0, WEB_SVG_RASTER_MAX_DPR));
        (
            (f64::from(base_w) * svg_scale).round().max(1.0) as u32,
            (f64::from(base_h) * svg_scale).round().max(1.0) as u32,
        )
    } else {
        (base_w, base_h)
    };
    let max_side: u32 = src_w.max(src_h);
    let (out_w, out_h): (u32, u32) = if max_side > WEB_IMAGE_MAX_DIM {
        let scale: f64 = f64::from(WEB_IMAGE_MAX_DIM) / f64::from(max_side);
        (
            (f64::from(src_w) * scale).round().max(1.0) as u32,
            (f64::from(src_h) * scale).round().max(1.0) as u32,
        )
    } else {
        (src_w, src_h)
    };
    let canvas_el: Element = doc.create_element(WEB_CANVAS_TAG).ok()?;
    let canvas: HtmlCanvasElement = canvas_el.dyn_into::<HtmlCanvasElement>().ok()?;
    canvas.set_width(out_w);
    canvas.set_height(out_h);
    let ctx_obj: Object = canvas.get_context(WEB_CONTEXT_2D).ok()??;
    let ctx2d: CanvasRenderingContext2d = ctx_obj.dyn_into::<CanvasRenderingContext2d>().ok()?;
    let _: Result<bool, JsValue> = Reflect::set(
        ctx2d.as_ref(),
        &JsValue::from_str(WEB_PROP_IMAGE_SMOOTHING_QUALITY),
        &JsValue::from_str(WEB_IMG_SMOOTHING_HIGH),
    );
    ctx2d.clear_rect(0.0, 0.0, f64::from(out_w), f64::from(out_h));
    let draw_val: JsValue =
        Reflect::get(ctx2d.as_ref(), &JsValue::from_str(WEB_METHOD_DRAW_IMAGE)).ok()?;
    let draw_fn: Function = draw_val.dyn_into::<Function>().ok()?;
    let args: Array = Array::of5(
        img.as_ref(),
        &JsValue::from_f64(0.0),
        &JsValue::from_f64(0.0),
        &JsValue::from_f64(f64::from(out_w)),
        &JsValue::from_f64(f64::from(out_h)),
    );
    let _: JsValue = draw_fn.apply(ctx2d.as_ref(), &args).ok()?;
    let img_data: ImageData = ctx2d
        .get_image_data(0.0, 0.0, f64::from(out_w), f64::from(out_h))
        .ok()?;
    let pixels: Vec<u8> = img_data.data().0;
    Some(ImageBuffer::new(out_w, out_h, pixels))
}

/// Asynchronously fetches and decodes `url` via a browser-native `<img>` element, finalizing waiters in `complete_network_image_load`.
///
/// # Arguments
///
/// - `&str` - Resolved image URL (local relative path or remote HTTP(S) URL).
pub(crate) fn web_load_network_image(url: &str) {
    let Some(doc) = window().and_then(|width_val: Window| width_val.document()) else {
        complete_network_image_load(url, None);
        return;
    };
    let Ok(img) = doc.create_element(WEB_TAG_IMG) else {
        complete_network_image_load(url, None);
        return;
    };
    let lower: String = url.to_ascii_lowercase();
    if lower.starts_with(WEB_SCHEME_HTTP) || lower.starts_with(WEB_SCHEME_HTTPS) {
        let _: Result<bool, JsValue> = Reflect::set(
            img.as_ref(),
            &JsValue::from_str(WEB_PROP_CROSS_ORIGIN),
            &JsValue::from_str(WEB_CORS_ANONYMOUS),
        );
    }
    let url_load: String = url.to_string();
    let img_load: Element = img.clone();
    let doc_load: Document = doc.clone();
    let on_load: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
        let decoded: Option<ImageBuffer> =
            web_rasterize_loaded_img(&doc_load, &img_load, &url_load);
        complete_network_image_load(&url_load, decoded);
    }) as Box<dyn FnMut(Event)>);
    let url_err: String = url.to_string();
    let on_err: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
        complete_network_image_load(&url_err, None);
    }) as Box<dyn FnMut(Event)>);
    drop(img.add_event_listener_with_callback(WEB_EVENT_LOAD, on_load.as_ref().unchecked_ref()));
    drop(img.add_event_listener_with_callback(WEB_EVENT_ERROR, on_err.as_ref().unchecked_ref()));
    on_load.forget();
    on_err.forget();
    let _: Result<bool, JsValue> = Reflect::set(
        img.as_ref(),
        &JsValue::from_str(WEB_PROP_SRC),
        &JsValue::from_str(url),
    );
}