euv-core 0.48.3

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
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(|w: Window| {
            let raw: f64 = w.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()
}

/// 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]
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(|v: JsValue| v.as_f64())
            .filter(|v: &f64| v.is_finite() && *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(|v: JsValue| v.as_f64())
                .filter(|v: &f64| v.is_finite() && *v >= 64.0);
            let vh: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_HEIGHT))
                .ok()
                .and_then(|v: JsValue| v.as_f64())
                .filter(|v: &f64| v.is_finite() && *v >= 64.0);
            if let (Some(w), Some(h)) = (vw, vh) {
                return (w, h);
            }
        }
    }
    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 w: f64 = win
        .inner_width()
        .ok()
        .and_then(|v: JsValue| v.as_f64())
        .filter(|v: &f64| v.is_finite() && *v >= 64.0)
        .unwrap_or(fallback_w.max(64.0));
    let h: f64 = win
        .inner_height()
        .ok()
        .and_then(|v: JsValue| v.as_f64())
        .filter(|v: &f64| v.is_finite() && *v >= 64.0)
        .unwrap_or(fallback_h.max(64.0));
    (w, h)
}

/// 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(|v: JsValue| v.dyn_into::<Function>().ok())
        .and_then(|f: Function| f.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(|w: Window| w.document())
        .map(|d: Document| d.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(|w: Window| w.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(|w: Window| w.navigator().language())
        .filter(|s: &String| !s.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(|b: HtmlElement| b.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,
    })
}

/// 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 texture: Option<JsValue> =
        Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_CREATE_TEXTURE))
            .ok()
            .and_then(|v: JsValue| v.dyn_into::<Function>().ok())
            .and_then(|f: Function| f.call0(gl.as_ref()).ok())
            .filter(|t: &JsValue| !t.is_null() && !t.is_undefined());
    if let Some(tex) = texture.as_ref() {
        let target: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
        if let Ok(bind_val) = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_BIND_TEXTURE))
            && let Ok(bind_fn) = bind_val.dyn_into::<Function>()
        {
            drop(bind_fn.call2(gl.as_ref(), &target, tex));
        }
        if let Ok(param_val) = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_TEX_PARAMETERI))
            && let Ok(param_fn) = param_val.dyn_into::<Function>()
        {
            let linear: JsValue = JsValue::from_f64(WebGl2RenderingContext::LINEAR as f64);
            let clamp: JsValue = JsValue::from_f64(WebGl2RenderingContext::CLAMP_TO_EDGE as f64);
            drop(param_fn.call3(
                gl.as_ref(),
                &target,
                &JsValue::from_f64(WebGl2RenderingContext::TEXTURE_MIN_FILTER as f64),
                &linear,
            ));
            drop(param_fn.call3(
                gl.as_ref(),
                &target,
                &JsValue::from_f64(WebGl2RenderingContext::TEXTURE_MAG_FILTER as f64),
                &linear,
            ));
            drop(param_fn.call3(
                gl.as_ref(),
                &target,
                &JsValue::from_f64(WebGl2RenderingContext::TEXTURE_WRAP_S as f64),
                &clamp,
            ));
            drop(param_fn.call3(
                gl.as_ref(),
                &target,
                &JsValue::from_f64(WebGl2RenderingContext::TEXTURE_WRAP_T as f64),
                &clamp,
            ));
        }
    }
    Some(WebGl2BlitPipeline {
        program: prog,
        texture,
        view_loc,
    })
}

/// 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(|cb: &Closure<dyn FnMut(JsValue)>| {
            let _: Promise = promise.catch(cb);
        });
    }
    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(|v: JsValue| !v.is_null() && !v.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(|w: Window| w.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();
    if render_mode == RenderMode::Hardware
        && web_has_webgpu()
        && let Ok(Some(gpu_ctx)) = canvas.get_context(WEB_CONTEXT_WEBGPU)
    {
        return Ok(WebCanvasSurface {
            canvas,
            context_kind: WebCanvasContextKind::WebGpu,
            presentation_mode: WebPresentationMode::GpuDirect,
            webgpu_ctx: Some(gpu_ctx),
            gl2: 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,
            ctx2d: None,
        });
    }
    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 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(d) => (Some(d.program), d.view_loc, d.rect_loc, d.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): (
                Option<WebGlProgram>,
                Option<JsValue>,
                Option<WebGlUniformLocation>,
            ) = match pipeline {
                Some(p) => (Some(p.program), p.texture, p.view_loc),
                None => (None, None, None),
            };
            let pres_mode: WebPresentationMode = if prefer_direct && gl2_direct_program.is_some() {
                WebPresentationMode::GpuDirect
            } else {
                WebPresentationMode::GpuUpload
            };
            return Ok(WebCanvasSurface {
                canvas,
                context_kind: WebCanvasContextKind::WebGl2,
                presentation_mode: pres_mode,
                webgpu_ctx: None,
                gl2: Some(gl2),
                gl2_direct_program,
                gl2_direct_view_loc,
                gl2_direct_rect_loc,
                gl2_direct_color_loc,
                gl2_program,
                gl2_texture,
                gl2_view_loc,
                ctx2d: None,
            });
        }
    }
    let raw_ctx: Object = canvas
        .get_context(WEB_CONTEXT_2D)
        .map_err(|_: JsValue| PlatformError::SurfaceError(ERR_WEB_CTX2D_MISSING.to_string()))?
        .ok_or_else(|| PlatformError::SurfaceError(ERR_WEB_CTX2D_MISSING.to_string()))?;
    let ctx2d: CanvasRenderingContext2d = raw_ctx
        .dyn_into::<CanvasRenderingContext2d>()
        .map_err(|_: Object| PlatformError::SurfaceError(ERR_WEB_CTX2D_MISSING.to_string()))?;
    Ok(WebCanvasSurface {
        canvas,
        context_kind: WebCanvasContextKind::Canvas2d,
        presentation_mode: WebPresentationMode::Software,
        webgpu_ctx: None,
        gl2: 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,
        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 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(d) => (Some(d.program), d.view_loc, d.rect_loc, d.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): (
                Option<WebGlProgram>,
                Option<JsValue>,
                Option<WebGlUniformLocation>,
            ) = match pipeline {
                Some(p) => (Some(p.program), p.texture, p.view_loc),
                None => (None, None, None),
            };
            if target_mode == WebPresentationMode::GpuDirect && 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,
                gl2: Some(gl2),
                gl2_direct_program,
                gl2_direct_view_loc,
                gl2_direct_rect_loc,
                gl2_direct_color_loc,
                gl2_program,
                gl2_texture,
                gl2_view_loc,
                ctx2d: None,
            })
        }
        WebPresentationMode::Software => {
            let raw_ctx: Object = canvas
                .get_context(WEB_CONTEXT_2D)
                .map_err(|_: JsValue| {
                    canvas.remove();
                    PlatformError::SurfaceError(ERR_WEB_CTX2D_MISSING.to_string())
                })?
                .ok_or_else(|| {
                    canvas.remove();
                    PlatformError::SurfaceError(ERR_WEB_CTX2D_MISSING.to_string())
                })?;
            let ctx2d: CanvasRenderingContext2d = raw_ctx
                .dyn_into::<CanvasRenderingContext2d>()
                .map_err(|_: Object| {
                    canvas.remove();
                    PlatformError::SurfaceError(ERR_WEB_CTX2D_MISSING.to_string())
                })?;
            Ok(WebCanvasSurface {
                canvas,
                context_kind: WebCanvasContextKind::Canvas2d,
                presentation_mode: WebPresentationMode::Software,
                webgpu_ctx: None,
                gl2: 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,
                ctx2d: Some(ctx2d),
            })
        }
    }
}

/// Renders GPU primitive `batches` directly onto a WebGL2 context using `WEB_GL2_DIRECT_*_SHADER` with zero CPU framebuffer upload (`cpu_mirror_active = false`).
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL2 context.
/// - `&WebGlProgram` - Compiled direct primitive program.
/// - `Option<&WebGlUniformLocation>` - `u_view` uniform location.
/// - `Option<&WebGlUniformLocation>` - `u_rect` uniform location.
/// - `Option<&WebGlUniformLocation>` - `u_color` uniform location.
/// - `u32` - Physical surface width in pixels.
/// - `u32` - Physical surface height in pixels.
/// - `Color` - Frame clear color.
/// - `&[GpuBatch]` - Ordered GPU primitive draw batches.
///
/// # Returns
///
/// - `u32` - Count of GPU primitives drawn directly on WebGL2.
pub(crate) fn web_draw_gl2_direct_batches(
    gl: &WebGl2RenderingContext,
    program: &WebGlProgram,
    view_loc: Option<&WebGlUniformLocation>,
    rect_loc: Option<&WebGlUniformLocation>,
    color_loc: Option<&WebGlUniformLocation>,
    width: u32,
    height: u32,
    clear_color: Color,
    batches: &[GpuBatch],
) -> u32 {
    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_r()) / 255.0,
        f32::from(clear_color.get_g()) / 255.0,
        f32::from(clear_color.get_b()) / 255.0,
        f32::from(clear_color.get_a()) / 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 r: f32 = f32::from((packed & 0xFF) as u8) / 255.0;
            let g: f32 = f32::from(((packed >> 8) & 0xFF) as u8) / 255.0;
            let b: f32 = f32::from(((packed >> 16) & 0xFF) as u8) / 255.0;
            let a: 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), r, g, b, a);
            }
            gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 6);
            drawn = drawn.saturating_add(1);
        }
    }
    drawn
}

/// 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.
///
/// # Returns
///
/// - `Vec<u8>` - Tightly packed RGBA8 sub-rectangle pixels.
fn web_pack_rgba_subrect(
    framebuffer: &Framebuffer,
    x0: u32,
    y0: u32,
    width: u32,
    height: u32,
) -> 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 mut out: Vec<u8> = Vec::with_capacity(row_bytes * (height as usize));
    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]);
        }
    }
    out
}

/// 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_tex_width,
        gl2_tex_height,
        ..
    } = 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 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;
    }
    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);
    if let Ok(active_val) = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_ACTIVE_TEXTURE))
        && let Ok(active_fn) = active_val.dyn_into::<Function>()
    {
        drop(active_fn.call1(
            gl.as_ref(),
            &JsValue::from_f64(WebGl2RenderingContext::TEXTURE0 as f64),
        ));
    }
    if let Ok(bind_val) = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_BIND_TEXTURE))
        && let Ok(bind_fn) = bind_val.dyn_into::<Function>()
    {
        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) };
        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;
        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() {
        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: 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 {
            return Ok(0);
        }
        let rw: u32 = x1 - x0;
        let rh: u32 = y1 - y0;
        let sub: Vec<u8> = web_pack_rgba_subrect(framebuffer, x0, y0, rw, rh);
        let copied_bytes: u64 = sub.len() as u64;
        let clamped: Clamped<&[u8]> = Clamped(sub.as_slice());
        let img: ImageData = ImageData::new_with_u8_clamped_array_and_sh(clamped, rw, rh).map_err(
            |_: JsValue| PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string()),
        )?;
        ctx2d
            .put_image_data(&img, x0 as f64, y0 as f64)
            .map_err(|_: JsValue| {
                PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
            })?;
        Ok(copied_bytes)
    }
}

/// 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 b: f32 = beta_deg * WEB_DEG_TO_RAD;
    let g: 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 * b.cos() * g.sin(),
        -STANDARD_GRAVITY_MPS2 * b.sin(),
        -STANDARD_GRAVITY_MPS2 * b.cos() * g.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 st) = cell.try_borrow_mut() {
            st.orient_gravity_dev = Some(g_dev);
            st.last_yaw_rad = yaw_rad;
            if !st.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);
                st.pending_sample = sample;
                st.has_pending_sample = true;
            }
        }
    });
}

/// 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 gyro_dev: [f32; 3] = web_read_rotation_rate_rad(ev_val);
    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 st) = cell.try_borrow_mut() {
            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 {
                st.has_motion_event = true;
                let (raw_g, 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] = st.filtered_gravity_dev.unwrap_or(ag);
                    let a: f32 = WEB_GRAVITY_LPF_ALPHA;
                    let filt: [f32; 3] = [
                        prev[0] * (1.0 - a) + ag[0] * a,
                        prev[1] * (1.0 - a) + ag[1] * a,
                        prev[2] * (1.0 - a) + ag[2] * a,
                    ];
                    st.filtered_gravity_dev = Some(filt);
                    (filt, [ag[0] - filt[0], ag[1] - filt[1], ag[2] - filt[2]])
                };
                if let Some(og) = st.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 {
                        st.gravity_sign = 1.0;
                    } else if dot < -WEB_GRAVITY_SIGN_DOT_THRESHOLD {
                        st.gravity_sign = -1.0;
                    }
                }
                let s: f32 = st.gravity_sign;
                g_dev_opt = Some([raw_g[0] * s, raw_g[1] * s, raw_g[2] * s]);
                let lin_sign: f32 = if s > 0.0 { -1.0 } else { 1.0 };
                lin_dev = [
                    raw_lin[0] * lin_sign,
                    raw_lin[1] * lin_sign,
                    raw_lin[2] * lin_sign,
                ];
            } else if let Some(og) = st.orient_gravity_dev {
                g_dev_opt = Some(og);
                if let Some(al) = accel_lin {
                    lin_dev = al;
                }
            }
            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(st.last_yaw_rad);
                st.pending_sample = sample;
                st.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(|st: Ref<'_, WebDeviceMotionState>| st.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(|ev: Event| {
        web_handle_device_motion(&ev);
    }) 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(|ev: Event| {
        web_handle_device_orientation(&ev);
    }) 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 st) = cell.try_borrow_mut() {
                st.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 st: RefMut<'_, WebDeviceMotionState>| {
                if st.has_pending_sample {
                    st.has_pending_sample = false;
                    Some(st.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(|cb: &Closure<dyn FnMut(JsValue)>| {
            let _: Promise = chained.catch(cb);
        });
        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(|v: JsValue| v.as_f64())
        .map(|n: f64| n.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(|v: JsValue| v.as_f64())
        .map(|n: f64| n.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(|w: Window| w.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),
    );
}