arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/phone-input/phone-input.tsx` & `.module.css`
//!
//! P4 Component #10: `phone-input`
//!
//! - Phone number field with a country picker, value emitted as E.164:
//!   - Compact country table (46 countries) carrying dial codes, national format patterns
//!     (`#` is a digit), typed trunk prefixes, example numbers, and shared-dial area codes
//!     (Canada inside `+1`). No metadata dependency; formatting is pattern-driven.
//!   - The number formats as it is typed (`(###) ###-####`), with a faint guide painting the
//!     rest of the country's example shape after the typed digits, and a `success` check that
//!     pops on `motion.spring.snappy` once the national digit count matches the pattern.
//!   - The country button morphs into a searchable list: one surface whose width, height, and
//!     corners spring between the closed trigger (`17px` radius) and the open panel
//!     (`22px` radius, `340px` max) on `physical(0.4, 0)` grow / `physical(0.32, 0)` shrink
//!     springs, with a gliding highlight pill and `Suggested` / `All countries` sections.
//!   - Typing `+` in the number opens the picker seeded with a calling-code search; pasting an
//!     international number (`+44 (0)7911 123456`, `0044 …`) picks its own country; the flag
//!     and dial roll in the direction of the list move.
//!   - Validation reads the national digit count against the pattern capacities (`empty`,
//!     `incomplete`, `valid`, `too-long`) and reports `Numbers in <country> have N digits`.
//!
//! Known deviations from upstream:
//! - No caret editing in the number field: the number is self-painted text (no system text
//!   input), so editing appends digits at the end and `Backspace` deletes the last digit;
//!   paste replaces the draft with a whole number or appends a fragment.
//! - The built-in validation message shows while the field is not focused (upstream latches it
//!   after the first blur); there is no `aria-live` announcement region.
//! - The web-only `name` hidden form field is omitted; the flag renders as regional-indicator
//!   letters when the platform lacks color-emoji glyphs (same fallback as upstream).
//! - Keyboard moves in the country list do not scroll an out-of-viewport active row into view
//!   yet (the list scrolls by wheel); selection itself works for any row.

use std::{cell::RefCell, rc::Rc};

use arc_motion::{
    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, arc_spring_with_options,
    arc_transition, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{
    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix,
};
use gpui_kit::{
    AnyElement, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement, KeyDownEvent,
    MouseButton, MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role,
    SharedString, Styled, TestSupportExt as _, Window,
    assets::IconName,
    base::{Button as BaseButton, StyledExt as _},
    canvas,
    component::{
        Icon,
        input::{Input as KitInput, InputState},
    },
    deferred, div, point,
    prelude::*,
    px,
};

use super::field_message::render_field_message;

type PhoneValueChangeHandler = Rc<dyn Fn(&PhoneValueEvent, &mut Window, &mut App)>;
type PhoneCountryChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;

/// One surface for both picker states: closed trigger radius (`8px`), open panel radius (`10px`).
pub const PHONE_CLOSED_RADIUS: f32 = 8.0;
pub const PHONE_OPEN_RADIUS: f32 = 10.0;
/// Max width (`310px`) of the open country panel.
pub const PHONE_PANEL_MAX: f32 = 310.0;
/// Page size (`8` rows) for `PageUp` / `PageDown` in the country list.
pub const PHONE_PAGE: usize = 8;
/// Max height (`240px`) of the country list viewport.
pub const PHONE_LIST_MAX_H: f32 = 240.0;

/// The panel springs open on `physical(0.4, 0)` and closed on `physical(0.32, 0)`.
pub const fn phone_grow_spring() -> SpringSpec {
    SpringSpec::visual(0.4, 0.0)
}
pub const fn phone_shrink_spring() -> SpringSpec {
    SpringSpec::visual(0.32, 0.0)
}
/// Gliding highlights, chevron rotation, and flag rolls run on `physical(0.28, 0)`.
pub const fn phone_glide_spring() -> SpringSpec {
    SpringSpec::visual(0.28, 0.0)
}
/// The panel width morphs on `physical(0.42, 0)` (`WIDTH`).
pub const fn phone_width_spring() -> SpringSpec {
    SpringSpec::visual(0.42, 0.0)
}

/// One country entry: ISO code, name, calling code, national format patterns, typed trunk
/// prefix, a realistic example number, and optional shared-dial area codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PhoneCountry {
    pub iso: &'static str,
    pub name: &'static str,
    pub dial: &'static str,
    pub patterns: &'static [&'static str],
    pub trunk: &'static str,
    pub example: &'static str,
    pub area_codes: &'static [&'static str],
}

/// Most countries type a `0` trunk prefix before the national number
/// (upstream `country(..., trunk = "0")` default).
const fn country(
    iso: &'static str,
    name: &'static str,
    dial: &'static str,
    patterns: &'static [&'static str],
    example: &'static str,
) -> PhoneCountry {
    PhoneCountry {
        iso,
        name,
        dial,
        patterns,
        trunk: "0",
        example,
        area_codes: &[],
    }
}

/// Countries whose numbers carry no trunk prefix.
const fn country_flat(
    iso: &'static str,
    name: &'static str,
    dial: &'static str,
    patterns: &'static [&'static str],
    example: &'static str,
) -> PhoneCountry {
    PhoneCountry {
        iso,
        name,
        dial,
        patterns,
        trunk: "",
        example,
        area_codes: &[],
    }
}

/// Countries with a typed trunk prefix that is not `0` (NANP members type `1`).
const fn country_trunk(
    iso: &'static str,
    name: &'static str,
    dial: &'static str,
    patterns: &'static [&'static str],
    example: &'static str,
    trunk: &'static str,
) -> PhoneCountry {
    PhoneCountry {
        iso,
        name,
        dial,
        patterns,
        trunk,
        example,
        area_codes: &[],
    }
}

/// Canada shares the `+1` dial; area codes pick it inside `phone_parse_number`.
const CA_AREA_CODES: &[&str] = &[
    "204", "226", "236", "249", "250", "263", "289", "306", "343", "354", "365", "367", "368",
    "382", "387", "403", "416", "418", "428", "431", "437", "438", "450", "468", "474", "506",
    "514", "519", "548", "579", "581", "584", "587", "604", "613", "639", "647", "672", "683",
    "705", "709", "742", "753", "778", "780", "782", "807", "819", "825", "867", "873", "879",
    "902", "905",
];

/// The compact country table (upstream `PHONE_COUNTRIES`, 46 entries).
pub static PHONE_COUNTRIES: &[PhoneCountry] = &[
    country_trunk(
        "US",
        "United States",
        "1",
        &["(###) ###-####"],
        "2015550123",
        "1",
    ),
    PhoneCountry {
        iso: "CA",
        name: "Canada",
        dial: "1",
        patterns: &["(###) ###-####"],
        trunk: "1",
        example: "5065550123",
        area_codes: CA_AREA_CODES,
    },
    country_flat("MX", "Mexico", "52", &["## #### ####"], "2221234567"),
    country(
        "BR",
        "Brazil",
        "55",
        &["(##) ####-####", "(##) #####-####"],
        "11961234567",
    ),
    country("AR", "Argentina", "54", &["## ####-####"], "1123456789"),
    country_flat("CO", "Colombia", "57", &["### ### ####"], "3211234567"),
    country_flat("CL", "Chile", "56", &["# #### ####"], "221234567"),
    country_flat("PE", "Peru", "51", &["### ### ###"], "912345678"),
    country("GB", "United Kingdom", "44", &["#### ######"], "7400123456"),
    country("IE", "Ireland", "353", &["## ### ####"], "850123456"),
    country("FR", "France", "33", &["# ## ## ## ##"], "612345678"),
    country(
        "DE",
        "Germany",
        "49",
        &["### #######", "### ########"],
        "15123456789",
    ),
    country_flat("ES", "Spain", "34", &["### ## ## ##"], "612345678"),
    country_flat(
        "IT",
        "Italy",
        "39",
        &["### ### ###", "### ### ####"],
        "3123456789",
    ),
    country_flat("PT", "Portugal", "351", &["### ### ###"], "912345678"),
    country_flat("NL", "Netherlands", "31", &["# ########"], "612345678"),
    country_flat("BE", "Belgium", "32", &["### ## ## ##"], "470123456"),
    country_flat("CH", "Switzerland", "41", &["## ### ## ##"], "781234567"),
    country(
        "AT",
        "Austria",
        "43",
        &["### #######", "### ########"],
        "6641234567",
    ),
    country("SE", "Sweden", "46", &["## ### ## ##"], "701234567"),
    country_flat("NO", "Norway", "47", &["### ## ###"], "40612345"),
    country_flat("DK", "Denmark", "45", &["## ## ## ##"], "32123456"),
    country(
        "FI",
        "Finland",
        "358",
        &["## ### ####", "## ### #####"],
        "412345678",
    ),
    country_flat("PL", "Poland", "48", &["### ### ###"], "512345678"),
    country_flat("CZ", "Czechia", "420", &["### ### ###"], "601123456"),
    country_flat("GR", "Greece", "30", &["### ### ####"], "6912345678"),
    country("UA", "Ukraine", "380", &["## ### ## ##"], "501234567"),
    country("TR", "Turkey", "90", &["### ### ## ##"], "5012345678"),
    country("IL", "Israel", "972", &["##-###-####"], "502345678"),
    country(
        "AE",
        "United Arab Emirates",
        "971",
        &["## ### ####"],
        "501234567",
    ),
    country("SA", "Saudi Arabia", "966", &["## ### ####"], "512345678"),
    country("EG", "Egypt", "20", &["### ### ####"], "1001234567"),
    country("NG", "Nigeria", "234", &["### ### ####"], "8021234567"),
    country("KE", "Kenya", "254", &["### ######"], "712123456"),
    country("ZA", "South Africa", "27", &["## ### ####"], "711234567"),
    country("IN", "India", "91", &["#####-#####"], "8123456789"),
    country("PK", "Pakistan", "92", &["### #######"], "3012345678"),
    country("CN", "China", "86", &["### #### ####"], "13123456789"),
    country("JP", "Japan", "81", &["##-####-####"], "9012345678"),
    country(
        "KR",
        "South Korea",
        "82",
        &["##-###-####", "##-####-####"],
        "1020000000",
    ),
    country("TW", "Taiwan", "886", &["### ### ###"], "912345678"),
    country_flat("HK", "Hong Kong", "852", &["#### ####"], "51234567"),
    country_flat("SG", "Singapore", "65", &["#### ####"], "81234567"),
    country("PH", "Philippines", "63", &["### ### ####"], "9051234567"),
    country(
        "ID",
        "Indonesia",
        "62",
        &["###-###-####", "###-####-####", "###-####-#####"],
        "81234567890",
    ),
    country("TH", "Thailand", "66", &["## ### ####"], "812345678"),
    country("VN", "Vietnam", "84", &["## ### ## ##"], "912345678"),
    country("AU", "Australia", "61", &["### ### ###"], "412345678"),
    country(
        "NZ",
        "New Zealand",
        "64",
        &["# ### ####", "## ### ####", "## #### ####"],
        "211234567",
    ),
];

/// Resolves a country by ISO code.
pub fn phone_country_by_iso(iso: &str) -> Option<&'static PhoneCountry> {
    PHONE_COUNTRIES.iter().find(|entry| entry.iso == iso)
}

pub fn phone_only_digits(text: &str) -> String {
    text.chars().filter(|c| c.is_ascii_digit()).collect()
}

/// Regional indicator letters; platforms without flag glyphs show the two letters.
pub fn phone_flag_of(iso: &str) -> String {
    iso.to_uppercase()
        .chars()
        .map(|c| char::from_u32(0x1f1e6 + (u32::from(c) - 65)).unwrap_or(c))
        .collect()
}

/// `(typed trunk, national rest)` — a typed trunk prefix earns its own room.
pub fn phone_split_trunk<'a>(entry: &PhoneCountry, digits: &'a str) -> (&'a str, &'a str) {
    if !entry.trunk.is_empty() && digits.starts_with(entry.trunk) {
        (entry.trunk, &digits[entry.trunk.len()..])
    } else {
        ("", digits)
    }
}

/// Digit capacity of one pattern (`#` count).
pub fn phone_capacity(pattern: &str) -> usize {
    pattern.matches('#').count()
}

/// Valid national lengths, i.e. the digit capacities of the patterns.
pub fn phone_lengths(entry: &PhoneCountry) -> Vec<usize> {
    entry.patterns.iter().map(|p| phone_capacity(p)).collect()
}

/// Caps digits so a typed trunk prefix plus the longest pattern still fit.
pub fn phone_cap_digits(entry: &PhoneCountry, digits: &str) -> String {
    let trunk_len = phone_split_trunk(entry, digits).0.len();
    let max_len = phone_lengths(entry).into_iter().max().unwrap_or(0);
    digits.chars().take(trunk_len + max_len).collect()
}

/// Applies a format pattern: separators only print while digits follow and consume no digit,
/// and digits beyond the pattern are appended as-is.
pub fn phone_apply_pattern(digits: &str, pattern: &str) -> String {
    let mut out = String::new();
    let mut chars = digits.chars().peekable();
    for ch in pattern.chars() {
        if chars.peek().is_none() {
            break;
        }
        if ch == '#' {
            if let Some(d) = chars.next() {
                out.push(d);
            }
        } else {
            out.push(ch);
        }
    }
    let rest: String = chars.collect();
    out + &rest
}

/// Picks the pattern whose capacity first covers `length`, else the longest pattern.
pub fn phone_pattern_for(entry: &PhoneCountry, length: usize) -> &str {
    entry
        .patterns
        .iter()
        .find(|p| phone_capacity(p) >= length)
        .copied()
        .unwrap_or_else(|| entry.patterns.last().expect("patterns is non-empty"))
}

/// Formats national digits as typed, keeping a typed trunk prefix:
/// `"07911123456"` in the UK reads `"07911 123456"`.
pub fn phone_format_national(entry: &PhoneCountry, digits: &str) -> String {
    let (trunk, rest) = phone_split_trunk(entry, digits);
    let pattern = phone_pattern_for(entry, rest.len());
    let body = phone_apply_pattern(rest, pattern);
    if trunk.is_empty() {
        return body;
    }
    if rest.is_empty() {
        return trunk.to_string();
    }
    let gap = if pattern.starts_with('#') { "" } else { " " };
    format!("{trunk}{gap}{body}")
}

/// Validation status read from the national digit count against the pattern capacities.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PhoneStatus {
    Empty,
    Incomplete,
    Valid,
    TooLong,
}

pub fn phone_status_of(entry: &PhoneCountry, digits: &str) -> PhoneStatus {
    let length = phone_split_trunk(entry, digits).1.len();
    let lengths = phone_lengths(entry);
    if length == 0 {
        return PhoneStatus::Empty;
    }
    if lengths.contains(&length) {
        return PhoneStatus::Valid;
    }
    if length > lengths.iter().max().copied().unwrap_or(0) {
        PhoneStatus::TooLong
    } else {
        PhoneStatus::Incomplete
    }
}

/// E.164 encoding: `+<dial><national>` (empty when there are no national digits).
pub fn phone_to_e164(entry: &PhoneCountry, digits: &str) -> String {
    let rest = phone_split_trunk(entry, digits).1;
    if rest.is_empty() {
        String::new()
    } else {
        format!("+{}{}", entry.dial, rest)
    }
}

/// Reads `"+44 (0)7911 123456"`, `"0044 7911…"`, or `"+14165550123"` into a country and
/// national digits. Longest calling code wins; shared dials resolve through area codes.
pub fn phone_parse_number(input: &str) -> Option<(&'static PhoneCountry, String)> {
    let trimmed = input.trim();
    let all_digits = phone_only_digits(trimmed);
    let digits = if trimmed.starts_with('+') {
        all_digits
    } else if trimmed.starts_with("00") && all_digits.len() > 2 {
        all_digits[2..].to_string()
    } else {
        return None;
    };
    for size in [3usize, 2, 1] {
        if digits.len() < size {
            continue;
        }
        let dial = &digits[..size];
        let matches: Vec<&PhoneCountry> =
            PHONE_COUNTRIES.iter().filter(|e| e.dial == dial).collect();
        if matches.is_empty() {
            continue;
        }
        let mut rest = digits[size..].to_string();
        let entry = matches
            .iter()
            .find(|item| item.area_codes.iter().any(|code| rest.starts_with(code)))
            .or_else(|| matches.iter().find(|item| item.area_codes.is_empty()))
            .or_else(|| matches.first())
            .copied()
            .expect("matches is non-empty");
        // "+44 (0)7911…" carries a trunk zero it should not; drop it when the rest is still a
        // full number without it.
        let min_len = phone_lengths(entry).into_iter().min().unwrap_or(0);
        if !entry.trunk.is_empty()
            && rest.starts_with(entry.trunk)
            && rest.len() - entry.trunk.len() >= min_len
        {
            rest = rest[entry.trunk.len()..].to_string();
        }
        return Some((entry, phone_cap_digits(entry, &rest)));
    }
    None
}

/// Formats an E.164 number for display (`"+44 7911 123456"`); returns the input unreadable.
pub fn phone_format_e164(e164: &str) -> String {
    match phone_parse_number(e164) {
        Some((entry, national)) => {
            format!(
                "+{} {}",
                entry.dial,
                phone_format_national(entry, &national)
            )
        }
        None => e164.to_string(),
    }
}

/// Picker search: digits match calling codes (either direction), letters match names/ISO codes.
pub fn phone_matches_query(entry: &PhoneCountry, needle: &str) -> bool {
    if needle.is_empty() {
        return true;
    }
    let digits = phone_only_digits(needle);
    let is_dial_query = !digits.is_empty()
        && needle.chars().all(|c| {
            c.is_ascii_digit() || c == '+' || c == ' ' || c == '(' || c == ')' || c == '-'
        });
    if is_dial_query {
        return entry.dial.starts_with(&digits) || digits.starts_with(entry.dial);
    }
    if needle.chars().all(|c| c == '+') {
        return true;
    }
    entry.name.to_lowercase().contains(needle) || entry.iso.to_lowercase() == needle
}

/// Country position in the name-sorted order, used to roll the flag toward the list move.
fn phone_order_of(iso: &str) -> usize {
    let mut sorted: Vec<&PhoneCountry> = PHONE_COUNTRIES.iter().collect();
    sorted.sort_by_key(|entry| entry.name);
    sorted
        .iter()
        .position(|entry| entry.iso == iso)
        .unwrap_or(0)
}

/// Details snapshot passed alongside the E.164 value in [`PhoneValueEvent`].
#[derive(Clone, Debug, PartialEq)]
pub struct PhoneInputDetails {
    pub country: &'static PhoneCountry,
    pub formatted: String,
    pub status: PhoneStatus,
    pub valid: bool,
}

/// Single event for [`PhoneInput::on_value_change`]: the E.164 number (empty when there are no
/// digits) plus its parsed details.
#[derive(Clone, Debug, PartialEq)]
pub struct PhoneValueEvent {
    pub value: String,
    pub details: PhoneInputDetails,
}

#[derive(Clone)]
struct PhoneInternal {
    uncontrolled_iso: SharedString,
    digits: String,
    seen_value: Option<String>,
    source_changed_at_secs: f64,
    roll_dir: i8,
    menu_open: bool,
    active_iso: Option<SharedString>,
    highlight_seeded: bool,
    control_hovered: bool,
    trigger_hovered: bool,
    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    control_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    query_input: Entity<InputState>,
    focus_handle: FocusHandle,
}

impl PhoneInternal {
    fn new(now: f64, window: &mut Window, cx: &mut App) -> Self {
        let query_input = cx.new(|cx| InputState::new(window, cx).placeholder("Country or code"));
        Self {
            uncontrolled_iso: "US".into(),
            digits: String::new(),
            seen_value: None,
            source_changed_at_secs: now - 10.0,
            roll_dir: 1,
            menu_open: false,
            active_iso: None,
            highlight_seeded: false,
            control_hovered: false,
            trigger_hovered: false,
            trigger_bounds: Rc::new(RefCell::new(None)),
            panel_bounds: Rc::new(RefCell::new(None)),
            control_bounds: Rc::new(RefCell::new(None)),
            query_input,
            focus_handle: cx.focus_handle(),
        }
    }
}

fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
    let rad = angle_deg.to_radians();
    let cos_a = rad.cos();
    let sin_a = rad.sin();
    let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
    let mut builder = PathBuilder::stroke(px(1.75));
    for (i, (lx, ly)) in pts.iter().enumerate() {
        let rx = cx + lx * cos_a - ly * sin_a;
        let ry = cy + lx * sin_a + ly * cos_a;
        let p = point(px(rx), px(ry));
        if i == 0 {
            builder.move_to(p);
        } else {
            builder.line_to(p);
        }
    }
    if let Ok(path) = builder.build() {
        window.paint_path(path, color);
    }
}

fn paint_scaled_check(
    cx: f32,
    cy: f32,
    scale: f32,
    opacity: f32,
    color: Hsla,
    window: &mut Window,
) {
    if opacity <= 0.01 {
        return;
    }
    let pts = [(-4.0_f32, 0.2_f32), (-1.4, 3.3), (4.8, -3.2)];
    let mut builder = PathBuilder::stroke(px(2.0));
    for (i, (lx, ly)) in pts.iter().enumerate() {
        let p = point(px(cx + lx * scale), px(cy + ly * scale));
        if i == 0 {
            builder.move_to(p);
        } else {
            builder.line_to(p);
        }
    }
    let c = Hsla {
        a: color.a * opacity.clamp(0.0, 1.0),
        ..color
    };
    if let Ok(path) = builder.build() {
        window.paint_path(path, c);
    }
}

/// Arc `PhoneInput` — phone field with a morphing country picker, live formatting with a faint
/// shape guide, and E.164 output.
#[derive(IntoElement)]
pub struct PhoneInput {
    id: ElementId,
    label: SharedString,
    hide_label: bool,
    value: Option<String>,
    default_value: Option<String>,
    country: Option<SharedString>,
    default_country: SharedString,
    countries: Vec<SharedString>,
    preferred_countries: Vec<SharedString>,
    description: Option<SharedString>,
    error: Option<SharedString>,
    validate: bool,
    disabled: bool,
    width: Option<Pixels>,
    on_value_change: Option<PhoneValueChangeHandler>,
    on_country_change: Option<PhoneCountryChangeHandler>,
}

impl PhoneInput {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            hide_label: false,
            value: None,
            default_value: None,
            country: None,
            default_country: "US".into(),
            countries: Vec::new(),
            preferred_countries: vec!["US".into(), "CA".into(), "GB".into()],
            description: None,
            error: None,
            validate: true,
            disabled: false,
            width: None,
            on_value_change: None,
            on_country_change: None,
        }
    }

    pub fn hide_label(mut self, hide: bool) -> Self {
        self.hide_label = hide;
        self
    }

    /// The number in E.164 (`"+14155550132"`); an empty string clears the field.
    pub fn value(mut self, e164: impl Into<String>) -> Self {
        self.value = Some(e164.into());
        self
    }

    pub fn default_value(mut self, e164: impl Into<String>) -> Self {
        self.default_value = Some(e164.into());
        self
    }

    pub fn country(mut self, iso: impl Into<SharedString>) -> Self {
        self.country = Some(iso.into());
        self
    }

    pub fn default_country(mut self, iso: impl Into<SharedString>) -> Self {
        self.default_country = iso.into();
        self
    }

    /// Limits the picker to these ISO codes (empty keeps the full table).
    pub fn countries<I, S>(mut self, codes: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<SharedString>,
    {
        self.countries = codes.into_iter().map(Into::into).collect();
        self
    }

    /// Pinned at the top of the picker under "Suggested".
    pub fn preferred_countries<I, S>(mut self, codes: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<SharedString>,
    {
        self.preferred_countries = codes.into_iter().map(Into::into).collect();
        self
    }

    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
        self.description = Some(description.into());
        self
    }

    pub fn error(mut self, error: impl Into<SharedString>) -> Self {
        self.error = Some(error.into());
        self
    }

    pub fn validate(mut self, validate: bool) -> Self {
        self.validate = validate;
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
        self.width = Some(width.into());
        self
    }

    pub fn on_value_change(
        mut self,
        handler: impl Fn(&PhoneValueEvent, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_value_change = Some(Rc::new(handler));
        self
    }

    pub fn on_country_change(
        mut self,
        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_country_change = Some(Rc::new(handler));
        self
    }
}

fn build_phone_details(entry: &'static PhoneCountry, digits: &str) -> PhoneInputDetails {
    let status = phone_status_of(entry, digits);
    PhoneInputDetails {
        country: entry,
        formatted: phone_format_national(entry, digits),
        status,
        valid: status == PhoneStatus::Valid,
    }
}

fn phone_pool(countries: &[SharedString]) -> Vec<&'static PhoneCountry> {
    if countries.is_empty() {
        PHONE_COUNTRIES.iter().collect()
    } else {
        PHONE_COUNTRIES
            .iter()
            .filter(|entry| countries.iter().any(|c| c.as_ref() == entry.iso))
            .collect()
    }
}

impl RenderOnce for PhoneInput {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);

        let pool = phone_pool(&self.countries);
        let default_entry = phone_country_by_iso(&self.default_country)
            .or_else(|| pool.first().copied())
            .unwrap_or(&PHONE_COUNTRIES[0]);

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-phone-state".into());
        let internal = window.use_keyed_state(state_id, cx, |window, cx| {
            // Seed from a controlled or default international value when it parses.
            let seed = self
                .value
                .clone()
                .or_else(|| self.default_value.clone())
                .unwrap_or_default();
            let (iso, digits) = if seed.is_empty() {
                (default_entry.iso.to_string(), String::new())
            } else {
                match phone_parse_number(&seed) {
                    Some((entry, national)) => (entry.iso.to_string(), national),
                    None => (default_entry.iso.to_string(), String::new()),
                }
            };
            PhoneInternal {
                uncontrolled_iso: iso.into(),
                digits,
                seen_value: self.value.clone(),
                ..PhoneInternal::new(now, window, cx)
            }
        });

        // Sync a controlled external value that differs from what the field last produced.
        if self.value != internal.read(cx).seen_value {
            let seen = self.value.clone();
            internal.update(cx, |s, _| {
                s.seen_value = seen.clone();
                if let Some(ext) = seen {
                    let cur_e164 = {
                        let iso = s.uncontrolled_iso.clone();
                        let entry = phone_country_by_iso(&iso).unwrap_or(default_entry);
                        phone_to_e164(entry, &s.digits)
                    };
                    if ext != cur_e164 {
                        if let Some((entry, national)) = phone_parse_number(&ext) {
                            s.uncontrolled_iso = entry.iso.into();
                            s.digits = national;
                        } else {
                            s.digits = String::new();
                        }
                        s.source_changed_at_secs = now;
                    }
                }
            });
        }

        let iso = self
            .country
            .clone()
            .unwrap_or_else(|| internal.read(cx).uncontrolled_iso.clone());
        let current = phone_country_by_iso(&iso).unwrap_or(default_entry);
        let snap = internal.read(cx).clone();
        let digits = snap.digits.clone();
        let formatted = phone_format_national(current, &digits);
        let status = phone_status_of(current, &digits);

        // The guide: the rest of the example number, in this country's shape, drawn faintly
        // after what was typed.
        let guide = {
            let (trunk, rest) = phone_split_trunk(current, &digits);
            if rest.len() >= current.example.len() {
                String::new()
            } else {
                let filled = format!("{trunk}{}{}", rest, &current.example[rest.len()..]);
                let full = phone_format_national(current, &filled);
                if full.starts_with(&formatted) {
                    full[formatted.len()..].to_string()
                } else {
                    String::new()
                }
            }
        };

        // Built-in validation message while unfocused (see deviation note).
        let is_focused = snap.focus_handle.is_focused(window);
        let lengths = phone_lengths(current);
        let length_copy = if lengths.len() == 1 {
            format!("{}", lengths[0])
        } else {
            let heads: Vec<String> = lengths[..lengths.len() - 1]
                .iter()
                .map(|l| l.to_string())
                .collect();
            format!("{} or {}", heads.join(", "), lengths[lengths.len() - 1])
        };
        let built_in_error: Option<SharedString> = if self.validate
            && !is_focused
            && !digits.is_empty()
            && matches!(status, PhoneStatus::Incomplete | PhoneStatus::TooLong)
        {
            Some(SharedString::from(format!(
                "Numbers in {} have {} digits",
                current.name, length_copy
            )))
        } else {
            None
        };
        let effective_error = self.error.clone().or(built_in_error);
        let is_invalid = effective_error.is_some();

        let control_border = if is_invalid {
            colors.danger
        } else if !self.disabled && is_focused {
            colors.foreground
        } else {
            colors.border_strong
        };

        // Country picker search sections.
        let needle = snap.query_input.read(cx).value().trim().to_lowercase();
        let mut sorted: Vec<&PhoneCountry> = pool.clone();
        sorted.sort_by_key(|entry| entry.name);
        let sections: Vec<(&'static str, Option<&'static str>, Vec<&PhoneCountry>)> =
            if !needle.is_empty() && needle != "+" {
                let mut hits: Vec<&PhoneCountry> = sorted
                    .iter()
                    .copied()
                    .filter(|entry| phone_matches_query(entry, &needle))
                    .collect();
                let digits_only = phone_only_digits(&needle);
                if !digits_only.is_empty() {
                    hits.sort_by_key(|entry| {
                        (
                            std::cmp::Reverse(entry.dial == digits_only),
                            entry.dial.len(),
                        )
                    });
                }
                vec![("results", None, hits)]
            } else {
                let preferred: Vec<&PhoneCountry> = self
                    .preferred_countries
                    .iter()
                    .filter_map(|code| {
                        pool.iter()
                            .find(|entry| entry.iso == code.as_ref())
                            .copied()
                    })
                    .collect();
                if preferred.is_empty() {
                    vec![("all", None, sorted.clone())]
                } else {
                    vec![
                        ("preferred", Some("Suggested"), preferred),
                        ("all", Some("All countries"), sorted.clone()),
                    ]
                }
            };
        let rows: Vec<&PhoneCountry> = sections
            .iter()
            .flat_map(|(_, _, r)| r.iter().copied())
            .collect();
        let active_iso = snap
            .active_iso
            .clone()
            .filter(|a| rows.iter().any(|r| r.iso == a.as_ref()))
            .or_else(|| rows.first().map(|r| SharedString::from(r.iso)));

        let menu_open = snap.menu_open && !self.disabled;

        // Flag-and-dial roll when the country changed (upstream layerVariants: ±0.6em roll with
        // a soft blur sharpen).
        let src_elapsed = (now - snap.source_changed_at_secs).max(0.0);
        let (flag_op, flag_y) = if src_elapsed >= 0.22 {
            (1.0_f32, 0.0_f32)
        } else {
            window.request_animation_frame();
            let t = (src_elapsed / 0.20).clamp(0.0, 1.0) as f32;
            let e = if reduced {
                t
            } else {
                CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
            };
            let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
            let op = (e * blur.opacity_multiplier).clamp(0.0, 1.0);
            let y = if reduced {
                0.0
            } else {
                (snap.roll_dir as f32) * 0.6 * 17.0 * (1.0 - e)
            };
            (op, y)
        };

        // Chevron rotation (`GLIDE = physical(0.28, 0)`).
        let glide_spec = phone_glide_spring();
        let chevron_deg = if reduced {
            if menu_open { 180.0 } else { 0.0 }
        } else {
            arc_spring(
                (self.id.clone(), "chevron-deg"),
                if menu_open { 180.0 } else { 0.0 },
                glide_spec,
                window,
                cx,
            )
        };

        // Panel presence (`fast` 160ms enter / `instant` 120ms exit) + width/height/radius morph.
        let panel_presence = ArcPresence::new((self.id.clone(), "panel-presence"), menu_open)
            .animate_initial(false)
            .config(ArcPresenceConfig {
                enter_duration: motion.duration.fast,
                exit_duration: motion.duration.instant,
                enter_ease: motion.ease.enter,
                exit_ease: motion.ease.standard,
                fade_on_reduced_motion: true,
            })
            .sample(window, cx);
        let panel_p = panel_presence.progress.clamp(0.0, 1.0);

        let trigger_w = snap
            .trigger_bounds
            .borrow()
            .map(|b| f32::from(b.size.width))
            .unwrap_or(72.0);
        let panel_target_w = trigger_w.max(PHONE_PANEL_MAX);
        let grow_spec = phone_grow_spring();
        let width_spec = phone_width_spring();
        let panel_rendering = panel_presence.should_render();
        let (panel_w, panel_r) = if reduced || !panel_rendering {
            (
                if panel_rendering {
                    panel_target_w
                } else {
                    trigger_w
                },
                if panel_rendering {
                    PHONE_OPEN_RADIUS
                } else {
                    PHONE_CLOSED_RADIUS
                },
            )
        } else {
            let w = arc_spring_with_options(
                (self.id.clone(), "panel-w"),
                panel_target_w,
                SpringOptions::new(width_spec).with_initial_value(trigger_w),
                window,
                cx,
            )
            .value;
            let r = arc_spring(
                (self.id.clone(), "panel-r"),
                PHONE_OPEN_RADIUS,
                grow_spec,
                window,
                cx,
            );
            (w, r)
        };

        let show_check = status == PhoneStatus::Valid;
        let check_scale = if reduced {
            if show_check { 1.0 } else { 0.6 }
        } else {
            arc_spring(
                (self.id.clone(), "check-sc"),
                if show_check { 1.0 } else { 0.6 },
                motion.spring.snappy,
                window,
                cx,
            )
        };
        let check_op = arc_transition(
            (self.id.clone(), "check-op"),
            if show_check { 1.0 } else { 0.0 },
            if reduced {
                std::time::Duration::ZERO
            } else {
                motion.duration.fast
            },
            motion.ease.standard,
            window,
            cx,
        );

        let highlight_bg = oklab_mix(colors.foreground, colors.surface_raised, 0.065);
        let guide_color = oklab_mix(colors.text_muted, colors.surface, 0.72);

        // ── Panel content ─────────────────────────────────────────────────────────────────────
        let mut section_els: Vec<AnyElement> = Vec::new();
        for (section_key, label, rows_in_section) in &sections {
            let mut rows_el: Vec<AnyElement> = Vec::new();
            for entry in rows_in_section {
                let row_key = format!("{section_key}-{}", entry.iso);
                let is_selected = entry.iso == current.iso;
                let is_active = active_iso.as_ref().is_some_and(|a| a.as_ref() == entry.iso);
                let check_op_row = arc_transition(
                    (self.id.clone(), format!("ph-chk-op-{}", entry.iso)),
                    if is_selected { 1.0 } else { 0.0 },
                    if reduced {
                        std::time::Duration::ZERO
                    } else {
                        motion.duration.fast
                    },
                    motion.ease.standard,
                    window,
                    cx,
                );
                let check_scale_row = if reduced {
                    if is_selected { 1.0 } else { 0.6 }
                } else {
                    arc_spring(
                        (self.id.clone(), format!("ph-chk-sc-{}", entry.iso)),
                        if is_selected { 1.0 } else { 0.6 },
                        glide_spec,
                        window,
                        cx,
                    )
                };
                let row_fg = if is_active || is_selected {
                    colors.foreground
                } else {
                    colors.text_secondary
                };
                let entry_clone = *entry;
                let int_hover = internal.clone();
                let iso_hover = SharedString::from(entry.iso);
                let int_pick = internal.clone();
                let on_v_pick = self.on_value_change.clone();
                let on_c_pick = self.on_country_change.clone();
                rows_el.push(
                    div()
                        .id(ElementId::NamedChild(
                            self.id.clone().into(),
                            SharedString::from(format!("country-{row_key}")),
                        ))
                        .test_support()
                        .role(Role::ListBoxOption)
                        .aria_label(SharedString::from(format!(
                            "{} +{}",
                            entry.name, entry.dial
                        )))
                        .w_full()
                        .flex_none()
                        .h(px(36.0))
                        .min_h(px(36.0))
                        .px(px(10.0))
                        .flex()
                        .flex_row()
                        .items_center()
                        .gap(px(10.0))
                        .rounded(px(6.0))
                        .text_size(Typography::TEXT_SM)
                        .text_color(row_fg)
                        .cursor_pointer()
                        .on_hover(move |hovered, window, cx| {
                            if *hovered {
                                int_hover.update(cx, |s, _| {
                                    s.active_iso = Some(iso_hover.clone());
                                });
                                window.refresh();
                            }
                        })
                        .on_click(move |_, window, cx| {
                            let entry = entry_clone;
                            let t_now = motion_now(cx);
                            let (cur_digits, cur_iso, q_in) = {
                                let s = int_pick.read(cx);
                                (
                                    s.digits.clone(),
                                    s.uncontrolled_iso.clone(),
                                    s.query_input.clone(),
                                )
                            };
                            let changed = entry.iso != cur_iso.as_ref();
                            let next_digits = phone_cap_digits(entry, &cur_digits);
                            let ev = PhoneValueEvent {
                                value: phone_to_e164(entry, &next_digits),
                                details: build_phone_details(entry, &next_digits),
                            };
                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
                            int_pick.update(cx, |s, _| {
                                s.menu_open = false;
                                s.highlight_seeded = false;
                                s.active_iso = None;
                                if changed {
                                    s.roll_dir = (phone_order_of(entry.iso) as i64
                                        - phone_order_of(cur_iso.as_ref()) as i64)
                                        .signum()
                                        as i8;
                                    s.source_changed_at_secs = t_now;
                                    s.uncontrolled_iso = entry.iso.into();
                                }
                                s.digits = next_digits;
                            });
                            if changed && let Some(cb) = &on_c_pick {
                                cb(&SharedString::from(entry.iso), window, cx);
                            }
                            if let Some(cb) = &on_v_pick {
                                cb(&ev, window, cx);
                            }
                            window.refresh();
                        })
                        .child(
                            div()
                                .w(px(20.0))
                                .flex_none()
                                .text_size(px(15.0))
                                .child(SharedString::from(phone_flag_of(entry.iso))),
                        )
                        .child(
                            div()
                                .flex_1()
                                .min_w_0()
                                .font_medium()
                                .truncate()
                                .child(SharedString::from(entry.name)),
                        )
                        .child(
                            div()
                                .flex_none()
                                .text_size(Typography::TEXT_XS)
                                .text_color(colors.text_muted)
                                .child(SharedString::from(format!("+{}", entry.dial))),
                        )
                        .child(
                            div().size(px(16.0)).flex_none().child(
                                canvas(
                                    |_, _, _| {},
                                    move |rect, _, window, _| {
                                        let cx_pt =
                                            f32::from(rect.origin.x + rect.size.width * 0.5);
                                        let cy_pt =
                                            f32::from(rect.origin.y + rect.size.height * 0.5);
                                        paint_scaled_check(
                                            cx_pt,
                                            cy_pt,
                                            check_scale_row,
                                            check_op_row,
                                            colors.foreground,
                                            window,
                                        );
                                    },
                                )
                                .size_full(),
                            ),
                        )
                        .into_any_element(),
                );
            }
            let group_el = if let Some(label_text) = label {
                div()
                    .flex_none()
                    .w_full()
                    .flex()
                    .flex_col()
                    .gap(px(2.0))
                    .child(
                        div()
                            .flex_none()
                            .pt(px(8.0))
                            .px(px(10.0))
                            .pb(px(4.0))
                            .text_size(Typography::TEXT_XS)
                            .text_color(colors.text_muted)
                            .child(SharedString::from(*label_text)),
                    )
                    .children(rows_el)
                    .into_any_element()
            } else {
                div()
                    .flex_none()
                    .w_full()
                    .flex()
                    .flex_col()
                    .gap(px(2.0))
                    .children(rows_el)
                    .into_any_element()
            };
            section_els.push(group_el);
        }

        let empty_el = if rows.is_empty() {
            Some(
                div()
                    .px(px(10.0))
                    .pt(px(12.0))
                    .pb(px(14.0))
                    .text_size(Typography::TEXT_SM)
                    .text_color(colors.text_muted)
                    .child(SharedString::from(format!(
                        "No countries match \u{201c}{}\u{201d}",
                        needle.trim()
                    ))),
            )
        } else {
            None
        };

        // Highlight pill position (glide spring; seeded on first render). Rows stride 38px
        // (36px row + 2px gap); group labels shift the stride by 26px each (24px header + 2px gap).
        let target_hy = {
            let mut cur_y = 6.0_f32;
            let mut found_y = 6.0_f32;
            let mut found = false;
            for (sec_idx, (_, label, rows_in_section)) in sections.iter().enumerate() {
                if sec_idx > 0 {
                    cur_y += 2.0;
                }
                if label.is_some() {
                    cur_y += 24.0 + 2.0;
                }
                for (row_idx, entry) in rows_in_section.iter().enumerate() {
                    if row_idx > 0 {
                        cur_y += 2.0;
                    }
                    if !found && active_iso.as_ref().is_some_and(|a| a.as_ref() == entry.iso) {
                        found_y = cur_y;
                        found = true;
                    }
                    cur_y += 36.0;
                }
            }
            found_y
        };
        let pill_y = if reduced || !snap.highlight_seeded {
            let _ = arc_spring_with_options(
                (self.id.clone(), "hi-y"),
                target_hy,
                SpringOptions::new(glide_spec).with_initial_value(target_hy),
                window,
                cx,
            );
            if menu_open && !snap.highlight_seeded {
                internal.update(cx, |s, _| s.highlight_seeded = true);
            }
            target_hy
        } else {
            arc_spring((self.id.clone(), "hi-y"), target_hy, glide_spec, window, cx)
        };

        // ── Overlay panel ─────────────────────────────────────────────────────────────────────
        let int_close = internal.clone();
        let control_bounds_ref = snap.control_bounds.clone();
        let panel_bounds_ref_out = snap.panel_bounds.clone();
        let panel_el = if panel_rendering {
            let search_input = KitInput::new(&snap.query_input)
                .appearance(false)
                .w_full()
                .text_size(Typography::TEXT_SM);
            let int_clear = internal.clone();
            Some(
                deferred(
                    div()
                        .id(ElementId::NamedChild(
                            self.id.clone().into(),
                            "country-panel".into(),
                        ))
                        .test_support()
                        .role(Role::ListBox)
                        .absolute()
                        .left_0()
                        .top_full()
                        .overflow_hidden()
                        .w(px(panel_w))
                        .rounded(px(panel_r))
                        .border_1()
                        .border_color(colors.border)
                        .bg(colors.surface_raised)
                        .shadow(Shadows::floating(theme.mode))
                        .opacity(panel_p)
                        .on_key_down({
                            let int_key = internal.clone();
                            let rows_for_key = rows.clone();
                            let on_v_key = self.on_value_change.clone();
                            let on_c_key = self.on_country_change.clone();
                            move |event: &KeyDownEvent, window, cx| {
                                if !int_key.read(cx).menu_open {
                                    return;
                                }
                                let cur_active = int_key.read(cx).active_iso.clone();
                                let at = cur_active
                                    .as_ref()
                                    .and_then(|a| {
                                        rows_for_key.iter().position(|r| r.iso == a.as_ref())
                                    })
                                    .unwrap_or(0);
                                match event.keystroke.key.as_str() {
                                    "escape" => {
                                        let q_in = int_key.read(cx).query_input.clone();
                                        q_in.update(cx, |s, cx| s.set_value("", window, cx));
                                        int_key.update(cx, |s, _| {
                                            s.menu_open = false;
                                            s.highlight_seeded = false;
                                            s.active_iso = None;
                                        });
                                        window.refresh();
                                    }
                                    "down" | "arrowdown" => {
                                        let idx = (at + 1).min(rows_for_key.len() - 1);
                                        if let Some(next) = rows_for_key.get(idx) {
                                            int_key.update(cx, |s, _| {
                                                s.active_iso = Some(SharedString::from(next.iso));
                                            });
                                            window.refresh();
                                        }
                                    }
                                    "up" | "arrowup" => {
                                        if let Some(prev) = rows_for_key.get(at.saturating_sub(1)) {
                                            int_key.update(cx, |s, _| {
                                                s.active_iso = Some(SharedString::from(prev.iso));
                                            });
                                            window.refresh();
                                        }
                                    }
                                    "pageup" => {
                                        if let Some(prev) =
                                            rows_for_key.get(at.saturating_sub(PHONE_PAGE))
                                        {
                                            int_key.update(cx, |s, _| {
                                                s.active_iso = Some(SharedString::from(prev.iso));
                                            });
                                            window.refresh();
                                        }
                                    }
                                    "pagedown" => {
                                        let idx = (at + PHONE_PAGE).min(rows_for_key.len() - 1);
                                        if let Some(next) = rows_for_key.get(idx) {
                                            int_key.update(cx, |s, _| {
                                                s.active_iso = Some(SharedString::from(next.iso));
                                            });
                                            window.refresh();
                                        }
                                    }
                                    "enter" => {
                                        if let Some(entry) = rows_for_key.get(at).copied() {
                                            let t_now = motion_now(cx);
                                            let (cur_digits, cur_iso, q_in) = {
                                                let s = int_key.read(cx);
                                                (
                                                    s.digits.clone(),
                                                    s.uncontrolled_iso.clone(),
                                                    s.query_input.clone(),
                                                )
                                            };
                                            let changed = entry.iso != cur_iso.as_ref();
                                            let next_digits = phone_cap_digits(entry, &cur_digits);
                                            let ev = PhoneValueEvent {
                                                value: phone_to_e164(entry, &next_digits),
                                                details: build_phone_details(entry, &next_digits),
                                            };
                                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
                                            int_key.update(cx, |s, _| {
                                                s.menu_open = false;
                                                s.highlight_seeded = false;
                                                s.active_iso = None;
                                                if changed {
                                                    s.roll_dir = (phone_order_of(entry.iso) as i64
                                                        - phone_order_of(cur_iso.as_ref()) as i64)
                                                        .signum()
                                                        as i8;
                                                    s.source_changed_at_secs = t_now;
                                                    s.uncontrolled_iso = entry.iso.into();
                                                }
                                                s.digits = next_digits;
                                            });
                                            if changed && let Some(cb) = &on_c_key {
                                                cb(&SharedString::from(entry.iso), window, cx);
                                            }
                                            if let Some(cb) = &on_v_key {
                                                cb(&ev, window, cx);
                                            }
                                            window.refresh();
                                        }
                                    }
                                    _ => {}
                                }
                            }
                        })
                        .child(
                            div()
                                .relative()
                                .h(ControlHeights::MD)
                                .flex()
                                .flex_row()
                                .items_center()
                                .gap(Spacing::S2)
                                .pl(px(13.0))
                                .pr(px(2.0))
                                .child(
                                    Icon::new(IconName::Search)
                                        .text_size(px(16.0))
                                        .text_color(colors.text_muted),
                                )
                                .child(
                                    div()
                                        .flex_1()
                                        .min_w_0()
                                        .text_color(colors.foreground)
                                        .child(search_input),
                                )
                                .when(!needle.is_empty(), |this| {
                                    this.child(
                                        BaseButton::new(ElementId::NamedChild(
                                            self.id.clone().into(),
                                            "clear-search".into(),
                                        ))
                                        .accessibility_label("Clear search")
                                        .on_click(move |_, window, cx| {
                                            let q_in = int_clear.read(cx).query_input.clone();
                                            q_in.update(cx, |s, cx| {
                                                s.set_value("", window, cx);
                                                s.focus(window, cx);
                                            });
                                            window.refresh();
                                        })
                                        .size(px(24.0))
                                        .flex()
                                        .items_center()
                                        .justify_center()
                                        .rounded(Radii::PILL)
                                        .bg(highlight_bg)
                                        .text_color(colors.text_secondary)
                                        .cursor_pointer()
                                        .child(Icon::new(IconName::Close).text_size(px(14.0))),
                                    )
                                }),
                        )
                        .child(div().mx(px(14.0)).h(px(1.0)).bg(colors.border))
                        .child(
                            div()
                                .flex_none()
                                .flex()
                                .flex_col()
                                .px(px(6.0))
                                .pb(px(6.0))
                                .child(
                                    div()
                                        .id(ElementId::NamedChild(
                                            self.id.clone().into(),
                                            "country-scroll".into(),
                                        ))
                                        .test_support()
                                        .relative()
                                        .w_full()
                                        .pt(px(6.0))
                                        .h(px(PHONE_LIST_MAX_H))
                                        .max_h(px(PHONE_LIST_MAX_H))
                                        .overflow_y_scroll()
                                        .on_scroll(|_, _, cx| cx.stop_propagation())
                                        .flex()
                                        .flex_col()
                                        .gap(px(2.0))
                                        .child(
                                            div()
                                                .absolute()
                                                .left_0()
                                                .right_0()
                                                .top(px(pill_y))
                                                .h(px(36.0))
                                                .rounded(px(6.0))
                                                .bg(highlight_bg),
                                        )
                                        .children(section_els)
                                        .children(empty_el),
                                ),
                        )
                        .child(
                            canvas(
                                {
                                    let probe = panel_bounds_ref_out.clone();
                                    move |rect, _, _| {
                                        *probe.borrow_mut() = Some(rect);
                                    }
                                },
                                |_, _, _, _| {},
                            )
                            .absolute()
                            .inset_0(),
                        )
                        .child(canvas(
                            |_, _, _| {},
                            move |_, _, window, _| {
                                // Dismiss on outside pointer down (window-level, like money-input).
                                let c_ref = control_bounds_ref.clone();
                                let p_ref = panel_bounds_ref_out.clone();
                                let st = int_close.clone();
                                window.on_mouse_event(
                                    move |event: &MouseDownEvent, phase, window, cx| {
                                        if !phase.bubble() {
                                            return;
                                        }
                                        let in_ctrl = c_ref
                                            .borrow()
                                            .is_some_and(|b| b.contains(&event.position));
                                        let in_panel = p_ref
                                            .borrow()
                                            .is_some_and(|b| b.contains(&event.position));
                                        if !in_ctrl && !in_panel {
                                            st.update(cx, |s, _| {
                                                s.menu_open = false;
                                                s.highlight_seeded = false;
                                                s.active_iso = None;
                                            });
                                            window.refresh();
                                        }
                                    },
                                );
                            },
                        )),
                )
                .with_priority(25),
            )
        } else {
            None
        };

        // ── Number key handling (append model, see deviation note) ────────────────────────────
        let int_key = internal.clone();
        let on_v_change_key = self.on_value_change.clone();
        let on_c_change_key = self.on_country_change.clone();
        let disabled_key = self.disabled;
        let focus_handle_key = snap.focus_handle.clone();
        let focus_for_wrap = snap.focus_handle.clone();

        let control = div()
            .id(ElementId::NamedChild(
                self.id.clone().into(),
                "control".into(),
            ))
            .test_support()
            .role(Role::Group)
            .track_focus(&focus_handle_key)
            .on_hover({
                let int_h = internal.clone();
                move |hovered, window, cx| {
                    int_h.update(cx, |s, _| s.control_hovered = *hovered);
                    window.refresh();
                }
            })
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if disabled_key || int_key.read(cx).menu_open {
                    return;
                }
                let key = event.keystroke.key.as_str();
                let ctrl_or_platform =
                    event.keystroke.modifiers.control || event.keystroke.modifiers.platform;
                let t_now = motion_now(cx);
                if key == "+" && !ctrl_or_platform {
                    int_key.update(cx, |s, _| {
                        s.menu_open = true;
                        s.highlight_seeded = false;
                    });
                    let q_in = int_key.read(cx).query_input.clone();
                    q_in.update(cx, |s, cx| {
                        s.set_value("+", window, cx);
                        s.focus(window, cx);
                    });
                    window.refresh();
                    return;
                }
                if ctrl_or_platform && key == "v" {
                    let pasted = cx
                        .read_from_clipboard()
                        .and_then(|item| item.text())
                        .unwrap_or_default();
                    let entry = current;
                    let parsed = if pasted.trim_start().starts_with('+')
                        || pasted.trim_start().starts_with("00")
                    {
                        phone_parse_number(&pasted)
                    } else {
                        None
                    };
                    let (entry, next_digits) = match parsed {
                        Some((entry, national)) if !national.is_empty() => (entry, national),
                        _ => {
                            let mut fragment = phone_only_digits(&pasted);
                            let cap_len = phone_cap_digits(entry, &fragment).len();
                            // "1 415 555 0132" into a US field: the leading calling code is
                            // dropped when the number would not fit otherwise.
                            if fragment.starts_with(entry.dial) && fragment.len() > cap_len {
                                fragment = fragment[entry.dial.len()..].to_string();
                            }
                            (entry, phone_cap_digits(entry, &fragment))
                        }
                    };
                    let changed_iso = entry.iso != current.iso;
                    let ev = PhoneValueEvent {
                        value: phone_to_e164(entry, &next_digits),
                        details: build_phone_details(entry, &next_digits),
                    };
                    int_key.update(cx, |s, _| {
                        if changed_iso {
                            s.roll_dir = (phone_order_of(entry.iso) as i64
                                - phone_order_of(current.iso) as i64)
                                .signum() as i8;
                            s.source_changed_at_secs = t_now;
                            s.uncontrolled_iso = entry.iso.into();
                        }
                        s.digits = next_digits;
                    });
                    if changed_iso && let Some(cb) = &on_c_change_key {
                        cb(&SharedString::from(entry.iso), window, cx);
                    }
                    if let Some(cb) = &on_v_change_key {
                        cb(&ev, window, cx);
                    }
                    window.refresh();
                    return;
                }
                let digit_char = event
                    .keystroke
                    .key_char
                    .as_deref()
                    .and_then(|kc| (kc.len() == 1).then(|| kc.chars().next()).flatten())
                    .filter(|c| c.is_ascii_digit())
                    .or_else(|| {
                        (key.len() == 1)
                            .then(|| key.chars().next())
                            .flatten()
                            .filter(|c| c.is_ascii_digit())
                    });
                if let Some(digit) = digit_char
                    && !ctrl_or_platform
                {
                    let entry = current;
                    let next = {
                        let s = int_key.read(cx);
                        let candidate = format!("{}{digit}", s.digits);
                        phone_cap_digits(entry, &candidate)
                    };
                    let ev = PhoneValueEvent {
                        value: phone_to_e164(entry, &next),
                        details: build_phone_details(entry, &next),
                    };
                    int_key.update(cx, |s, _| {
                        s.digits = next;
                        s.seen_value = Some(ev.value.clone());
                    });
                    if let Some(cb) = &on_v_change_key {
                        cb(&ev, window, cx);
                    }
                    window.refresh();
                    return;
                }
                if key == "backspace" {
                    let entry = current;
                    let next: String = {
                        let s = int_key.read(cx);
                        s.digits
                            .chars()
                            .take(s.digits.len().saturating_sub(1))
                            .collect()
                    };
                    let ev = PhoneValueEvent {
                        value: phone_to_e164(entry, &next),
                        details: build_phone_details(entry, &next),
                    };
                    int_key.update(cx, |s, _| {
                        s.digits = next;
                        s.seen_value = Some(ev.value.clone());
                    });
                    if let Some(cb) = &on_v_change_key {
                        cb(&ev, window, cx);
                    }
                    window.refresh();
                }
            })
            .relative()
            .w_full()
            .h(ControlHeights::MD)
            .px(px(1.0))
            .flex()
            .flex_row()
            .items_center()
            .rounded(Radii::CONTROL)
            .border_1()
            .border_color(control_border)
            .bg(if self.disabled {
                colors.surface_muted
            } else {
                colors.surface
            })
            .opacity(if self.disabled { 0.5 } else { 1.0 })
            .child(
                canvas(
                    {
                        let probe = snap.control_bounds.clone();
                        move |rect, _, _| {
                            *probe.borrow_mut() = Some(rect);
                        }
                    },
                    |_, _, _, _| {},
                )
                .absolute()
                .inset_0(),
            )
            // ── Country trigger + morphing panel ──────────────────────────────────────────────
            .child(
                div()
                    .relative()
                    .h_full()
                    .flex_none()
                    .when_some(panel_el, |this, panel| this.child(panel))
                    .child(
                        div()
                            .id(ElementId::NamedChild(
                                self.id.clone().into(),
                                "trigger".into(),
                            ))
                            .test_support()
                            .role(Role::Button)
                            .aria_label(SharedString::from(format!(
                                "Country, {} +{}",
                                current.name, current.dial
                            )))
                            .relative()
                            .h_full()
                            .pl(px(11.0))
                            .pr(px(33.0))
                            .flex()
                            .flex_row()
                            .items_center()
                            .gap(px(6.0))
                            .rounded(px(PHONE_CLOSED_RADIUS - 4.0))
                            .when(
                                !self.disabled && (snap.trigger_hovered || menu_open),
                                |this| this.bg(colors.surface_muted),
                            )
                            .when(!self.disabled, |this| {
                                this.cursor_pointer().on_hover({
                                    let int_t = internal.clone();
                                    move |hovered, window, cx| {
                                        int_t.update(cx, |s, _| s.trigger_hovered = *hovered);
                                        window.refresh();
                                    }
                                })
                            })
                            .on_click({
                                let int_t = internal.clone();
                                let disabled_t = self.disabled;
                                let focus_t = snap.focus_handle.clone();
                                move |_, window, cx| {
                                    if disabled_t {
                                        return;
                                    }
                                    window.focus(&focus_t, cx);
                                    let will_open = !int_t.read(cx).menu_open;
                                    int_t.update(cx, |s, _| {
                                        s.menu_open = !s.menu_open;
                                        s.highlight_seeded = false;
                                    });
                                    if will_open {
                                        let q_in = int_t.read(cx).query_input.clone();
                                        q_in.update(cx, |s, cx| {
                                            s.set_value("", window, cx);
                                            s.focus(window, cx);
                                        });
                                    }
                                    window.refresh();
                                }
                            })
                            .child(
                                div()
                                    .mt(px(flag_y))
                                    .opacity(flag_op)
                                    .flex()
                                    .flex_row()
                                    .items_center()
                                    .gap(px(6.0))
                                    .child(
                                        div()
                                            .w(px(20.0))
                                            .flex_none()
                                            .text_size(px(17.0))
                                            .child(SharedString::from(phone_flag_of(current.iso))),
                                    )
                                    .child(
                                        div()
                                            .flex_none()
                                            .text_size(Typography::TEXT_SM)
                                            .font_medium()
                                            .text_color(colors.foreground)
                                            .child(SharedString::from(format!(
                                                "+{}",
                                                current.dial
                                            ))),
                                    ),
                            )
                            .child(
                                div()
                                    .absolute()
                                    .right(px(12.0))
                                    .top(px(14.0))
                                    .size(px(16.0))
                                    .child(
                                        canvas(
                                            |_, _, _| {},
                                            move |rect, _, window, _| {
                                                let cx_pt = f32::from(
                                                    rect.origin.x + rect.size.width * 0.5,
                                                );
                                                let cy_pt = f32::from(
                                                    rect.origin.y + rect.size.height * 0.5,
                                                );
                                                paint_rotated_chevron(
                                                    cx_pt,
                                                    cy_pt,
                                                    chevron_deg,
                                                    colors.text_muted,
                                                    window,
                                                );
                                            },
                                        )
                                        .size_full(),
                                    ),
                            )
                            .child(
                                canvas(
                                    {
                                        let probe = snap.trigger_bounds.clone();
                                        move |rect, _, _| {
                                            *probe.borrow_mut() = Some(rect);
                                        }
                                    },
                                    |_, _, _, _| {},
                                )
                                .absolute()
                                .inset_0(),
                            ),
                    ),
            )
            // ── Number + guide + valid check ───────────────────────────────────────────────────
            .child(
                div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        "number-wrap".into(),
                    ))
                    .test_support()
                    .flex_1()
                    .min_w_0()
                    .h_full()
                    .flex()
                    .items_center()
                    .pl(px(11.0))
                    .pr(px(36.0))
                    .when(!self.disabled, |this| {
                        let focus_down = focus_for_wrap.clone();
                        this.cursor_pointer()
                            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                                window.focus(&focus_down, cx);
                                window.refresh();
                            })
                            .on_click({
                                let int_n = internal.clone();
                                move |_, window, cx| {
                                    window.focus(&focus_for_wrap, cx);
                                    let _ = &int_n;
                                    window.refresh();
                                }
                            })
                    })
                    .child(
                        div()
                            .flex()
                            .flex_row()
                            .items_center()
                            .min_w_0()
                            .whitespace_nowrap()
                            .text_size(Typography::TEXT_SM)
                            .child(
                                div()
                                    .flex_none()
                                    .text_color(colors.foreground)
                                    .child(SharedString::from(formatted.clone())),
                            )
                            .when(is_focused && !menu_open && !self.disabled, |this| {
                                this.child(
                                    div()
                                        .mx(px(1.0))
                                        .w(px(1.5))
                                        .h(px(16.0))
                                        .bg(colors.foreground),
                                )
                            })
                            .when(!guide.is_empty(), |this| {
                                this.child(
                                    div()
                                        .flex_none()
                                        .text_color(guide_color)
                                        .child(SharedString::from(guide.clone())),
                                )
                            }),
                    )
                    .child(
                        div()
                            .absolute()
                            .right(px(12.0))
                            .top(px(13.0))
                            .size(px(18.0))
                            .child(
                                canvas(
                                    |_, _, _| {},
                                    move |rect, _, window, _| {
                                        let cx_pt =
                                            f32::from(rect.origin.x + rect.size.width * 0.5);
                                        let cy_pt =
                                            f32::from(rect.origin.y + rect.size.height * 0.5);
                                        paint_scaled_check(
                                            cx_pt,
                                            cy_pt,
                                            check_scale,
                                            check_op,
                                            colors.success,
                                            window,
                                        );
                                    },
                                )
                                .size_full(),
                            ),
                    ),
            );

        let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
        let msg_text = effective_error.clone().or(self.description);

        div()
            .id(self.id)
            .test_support()
            .when_some(self.width, |this, w| this.w(w))
            .when(self.width.is_none(), |this| this.w_full())
            .flex()
            .flex_col()
            .when(!self.hide_label, |this| {
                this.child(
                    div()
                        .mb(Spacing::S2)
                        .text_size(Typography::TEXT_SM)
                        .font_medium()
                        .text_color(colors.foreground)
                        .child(self.label),
                )
            })
            .child(control)
            .child(render_field_message(
                msg_id, msg_text, is_invalid, window, cx,
            ))
    }
}

#[cfg(test)]
mod tests {
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{ClipboardItem, Context, Render, TestAppContext, test::TestWindowExt as _};

    use super::*;

    #[test]
    fn phone_patterns_format_national_numbers_with_trunk_prefix() {
        let us = phone_country_by_iso("US").unwrap();
        assert_eq!(phone_format_national(us, "2015550123"), "(201) 555-0123");
        assert_eq!(phone_to_e164(us, "2015550123"), "+12015550123");
        // A typed UK trunk prefix keeps its own room: "07911123456" -> "07911 123456".
        let gb = phone_country_by_iso("GB").unwrap();
        assert_eq!(phone_format_national(gb, "07911123456"), "07911 123456");
        assert_eq!(phone_status_of(gb, "07911123456"), PhoneStatus::Valid);
        assert_eq!(phone_status_of(gb, ""), PhoneStatus::Empty);
        assert_eq!(phone_status_of(gb, "07911"), PhoneStatus::Incomplete);
        assert_eq!(phone_status_of(gb, "079111234567"), PhoneStatus::TooLong);
    }

    #[test]
    fn phone_parse_number_resolves_longest_dial_and_area_codes() {
        // Longest calling code wins: +353 is Ireland, not +3 with junk.
        let (entry, national) = phone_parse_number("+353850123456").unwrap();
        assert_eq!(entry.iso, "IE");
        assert_eq!(national, "850123456");
        // Canada resolves inside the shared +1 dial through its area codes.
        let (entry, national) = phone_parse_number("+14165550123").unwrap();
        assert_eq!(entry.iso, "CA");
        assert_eq!(national, "4165550123");
        // "+44 (0)…" carries a trunk zero that is dropped.
        let (entry, national) = phone_parse_number("+44 (0)7400 123456").unwrap();
        assert_eq!(entry.iso, "GB");
        assert_eq!(national, "7400123456");
        // 00 international prefix.
        let (entry, _) = phone_parse_number("0041 78 123 45 67").unwrap();
        assert_eq!(entry.iso, "CH");
        assert!(phone_parse_number("not a phone").is_none());
    }

    #[test]
    fn phone_cap_digits_earn_trunk_room_and_format_e164_round_trips() {
        let gb = phone_country_by_iso("GB").unwrap();
        // The typed trunk "0" earns its own room: 1 + 10 digits fit.
        assert_eq!(phone_cap_digits(gb, "0791112345678"), "07911123456");
        let e164 = phone_to_e164(gb, "07911123456");
        assert_eq!(e164, "+447911123456");
        assert_eq!(phone_format_e164(&e164), "+44 7911 123456");
    }

    #[test]
    fn phone_matches_query_matches_dials_names_and_iso() {
        let us = phone_country_by_iso("US").unwrap();
        let de = phone_country_by_iso("DE").unwrap();
        assert!(phone_matches_query(us, "1"));
        assert!(phone_matches_query(us, "+1"));
        assert!(phone_matches_query(de, "49"));
        assert!(phone_matches_query(de, "germ"));
        assert!(phone_matches_query(de, "de"));
        assert!(!phone_matches_query(de, "44"));
        assert!(phone_matches_query(us, "+"));
    }

    struct PhoneHost {
        value: String,
        iso: SharedString,
        disabled: bool,
        events: Rc<RefCell<Vec<String>>>,
        countries_seen: Rc<RefCell<Vec<SharedString>>>,
    }

    impl Render for PhoneHost {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let events = self.events.clone();
            let countries_seen = self.countries_seen.clone();
            div().w(px(560.0)).p(px(16.0)).child(
                PhoneInput::new("phone-test", "Phone")
                    .value(self.value.clone())
                    .country(self.iso.clone())
                    .disabled(self.disabled)
                    .on_value_change(cx.listener({
                        let events = events.clone();
                        move |this, event: &PhoneValueEvent, _, cx| {
                            events.borrow_mut().push(event.value.clone());
                            this.value = event.value.clone();
                            cx.notify();
                        }
                    }))
                    .on_country_change(cx.listener({
                        let countries_seen = countries_seen.clone();
                        move |this, iso: &SharedString, _, cx| {
                            countries_seen.borrow_mut().push(iso.clone());
                            this.iso = iso.clone();
                            cx.notify();
                        }
                    })),
            )
        }
    }

    fn phone_element(name: &str) -> ElementId {
        ElementId::NamedChild(ElementId::Name("phone-test".into()).into(), name.into())
    }

    #[gpui_kit::test]
    fn phone_input_types_backspaces_picks_country_and_parses_paste(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });

        let host = PhoneHost {
            value: String::new(),
            iso: "US".into(),
            disabled: false,
            events: Rc::new(RefCell::new(Vec::new())),
            countries_seen: Rc::new(RefCell::new(Vec::new())),
        };
        let events = host.events.clone();
        let countries_seen = host.countries_seen.clone();
        let (view, cx) = cx.add_window_view(|_, _| host);

        cx.update(|window, cx| {
            window.render_frame(cx);
            let trigger = window.find(phone_element("trigger"));
            assert_eq!(trigger.role(), Some(Role::Button));

            // Typing digits emits the running draft as E.164 per keystroke.
            window.click(phone_element("number-wrap"), cx);
            window.input("201555", cx);
        });
        assert_eq!(events.borrow().last(), Some(&"+1201555".to_string()));

        cx.update(|window, cx| {
            window.press("backspace", cx);
        });
        assert_eq!(events.borrow().last(), Some(&"+120155".to_string()));

        // The country picker opens as a listbox; picking Canada keeps the digits.
        cx.update(|window, cx| {
            window.click(phone_element("trigger"), cx);
            window.render_frame(cx);
            let panel = window.find(phone_element("country-panel"));
            assert_eq!(panel.role(), Some(Role::ListBox));
            let row = window.find(phone_element("country-preferred-CA"));
            assert_eq!(row.role(), Some(Role::ListBoxOption));
            window.click(phone_element("country-preferred-CA"), cx);
        });
        assert_eq!(
            countries_seen.borrow().last().map(|c| c.to_string()),
            Some("CA".to_string())
        );

        // Pasting an international number picks its own country.
        cx.update(|window, cx| {
            window.click(phone_element("number-wrap"), cx);
        });
        cx.update(|_window, cx| {
            cx.write_to_clipboard(ClipboardItem::new_string("+447911123456".to_string()));
        });
        cx.update(|window, cx| {
            window.press("ctrl-v", cx);
        });
        assert_eq!(
            countries_seen.borrow().last().map(|c| c.to_string()),
            Some("GB".to_string())
        );
        assert_eq!(events.borrow().last(), Some(&"+447911123456".to_string()));

        // "+" opens the picker seeded with a calling-code search.
        cx.update(|window, cx| {
            window.click(phone_element("number-wrap"), cx);
            window.press("+", cx);
            window.render_frame(cx);
            assert!(window.try_find(phone_element("country-panel")).is_some());
        });

        // Disabled swallows typing.
        view.update(cx, |host, cx| {
            host.disabled = true;
            cx.notify();
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.click(phone_element("number-wrap"), cx);
            window.input("7", cx);
        });
        assert_eq!(events.borrow().last(), Some(&"+447911123456".to_string()));
    }

    #[gpui_kit::test]
    fn phone_input_reduced_motion_keeps_interactions_instant(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
        });

        let host = PhoneHost {
            value: String::new(),
            iso: "US".into(),
            disabled: false,
            events: Rc::new(RefCell::new(Vec::new())),
            countries_seen: Rc::new(RefCell::new(Vec::new())),
        };
        let events = host.events.clone();
        let (_view, cx) = cx.add_window_view(|_, _| host);

        cx.update(|window, cx| {
            window.render_frame(cx);
            window.click(phone_element("number-wrap"), cx);
            window.input("20", cx);
        });
        assert_eq!(
            events.borrow().as_slice(),
            ["+12".to_string(), "+120".to_string()]
        );
    }
}