playwright-cdp 0.1.1

Drive Chromium directly via the Chrome DevTools Protocol (CDP) — no Playwright driver required.
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
//! `Page` — a browser tab. Tracks its main execution context, drives
//! navigation, evaluation, screenshots, and produces locators.

use crate::browser::Browser;
use crate::api_request::APIRequestContext;
use crate::cdp::session::CdpSession;
use crate::download::{Download, DownloadState, DownloadStateCell};
use crate::element_handle::ElementHandle;
use crate::error::{Error, Result};
use crate::file_chooser::FileChooser;
use crate::frame::Frame;
use crate::frame_locator::FrameLocator;
use crate::keyboard::Keyboard;
use crate::locator::Locator;
use crate::mouse::Mouse;
use crate::network::{network_tracker, NetworkStore, RequestHandler, ResponseHandler};
use crate::options::{
    DragToOptions, EmulateMediaOptions, GotoOptions, ScreenshotOptions, WaitForFunctionOptions, WaitUntil,
};
use crate::request::Request;
use crate::response::Response;
use crate::route::{route_listener, Route, RouteEntry};
use crate::selectors;
use crate::touchscreen::Touchscreen;
use crate::types::{AriaRole, ConsoleMessage, Headers, Viewport};
use crate::worker::Worker;
use base64::Engine;
use parking_lot::Mutex;
use serde::de::DeserializeOwned;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::future::Future;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::broadcast;

/// A page (tab) in a browser.
#[derive(Clone)]
pub struct Page {
    inner: Arc<PageInner>,
}

type CloseHandler =
    Arc<dyn Fn() -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;

/// An erased, callable binding: takes the JS args and returns a JSON value.
type ExposedBindingHandler =
    Arc<dyn Fn(Vec<Value>) -> std::pin::Pin<Box<dyn Future<Output = Value> + Send>> + Send + Sync>;

struct PageInner {
    browser: Browser,
    session: Arc<CdpSession>,
    target_id: String,
    main_world_ctx: Arc<Mutex<Option<i64>>>,
    default_timeout_ms: AtomicU64,
    default_navigation_timeout_ms: AtomicU64,
    viewport: Mutex<Option<Viewport>>,
    mouse_pos: Arc<Mutex<(f64, f64)>>,
    network_store: Arc<NetworkStore>,
    on_request_handlers: Arc<Mutex<Vec<RequestHandler>>>,
    on_response_handlers: Arc<Mutex<Vec<ResponseHandler>>>,
    on_requestfailed_handlers: Arc<Mutex<Vec<RequestHandler>>>,
    frames: Arc<Mutex<HashMap<String, FrameData>>>,
    main_frame_id: Arc<Mutex<Option<String>>>,
    route_handlers: Arc<Mutex<Vec<RouteEntry>>>,
    route_started: AtomicBool,
    on_close_handlers: Mutex<Vec<CloseHandler>>,
    closed: Mutex<bool>,
    // Download capture: the temp dir (kept alive for the page's lifetime), its
    // path, per-guid progress state, and a one-shot flag for behavior setup.
    download_dir: Mutex<Option<Arc<tempfile::TempDir>>>,
    download_path: Mutex<Option<PathBuf>>,
    download_states: Arc<Mutex<HashMap<String, DownloadStateCell>>>,
    download_started: AtomicBool,
    // File-chooser interception: a one-shot flag for enabling interception.
    filechooser_started: AtomicBool,
    // Worker capture: a one-shot flag for enabling page-session auto-attach.
    worker_started: AtomicBool,
    // Touchscreen: a one-shot flag for enabling touch emulation. Arc-wrapped so
    // it can be shared across `Touchscreen` clones produced from this page.
    touch_emulation_started: Arc<AtomicBool>,
}

/// Cached frame-tree data for one frame.
#[derive(Clone)]
pub(crate) struct FrameData {
    pub url: String,
    pub name: String,
    pub parent_id: Option<String>,
    pub detached: bool,
}

impl Page {
    /// Attach to an existing target by session/target id. Enables domains,
    /// injects the selector engine, and applies context defaults.
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn attach(
        browser: Browser,
        session_id: String,
        target_id: String,
        init_scripts: &[String],
        default_timeout_ms: u64,
        extra_headers: Option<&Headers>,
        user_agent: Option<&str>,
        viewport: Option<Viewport>,
    ) -> Result<Page> {
        let session = Arc::new(CdpSession::target(
            browser.connection().clone(),
            session_id,
        ));
        session.set_default_timeout_ms(default_timeout_ms);

        let main_world_ctx: Arc<Mutex<Option<i64>>> = Arc::new(Mutex::new(None));
        let ctx_rx = session.subscribe();
        // Context-tracking + engine re-injection task. Subscribe before
        // enabling Runtime so the initial executionContextCreated is captured.
        {
            let session_for_task = Arc::clone(&session);
            let ctx_cell = Arc::clone(&main_world_ctx);
            tokio::spawn(async move {
                context_tracker(ctx_rx, session_for_task, ctx_cell).await;
            });
        }

        let network_store = NetworkStore::new();
        // Handler lists shared between the page and the network tracker task.
        let on_request_handlers: Arc<Mutex<Vec<RequestHandler>>> = Arc::new(Mutex::new(Vec::new()));
        let on_response_handlers: Arc<Mutex<Vec<ResponseHandler>>> =
            Arc::new(Mutex::new(Vec::new()));
        let on_requestfailed_handlers: Arc<Mutex<Vec<RequestHandler>>> =
            Arc::new(Mutex::new(Vec::new()));

        // Network capture task. Subscribe before Network.enable so no event is missed.
        {
            let net_rx = session.subscribe();
            let session_for_task = Arc::clone(&session);
            let store_for_task = Arc::clone(&network_store);
            let on_request = Arc::clone(&on_request_handlers);
            let on_response = Arc::clone(&on_response_handlers);
            let on_failed = Arc::clone(&on_requestfailed_handlers);
            tokio::spawn(async move {
                network_tracker(
                    net_rx,
                    session_for_task,
                    store_for_task,
                    on_request,
                    on_response,
                    on_failed,
                )
                .await;
            });
        }

        let page = Page {
            inner: Arc::new(PageInner {
                browser,
                session: Arc::clone(&session),
                target_id,
                main_world_ctx: Arc::clone(&main_world_ctx),
                default_timeout_ms: AtomicU64::new(default_timeout_ms),
                default_navigation_timeout_ms: AtomicU64::new(default_timeout_ms),
                viewport: Mutex::new(viewport),
                mouse_pos: Arc::new(Mutex::new((0.0, 0.0))),
                network_store,
                on_request_handlers,
                on_response_handlers,
                on_requestfailed_handlers,
                frames: Arc::new(Mutex::new(HashMap::new())),
                main_frame_id: Arc::new(Mutex::new(None)),
                route_handlers: Arc::new(Mutex::new(Vec::new())),
                route_started: AtomicBool::new(false),
                on_close_handlers: Mutex::new(Vec::new()),
                closed: Mutex::new(false),
                download_dir: Mutex::new(None),
                download_path: Mutex::new(None),
                download_states: Arc::new(Mutex::new(HashMap::new())),
                download_started: AtomicBool::new(false),
                filechooser_started: AtomicBool::new(false),
                worker_started: AtomicBool::new(false),
                touch_emulation_started: Arc::new(AtomicBool::new(false)),
            }),
        };

        // Live frame-tree tracking (urls/names/children) for `Frame`.
        {
            let rx = session.subscribe();
            let frames_store = Arc::clone(&page.inner.frames);
            let main_id = Arc::clone(&page.inner.main_frame_id);
            tokio::spawn(async move {
                frame_tracker(rx, frames_store, main_id).await;
            });
        }
        // Populate the frame tree eagerly so `main_frame()` is always valid.
        let _ = page.refresh_frame_tree().await;

        // Domain enablement. Order matters only in that Runtime must be last
        // (after the context receiver exists) so contexts are captured.
        let _ = session.send("Page.enable", json!({})).await;
        let _ = session.send("Runtime.enable", json!({})).await;
        let _ = session.send("Network.enable", json!({})).await;
        let _ = session.send("Log.enable", json!({})).await;

        // Inject selector engine + user init scripts for all future documents.
        let mut source = String::from(selectors::INJECTED_SCRIPT);
        for s in init_scripts {
            source.push_str("\n");
            source.push_str(s);
        }
        let _ = session
            .send(
                "Page.addScriptToEvaluateOnNewDocument",
                json!({ "source": source }),
            )
            .await;

        // Ensure the engine is present in whatever context exists right now.
        page.ensure_engine_in_current_context().await;

        if let Some(headers) = extra_headers {
            let _ = page.set_extra_http_headers(headers.clone()).await;
        }
        if let Some(ua) = user_agent {
            let _ = session
                .send("Emulation.setUserAgentOverride", json!({ "userAgent": ua }))
                .await;
        }
        if let Some(vp) = page.inner.viewport.lock().as_ref().copied() {
            let _ = page.set_viewport_size(vp).await;
        }

        Ok(page)
    }

    // --- accessors ---

    pub(crate) fn session(&self) -> &CdpSession {
        &self.inner.session
    }

    pub(crate) fn context_id(&self) -> Option<i64> {
        self.inner.main_world_ctx.lock().as_ref().copied()
    }

    /// The current main-world execution context, waiting briefly for one to
    /// become available after a navigation (when the old context is destroyed
    /// before the new one is reported).
    pub(crate) async fn ctx(&self) -> Option<i64> {
        let deadline = tokio::time::Instant::now() + Duration::from_millis(2000);
        loop {
            if let Some(id) = self.context_id() {
                return Some(id);
            }
            if tokio::time::Instant::now() >= deadline {
                return self.context_id();
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
    }

    pub fn browser(&self) -> Browser {
        self.inner.browser.clone()
    }

    pub fn target_id(&self) -> &str {
        &self.inner.target_id
    }

    pub fn is_closed(&self) -> bool {
        *self.inner.closed.lock()
    }

    pub(crate) fn set_default_timeout(&self, ms: u64) {
        self.inner.default_timeout_ms.store(ms, Ordering::Relaxed);
        self.inner.session.set_default_timeout_ms(ms);
    }

    pub(crate) fn default_timeout(&self) -> Duration {
        Duration::from_millis(self.inner.default_timeout_ms.load(Ordering::Relaxed))
    }

    pub(crate) fn default_navigation_timeout(&self) -> Duration {
        Duration::from_millis(self.inner.default_navigation_timeout_ms.load(Ordering::Relaxed))
    }

    async fn ensure_engine_in_current_context(&self) {
        // Idempotent: the bundle early-returns if already installed.
        let _ = selectors::eval_context(
            &self.inner.session,
            self.ctx().await,
            "(arg) => { void arg; }",
            Value::Null,
        )
        .await;
    }

    // --- navigation ---

    /// Navigate to `url`.
    pub async fn goto(
        &self,
        url: &str,
        opts: Option<GotoOptions>,
    ) -> Result<Option<Response>> {
        let opts = opts.unwrap_or_default();
        let wait = opts.wait_until_or_default();

        // Subscribe before navigating so lifecycle events aren't missed.
        let mut rx = self.inner.session.subscribe();
        let mut params = json!({ "url": url });
        if let Some(referer) = &opts.referer {
            params["referer"] = json!(referer);
        }
        let nav = self.inner.session.send("Page.navigate", params).await?;
        if let Some(err) = nav.get("errorText").and_then(|v| v.as_str()) {
            return Err(Error::ProtocolError(format!("navigation to {url} failed: {err}")));
        }
        let loader_id = nav.get("loaderId").and_then(|v| v.as_str()).map(String::from);

        let timeout = opts.timeout.unwrap_or_else(|| self.default_timeout());
        self.wait_lifecycle(&mut rx, loader_id.as_deref(), wait, timeout, url)
            .await?;

        // Correlate the main-frame document response for this navigation.
        let response = match &loader_id {
            Some(lid) => self.wait_for_nav_response(lid).await,
            None => None,
        };
        Ok(response)
    }

    /// Poll the network store briefly for the document response of `loader_id`.
    async fn wait_for_nav_response(&self, loader_id: &str) -> Option<Response> {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
        loop {
            if let Some(r) = self.inner.network_store.response_for_loader(loader_id) {
                return Some(r);
            }
            if tokio::time::Instant::now() >= deadline {
                return None;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    }

    /// Wait until the in-flight request count stays at 0 for ~500ms (or deadline).
    async fn wait_network_idle(&self, deadline: tokio::time::Instant) {
        let window = Duration::from_millis(500);
        loop {
            if self.inner.network_store.inflight() == 0 {
                let settled_at = tokio::time::Instant::now();
                loop {
                    if self.inner.network_store.inflight() != 0 {
                        break; // a new request started; restart
                    }
                    if tokio::time::Instant::now().duration_since(settled_at) >= window {
                        return; // stayed idle for the window
                    }
                    if tokio::time::Instant::now() >= deadline {
                        return; // overall nav timeout
                    }
                    tokio::time::sleep(Duration::from_millis(50)).await;
                }
            }
            if tokio::time::Instant::now() >= deadline {
                return;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    }

    async fn wait_lifecycle(
        &self,
        rx: &mut broadcast::Receiver<crate::cdp::CdpEvent>,
        loader_id: Option<&str>,
        wait: WaitUntil,
        timeout: Duration,
        url: &str,
    ) -> Result<()> {
        if matches!(wait, WaitUntil::Commit) {
            return Ok(()); // Page.navigate returned => committed.
        }
        let target_name = match wait {
            WaitUntil::Load => "load",
            WaitUntil::DomContentLoaded => "DOMContentLoaded",
            WaitUntil::NetworkIdle => "load", // then settle below
            WaitUntil::Commit => "load",
        };

        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            match tokio::time::timeout(remaining, rx.recv()).await {
                Err(_) => {
                    return Err(Error::NavigationTimeout {
                        url: url.to_string(),
                        duration_ms: timeout.as_millis() as u64,
                    })
                }
                Ok(Err(broadcast::error::RecvError::Closed)) => {
                    return Err(Error::ChannelClosed);
                }
                Ok(Err(broadcast::error::RecvError::Lagged(_))) => continue,
                Ok(Ok(ev)) => {
                    // Some Chrome builds emit modern `Page.lifecycleEvent`
                    // (carrying `name`), others emit the legacy discrete events
                    // (`Page.loadEventFired`, `Page.domContentEventFired`).
                    // Handle both.
                    let matched = match ev.method.as_str() {
                        "Page.lifecycleEvent" => {
                            let same_loader = loader_id
                                .map(|l| {
                                    ev.params.get("loaderId").and_then(|v| v.as_str()) == Some(l)
                                })
                                .unwrap_or(true);
                            let name = ev.params.get("name").and_then(|v| v.as_str()).unwrap_or("");
                            same_loader && name == target_name
                        }
                        "Page.loadEventFired" => target_name == "load",
                        "Page.domContentEventFired" => target_name == "DOMContentLoaded",
                        _ => false,
                    };
                    if matched {
                        if matches!(wait, WaitUntil::NetworkIdle) {
                            // Settle: wait until in-flight requests hit 0 and stay there
                            // for ~500ms (Playwright's networkidle window).
                            self.wait_network_idle(deadline).await;
                        }
                        return Ok(());
                    }
                }
            }
        }
    }

    /// Reload the page.
    pub async fn reload(&self, opts: Option<GotoOptions>) -> Result<Option<Response>> {
        let opts = opts.unwrap_or_default();
        let wait = opts.wait_until_or_default();
        let mut rx = self.inner.session.subscribe();
        let _ = self.inner.session.send("Page.reload", json!({})).await?;
        let timeout = opts.timeout.unwrap_or_else(|| self.default_timeout());
        self.wait_lifecycle(&mut rx, None, wait, timeout, "reload").await?;
        Ok(None)
    }

    /// Wait for a given document lifecycle state.
    pub async fn wait_for_load_state(&self, state: Option<WaitUntil>) -> Result<()> {
        let state = state.unwrap_or_default();
        let mut rx = self.inner.session.subscribe();
        self.wait_lifecycle(&mut rx, None, state, self.default_timeout(), "wait_for_load_state")
            .await
    }

    /// Navigate one entry back in history (best-effort; returns no response).
    pub async fn go_back(&self, opts: Option<GotoOptions>) -> Result<Option<Response>> {
        self.history_nav("history.back()", opts).await
    }

    /// Navigate one entry forward in history (best-effort; returns no response).
    pub async fn go_forward(&self, opts: Option<GotoOptions>) -> Result<Option<Response>> {
        self.history_nav("history.forward()", opts).await
    }

    async fn history_nav(
        &self,
        expr: &str,
        opts: Option<GotoOptions>,
    ) -> Result<Option<Response>> {
        let opts = opts.unwrap_or_default();
        // `history.back()/forward()` returns true iff a navigation occurred.
        let navigated: bool = self.evaluate(expr).await.unwrap_or(false);
        if navigated {
            let wait = opts.wait_until_or_default();
            let mut rx = self.inner.session.subscribe();
            let timeout = opts
                .timeout
                .unwrap_or_else(|| self.default_navigation_timeout());
            let _ = self
                .wait_lifecycle(&mut rx, None, wait, timeout, "history navigation")
                .await;
        }
        Ok(None)
    }

    /// Wait until the page URL matches `url` (exact, or `*` glob), then optionally
    /// wait for a lifecycle state.
    pub async fn wait_for_url(&self, url: &str, opts: Option<GotoOptions>) -> Result<()> {
        let opts = opts.unwrap_or_default();
        let timeout = opts
            .timeout
            .unwrap_or_else(|| self.default_navigation_timeout());
        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let cur = self.url().await.unwrap_or_default();
            if glob_matches(url, &cur) {
                break;
            }
            if tokio::time::Instant::now() >= deadline {
                return Err(Error::Timeout(format!(
                    "wait_for_url '{url}' timed out after {}ms (last: '{cur}')",
                    timeout.as_millis()
                )));
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
        if let Some(state) = opts.wait_until {
            self.wait_for_load_state(Some(state)).await?;
        }
        Ok(())
    }

    /// Set the default navigation timeout (ms), separate from action timeout.
    pub fn set_default_navigation_timeout(&self, ms: u64) {
        self.inner
            .default_navigation_timeout_ms
            .store(ms, Ordering::Relaxed);
    }

    /// Emulate CSS media (media / color-scheme / reduced-motion).
    pub async fn emulate_media(&self, opts: Option<EmulateMediaOptions>) -> Result<()> {
        use crate::options::{ColorScheme, Media, ReducedMotion};
        let opts = opts.unwrap_or_default();
        let mut params = json!({});
        if let Some(m) = opts.media {
            params["media"] = json!(match m {
                Media::Screen => "screen",
                Media::Print => "print",
            });
        }
        let mut features = Vec::new();
        if let Some(cs) = opts.color_scheme {
            features.push(json!({
                "name": "prefers-color-scheme",
                "value": match cs {
                    ColorScheme::Light => "light",
                    ColorScheme::Dark => "dark",
                    ColorScheme::NoPreference => "no-preference",
                }
            }));
        }
        if let Some(rm) = opts.reduced_motion {
            features.push(json!({
                "name": "prefers-reduced-motion",
                "value": match rm {
                    ReducedMotion::Reduce => "reduce",
                    ReducedMotion::NoPreference => "no-preference",
                }
            }));
        }
        if !features.is_empty() {
            params["features"] = json!(features);
        }
        self.inner
            .session
            .send("Emulation.setEmulatedMedia", params)
            .await
            .map(|_: Value| ())
    }

    /// Toggle network offline emulation.
    pub async fn set_offline(&self, offline: bool) -> Result<()> {
        let params = if offline {
            json!({ "offline": true, "latency": 0, "downloadThroughput": 0, "uploadThroughput": 0 })
        } else {
            json!({ "offline": false, "latency": 0, "downloadThroughput": -1, "uploadThroughput": -1 })
        };
        self.inner
            .session
            .send("Network.emulateNetworkConditions", params)
            .await
            .map(|_: Value| ())
    }

    /// Drag the element matched by `source` onto the element matched by `target`.
    pub async fn drag_and_drop(
        &self,
        source: &str,
        target: &str,
        options: Option<DragToOptions>,
    ) -> Result<()> {
        let src = self.locator(source);
        let tgt = self.locator(target);
        src.drag_to(&tgt, options).await
    }

    // --- content & evaluation ---

    pub async fn url(&self) -> Result<String> {
        self.evaluate::<String>("location.href").await
    }

    pub async fn title(&self) -> Result<String> {
        self.evaluate::<String>("document.title").await
    }

    pub async fn content(&self) -> Result<String> {
        self.evaluate::<String>("document.documentElement.outerHTML").await
    }

    pub async fn set_content(&self, html: &str) -> Result<()> {
        let _ = selectors::eval_context(
            &self.inner.session,
            self.ctx().await,
            "(html) => { document.open(); document.write(html); document.close(); }",
            json!(html),
        )
        .await?;
        Ok(())
    }

    /// Evaluate a JS expression in the main world, returning a typed result.
    ///
    /// `expression` is wrapped as `(arg) => { return (<expression>); }`.
    pub async fn evaluate<R: DeserializeOwned>(&self, expression: &str) -> Result<R> {
        let function = format!("(arg) => {{ return ({expression}); }}");
        let v = selectors::eval_context(&self.inner.session, self.ctx().await, &function, Value::Null)
            .await?;
        serde_json::from_value::<R>(v).map_err(Error::from)
    }

    /// Evaluate a JS expression with a JSON-serializable argument.
    pub async fn evaluate_with_arg<R: DeserializeOwned, T: serde::Serialize>(
        &self,
        expression: &str,
        arg: &T,
    ) -> Result<R> {
        let function = format!("(arg) => {{ return ({expression}); }}");
        let arg_val = serde_json::to_value(arg)?;
        let v = selectors::eval_context(&self.inner.session, self.ctx().await, &function, arg_val)
            .await?;
        serde_json::from_value::<R>(v).map_err(Error::from)
    }

    /// Poll `expression` until it evaluates to a truthy value, then return the
    /// deserialized result. Mirrors Playwright's `page.waitForFunction`.
    ///
    /// `expression` is wrapped as `(arg) => { return (<expression>); }` (the
    /// same form as [`Page::evaluate`]). A value is considered truthy unless it
    /// is `null`, `false`, `0`, or `""`. On timeout (default 30s) this returns
    /// [`Error::Timeout`]. Polls every `polling_interval` ms (default 100).
    pub async fn wait_for_function<R: DeserializeOwned>(
        &self,
        expression: &str,
        arg: Option<Value>,
        options: Option<WaitForFunctionOptions>,
    ) -> Result<R> {
        let opts = options.unwrap_or_default();
        let timeout = Duration::from_millis(opts.timeout.unwrap_or_else(|| self.default_timeout().as_millis() as f64) as u64);
        let poll = Duration::from_millis(opts.polling_interval.unwrap_or(100.0) as u64);
        let function = format!("(arg) => {{ return ({expression}); }}");
        let arg_val = arg.unwrap_or(Value::Null);

        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let v =
                selectors::eval_context(&self.inner.session, self.ctx().await, &function, arg_val.clone())
                    .await?;
            if is_truthy(&v) {
                return serde_json::from_value::<R>(v).map_err(Error::from);
            }
            if tokio::time::Instant::now() >= deadline {
                return Err(Error::Timeout(format!(
                    "wait_for_function timed out after {}ms (expression: {expression})",
                    timeout.as_millis()
                )));
            }
            tokio::time::sleep(poll).await;
        }
    }

    /// Evaluate `expression` against the first element matching `selector`.
    pub async fn eval_on_selector<R: DeserializeOwned>(
        &self,
        selector: &str,
        expression: &str,
    ) -> Result<R> {
        let object_id = self
            .resolve_strict(selector, Some(0))
            .await?
            .ok_or_else(|| Error::ElementNotFound(selector.to_string()))?;
        let function = format!("(el) => {{ return ({expression}); }}");
        let v = selectors::eval_object(&self.inner.session, &object_id, &function, Value::Null)
            .await?;
        self.release_object(&object_id).await;
        serde_json::from_value::<R>(v).map_err(Error::from)
    }

    /// Evaluate `expression` against all elements matching `selector`.
    pub async fn eval_on_selector_all<R: DeserializeOwned>(
        &self,
        selector: &str,
        expression: &str,
    ) -> Result<Vec<R>> {
        let n = selectors::count(&self.inner.session, self.ctx().await, selector).await?;
        let mut out = Vec::with_capacity(n);
        for i in 0..n {
            if let Some(oid) = selectors::element_at(&self.inner.session, self.ctx().await, selector, i).await? {
                let function = format!("(el) => {{ return ({expression}); }}");
                let v = selectors::eval_object(&self.inner.session, &oid, &function, Value::Null).await?;
                self.release_object(&oid).await;
                out.push(serde_json::from_value::<R>(v).map_err(Error::from)?);
            }
        }
        Ok(out)
    }

    async fn release_object(&self, object_id: &str) {
        let _ = self
            .inner
            .session
            .send("Runtime.releaseObject", json!({ "objectId": object_id }))
            .await;
    }

    // --- viewport / screenshot ---

    pub async fn set_viewport_size(&self, viewport: Viewport) -> Result<()> {
        *self.inner.viewport.lock() = Some(viewport);
        self.inner
            .session
            .send(
                "Emulation.setDeviceMetricsOverride",
                json!({
                    "width": viewport.width,
                    "height": viewport.height,
                    "deviceScaleFactor": 1,
                    "mobile": false,
                }),
            )
            .await?;
        Ok(())
    }

    pub async fn screenshot(&self, opts: Option<ScreenshotOptions>) -> Result<Vec<u8>> {
        let opts = opts.unwrap_or_default();
        let format = match opts.r#type.unwrap_or_default() {
            crate::types::ScreenshotType::Png => "png",
            crate::types::ScreenshotType::Jpeg => "jpeg",
            crate::types::ScreenshotType::Webp => "webp",
        };
        let mut params = json!({ "format": format });
        if opts.full_page.unwrap_or(false) {
            params["captureBeyondViewport"] = json!(true);
        }
        if opts.omit_background.unwrap_or(false) && format == "png" {
            params["omitBackground"] = json!(true);
        }
        let resp = self
            .inner
            .session
            .send("Page.captureScreenshot", params)
            .await?;
        let data = resp
            .get("data")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::ProtocolError("screenshot missing data".into()))?;
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(data)
            .map_err(|e| Error::ProtocolError(format!("base64 decode: {e}")))?;
        if let Some(path) = &opts.path {
            tokio::fs::write(path, &bytes).await?;
        }
        Ok(bytes)
    }

    // --- headers / init scripts ---

    /// Inject a `<script>` tag into the page (inline `content` and/or `url`).
    pub async fn add_script_tag(
        &self,
        content: Option<&str>,
        url: Option<&str>,
    ) -> Result<()> {
        let arg = json!({ "content": content, "url": url });
        let _ = selectors::eval_context(
            &self.inner.session,
            self.ctx().await,
            "(a) => { const s = document.createElement('script'); if (a.url) s.src = a.url; if (a.content) s.textContent = a.content; document.head.appendChild(s); }",
            arg,
        )
        .await?;
        Ok(())
    }

    /// Inject a `<style>` tag into the page.
    pub async fn add_style_tag(&self, content: &str) -> Result<()> {
        let _ = selectors::eval_context(
            &self.inner.session,
            self.ctx().await,
            "(a) => { const s = document.createElement('style'); s.textContent = a; document.head.appendChild(s); }",
            json!(content),
        )
        .await?;
        Ok(())
    }

    /// Enable/disable the HTTP cache for this page.
    pub async fn set_cache_disabled(&self, disabled: bool) -> Result<()> {
        self.inner
            .session
            .send("Network.setCacheDisabled", json!({ "cacheDisabled": disabled }))
            .await
            .map(|_: Value| ())
    }

    /// Bring the page to the front (focus).
    pub async fn bring_to_front(&self) -> Result<()> {
        self.inner
            .session
            .send("Page.bringToFront", json!({}))
            .await
            .map(|_: Value| ())
    }

    /// Override geolocation `(latitude, longitude)` (or clear with `None`).
    /// Requires a granted `geolocation` permission.
    pub async fn set_geolocation(&self, geolocation: Option<(f64, f64)>) -> Result<()> {
        let params = match geolocation {
            Some((lat, lon)) => json!({ "latitude": lat, "longitude": lon }),
            None => json!({}),
        };
        self.inner
            .session
            .send("Emulation.setGeolocationOverride", params)
            .await
            .map(|_: Value| ())
    }

    /// Return a standalone HTTP client ([`APIRequestContext`]) tied to this
    /// page. The client shares no state with the browser tab — it is a direct
    /// HTTP client useful for API testing.
    ///
    /// Note: the page does not retain its `extra_http_headers` in Rust (they
    /// are applied directly to CDP), so the returned context starts with an
    /// empty default header set. Use [`BrowserContext::request`] to seed
    /// defaults from the context.
    pub fn request(&self) -> APIRequestContext {
        APIRequestContext::new(Headers::new())
    }

    pub async fn set_extra_http_headers(&self, headers: Headers) -> Result<()> {
        // CDP wants an array of {name, value}.
        let list: Vec<Value> = headers
            .iter()
            .map(|(k, v)| json!({ "name": k, "value": v }))
            .collect();
        self.inner
            .session
            .send("Network.setExtraHTTPHeaders", json!({ "headers": list }))
            .await?;
        Ok(())
    }

    pub async fn add_init_script(&self, script: &str) -> Result<()> {
        let _ = self
            .inner
            .session
            .send(
                "Page.addScriptToEvaluateOnNewDocument",
                json!({ "source": script }),
            )
            .await;
        // Also run once in the current context.
        let _ = selectors::eval_context(
            &self.inner.session,
            self.ctx().await,
            "(s) => { (0, eval)(s); }",
            json!(script),
        )
        .await;
        Ok(())
    }

    /// Expose a Rust function to the page as `window[name]`.
    ///
    /// After this returns, page JS can call `await window.<name>(...args)` and
    /// receive the Rust `callback`'s return value (serialized as JSON). Mirrors
    /// Playwright's `page.exposeFunction`.
    ///
    /// The `callback` receives the JS arguments as a `Vec<serde_json::Value>`
    /// and returns a `serde_json::Value`. If the callback panics or its result
    /// fails to serialize, the JS promise resolves with
    /// `{ "__error": "<message>" }` rather than rejecting.
    ///
    /// # Mechanism
    /// A CDP binding is registered under the internal name `__pwcdpInvoke_<name>`
    /// via `Runtime.addBinding`. A JS wrapper turns `window[name]` into a
    /// Promise-returning function that forwards `{ id, args }` to that binding
    /// (as a JSON string). A per-registration listener handles
    /// `Runtime.bindingCalled`, invokes the callback on its own task, and
    /// resolves the Promise by evaluating against the pending-callback map.
    ///
    /// The wrapper is installed for future documents via
    /// `Page.addScriptToEvaluateOnNewDocument` and once in the current context.
    /// Bindings are per-execution-context and reset on navigation: the wrapper
    /// is re-installed on every new document, but `Runtime.addBinding` is only
    /// re-asserted lazily if needed (it persists across same-origin navigations
    /// on a live page session; call `expose_function` again after a cross-origin
    /// navigation if the binding goes missing).
    pub async fn expose_function<F, Fut>(&self, name: &str, callback: F) -> Result<()>
    where
        F: Fn(Vec<Value>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Value> + Send + 'static,
    {
        // Wrap the typed callback in an erased `Arc<dyn Fn>` so the listener
        // task can invoke it without carrying generics.
        let handler: ExposedBindingHandler =
            Arc::new(move |args| Box::pin(callback(args)));

        // Register the CDP binding under a distinct internal name so it does not
        // clash with the Promise-returning `window[name]` wrapper.
        let binding_name = internal_binding_name(name);
        let _ = self
            .inner
            .session
            .send("Runtime.addBinding", json!({ "name": binding_name }))
            .await;

        // Install the JS wrapper for future documents...
        let wrapper = binding_wrapper_source(name);
        let _ = self
            .inner
            .session
            .send(
                "Page.addScriptToEvaluateOnNewDocument",
                json!({ "source": wrapper }),
            )
            .await;
        // ...and once in the current context (idempotent).
        let _ = selectors::eval_context(
            &self.inner.session,
            self.ctx().await,
            "(s) => { (0, eval)(s); }",
            json!(wrapper),
        )
        .await;

        // Per-registration listener: dispatch bindingCalled -> callback -> resolve.
        let mut rx = self.inner.session.subscribe();
        let session = Arc::clone(&self.inner.session);
        let name_owned = name.to_string();
        tokio::spawn(async move {
            binding_listener(&mut rx, &session, &name_owned, &handler).await;
        });

        Ok(())
    }

    // --- locators ---

    pub fn locator(&self, selector: impl Into<String>) -> Locator {
        Locator::new(self.clone(), selector.into(), true, None)
    }

    /// Return a [`FrameLocator`] scoped to the same-origin `<iframe>` matched
    /// by `selector`. Element queries on the returned locator resolve inside
    /// the iframe's `contentDocument`.
    ///
    /// **Same-origin only.** Cross-origin iframes cannot be reached from the
    /// page's main world; their `contentDocument` reads as `null`, and queries
    /// against them will report zero matches. `srcdoc` iframes and same-origin
    /// `src` iframes are supported.
    pub fn frame_locator(&self, selector: impl Into<String>) -> FrameLocator {
        FrameLocator::new(self.clone(), selector.into())
    }

    pub fn get_by_text(&self, text: &str, _exact: bool) -> Locator {
        // Minimal engine treats `text=` as case-insensitive substring.
        self.locator(format!("text={text}"))
    }

    pub fn get_by_label(&self, text: &str) -> Locator {
        self.locator(format!("[aria-label=\"{}\"]", attr_escape(text)))
    }

    pub fn get_by_placeholder(&self, text: &str) -> Locator {
        self.locator(format!("[placeholder=\"{}\"]", attr_escape(text)))
    }

    pub fn get_by_alt_text(&self, text: &str) -> Locator {
        self.locator(format!("[alt=\"{}\"]", attr_escape(text)))
    }

    pub fn get_by_title(&self, text: &str) -> Locator {
        self.locator(format!("[title=\"{}\"]", attr_escape(text)))
    }

    pub fn get_by_test_id(&self, text: &str) -> Locator {
        self.locator(format!("[data-testid=\"{}\"]", attr_escape(text)))
    }

    pub fn get_by_role(&self, role: AriaRole, opts: Option<crate::options::GetByRoleOptions>) -> Locator {
        let opts = opts.unwrap_or_default();
        let mut sel = format!("role={}", role.as_str());
        if let Some(name) = &opts.name {
            sel.push_str(&format!("[name=\"{name}\"]"));
        }
        if opts.exact == Some(true) {
            sel.push_str("[exact=\"true\"]");
        }
        Locator::new(self.clone(), sel, true, None)
    }

    /// (Internal) resolve a selector to a single element RemoteObjectId,
    /// enforcing strict mode unless `index` was explicitly chosen.
    pub(crate) async fn resolve_strict(
        &self,
        selector: &str,
        forced_index: Option<usize>,
    ) -> Result<Option<String>> {
        let n = selectors::count(&self.inner.session, self.ctx().await, selector).await?;
        if n == 0 {
            return Ok(None);
        }
        let index = forced_index.unwrap_or_else(|| {
            // Strict callers (no forced index) pick 0; strict-violation is the
            // caller's responsibility. See Locator::resolve.
            0
        });
        selectors::element_at(&self.inner.session, self.ctx().await, selector, index).await
    }

    /// The first element matching `selector`, if any.
    pub async fn query_selector(&self, selector: &str) -> Result<Option<ElementHandle>> {
        let oid = self.resolve_strict(selector, Some(0)).await?;
        Ok(oid.map(|oid| ElementHandle::new(self.clone(), oid)))
    }

    /// All elements matching `selector`.
    pub async fn query_selector_all(&self, selector: &str) -> Result<Vec<ElementHandle>> {
        let n = selectors::count(&self.inner.session, self.ctx().await, selector).await?;
        let mut out = Vec::with_capacity(n);
        for i in 0..n {
            if let Some(oid) =
                selectors::element_at(&self.inner.session, self.ctx().await, selector, i).await?
            {
                out.push(ElementHandle::new(self.clone(), oid));
            }
        }
        Ok(out)
    }

    // --- input devices & frames ---

    pub fn keyboard(&self) -> Keyboard {
        Keyboard::new(self.clone())
    }

    pub fn mouse(&self) -> Mouse {
        Mouse::with_pos(self.clone(), Arc::clone(&self.inner.mouse_pos))
    }

    pub fn touchscreen(&self) -> Touchscreen {
        Touchscreen::with_flag(self.clone(), Arc::clone(&self.inner.touch_emulation_started))
    }

    pub fn main_frame(&self) -> Frame {
        Frame::main(self.clone())
    }

    /// All frames in the page (refreshed from the browser).
    pub async fn frames(&self) -> Result<Vec<Frame>> {
        self.refresh_frame_tree().await?;
        let ids: Vec<String> = self.inner.frames.lock().keys().cloned().collect();
        Ok(ids.into_iter().map(|id| Frame::new(self.clone(), id)).collect())
    }

    /// Refresh the cached frame tree from `Page.getFrameTree`.
    pub(crate) async fn refresh_frame_tree(&self) -> Result<()> {
        let resp = self
            .inner
            .session
            .send("Page.getFrameTree", json!({}))
            .await?;
        if let Some(tree) = resp.get("frameTree") {
            let mut frames = self.inner.frames.lock();
            frames.clear();
            walk_frame_tree(tree, &mut frames);
            if let Some(id) = tree
                .get("frame")
                .and_then(|f| f.get("id"))
                .and_then(|v| v.as_str())
            {
                *self.inner.main_frame_id.lock() = Some(id.to_string());
            }
        }
        Ok(())
    }

    pub(crate) fn main_frame_id(&self) -> Option<String> {
        self.inner.main_frame_id.lock().clone()
    }

    pub(crate) fn frame_data(&self, frame_id: &str) -> Option<FrameData> {
        self.inner.frames.lock().get(frame_id).cloned()
    }

    pub(crate) fn frame_ids_with_parent(&self, parent: &str) -> Vec<String> {
        self.inner
            .frames
            .lock()
            .iter()
            .filter(|(_, d)| d.parent_id.as_deref() == Some(parent))
            .map(|(k, _)| k.clone())
            .collect()
    }

    // --- events ---

    pub fn on_console<F, Fut>(&self, handler: F)
    where
        F: Fn(ConsoleMessage) -> Fut + Send + Sync + 'static,
        Fut: std::future::Future<Output = ()> + Send + 'static,
    {
        let mut rx = self.inner.session.subscribe();
        tokio::spawn(async move {
            while let Ok(ev) = rx.recv().await {
                if ev.method == "Runtime.consoleAPICalled" {
                    let msg = parse_console(&ev.params);
                    handler(msg).await;
                }
            }
        });
    }

    pub fn on_dialog<F, Fut>(&self, handler: F)
    where
        F: Fn(Dialog) -> Fut + Send + Sync + 'static,
        Fut: std::future::Future<Output = ()> + Send + 'static,
    {
        let mut rx = self.inner.session.subscribe();
        let session = Arc::clone(&self.inner.session);
        tokio::spawn(async move {
            while let Ok(ev) = rx.recv().await {
                if ev.method == "Page.javascriptDialogOpening" {
                    let dialog = Dialog::from_event(&ev.params, &session);
                    handler(dialog).await;
                }
            }
        });
    }

    /// Register a handler invoked for each network request sent.
    pub fn on_request<F, Fut>(&self, handler: F)
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let h: RequestHandler = Arc::new(move |r| Box::pin(handler(r)));
        self.inner.on_request_handlers.lock().push(h);
    }

    /// Register a handler invoked for each network response received.
    pub fn on_response<F, Fut>(&self, handler: F)
    where
        F: Fn(Response) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let h: ResponseHandler = Arc::new(move |r| Box::pin(handler(r)));
        self.inner.on_response_handlers.lock().push(h);
    }

    /// Register a handler invoked when a network request fails.
    pub fn on_requestfailed<F, Fut>(&self, handler: F)
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let h: RequestHandler = Arc::new(move |r| Box::pin(handler(r)));
        self.inner.on_requestfailed_handlers.lock().push(h);
    }

    /// Register a handler invoked when an uncaught page error occurs.
    pub fn on_pageerror<F, Fut>(&self, handler: F)
    where
        F: Fn(String) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let mut rx = self.inner.session.subscribe();
        tokio::spawn(async move {
            while let Ok(ev) = rx.recv().await {
                if ev.method == "Runtime.exceptionThrown" {
                    let msg = ev
                        .params
                        .get("exceptionDetails")
                        .and_then(|d| d.get("exception"))
                        .and_then(|e| e.get("description"))
                        .and_then(|v| v.as_str())
                        .unwrap_or("unknown error")
                        .to_string();
                    handler(msg).await;
                }
            }
        });
    }

    /// Register a handler invoked when a network request finishes loading.
    pub fn on_requestfinished<F, Fut>(&self, handler: F)
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let mut rx = self.inner.session.subscribe();
        let store = Arc::clone(&self.inner.network_store);
        tokio::spawn(async move {
            while let Ok(ev) = rx.recv().await {
                if ev.method == "Network.loadingFinished" {
                    if let Some(rid) = ev.params.get("requestId").and_then(|v| v.as_str()) {
                        if let Some(req) = store.get_request(rid) {
                            handler(req).await;
                        }
                    }
                }
            }
        });
    }

    /// Register a handler invoked when the page closes.
    pub fn on_close<F, Fut>(&self, handler: F)
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let h: CloseHandler = Arc::new(move || Box::pin(handler()));
        self.inner.on_close_handlers.lock().push(h);
    }

    /// Register a handler invoked for each file download (`Page.downloadWillBegin`).
    ///
    /// On first registration, downloads are routed to a per-page temp directory
    /// via `Page.setDownloadBehavior` `allow`. Progress events update the
    /// download's shared state so [`Download::path`] / [`Download::save_as`]
    /// can await completion.
    pub fn on_download<F, Fut>(&self, handler: F)
    where
        F: Fn(Download) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        // Lazily set up the download behavior + listener task exactly once.
        if self
            .inner
            .download_started
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
        {
            let dir = match tempfile::TempDir::new() {
                Ok(d) => Arc::new(d),
                Err(e) => {
                    tracing::error!("failed to create download temp dir: {e}");
                    return;
                }
            };
            let dir_path = dir.path().to_path_buf();
            *self.inner.download_dir.lock() = Some(Arc::clone(&dir));
            *self.inner.download_path.lock() = Some(dir_path.clone());

            // Tell Chrome to save downloads into our temp dir.
            let session_for_setup = Arc::clone(&self.inner.session);
            let setup_path = dir_path.clone();
            tokio::spawn(async move {
                let _ = session_for_setup
                    .send(
                        "Page.setDownloadBehavior",
                        json!({ "behavior": "allow", "downloadPath": setup_path }),
                    )
                    .await;
            });

            // Listener task: maps downloadWillBegin -> Download, downloadProgress -> state.
            let mut rx = self.inner.session.subscribe();
            let session = Arc::clone(&self.inner.session);
            let states = Arc::clone(&self.inner.download_states);
            let download_path = dir_path.clone();
            // The handler is wrapped in an Arc and invoked from the task. We
            // hold a Page clone so each Download can reference its page.
            let page = self.clone();
            let handler: Arc<dyn Fn(Download) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync> =
                Arc::new(move |d| Box::pin(handler(d)));
            tokio::spawn(async move {
                download_listener(
                    &mut rx,
                    &session,
                    &states,
                    &download_path,
                    page.clone(),
                    &handler,
                )
                .await;
            });
        }
    }

    /// Register a handler invoked when a file-chooser dialog opens
    /// (`Page.fileChooserOpened`), mirroring Playwright's `page.on('filechooser')`.
    ///
    /// On first registration, chooser interception is enabled once via
    /// `Page.setInterceptFileChooserDialog { enabled: true }` (must be in place
    /// before the action that opens the chooser). The handler may inspect the
    /// [`FileChooser`] and call [`FileChooser::set_files`] to accept it.
    pub async fn on_filechooser<F, Fut>(&self, handler: F)
    where
        F: Fn(FileChooser) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        // Lazily enable interception + spawn the listener task exactly once.
        if self
            .inner
            .filechooser_started
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
        {
            // Subscribe before enabling so the first fileChooserOpened event
            // is never missed.
            let mut rx = self.inner.session.subscribe();
            // Enable interception and await it inline so the caller knows it is
            // in place before triggering the chooser.
            let _ = self
                .inner
                .session
                .send(
                    "Page.setInterceptFileChooserDialog",
                    json!({ "enabled": true }),
                )
                .await;

            // Wrap the handler in an Arc for invocation from the task.
            let page = self.clone();
            let handler: Arc<
                dyn Fn(FileChooser) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>>
                    + Send
                    + Sync,
            > = Arc::new(move |fc| Box::pin(handler(fc)));
            tokio::spawn(async move {
                while let Ok(ev) = rx.recv().await {
                    if ev.method == "Page.fileChooserOpened" {
                        let multiple = ev
                            .params
                            .get("mode")
                            .and_then(|v| v.as_str())
                            == Some("selectMultiple");
                        let backend_node_id = ev
                            .params
                            .get("backendNodeId")
                            .and_then(|v| v.as_i64());
                        let fc = FileChooser::new(page.clone(), backend_node_id, multiple);
                        let h = Arc::clone(&handler);
                        tokio::spawn(async move {
                            (h)(fc).await;
                        });
                    }
                }
            });
        }
    }

    /// Register a handler invoked when a web/service/shared worker is created,
    /// mirroring Playwright's `page.on('worker')`.
    ///
    /// On first registration, flattened auto-attach is enabled on the page
    /// session (`Target.setAutoAttach { flatten: true }`) so workers show up as
    /// child sessions on the same connection. Each child target of type
    /// `worker`/`service_worker`/`shared_worker` surfaces via
    /// `Target.attachedToTarget` and is wrapped in a [`Worker`].
    ///
    /// Subscribe before enabling so the first `attachedToTarget` is never missed.
    pub async fn on_worker<F, Fut>(&self, handler: F)
    where
        F: Fn(Worker) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        // Lazily enable page-session auto-attach + spawn the listener once.
        if self
            .inner
            .worker_started
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
        {
            // Subscribe BEFORE enabling auto-attach so the attach event for a
            // worker spawned right after is captured.
            let mut rx = self.inner.session.subscribe();
            let _ = self
                .inner
                .session
                .send(
                    "Target.setAutoAttach",
                    json!({ "autoAttach": true, "waitForDebuggerOnStart": false, "flatten": true }),
                )
                .await;

            let connection = self.inner.session.connection().clone();
            let handler: Arc<
                dyn Fn(Worker) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,
            > = Arc::new(move |w| Box::pin(handler(w)));
            tokio::spawn(async move {
                while let Ok(ev) = rx.recv().await {
                    if ev.method != "Target.attachedToTarget" {
                        continue;
                    }
                    // Defensive casing: `sessionId` (modern) then `session_id`.
                    let session_id = ev
                        .params
                        .get("sessionId")
                        .or_else(|| ev.params.get("session_id"))
                        .and_then(|v| v.as_str());
                    let target_info = match ev.params.get("targetInfo") {
                        Some(t) => t,
                        None => continue,
                    };
                    let target_type = target_info
                        .get("type")
                        .and_then(|v| v.as_str())
                        .unwrap_or("");
                    // Only workers — skip iframes, pages, popups, etc.
                    if !matches!(target_type, "worker" | "service_worker" | "shared_worker") {
                        continue;
                    }
                    let (sid, url) = match (session_id, target_info.get("url").and_then(|v| v.as_str())) {
                        (Some(sid), Some(url)) => (sid.to_string(), url.to_string()),
                        _ => continue,
                    };
                    let worker = Worker::new(connection.clone(), sid, url);
                    // Enable Runtime on the worker session so evaluate works.
                    worker.enable_runtime().await;
                    let h = Arc::clone(&handler);
                    tokio::spawn(async move {
                        (h)(worker).await;
                    });
                }
            });
        }
    }

    // --- close ---

    pub async fn close(&self) -> Result<()> {
        if *self.inner.closed.lock() {
            return Ok(());
        }
        *self.inner.closed.lock() = true;
        let handlers = std::mem::take(&mut *self.inner.on_close_handlers.lock());
        for h in handlers {
            tokio::spawn(async move { (h)().await; });
        }
        let _ = self
            .inner
            .browser
            .browser_session()
            .send("Target.closeTarget", json!({ "targetId": self.inner.target_id }))
            .await;
        Ok(())
    }

    // --- network interception (Fetch domain) ---

    /// Intercept requests matching `pattern` (a URL glob, `*`-wildcarded) and
    /// route them to `handler`. The handler must continue/fulfill/abort the
    /// [`Route`] (an unhandled route stalls the request).
    pub async fn route<F, Fut>(&self, pattern: &str, handler: F) -> Result<()>
    where
        F: Fn(Route) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let entry = RouteEntry {
            pattern: pattern.to_string(),
            handler: Arc::new(move |r| Box::pin(handler(r))),
        };
        self.inner.route_handlers.lock().push(entry);
        self.ensure_route_listener().await;
        self.refresh_fetch_patterns().await
    }

    /// Remove the first route registered with exactly `pattern`.
    pub async fn unroute(&self, pattern: &str) -> Result<()> {
        let mut handlers = self.inner.route_handlers.lock();
        if let Some(pos) = handlers.iter().position(|e| e.pattern == pattern) {
            handlers.remove(pos);
        }
        drop(handlers);
        self.refresh_fetch_patterns().await
    }

    /// Remove all routes.
    pub async fn unroute_all(&self) -> Result<()> {
        self.inner.route_handlers.lock().clear();
        let _ = self.inner.session.send("Fetch.disable", json!({})).await;
        Ok(())
    }

    async fn ensure_route_listener(&self) {
        if self
            .inner
            .route_started
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
        {
            let rx = self.inner.session.subscribe();
            let session = Arc::clone(&self.inner.session);
            let store = Arc::clone(&self.inner.network_store);
            let handlers = Arc::clone(&self.inner.route_handlers);
            tokio::spawn(async move {
                route_listener(rx, session, store, handlers).await;
            });
        }
    }

    async fn refresh_fetch_patterns(&self) -> Result<()> {
        let patterns: Vec<Value> = self
            .inner
            .route_handlers
            .lock()
            .iter()
            .map(|e| json!({ "urlPattern": e.pattern }))
            .collect();
        if patterns.is_empty() {
            let _ = self.inner.session.send("Fetch.disable", json!({})).await;
        } else {
            self.inner
                .session
                .send("Fetch.enable", json!({ "patterns": patterns }))
                .await?;
        }
        Ok(())
    }

    // --- Tier 3 stubs (API completeness) ---

    pub async fn pdf(&self, opts: Option<crate::options::PdfOptions>) -> Result<Vec<u8>> {
        let opts = opts.unwrap_or_default();
        let mut params = json!({ "printBackground": opts.print_background.unwrap_or(true) });
        if let Some(fmt) = opts.format {
            let (w, h) = fmt.inches();
            params["paperWidth"] = json!(w);
            params["paperHeight"] = json!(h);
        }
        if let Some(l) = opts.landscape {
            params["landscape"] = json!(l);
        }
        if let Some(s) = opts.scale {
            params["scale"] = json!(s);
        }
        if let Some(p) = opts.prefer_css_page_size {
            params["preferCSSPageSize"] = json!(p);
        }
        if let Some(m) = opts.margin {
            if let Some(v) = m.top {
                params["marginTop"] = json!(v);
            }
            if let Some(v) = m.bottom {
                params["marginBottom"] = json!(v);
            }
            if let Some(v) = m.left {
                params["marginLeft"] = json!(v);
            }
            if let Some(v) = m.right {
                params["marginRight"] = json!(v);
            }
        }
        let resp = self.inner.session.send("Page.printToPDF", params).await?;
        let data = resp
            .get("data")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::ProtocolError("pdf missing data".into()))?;
        Ok(base64::engine::general_purpose::STANDARD
            .decode(data)
            .map_err(|e| Error::ProtocolError(format!("pdf base64 decode: {e}")))?)
    }

    /// Capture an aria-snapshot (Playwright's YAML-ish accessibility-tree
    /// format) of the whole page.
    ///
    /// Fetches the full accessibility tree via `Accessibility.getFullAXTree`
    /// and serializes it with [`crate::aria_snapshot`]. The Accessibility
    /// domain is enabled best-effort first (some Chrome builds require it).
    pub async fn aria_snapshot(&self) -> Result<String> {
        let _ = self
            .inner
            .session
            .send("Accessibility.enable", json!({}))
            .await;
        let resp = self
            .inner
            .session
            .send("Accessibility.getFullAXTree", json!({}))
            .await?;
        let nodes = resp
            .get("nodes")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();
        Ok(crate::aria_snapshot::serialize(&nodes, None))
    }
}

fn attr_escape(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Whether a JSON value is "truthy" for `wait_for_function`: `null`, `false`,
/// `0`, and `""` are not-yet-truthy; everything else (objects, arrays, nonzero
/// numbers, non-empty strings) is truthy.
fn is_truthy(v: &Value) -> bool {
    match v {
        Value::Null => false,
        Value::Bool(b) => *b,
        Value::Number(n) => n.as_f64().map(|f| f != 0.0).unwrap_or(true),
        Value::String(s) => !s.is_empty(),
        _ => true,
    }
}

/// Match `pattern` against `value`: exact, or a leading/trailing/both `*` glob
/// (good enough for `wait_for_url`).
fn glob_matches(pattern: &str, value: &str) -> bool {
    if pattern == value {
        return true;
    }
    // `*middle*` → contains.
    if pattern.len() >= 2 && pattern.starts_with('*') && pattern.ends_with('*') {
        return value.contains(&pattern[1..pattern.len() - 1]);
    }
    if let Some(rest) = pattern.strip_prefix('*') {
        if value.ends_with(rest) {
            return true;
        }
    }
    if let Some(rest) = pattern.strip_suffix('*') {
        if value.starts_with(rest) {
            return true;
        }
    }
    false
}

/// Recursively walk a `Page.getFrameTree` response into the frame store.
fn walk_frame_tree(node: &Value, frames: &mut HashMap<String, FrameData>) {
    let frame = match node.get("frame") {
        Some(f) => f,
        None => return,
    };
    let id = match frame.get("id").and_then(|v| v.as_str()) {
        Some(s) => s.to_string(),
        None => return,
    };
    let data = FrameData {
        url: frame.get("url").and_then(|v| v.as_str()).unwrap_or("").to_string(),
        name: frame.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string(),
        parent_id: frame
            .get("parentId")
            .and_then(|v| v.as_str())
            .map(String::from),
        detached: false,
    };
    frames.insert(id, data);
    if let Some(children) = node.get("childFrames").and_then(|v| v.as_array()) {
        for child in children {
            walk_frame_tree(child, frames);
        }
    }
}

/// Background task: keep the frame store fresh from `Page.frame*` events.
async fn frame_tracker(
    mut rx: broadcast::Receiver<crate::cdp::CdpEvent>,
    frames: Arc<Mutex<HashMap<String, FrameData>>>,
    main_id: Arc<Mutex<Option<String>>>,
) {
    loop {
        match rx.recv().await {
            Ok(ev) => match ev.method.as_str() {
                "Page.frameNavigated" => {
                    if let Some(frame) = ev.params.get("frame") {
                        let id = match frame.get("id").and_then(|v| v.as_str()) {
                            Some(s) => s.to_string(),
                            None => continue,
                        };
                        let parent = frame
                            .get("parentId")
                            .and_then(|v| v.as_str())
                            .map(String::from);
                        let data = FrameData {
                            url: frame.get("url").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                            name: frame.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                            parent_id: parent.clone(),
                            detached: false,
                        };
                        if parent.is_none() {
                            *main_id.lock() = Some(id.clone());
                        }
                        frames.lock().insert(id, data);
                    }
                }
                "Page.frameDetached" => {
                    if let Some(id) = ev.params.get("frameId").and_then(|v| v.as_str()) {
                        if let Some(d) = frames.lock().get_mut(id) {
                            d.detached = true;
                        }
                    }
                }
                _ => {}
            },
            Err(broadcast::error::RecvError::Closed) => break,
            Err(broadcast::error::RecvError::Lagged(_)) => continue,
        }
    }
}

/// Background task: dispatch `Page.downloadWillBegin`/`downloadProgress` events.
async fn download_listener(
    rx: &mut broadcast::Receiver<crate::cdp::CdpEvent>,
    _session: &Arc<CdpSession>,
    states: &Arc<Mutex<HashMap<String, DownloadStateCell>>>,
    download_path: &std::path::Path,
    page: Page,
    handler: &Arc<
        dyn Fn(Download) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,
    >,
) {
    while let Ok(ev) = rx.recv().await {
        match ev.method.as_str() {
            "Page.downloadWillBegin" => {
                let guid = ev
                    .params
                    .get("guid")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let url = ev
                    .params
                    .get("url")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let suggested = ev
                    .params
                    .get("suggestedFilename")
                    .and_then(|v| v.as_str())
                    .unwrap_or("download")
                    .to_string();
                let cell = DownloadStateCell::new();
                states.lock().insert(guid.clone(), cell.clone());
                let dl = Download::new(
                    url,
                    suggested,
                    guid,
                    cell,
                    download_path.to_path_buf(),
                    page.clone(),
                );
                let h = Arc::clone(handler);
                tokio::spawn(async move {
                    (h)(dl).await;
                });
            }
            "Page.downloadProgress" => {
                let guid = match ev.params.get("guid").and_then(|v| v.as_str()) {
                    Some(g) => g.to_string(),
                    None => continue,
                };
                let state = ev
                    .params
                    .get("state")
                    .and_then(|v| v.as_str())
                    .unwrap_or("InProgress");
                let mapped = match state {
                    "Completed" => DownloadState::Completed,
                    "Canceled" => DownloadState::Canceled,
                    _ => DownloadState::InProgress,
                };
                if let Some(cell) = states.lock().get(&guid) {
                    *cell.state.lock() = mapped;
                }
            }
            _ => {}
        }
    }
}

/// The distinct internal name under which the CDP binding for the public
/// `name` is registered (`Runtime.addBinding`). Keeping it separate avoids
/// clashing with the Promise-returning `window[name]` wrapper.
fn internal_binding_name(name: &str) -> String {
    format!("__pwcdpInvoke_{name}")
}

/// The JS wrapper that turns `window[name]` into a Promise-returning function.
/// Each call assigns a monotonic id, registers its `resolve`, and forwards
/// `{ id, args }` (as a JSON string) to the CDP binding under
/// `__pwcdpInvoke_<name>`. The Rust listener resolves the promise later.
fn binding_wrapper_source(name: &str) -> String {
    // `name` is interpolated as a JSON string literal so it is safe to embed
    // even if it contains quotes/backslashes.
    let name_json = serde_json::to_string(name).unwrap_or_else(|_| "\"\"".to_string());
    format!(
        r#"(function(){{
  var publicName = {name_json};
  var invokeName = "__pwcdpInvoke_" + publicName;
  var pending = (self.__pwcdpBindings = self.__pwcdpBindings || {{}});
  var map = pending[publicName] = pending[publicName] || {{ id: 0, cbs: {{}} }};
  self[publicName] = function(){{
    var args = Array.prototype.slice.call(arguments);
    return new Promise(function(resolve){{
      var id = ++map.id;
      map.cbs[id] = resolve;
      // The CDP binding (self[invokeName]) is installed by Runtime.addBinding;
      // if it is not present yet, surface an error so callers see a clear cause.
      if (typeof self[invokeName] !== "function") {{
        delete map.cbs[id];
        resolve({{ "__error": "binding not installed: " + invokeName }});
        return;
      }}
      try {{
        self[invokeName](JSON.stringify({{ id: id, args: args }}));
      }} catch (e) {{
        delete map.cbs[id];
        resolve({{ "__error": String((e && e.message) || e) }});
      }}
    }});
  }};
}})();
"#
    )
}

/// Background task for one `expose_function` registration: on
/// `Runtime.bindingCalled` for the internal binding name, parse the payload,
/// run the Rust callback on its own task, then resolve the JS promise.
async fn binding_listener(
    rx: &mut broadcast::Receiver<crate::cdp::CdpEvent>,
    session: &Arc<CdpSession>,
    name: &str,
    handler: &ExposedBindingHandler,
) {
    let binding_name = internal_binding_name(name);
    loop {
        match rx.recv().await {
            Ok(ev) if ev.method == "Runtime.bindingCalled" => {
                let fired_name = ev
                    .params
                    .get("name")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                if fired_name != binding_name {
                    continue;
                }
                let payload_str = match ev.params.get("payload").and_then(|v| v.as_str()) {
                    Some(s) => s,
                    None => continue,
                };
                let parsed: Value = match serde_json::from_str(payload_str) {
                    Ok(v) => v,
                    Err(_) => continue,
                };
                let id = match parsed.get("id").and_then(|v| v.as_i64()) {
                    Some(i) => i,
                    None => continue,
                };
                let args = parsed
                    .get("args")
                    .and_then(|v| v.as_array())
                    .cloned()
                    .unwrap_or_default();

                let h = Arc::clone(handler);
                let session = Arc::clone(session);
                let name_owned = name.to_string();
                // Resolve on a separate task so a slow callback doesn't stall
                // event processing.
                tokio::spawn(async move {
                    let result = (h)(args).await;
                    let result_json = serde_json::to_string(&result)
                        .unwrap_or_else(|_| r#"{"__error":"serialize failed"}"#.to_string());
                    // Re-serialize as a JSON string literal so it can be passed
                    // to JSON.parse safely (handles quotes/newlines/etc.).
                    let result_str_literal = serde_json::to_string(&result_json)
                        .unwrap_or_else(|_| r#""{\"__error\":\"serialize failed\"}""#.to_string());
                    // Resolve the pending promise: look up the resolve fn by id,
                    // call it with the parsed result, then delete the entry.
                    let name_j = serde_json::to_string(&name_owned).unwrap_or_else(|_| "\"\"".into());
                    let expr = format!(
                        "(function(){{
  var m = (self.__pwcdpBindings && self.__pwcdpBindings[{name_j}]) || null;
  if (!m || !m.cbs || !m.cbs[{id}]) return;
  var fn_ = m.cbs[{id}]; delete m.cbs[{id}];
  fn_(JSON.parse({result_str_literal}));
}})();"
                    );
                    let _ = session
                        .send(
                            "Runtime.evaluate",
                            json!({ "expression": expr, "awaitPromise": false }),
                        )
                        .await;
                });
            }
            Ok(_) => {}
            Err(broadcast::error::RecvError::Closed) => break,
            Err(broadcast::error::RecvError::Lagged(_)) => continue,
        }
    }
}

fn parse_console(params: &Value) -> ConsoleMessage {    let text = params
        .get("args")
        .and_then(|a| a.as_array())
        .map(|args| {
            args.iter()
                .filter_map(|a| {
                    a.get("value")
                        .and_then(|v| v.as_str())
                        .or_else(|| a.get("description").and_then(|v| v.as_str()))
                        .map(String::from)
                })
                .collect::<Vec<_>>()
                .join(" ")
        })
        .unwrap_or_default();
    let kind = params
        .get("type")
        .and_then(|v| v.as_str())
        .unwrap_or("log")
        .to_string();
    ConsoleMessage { text, r#type: kind }
}

/// Background task: track the main-world execution context and keep the
/// selector engine installed after navigations.
async fn context_tracker(
    mut rx: broadcast::Receiver<crate::cdp::CdpEvent>,
    session: Arc<CdpSession>,
    ctx_cell: Arc<Mutex<Option<i64>>>,
) {
    loop {
        match rx.recv().await {
            Ok(ev) => match ev.method.as_str() {
                "Runtime.executionContextCreated" => {
                    let is_default = ev
                        .params
                        .get("context")
                        .and_then(|c| c.get("auxData"))
                        .and_then(|a| a.get("type"))
                        .and_then(|t| t.as_str())
                        == Some("default");
                    if is_default {
                        let id = ev
                            .params
                            .get("context")
                            .and_then(|c| c.get("id"))
                            .and_then(|i| i.as_i64());
                        if let Some(id) = id {
                            *ctx_cell.lock() = Some(id);
                            // Ensure the engine is installed in this context.
                            let s = Arc::clone(&session);
                            tokio::spawn(async move {
                                let _ = s
                                    .send(
                                        "Runtime.evaluate",
                                        json!({
                                            "expression": selectors::INJECTED_SCRIPT,
                                            "contextId": id,
                                        }),
                                    )
                                    .await;
                            });
                        }
                    }
                }
                "Runtime.executionContextsCleared" => {
                    *ctx_cell.lock() = None;
                }
                "Runtime.executionContextDestroyed" => {
                    let id = ev
                        .params
                        .get("executionContextId")
                        .and_then(|v| v.as_i64());
                    let mut cell = ctx_cell.lock();
                    if id.is_some() && *cell == id {
                        *cell = None;
                    }
                }
                _ => {}
            },
            Err(broadcast::error::RecvError::Closed) => break,
            Err(broadcast::error::RecvError::Lagged(_)) => continue,
        }
    }
}

/// A JavaScript dialog (alert/confirm/prompt/beforeunload).
pub struct Dialog {
    message: String,
    kind: String,
    session: Arc<CdpSession>,
}

impl Dialog {
    pub(crate) fn from_event(params: &Value, session: &Arc<CdpSession>) -> Self {
        Self {
            message: params
                .get("message")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            kind: params
                .get("type")
                .and_then(|v| v.as_str())
                .unwrap_or("alert")
                .to_string(),
            session: Arc::clone(session),
        }
    }

    pub fn message(&self) -> &str {
        &self.message
    }

    pub fn kind(&self) -> &str {
        &self.kind
    }

    pub async fn accept(&self, prompt_text: Option<&str>) -> Result<()> {
        let mut p = json!({ "accept": true });
        if let Some(t) = prompt_text {
            p["promptText"] = json!(t);
        }
        self.session
            .send("Page.handleJavaScriptDialog", p)
            .await
            .map(|_| ())
    }

    pub async fn dismiss(&self) -> Result<()> {
        self.session
            .send("Page.handleJavaScriptDialog", json!({ "accept": false }))
            .await
            .map(|_| ())
    }
}