playwright-cdp 0.3.0

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
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
//! `Page` — a browser tab. Tracks its main execution context, drives
//! navigation, evaluation, screenshots, and produces locators.

use crate::accessibility::Accessibility;
use crate::browser::Browser;
use crate::api_request::APIRequestContext;
use crate::cdp::session::CdpSession;
use crate::clock::Clock;
use crate::coverage::Coverage;
use crate::js_handle::JSHandle;
use crate::video::Video;
use crate::web_socket::{WebSocket, WebSocketRegistry};
use crate::web_storage::WebStorage;
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;
use tokio::sync::oneshot;

/// 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 popup handler: takes the popup [`Page`] and resolves when done.
type PopupHandler =
    Arc<dyn Fn(Page) -> 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>>>,
    /// Per-frame main-world execution contexts: `frame_id → context id`.
    /// Populated by the `context_tracker` from
    /// `Runtime.executionContextCreated { auxData.frameId }`. Used to scope
    /// `Frame` evaluate/locator resolution to a child frame's own context.
    frame_contexts: Arc<Mutex<HashMap<String, 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>>,
    // Popup (window.open) capture: erased handlers + a one-shot flag for
    // enabling page-session child-target auto-attach.
    on_popup_handlers: Arc<Mutex<Vec<PopupHandler>>>,
    popup_started: AtomicBool,
    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>,
    // WebSocket capture: a registry that subscribes to the page session and
    // accumulates one `WebSocket` per `Network.webSocket*` connection. Attached
    // in `Page::attach` BEFORE `Network.enable` so no event is missed.
    web_socket_registry: Arc<WebSocketRegistry>,
    // Optional pre-configured video output path (Playwright configures the video
    // path up front at context/page creation time).
    video_path: Mutex<Option<PathBuf>>,
}

/// 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 frame_contexts: Arc<Mutex<HashMap<String, i64>>> =
            Arc::new(Mutex::new(HashMap::new()));
        // The main frame id and frame store are shared with the context tracker
        // (so it can tell the main frame's default context apart from a child
        // frame's) and the frame tracker.
        let frames_store: Arc<Mutex<HashMap<String, FrameData>>> =
            Arc::new(Mutex::new(HashMap::new()));
        let main_frame_id: Arc<Mutex<Option<String>>> = 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);
            let frame_ctx_cell = Arc::clone(&frame_contexts);
            let main_id_cell = Arc::clone(&main_frame_id);
            tokio::spawn(async move {
                context_tracker(
                    ctx_rx,
                    session_for_task,
                    ctx_cell,
                    frame_ctx_cell,
                    main_id_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),
                frame_contexts: Arc::clone(&frame_contexts),
                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::clone(&frames_store),
                main_frame_id: Arc::clone(&main_frame_id),
                route_handlers: Arc::new(Mutex::new(Vec::new())),
                route_started: AtomicBool::new(false),
                on_close_handlers: Mutex::new(Vec::new()),
                on_popup_handlers: Arc::new(Mutex::new(Vec::new())),
                popup_started: AtomicBool::new(false),
                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)),
                web_socket_registry: Arc::new(WebSocketRegistry::new()),
                video_path: Mutex::new(None),
            }),
        };

        // WebSocket capture: attach the registry's subscriber BEFORE
        // Network.enable is sent so no `Network.webSocket*` event is missed.
        page.inner.web_socket_registry.attach(&page.inner.session);

        // 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;
        }
        // Drop the mutex guard before the `.await` below so the (non-`Send`)
        // `parking_lot::MutexGuard` is not held across an await point — this
        // keeps `Page::attach`'s returned future `Send`, which `tokio::spawn`
        // callers (e.g. `on_popup`) require.
        let vp = page.inner.viewport.lock().as_ref().copied();
        if let Some(vp) = vp {
            let _ = page.set_viewport_size(vp).await;
        }

        Ok(page)
    }

    // --- accessors ---

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

    /// The owning CDP session as a cloned `Arc`, for building a [`JSHandle`]
    /// (which retains its own `Arc<CdpSession>`).
    pub(crate) fn session_arc(&self) -> Arc<CdpSession> {
        Arc::clone(&self.inner.session)
    }

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

    /// The execution context to use for page-level evaluation.
    ///
    /// Returns `None` intentionally: omitting `contextId` from
    /// `Runtime.evaluate` lets CDP resolve the page's default (main-world)
    /// context itself, which is always fresh and avoids the stale-context race
    /// that occurs right after a navigation (when the old context is destroyed
    /// before the new one is reported and our tracker has not caught up).
    ///
    /// The tracked id ([`context_id`](Self::context_id)) is still maintained
    /// for callers that need a concrete handle (e.g. [`JSHandle`] context
    /// tagging) and to seed per-frame lookups.
    pub(crate) async fn ctx(&self) -> Option<i64> {
        None
    }

    /// The execution-context id to use when targeting `frame_id`.
    ///
    /// Returns `None` for the page's main frame (so its ops run in CDP's
    /// default, race-free context) and `Some(child_ctx)` for a child frame's
    /// own context. If a child frame's context has not been reported yet,
    /// returns `None` as a safe fallback (default context).
    pub(crate) fn context_for_frame(&self, frame_id: &str) -> Option<i64> {
        // The main frame uses the default context (no id) to stay race-free.
        if self
            .inner
            .main_frame_id
            .lock()
            .as_deref()
            .map(|m| m == frame_id)
            .unwrap_or(false)
        {
            return None;
        }
        self.inner
            .frame_contexts
            .lock()
            .get(frame_id)
            .copied()
            // Unknown child frame: fall back to the default context.
            .or(None)
    }

    /// Like [`context_for_frame`](Self::context_for_frame), but waits briefly
    /// for a child frame's context to arrive (the context-tracker is
    /// asynchronous and may lag a freshly-attached frame). The main frame
    /// returns `None` immediately.
    pub(crate) async fn ctx_for_frame(&self, frame_id: &str) -> Option<i64> {
        // Main frame: default context, no waiting.
        if self
            .inner
            .main_frame_id
            .lock()
            .as_deref()
            .map(|m| m == frame_id)
            .unwrap_or(false)
        {
            return None;
        }
        let deadline = tokio::time::Instant::now() + Duration::from_millis(2000);
        loop {
            if let Some(id) = self.inner.frame_contexts.lock().get(frame_id).copied() {
                return Some(id);
            }
            if tokio::time::Instant::now() >= deadline {
                // Unknown child frame: fall back to the default context rather
                // than erroring.
                return None;
            }
            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()
    }

    /// Set the default timeout (ms) for all actions on this page, mirroring
    /// Playwright's `page.setDefaultTimeout`. The value is stored on the page
    /// ([`PageInner::default_timeout_ms`]) and propagated to the underlying
    /// CDP session's command timeout.
    pub 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 in the main world, returning a [`JSHandle`] to
    /// the result (returned by reference, not by value). Mirrors Playwright's
    /// `page.evaluateHandle`.
    ///
    /// Like [`evaluate`](Self::evaluate), `expression` is wrapped as
    /// `(arg) => { return (<expression>); }` and run against the page's main
    /// world. The returned `Runtime.RemoteObjectId` is captured and wrapped in
    /// a [`JSHandle`]. Returns an error if the evaluation yields `null`/
    /// `undefined` (no remote object to reference).
    pub async fn evaluate_handle(&self, expression: &str) -> Result<JSHandle> {
        let function = format!("(arg) => {{ return ({expression}); }}");
        let object_id = selectors::eval_context_handle(
            &self.inner.session,
            self.ctx().await,
            &function,
            Value::Null,
        )
        .await?
        .ok_or_else(|| {
            Error::ProtocolError(
                "evaluate_handle returned no remote object (null/undefined result)".into(),
            )
        })?;
        Ok(JSHandle::with_context(
            Arc::clone(&self.inner.session),
            object_id,
            self.context_id(),
        ))
    }

    /// 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))
    }

    // --- feature handles (wave-1 modules) ---

    /// The page video capture handle, mirroring Playwright's `page.video()`.
    ///
    /// If a video output path was configured for the page, it is pre-recorded on
    /// the handle (via [`Video::with_path`]); otherwise the handle starts with
    /// no path and one can be supplied at [`Video::start`].
    pub fn video(&self) -> Video {
        let session = Arc::clone(&self.inner.session);
        match self.inner.video_path.lock().clone() {
            Some(path) => Video::with_path(session, path),
            None => Video::new(session),
        }
    }

    /// The page accessibility-tree handle, mirroring Playwright's
    /// `page.accessibility()`.
    pub fn accessibility(&self) -> Accessibility {
        Accessibility::new(self.target_session())
    }

    /// The page code-coverage handle, mirroring Playwright's
    /// `page.coverage()`.
    pub fn coverage(&self) -> Coverage {
        Coverage::new(self.target_session())
    }

    /// The page fake-timer handle, mirroring Playwright's `page.clock()`.
    pub fn clock(&self) -> Clock {
        Clock::new(self.target_session())
    }

    /// The page's `localStorage` for its current security origin, mirroring
    /// Playwright's `page.evaluate(() => localStorage)`-backed access but
    /// speaking CDP's `DOMStorage` domain directly.
    ///
    /// The origin is derived from the current `location.href` (scheme://host
    /// with port). Returns a best-effort handle; if the URL has no parseable
    /// origin (e.g. `about:blank`), the empty string is used as the origin.
    pub async fn web_storage(&self) -> WebStorage {
        let origin = self.security_origin().await;
        WebStorage::local_storage(self.target_session(), origin)
    }

    /// The page's `localStorage` for its current security origin.
    pub async fn local_storage(&self) -> WebStorage {
        let origin = self.security_origin().await;
        WebStorage::local_storage(self.target_session(), origin)
    }

    /// The page's `sessionStorage` for its current security origin.
    pub async fn session_storage(&self) -> WebStorage {
        let origin = self.security_origin().await;
        WebStorage::session_storage(self.target_session(), origin)
    }

    /// Build a by-value [`CdpSession`] for this page's target.
    ///
    /// The wave-1 feature modules ([`Coverage`], [`Clock`], [`WebStorage`],
    /// [`Accessibility`]) own their session by value, but the page holds its
    /// session behind an `Arc`. We rebuild an equivalent target-level session
    /// (same connection + session id) and re-apply the page's default timeout
    /// so command timeouts match the page's configured value.
    fn target_session(&self) -> CdpSession {
        let conn = self.inner.session.connection().clone();
        let session_id = self
            .inner
            .session
            .session_id()
            .map(|s| s.to_string())
            .unwrap_or_default();
        let session = CdpSession::target(conn, session_id);
        session.set_default_timeout_ms(self.inner.default_timeout_ms.load(Ordering::Relaxed));
        session
    }

    /// Derive the security origin (`scheme://host[:port]`) from the current page
    /// URL. Falls back to an empty origin for opaque URLs like `about:blank`.
    async fn security_origin(&self) -> String {
        let url = self.url().await.unwrap_or_default();
        derive_security_origin(&url)
    }

    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;
                }
            }
        });
    }

    /// Register a handler invoked when the page fires its `load` event
    /// (`Page.loadEventFired`), mirroring Playwright's `page.on('load')`.
    pub fn on_load<F, Fut>(&self, handler: F)
    where
        F: Fn(()) -> 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 == "Page.loadEventFired" {
                    handler(()).await;
                }
            }
        });
    }

    /// Register a handler invoked when the page crashes (`Inspector.targetCrashed`),
    /// mirroring Playwright's `page.on('crash')`.
    pub fn on_crash<F, Fut>(&self, handler: F)
    where
        F: Fn(()) -> 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 == "Inspector.targetCrashed" {
                    handler(()).await;
                }
            }
        });
    }

    /// Register a handler invoked when a frame is attached to the page
    /// (`Page.frameAttached`), mirroring Playwright's `page.on('frameattached')`.
    pub fn on_frameattached<F, Fut>(&self, handler: F)
    where
        F: Fn(FrameEvent) -> 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 == "Page.frameAttached" {
                    if let Some(fe) = FrameEvent::from_attached(&ev.params) {
                        handler(fe).await;
                    }
                }
            }
        });
    }

    /// Register a handler invoked when a frame is detached from the page
    /// (`Page.frameDetached`), mirroring Playwright's `page.on('framedetached')`.
    pub fn on_framedetached<F, Fut>(&self, handler: F)
    where
        F: Fn(FrameEvent) -> 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 == "Page.frameDetached" {
                    if let Some(fe) = FrameEvent::from_detached(&ev.params) {
                        handler(fe).await;
                    }
                }
            }
        });
    }

    /// Register a handler invoked when a frame is navigated to a new URL
    /// (`Page.frameNavigated`), mirroring Playwright's `page.on('framenavigated')`.
    pub fn on_framenavigated<F, Fut>(&self, handler: F)
    where
        F: Fn(FrameEvent) -> 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 == "Page.frameNavigated" {
                    if let Some(fe) = FrameEvent::from_navigated(&ev.params) {
                        handler(fe).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);
    }

    /// Wait for a network request whose URL contains `url_predicate`, returning
    /// it. Times out after `timeout` (default 30s) with [`Error::Timeout`].
    ///
    /// The matcher is a plain substring test against the request URL
    /// (`str::contains`), not a regex or glob — keep predicates literal.
    ///
    /// A one-shot handler is registered with [`on_request`](Self::on_request);
    /// it sends the first matching event over a `tokio::sync::oneshot` channel
    /// and then drains its sender to `None`, so subsequent events are no-ops.
    /// The handler is *not* removed from the handler list after it fires — it
    /// simply has nothing to send — so it is idempotent and harmless to leave
    /// in place (one extra closure in a `Vec`, no side effects).
    ///
    /// Typical use races the wait against the action that triggers the request:
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # async fn example(page: &playwright_cdp::Page) {
    /// let button = page.locator("button#submit");
    /// let (req, _) = tokio::join!(
    ///     page.expect_request("/api/login", Some(Duration::from_secs(5))),
    ///     button.click(None),
    /// );
    /// let req = req.unwrap();
    /// assert!(req.url().contains("/api/login"));
    /// # }
    /// ```
    pub async fn expect_request(
        &self,
        url_predicate: &str,
        timeout: Option<Duration>,
    ) -> Result<Request> {
        let (tx, rx) = oneshot::channel::<Request>();
        let tx = Arc::new(Mutex::new(Some(tx)));
        // Own the predicate so the `'static` handler closure can capture it.
        let url_predicate = url_predicate.to_string();
        self.on_request({
            // Move a separate clone into the closure so the outer binding
            // remains available for the timeout message below.
            let url_predicate = url_predicate.clone();
            move |req| {
                let tx = Arc::clone(&tx);
                // The `Fn` closure may fire many times; re-clone per call so the
                // owned predicate is never consumed.
                let url_predicate = url_predicate.clone();
                Box::pin(async move {
                    if req.url().contains(&url_predicate) {
                        if let Some(sender) = tx.lock().take() {
                            let _ = sender.send(req);
                        }
                    }
                })
            }
        });
        match tokio::time::timeout(timeout.unwrap_or_else(|| Duration::from_secs(30)), rx).await {
            Ok(Ok(req)) => Ok(req),
            Ok(Err(_)) => Err(Error::Timeout(
                "expect_request: oneshot sender dropped before a match arrived".into(),
            )),
            Err(_) => Err(Error::Timeout(format!(
                "expect_request: no request matched {url_predicate:?} within the timeout"
            ))),
        }
    }

    /// 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);
    }

    /// Wait for a network response whose URL contains `url_predicate`, returning
    /// it. Times out after `timeout` (default 30s) with [`Error::Timeout`].
    ///
    /// The matcher is a plain substring test against the response URL
    /// (`str::contains`), not a regex or glob — keep predicates literal.
    ///
    /// A one-shot handler is registered with [`on_response`](Self::on_response);
    /// it sends the first matching event over a `tokio::sync::oneshot` channel
    /// and then drains its sender to `None`, so subsequent events are no-ops.
    /// The handler is *not* removed from the handler list after it fires — it
    /// simply has nothing to send — so it is idempotent and harmless to leave
    /// in place (one extra closure in a `Vec`, no side effects).
    ///
    /// Typical use races the wait against the navigation that triggers it:
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # async fn example(page: &playwright_cdp::Page, url: &str) {
    /// let (resp, _) = tokio::join!(
    ///     page.expect_response("127.0.0.1", Some(Duration::from_secs(5))),
    ///     page.goto(url, None),
    /// );
    /// assert_eq!(resp.unwrap().status(), 200);
    /// # }
    /// ```
    pub async fn expect_response(
        &self,
        url_predicate: &str,
        timeout: Option<Duration>,
    ) -> Result<Response> {
        let (tx, rx) = oneshot::channel::<Response>();
        let tx = Arc::new(Mutex::new(Some(tx)));
        // Own the predicate so the `'static` handler closure can capture it.
        let url_predicate = url_predicate.to_string();
        self.on_response({
            // Move a separate clone into the closure so the outer binding
            // remains available for the timeout message below.
            let url_predicate = url_predicate.clone();
            move |resp| {
                let tx = Arc::clone(&tx);
                // The `Fn` closure may fire many times; re-clone per call so the
                // owned predicate is never consumed.
                let url_predicate = url_predicate.clone();
                Box::pin(async move {
                    if resp.url().contains(&url_predicate) {
                        if let Some(sender) = tx.lock().take() {
                            let _ = sender.send(resp);
                        }
                    }
                })
            }
        });
        match tokio::time::timeout(timeout.unwrap_or_else(|| Duration::from_secs(30)), rx).await {
            Ok(Ok(resp)) => Ok(resp),
            Ok(Err(_)) => Err(Error::Timeout(
                "expect_response: oneshot sender dropped before a match arrived".into(),
            )),
            Err(_) => Err(Error::Timeout(format!(
                "expect_response: no response matched {url_predicate:?} within the timeout"
            ))),
        }
    }

    /// Wait for the next CDP event whose method equals `event_name`, returning
    /// its `params`. Times out after `timeout` (default 30s) with
    /// [`Error::Timeout`].
    ///
    /// Subscribes to the page session's event stream, so it only sees events
    /// emitted **after** this call — race it against the triggering action with
    /// `tokio::join!`.
    ///
    /// Example: wait for the page's load event during navigation.
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # async fn example(page: &playwright_cdp::Page, url: &str) {
    /// let (params, _) = tokio::join!(
    ///     page.expect_event("Page.loadEventFired", Some(Duration::from_secs(5))),
    ///     page.goto(url, None),
    /// );
    /// let _params = params.unwrap();
    /// # }
    /// ```
    pub async fn expect_event(
        &self,
        event_name: &str,
        timeout: Option<Duration>,
    ) -> Result<Value> {
        // Subscribe *before* the triggering action so we capture every event
        // it produces. New receivers only see events emitted after subscribe.
        let mut rx = self.inner.session.subscribe();
        let effective = timeout.unwrap_or(Duration::from_secs(30));
        let deadline = tokio::time::Instant::now() + effective;

        loop {
            match tokio::time::timeout_at(deadline, rx.recv()).await {
                Ok(Ok(ev)) if ev.method == event_name => return Ok(ev.params),
                Ok(Ok(_)) => continue,
                Ok(Err(broadcast::error::RecvError::Lagged(_))) => continue,
                Ok(Err(broadcast::error::RecvError::Closed)) => {
                    return Err(Error::Timeout(format!(
                        "expect_event('{event_name}'): event stream closed before a match arrived"
                    )));
                }
                Err(_) => {
                    return Err(Error::Timeout(format!(
                        "expect_event('{event_name}') timed out after {}ms",
                        effective.as_millis()
                    )));
                }
            }
        }
    }

    /// 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 for each new WebSocket connection, mirroring
    /// Playwright's `page.on('websocket')`.
    ///
    /// Capture is always on: the page's [`WebSocketRegistry`] subscribes to the
    /// session in [`Page::attach`] (before `Network.enable`), so every
    /// `Network.webSocket*` event is already being accumulated into a
    /// [`WebSocket`] handle. This method registers against the registry's
    /// created-connection bus and invokes `handler` for each newly-created
    /// connection. Connections created *before* this call are not replayed —
    /// register the handler early (before the page opens the socket) to observe
    /// every one.
    pub fn on_websocket<F, Fut>(&self, handler: F)
    where
        F: Fn(WebSocket) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let mut rx = self.inner.web_socket_registry.on_created();
        // Wrap in an Arc<dyn Fn> so the handler can be invoked from each
        // spawned task without being moved out of the loop.
        let handler: Arc<dyn Fn(WebSocket) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync> =
            Arc::new(move |ws| Box::pin(handler(ws)));
        tokio::spawn(async move {
            while let Ok(ws) = rx.recv().await {
                let h = Arc::clone(&handler);
                // Invoke on its own task so a slow handler doesn't stall the
                // registry's broadcast bus.
                tokio::spawn(async move {
                    h(ws).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;
            });
        }
    }

    /// Wait for a download whose URL contains `url_predicate`, returning it.
    /// Times out after `timeout` (default 30s) with [`Error::Timeout`].
    ///
    /// The matcher is a plain substring test against the download URL
    /// (`str::contains`), not a regex or glob — keep predicates literal.
    ///
    /// A one-shot handler is registered with [`on_download`](Self::on_download);
    /// it sends the first matching event over a `tokio::sync::oneshot` channel
    /// and then drains its sender to `None`, so subsequent events are no-ops.
    /// The handler is *not* removed from the handler list after it fires — it
    /// simply has nothing to send — so it is idempotent and harmless to leave
    /// in place (one extra closure in a `Vec`, no side effects).
    ///
    /// Note that the first `on_download` registration on a page lazily wires up
    /// `Page.setDownloadBehavior`, so this call implicitly opts the page into
    /// download routing to a temp dir.
    ///
    /// Typical use races the wait against the click that triggers the download:
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # async fn example(page: &playwright_cdp::Page) {
    /// let link = page.locator("a#download");
    /// let (dl, _) = tokio::join!(
    ///     page.expect_download("/report.pdf", Some(Duration::from_secs(5))),
    ///     link.click(None),
    /// );
    /// let dl = dl.unwrap();
    /// assert!(dl.url().contains("/report.pdf"));
    /// # }
    /// ```
    pub async fn expect_download(
        &self,
        url_predicate: &str,
        timeout: Option<Duration>,
    ) -> Result<Download> {
        let (tx, rx) = oneshot::channel::<Download>();
        let tx = Arc::new(Mutex::new(Some(tx)));
        // Own the predicate so the `'static` handler closure can capture it.
        let url_predicate = url_predicate.to_string();
        self.on_download({
            // Move a separate clone into the closure so the outer binding
            // remains available for the timeout message below.
            let url_predicate = url_predicate.clone();
            move |dl| {
                let tx = Arc::clone(&tx);
                // The `Fn` closure may fire many times; re-clone per call so the
                // owned predicate is never consumed.
                let url_predicate = url_predicate.clone();
                Box::pin(async move {
                    if dl.url().contains(&url_predicate) {
                        if let Some(sender) = tx.lock().take() {
                            let _ = sender.send(dl);
                        }
                    }
                })
            }
        });
        match tokio::time::timeout(timeout.unwrap_or_else(|| Duration::from_secs(30)), rx).await {
            Ok(Ok(dl)) => Ok(dl),
            Ok(Err(_)) => Err(Error::Timeout(
                "expect_download: oneshot sender dropped before a match arrived".into(),
            )),
            Err(_) => Err(Error::Timeout(format!(
                "expect_download: no download matched {url_predicate:?} within the timeout"
            ))),
        }
    }

    /// Wait for a console message whose text contains `text_predicate`,
    /// returning it. Times out after `timeout` (default 30s) with
    /// [`Error::Timeout`].
    ///
    /// The matcher is a plain substring test against the console message text
    /// ([`ConsoleMessage::text`], `str::contains`), not a regex or glob — keep
    /// predicates literal.
    ///
    /// A one-shot handler is registered with [`on_console`](Self::on_console);
    /// it sends the first matching event over a `tokio::sync::oneshot` channel
    /// and then drains its sender to `None`, so subsequent events are no-ops.
    /// The handler task keeps running for the life of the page (one extra
    /// spawned task, no side effects), mirroring the oneshot pattern used by
    /// the other `expect_*` helpers.
    ///
    /// Typical use races the wait against the script that logs the message:
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # async fn example(page: &playwright_cdp::Page) {
    /// let (msg, _) = tokio::join!(
    ///     page.expect_console_message("hello", Some(Duration::from_secs(5))),
    ///     page.evaluate::<()>("console.log('hello world')"),
    /// );
    /// assert!(msg.unwrap().text().contains("hello"));
    /// # }
    /// ```
    pub async fn expect_console_message(
        &self,
        text_predicate: &str,
        timeout: Option<Duration>,
    ) -> Result<ConsoleMessage> {
        let (tx, rx) = oneshot::channel::<ConsoleMessage>();
        let tx = Arc::new(Mutex::new(Some(tx)));
        // Own the predicate so the `'static` handler closure can capture it.
        let text_predicate = text_predicate.to_string();
        self.on_console({
            // Move a separate clone into the closure so the outer binding
            // remains available for the timeout message below.
            let text_predicate = text_predicate.clone();
            move |msg| {
                let tx = Arc::clone(&tx);
                // The `Fn` closure may fire many times; re-clone per call so the
                // owned predicate is never consumed.
                let text_predicate = text_predicate.clone();
                Box::pin(async move {
                    if msg.text().contains(&text_predicate) {
                        if let Some(sender) = tx.lock().take() {
                            let _ = sender.send(msg);
                        }
                    }
                })
            }
        });
        match tokio::time::timeout(timeout.unwrap_or_else(|| Duration::from_secs(30)), rx).await {
            Ok(Ok(msg)) => Ok(msg),
            Ok(Err(_)) => Err(Error::Timeout(
                "expect_console_message: oneshot sender dropped before a match arrived".into(),
            )),
            Err(_) => Err(Error::Timeout(format!(
                "expect_console_message: no message matched {text_predicate:?} within the timeout"
            ))),
        }
    }

    /// Wait for a popup (`window.open`) opened by this page, returning it as a
    /// new [`Page`]. Times out after `timeout` (default 30s) with
    /// [`Error::Timeout`].
    ///
    /// # Implementation (polling-based)
    ///
    /// A popup (`window.open`) is a new top-level page target rather than a
    /// child of this page's target, so child-target auto-attach does not surface
    /// it (and `Target.targetCreated` does not fire for popups on stock Chrome
    /// in this setup, while `Target.getTargets` omits `openerId`). This helper
    /// therefore registers a one-shot handler with
    /// [`on_popup`](Self::on_popup), which polls `Target.getTargets` and treats
    /// the first new `type == "page"` target in this page's browser context as
    /// the popup. See [`on_popup`](Self::on_popup) for the full limitations.
    ///
    /// The popup [`Page`] is built with an empty init-script set and this
    /// page's default timeout; per-context defaults (extra headers, user
    /// agent, viewport) are not re-applied, since `Page` does not expose them
    /// as raw values. This is sufficient for typical popup-driving flows
    /// (interact with the popup, then close it).
    ///
    /// Typical use races the wait against the script that opens the popup:
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # async fn example(page: &playwright_cdp::Page) {
    /// let (popup, _) = tokio::join!(
    ///     page.expect_popup(Some(Duration::from_secs(5))),
    ///     page.evaluate::<()>("window.open('about:blank')"),
    /// );
    /// let _popup = popup.unwrap();
    /// # }
    /// ```
    pub async fn expect_popup(&self, timeout: Option<Duration>) -> Result<Page> {
        let (tx, rx) = oneshot::channel::<Page>();
        let tx = Arc::new(Mutex::new(Some(tx)));
        self.on_popup(move |popup| {
            let tx = Arc::clone(&tx);
            Box::pin(async move {
                if let Some(sender) = tx.lock().take() {
                    let _ = sender.send(popup);
                }
            })
        })
        .await;
        match tokio::time::timeout(timeout.unwrap_or_else(|| Duration::from_secs(30)), rx).await {
            Ok(Ok(popup)) => Ok(popup),
            Ok(Err(_)) => Err(Error::Timeout(
                "expect_popup: oneshot sender dropped before a popup arrived".into(),
            )),
            Err(_) => Err(Error::Timeout(
                "expect_popup: no popup opened within the timeout".into(),
            )),
        }
    }

    /// Register a handler invoked when this page opens a popup (`window.open`),
    /// mirroring Playwright's `page.on('popup')`.
    ///
    /// # Implementation (polling, not event-driven)
    ///
    /// A popup is a brand-new top-level page target, *not* a child of this
    /// page's target, so this page session's `Target.setAutoAttach` does not
    /// surface it (and, empirically, `Target.setDiscoverTargets` /
    /// `Target.targetCreated` do not fire for `window.open` popups on stock
    /// Chrome in this setup). `Target.getTargets` also omits `openerId`, so
    /// strict opener attribution is not available.
    ///
    /// Instead, on first registration a background task polls `Target.getTargets`
    /// on a short interval. Any `type == "page"` target that shares this page's
    /// `browserContextId`, is not this page itself, and has not already been
    /// delivered is treated as the popup: the task attaches to it
    /// (`Target.attachToTarget { flatten }`), builds a full [`Page`] via
    /// [`Page::attach`], and hands it to every registered handler. A `delivered`
    /// set (rather than a registration-time baseline) is used because a baseline
    /// diff races with the trigger under `tokio::join!` — the popup can appear
    /// before the snapshot completes.
    ///
    /// **Limitations** (documented honestly): attribution is "any page target in
    /// this browser context that isn't this page," not opener-precise, so it can
    /// misattribute if another page already exists or is opened concurrently in
    /// the same context. Each distinct popup target fires the handlers once.
    ///
    /// The popup [`Page`] is built with an empty init-scripts set and this
    /// page's default timeout; context-level defaults (extra headers, user
    /// agent, viewport) are not re-applied (see [`expect_popup`](Self::expect_popup)).
    pub async fn on_popup<F, Fut>(&self, handler: F)
    where
        F: Fn(Page) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        // Record this handler so the background task dispatches to it.
        let handler: PopupHandler = Arc::new(move |p| Box::pin(handler(p)));
        self.inner.on_popup_handlers.lock().push(handler);

        // Lazily spawn the popup poller once.
        if self
            .inner
            .popup_started
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
        {
            let browser = self.inner.browser.clone();
            let default_timeout_ms = self.inner.default_timeout_ms.load(Ordering::Relaxed);
            let opener_target_id = self.inner.target_id.clone();
            let handlers = Arc::clone(&self.inner.on_popup_handlers);
            let browser_session = browser.new_browser_cdp_session();

            tokio::spawn(async move {
                // Determine this page's browserContextId (and the baseline set
                // of already-existing page targets) so we only surface brand-new
                // page targets in the same context.
                let resp = match browser_session
                    .send("Target.getTargets", json!({}))
                    .await
                {
                    Ok(r) => r,
                    Err(_) => return,
                };
                let targets = resp
                    .get("targetInfos")
                    .and_then(|v| v.as_array())
                    .cloned()
                    .unwrap_or_default();
                // This page's context id (look it up by target id).
                let my_context = targets
                    .iter()
                    .find(|t| {
                        t.get("targetId").and_then(|v| v.as_str()) == Some(&opener_target_id)
                    })
                    .and_then(|t| t.get("browserContextId"))
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());
                // Track which popup targets we have already delivered, so each
                // distinct popup fires the handlers exactly once. We do NOT
                // snapshot a baseline: a baseline diff races with the trigger
                // under `tokio::join!` (the popup can appear before the
                // snapshot completes). Instead we deliver every same-context
                // page target that isn't this page itself and that we haven't
                // already handed off. This assumes no pre-existing unrelated
                // page target in the same browser context at registration time
                // (true for the common one-page-then-popup flow).
                let mut delivered: std::collections::HashSet<String> =
                    std::collections::HashSet::new();

                loop {
                    tokio::time::sleep(Duration::from_millis(100)).await;
                    let resp = match browser_session.send("Target.getTargets", json!({})).await {
                        Ok(r) => r,
                        Err(_) => continue,
                    };
                    let targets = match resp.get("targetInfos").and_then(|v| v.as_array()) {
                        Some(a) => a,
                        None => continue,
                    };
                    // Undelivered page targets in the same context (excluding
                    // this page itself).
                    let new_popups: Vec<&Value> = targets
                        .iter()
                        .filter(|t| t.get("type").and_then(|v| v.as_str()) == Some("page"))
                        .filter(|t| {
                            my_context
                                .as_deref()
                                .zip(t.get("browserContextId").and_then(|v| v.as_str()))
                                .map(|(mc, c)| mc == c)
                                .unwrap_or(true)
                        })
                        .filter(|t| {
                            t.get("targetId")
                                .and_then(|v| v.as_str())
                                .map(|id| {
                                    !delivered.contains(id) && id != opener_target_id
                                })
                                .unwrap_or(false)
                        })
                        .collect();
                    if new_popups.is_empty() {
                        continue;
                    }
                    for np in new_popups {
                        let target_id = match np.get("targetId").and_then(|v| v.as_str()) {
                            Some(id) => id.to_string(),
                            None => continue,
                        };
                        delivered.insert(target_id.clone());
                        // Attach to the popup target to obtain a session id.
                        let attach = match browser_session
                            .send(
                                "Target.attachToTarget",
                                json!({ "targetId": target_id, "flatten": true }),
                            )
                            .await
                        {
                            Ok(r) => r,
                            Err(_) => continue,
                        };
                        let sid = match attach.get("sessionId").and_then(|v| v.as_str()) {
                            Some(s) => s.to_string(),
                            None => continue,
                        };
                        // Build a full Page for the popup target, mirroring
                        // BrowserContext::new_page (empty init scripts / no
                        // extra defaults — see the doc on `expect_popup`).
                        let popup = match Page::attach(
                            browser.clone(),
                            sid,
                            target_id,
                            &[],
                            default_timeout_ms,
                            None,
                            None,
                            None,
                        )
                        .await
                        {
                            Ok(p) => p,
                            Err(_) => continue,
                        };
                        // Snapshot the current handlers and dispatch to each.
                        let snapshot = handlers.lock().clone();
                        for h in snapshot {
                            let p = popup.clone();
                            tokio::spawn(async move {
                                (h)(p).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('"', "\\\"")
}

/// Derive the CDP `securityOrigin` (`scheme://host[:port]`) from a URL string.
///
/// Opaque schemes (`about:`, `data:`, `blob:`) yield an empty origin, since
/// `DOMStorage` has nothing to scope to for them. A URL without a parseable
/// scheme also yields an empty origin.
fn derive_security_origin(url: &str) -> String {
    // Find the scheme delimiter.
    let after_scheme = match url.find("://") {
        Some(i) => &url[i + 3..],
        None => return String::new(),
    };
    let scheme = &url[..url.find("://").unwrap()];
    // Opaque/special schemes have no real origin.
    if matches!(scheme, "about" | "data" | "blob" | "javascript") {
        return String::new();
    }
    // The authority ends at the first `/`, `?`, or `#`.
    let end = after_scheme
        .find(|c: char| c == '/' || c == '?' || c == '#')
        .unwrap_or(after_scheme.len());
    let authority = &after_scheme[..end];
    if authority.is_empty() {
        return String::new();
    }
    format!("{scheme}://{authority}")
}

/// Whether a JSON value is "truthy" for `wait_for_function`: `null`, `false`,
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();
    // Source location from the top call frame of the reported stack trace.
    let location = params
        .get("stackTrace")
        .and_then(|s| s.get("callFrames"))
        .and_then(|f| f.as_array())
        .and_then(|frames| frames.first())
        .map(|frame| {
            use crate::types::ConsoleMessageLocation;
            ConsoleMessageLocation {
                url: frame
                    .get("url")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                line_number: frame.get("lineNumber").and_then(|v| v.as_i64()),
                column_number: frame.get("columnNumber").and_then(|v| v.as_i64()),
            }
        });
    ConsoleMessage {
        text,
        r#type: kind,
        location,
    }
}

/// Background task: track the main-world execution context and keep the
/// selector engine installed after navigations. Also records per-frame
/// contexts (frame id → context id) from `auxData.frameId` so child-frame
/// evaluation/locator resolution can target a frame's own context.
///
/// `main_world_ctx` is set ONLY for the main (top) frame's default context —
/// a child iframe also has a "default" context, and accepting every default
/// context would let the child's context clobber the main one.
async fn context_tracker(
    mut rx: broadcast::Receiver<crate::cdp::CdpEvent>,
    session: Arc<CdpSession>,
    ctx_cell: Arc<Mutex<Option<i64>>>,
    frame_ctx_cell: Arc<Mutex<HashMap<String, i64>>>,
    main_frame_id: Arc<Mutex<Option<String>>>,
) {
    loop {
        match rx.recv().await {
            Ok(ev) => match ev.method.as_str() {
                "Runtime.executionContextCreated" => {
                    let context = match ev.params.get("context") {
                        Some(c) => c,
                        None => continue,
                    };
                    let aux = context.get("auxData");
                    let is_default = aux
                        .and_then(|a| a.get("type"))
                        .and_then(|t| t.as_str())
                        == Some("default");
                    let id = context.get("id").and_then(|i| i.as_i64());
                    let Some(id) = id else { continue };

                    let frame_id = aux
                        .and_then(|a| a.get("frameId"))
                        .and_then(|v| v.as_str())
                        .map(String::from);

                    if is_default {
                        // Record the frame → context mapping. Only default
                        // (main-world) contexts are tracked; utility/isolated
                        // worlds have their own ids and must not shadow a
                        // frame's main context.
                        if let Some(fid) = &frame_id {
                            frame_ctx_cell.lock().insert(fid.clone(), id);
                        }

                        // The page-wide "main" context is the main frame's
                        // default context. A child iframe's default context
                        // must NOT overwrite it. Accept this context as main
                        // when (a) its frame is the known main frame, or
                        // (b) the main frame id is not yet known and no main
                        // context has been recorded yet (initial top-frame
                        // context typically arrives before the frame tree is
                        // populated).
                        let main_id = main_frame_id.lock().clone();
                        let is_main_frame = match (&main_id, &frame_id) {
                            (Some(m), Some(f)) => m == f,
                            (None, _) => ctx_cell.lock().is_none(),
                            // main frame known but this context has no frameId:
                            // treat as main only if none recorded yet.
                            (Some(_), None) => ctx_cell.lock().is_none(),
                        };
                        if is_main_frame {
                            *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;
                    frame_ctx_cell.lock().clear();
                }
                "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;
                        }
                    }
                    if let Some(id) = id {
                        let mut frames = frame_ctx_cell.lock();
                        // Drop any frame→context entries that pointed at the
                        // destroyed context (a new contextCreated will repopulate).
                        frames.retain(|_, v| *v != id);
                    }
                }
                _ => {}
            },
            Err(broadcast::error::RecvError::Closed) => break,
            Err(broadcast::error::RecvError::Lagged(_)) => continue,
        }
    }
}

/// A frame lifecycle event payload for `on_frameattached` /
/// `on_framedetached` / `on_framenavigated`. Carries the frame id, its
/// parent's id (if any), and — for navigations — the frame's new URL.
#[derive(Debug, Clone)]
pub struct FrameEvent {
    /// The id of the frame the event concerns.
    pub id: String,
    /// The parent frame id, if the frame has one (the main frame does not).
    pub parent_id: Option<String>,
    /// The frame's URL. Populated for navigations; empty for attach/detach.
    pub url: String,
}

impl FrameEvent {
    /// Parse `Page.frameAttached` params (`params.frame.{id,parentFrameId}`).
    pub(crate) fn from_attached(params: &Value) -> Option<Self> {
        let frame = params.get("frame").unwrap_or(params);
        let id = frame.get("id").and_then(|v| v.as_str())?.to_string();
        let parent_id = frame
            .get("parentFrameId")
            .and_then(|v| v.as_str())
            .map(String::from);
        Some(Self {
            id,
            parent_id,
            url: String::new(),
        })
    }

    /// Parse `Page.frameDetached` params (`params.frameId`, plus any `frame`).
    pub(crate) fn from_detached(params: &Value) -> Option<Self> {
        // frameDetached carries a bare `frameId`; `frame` may be absent.
        let id = params
            .get("frameId")
            .or_else(|| params.get("frame"))
            .and_then(|v| {
                v.as_str()
                    .map(String::from)
                    .or_else(|| v.get("id").and_then(|i| i.as_str()).map(String::from))
            })?;
        let parent_id = params
            .get("frame")
            .and_then(|f| f.get("parentFrameId"))
            .and_then(|v| v.as_str())
            .map(String::from);
        Some(Self {
            id,
            parent_id,
            url: String::new(),
        })
    }

    /// Parse `Page.frameNavigated` params (`params.frame.{id,url,parentId}`).
    pub(crate) fn from_navigated(params: &Value) -> Option<Self> {
        let frame = params.get("frame")?;
        let id = frame.get("id").and_then(|v| v.as_str())?.to_string();
        let url = frame
            .get("url")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let parent_id = frame
            .get("parentId")
            .and_then(|v| v.as_str())
            .map(String::from);
        Some(Self {
            id,
            parent_id,
            url,
        })
    }
}

/// 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(|_| ())
    }
}