delopay 0.20.0

Official Rust SDK for the DeloPay payments API
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
//! Stripe **native panes**: merchant-configured payment methods that render as
//! DeloPay-drawn tiles in the embedded checkout instead of inside Stripe's
//! Payment Element.
//!
//! Why they exist: Stripe only offers Apple Pay / Google Pay / Link when the
//! *top-level* document's domain is registered as a payment method domain on
//! the merchant's Stripe account. In an embedded iframe that domain is the
//! merchant's shop, not the DeloPay checkout — so the wallet silently
//! disappears. A native pane replaces it with a DeloPay tile that opens the
//! hosted checkout at the top level, in a focused single-method view. Nothing
//! here is Apple-Pay-specific.
//!
//! A direct port of the TypeScript SDK's `nativePanes` module, wire-compatible
//! with it: [`decode_panes`] / [`encode_panes`] round-trip the
//! `metadata.native_panes` blob on a Stripe connector account, and
//! [`focused_checkout_url`] builds the single-method link a merchant puts
//! behind their own button.
//!
//! This module is a **mirror**, not the source of truth — the catalog and wire
//! shapes are owned by the API. Drift is safe in one
//! direction only: the API silently drops a key it does not know, so a
//! stale entry here produces a row that never renders rather than a broken
//! checkout.
//!
//! It has no HTTP dependencies and is therefore always compiled, including in
//! the `default-features = false` build.
//!
//! # Example
//!
//! ```
//! use delopay::panes::{self, FocusedCheckoutUrlParams, STRIPE_FALLBACK_PANE_CATALOG};
//!
//! // The catalogue comes from `connectors().panes_catalog(account_id)`; the
//! // frozen Stripe table is the degradation path for a router without it.
//! let mut pane = panes::default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
//! pane.label = "Apple Pay".into();
//!
//! let blob = panes::encode_panes(&[pane.clone()]);
//! let round_tripped = panes::decode_panes(&blob).unwrap();
//! assert_eq!(round_tripped[0], pane);
//!
//! let url = panes::focused_checkout_url(&FocusedCheckoutUrlParams {
//!     checkout_base_url: "https://checkout.delopay.net",
//!     merchant_id: "merchant_1",
//!     payment_id: "pay_123",
//!     payment_link_id: None,
//!     method: "apple_pay",
//!     connector: Some("stripe"),
//!     merchant_connector_id: None,
//!     locale: Some("de"),
//!     custom_fields_collected: false,
//! });
//! assert_eq!(
//!     url,
//!     "https://checkout.delopay.net/pay/merchant_1/pay_123?pane=apple_pay&connector=stripe&locale=de"
//! );
//! ```

use std::collections::BTreeMap;
use std::sync::LazyLock;

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

// --- Wire enums ---------------------------------------------------------

/// How the focused external checkout charges a paned method. Decided
/// server-side; the browser never picks.
///
/// - [`Wallet`](PaneRail::Wallet) — the method rides inside Stripe's
///   `card` rail (Apple Pay, Google Pay, Link). The focused view charges the
///   **same** PaymentIntent the embedded checkout already holds, so no second
///   intent is ever created.
/// - [`Redirect`](PaneRail::Redirect) — the method has its own
///   `payment_method_types[]` entry. The focused view confirms through the
///   standard `/payments/{id}/confirm` rail and follows
///   `next_action.redirect_to_url`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PaneRail {
    /// Rides inside the card rail's PaymentIntent.
    Wallet,
    /// Confirms through `/payments/{id}/confirm` and follows the redirect.
    Redirect,
    /// The connector mounts its own element for the method — the rail
    /// Airwallex's catalogue sits on. The tile names the element to mount in
    /// [`PaneView::connector_method_name`].
    HostedElement,
}

impl PaneRail {
    /// The wire string (`"wallet"`, `"redirect"` or `"hosted_element"`).
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::Wallet => "wallet",
            Self::Redirect => "redirect",
            Self::HostedElement => "hosted_element",
        }
    }
}

/// Where a pane's tile is offered. Wallet rail only — a redirect pane is
/// suppressed server-side, before any render knows whether it is framed, so
/// `embedded_only` there would leave the method unpayable at top level and the
/// router forces it back to `always`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum PaneVisibility {
    /// Offered wherever the checkout renders.
    #[default]
    Always,
    /// Offered only inside a merchant iframe, where the wallet Stripe would
    /// otherwise draw is unavailable.
    EmbeddedOnly,
    /// Offered only at top level — a hosted payment link or the focused view —
    /// and hidden inside a merchant iframe.
    ExternalOnly,
}

impl PaneVisibility {
    /// The wire string (`"always"` / `"embedded_only"` / `"external_only"`).
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::Always => "always",
            Self::EmbeddedOnly => "embedded_only",
            Self::ExternalOnly => "external_only",
        }
    }

    /// Parse a stored wire value. Anything unrecognised degrades to
    /// [`Always`](Self::Always) rather than failing: an older SDK reading a
    /// blob a newer dashboard wrote is a normal state during a rollout, and
    /// failing there would take out a merchant's whole connector config rather
    /// than one tile.
    pub fn from_wire(raw: Option<&Value>) -> Self {
        match raw.and_then(Value::as_str) {
            Some("embedded_only") => Self::EmbeddedOnly,
            Some("external_only") => Self::ExternalOnly,
            _ => Self::Always,
        }
    }
}

/// How the embedded checkout opens a pane's focused single-method view.
///
/// `Tab` (the historical behaviour and the default) opens a new tab; `Popup`
/// opens a centred popup window, which keeps the merchant's embedded page
/// visible behind it. Only meaningful for an embedded render — a top-level
/// render always navigates in place, and a browser that refuses popups falls
/// back to a tab on its own.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum PaneOpenTarget {
    #[default]
    Tab,
    Popup,
}

impl PaneOpenTarget {
    /// The wire string (`"tab"` / `"popup"`).
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::Tab => "tab",
            Self::Popup => "popup",
        }
    }

    /// Parse a stored wire value. Anything unrecognised degrades to
    /// [`Tab`](Self::Tab) rather than failing — matching the TypeScript codec,
    /// and keeping a blob written by a newer editor readable here.
    pub fn from_wire(raw: Option<&Value>) -> Self {
        match raw.and_then(Value::as_str) {
            Some("popup") => Self::Popup,
            _ => Self::Tab,
        }
    }
}

// --- Config shape -------------------------------------------------------

/// One native pane exactly as the merchant configures it. Persisted (JSON)
/// under `metadata.native_panes` on the Stripe merchant connector account.
///
/// The snake_case wire field names are the contract — see
/// [`encode_panes`]. The router decodes strictly row by row: a row
/// that fails strict decoding (e.g. a wrong-typed field like
/// `"display_order": "3"`) is dropped whole with a server log while the
/// remaining rows still render. [`decode_panes`] is additionally
/// per-property tolerant — including clamping `display_order` into the
/// router's `i32` range — so a decode→encode round-trip through this SDK
/// repairs a blob the router would partially drop.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pane {
    /// Catalog key of the promoted method — see [`STRIPE_FALLBACK_PANE_METHODS`].
    pub method: String,
    /// Disabled rows keep their tuning but never reach a buyer.
    pub enabled: bool,
    /// Default-language tile label. Empty falls back to the catalog name.
    pub label: String,
    /// Per-locale overrides of `label`, keyed by checkout locale (`de`, `de-AT`).
    pub label_translations: BTreeMap<String, String>,
    /// Secondary line under the label. `None` means "use the catalog default";
    /// an empty string means the merchant deliberately hid the line. That
    /// distinction is the whole reason this is optional and `label` is not.
    pub sublabel: Option<String>,
    /// Per-locale overrides of `sublabel`.
    pub sublabel_translations: BTreeMap<String, String>,
    /// Section the tile groups under. Empty falls back to the catalog category.
    pub category: String,
    /// Built-in icon key — see [`PANE_ICON_KEYS`].
    pub icon: String,
    /// Custom inline SVG. Sanitized server-side before it reaches a buyer; a
    /// rejected payload falls back to the built-in `icon`.
    pub icon_svg: String,
    /// Lower renders first; ties break on catalog order.
    pub display_order: i64,
    /// `EmbeddedOnly` keeps the wallet inside Stripe's form at top level.
    pub visibility: PaneVisibility,
    /// How the embedded checkout opens the focused view — see
    /// [`PaneOpenTarget`].
    pub open_in: PaneOpenTarget,
}

/// One resolved native pane as the buyer-facing checkout receives it on the
/// payment-link payload (`native_panes`). Labels are already localized for the
/// render's locale and icons already sanitized.
///
/// `rail` stays a plain string (`"wallet"`, `"redirect"`, `"hosted_element"`)
/// so an unknown future rail degrades readably instead of failing
/// deserialisation.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PaneView {
    /// Catalogue key of the promoted method.
    pub method: String,
    /// Connector brand that owns this tile (`stripe`, `klarna`, …).
    ///
    /// Pass it to [`FocusedCheckoutUrlParams::connector`] to mint a link that
    /// resolves to this tile and no other: the method key alone is ambiguous
    /// the moment two connectors publish it, and a bare `pane=` then resolves
    /// to whichever tile sorts first server-side.
    ///
    /// It names a brand, not an account —
    /// [`merchant_connector_id`](Self::merchant_connector_id) is what
    /// separates two accounts of the same connector. Empty only on a payload
    /// from a router that predates the field.
    pub connector: Option<String>,
    /// Merchant connector **account** this tile was configured on, for
    /// [`FocusedCheckoutUrlParams::merchant_connector_id`].
    ///
    /// The checkout echoes it back on confirm and the router re-validates it
    /// against the profile's live accounts, so a tile charges the credentials
    /// it was configured on rather than a sibling account's.
    ///
    /// Absent on the wallet rail — that rail charges the PaymentIntent the
    /// card connector already created, so there is no routing decision to pin
    /// — and on payloads predating the field.
    pub merchant_connector_id: Option<String>,
    /// `"wallet"`, `"redirect"` or `"hosted_element"` — see [`PaneRail`].
    pub rail: String,
    /// On the hosted-element rail, the connector's own name for the method —
    /// the name the checkout mounts the element by. Absent on the other rails
    /// and on payloads from a router that predates the field.
    pub connector_method_name: Option<String>,
    /// Label, already localized for the render's locale.
    pub label: String,
    /// Second line, already localized.
    pub sublabel: String,
    /// `Some(true)` when [`label`](Self::label) is the router's compiled
    /// catalogue default rather than anything the merchant typed.
    ///
    /// Those defaults are compiled in English only, so a merchant who
    /// configures nothing gets an English tile label under a translated
    /// section heading. This is what lets a localizing surface substitute its
    /// own copy for exactly those tiles and leave merchant-authored ones
    /// alone. Key that copy on [`method`](Self::method) alone, and append
    /// [`connector_display_name`](Self::connector_display_name) — two
    /// connectors may publish one key with identical catalogue copy, and the
    /// brand is what tells the pair apart.
    ///
    /// `None` on payloads that predate the field, which is merchant-authored
    /// for this purpose: nothing gets rewritten.
    pub label_is_default: Option<bool>,
    /// `Some(true)` when [`sublabel`](Self::sublabel) is the compiled
    /// catalogue default, on the same terms as
    /// [`label_is_default`](Self::label_is_default).
    ///
    /// An explicitly empty sublabel is a merchant decision — "hide the second
    /// line" — and reports `false`, so substituting copy there would restore a
    /// line they deliberately cleared.
    pub sublabel_is_default: Option<bool>,
    /// The connector's brand, present **only** when this render would
    /// otherwise show two tiles a buyer cannot tell apart.
    ///
    /// Append it to the sublabel you render. It travels separately from
    /// [`sublabel`](Self::sublabel) precisely because that string is replaced
    /// wholesale when [`sublabel_is_default`](Self::sublabel_is_default) is
    /// set: a brand baked into it would be discarded with it, collapsing the
    /// two tiles again. Do not translate it.
    pub connector_display_name: Option<String>,
    /// Section the tile groups under.
    pub category: String,
    pub icon: Option<String>,
    pub icon_svg: Option<String>,
    /// The provider's original artwork. Render it only as an SVG image
    /// document, never inline.
    pub icon_image: Option<String>,
    /// The eligible methods a provider-hosted checkout tile stands for. Empty
    /// on other tiles and on payloads that predate the field.
    pub method_logos: Vec<String>,
    pub display_order: i64,
    /// Redirect rail only — echo verbatim on confirm, never derive.
    pub payment_method: Option<String>,
    /// Redirect rail only — echo verbatim on confirm, never derive.
    pub payment_method_type: Option<String>,
    /// Redirect rail only — echo verbatim on confirm, never derive.
    pub payment_method_data: Option<Value>,
    /// The confirm body needs the buyer's country: merged into
    /// `billing.address.country` and echoed into the single
    /// `payment_method_data` variant's `billing_country`.
    pub requires_billing_country: Option<bool>,
    /// `true` when the tile is only offered inside an iframe. Wallet rail only.
    ///
    /// Superseded by [`visibility`](Self::visibility), which carries all three
    /// states, and kept by the router at exactly its historical meaning so
    /// checkout builds predating that field keep working. Such a build reads
    /// an `external_only` tile as `embedded_only: false` and shows it in the
    /// embed too — it over-shows, losing a placement rule, rather than hiding
    /// a tile the buyer needs. Read [`pane_view_visibility`] rather than
    /// either field.
    pub embedded_only: Option<bool>,
    /// Which render contexts this tile is offered in.
    ///
    /// **The resolved value, not the merchant's stored one, and the two do not
    /// round-trip.** The router coerces anything the render path cannot
    /// honour before emitting: every redirect-rail pane comes back `always`
    /// whatever the merchant configured, because suppression there is decided
    /// before any render knows whether it is framed. Read
    /// [`Pane::visibility`] off the connector account's metadata for the
    /// merchant's setting.
    ///
    /// A plain string for the same reason as [`rail`](Self::rail), and read
    /// through [`pane_view_visibility`] rather than compared directly.
    pub visibility: Option<String>,
    /// How the embedded checkout opens this tile's focused view (`"tab"` /
    /// `"popup"`). Absent on payloads from older backends — treat as `"tab"`.
    /// A plain string for the same reason as `rail`: an unknown future target
    /// degrades readably instead of failing deserialisation.
    pub open_in: Option<String>,
    /// Whether the merchant asked for this tile to be drawn as the wallet's
    /// own button, and where: `"everywhere"`, `"embedded_only"` or
    /// `"external_only"`. Absent means "as a tile".
    pub native_element: Option<String>,
    /// What this tile's own provider adds to — or takes off — the buyer's
    /// total, resolved server-side against that pane's account.
    ///
    /// **Absent means render nothing.** It is absent whenever no rule applies,
    /// and on every payload from a router that predates provider surcharges.
    /// Never substitute a merchant-wide figure for it.
    pub surcharge: Option<PaneSurcharge>,
    /// `Some(true)` when the shop's Smart Routing decides which account takes
    /// this tile's payment. The confirm then leaves out `connector`, still
    /// sends [`merchant_connector_id`](Self::merchant_connector_id) as
    /// `native_pane_merchant_connector_id`, and adds
    /// `native_pane_routed: true`. `Some(false)` pins the confirm to the
    /// account. `None` on payloads that predate the field.
    pub routed: Option<bool>,
    /// Where the checkout loads Rapyd's Checkout Toolkit, for Rapyd's embedded
    /// card pane. `None` on other panes and on payloads that predate the
    /// field.
    pub rapyd_toolkit: Option<RapydToolkitConfig>,
    /// Any additional fields present on the wire but not modeled here.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Where the checkout loads Rapyd's Checkout Toolkit for Rapyd's embedded card
/// pane. The toolkit frames Rapyd's own checkout page from the host of the
/// environment the confirm creates the payment in.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct RapydToolkitConfig {
    /// Whether the account's sandbox credentials serve this payment.
    pub sandbox: bool,
    /// Any additional fields present on the wire but not modeled here.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What one tile's own provider adds to (or takes off) the buyer's total.
///
/// Amounts are in the payment's minor units and are **signed by
/// [`direction`](Self::direction)**, not by the numbers: the router's
/// percentage type is unsigned by construction, so a discount arrives as a
/// positive magnitude with `direction: "discount"`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PaneSurcharge {
    /// The adjustment itself, in minor units.
    pub surcharge_amount: i64,
    /// Tax charged on the adjustment, in minor units.
    pub tax_amount: i64,
    /// Adjustment plus its tax, in minor units.
    pub total_amount: i64,
    /// What to print beside the tile, in minor units.
    pub display_total_amount: i64,
    /// `"surcharge"` or `"discount"` — which way the total moves.
    pub direction: String,
    /// The adjustment as a percentage of the order, when it was configured as
    /// a rate.
    #[serde(default)]
    pub percent_of_order: Option<f64>,
    /// Any additional fields present on the wire but not modeled here.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// --- Catalog ------------------------------------------------------------

/// One catalog entry: a method that may be promoted to a native pane, with the
/// defaults the editor shows as placeholders.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PaneMethodInfo {
    /// Catalog key (`apple_pay`, `klarna`, …).
    pub key: &'static str,
    /// How the focused checkout charges the method.
    pub rail: PaneRail,
    /// Confirm routing key. Pass through verbatim; never derive it.
    pub payment_method: &'static str,
    /// Confirm routing key. Pass through verbatim; never derive it.
    pub payment_method_type: &'static str,
    /// Whether the focused checkout has to collect a billing country to
    /// confirm this method.
    pub requires_billing_country: bool,
    /// Catalog default label, shown as the editor's placeholder.
    pub default_label: &'static str,
    /// Catalog default sub-text.
    pub default_sublabel: &'static str,
    /// Catalog default section.
    pub default_category: &'static str,
    /// Catalog default icon key.
    pub default_icon: &'static str,
}

/// Methods that may be promoted to a native pane.
///
/// **The API owns this list.** This is a mirror so SDK consumers can validate or offer
/// the promotable methods without a round-trip.
pub const STRIPE_FALLBACK_PANE_METHODS: &[PaneMethodInfo] = &[
    PaneMethodInfo {
        key: "apple_pay",
        rail: PaneRail::Wallet,
        payment_method: "wallet",
        payment_method_type: "apple_pay",
        requires_billing_country: false,
        default_label: "Apple Pay",
        default_sublabel: "Pay with Apple Pay",
        default_category: "wallet",
        default_icon: "apple",
    },
    PaneMethodInfo {
        key: "google_pay",
        rail: PaneRail::Wallet,
        payment_method: "wallet",
        payment_method_type: "google_pay",
        requires_billing_country: false,
        default_label: "Google Pay",
        default_sublabel: "Pay with Google Pay",
        default_category: "wallet",
        default_icon: "google",
    },
    PaneMethodInfo {
        key: "link",
        rail: PaneRail::Wallet,
        payment_method: "wallet",
        payment_method_type: "link",
        requires_billing_country: false,
        default_label: "Link",
        default_sublabel: "Pay with saved details",
        default_category: "wallet",
        default_icon: "wallet",
    },
    PaneMethodInfo {
        // The sublabel is deliberately the copy a router predating the
        // capability endpoint renders, not the router's current string. This
        // whole table is what such a router produces; restating today's copy
        // here would put text no reachable router emits in front of a
        // merchant.
        key: "klarna",
        rail: PaneRail::Redirect,
        payment_method: "pay_later",
        payment_method_type: "klarna",
        requires_billing_country: true,
        default_label: "Klarna",
        default_sublabel: "Pay later or in instalments",
        default_category: "bnpl",
        default_icon: "bnpl",
    },
    PaneMethodInfo {
        key: "affirm",
        rail: PaneRail::Redirect,
        payment_method: "pay_later",
        payment_method_type: "affirm",
        requires_billing_country: false,
        default_label: "Affirm",
        default_sublabel: "Pay over time",
        default_category: "bnpl",
        default_icon: "bnpl",
    },
    PaneMethodInfo {
        key: "ideal",
        rail: PaneRail::Redirect,
        payment_method: "bank_redirect",
        payment_method_type: "ideal",
        requires_billing_country: false,
        default_label: "iDEAL",
        default_sublabel: "Pay from your bank",
        default_category: "bank_redirect",
        default_icon: "bank",
    },
    // eps / p24 / bancontact were removed from the router catalog: Stripe
    // hard-requires billing fields the focused checkout never collects (full
    // name for EPS/Bancontact, email for Przelewy24), so their tiles could
    // never succeed. They may return behind billing-aware gating.
    PaneMethodInfo {
        key: "alipay",
        rail: PaneRail::Redirect,
        payment_method: "wallet",
        payment_method_type: "ali_pay",
        requires_billing_country: false,
        default_label: "Alipay",
        default_sublabel: "Pay with Alipay",
        default_category: "wallet",
        default_icon: "wallet",
    },
    PaneMethodInfo {
        key: "revolut_pay",
        rail: PaneRail::Redirect,
        payment_method: "wallet",
        payment_method_type: "revolut_pay",
        requires_billing_country: false,
        default_label: "Revolut Pay",
        default_sublabel: "Pay with Revolut",
        default_category: "wallet",
        default_icon: "wallet",
    },
    PaneMethodInfo {
        key: "amazon_pay",
        rail: PaneRail::Redirect,
        payment_method: "wallet",
        payment_method_type: "amazon_pay",
        requires_billing_country: false,
        default_label: "Amazon Pay",
        default_sublabel: "Pay with Amazon",
        default_category: "wallet",
        default_icon: "wallet",
    },
];

/// Built-in tile icon keys the buyer-facing checkout ships a glyph for.
///
/// Reconciled against both ends: every key here has a branch in the checkout's
/// icon component, and every `default_icon` the router's catalogue publishes is
/// in this list. A key that drifts in renders as the wrong glyph rather than as
/// nothing, since the checkout falls through to `wallet`.
pub const PANE_ICON_KEYS: &[&str] = &[
    "wallet", "card", "bank", "apple", "google", "bnpl", "cash",
    // Brand marks, not category glyphs: the checkout draws PayPal's monogram,
    // Klarna's squircle-K and the Bitcoin mark for these. Listed so a
    // merchant's own dashboard can offer them; the router decides which one a
    // tile *defaults* to, and a router predating them keeps sending the old
    // default.
    "paypal", "klarna", "crypto",
];

/// Section keys a pane's tile may group under.
///
/// Reconciled against the router's actual `default_category` values rather than
/// against what the Stripe table happened to need: `crypto` and `game_items`
/// are router defaults, and a merchant configuring one of those panes was
/// otherwise shown a category their editor did not recognise. A custom value is
/// allowed and renders as its own section under that literal text.
pub const PANE_CATEGORY_KEYS: &[&str] = &[
    "wallet",
    "card",
    "bnpl",
    "bank_redirect",
    "bank_transfer",
    "crypto",
    "game_items",
    "cash",
];

/// Mirror of the router's per-connector cap.
pub const PANES_MAX: usize = 12;

/// The key the pane list is stored under in the connector account's `metadata`.
pub const PANES_METADATA_KEY: &str = "native_panes";

/// The closed vocabulary of buyer-side checkout events recorded on the
/// payment's status timeline. Written through
/// `POST /payment-link/{merchant_id}/{payment_id}/checkout-events`, authorized
/// with the payment's `client_secret` as a bearer token. These rows surface on
/// `payment_status_history` with `entity_type = "checkout"`.
pub const CHECKOUT_EVENT_KINDS: &[&str] = &[
    "native_pane_selected",
    "native_pane_tab_opened",
    "native_pane_tab_blocked",
    "native_pane_abandoned",
    // Recorded when a buyer opens a pane and then walks back to the picker via
    // "Use another payment method" / "Choose another".
    "native_pane_returned",
];

/// The frozen fallback table's entry for `method`, or `None` when that table
/// does not carry it.
///
/// This reads the **degradation path**, not the live catalogue: it is what a
/// router predating the capability endpoint publishes for Stripe, copy
/// included. For anything else, read the live catalogue with
/// [`pane_capability`].
pub fn pane_method_info(method: &str) -> Option<&'static PaneMethodInfo> {
    STRIPE_FALLBACK_PANE_METHODS
        .iter()
        .find(|m| m.key == method)
}

// --- Codec --------------------------------------------------------------

/// A new pane for `method`, with its glyph and section resolved from the
/// connector's catalogue entry rather than from a Stripe-keyed table — so a
/// pane for a connector this crate has never heard of is a designed tile and
/// not a blank one.
///
/// Pass the catalogue entry for the connector being configured, from
/// [`crate::Connectors::panes_catalog`] via [`pane_catalog_for`];
/// [`STRIPE_FALLBACK_PANE_CATALOG`] is the degradation path.
///
/// Labels are deliberately left empty: empty means "use the catalogue
/// default", which the router resolves at render, and the router ships no copy
/// for a caller to mirror.
pub fn default_pane(method: &str, catalog: &PanesConnectorCatalog) -> Pane {
    let defaults = pane_display_defaults(pane_capability(method, catalog));
    Pane {
        method: method.to_owned(),
        enabled: true,
        label: String::new(),
        label_translations: BTreeMap::new(),
        sublabel: None,
        sublabel_translations: BTreeMap::new(),
        category: defaults.category.to_owned(),
        icon: defaults.icon.to_owned(),
        icon_svg: String::new(),
        display_order: 0,
        visibility: PaneVisibility::Always,
        open_in: PaneOpenTarget::Tab,
    }
}

fn str_or_empty(row: &Map<String, Value>, key: &str) -> String {
    row.get(key)
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_owned()
}

fn parse_translations(raw: Option<&Value>) -> BTreeMap<String, String> {
    let mut out = BTreeMap::new();
    if let Some(Value::Object(map)) = raw {
        for (locale, value) in map {
            if let Some(text) = value.as_str()
                && !text.is_empty()
            {
                out.insert(locale.clone(), text.to_owned());
            }
        }
    }
    out
}

fn int_or_zero(raw: Option<&Value>) -> i64 {
    let wide = match raw {
        Some(Value::Number(n)) => n
            .as_i64()
            .or_else(|| n.as_f64().filter(|f| f.is_finite()).map(|f| f as i64))
            .unwrap_or(0),
        // The TypeScript codec runs the value through Number(), which accepts
        // numeric strings — keep a hand-edited blob decoding the same way.
        Some(Value::String(s)) => s
            .trim()
            .parse::<f64>()
            .ok()
            .filter(|f| f.is_finite())
            .map(|f| f as i64)
            .unwrap_or(0),
        _ => 0,
    };
    // Clamp into the router's `i32` range: the wire type is an `i32` and an
    // out-of-range value fails its strict row decode, dropping the whole row
    // server-side. Clamped, what this codec emits is always a value the
    // router accepts.
    wide.clamp(i64::from(i32::MIN), i64::from(i32::MAX))
}

/// Decode the stored `metadata.native_panes` blob into editor rows.
///
/// Tolerant like the branding codecs: anything malformed falls back per
/// property (including clamping `display_order` into the router's `i32`
/// range), rows without a usable `method` are dropped, duplicates keep the row
/// the router would render (the first, except that an enabled row wins over an
/// earlier disabled one), and decoding stops after [`PANES_MAX`] *decoded*
/// rows — dropped junk and duplicate entries don't consume a slot. That is
/// more forgiving than the router, which drops a strict-decode-failing row
/// whole (keeping the rest) and caps *accepted* panes (enabled, known,
/// deduplicated) rather than decoded rows — an oversized hand-written blob may
/// render a pane this decoder drops. Returns `None` when the input is not an
/// array so the caller can distinguish "never configured" from "cleared".
pub fn decode_panes(raw: &Value) -> Option<Vec<Pane>> {
    let rows = raw.as_array()?;
    // Build one editor row from a stored entry. Tolerant per property.
    let decode_row = |row: &Map<String, Value>, method: String| Pane {
        method,
        // Only an explicit `false` disables — anything else stays enabled.
        enabled: row.get("enabled") != Some(&Value::Bool(false)),
        label: str_or_empty(row, "label"),
        label_translations: parse_translations(row.get("label_translations")),
        sublabel: row
            .get("sublabel")
            .and_then(Value::as_str)
            .map(str::to_owned),
        sublabel_translations: parse_translations(row.get("sublabel_translations")),
        category: str_or_empty(row, "category"),
        icon: str_or_empty(row, "icon"),
        icon_svg: str_or_empty(row, "icon_svg"),
        display_order: int_or_zero(row.get("display_order")),
        // Anything unrecognised degrades to `always` rather than dropping
        // the row.
        visibility: PaneVisibility::from_wire(row.get("visibility")),
        // Same tolerance: an unknown value degrades to the default `tab`.
        open_in: PaneOpenTarget::from_wire(row.get("open_in")),
    };

    let mut index_by_method: BTreeMap<String, usize> = BTreeMap::new();
    let mut out: Vec<Pane> = Vec::new();
    for entry in rows {
        if out.len() >= PANES_MAX {
            break;
        }
        let Some(row) = entry.as_object() else {
            continue;
        };
        let method = str_or_empty(row, "method").trim().to_owned();
        if method.is_empty() {
            continue;
        }
        if let Some(&kept) = index_by_method.get(&method) {
            // Duplicate method. Keep the row the ROUTER would render: it skips
            // disabled rows BEFORE deduping (`native_panes.rs`), so where a
            // blob holds both a disabled and an enabled row for one method,
            // buyers see the enabled one. Keeping the disabled row here would
            // show the merchant a pane that is off while it is live, and
            // delete it on the next save.
            let enabled = row.get("enabled") != Some(&Value::Bool(false));
            if enabled && !out[kept].enabled {
                out[kept] = decode_row(row, method);
            }
            continue;
        }
        index_by_method.insert(method.clone(), out.len());
        out.push(decode_row(row, method));
    }
    Some(out)
}

/// Encode editor rows back into the snake_case blob the connector account
/// stores (a JSON array, ready to place under `metadata.native_panes`). Empty
/// optional strings are omitted so the metadata stays small and a merchant who
/// typed nothing round-trips as "use the catalog default" rather than as an
/// explicit empty override.
///
/// `sublabel` is the exception: an explicitly-empty value is preserved (as
/// `""`) because that is how a merchant hides the second line.
pub fn encode_panes(panes: &[Pane]) -> Value {
    let non_empty = |map: &BTreeMap<String, String>| -> Option<Map<String, Value>> {
        let entries: Map<String, Value> = map
            .iter()
            .filter(|(_, v)| !v.trim().is_empty())
            .map(|(k, v)| (k.clone(), Value::String(v.clone())))
            .collect();
        (!entries.is_empty()).then_some(entries)
    };
    let rows: Vec<Value> = panes
        .iter()
        .take(PANES_MAX)
        .map(|pane| {
            let mut row = Map::new();
            row.insert("method".into(), Value::String(pane.method.clone()));
            row.insert("enabled".into(), Value::Bool(pane.enabled));
            if !pane.label.trim().is_empty() {
                row.insert("label".into(), Value::String(pane.label.trim().to_owned()));
            }
            if let Some(translations) = non_empty(&pane.label_translations) {
                row.insert("label_translations".into(), Value::Object(translations));
            }
            // `None` omits the key entirely (catalog default wins); `""` is
            // sent as-is because that is how the merchant hides the second
            // line.
            if let Some(sublabel) = &pane.sublabel {
                row.insert("sublabel".into(), Value::String(sublabel.clone()));
            }
            if let Some(translations) = non_empty(&pane.sublabel_translations) {
                row.insert("sublabel_translations".into(), Value::Object(translations));
            }
            if !pane.category.trim().is_empty() {
                row.insert(
                    "category".into(),
                    Value::String(pane.category.trim().to_owned()),
                );
            }
            if !pane.icon.trim().is_empty() {
                row.insert("icon".into(), Value::String(pane.icon.trim().to_owned()));
            }
            if !pane.icon_svg.trim().is_empty() {
                row.insert(
                    "icon_svg".into(),
                    Value::String(pane.icon_svg.trim().to_owned()),
                );
            }
            // Clamped on encode too, not only decode: the field is an `i64`
            // for hand-edited-blob tolerance, but the router's wire type is a
            // strict `i32` — an out-of-range value written verbatim would
            // fail its row decode and silently delete the pane at render.
            row.insert(
                "display_order".into(),
                Value::from(
                    pane.display_order
                        .clamp(i64::from(i32::MIN), i64::from(i32::MAX)),
                ),
            );
            row.insert(
                "visibility".into(),
                Value::String(pane.visibility.as_wire().to_owned()),
            );
            row.insert(
                "open_in".into(),
                Value::String(pane.open_in.as_wire().to_owned()),
            );
            Value::Object(row)
        })
        .collect();
    Value::Array(rows)
}

// --- Live catalogue -----------------------------------------------------

/// One method a connector can publish as a pane, as the router reports it.
///
/// Capability facts only: no label, sublabel or category comes back. A caller
/// renders a method's copy from its own locale files, keyed by
/// [`key`](Self::key), and takes the two routing keys from here verbatim
/// rather than deriving them.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[non_exhaustive]
pub struct PaneCapability {
    /// Stable catalogue key (`apple_pay`, `klarna`, …). The copy lookup key.
    pub key: String,
    /// `"wallet"`, `"redirect"` or `"hosted_element"`.
    pub rail: String,
    /// Routing key sent on confirm. Pass through verbatim; never derive it.
    pub payment_method: String,
    /// Routing key sent on confirm. Pass through verbatim; never derive it.
    pub payment_method_type: String,
    /// Whether a configuration for this method must carry a billing country.
    #[serde(default)]
    pub requires_billing_country: bool,
    /// Whether the method can be drawn as the wallet's own button rather than
    /// as a tile. The router's answer: Apple Pay and Google Pay on Stripe's
    /// wallet rail and on Airwallex's hosted-element rail, and e-Payouts'
    /// PayPal Express and Pay with card panes, which draw PayPal's button and
    /// card fields. Absent reads as `false`.
    #[serde(default)]
    pub supports_native_element: bool,
}

impl PaneCapability {
    /// The rail as an enum, or `None` for a rail this SDK does not know —
    /// which is a router newer than this crate, not an error.
    pub fn rail(&self) -> Option<PaneRail> {
        match self.rail.as_str() {
            "wallet" => Some(PaneRail::Wallet),
            "redirect" => Some(PaneRail::Redirect),
            _ => None,
        }
    }
}

/// What one connector can publish as panes.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[non_exhaustive]
pub struct PanesConnectorCatalog {
    /// Connector name (`stripe`, `creem`, …).
    pub connector: String,
    /// Rails this connector supports at all. A pane declaring a rail absent
    /// from this list is refused when the connector account is saved, rather
    /// than accepted and silently dropped.
    #[serde(default)]
    pub allowed_rails: Vec<String>,
    /// The methods themselves.
    #[serde(default)]
    pub methods: Vec<PaneCapability>,
}

/// Every connector's pane capabilities, as `GET
/// /account/{account_id}/connectors/native-panes/catalog` reports them.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[non_exhaustive]
pub struct PanesCatalogResponse {
    /// One entry per connector the router knows.
    pub connectors: Vec<PanesConnectorCatalog>,
}

/// What this SDK assumes when the router cannot answer.
///
/// The capability endpoint does not exist on an older router, which answers
/// [`crate::Connectors::panes_catalog`] with a 404. Rather than leaving a
/// caller with nothing, the helpers here default to exactly the behaviour they
/// had before that endpoint existed: panes on Stripe only, with the method set
/// the router's Stripe catalogue had at the time.
///
/// **This is a degradation path, not a mirror. Do not keep it in sync by hand,
/// and do not add a connector or a method to it.** A connector the router
/// serves panes for arrives through the endpoint and needs no entry here; a
/// connector that would need one to appear is a connector the router will not
/// deliver panes for anyway. Once the endpoint is reachable this is never
/// consulted for a connector the router answered for.
pub static STRIPE_FALLBACK_PANE_CATALOG: LazyLock<PanesConnectorCatalog> =
    LazyLock::new(|| PanesConnectorCatalog {
        connector: "stripe".to_owned(),
        allowed_rails: vec!["wallet".to_owned(), "redirect".to_owned()],
        methods: STRIPE_FALLBACK_PANE_METHODS
            .iter()
            .map(|info| PaneCapability {
                key: info.key.to_owned(),
                rail: info.rail.as_wire().to_owned(),
                payment_method: info.payment_method.to_owned(),
                payment_method_type: info.payment_method_type.to_owned(),
                requires_billing_country: info.requires_billing_country,
                // The frozen Stripe table predates native wallet buttons and
                // describes tiles only: a live catalogue is what says a method
                // can be drawn as the wallet's own button.
                supports_native_element: false,
            })
            .collect(),
    });

/// An empty catalogue — a connector the router does not offer panes for.
///
/// Exported so a caller can express "asked, and the answer was no" without
/// reaching for `None` in the middle of a computation.
pub fn empty_pane_catalog(connector: &str) -> PanesConnectorCatalog {
    PanesConnectorCatalog {
        connector: connector.to_owned(),
        allowed_rails: Vec::new(),
        methods: Vec::new(),
    }
}

/// Pull one connector's entry out of a catalogue response.
///
/// Answers [`empty_pane_catalog`] for a connector the response does not name:
/// "the router knows this connector and publishes no panes for it" and "the
/// router has never heard of it" are the same answer to a caller building an
/// editor, and both mean "offer nothing".
pub fn pane_catalog_for(response: &PanesCatalogResponse, connector: &str) -> PanesConnectorCatalog {
    response
        .connectors
        .iter()
        .find(|entry| entry.connector == connector)
        .cloned()
        .unwrap_or_else(|| empty_pane_catalog(connector))
}

/// Look a method up in one connector's catalogue.
///
/// Pass the entry for the connector being configured, from
/// [`crate::Connectors::panes_catalog`] via [`pane_catalog_for`].
pub fn pane_capability<'a>(
    method: &str,
    catalog: &'a PanesConnectorCatalog,
) -> Option<&'a PaneCapability> {
    catalog.methods.iter().find(|info| info.key == method)
}

/// Whether this connector may declare a pane on `rail` at all.
///
/// A wallet pane on a connector outside its allowed rails is refused at save
/// time: that rail rides on Stripe's Express Checkout Element charging the
/// *same* payment intent the embedded checkout holds, which does not
/// generalise.
pub fn pane_rail_allowed(rail: &str, catalog: &PanesConnectorCatalog) -> bool {
    catalog.allowed_rails.iter().any(|r| r == rail)
}

/// The methods a caller may actually offer for this connector: the catalogue's
/// own list, minus anything on a rail the connector does not allow.
///
/// The router should not report such a pair, but the two fields are
/// independent in the response and a save that crosses them is refused at the
/// API. Filter rather than trust, so a merchant never configures a tile the
/// save will bounce.
pub fn offerable_pane_methods(catalog: &PanesConnectorCatalog) -> Vec<&PaneCapability> {
    catalog
        .methods
        .iter()
        .filter(|info| pane_rail_allowed(&info.rail, catalog))
        .collect()
}

/// Non-copy display defaults for a tile: which built-in glyph and which
/// section heading a new pane starts on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PaneDisplayDefaults {
    /// Built-in icon key — see [`PANE_ICON_KEYS`].
    pub icon: &'static str,
    /// Section key — see [`PANE_CATEGORY_KEYS`].
    pub category: &'static str,
}

/// Per-method overrides, for the handful whose brand glyph is not what their
/// payment method would suggest.
///
/// Keyed by method and not by `payment_method`: `wallet` also routes Link,
/// Alipay, Revolut Pay and Amazon Pay, and `pay_later` also routes Affirm —
/// none of which this SDK has a mark for. Getting this wrong is not cosmetic,
/// because [`default_pane`] materialises the value and [`encode_panes`] writes
/// it, where a stored `icon` outranks the router's default for the life of the
/// pane.
const DISPLAY_DEFAULTS_BY_KEY: &[(&str, PaneDisplayDefaults)] = &[
    (
        "apple_pay",
        PaneDisplayDefaults {
            icon: "apple",
            category: "wallet",
        },
    ),
    (
        "google_pay",
        PaneDisplayDefaults {
            icon: "google",
            category: "wallet",
        },
    ),
    (
        "paypal",
        PaneDisplayDefaults {
            icon: "paypal",
            category: "wallet",
        },
    ),
    // Both the Klarna connector's own tile and Stripe's Klarna. Affirm stays
    // on the generic `bnpl` glyph — same rail, no mark of its own.
    (
        "klarna",
        PaneDisplayDefaults {
            icon: "klarna",
            category: "bnpl",
        },
    ),
];

/// Derived from the `payment_method` half of the catalogue's routing pair.
///
/// Every value here reproduces the router's own defaults for the methods it
/// publishes today, so a tile this SDK lays out and a tile the router lays out
/// agree — and a connector added to the router's catalogue tomorrow is
/// designable today without an SDK release.
const DISPLAY_DEFAULTS_BY_PAYMENT_METHOD: &[(&str, PaneDisplayDefaults)] = &[
    (
        "wallet",
        PaneDisplayDefaults {
            icon: "wallet",
            category: "wallet",
        },
    ),
    (
        "card",
        PaneDisplayDefaults {
            icon: "card",
            category: "card",
        },
    ),
    (
        "card_redirect",
        PaneDisplayDefaults {
            icon: "card",
            category: "card",
        },
    ),
    (
        "pay_later",
        PaneDisplayDefaults {
            icon: "bnpl",
            category: "bnpl",
        },
    ),
    (
        "bank_redirect",
        PaneDisplayDefaults {
            icon: "bank",
            category: "bank_redirect",
        },
    ),
    (
        "bank_transfer",
        PaneDisplayDefaults {
            icon: "bank",
            category: "bank_transfer",
        },
    ),
    (
        "bank_debit",
        PaneDisplayDefaults {
            icon: "bank",
            category: "bank_transfer",
        },
    ),
    // Cryptomus and NowPayments publish the same `crypto` key on this rail,
    // and the router defaults both to the Bitcoin mark.
    (
        "crypto",
        PaneDisplayDefaults {
            icon: "crypto",
            category: "crypto",
        },
    ),
    // Skinsback, which has no mark: the router defaults it to `wallet` too.
    (
        "game_items",
        PaneDisplayDefaults {
            icon: "wallet",
            category: "game_items",
        },
    ),
    (
        "cash",
        PaneDisplayDefaults {
            icon: "cash",
            category: "cash",
        },
    ),
    (
        "voucher",
        PaneDisplayDefaults {
            icon: "cash",
            category: "cash",
        },
    ),
];

const DISPLAY_DEFAULTS_FALLBACK: PaneDisplayDefaults = PaneDisplayDefaults {
    icon: "wallet",
    category: "wallet",
};

/// What a new tile looks like before the merchant designs it.
///
/// The router serves capability, not presentation, so the glyph and the
/// section come from here and the accompanying text comes from the caller's
/// own locale files. A method with no entry still resolves — that is the point
/// of deriving from the routing key.
pub fn pane_display_defaults(info: Option<&PaneCapability>) -> PaneDisplayDefaults {
    let Some(info) = info else {
        return DISPLAY_DEFAULTS_FALLBACK;
    };
    if let Some((_, d)) = DISPLAY_DEFAULTS_BY_KEY.iter().find(|(k, _)| *k == info.key) {
        return *d;
    }
    if let Some((_, d)) = DISPLAY_DEFAULTS_BY_PAYMENT_METHOD
        .iter()
        .find(|(k, _)| *k == info.payment_method)
    {
        return *d;
    }
    DISPLAY_DEFAULTS_FALLBACK
}

// --- Validation ---------------------------------------------------------

/// Why a configured pane would not survive a save or a render.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PaneIssueCode {
    /// The connector's catalogue does not publish this key, so the router
    /// drops the row at render.
    MethodUnknown,
    /// The method's rail is not one the connector allows; the API refuses this
    /// at save time.
    RailNotAllowed,
    /// Past the router's per-connector cap of [`PANES_MAX`]; the row is stored
    /// but never rendered.
    OverCap,
    /// An earlier **enabled** row already claims this method. The router skips
    /// disabled rows and then dedupes, so the first enabled row renders and
    /// every later one is dropped in silence. Reported on the losing rows,
    /// never on the one that survives.
    DuplicateMethod,
}

/// One reason a configured list would not render as written.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PaneIssue {
    /// Index into the list handed to [`validate_panes`].
    pub index: usize,
    /// The row's method key.
    pub method: String,
    /// What is wrong with it.
    pub code: PaneIssueCode,
}

/// Check a configured list against one connector's catalogue, before writing
/// it to the connector account's metadata.
///
/// The API applies the same rules at save time, so this changes where the
/// merchant finds out, not whether they do — and a caller building an editor
/// would otherwise learn it from a bounced request with no row to point at. An
/// empty result means nothing here will be refused or silently dropped.
pub fn validate_panes(panes: &[Pane], catalog: &PanesConnectorCatalog) -> Vec<PaneIssue> {
    let mut issues = Vec::new();
    // Keyed on the catalogue's own key rather than the raw string, because
    // that is what the router dedupes on. Only enabled rows are recorded: a
    // disabled row never reaches the router's `seen` set, so it neither claims
    // a method nor loses to one.
    let mut claimed: Vec<&str> = Vec::new();
    for (index, pane) in panes.iter().enumerate() {
        match pane_capability(&pane.method, catalog) {
            None => issues.push(PaneIssue {
                index,
                method: pane.method.clone(),
                code: PaneIssueCode::MethodUnknown,
            }),
            Some(info) if !pane_rail_allowed(&info.rail, catalog) => issues.push(PaneIssue {
                index,
                method: pane.method.clone(),
                code: PaneIssueCode::RailNotAllowed,
            }),
            // Unknown and rail-refused rows are dropped before the router
            // dedupes, so they cannot claim a key — and reporting two codes
            // for one row would point the merchant at the wrong repair.
            Some(info) if pane.enabled => {
                if claimed.contains(&info.key.as_str()) {
                    issues.push(PaneIssue {
                        index,
                        method: pane.method.clone(),
                        code: PaneIssueCode::DuplicateMethod,
                    });
                } else {
                    claimed.push(info.key.as_str());
                }
            }
            Some(_) => {}
        }
        if index >= PANES_MAX {
            issues.push(PaneIssue {
                index,
                method: pane.method.clone(),
                code: PaneIssueCode::OverCap,
            });
        }
    }
    issues
}

/// Read a resolved tile's placement rule, across every payload version.
///
/// Prefer this to touching either field. They are independent on the wire — a
/// payload may carry either, both or neither — and each alone loses a
/// placement rule: `embedded_only` cannot express `external_only`, so such a
/// tile read through it renders inside the merchant iframe the merchant asked
/// to keep it out of; `visibility` is absent on a router that predates it, so
/// an `embedded_only` tile read through it alone renders at top level too,
/// duplicating a method Stripe's own form already offers there.
///
/// A recognised `visibility` wins. Otherwise the legacy boolean answers.
/// Neither path fails, and both degrade toward showing a tile — losing a
/// placement rule, never stranding a method.
pub fn pane_view_visibility(view: &PaneView) -> PaneVisibility {
    match view.visibility.as_deref() {
        Some("always") => PaneVisibility::Always,
        Some("embedded_only") => PaneVisibility::EmbeddedOnly,
        Some("external_only") => PaneVisibility::ExternalOnly,
        _ if view.embedded_only == Some(true) => PaneVisibility::EmbeddedOnly,
        _ => PaneVisibility::Always,
    }
}

// --- Focused checkout URL ------------------------------------------------

/// Inputs for [`focused_checkout_url`].
#[derive(Debug, Clone, Copy)]
pub struct FocusedCheckoutUrlParams<'a> {
    /// Base URL of the DeloPay hosted checkout, e.g.
    /// [`https://checkout.delopay.net`](crate::CHECKOUT_URL).
    pub checkout_base_url: &'a str,
    pub merchant_id: &'a str,
    pub payment_id: &'a str,
    /// The payment's `payment_link.payment_link_id`. When it is the opaque id
    /// the API issues (a lowercase, hyphenated UUID), the link is
    /// `/pay/{payment_link_id}`, which names neither the merchant nor the
    /// payment. `None`, or an older `plink_` id, keeps
    /// `/pay/{merchant_id}/{payment_id}`, which the checkout still serves.
    pub payment_link_id: Option<&'a str>,
    /// Pane method key to focus on (`apple_pay`, `klarna`, …).
    pub method: &'a str,
    /// Connector that owns the tile, forwarded as `connector=`.
    ///
    /// A bare `pane=` resolves to the **first payable match in server-sorted
    /// order**, which is unambiguous only while one connector publishes a
    /// given key. Stripe publishes `klarna` and so does the Klarna connector,
    /// so a deep link naming neither charges through whichever tile happens to
    /// sort first. Name the connector whenever you know it.
    ///
    /// `None` because links minted before this parameter existed are already
    /// in merchants' pages and still have to resolve.
    pub connector: Option<&'a str>,
    /// Merchant connector **account** that owns the tile, forwarded as `mca=`.
    ///
    /// Needed for the same reason as [`connector`](Self::connector), one level
    /// down: a shop may hold two enabled accounts of one connector, each
    /// publishing its own tile, and the two links would otherwise be
    /// identical. Only meaningful alongside `connector`.
    pub merchant_connector_id: Option<&'a str>,
    /// Optional buyer locale, forwarded as `?locale=`.
    pub locale: Option<&'a str>,
    /// Set when the merchant's checkout-custom-field answers are already
    /// persisted on the payment — forwarded as `cf=1` so the focused view
    /// skips asking a second time. Purely a UI hint: the values live on the
    /// intent either way, and the backend only accepts the merchant's
    /// configured field keys from a client, so a wrongly-set flag can at worst
    /// skip an informational prompt.
    pub custom_fields_collected: bool,
}

/// A payment link id the hosted checkout serves on its own, as
/// `/pay/{payment_link_id}`: the lowercase, hyphenated UUID the API issues.
fn is_opaque_payment_link_id(id: &str) -> bool {
    id.len() == 36
        && id.char_indices().all(|(i, c)| match i {
            8 | 13 | 18 | 23 => c == '-',
            _ => matches!(c, '0'..='9' | 'a'..='f'),
        })
}

/// Build the link to the **focused single-method checkout**: the DeloPay hosted
/// checkout rendered with one payment method, one button, no picker.
///
/// Two callers: the embedded checkout, which opens this in a new tab when a
/// buyer clicks a native pane tile, and a merchant running their own checkout,
/// who puts it behind their own button — the same mechanism without an iframe.
///
/// Open it **at the top level** (a new tab or a full-page navigation). The
/// whole point is that the top-level domain is the registered payment method
/// domain; rendering it in an iframe puts you back where you started. If you
/// open it with `window.open`, call that synchronously inside the click handler
/// or the popup blocker will eat it, and make sure any iframe you render
/// DeloPay in permits popups (`allow-popups`, plus
/// `allow-popups-to-escape-sandbox` under a restrictive `sandbox`).
pub fn focused_checkout_url(params: &FocusedCheckoutUrlParams<'_>) -> String {
    let base = params.checkout_base_url.trim_end_matches('/');
    let path = match params
        .payment_link_id
        .filter(|id| is_opaque_payment_link_id(id))
    {
        Some(payment_link_id) => format!("{base}/pay/{payment_link_id}"),
        None => format!(
            "{base}/pay/{}/{}",
            encode_path_segment(params.merchant_id),
            encode_path_segment(params.payment_id),
        ),
    };
    let mut url = format!("{path}?pane={}", encode_query_value(params.method));
    // Parameter order matches the embedded checkout's own focused link, so a
    // merchant's deep link and a tile click produce the same string for the
    // same tile. A blank value is treated as absent rather than emitted empty:
    // `connector=` would otherwise read as a connector named "" instead of as
    // "not specified".
    if let Some(connector) = params.connector.map(str::trim).filter(|c| !c.is_empty()) {
        url.push_str("&connector=");
        url.push_str(&encode_query_value(connector));
    }
    if let Some(mca) = params
        .merchant_connector_id
        .map(str::trim)
        .filter(|m| !m.is_empty())
    {
        url.push_str("&mca=");
        url.push_str(&encode_query_value(mca));
    }
    if let Some(locale) = params.locale.filter(|l| !l.is_empty()) {
        url.push_str("&locale=");
        url.push_str(&encode_query_value(locale));
    }
    if params.custom_fields_collected {
        url.push_str("&cf=1");
    }
    url
}

/// Percent-encode a URL path segment, matching TypeScript's
/// `encodeURIComponent` on the id alphabets the API actually issues.
fn encode_path_segment(s: &str) -> String {
    percent_encode(s, false)
}

/// Encode a query value the way `URLSearchParams` does (form encoding: space
/// becomes `+`).
fn encode_query_value(s: &str) -> String {
    percent_encode(s, true)
}

fn percent_encode(s: &str, form: bool) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' => out.push(b as char),
            b'~' if !form => out.push('~'),
            b'*' if form => out.push('*'),
            b' ' if form => out.push('+'),
            _ => {
                out.push('%');
                out.push_str(&format!("{b:02X}"));
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    // --- catalog ----------------------------------------------------------

    #[test]
    fn catalog_has_unique_keys() {
        let mut keys: Vec<_> = STRIPE_FALLBACK_PANE_METHODS.iter().map(|m| m.key).collect();
        keys.sort_unstable();
        keys.dedup();
        assert_eq!(keys.len(), STRIPE_FALLBACK_PANE_METHODS.len());
    }

    #[test]
    fn catalog_never_offers_the_card_rail() {
        for key in ["card", "credit", "debit"] {
            assert!(pane_method_info(key).is_none());
        }
    }

    #[test]
    fn catalog_marks_exactly_the_browser_wallets_as_the_wallet_rail() {
        let wallets: Vec<_> = STRIPE_FALLBACK_PANE_METHODS
            .iter()
            .filter(|m| m.rail == PaneRail::Wallet)
            .map(|m| m.key)
            .collect();
        assert_eq!(wallets, ["apple_pay", "google_pay", "link"]);
    }

    // --- decode -----------------------------------------------------------

    #[test]
    fn decode_returns_none_for_a_non_array() {
        assert!(decode_panes(&Value::Null).is_none());
        assert!(decode_panes(&json!({})).is_none());
        assert!(decode_panes(&json!("[]")).is_none());
    }

    #[test]
    fn decode_reads_a_stored_row() {
        let decoded = decode_panes(&json!([{
            "method": "apple_pay",
            "enabled": true,
            "label": "Apple Pay",
            "label_translations": {"de": "Apple Pay DE"},
            "sublabel": "",
            "category": "wallet",
            "icon": "apple",
            "display_order": 2,
        }]))
        .unwrap();
        assert_eq!(decoded.len(), 1);
        let pane = &decoded[0];
        assert_eq!(pane.method, "apple_pay");
        assert!(pane.enabled);
        assert_eq!(pane.label, "Apple Pay");
        assert_eq!(pane.label_translations["de"], "Apple Pay DE");
        assert_eq!(pane.sublabel.as_deref(), Some(""));
        assert_eq!(pane.category, "wallet");
        assert_eq!(pane.icon, "apple");
        assert_eq!(pane.display_order, 2);
    }

    #[test]
    fn decode_drops_methodless_rows_and_keeps_the_first_duplicate() {
        let decoded = decode_panes(&json!([
            {"label": "nameless"},
            {"method": "klarna", "label": "first"},
            {"method": "klarna", "label": "second"},
        ]))
        .unwrap();
        assert_eq!(decoded.len(), 1);
        assert_eq!(decoded[0].label, "first");
    }

    // The router skips disabled rows before deduping, so buyers see the
    // enabled Klarna tile. Keeping the disabled row would show the merchant a
    // pane that is off while it is live — and delete it on the next save.
    #[test]
    fn decode_keeps_the_enabled_duplicate_the_router_renders() {
        let decoded = decode_panes(&json!([
            {"method": "klarna", "enabled": false},
            {"method": "klarna", "enabled": true, "label": "Later"},
        ]))
        .unwrap();
        assert_eq!(decoded.len(), 1);
        assert!(decoded[0].enabled);
        assert_eq!(decoded[0].label, "Later");
    }

    #[test]
    fn decode_caps_the_list() {
        let rows: Vec<Value> = (0..PANES_MAX + 5)
            .map(|i| json!({"method": format!("m{i}")}))
            .collect();
        assert_eq!(decode_panes(&Value::Array(rows)).unwrap().len(), PANES_MAX);
    }

    #[test]
    fn decode_distinguishes_an_absent_sublabel_from_a_deliberately_blank_one() {
        let absent = decode_panes(&json!([{"method": "apple_pay"}])).unwrap();
        assert_eq!(absent[0].sublabel, None);
        let blank = decode_panes(&json!([{"method": "apple_pay", "sublabel": ""}])).unwrap();
        assert_eq!(blank[0].sublabel.as_deref(), Some(""));
    }

    #[test]
    fn decode_tolerates_junk_in_every_optional_field() {
        let decoded = decode_panes(&json!([{
            "method": "ideal",
            "enabled": "yes",
            "label": 42,
            "label_translations": {"de": 7, "fr": "Banque"},
            "category": null,
            "display_order": "nope",
        }]))
        .unwrap();
        let pane = &decoded[0];
        assert_eq!(pane.method, "ideal");
        // Only an explicit `false` disables — anything else stays enabled.
        assert!(pane.enabled);
        assert_eq!(pane.label, "");
        assert_eq!(pane.label_translations.len(), 1);
        assert_eq!(pane.label_translations["fr"], "Banque");
        assert_eq!(pane.category, "");
        assert_eq!(pane.display_order, 0);
    }

    #[test]
    fn decode_accepts_a_numeric_string_display_order() {
        let decoded = decode_panes(&json!([{"method": "ideal", "display_order": "3"}])).unwrap();
        assert_eq!(decoded[0].display_order, 3);
    }

    #[test]
    fn decode_clamps_display_order_into_the_router_i32_range() {
        // The router's wire type is an `i32`; an out-of-range value would
        // fail its strict row decode and drop the row whole. Clamped, the
        // round-trip emits a value the router accepts — and is stable.
        let decoded = decode_panes(&json!([
            {"method": "ideal", "display_order": 3_000_000_000_i64},
            {"method": "klarna", "display_order": -3_000_000_000_i64},
        ]))
        .unwrap();
        assert_eq!(decoded[0].display_order, i64::from(i32::MAX));
        assert_eq!(decoded[1].display_order, i64::from(i32::MIN));
        let round_tripped = decode_panes(&encode_panes(&decoded)).unwrap();
        assert_eq!(round_tripped, decoded);
    }

    #[test]
    fn encode_clamps_display_order_that_never_went_through_decode() {
        // A caller-constructed pane can hold any `i64` (e.g. epoch-millis
        // ordering); written verbatim it would fail the router's strict `i32`
        // row decode and silently delete the pane at render.
        let mut pane = default_pane("ideal", &STRIPE_FALLBACK_PANE_CATALOG);
        pane.display_order = 1_753_000_000_000;
        let encoded = encode_panes(&[pane]);
        assert_eq!(
            encoded[0].get("display_order"),
            Some(&Value::from(i32::MAX))
        );
    }

    // --- encode -----------------------------------------------------------

    #[test]
    fn encode_round_trips_through_decode() {
        let mut pane = default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
        pane.label = "Wallet".into();
        pane.label_translations
            .insert("de".into(), "Geldbörse".into());
        pane.display_order = 3;
        let round_tripped = decode_panes(&encode_panes(std::slice::from_ref(&pane))).unwrap();
        assert_eq!(round_tripped[0], pane);
    }

    /// Copy is left to the router; presentation is not.
    ///
    /// `label` and `sublabel` stay absent because empty means "use the
    /// catalogue default", which the router resolves at render and ships no
    /// copy here to mirror. `category` and `icon` are written, because the
    /// router serves capability rather than presentation — a tile with neither
    /// is a blank one.
    #[test]
    fn encode_omits_the_copy_and_keeps_the_presentation() {
        let encoded = encode_panes(&[default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG)]);
        let row = encoded[0].as_object().unwrap();
        assert!(!row.contains_key("label"));
        assert!(!row.contains_key("sublabel"));
        assert!(!row.contains_key("icon_svg"));
        assert_eq!(row["method"], "apple_pay");
        assert_eq!(row["category"], "wallet");
        assert_eq!(row["icon"], "apple");
    }

    #[test]
    fn encode_preserves_a_deliberately_blank_sublabel() {
        let mut pane = default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
        pane.sublabel = Some(String::new());
        let encoded = encode_panes(std::slice::from_ref(&pane));
        assert_eq!(encoded[0]["sublabel"], "");
    }

    #[test]
    fn encode_drops_blank_translation_entries() {
        let mut pane = default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
        pane.label_translations.insert("de".into(), "   ".into());
        pane.label_translations
            .insert("fr".into(), "Portefeuille".into());
        let encoded = encode_panes(std::slice::from_ref(&pane));
        assert_eq!(
            encoded[0]["label_translations"],
            json!({"fr": "Portefeuille"})
        );
    }

    // --- visibility -------------------------------------------------------

    #[test]
    fn visibility_defaults_to_always_and_round_trips_embedded_only() {
        let decoded = decode_panes(&json!([{"method": "apple_pay"}])).unwrap();
        assert_eq!(decoded[0].visibility, PaneVisibility::Always);
        let mut pane = default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
        pane.visibility = PaneVisibility::EmbeddedOnly;
        let round_tripped = decode_panes(&encode_panes(std::slice::from_ref(&pane))).unwrap();
        assert_eq!(round_tripped[0].visibility, PaneVisibility::EmbeddedOnly);
    }

    #[test]
    fn visibility_degrades_an_unknown_stored_value_instead_of_dropping_the_row() {
        let decoded =
            decode_panes(&json!([{"method": "apple_pay", "visibility": "sometimes"}])).unwrap();
        assert_eq!(decoded.len(), 1);
        assert_eq!(decoded[0].visibility, PaneVisibility::Always);
    }

    // --- open target ------------------------------------------------------

    #[test]
    fn open_in_defaults_to_tab_and_round_trips_popup() {
        let decoded = decode_panes(&json!([{"method": "apple_pay"}])).unwrap();
        assert_eq!(decoded[0].open_in, PaneOpenTarget::Tab);
        let mut pane = default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
        pane.open_in = PaneOpenTarget::Popup;
        let round_tripped = decode_panes(&encode_panes(std::slice::from_ref(&pane))).unwrap();
        assert_eq!(round_tripped[0].open_in, PaneOpenTarget::Popup);
    }

    /// A blob written by a newer editor must stay readable here rather than
    /// costing the merchant the whole row.
    #[test]
    fn open_in_degrades_an_unknown_stored_value_instead_of_dropping_the_row() {
        let decoded = decode_panes(&json!([{"method": "apple_pay", "open_in": "modal"}])).unwrap();
        assert_eq!(decoded.len(), 1);
        assert_eq!(decoded[0].open_in, PaneOpenTarget::Tab);
    }

    /// The resolved wire shape leaves `open_in` absent on older backends, and
    /// absent must stay distinguishable from an explicit `"tab"` so a caller
    /// can tell "the backend does not know this field" from "the merchant
    /// chose a tab".
    #[test]
    fn native_pane_view_keeps_open_in_optional() {
        let older: PaneView =
            serde_json::from_value(json!({"method": "apple_pay", "rail": "wallet"})).unwrap();
        assert_eq!(older.open_in, None);
        let newer: PaneView = serde_json::from_value(
            json!({"method": "apple_pay", "rail": "wallet", "open_in": "popup"}),
        )
        .unwrap();
        assert_eq!(newer.open_in.as_deref(), Some("popup"));
    }

    // --- clone ------------------------------------------------------------

    #[test]
    fn clone_copies_the_translation_maps_rather_than_sharing_them() {
        let mut pane = default_pane("klarna", &STRIPE_FALLBACK_PANE_CATALOG);
        pane.label_translations.insert("de".into(), "Klarna".into());
        let mut copy = pane.clone();
        copy.label_translations
            .insert("de".into(), "changed".into());
        assert_eq!(pane.label_translations["de"], "Klarna");
    }

    // --- focused checkout URL --------------------------------------------

    #[test]
    fn focused_url_builds_a_top_level_single_method_link() {
        let url = focused_checkout_url(&FocusedCheckoutUrlParams {
            checkout_base_url: "https://checkout.delopay.net",
            merchant_id: "merchant_1",
            payment_id: "pay_123",
            payment_link_id: None,
            method: "apple_pay",
            connector: None,
            merchant_connector_id: None,
            locale: None,
            custom_fields_collected: false,
        });
        assert_eq!(
            url,
            "https://checkout.delopay.net/pay/merchant_1/pay_123?pane=apple_pay"
        );
    }

    #[test]
    fn focused_url_tolerates_a_trailing_slash_and_adds_the_locale() {
        let url = focused_checkout_url(&FocusedCheckoutUrlParams {
            checkout_base_url: "https://checkout.delopay.net/",
            merchant_id: "merchant_1",
            payment_id: "pay_123",
            payment_link_id: None,
            method: "klarna",
            connector: None,
            merchant_connector_id: None,
            locale: Some("de"),
            custom_fields_collected: false,
        });
        assert_eq!(
            url,
            "https://checkout.delopay.net/pay/merchant_1/pay_123?pane=klarna&locale=de"
        );
    }

    #[test]
    fn focused_url_names_only_the_opaque_payment_link_id() {
        let url = focused_checkout_url(&FocusedCheckoutUrlParams {
            checkout_base_url: "https://checkout.delopay.net",
            merchant_id: "merchant_1",
            payment_id: "ORD-08467086",
            payment_link_id: Some("0b9a6e3c-6f1d-4a57-9a1e-2f4c8d7b5e10"),
            method: "apple_pay",
            connector: None,
            merchant_connector_id: None,
            locale: None,
            custom_fields_collected: false,
        });
        assert_eq!(
            url,
            "https://checkout.delopay.net/pay/0b9a6e3c-6f1d-4a57-9a1e-2f4c8d7b5e10?pane=apple_pay"
        );
    }

    #[test]
    fn focused_url_keeps_the_merchant_and_payment_path_for_other_link_ids() {
        for payment_link_id in [
            Some("plink_abcdefghij0123456789"),
            Some("0B9A6E3C-6F1D-4A57-9A1E-2F4C8D7B5E10"),
            Some("0b9a6e3c6f1d4a579a1e2f4c8d7b5e10"),
            None,
        ] {
            let url = focused_checkout_url(&FocusedCheckoutUrlParams {
                checkout_base_url: "https://checkout.delopay.net",
                merchant_id: "merchant_1",
                payment_id: "pay_123",
                payment_link_id,
                method: "apple_pay",
                connector: None,
                merchant_connector_id: None,
                locale: None,
                custom_fields_collected: false,
            });
            assert_eq!(
                url, "https://checkout.delopay.net/pay/merchant_1/pay_123?pane=apple_pay",
                "{payment_link_id:?}"
            );
        }
    }

    #[test]
    fn focused_url_escapes_path_segments() {
        let url = focused_checkout_url(&FocusedCheckoutUrlParams {
            checkout_base_url: "https://checkout.delopay.net",
            merchant_id: "a/b",
            payment_id: "c d",
            payment_link_id: None,
            method: "ideal",
            connector: None,
            merchant_connector_id: None,
            locale: None,
            custom_fields_collected: false,
        });
        assert_eq!(
            url,
            "https://checkout.delopay.net/pay/a%2Fb/c%20d?pane=ideal"
        );
    }

    #[test]
    fn focused_url_adds_the_custom_fields_hint() {
        let url = focused_checkout_url(&FocusedCheckoutUrlParams {
            checkout_base_url: "https://checkout.delopay.net",
            merchant_id: "merchant_1",
            payment_id: "pay_123",
            payment_link_id: None,
            method: "apple_pay",
            connector: None,
            merchant_connector_id: None,
            locale: None,
            custom_fields_collected: true,
        });
        assert_eq!(
            url,
            "https://checkout.delopay.net/pay/merchant_1/pay_123?pane=apple_pay&cf=1"
        );
    }

    // --- wire view --------------------------------------------------------

    /// Mutation: drop `routed`, `method_logos`, `icon_image` or `rapyd_toolkit`
    /// from `PaneView` and the value lands in `extra` instead; the typed
    /// assertion fails.
    #[test]
    fn native_pane_view_reads_routing_artwork_and_rapyd_toolkit() {
        let view: PaneView = serde_json::from_value(json!({
            "method": "rapyd_card",
            "rail": "hosted_element",
            "label": "Card",
            "display_order": 2,
            "icon_image": "<svg xmlns='http://www.w3.org/2000/svg'/>",
            "method_logos": ["visa", "mastercard"],
            "routed": true,
            "rapyd_toolkit": {"sandbox": true, "future_toolkit_field": 1},
        }))
        .unwrap();
        assert_eq!(view.routed, Some(true));
        assert_eq!(view.method_logos, ["visa", "mastercard"]);
        assert_eq!(
            view.icon_image.as_deref(),
            Some("<svg xmlns='http://www.w3.org/2000/svg'/>")
        );
        let toolkit = view.rapyd_toolkit.as_ref().unwrap();
        assert!(toolkit.sandbox);
        assert_eq!(toolkit.extra["future_toolkit_field"], 1);
        assert!(view.extra.is_empty(), "{:?}", view.extra);

        // A payload that predates the fields reads as "absent", not as a
        // decode failure.
        let older: PaneView =
            serde_json::from_value(json!({"method": "klarna", "rail": "redirect"})).unwrap();
        assert_eq!(older.routed, None);
        assert!(older.method_logos.is_empty());
        assert!(older.icon_image.is_none());
        assert!(older.rapyd_toolkit.is_none());
    }

    #[test]
    fn native_pane_view_deserializes_from_the_wire_shape() {
        let view: PaneView = serde_json::from_value(json!({
            "method": "klarna",
            "rail": "redirect",
            "label": "Klarna",
            "sublabel": "Pay later",
            "category": "bnpl",
            "icon": "bnpl",
            "display_order": 1,
            "payment_method": "pay_later",
            "payment_method_type": "klarna",
            "payment_method_data": {"pay_later": {"klarna_redirect": {}}},
            "requires_billing_country": true,
            "some_future_field": "kept",
        }))
        .unwrap();
        assert_eq!(view.method, "klarna");
        assert_eq!(view.rail, "redirect");
        assert_eq!(view.display_order, 1);
        assert_eq!(view.payment_method.as_deref(), Some("pay_later"));
        assert_eq!(view.payment_method_type.as_deref(), Some("klarna"));
        assert_eq!(view.requires_billing_country, Some(true));
        assert_eq!(view.embedded_only, None);
        // Response model — unknown wire fields are kept in `extra` (and
        // re-emitted on serialize), not dropped.
        assert_eq!(
            view.extra.get("some_future_field"),
            Some(&Value::String("kept".into()))
        );
        let reserialized = serde_json::to_value(&view).unwrap();
        assert_eq!(reserialized["some_future_field"], "kept");
    }

    // --- checkout events --------------------------------------------------

    #[test]
    fn checkout_event_vocabulary_matches_the_router_enum() {
        assert_eq!(
            CHECKOUT_EVENT_KINDS,
            [
                "native_pane_selected",
                "native_pane_tab_opened",
                "native_pane_tab_blocked",
                "native_pane_abandoned",
                "native_pane_returned",
            ]
        );
    }

    // --- live catalogue ---------------------------------------------------

    fn catalog_response() -> PanesCatalogResponse {
        serde_json::from_value(json!({
            "connectors": [
                {
                    "connector": "cryptomus",
                    "allowed_rails": ["redirect"],
                    "methods": [
                        {
                            "key": "crypto",
                            "rail": "redirect",
                            "payment_method": "crypto",
                            "payment_method_type": "crypto_currency",
                            "requires_billing_country": false
                        },
                        {
                            "key": "apple_pay",
                            "rail": "wallet",
                            "payment_method": "wallet",
                            "payment_method_type": "apple_pay",
                            "requires_billing_country": false
                        }
                    ]
                }
            ]
        }))
        .unwrap()
    }

    /// A connector the response does not name reads as "offer nothing", not as
    /// an error and not as the Stripe table.
    ///
    /// Mutation: return the fallback catalogue for an unnamed connector and
    /// this fails — which would offer a merchant Apple Pay on a connector that
    /// cannot charge it.
    #[test]
    fn an_unknown_connector_gets_an_empty_catalogue() {
        let empty = pane_catalog_for(&catalog_response(), "adyen");
        assert_eq!(empty.connector, "adyen");
        assert!(empty.methods.is_empty());
        assert!(empty.allowed_rails.is_empty());
    }

    /// A method on a rail the connector does not allow is filtered out, even
    /// though the catalogue lists it: the save would bounce.
    ///
    /// Mutation: have `offerable_pane_methods` return every method and this
    /// fails.
    #[test]
    fn a_method_on_a_disallowed_rail_is_not_offerable() {
        let catalog = pane_catalog_for(&catalog_response(), "cryptomus");
        let offerable: Vec<&str> = offerable_pane_methods(&catalog)
            .into_iter()
            .map(|m| m.key.as_str())
            .collect();
        assert_eq!(offerable, ["crypto"]);
        assert!(!pane_rail_allowed("wallet", &catalog));
    }

    /// A connector this crate has never heard of still gets a designed tile,
    /// because the defaults derive from the catalogue's routing key rather
    /// than from a Stripe-keyed table.
    ///
    /// Mutation: drop the `payment_method` arm of `pane_display_defaults` and
    /// this falls back to a generic wallet glyph, which is the blank tile this
    /// exists to avoid.
    #[test]
    fn a_pane_for_an_unknown_connector_is_designed_not_blank() {
        let catalog = pane_catalog_for(&catalog_response(), "cryptomus");
        let pane = default_pane("crypto", &catalog);
        assert_eq!(pane.icon, "crypto");
        assert_eq!(pane.category, "crypto");
    }

    /// A method nothing knows still yields a usable tile rather than an empty
    /// one.
    #[test]
    fn an_unknown_method_falls_back_to_a_wallet_tile() {
        let pane = default_pane("what_is_this", &empty_pane_catalog("mystery"));
        assert_eq!(pane.icon, "wallet");
        assert_eq!(pane.category, "wallet");
    }

    // --- validation -------------------------------------------------------

    /// The four ways a stored list quietly renders as something else.
    ///
    /// The duplicate rule is the subtle one: the router skips disabled rows
    /// and only then dedupes, so a disabled row neither claims a method nor
    /// loses to one, and the *second enabled* row is the one dropped.
    ///
    /// Mutation: record disabled rows in the claimed set and the disabled
    /// `crypto` row below starts stealing the key from the enabled one.
    #[test]
    fn validation_reports_what_the_router_would_drop() {
        let catalog = pane_catalog_for(&catalog_response(), "cryptomus");
        let mut disabled_crypto = default_pane("crypto", &catalog);
        disabled_crypto.enabled = false;

        let panes = vec![
            disabled_crypto,
            default_pane("crypto", &catalog),
            default_pane("crypto", &catalog),
            default_pane("apple_pay", &catalog),
            default_pane("not_a_method", &catalog),
        ];
        let issues = validate_panes(&panes, &catalog);

        assert_eq!(
            issues,
            vec![
                PaneIssue {
                    index: 2,
                    method: "crypto".to_string(),
                    code: PaneIssueCode::DuplicateMethod,
                },
                PaneIssue {
                    index: 3,
                    method: "apple_pay".to_string(),
                    code: PaneIssueCode::RailNotAllowed,
                },
                PaneIssue {
                    index: 4,
                    method: "not_a_method".to_string(),
                    code: PaneIssueCode::MethodUnknown,
                },
            ]
        );
    }

    /// Rows past the cap are stored and never rendered, so they are reported
    /// even when everything about them is otherwise valid.
    #[test]
    fn validation_reports_rows_past_the_cap() {
        let catalog = &STRIPE_FALLBACK_PANE_CATALOG;
        let mut panes: Vec<Pane> = (0..=PANES_MAX)
            .map(|_| default_pane("apple_pay", catalog))
            .collect();
        for pane in panes.iter_mut().skip(1) {
            pane.enabled = false;
        }
        let issues = validate_panes(&panes, catalog);
        assert_eq!(
            issues,
            vec![PaneIssue {
                index: PANES_MAX,
                method: "apple_pay".to_string(),
                code: PaneIssueCode::OverCap,
            }]
        );
    }

    // --- resolved placement ------------------------------------------------

    /// Each field alone loses a placement rule; read together they do not.
    ///
    /// Mutation: read `embedded_only` first and an `external_only` tile starts
    /// rendering inside the merchant iframe the merchant asked to keep it out
    /// of. Ignore the boolean and a tile from a router predating `visibility`
    /// renders at top level too, duplicating a method Stripe's own form
    /// already offers there.
    #[test]
    fn placement_reads_both_fields_across_payload_versions() {
        let newer = PaneView {
            visibility: Some("external_only".to_string()),
            embedded_only: Some(false),
            ..PaneView::default()
        };
        assert_eq!(pane_view_visibility(&newer), PaneVisibility::ExternalOnly);

        let older = PaneView {
            visibility: None,
            embedded_only: Some(true),
            ..PaneView::default()
        };
        assert_eq!(pane_view_visibility(&older), PaneVisibility::EmbeddedOnly);

        // A value from a router newer than this crate: unrecognised, so the
        // boolean answers, and the tile is shown rather than stranded.
        let unknown = PaneView {
            visibility: Some("only_on_tuesdays".to_string()),
            embedded_only: None,
            ..PaneView::default()
        };
        assert_eq!(pane_view_visibility(&unknown), PaneVisibility::Always);
    }

    /// The stored setting round-trips through the codec, including the third
    /// state a `bool` cannot carry.
    #[test]
    fn external_only_survives_the_codec() {
        let mut pane = default_pane("apple_pay", &STRIPE_FALLBACK_PANE_CATALOG);
        pane.visibility = PaneVisibility::ExternalOnly;
        let round_tripped = decode_panes(&encode_panes(std::slice::from_ref(&pane))).unwrap();
        assert_eq!(round_tripped[0].visibility, PaneVisibility::ExternalOnly);
    }

    // --- focused link ------------------------------------------------------

    /// Naming the tile's owner is what makes a deep link resolve to one tile.
    ///
    /// Mutation: drop either parameter from the URL and a merchant running two
    /// connectors that publish one key gets whichever tile sorts first.
    #[test]
    fn the_focused_link_can_name_the_connector_and_the_account() {
        let url = focused_checkout_url(&FocusedCheckoutUrlParams {
            checkout_base_url: "https://checkout.delopay.net",
            merchant_id: "merchant_1",
            payment_id: "pay_123",
            payment_link_id: None,
            method: "klarna",
            connector: Some("klarna"),
            merchant_connector_id: Some("mca_1"),
            locale: Some("de"),
            custom_fields_collected: false,
        });
        assert_eq!(
            url,
            "https://checkout.delopay.net/pay/merchant_1/pay_123\
             ?pane=klarna&connector=klarna&mca=mca_1&locale=de"
        );
    }

    /// A blank owner is absent, not an owner named "".
    ///
    /// Mutation: emit the parameter unconditionally and the link asks for a
    /// connector with an empty name, which resolves to nothing.
    #[test]
    fn a_blank_connector_is_omitted_rather_than_sent_empty() {
        let url = focused_checkout_url(&FocusedCheckoutUrlParams {
            checkout_base_url: "https://checkout.delopay.net",
            merchant_id: "merchant_1",
            payment_id: "pay_123",
            payment_link_id: None,
            method: "apple_pay",
            connector: Some("   "),
            merchant_connector_id: None,
            locale: None,
            custom_fields_collected: false,
        });
        assert_eq!(
            url,
            "https://checkout.delopay.net/pay/merchant_1/pay_123?pane=apple_pay"
        );
    }
}