playwright-rs 0.12.0

Rust bindings for Microsoft Playwright
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
// Page protocol object
//
// Represents a web page within a browser context.
// Pages are isolated tabs or windows within a context.

use crate::error::{Error, Result};
use crate::protocol::browser_context::Viewport;
use crate::protocol::{Dialog, Download, Request, ResponseObject, Route, WebSocket, Worker};
use crate::server::channel::Channel;
use crate::server::channel_owner::{ChannelOwner, ChannelOwnerImpl, ParentOrConnection};
use crate::server::connection::{ConnectionExt, downcast_parent};
use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::any::Any;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};

/// Page represents a web page within a browser context.
///
/// A Page is created when you call `BrowserContext::new_page()` or `Browser::new_page()`.
/// Each page is an isolated tab/window within its parent context.
///
/// Initially, pages are navigated to "about:blank". Use navigation methods
/// Use navigation methods to navigate to URLs.
///
/// # Example
///
/// ```ignore
/// use playwright_rs::protocol::{
///     Playwright, ScreenshotOptions, ScreenshotType, AddStyleTagOptions, AddScriptTagOptions,
///     EmulateMediaOptions, Media, ColorScheme, Viewport,
/// };
/// use std::path::PathBuf;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let playwright = Playwright::launch().await?;
///     let browser = playwright.chromium().launch().await?;
///     let page = browser.new_page().await?;
///
///     // Demonstrate url() - initially at about:blank
///     assert_eq!(page.url(), "about:blank");
///
///     // Demonstrate goto() - navigate to a page
///     let html = r#"<!DOCTYPE html>
///         <html>
///             <head><title>Test Page</title></head>
///             <body>
///                 <h1 id="heading">Hello World</h1>
///                 <p>First paragraph</p>
///                 <p>Second paragraph</p>
///                 <button onclick="alert('Alert!')">Alert</button>
///                 <a href="data:text/plain,file" download="test.txt">Download</a>
///             </body>
///         </html>
///     "#;
///     // Data URLs may not return a response (this is normal)
///     let _response = page.goto(&format!("data:text/html,{}", html), None).await?;
///
///     // Demonstrate title()
///     let title = page.title().await?;
///     assert_eq!(title, "Test Page");
///
///     // Demonstrate content() - returns full HTML including DOCTYPE
///     let content = page.content().await?;
///     assert!(content.contains("<!DOCTYPE html>") || content.to_lowercase().contains("<!doctype html>"));
///     assert!(content.contains("<title>Test Page</title>"));
///     assert!(content.contains("Hello World"));
///
///     // Demonstrate locator()
///     let heading = page.locator("#heading").await;
///     let text = heading.text_content().await?;
///     assert_eq!(text, Some("Hello World".to_string()));
///
///     // Demonstrate query_selector()
///     let element = page.query_selector("h1").await?;
///     assert!(element.is_some(), "Should find the h1 element");
///
///     // Demonstrate query_selector_all()
///     let paragraphs = page.query_selector_all("p").await?;
///     assert_eq!(paragraphs.len(), 2);
///
///     // Demonstrate evaluate()
///     page.evaluate::<(), ()>("console.log('Hello from Playwright!')", None).await?;
///
///     // Demonstrate evaluate_value()
///     let result = page.evaluate_value("1 + 1").await?;
///     assert_eq!(result, "2");
///
///     // Demonstrate screenshot()
///     let bytes = page.screenshot(None).await?;
///     assert!(!bytes.is_empty());
///
///     // Demonstrate screenshot_to_file()
///     let temp_dir = std::env::temp_dir();
///     let path = temp_dir.join("playwright_doctest_screenshot.png");
///     let bytes = page.screenshot_to_file(&path, Some(
///         ScreenshotOptions::builder()
///             .screenshot_type(ScreenshotType::Png)
///             .build()
///     )).await?;
///     assert!(!bytes.is_empty());
///
///     // Demonstrate reload()
///     // Data URLs may not return a response on reload (this is normal)
///     let _response = page.reload(None).await?;
///
///     // Demonstrate route() - network interception
///     page.route("**/*.png", |route| async move {
///         route.abort(None).await
///     }).await?;
///
///     // Demonstrate on_download() - download handler
///     page.on_download(|download| async move {
///         println!("Download started: {}", download.url());
///         Ok(())
///     }).await?;
///
///     // Demonstrate on_dialog() - dialog handler
///     page.on_dialog(|dialog| async move {
///         println!("Dialog: {} - {}", dialog.type_(), dialog.message());
///         dialog.accept(None).await
///     }).await?;
///
///     // Demonstrate add_style_tag() - inject CSS
///     page.add_style_tag(
///         AddStyleTagOptions::builder()
///             .content("body { background-color: blue; }")
///             .build()
///     ).await?;
///
///     // Demonstrate set_extra_http_headers() - set page-level headers
///     let mut headers = std::collections::HashMap::new();
///     headers.insert("x-custom-header".to_string(), "value".to_string());
///     page.set_extra_http_headers(headers).await?;
///
///     // Demonstrate emulate_media() - emulate print media type
///     page.emulate_media(Some(
///         EmulateMediaOptions::builder()
///             .media(Media::Print)
///             .color_scheme(ColorScheme::Dark)
///             .build()
///     )).await?;
///
///     // Demonstrate add_script_tag() - inject a script
///     page.add_script_tag(Some(
///         AddScriptTagOptions::builder()
///             .content("window.injectedByScriptTag = true;")
///             .build()
///     )).await?;
///
///     // Demonstrate pdf() - generate PDF (Chromium only)
///     let pdf_bytes = page.pdf(None).await?;
///     assert!(!pdf_bytes.is_empty());
///
///     // Demonstrate set_viewport_size() - responsive testing
///     let mobile_viewport = Viewport {
///         width: 375,
///         height: 667,
///     };
///     page.set_viewport_size(mobile_viewport).await?;
///
///     // Demonstrate close()
///     page.close().await?;
///
///     browser.close().await?;
///     Ok(())
/// }
/// ```
///
/// See: <https://playwright.dev/docs/api/class-page>
#[derive(Clone)]
pub struct Page {
    base: ChannelOwnerImpl,
    /// Current URL of the page
    /// Wrapped in RwLock to allow updates from events
    url: Arc<RwLock<String>>,
    /// GUID of the main frame
    main_frame_guid: Arc<str>,
    /// Cached reference to the main frame for synchronous URL access
    /// This is populated after the first call to main_frame()
    cached_main_frame: Arc<Mutex<Option<crate::protocol::Frame>>>,
    /// Route handlers for network interception
    route_handlers: Arc<Mutex<Vec<RouteHandlerEntry>>>,
    /// Download event handlers
    download_handlers: Arc<Mutex<Vec<DownloadHandler>>>,
    /// Dialog event handlers
    dialog_handlers: Arc<Mutex<Vec<DialogHandler>>>,
    /// Request event handlers
    request_handlers: Arc<Mutex<Vec<RequestHandler>>>,
    /// Request finished event handlers
    request_finished_handlers: Arc<Mutex<Vec<RequestHandler>>>,
    /// Request failed event handlers
    request_failed_handlers: Arc<Mutex<Vec<RequestHandler>>>,
    /// Response event handlers
    response_handlers: Arc<Mutex<Vec<ResponseHandler>>>,
    /// WebSocket event handlers
    websocket_handlers: Arc<Mutex<Vec<WebSocketHandler>>>,
    /// WebSocketRoute handlers for route_web_socket()
    ws_route_handlers: Arc<Mutex<Vec<WsRouteHandlerEntry>>>,
    /// Current viewport size (None when no_viewport is set).
    /// Updated by set_viewport_size().
    viewport: Arc<RwLock<Option<Viewport>>>,
    /// Whether this page has been closed.
    /// Set to true when close() is called or a "close" event is received.
    is_closed: Arc<AtomicBool>,
    /// Default timeout for actions (milliseconds), stored as f64 bits.
    default_timeout_ms: Arc<AtomicU64>,
    /// Default timeout for navigation operations (milliseconds), stored as f64 bits.
    default_navigation_timeout_ms: Arc<AtomicU64>,
    /// Page-level binding callbacks registered via expose_function / expose_binding
    binding_callbacks: Arc<Mutex<HashMap<String, PageBindingCallback>>>,
    /// Console event handlers
    console_handlers: Arc<Mutex<Vec<ConsoleHandler>>>,
    /// FileChooser event handlers
    filechooser_handlers: Arc<Mutex<Vec<FileChooserHandler>>>,
    /// One-shot senders waiting for the next "fileChooser" event (expect_file_chooser)
    filechooser_waiters:
        Arc<Mutex<Vec<tokio::sync::oneshot::Sender<crate::protocol::FileChooser>>>>,
    /// One-shot senders waiting for the next "popup" event (expect_popup)
    popup_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<Page>>>>,
    /// One-shot senders waiting for the next "download" event (expect_download)
    download_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<Download>>>>,
    /// One-shot senders waiting for the next "response" event (expect_response)
    response_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<ResponseObject>>>>,
    /// One-shot senders waiting for the next "request" event (expect_request)
    request_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<Request>>>>,
    /// One-shot senders waiting for the next "console" event (expect_console_message)
    console_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<crate::protocol::ConsoleMessage>>>>,
    /// close event handlers (fires when page is closed)
    close_handlers: Arc<Mutex<Vec<CloseHandler>>>,
    /// load event handlers (fires when page fully loads)
    load_handlers: Arc<Mutex<Vec<LoadHandler>>>,
    /// crash event handlers (fires when page crashes)
    crash_handlers: Arc<Mutex<Vec<CrashHandler>>>,
    /// pageError event handlers (fires on uncaught JS exceptions)
    pageerror_handlers: Arc<Mutex<Vec<PageErrorHandler>>>,
    /// popup event handlers (fires when a popup window opens)
    popup_handlers: Arc<Mutex<Vec<PopupHandler>>>,
    /// frameAttached event handlers
    frameattached_handlers: Arc<Mutex<Vec<FrameAttachedHandler>>>,
    /// frameDetached event handlers
    framedetached_handlers: Arc<Mutex<Vec<FrameDetachedHandler>>>,
    /// frameNavigated event handlers
    framenavigated_handlers: Arc<Mutex<Vec<FrameNavigatedHandler>>>,
    /// worker event handlers (fires when a web worker is created in the page)
    worker_handlers: Arc<Mutex<Vec<WorkerHandler>>>,
    /// One-shot senders waiting for the next "close" event (expect_event("close"))
    close_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<()>>>>,
    /// One-shot senders waiting for the next "load" event (expect_event("load"))
    load_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<()>>>>,
    /// One-shot senders waiting for the next "crash" event (expect_event("crash"))
    crash_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<()>>>>,
    /// One-shot senders waiting for the next "pageerror" event (expect_event("pageerror"))
    pageerror_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<String>>>>,
    /// One-shot senders waiting for the next frame event (frameattached/detached/navigated)
    frameattached_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<crate::protocol::Frame>>>>,
    framedetached_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<crate::protocol::Frame>>>>,
    framenavigated_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<crate::protocol::Frame>>>>,
    /// One-shot senders waiting for the next "worker" event (expect_event("worker"))
    worker_waiters: Arc<Mutex<Vec<tokio::sync::oneshot::Sender<crate::protocol::Worker>>>>,
    /// Accumulated console messages received so far (appended by trigger_console_event)
    console_messages_log: Arc<Mutex<Vec<crate::protocol::ConsoleMessage>>>,
    /// Accumulated uncaught JS error messages received so far (appended by trigger_pageerror_event)
    page_errors_log: Arc<Mutex<Vec<String>>>,
    /// Active web workers tracked via "worker" events (appended on creation)
    workers_list: Arc<Mutex<Vec<Worker>>>,
    /// Video object — Some when this page was created in a record_video context.
    /// The inner Video is created eagerly on Page construction; the underlying
    /// Artifact GUID is read from the Page initializer and resolved asynchronously.
    video: Option<crate::protocol::Video>,
    /// Registered locator handlers: maps uid -> (selector, handler fn, times_remaining)
    /// times_remaining is None when the handler should run indefinitely.
    locator_handlers: Arc<Mutex<Vec<LocatorHandlerEntry>>>,
}

/// Type alias for boxed route handler future
type RouteHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// Type alias for boxed download handler future
type DownloadHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// Type alias for boxed dialog handler future
type DialogHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// Type alias for boxed request handler future
type RequestHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// Type alias for boxed response handler future
type ResponseHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// Type alias for boxed websocket handler future
type WebSocketHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// Type alias for boxed WebSocketRoute handler future
type WebSocketRouteHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// Storage for a single WebSocket route handler entry
#[derive(Clone)]
struct WsRouteHandlerEntry {
    pattern: String,
    handler:
        Arc<dyn Fn(crate::protocol::WebSocketRoute) -> WebSocketRouteHandlerFuture + Send + Sync>,
}

/// Storage for a single route handler
#[derive(Clone)]
struct RouteHandlerEntry {
    pattern: String,
    handler: Arc<dyn Fn(Route) -> RouteHandlerFuture + Send + Sync>,
}

/// Download event handler
type DownloadHandler = Arc<dyn Fn(Download) -> DownloadHandlerFuture + Send + Sync>;

/// Dialog event handler
type DialogHandler = Arc<dyn Fn(Dialog) -> DialogHandlerFuture + Send + Sync>;

/// Request event handler
type RequestHandler = Arc<dyn Fn(Request) -> RequestHandlerFuture + Send + Sync>;

/// Response event handler
type ResponseHandler = Arc<dyn Fn(ResponseObject) -> ResponseHandlerFuture + Send + Sync>;

/// WebSocket event handler
type WebSocketHandler = Arc<dyn Fn(WebSocket) -> WebSocketHandlerFuture + Send + Sync>;

/// Type alias for boxed console handler future
type ConsoleHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// Console event handler
type ConsoleHandler =
    Arc<dyn Fn(crate::protocol::ConsoleMessage) -> ConsoleHandlerFuture + Send + Sync>;

/// Type alias for boxed filechooser handler future
type FileChooserHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// FileChooser event handler
type FileChooserHandler =
    Arc<dyn Fn(crate::protocol::FileChooser) -> FileChooserHandlerFuture + Send + Sync>;

/// Type alias for boxed close handler future
type CloseHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// close event handler (no arguments)
type CloseHandler = Arc<dyn Fn() -> CloseHandlerFuture + Send + Sync>;

/// Type alias for boxed load handler future
type LoadHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// load event handler (no arguments)
type LoadHandler = Arc<dyn Fn() -> LoadHandlerFuture + Send + Sync>;

/// Type alias for boxed crash handler future
type CrashHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// crash event handler (no arguments)
type CrashHandler = Arc<dyn Fn() -> CrashHandlerFuture + Send + Sync>;

/// Type alias for boxed pageError handler future
type PageErrorHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// pageError event handler — receives the error message as a String
type PageErrorHandler = Arc<dyn Fn(String) -> PageErrorHandlerFuture + Send + Sync>;

/// Type alias for boxed popup handler future
type PopupHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// popup event handler — receives the new popup Page
type PopupHandler = Arc<dyn Fn(Page) -> PopupHandlerFuture + Send + Sync>;

/// Type alias for boxed frameAttached/Detached/Navigated handler future
type FrameEventHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// frameAttached event handler
type FrameAttachedHandler =
    Arc<dyn Fn(crate::protocol::Frame) -> FrameEventHandlerFuture + Send + Sync>;

/// frameDetached event handler
type FrameDetachedHandler =
    Arc<dyn Fn(crate::protocol::Frame) -> FrameEventHandlerFuture + Send + Sync>;

/// frameNavigated event handler
type FrameNavigatedHandler =
    Arc<dyn Fn(crate::protocol::Frame) -> FrameEventHandlerFuture + Send + Sync>;

/// Type alias for boxed worker handler future
type WorkerHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// worker event handler — receives the new Worker
type WorkerHandler = Arc<dyn Fn(crate::protocol::Worker) -> WorkerHandlerFuture + Send + Sync>;

/// Type alias for boxed page-level binding callback future
type PageBindingCallbackFuture = Pin<Box<dyn Future<Output = serde_json::Value> + Send>>;

/// Page-level binding callback: receives deserialized JS args, returns a JSON value
type PageBindingCallback =
    Arc<dyn Fn(Vec<serde_json::Value>) -> PageBindingCallbackFuture + Send + Sync>;

/// Type alias for boxed locator handler future
type LocatorHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;

/// Locator handler callback: receives the matching Locator
type LocatorHandlerFn = Arc<dyn Fn(crate::protocol::Locator) -> LocatorHandlerFuture + Send + Sync>;

/// Entry in the locator handler registry
struct LocatorHandlerEntry {
    uid: u32,
    selector: String,
    handler: LocatorHandlerFn,
    /// Remaining invocations; `None` means unlimited.
    times_remaining: Option<u32>,
}

impl Page {
    /// Creates a new Page from protocol initialization
    ///
    /// This is called by the object factory when the server sends a `__create__` message
    /// for a Page object.
    ///
    /// # Arguments
    ///
    /// * `parent` - The parent BrowserContext object
    /// * `type_name` - The protocol type name ("Page")
    /// * `guid` - The unique identifier for this page
    /// * `initializer` - The initialization data from the server
    ///
    /// # Errors
    ///
    /// Returns error if initializer is malformed
    pub fn new(
        parent: Arc<dyn ChannelOwner>,
        type_name: String,
        guid: Arc<str>,
        initializer: Value,
    ) -> Result<Self> {
        // Extract mainFrame GUID from initializer
        let main_frame_guid: Arc<str> =
            Arc::from(initializer["mainFrame"]["guid"].as_str().ok_or_else(|| {
                crate::error::Error::ProtocolError(
                    "Page initializer missing 'mainFrame.guid' field".to_string(),
                )
            })?);

        // Check the parent BrowserContext's initializer for record_video before
        // moving `parent` into ChannelOwnerImpl. The Playwright server delivers
        // the video artifact GUID directly in the Page initializer's "video" field.
        let has_video = parent
            .initializer()
            .get("options")
            .and_then(|opts| opts.get("recordVideo"))
            .is_some();

        let video_artifact_guid: Option<String> = initializer
            .get("video")
            .and_then(|v| v.get("guid"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let base = ChannelOwnerImpl::new(
            ParentOrConnection::Parent(parent),
            type_name,
            guid,
            initializer,
        );

        // Initialize URL to about:blank
        let url = Arc::new(RwLock::new("about:blank".to_string()));

        // Initialize empty route handlers
        let route_handlers = Arc::new(Mutex::new(Vec::new()));

        // Initialize empty event handlers
        let download_handlers = Arc::new(Mutex::new(Vec::new()));
        let dialog_handlers = Arc::new(Mutex::new(Vec::new()));
        let websocket_handlers = Arc::new(Mutex::new(Vec::new()));
        let ws_route_handlers = Arc::new(Mutex::new(Vec::new()));

        // Initialize cached main frame as empty (will be populated on first access)
        let cached_main_frame = Arc::new(Mutex::new(None));

        // Extract viewport from initializer (may be null for no_viewport contexts)
        let initial_viewport: Option<Viewport> =
            base.initializer().get("viewportSize").and_then(|v| {
                if v.is_null() {
                    None
                } else {
                    serde_json::from_value(v.clone()).ok()
                }
            });
        let viewport = Arc::new(RwLock::new(initial_viewport));

        let video = if has_video {
            let v = crate::protocol::Video::new();
            // Resolve the artifact from the initializer-provided GUID.
            if let Some(artifact_guid) = video_artifact_guid {
                let connection = base.connection();
                let v_clone = v.clone();
                tokio::spawn(async move {
                    match connection.get_object(&artifact_guid).await {
                        Ok(artifact_arc) => v_clone.set_artifact(artifact_arc),
                        Err(e) => tracing::warn!(
                            "Failed to resolve video artifact {} from initializer: {}",
                            artifact_guid,
                            e
                        ),
                    }
                });
            }
            Some(v)
        } else {
            None
        };

        Ok(Self {
            base,
            url,
            main_frame_guid,
            cached_main_frame,
            route_handlers,
            download_handlers,
            dialog_handlers,
            request_handlers: Default::default(),
            request_finished_handlers: Default::default(),
            request_failed_handlers: Default::default(),
            response_handlers: Default::default(),
            websocket_handlers,
            ws_route_handlers,
            viewport,
            is_closed: Arc::new(AtomicBool::new(false)),
            default_timeout_ms: Arc::new(AtomicU64::new(crate::DEFAULT_TIMEOUT_MS.to_bits())),
            default_navigation_timeout_ms: Arc::new(AtomicU64::new(
                crate::DEFAULT_TIMEOUT_MS.to_bits(),
            )),
            binding_callbacks: Arc::new(Mutex::new(HashMap::new())),
            console_handlers: Arc::new(Mutex::new(Vec::new())),
            filechooser_handlers: Arc::new(Mutex::new(Vec::new())),
            filechooser_waiters: Arc::new(Mutex::new(Vec::new())),
            popup_waiters: Arc::new(Mutex::new(Vec::new())),
            download_waiters: Arc::new(Mutex::new(Vec::new())),
            response_waiters: Arc::new(Mutex::new(Vec::new())),
            request_waiters: Arc::new(Mutex::new(Vec::new())),
            console_waiters: Arc::new(Mutex::new(Vec::new())),
            close_handlers: Arc::new(Mutex::new(Vec::new())),
            load_handlers: Arc::new(Mutex::new(Vec::new())),
            crash_handlers: Arc::new(Mutex::new(Vec::new())),
            pageerror_handlers: Arc::new(Mutex::new(Vec::new())),
            popup_handlers: Arc::new(Mutex::new(Vec::new())),
            frameattached_handlers: Arc::new(Mutex::new(Vec::new())),
            framedetached_handlers: Arc::new(Mutex::new(Vec::new())),
            framenavigated_handlers: Arc::new(Mutex::new(Vec::new())),
            worker_handlers: Arc::new(Mutex::new(Vec::new())),
            close_waiters: Arc::new(Mutex::new(Vec::new())),
            load_waiters: Arc::new(Mutex::new(Vec::new())),
            crash_waiters: Arc::new(Mutex::new(Vec::new())),
            pageerror_waiters: Arc::new(Mutex::new(Vec::new())),
            frameattached_waiters: Arc::new(Mutex::new(Vec::new())),
            framedetached_waiters: Arc::new(Mutex::new(Vec::new())),
            framenavigated_waiters: Arc::new(Mutex::new(Vec::new())),
            worker_waiters: Arc::new(Mutex::new(Vec::new())),
            console_messages_log: Arc::new(Mutex::new(Vec::new())),
            page_errors_log: Arc::new(Mutex::new(Vec::new())),
            workers_list: Arc::new(Mutex::new(Vec::new())),
            video,
            locator_handlers: Arc::new(Mutex::new(Vec::new())),
        })
    }

    /// Returns the channel for sending protocol messages
    ///
    /// Used internally for sending RPC calls to the page.
    fn channel(&self) -> &Channel {
        self.base.channel()
    }

    /// Returns the main frame of the page.
    ///
    /// The main frame is where navigation and DOM operations actually happen.
    ///
    /// This method also wires up the back-reference from the frame to the page so that
    /// `frame.page()`, `frame.locator()`, and `frame.get_by_*()` work correctly.
    pub async fn main_frame(&self) -> Result<crate::protocol::Frame> {
        // Get and downcast the Frame object from the connection's object registry
        let frame: crate::protocol::Frame = self
            .connection()
            .get_typed::<crate::protocol::Frame>(&self.main_frame_guid)
            .await?;

        // Wire up the back-reference so frame.page() / frame.locator() work.
        // This is safe to call multiple times (subsequent calls are no-ops once set).
        frame.set_page(self.clone());

        // Cache the frame for synchronous access in url()
        if let Ok(mut cached) = self.cached_main_frame.lock() {
            *cached = Some(frame.clone());
        }

        Ok(frame)
    }

    /// Returns the current URL of the page.
    ///
    /// This returns the last committed URL, including hash fragments from anchor navigation.
    /// Initially, pages are at "about:blank".
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-url>
    pub fn url(&self) -> String {
        // Try to get URL from the cached main frame (source of truth for navigation including hashes)
        if let Ok(cached) = self.cached_main_frame.lock()
            && let Some(frame) = cached.as_ref()
        {
            return frame.url();
        }

        // Fallback to cached URL if frame not yet loaded
        self.url.read().unwrap().clone()
    }

    /// Closes the page.
    ///
    /// This is a graceful operation that sends a close command to the page
    /// and waits for it to shut down properly.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Page has already been closed
    /// - Communication with browser process fails
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-close>
    pub async fn close(&self) -> Result<()> {
        // Send close RPC to server
        let result = self
            .channel()
            .send_no_result("close", serde_json::json!({}))
            .await;
        // Mark as closed regardless of error (best-effort)
        self.is_closed.store(true, Ordering::Relaxed);
        result
    }

    /// Returns whether the page has been closed.
    ///
    /// Returns `true` after `close()` has been called on this page, or after the
    /// page receives a close event from the server (e.g. when the browser context
    /// is closed).
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-is-closed>
    pub fn is_closed(&self) -> bool {
        self.is_closed.load(Ordering::Relaxed)
    }

    /// Returns all console messages received so far on this page.
    ///
    /// Messages are accumulated in order as they arrive via the `console` event.
    /// Each call returns a snapshot; new messages arriving concurrently may or may not
    /// be included depending on timing.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-console-messages>
    pub fn console_messages(&self) -> Vec<crate::protocol::ConsoleMessage> {
        self.console_messages_log.lock().unwrap().clone()
    }

    /// Returns all uncaught JavaScript error messages received so far on this page.
    ///
    /// Errors are accumulated in order as they arrive via the `pageError` event.
    /// Each string is the `.message` field of the thrown `Error`.
    pub fn page_errors(&self) -> Vec<String> {
        self.page_errors_log.lock().unwrap().clone()
    }

    /// Returns the page that opened this popup, or `None` if this page was not opened
    /// by another page.
    ///
    /// The opener is available from the page's initializer — it is the page that called
    /// `window.open()` or triggered a link with `target="_blank"`. Returns `None` for
    /// top-level pages that were not opened as popups.
    ///
    /// # Errors
    ///
    /// Returns error if the opener page GUID is present in the initializer but the
    /// object is not found in the connection registry.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-opener>
    pub async fn opener(&self) -> Result<Option<Page>> {
        // The opener guid is stored in the page initializer as {"opener": {"guid": "..."}}.
        // It is set when the page is created as a popup; absent for non-popup pages.
        let opener_guid = self
            .base
            .initializer()
            .get("opener")
            .and_then(|v| v.get("guid"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        match opener_guid {
            None => Ok(None),
            Some(guid) => {
                let page = self.connection().get_typed::<Page>(&guid).await?;
                Ok(Some(page))
            }
        }
    }

    /// Returns all active web workers belonging to this page.
    ///
    /// Workers are tracked as they are created (`worker` event) and this method
    /// returns a snapshot of the current list.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-workers>
    pub fn workers(&self) -> Vec<Worker> {
        self.workers_list.lock().unwrap().clone()
    }

    /// Sets the default timeout for all operations on this page.
    ///
    /// The timeout applies to actions such as `click`, `fill`, `locator.wait_for`, etc.
    /// Pass `0` to disable timeouts.
    ///
    /// This stores the value locally so that subsequent action calls use it when
    /// no explicit timeout is provided, and also notifies the Playwright server
    /// so it can apply the same default on its side.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Timeout in milliseconds
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-set-default-timeout>
    pub async fn set_default_timeout(&self, timeout: f64) {
        self.default_timeout_ms
            .store(timeout.to_bits(), Ordering::Relaxed);
        set_timeout_and_notify(self.channel(), "setDefaultTimeoutNoReply", timeout).await;
    }

    /// Sets the default timeout for navigation operations on this page.
    ///
    /// The timeout applies to navigation actions such as `goto`, `reload`,
    /// `go_back`, and `go_forward`. Pass `0` to disable timeouts.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Timeout in milliseconds
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-set-default-navigation-timeout>
    pub async fn set_default_navigation_timeout(&self, timeout: f64) {
        self.default_navigation_timeout_ms
            .store(timeout.to_bits(), Ordering::Relaxed);
        set_timeout_and_notify(
            self.channel(),
            "setDefaultNavigationTimeoutNoReply",
            timeout,
        )
        .await;
    }

    /// Returns the current default action timeout in milliseconds.
    pub fn default_timeout_ms(&self) -> f64 {
        f64::from_bits(self.default_timeout_ms.load(Ordering::Relaxed))
    }

    /// Returns the current default navigation timeout in milliseconds.
    pub fn default_navigation_timeout_ms(&self) -> f64 {
        f64::from_bits(self.default_navigation_timeout_ms.load(Ordering::Relaxed))
    }

    /// Returns GotoOptions with the navigation timeout filled in if not already set.
    ///
    /// Used internally to ensure the page's configured default navigation timeout
    /// is used when the caller does not provide an explicit timeout.
    fn with_navigation_timeout(&self, options: Option<GotoOptions>) -> GotoOptions {
        let nav_timeout = self.default_navigation_timeout_ms();
        match options {
            Some(opts) if opts.timeout.is_some() => opts,
            Some(mut opts) => {
                opts.timeout = Some(std::time::Duration::from_millis(nav_timeout as u64));
                opts
            }
            None => GotoOptions {
                timeout: Some(std::time::Duration::from_millis(nav_timeout as u64)),
                wait_until: None,
            },
        }
    }

    /// Returns all frames in the page, including the main frame.
    ///
    /// Currently returns only the main (top-level) frame. Iframe enumeration
    /// is not yet implemented and will be added in a future release.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Page has been closed
    /// - Communication with browser process fails
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-frames>
    pub async fn frames(&self) -> Result<Vec<crate::protocol::Frame>> {
        // Start with the main frame
        let main = self.main_frame().await?;
        Ok(vec![main])
    }

    /// Navigates to the specified URL.
    ///
    /// Returns `None` when navigating to URLs that don't produce responses (e.g., data URLs,
    /// about:blank). This matches Playwright's behavior across all language bindings.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to navigate to
    /// * `options` - Optional navigation options (timeout, wait_until)
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - URL is invalid
    /// - Navigation timeout (default 30s)
    /// - Network error
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-goto>
    pub async fn goto(&self, url: &str, options: Option<GotoOptions>) -> Result<Option<Response>> {
        // Inject the page-level navigation timeout when no explicit timeout is given
        let options = self.with_navigation_timeout(options);

        // Delegate to main frame
        let frame = self.main_frame().await.map_err(|e| match e {
            Error::TargetClosed { context, .. } => Error::TargetClosed {
                target_type: "Page".to_string(),
                context,
            },
            other => other,
        })?;

        let response = frame.goto(url, Some(options)).await.map_err(|e| match e {
            Error::TargetClosed { context, .. } => Error::TargetClosed {
                target_type: "Page".to_string(),
                context,
            },
            other => other,
        })?;

        // Update the page's URL if we got a response
        if let Some(ref resp) = response
            && let Ok(mut page_url) = self.url.write()
        {
            *page_url = resp.url().to_string();
        }

        Ok(response)
    }

    /// Returns the browser context that the page belongs to.
    pub fn context(&self) -> Result<crate::protocol::BrowserContext> {
        downcast_parent::<crate::protocol::BrowserContext>(self)
            .ok_or_else(|| Error::ProtocolError("Page parent is not a BrowserContext".to_string()))
    }

    /// Returns the Clock object for this page's browser context.
    ///
    /// This is a convenience accessor that delegates to the parent context's clock.
    /// All clock RPCs are sent on the BrowserContext channel regardless of whether
    /// the Clock is obtained via `page.clock()` or `context.clock()`.
    ///
    /// # Errors
    ///
    /// Returns error if the page's parent is not a BrowserContext.
    ///
    /// See: <https://playwright.dev/docs/api/class-clock>
    pub fn clock(&self) -> Result<crate::protocol::clock::Clock> {
        Ok(self.context()?.clock())
    }

    /// Returns the `Video` object associated with this page, if video recording is enabled.
    ///
    /// Returns `Some(Video)` when the browser context was created with the `record_video`
    /// option; returns `None` otherwise.
    ///
    /// The `Video` shell is created eagerly. The underlying recording artifact is wired
    /// up when the Playwright server fires the internal `"video"` event (which typically
    /// happens when the page is first navigated). Calling [`crate::protocol::Video::save_as`] or
    /// [`crate::protocol::Video::path`] before the artifact arrives returns an error; close the page
    /// first to guarantee the artifact is ready.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-video>
    pub fn video(&self) -> Option<crate::protocol::Video> {
        self.video.clone()
    }

    /// Pauses script execution.
    ///
    /// Playwright will stop executing the script and wait for the user to either press
    /// "Resume" in the page overlay or in the debugger.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-pause>
    pub async fn pause(&self) -> Result<()> {
        self.context()?.pause().await
    }

    /// Returns the page's title.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-title>
    pub async fn title(&self) -> Result<String> {
        // Delegate to main frame
        let frame = self.main_frame().await?;
        frame.title().await
    }

    /// Returns the full HTML content of the page, including the DOCTYPE.
    ///
    /// This method retrieves the complete HTML markup of the page,
    /// including the doctype declaration and all DOM elements.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-content>
    pub async fn content(&self) -> Result<String> {
        // Delegate to main frame
        let frame = self.main_frame().await?;
        frame.content().await
    }

    /// Sets the content of the page.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-set-content>
    pub async fn set_content(&self, html: &str, options: Option<GotoOptions>) -> Result<()> {
        let frame = self.main_frame().await?;
        frame.set_content(html, options).await
    }

    /// Waits for the required load state to be reached.
    ///
    /// This resolves when the page reaches a required load state, `load` by default.
    /// The navigation must have been committed when this method is called. If the current
    /// document has already reached the required state, resolves immediately.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-wait-for-load-state>
    pub async fn wait_for_load_state(&self, state: Option<WaitUntil>) -> Result<()> {
        let frame = self.main_frame().await?;
        frame.wait_for_load_state(state).await
    }

    /// Waits for the main frame to navigate to a URL matching the given string or glob pattern.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-wait-for-url>
    pub async fn wait_for_url(&self, url: &str, options: Option<GotoOptions>) -> Result<()> {
        let frame = self.main_frame().await?;
        frame.wait_for_url(url, options).await
    }

    /// Creates a locator for finding elements on the page.
    ///
    /// Locators are the central piece of Playwright's auto-waiting and retry-ability.
    /// They don't execute queries until an action is performed.
    ///
    /// # Arguments
    ///
    /// * `selector` - CSS selector or other locating strategy
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-locator>
    pub async fn locator(&self, selector: &str) -> crate::protocol::Locator {
        // Get the main frame
        let frame = self.main_frame().await.expect("Main frame should exist");

        crate::protocol::Locator::new(Arc::new(frame), selector.to_string(), self.clone())
    }

    /// Creates a [`FrameLocator`](crate::protocol::FrameLocator) for an iframe on this page.
    ///
    /// The `selector` identifies the iframe element (e.g., `"iframe[name='content']"`).
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-frame-locator>
    pub async fn frame_locator(&self, selector: &str) -> crate::protocol::FrameLocator {
        let frame = self.main_frame().await.expect("Main frame should exist");
        crate::protocol::FrameLocator::new(Arc::new(frame), selector.to_string(), self.clone())
    }

    /// Returns a locator that matches elements containing the given text.
    ///
    /// By default, matching is case-insensitive and searches for a substring.
    /// Set `exact` to `true` for case-sensitive exact matching.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-get-by-text>
    pub async fn get_by_text(&self, text: &str, exact: bool) -> crate::protocol::Locator {
        self.locator(&crate::protocol::locator::get_by_text_selector(text, exact))
            .await
    }

    /// Returns a locator that matches elements by their associated label text.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-get-by-label>
    pub async fn get_by_label(&self, text: &str, exact: bool) -> crate::protocol::Locator {
        self.locator(&crate::protocol::locator::get_by_label_selector(
            text, exact,
        ))
        .await
    }

    /// Returns a locator that matches elements by their placeholder text.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-get-by-placeholder>
    pub async fn get_by_placeholder(&self, text: &str, exact: bool) -> crate::protocol::Locator {
        self.locator(&crate::protocol::locator::get_by_placeholder_selector(
            text, exact,
        ))
        .await
    }

    /// Returns a locator that matches elements by their alt text.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-get-by-alt-text>
    pub async fn get_by_alt_text(&self, text: &str, exact: bool) -> crate::protocol::Locator {
        self.locator(&crate::protocol::locator::get_by_alt_text_selector(
            text, exact,
        ))
        .await
    }

    /// Returns a locator that matches elements by their title attribute.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-get-by-title>
    pub async fn get_by_title(&self, text: &str, exact: bool) -> crate::protocol::Locator {
        self.locator(&crate::protocol::locator::get_by_title_selector(
            text, exact,
        ))
        .await
    }

    /// Returns a locator that matches elements by their test ID attribute.
    ///
    /// By default, uses the `data-testid` attribute. Call
    /// [`playwright.selectors().set_test_id_attribute()`](crate::protocol::Selectors::set_test_id_attribute)
    /// to change the attribute name.
    ///
    /// Always uses exact matching (case-sensitive).
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-get-by-test-id>
    pub async fn get_by_test_id(&self, test_id: &str) -> crate::protocol::Locator {
        let attr = self.connection().selectors().test_id_attribute();
        self.locator(&crate::protocol::locator::get_by_test_id_selector_with_attr(test_id, &attr))
            .await
    }

    /// Returns a locator that matches elements by their ARIA role.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-get-by-role>
    pub async fn get_by_role(
        &self,
        role: crate::protocol::locator::AriaRole,
        options: Option<crate::protocol::locator::GetByRoleOptions>,
    ) -> crate::protocol::Locator {
        self.locator(&crate::protocol::locator::get_by_role_selector(
            role, options,
        ))
        .await
    }

    /// Returns the keyboard instance for low-level keyboard control.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-keyboard>
    pub fn keyboard(&self) -> crate::protocol::Keyboard {
        crate::protocol::Keyboard::new(self.clone())
    }

    /// Returns the mouse instance for low-level mouse control.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-mouse>
    pub fn mouse(&self) -> crate::protocol::Mouse {
        crate::protocol::Mouse::new(self.clone())
    }

    // Internal keyboard methods (called by Keyboard struct)

    pub(crate) async fn keyboard_down(&self, key: &str) -> Result<()> {
        self.channel()
            .send_no_result(
                "keyboardDown",
                serde_json::json!({
                    "key": key
                }),
            )
            .await
    }

    pub(crate) async fn keyboard_up(&self, key: &str) -> Result<()> {
        self.channel()
            .send_no_result(
                "keyboardUp",
                serde_json::json!({
                    "key": key
                }),
            )
            .await
    }

    pub(crate) async fn keyboard_press(
        &self,
        key: &str,
        options: Option<crate::protocol::KeyboardOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "key": key
        });

        if let Some(opts) = options {
            let opts_json = opts.to_json();
            if let Some(obj) = params.as_object_mut()
                && let Some(opts_obj) = opts_json.as_object()
            {
                obj.extend(opts_obj.clone());
            }
        }

        self.channel().send_no_result("keyboardPress", params).await
    }

    pub(crate) async fn keyboard_type(
        &self,
        text: &str,
        options: Option<crate::protocol::KeyboardOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "text": text
        });

        if let Some(opts) = options {
            let opts_json = opts.to_json();
            if let Some(obj) = params.as_object_mut()
                && let Some(opts_obj) = opts_json.as_object()
            {
                obj.extend(opts_obj.clone());
            }
        }

        self.channel().send_no_result("keyboardType", params).await
    }

    pub(crate) async fn keyboard_insert_text(&self, text: &str) -> Result<()> {
        self.channel()
            .send_no_result(
                "keyboardInsertText",
                serde_json::json!({
                    "text": text
                }),
            )
            .await
    }

    // Internal mouse methods (called by Mouse struct)

    pub(crate) async fn mouse_move(
        &self,
        x: i32,
        y: i32,
        options: Option<crate::protocol::MouseOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "x": x,
            "y": y
        });

        if let Some(opts) = options {
            let opts_json = opts.to_json();
            if let Some(obj) = params.as_object_mut()
                && let Some(opts_obj) = opts_json.as_object()
            {
                obj.extend(opts_obj.clone());
            }
        }

        self.channel().send_no_result("mouseMove", params).await
    }

    pub(crate) async fn mouse_click(
        &self,
        x: i32,
        y: i32,
        options: Option<crate::protocol::MouseOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "x": x,
            "y": y
        });

        if let Some(opts) = options {
            let opts_json = opts.to_json();
            if let Some(obj) = params.as_object_mut()
                && let Some(opts_obj) = opts_json.as_object()
            {
                obj.extend(opts_obj.clone());
            }
        }

        self.channel().send_no_result("mouseClick", params).await
    }

    pub(crate) async fn mouse_dblclick(
        &self,
        x: i32,
        y: i32,
        options: Option<crate::protocol::MouseOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "x": x,
            "y": y,
            "clickCount": 2
        });

        if let Some(opts) = options {
            let opts_json = opts.to_json();
            if let Some(obj) = params.as_object_mut()
                && let Some(opts_obj) = opts_json.as_object()
            {
                obj.extend(opts_obj.clone());
            }
        }

        self.channel().send_no_result("mouseClick", params).await
    }

    pub(crate) async fn mouse_down(
        &self,
        options: Option<crate::protocol::MouseOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({});

        if let Some(opts) = options {
            let opts_json = opts.to_json();
            if let Some(obj) = params.as_object_mut()
                && let Some(opts_obj) = opts_json.as_object()
            {
                obj.extend(opts_obj.clone());
            }
        }

        self.channel().send_no_result("mouseDown", params).await
    }

    pub(crate) async fn mouse_up(
        &self,
        options: Option<crate::protocol::MouseOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({});

        if let Some(opts) = options {
            let opts_json = opts.to_json();
            if let Some(obj) = params.as_object_mut()
                && let Some(opts_obj) = opts_json.as_object()
            {
                obj.extend(opts_obj.clone());
            }
        }

        self.channel().send_no_result("mouseUp", params).await
    }

    pub(crate) async fn mouse_wheel(&self, delta_x: i32, delta_y: i32) -> Result<()> {
        self.channel()
            .send_no_result(
                "mouseWheel",
                serde_json::json!({
                    "deltaX": delta_x,
                    "deltaY": delta_y
                }),
            )
            .await
    }

    // Internal touchscreen method (called by Touchscreen struct)

    pub(crate) async fn touchscreen_tap(&self, x: f64, y: f64) -> Result<()> {
        self.channel()
            .send_no_result(
                "touchscreenTap",
                serde_json::json!({
                    "x": x,
                    "y": y
                }),
            )
            .await
    }

    /// Returns the touchscreen instance for low-level touch input simulation.
    ///
    /// Requires a touch-enabled browser context (`has_touch: true` in
    /// [`BrowserContextOptions`](crate::protocol::browser_context::BrowserContext)).
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-touchscreen>
    pub fn touchscreen(&self) -> crate::protocol::Touchscreen {
        crate::protocol::Touchscreen::new(self.clone())
    }

    /// Performs a drag from source selector to target selector.
    ///
    /// This is the page-level equivalent of `Locator::drag_to()`. It resolves
    /// both selectors in the main frame and performs the drag.
    ///
    /// # Arguments
    ///
    /// * `source` - A CSS selector for the element to drag from
    /// * `target` - A CSS selector for the element to drop onto
    /// * `options` - Optional drag options (positions, force, timeout, trial)
    ///
    /// # Errors
    ///
    /// Returns error if either selector does not resolve to an element, the
    /// drag action times out, or the page has been closed.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-drag-and-drop>
    pub async fn drag_and_drop(
        &self,
        source: &str,
        target: &str,
        options: Option<crate::protocol::DragToOptions>,
    ) -> Result<()> {
        let frame = self.main_frame().await?;
        frame.locator_drag_to(source, target, options).await
    }

    /// Reloads the current page.
    ///
    /// # Arguments
    ///
    /// * `options` - Optional reload options (timeout, wait_until)
    ///
    /// Returns `None` when reloading pages that don't produce responses (e.g., data URLs,
    /// about:blank). This matches Playwright's behavior across all language bindings.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-reload>
    pub async fn reload(&self, options: Option<GotoOptions>) -> Result<Option<Response>> {
        self.navigate_history("reload", options).await
    }

    /// Navigates to the previous page in history.
    ///
    /// Returns the main resource response. In case of multiple server redirects, the navigation
    /// will resolve with the response of the last redirect. If can not go back, returns `None`.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-go-back>
    pub async fn go_back(&self, options: Option<GotoOptions>) -> Result<Option<Response>> {
        self.navigate_history("goBack", options).await
    }

    /// Navigates to the next page in history.
    ///
    /// Returns the main resource response. In case of multiple server redirects, the navigation
    /// will resolve with the response of the last redirect. If can not go forward, returns `None`.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-go-forward>
    pub async fn go_forward(&self, options: Option<GotoOptions>) -> Result<Option<Response>> {
        self.navigate_history("goForward", options).await
    }

    /// Shared implementation for reload, go_back and go_forward.
    async fn navigate_history(
        &self,
        method: &str,
        options: Option<GotoOptions>,
    ) -> Result<Option<Response>> {
        // Inject the page-level navigation timeout when no explicit timeout is given
        let opts = self.with_navigation_timeout(options);
        let mut params = serde_json::json!({});

        // opts.timeout is always Some(...) because with_navigation_timeout guarantees it
        if let Some(timeout) = opts.timeout {
            params["timeout"] = serde_json::json!(timeout.as_millis() as u64);
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }
        if let Some(wait_until) = opts.wait_until {
            params["waitUntil"] = serde_json::json!(wait_until.as_str());
        }

        #[derive(Deserialize)]
        struct NavigationResponse {
            response: Option<ResponseReference>,
        }

        #[derive(Deserialize)]
        struct ResponseReference {
            #[serde(deserialize_with = "crate::server::connection::deserialize_arc_str")]
            guid: Arc<str>,
        }

        let result: NavigationResponse = self.channel().send(method, params).await?;

        if let Some(response_ref) = result.response {
            let response_arc = {
                let mut attempts = 0;
                let max_attempts = 20;
                loop {
                    match self.connection().get_object(&response_ref.guid).await {
                        Ok(obj) => break obj,
                        Err(_) if attempts < max_attempts => {
                            attempts += 1;
                            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                        }
                        Err(e) => return Err(e),
                    }
                }
            };

            let initializer = response_arc.initializer();

            let status = initializer["status"].as_u64().ok_or_else(|| {
                crate::error::Error::ProtocolError("Response missing status".to_string())
            })? as u16;

            let headers = initializer["headers"]
                .as_array()
                .ok_or_else(|| {
                    crate::error::Error::ProtocolError("Response missing headers".to_string())
                })?
                .iter()
                .filter_map(|h| {
                    let name = h["name"].as_str()?;
                    let value = h["value"].as_str()?;
                    Some((name.to_string(), value.to_string()))
                })
                .collect();

            let response = Response::new(
                initializer["url"]
                    .as_str()
                    .ok_or_else(|| {
                        crate::error::Error::ProtocolError("Response missing url".to_string())
                    })?
                    .to_string(),
                status,
                initializer["statusText"].as_str().unwrap_or("").to_string(),
                headers,
                Some(response_arc),
            );

            if let Ok(mut page_url) = self.url.write() {
                *page_url = response.url().to_string();
            }

            Ok(Some(response))
        } else {
            Ok(None)
        }
    }

    /// Returns the first element matching the selector, or None if not found.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-query-selector>
    pub async fn query_selector(
        &self,
        selector: &str,
    ) -> Result<Option<Arc<crate::protocol::ElementHandle>>> {
        let frame = self.main_frame().await?;
        frame.query_selector(selector).await
    }

    /// Returns all elements matching the selector.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-query-selector-all>
    pub async fn query_selector_all(
        &self,
        selector: &str,
    ) -> Result<Vec<Arc<crate::protocol::ElementHandle>>> {
        let frame = self.main_frame().await?;
        frame.query_selector_all(selector).await
    }

    /// Takes a screenshot of the page and returns the image bytes.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-screenshot>
    pub async fn screenshot(
        &self,
        options: Option<crate::protocol::ScreenshotOptions>,
    ) -> Result<Vec<u8>> {
        let params = if let Some(opts) = options {
            opts.to_json()
        } else {
            // Default to PNG with required timeout
            serde_json::json!({
                "type": "png",
                "timeout": crate::DEFAULT_TIMEOUT_MS
            })
        };

        #[derive(Deserialize)]
        struct ScreenshotResponse {
            binary: String,
        }

        let response: ScreenshotResponse = self.channel().send("screenshot", params).await?;

        // Decode base64 to bytes
        let bytes = base64::prelude::BASE64_STANDARD
            .decode(&response.binary)
            .map_err(|e| {
                crate::error::Error::ProtocolError(format!("Failed to decode screenshot: {}", e))
            })?;

        Ok(bytes)
    }

    /// Takes a screenshot and saves it to a file, also returning the bytes.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-screenshot>
    pub async fn screenshot_to_file(
        &self,
        path: &std::path::Path,
        options: Option<crate::protocol::ScreenshotOptions>,
    ) -> Result<Vec<u8>> {
        // Get the screenshot bytes
        let bytes = self.screenshot(options).await?;

        // Write to file
        tokio::fs::write(path, &bytes).await.map_err(|e| {
            crate::error::Error::ProtocolError(format!("Failed to write screenshot file: {}", e))
        })?;

        Ok(bytes)
    }

    /// Evaluates JavaScript in the page context (without return value).
    ///
    /// Executes the provided JavaScript expression or function within the page's
    /// context without returning a value.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-evaluate>
    pub async fn evaluate_expression(&self, expression: &str) -> Result<()> {
        // Delegate to the main frame
        let frame = self.main_frame().await?;
        frame.frame_evaluate_expression(expression).await
    }

    /// Evaluates JavaScript in the page context with optional arguments.
    ///
    /// Executes the provided JavaScript expression or function within the page's
    /// context and returns the result. The return value must be JSON-serializable.
    ///
    /// # Arguments
    ///
    /// * `expression` - JavaScript code to evaluate
    /// * `arg` - Optional argument to pass to the expression (must implement Serialize)
    ///
    /// # Returns
    ///
    /// The result as a `serde_json::Value`
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-evaluate>
    pub async fn evaluate<T: serde::Serialize, U: serde::de::DeserializeOwned>(
        &self,
        expression: &str,
        arg: Option<&T>,
    ) -> Result<U> {
        // Delegate to the main frame
        let frame = self.main_frame().await?;
        let result = frame.evaluate(expression, arg).await?;
        serde_json::from_value(result).map_err(Error::from)
    }

    /// Evaluates a JavaScript expression and returns the result as a String.
    ///
    /// # Arguments
    ///
    /// * `expression` - JavaScript code to evaluate
    ///
    /// # Returns
    ///
    /// The result converted to a String
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-evaluate>
    pub async fn evaluate_value(&self, expression: &str) -> Result<String> {
        let frame = self.main_frame().await?;
        frame.frame_evaluate_expression_value(expression).await
    }

    /// Registers a route handler for network interception.
    ///
    /// When a request matches the specified pattern, the handler will be called
    /// with a Route object that can abort, continue, or fulfill the request.
    ///
    /// # Arguments
    ///
    /// * `pattern` - URL pattern to match (supports glob patterns like "**/*.png")
    /// * `handler` - Async closure that handles the route
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-route>
    pub async fn route<F, Fut>(&self, pattern: &str, handler: F) -> Result<()>
    where
        F: Fn(Route) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        // 1. Wrap handler in Arc with type erasure
        let handler =
            Arc::new(move |route: Route| -> RouteHandlerFuture { Box::pin(handler(route)) });

        // 2. Store in handlers list
        self.route_handlers.lock().unwrap().push(RouteHandlerEntry {
            pattern: pattern.to_string(),
            handler,
        });

        // 3. Enable network interception via protocol
        self.enable_network_interception().await?;

        Ok(())
    }

    /// Updates network interception patterns for this page
    async fn enable_network_interception(&self) -> Result<()> {
        // Collect all patterns from registered handlers
        // Each pattern must be an object with "glob" field
        let patterns: Vec<serde_json::Value> = self
            .route_handlers
            .lock()
            .unwrap()
            .iter()
            .map(|entry| serde_json::json!({ "glob": entry.pattern }))
            .collect();

        // Send protocol command to update network interception patterns
        // Follows playwright-python's approach
        self.channel()
            .send_no_result(
                "setNetworkInterceptionPatterns",
                serde_json::json!({
                    "patterns": patterns
                }),
            )
            .await
    }

    /// Removes route handler(s) matching the given URL pattern.
    ///
    /// # Arguments
    ///
    /// * `pattern` - URL pattern to remove handlers for
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-unroute>
    pub async fn unroute(&self, pattern: &str) -> Result<()> {
        self.route_handlers
            .lock()
            .unwrap()
            .retain(|entry| entry.pattern != pattern);
        self.enable_network_interception().await
    }

    /// Removes all registered route handlers.
    ///
    /// # Arguments
    ///
    /// * `behavior` - Optional behavior for in-flight handlers
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-unroute-all>
    pub async fn unroute_all(
        &self,
        _behavior: Option<crate::protocol::route::UnrouteBehavior>,
    ) -> Result<()> {
        self.route_handlers.lock().unwrap().clear();
        self.enable_network_interception().await
    }

    /// Replays network requests from a HAR file recorded previously.
    ///
    /// Requests matching `options.url` (or all requests if omitted) will be
    /// served from the archive instead of hitting the network.  Unmatched
    /// requests are either aborted or passed through depending on
    /// `options.not_found` (`"abort"` is the default).
    ///
    /// # Arguments
    ///
    /// * `har_path` - Path to the `.har` file on disk
    /// * `options` - Optional settings (url filter, not_found policy, update mode)
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - `har_path` does not exist or cannot be read by the Playwright server
    /// - The Playwright server fails to open the archive
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-route-from-har>
    pub async fn route_from_har(
        &self,
        har_path: &str,
        options: Option<RouteFromHarOptions>,
    ) -> Result<()> {
        let opts = options.unwrap_or_default();
        let not_found = opts.not_found.unwrap_or_else(|| "abort".to_string());
        let url_filter = opts.url.clone();

        // Resolve to an absolute path so the Playwright server can open it
        // regardless of its working directory.
        let abs_path = std::path::Path::new(har_path).canonicalize().map_err(|e| {
            Error::InvalidPath(format!(
                "route_from_har: cannot resolve '{}': {}",
                har_path, e
            ))
        })?;
        let abs_str = abs_path.to_string_lossy().into_owned();

        // Locate LocalUtils in the connection object registry by type name.
        // The Playwright server registers it with a guid like "localUtils@1"
        // so we scan all objects for the one with type_name "LocalUtils".
        let connection = self.connection();
        let local_utils = {
            let all = connection.all_objects_sync();
            all.into_iter()
                .find(|o| o.type_name() == "LocalUtils")
                .and_then(|o| {
                    o.as_any()
                        .downcast_ref::<crate::protocol::LocalUtils>()
                        .cloned()
                })
                .ok_or_else(|| {
                    Error::ProtocolError(
                        "route_from_har: LocalUtils not found in connection registry".to_string(),
                    )
                })?
        };

        // Open the HAR archive on the server side.
        let har_id = local_utils.har_open(&abs_str).await?;

        // Determine the URL pattern to intercept.
        let pattern = url_filter.clone().unwrap_or_else(|| "**/*".to_string());

        // Register a route handler that performs HAR lookup for each request.
        let har_id_clone = har_id.clone();
        let local_utils_clone = local_utils.clone();
        let not_found_clone = not_found.clone();

        self.route(&pattern, move |route| {
            let har_id = har_id_clone.clone();
            let local_utils = local_utils_clone.clone();
            let not_found = not_found_clone.clone();
            async move {
                let request = route.request();
                let req_url = request.url().to_string();
                let req_method = request.method().to_string();

                // Build headers array as [{name, value}]
                let headers: Vec<serde_json::Value> = request
                    .headers()
                    .iter()
                    .map(|(k, v)| serde_json::json!({"name": k, "value": v}))
                    .collect();

                let lookup = local_utils
                    .har_lookup(
                        &har_id,
                        &req_url,
                        &req_method,
                        headers,
                        None,
                        request.is_navigation_request(),
                    )
                    .await;

                match lookup {
                    Err(e) => {
                        tracing::warn!("har_lookup error for {}: {}", req_url, e);
                        route.continue_(None).await
                    }
                    Ok(result) => match result.action.as_str() {
                        "redirect" => {
                            let redirect_url = result.redirect_url.unwrap_or_default();
                            let opts = crate::protocol::ContinueOptions::builder()
                                .url(redirect_url)
                                .build();
                            route.continue_(Some(opts)).await
                        }
                        "fulfill" => {
                            let status = result.status.unwrap_or(200);

                            // Decode base64 body if present
                            let body_bytes = result.body.as_deref().map(|b64| {
                                base64::engine::general_purpose::STANDARD
                                    .decode(b64)
                                    .unwrap_or_default()
                            });

                            // Build headers map
                            let mut headers_map = std::collections::HashMap::new();
                            if let Some(raw_headers) = result.headers {
                                for h in raw_headers {
                                    if let (Some(name), Some(value)) = (
                                        h.get("name").and_then(|v| v.as_str()),
                                        h.get("value").and_then(|v| v.as_str()),
                                    ) {
                                        headers_map.insert(name.to_string(), value.to_string());
                                    }
                                }
                            }

                            let mut builder =
                                crate::protocol::FulfillOptions::builder().status(status);

                            if !headers_map.is_empty() {
                                builder = builder.headers(headers_map);
                            }

                            if let Some(body) = body_bytes {
                                builder = builder.body(body);
                            }

                            route.fulfill(Some(builder.build())).await
                        }
                        _ => {
                            // "fallback" or "error" or unknown
                            if not_found == "fallback" {
                                route.fallback(None).await
                            } else {
                                route.abort(None).await
                            }
                        }
                    },
                }
            }
        })
        .await
    }

    /// Intercepts WebSocket connections matching the given URL pattern.
    ///
    /// When a WebSocket connection from the page matches `url`, the `handler`
    /// is called with a [`WebSocketRoute`](crate::protocol::WebSocketRoute) object.
    /// The handler must call [`connect_to_server`](crate::protocol::WebSocketRoute::connect_to_server)
    /// to forward the connection to the real server, or
    /// [`close`](crate::protocol::WebSocketRoute::close) to terminate it.
    ///
    /// # Arguments
    ///
    /// * `url` — URL glob pattern (e.g. `"ws://**"` or `"wss://example.com/ws"`).
    /// * `handler` — Async closure receiving a `WebSocketRoute`.
    ///
    /// # Errors
    ///
    /// Returns an error if the RPC call to enable interception fails.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-route-web-socket>
    pub async fn route_web_socket<F, Fut>(&self, url: &str, handler: F) -> Result<()>
    where
        F: Fn(crate::protocol::WebSocketRoute) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(
            move |route: crate::protocol::WebSocketRoute| -> WebSocketRouteHandlerFuture {
                Box::pin(handler(route))
            },
        );

        self.ws_route_handlers
            .lock()
            .unwrap()
            .push(WsRouteHandlerEntry {
                pattern: url.to_string(),
                handler,
            });

        self.enable_ws_interception().await
    }

    /// Updates WebSocket interception patterns for this page.
    async fn enable_ws_interception(&self) -> Result<()> {
        let patterns: Vec<serde_json::Value> = self
            .ws_route_handlers
            .lock()
            .unwrap()
            .iter()
            .map(|entry| serde_json::json!({ "glob": entry.pattern }))
            .collect();

        self.channel()
            .send_no_result(
                "setWebSocketInterceptionPatterns",
                serde_json::json!({ "patterns": patterns }),
            )
            .await
    }

    /// Handles a route event from the protocol
    ///
    /// Called by on_event when a "route" event is received.
    /// Supports handler chaining via `route.fallback()` — if a handler calls
    /// `fallback()` instead of `continue_()`, `abort()`, or `fulfill()`, the
    /// next matching handler in the chain is tried.
    async fn on_route_event(&self, route: Route) {
        let handlers = self.route_handlers.lock().unwrap().clone();
        let url = route.request().url().to_string();

        // Find matching handler (last registered wins, with fallback chaining)
        for entry in handlers.iter().rev() {
            if crate::protocol::route::matches_pattern(&entry.pattern, &url) {
                let handler = entry.handler.clone();
                if let Err(e) = handler(route.clone()).await {
                    tracing::warn!("Route handler error: {}", e);
                    break;
                }
                // If handler called fallback(), try the next matching handler
                if !route.was_handled() {
                    continue;
                }
                break;
            }
        }
    }

    /// Registers a download event handler.
    ///
    /// The handler will be called when a download is triggered by the page.
    /// Downloads occur when the page initiates a file download (e.g., clicking a link
    /// with the download attribute, or a server response with Content-Disposition: attachment).
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure that receives the Download object
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-download>
    pub async fn on_download<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(Download) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        // Wrap handler with type erasure
        let handler = Arc::new(move |download: Download| -> DownloadHandlerFuture {
            Box::pin(handler(download))
        });

        // Store handler
        self.download_handlers.lock().unwrap().push(handler);

        Ok(())
    }

    /// Registers a dialog event handler.
    ///
    /// The handler will be called when a JavaScript dialog is triggered (alert, confirm, prompt, or beforeunload).
    /// The dialog must be explicitly accepted or dismissed, otherwise the page will freeze.
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure that receives the Dialog object
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-dialog>
    pub async fn on_dialog<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(Dialog) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        // Wrap handler with type erasure
        let handler =
            Arc::new(move |dialog: Dialog| -> DialogHandlerFuture { Box::pin(handler(dialog)) });

        // Store handler
        self.dialog_handlers.lock().unwrap().push(handler);

        // Dialog events are auto-emitted (no subscription needed)

        Ok(())
    }

    /// Registers a console event handler.
    ///
    /// The handler is called whenever the page emits a JavaScript console message
    /// (e.g. `console.log`, `console.error`, `console.warn`, etc.).
    ///
    /// The server only sends console events after the first handler is registered
    /// (subscription is managed automatically).
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure that receives the [`ConsoleMessage`](crate::protocol::ConsoleMessage)
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-console>
    pub async fn on_console<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(crate::protocol::ConsoleMessage) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(
            move |msg: crate::protocol::ConsoleMessage| -> ConsoleHandlerFuture {
                Box::pin(handler(msg))
            },
        );

        let needs_subscription = {
            let handlers = self.console_handlers.lock().unwrap();
            let waiters = self.console_waiters.lock().unwrap();
            handlers.is_empty() && waiters.is_empty()
        };
        if needs_subscription {
            _ = self.channel().update_subscription("console", true).await;
        }
        self.console_handlers.lock().unwrap().push(handler);

        Ok(())
    }

    /// Registers a handler for file chooser events.
    ///
    /// The handler is called whenever the page opens a file chooser dialog
    /// (e.g. when the user clicks an `<input type="file">` element).
    ///
    /// Use [`FileChooser::set_files`](crate::protocol::FileChooser::set_files) inside
    /// the handler to satisfy the file chooser without OS-level interaction.
    ///
    /// The server only sends `"fileChooser"` events after the first handler is
    /// registered (subscription is managed automatically via `updateSubscription`).
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure that receives a [`FileChooser`](crate::protocol::FileChooser)
    ///
    /// # Example
    ///
    /// ```ignore
    /// page.on_filechooser(|chooser| async move {
    ///     chooser.set_files(&[std::path::PathBuf::from("/tmp/file.txt")]).await
    /// }).await?;
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-file-chooser>
    pub async fn on_filechooser<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(crate::protocol::FileChooser) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(
            move |chooser: crate::protocol::FileChooser| -> FileChooserHandlerFuture {
                Box::pin(handler(chooser))
            },
        );

        let needs_subscription = {
            let handlers = self.filechooser_handlers.lock().unwrap();
            let waiters = self.filechooser_waiters.lock().unwrap();
            handlers.is_empty() && waiters.is_empty()
        };
        if needs_subscription {
            _ = self
                .channel()
                .update_subscription("fileChooser", true)
                .await;
        }
        self.filechooser_handlers.lock().unwrap().push(handler);

        Ok(())
    }

    /// Creates a one-shot waiter that resolves when the next file chooser opens.
    ///
    /// The waiter **must** be created before the action that triggers the file
    /// chooser to avoid a race condition.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Timeout in milliseconds. Defaults to 30 000 ms if `None`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::Error::Timeout`] if the file chooser
    /// does not open within the timeout.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Set up waiter BEFORE triggering the file chooser
    /// let waiter = page.expect_file_chooser(None).await?;
    /// page.locator("input[type=file]").await.click(None).await?;
    /// let chooser = waiter.wait().await?;
    /// chooser.set_files(&[PathBuf::from("/tmp/file.txt")]).await?;
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-wait-for-event>
    pub async fn expect_file_chooser(
        &self,
        timeout: Option<f64>,
    ) -> Result<crate::protocol::EventWaiter<crate::protocol::FileChooser>> {
        let (tx, rx) = tokio::sync::oneshot::channel();

        let needs_subscription = {
            let handlers = self.filechooser_handlers.lock().unwrap();
            let waiters = self.filechooser_waiters.lock().unwrap();
            handlers.is_empty() && waiters.is_empty()
        };
        if needs_subscription {
            _ = self
                .channel()
                .update_subscription("fileChooser", true)
                .await;
        }
        self.filechooser_waiters.lock().unwrap().push(tx);

        Ok(crate::protocol::EventWaiter::new(
            rx,
            timeout.or(Some(30_000.0)),
        ))
    }

    /// Creates a one-shot waiter that resolves when the next popup window opens.
    ///
    /// The waiter **must** be created before the action that opens the popup to
    /// avoid a race condition.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Timeout in milliseconds. Defaults to 30 000 ms if `None`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::Error::Timeout`] if no popup
    /// opens within the timeout.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-wait-for-event>
    pub async fn expect_popup(
        &self,
        timeout: Option<f64>,
    ) -> Result<crate::protocol::EventWaiter<Page>> {
        let (tx, rx) = tokio::sync::oneshot::channel();
        self.popup_waiters.lock().unwrap().push(tx);
        Ok(crate::protocol::EventWaiter::new(
            rx,
            timeout.or(Some(30_000.0)),
        ))
    }

    /// Creates a one-shot waiter that resolves when the next download starts.
    ///
    /// The waiter **must** be created before the action that triggers the download
    /// to avoid a race condition.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Timeout in milliseconds. Defaults to 30 000 ms if `None`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::Error::Timeout`] if no download
    /// starts within the timeout.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-wait-for-event>
    pub async fn expect_download(
        &self,
        timeout: Option<f64>,
    ) -> Result<crate::protocol::EventWaiter<Download>> {
        let (tx, rx) = tokio::sync::oneshot::channel();
        self.download_waiters.lock().unwrap().push(tx);
        Ok(crate::protocol::EventWaiter::new(
            rx,
            timeout.or(Some(30_000.0)),
        ))
    }

    /// Creates a one-shot waiter that resolves when the next network response is received.
    ///
    /// The waiter **must** be created before the action that triggers the response
    /// to avoid a race condition.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Timeout in milliseconds. Defaults to 30 000 ms if `None`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::Error::Timeout`] if no response
    /// arrives within the timeout.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-wait-for-event>
    pub async fn expect_response(
        &self,
        timeout: Option<f64>,
    ) -> Result<crate::protocol::EventWaiter<ResponseObject>> {
        let (tx, rx) = tokio::sync::oneshot::channel();

        let needs_subscription = {
            let handlers = self.response_handlers.lock().unwrap();
            let waiters = self.response_waiters.lock().unwrap();
            handlers.is_empty() && waiters.is_empty()
        };
        if needs_subscription {
            _ = self.channel().update_subscription("response", true).await;
        }
        self.response_waiters.lock().unwrap().push(tx);

        Ok(crate::protocol::EventWaiter::new(
            rx,
            timeout.or(Some(30_000.0)),
        ))
    }

    /// Creates a one-shot waiter that resolves when the next network request is issued.
    ///
    /// The waiter **must** be created before the action that issues the request
    /// to avoid a race condition.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Timeout in milliseconds. Defaults to 30 000 ms if `None`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::Error::Timeout`] if no request
    /// is issued within the timeout.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-wait-for-event>
    pub async fn expect_request(
        &self,
        timeout: Option<f64>,
    ) -> Result<crate::protocol::EventWaiter<Request>> {
        let (tx, rx) = tokio::sync::oneshot::channel();

        let needs_subscription = {
            let handlers = self.request_handlers.lock().unwrap();
            let waiters = self.request_waiters.lock().unwrap();
            handlers.is_empty() && waiters.is_empty()
        };
        if needs_subscription {
            _ = self.channel().update_subscription("request", true).await;
        }
        self.request_waiters.lock().unwrap().push(tx);

        Ok(crate::protocol::EventWaiter::new(
            rx,
            timeout.or(Some(30_000.0)),
        ))
    }

    /// Creates a one-shot waiter that resolves when the next console message is produced.
    ///
    /// The waiter **must** be created before the action that produces the console
    /// message to avoid a race condition.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Timeout in milliseconds. Defaults to 30 000 ms if `None`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::Error::Timeout`] if no console
    /// message is produced within the timeout.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-wait-for-event>
    pub async fn expect_console_message(
        &self,
        timeout: Option<f64>,
    ) -> Result<crate::protocol::EventWaiter<crate::protocol::ConsoleMessage>> {
        let (tx, rx) = tokio::sync::oneshot::channel();

        let needs_subscription = {
            let handlers = self.console_handlers.lock().unwrap();
            let waiters = self.console_waiters.lock().unwrap();
            handlers.is_empty() && waiters.is_empty()
        };
        if needs_subscription {
            _ = self.channel().update_subscription("console", true).await;
        }
        self.console_waiters.lock().unwrap().push(tx);

        Ok(crate::protocol::EventWaiter::new(
            rx,
            timeout.or(Some(30_000.0)),
        ))
    }

    /// Waits for the given event to fire and returns a typed `EventValue`.
    ///
    /// This is the generic version of the specific `expect_*` methods. It matches
    /// the playwright-python / playwright-js `page.expect_event(event_name)` API.
    ///
    /// The waiter **must** be created before the action that triggers the event.
    ///
    /// # Supported event names
    ///
    /// `"request"`, `"response"`, `"popup"`, `"download"`, `"console"`,
    /// `"filechooser"`, `"close"`, `"load"`, `"crash"`, `"pageerror"`,
    /// `"frameattached"`, `"framedetached"`, `"framenavigated"`, `"worker"`
    ///
    /// # Arguments
    ///
    /// * `event` - Event name (case-sensitive, matches Playwright protocol names).
    /// * `timeout` - Timeout in milliseconds. Defaults to 30 000 ms if `None`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::Error::InvalidArgument`] for unknown event names.
    /// Returns [`crate::error::Error::Timeout`] if the event does not fire within the timeout.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-wait-for-event>
    pub async fn expect_event(
        &self,
        event: &str,
        timeout: Option<f64>,
    ) -> Result<crate::protocol::EventWaiter<crate::protocol::EventValue>> {
        use crate::protocol::EventValue;
        use tokio::sync::oneshot;

        let timeout_ms = timeout.or(Some(30_000.0));

        match event {
            "request" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<Request>();

                let needs_subscription = {
                    let handlers = self.request_handlers.lock().unwrap();
                    let waiters = self.request_waiters.lock().unwrap();
                    handlers.is_empty() && waiters.is_empty()
                };
                if needs_subscription {
                    _ = self.channel().update_subscription("request", true).await;
                }
                self.request_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if let Ok(v) = inner_rx.await {
                        let _ = tx.send(EventValue::Request(v));
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "response" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<ResponseObject>();

                let needs_subscription = {
                    let handlers = self.response_handlers.lock().unwrap();
                    let waiters = self.response_waiters.lock().unwrap();
                    handlers.is_empty() && waiters.is_empty()
                };
                if needs_subscription {
                    _ = self.channel().update_subscription("response", true).await;
                }
                self.response_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if let Ok(v) = inner_rx.await {
                        let _ = tx.send(EventValue::Response(v));
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "popup" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<Page>();
                self.popup_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if let Ok(v) = inner_rx.await {
                        let _ = tx.send(EventValue::Page(v));
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "download" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<crate::protocol::Download>();
                self.download_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if let Ok(v) = inner_rx.await {
                        let _ = tx.send(EventValue::Download(v));
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "console" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<crate::protocol::ConsoleMessage>();

                let needs_subscription = {
                    let handlers = self.console_handlers.lock().unwrap();
                    let waiters = self.console_waiters.lock().unwrap();
                    handlers.is_empty() && waiters.is_empty()
                };
                if needs_subscription {
                    _ = self.channel().update_subscription("console", true).await;
                }
                self.console_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if let Ok(v) = inner_rx.await {
                        let _ = tx.send(EventValue::ConsoleMessage(v));
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "filechooser" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<crate::protocol::FileChooser>();

                let needs_subscription = {
                    let handlers = self.filechooser_handlers.lock().unwrap();
                    let waiters = self.filechooser_waiters.lock().unwrap();
                    handlers.is_empty() && waiters.is_empty()
                };
                if needs_subscription {
                    _ = self
                        .channel()
                        .update_subscription("fileChooser", true)
                        .await;
                }
                self.filechooser_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if let Ok(v) = inner_rx.await {
                        let _ = tx.send(EventValue::FileChooser(v));
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "close" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<()>();
                self.close_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if inner_rx.await.is_ok() {
                        let _ = tx.send(EventValue::Close);
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "load" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<()>();
                self.load_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if inner_rx.await.is_ok() {
                        let _ = tx.send(EventValue::Load);
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "crash" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<()>();
                self.crash_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if inner_rx.await.is_ok() {
                        let _ = tx.send(EventValue::Crash);
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "pageerror" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<String>();
                self.pageerror_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if let Ok(msg) = inner_rx.await {
                        let _ = tx.send(EventValue::PageError(msg));
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "frameattached" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<crate::protocol::Frame>();
                self.frameattached_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if let Ok(v) = inner_rx.await {
                        let _ = tx.send(EventValue::Frame(v));
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "framedetached" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<crate::protocol::Frame>();
                self.framedetached_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if let Ok(v) = inner_rx.await {
                        let _ = tx.send(EventValue::Frame(v));
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "framenavigated" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<crate::protocol::Frame>();
                self.framenavigated_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if let Ok(v) = inner_rx.await {
                        let _ = tx.send(EventValue::Frame(v));
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            "worker" => {
                let (tx, rx) = oneshot::channel::<EventValue>();
                let (inner_tx, inner_rx) = oneshot::channel::<crate::protocol::Worker>();
                self.worker_waiters.lock().unwrap().push(inner_tx);

                tokio::spawn(async move {
                    if let Ok(v) = inner_rx.await {
                        let _ = tx.send(EventValue::Worker(v));
                    }
                });

                Ok(crate::protocol::EventWaiter::new(rx, timeout_ms))
            }

            other => Err(Error::InvalidArgument(format!(
                "Unknown event name '{}'. Supported: request, response, popup, download, \
                 console, filechooser, close, load, crash, pageerror, \
                 frameattached, framedetached, framenavigated, worker",
                other
            ))),
        }
    }

    /// See: <https://playwright.dev/docs/api/class-page#page-event-request>
    pub async fn on_request<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(move |request: Request| -> RequestHandlerFuture {
            Box::pin(handler(request))
        });

        let needs_subscription = {
            let handlers = self.request_handlers.lock().unwrap();
            let waiters = self.request_waiters.lock().unwrap();
            handlers.is_empty() && waiters.is_empty()
        };
        if needs_subscription {
            _ = self.channel().update_subscription("request", true).await;
        }
        self.request_handlers.lock().unwrap().push(handler);

        Ok(())
    }

    /// See: <https://playwright.dev/docs/api/class-page#page-event-request-finished>
    pub async fn on_request_finished<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(move |request: Request| -> RequestHandlerFuture {
            Box::pin(handler(request))
        });

        let needs_subscription = self.request_finished_handlers.lock().unwrap().is_empty();
        if needs_subscription {
            _ = self
                .channel()
                .update_subscription("requestFinished", true)
                .await;
        }
        self.request_finished_handlers.lock().unwrap().push(handler);

        Ok(())
    }

    /// See: <https://playwright.dev/docs/api/class-page#page-event-request-failed>
    pub async fn on_request_failed<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(move |request: Request| -> RequestHandlerFuture {
            Box::pin(handler(request))
        });

        let needs_subscription = self.request_failed_handlers.lock().unwrap().is_empty();
        if needs_subscription {
            _ = self
                .channel()
                .update_subscription("requestFailed", true)
                .await;
        }
        self.request_failed_handlers.lock().unwrap().push(handler);

        Ok(())
    }

    /// See: <https://playwright.dev/docs/api/class-page#page-event-response>
    pub async fn on_response<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(ResponseObject) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(move |response: ResponseObject| -> ResponseHandlerFuture {
            Box::pin(handler(response))
        });

        let needs_subscription = {
            let handlers = self.response_handlers.lock().unwrap();
            let waiters = self.response_waiters.lock().unwrap();
            handlers.is_empty() && waiters.is_empty()
        };
        if needs_subscription {
            _ = self.channel().update_subscription("response", true).await;
        }
        self.response_handlers.lock().unwrap().push(handler);

        Ok(())
    }

    /// Adds a listener for the `websocket` event.
    ///
    /// The handler will be called when a WebSocket request is dispatched.
    ///
    /// # Arguments
    ///
    /// * `handler` - The function to call when the event occurs
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-on-websocket>
    pub async fn on_websocket<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(WebSocket) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler =
            Arc::new(move |ws: WebSocket| -> WebSocketHandlerFuture { Box::pin(handler(ws)) });
        self.websocket_handlers.lock().unwrap().push(handler);
        Ok(())
    }

    /// Registers a handler for the `worker` event.
    ///
    /// The handler is called when a new Web Worker is created in the page.
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure called with the new [`Worker`] object
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-worker>
    pub async fn on_worker<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(Worker) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(move |w: Worker| -> WorkerHandlerFuture { Box::pin(handler(w)) });
        self.worker_handlers.lock().unwrap().push(handler);
        Ok(())
    }

    /// Registers a handler for the `close` event.
    ///
    /// The handler is called when the page is closed, either by calling `page.close()`,
    /// by the browser context being closed, or when the browser process exits.
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure called with no arguments when the page closes
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-close>
    pub async fn on_close<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(move || -> CloseHandlerFuture { Box::pin(handler()) });
        self.close_handlers.lock().unwrap().push(handler);
        Ok(())
    }

    /// Registers a handler for the `load` event.
    ///
    /// The handler is called when the page's `load` event fires, i.e. after
    /// all resources including stylesheets and images have finished loading.
    ///
    /// The server only sends `"load"` events after the first handler is registered
    /// (subscription is managed automatically).
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure called with no arguments when the page loads
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-load>
    pub async fn on_load<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(move || -> LoadHandlerFuture { Box::pin(handler()) });
        // "load" events come via Frame's "loadstate" event, no subscription needed.
        self.load_handlers.lock().unwrap().push(handler);
        Ok(())
    }

    /// Registers a handler for the `crash` event.
    ///
    /// The handler is called when the page crashes (e.g. runs out of memory).
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure called with no arguments when the page crashes
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-crash>
    pub async fn on_crash<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(move || -> CrashHandlerFuture { Box::pin(handler()) });
        self.crash_handlers.lock().unwrap().push(handler);
        Ok(())
    }

    /// Registers a handler for the `pageError` event.
    ///
    /// The handler is called when an uncaught JavaScript exception is thrown in the page.
    /// The handler receives the error message as a `String`.
    ///
    /// The server only sends `"pageError"` events after the first handler is registered
    /// (subscription is managed automatically).
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure that receives the error message string
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-page-error>
    pub async fn on_pageerror<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(String) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler =
            Arc::new(move |msg: String| -> PageErrorHandlerFuture { Box::pin(handler(msg)) });
        // "pageError" events come via BrowserContext, no subscription needed.
        self.pageerror_handlers.lock().unwrap().push(handler);
        Ok(())
    }

    /// Registers a handler for the `popup` event.
    ///
    /// The handler is called when the page opens a popup window (e.g. via `window.open()`).
    /// The handler receives the new popup [`Page`] object.
    ///
    /// The server only sends `"popup"` events after the first handler is registered
    /// (subscription is managed automatically).
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure that receives the popup Page
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-popup>
    pub async fn on_popup<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(Page) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(move |page: Page| -> PopupHandlerFuture { Box::pin(handler(page)) });
        // "popup" events arrive via BrowserContext's "page" event when a page has an opener.
        self.popup_handlers.lock().unwrap().push(handler);
        Ok(())
    }

    /// Registers a handler for the `frameAttached` event.
    ///
    /// The handler is called when a new frame (iframe) is attached to the page.
    /// The handler receives the attached [`Frame`](crate::protocol::Frame) object.
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure that receives the attached Frame
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-frameattached>
    pub async fn on_frameattached<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(crate::protocol::Frame) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(
            move |frame: crate::protocol::Frame| -> FrameEventHandlerFuture {
                Box::pin(handler(frame))
            },
        );
        self.frameattached_handlers.lock().unwrap().push(handler);
        Ok(())
    }

    /// Registers a handler for the `frameDetached` event.
    ///
    /// The handler is called when a frame (iframe) is detached from the page.
    /// The handler receives the detached [`Frame`](crate::protocol::Frame) object.
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure that receives the detached Frame
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-framedetached>
    pub async fn on_framedetached<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(crate::protocol::Frame) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(
            move |frame: crate::protocol::Frame| -> FrameEventHandlerFuture {
                Box::pin(handler(frame))
            },
        );
        self.framedetached_handlers.lock().unwrap().push(handler);
        Ok(())
    }

    /// Registers a handler for the `frameNavigated` event.
    ///
    /// The handler is called when a frame navigates to a new URL.
    /// The handler receives the navigated [`Frame`](crate::protocol::Frame) object.
    ///
    /// # Arguments
    ///
    /// * `handler` - Async closure that receives the navigated Frame
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-event-framenavigated>
    pub async fn on_framenavigated<F, Fut>(&self, handler: F) -> Result<()>
    where
        F: Fn(crate::protocol::Frame) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let handler = Arc::new(
            move |frame: crate::protocol::Frame| -> FrameEventHandlerFuture {
                Box::pin(handler(frame))
            },
        );
        self.framenavigated_handlers.lock().unwrap().push(handler);
        Ok(())
    }

    /// Exposes a Rust function to this page as `window[name]` in JavaScript.
    ///
    /// When JavaScript code calls `window[name](arg1, arg2, …)` the Playwright
    /// server fires a `bindingCall` event on the **page** channel that invokes
    /// `callback` with the deserialized arguments. The return value is sent back
    /// to JS so the `await window[name](…)` expression resolves with it.
    ///
    /// The binding is page-scoped and not visible to other pages in the same context.
    ///
    /// # Arguments
    ///
    /// * `name`     – JavaScript identifier that will be available as `window[name]`.
    /// * `callback` – Async closure called with `Vec<serde_json::Value>` (JS arguments)
    ///   returning `serde_json::Value` (the result).
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - The page has been closed.
    /// - Communication with the browser process fails.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-expose-function>
    pub async fn expose_function<F, Fut>(&self, name: &str, callback: F) -> Result<()>
    where
        F: Fn(Vec<serde_json::Value>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = serde_json::Value> + Send + 'static,
    {
        self.expose_binding_internal(name, false, callback).await
    }

    /// Exposes a Rust function to this page as `window[name]` in JavaScript,
    /// with `needsHandle: true`.
    ///
    /// Identical to [`expose_function`](Self::expose_function) but the Playwright
    /// server passes the first argument as a `JSHandle` object rather than a plain
    /// value.
    ///
    /// # Arguments
    ///
    /// * `name`     – JavaScript identifier.
    /// * `callback` – Async closure with `Vec<serde_json::Value>` → `serde_json::Value`.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - The page has been closed.
    /// - Communication with the browser process fails.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-expose-binding>
    pub async fn expose_binding<F, Fut>(&self, name: &str, callback: F) -> Result<()>
    where
        F: Fn(Vec<serde_json::Value>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = serde_json::Value> + Send + 'static,
    {
        self.expose_binding_internal(name, true, callback).await
    }

    /// Internal implementation shared by page-level expose_function and expose_binding.
    ///
    /// Both `expose_function` and `expose_binding` use `needsHandle: false` because
    /// the current implementation does not support JSHandle objects. Using
    /// `needsHandle: true` would cause the Playwright server to wrap the first
    /// argument as a `JSHandle`, which requires a JSHandle protocol object that
    /// is not yet implemented.
    async fn expose_binding_internal<F, Fut>(
        &self,
        name: &str,
        _needs_handle: bool,
        callback: F,
    ) -> Result<()>
    where
        F: Fn(Vec<serde_json::Value>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = serde_json::Value> + Send + 'static,
    {
        let callback: PageBindingCallback = Arc::new(move |args: Vec<serde_json::Value>| {
            Box::pin(callback(args)) as PageBindingCallbackFuture
        });

        // Store callback before sending RPC (avoids race with early bindingCall events)
        self.binding_callbacks
            .lock()
            .unwrap()
            .insert(name.to_string(), callback);

        // Tell the Playwright server to inject window[name] into this page.
        // Always use needsHandle: false — see note above.
        self.channel()
            .send_no_result(
                "exposeBinding",
                serde_json::json!({ "name": name, "needsHandle": false }),
            )
            .await
    }

    /// Handles a download event from the protocol
    async fn on_download_event(&self, download: Download) {
        let handlers = self.download_handlers.lock().unwrap().clone();

        for handler in handlers {
            if let Err(e) = handler(download.clone()).await {
                tracing::warn!("Download handler error: {}", e);
            }
        }
        // Notify the first expect_download() waiter (FIFO order)
        if let Some(tx) = self.download_waiters.lock().unwrap().pop() {
            let _ = tx.send(download);
        }
    }

    /// Handles a dialog event from the protocol
    async fn on_dialog_event(&self, dialog: Dialog) {
        let handlers = self.dialog_handlers.lock().unwrap().clone();

        for handler in handlers {
            if let Err(e) = handler(dialog.clone()).await {
                tracing::warn!("Dialog handler error: {}", e);
            }
        }
    }

    async fn on_request_event(&self, request: Request) {
        let handlers = self.request_handlers.lock().unwrap().clone();

        for handler in handlers {
            if let Err(e) = handler(request.clone()).await {
                tracing::warn!("Request handler error: {}", e);
            }
        }
        // Notify the first expect_request() waiter (FIFO order)
        if let Some(tx) = self.request_waiters.lock().unwrap().pop() {
            let _ = tx.send(request);
        }
    }

    async fn on_request_failed_event(&self, request: Request) {
        let handlers = self.request_failed_handlers.lock().unwrap().clone();

        for handler in handlers {
            if let Err(e) = handler(request.clone()).await {
                tracing::warn!("RequestFailed handler error: {}", e);
            }
        }
    }

    async fn on_request_finished_event(&self, request: Request) {
        let handlers = self.request_finished_handlers.lock().unwrap().clone();

        for handler in handlers {
            if let Err(e) = handler(request.clone()).await {
                tracing::warn!("RequestFinished handler error: {}", e);
            }
        }
    }

    async fn on_response_event(&self, response: ResponseObject) {
        let handlers = self.response_handlers.lock().unwrap().clone();

        for handler in handlers {
            if let Err(e) = handler(response.clone()).await {
                tracing::warn!("Response handler error: {}", e);
            }
        }
        // Notify the first expect_response() waiter (FIFO order)
        if let Some(tx) = self.response_waiters.lock().unwrap().pop() {
            let _ = tx.send(response);
        }
    }

    /// Registers a handler function that runs whenever a locator matches an element on the page.
    ///
    /// This is useful for handling overlays (cookie banners, modals, permission dialogs)
    /// that appear unexpectedly and need to be dismissed before test actions can proceed.
    ///
    /// When a matching element appears, Playwright sends a `locatorHandlerTriggered` event.
    /// The handler is called with the matching `Locator`. After the handler completes,
    /// Playwright is notified via `resolveLocatorHandler` so it can resume pending actions.
    ///
    /// # Arguments
    ///
    /// * `locator` - A locator identifying the overlay element to watch for
    /// * `handler` - Async function called with the matching Locator when the element appears
    /// * `options` - Optional settings (no_wait_after, times)
    ///
    /// # Errors
    ///
    /// Returns error if communication with the browser process fails.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-add-locator-handler>
    pub async fn add_locator_handler<F, Fut>(
        &self,
        locator: &crate::protocol::Locator,
        handler: F,
        options: Option<AddLocatorHandlerOptions>,
    ) -> Result<()>
    where
        F: Fn(crate::protocol::Locator) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let selector = locator.selector().to_string();
        let no_wait_after = options
            .as_ref()
            .and_then(|o| o.no_wait_after)
            .unwrap_or(false);
        let times = options.as_ref().and_then(|o| o.times);

        // Send registerLocatorHandler RPC — returns {"uid": N}
        let params = serde_json::json!({
            "selector": selector,
            "noWaitAfter": no_wait_after,
        });
        let result: Value = self
            .channel()
            .send("registerLocatorHandler", params)
            .await?;

        let uid = result
            .get("uid")
            .and_then(|v| v.as_u64())
            .map(|v| v as u32)
            .ok_or_else(|| {
                Error::ProtocolError("registerLocatorHandler response missing 'uid'".to_string())
            })?;

        let handler_fn: LocatorHandlerFn = Arc::new(
            move |loc: crate::protocol::Locator| -> LocatorHandlerFuture { Box::pin(handler(loc)) },
        );

        self.locator_handlers
            .lock()
            .unwrap()
            .push(LocatorHandlerEntry {
                uid,
                selector,
                handler: handler_fn,
                times_remaining: times,
            });

        Ok(())
    }

    /// Removes a previously registered locator handler.
    ///
    /// Sends `unregisterLocatorHandler` to the Playwright server using the uid
    /// that was assigned when the handler was first registered.
    ///
    /// # Arguments
    ///
    /// * `locator` - The same locator that was passed to `add_locator_handler`
    ///
    /// # Errors
    ///
    /// Returns error if no handler for this locator is registered, or if
    /// communication with the browser process fails.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-remove-locator-handler>
    pub async fn remove_locator_handler(&self, locator: &crate::protocol::Locator) -> Result<()> {
        let selector = locator.selector();

        // Find the uid for this selector
        let uid = {
            let handlers = self.locator_handlers.lock().unwrap();
            handlers
                .iter()
                .find(|e| e.selector == selector)
                .map(|e| e.uid)
        };

        let uid = uid.ok_or_else(|| {
            Error::ProtocolError(format!(
                "No locator handler registered for selector '{}'",
                selector
            ))
        })?;

        // Send unregisterLocatorHandler RPC
        self.channel()
            .send_no_result(
                "unregisterLocatorHandler",
                serde_json::json!({ "uid": uid }),
            )
            .await?;

        // Remove from local registry
        self.locator_handlers
            .lock()
            .unwrap()
            .retain(|e| e.uid != uid);

        Ok(())
    }

    /// Triggers dialog event (called by BrowserContext when dialog events arrive)
    ///
    /// Dialog events are sent to BrowserContext and forwarded to the associated Page.
    /// This method is public so BrowserContext can forward dialog events.
    pub async fn trigger_dialog_event(&self, dialog: Dialog) {
        self.on_dialog_event(dialog).await;
    }

    /// Triggers request event (called by BrowserContext when request events arrive)
    pub(crate) async fn trigger_request_event(&self, request: Request) {
        self.on_request_event(request).await;
    }

    pub(crate) async fn trigger_request_finished_event(&self, request: Request) {
        self.on_request_finished_event(request).await;
    }

    pub(crate) async fn trigger_request_failed_event(&self, request: Request) {
        self.on_request_failed_event(request).await;
    }

    /// Triggers response event (called by BrowserContext when response events arrive)
    pub(crate) async fn trigger_response_event(&self, response: ResponseObject) {
        self.on_response_event(response).await;
    }

    /// Triggers console event (called by BrowserContext when console events arrive).
    ///
    /// The BrowserContext receives all `"console"` events, constructs the
    /// [`ConsoleMessage`](crate::protocol::ConsoleMessage), dispatches to
    /// context-level handlers, then calls this method to forward to page-level handlers.
    pub(crate) async fn trigger_console_event(&self, msg: crate::protocol::ConsoleMessage) {
        self.on_console_event(msg).await;
    }

    async fn on_console_event(&self, msg: crate::protocol::ConsoleMessage) {
        // Accumulate message for console_messages() accessor
        self.console_messages_log.lock().unwrap().push(msg.clone());
        // Notify the first expect_console_message() waiter (FIFO order)
        if let Some(tx) = self.console_waiters.lock().unwrap().pop() {
            let _ = tx.send(msg.clone());
        }
        let handlers = self.console_handlers.lock().unwrap().clone();
        for handler in handlers {
            if let Err(e) = handler(msg.clone()).await {
                tracing::warn!("Console handler error: {}", e);
            }
        }
    }

    /// Dispatches a FileChooser event to registered handlers and one-shot waiters.
    async fn on_filechooser_event(&self, chooser: crate::protocol::FileChooser) {
        // Dispatch to persistent handlers
        let handlers = self.filechooser_handlers.lock().unwrap().clone();
        for handler in handlers {
            if let Err(e) = handler(chooser.clone()).await {
                tracing::warn!("FileChooser handler error: {}", e);
            }
        }

        // Notify the first expect_file_chooser() waiter (FIFO order)
        if let Some(tx) = self.filechooser_waiters.lock().unwrap().pop() {
            let _ = tx.send(chooser);
        }
    }

    /// Triggers load event (called by Frame when loadstate "load" is added)
    pub(crate) async fn trigger_load_event(&self) {
        self.on_load_event().await;
    }

    /// Triggers pageError event (called by BrowserContext when pageError arrives)
    pub(crate) async fn trigger_pageerror_event(&self, message: String) {
        self.on_pageerror_event(message).await;
    }

    /// Triggers popup event (called by BrowserContext when a page is opened with an opener)
    pub(crate) async fn trigger_popup_event(&self, popup: Page) {
        self.on_popup_event(popup).await;
    }

    /// Triggers frameNavigated event (called by Frame when "navigated" is received)
    pub(crate) async fn trigger_framenavigated_event(&self, frame: crate::protocol::Frame) {
        self.on_framenavigated_event(frame).await;
    }

    async fn on_close_event(&self) {
        let handlers = self.close_handlers.lock().unwrap().clone();
        for handler in handlers {
            if let Err(e) = handler().await {
                tracing::warn!("Close handler error: {}", e);
            }
        }
        // Notify expect_event("close") waiters
        let waiters: Vec<_> = self.close_waiters.lock().unwrap().drain(..).collect();
        for tx in waiters {
            let _ = tx.send(());
        }
    }

    async fn on_load_event(&self) {
        let handlers = self.load_handlers.lock().unwrap().clone();
        for handler in handlers {
            if let Err(e) = handler().await {
                tracing::warn!("Load handler error: {}", e);
            }
        }
        // Notify expect_event("load") waiters
        let waiters: Vec<_> = self.load_waiters.lock().unwrap().drain(..).collect();
        for tx in waiters {
            let _ = tx.send(());
        }
    }

    async fn on_crash_event(&self) {
        let handlers = self.crash_handlers.lock().unwrap().clone();
        for handler in handlers {
            if let Err(e) = handler().await {
                tracing::warn!("Crash handler error: {}", e);
            }
        }
        // Notify expect_event("crash") waiters
        let waiters: Vec<_> = self.crash_waiters.lock().unwrap().drain(..).collect();
        for tx in waiters {
            let _ = tx.send(());
        }
    }

    async fn on_pageerror_event(&self, message: String) {
        // Accumulate error for page_errors() accessor
        self.page_errors_log.lock().unwrap().push(message.clone());
        let handlers = self.pageerror_handlers.lock().unwrap().clone();
        for handler in handlers {
            if let Err(e) = handler(message.clone()).await {
                tracing::warn!("PageError handler error: {}", e);
            }
        }
        // Notify expect_event("pageerror") waiters
        if let Some(tx) = self.pageerror_waiters.lock().unwrap().pop() {
            let _ = tx.send(message);
        }
    }

    async fn on_popup_event(&self, popup: Page) {
        let handlers = self.popup_handlers.lock().unwrap().clone();
        for handler in handlers {
            if let Err(e) = handler(popup.clone()).await {
                tracing::warn!("Popup handler error: {}", e);
            }
        }
        // Notify the first expect_popup() waiter (FIFO order)
        if let Some(tx) = self.popup_waiters.lock().unwrap().pop() {
            let _ = tx.send(popup);
        }
    }

    async fn on_frameattached_event(&self, frame: crate::protocol::Frame) {
        let handlers = self.frameattached_handlers.lock().unwrap().clone();
        for handler in handlers {
            if let Err(e) = handler(frame.clone()).await {
                tracing::warn!("FrameAttached handler error: {}", e);
            }
        }
        if let Some(tx) = self.frameattached_waiters.lock().unwrap().pop() {
            let _ = tx.send(frame);
        }
    }

    async fn on_framedetached_event(&self, frame: crate::protocol::Frame) {
        let handlers = self.framedetached_handlers.lock().unwrap().clone();
        for handler in handlers {
            if let Err(e) = handler(frame.clone()).await {
                tracing::warn!("FrameDetached handler error: {}", e);
            }
        }
        if let Some(tx) = self.framedetached_waiters.lock().unwrap().pop() {
            let _ = tx.send(frame);
        }
    }

    async fn on_framenavigated_event(&self, frame: crate::protocol::Frame) {
        let handlers = self.framenavigated_handlers.lock().unwrap().clone();
        for handler in handlers {
            if let Err(e) = handler(frame.clone()).await {
                tracing::warn!("FrameNavigated handler error: {}", e);
            }
        }
        if let Some(tx) = self.framenavigated_waiters.lock().unwrap().pop() {
            let _ = tx.send(frame);
        }
    }

    /// Adds a `<style>` tag into the page with the desired content.
    ///
    /// # Arguments
    ///
    /// * `options` - Style tag options (content, url, or path)
    ///
    /// # Returns
    ///
    /// Returns an ElementHandle pointing to the injected `<style>` tag
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use playwright_rs::protocol::{Playwright, AddStyleTagOptions};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let playwright = Playwright::launch().await?;
    /// # let browser = playwright.chromium().launch().await?;
    /// # let context = browser.new_context().await?;
    /// # let page = context.new_page().await?;
    /// use playwright_rs::protocol::AddStyleTagOptions;
    ///
    /// // With inline CSS
    /// page.add_style_tag(
    ///     AddStyleTagOptions::builder()
    ///         .content("body { background-color: red; }")
    ///         .build()
    /// ).await?;
    ///
    /// // With external URL
    /// page.add_style_tag(
    ///     AddStyleTagOptions::builder()
    ///         .url("https://example.com/style.css")
    ///         .build()
    /// ).await?;
    ///
    /// // From file
    /// page.add_style_tag(
    ///     AddStyleTagOptions::builder()
    ///         .path("./styles/custom.css")
    ///         .build()
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-add-style-tag>
    pub async fn add_style_tag(
        &self,
        options: AddStyleTagOptions,
    ) -> Result<Arc<crate::protocol::ElementHandle>> {
        let frame = self.main_frame().await?;
        frame.add_style_tag(options).await
    }

    /// Adds a script which would be evaluated in one of the following scenarios:
    /// - Whenever the page is navigated
    /// - Whenever a child frame is attached or navigated
    ///
    /// The script is evaluated after the document was created but before any of its scripts were run.
    ///
    /// # Arguments
    ///
    /// * `script` - JavaScript code to be injected into the page
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use playwright_rs::protocol::Playwright;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let playwright = Playwright::launch().await?;
    /// # let browser = playwright.chromium().launch().await?;
    /// # let context = browser.new_context().await?;
    /// # let page = context.new_page().await?;
    /// page.add_init_script("window.injected = 123;").await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-add-init-script>
    pub async fn add_init_script(&self, script: &str) -> Result<()> {
        self.channel()
            .send_no_result("addInitScript", serde_json::json!({ "source": script }))
            .await
    }

    /// Sets the viewport size for the page.
    ///
    /// This method allows dynamic resizing of the viewport after page creation,
    /// useful for testing responsive layouts at different screen sizes.
    ///
    /// # Arguments
    ///
    /// * `viewport` - The viewport dimensions (width and height in pixels)
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use playwright_rs::protocol::{Playwright, Viewport};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let playwright = Playwright::launch().await?;
    /// # let browser = playwright.chromium().launch().await?;
    /// # let page = browser.new_page().await?;
    /// // Set viewport to mobile size
    /// let mobile = Viewport {
    ///     width: 375,
    ///     height: 667,
    /// };
    /// page.set_viewport_size(mobile).await?;
    ///
    /// // Later, test desktop layout
    /// let desktop = Viewport {
    ///     width: 1920,
    ///     height: 1080,
    /// };
    /// page.set_viewport_size(desktop).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Page has been closed
    /// - Communication with browser process fails
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-set-viewport-size>
    pub async fn set_viewport_size(&self, viewport: crate::protocol::Viewport) -> Result<()> {
        // Store the new viewport locally so viewport_size() can reflect the change
        if let Ok(mut guard) = self.viewport.write() {
            *guard = Some(viewport.clone());
        }
        self.channel()
            .send_no_result(
                "setViewportSize",
                serde_json::json!({ "viewportSize": viewport }),
            )
            .await
    }

    /// Brings this page to the front (activates the tab).
    ///
    /// Activates the page in the browser, making it the focused tab. This is
    /// useful in multi-page tests to ensure actions target the correct page.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Page has been closed
    /// - Communication with browser process fails
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-bring-to-front>
    pub async fn bring_to_front(&self) -> Result<()> {
        self.channel()
            .send_no_result("bringToFront", serde_json::json!({}))
            .await
    }

    /// Forces garbage collection in the browser (Chromium only).
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-request-gc>
    pub async fn request_gc(&self) -> Result<()> {
        self.channel()
            .send_no_result("requestGC", serde_json::json!({}))
            .await
    }

    /// Sets extra HTTP headers that will be sent with every request from this page.
    ///
    /// These headers are sent in addition to headers set on the browser context via
    /// `BrowserContext::set_extra_http_headers()`. Page-level headers take precedence
    /// over context-level headers when names conflict.
    ///
    /// # Arguments
    ///
    /// * `headers` - Map of header names to values.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Page has been closed
    /// - Communication with browser process fails
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-set-extra-http-headers>
    pub async fn set_extra_http_headers(
        &self,
        headers: std::collections::HashMap<String, String>,
    ) -> Result<()> {
        // Playwright protocol expects an array of {name, value} objects
        // This RPC is sent on the Page channel (not the Frame channel)
        let headers_array: Vec<serde_json::Value> = headers
            .into_iter()
            .map(|(name, value)| serde_json::json!({ "name": name, "value": value }))
            .collect();
        self.channel()
            .send_no_result(
                "setExtraHTTPHeaders",
                serde_json::json!({ "headers": headers_array }),
            )
            .await
    }

    /// Emulates media features for the page.
    ///
    /// This method allows emulating CSS media features such as `media`, `color-scheme`,
    /// `reduced-motion`, and `forced-colors`. Pass `None` to call with no changes.
    ///
    /// To reset a specific feature to the browser default, use the `NoOverride` variant.
    ///
    /// # Arguments
    ///
    /// * `options` - Optional emulation options. If `None`, this is a no-op.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use playwright_rs::protocol::{Playwright, EmulateMediaOptions, Media, ColorScheme};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let playwright = Playwright::launch().await?;
    /// # let browser = playwright.chromium().launch().await?;
    /// # let page = browser.new_page().await?;
    /// // Emulate print media
    /// page.emulate_media(Some(
    ///     EmulateMediaOptions::builder()
    ///         .media(Media::Print)
    ///         .build()
    /// )).await?;
    ///
    /// // Emulate dark color scheme
    /// page.emulate_media(Some(
    ///     EmulateMediaOptions::builder()
    ///         .color_scheme(ColorScheme::Dark)
    ///         .build()
    /// )).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Page has been closed
    /// - Communication with browser process fails
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-emulate-media>
    pub async fn emulate_media(&self, options: Option<EmulateMediaOptions>) -> Result<()> {
        let mut params = serde_json::json!({});

        if let Some(opts) = options {
            if let Some(media) = opts.media {
                params["media"] = serde_json::to_value(media).map_err(|e| {
                    crate::error::Error::ProtocolError(format!("Failed to serialize media: {}", e))
                })?;
            }
            if let Some(color_scheme) = opts.color_scheme {
                params["colorScheme"] = serde_json::to_value(color_scheme).map_err(|e| {
                    crate::error::Error::ProtocolError(format!(
                        "Failed to serialize colorScheme: {}",
                        e
                    ))
                })?;
            }
            if let Some(reduced_motion) = opts.reduced_motion {
                params["reducedMotion"] = serde_json::to_value(reduced_motion).map_err(|e| {
                    crate::error::Error::ProtocolError(format!(
                        "Failed to serialize reducedMotion: {}",
                        e
                    ))
                })?;
            }
            if let Some(forced_colors) = opts.forced_colors {
                params["forcedColors"] = serde_json::to_value(forced_colors).map_err(|e| {
                    crate::error::Error::ProtocolError(format!(
                        "Failed to serialize forcedColors: {}",
                        e
                    ))
                })?;
            }
        }

        self.channel().send_no_result("emulateMedia", params).await
    }

    /// Generates a PDF of the page and returns it as bytes.
    ///
    /// Note: Generating a PDF is only supported in Chromium headless. PDF generation is
    /// not supported in Firefox or WebKit.
    ///
    /// The PDF bytes are returned. If `options.path` is set, the PDF will also be
    /// saved to that file.
    ///
    /// # Arguments
    ///
    /// * `options` - Optional PDF generation options
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use playwright_rs::protocol::Playwright;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let playwright = Playwright::launch().await?;
    /// # let browser = playwright.chromium().launch().await?;
    /// # let page = browser.new_page().await?;
    /// let pdf_bytes = page.pdf(None).await?;
    /// assert!(!pdf_bytes.is_empty());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - The browser is not Chromium (PDF only supported in Chromium)
    /// - Page has been closed
    /// - Communication with browser process fails
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-pdf>
    pub async fn pdf(&self, options: Option<PdfOptions>) -> Result<Vec<u8>> {
        let mut params = serde_json::json!({});
        let mut save_path: Option<std::path::PathBuf> = None;

        if let Some(opts) = options {
            // Capture the file path before consuming opts
            save_path = opts.path;

            if let Some(scale) = opts.scale {
                params["scale"] = serde_json::json!(scale);
            }
            if let Some(v) = opts.display_header_footer {
                params["displayHeaderFooter"] = serde_json::json!(v);
            }
            if let Some(v) = opts.header_template {
                params["headerTemplate"] = serde_json::json!(v);
            }
            if let Some(v) = opts.footer_template {
                params["footerTemplate"] = serde_json::json!(v);
            }
            if let Some(v) = opts.print_background {
                params["printBackground"] = serde_json::json!(v);
            }
            if let Some(v) = opts.landscape {
                params["landscape"] = serde_json::json!(v);
            }
            if let Some(v) = opts.page_ranges {
                params["pageRanges"] = serde_json::json!(v);
            }
            if let Some(v) = opts.format {
                params["format"] = serde_json::json!(v);
            }
            if let Some(v) = opts.width {
                params["width"] = serde_json::json!(v);
            }
            if let Some(v) = opts.height {
                params["height"] = serde_json::json!(v);
            }
            if let Some(v) = opts.prefer_css_page_size {
                params["preferCSSPageSize"] = serde_json::json!(v);
            }
            if let Some(margin) = opts.margin {
                params["margin"] = serde_json::to_value(margin).map_err(|e| {
                    crate::error::Error::ProtocolError(format!("Failed to serialize margin: {}", e))
                })?;
            }
        }

        #[derive(Deserialize)]
        struct PdfResponse {
            pdf: String,
        }

        let response: PdfResponse = self.channel().send("pdf", params).await?;

        // Decode base64 to bytes
        let pdf_bytes = base64::engine::general_purpose::STANDARD
            .decode(&response.pdf)
            .map_err(|e| {
                crate::error::Error::ProtocolError(format!("Failed to decode PDF base64: {}", e))
            })?;

        // If a path was specified, save the PDF to disk as well
        if let Some(path) = save_path {
            tokio::fs::write(&path, &pdf_bytes).await.map_err(|e| {
                crate::error::Error::InvalidArgument(format!(
                    "Failed to write PDF to '{}': {}",
                    path.display(),
                    e
                ))
            })?;
        }

        Ok(pdf_bytes)
    }

    /// Adds a `<script>` tag into the page with the desired URL or content.
    ///
    /// # Arguments
    ///
    /// * `options` - Optional script tag options (content, url, or path).
    ///   If `None`, returns an error because no source is specified.
    ///
    /// At least one of `content`, `url`, or `path` must be provided.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use playwright_rs::protocol::{Playwright, AddScriptTagOptions};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let playwright = Playwright::launch().await?;
    /// # let browser = playwright.chromium().launch().await?;
    /// # let context = browser.new_context().await?;
    /// # let page = context.new_page().await?;
    /// // With inline JavaScript
    /// page.add_script_tag(Some(
    ///     AddScriptTagOptions::builder()
    ///         .content("window.myVar = 42;")
    ///         .build()
    /// )).await?;
    ///
    /// // With external URL
    /// page.add_script_tag(Some(
    ///     AddScriptTagOptions::builder()
    ///         .url("https://example.com/script.js")
    ///         .build()
    /// )).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - `options` is `None` or no content/url/path is specified
    /// - Page has been closed
    /// - Script loading fails (e.g., invalid URL)
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-add-script-tag>
    pub async fn add_script_tag(
        &self,
        options: Option<AddScriptTagOptions>,
    ) -> Result<Arc<crate::protocol::ElementHandle>> {
        let opts = options.ok_or_else(|| {
            Error::InvalidArgument(
                "At least one of content, url, or path must be specified".to_string(),
            )
        })?;
        let frame = self.main_frame().await?;
        frame.add_script_tag(opts).await
    }

    /// Returns the current viewport size of the page, or `None` if no viewport is set.
    ///
    /// Returns `None` when the context was created with `no_viewport: true`. Otherwise
    /// returns the dimensions configured at context creation time or updated via
    /// `set_viewport_size()`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use playwright_rs::protocol::{Playwright, BrowserContextOptions, Viewport};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let playwright = Playwright::launch().await?;
    /// # let browser = playwright.chromium().launch().await?;
    /// let context = browser.new_context_with_options(
    ///     BrowserContextOptions::builder().viewport(Viewport { width: 1280, height: 720 }).build()
    /// ).await?;
    /// let page = context.new_page().await?;
    /// let size = page.viewport_size().expect("Viewport should be set");
    /// assert_eq!(size.width, 1280);
    /// assert_eq!(size.height, 720);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-viewport-size>
    pub fn viewport_size(&self) -> Option<Viewport> {
        self.viewport.read().ok()?.clone()
    }

    /// Returns the `Accessibility` object for this page.
    ///
    /// Use `accessibility().snapshot()` to capture the current state of the
    /// page's accessibility tree.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-accessibility>
    pub fn accessibility(&self) -> crate::protocol::Accessibility {
        crate::protocol::Accessibility::new(self.clone())
    }

    /// Returns the `Coverage` object for this page (Chromium only).
    ///
    /// Use `coverage().start_js_coverage()` / `stop_js_coverage()` and
    /// `start_css_coverage()` / `stop_css_coverage()` to collect code coverage data.
    ///
    /// Coverage is only available in Chromium. Calling coverage methods on
    /// Firefox or WebKit will return an error from the Playwright server.
    ///
    /// See: <https://playwright.dev/docs/api/class-page#page-coverage>
    pub fn coverage(&self) -> crate::protocol::Coverage {
        crate::protocol::Coverage::new(self.clone())
    }

    // Internal accessibility method (called by Accessibility struct)
    //
    // The legacy `accessibilitySnapshot` RPC was removed in modern Playwright.
    // We implement snapshot() using `FrameAriaSnapshot` on the main frame, which
    // returns the ARIA accessibility tree as a YAML string (the current equivalent).
    // The YAML string is returned as a JSON string Value for API compatibility.

    pub(crate) async fn accessibility_snapshot(
        &self,
        _options: Option<crate::protocol::accessibility::AccessibilitySnapshotOptions>,
    ) -> Result<serde_json::Value> {
        let frame = self.main_frame().await?;
        let timeout = self.default_timeout_ms();
        let snapshot = frame.aria_snapshot_raw("body", timeout).await?;
        Ok(serde_json::Value::String(snapshot))
    }

    // Internal coverage methods (called by Coverage struct)

    pub(crate) async fn coverage_start_js(
        &self,
        options: Option<crate::protocol::coverage::StartJSCoverageOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({});

        if let Some(opts) = options {
            if let Some(v) = opts.reset_on_navigation {
                params["resetOnNavigation"] = serde_json::json!(v);
            }
            if let Some(v) = opts.report_anonymous_scripts {
                params["reportAnonymousScripts"] = serde_json::json!(v);
            }
        }

        self.channel()
            .send_no_result("startJSCoverage", params)
            .await
    }

    pub(crate) async fn coverage_stop_js(
        &self,
    ) -> Result<Vec<crate::protocol::coverage::JSCoverageEntry>> {
        #[derive(serde::Deserialize)]
        struct StopJSCoverageResponse {
            entries: Vec<crate::protocol::coverage::JSCoverageEntry>,
        }

        let response: StopJSCoverageResponse = self
            .channel()
            .send("stopJSCoverage", serde_json::json!({}))
            .await?;

        Ok(response.entries)
    }

    pub(crate) async fn coverage_start_css(
        &self,
        options: Option<crate::protocol::coverage::StartCSSCoverageOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({});

        if let Some(opts) = options
            && let Some(v) = opts.reset_on_navigation
        {
            params["resetOnNavigation"] = serde_json::json!(v);
        }

        self.channel()
            .send_no_result("startCSSCoverage", params)
            .await
    }

    pub(crate) async fn coverage_stop_css(
        &self,
    ) -> Result<Vec<crate::protocol::coverage::CSSCoverageEntry>> {
        #[derive(serde::Deserialize)]
        struct StopCSSCoverageResponse {
            entries: Vec<crate::protocol::coverage::CSSCoverageEntry>,
        }

        let response: StopCSSCoverageResponse = self
            .channel()
            .send("stopCSSCoverage", serde_json::json!({}))
            .await?;

        Ok(response.entries)
    }
}

impl ChannelOwner for Page {
    fn guid(&self) -> &str {
        self.base.guid()
    }

    fn type_name(&self) -> &str {
        self.base.type_name()
    }

    fn parent(&self) -> Option<Arc<dyn ChannelOwner>> {
        self.base.parent()
    }

    fn connection(&self) -> Arc<dyn crate::server::connection::ConnectionLike> {
        self.base.connection()
    }

    fn initializer(&self) -> &Value {
        self.base.initializer()
    }

    fn channel(&self) -> &Channel {
        self.base.channel()
    }

    fn dispose(&self, reason: crate::server::channel_owner::DisposeReason) {
        self.base.dispose(reason)
    }

    fn adopt(&self, child: Arc<dyn ChannelOwner>) {
        self.base.adopt(child)
    }

    fn add_child(&self, guid: Arc<str>, child: Arc<dyn ChannelOwner>) {
        self.base.add_child(guid, child)
    }

    fn remove_child(&self, guid: &str) {
        self.base.remove_child(guid)
    }

    fn on_event(&self, method: &str, params: Value) {
        match method {
            "navigated" => {
                // Update URL when page navigates
                if let Some(url_value) = params.get("url")
                    && let Some(url_str) = url_value.as_str()
                    && let Ok(mut url) = self.url.write()
                {
                    *url = url_str.to_string();
                }
            }
            "route" => {
                // Handle network routing event
                if let Some(route_guid) = params
                    .get("route")
                    .and_then(|v| v.get("guid"))
                    .and_then(|v| v.as_str())
                {
                    // Get the Route object from connection's registry
                    let connection = self.connection();
                    let route_guid_owned = route_guid.to_string();
                    let self_clone = self.clone();

                    tokio::spawn(async move {
                        // Get and downcast Route object
                        let route: Route =
                            match connection.get_typed::<Route>(&route_guid_owned).await {
                                Ok(r) => r,
                                Err(e) => {
                                    tracing::warn!("Failed to get route object: {}", e);
                                    return;
                                }
                            };

                        // Set APIRequestContext on the route for fetch() support.
                        // Page's parent is BrowserContext, which has the request context.
                        if let Some(ctx) =
                            downcast_parent::<crate::protocol::BrowserContext>(&self_clone)
                            && let Ok(api_ctx) = ctx.request().await
                        {
                            route.set_api_request_context(api_ctx);
                        }

                        // Call the route handler and wait for completion
                        self_clone.on_route_event(route).await;
                    });
                }
            }
            "download" => {
                // Handle download event
                // Event params: {url, suggestedFilename, artifact: {guid: "..."}}
                let url = params
                    .get("url")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();

                let suggested_filename = params
                    .get("suggestedFilename")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();

                if let Some(artifact_guid) = params
                    .get("artifact")
                    .and_then(|v| v.get("guid"))
                    .and_then(|v| v.as_str())
                {
                    let connection = self.connection();
                    let artifact_guid_owned = artifact_guid.to_string();
                    let self_clone = self.clone();

                    tokio::spawn(async move {
                        // Wait for Artifact object to be created
                        let artifact_arc = match connection.get_object(&artifact_guid_owned).await {
                            Ok(obj) => obj,
                            Err(e) => {
                                tracing::warn!("Failed to get artifact object: {}", e);
                                return;
                            }
                        };

                        // Create Download wrapper from Artifact + event params
                        let download = Download::from_artifact(
                            artifact_arc,
                            url,
                            suggested_filename,
                            self_clone.clone(),
                        );

                        // Call the download handlers
                        self_clone.on_download_event(download).await;
                    });
                }
            }
            "dialog" => {
                // Dialog events are handled by BrowserContext and forwarded to Page
                // This case should not be reached, but keeping for completeness
            }
            "webSocket" => {
                if let Some(ws_guid) = params
                    .get("webSocket")
                    .and_then(|v| v.get("guid"))
                    .and_then(|v| v.as_str())
                {
                    let connection = self.connection();
                    let ws_guid_owned = ws_guid.to_string();
                    let self_clone = self.clone();

                    tokio::spawn(async move {
                        // Get and downcast WebSocket object
                        let ws: WebSocket =
                            match connection.get_typed::<WebSocket>(&ws_guid_owned).await {
                                Ok(ws) => ws,
                                Err(e) => {
                                    tracing::warn!("Failed to get WebSocket object: {}", e);
                                    return;
                                }
                            };

                        // Call handlers
                        let handlers = self_clone.websocket_handlers.lock().unwrap().clone();
                        for handler in handlers {
                            let ws_clone = ws.clone();
                            tokio::spawn(async move {
                                if let Err(e) = handler(ws_clone).await {
                                    tracing::error!("Error in websocket handler: {}", e);
                                }
                            });
                        }
                    });
                }
            }
            "webSocketRoute" => {
                // A WebSocket matched a route_web_socket pattern.
                // Event format: {webSocketRoute: {guid: "WebSocketRoute@..."}}
                if let Some(wsr_guid) = params
                    .get("webSocketRoute")
                    .and_then(|v| v.get("guid"))
                    .and_then(|v| v.as_str())
                {
                    let connection = self.connection();
                    let wsr_guid_owned = wsr_guid.to_string();
                    let self_clone = self.clone();

                    tokio::spawn(async move {
                        let route: crate::protocol::WebSocketRoute = match connection
                            .get_typed::<crate::protocol::WebSocketRoute>(&wsr_guid_owned)
                            .await
                        {
                            Ok(r) => r,
                            Err(e) => {
                                tracing::warn!("Failed to get WebSocketRoute object: {}", e);
                                return;
                            }
                        };

                        let url = route.url().to_string();
                        let handlers = self_clone.ws_route_handlers.lock().unwrap().clone();
                        for entry in handlers.iter().rev() {
                            if crate::protocol::route::matches_pattern(&entry.pattern, &url) {
                                let handler = entry.handler.clone();
                                let route_clone = route.clone();
                                tokio::spawn(async move {
                                    if let Err(e) = handler(route_clone).await {
                                        tracing::error!("Error in webSocketRoute handler: {}", e);
                                    }
                                });
                                break;
                            }
                        }
                    });
                }
            }
            "worker" => {
                // A new Web Worker was created in the page.
                // Event format: {worker: {guid: "Worker@..."}}
                if let Some(worker_guid) = params
                    .get("worker")
                    .and_then(|v| v.get("guid"))
                    .and_then(|v| v.as_str())
                {
                    let connection = self.connection();
                    let worker_guid_owned = worker_guid.to_string();
                    let self_clone = self.clone();

                    tokio::spawn(async move {
                        let worker: Worker =
                            match connection.get_typed::<Worker>(&worker_guid_owned).await {
                                Ok(w) => w,
                                Err(e) => {
                                    tracing::warn!("Failed to get Worker object: {}", e);
                                    return;
                                }
                            };

                        // Track the worker for workers() accessor
                        self_clone.workers_list.lock().unwrap().push(worker.clone());

                        let handlers = self_clone.worker_handlers.lock().unwrap().clone();
                        for handler in handlers {
                            let worker_clone = worker.clone();
                            tokio::spawn(async move {
                                if let Err(e) = handler(worker_clone).await {
                                    tracing::error!("Error in worker handler: {}", e);
                                }
                            });
                        }
                        // Notify expect_event("worker") waiters
                        if let Some(tx) = self_clone.worker_waiters.lock().unwrap().pop() {
                            let _ = tx.send(worker);
                        }
                    });
                }
            }
            "bindingCall" => {
                // A JS caller on this page invoked a page-level exposed function.
                // Event format: {binding: {guid: "..."}}
                if let Some(binding_guid) = params
                    .get("binding")
                    .and_then(|v| v.get("guid"))
                    .and_then(|v| v.as_str())
                {
                    let connection = self.connection();
                    let binding_guid_owned = binding_guid.to_string();
                    let binding_callbacks = self.binding_callbacks.clone();

                    tokio::spawn(async move {
                        let binding_call: crate::protocol::BindingCall = match connection
                            .get_typed::<crate::protocol::BindingCall>(&binding_guid_owned)
                            .await
                        {
                            Ok(bc) => bc,
                            Err(e) => {
                                tracing::warn!("Failed to get BindingCall object: {}", e);
                                return;
                            }
                        };

                        let name = binding_call.name().to_string();

                        // Look up page-level callback
                        let callback = {
                            let callbacks = binding_callbacks.lock().unwrap();
                            callbacks.get(&name).cloned()
                        };

                        let Some(callback) = callback else {
                            // No page-level handler — the context-level handler on
                            // BrowserContext::on_event("bindingCall") will handle it.
                            return;
                        };

                        // Deserialize args from Playwright protocol format
                        let raw_args = binding_call.args();
                        let args = crate::protocol::browser_context::BrowserContext::deserialize_binding_args_pub(raw_args);

                        // Call callback and serialize result
                        let result_value = callback(args).await;
                        let serialized =
                            crate::protocol::evaluate_conversion::serialize_argument(&result_value);

                        if let Err(e) = binding_call.resolve(serialized).await {
                            tracing::warn!("Failed to resolve BindingCall '{}': {}", name, e);
                        }
                    });
                }
            }
            "fileChooser" => {
                // FileChooser event: sent when an <input type="file"> is interacted with.
                // Event params: {element: {guid: "..."}, isMultiple: bool}
                let is_multiple = params
                    .get("isMultiple")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);

                if let Some(element_guid) = params
                    .get("element")
                    .and_then(|v| v.get("guid"))
                    .and_then(|v| v.as_str())
                {
                    let connection = self.connection();
                    let element_guid_owned = element_guid.to_string();
                    let self_clone = self.clone();

                    tokio::spawn(async move {
                        let element: crate::protocol::ElementHandle = match connection
                            .get_typed::<crate::protocol::ElementHandle>(&element_guid_owned)
                            .await
                        {
                            Ok(e) => e,
                            Err(err) => {
                                tracing::warn!(
                                    "Failed to get ElementHandle for fileChooser: {}",
                                    err
                                );
                                return;
                            }
                        };

                        let chooser = crate::protocol::FileChooser::new(
                            self_clone.clone(),
                            std::sync::Arc::new(element),
                            is_multiple,
                        );

                        self_clone.on_filechooser_event(chooser).await;
                    });
                }
            }
            "close" => {
                // Server-initiated close (e.g. context was closed)
                self.is_closed.store(true, Ordering::Relaxed);
                // Dispatch close handlers
                let self_clone = self.clone();
                tokio::spawn(async move {
                    self_clone.on_close_event().await;
                });
            }
            "load" => {
                let self_clone = self.clone();
                tokio::spawn(async move {
                    self_clone.on_load_event().await;
                });
            }
            "crash" => {
                let self_clone = self.clone();
                tokio::spawn(async move {
                    self_clone.on_crash_event().await;
                });
            }
            "pageError" => {
                // params: {"error": {"message": "...", "stack": "..."}}
                let message = params
                    .get("error")
                    .and_then(|e| e.get("message"))
                    .and_then(|m| m.as_str())
                    .unwrap_or("")
                    .to_string();
                let self_clone = self.clone();
                tokio::spawn(async move {
                    self_clone.on_pageerror_event(message).await;
                });
            }
            // "popup" is forwarded from BrowserContext::on_event when a "page" event
            // is received for a page that has an opener. No direct "popup" event on Page.
            "frameAttached" => {
                // params: {"frame": {"guid": "..."}}
                if let Some(frame_guid) = params
                    .get("frame")
                    .and_then(|v| v.get("guid"))
                    .and_then(|v| v.as_str())
                {
                    let connection = self.connection();
                    let frame_guid_owned = frame_guid.to_string();
                    let self_clone = self.clone();

                    tokio::spawn(async move {
                        let frame: crate::protocol::Frame = match connection
                            .get_typed::<crate::protocol::Frame>(&frame_guid_owned)
                            .await
                        {
                            Ok(f) => f,
                            Err(e) => {
                                tracing::warn!("Failed to get Frame for frameAttached: {}", e);
                                return;
                            }
                        };
                        self_clone.on_frameattached_event(frame).await;
                    });
                }
            }
            "frameDetached" => {
                // params: {"frame": {"guid": "..."}}
                if let Some(frame_guid) = params
                    .get("frame")
                    .and_then(|v| v.get("guid"))
                    .and_then(|v| v.as_str())
                {
                    let connection = self.connection();
                    let frame_guid_owned = frame_guid.to_string();
                    let self_clone = self.clone();

                    tokio::spawn(async move {
                        let frame: crate::protocol::Frame = match connection
                            .get_typed::<crate::protocol::Frame>(&frame_guid_owned)
                            .await
                        {
                            Ok(f) => f,
                            Err(e) => {
                                tracing::warn!("Failed to get Frame for frameDetached: {}", e);
                                return;
                            }
                        };
                        self_clone.on_framedetached_event(frame).await;
                    });
                }
            }
            "frameNavigated" => {
                // params: {"frame": {"guid": "..."}}
                // Note: frameNavigated may also contain url, name, etc. at top level
                // The frame guid is in the "frame" field (same as attached/detached)
                if let Some(frame_guid) = params
                    .get("frame")
                    .and_then(|v| v.get("guid"))
                    .and_then(|v| v.as_str())
                {
                    let connection = self.connection();
                    let frame_guid_owned = frame_guid.to_string();
                    let self_clone = self.clone();

                    tokio::spawn(async move {
                        let frame: crate::protocol::Frame = match connection
                            .get_typed::<crate::protocol::Frame>(&frame_guid_owned)
                            .await
                        {
                            Ok(f) => f,
                            Err(e) => {
                                tracing::warn!("Failed to get Frame for frameNavigated: {}", e);
                                return;
                            }
                        };
                        self_clone.on_framenavigated_event(frame).await;
                    });
                }
            }
            "locatorHandlerTriggered" => {
                // Server fires this when a registered locator matches an element.
                // params: {"uid": N}
                if let Some(uid) = params.get("uid").and_then(|v| v.as_u64()).map(|v| v as u32) {
                    let locator_handlers = self.locator_handlers.clone();
                    let self_clone = self.clone();

                    tokio::spawn(async move {
                        // Look up handler and decrement times_remaining
                        let (handler, selector, should_remove) = {
                            let mut handlers = locator_handlers.lock().unwrap();
                            let entry = handlers.iter_mut().find(|e| e.uid == uid);
                            match entry {
                                None => return,
                                Some(e) => {
                                    let handler = e.handler.clone();
                                    let selector = e.selector.clone();
                                    let remove = match e.times_remaining {
                                        Some(1) => true,
                                        Some(ref mut n) => {
                                            *n -= 1;
                                            false
                                        }
                                        None => false,
                                    };
                                    (handler, selector, remove)
                                }
                            }
                        };

                        // Build a Locator for the handler to receive
                        let locator = self_clone.locator(&selector).await;

                        // Run the handler
                        if let Err(e) = handler(locator).await {
                            tracing::warn!("locator handler error (uid={}): {}", uid, e);
                        }

                        // Send resolveLocatorHandler — remove=true if times exhausted
                        let _ = self_clone
                            .channel()
                            .send_no_result(
                                "resolveLocatorHandler",
                                serde_json::json!({ "uid": uid, "remove": should_remove }),
                            )
                            .await;

                        // Remove from local registry if one-shot
                        if should_remove {
                            self_clone
                                .locator_handlers
                                .lock()
                                .unwrap()
                                .retain(|e| e.uid != uid);
                        }
                    });
                }
            }
            _ => {
                // Other events not yet handled
            }
        }
    }

    fn was_collected(&self) -> bool {
        self.base.was_collected()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl std::fmt::Debug for Page {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Page")
            .field("guid", &self.guid())
            .field("url", &self.url())
            .finish()
    }
}

/// Options for page.goto() and page.reload()
#[derive(Debug, Clone)]
pub struct GotoOptions {
    /// Maximum operation time in milliseconds
    pub timeout: Option<std::time::Duration>,
    /// When to consider operation succeeded
    pub wait_until: Option<WaitUntil>,
}

impl GotoOptions {
    /// Creates new GotoOptions with default values
    pub fn new() -> Self {
        Self {
            timeout: None,
            wait_until: None,
        }
    }

    /// Sets the timeout
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Sets the wait_until option
    pub fn wait_until(mut self, wait_until: WaitUntil) -> Self {
        self.wait_until = Some(wait_until);
        self
    }
}

impl Default for GotoOptions {
    fn default() -> Self {
        Self::new()
    }
}

/// When to consider navigation succeeded
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WaitUntil {
    /// Consider operation to be finished when the `load` event is fired
    Load,
    /// Consider operation to be finished when the `DOMContentLoaded` event is fired
    DomContentLoaded,
    /// Consider operation to be finished when there are no network connections for at least 500ms
    NetworkIdle,
    /// Consider operation to be finished when the commit event is fired
    Commit,
}

impl WaitUntil {
    pub(crate) fn as_str(&self) -> &'static str {
        match self {
            WaitUntil::Load => "load",
            WaitUntil::DomContentLoaded => "domcontentloaded",
            WaitUntil::NetworkIdle => "networkidle",
            WaitUntil::Commit => "commit",
        }
    }
}

/// Options for adding a style tag to the page
///
/// See: <https://playwright.dev/docs/api/class-page#page-add-style-tag>
#[derive(Debug, Clone, Default)]
pub struct AddStyleTagOptions {
    /// Raw CSS content to inject
    pub content: Option<String>,
    /// URL of the `<link>` tag to add
    pub url: Option<String>,
    /// Path to a CSS file to inject
    pub path: Option<String>,
}

impl AddStyleTagOptions {
    /// Creates a new builder for AddStyleTagOptions
    pub fn builder() -> AddStyleTagOptionsBuilder {
        AddStyleTagOptionsBuilder::default()
    }

    /// Validates that at least one option is specified
    pub(crate) fn validate(&self) -> Result<()> {
        if self.content.is_none() && self.url.is_none() && self.path.is_none() {
            return Err(Error::InvalidArgument(
                "At least one of content, url, or path must be specified".to_string(),
            ));
        }
        Ok(())
    }
}

/// Builder for AddStyleTagOptions
#[derive(Debug, Clone, Default)]
pub struct AddStyleTagOptionsBuilder {
    content: Option<String>,
    url: Option<String>,
    path: Option<String>,
}

impl AddStyleTagOptionsBuilder {
    /// Sets the CSS content to inject
    pub fn content(mut self, content: impl Into<String>) -> Self {
        self.content = Some(content.into());
        self
    }

    /// Sets the URL of the stylesheet
    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    /// Sets the path to a CSS file
    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.path = Some(path.into());
        self
    }

    /// Builds the AddStyleTagOptions
    pub fn build(self) -> AddStyleTagOptions {
        AddStyleTagOptions {
            content: self.content,
            url: self.url,
            path: self.path,
        }
    }
}

// ============================================================================
// AddScriptTagOptions
// ============================================================================

/// Options for adding a `<script>` tag to the page.
///
/// At least one of `content`, `url`, or `path` must be specified.
///
/// See: <https://playwright.dev/docs/api/class-page#page-add-script-tag>
#[derive(Debug, Clone, Default)]
pub struct AddScriptTagOptions {
    /// Raw JavaScript content to inject
    pub content: Option<String>,
    /// URL of the `<script>` tag to add
    pub url: Option<String>,
    /// Path to a JavaScript file to inject (file contents will be read and sent as content)
    pub path: Option<String>,
    /// Script type attribute (e.g., `"module"`)
    pub type_: Option<String>,
}

impl AddScriptTagOptions {
    /// Creates a new builder for AddScriptTagOptions
    pub fn builder() -> AddScriptTagOptionsBuilder {
        AddScriptTagOptionsBuilder::default()
    }

    /// Validates that at least one option is specified
    pub(crate) fn validate(&self) -> Result<()> {
        if self.content.is_none() && self.url.is_none() && self.path.is_none() {
            return Err(Error::InvalidArgument(
                "At least one of content, url, or path must be specified".to_string(),
            ));
        }
        Ok(())
    }
}

/// Builder for AddScriptTagOptions
#[derive(Debug, Clone, Default)]
pub struct AddScriptTagOptionsBuilder {
    content: Option<String>,
    url: Option<String>,
    path: Option<String>,
    type_: Option<String>,
}

impl AddScriptTagOptionsBuilder {
    /// Sets the JavaScript content to inject
    pub fn content(mut self, content: impl Into<String>) -> Self {
        self.content = Some(content.into());
        self
    }

    /// Sets the URL of the script to load
    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    /// Sets the path to a JavaScript file to inject
    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.path = Some(path.into());
        self
    }

    /// Sets the script type attribute (e.g., `"module"`)
    pub fn type_(mut self, type_: impl Into<String>) -> Self {
        self.type_ = Some(type_.into());
        self
    }

    /// Builds the AddScriptTagOptions
    pub fn build(self) -> AddScriptTagOptions {
        AddScriptTagOptions {
            content: self.content,
            url: self.url,
            path: self.path,
            type_: self.type_,
        }
    }
}

// ============================================================================
// EmulateMediaOptions and related enums
// ============================================================================

/// Media type for `page.emulate_media()`.
///
/// See: <https://playwright.dev/docs/api/class-page#page-emulate-media>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Media {
    /// Emulate screen media type
    Screen,
    /// Emulate print media type
    Print,
    /// Reset media emulation to browser default (sends `"no-override"` to protocol)
    #[serde(rename = "no-override")]
    NoOverride,
}

/// Preferred color scheme for `page.emulate_media()`.
///
/// See: <https://playwright.dev/docs/api/class-page#page-emulate-media>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum ColorScheme {
    /// Emulate light color scheme
    #[serde(rename = "light")]
    Light,
    /// Emulate dark color scheme
    #[serde(rename = "dark")]
    Dark,
    /// Emulate no preference for color scheme
    #[serde(rename = "no-preference")]
    NoPreference,
    /// Reset color scheme to browser default
    #[serde(rename = "no-override")]
    NoOverride,
}

/// Reduced motion preference for `page.emulate_media()`.
///
/// See: <https://playwright.dev/docs/api/class-page#page-emulate-media>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum ReducedMotion {
    /// Emulate reduced motion preference
    #[serde(rename = "reduce")]
    Reduce,
    /// Emulate no preference for reduced motion
    #[serde(rename = "no-preference")]
    NoPreference,
    /// Reset reduced motion to browser default
    #[serde(rename = "no-override")]
    NoOverride,
}

/// Forced colors preference for `page.emulate_media()`.
///
/// See: <https://playwright.dev/docs/api/class-page#page-emulate-media>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum ForcedColors {
    /// Emulate active forced colors
    #[serde(rename = "active")]
    Active,
    /// Emulate no forced colors
    #[serde(rename = "none")]
    None_,
    /// Reset forced colors to browser default
    #[serde(rename = "no-override")]
    NoOverride,
}

/// Options for `page.emulate_media()`.
///
/// All fields are optional. Fields that are `None` are omitted from the protocol
/// message (meaning they are not changed). To reset a field to browser default,
/// use the `NoOverride` variant.
///
/// See: <https://playwright.dev/docs/api/class-page#page-emulate-media>
#[derive(Debug, Clone, Default)]
pub struct EmulateMediaOptions {
    /// Media type to emulate (screen, print, or no-override)
    pub media: Option<Media>,
    /// Color scheme preference to emulate
    pub color_scheme: Option<ColorScheme>,
    /// Reduced motion preference to emulate
    pub reduced_motion: Option<ReducedMotion>,
    /// Forced colors preference to emulate
    pub forced_colors: Option<ForcedColors>,
}

impl EmulateMediaOptions {
    /// Creates a new builder for EmulateMediaOptions
    pub fn builder() -> EmulateMediaOptionsBuilder {
        EmulateMediaOptionsBuilder::default()
    }
}

/// Builder for EmulateMediaOptions
#[derive(Debug, Clone, Default)]
pub struct EmulateMediaOptionsBuilder {
    media: Option<Media>,
    color_scheme: Option<ColorScheme>,
    reduced_motion: Option<ReducedMotion>,
    forced_colors: Option<ForcedColors>,
}

impl EmulateMediaOptionsBuilder {
    /// Sets the media type to emulate
    pub fn media(mut self, media: Media) -> Self {
        self.media = Some(media);
        self
    }

    /// Sets the color scheme preference
    pub fn color_scheme(mut self, color_scheme: ColorScheme) -> Self {
        self.color_scheme = Some(color_scheme);
        self
    }

    /// Sets the reduced motion preference
    pub fn reduced_motion(mut self, reduced_motion: ReducedMotion) -> Self {
        self.reduced_motion = Some(reduced_motion);
        self
    }

    /// Sets the forced colors preference
    pub fn forced_colors(mut self, forced_colors: ForcedColors) -> Self {
        self.forced_colors = Some(forced_colors);
        self
    }

    /// Builds the EmulateMediaOptions
    pub fn build(self) -> EmulateMediaOptions {
        EmulateMediaOptions {
            media: self.media,
            color_scheme: self.color_scheme,
            reduced_motion: self.reduced_motion,
            forced_colors: self.forced_colors,
        }
    }
}

// ============================================================================
// PdfOptions
// ============================================================================

/// Margin options for PDF generation.
///
/// See: <https://playwright.dev/docs/api/class-page#page-pdf>
#[derive(Debug, Clone, Default, Serialize)]
pub struct PdfMargin {
    /// Top margin (e.g. `"1in"`)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top: Option<String>,
    /// Right margin
    #[serde(skip_serializing_if = "Option::is_none")]
    pub right: Option<String>,
    /// Bottom margin
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bottom: Option<String>,
    /// Left margin
    #[serde(skip_serializing_if = "Option::is_none")]
    pub left: Option<String>,
}

/// Options for generating a PDF from a page.
///
/// Note: PDF generation is only supported by Chromium. Calling `page.pdf()` on
/// Firefox or WebKit will result in an error.
///
/// See: <https://playwright.dev/docs/api/class-page#page-pdf>
#[derive(Debug, Clone, Default)]
pub struct PdfOptions {
    /// If specified, the PDF will also be saved to this file path.
    pub path: Option<std::path::PathBuf>,
    /// Scale of the webpage rendering, between 0.1 and 2 (default 1).
    pub scale: Option<f64>,
    /// Whether to display header and footer (default false).
    pub display_header_footer: Option<bool>,
    /// HTML template for the print header. Should be valid HTML.
    pub header_template: Option<String>,
    /// HTML template for the print footer.
    pub footer_template: Option<String>,
    /// Whether to print background graphics (default false).
    pub print_background: Option<bool>,
    /// Paper orientation — `true` for landscape (default false).
    pub landscape: Option<bool>,
    /// Paper ranges to print, e.g. `"1-5, 8"`. Defaults to empty string (all pages).
    pub page_ranges: Option<String>,
    /// Paper format, e.g. `"Letter"` or `"A4"`. Overrides `width`/`height`.
    pub format: Option<String>,
    /// Paper width in CSS units, e.g. `"8.5in"`. Overrides `format`.
    pub width: Option<String>,
    /// Paper height in CSS units, e.g. `"11in"`. Overrides `format`.
    pub height: Option<String>,
    /// Whether or not to prefer page size as defined by CSS.
    pub prefer_css_page_size: Option<bool>,
    /// Paper margins, defaulting to none.
    pub margin: Option<PdfMargin>,
}

impl PdfOptions {
    /// Creates a new builder for PdfOptions
    pub fn builder() -> PdfOptionsBuilder {
        PdfOptionsBuilder::default()
    }
}

/// Builder for PdfOptions
#[derive(Debug, Clone, Default)]
pub struct PdfOptionsBuilder {
    path: Option<std::path::PathBuf>,
    scale: Option<f64>,
    display_header_footer: Option<bool>,
    header_template: Option<String>,
    footer_template: Option<String>,
    print_background: Option<bool>,
    landscape: Option<bool>,
    page_ranges: Option<String>,
    format: Option<String>,
    width: Option<String>,
    height: Option<String>,
    prefer_css_page_size: Option<bool>,
    margin: Option<PdfMargin>,
}

impl PdfOptionsBuilder {
    /// Sets the file path for saving the PDF
    pub fn path(mut self, path: std::path::PathBuf) -> Self {
        self.path = Some(path);
        self
    }

    /// Sets the scale of the webpage rendering
    pub fn scale(mut self, scale: f64) -> Self {
        self.scale = Some(scale);
        self
    }

    /// Sets whether to display header and footer
    pub fn display_header_footer(mut self, display: bool) -> Self {
        self.display_header_footer = Some(display);
        self
    }

    /// Sets the HTML template for the print header
    pub fn header_template(mut self, template: impl Into<String>) -> Self {
        self.header_template = Some(template.into());
        self
    }

    /// Sets the HTML template for the print footer
    pub fn footer_template(mut self, template: impl Into<String>) -> Self {
        self.footer_template = Some(template.into());
        self
    }

    /// Sets whether to print background graphics
    pub fn print_background(mut self, print: bool) -> Self {
        self.print_background = Some(print);
        self
    }

    /// Sets whether to use landscape orientation
    pub fn landscape(mut self, landscape: bool) -> Self {
        self.landscape = Some(landscape);
        self
    }

    /// Sets the page ranges to print
    pub fn page_ranges(mut self, ranges: impl Into<String>) -> Self {
        self.page_ranges = Some(ranges.into());
        self
    }

    /// Sets the paper format (e.g., `"Letter"`, `"A4"`)
    pub fn format(mut self, format: impl Into<String>) -> Self {
        self.format = Some(format.into());
        self
    }

    /// Sets the paper width
    pub fn width(mut self, width: impl Into<String>) -> Self {
        self.width = Some(width.into());
        self
    }

    /// Sets the paper height
    pub fn height(mut self, height: impl Into<String>) -> Self {
        self.height = Some(height.into());
        self
    }

    /// Sets whether to prefer page size as defined by CSS
    pub fn prefer_css_page_size(mut self, prefer: bool) -> Self {
        self.prefer_css_page_size = Some(prefer);
        self
    }

    /// Sets the paper margins
    pub fn margin(mut self, margin: PdfMargin) -> Self {
        self.margin = Some(margin);
        self
    }

    /// Builds the PdfOptions
    pub fn build(self) -> PdfOptions {
        PdfOptions {
            path: self.path,
            scale: self.scale,
            display_header_footer: self.display_header_footer,
            header_template: self.header_template,
            footer_template: self.footer_template,
            print_background: self.print_background,
            landscape: self.landscape,
            page_ranges: self.page_ranges,
            format: self.format,
            width: self.width,
            height: self.height,
            prefer_css_page_size: self.prefer_css_page_size,
            margin: self.margin,
        }
    }
}

/// Response from navigation operations.
///
/// Returned from `page.goto()`, `page.reload()`, `page.go_back()`, and similar
/// navigation methods. Provides access to the HTTP response status, headers, and body.
///
/// See: <https://playwright.dev/docs/api/class-response>
#[derive(Clone)]
pub struct Response {
    url: String,
    status: u16,
    status_text: String,
    ok: bool,
    headers: std::collections::HashMap<String, String>,
    /// Reference to the backing channel owner for RPC calls (body, rawHeaders, etc.)
    /// Stored as the generic trait object so it can be downcast to ResponseObject when needed.
    response_channel_owner: Option<std::sync::Arc<dyn crate::server::channel_owner::ChannelOwner>>,
}

impl Response {
    /// Creates a new Response from protocol data.
    ///
    /// This is used internally when constructing a Response from the protocol
    /// initializer (e.g., after `goto` or `reload`).
    pub(crate) fn new(
        url: String,
        status: u16,
        status_text: String,
        headers: std::collections::HashMap<String, String>,
        response_channel_owner: Option<
            std::sync::Arc<dyn crate::server::channel_owner::ChannelOwner>,
        >,
    ) -> Self {
        Self {
            url,
            status,
            status_text,
            ok: (200..300).contains(&status),
            headers,
            response_channel_owner,
        }
    }
}

impl Response {
    /// Returns the URL of the response.
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-url>
    pub fn url(&self) -> &str {
        &self.url
    }

    /// Returns the HTTP status code.
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-status>
    pub fn status(&self) -> u16 {
        self.status
    }

    /// Returns the HTTP status text.
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-status-text>
    pub fn status_text(&self) -> &str {
        &self.status_text
    }

    /// Returns whether the response was successful (status 200-299).
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-ok>
    pub fn ok(&self) -> bool {
        self.ok
    }

    /// Returns the response headers as a HashMap.
    ///
    /// Note: these are the headers from the protocol initializer. For the full
    /// raw headers (including duplicates), use `headers_array()` or `all_headers()`.
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-headers>
    pub fn headers(&self) -> &std::collections::HashMap<String, String> {
        &self.headers
    }

    /// Returns the [`Request`] that triggered this response.
    ///
    /// Navigates the protocol object hierarchy: ResponseObject → parent (Request).
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-request>
    pub fn request(&self) -> Option<crate::protocol::Request> {
        let owner = self.response_channel_owner.as_ref()?;
        downcast_parent::<crate::protocol::Request>(&**owner)
    }

    /// Returns the [`Frame`](crate::protocol::Frame) that initiated the request for this response.
    ///
    /// Navigates the protocol object hierarchy: ResponseObject → Request → Frame.
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-frame>
    pub fn frame(&self) -> Option<crate::protocol::Frame> {
        let request = self.request()?;
        request.frame()
    }

    /// Returns the backing `ResponseObject`, or an error if unavailable.
    pub(crate) fn response_object(&self) -> crate::error::Result<crate::protocol::ResponseObject> {
        let arc = self.response_channel_owner.as_ref().ok_or_else(|| {
            crate::error::Error::ProtocolError(
                "Response has no backing protocol object".to_string(),
            )
        })?;
        arc.as_any()
            .downcast_ref::<crate::protocol::ResponseObject>()
            .cloned()
            .ok_or_else(|| crate::error::Error::TypeMismatch {
                guid: arc.guid().to_string(),
                expected: "ResponseObject".to_string(),
                actual: arc.type_name().to_string(),
            })
    }

    /// Returns TLS/SSL security details for HTTPS connections, or `None` for HTTP.
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-security-details>
    pub async fn security_details(
        &self,
    ) -> crate::error::Result<Option<crate::protocol::response::SecurityDetails>> {
        self.response_object()?.security_details().await
    }

    /// Returns the server's IP address and port, or `None`.
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-server-addr>
    pub async fn server_addr(
        &self,
    ) -> crate::error::Result<Option<crate::protocol::response::RemoteAddr>> {
        self.response_object()?.server_addr().await
    }

    /// Waits for this response to finish loading.
    ///
    /// For responses obtained from navigation methods (`goto`, `reload`), the response
    /// is already finished when returned. For responses from `on_response` handlers,
    /// the body may still be loading.
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-finished>
    pub async fn finished(&self) -> crate::error::Result<()> {
        // The Playwright protocol dispatches `requestFinished` as a separate event
        // rather than exposing a `finished` RPC method on Response.
        // For responses from goto/reload, the response is already complete.
        // TODO: For on_response handlers, implement proper waiting via requestFinished event.
        Ok(())
    }

    /// Returns the HTTP version used by this response (e.g. `"HTTP/1.1"` or `"HTTP/2.0"`).
    ///
    /// Makes an RPC call to the Playwright server.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No backing protocol object is available (edge case)
    /// - The RPC call to the server fails
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-http-version>
    pub async fn http_version(&self) -> crate::error::Result<String> {
        self.response_object()?.http_version().await
    }

    /// Returns the response body as raw bytes.
    ///
    /// Makes an RPC call to the Playwright server to fetch the response body.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No backing protocol object is available (edge case)
    /// - The RPC call to the server fails
    /// - The base64 response cannot be decoded
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-body>
    pub async fn body(&self) -> crate::error::Result<Vec<u8>> {
        self.response_object()?.body().await
    }

    /// Returns the response body as a UTF-8 string.
    ///
    /// Calls `body()` then converts bytes to a UTF-8 string.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `body()` fails
    /// - The body is not valid UTF-8
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-text>
    pub async fn text(&self) -> crate::error::Result<String> {
        let bytes = self.body().await?;
        String::from_utf8(bytes).map_err(|e| {
            crate::error::Error::ProtocolError(format!("Response body is not valid UTF-8: {}", e))
        })
    }

    /// Parses the response body as JSON and deserializes it into type `T`.
    ///
    /// Calls `text()` then uses `serde_json` to deserialize the body.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `text()` fails
    /// - The body is not valid JSON or doesn't match the expected type
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-json>
    pub async fn json<T: serde::de::DeserializeOwned>(&self) -> crate::error::Result<T> {
        let text = self.text().await?;
        serde_json::from_str(&text).map_err(|e| {
            crate::error::Error::ProtocolError(format!("Failed to parse response JSON: {}", e))
        })
    }

    /// Returns all response headers as name-value pairs, preserving duplicates.
    ///
    /// Makes an RPC call for `"rawHeaders"` which returns the complete header list.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No backing protocol object is available (edge case)
    /// - The RPC call to the server fails
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-headers-array>
    pub async fn headers_array(
        &self,
    ) -> crate::error::Result<Vec<crate::protocol::response::HeaderEntry>> {
        self.response_object()?.raw_headers().await
    }

    /// Returns all response headers merged into a HashMap with lowercase keys.
    ///
    /// When multiple headers have the same name, their values are joined with `, `.
    /// This matches the behavior of `response.allHeaders()` in other Playwright bindings.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No backing protocol object is available (edge case)
    /// - The RPC call to the server fails
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-all-headers>
    pub async fn all_headers(
        &self,
    ) -> crate::error::Result<std::collections::HashMap<String, String>> {
        let entries = self.headers_array().await?;
        let mut map: std::collections::HashMap<String, String> = std::collections::HashMap::new();
        for entry in entries {
            let key = entry.name.to_lowercase();
            map.entry(key)
                .and_modify(|v| {
                    v.push_str(", ");
                    v.push_str(&entry.value);
                })
                .or_insert(entry.value);
        }
        Ok(map)
    }

    /// Returns the value for a single response header, or `None` if not present.
    ///
    /// The lookup is case-insensitive.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No backing protocol object is available (edge case)
    /// - The RPC call to the server fails
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-header-value>
    /// Returns the value for a single response header, or `None` if not present.
    ///
    /// The lookup is case-insensitive. When multiple headers share the same name,
    /// their values are joined with `, ` (matching Playwright's behavior).
    ///
    /// Uses the raw headers from the server for accurate results.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying `headers_array()` RPC call fails.
    ///
    /// See: <https://playwright.dev/docs/api/class-response#response-header-value>
    pub async fn header_value(&self, name: &str) -> crate::error::Result<Option<String>> {
        let entries = self.headers_array().await?;
        let name_lower = name.to_lowercase();
        let mut values: Vec<String> = entries
            .into_iter()
            .filter(|h| h.name.to_lowercase() == name_lower)
            .map(|h| h.value)
            .collect();

        if values.is_empty() {
            Ok(None)
        } else if values.len() == 1 {
            Ok(Some(values.remove(0)))
        } else {
            Ok(Some(values.join(", ")))
        }
    }
}

impl std::fmt::Debug for Response {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Response")
            .field("url", &self.url)
            .field("status", &self.status)
            .field("status_text", &self.status_text)
            .field("ok", &self.ok)
            .finish_non_exhaustive()
    }
}

/// Options for `page.route_from_har()` and `context.route_from_har()`.
///
/// See: <https://playwright.dev/docs/api/class-page#page-route-from-har>
#[derive(Debug, Clone, Default)]
pub struct RouteFromHarOptions {
    /// URL glob pattern — only requests matching this pattern are served from
    /// the HAR file.  All requests are intercepted when omitted.
    pub url: Option<String>,

    /// Policy for requests not found in the HAR file.
    ///
    /// - `"abort"` (default) — terminate the request with a network error.
    /// - `"fallback"` — pass the request through to the next handler (or network).
    pub not_found: Option<String>,

    /// When `true`, record new network activity into the HAR file instead of
    /// replaying existing entries.  Defaults to `false`.
    pub update: Option<bool>,

    /// Content storage strategy used when `update` is `true`.
    ///
    /// - `"embed"` (default) — inline base64-encoded content in the HAR.
    /// - `"attach"` — store content as separate files alongside the HAR.
    pub update_content: Option<String>,

    /// Recording detail level used when `update` is `true`.
    ///
    /// - `"minimal"` (default) — omit timing, cookies, and security info.
    /// - `"full"` — record everything.
    pub update_mode: Option<String>,
}

/// Options for `page.add_locator_handler()`.
///
/// See: <https://playwright.dev/docs/api/class-page#page-add-locator-handler>
#[derive(Debug, Clone, Default)]
pub struct AddLocatorHandlerOptions {
    /// Whether to keep the page frozen after the handler has been called.
    ///
    /// When `false` (default), Playwright resumes normal page operation after
    /// the handler completes. When `true`, the page stays paused.
    pub no_wait_after: Option<bool>,

    /// Maximum number of times to invoke this handler.
    ///
    /// Once exhausted, the handler is automatically unregistered.
    /// `None` (default) means the handler runs indefinitely.
    pub times: Option<u32>,
}

/// Shared helper: store timeout locally and notify the Playwright server.
/// Used by both Page and BrowserContext timeout setters.
pub(crate) async fn set_timeout_and_notify(
    channel: &crate::server::channel::Channel,
    method: &str,
    timeout: f64,
) {
    if let Err(e) = channel
        .send_no_result(method, serde_json::json!({ "timeout": timeout }))
        .await
    {
        tracing::warn!("{} send error: {}", method, e);
    }
}