playwright-rs 0.10.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
// 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};
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>>>,
    /// 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>>>,
}

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

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

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(),
                )
            })?);

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

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

        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,
            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())),
        })
    }

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

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

    /// 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 `data-testid` attribute.
    ///
    /// 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 {
        self.locator(&crate::protocol::locator::get_by_test_id_selector(test_id))
            .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
    }

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

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

    /// 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 = self.request_handlers.lock().unwrap().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 = self.response_handlers.lock().unwrap().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(())
    }

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

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

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

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

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

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

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);
                                }
                            });
                        }
                    });
                }
            }
            "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);
                        }
                    });
                }
            }
            "close" => {
                // Server-initiated close (e.g. context was closed)
                self.is_closed.store(true, Ordering::Relaxed);
            }
            _ => {
                // Other events will be handled in future phases
                // Events: load, domcontentloaded, crash, etc.
            }
        }
    }

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

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