playwright-rs 0.12.0

Rust bindings for Microsoft Playwright
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
// Frame protocol object
//
// Represents a frame within a page. Pages have a main frame, and can have child frames (iframes).
// Navigation and DOM operations happen on frames, not directly on pages.

use crate::error::{Error, Result};
use crate::protocol::page::{GotoOptions, Response, WaitUntil};
use crate::protocol::{parse_result, serialize_argument, serialize_null};
use crate::server::channel::Channel;
use crate::server::channel_owner::{ChannelOwner, ChannelOwnerImpl, ParentOrConnection};
use crate::server::connection::ConnectionExt;
use serde::Deserialize;
use serde_json::Value;
use std::any::Any;
use std::sync::{Arc, Mutex, RwLock};

/// Frame represents a frame within a page.
///
/// Every page has a main frame, and pages can have additional child frames (iframes).
/// Frame is where navigation, selector queries, and DOM operations actually happen.
///
/// In Playwright's architecture, Page delegates navigation and interaction methods to Frame.
///
/// See: <https://playwright.dev/docs/api/class-frame>
#[derive(Clone)]
pub struct Frame {
    base: ChannelOwnerImpl,
    /// Current URL of the frame.
    /// Wrapped in RwLock to allow updates from events.
    url: Arc<RwLock<String>>,
    /// The name attribute of the frame element (empty string for the main frame).
    /// Extracted from the protocol initializer.
    name: Arc<str>,
    /// GUID of the parent frame, if any (None for the main/top-level frame).
    /// Extracted from the protocol initializer.
    parent_frame_guid: Option<Arc<str>>,
    /// Whether this frame has been detached from the page.
    /// Set to true when a "detached" event is received.
    is_detached: Arc<RwLock<bool>>,
    /// The owning Page, set after the Page is created and the frame is adopted.
    ///
    /// This is `None` until `set_page()` is called by the owning Page.
    /// Using `Mutex<Option<...>>` so that `set_page()` can be called on a shared `&Frame`.
    page: Arc<Mutex<Option<crate::protocol::Page>>>,
}

impl Frame {
    /// Creates a new Frame from protocol initialization.
    ///
    /// This is called by the object factory when the server sends a `__create__` message
    /// for a Frame object.
    pub fn new(
        parent: Arc<dyn ChannelOwner>,
        type_name: String,
        guid: Arc<str>,
        initializer: Value,
    ) -> Result<Self> {
        let base = ChannelOwnerImpl::new(
            ParentOrConnection::Parent(parent),
            type_name,
            guid,
            initializer.clone(),
        );

        // Extract initial URL from initializer if available
        let initial_url = initializer
            .get("url")
            .and_then(|v| v.as_str())
            .unwrap_or("about:blank")
            .to_string();

        let url = Arc::new(RwLock::new(initial_url));

        // Extract the frame's name attribute (empty string for main frame)
        let name: Arc<str> = Arc::from(
            initializer
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or(""),
        );

        // Extract parent frame GUID if present
        let parent_frame_guid: Option<Arc<str>> = initializer
            .get("parentFrame")
            .and_then(|v| v.get("guid"))
            .and_then(|v| v.as_str())
            .map(Arc::from);

        Ok(Self {
            base,
            url,
            name,
            parent_frame_guid,
            is_detached: Arc::new(RwLock::new(false)),
            page: Arc::new(Mutex::new(None)),
        })
    }

    /// Sets the owning Page for this frame.
    ///
    /// Called by `Page::main_frame()` after the frame is retrieved from the registry.
    /// This allows `frame.page()` and `frame.locator()` to work.
    pub(crate) fn set_page(&self, page: crate::protocol::Page) {
        if let Ok(mut guard) = self.page.lock() {
            *guard = Some(page);
        }
    }

    /// Returns the owning Page for this frame, if it has been set.
    ///
    /// Returns `None` if `set_page()` has not been called yet (i.e., before the frame
    /// has been adopted by a Page). In normal usage the main frame always has a Page.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-page>
    pub fn page(&self) -> Option<crate::protocol::Page> {
        self.page.lock().ok().and_then(|g| g.clone())
    }

    /// Returns the `name` attribute value of the frame element used to create this frame.
    ///
    /// For the main (top-level) frame this is always an empty string.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-name>
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the parent `Frame`, or `None` if this is the top-level (main) frame.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-parent-frame>
    pub fn parent_frame(&self) -> Option<crate::protocol::Frame> {
        let guid = self.parent_frame_guid.as_ref()?;
        // Look up the parent frame in the connection registry (sync-compatible via block_on)
        // We spawn a brief async lookup using the connection.
        let conn = self.base.connection();
        // Use tokio's block_in_place / futures executor to do a synchronous resolution.
        // This mirrors how other Rust Playwright clients resolve parent references.
        tokio::task::block_in_place(|| {
            tokio::runtime::Handle::current()
                .block_on(conn.get_typed::<crate::protocol::Frame>(guid))
                .ok()
        })
    }

    /// Returns `true` if the frame has been detached from its page.
    ///
    /// A frame becomes detached when the corresponding `<iframe>` element is removed
    /// from the DOM or when the owning page is closed.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-is-detached>
    pub fn is_detached(&self) -> bool {
        self.is_detached.read().map(|v| *v).unwrap_or(false)
    }

    /// Returns all child frames embedded in this frame.
    ///
    /// Child frames are created by `<iframe>` elements within this frame.
    /// For the main frame this may include multiple iframes.
    ///
    /// # Implementation Note
    ///
    /// This iterates all objects in the connection registry to find `Frame` objects
    /// whose `parentFrame` initializer field matches this frame's GUID. This matches
    /// the relationship Playwright establishes when creating child frames.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-child-frames>
    pub fn child_frames(&self) -> Vec<crate::protocol::Frame> {
        let my_guid = self.guid().to_string();
        let conn = self.base.connection();

        // Use the synchronous registry snapshot — no async needed since the
        // underlying storage is a parking_lot::Mutex (sync-safe to lock).
        conn.all_objects_sync()
            .into_iter()
            .filter_map(|obj| {
                // Only consider Frame-typed objects
                if obj.type_name() != "Frame" {
                    return None;
                }
                // Check the initializer's parentFrame.guid field
                let parent_guid = obj
                    .initializer()
                    .get("parentFrame")
                    .and_then(|v| v.get("guid"))
                    .and_then(|v| v.as_str())?;

                if parent_guid == my_guid {
                    obj.as_any()
                        .downcast_ref::<crate::protocol::Frame>()
                        .cloned()
                } else {
                    None
                }
            })
            .collect()
    }

    /// Evaluates a JavaScript expression and returns a handle to the result.
    ///
    /// Unlike [`evaluate`](Frame::evaluate) which serializes the return value to JSON,
    /// `evaluate_handle` returns a handle to the in-browser object. This is useful when
    /// the return value is a non-serializable DOM element or complex JS object.
    ///
    /// # Arguments
    ///
    /// * `expression` - JavaScript expression to evaluate in the frame context
    ///
    /// # Returns
    ///
    /// An `Arc<ElementHandle>` pointing to the in-browser object.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # 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?;
    /// page.goto("https://example.com", None).await?;
    /// let frame = page.main_frame().await?;
    ///
    /// let handle = frame.evaluate_handle("document.body").await?;
    /// let screenshot = handle.screenshot(None).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - The JavaScript expression throws an error
    /// - The result handle GUID cannot be found in the registry
    /// - Communication with the browser fails
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-evaluate-handle>
    pub async fn evaluate_handle(
        &self,
        expression: &str,
    ) -> Result<Arc<crate::protocol::ElementHandle>> {
        let params = serde_json::json!({
            "expression": expression,
            "isFunction": false,
            "arg": {"value": {"v": "undefined"}, "handles": []}
        });

        // The server returns {"handle": {"guid": "JSHandle@..."}}
        #[derive(Deserialize)]
        struct HandleRef {
            guid: String,
        }
        #[derive(Deserialize)]
        struct EvaluateHandleResponse {
            handle: HandleRef,
        }

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

        let guid = &response.handle.guid;

        // Look up in the connection registry with retry (the __create__ may arrive slightly later)
        let connection = self.base.connection();
        let mut attempts = 0;
        let max_attempts = 20;
        let handle = loop {
            match connection
                .get_typed::<crate::protocol::ElementHandle>(guid)
                .await
            {
                Ok(h) => break h,
                Err(_) if attempts < max_attempts => {
                    attempts += 1;
                    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                }
                Err(e) => return Err(e),
            }
        };

        Ok(Arc::new(handle))
    }

    /// Evaluates a JavaScript expression and returns a [`JSHandle`](crate::protocol::JSHandle) to the result.
    ///
    /// Unlike [`evaluate_handle`](Frame::evaluate_handle) which returns an `Arc<ElementHandle>`,
    /// this method returns an `Arc<JSHandle>` and is suitable for non-DOM values such as
    /// plain objects, numbers, and strings.
    ///
    /// # Arguments
    ///
    /// * `expression` - JavaScript expression to evaluate in the frame context
    ///
    /// # Returns
    ///
    /// An `Arc<JSHandle>` pointing to the in-browser value.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - The JavaScript expression throws an error
    /// - The result handle GUID cannot be found in the registry
    /// - Communication with the browser fails
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-evaluate-handle>
    pub async fn evaluate_handle_js(
        &self,
        expression: &str,
    ) -> Result<std::sync::Arc<crate::protocol::JSHandle>> {
        // Detect whether the expression is a function (arrow function or function keyword)
        // so we can set isFunction correctly and the server invokes it rather than
        // evaluating the function literal.
        let trimmed = expression.trim();
        let is_function = trimmed.starts_with("(")
            || trimmed.starts_with("function")
            || trimmed.starts_with("async ");

        let params = serde_json::json!({
            "expression": expression,
            "isFunction": is_function,
            "arg": {"value": {"v": "undefined"}, "handles": []}
        });

        // The server returns {"handle": {"guid": "JSHandle@..."}}
        #[derive(Deserialize)]
        struct HandleRef {
            guid: String,
        }
        #[derive(Deserialize)]
        struct EvaluateHandleResponse {
            handle: HandleRef,
        }

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

        let guid = &response.handle.guid;

        // Look up in the connection registry with retry (the __create__ may arrive slightly later)
        let connection = self.base.connection();
        let mut attempts = 0;
        let max_attempts = 20;
        let handle = loop {
            match connection
                .get_typed::<crate::protocol::JSHandle>(guid)
                .await
            {
                Ok(h) => break h,
                Err(_) if attempts < max_attempts => {
                    attempts += 1;
                    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                }
                Err(e) => return Err(e),
            }
        };

        Ok(std::sync::Arc::new(handle))
    }

    /// Creates a [`Locator`](crate::protocol::Locator) scoped to this frame.
    ///
    /// The locator is lazy — it does not query the DOM until an action is performed on it.
    ///
    /// # Arguments
    ///
    /// * `selector` - A CSS selector or other Playwright selector strategy
    ///
    /// # Panics
    ///
    /// Panics if the owning Page has not been set (i.e., `set_page()` was never called).
    /// In normal usage the main frame always has its page wired up by `Page::main_frame()`.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-locator>
    pub fn locator(&self, selector: &str) -> crate::protocol::Locator {
        let page = self
            .page()
            .expect("Frame::locator() called before set_page(); call page.main_frame() first");
        crate::protocol::Locator::new(Arc::new(self.clone()), selector.to_string(), page)
    }

    /// Returns a locator that matches elements containing the given text.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-get-by-text>
    pub fn get_by_text(&self, text: &str, exact: bool) -> crate::protocol::Locator {
        self.locator(&crate::protocol::locator::get_by_text_selector(text, exact))
    }

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

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

    /// Returns a locator that matches elements by their alt text.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-get-by-alt-text>
    pub 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,
        ))
    }

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

    /// Returns a locator that matches elements by their test ID attribute.
    ///
    /// By default, uses the `data-testid` attribute. Call
    /// `playwright.selectors().set_test_id_attribute()` to change the attribute name.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-get-by-test-id>
    pub fn get_by_test_id(&self, test_id: &str) -> crate::protocol::Locator {
        use crate::server::channel_owner::ChannelOwner;
        let attr = self.connection().selectors().test_id_attribute();
        self.locator(&crate::protocol::locator::get_by_test_id_selector_with_attr(test_id, &attr))
    }

    /// Returns a locator that matches elements by their ARIA role.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-get-by-role>
    pub 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,
        ))
    }

    /// Returns the channel for sending protocol messages
    fn channel(&self) -> &Channel {
        self.base.channel()
    }

    /// Returns the current URL of the frame.
    ///
    /// This returns the last committed URL. Initially, frames are at "about:blank".
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-url>
    pub fn url(&self) -> String {
        self.url.read().unwrap().clone()
    }

    /// Navigates the frame to the specified URL.
    ///
    /// This is the actual protocol method for navigation. Page.goto() delegates to this.
    ///
    /// 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)
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-goto>
    pub async fn goto(&self, url: &str, options: Option<GotoOptions>) -> Result<Option<Response>> {
        // Build params manually using json! macro
        let mut params = serde_json::json!({
            "url": url,
        });

        // Add optional parameters
        if let Some(opts) = options {
            if let Some(timeout) = opts.timeout {
                params["timeout"] = serde_json::json!(timeout.as_millis() as u64);
            } else {
                // Default timeout required in Playwright 1.56.1+
                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());
            }
        } else {
            // No options provided, set default timeout (required in Playwright 1.56.1+)
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

        // Send goto RPC to Frame
        // The server returns { "response": { "guid": "..." } } or null
        #[derive(Deserialize)]
        struct GotoResponse {
            response: Option<ResponseReference>,
        }

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

        let goto_result: GotoResponse = self.channel().send("goto", params).await?;

        // If navigation returned a response, get the Response object from the connection
        if let Some(response_ref) = goto_result.response {
            // The server returns a Response GUID, but the __create__ message might not have
            // arrived yet. Retry a few times to wait for the object to be created.
            // TODO(Phase 4+): Implement proper GUID replacement like Python's _replace_guids_with_channels
            //   - Eliminates retry loop for better performance
            //   - See: playwright-python's _replace_guids_with_channels method
            let response_arc = {
                let mut attempts = 0;
                let max_attempts = 20; // 20 * 50ms = 1 second max wait
                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),
                    }
                }
            };

            // Extract Response data from the initializer, and store the Arc for RPC calls
            // (body(), rawHeaders(), headerValue()) that need to contact the server.
            let initializer = response_arc.initializer();

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

            // Convert headers from array format to HashMap
            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();

            Ok(Some(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),
            )))
        } else {
            // Navigation returned null (e.g., data URLs, about:blank)
            // This is a valid result, not an error
            Ok(None)
        }
    }

    /// Returns the frame's title.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-title>
    pub async fn title(&self) -> Result<String> {
        #[derive(Deserialize)]
        struct TitleResponse {
            value: String,
        }

        let response: TitleResponse = self.channel().send("title", serde_json::json!({})).await?;
        Ok(response.value)
    }

    /// Returns the full HTML content of the frame, including the DOCTYPE.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-content>
    pub async fn content(&self) -> Result<String> {
        #[derive(Deserialize)]
        struct ContentResponse {
            value: String,
        }

        let response: ContentResponse = self
            .channel()
            .send("content", serde_json::json!({}))
            .await?;
        Ok(response.value)
    }

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

        if let Some(opts) = options {
            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());
            }
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

    /// Waits for the required load state to be reached.
    ///
    /// Playwright's protocol doesn't expose `waitForLoadState` as a server-side command —
    /// it's implemented client-side using lifecycle events. We implement it by polling
    /// `document.readyState` via JavaScript evaluation.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-wait-for-load-state>
    pub async fn wait_for_load_state(&self, state: Option<WaitUntil>) -> Result<()> {
        let target_state = state.unwrap_or(WaitUntil::Load);

        let js_check = match target_state {
            // "load" means the full page has loaded (readyState === "complete")
            WaitUntil::Load => "document.readyState === 'complete'",
            // "domcontentloaded" means DOM is ready (readyState !== "loading")
            WaitUntil::DomContentLoaded => "document.readyState !== 'loading'",
            // "networkidle" has no direct readyState equivalent; we approximate
            // by checking "complete" (same as Load)
            WaitUntil::NetworkIdle => "document.readyState === 'complete'",
            // "commit" means any response has been received (readyState !== "loading" at minimum)
            WaitUntil::Commit => "document.readyState !== 'loading'",
        };

        let timeout_ms = crate::DEFAULT_TIMEOUT_MS as u64;
        let poll_interval = std::time::Duration::from_millis(50);
        let start = std::time::Instant::now();

        loop {
            #[derive(Deserialize)]
            struct EvalResponse {
                value: serde_json::Value,
            }

            let result: EvalResponse = self
                .channel()
                .send(
                    "evaluateExpression",
                    serde_json::json!({
                        "expression": js_check,
                        "isFunction": false,
                        "arg": crate::protocol::serialize_null(),
                    }),
                )
                .await?;

            // Playwright protocol returns booleans as {"b": true/false}
            let is_ready = result
                .value
                .as_object()
                .and_then(|m| m.get("b"))
                .and_then(|v| v.as_bool())
                .unwrap_or(false);

            if is_ready {
                return Ok(());
            }

            if start.elapsed().as_millis() as u64 >= timeout_ms {
                return Err(crate::error::Error::Timeout(format!(
                    "wait_for_load_state({}) timed out after {}ms",
                    target_state.as_str(),
                    timeout_ms
                )));
            }

            tokio::time::sleep(poll_interval).await;
        }
    }

    /// Waits for the frame to navigate to a URL matching the given string or glob pattern.
    ///
    /// Playwright's protocol doesn't expose `waitForURL` as a server-side command —
    /// it's implemented client-side. We implement it by polling `window.location.href`.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-wait-for-url>
    pub async fn wait_for_url(&self, url: &str, options: Option<GotoOptions>) -> Result<()> {
        let timeout_ms = options
            .as_ref()
            .and_then(|o| o.timeout)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(crate::DEFAULT_TIMEOUT_MS as u64);

        // Convert glob pattern to regex for matching
        // Playwright supports string (exact), glob (**), and regex patterns
        // We support exact string and basic glob patterns
        let is_glob = url.contains('*');

        let poll_interval = std::time::Duration::from_millis(50);
        let start = std::time::Instant::now();

        loop {
            let current_url = self.url();

            let matches = if is_glob {
                glob_match(url, &current_url)
            } else {
                current_url == url
            };

            if matches {
                // URL matches — optionally wait for load state
                if let Some(ref opts) = options
                    && let Some(wait_until) = opts.wait_until
                {
                    self.wait_for_load_state(Some(wait_until)).await?;
                }
                return Ok(());
            }

            if start.elapsed().as_millis() as u64 >= timeout_ms {
                return Err(crate::error::Error::Timeout(format!(
                    "wait_for_url({}) timed out after {}ms, current URL: {}",
                    url, timeout_ms, current_url
                )));
            }

            tokio::time::sleep(poll_interval).await;
        }
    }

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

        // Check if response is empty (no element found)
        if response.as_object().map(|o| o.is_empty()).unwrap_or(true) {
            return Ok(None);
        }

        // Try different possible field names
        let element_value = if let Some(elem) = response.get("element") {
            elem
        } else if let Some(elem) = response.get("handle") {
            elem
        } else {
            // Maybe the response IS the guid object itself
            &response
        };

        if element_value.is_null() {
            return Ok(None);
        }

        // Element response contains { guid: "elementHandle@123" }
        let guid = element_value["guid"].as_str().ok_or_else(|| {
            crate::error::Error::ProtocolError("Element GUID missing".to_string())
        })?;

        // Look up the ElementHandle object in the connection's object registry and downcast
        let connection = self.base.connection();
        let handle: crate::protocol::ElementHandle = connection
            .get_typed::<crate::protocol::ElementHandle>(guid)
            .await?;

        Ok(Some(Arc::new(handle)))
    }

    /// Returns all elements matching the selector.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-query-selector-all>
    pub async fn query_selector_all(
        &self,
        selector: &str,
    ) -> Result<Vec<Arc<crate::protocol::ElementHandle>>> {
        #[derive(Deserialize)]
        struct QueryAllResponse {
            elements: Vec<serde_json::Value>,
        }

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

        // Convert GUID responses to ElementHandle objects
        let connection = self.base.connection();
        let mut handles = Vec::new();

        for element_value in response.elements {
            let guid = element_value["guid"].as_str().ok_or_else(|| {
                crate::error::Error::ProtocolError("Element GUID missing".to_string())
            })?;

            let handle: crate::protocol::ElementHandle = connection
                .get_typed::<crate::protocol::ElementHandle>(guid)
                .await?;

            handles.push(Arc::new(handle));
        }

        Ok(handles)
    }

    // Locator delegate methods
    // These are called by Locator to perform actual queries

    /// Returns the number of elements matching the selector.
    pub(crate) async fn locator_count(&self, selector: &str) -> Result<usize> {
        // Use querySelectorAll which returns array of element handles
        #[derive(Deserialize)]
        struct QueryAllResponse {
            elements: Vec<serde_json::Value>,
        }

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

        Ok(response.elements.len())
    }

    /// Returns the text content of the element.
    pub(crate) async fn locator_text_content(&self, selector: &str) -> Result<Option<String>> {
        #[derive(Deserialize)]
        struct TextContentResponse {
            value: Option<String>,
        }

        let response: TextContentResponse = self
            .channel()
            .send(
                "textContent",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS
                }),
            )
            .await?;

        Ok(response.value)
    }

    /// Returns the inner text of the element.
    pub(crate) async fn locator_inner_text(&self, selector: &str) -> Result<String> {
        #[derive(Deserialize)]
        struct InnerTextResponse {
            value: String,
        }

        let response: InnerTextResponse = self
            .channel()
            .send(
                "innerText",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS
                }),
            )
            .await?;

        Ok(response.value)
    }

    /// Returns the inner HTML of the element.
    pub(crate) async fn locator_inner_html(&self, selector: &str) -> Result<String> {
        #[derive(Deserialize)]
        struct InnerHTMLResponse {
            value: String,
        }

        let response: InnerHTMLResponse = self
            .channel()
            .send(
                "innerHTML",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS
                }),
            )
            .await?;

        Ok(response.value)
    }

    /// Returns the value of the specified attribute.
    pub(crate) async fn locator_get_attribute(
        &self,
        selector: &str,
        name: &str,
    ) -> Result<Option<String>> {
        #[derive(Deserialize)]
        struct GetAttributeResponse {
            value: Option<String>,
        }

        let response: GetAttributeResponse = self
            .channel()
            .send(
                "getAttribute",
                serde_json::json!({
                    "selector": selector,
                    "name": name,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS
                }),
            )
            .await?;

        Ok(response.value)
    }

    /// Returns whether the element is visible.
    pub(crate) async fn locator_is_visible(&self, selector: &str) -> Result<bool> {
        #[derive(Deserialize)]
        struct IsVisibleResponse {
            value: bool,
        }

        let response: IsVisibleResponse = self
            .channel()
            .send(
                "isVisible",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS
                }),
            )
            .await?;

        Ok(response.value)
    }

    /// Returns whether the element is enabled.
    pub(crate) async fn locator_is_enabled(&self, selector: &str) -> Result<bool> {
        #[derive(Deserialize)]
        struct IsEnabledResponse {
            value: bool,
        }

        let response: IsEnabledResponse = self
            .channel()
            .send(
                "isEnabled",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS
                }),
            )
            .await?;

        Ok(response.value)
    }

    /// Returns whether the checkbox or radio button is checked.
    pub(crate) async fn locator_is_checked(&self, selector: &str) -> Result<bool> {
        #[derive(Deserialize)]
        struct IsCheckedResponse {
            value: bool,
        }

        let response: IsCheckedResponse = self
            .channel()
            .send(
                "isChecked",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS
                }),
            )
            .await?;

        Ok(response.value)
    }

    /// Returns whether the element is editable.
    pub(crate) async fn locator_is_editable(&self, selector: &str) -> Result<bool> {
        #[derive(Deserialize)]
        struct IsEditableResponse {
            value: bool,
        }

        let response: IsEditableResponse = self
            .channel()
            .send(
                "isEditable",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS
                }),
            )
            .await?;

        Ok(response.value)
    }

    /// Returns whether the element is hidden.
    pub(crate) async fn locator_is_hidden(&self, selector: &str) -> Result<bool> {
        #[derive(Deserialize)]
        struct IsHiddenResponse {
            value: bool,
        }

        let response: IsHiddenResponse = self
            .channel()
            .send(
                "isHidden",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS
                }),
            )
            .await?;

        Ok(response.value)
    }

    /// Returns whether the element is disabled.
    pub(crate) async fn locator_is_disabled(&self, selector: &str) -> Result<bool> {
        #[derive(Deserialize)]
        struct IsDisabledResponse {
            value: bool,
        }

        let response: IsDisabledResponse = self
            .channel()
            .send(
                "isDisabled",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS
                }),
            )
            .await?;

        Ok(response.value)
    }

    /// Returns whether the element is focused (currently has focus).
    ///
    /// This implementation checks if the element is the activeElement in the DOM
    /// using JavaScript evaluation, since Playwright doesn't expose isFocused() at
    /// the protocol level.
    pub(crate) async fn locator_is_focused(&self, selector: &str) -> Result<bool> {
        #[derive(Deserialize)]
        struct EvaluateResult {
            value: serde_json::Value,
        }

        // Use JavaScript to check if the element is the active element
        // The script queries the DOM and returns true/false
        let script = r#"selector => {
                const elements = document.querySelectorAll(selector);
                if (elements.length === 0) return false;
                const element = elements[0];
                return document.activeElement === element;
            }"#;

        let params = serde_json::json!({
            "expression": script,
            "arg": {
                "value": {"s": selector},
                "handles": []
            }
        });

        let result: EvaluateResult = self.channel().send("evaluateExpression", params).await?;

        // Playwright protocol returns booleans as {"b": true} or {"b": false}
        if let serde_json::Value::Object(map) = &result.value
            && let Some(b) = map.get("b").and_then(|v| v.as_bool())
        {
            return Ok(b);
        }

        // Fallback: check if the string representation is "true"
        Ok(result.value.to_string().to_lowercase().contains("true"))
    }

    // Action delegate methods

    /// Clicks the element matching the selector.
    pub(crate) async fn locator_click(
        &self,
        selector: &str,
        options: Option<crate::protocol::ClickOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "selector": selector,
            "strict": true
        });

        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());
            }
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

        self.channel()
            .send_no_result("click", params)
            .await
            .map_err(|e| match e {
                Error::Timeout(msg) => {
                    Error::Timeout(format!("{} (selector: '{}')", msg, selector))
                }
                other => other,
            })
    }

    /// Double clicks the element matching the selector.
    pub(crate) async fn locator_dblclick(
        &self,
        selector: &str,
        options: Option<crate::protocol::ClickOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "selector": selector,
            "strict": true
        });

        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());
            }
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

    /// Fills the element with text.
    pub(crate) async fn locator_fill(
        &self,
        selector: &str,
        text: &str,
        options: Option<crate::protocol::FillOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "selector": selector,
            "value": text,
            "strict": true
        });

        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());
            }
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

    /// Clears the element's value.
    pub(crate) async fn locator_clear(
        &self,
        selector: &str,
        options: Option<crate::protocol::FillOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "selector": selector,
            "value": "",
            "strict": true
        });

        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());
            }
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

    /// Presses a key on the element.
    pub(crate) async fn locator_press(
        &self,
        selector: &str,
        key: &str,
        options: Option<crate::protocol::PressOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "selector": selector,
            "key": key,
            "strict": true
        });

        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());
            }
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

    /// Sets focus on the element matching the selector.
    pub(crate) async fn locator_focus(&self, selector: &str) -> Result<()> {
        self.channel()
            .send_no_result(
                "focus",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS
                }),
            )
            .await
    }

    /// Removes focus from the element matching the selector.
    pub(crate) async fn locator_blur(&self, selector: &str) -> Result<()> {
        self.channel()
            .send_no_result(
                "blur",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS
                }),
            )
            .await
    }

    /// Types text into the element character by character.
    ///
    /// Uses the Playwright protocol `"type"` message (the legacy name for pressSequentially).
    pub(crate) async fn locator_press_sequentially(
        &self,
        selector: &str,
        text: &str,
        options: Option<crate::protocol::PressSequentiallyOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "selector": selector,
            "text": text,
            "strict": true
        });

        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());
            }
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

    /// Returns the inner text of all elements matching the selector.
    pub(crate) async fn locator_all_inner_texts(&self, selector: &str) -> Result<Vec<String>> {
        #[derive(serde::Deserialize)]
        struct EvaluateResult {
            value: serde_json::Value,
        }

        // The Playwright protocol's evalOnSelectorAll requires an `arg` field.
        // We pass a null argument since our expression doesn't use one.
        let params = serde_json::json!({
            "selector": selector,
            "expression": "ee => ee.map(e => e.innerText)",
            "isFunction": true,
            "arg": {
                "value": {"v": "null"},
                "handles": []
            }
        });

        let result: EvaluateResult = self.channel().send("evalOnSelectorAll", params).await?;

        Self::parse_string_array(result.value)
    }

    /// Returns the text content of all elements matching the selector.
    pub(crate) async fn locator_all_text_contents(&self, selector: &str) -> Result<Vec<String>> {
        #[derive(serde::Deserialize)]
        struct EvaluateResult {
            value: serde_json::Value,
        }

        // The Playwright protocol's evalOnSelectorAll requires an `arg` field.
        // We pass a null argument since our expression doesn't use one.
        let params = serde_json::json!({
            "selector": selector,
            "expression": "ee => ee.map(e => e.textContent || '')",
            "isFunction": true,
            "arg": {
                "value": {"v": "null"},
                "handles": []
            }
        });

        let result: EvaluateResult = self.channel().send("evalOnSelectorAll", params).await?;

        Self::parse_string_array(result.value)
    }

    /// Performs a touch-tap on the element matching the selector.
    ///
    /// Sends touch events rather than mouse events. Requires the browser context to be
    /// created with `has_touch: true`.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-tap>
    pub(crate) async fn locator_tap(
        &self,
        selector: &str,
        options: Option<crate::protocol::TapOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "selector": selector,
            "strict": true
        });

        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());
            }
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

    /// Drags the source element onto the target element.
    ///
    /// Both selectors must resolve to elements in this frame.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-drag-to>
    pub(crate) async fn locator_drag_to(
        &self,
        source_selector: &str,
        target_selector: &str,
        options: Option<crate::protocol::DragToOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "source": source_selector,
            "target": target_selector,
            "strict": true
        });

        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());
            }
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

    /// Waits for the element to satisfy a state condition.
    ///
    /// Uses Playwright's `waitForSelector` RPC. The element state defaults to `visible`
    /// if not specified.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-wait-for>
    pub(crate) async fn locator_wait_for(
        &self,
        selector: &str,
        options: Option<crate::protocol::WaitForOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "selector": selector,
            "strict": true
        });

        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());
            }
        } else {
            // Default: wait for visible with default timeout
            params["state"] = serde_json::json!("visible");
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

        // waitForSelector returns an ElementHandle or null — we discard the return value
        let _: serde_json::Value = self.channel().send("waitForSelector", params).await?;
        Ok(())
    }

    /// Evaluates a JavaScript expression in the scope of the element matching the selector.
    ///
    /// The element is passed as the first argument to the expression. This is equivalent
    /// to Playwright's `evalOnSelector` protocol call with `strict: true`.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-evaluate>
    pub(crate) async fn locator_evaluate<T: serde::Serialize>(
        &self,
        selector: &str,
        expression: &str,
        arg: Option<T>,
    ) -> Result<serde_json::Value> {
        let serialized_arg = match arg {
            Some(a) => serialize_argument(&a),
            None => serialize_null(),
        };

        let params = serde_json::json!({
            "selector": selector,
            "expression": expression,
            "isFunction": true,
            "arg": serialized_arg,
            "strict": true
        });

        #[derive(Deserialize)]
        struct EvaluateResult {
            value: serde_json::Value,
        }

        let result: EvaluateResult = self.channel().send("evalOnSelector", params).await?;
        Ok(parse_result(&result.value))
    }

    /// Evaluates a JavaScript expression in the scope of all elements matching the selector.
    ///
    /// The array of all matching elements is passed as the first argument to the expression.
    /// This is equivalent to Playwright's `evalOnSelectorAll` protocol call.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-evaluate-all>
    pub(crate) async fn locator_evaluate_all<T: serde::Serialize>(
        &self,
        selector: &str,
        expression: &str,
        arg: Option<T>,
    ) -> Result<serde_json::Value> {
        let serialized_arg = match arg {
            Some(a) => serialize_argument(&a),
            None => serialize_null(),
        };

        let params = serde_json::json!({
            "selector": selector,
            "expression": expression,
            "isFunction": true,
            "arg": serialized_arg
        });

        #[derive(Deserialize)]
        struct EvaluateResult {
            value: serde_json::Value,
        }

        let result: EvaluateResult = self.channel().send("evalOnSelectorAll", params).await?;
        Ok(parse_result(&result.value))
    }

    /// Parses a Playwright protocol array value into a Vec<String>.
    ///
    /// The Playwright protocol returns arrays as:
    /// `{"a": [{"s": "value1"}, {"s": "value2"}, ...]}`
    fn parse_string_array(value: serde_json::Value) -> Result<Vec<String>> {
        // Playwright protocol wraps arrays in {"a": [...]}
        let array = if let Some(arr) = value.get("a").and_then(|v| v.as_array()) {
            arr.clone()
        } else if let Some(arr) = value.as_array() {
            arr.clone()
        } else {
            return Ok(Vec::new());
        };

        let mut result = Vec::with_capacity(array.len());
        for item in &array {
            // Each string item is wrapped as {"s": "value"} in Playwright protocol
            let s = if let Some(s) = item.get("s").and_then(|v| v.as_str()) {
                s.to_string()
            } else if let Some(s) = item.as_str() {
                s.to_string()
            } else if item.is_null() {
                String::new()
            } else {
                item.to_string()
            };
            result.push(s);
        }
        Ok(result)
    }

    pub(crate) async fn locator_check(
        &self,
        selector: &str,
        options: Option<crate::protocol::CheckOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "selector": selector,
            "strict": true
        });

        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());
            }
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

    pub(crate) async fn locator_uncheck(
        &self,
        selector: &str,
        options: Option<crate::protocol::CheckOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "selector": selector,
            "strict": true
        });

        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());
            }
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

    pub(crate) async fn locator_hover(
        &self,
        selector: &str,
        options: Option<crate::protocol::HoverOptions>,
    ) -> Result<()> {
        let mut params = serde_json::json!({
            "selector": selector,
            "strict": true
        });

        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());
            }
        } else {
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

    pub(crate) async fn locator_input_value(&self, selector: &str) -> Result<String> {
        #[derive(Deserialize)]
        struct InputValueResponse {
            value: String,
        }

        let response: InputValueResponse = self
            .channel()
            .send(
                "inputValue",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS  // Required in Playwright 1.56.1+
                }),
            )
            .await?;

        Ok(response.value)
    }

    pub(crate) async fn locator_select_option(
        &self,
        selector: &str,
        value: crate::protocol::SelectOption,
        options: Option<crate::protocol::SelectOptions>,
    ) -> Result<Vec<String>> {
        #[derive(Deserialize)]
        struct SelectOptionResponse {
            values: Vec<String>,
        }

        let mut params = serde_json::json!({
            "selector": selector,
            "strict": true,
            "options": [value.to_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());
            }
        } else {
            // No options provided, add default timeout (required in Playwright 1.56.1+)
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

        Ok(response.values)
    }

    pub(crate) async fn locator_select_option_multiple(
        &self,
        selector: &str,
        values: Vec<crate::protocol::SelectOption>,
        options: Option<crate::protocol::SelectOptions>,
    ) -> Result<Vec<String>> {
        #[derive(Deserialize)]
        struct SelectOptionResponse {
            values: Vec<String>,
        }

        let values_array: Vec<_> = values.iter().map(|v| v.to_json()).collect();

        let mut params = serde_json::json!({
            "selector": selector,
            "strict": true,
            "options": values_array
        });

        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());
            }
        } else {
            // No options provided, add default timeout (required in Playwright 1.56.1+)
            params["timeout"] = serde_json::json!(crate::DEFAULT_TIMEOUT_MS);
        }

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

        Ok(response.values)
    }

    pub(crate) async fn locator_set_input_files(
        &self,
        selector: &str,
        file: &std::path::PathBuf,
    ) -> Result<()> {
        use base64::{Engine as _, engine::general_purpose};
        use std::io::Read;

        // Read file contents
        let mut file_handle = std::fs::File::open(file)?;
        let mut buffer = Vec::new();
        file_handle.read_to_end(&mut buffer)?;

        // Base64 encode the file contents
        let base64_content = general_purpose::STANDARD.encode(&buffer);

        // Get file name
        let file_name = file
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| crate::error::Error::InvalidArgument("Invalid file path".to_string()))?;

        self.channel()
            .send_no_result(
                "setInputFiles",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS,  // Required in Playwright 1.56.1+
                    "payloads": [{
                        "name": file_name,
                        "buffer": base64_content
                    }]
                }),
            )
            .await
    }

    pub(crate) async fn locator_set_input_files_multiple(
        &self,
        selector: &str,
        files: &[&std::path::PathBuf],
    ) -> Result<()> {
        use base64::{Engine as _, engine::general_purpose};
        use std::io::Read;

        // If empty array, clear the files
        if files.is_empty() {
            return self
                .channel()
                .send_no_result(
                    "setInputFiles",
                    serde_json::json!({
                        "selector": selector,
                        "strict": true,
                        "timeout": crate::DEFAULT_TIMEOUT_MS,  // Required in Playwright 1.56.1+
                        "payloads": []
                    }),
                )
                .await;
        }

        // Read and encode each file
        let mut file_objects = Vec::new();
        for file_path in files {
            let mut file_handle = std::fs::File::open(file_path)?;
            let mut buffer = Vec::new();
            file_handle.read_to_end(&mut buffer)?;

            let base64_content = general_purpose::STANDARD.encode(&buffer);
            let file_name = file_path
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| {
                    crate::error::Error::InvalidArgument("Invalid file path".to_string())
                })?;

            file_objects.push(serde_json::json!({
                "name": file_name,
                "buffer": base64_content
            }));
        }

        self.channel()
            .send_no_result(
                "setInputFiles",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS,  // Required in Playwright 1.56.1+
                    "payloads": file_objects
                }),
            )
            .await
    }

    pub(crate) async fn locator_set_input_files_payload(
        &self,
        selector: &str,
        file: crate::protocol::FilePayload,
    ) -> Result<()> {
        use base64::{Engine as _, engine::general_purpose};

        // Base64 encode the file contents
        let base64_content = general_purpose::STANDARD.encode(&file.buffer);

        self.channel()
            .send_no_result(
                "setInputFiles",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS,
                    "payloads": [{
                        "name": file.name,
                        "mimeType": file.mime_type,
                        "buffer": base64_content
                    }]
                }),
            )
            .await
    }

    pub(crate) async fn locator_set_input_files_payload_multiple(
        &self,
        selector: &str,
        files: &[crate::protocol::FilePayload],
    ) -> Result<()> {
        use base64::{Engine as _, engine::general_purpose};

        // If empty array, clear the files
        if files.is_empty() {
            return self
                .channel()
                .send_no_result(
                    "setInputFiles",
                    serde_json::json!({
                        "selector": selector,
                        "strict": true,
                        "timeout": crate::DEFAULT_TIMEOUT_MS,
                        "payloads": []
                    }),
                )
                .await;
        }

        // Encode each file
        let file_objects: Vec<_> = files
            .iter()
            .map(|file| {
                let base64_content = general_purpose::STANDARD.encode(&file.buffer);
                serde_json::json!({
                    "name": file.name,
                    "mimeType": file.mime_type,
                    "buffer": base64_content
                })
            })
            .collect();

        self.channel()
            .send_no_result(
                "setInputFiles",
                serde_json::json!({
                    "selector": selector,
                    "strict": true,
                    "timeout": crate::DEFAULT_TIMEOUT_MS,
                    "payloads": file_objects
                }),
            )
            .await
    }

    /// Returns the ARIA accessibility tree snapshot for the element matching the selector.
    ///
    /// The snapshot is returned as a YAML-formatted string describing the accessible roles,
    /// names, and properties of the element and its descendants.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-aria-snapshot>
    pub(crate) async fn locator_aria_snapshot(&self, selector: &str) -> Result<String> {
        self.aria_snapshot_raw(selector, crate::DEFAULT_TIMEOUT_MS)
            .await
    }

    pub(crate) async fn aria_snapshot_raw(&self, selector: &str, timeout: f64) -> Result<String> {
        #[derive(Deserialize)]
        struct AriaSnapshotResponse {
            snapshot: String,
        }

        let response: AriaSnapshotResponse = self
            .channel()
            .send(
                "ariaSnapshot",
                serde_json::json!({
                    "selector": selector,
                    "timeout": timeout
                }),
            )
            .await?;

        Ok(response.snapshot)
    }

    /// Highlights the element matching the selector in the browser (debug tool).
    ///
    /// Draws a colored overlay over the matched element for a short period.
    /// This is a visual debugging tool and does not affect test assertions.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-highlight>
    pub(crate) async fn locator_highlight(&self, selector: &str) -> Result<()> {
        self.channel()
            .send_no_result(
                "highlight",
                serde_json::json!({
                    "selector": selector
                }),
            )
            .await
    }

    /// Evaluates JavaScript expression in the frame context (without return value).
    ///
    /// This is used internally by Page.evaluate().
    pub(crate) async fn frame_evaluate_expression(&self, expression: &str) -> Result<()> {
        let params = serde_json::json!({
            "expression": expression,
            "arg": {
                "value": {"v": "null"},
                "handles": []
            }
        });

        let _: serde_json::Value = self.channel().send("evaluateExpression", params).await?;
        Ok(())
    }

    /// Evaluates JavaScript expression and returns the result as a String.
    ///
    /// The return value is automatically converted to a string representation.
    ///
    /// # Arguments
    ///
    /// * `expression` - JavaScript code to evaluate
    ///
    /// # Returns
    ///
    /// The result as a String
    pub(crate) async fn frame_evaluate_expression_value(&self, expression: &str) -> Result<String> {
        let params = serde_json::json!({
            "expression": expression,
            "arg": {
                "value": {"v": "null"},
                "handles": []
            }
        });

        #[derive(Deserialize)]
        struct EvaluateResult {
            value: serde_json::Value,
        }

        let result: EvaluateResult = self.channel().send("evaluateExpression", params).await?;

        // Playwright protocol returns values in a wrapped format:
        // - String: {"s": "value"}
        // - Number: {"n": 123}
        // - Boolean: {"b": true}
        // - Null: {"v": "null"}
        // - Undefined: {"v": "undefined"}
        match &result.value {
            Value::Object(map) => {
                if let Some(s) = map.get("s").and_then(|v| v.as_str()) {
                    // String value
                    Ok(s.to_string())
                } else if let Some(n) = map.get("n") {
                    // Number value
                    Ok(n.to_string())
                } else if let Some(b) = map.get("b").and_then(|v| v.as_bool()) {
                    // Boolean value
                    Ok(b.to_string())
                } else if let Some(v) = map.get("v").and_then(|v| v.as_str()) {
                    // null or undefined
                    Ok(v.to_string())
                } else {
                    // Unknown format, return JSON
                    Ok(result.value.to_string())
                }
            }
            _ => {
                // Fallback for unexpected formats
                Ok(result.value.to_string())
            }
        }
    }

    /// Evaluates a JavaScript expression in the frame context with optional arguments.
    ///
    /// Executes the provided JavaScript expression within the frame'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`
    ///
    /// # Example
    ///
    /// ```ignore
    /// use serde_json::json;
    /// 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 frame = page.main_frame().await?;
    ///
    ///     // Evaluate without arguments
    ///     let result = frame.evaluate::<()>("1 + 1", None).await?;
    ///
    ///     // Evaluate with argument
    ///     let arg = json!({"x": 5, "y": 3});
    ///     let result = frame.evaluate::<serde_json::Value>("(arg) => arg.x + arg.y", Some(&arg)).await?;
    ///     assert_eq!(result, json!(8));
    ///     Ok(())
    /// }
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-evaluate>
    pub async fn evaluate<T: serde::Serialize>(
        &self,
        expression: &str,
        arg: Option<&T>,
    ) -> Result<Value> {
        // Serialize the argument
        let serialized_arg = match arg {
            Some(a) => serialize_argument(a),
            None => serialize_null(),
        };

        // Build the parameters
        let params = serde_json::json!({
            "expression": expression,
            "arg": serialized_arg
        });

        // Send the evaluateExpression command
        #[derive(Deserialize)]
        struct EvaluateResult {
            value: serde_json::Value,
        }

        let result: EvaluateResult = self.channel().send("evaluateExpression", params).await?;

        // Deserialize the result using parse_result
        Ok(parse_result(&result.value))
    }

    /// Adds a `<style>` tag into the page with the desired content.
    ///
    /// # Arguments
    ///
    /// * `options` - Style tag options (content, url, or path)
    ///
    /// At least one of `content`, `url`, or `path` must be specified.
    ///
    /// # 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?;
    /// # let frame = page.main_frame().await?;
    /// use playwright_rs::protocol::AddStyleTagOptions;
    ///
    /// // With inline CSS
    /// frame.add_style_tag(
    ///     AddStyleTagOptions::builder()
    ///         .content("body { background-color: red; }")
    ///         .build()
    /// ).await?;
    ///
    /// // With URL
    /// frame.add_style_tag(
    ///     AddStyleTagOptions::builder()
    ///         .url("https://example.com/style.css")
    ///         .build()
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-add-style-tag>
    pub async fn add_style_tag(
        &self,
        options: crate::protocol::page::AddStyleTagOptions,
    ) -> Result<Arc<crate::protocol::ElementHandle>> {
        // Validate that at least one option is provided
        options.validate()?;

        // Build protocol parameters
        let mut params = serde_json::json!({});

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

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

        if let Some(path) = &options.path {
            // Read file content and send as content
            let css_content = tokio::fs::read_to_string(path).await.map_err(|e| {
                Error::InvalidArgument(format!("Failed to read CSS file '{}': {}", path, e))
            })?;
            params["content"] = serde_json::json!(css_content);
        }

        #[derive(Deserialize)]
        struct AddStyleTagResponse {
            element: serde_json::Value,
        }

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

        let guid = response.element["guid"].as_str().ok_or_else(|| {
            Error::ProtocolError("Element GUID missing in addStyleTag response".to_string())
        })?;

        let connection = self.base.connection();
        let handle: crate::protocol::ElementHandle = connection
            .get_typed::<crate::protocol::ElementHandle>(guid)
            .await?;

        Ok(Arc::new(handle))
    }

    /// Dispatches a DOM event on the element matching the selector.
    ///
    /// Unlike clicking or typing, `dispatch_event` directly sends the event without
    /// performing any actionability checks. It still waits for the element to be present
    /// in the DOM.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-dispatch-event>
    pub(crate) async fn locator_dispatch_event(
        &self,
        selector: &str,
        type_: &str,
        event_init: Option<serde_json::Value>,
    ) -> Result<()> {
        // Serialize eventInit using Playwright's protocol argument format.
        // If None, use {"value": {"v": "undefined"}, "handles": []}.
        let event_init_serialized = match event_init {
            Some(v) => serialize_argument(&v),
            None => serde_json::json!({"value": {"v": "undefined"}, "handles": []}),
        };

        let params = serde_json::json!({
            "selector": selector,
            "type": type_,
            "eventInit": event_init_serialized,
            "strict": true,
            "timeout": crate::DEFAULT_TIMEOUT_MS
        });

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

    /// Returns the bounding box of the element matching the selector, or None if not visible.
    ///
    /// The bounding box is returned in pixels. If the element is not visible (e.g.,
    /// `display: none`), returns `None`.
    ///
    /// Implemented via ElementHandle because `boundingBox` is an ElementHandle-level
    /// protocol method, not a Frame-level method.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-bounding-box>
    pub(crate) async fn locator_bounding_box(
        &self,
        selector: &str,
    ) -> Result<Option<crate::protocol::locator::BoundingBox>> {
        let element = self.query_selector(selector).await?;
        match element {
            Some(handle) => handle.bounding_box().await,
            None => Ok(None),
        }
    }

    /// Scrolls the element into view if it is not already visible in the viewport.
    ///
    /// Implemented via ElementHandle because `scrollIntoViewIfNeeded` is an
    /// ElementHandle-level protocol method, not a Frame-level method.
    ///
    /// See: <https://playwright.dev/docs/api/class-locator#locator-scroll-into-view-if-needed>
    pub(crate) async fn locator_scroll_into_view_if_needed(&self, selector: &str) -> Result<()> {
        let element = self.query_selector(selector).await?;
        match element {
            Some(handle) => handle.scroll_into_view_if_needed().await,
            None => Err(crate::error::Error::ElementNotFound(format!(
                "Element not found: {}",
                selector
            ))),
        }
    }

    /// Calls the Playwright server's `expect` method on the Frame channel.
    ///
    /// Used for assertions that are auto-retried server-side (e.g. `to.match.aria`).
    /// Returns `Ok(())` when the assertion passes, or an error containing the
    /// server-supplied `errorMessage` when the assertion fails or times out.
    pub(crate) async fn frame_expect(
        &self,
        selector: &str,
        expression: &str,
        expected_value: serde_json::Value,
        is_not: bool,
        timeout_ms: f64,
    ) -> Result<()> {
        #[derive(serde::Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct ExpectResult {
            matches: bool,
            #[serde(default)]
            timed_out: Option<bool>,
            #[serde(default)]
            error_message: Option<String>,
        }

        let params = serde_json::json!({
            "selector": selector,
            "expression": expression,
            "expectedValue": expected_value,
            "isNot": is_not,
            "timeout": timeout_ms
        });

        let result: ExpectResult = self.channel().send("expect", params).await?;

        if result.matches != is_not {
            Ok(())
        } else {
            let msg = result
                .error_message
                .unwrap_or_else(|| format!("Assertion '{}' failed", expression));
            if result.timed_out == Some(true) {
                Err(crate::error::Error::AssertionTimeout(msg))
            } else {
                Err(crate::error::Error::AssertionFailed(msg))
            }
        }
    }

    /// Adds a `<script>` tag into the frame with the desired content.
    ///
    /// # Arguments
    ///
    /// * `options` - Script tag options (content, url, or path)
    ///
    /// At least one of `content`, `url`, or `path` must be specified.
    ///
    /// See: <https://playwright.dev/docs/api/class-frame#frame-add-script-tag>
    pub async fn add_script_tag(
        &self,
        options: crate::protocol::page::AddScriptTagOptions,
    ) -> Result<Arc<crate::protocol::ElementHandle>> {
        // Validate that at least one option is provided
        options.validate()?;

        // Build protocol parameters
        let mut params = serde_json::json!({});

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

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

        if let Some(path) = &options.path {
            // Read file content and send as content
            let js_content = tokio::fs::read_to_string(path).await.map_err(|e| {
                Error::InvalidArgument(format!("Failed to read JS file '{}': {}", path, e))
            })?;
            params["content"] = serde_json::json!(js_content);
        }

        if let Some(type_) = &options.type_ {
            params["type"] = serde_json::json!(type_);
        }

        #[derive(Deserialize)]
        struct AddScriptTagResponse {
            element: serde_json::Value,
        }

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

        let guid = response.element["guid"].as_str().ok_or_else(|| {
            Error::ProtocolError("Element GUID missing in addScriptTag response".to_string())
        })?;

        let connection = self.base.connection();
        let handle: crate::protocol::ElementHandle = connection
            .get_typed::<crate::protocol::ElementHandle>(guid)
            .await?;

        Ok(Arc::new(handle))
    }
}

impl ChannelOwner for Frame {
    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 frame's URL when navigation occurs (including hash changes)
                if let Some(url_value) = params.get("url")
                    && let Some(url_str) = url_value.as_str()
                {
                    // Update frame's URL
                    if let Ok(mut url) = self.url.write() {
                        *url = url_str.to_string();
                    }
                }
                // Forward frameNavigated event to page-level handlers
                let self_clone = self.clone();
                tokio::spawn(async move {
                    if let Some(page) = self_clone.page() {
                        page.trigger_framenavigated_event(self_clone).await;
                    }
                });
            }
            "loadstate" => {
                // Track which load states are active.
                // When "load" is added, fire page-level on_load handlers.
                if let Some(add) = params.get("add").and_then(|v| v.as_str())
                    && add == "load"
                {
                    let self_clone = self.clone();
                    tokio::spawn(async move {
                        if let Some(page) = self_clone.page() {
                            page.trigger_load_event().await;
                        }
                    });
                }
            }
            "detached" => {
                // Mark this frame as detached
                if let Ok(mut flag) = self.is_detached.write() {
                    *flag = true;
                }
            }
            _ => {
                // Other frame events not yet handled
            }
        }
    }

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

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

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

/// Simple glob pattern matching for URL patterns.
///
/// Supports `*` (matches any characters except `/`) and `**` (matches any characters including `/`).
/// This matches Playwright's URL glob pattern behavior.
fn glob_match(pattern: &str, text: &str) -> bool {
    let regex_str = pattern
        .replace('.', "\\.")
        .replace("**", "\x00") // placeholder for **
        .replace('*', "[^/]*")
        .replace('\x00', ".*"); // restore ** as .*
    let regex_str = format!("^{}$", regex_str);
    regex::Regex::new(&regex_str)
        .map(|re| re.is_match(text))
        .unwrap_or(false)
}