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
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
//! Checkout branding: typed shape, design tokens, palettes, persistence codec,
//! CSS sanitizer, and the `--dp-*` CSS custom-property set.
//!
//! This is a direct port of the TypeScript SDK's `branding` module, and it is
//! wire-compatible with it: the merchant control-center writes the encoded form
//! and the buyer-facing checkout reads it back, so [`encode_branding`] /
//! [`decode_branding`] and [`encode_badges`] / [`decode_badges`] must keep
//! producing exactly what the TypeScript implementation produces.
//!
//! It has no HTTP dependencies and is therefore always compiled, including in
//! the `default-features = false` build.
//!
//! # Persistence layout
//!
//! Top-level fields own the "loud" tokens (logo, theme, `payment_button_*`,
//! `background_colour`, …). Everything else lives in `sdk_ui_rules.branding` as
//! a nested string-keyed map — booleans and numbers round-trip as strings, and
//! the trust-badge list is JSON-stringified.
//!
//! # Example
//!
//! ```
//! use delopay::branding::{self, CheckoutBranding, CornerRadius};
//!
//! let mut b = branding::default_branding();
//! b.radius_button = CornerRadius::Pill;
//!
//! let encoded = branding::encode_branding(&b);
//! assert_eq!(encoded.payment_button_colour, b.button_background);
//!
//! let source: branding::BrandingSource =
//!     serde_json::from_value(serde_json::to_value(&encoded).unwrap()).unwrap();
//! let round_tripped: CheckoutBranding = branding::decode_branding(Some(&source));
//! assert_eq!(round_tripped.radius_button, CornerRadius::Pill);
//! ```

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

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

use crate::core::custom_fields::{
    CheckoutCustomField, CustomFieldTranslations, decode_custom_fields, encode_custom_fields,
    parse_custom_fields_loose,
};

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

/// Internal glue so the generic `pick_enum` helper can parse any wire enum.
trait WireEnum: Sized + Copy {
    fn parse_wire(value: &str) -> Option<Self>;
}

/// Declare a closed enum whose wire representation is a fixed string, matching
/// the TypeScript string-union member for member.
macro_rules! wire_enum {
    (
        $(#[$meta:meta])*
        $name:ident {
            $( $(#[$vmeta:meta])* $variant:ident => $wire:literal ),+ $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum $name {
            $( $(#[$vmeta])* $variant, )+
        }

        impl $name {
            /// The wire (JSON) string for this variant.
            pub const fn as_str(self) -> &'static str {
                match self { $( Self::$variant => $wire, )+ }
            }

            /// Parse a wire string. Returns `None` for any value outside the set.
            pub fn from_wire(value: &str) -> Option<Self> {
                match value {
                    $( $wire => Some(Self::$variant), )+
                    _ => None,
                }
            }
        }

        impl WireEnum for $name {
            fn parse_wire(value: &str) -> Option<Self> { Self::from_wire(value) }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str(self.as_str())
            }
        }

        impl Serialize for $name {
            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
                s.serialize_str(self.as_str())
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
                let raw = String::deserialize(d)?;
                Self::from_wire(&raw).ok_or_else(|| {
                    serde::de::Error::custom(format!(
                        concat!("unknown ", stringify!($name), " value: {}"),
                        raw
                    ))
                })
            }
        }
    };
}

wire_enum! {
    /// Corner-radius scale. `Pill` is only legitimate on buttons and badges.
    CornerRadius {
        /// No rounding.
        Square => "square",
        /// 6px.
        Small => "small",
        /// 12px.
        Medium => "medium",
        /// 20px.
        Large => "large",
        /// Fully rounded (999px).
        Pill => "pill",
    }
}

wire_enum! {
    /// Corner-radius scale without `pill`.
    ///
    /// Surfaces and inputs never make sense pill-shaped (a pill input ends up
    /// with half-circle ends crammed against text). The form picker only
    /// exposes these four; if a stale `"pill"` value lands here from older
    /// saved data, [`decode_branding`] drops it back to `Medium`.
    NonPillRadius {
        /// No rounding.
        Square => "square",
        /// 6px.
        Small => "small",
        /// 12px.
        Medium => "medium",
        /// 20px.
        Large => "large",
    }
}

impl From<NonPillRadius> for CornerRadius {
    fn from(value: NonPillRadius) -> Self {
        match value {
            NonPillRadius::Square => CornerRadius::Square,
            NonPillRadius::Small => CornerRadius::Small,
            NonPillRadius::Medium => CornerRadius::Medium,
            NonPillRadius::Large => CornerRadius::Large,
        }
    }
}

wire_enum! {
    /// Spacing scale for surface padding and vertical rhythm.
    SpacingScale {
        /// Tightest.
        Compact => "compact",
        /// Default.
        Comfortable => "comfortable",
        /// Airiest.
        Spacious => "spacious",
    }
}

wire_enum! {
    /// Size scale for input and pay-button height.
    SizeScale {
        /// Small.
        Sm => "sm",
        /// Medium (default).
        Md => "md",
        /// Large.
        Lg => "lg",
    }
}

wire_enum! {
    /// How the checkout surface is separated from the page background.
    SurfaceStyle {
        /// No border, no shadow.
        Flat => "flat",
        /// 1px border in the brand's border colour.
        Outlined => "outlined",
        /// Soft drop shadow.
        Elevated => "elevated",
    }
}

wire_enum! {
    /// Self-hostable font families offered by the branding form.
    FontFamily {
        /// Inter.
        Inter => "inter",
        /// The platform UI font.
        System => "system",
        /// Georgia-led serif stack.
        Serif => "serif",
        /// Monospace stack.
        Mono => "mono",
        /// Roboto.
        Roboto => "roboto",
        /// Poppins.
        Poppins => "poppins",
        /// Manrope.
        Manrope => "manrope",
        /// DM Sans.
        DmSans => "dm-sans",
        /// Space Grotesk.
        SpaceGrotesk => "space-grotesk",
        /// IBM Plex Sans.
        PlexSans => "plex-sans",
        /// Work Sans.
        WorkSans => "work-sans",
        /// Open Sans.
        OpenSans => "open-sans",
        /// Lora.
        Lora => "lora",
        /// Playfair Display.
        Playfair => "playfair",
        /// IBM Plex Mono.
        PlexMono => "plex-mono",
        /// JetBrains Mono.
        JetbrainsMono => "jetbrains-mono",
    }
}

wire_enum! {
    /// Heading font weight.
    FontWeight {
        /// 400.
        Regular => "regular",
        /// 500.
        Medium => "medium",
        /// 600.
        Semibold => "semibold",
        /// 700.
        Bold => "bold",
    }
}

wire_enum! {
    /// Overall page layout.
    LayoutStyle {
        /// Single column.
        Compact => "compact",
        /// Form and order summary side by side.
        Split => "split",
    }
}

wire_enum! {
    /// Which side the order summary sits on in the `Split` layout.
    SummaryPosition {
        /// Summary on the left.
        Left => "left",
        /// Summary on the right.
        Right => "right",
    }
}

wire_enum! {
    /// Stripe Elements label mode.
    ///
    /// Stripe only supports two modes; a "floating" label is not a Stripe
    /// concept, so a persisted `"floating"` decodes to [`LabelStyle::Above`].
    LabelStyle {
        /// Label rendered above the field.
        Above => "above",
        /// Label hidden.
        Hidden => "hidden",
    }
}

wire_enum! {
    /// The legacy `payment_form_label_type` wire vocabulary.
    ///
    /// [`encode_branding`] maps [`LabelStyle::Hidden`] back onto
    /// [`LegacyLabelType::Never`], which is what the API's enum understands.
    LegacyLabelType {
        /// Label rendered above the field.
        Above => "above",
        /// Label hidden.
        Never => "never",
    }
}

wire_enum! {
    /// Stripe Elements payment-method layout.
    ///
    /// Honoured inside the Stripe card pane only — other connector panes stack
    /// vertically regardless of this setting.
    PaymentLayout {
        /// Tabbed.
        Tabs => "tabs",
        /// Accordion.
        Accordion => "accordion",
        /// Accordion with spacing between items.
        SpacedAccordion => "spaced_accordion",
    }
}

wire_enum! {
    /// Merchant logo silhouette.
    LogoShape {
        /// Sharp corners.
        Square => "square",
        /// Rounded corners.
        Rounded => "rounded",
        /// Circular.
        Circle => "circle",
    }
}

wire_enum! {
    /// Merchant logo size.
    LogoSize {
        /// 36px.
        Sm => "sm",
        /// 48px.
        Md => "md",
        /// 64px.
        Lg => "lg",
    }
}

// --- Types --------------------------------------------------------------

wire_enum! {
    /// Where a tile's provider adjustment is painted, relative to its label.
    ///
    /// `CornerStart` / `CornerEnd` hang the figure on a tile corner, which is
    /// what the `Ribbon` style runs across.
    SurchargePosition {
        /// On the label's own line.
        Inline => "inline",
        /// After the label, at the end of the row. The default.
        Trailing => "trailing",
        /// Under the sublabel.
        Below => "below",
        /// Over the label, as an eyebrow — the one position that reads before
        /// the method name.
        Above => "above",
        /// The leading corner of the tile.
        CornerStart => "cornerStart",
        /// The trailing corner of the tile.
        CornerEnd => "cornerEnd",
    }
}

wire_enum! {
    /// Where the wallet buttons' express strip sits on the payment surface.
    ///
    /// The rows drawn as the wallet's **own** button leave their section
    /// entirely and are lifted into one strip; this says where that strip goes.
    /// They keep their relative order whichever end it sits at.
    NativeElementPosition {
        /// Above everything, the custom fields included. The default.
        Top => "top",
        /// Under the merchant's custom fields, above the card form and every
        /// section.
        BelowFields => "belowFields",
        /// Directly under the card form. With no card form in the render it
        /// falls back to `belowFields`.
        BelowCard => "belowCard",
        /// Under the last section — the last thing offered.
        Bottom => "bottom",
    }
}

wire_enum! {
    /// How a provider adjustment is painted.
    SurchargeStyle {
        /// Text in the configured colour.
        Plain => "plain",
        /// The shape, filled with a tint of the colour. The default.
        Badge => "badge",
        /// The border only.
        Outline => "outline",
        /// Filled with the colour itself, written on in whichever of black or
        /// white reads better — the loudest option.
        Solid => "solid",
        /// Plain text with a rule beneath it.
        Underline => "underline",
        /// Run diagonally across a tile corner.
        Ribbon => "ribbon",
    }
}

wire_enum! {
    /// The border thickness of the shapes `Badge`, `Outline`, `Solid` and
    /// `Ribbon` paint.
    ///
    /// `Outline` draws nothing *but* its border, so `None` there would erase
    /// the style rather than restyle it and reads as `Thin` instead.
    SurchargeBorderWidth {
        /// No border.
        None => "none",
        /// 1px. The default.
        Thin => "thin",
        /// 2px.
        Medium => "medium",
        /// 3px.
        Thick => "thick",
    }
}

wire_enum! {
    /// How that border is drawn.
    SurchargeBorderStyle {
        /// The neutral default.
        Solid => "solid",
        /// Reads as provisional — suits a promotional discount.
        Dashed => "dashed",
        /// Reads as provisional, quieter than dashed.
        Dotted => "dotted",
    }
}

wire_enum! {
    /// The figure's type size, relative to the tile's own text.
    SurchargeSize {
        /// Small. The default.
        Sm => "sm",
        /// Medium.
        Md => "md",
        /// Large.
        Lg => "lg",
    }
}

wire_enum! {
    /// The corner treatment of the shapes `Badge`, `Outline` and `Solid` draw.
    /// Ignored by `Plain` and `Underline`, which draw no shape.
    SurchargeShape {
        /// Fully rounded. The default.
        Pill => "pill",
        /// 6px corners.
        Rounded => "rounded",
        /// Square corners.
        Square => "square",
    }
}

wire_enum! {
    /// How heavily the figure is set.
    SurchargeWeight {
        /// 400.
        Regular => "regular",
        /// 600. The default.
        Medium => "medium",
        /// 700.
        Bold => "bold",
    }
}

wire_enum! {
    /// Whether the figure carries an explicit sign.
    SurchargeSign {
        /// `+` on a surcharge, `−` on a discount (U+2212, so it aligns with the
        /// digits). The default.
        Always => "always",
        /// The minus only; a surcharge is unsigned and reads as a price.
        MinusOnly => "minusOnly",
        /// Neither — the two colours carry the direction alone.
        None => "none",
    }
}

wire_enum! {
    /// Whether the figure names itself.
    SurchargeLabelMode {
        /// The figure alone.
        Amount => "amount",
        /// The localized word for the direction, then the figure. The default.
        Labelled => "labelled",
    }
}

wire_enum! {
    /// Which figure the tile prints, and in which order when it prints both.
    ///
    /// The two directions carry this setting separately: a saving is advertised
    /// and its percentage is the persuasive half, while a fee is disclosed and
    /// the money is the half the buyer cares about.
    SurchargeFigureMode {
        /// The money only. The surcharge default.
        Amount => "amount",
        /// The percentage only.
        Percent => "percent",
        /// Money, then percentage.
        AmountThenPercent => "amountThenPercent",
        /// Percentage, then money. The discount default.
        PercentThenAmount => "percentThenAmount",
    }
}

wire_enum! {
    /// The Airwallex card form's geometry preset.
    ///
    /// Presentation only: every one collects the card inside Airwallex's own
    /// iframes and confirms the same intent, so the PCI scope is identical
    /// whichever the merchant picks.
    AirwallexCardPreset {
        /// Airwallex's combined element — number, expiry and CVC in one iframe
        /// on one line.
        SingleRow => "single_row",
        /// The trio, with placeholders carrying the meaning.
        SplitFields => "split_fields",
        /// The trio, captioned — what a shop with nothing configured gets.
        SplitFieldsLabelled => "split_fields_labelled",
        /// Every field full width.
        Stacked => "stacked",
        /// Number and expiry on one row, CVC beneath. The row is weighted 3:2
        /// toward the number, which is nineteen characters against five.
        NumberExpiryRow => "number_expiry_row",
        /// Split geometry at reduced density and type size.
        Compact => "compact",
    }
}

wire_enum! {
    /// How the box around each Airwallex field is drawn.
    AirwallexFieldChrome {
        /// A border. The default.
        Outlined => "outlined",
        /// A filled box.
        Filled => "filled",
        /// A rule under the field.
        Underline => "underline",
    }
}

wire_enum! {
    /// How an Airwallex field's caption is drawn.
    ///
    /// Every one of these is **visual only**, and not by choice: `for` cannot
    /// cross into a cross-origin iframe, so a `<label>` here would name nothing
    /// and focus nothing. The field keeps the accessible name Airwallex gives
    /// it inside the frame.
    AirwallexLabelStyle {
        /// Above the field.
        Above => "above",
        /// On the field's own line.
        Inline => "inline",
        /// Floating into the border on focus.
        Floating => "floating",
        /// No caption.
        None => "none",
    }
}

wire_enum! {
    /// Airwallex field type size.
    AirwallexFieldFontSize {
        /// Small.
        Sm => "sm",
        /// Medium. The default.
        Md => "md",
        /// Large.
        Lg => "lg",
    }
}

wire_enum! {
    /// Airwallex field type weight.
    AirwallexFieldWeight {
        /// 400.
        Regular => "regular",
        /// 600 — what the pane hardcoded before this existed. The default.
        Medium => "medium",
        /// 700.
        Semibold => "semibold",
    }
}

wire_enum! {
    /// The ring drawn around the focused Airwallex field.
    AirwallexFocusRing {
        /// No ring. The default.
        None => "none",
        /// A quiet ring.
        Subtle => "subtle",
        /// A pronounced ring.
        Strong => "strong",
    }
}

wire_enum! {
    /// What the browser's autofill highlight may do to an Airwallex field.
    AirwallexAutofillTreatment {
        /// Leave it alone — the buyer's own browser telling them it filled the
        /// field is information, not a style bug. The default.
        System => "system",
        /// Tint it with the merchant's brand colour.
        Brand => "brand",
        /// Flatten it to the field's own background.
        Neutral => "neutral",
    }
}

/// How the box around a card field is drawn, on the card forms that are not
/// Airwallex's. The same vocabulary as [`AirwallexFieldChrome`].
pub type CardFieldChrome = AirwallexFieldChrome;

/// Card field type size: `sm` 14px, `md` 16px, `lg` 18px. The same
/// vocabulary as [`AirwallexFieldFontSize`].
pub type CardFieldFontSize = AirwallexFieldFontSize;

/// Card field type weight. The same vocabulary as [`AirwallexFieldWeight`].
pub type CardFieldWeight = AirwallexFieldWeight;

/// The ring around a focused card field. The same vocabulary as
/// [`AirwallexFocusRing`].
pub type CardFocusRing = AirwallexFocusRing;

wire_enum! {
    /// Where the hosted checkout's back-to-merchant link sits.
    CancelLinkPosition {
        /// Above the checkout. The default.
        Top => "top",
        /// Below the checkout.
        Bottom => "bottom",
    }
}

wire_enum! {
    /// How the hosted checkout's back-to-merchant link is drawn.
    CancelLinkStyle {
        /// A text link. The default.
        Link => "link",
        /// A button.
        Button => "button",
    }
}

wire_enum! {
    /// Stripe's base theme. `Auto` is `night` on a dark checkout and `stripe`
    /// on a light one, which is what the pane chose before the setting existed.
    StripeTheme {
        /// Follow the checkout: `night` when dark, `stripe` otherwise. The default.
        Auto => "auto",
        /// Stripe's light theme.
        Stripe => "stripe",
        /// Stripe's flat theme.
        Flat => "flat",
        /// Stripe's dark theme.
        Night => "night",
    }
}

wire_enum! {
    /// Stripe's input style.
    StripeInputStyle {
        /// Separate boxes. The default.
        Spaced => "spaced",
        /// One condensed block.
        Condensed => "condensed",
    }
}

wire_enum! {
    /// Where Stripe places its field labels.
    StripeLabelPlacement {
        /// Above the field. The default.
        Above => "above",
        /// Inside the field until it is filled.
        Floating => "floating",
    }
}

wire_enum! {
    /// The space between Stripe's fields and rows.
    StripeSpacing {
        /// 3px unit, 8px rows.
        Compact => "compact",
        /// 4px unit, 12px rows: what the pane always sent. The default.
        Comfortable => "comfortable",
        /// 5px unit, 16px rows.
        Spacious => "spacious",
    }
}

wire_enum! {
    /// The rows of a PayPal card form.
    PaypalCardLayout {
        /// Expiry and CVC side by side. The default.
        Split => "split",
        /// Every field full width.
        Stacked => "stacked",
    }
}

wire_enum! {
    /// Captions over PayPal's card fields. Visual only: a caption cannot reach
    /// an input inside PayPal's frame.
    PaypalLabelStyle {
        /// A caption above each field. The default.
        Above => "above",
        /// No captions.
        None => "none",
    }
}

wire_enum! {
    /// NomuPay's widget style.
    NomupayFormStyle {
        /// Bare labelled fields. The default.
        Plain => "plain",
        /// The widget's card-shaped presentation.
        Card => "card",
    }
}

wire_enum! {
    /// The Apple Pay button's style. `Auto` is `white` on a dark checkout and
    /// `black` on a light one.
    ApplePayButtonStyle {
        /// Follow the checkout. The default.
        Auto => "auto",
        /// Black.
        Black => "black",
        /// White.
        White => "white",
        /// White with an outline.
        WhiteOutline => "white-outline",
    }
}

wire_enum! {
    /// The word on the Apple Pay button: Apple's own list.
    ApplePayButtonType {
        /// `pay`. The default.
        Pay => "pay",
        /// `plain`.
        Plain => "plain",
        /// `buy`.
        Buy => "buy",
        /// `check-out`.
        CheckOut => "check-out",
        /// `continue`.
        Continue => "continue",
        /// `book`.
        Book => "book",
        /// `order`.
        Order => "order",
        /// `subscribe`.
        Subscribe => "subscribe",
        /// `donate`.
        Donate => "donate",
        /// `contribute`.
        Contribute => "contribute",
        /// `support`.
        Support => "support",
        /// `tip`.
        Tip => "tip",
        /// `add-money`.
        AddMoney => "add-money",
        /// `top-up`.
        TopUp => "top-up",
        /// `reload`.
        Reload => "reload",
        /// `rent`.
        Rent => "rent",
    }
}

wire_enum! {
    /// The Google Pay button's colour. `Auto` is `white` on a dark checkout and
    /// `black` on a light one; `Default` lets Google choose for the buyer's
    /// browser.
    GooglePayButtonColor {
        /// Follow the checkout. The default.
        Auto => "auto",
        /// Google chooses.
        Default => "default",
        /// Black.
        Black => "black",
        /// White.
        White => "white",
    }
}

wire_enum! {
    /// The word on the Google Pay button: Google's own list.
    GooglePayButtonType {
        /// `pay`. The default.
        Pay => "pay",
        /// `plain`.
        Plain => "plain",
        /// `buy`.
        Buy => "buy",
        /// `checkout`.
        Checkout => "checkout",
        /// `book`.
        Book => "book",
        /// `order`.
        Order => "order",
        /// `subscribe`.
        Subscribe => "subscribe",
        /// `donate`.
        Donate => "donate",
    }
}

wire_enum! {
    /// The Whop card form's shape.
    WhopCardPreset {
        /// Whop's Payment Element, methods stacked.
        Accordion => "accordion",
        /// Whop's Payment Element as equal-width tiles.
        Tiles => "tiles",
        /// Whop's Card Element, number above expiry and CVC. Cards only. The default.
        CardStacked => "card_stacked",
        /// Whop's Card Element on one row. Cards only.
        CardCompact => "card_compact",
    }
}

wire_enum! {
    /// The palette Whop draws its radios, selected rows and buttons in. Whop
    /// takes a palette name only, never a colour.
    WhopAccentColor {
        /// Nearest palette to the checkout's primary colour. The default.
        Auto => "auto",
        /// `gray`.
        Gray => "gray",
        /// `blue`.
        Blue => "blue",
        /// `indigo`.
        Indigo => "indigo",
        /// `iris`.
        Iris => "iris",
        /// `violet`.
        Violet => "violet",
        /// `purple`.
        Purple => "purple",
        /// `plum`.
        Plum => "plum",
        /// `pink`.
        Pink => "pink",
        /// `crimson`.
        Crimson => "crimson",
        /// `ruby`.
        Ruby => "ruby",
        /// `red`.
        Red => "red",
        /// `tomato`.
        Tomato => "tomato",
        /// `orange`.
        Orange => "orange",
        /// `amber`.
        Amber => "amber",
        /// `yellow`.
        Yellow => "yellow",
        /// `lime`.
        Lime => "lime",
        /// `grass`.
        Grass => "grass",
        /// `green`.
        Green => "green",
        /// `jade`.
        Jade => "jade",
        /// `teal`.
        Teal => "teal",
        /// `cyan`.
        Cyan => "cyan",
        /// `sky`.
        Sky => "sky",
        /// `mint`.
        Mint => "mint",
        /// `brown`.
        Brown => "brown",
        /// `bronze`.
        Bronze => "bronze",
        /// `gold`.
        Gold => "gold",
    }
}

wire_enum! {
    /// The neutral scale Whop draws its borders, muted text and backgrounds in.
    WhopGrayColor {
        /// Whop matches it to the accent. The default.
        Auto => "auto",
        /// `gray`.
        Gray => "gray",
        /// `mauve`.
        Mauve => "mauve",
        /// `slate`.
        Slate => "slate",
        /// `sage`.
        Sage => "sage",
        /// `olive`.
        Olive => "olive",
        /// `sand`.
        Sand => "sand",
    }
}

wire_enum! {
    /// How much billing address Whop asks a card for.
    WhopBillingDetails {
        /// Whop's minimum for a card: name, country and postal code. The default.
        Minimal => "minimal",
        /// The complete address in the country's own format.
        Full => "full",
    }
}

wire_enum! {
    /// How Whop captions its email field.
    WhopEmailLabel {
        /// A caption above the box. The default.
        Above => "above",
        /// Inside the box until typed.
        Floating => "floating",
    }
}

wire_enum! {
    /// The corners of Whop's form.
    WhopRadius {
        /// Follow the checkout's own input radius. The default.
        Checkout => "checkout",
        /// Square.
        Square => "square",
        /// Small.
        Small => "small",
        /// Medium.
        Medium => "medium",
        /// Large.
        Large => "large",
    }
}

wire_enum! {
    /// Whether Whop's fields keep the soft drop shadow Whop draws under them.
    WhopShadow {
        /// Flat, like the checkout's own fields.
        None => "none",
        /// Whop's soft shadow. The default.
        Soft => "soft",
    }
}

wire_enum! {
    /// How Whop's method list marks the chosen method. Tiles always ring the
    /// chosen tile.
    WhopSelection {
        /// Radio dots, with the chosen method tinted. The default.
        RadioTint => "radio_tint",
        /// Radio dots only.
        Radio => "radio",
        /// The tint only.
        Tint => "tint",
    }
}

wire_enum! {
    /// Where a checkout notice is drawn.
    NoticeSection {
        /// Under the order summary in the split layout; under the compact header
        /// when there is no summary pane.
        Summary => "summary",
        /// At the bottom of the payment element, under the pay button.
        Payment => "payment",
    }
}

wire_enum! {
    /// The mark a checkout notice carries, in the order the editor offers them.
    NoticeIcon {
        /// `lock`.
        Lock => "lock",
        /// `shield`.
        Shield => "shield",
        /// `check`.
        Check => "check",
        /// `truck`.
        Truck => "truck",
        /// `package`.
        Package => "package",
        /// `refresh`.
        Refresh => "refresh",
        /// `star`.
        Star => "star",
        /// `support`.
        Support => "support",
        /// `globe`.
        Globe => "globe",
        /// `tag`.
        Tag => "tag",
        /// `heart`.
        Heart => "heart",
        /// `leaf`.
        Leaf => "leaf",
        /// `clock`.
        Clock => "clock",
        /// `bank`.
        Bank => "bank",
    }
}

/// A fully customizable trust badge shown under the pay button.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustBadge {
    /// Stable identifier, used as the list key.
    pub id: String,
    /// Visible text. A badge with an empty label is dropped on decode.
    pub label: String,
    /// Foreground colour, hex.
    pub text_color: String,
    /// Chip background colour, hex.
    pub background_color: String,
    /// Optional chip border colour, hex. `None` means no border.
    #[serde(default)]
    pub border_color: Option<String>,
}

impl TrustBadge {
    /// Construct a badge without a border.
    pub fn new(
        id: impl Into<String>,
        label: impl Into<String>,
        text_color: impl Into<String>,
        background_color: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            text_color: text_color.into(),
            background_color: background_color.into(),
            border_color: None,
        }
    }

    /// Set the chip border colour.
    #[must_use]
    pub fn border_color(mut self, colour: impl Into<String>) -> Self {
        self.border_color = Some(colour.into());
        self
    }
}

// --- Notices ------------------------------------------------------------
//
// A notice is one short reassurance line on the checkout — a line icon and a
// text — in one of two places. Notices replace the trust badges as the
// default: a notice carries no colours of its own and is drawn in the
// checkout's muted text and accent colour, so it follows the merchant's
// palette, and its text is written per locale.
//
// Persisted JSON-stringified under `sdk_ui_rules.branding.notices`, the same
// transport as `trustBadges` and `customFields`.

/// How many notices one section draws. The decoder drops the overflow.
pub const NOTICES_PER_SECTION: usize = 3;

/// Longest notice text, per locale, in characters.
pub const NOTICE_LABEL_MAX_LENGTH: usize = 80;

/// Longest notice id. An id is code-shaped: `[A-Za-z0-9_-]`.
const NOTICE_ID_MAX_LENGTH: usize = 40;

/// What an unknown or missing icon decodes to.
pub const NOTICE_ICON_FALLBACK: NoticeIcon = NoticeIcon::Check;

/// One reassurance line on the checkout.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutNotice {
    /// Stable across edits and drags; `[A-Za-z0-9_-]`, at most 40 characters.
    pub id: String,
    /// Where the notice is drawn.
    pub section: NoticeSection,
    /// The mark beside the text.
    pub icon: NoticeIcon,
    /// Default-language text, and what every locale without an override
    /// reads.
    pub label: String,
    /// Per-locale overrides of `label`; a blank entry means "use `label`".
    #[serde(default)]
    pub label_translations: CustomFieldTranslations,
}

impl CheckoutNotice {
    /// A notice with no translations.
    pub fn new(
        id: impl Into<String>,
        section: NoticeSection,
        icon: NoticeIcon,
        label: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            section,
            icon,
            label: label.into(),
            label_translations: CustomFieldTranslations::new(),
        }
    }

    /// Add a per-locale override of the label.
    #[must_use]
    pub fn translation(mut self, locale: impl Into<String>, label: impl Into<String>) -> Self {
        self.label_translations.insert(locale.into(), label.into());
        self
    }
}

/// The notices every shop starts with: the payment is secure, and the
/// connection is encrypted. A default may only say what is true of every
/// shop.
pub static DEFAULT_NOTICES: LazyLock<Vec<CheckoutNotice>> = LazyLock::new(|| {
    vec![
        CheckoutNotice::new(
            "secure",
            NoticeSection::Summary,
            NoticeIcon::Shield,
            "Secure payment",
        )
        .translation("de", "Sichere Zahlung")
        .translation("fr", "Paiement sécurisé")
        .translation("es", "Pago seguro")
        .translation("it", "Pagamento sicuro")
        .translation("nl", "Veilig betalen")
        .translation("zh", "安全支付")
        .translation("zh-Hant", "安全付款")
        .translation("hi", "सुरक्षित भुगतान")
        .translation("ar", "دفع آمن"),
        CheckoutNotice::new(
            "ssl",
            NoticeSection::Summary,
            NoticeIcon::Lock,
            "Encrypted · 256-bit SSL",
        )
        .translation("de", "Verschlüsselt · 256-Bit-SSL")
        .translation("fr", "Chiffré · SSL 256 bits")
        .translation("es", "Cifrado · SSL de 256 bits")
        .translation("it", "Crittografato · SSL a 256 bit")
        .translation("nl", "Versleuteld · 256-bit SSL")
        .translation("zh", "加密 · 256 位 SSL")
        .translation("zh-Hant", "加密 · 256 位元 SSL")
        .translation("hi", "एन्क्रिप्टेड · 256-बिट SSL")
        .translation("ar", "مشفّر · SSL بطول 256 بت"),
    ]
});

/// A fresh copy of [`DEFAULT_NOTICES`].
pub fn default_notices() -> Vec<CheckoutNotice> {
    DEFAULT_NOTICES.clone()
}

/// `value` with the characters JavaScript's `String.prototype.trim` strips
/// removed from both ends: the ECMAScript WhiteSpace and LineTerminator set.
///
/// Not `str::trim`: that also strips U+0085, which JavaScript keeps, and
/// keeps U+FEFF, which JavaScript strips. The notice rules must decide
/// blankness exactly as the TypeScript codec does, or a label one side drops
/// takes a section slot on the other.
fn js_trim(value: &str) -> &str {
    fn is_js_space(c: char) -> bool {
        matches!(
            c,
            '\t' | '\n'
                | '\u{000B}'
                | '\u{000C}'
                | '\r'
                | ' '
                | '\u{00A0}'
                | '\u{1680}'
                | '\u{2000}'
                ..='\u{200A}'
                    | '\u{2028}'
                    | '\u{2029}'
                    | '\u{202F}'
                    | '\u{205F}'
                    | '\u{3000}'
                    | '\u{FEFF}'
        )
    }
    value.trim_matches(is_js_space)
}

fn cap_notice_text(value: &str) -> String {
    value.chars().take(NOTICE_LABEL_MAX_LENGTH).collect()
}

/// A translations map from the bag (a JSON string) or an import file (an
/// object). Only non-blank string values are kept.
fn parse_notice_translations(raw: Option<&Value>) -> CustomFieldTranslations {
    let parsed;
    let value = match raw {
        Some(Value::String(s)) => match serde_json::from_str::<Value>(s) {
            Ok(v) => {
                parsed = v;
                &parsed
            }
            Err(_) => return CustomFieldTranslations::new(),
        },
        Some(v) => v,
        None => return CustomFieldTranslations::new(),
    };
    let mut out = CustomFieldTranslations::new();
    if let Some(obj) = value.as_object() {
        for (k, v) in obj {
            if let Some(text) = v.as_str()
                && !js_trim(text).is_empty()
            {
                out.insert(k.clone(), text.to_string());
            }
        }
    }
    out
}

/// Normalize a list of notices from any source.
///
/// Total: a malformed entry degrades to a smaller list, never to an error.
/// A non-object is dropped; an unknown section reads as `summary` and an
/// unknown icon as [`NOTICE_ICON_FALLBACK`]; the id is cleaned to
/// `[A-Za-z0-9_-]` and a missing or repeated one replaced; text is cut to
/// [`NOTICE_LABEL_MAX_LENGTH`] characters; a notice with no text in any
/// language is dropped; a notice past [`NOTICES_PER_SECTION`] in its section
/// is dropped, first come first kept.
fn normalize_notices(list: &[Value]) -> Vec<CheckoutNotice> {
    let mut seen = std::collections::BTreeSet::new();
    let mut per_section: BTreeMap<&'static str, usize> = BTreeMap::new();
    let mut out = Vec::new();

    for (index, raw) in list.iter().enumerate() {
        let Some(src) = raw.as_object() else {
            continue;
        };

        let label = src
            .get("label")
            .and_then(Value::as_str)
            .map(cap_notice_text)
            .unwrap_or_default();
        let label_translations: CustomFieldTranslations =
            parse_notice_translations(src.get("labelTranslations"))
                .into_iter()
                .map(|(locale, text)| (locale, cap_notice_text(&text)))
                .collect();
        if js_trim(&label).is_empty() && label_translations.is_empty() {
            continue;
        }

        let section = pick_enum(src.get("section"), NoticeSection::Summary);
        let used = per_section.entry(section.as_str()).or_insert(0);
        if *used >= NOTICES_PER_SECTION {
            continue;
        }
        *used += 1;

        let mut id: String = src
            .get("id")
            .and_then(Value::as_str)
            .map(|raw| {
                raw.chars()
                    .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
                    .take(NOTICE_ID_MAX_LENGTH)
                    .collect()
            })
            .unwrap_or_default();
        if id.is_empty() || seen.contains(&id) {
            id = format!("notice-{}", index + 1);
        }
        while seen.contains(&id) {
            id.push('x');
        }
        seen.insert(id.clone());

        out.push(CheckoutNotice {
            id,
            section,
            icon: pick_enum(src.get("icon"), NOTICE_ICON_FALLBACK),
            label,
            label_translations,
        });
    }
    out
}

/// Decode `sdk_ui_rules.branding.notices`.
///
/// `None` when the key is absent or is not a JSON array: the shop has no say
/// about notices, which [`resolve_notices_and_badges`] turns into the
/// migration. An empty array is a say: the merchant removed every notice.
pub fn decode_notices(raw: Option<&str>) -> Option<Vec<CheckoutNotice>> {
    let parsed: Value = serde_json::from_str(raw?).ok()?;
    parsed.as_array().map(Vec::as_slice).map(normalize_notices)
}

/// [`decode_notices`] for an import file, which carries the array inline
/// rather than as a JSON string. Either form is accepted.
pub fn parse_notices_loose(raw: Option<&Value>) -> Option<Vec<CheckoutNotice>> {
    match raw? {
        Value::String(s) => decode_notices(Some(s)),
        Value::Array(items) => Some(normalize_notices(items)),
        _ => None,
    }
}

/// The exact wire shape `encode_notices` emits, in declaration order.
#[derive(Serialize)]
struct NoticeWire<'a> {
    id: &'a str,
    section: &'static str,
    icon: &'static str,
    label: &'a str,
    #[serde(rename = "labelTranslations", skip_serializing_if = "Option::is_none")]
    label_translations: Option<BTreeMap<&'a str, &'a str>>,
}

/// JSON-stringify notices for the bag. Always a JSON array, `[]` included:
/// the key's presence is what tells a later decode that the shop has
/// decided. Blank translations are left out, and the whole map when none is
/// left.
pub fn encode_notices(notices: &[CheckoutNotice]) -> String {
    let wire: Vec<NoticeWire<'_>> = notices
        .iter()
        .map(|n| {
            let translations: BTreeMap<&str, &str> = n
                .label_translations
                .iter()
                .filter(|(_, text)| !js_trim(text).is_empty())
                .map(|(locale, text)| (locale.as_str(), text.as_str()))
                .collect();
            NoticeWire {
                id: &n.id,
                section: n.section.as_str(),
                icon: n.icon.as_str(),
                label: &n.label,
                label_translations: (!translations.is_empty()).then_some(translations),
            }
        })
        .collect();
    serde_json::to_string(&wire).unwrap_or_else(|_| "[]".to_string())
}

/// Exact-locale-then-shorter-prefix lookup, case-insensitive, skipping
/// empty values.
fn notice_translation_for(map: &CustomFieldTranslations, locale: Option<&str>) -> Option<String> {
    let locale = locale.filter(|l| !l.is_empty())?;
    let mut folded: BTreeMap<String, &str> = BTreeMap::new();
    for (k, v) in map {
        if !v.is_empty() {
            folded.entry(k.to_lowercase()).or_insert(v.as_str());
        }
    }
    let parts: Vec<String> = locale
        .to_lowercase()
        .split('-')
        .map(str::to_string)
        .collect();
    (1..=parts.len())
        .rev()
        .find_map(|i| folded.get(&parts[..i].join("-")).map(|v| (*v).to_string()))
}

/// A notice's text in the buyer's locale: exact locale, then its base
/// language, then the default text. `""` when the notice has no text for the
/// locale.
pub fn notice_text(notice: &CheckoutNotice, locale: Option<&str>) -> String {
    notice_translation_for(&notice.label_translations, locale)
        .unwrap_or_else(|| notice.label.clone())
}

/// The notices one section draws, in order, capped at
/// [`NOTICES_PER_SECTION`].
pub fn notices_in(notices: &[CheckoutNotice], section: NoticeSection) -> Vec<&CheckoutNotice> {
    notices
        .iter()
        .filter(|n| n.section == section)
        .take(NOTICES_PER_SECTION)
        .collect()
}

/// One notice as a buyer sees it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShownNotice<'a> {
    /// The notice.
    pub notice: &'a CheckoutNotice,
    /// Its text in the buyer's locale, trimmed.
    pub text: String,
}

/// What one section draws for a buyer: its notices (capped, as
/// [`notices_in`]), each with its text in `locale`, leaving out every notice
/// with no text there.
pub fn shown_notices<'a>(
    notices: &'a [CheckoutNotice],
    section: NoticeSection,
    locale: Option<&str>,
) -> Vec<ShownNotice<'a>> {
    notices_in(notices, section)
        .into_iter()
        .map(|notice| ShownNotice {
            notice,
            text: js_trim(&notice_text(notice, locale)).to_string(),
        })
        .filter(|shown| !shown.text.is_empty())
        .collect()
}

/// `#rrggbb` to its three channels, or `None` for anything else.
fn hex6_channels(hex: &str) -> Option<[u8; 3]> {
    let rest = hex.trim().strip_prefix('#')?;
    if rest.len() != 6 || !rest.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let ch = |i: usize| u8::from_str_radix(&rest[i..i + 2], 16).ok();
    Some([ch(0)?, ch(2)?, ch(4)?])
}

/// Whether a badge colouring is one a built-in theme generated: text = the
/// primary, fill = the surface mixed 8 % towards it, border = mixed 30 %,
/// rounded per channel. The surface is recovered by searching each channel
/// for a value that reproduces both the fill and the border.
fn is_theme_tinted_badge_colouring(text_color: &str, fill: &str, border: &str) -> bool {
    let (Some(primary), Some(bg), Some(line)) = (
        hex6_channels(text_color),
        hex6_channels(fill),
        hex6_channels(border),
    ) else {
        return false;
    };
    // `Math.round` on a non-negative value: half rounds up.
    let mixed =
        |surface: f64, to: f64, share: f64| (surface + (to - surface) * share + 0.5).floor();
    (0..3).all(|i| {
        let p = f64::from(primary[i]);
        (0..=255).any(|surface| {
            let surface = f64::from(surface);
            mixed(surface, p, 0.08) == f64::from(bg[i])
                && mixed(surface, p, 0.3) == f64::from(line[i])
        })
    })
}

/// Whether a badge list is a default shipped with the checkout rather than
/// something the merchant configured.
///
/// Stock means the two stock badges (`secure` / "Secure", then `ssl` /
/// "256-bit SSL") in a generated colouring: the light default, the dark
/// default, or one theme colouring shared by both badges. Anything else was
/// edited, and so is an empty list: a merchant who removed both badges chose
/// to show nothing.
pub fn is_default_badge_set(badges: &[TrustBadge]) -> bool {
    if badges.len() != DEFAULT_BADGES.len() {
        return false;
    }
    let same_content = badges
        .iter()
        .zip(DEFAULT_BADGES.iter())
        .all(|(b, d)| b.id == d.id && b.label == d.label);
    if !same_content {
        return false;
    }

    let colouring = |set: &[TrustBadge]| -> Vec<String> {
        set.iter()
            .map(|b| {
                format!(
                    "{}|{}|{}",
                    b.text_color,
                    b.background_color,
                    b.border_color.as_deref().unwrap_or("")
                )
                .to_lowercase()
            })
            .collect()
    };
    let mine = colouring(badges);
    if mine == colouring(DEFAULT_BADGES.as_slice())
        || mine == colouring(DEFAULT_BADGES_DARK.as_slice())
    {
        return true;
    }

    // A theme gave both badges one colouring, border included.
    let first = &badges[0];
    let Some(border) = first.border_color.as_deref().filter(|b| !b.is_empty()) else {
        return false;
    };
    let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
    badges.iter().all(|b| {
        same(&b.text_color, &first.text_color)
            && same(&b.background_color, &first.background_color)
            && same(b.border_color.as_deref().unwrap_or(""), border)
    }) && is_theme_tinted_badge_colouring(&first.text_color, &first.background_color, border)
}

/// A shop's trust badges and notices, decided together.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NoticesAndBadges {
    /// The trust badges to draw.
    pub trust_badges: Vec<TrustBadge>,
    /// The notices to draw.
    pub notices: Vec<CheckoutNotice>,
}

/// Decide a shop's badges and notices from what it saved. `None` means the
/// key is absent (or unreadable). In order:
///
/// 1. Notices saved: they decide, and the badges are whatever was saved
///    (none when absent).
/// 2. No notices, and no badges or the stock badges: the badges go and
///    [`DEFAULT_NOTICES`] come in.
/// 3. No notices, and badges the merchant configured: they stay as they are,
///    and no notices are added.
///
/// Decode-time only: nothing is written until the merchant saves.
pub fn resolve_notices_and_badges(
    saved_badges: Option<Vec<TrustBadge>>,
    saved_notices: Option<Vec<CheckoutNotice>>,
) -> NoticesAndBadges {
    if let Some(notices) = saved_notices {
        return NoticesAndBadges {
            trust_badges: saved_badges.unwrap_or_default(),
            notices,
        };
    }
    match saved_badges {
        Some(badges) if !is_default_badge_set(&badges) => NoticesAndBadges {
            trust_badges: badges,
            notices: Vec::new(),
        },
        _ => NoticesAndBadges {
            trust_badges: Vec::new(),
            notices: default_notices(),
        },
    }
}

/// The fully-resolved branding of a checkout.
///
/// Every field is always populated: [`decode_branding`] and
/// [`parse_imported_branding`] fall back to [`DEFAULT_BRANDING`] per field
/// rather than leaving anything unset. Copy fields use the empty string to
/// mean "unset" — consumers fall back (e.g. `pay_button_label` falls back to a
/// localized "Pay $X" string).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CheckoutBranding {
    /// Merchant display name.
    pub display_name: String,
    /// Absolute URL of the merchant logo.
    pub logo_url: String,
    /// Short line under the display name.
    pub tagline: String,
    /// Whether the logo block is rendered at all.
    pub show_logo: bool,
    /// Logo silhouette.
    pub logo_shape: LogoShape,
    /// Logo size.
    pub logo_size: LogoSize,

    /// Brand colour, also the Stripe Elements accent.
    pub primary: String,
    /// Page background colour.
    pub background: String,
    /// Card/surface colour.
    pub surface: String,
    /// Body text colour.
    pub text: String,
    /// Heading text colour.
    pub heading: String,
    /// Secondary/meta text colour.
    pub muted: String,
    /// Hairline/border colour.
    pub border: String,
    /// Colour of links and accented text.
    pub accent_text: String,
    /// Pay-button background colour.
    pub button_background: String,
    /// Pay-button foreground colour.
    pub button_text: String,

    /// Font family for the whole checkout.
    pub font_family: FontFamily,
    /// Weight used for headings.
    pub heading_weight: FontWeight,

    /// Corner radius of cards and surfaces.
    pub radius_surface: NonPillRadius,
    /// Corner radius of inputs.
    pub radius_input: NonPillRadius,
    /// Corner radius of the pay button.
    pub radius_button: CornerRadius,
    /// Corner radius of trust badges.
    pub radius_badge: CornerRadius,
    /// How the surface separates from the background.
    pub surface_style: SurfaceStyle,

    /// Padding inside surfaces.
    pub surface_padding: SpacingScale,
    /// Vertical rhythm between blocks.
    pub vertical_gap: SpacingScale,
    /// Input height scale.
    pub input_size: SizeScale,
    /// Pay-button height scale.
    pub button_size: SizeScale,

    /// Overall layout.
    pub layout: LayoutStyle,
    /// Which side the order summary sits on.
    pub summary_position: SummaryPosition,
    /// Whether the order summary is shown.
    pub show_order_summary: bool,
    /// Whether the summary gets a primary-tinted gradient.
    pub summary_gradient: bool,
    /// Whether the total row is shown.
    pub show_total: bool,
    /// Label of the total row.
    pub total_label: String,
    /// Whether the currency code is printed next to amounts.
    pub show_currency_code: bool,
    /// Whether individual line items are listed.
    pub show_order_items: bool,

    /// Whether the back-to-merchant link is drawn. Drawn only when the payment resolves a cancel URL.
    pub cancel_link_enabled: bool,
    /// Where the back-to-merchant link sits.
    pub cancel_link_position: CancelLinkPosition,
    /// How the back-to-merchant link is drawn.
    pub cancel_link_style: CancelLinkStyle,

    /// Whether a tile's provider adjustment is painted at all. The flag decides
    /// whether a figure renders, not what colour it would be.
    pub show_surcharge: bool,
    /// Where that figure sits relative to the tile's label.
    pub surcharge_position: SurchargePosition,
    /// Where the wallet buttons' express strip sits on the payment surface.
    pub native_element_position: NativeElementPosition,
    /// One wallet button per line instead of side by side.
    pub native_element_stacked: bool,
    /// How the figure is painted.
    pub surcharge_style: SurchargeStyle,
    /// The figure's type size.
    pub surcharge_size: SurchargeSize,
    /// The corner treatment of the shape it draws.
    pub surcharge_shape: SurchargeShape,
    /// The border thickness of that shape.
    pub surcharge_border_width: SurchargeBorderWidth,
    /// How that border is drawn.
    pub surcharge_border_style: SurchargeBorderStyle,
    /// How heavily the figure is set.
    pub surcharge_weight: SurchargeWeight,
    /// Whether the figure carries an explicit sign.
    pub surcharge_sign: SurchargeSign,
    /// Whether the figure is upper-cased.
    pub surcharge_uppercase: bool,
    /// Whether the figure names itself.
    pub surcharge_label: SurchargeLabelMode,
    /// Which figure a surcharge prints.
    pub surcharge_figure: SurchargeFigureMode,
    /// Which figure a discount prints.
    pub discount_figure: SurchargeFigureMode,
    /// The colour a surcharge is painted in.
    pub surcharge_color: String,
    /// The colour a discount is painted in. A minus sign is easy to miss on a
    /// page about money, so the two directions do not share a colour.
    pub discount_color: String,

    /// Where each payment-method section renders: section id to a number from
    /// 1 to 100, lower first. An id this build does not know is kept and sorts
    /// last — see [`compare_sections`].
    pub method_section_order: MethodSectionOrder,
    /// The merchant's own name for a section, per buyer locale. A section with
    /// no caption prints as itself — see [`section_label`].
    pub method_section_labels: MethodSectionLabels,

    /// Trust badges. An empty list hides the row. No longer a default: a new
    /// shop starts with none and gets [`notices`](Self::notices) instead; a
    /// shop that configured its badges keeps them. See
    /// [`resolve_notices_and_badges`].
    pub trust_badges: Vec<TrustBadge>,

    /// Reassurance lines (icon and per-locale text) in the summary and at
    /// the bottom of the payment element. An empty list shows none.
    pub notices: Vec<CheckoutNotice>,

    /// Merchant-defined buyer-facing inputs, whose submitted values land in the
    /// payment's `metadata` under each field's `key`. See
    /// [`crate::custom_fields`] for the codec, the conditional-visibility rules
    /// and the evaluator.
    pub custom_fields: Vec<CheckoutCustomField>,

    /// Header copy above the form.
    pub header_text: String,
    /// Pay-button label.
    pub pay_button_label: String,
    /// Card terms/consent message.
    pub card_terms_message: String,
    /// Footer copy.
    pub footer_text: String,
    /// Support email address shown in the footer.
    pub support_email: String,

    /// Stripe Elements payment-method layout.
    pub payment_layout: PaymentLayout,
    /// Stripe Elements label mode.
    pub label_style: LabelStyle,

    /// Which geometry the buyer's Airwallex card form takes.
    ///
    /// `None` means **the merchant has not chosen in the customizer**, and that
    /// is load-bearing: it is what lets the connector account's existing
    /// `integration_style` decide instead. A concrete default here would
    /// override every account already configured. Resolve it with
    /// [`resolve_airwallex_card_preset`].
    pub airwallex_card_preset: Option<AirwallexCardPreset>,
    /// Hide the Airwallex card form entirely.
    pub airwallex_hide_card: bool,
    /// Drop the "Card" heading over the Airwallex card form. Presentation only:
    /// the surcharge chip on that line is not its business, and the checkout
    /// keeps drawing it.
    pub airwallex_hide_card_title: bool,
    /// How the box around each Airwallex field is drawn.
    pub airwallex_field_chrome: AirwallexFieldChrome,
    /// How each field's caption is drawn. `None` means "whatever the preset
    /// says", which is what keeps `split_fields` and `split_fields_labelled`
    /// meaning what they mean.
    pub airwallex_label_style: Option<AirwallexLabelStyle>,
    /// Airwallex field type size.
    pub airwallex_field_font_size: AirwallexFieldFontSize,
    /// Airwallex field type weight.
    pub airwallex_field_weight: AirwallexFieldWeight,
    /// The ring drawn around the focused field.
    pub airwallex_focus_ring: AirwallexFocusRing,
    /// What the browser's autofill highlight may do to a field.
    pub airwallex_autofill: AirwallexAutofillTreatment,
    /// Tint a field that has validated.
    pub airwallex_valid_tint: bool,
    /// Draw the card-network marks. **Decorative**: it does not narrow the
    /// networks a buyer may pay with, which would be an acceptance change
    /// rather than a styling one.
    pub airwallex_network_marks: bool,

    // The card forms that are not Airwallex's. Every default is what the pane
    // drew before the setting existed.
    /// Stripe's base theme, applied under the colour, font and radius tokens.
    pub stripe_theme: StripeTheme,
    /// Stripe's input style: separate boxes or one condensed block.
    pub stripe_inputs: StripeInputStyle,
    /// Where Stripe places field labels. A checkout-wide hidden `label_style` still wins.
    pub stripe_labels: StripeLabelPlacement,
    /// The space between Stripe's fields and rows.
    pub stripe_spacing: StripeSpacing,
    /// Stripe field type size.
    pub stripe_field_font_size: CardFieldFontSize,
    /// Stripe field type weight.
    pub stripe_field_weight: CardFieldWeight,
    /// The ring around Stripe's focused field.
    pub stripe_focus_ring: CardFocusRing,
    /// Turn off Stripe's own animations.
    pub stripe_disable_animations: bool,
    /// The PayPal card form's rows.
    pub paypal_card_layout: PaypalCardLayout,
    /// Captions over PayPal's fields. Visual only.
    pub paypal_label_style: PaypalLabelStyle,
    /// How the box around each PayPal field is drawn.
    pub paypal_field_chrome: CardFieldChrome,
    /// How the box around each Mollie field is drawn.
    pub mollie_field_chrome: CardFieldChrome,
    /// PayPal field type size.
    pub paypal_field_font_size: CardFieldFontSize,
    /// Mollie field type size.
    pub mollie_field_font_size: CardFieldFontSize,
    /// PayPal field type weight.
    pub paypal_field_weight: CardFieldWeight,
    /// Mollie field type weight.
    pub mollie_field_weight: CardFieldWeight,
    /// The ring around PayPal's focused field.
    pub paypal_focus_ring: CardFocusRing,
    /// The ring around Mollie's focused field.
    pub mollie_focus_ring: CardFocusRing,
    /// Tint a PayPal field that has validated.
    pub paypal_valid_tint: bool,
    /// The e-Payouts Pay with card form's rows. A stored look without it reads `paypalCardLayout`.
    pub epayouts_card_layout: PaypalCardLayout,
    /// Captions over the e-Payouts card fields. Falls back to `paypalLabelStyle`.
    pub epayouts_label_style: PaypalLabelStyle,
    /// How the box around each e-Payouts card field is drawn. Falls back to `paypalFieldChrome`.
    pub epayouts_field_chrome: CardFieldChrome,
    /// e-Payouts card field type size. Falls back to `paypalFieldFontSize`.
    pub epayouts_field_font_size: CardFieldFontSize,
    /// e-Payouts card field type weight. Falls back to `paypalFieldWeight`.
    pub epayouts_field_weight: CardFieldWeight,
    /// The ring around the focused e-Payouts card field. Falls back to `paypalFocusRing`.
    pub epayouts_focus_ring: CardFocusRing,
    /// Tint an e-Payouts card field that has validated. Falls back to `paypalValidTint`.
    pub epayouts_valid_tint: bool,
    /// NomuPay's widget style.
    pub nomupay_form_style: NomupayFormStyle,
    /// Show labels on NomuPay's fields.
    pub nomupay_show_labels: bool,
    /// Show placeholders in NomuPay's fields.
    pub nomupay_show_placeholders: bool,
    /// Show NomuPay's CVV hint.
    pub nomupay_show_cvv_hint: bool,
    /// How the box around each NomuPay field is drawn.
    pub nomupay_field_chrome: CardFieldChrome,
    /// NomuPay field type size.
    pub nomupay_field_font_size: CardFieldFontSize,
    /// The ring around NomuPay's focused field.
    pub nomupay_focus_ring: CardFocusRing,
    /// The Apple Pay button NomuPay's widget draws.
    pub nomupay_apple_pay_button_style: ApplePayButtonStyle,
    /// The word on NomuPay's Apple Pay button.
    pub nomupay_apple_pay_button_type: ApplePayButtonType,
    /// The colour of NomuPay's Google Pay button.
    pub nomupay_google_pay_button_color: GooglePayButtonColor,
    /// The word on NomuPay's Google Pay button.
    pub nomupay_google_pay_button_type: GooglePayButtonType,
    /// How the box around each MicroPayment field is drawn.
    pub micropayment_field_chrome: CardFieldChrome,
    /// MicroPayment field type size.
    pub micropayment_field_font_size: CardFieldFontSize,
    /// MicroPayment field type weight.
    pub micropayment_field_weight: CardFieldWeight,
    /// The ring around MicroPayment's focused field.
    pub micropayment_focus_ring: CardFocusRing,
    /// Which Whop element and layout the card form mounts.
    pub whop_card_preset: WhopCardPreset,
    /// The palette Whop draws its controls in. `Auto` picks the one nearest the primary colour.
    pub whop_accent_color: WhopAccentColor,
    /// The neutral scale Whop draws borders and muted text in.
    pub whop_gray_color: WhopGrayColor,
    /// How much billing address Whop asks a card for.
    pub whop_billing_details: WhopBillingDetails,
    /// Accordion only: each method in its own card, with space between.
    pub whop_separated: bool,
    /// How Whop captions its email field.
    pub whop_email_label: WhopEmailLabel,
    /// How the box around each Whop field is drawn.
    pub whop_field_chrome: CardFieldChrome,
    /// Kept for stored brandings and no longer read: Whop sets its own type size.
    pub whop_field_font_size: CardFieldFontSize,
    /// Kept for stored brandings and no longer read: Whop sets its own type weight.
    pub whop_field_weight: CardFieldWeight,
    /// Kept for stored brandings and no longer read: Whop marks focus itself.
    pub whop_focus_ring: CardFocusRing,
    /// The corners of Whop's form.
    pub whop_radius: WhopRadius,
    /// Whether Whop's fields keep their soft drop shadow.
    pub whop_shadow: WhopShadow,
    /// Whether Whop's method list shows each method's icon.
    pub whop_method_icons: bool,
    /// How Whop's method list marks the chosen method.
    pub whop_selection: WhopSelection,

    /// Whether the "Powered by DeloPay" footer is shown.
    pub show_powered_by: bool,

    /// Raw CSS appended after the brand-token CSS variables, so its
    /// declarations win cascade order. Persisted as-typed; sanitize with
    /// [`sanitize_custom_css`] at render time.
    pub custom_css: String,
}

impl Default for CheckoutBranding {
    fn default() -> Self {
        DEFAULT_BRANDING.clone()
    }
}

// --- Token maps ---------------------------------------------------------

/// Self-hostable font stacks. The buyer-facing checkout bundles these via
/// `@fontsource*` packages; the variable-font names (`'Inter Variable'`, …) are
/// listed first so the smaller variable file is preferred when bundled.
///
/// Unlike the TypeScript map lookup, this is total: every [`FontFamily`] has a
/// stack.
pub const fn font_stack(family: FontFamily) -> &'static str {
    match family {
        FontFamily::Inter => "'Inter Variable', 'Inter', system-ui, -apple-system, sans-serif",
        FontFamily::System => {
            "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif"
        }
        FontFamily::Serif => "Georgia, 'Times New Roman', serif",
        FontFamily::Mono => "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
        FontFamily::Roboto => "'Roboto', system-ui, sans-serif",
        FontFamily::Poppins => "'Poppins', system-ui, sans-serif",
        FontFamily::Manrope => "'Manrope Variable', 'Manrope', system-ui, sans-serif",
        FontFamily::DmSans => "'DM Sans Variable', 'DM Sans', system-ui, sans-serif",
        FontFamily::SpaceGrotesk => {
            "'Space Grotesk Variable', 'Space Grotesk', system-ui, sans-serif"
        }
        FontFamily::PlexSans => "'IBM Plex Sans', system-ui, sans-serif",
        FontFamily::WorkSans => "'Work Sans Variable', 'Work Sans', system-ui, sans-serif",
        FontFamily::OpenSans => "'Open Sans Variable', 'Open Sans', system-ui, sans-serif",
        FontFamily::Lora => "'Lora Variable', 'Lora', Georgia, serif",
        FontFamily::Playfair => "'Playfair Display Variable', 'Playfair Display', Georgia, serif",
        FontFamily::PlexMono => "'IBM Plex Mono', ui-monospace, monospace",
        FontFamily::JetbrainsMono => {
            "'JetBrains Mono Variable', 'JetBrains Mono', ui-monospace, monospace"
        }
    }
}

/// The CSS length for a [`CornerRadius`].
pub const fn radius_value(radius: CornerRadius) -> &'static str {
    match radius {
        CornerRadius::Square => "0px",
        CornerRadius::Small => "6px",
        CornerRadius::Medium => "12px",
        CornerRadius::Large => "20px",
        CornerRadius::Pill => "999px",
    }
}

/// The numeric CSS `font-weight` for a [`FontWeight`].
pub const fn font_weight_value(weight: FontWeight) -> &'static str {
    match weight {
        FontWeight::Regular => "400",
        FontWeight::Medium => "500",
        FontWeight::Semibold => "600",
        FontWeight::Bold => "700",
    }
}

/// Surface padding for a [`SpacingScale`].
pub const fn surface_pad_value(scale: SpacingScale) -> &'static str {
    match scale {
        SpacingScale::Compact => "1rem",
        SpacingScale::Comfortable => "1.5rem",
        SpacingScale::Spacious => "2rem",
    }
}

/// Vertical gap for a [`SpacingScale`].
pub const fn vertical_gap_value(scale: SpacingScale) -> &'static str {
    match scale {
        SpacingScale::Compact => "0.75rem",
        SpacingScale::Comfortable => "1rem",
        SpacingScale::Spacious => "1.5rem",
    }
}

/// Input padding for a [`SizeScale`].
pub const fn input_pad_value(size: SizeScale) -> &'static str {
    match size {
        SizeScale::Sm => "0.5rem 0.75rem",
        SizeScale::Md => "0.625rem 0.75rem",
        SizeScale::Lg => "0.875rem 0.875rem",
    }
}

/// Pay-button padding for a [`SizeScale`].
pub const fn button_pad_value(size: SizeScale) -> &'static str {
    match size {
        SizeScale::Sm => "0.625rem 1rem",
        SizeScale::Md => "0.875rem 1.25rem",
        SizeScale::Lg => "1.125rem 1.5rem",
    }
}

/// Rendered pixel dimensions of the merchant logo block.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LogoDimensions {
    /// Side length in CSS pixels.
    pub px: u32,
    /// Corner radius in CSS pixels.
    pub radius: u32,
}

/// Pixel dimensions for a [`LogoSize`].
pub const fn logo_dimensions(size: LogoSize) -> LogoDimensions {
    match size {
        LogoSize::Sm => LogoDimensions { px: 36, radius: 8 },
        LogoSize::Lg => LogoDimensions { px: 64, radius: 16 },
        LogoSize::Md => LogoDimensions { px: 48, radius: 12 },
    }
}

/// The `box-shadow` for a [`SurfaceStyle`].
pub const fn shadow_for(style: SurfaceStyle) -> &'static str {
    match style {
        SurfaceStyle::Elevated => {
            "0 1px 2px rgba(15, 23, 42, 0.04), 0 8px 32px -12px rgba(15, 23, 42, 0.08)"
        }
        SurfaceStyle::Outlined | SurfaceStyle::Flat => "none",
    }
}

/// Whether `value` is a 3- or 6-digit hex colour (leading `#` required,
/// surrounding whitespace ignored).
pub fn is_hex_color(value: &str) -> bool {
    let t = value.trim();
    let Some(rest) = t.strip_prefix('#') else {
        return false;
    };
    if rest.len() != 3 && rest.len() != 6 {
        return false;
    }
    rest.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Minimum contrast for body text — WCAG 2.1 success criterion 1.4.3.
pub const WCAG_AA_TEXT: f64 = 4.5;

/// Minimum contrast for non-text UI — WCAG 2.1 success criterion 1.4.11.
/// Focus rings, borders, icons carrying meaning.
pub const WCAG_AA_UI: f64 = 3.0;

/// The three channels of a CSS `<hex-color>`, or `None` when `value` is not
/// one. The leading `#` is required — see [`contrast_ratio`].
fn css_hex_channels(value: &str) -> Option<(f64, f64, f64)> {
    let t = value.trim();
    let rest = t.strip_prefix('#')?;
    if rest.len() != 3 && rest.len() != 6 {
        return None;
    }
    if !rest.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let full: String = if rest.len() == 3 {
        rest.chars().flat_map(|c| [c, c]).collect()
    } else {
        rest.to_owned()
    };
    let channel = |i: usize| -> Option<f64> {
        u8::from_str_radix(full.get(i..i + 2)?, 16)
            .ok()
            .map(f64::from)
    };
    Some((channel(0)?, channel(2)?, channel(4)?))
}

fn relative_luminance((r, g, b): (f64, f64, f64)) -> f64 {
    let linear = |channel: f64| {
        let c = channel / 255.0;
        if c <= 0.03928 {
            c / 12.92
        } else {
            ((c + 0.055) / 1.055).powf(2.4)
        }
    };
    0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b)
}

/// WCAG 2.1 contrast ratio between two colours, 1–21. Order does not matter.
///
/// Compare against [`WCAG_AA_TEXT`] or [`WCAG_AA_UI`]:
///
/// ```
/// use delopay::branding::{contrast_ratio, WCAG_AA_TEXT};
///
/// match contrast_ratio("#ffffff", "#767676") {
///     Some(ratio) if ratio >= WCAG_AA_TEXT => { /* legible */ }
///     _ => { /* unreadable, or unreadable to us — use the default palette */ }
/// }
/// ```
///
/// **`None` — never a number — when either colour cannot be parsed.** That is
/// the load-bearing part of this signature: a plausible-looking `0.0` or
/// `21.0` would be believed by exactly the branch deciding whether text is
/// legible.
///
/// Accepts `#rgb` and `#rrggbb`, a CSS `<hex-color>`. A hash-less token is
/// `None`, not a ratio: branding values are written into custom properties
/// verbatim, so `"000"` reaches CSS as something that is not a colour, and
/// answering `21` for it would approve a palette that never renders.
/// [`is_dark_surface`] keeps its historical hash-less tolerance; this is new
/// API and does not inherit it.
pub fn contrast_ratio(a: &str, b: &str) -> Option<f64> {
    let first = relative_luminance(css_hex_channels(a)?);
    let second = relative_luminance(css_hex_channels(b)?);
    let (lighter, darker) = if first >= second {
        (first, second)
    } else {
        (second, first)
    };
    Some((lighter + 0.05) / (darker + 0.05))
}

/// Crude perceived-luminance check.
///
/// Picks the right Stripe Elements preset (`"night"` vs `"stripe"`) when the
/// merchant has a dark surface. Inputs not recognized as a 3-/6-digit hex fall
/// through to "light", since that is the safer assumption for the default
/// palette.
///
/// **This is not a readability test — use [`contrast_ratio`] for that.** It is
/// a YIQ luma split at 128, and on real brand colours its verdict and actual
/// legibility can be anti-correlated: `#ff00ff` reads as dark and manages
/// 3.14:1 against white (failing AA text), while `#00ff00` reads as light at
/// 1.37:1 (also failing). A caller picking a text colour from this gets the
/// wrong answer on both. It is kept because choosing a Stripe preset is a
/// legitimate and different question.
pub fn is_dark_surface(color: &str) -> bool {
    // Mirrors the TS `color.replace('#', '').trim()`: only the *first* '#' is
    // removed, then the result is trimmed.
    let stripped = color.replacen('#', "", 1);
    let m = stripped.trim();
    if m.len() != 3 && m.len() != 6 {
        return false;
    }
    let full: String = if m.len() == 3 {
        m.chars().flat_map(|c| [c, c]).collect()
    } else {
        m.to_string()
    };
    let bytes = full.as_bytes();
    if !bytes.iter().all(u8::is_ascii_hexdigit) {
        return false;
    }
    let pair = |i: usize| -> u32 { u32::from_str_radix(&full[i..i + 2], 16).unwrap_or(0) };
    let (r, g, b) = (pair(0), pair(2), pair(4));
    let luma = (r * 299 + g * 587 + b * 114) / 1000;
    luma < 128
}

// --- Defaults -----------------------------------------------------------

/// Light-mode DeloPay-branded baseline badge set.
pub static DEFAULT_BADGES: LazyLock<Vec<TrustBadge>> = LazyLock::new(|| {
    vec![
        TrustBadge::new("secure", "Secure", "#047857", "#ecfdf5").border_color("#a7f3d0"),
        TrustBadge::new("ssl", "256-bit SSL", "#1E4FEB", "#eff6ff").border_color("#bfdbfe"),
    ]
});

/// Dark-mode equivalents of [`DEFAULT_BADGES`].
///
/// Dark trust chips need solid hex (the form's colour picker only accepts hex),
/// so these pair the design system's success-900 / info-900 backdrops with
/// their `*-400` foreground tokens.
pub static DEFAULT_BADGES_DARK: LazyLock<Vec<TrustBadge>> = LazyLock::new(|| {
    vec![
        TrustBadge::new("secure", "Secure", "#34d399", "#064e3b").border_color("#065f46"),
        TrustBadge::new("ssl", "256-bit SSL", "#60a5fa", "#172554").border_color("#1e40af"),
    ]
});

fn default_branding_base() -> CheckoutBranding {
    CheckoutBranding {
        display_name: String::new(),
        logo_url: String::new(),
        tagline: String::new(),
        // Logo + summary gradient OFF by default — an unconfigured DeloPay
        // checkout reads cleaner without a placeholder logo block, and the
        // gradient implies a primary tint the merchant hasn't yet picked.
        show_logo: false,
        logo_shape: LogoShape::Rounded,
        logo_size: LogoSize::Md,

        primary: String::new(),
        background: String::new(),
        surface: String::new(),
        text: String::new(),
        heading: String::new(),
        muted: String::new(),
        border: String::new(),
        accent_text: String::new(),
        button_background: String::new(),
        button_text: String::new(),

        font_family: FontFamily::Inter,
        heading_weight: FontWeight::Semibold,

        radius_surface: NonPillRadius::Medium,
        radius_input: NonPillRadius::Medium,
        radius_button: CornerRadius::Medium,
        radius_badge: CornerRadius::Pill,
        surface_style: SurfaceStyle::Elevated,
        surface_padding: SpacingScale::Comfortable,
        vertical_gap: SpacingScale::Comfortable,
        input_size: SizeScale::Md,
        button_size: SizeScale::Md,

        layout: LayoutStyle::Split,
        summary_position: SummaryPosition::Left,
        show_order_summary: true,
        summary_gradient: false,
        show_total: true,
        total_label: "Total".to_string(),
        show_currency_code: false,
        show_order_items: true,
        cancel_link_enabled: true,
        cancel_link_position: CancelLinkPosition::Top,
        cancel_link_style: CancelLinkStyle::Link,

        show_surcharge: true,
        surcharge_position: SurchargePosition::Trailing,
        native_element_position: NativeElementPosition::Top,
        native_element_stacked: false,
        surcharge_style: SurchargeStyle::Badge,
        surcharge_size: SurchargeSize::Sm,
        surcharge_shape: SurchargeShape::Pill,
        surcharge_border_width: SurchargeBorderWidth::Thin,
        surcharge_border_style: SurchargeBorderStyle::Solid,
        surcharge_weight: SurchargeWeight::Medium,
        surcharge_sign: SurchargeSign::Always,
        surcharge_uppercase: false,
        surcharge_label: SurchargeLabelMode::Labelled,
        surcharge_figure: SurchargeFigureMode::Amount,
        discount_figure: SurchargeFigureMode::PercentThenAmount,
        // Filled in per theme by DEFAULT_BRANDING / DEFAULT_BRANDING_DARK: the
        // two need different colours to clear WCAG AA on their own surface.
        surcharge_color: String::new(),
        discount_color: String::new(),

        method_section_order: default_method_section_order(),
        method_section_labels: MethodSectionLabels::new(),

        airwallex_card_preset: None,
        airwallex_hide_card: false,
        airwallex_hide_card_title: false,
        airwallex_field_chrome: AirwallexFieldChrome::Outlined,
        airwallex_label_style: None,
        airwallex_field_font_size: AirwallexFieldFontSize::Md,
        airwallex_field_weight: AirwallexFieldWeight::Medium,
        airwallex_focus_ring: AirwallexFocusRing::None,
        airwallex_autofill: AirwallexAutofillTreatment::System,
        airwallex_valid_tint: false,
        airwallex_network_marks: false,

        stripe_theme: StripeTheme::Auto,
        stripe_inputs: StripeInputStyle::Spaced,
        stripe_labels: StripeLabelPlacement::Above,
        stripe_spacing: StripeSpacing::Comfortable,
        stripe_field_font_size: CardFieldFontSize::Md,
        stripe_field_weight: CardFieldWeight::Medium,
        stripe_focus_ring: CardFocusRing::Strong,
        stripe_disable_animations: false,
        paypal_card_layout: PaypalCardLayout::Split,
        paypal_label_style: PaypalLabelStyle::Above,
        paypal_field_chrome: CardFieldChrome::Outlined,
        mollie_field_chrome: CardFieldChrome::Outlined,
        paypal_field_font_size: CardFieldFontSize::Md,
        mollie_field_font_size: CardFieldFontSize::Md,
        paypal_field_weight: CardFieldWeight::Regular,
        mollie_field_weight: CardFieldWeight::Regular,
        paypal_focus_ring: CardFocusRing::Strong,
        mollie_focus_ring: CardFocusRing::Strong,
        paypal_valid_tint: false,
        epayouts_card_layout: PaypalCardLayout::Split,
        epayouts_label_style: PaypalLabelStyle::Above,
        epayouts_field_chrome: CardFieldChrome::Outlined,
        epayouts_field_font_size: CardFieldFontSize::Md,
        epayouts_field_weight: CardFieldWeight::Regular,
        epayouts_focus_ring: CardFocusRing::Strong,
        epayouts_valid_tint: false,
        nomupay_form_style: NomupayFormStyle::Plain,
        nomupay_show_labels: true,
        nomupay_show_placeholders: true,
        nomupay_show_cvv_hint: false,
        nomupay_field_chrome: CardFieldChrome::Outlined,
        nomupay_field_font_size: CardFieldFontSize::Md,
        nomupay_focus_ring: CardFocusRing::None,
        nomupay_apple_pay_button_style: ApplePayButtonStyle::Auto,
        nomupay_apple_pay_button_type: ApplePayButtonType::Pay,
        nomupay_google_pay_button_color: GooglePayButtonColor::Auto,
        nomupay_google_pay_button_type: GooglePayButtonType::Pay,
        micropayment_field_chrome: CardFieldChrome::Outlined,
        micropayment_field_font_size: CardFieldFontSize::Md,
        micropayment_field_weight: CardFieldWeight::Regular,
        micropayment_focus_ring: CardFocusRing::Strong,
        whop_card_preset: WhopCardPreset::CardStacked,
        whop_accent_color: WhopAccentColor::Auto,
        whop_gray_color: WhopGrayColor::Auto,
        whop_billing_details: WhopBillingDetails::Minimal,
        whop_separated: false,
        whop_email_label: WhopEmailLabel::Above,
        whop_field_chrome: CardFieldChrome::Outlined,
        whop_field_font_size: CardFieldFontSize::Md,
        whop_field_weight: CardFieldWeight::Regular,
        whop_focus_ring: CardFocusRing::Strong,
        whop_radius: WhopRadius::Checkout,
        whop_shadow: WhopShadow::Soft,
        whop_method_icons: true,
        whop_selection: WhopSelection::RadioTint,

        trust_badges: Vec::new(),
        // Filled in by DEFAULT_BRANDING / DEFAULT_BRANDING_DARK.
        notices: Vec::new(),

        custom_fields: Vec::new(),

        header_text: String::new(),
        pay_button_label: String::new(),
        card_terms_message: String::new(),
        footer_text: String::new(),
        support_email: String::new(),

        payment_layout: PaymentLayout::Tabs,
        label_style: LabelStyle::Above,
        show_powered_by: true,

        custom_css: String::new(),
    }
}

/// The light-mode DeloPay-branded baseline.
///
/// Hex values come straight from `design-guidelines/colors.md`: `#1E4FEB` is
/// the wordmark/icon brand blue, `#0A1130` the wordmark navy, and the rest are
/// slate-50 / slate-200 / slate-500 / slate-800 from the neutral ramp.
pub static DEFAULT_BRANDING: LazyLock<CheckoutBranding> = LazyLock::new(|| CheckoutBranding {
    primary: "#1E4FEB".to_string(),
    background: "#f8fafc".to_string(),
    surface: "#ffffff".to_string(),
    text: "#1e293b".to_string(),
    heading: "#0A1130".to_string(),
    muted: "#64748b".to_string(),
    border: "#e2e8f0".to_string(),
    accent_text: "#1E4FEB".to_string(),
    button_background: "#0A1130".to_string(),
    button_text: "#ffffff".to_string(),
    surcharge_color: "#b45309".to_string(),
    discount_color: "#047857".to_string(),
    // No badges by default any more: notices took their place.
    // `DEFAULT_BADGES` stays because `is_default_badge_set` still has to
    // recognise the pair on shops saved before.
    trust_badges: Vec::new(),
    notices: default_notices(),
    ..default_branding_base()
});

/// The dark counterpart to [`DEFAULT_BRANDING`].
///
/// The same form-only fields stay empty (logo / display name / tagline / copy);
/// only visual tokens diverge. `surface_style` is [`SurfaceStyle::Flat`]
/// because soft drop shadows don't read on dark surfaces.
pub static DEFAULT_BRANDING_DARK: LazyLock<CheckoutBranding> = LazyLock::new(|| CheckoutBranding {
    primary: "#1E4FEB".to_string(),
    background: "#020617".to_string(),
    surface: "#0f172a".to_string(),
    text: "#e2e8f0".to_string(),
    heading: "#f8fafc".to_string(),
    muted: "#94a3b8".to_string(),
    border: "#1e293b".to_string(),
    accent_text: "#60a5fa".to_string(),
    button_background: "#1E4FEB".to_string(),
    button_text: "#ffffff".to_string(),
    surface_style: SurfaceStyle::Flat,
    surcharge_color: "#fbbf24".to_string(),
    discount_color: "#34d399".to_string(),
    trust_badges: Vec::new(),
    notices: default_notices(),
    ..default_branding_base()
});

/// A fresh copy of [`DEFAULT_BRANDING`].
///
/// Back-compat alias for the TypeScript `defaultBranding()`; prefer
/// `DEFAULT_BRANDING.clone()`.
pub fn default_branding() -> CheckoutBranding {
    clone_branding(&DEFAULT_BRANDING)
}

/// Clone a branding value.
///
/// Exists for parity with the TypeScript `cloneBranding`, where the deep-ish
/// copy of `trustBadges` is load-bearing. In Rust `Clone` is already deep, so
/// this is exactly `b.clone()`.
pub fn clone_branding(b: &CheckoutBranding) -> CheckoutBranding {
    b.clone()
}

// --- Method sections: order and captions ---------------------------------

/// Section id to its order number, lower first.
pub type MethodSectionOrder = BTreeMap<String, i64>;

/// Section id to buyer locale to the merchant's caption.
pub type MethodSectionLabels = BTreeMap<String, BTreeMap<String, String>>;

/// Inclusive lower bound of one section's order number.
pub const MIN_SECTION_ORDER: i64 = 1;

/// Inclusive upper bound of one section's order number.
pub const MAX_SECTION_ORDER: i64 = 100;

/// Ceiling on one caption, in characters.
pub const MAX_SECTION_LABEL_LENGTH: usize = 120;

/// Where an id [`METHOD_SECTIONS`] does not know goes: **last**, not first.
pub const UNKNOWN_SECTION_ORDER: i64 = MAX_SECTION_ORDER;

/// One known payment-method section and its default position.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MethodSectionSpec {
    /// The section's id, which is also its identity in the order and caption
    /// maps.
    pub id: &'static str,
    /// The `sections.*` translation key used when the merchant captions
    /// nothing.
    pub label_key: &'static str,
    /// The default order number.
    pub order: i64,
}

/// Every known section, with its default number. Lower renders first.
///
/// Array order is also the tie-break between two sections sharing a number, so
/// it is a display order rather than an arbitrary list — without it, two
/// sections on the same number could swap between renders.
pub const METHOD_SECTIONS: &[MethodSectionSpec] = &[
    MethodSectionSpec {
        id: "card",
        label_key: "sections.card",
        order: 10,
    },
    MethodSectionSpec {
        id: "wallet",
        label_key: "sections.wallets",
        order: 20,
    },
    MethodSectionSpec {
        id: "bnpl",
        label_key: "sections.bnpl",
        order: 30,
    },
    MethodSectionSpec {
        id: "bank_redirect",
        label_key: "sections.onlineBanking",
        order: 40,
    },
    MethodSectionSpec {
        id: "bank_transfer",
        label_key: "sections.bankTransfer",
        order: 45,
    },
    MethodSectionSpec {
        id: "crypto",
        label_key: "sections.cryptocurrency",
        order: 50,
    },
    MethodSectionSpec {
        id: "game_items",
        label_key: "sections.gameItems",
        order: 60,
    },
    MethodSectionSpec {
        id: "voucher",
        label_key: "sections.vouchers",
        order: 70,
    },
    MethodSectionSpec {
        id: "gift_card",
        label_key: "sections.giftCards",
        order: 75,
    },
    MethodSectionSpec {
        id: "reward",
        label_key: "sections.rewards",
        order: 80,
    },
    MethodSectionSpec {
        id: "cash",
        label_key: "sections.cash",
        order: 90,
    },
];

/// Ids that mean an existing section under another name.
pub const SECTION_ALIASES: &[(&str, &str)] = &[("card_redirect", "card")];

/// The id a section is stored under, resolving the aliases above.
pub fn canonical_section_id(id: &str) -> String {
    for (alias, canonical) in SECTION_ALIASES {
        if *alias == id {
            return (*canonical).to_string();
        }
    }
    id.to_string()
}

/// The default order map: every known section at its own default number.
pub fn default_method_section_order() -> MethodSectionOrder {
    METHOD_SECTIONS
        .iter()
        .map(|spec| (spec.id.to_string(), spec.order))
        .collect()
}

fn section_position(id: &str) -> usize {
    METHOD_SECTIONS
        .iter()
        .position(|spec| spec.id == id)
        .unwrap_or(METHOD_SECTIONS.len())
}

/// Compare two section ids for display, under one merchant's order map.
///
/// Sorts by the merchant's number, then by [`METHOD_SECTIONS`] order, then by
/// the id itself. The last two exist so two sections sharing a number cannot
/// swap between renders; an id this build does not know sorts last rather than
/// first.
pub fn compare_sections(a: &str, b: &str, order: &MethodSectionOrder) -> std::cmp::Ordering {
    let a_id = canonical_section_id(a);
    let b_id = canonical_section_id(b);
    let a_order = order.get(&a_id).copied().unwrap_or(UNKNOWN_SECTION_ORDER);
    let b_order = order.get(&b_id).copied().unwrap_or(UNKNOWN_SECTION_ORDER);
    a_order
        .cmp(&b_order)
        .then_with(|| section_position(&a_id).cmp(&section_position(&b_id)))
        .then_with(|| a_id.cmp(&b_id))
}

/// The caption to print for one section, for one buyer locale.
///
/// Resolves caption-for-locale, then caption-in-any-locale, then the caller's
/// own name for the section, then the raw id — so a section always prints as
/// *something*, and never as an empty heading. Locale matching folds case and
/// walks parent tags (`de-AT` finds `de`), because a tag arrives in whatever
/// case the browser sent it.
pub fn section_label(
    id: &str,
    locale: &str,
    labels: &MethodSectionLabels,
    fallback: Option<&str>,
) -> String {
    let section = canonical_section_id(id);
    if let Some(by_locale) = labels.get(&section) {
        let wanted = locale.to_ascii_lowercase();
        let mut candidate: &str = &wanted;
        loop {
            for (key, value) in by_locale {
                if key.to_ascii_lowercase() == candidate && !value.trim().is_empty() {
                    return value.clone();
                }
            }
            match candidate.rfind('-') {
                Some(cut) => candidate = &candidate[..cut],
                None => break,
            }
        }
        // Any translation beats no heading at all.
        if let Some(value) = by_locale.values().find(|v| !v.trim().is_empty()) {
            return value.clone();
        }
    }
    match fallback {
        Some(name) if !name.trim().is_empty() => name.to_string(),
        _ => section,
    }
}

/// Decode the JSON-encoded section order stored under
/// `sdk_ui_rules.branding.methodSectionOrder`.
///
/// Tolerant on purpose — this reaches a page every buyer sees: a malformed
/// payload gives the defaults, and one bad entry never costs the others.
pub fn decode_method_section_order(raw: Option<&str>) -> MethodSectionOrder {
    let mut order = default_method_section_order();
    let Some(raw) = raw else { return order };
    let Ok(Value::Object(parsed)) = serde_json::from_str::<Value>(raw) else {
        return order;
    };
    for (key, value) in parsed {
        let Some(number) = value.as_i64() else {
            continue;
        };
        if !(MIN_SECTION_ORDER..=MAX_SECTION_ORDER).contains(&number) {
            continue;
        }
        order.insert(canonical_section_id(&key), number);
    }
    order
}

/// Encode a section order for the branding bag.
pub fn encode_method_section_order(order: &MethodSectionOrder) -> String {
    serde_json::to_string(order).unwrap_or_else(|_| "{}".to_string())
}

/// Decode the JSON-encoded section captions stored under
/// `sdk_ui_rules.branding.methodSectionLabels`.
///
/// Blank captions are dropped, so an emptied field round-trips as absence
/// rather than as a heading the buyer sees blank.
pub fn decode_method_section_labels(raw: Option<&str>) -> MethodSectionLabels {
    let mut labels = MethodSectionLabels::new();
    let Some(raw) = raw else { return labels };
    let Ok(Value::Object(parsed)) = serde_json::from_str::<Value>(raw) else {
        return labels;
    };
    for (section, by_locale) in parsed {
        let Some(by_locale) = by_locale.as_object() else {
            continue;
        };
        if section.trim().is_empty() {
            continue;
        }
        let mut entries: BTreeMap<String, String> = BTreeMap::new();
        for (locale, caption) in by_locale {
            let Some(caption) = caption.as_str() else {
                continue;
            };
            let caption = caption.trim();
            if locale.trim().is_empty() || caption.is_empty() {
                continue;
            }
            // Truncated, not dropped: the same stored value must survive here
            // and in the TypeScript codec, and dropping it would blank a
            // heading the other client still prints.
            entries.insert(locale.clone(), truncate_section_label(caption));
        }
        if !entries.is_empty() {
            labels.insert(canonical_section_id(&section), entries);
        }
    }
    labels
}

/// Encode section captions for the branding bag.
///
/// Normalizes on the way out exactly as [`decode_method_section_labels`] does
/// on the way in — trimmed, truncated to [`MAX_SECTION_LABEL_LENGTH`], blank
/// entries dropped — so a caption written through this codec reads back as
/// itself rather than as something a stricter decoder discards.
pub fn encode_method_section_labels(labels: &MethodSectionLabels) -> String {
    let mut cleaned = MethodSectionLabels::new();
    for (section, by_locale) in labels {
        let mut kept: BTreeMap<String, String> = BTreeMap::new();
        for (locale, caption) in by_locale {
            let caption = caption.trim();
            if locale.trim().is_empty() || caption.is_empty() {
                continue;
            }
            kept.insert(locale.clone(), truncate_section_label(caption));
        }
        if !kept.is_empty() {
            cleaned.insert(canonical_section_id(section), kept);
        }
    }
    serde_json::to_string(&cleaned).unwrap_or_else(|_| "{}".to_string())
}

/// Cap a caption at [`MAX_SECTION_LABEL_LENGTH`] UTF-16 code units — the unit
/// JavaScript's `slice` counts, so the two codecs cut at the same place — never
/// splitting a character.
fn truncate_section_label(caption: &str) -> String {
    if utf16_len(caption) <= MAX_SECTION_LABEL_LENGTH {
        return caption.to_string();
    }
    let mut out = String::new();
    let mut units = 0;
    for c in caption.chars() {
        let w = c.len_utf16();
        if units + w > MAX_SECTION_LABEL_LENGTH {
            break;
        }
        out.push(c);
        units += w;
    }
    out
}

// --- Surcharge disclosure token maps ------------------------------------

/// Type size per [`SurchargeSize`].
pub const fn surcharge_font_size(size: SurchargeSize) -> &'static str {
    match size {
        SurchargeSize::Sm => "0.6875rem",
        SurchargeSize::Md => "0.8125rem",
        SurchargeSize::Lg => "0.9375rem",
    }
}

/// Shape padding per [`SurchargeSize`]. Grows with the type.
pub const fn surcharge_pad(size: SurchargeSize) -> &'static str {
    match size {
        SurchargeSize::Sm => "1px 6px",
        SurchargeSize::Md => "2px 8px",
        SurchargeSize::Lg => "3px 10px",
    }
}

/// Corner radius per [`SurchargeShape`].
pub const fn surcharge_radius(shape: SurchargeShape) -> &'static str {
    match shape {
        SurchargeShape::Pill => "999px",
        SurchargeShape::Rounded => "6px",
        SurchargeShape::Square => "0px",
    }
}

/// Border thickness per [`SurchargeBorderWidth`].
pub const fn surcharge_border_width_value(width: SurchargeBorderWidth) -> &'static str {
    match width {
        SurchargeBorderWidth::None => "0px",
        SurchargeBorderWidth::Thin => "1px",
        SurchargeBorderWidth::Medium => "2px",
        SurchargeBorderWidth::Thick => "3px",
    }
}

/// Font weight per [`SurchargeWeight`].
pub const fn surcharge_font_weight(weight: SurchargeWeight) -> &'static str {
    match weight {
        SurchargeWeight::Regular => "400",
        SurchargeWeight::Medium => "600",
        SurchargeWeight::Bold => "700",
    }
}

/// Whether a style has a fill or a border, and therefore whether
/// [`CheckoutBranding::surcharge_shape`] means anything for it.
///
/// A dashboard that leaves the corner picker live under `Plain` offers a
/// control that changes nothing on screen.
pub const fn surcharge_style_draws_a_shape(style: SurchargeStyle) -> bool {
    matches!(
        style,
        SurchargeStyle::Badge
            | SurchargeStyle::Outline
            | SurchargeStyle::Solid
            | SurchargeStyle::Ribbon
    )
}

/// Black or white, whichever reads better **on** `color`.
///
/// Measured by contrast ratio rather than by a luminance threshold, because the
/// `Solid` style fills with the merchant's own colour and one fixed ink makes
/// the loudest style the least readable. Anything unparseable answers white.
pub fn readable_ink_on(color: &str) -> &'static str {
    let on_black = contrast_ratio(color, "#000000");
    let on_white = contrast_ratio(color, "#ffffff");
    match (on_black, on_white) {
        (Some(black), Some(white)) if black >= white => "#000000",
        (Some(_), Some(_)) => "#ffffff",
        _ => "#ffffff",
    }
}

/// The Airwallex card preset actually drawn, in the order the sources decide
/// it.
///
/// 1. The shop's branding, empty until the merchant opens the customizer.
/// 2. The connector account's own `integration_style`, where this setting lived
///    before the customizer existed. Still authoritative for every merchant who
///    set it; nothing migrates it.
/// 3. `split_fields_labelled`, for a shop that has never set either.
///
/// Anything unrecognised at either step falls through rather than failing: a
/// card form in the wrong layout is a cosmetic disappointment, and no card form
/// is a lost sale.
pub fn resolve_airwallex_card_preset(
    from_branding: Option<&str>,
    from_connector: Option<&str>,
) -> AirwallexCardPreset {
    let parse = |value: Option<&str>| -> Option<AirwallexCardPreset> {
        let raw = value?.trim().to_ascii_lowercase();
        AirwallexCardPreset::from_wire(&raw)
    };
    parse(from_branding)
        .or_else(|| parse(from_connector))
        .unwrap_or(AIRWALLEX_CARD_PRESET_FALLBACK)
}

/// The preset that renders when nobody has chosen one.
pub const AIRWALLEX_CARD_PRESET_FALLBACK: AirwallexCardPreset =
    AirwallexCardPreset::SplitFieldsLabelled;

// --- Sanitizer ----------------------------------------------------------

/// Hard cap on the persisted custom-CSS payload, in UTF-16 code units (the
/// unit JavaScript's `String.length` counts, so the two sides agree).
///
/// Oversized input is dropped entirely rather than truncated, since a
/// half-truncated rule is worse than no rule.
pub const CUSTOM_CSS_MAX_LENGTH: usize = 50_000;

/// Strip CSS constructs that turn a stylesheet into a delivery vector.
///
/// Returns `None` for absent, blank, or oversized input; otherwise the
/// sanitized CSS. The list is not exhaustive — it is the everyday surface
/// area, applied in this order:
///
/// - `</style` becomes `<\/style`, so injected text cannot break out of the
///   `<style>` block and parse as HTML/JS. It is *replaced*, not removed, so a
///   `</styled-tag` inside a `content:` string doesn't silently merge into the
///   surrounding text.
/// - `@import …;` is removed — it would let the merchant pull a remote
///   stylesheet on every buyer page-load (analytics by side channel, possible
///   buyer-IP leak). The rest of the declaration up to and including the next
///   `;` goes with it; with no `;`, everything to the end of input.
/// - `expression(` becomes `/* expression( */` — a legacy IE construct that
///   ran JS from CSS.
/// - `behavior:` becomes `/* behavior: */`, but only when not preceded by an
///   ASCII letter or `-`, so `-webkit-behavior:` is left alone.
/// - `-moz-binding:` becomes `/* -moz-binding: */`.
/// - `url(javascript:` (with optional whitespace and one optional quote)
///   becomes `url(invalid:`.
///
/// All matching is ASCII case-insensitive. Anything else passes through: the
/// merchant can still write background images, gradients, transforms,
/// keyframes, container queries, and so on.
pub fn sanitize_custom_css(raw: Option<&str>) -> Option<String> {
    let raw = raw?;
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    if utf16_len(trimmed) > CUSTOM_CSS_MAX_LENGTH {
        return None;
    }

    let mut out = trimmed.to_string();
    out = escape_style_close(&out);
    out = strip_imports(&out);
    out = comment_out(&out, "expression", Some('('), "/* expression( */", false);
    out = comment_out(&out, "behavior", Some(':'), "/* behavior: */", true);
    out = comment_out(
        &out,
        "-moz-binding",
        Some(':'),
        "/* -moz-binding: */",
        false,
    );
    out = neutralize_javascript_urls(&out);
    Some(out)
}

fn utf16_len(s: &str) -> usize {
    s.encode_utf16().count()
}

/// ASCII-case-insensitive substring search starting at `from`.
///
/// `needle` must be ASCII lowercase. Matching bytes of an ASCII needle can
/// never fall inside a multi-byte UTF-8 sequence, so the returned index is
/// always a char boundary.
fn find_ci(hay: &str, needle: &str, from: usize) -> Option<usize> {
    let hb = hay.as_bytes();
    let nb = needle.as_bytes();
    if nb.is_empty() || hb.len() < nb.len() {
        return None;
    }
    (from..=hb.len() - nb.len()).find(|&i| {
        hb[i..i + nb.len()]
            .iter()
            .zip(nb)
            .all(|(a, b)| a.to_ascii_lowercase() == *b)
    })
}

/// Advance past whitespace, matching JavaScript's `\s` closely enough:
/// Unicode `White_Space` plus U+FEFF.
fn skip_ws(s: &str, mut i: usize) -> usize {
    while let Some(c) = s[i..].chars().next() {
        if c.is_whitespace() || c == '\u{feff}' {
            i += c.len_utf8();
        } else {
            break;
        }
    }
    i
}

fn escape_style_close(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while let Some(idx) = find_ci(s, "</style", i) {
        out.push_str(&s[i..idx]);
        out.push_str("<\\/style");
        i = idx + "</style".len();
    }
    out.push_str(&s[i..]);
    out
}

fn is_word_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

fn strip_imports(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while let Some(idx) = find_ci(s, "@import", i) {
        let after = idx + "@import".len();
        // `\b` after a word character: the next byte must not be a word byte.
        if s.as_bytes().get(after).copied().is_some_and(is_word_byte) {
            out.push_str(&s[i..idx + 1]);
            i = idx + 1;
            continue;
        }
        out.push_str(&s[i..idx]);
        // `[^;]*;?` — everything up to and including the next `;`, or to the
        // end of input when there is none.
        i = match s[after..].find(';') {
            Some(rel) => after + rel + 1,
            None => s.len(),
        };
    }
    out.push_str(&s[i..]);
    out
}

/// Replace `token` (optionally followed by whitespace and `terminator`) with
/// `replacement`.
///
/// When `guard_prefix` is set, a match is skipped unless the preceding
/// character is neither an ASCII letter nor `-` (the TS `(^|[^a-z-])` group,
/// which the `i` flag widens to both cases).
fn comment_out(
    s: &str,
    token: &str,
    terminator: Option<char>,
    replacement: &str,
    guard_prefix: bool,
) -> String {
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while let Some(idx) = find_ci(s, token, i) {
        if guard_prefix
            && idx > 0
            && s[..idx]
                .chars()
                .next_back()
                .is_some_and(|c| c.is_ascii_alphabetic() || c == '-')
        {
            out.push_str(&s[i..idx + 1]);
            i = idx + 1;
            continue;
        }
        let after = skip_ws(s, idx + token.len());
        let end = match terminator {
            Some(t) if s[after..].starts_with(t) => after + t.len_utf8(),
            Some(_) => {
                out.push_str(&s[i..idx + 1]);
                i = idx + 1;
                continue;
            }
            None => after,
        };
        out.push_str(&s[i..idx]);
        out.push_str(replacement);
        i = end;
    }
    out.push_str(&s[i..]);
    out
}

fn neutralize_javascript_urls(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while let Some(idx) = find_ci(s, "url", i) {
        let mut p = skip_ws(s, idx + 3);
        if !s[p..].starts_with('(') {
            out.push_str(&s[i..idx + 1]);
            i = idx + 1;
            continue;
        }
        p = skip_ws(s, p + 1);
        if s[p..].starts_with('"') || s[p..].starts_with('\'') {
            p += 1;
        }
        p = skip_ws(s, p);
        if find_ci(s, "javascript:", p) != Some(p) {
            out.push_str(&s[i..idx + 1]);
            i = idx + 1;
            continue;
        }
        out.push_str(&s[i..idx]);
        out.push_str("url(invalid:");
        i = p + "javascript:".len();
    }
    out.push_str(&s[i..]);
    out
}

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

/// Structural shape the decoder reads.
///
/// Both the public buyer payload and the merchant config request shape satisfy
/// this: they each fill some of these fields and leave the rest unset.
/// `merchant_*` and `seller_*` / `logo` are aliases for the same API field,
/// surfaced under different names by the two payloads.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct BrandingSource {
    /// Merchant name, public payload spelling.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub merchant_name: Option<String>,
    /// Merchant name, request payload spelling.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seller_name: Option<String>,
    /// Logo URL, public payload spelling.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub merchant_logo: Option<String>,
    /// Logo URL, request payload spelling.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub logo: Option<String>,
    /// Public surface of the tagline.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub merchant_description: Option<String>,

    /// Brand colour.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub theme: Option<String>,
    /// Page background colour.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background_colour: Option<String>,
    /// Pay-button background colour.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payment_button_colour: Option<String>,
    /// Pay-button foreground colour.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payment_button_text_colour: Option<String>,

    /// Header copy above the form.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payment_form_header_text: Option<String>,
    /// Pay-button label.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payment_button_text: Option<String>,
    /// Card terms/consent message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub custom_message_for_card_terms: Option<String>,

    /// Whether the "Powered by DeloPay" footer is shown. Only an explicit
    /// `false` hides it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branding_visibility: Option<bool>,

    /// Stripe Elements payment-method layout.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sdk_layout: Option<String>,
    /// Legacy Stripe label mode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payment_form_label_type: Option<String>,

    /// The bag for everything the flat columns don't carry. Branding lives
    /// under the `"branding"` group.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sdk_ui_rules: Option<Map<String, Value>>,
}

/// The `sdk_ui_rules` group branding is persisted under.
const BRANDING_GROUP_KEY: &str = "branding";

fn s(v: &Option<String>) -> &str {
    v.as_deref().unwrap_or("")
}

fn or_else(value: &str, fallback: &str) -> String {
    if value.is_empty() {
        fallback.to_string()
    } else {
        value.to_string()
    }
}

fn pick_enum<T: WireEnum>(value: Option<&Value>, fallback: T) -> T {
    match value.and_then(Value::as_str) {
        Some(raw) => T::parse_wire(raw).unwrap_or(fallback),
        None => fallback,
    }
}

/// A wire enum that may be deliberately unset.
///
/// An empty string is the wire's way of saying "the merchant has not chosen",
/// which is a different answer from any member of the set — so it decodes to
/// `None` rather than to a default that would override another source.
fn pick_optional_enum<T: WireEnum>(value: Option<&Value>) -> Option<T> {
    let raw = value?.as_str()?.trim();
    if raw.is_empty() {
        return None;
    }
    T::parse_wire(raw)
}

fn parse_bool(value: Option<&Value>, fallback: bool) -> bool {
    match value {
        Some(Value::Bool(b)) => *b,
        Some(Value::String(raw)) if raw == "true" => true,
        Some(Value::String(raw)) if raw == "false" => false,
        _ => fallback,
    }
}

/// Read a bag entry as a string, treating a missing or non-string value as
/// `""` (the TypeScript `s()` helper).
fn bag_str<'a>(bag: &'a Map<String, Value>, key: &str) -> &'a str {
    bag.get(key).and_then(Value::as_str).unwrap_or("")
}

/// Decode the JSON-encoded trust badges stored under
/// `sdk_ui_rules.branding.trustBadges`.
///
/// Tolerant: a malformed payload, missing fields, or wrong types fall through
/// to `None` so the caller can substitute the default badge set. An explicit
/// empty array means "no badges" and is honoured — merchants who hide the row
/// need a way to express that. Badges with an empty label are dropped.
pub fn decode_badges(raw: Option<&str>) -> Option<Vec<TrustBadge>> {
    let raw = raw?;
    let parsed: Value = serde_json::from_str(raw).ok()?;
    let items = parsed.as_array()?;
    Some(
        items
            .iter()
            .enumerate()
            .filter_map(|(i, item)| {
                let obj = item.as_object()?;
                let str_field = |k: &str| obj.get(k).and_then(Value::as_str);
                Some(TrustBadge {
                    id: match str_field("id") {
                        Some(id) if !id.is_empty() => id.to_string(),
                        _ => format!("badge-{i}"),
                    },
                    label: str_field("label").unwrap_or("").to_string(),
                    text_color: str_field("textColor").unwrap_or("#0f172a").to_string(),
                    background_color: str_field("backgroundColor")
                        .unwrap_or("#f1f5f9")
                        .to_string(),
                    border_color: str_field("borderColor")
                        .filter(|v| !v.is_empty())
                        .map(str::to_string),
                })
            })
            .filter(|b| !b.label.is_empty())
            .collect(),
    )
}

/// The exact wire shape `encode_badges` emits, in declaration order, so the
/// JSON string is byte-identical to the TypeScript `JSON.stringify` output.
#[derive(Serialize)]
struct BadgeWire<'a> {
    id: &'a str,
    label: &'a str,
    #[serde(rename = "textColor")]
    text_color: &'a str,
    #[serde(rename = "backgroundColor")]
    background_color: &'a str,
    #[serde(rename = "borderColor", skip_serializing_if = "Option::is_none")]
    border_color: Option<&'a str>,
}

/// JSON-stringify trust badges for the `sdk_ui_rules.branding.trustBadges` bag
/// entry.
///
/// A `None` or empty `border_color` is omitted from the object entirely, which
/// is what the TypeScript encoder does.
pub fn encode_badges(badges: &[TrustBadge]) -> String {
    let wire: Vec<BadgeWire<'_>> = badges
        .iter()
        .map(|b| BadgeWire {
            id: &b.id,
            label: &b.label,
            text_color: &b.text_color,
            background_color: &b.background_color,
            border_color: b.border_color.as_deref().filter(|v| !v.is_empty()),
        })
        .collect();
    serde_json::to_string(&wire).unwrap_or_else(|_| "[]".to_string())
}

/// Read a branding source into a fully-resolved [`CheckoutBranding`].
///
/// Flat fields are authoritative when set; the `sdk_ui_rules.branding` bag
/// fills in everything not reachable via a flat column. A persisted
/// `labelStyle: "floating"` (legacy preview-only value Stripe Elements never
/// honoured) decodes to [`LabelStyle::Above`], and the legacy `"never"`
/// decodes to [`LabelStyle::Hidden`]. `None` yields [`DEFAULT_BRANDING`].
pub fn decode_branding(source: Option<&BrandingSource>) -> CheckoutBranding {
    let Some(source) = source else {
        return clone_branding(&DEFAULT_BRANDING);
    };
    let dflt = &*DEFAULT_BRANDING;

    let empty = Map::new();
    let extras: &Map<String, Value> = source
        .sdk_ui_rules
        .as_ref()
        .and_then(|rules| rules.get(BRANDING_GROUP_KEY))
        .and_then(Value::as_object)
        .unwrap_or(&empty);

    // Badges and notices are decided together: which one a shop gets depends
    // on what it saved of both.
    let trust_row = resolve_notices_and_badges(
        decode_badges(extras.get("trustBadges").and_then(Value::as_str)),
        decode_notices(extras.get("notices").and_then(Value::as_str)),
    );
    let decoded_custom_fields =
        decode_custom_fields(extras.get("customFields").and_then(Value::as_str));

    // Identity name: public payloads call it `merchant_name`, request payloads
    // call it `seller_name`. Same API field; pick whichever is present.
    let display_name = or_else(s(&source.merchant_name), s(&source.seller_name));
    let logo_url = or_else(s(&source.merchant_logo), s(&source.logo));

    // Tagline lives in the bag, but `merchant_description` is its public
    // surface. Either may fill it; the bag wins if both are set.
    let tagline = or_else(bag_str(extras, "tagline"), s(&source.merchant_description));

    // The bag's `labelStyle` is the new source of truth; the legacy flat
    // `payment_form_label_type` is consulted only when the bag is empty.
    let label_style = {
        let from_bag = bag_str(extras, "labelStyle");
        match from_bag {
            "above" | "floating" => LabelStyle::Above,
            "hidden" => LabelStyle::Hidden,
            _ => match s(&source.payment_form_label_type) {
                "above" | "floating" => LabelStyle::Above,
                "hidden" | "never" => LabelStyle::Hidden,
                _ => dflt.label_style,
            },
        }
    };

    CheckoutBranding {
        display_name,
        logo_url,
        tagline,
        show_logo: parse_bool(extras.get("showLogo"), dflt.show_logo),
        logo_shape: pick_enum(extras.get("logoShape"), dflt.logo_shape),
        logo_size: pick_enum(extras.get("logoSize"), dflt.logo_size),

        primary: or_else(s(&source.theme), &dflt.primary),
        background: or_else(s(&source.background_colour), &dflt.background),
        surface: or_else(bag_str(extras, "surface"), &dflt.surface),
        text: or_else(bag_str(extras, "text"), &dflt.text),
        heading: or_else(
            bag_str(extras, "heading"),
            &or_else(bag_str(extras, "text"), &dflt.heading),
        ),
        muted: or_else(bag_str(extras, "muted"), &dflt.muted),
        border: or_else(bag_str(extras, "border"), &dflt.border),
        accent_text: or_else(
            bag_str(extras, "accentText"),
            &or_else(s(&source.theme), &dflt.accent_text),
        ),
        button_background: or_else(
            s(&source.payment_button_colour),
            &or_else(s(&source.theme), &dflt.button_background),
        ),
        button_text: or_else(s(&source.payment_button_text_colour), &dflt.button_text),

        font_family: pick_enum(extras.get("fontFamily"), dflt.font_family),
        heading_weight: pick_enum(extras.get("headingWeight"), dflt.heading_weight),

        radius_surface: pick_enum(extras.get("radiusSurface"), dflt.radius_surface),
        radius_input: pick_enum(extras.get("radiusInput"), dflt.radius_input),
        radius_button: pick_enum(extras.get("radiusButton"), dflt.radius_button),
        radius_badge: pick_enum(extras.get("radiusBadge"), dflt.radius_badge),
        surface_style: pick_enum(extras.get("surfaceStyle"), dflt.surface_style),
        surface_padding: pick_enum(extras.get("surfacePadding"), dflt.surface_padding),
        vertical_gap: pick_enum(extras.get("verticalGap"), dflt.vertical_gap),
        input_size: pick_enum(extras.get("inputSize"), dflt.input_size),
        button_size: pick_enum(extras.get("buttonSize"), dflt.button_size),

        layout: pick_enum(extras.get("layout"), dflt.layout),
        summary_position: pick_enum(extras.get("summaryPosition"), dflt.summary_position),
        show_order_summary: parse_bool(extras.get("showOrderSummary"), dflt.show_order_summary),
        summary_gradient: parse_bool(extras.get("summaryGradient"), dflt.summary_gradient),
        show_total: parse_bool(extras.get("showTotal"), dflt.show_total),
        total_label: or_else(bag_str(extras, "totalLabel"), &dflt.total_label),
        show_currency_code: parse_bool(extras.get("showCurrencyCode"), dflt.show_currency_code),
        show_order_items: parse_bool(extras.get("showOrderItems"), dflt.show_order_items),
        cancel_link_enabled: parse_bool(extras.get("cancelLinkEnabled"), dflt.cancel_link_enabled),
        cancel_link_position: pick_enum(
            extras.get("cancelLinkPosition"),
            dflt.cancel_link_position,
        ),
        cancel_link_style: pick_enum(extras.get("cancelLinkStyle"), dflt.cancel_link_style),

        show_surcharge: parse_bool(extras.get("showSurcharge"), dflt.show_surcharge),
        surcharge_position: pick_enum(extras.get("surchargePosition"), dflt.surcharge_position),
        native_element_position: pick_enum(
            extras.get("nativeElementPosition"),
            dflt.native_element_position,
        ),
        native_element_stacked: parse_bool(
            extras.get("nativeElementStacked"),
            dflt.native_element_stacked,
        ),
        surcharge_style: pick_enum(extras.get("surchargeStyle"), dflt.surcharge_style),
        surcharge_size: pick_enum(extras.get("surchargeSize"), dflt.surcharge_size),
        surcharge_shape: pick_enum(extras.get("surchargeShape"), dflt.surcharge_shape),
        surcharge_border_width: pick_enum(
            extras.get("surchargeBorderWidth"),
            dflt.surcharge_border_width,
        ),
        surcharge_border_style: pick_enum(
            extras.get("surchargeBorderStyle"),
            dflt.surcharge_border_style,
        ),
        surcharge_weight: pick_enum(extras.get("surchargeWeight"), dflt.surcharge_weight),
        surcharge_sign: pick_enum(extras.get("surchargeSign"), dflt.surcharge_sign),
        surcharge_uppercase: parse_bool(extras.get("surchargeUppercase"), dflt.surcharge_uppercase),
        surcharge_label: pick_enum(extras.get("surchargeLabel"), dflt.surcharge_label),
        surcharge_figure: pick_enum(extras.get("surchargeFigure"), dflt.surcharge_figure),
        discount_figure: pick_enum(extras.get("discountFigure"), dflt.discount_figure),
        surcharge_color: or_else(bag_str(extras, "surchargeColor"), &dflt.surcharge_color),
        discount_color: or_else(bag_str(extras, "discountColor"), &dflt.discount_color),

        method_section_order: decode_method_section_order(
            extras.get("methodSectionOrder").and_then(Value::as_str),
        ),
        method_section_labels: decode_method_section_labels(
            extras.get("methodSectionLabels").and_then(Value::as_str),
        ),

        trust_badges: trust_row.trust_badges,
        notices: trust_row.notices,

        // Unlike badges, an absent blob means "no custom fields" rather than
        // "use the defaults": there is no default field set to fall back to.
        custom_fields: decoded_custom_fields.unwrap_or_default(),

        header_text: s(&source.payment_form_header_text).to_string(),
        pay_button_label: s(&source.payment_button_text).to_string(),
        card_terms_message: s(&source.custom_message_for_card_terms).to_string(),
        footer_text: bag_str(extras, "footerText").to_string(),
        support_email: bag_str(extras, "supportEmail").to_string(),

        payment_layout: PaymentLayout::from_wire(s(&source.sdk_layout))
            .unwrap_or(dflt.payment_layout),
        label_style,

        // An empty string is not a preset: it means the merchant has not chosen
        // one, which is what lets the connector account's own setting decide.
        airwallex_card_preset: pick_optional_enum(extras.get("airwallexCardPreset")),
        airwallex_hide_card: parse_bool(extras.get("airwallexHideCard"), dflt.airwallex_hide_card),
        airwallex_hide_card_title: parse_bool(
            extras.get("airwallexHideCardTitle"),
            dflt.airwallex_hide_card_title,
        ),
        airwallex_field_chrome: pick_enum(
            extras.get("airwallexFieldChrome"),
            dflt.airwallex_field_chrome,
        ),
        airwallex_label_style: pick_optional_enum(extras.get("airwallexLabelStyle")),
        airwallex_field_font_size: pick_enum(
            extras.get("airwallexFieldFontSize"),
            dflt.airwallex_field_font_size,
        ),
        airwallex_field_weight: pick_enum(
            extras.get("airwallexFieldWeight"),
            dflt.airwallex_field_weight,
        ),
        airwallex_focus_ring: pick_enum(
            extras.get("airwallexFocusRing"),
            dflt.airwallex_focus_ring,
        ),
        airwallex_autofill: pick_enum(extras.get("airwallexAutofill"), dflt.airwallex_autofill),
        airwallex_valid_tint: parse_bool(
            extras.get("airwallexValidTint"),
            dflt.airwallex_valid_tint,
        ),
        airwallex_network_marks: parse_bool(
            extras.get("airwallexNetworkMarks"),
            dflt.airwallex_network_marks,
        ),

        // A look stored before e-Payouts had its own keys has none: the form
        // keeps the PayPal values it was drawn with until then.
        stripe_theme: pick_enum(extras.get("stripeTheme"), dflt.stripe_theme),
        stripe_inputs: pick_enum(extras.get("stripeInputs"), dflt.stripe_inputs),
        stripe_labels: pick_enum(extras.get("stripeLabels"), dflt.stripe_labels),
        stripe_spacing: pick_enum(extras.get("stripeSpacing"), dflt.stripe_spacing),
        stripe_field_font_size: pick_enum(
            extras.get("stripeFieldFontSize"),
            dflt.stripe_field_font_size,
        ),
        stripe_field_weight: pick_enum(extras.get("stripeFieldWeight"), dflt.stripe_field_weight),
        stripe_focus_ring: pick_enum(extras.get("stripeFocusRing"), dflt.stripe_focus_ring),
        stripe_disable_animations: parse_bool(
            extras.get("stripeDisableAnimations"),
            dflt.stripe_disable_animations,
        ),
        paypal_card_layout: pick_enum(extras.get("paypalCardLayout"), dflt.paypal_card_layout),
        paypal_label_style: pick_enum(extras.get("paypalLabelStyle"), dflt.paypal_label_style),
        paypal_field_chrome: pick_enum(extras.get("paypalFieldChrome"), dflt.paypal_field_chrome),
        mollie_field_chrome: pick_enum(extras.get("mollieFieldChrome"), dflt.mollie_field_chrome),
        paypal_field_font_size: pick_enum(
            extras.get("paypalFieldFontSize"),
            dflt.paypal_field_font_size,
        ),
        mollie_field_font_size: pick_enum(
            extras.get("mollieFieldFontSize"),
            dflt.mollie_field_font_size,
        ),
        paypal_field_weight: pick_enum(extras.get("paypalFieldWeight"), dflt.paypal_field_weight),
        mollie_field_weight: pick_enum(extras.get("mollieFieldWeight"), dflt.mollie_field_weight),
        paypal_focus_ring: pick_enum(extras.get("paypalFocusRing"), dflt.paypal_focus_ring),
        mollie_focus_ring: pick_enum(extras.get("mollieFocusRing"), dflt.mollie_focus_ring),
        paypal_valid_tint: parse_bool(extras.get("paypalValidTint"), dflt.paypal_valid_tint),
        epayouts_card_layout: pick_enum(
            extras.get("epayoutsCardLayout"),
            pick_enum(extras.get("paypalCardLayout"), dflt.epayouts_card_layout),
        ),
        epayouts_label_style: pick_enum(
            extras.get("epayoutsLabelStyle"),
            pick_enum(extras.get("paypalLabelStyle"), dflt.epayouts_label_style),
        ),
        epayouts_field_chrome: pick_enum(
            extras.get("epayoutsFieldChrome"),
            pick_enum(extras.get("paypalFieldChrome"), dflt.epayouts_field_chrome),
        ),
        epayouts_field_font_size: pick_enum(
            extras.get("epayoutsFieldFontSize"),
            pick_enum(
                extras.get("paypalFieldFontSize"),
                dflt.epayouts_field_font_size,
            ),
        ),
        epayouts_field_weight: pick_enum(
            extras.get("epayoutsFieldWeight"),
            pick_enum(extras.get("paypalFieldWeight"), dflt.epayouts_field_weight),
        ),
        epayouts_focus_ring: pick_enum(
            extras.get("epayoutsFocusRing"),
            pick_enum(extras.get("paypalFocusRing"), dflt.epayouts_focus_ring),
        ),
        epayouts_valid_tint: parse_bool(
            extras.get("epayoutsValidTint"),
            parse_bool(extras.get("paypalValidTint"), dflt.epayouts_valid_tint),
        ),
        nomupay_form_style: pick_enum(extras.get("nomupayFormStyle"), dflt.nomupay_form_style),
        nomupay_show_labels: parse_bool(extras.get("nomupayShowLabels"), dflt.nomupay_show_labels),
        nomupay_show_placeholders: parse_bool(
            extras.get("nomupayShowPlaceholders"),
            dflt.nomupay_show_placeholders,
        ),
        nomupay_show_cvv_hint: parse_bool(
            extras.get("nomupayShowCvvHint"),
            dflt.nomupay_show_cvv_hint,
        ),
        nomupay_field_chrome: pick_enum(
            extras.get("nomupayFieldChrome"),
            dflt.nomupay_field_chrome,
        ),
        nomupay_field_font_size: pick_enum(
            extras.get("nomupayFieldFontSize"),
            dflt.nomupay_field_font_size,
        ),
        nomupay_focus_ring: pick_enum(extras.get("nomupayFocusRing"), dflt.nomupay_focus_ring),
        nomupay_apple_pay_button_style: pick_enum(
            extras.get("nomupayApplePayButtonStyle"),
            dflt.nomupay_apple_pay_button_style,
        ),
        nomupay_apple_pay_button_type: pick_enum(
            extras.get("nomupayApplePayButtonType"),
            dflt.nomupay_apple_pay_button_type,
        ),
        nomupay_google_pay_button_color: pick_enum(
            extras.get("nomupayGooglePayButtonColor"),
            dflt.nomupay_google_pay_button_color,
        ),
        nomupay_google_pay_button_type: pick_enum(
            extras.get("nomupayGooglePayButtonType"),
            dflt.nomupay_google_pay_button_type,
        ),
        micropayment_field_chrome: pick_enum(
            extras.get("micropaymentFieldChrome"),
            dflt.micropayment_field_chrome,
        ),
        micropayment_field_font_size: pick_enum(
            extras.get("micropaymentFieldFontSize"),
            dflt.micropayment_field_font_size,
        ),
        micropayment_field_weight: pick_enum(
            extras.get("micropaymentFieldWeight"),
            dflt.micropayment_field_weight,
        ),
        micropayment_focus_ring: pick_enum(
            extras.get("micropaymentFocusRing"),
            dflt.micropayment_focus_ring,
        ),
        whop_card_preset: pick_enum(extras.get("whopCardPreset"), dflt.whop_card_preset),
        whop_accent_color: pick_enum(extras.get("whopAccentColor"), dflt.whop_accent_color),
        whop_gray_color: pick_enum(extras.get("whopGrayColor"), dflt.whop_gray_color),
        whop_billing_details: pick_enum(
            extras.get("whopBillingDetails"),
            dflt.whop_billing_details,
        ),
        whop_separated: parse_bool(extras.get("whopSeparated"), dflt.whop_separated),
        whop_email_label: pick_enum(extras.get("whopEmailLabel"), dflt.whop_email_label),
        whop_field_chrome: pick_enum(extras.get("whopFieldChrome"), dflt.whop_field_chrome),
        whop_field_font_size: pick_enum(extras.get("whopFieldFontSize"), dflt.whop_field_font_size),
        whop_field_weight: pick_enum(extras.get("whopFieldWeight"), dflt.whop_field_weight),
        whop_focus_ring: pick_enum(extras.get("whopFocusRing"), dflt.whop_focus_ring),
        whop_radius: pick_enum(extras.get("whopRadius"), dflt.whop_radius),
        whop_shadow: pick_enum(extras.get("whopShadow"), dflt.whop_shadow),
        whop_method_icons: parse_bool(extras.get("whopMethodIcons"), dflt.whop_method_icons),
        whop_selection: pick_enum(extras.get("whopSelection"), dflt.whop_selection),

        show_powered_by: source.branding_visibility != Some(false),

        custom_css: bag_str(extras, "customCss").to_string(),
    }
}

/// The encoded API request shape — the union of fields [`encode_branding`]
/// fills.
///
/// `None` serializes as JSON `null` (not omitted), matching the TypeScript
/// encoder, because a cleared field must actually clear server-side.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EncodedBranding {
    /// Brand colour.
    pub theme: String,
    /// Logo URL, or `null` when unset.
    pub logo: Option<String>,
    /// Merchant display name, or `null` when unset.
    pub seller_name: Option<String>,
    /// Stripe Elements payment-method layout.
    pub sdk_layout: PaymentLayout,
    /// Pay-button label, or `null` when unset.
    pub payment_button_text: Option<String>,
    /// Pay-button background colour.
    pub payment_button_colour: String,
    /// Pay-button foreground colour.
    pub payment_button_text_colour: String,
    /// Page background colour.
    pub background_colour: String,
    /// Header copy, or `null` when unset.
    pub payment_form_header_text: Option<String>,
    /// Legacy label mode.
    pub payment_form_label_type: LegacyLabelType,
    /// Card terms message, or `null` when unset.
    pub custom_message_for_card_terms: Option<String>,
    /// The `sdk_ui_rules` bag, with branding under the `"branding"` group.
    pub sdk_ui_rules: BTreeMap<String, BTreeMap<String, String>>,
    /// Whether the "Powered by DeloPay" footer is shown.
    pub branding_visibility: bool,
}

fn trim_opt(v: &str) -> Option<String> {
    let t = v.trim();
    if t.is_empty() {
        None
    } else {
        Some(t.to_string())
    }
}

/// Build the `sdk_ui_rules.branding` bag for a branding value.
fn branding_extras(branding: &CheckoutBranding) -> BTreeMap<String, String> {
    let mut extras = BTreeMap::new();
    let mut put = |k: &str, v: String| {
        extras.insert(k.to_string(), v);
    };
    put("surface", branding.surface.clone());
    put("text", branding.text.clone());
    put("heading", branding.heading.clone());
    put("muted", branding.muted.clone());
    put("border", branding.border.clone());
    put("accentText", branding.accent_text.clone());
    put("fontFamily", branding.font_family.as_str().to_string());
    put(
        "headingWeight",
        branding.heading_weight.as_str().to_string(),
    );
    put(
        "radiusSurface",
        branding.radius_surface.as_str().to_string(),
    );
    put("radiusInput", branding.radius_input.as_str().to_string());
    put("radiusButton", branding.radius_button.as_str().to_string());
    put("radiusBadge", branding.radius_badge.as_str().to_string());
    put("surfaceStyle", branding.surface_style.as_str().to_string());
    put(
        "surfacePadding",
        branding.surface_padding.as_str().to_string(),
    );
    put("verticalGap", branding.vertical_gap.as_str().to_string());
    put("inputSize", branding.input_size.as_str().to_string());
    put("buttonSize", branding.button_size.as_str().to_string());
    put("layout", branding.layout.as_str().to_string());
    put(
        "summaryPosition",
        branding.summary_position.as_str().to_string(),
    );
    put("showOrderSummary", branding.show_order_summary.to_string());
    put("summaryGradient", branding.summary_gradient.to_string());
    put("showTotal", branding.show_total.to_string());
    put("totalLabel", branding.total_label.clone());
    put("showCurrencyCode", branding.show_currency_code.to_string());
    put("showOrderItems", branding.show_order_items.to_string());
    put(
        "cancelLinkEnabled",
        branding.cancel_link_enabled.to_string(),
    );
    put(
        "cancelLinkPosition",
        branding.cancel_link_position.as_str().to_string(),
    );
    put(
        "cancelLinkStyle",
        branding.cancel_link_style.as_str().to_string(),
    );
    put("showLogo", branding.show_logo.to_string());
    put("logoShape", branding.logo_shape.as_str().to_string());
    put("logoSize", branding.logo_size.as_str().to_string());
    put("labelStyle", branding.label_style.as_str().to_string());

    put("showSurcharge", branding.show_surcharge.to_string());
    put(
        "surchargePosition",
        branding.surcharge_position.as_str().to_string(),
    );
    put(
        "nativeElementPosition",
        branding.native_element_position.as_str().to_string(),
    );
    put(
        "nativeElementStacked",
        branding.native_element_stacked.to_string(),
    );
    put(
        "surchargeStyle",
        branding.surcharge_style.as_str().to_string(),
    );
    put(
        "surchargeSize",
        branding.surcharge_size.as_str().to_string(),
    );
    put(
        "surchargeShape",
        branding.surcharge_shape.as_str().to_string(),
    );
    put(
        "surchargeBorderWidth",
        branding.surcharge_border_width.as_str().to_string(),
    );
    put(
        "surchargeBorderStyle",
        branding.surcharge_border_style.as_str().to_string(),
    );
    put(
        "surchargeWeight",
        branding.surcharge_weight.as_str().to_string(),
    );
    put(
        "surchargeSign",
        branding.surcharge_sign.as_str().to_string(),
    );
    put(
        "surchargeUppercase",
        branding.surcharge_uppercase.to_string(),
    );
    put(
        "surchargeLabel",
        branding.surcharge_label.as_str().to_string(),
    );
    put(
        "surchargeFigure",
        branding.surcharge_figure.as_str().to_string(),
    );
    put(
        "discountFigure",
        branding.discount_figure.as_str().to_string(),
    );
    put("surchargeColor", branding.surcharge_color.clone());
    put("discountColor", branding.discount_color.clone());

    put(
        "methodSectionOrder",
        encode_method_section_order(&branding.method_section_order),
    );
    // Written only when something is captioned — and only when something
    // survives normalization, so a bag of blank captions stays absent rather
    // than becoming an empty object.
    let section_labels = encode_method_section_labels(&branding.method_section_labels);
    if section_labels != "{}" {
        put("methodSectionLabels", section_labels);
    }

    // An unchosen preset or caption style is stored as the empty string, which
    // is what `decode_branding` reads back as `None` — the merchant has not
    // chosen, so the connector account's own setting still decides.
    put(
        "airwallexCardPreset",
        branding
            .airwallex_card_preset
            .map(|p| p.as_str().to_string())
            .unwrap_or_default(),
    );
    put(
        "airwallexHideCard",
        branding.airwallex_hide_card.to_string(),
    );
    put(
        "airwallexHideCardTitle",
        branding.airwallex_hide_card_title.to_string(),
    );
    put(
        "airwallexFieldChrome",
        branding.airwallex_field_chrome.as_str().to_string(),
    );
    put(
        "airwallexLabelStyle",
        branding
            .airwallex_label_style
            .map(|v| v.as_str().to_string())
            .unwrap_or_default(),
    );
    put(
        "airwallexFieldFontSize",
        branding.airwallex_field_font_size.as_str().to_string(),
    );
    put(
        "airwallexFieldWeight",
        branding.airwallex_field_weight.as_str().to_string(),
    );
    put(
        "airwallexFocusRing",
        branding.airwallex_focus_ring.as_str().to_string(),
    );
    put(
        "airwallexAutofill",
        branding.airwallex_autofill.as_str().to_string(),
    );
    put(
        "airwallexValidTint",
        branding.airwallex_valid_tint.to_string(),
    );
    put(
        "airwallexNetworkMarks",
        branding.airwallex_network_marks.to_string(),
    );
    put("stripeTheme", branding.stripe_theme.as_str().to_string());
    put("stripeInputs", branding.stripe_inputs.as_str().to_string());
    put("stripeLabels", branding.stripe_labels.as_str().to_string());
    put(
        "stripeSpacing",
        branding.stripe_spacing.as_str().to_string(),
    );
    put(
        "stripeFieldFontSize",
        branding.stripe_field_font_size.as_str().to_string(),
    );
    put(
        "stripeFieldWeight",
        branding.stripe_field_weight.as_str().to_string(),
    );
    put(
        "stripeFocusRing",
        branding.stripe_focus_ring.as_str().to_string(),
    );
    put(
        "stripeDisableAnimations",
        branding.stripe_disable_animations.to_string(),
    );
    put(
        "paypalCardLayout",
        branding.paypal_card_layout.as_str().to_string(),
    );
    put(
        "paypalLabelStyle",
        branding.paypal_label_style.as_str().to_string(),
    );
    put(
        "paypalFieldChrome",
        branding.paypal_field_chrome.as_str().to_string(),
    );
    put(
        "mollieFieldChrome",
        branding.mollie_field_chrome.as_str().to_string(),
    );
    put(
        "paypalFieldFontSize",
        branding.paypal_field_font_size.as_str().to_string(),
    );
    put(
        "mollieFieldFontSize",
        branding.mollie_field_font_size.as_str().to_string(),
    );
    put(
        "paypalFieldWeight",
        branding.paypal_field_weight.as_str().to_string(),
    );
    put(
        "mollieFieldWeight",
        branding.mollie_field_weight.as_str().to_string(),
    );
    put(
        "paypalFocusRing",
        branding.paypal_focus_ring.as_str().to_string(),
    );
    put(
        "mollieFocusRing",
        branding.mollie_focus_ring.as_str().to_string(),
    );
    put("paypalValidTint", branding.paypal_valid_tint.to_string());
    put(
        "epayoutsCardLayout",
        branding.epayouts_card_layout.as_str().to_string(),
    );
    put(
        "epayoutsLabelStyle",
        branding.epayouts_label_style.as_str().to_string(),
    );
    put(
        "epayoutsFieldChrome",
        branding.epayouts_field_chrome.as_str().to_string(),
    );
    put(
        "epayoutsFieldFontSize",
        branding.epayouts_field_font_size.as_str().to_string(),
    );
    put(
        "epayoutsFieldWeight",
        branding.epayouts_field_weight.as_str().to_string(),
    );
    put(
        "epayoutsFocusRing",
        branding.epayouts_focus_ring.as_str().to_string(),
    );
    put(
        "epayoutsValidTint",
        branding.epayouts_valid_tint.to_string(),
    );
    put(
        "nomupayFormStyle",
        branding.nomupay_form_style.as_str().to_string(),
    );
    put(
        "nomupayShowLabels",
        branding.nomupay_show_labels.to_string(),
    );
    put(
        "nomupayShowPlaceholders",
        branding.nomupay_show_placeholders.to_string(),
    );
    put(
        "nomupayShowCvvHint",
        branding.nomupay_show_cvv_hint.to_string(),
    );
    put(
        "nomupayFieldChrome",
        branding.nomupay_field_chrome.as_str().to_string(),
    );
    put(
        "nomupayFieldFontSize",
        branding.nomupay_field_font_size.as_str().to_string(),
    );
    put(
        "nomupayFocusRing",
        branding.nomupay_focus_ring.as_str().to_string(),
    );
    put(
        "nomupayApplePayButtonStyle",
        branding.nomupay_apple_pay_button_style.as_str().to_string(),
    );
    put(
        "nomupayApplePayButtonType",
        branding.nomupay_apple_pay_button_type.as_str().to_string(),
    );
    put(
        "nomupayGooglePayButtonColor",
        branding
            .nomupay_google_pay_button_color
            .as_str()
            .to_string(),
    );
    put(
        "nomupayGooglePayButtonType",
        branding.nomupay_google_pay_button_type.as_str().to_string(),
    );
    put(
        "micropaymentFieldChrome",
        branding.micropayment_field_chrome.as_str().to_string(),
    );
    put(
        "micropaymentFieldFontSize",
        branding.micropayment_field_font_size.as_str().to_string(),
    );
    put(
        "micropaymentFieldWeight",
        branding.micropayment_field_weight.as_str().to_string(),
    );
    put(
        "micropaymentFocusRing",
        branding.micropayment_focus_ring.as_str().to_string(),
    );
    put(
        "whopCardPreset",
        branding.whop_card_preset.as_str().to_string(),
    );
    put(
        "whopAccentColor",
        branding.whop_accent_color.as_str().to_string(),
    );
    put(
        "whopGrayColor",
        branding.whop_gray_color.as_str().to_string(),
    );
    put(
        "whopBillingDetails",
        branding.whop_billing_details.as_str().to_string(),
    );
    put("whopSeparated", branding.whop_separated.to_string());
    put(
        "whopEmailLabel",
        branding.whop_email_label.as_str().to_string(),
    );
    put(
        "whopFieldChrome",
        branding.whop_field_chrome.as_str().to_string(),
    );
    put(
        "whopFieldFontSize",
        branding.whop_field_font_size.as_str().to_string(),
    );
    put(
        "whopFieldWeight",
        branding.whop_field_weight.as_str().to_string(),
    );
    put(
        "whopFocusRing",
        branding.whop_focus_ring.as_str().to_string(),
    );
    put("whopRadius", branding.whop_radius.as_str().to_string());
    put("whopShadow", branding.whop_shadow.as_str().to_string());
    put("whopMethodIcons", branding.whop_method_icons.to_string());
    put(
        "whopSelection",
        branding.whop_selection.as_str().to_string(),
    );

    // Always written, `[]` included: its presence is what stops a later
    // decode from migrating the shop again (`resolve_notices_and_badges`).
    put("notices", encode_notices(&branding.notices));
    // Badges only when there are some. The group is rebuilt on every save, so
    // a writer that predates notices drops them; such a writer decodes a
    // missing `trustBadges` to its stock pair and saves that, which decodes
    // here to the default notices again. Had `[]` been written, it would save
    // `[]` back, and `[]` without notices reads as "the merchant removed the
    // trust row", so the checkout would show nothing.
    if !branding.trust_badges.is_empty() {
        put("trustBadges", encode_badges(&branding.trust_badges));
    }
    // Written only when there is something to write, so a shop that configures
    // no custom fields keeps a bag byte-identical to its pre-feature one.
    if !branding.custom_fields.is_empty() {
        put(
            "customFields",
            encode_custom_fields(&branding.custom_fields),
        );
    }

    if let Some(v) = trim_opt(&branding.tagline) {
        put("tagline", v);
    }
    if let Some(v) = trim_opt(&branding.footer_text) {
        put("footerText", v);
    }
    if let Some(v) = trim_opt(&branding.support_email) {
        put("supportEmail", v);
    }
    // Persisted raw — sanitization runs at render time so the merchant's input
    // is kept as typed (comments, whitespace) and every reader strips the same
    // dangerous tokens.
    if let Some(v) = trim_opt(&branding.custom_css) {
        put("customCss", v);
    }
    extras
}

/// Encode a [`CheckoutBranding`] into the API request shape.
///
/// Use [`encode_branding_with_base`] when an existing config must be preserved.
pub fn encode_branding(branding: &CheckoutBranding) -> EncodedBranding {
    let mut rules = BTreeMap::new();
    rules.insert(BRANDING_GROUP_KEY.to_string(), branding_extras(branding));
    encoded_with_rules(branding, rules)
}

fn encoded_with_rules(
    branding: &CheckoutBranding,
    sdk_ui_rules: BTreeMap<String, BTreeMap<String, String>>,
) -> EncodedBranding {
    EncodedBranding {
        theme: branding.primary.clone(),
        logo: trim_opt(&branding.logo_url),
        seller_name: trim_opt(&branding.display_name),
        sdk_layout: branding.payment_layout,
        payment_button_text: trim_opt(&branding.pay_button_label),
        payment_button_colour: branding.button_background.clone(),
        payment_button_text_colour: branding.button_text.clone(),
        background_colour: branding.background.clone(),
        payment_form_header_text: trim_opt(&branding.header_text),
        // Map `Hidden` back to the legacy `never` token the API's label-type
        // enum understands. `floating` no longer exists.
        payment_form_label_type: match branding.label_style {
            LabelStyle::Hidden => LegacyLabelType::Never,
            LabelStyle::Above => LegacyLabelType::Above,
        },
        custom_message_for_card_terms: trim_opt(&branding.card_terms_message),
        sdk_ui_rules,
        branding_visibility: branding.show_powered_by,
    }
}

/// Encode a [`CheckoutBranding`] on top of an existing config object.
///
/// `base` is merged first, so fields the encoder doesn't surface
/// (`show_card_terms`, `background_image`, `business_specific_configs`, …)
/// survive, and other `sdk_ui_rules` groups are preserved alongside the
/// `"branding"` group. Returns a JSON object; a non-object `base` is ignored.
///
/// JSON object key order differs from the TypeScript output (serde emits keys
/// sorted), which is semantically irrelevant. The one place order *is*
/// load-bearing — the JSON-stringified `trustBadges` value — is byte-identical;
/// see [`encode_badges`].
pub fn encode_branding_with_base(branding: &CheckoutBranding, base: Option<&Value>) -> Value {
    let base_obj = base.and_then(Value::as_object);

    let mut rules: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
    if let Some(existing) = base_obj
        .and_then(|o| o.get("sdk_ui_rules"))
        .and_then(Value::as_object)
    {
        for (group, value) in existing {
            let Some(entries) = value.as_object() else {
                continue;
            };
            let mut group_map = BTreeMap::new();
            for (k, v) in entries {
                if let Some(sv) = v.as_str() {
                    group_map.insert(k.clone(), sv.to_string());
                }
            }
            rules.insert(group.clone(), group_map);
        }
    }
    rules.insert(BRANDING_GROUP_KEY.to_string(), branding_extras(branding));

    let flat = encoded_with_rules(branding, rules);
    let mut out: Map<String, Value> = base_obj.cloned().unwrap_or_default();
    if let Value::Object(flat_map) = serde_json::to_value(&flat).unwrap_or(Value::Null) {
        for (k, v) in flat_map {
            out.insert(k, v);
        }
    }
    Value::Object(out)
}

// --- Import / Export envelope ------------------------------------------

/// The `format` discriminator of a branding export envelope.
pub const BRANDING_EXPORT_FORMAT: &str = "delopay-checkout-branding";

/// The current envelope version. Bumping it is informational; the importer
/// accepts any version (or no envelope at all).
pub const BRANDING_EXPORT_VERSION: u32 = 1;

/// Versioned envelope used by the merchant control-center's "Import / Export"
/// buttons.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BrandingExport {
    /// Always [`BRANDING_EXPORT_FORMAT`].
    pub format: String,
    /// Envelope version, [`BRANDING_EXPORT_VERSION`] when freshly built.
    pub version: u32,
    /// ISO 8601 UTC timestamp with millisecond precision, matching the
    /// JavaScript `Date.prototype.toISOString()` output.
    pub exported_at: String,
    /// The exported branding.
    pub branding: CheckoutBranding,
}

/// Build an export envelope, stamped with the current system time.
///
/// Use [`build_branding_export_at`] when the timestamp must be deterministic.
pub fn build_branding_export(branding: &CheckoutBranding) -> BrandingExport {
    let now = std::time::SystemTime::now();
    let millis = match now.duration_since(std::time::UNIX_EPOCH) {
        Ok(d) => d.as_millis() as i64,
        Err(e) => -(e.duration().as_millis() as i64),
    };
    build_branding_export_at(branding, millis)
}

/// Build an export envelope stamped with an explicit Unix timestamp in
/// milliseconds.
pub fn build_branding_export_at(branding: &CheckoutBranding, unix_millis: i64) -> BrandingExport {
    BrandingExport {
        format: BRANDING_EXPORT_FORMAT.to_string(),
        version: BRANDING_EXPORT_VERSION,
        exported_at: iso8601_millis(unix_millis),
        branding: clone_branding(branding),
    }
}

/// Format a Unix millisecond timestamp as `YYYY-MM-DDTHH:MM:SS.sssZ`.
///
/// Implemented locally (civil-from-days) so the crate needs no date
/// dependency in the `default-features = false` build.
fn iso8601_millis(unix_millis: i64) -> String {
    const MS_PER_DAY: i64 = 86_400_000;
    let days = unix_millis.div_euclid(MS_PER_DAY);
    let ms_of_day = unix_millis.rem_euclid(MS_PER_DAY);

    let (hour, minute, second, milli) = (
        ms_of_day / 3_600_000,
        (ms_of_day / 60_000) % 60,
        (ms_of_day / 1_000) % 60,
        ms_of_day % 1_000,
    );

    // Howard Hinnant's civil_from_days.
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = y + i64::from(m <= 2);

    format!("{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{milli:03}Z")
}

fn value_str(v: Option<&Value>, fallback: &str) -> String {
    match v.and_then(Value::as_str) {
        Some(raw) => raw.to_string(),
        None => fallback.to_string(),
    }
}

fn value_hex(v: Option<&Value>, fallback: &str) -> String {
    match v.and_then(Value::as_str) {
        Some(raw) if is_hex_color(raw) => raw.to_string(),
        _ => fallback.to_string(),
    }
}

/// Loose trust-badge parser used by the importer.
///
/// Unlike [`decode_badges`] (which reads the JSON-stringified API bag), this
/// accepts an array of objects directly, and colours that are not valid hex
/// fall back to neutral defaults. Returns `None` when the input is not an
/// array; an explicit empty array is honoured.
fn parse_trust_badges_loose(raw: Option<&Value>) -> Option<Vec<TrustBadge>> {
    let items = raw?.as_array()?;
    Some(
        items
            .iter()
            .enumerate()
            .filter_map(|(i, item)| {
                let obj = item.as_object()?;
                let hex = |k: &str| {
                    obj.get(k)
                        .and_then(Value::as_str)
                        .filter(|v| is_hex_color(v))
                };
                Some(TrustBadge {
                    id: match obj.get("id").and_then(Value::as_str) {
                        Some(id) if !id.is_empty() => id.to_string(),
                        _ => format!("badge-{i}"),
                    },
                    label: obj
                        .get("label")
                        .and_then(Value::as_str)
                        .unwrap_or("")
                        .to_string(),
                    text_color: hex("textColor").unwrap_or("#0f172a").to_string(),
                    background_color: hex("backgroundColor").unwrap_or("#f1f5f9").to_string(),
                    border_color: hex("borderColor").map(str::to_string),
                })
            })
            .filter(|b| !b.label.is_empty())
            .collect(),
    )
}

/// Resolve arbitrary JSON into a fully-typed [`CheckoutBranding`].
///
/// Total by construction — every field is independently validated and silently
/// falls back to the light-mode default when missing or malformed:
///
/// - unknown fields are ignored,
/// - missing fields inherit defaults,
/// - hex colours that fail [`is_hex_color`] stay at the default,
/// - enum values outside the allowed set fall back,
/// - a payload with no recognizable shape produces [`DEFAULT_BRANDING`].
///
/// Accepts either a bare branding object or an envelope produced by
/// [`build_branding_export`]; the envelope's `version` is not gated on, since
/// this function *is* the migration layer.
pub fn parse_imported_branding(raw: &Value) -> CheckoutBranding {
    // Unwrap the envelope if present.
    let root: Option<&Map<String, Value>> = match raw.as_object() {
        Some(obj) => match obj.get("branding").and_then(Value::as_object) {
            Some(inner) => Some(inner),
            None => Some(obj),
        },
        None => None,
    };
    let Some(root) = root else {
        return clone_branding(&DEFAULT_BRANDING);
    };

    let dflt = &*DEFAULT_BRANDING;
    let g = |k: &str| root.get(k);

    // The same rule as `decode_branding`: an export made before notices
    // existed carries badges only, and is migrated exactly as a saved shop
    // would be.
    let trust_row = resolve_notices_and_badges(
        parse_trust_badges_loose(g("trustBadges")),
        parse_notices_loose(g("notices")),
    );

    // The export carries the structured array, not the stringified bag entry.
    let custom_fields = g("customFields")
        .and_then(parse_custom_fields_loose)
        .unwrap_or_default();

    // Unlike `decode_branding`, an unrecognized value (including the legacy
    // `"floating"`) falls back to the default rather than normalizing.
    let label_style = pick_enum(g("labelStyle"), dflt.label_style);

    CheckoutBranding {
        display_name: value_str(g("displayName"), &dflt.display_name),
        logo_url: value_str(g("logoUrl"), &dflt.logo_url),
        tagline: value_str(g("tagline"), &dflt.tagline),
        show_logo: parse_bool(g("showLogo"), dflt.show_logo),
        logo_shape: pick_enum(g("logoShape"), dflt.logo_shape),
        logo_size: pick_enum(g("logoSize"), dflt.logo_size),

        primary: value_hex(g("primary"), &dflt.primary),
        background: value_hex(g("background"), &dflt.background),
        surface: value_hex(g("surface"), &dflt.surface),
        text: value_hex(g("text"), &dflt.text),
        heading: value_hex(g("heading"), &dflt.heading),
        muted: value_hex(g("muted"), &dflt.muted),
        border: value_hex(g("border"), &dflt.border),
        accent_text: value_hex(g("accentText"), &dflt.accent_text),
        button_background: value_hex(g("buttonBackground"), &dflt.button_background),
        button_text: value_hex(g("buttonText"), &dflt.button_text),

        font_family: pick_enum(g("fontFamily"), dflt.font_family),
        heading_weight: pick_enum(g("headingWeight"), dflt.heading_weight),

        radius_surface: pick_enum(g("radiusSurface"), dflt.radius_surface),
        radius_input: pick_enum(g("radiusInput"), dflt.radius_input),
        radius_button: pick_enum(g("radiusButton"), dflt.radius_button),
        radius_badge: pick_enum(g("radiusBadge"), dflt.radius_badge),
        surface_style: pick_enum(g("surfaceStyle"), dflt.surface_style),
        surface_padding: pick_enum(g("surfacePadding"), dflt.surface_padding),
        vertical_gap: pick_enum(g("verticalGap"), dflt.vertical_gap),
        input_size: pick_enum(g("inputSize"), dflt.input_size),
        button_size: pick_enum(g("buttonSize"), dflt.button_size),

        layout: pick_enum(g("layout"), dflt.layout),
        summary_position: pick_enum(g("summaryPosition"), dflt.summary_position),
        show_order_summary: parse_bool(g("showOrderSummary"), dflt.show_order_summary),
        summary_gradient: parse_bool(g("summaryGradient"), dflt.summary_gradient),
        show_total: parse_bool(g("showTotal"), dflt.show_total),
        total_label: value_str(g("totalLabel"), &dflt.total_label),
        show_currency_code: parse_bool(g("showCurrencyCode"), dflt.show_currency_code),
        show_order_items: parse_bool(g("showOrderItems"), dflt.show_order_items),
        cancel_link_enabled: parse_bool(g("cancelLinkEnabled"), dflt.cancel_link_enabled),
        cancel_link_position: pick_enum(g("cancelLinkPosition"), dflt.cancel_link_position),
        cancel_link_style: pick_enum(g("cancelLinkStyle"), dflt.cancel_link_style),

        trust_badges: trust_row.trust_badges,
        notices: trust_row.notices,

        custom_fields,

        header_text: value_str(g("headerText"), &dflt.header_text),
        pay_button_label: value_str(g("payButtonLabel"), &dflt.pay_button_label),
        card_terms_message: value_str(g("cardTermsMessage"), &dflt.card_terms_message),
        footer_text: value_str(g("footerText"), &dflt.footer_text),
        support_email: value_str(g("supportEmail"), &dflt.support_email),

        payment_layout: pick_enum(g("paymentLayout"), dflt.payment_layout),
        label_style,

        show_surcharge: parse_bool(g("showSurcharge"), dflt.show_surcharge),
        surcharge_position: pick_enum(g("surchargePosition"), dflt.surcharge_position),
        native_element_position: pick_enum(
            g("nativeElementPosition"),
            dflt.native_element_position,
        ),
        native_element_stacked: parse_bool(g("nativeElementStacked"), dflt.native_element_stacked),
        surcharge_style: pick_enum(g("surchargeStyle"), dflt.surcharge_style),
        surcharge_size: pick_enum(g("surchargeSize"), dflt.surcharge_size),
        surcharge_shape: pick_enum(g("surchargeShape"), dflt.surcharge_shape),
        surcharge_border_width: pick_enum(g("surchargeBorderWidth"), dflt.surcharge_border_width),
        surcharge_border_style: pick_enum(g("surchargeBorderStyle"), dflt.surcharge_border_style),
        surcharge_weight: pick_enum(g("surchargeWeight"), dflt.surcharge_weight),
        surcharge_sign: pick_enum(g("surchargeSign"), dflt.surcharge_sign),
        surcharge_uppercase: parse_bool(g("surchargeUppercase"), dflt.surcharge_uppercase),
        surcharge_label: pick_enum(g("surchargeLabel"), dflt.surcharge_label),
        surcharge_figure: pick_enum(g("surchargeFigure"), dflt.surcharge_figure),
        discount_figure: pick_enum(g("discountFigure"), dflt.discount_figure),
        surcharge_color: value_hex(g("surchargeColor"), &dflt.surcharge_color),
        discount_color: value_hex(g("discountColor"), &dflt.discount_color),

        // The export carries the structured maps, not the stringified bag
        // entries — so re-encode them and read them back through the same
        // tolerant decoder the bag uses.
        method_section_order: decode_method_section_order(
            g("methodSectionOrder").map(|v| v.to_string()).as_deref(),
        ),
        method_section_labels: decode_method_section_labels(
            g("methodSectionLabels").map(|v| v.to_string()).as_deref(),
        ),

        airwallex_card_preset: pick_optional_enum(g("airwallexCardPreset")),
        airwallex_hide_card: parse_bool(g("airwallexHideCard"), dflt.airwallex_hide_card),
        airwallex_hide_card_title: parse_bool(
            g("airwallexHideCardTitle"),
            dflt.airwallex_hide_card_title,
        ),
        airwallex_field_chrome: pick_enum(g("airwallexFieldChrome"), dflt.airwallex_field_chrome),
        airwallex_label_style: pick_optional_enum(g("airwallexLabelStyle")),
        airwallex_field_font_size: pick_enum(
            g("airwallexFieldFontSize"),
            dflt.airwallex_field_font_size,
        ),
        airwallex_field_weight: pick_enum(g("airwallexFieldWeight"), dflt.airwallex_field_weight),
        airwallex_focus_ring: pick_enum(g("airwallexFocusRing"), dflt.airwallex_focus_ring),
        airwallex_autofill: pick_enum(g("airwallexAutofill"), dflt.airwallex_autofill),
        airwallex_valid_tint: parse_bool(g("airwallexValidTint"), dflt.airwallex_valid_tint),
        airwallex_network_marks: parse_bool(
            g("airwallexNetworkMarks"),
            dflt.airwallex_network_marks,
        ),

        stripe_theme: pick_enum(g("stripeTheme"), dflt.stripe_theme),
        stripe_inputs: pick_enum(g("stripeInputs"), dflt.stripe_inputs),
        stripe_labels: pick_enum(g("stripeLabels"), dflt.stripe_labels),
        stripe_spacing: pick_enum(g("stripeSpacing"), dflt.stripe_spacing),
        stripe_field_font_size: pick_enum(g("stripeFieldFontSize"), dflt.stripe_field_font_size),
        stripe_field_weight: pick_enum(g("stripeFieldWeight"), dflt.stripe_field_weight),
        stripe_focus_ring: pick_enum(g("stripeFocusRing"), dflt.stripe_focus_ring),
        stripe_disable_animations: parse_bool(
            g("stripeDisableAnimations"),
            dflt.stripe_disable_animations,
        ),
        paypal_card_layout: pick_enum(g("paypalCardLayout"), dflt.paypal_card_layout),
        paypal_label_style: pick_enum(g("paypalLabelStyle"), dflt.paypal_label_style),
        paypal_field_chrome: pick_enum(g("paypalFieldChrome"), dflt.paypal_field_chrome),
        mollie_field_chrome: pick_enum(g("mollieFieldChrome"), dflt.mollie_field_chrome),
        paypal_field_font_size: pick_enum(g("paypalFieldFontSize"), dflt.paypal_field_font_size),
        mollie_field_font_size: pick_enum(g("mollieFieldFontSize"), dflt.mollie_field_font_size),
        paypal_field_weight: pick_enum(g("paypalFieldWeight"), dflt.paypal_field_weight),
        mollie_field_weight: pick_enum(g("mollieFieldWeight"), dflt.mollie_field_weight),
        paypal_focus_ring: pick_enum(g("paypalFocusRing"), dflt.paypal_focus_ring),
        mollie_focus_ring: pick_enum(g("mollieFocusRing"), dflt.mollie_focus_ring),
        paypal_valid_tint: parse_bool(g("paypalValidTint"), dflt.paypal_valid_tint),
        epayouts_card_layout: pick_enum(
            g("epayoutsCardLayout"),
            pick_enum(g("paypalCardLayout"), dflt.epayouts_card_layout),
        ),
        epayouts_label_style: pick_enum(
            g("epayoutsLabelStyle"),
            pick_enum(g("paypalLabelStyle"), dflt.epayouts_label_style),
        ),
        epayouts_field_chrome: pick_enum(
            g("epayoutsFieldChrome"),
            pick_enum(g("paypalFieldChrome"), dflt.epayouts_field_chrome),
        ),
        epayouts_field_font_size: pick_enum(
            g("epayoutsFieldFontSize"),
            pick_enum(g("paypalFieldFontSize"), dflt.epayouts_field_font_size),
        ),
        epayouts_field_weight: pick_enum(
            g("epayoutsFieldWeight"),
            pick_enum(g("paypalFieldWeight"), dflt.epayouts_field_weight),
        ),
        epayouts_focus_ring: pick_enum(
            g("epayoutsFocusRing"),
            pick_enum(g("paypalFocusRing"), dflt.epayouts_focus_ring),
        ),
        epayouts_valid_tint: parse_bool(
            g("epayoutsValidTint"),
            parse_bool(g("paypalValidTint"), dflt.epayouts_valid_tint),
        ),
        nomupay_form_style: pick_enum(g("nomupayFormStyle"), dflt.nomupay_form_style),
        nomupay_show_labels: parse_bool(g("nomupayShowLabels"), dflt.nomupay_show_labels),
        nomupay_show_placeholders: parse_bool(
            g("nomupayShowPlaceholders"),
            dflt.nomupay_show_placeholders,
        ),
        nomupay_show_cvv_hint: parse_bool(g("nomupayShowCvvHint"), dflt.nomupay_show_cvv_hint),
        nomupay_field_chrome: pick_enum(g("nomupayFieldChrome"), dflt.nomupay_field_chrome),
        nomupay_field_font_size: pick_enum(g("nomupayFieldFontSize"), dflt.nomupay_field_font_size),
        nomupay_focus_ring: pick_enum(g("nomupayFocusRing"), dflt.nomupay_focus_ring),
        nomupay_apple_pay_button_style: pick_enum(
            g("nomupayApplePayButtonStyle"),
            dflt.nomupay_apple_pay_button_style,
        ),
        nomupay_apple_pay_button_type: pick_enum(
            g("nomupayApplePayButtonType"),
            dflt.nomupay_apple_pay_button_type,
        ),
        nomupay_google_pay_button_color: pick_enum(
            g("nomupayGooglePayButtonColor"),
            dflt.nomupay_google_pay_button_color,
        ),
        nomupay_google_pay_button_type: pick_enum(
            g("nomupayGooglePayButtonType"),
            dflt.nomupay_google_pay_button_type,
        ),
        micropayment_field_chrome: pick_enum(
            g("micropaymentFieldChrome"),
            dflt.micropayment_field_chrome,
        ),
        micropayment_field_font_size: pick_enum(
            g("micropaymentFieldFontSize"),
            dflt.micropayment_field_font_size,
        ),
        micropayment_field_weight: pick_enum(
            g("micropaymentFieldWeight"),
            dflt.micropayment_field_weight,
        ),
        micropayment_focus_ring: pick_enum(
            g("micropaymentFocusRing"),
            dflt.micropayment_focus_ring,
        ),
        whop_card_preset: pick_enum(g("whopCardPreset"), dflt.whop_card_preset),
        whop_accent_color: pick_enum(g("whopAccentColor"), dflt.whop_accent_color),
        whop_gray_color: pick_enum(g("whopGrayColor"), dflt.whop_gray_color),
        whop_billing_details: pick_enum(g("whopBillingDetails"), dflt.whop_billing_details),
        whop_separated: parse_bool(g("whopSeparated"), dflt.whop_separated),
        whop_email_label: pick_enum(g("whopEmailLabel"), dflt.whop_email_label),
        whop_field_chrome: pick_enum(g("whopFieldChrome"), dflt.whop_field_chrome),
        whop_field_font_size: pick_enum(g("whopFieldFontSize"), dflt.whop_field_font_size),
        whop_field_weight: pick_enum(g("whopFieldWeight"), dflt.whop_field_weight),
        whop_focus_ring: pick_enum(g("whopFocusRing"), dflt.whop_focus_ring),
        whop_radius: pick_enum(g("whopRadius"), dflt.whop_radius),
        whop_shadow: pick_enum(g("whopShadow"), dflt.whop_shadow),
        whop_method_icons: parse_bool(g("whopMethodIcons"), dflt.whop_method_icons),
        whop_selection: pick_enum(g("whopSelection"), dflt.whop_selection),

        show_powered_by: parse_bool(g("showPoweredBy"), dflt.show_powered_by),

        custom_css: truncate_utf16(&value_str(g("customCss"), &dflt.custom_css)),
    }
}

/// Truncate to [`CUSTOM_CSS_MAX_LENGTH`] UTF-16 code units, never splitting a
/// character (JavaScript's `slice` would emit a lone surrogate; we stop one
/// character earlier instead).
fn truncate_utf16(s: &str) -> String {
    if utf16_len(s) <= CUSTOM_CSS_MAX_LENGTH {
        return s.to_string();
    }
    let mut out = String::new();
    let mut units = 0;
    for c in s.chars() {
        let w = c.len_utf16();
        if units + w > CUSTOM_CSS_MAX_LENGTH {
            break;
        }
        units += w;
        out.push(c);
    }
    out
}

// --- CSS custom properties ---------------------------------------------

/// The `--dp-*` CSS custom properties for a branding value, in the order the
/// TypeScript SDK writes them.
///
/// The TypeScript `applyBrandingVariables(el, b)` mutates a DOM element via
/// `el.style.setProperty`. There is no DOM here, so this returns the same
/// name/value pairs instead and leaves application to the caller — either by
/// serving [`branding_variables_css`] or by handing the pairs to a template.
/// The set, the names, and the values are identical to the browser version.
pub fn branding_variables(b: &CheckoutBranding) -> Vec<(&'static str, String)> {
    vec![
        ("--dp-primary", b.primary.clone()),
        ("--dp-bg", b.background.clone()),
        ("--dp-surface", b.surface.clone()),
        ("--dp-text", b.text.clone()),
        ("--dp-heading", b.heading.clone()),
        ("--dp-muted", b.muted.clone()),
        ("--dp-border", b.border.clone()),
        ("--dp-accent-text", b.accent_text.clone()),
        ("--dp-btn-bg", b.button_background.clone()),
        ("--dp-btn-fg", b.button_text.clone()),
        (
            "--dp-radius-surface",
            radius_value(b.radius_surface.into()).to_string(),
        ),
        (
            "--dp-radius-input",
            radius_value(b.radius_input.into()).to_string(),
        ),
        (
            "--dp-radius-button",
            radius_value(b.radius_button).to_string(),
        ),
        (
            "--dp-radius-badge",
            radius_value(b.radius_badge).to_string(),
        ),
        ("--dp-font", font_stack(b.font_family).to_string()),
        (
            "--dp-heading-weight",
            font_weight_value(b.heading_weight).to_string(),
        ),
        (
            "--dp-pad-surface",
            surface_pad_value(b.surface_padding).to_string(),
        ),
        (
            "--dp-gap-vertical",
            vertical_gap_value(b.vertical_gap).to_string(),
        ),
        ("--dp-input-pad", input_pad_value(b.input_size).to_string()),
        (
            "--dp-button-pad",
            button_pad_value(b.button_size).to_string(),
        ),
        // Published whatever `show_surcharge` says: the flag decides whether a
        // figure renders, not what colour it would be, and a stylesheet reading
        // the variable must not get an empty string when the merchant has one
        // configured.
        ("--dp-surcharge", b.surcharge_color.clone()),
        ("--dp-discount", b.discount_color.clone()),
        // What `Solid` writes ON the fill. Computed here because CSS cannot ask
        // a colour how light it is, and one fixed ink would make either a pale
        // amber or a deep emerald unreadable.
        (
            "--dp-surcharge-ink",
            readable_ink_on(&b.surcharge_color).to_string(),
        ),
        (
            "--dp-discount-ink",
            readable_ink_on(&b.discount_color).to_string(),
        ),
        (
            "--dp-surcharge-size",
            surcharge_font_size(b.surcharge_size).to_string(),
        ),
        (
            "--dp-surcharge-pad",
            surcharge_pad(b.surcharge_size).to_string(),
        ),
        (
            "--dp-surcharge-radius",
            surcharge_radius(b.surcharge_shape).to_string(),
        ),
        (
            "--dp-surcharge-weight",
            surcharge_font_weight(b.surcharge_weight).to_string(),
        ),
        (
            "--dp-surcharge-border-width",
            // `Outline` draws nothing BUT its border, so `None` there would
            // erase the style rather than restyle it — it reads as `Thin`.
            surcharge_border_width_value(
                if b.surcharge_style == SurchargeStyle::Outline
                    && b.surcharge_border_width == SurchargeBorderWidth::None
                {
                    SurchargeBorderWidth::Thin
                } else {
                    b.surcharge_border_width
                },
            )
            .to_string(),
        ),
        (
            "--dp-surcharge-border-style",
            b.surcharge_border_style.as_str().to_string(),
        ),
        ("--dp-shadow", shadow_for(b.surface_style).to_string()),
        (
            "--dp-surface-border",
            if b.surface_style == SurfaceStyle::Outlined {
                format!("1px solid {}", b.border)
            } else {
                "1px solid transparent".to_string()
            },
        ),
    ]
}

/// Render [`branding_variables`] as a `:root{…}` rule, ready to inline into a
/// `<style>` element server-side.
pub fn branding_variables_css(b: &CheckoutBranding) -> String {
    let mut out = String::from(":root{");
    for (k, v) in branding_variables(b) {
        out.push_str(k);
        out.push(':');
        out.push_str(&v);
        out.push(';');
    }
    out.push('}');
    out
}

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

    // --- token maps ------------------------------------------------------

    #[test]
    fn token_maps_have_the_documented_values() {
        assert_eq!(
            font_stack(FontFamily::Inter),
            "'Inter Variable', 'Inter', system-ui, -apple-system, sans-serif"
        );
        assert_eq!(
            font_stack(FontFamily::Serif),
            "Georgia, 'Times New Roman', serif"
        );
        assert_eq!(
            font_stack(FontFamily::DmSans),
            "'DM Sans Variable', 'DM Sans', system-ui, sans-serif"
        );

        assert_eq!(radius_value(CornerRadius::Square), "0px");
        assert_eq!(radius_value(CornerRadius::Small), "6px");
        assert_eq!(radius_value(CornerRadius::Medium), "12px");
        assert_eq!(radius_value(CornerRadius::Large), "20px");
        assert_eq!(radius_value(CornerRadius::Pill), "999px");

        assert_eq!(font_weight_value(FontWeight::Regular), "400");
        assert_eq!(font_weight_value(FontWeight::Medium), "500");
        assert_eq!(font_weight_value(FontWeight::Semibold), "600");
        assert_eq!(font_weight_value(FontWeight::Bold), "700");

        assert_eq!(surface_pad_value(SpacingScale::Compact), "1rem");
        assert_eq!(surface_pad_value(SpacingScale::Comfortable), "1.5rem");
        assert_eq!(surface_pad_value(SpacingScale::Spacious), "2rem");

        assert_eq!(vertical_gap_value(SpacingScale::Compact), "0.75rem");
        assert_eq!(vertical_gap_value(SpacingScale::Comfortable), "1rem");
        assert_eq!(vertical_gap_value(SpacingScale::Spacious), "1.5rem");

        assert_eq!(input_pad_value(SizeScale::Sm), "0.5rem 0.75rem");
        assert_eq!(input_pad_value(SizeScale::Md), "0.625rem 0.75rem");
        assert_eq!(input_pad_value(SizeScale::Lg), "0.875rem 0.875rem");

        assert_eq!(button_pad_value(SizeScale::Sm), "0.625rem 1rem");
        assert_eq!(button_pad_value(SizeScale::Md), "0.875rem 1.25rem");
        assert_eq!(button_pad_value(SizeScale::Lg), "1.125rem 1.5rem");
    }

    #[test]
    fn logo_dimensions_scale() {
        assert_eq!(
            logo_dimensions(LogoSize::Sm),
            LogoDimensions { px: 36, radius: 8 }
        );
        assert_eq!(
            logo_dimensions(LogoSize::Md),
            LogoDimensions { px: 48, radius: 12 }
        );
        assert_eq!(
            logo_dimensions(LogoSize::Lg),
            LogoDimensions { px: 64, radius: 16 }
        );
    }

    #[test]
    fn shadow_only_on_elevated() {
        assert_eq!(
            shadow_for(SurfaceStyle::Elevated),
            "0 1px 2px rgba(15, 23, 42, 0.04), 0 8px 32px -12px rgba(15, 23, 42, 0.08)"
        );
        assert_eq!(shadow_for(SurfaceStyle::Flat), "none");
        assert_eq!(shadow_for(SurfaceStyle::Outlined), "none");
    }

    // --- colour helpers --------------------------------------------------

    #[test]
    fn is_hex_color_accepts_three_and_six_digits_only() {
        assert!(is_hex_color("#fff"));
        assert!(is_hex_color("#FFFFFF"));
        assert!(is_hex_color("  #1E4FEB  "), "surrounding space is trimmed");
        assert!(!is_hex_color("fff"), "leading # required");
        assert!(!is_hex_color("#ffff"));
        assert!(!is_hex_color("#fffffff"));
        assert!(!is_hex_color("#gggggg"));
        assert!(!is_hex_color("#"));
        assert!(!is_hex_color(""));
    }

    /// The ratio is symmetric, and matches the WCAG reference values.
    ///
    /// Mutation: drop the sRGB linearisation (use the raw channel) and the
    /// mid-grey pair below stops matching the published figure, which is the
    /// figure a designer checks against.
    #[test]
    fn contrast_ratio_matches_the_wcag_reference_values() {
        let black_on_white = contrast_ratio("#000000", "#ffffff").unwrap();
        assert!((black_on_white - 21.0).abs() < 1e-9);
        assert!((contrast_ratio("#ffffff", "#000000").unwrap() - 21.0).abs() < 1e-9);
        assert!((contrast_ratio("#ffffff", "#ffffff").unwrap() - 1.0).abs() < 1e-9);

        // The canonical "just passes AA text" grey.
        let grey = contrast_ratio("#767676", "#ffffff").unwrap();
        assert!(grey >= WCAG_AA_TEXT, "expected AA text pass, got {grey}");
        assert!(grey < 5.0, "expected a near-threshold value, got {grey}");

        // Short form is the same colour.
        assert!(
            (contrast_ratio("#fff", "#000").unwrap() - 21.0).abs() < 1e-9,
            "the 3-digit form expands to the same colour"
        );
    }

    /// An unreadable colour answers `None`, not a number.
    ///
    /// Mutation: return `Some(21.0)` (or `Some(0.0)`) for an unparseable input
    /// and every caller's legibility branch silently believes it. The
    /// hash-less case is the one that bites: branding values are written into
    /// CSS verbatim, so `"000"` never renders as a colour at all.
    #[test]
    fn an_unparseable_colour_has_no_ratio() {
        assert_eq!(contrast_ratio("000", "#ffffff"), None);
        assert_eq!(contrast_ratio("#ffffff", "not-a-colour"), None);
        assert_eq!(contrast_ratio("#0g0g0g", "#ffffff"), None);
        assert_eq!(contrast_ratio("#ffff", "#000000"), None);
        assert_eq!(contrast_ratio("", ""), None);
    }

    /// The luma split and the contrast ratio answer different questions, and
    /// on these colours they disagree — which is why one is documented as not
    /// being a readability test.
    #[test]
    fn the_luma_split_is_not_a_readability_test() {
        assert!(is_dark_surface("#ff00ff"));
        assert!(contrast_ratio("#ff00ff", "#ffffff").unwrap() < WCAG_AA_TEXT);

        assert!(!is_dark_surface("#00ff00"));
        assert!(contrast_ratio("#00ff00", "#ffffff").unwrap() < WCAG_AA_TEXT);
    }

    #[test]
    fn is_dark_surface_uses_perceived_luminance() {
        assert!(is_dark_surface("#000000"));
        assert!(is_dark_surface("#000"));
        assert!(is_dark_surface("#1E4FEB"), "brand blue is dark (luma 82)");
        assert!(!is_dark_surface("#ffffff"));
        assert!(!is_dark_surface("#f8fafc"));
        // luma of #808080 is 128 exactly -> not dark (strict <).
        assert!(!is_dark_surface("#808080"));
        assert!(is_dark_surface("#7f7f7f"), "one step darker flips it");
        assert!(!is_dark_surface("not-a-color"));
        assert!(!is_dark_surface("#zzzzzz"));
        assert!(!is_dark_surface(""));
    }

    // --- sanitizer -------------------------------------------------------

    fn sanitize(css: &str) -> String {
        sanitize_custom_css(Some(css)).expect("expected sanitized output")
    }

    #[test]
    fn sanitize_rejects_absent_blank_and_oversized_input() {
        assert_eq!(sanitize_custom_css(None), None);
        assert_eq!(sanitize_custom_css(Some("")), None);
        assert_eq!(sanitize_custom_css(Some("   \n\t ")), None);

        let big = "a".repeat(CUSTOM_CSS_MAX_LENGTH + 1);
        assert_eq!(sanitize_custom_css(Some(&big)), None);
        let at_limit = "a".repeat(CUSTOM_CSS_MAX_LENGTH);
        assert_eq!(sanitize_custom_css(Some(&at_limit)), Some(at_limit));
    }

    #[test]
    fn sanitize_trims_and_passes_benign_css_through() {
        assert_eq!(
            sanitize("  .dp-card { background: linear-gradient(#fff, #000); }  "),
            ".dp-card { background: linear-gradient(#fff, #000); }"
        );
        assert_eq!(
            sanitize("@media (min-width: 40rem) { .x { transform: rotate(1deg) } }"),
            "@media (min-width: 40rem) { .x { transform: rotate(1deg) } }"
        );
    }

    #[test]
    fn sanitize_escapes_style_close_tag() {
        assert_eq!(
            sanitize(".x{}</style><script>alert(1)</script>"),
            ".x{}<\\/style><script>alert(1)</script>",
            "only the </style break-out is escaped"
        );
        // Case-insensitive, and only the `</style` part is rewritten.
        assert_eq!(sanitize("</STYLE>"), "<\\/style>");
        assert_eq!(sanitize("</styled-tag"), "<\\/styled-tag");
    }

    #[test]
    fn sanitize_strips_import_rules() {
        assert_eq!(
            sanitize("@import url(https://evil.test/x.css); .a{}"),
            " .a{}"
        );
        assert_eq!(sanitize("@IMPORT 'x.css';.a{}"), ".a{}");
        // No terminating semicolon: everything to the end of input goes.
        assert_eq!(sanitize(".a{}\n@import \"x.css\""), ".a{}\n");
        // `\b` guard: `@importantly` is not an @import rule.
        assert_eq!(
            sanitize("@importantly { color: red }"),
            "@importantly { color: red }"
        );
    }

    #[test]
    fn sanitize_comments_out_expression() {
        assert_eq!(
            sanitize("width: expression(alert(1));"),
            "width: /* expression( */alert(1));"
        );
        assert_eq!(
            sanitize("width: EXPRESSION  (1)"),
            "width: /* expression( */1)"
        );
        // Not followed by `(` -> untouched.
        assert_eq!(
            sanitize("/* expression of intent */"),
            "/* expression of intent */"
        );
    }

    #[test]
    fn sanitize_comments_out_behavior_but_not_prefixed_properties() {
        assert_eq!(sanitize("behavior: url(#x)"), "/* behavior: */ url(#x)");
        assert_eq!(
            sanitize(".a{ behavior : url(#x) }"),
            ".a{ /* behavior: */ url(#x) }"
        );
        assert_eq!(sanitize(".a{ BEHAVIOR:x }"), ".a{ /* behavior: */x }");
        // Preceded by a letter or `-` -> left alone.
        assert_eq!(sanitize("-webkit-behavior: x"), "-webkit-behavior: x");
        assert_eq!(sanitize("scrollbehavior: x"), "scrollbehavior: x");
    }

    #[test]
    fn sanitize_comments_out_moz_binding() {
        assert_eq!(
            sanitize("-moz-binding: url(evil.xml#x)"),
            "/* -moz-binding: */ url(evil.xml#x)"
        );
        assert_eq!(sanitize("-MOZ-BINDING :x"), "/* -moz-binding: */x");
    }

    #[test]
    fn sanitize_neutralizes_javascript_urls() {
        assert_eq!(
            sanitize("background: url(javascript:alert(1))"),
            "background: url(invalid:alert(1))"
        );
        assert_eq!(
            sanitize("background: URL ( \"javascript:alert(1)\" )"),
            "background: url(invalid:alert(1)\" )"
        );
        assert_eq!(
            sanitize("background: url('JAVASCRIPT:x')"),
            "background: url(invalid:x')"
        );
        // Ordinary urls survive.
        assert_eq!(
            sanitize("background: url(https://cdn.test/a.png)"),
            "background: url(https://cdn.test/a.png)"
        );
    }

    #[test]
    fn sanitize_handles_several_constructs_in_one_payload() {
        let out = sanitize(
            "@import url(evil);\n.a{ behavior: url(#x); -moz-binding: url(y); \
             background: url( 'javascript:1' ); width: expression(2) }</style",
        );
        // Byte-for-byte what the TypeScript sanitizer emits for this input.
        assert_eq!(
            out,
            "\n.a{ /* behavior: */ url(#x); /* -moz-binding: */ url(y); \
             background: url(invalid:1' ); width: /* expression( */2) }<\\/style"
        );
        assert!(!out.contains("@import"), "{out}");
        assert!(!out.contains("javascript:"), "{out}");
        assert!(!out.contains("</style"), "{out}");
        assert!(out.contains("url(invalid:"), "{out}");
        assert!(out.contains("/* behavior: */"), "{out}");
        assert!(out.contains("/* -moz-binding: */"), "{out}");
        assert!(out.contains("/* expression( */"), "{out}");
        assert!(out.contains("<\\/style"), "{out}");
    }

    // --- badges ----------------------------------------------------------

    #[test]
    fn encode_badges_matches_the_typescript_json_string() {
        assert_eq!(
            encode_badges(&DEFAULT_BADGES),
            "[{\"id\":\"secure\",\"label\":\"Secure\",\"textColor\":\"#047857\",\
             \"backgroundColor\":\"#ecfdf5\",\"borderColor\":\"#a7f3d0\"},\
             {\"id\":\"ssl\",\"label\":\"256-bit SSL\",\"textColor\":\"#1E4FEB\",\
             \"backgroundColor\":\"#eff6ff\",\"borderColor\":\"#bfdbfe\"}]"
        );
        // A missing border colour is omitted from the object entirely.
        assert_eq!(
            encode_badges(&[TrustBadge::new("a", "A", "#000", "#fff")]),
            "[{\"id\":\"a\",\"label\":\"A\",\"textColor\":\"#000\",\"backgroundColor\":\"#fff\"}]"
        );
        assert_eq!(encode_badges(&[]), "[]");
    }

    #[test]
    fn decode_badges_is_tolerant() {
        assert_eq!(decode_badges(None), None);
        assert_eq!(decode_badges(Some("not json")), None);
        assert_eq!(
            decode_badges(Some("{\"a\":1}")),
            None,
            "non-array is rejected"
        );
        assert_eq!(
            decode_badges(Some("[]")),
            Some(vec![]),
            "an explicit empty list means 'hide the row'"
        );

        let decoded = decode_badges(Some("[{\"label\":\"L\"},{\"label\":\"\"},{\"id\":\"x\"}]"))
            .expect("array parses");
        assert_eq!(decoded.len(), 1, "label-less badges are dropped");
        assert_eq!(decoded[0].id, "badge-0", "missing id falls back to index");
        assert_eq!(decoded[0].text_color, "#0f172a");
        assert_eq!(decoded[0].background_color, "#f1f5f9");
        assert_eq!(decoded[0].border_color, None);
    }

    #[test]
    fn badges_round_trip() {
        let encoded = encode_badges(&DEFAULT_BADGES_DARK);
        assert_eq!(decode_badges(Some(&encoded)).unwrap(), *DEFAULT_BADGES_DARK);
    }

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

    fn source_with(extras: Value) -> BrandingSource {
        let mut rules = Map::new();
        rules.insert(BRANDING_GROUP_KEY.to_string(), extras);
        BrandingSource {
            sdk_ui_rules: Some(rules),
            ..Default::default()
        }
    }

    #[test]
    fn decode_branding_without_a_source_is_the_default() {
        assert_eq!(decode_branding(None), *DEFAULT_BRANDING);
        assert_eq!(
            decode_branding(Some(&BrandingSource::default())),
            *DEFAULT_BRANDING
        );
    }

    #[test]
    fn decode_branding_prefers_the_public_name_aliases() {
        let src = BrandingSource {
            merchant_name: Some("Public".into()),
            seller_name: Some("Request".into()),
            merchant_logo: Some("https://a.test/logo.png".into()),
            logo: Some("https://b.test/logo.png".into()),
            ..Default::default()
        };
        let b = decode_branding(Some(&src));
        assert_eq!(b.display_name, "Public");
        assert_eq!(b.logo_url, "https://a.test/logo.png");

        let src = BrandingSource {
            seller_name: Some("Request".into()),
            logo: Some("https://b.test/logo.png".into()),
            ..Default::default()
        };
        let b = decode_branding(Some(&src));
        assert_eq!(
            b.display_name, "Request",
            "falls back to the request spelling"
        );
        assert_eq!(b.logo_url, "https://b.test/logo.png");
    }

    #[test]
    fn decode_branding_colour_fallback_chain() {
        let mut src = source_with(json!({ "text": "#111111" }));
        src.theme = Some("#123456".into());
        let b = decode_branding(Some(&src));
        assert_eq!(b.primary, "#123456");
        assert_eq!(b.accent_text, "#123456", "accentText falls back to theme");
        assert_eq!(
            b.button_background, "#123456",
            "button background falls back to theme"
        );
        assert_eq!(b.heading, "#111111", "heading falls back to the bag's text");
        assert_eq!(b.text, "#111111");

        let mut src = source_with(json!({ "heading": "#222222", "accentText": "#333333" }));
        src.theme = Some("#123456".into());
        src.payment_button_colour = Some("#654321".into());
        let b = decode_branding(Some(&src));
        assert_eq!(b.heading, "#222222");
        assert_eq!(b.accent_text, "#333333");
        assert_eq!(b.button_background, "#654321");
    }

    #[test]
    fn decode_branding_tagline_prefers_the_bag() {
        let mut src = source_with(json!({ "tagline": "from bag" }));
        src.merchant_description = Some("from column".into());
        assert_eq!(decode_branding(Some(&src)).tagline, "from bag");

        let mut src = source_with(json!({}));
        src.merchant_description = Some("from column".into());
        assert_eq!(decode_branding(Some(&src)).tagline, "from column");
    }

    #[test]
    fn decode_branding_normalizes_label_style() {
        let bagged =
            |v: &str| decode_branding(Some(&source_with(json!({ "labelStyle": v })))).label_style;
        assert_eq!(bagged("above"), LabelStyle::Above);
        assert_eq!(bagged("hidden"), LabelStyle::Hidden);
        assert_eq!(
            bagged("floating"),
            LabelStyle::Above,
            "legacy floating -> above"
        );

        let legacy = |v: &str| {
            let src = BrandingSource {
                payment_form_label_type: Some(v.to_string()),
                ..Default::default()
            };
            decode_branding(Some(&src)).label_style
        };
        assert_eq!(
            legacy("never"),
            LabelStyle::Hidden,
            "legacy never -> hidden"
        );
        assert_eq!(legacy("hidden"), LabelStyle::Hidden);
        assert_eq!(legacy("floating"), LabelStyle::Above);
        assert_eq!(legacy("nonsense"), LabelStyle::Above, "default");

        // The bag wins over the legacy column.
        let mut src = source_with(json!({ "labelStyle": "hidden" }));
        src.payment_form_label_type = Some("above".into());
        assert_eq!(decode_branding(Some(&src)).label_style, LabelStyle::Hidden);

        // A bagged `floating` is normalized *by the bag arm* — it must not fall
        // through to the legacy column, which here says hidden.
        let mut src = source_with(json!({ "labelStyle": "floating" }));
        src.payment_form_label_type = Some("never".into());
        assert_eq!(decode_branding(Some(&src)).label_style, LabelStyle::Above);
    }

    #[test]
    fn decode_branding_rejects_out_of_range_enum_values() {
        let src = source_with(json!({
            "radiusSurface": "pill",
            "radiusButton": "pill",
            "fontFamily": "comic-sans",
            "inputSize": "xl",
            "layout": "split",
        }));
        let b = decode_branding(Some(&src));
        assert_eq!(
            b.radius_surface,
            NonPillRadius::Medium,
            "a stale 'pill' surface radius drops back to medium"
        );
        assert_eq!(b.radius_button, CornerRadius::Pill, "buttons may be pill");
        assert_eq!(b.font_family, FontFamily::Inter);
        assert_eq!(b.input_size, SizeScale::Md);
        assert_eq!(b.layout, LayoutStyle::Split);
    }

    #[test]
    fn decode_branding_parses_stringified_booleans() {
        let src = source_with(json!({
            "showLogo": "true",
            "showTotal": "false",
            "summaryGradient": true,
            "showOrderItems": "yes",
        }));
        let b = decode_branding(Some(&src));
        assert!(b.show_logo, "'true' string flips the default false");
        assert!(!b.show_total, "'false' string flips the default true");
        assert!(b.summary_gradient, "a real boolean is honoured");
        assert!(b.show_order_items, "an unparseable value keeps the default");
    }

    #[test]
    fn decode_branding_powered_by_only_hides_on_explicit_false() {
        let with = |v: Option<bool>| {
            let src = BrandingSource {
                branding_visibility: v,
                ..Default::default()
            };
            decode_branding(Some(&src)).show_powered_by
        };
        assert!(with(None), "absent means shown");
        assert!(with(Some(true)));
        assert!(!with(Some(false)), "only an explicit false hides it");
    }

    #[test]
    fn decode_branding_reads_flat_copy_and_layout_columns() {
        let src = BrandingSource {
            payment_form_header_text: Some("Checkout".into()),
            payment_button_text: Some("Pay now".into()),
            custom_message_for_card_terms: Some("Terms".into()),
            sdk_layout: Some("accordion".into()),
            ..Default::default()
        };
        let b = decode_branding(Some(&src));
        assert_eq!(b.header_text, "Checkout");
        assert_eq!(b.pay_button_label, "Pay now");
        assert_eq!(b.card_terms_message, "Terms");
        assert_eq!(b.payment_layout, PaymentLayout::Accordion);
    }

    /// A shop that never saved its trust row gets the default notices and no
    /// badges; one that removed every badge keeps none, and gets no notices.
    /// Mutation: decode a missing `trustBadges` to `DEFAULT_BADGES` again, or
    /// add notices when the merchant emptied the row, and this fails.
    #[test]
    fn decode_branding_migrates_an_untouched_trust_row_to_notices() {
        let b = decode_branding(Some(&source_with(json!({}))));
        assert!(b.trust_badges.is_empty());
        assert_eq!(b.notices, *DEFAULT_NOTICES);

        let b = decode_branding(Some(&source_with(json!({ "trustBadges": "[]" }))));
        assert!(
            b.trust_badges.is_empty(),
            "an explicit empty list is honoured"
        );
        assert!(b.notices.is_empty(), "and no notices are added to it");

        let b = decode_branding(Some(&source_with(json!({ "trustBadges": "broken" }))));
        assert!(b.trust_badges.is_empty(), "malformed reads as absent");
        assert_eq!(b.notices, *DEFAULT_NOTICES);
    }

    /// Custom fields have no default set to fall back to, so an absent or
    /// malformed blob means "no custom fields" — the opposite of badges.
    #[test]
    fn decode_branding_reads_custom_fields_from_the_bag() {
        let b = decode_branding(Some(&source_with(json!({}))));
        assert!(b.custom_fields.is_empty());

        let b = decode_branding(Some(&source_with(json!({ "customFields": "broken" }))));
        assert!(b.custom_fields.is_empty(), "malformed -> none");

        let b = decode_branding(Some(&source_with(json!({
            "customFields": r#"[{"key":"login","type":"email","required":true}]"#
        }))));
        assert_eq!(b.custom_fields.len(), 1);
        assert_eq!(b.custom_fields[0].key, "login");
        assert!(b.custom_fields[0].required);
    }

    /// A shop that configures no custom fields must keep a bag byte-identical
    /// to its pre-feature one, or upgrading rewrites every merchant's blob.
    #[test]
    fn encode_branding_omits_custom_fields_when_there_are_none() {
        let e = encode_branding(&default_branding());
        let bag = &e.sdk_ui_rules[BRANDING_GROUP_KEY];
        assert!(bag.get("customFields").is_none(), "{bag:?}");
    }

    #[test]
    fn encode_branding_round_trips_custom_fields_through_the_bag() {
        use crate::core::custom_fields::{CheckoutCustomField, CustomFieldType};

        let mut b = default_branding();
        let mut field = CheckoutCustomField::new("login");
        field.field_type = CustomFieldType::Email;
        field.required = true;
        b.custom_fields = vec![field];

        let encoded = encode_branding(&b);
        let source =
            source_with(serde_json::to_value(&encoded.sdk_ui_rules[BRANDING_GROUP_KEY]).unwrap());
        assert_eq!(
            decode_branding(Some(&source)).custom_fields,
            b.custom_fields
        );
    }

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

    fn customized() -> CheckoutBranding {
        CheckoutBranding {
            display_name: "  Acme  ".into(),
            logo_url: "https://acme.test/logo.png".into(),
            tagline: " fast checkout ".into(),
            show_logo: true,
            logo_shape: LogoShape::Circle,
            logo_size: LogoSize::Lg,
            primary: "#123456".into(),
            surface: "#fefefe".into(),
            radius_button: CornerRadius::Pill,
            radius_surface: NonPillRadius::Large,
            surface_style: SurfaceStyle::Outlined,
            layout: LayoutStyle::Compact,
            summary_position: SummaryPosition::Right,
            show_total: false,
            total_label: "Sum".into(),
            label_style: LabelStyle::Hidden,
            payment_layout: PaymentLayout::SpacedAccordion,
            show_powered_by: false,
            footer_text: "  bye  ".into(),
            support_email: "help@acme.test".into(),
            custom_css: ".a{}".into(),
            header_text: "  ".into(),
            trust_badges: vec![TrustBadge::new("x", "X", "#000000", "#ffffff")],
            ..default_branding()
        }
    }

    #[test]
    fn encode_branding_fills_the_flat_columns() {
        let b = customized();
        let e = encode_branding(&b);
        assert_eq!(e.theme, "#123456");
        assert_eq!(e.logo.as_deref(), Some("https://acme.test/logo.png"));
        assert_eq!(e.seller_name.as_deref(), Some("Acme"), "trimmed");
        assert_eq!(e.payment_form_header_text, None, "blank copy becomes null");
        assert_eq!(e.payment_button_colour, b.button_background);
        assert_eq!(e.payment_button_text_colour, b.button_text);
        assert_eq!(e.background_colour, b.background);
        assert_eq!(e.sdk_layout, PaymentLayout::SpacedAccordion);
        assert_eq!(
            e.payment_form_label_type,
            LegacyLabelType::Never,
            "hidden maps back to the legacy `never`"
        );
        assert!(!e.branding_visibility);

        let mut above = b.clone();
        above.label_style = LabelStyle::Above;
        assert_eq!(
            encode_branding(&above).payment_form_label_type,
            LegacyLabelType::Above
        );
    }

    #[test]
    fn encode_branding_writes_the_branding_bag() {
        let e = encode_branding(&customized());
        let bag = &e.sdk_ui_rules[BRANDING_GROUP_KEY];
        assert_eq!(bag["radiusButton"], "pill");
        assert_eq!(bag["radiusSurface"], "large");
        assert_eq!(bag["surfaceStyle"], "outlined");
        assert_eq!(bag["labelStyle"], "hidden");
        assert_eq!(bag["showLogo"], "true", "booleans persist as strings");
        assert_eq!(bag["showTotal"], "false");
        assert_eq!(bag["totalLabel"], "Sum");
        assert_eq!(bag["tagline"], "fast checkout", "trimmed");
        assert_eq!(bag["footerText"], "bye");
        assert_eq!(bag["supportEmail"], "help@acme.test");
        assert_eq!(bag["customCss"], ".a{}");
        assert_eq!(
            bag["trustBadges"],
            "[{\"id\":\"x\",\"label\":\"X\",\"textColor\":\"#000000\",\"backgroundColor\":\"#ffffff\"}]"
        );
    }

    #[test]
    fn encode_branding_omits_blank_optional_bag_entries() {
        let bag = encode_branding(&default_branding()).sdk_ui_rules[BRANDING_GROUP_KEY].clone();
        for key in ["tagline", "footerText", "supportEmail", "customCss"] {
            assert!(!bag.contains_key(key), "{key} must be omitted when blank");
        }
    }

    #[test]
    fn encode_branding_with_base_preserves_unrelated_fields_and_rule_groups() {
        let base = json!({
            "show_card_terms": true,
            "domain_name": "acme.test",
            "theme": "#000000",
            "sdk_ui_rules": {
                "other_group": { "keep": "me" },
                "branding": { "stale": "gone" },
            },
        });
        let out = encode_branding_with_base(&customized(), Some(&base));
        assert_eq!(
            out["show_card_terms"],
            json!(true),
            "unknown fields survive"
        );
        assert_eq!(out["domain_name"], json!("acme.test"));
        assert_eq!(
            out["theme"],
            json!("#123456"),
            "encoded fields win over base"
        );
        assert_eq!(out["sdk_ui_rules"]["other_group"]["keep"], json!("me"));
        assert_eq!(
            out["sdk_ui_rules"]["branding"].get("stale"),
            None,
            "the branding group is replaced wholesale"
        );
        assert_eq!(
            out["sdk_ui_rules"]["branding"]["radiusButton"],
            json!("pill")
        );

        // A `None` base is equivalent to encoding on its own.
        let bare = encode_branding_with_base(&customized(), None);
        assert_eq!(
            bare,
            serde_json::to_value(encode_branding(&customized())).unwrap()
        );
    }

    #[test]
    fn encode_then_decode_round_trips() {
        let original = customized();
        let encoded = encode_branding(&original);
        let source: BrandingSource =
            serde_json::from_value(serde_json::to_value(&encoded).unwrap()).unwrap();
        let decoded = decode_branding(Some(&source));

        let mut expected = original.clone();
        // Encoding trims the copy fields, and a blank header column decodes back
        // as the empty string.
        expected.display_name = "Acme".into();
        expected.tagline = "fast checkout".into();
        expected.footer_text = "bye".into();
        expected.header_text = String::new();
        assert_eq!(decoded, expected);
    }

    #[test]
    fn round_trip_survives_the_dark_default() {
        let encoded = encode_branding(&DEFAULT_BRANDING_DARK);
        let source: BrandingSource =
            serde_json::from_value(serde_json::to_value(&encoded).unwrap()).unwrap();
        assert_eq!(decode_branding(Some(&source)), *DEFAULT_BRANDING_DARK);
    }

    // --- import / export -------------------------------------------------

    #[test]
    fn iso8601_matches_javascript_to_iso_string() {
        assert_eq!(iso8601_millis(0), "1970-01-01T00:00:00.000Z");
        assert_eq!(
            iso8601_millis(1_700_000_000_000),
            "2023-11-14T22:13:20.000Z"
        );
        assert_eq!(
            iso8601_millis(1_700_000_000_123),
            "2023-11-14T22:13:20.123Z"
        );
        // A leap day, and a pre-epoch instant.
        assert_eq!(
            iso8601_millis(1_709_164_800_000),
            "2024-02-29T00:00:00.000Z"
        );
        assert_eq!(iso8601_millis(-1), "1969-12-31T23:59:59.999Z");
    }

    #[test]
    fn build_branding_export_wraps_the_branding() {
        let e = build_branding_export_at(&customized(), 1_700_000_000_000);
        assert_eq!(e.format, "delopay-checkout-branding");
        assert_eq!(e.version, 1);
        assert_eq!(e.exported_at, "2023-11-14T22:13:20.000Z");
        assert_eq!(e.branding, customized());

        let json = serde_json::to_value(&e).unwrap();
        assert_eq!(json["branding"]["radiusButton"], json!("pill"));
        assert_eq!(json["branding"]["showPoweredBy"], json!(false));
    }

    #[test]
    fn export_import_round_trips() {
        let e = build_branding_export_at(&customized(), 0);
        let raw = serde_json::to_value(&e).unwrap();
        assert_eq!(parse_imported_branding(&raw), customized());
    }

    #[test]
    fn parse_imported_branding_accepts_a_bare_object() {
        let raw = serde_json::to_value(customized()).unwrap();
        assert_eq!(parse_imported_branding(&raw), customized());
    }

    #[test]
    fn parse_imported_branding_falls_back_on_junk() {
        assert_eq!(parse_imported_branding(&json!(null)), *DEFAULT_BRANDING);
        assert_eq!(
            parse_imported_branding(&json!([1, 2, 3])),
            *DEFAULT_BRANDING
        );
        assert_eq!(parse_imported_branding(&json!("nope")), *DEFAULT_BRANDING);
        assert_eq!(parse_imported_branding(&json!({})), *DEFAULT_BRANDING);
    }

    #[test]
    fn parse_imported_branding_validates_each_field_independently() {
        let raw = json!({
            "displayName": "Acme",
            "primary": "not-a-hex",
            "background": "#abc",
            "surface": 42,
            "fontFamily": "comic-sans",
            "logoSize": "lg",
            "radiusBadge": "square",
            "showLogo": "true",
            "showPoweredBy": false,
            "labelStyle": "floating",
            "totalLabel": 7,
            "trustBadges": "not-an-array",
            "unknownField": "ignored",
        });
        let b = parse_imported_branding(&raw);
        assert_eq!(b.display_name, "Acme");
        assert_eq!(
            b.primary, DEFAULT_BRANDING.primary,
            "bad hex keeps the default"
        );
        assert_eq!(b.background, "#abc", "a 3-digit hex is valid");
        assert_eq!(
            b.surface, DEFAULT_BRANDING.surface,
            "non-strings keep the default"
        );
        assert_eq!(b.font_family, FontFamily::Inter);
        assert_eq!(b.logo_size, LogoSize::Lg);
        assert_eq!(b.radius_badge, CornerRadius::Square);
        assert!(b.show_logo);
        assert!(!b.show_powered_by);
        assert_eq!(
            b.label_style, DEFAULT_BRANDING.label_style,
            "the importer does not accept the legacy floating value"
        );
        assert_eq!(b.total_label, DEFAULT_BRANDING.total_label);
        assert!(b.trust_badges.is_empty());
        assert_eq!(b.notices, *DEFAULT_NOTICES);
    }

    #[test]
    fn parse_imported_branding_reads_loose_trust_badges() {
        let raw = json!({
            "trustBadges": [
                { "id": "a", "label": "A", "textColor": "#010101",
                  "backgroundColor": "#020202", "borderColor": "#030303" },
                { "label": "B", "textColor": "rgb(1,2,3)", "borderColor": "nope" },
                { "label": "" },
                "not-an-object",
            ],
        });
        let badges = parse_imported_branding(&raw).trust_badges;
        assert_eq!(
            badges.len(),
            2,
            "label-less and non-object entries are dropped"
        );
        assert_eq!(badges[0].border_color.as_deref(), Some("#030303"));
        assert_eq!(badges[1].id, "badge-1", "index-based id fallback");
        assert_eq!(badges[1].text_color, "#0f172a", "non-hex colours fall back");
        assert_eq!(badges[1].background_color, "#f1f5f9");
        assert_eq!(badges[1].border_color, None, "a non-hex border is dropped");

        let raw = json!({ "trustBadges": [] });
        assert!(parse_imported_branding(&raw).trust_badges.is_empty());
    }

    #[test]
    fn parse_imported_branding_truncates_custom_css() {
        let raw = json!({ "customCss": "x".repeat(CUSTOM_CSS_MAX_LENGTH + 10) });
        let css = parse_imported_branding(&raw).custom_css;
        assert_eq!(css.len(), CUSTOM_CSS_MAX_LENGTH);

        let raw = json!({ "customCss": ".a{}" });
        assert_eq!(parse_imported_branding(&raw).custom_css, ".a{}");
    }

    // --- defaults & CSS variables ---------------------------------------

    #[test]
    fn defaults_are_the_documented_palettes() {
        assert_eq!(DEFAULT_BRANDING.primary, "#1E4FEB");
        assert_eq!(DEFAULT_BRANDING.button_background, "#0A1130");
        assert_eq!(DEFAULT_BRANDING.surface_style, SurfaceStyle::Elevated);
        assert_eq!(DEFAULT_BRANDING.radius_badge, CornerRadius::Pill);
        assert!(!DEFAULT_BRANDING.show_logo);
        assert!(DEFAULT_BRANDING.show_powered_by);
        assert!(DEFAULT_BRANDING.trust_badges.is_empty());
        assert_eq!(DEFAULT_BRANDING.notices, *DEFAULT_NOTICES);

        assert_eq!(DEFAULT_BRANDING_DARK.background, "#020617");
        assert_eq!(DEFAULT_BRANDING_DARK.accent_text, "#60a5fa");
        assert_eq!(
            DEFAULT_BRANDING_DARK.surface_style,
            SurfaceStyle::Flat,
            "drop shadows don't read on dark surfaces"
        );
        assert!(DEFAULT_BRANDING_DARK.trust_badges.is_empty());
        assert_eq!(DEFAULT_BRANDING_DARK.notices, *DEFAULT_NOTICES);
        // Only visual tokens diverge.
        assert_eq!(
            DEFAULT_BRANDING_DARK.total_label,
            DEFAULT_BRANDING.total_label
        );
        assert_eq!(DEFAULT_BRANDING_DARK.layout, DEFAULT_BRANDING.layout);

        assert_eq!(default_branding(), *DEFAULT_BRANDING);
        assert_eq!(CheckoutBranding::default(), *DEFAULT_BRANDING);
        assert_eq!(
            clone_branding(&DEFAULT_BRANDING_DARK),
            *DEFAULT_BRANDING_DARK
        );
    }

    #[test]
    fn branding_variables_cover_every_dp_token() {
        let vars = branding_variables(&DEFAULT_BRANDING);
        assert_eq!(vars.len(), 32);
        let get = |k: &str| {
            vars.iter()
                .find(|(name, _)| *name == k)
                .map(|(_, v)| v.clone())
                .unwrap_or_else(|| panic!("missing {k}"))
        };
        assert_eq!(get("--dp-primary"), "#1E4FEB");
        assert_eq!(get("--dp-bg"), "#f8fafc");
        assert_eq!(get("--dp-btn-fg"), "#ffffff");
        assert_eq!(get("--dp-radius-badge"), "999px");
        assert_eq!(get("--dp-radius-surface"), "12px");
        assert_eq!(get("--dp-heading-weight"), "600");
        assert_eq!(get("--dp-pad-surface"), "1.5rem");
        assert_eq!(get("--dp-gap-vertical"), "1rem");
        assert_eq!(get("--dp-input-pad"), "0.625rem 0.75rem");
        assert_eq!(get("--dp-button-pad"), "0.875rem 1.25rem");
        assert_eq!(get("--dp-shadow"), shadow_for(SurfaceStyle::Elevated));
        assert_eq!(
            get("--dp-surface-border"),
            "1px solid transparent",
            "only the outlined style paints a border"
        );
        assert_eq!(vars[0].0, "--dp-primary", "order matches the TS writer");

        // The disclosure tokens. Both default colours are dark enough to be
        // written on in white.
        assert_eq!(get("--dp-surcharge"), "#b45309");
        assert_eq!(get("--dp-discount"), "#047857");
        assert_eq!(get("--dp-surcharge-ink"), "#ffffff");
        assert_eq!(get("--dp-discount-ink"), "#ffffff");
        assert_eq!(get("--dp-surcharge-size"), "0.6875rem");
        assert_eq!(get("--dp-surcharge-pad"), "1px 6px");
        assert_eq!(get("--dp-surcharge-radius"), "999px");
        assert_eq!(get("--dp-surcharge-weight"), "600");
        assert_eq!(get("--dp-surcharge-border-width"), "1px");
        assert_eq!(get("--dp-surcharge-border-style"), "solid");
    }

    /// The ink is measured against the colour it is written on, not fixed.
    /// Mutation: publish `--dp-surcharge-ink` as a constant `#ffffff` — the
    /// pale-amber case fails, because white on `#fbbf24` is unreadable.
    #[test]
    fn the_surcharge_ink_follows_the_colour_it_is_written_on() {
        let mut pale = default_branding();
        pale.surcharge_color = "#fbbf24".to_string();
        pale.discount_color = "#34d399".to_string();
        let vars = branding_variables(&pale);
        let get = |k: &str| {
            vars.iter()
                .find(|(name, _)| *name == k)
                .map(|(_, v)| v.clone())
                .unwrap_or_else(|| panic!("missing {k}"))
        };
        assert_eq!(get("--dp-surcharge-ink"), "#000000");
        assert_eq!(get("--dp-discount-ink"), "#000000");
        assert_eq!(readable_ink_on("#b45309"), "#ffffff");
        // An unparseable colour answers white rather than panicking.
        assert_eq!(readable_ink_on("not-a-colour"), "#ffffff");
    }

    /// `Outline` draws nothing but its border, so a width of `None` there reads
    /// as `Thin` rather than erasing the style. Mutation: drop the `Outline`
    /// arm from the variable writer — the first assertion returns `0px`.
    #[test]
    fn outline_never_publishes_a_zero_border_width() {
        let mut outlined = default_branding();
        outlined.surcharge_style = SurchargeStyle::Outline;
        outlined.surcharge_border_width = SurchargeBorderWidth::None;
        let vars = branding_variables(&outlined);
        let width = vars
            .iter()
            .find(|(name, _)| *name == "--dp-surcharge-border-width")
            .map(|(_, v)| v.clone())
            .unwrap();
        assert_eq!(width, "1px");

        // Every other style keeps the merchant's own answer.
        let mut badged = default_branding();
        badged.surcharge_style = SurchargeStyle::Badge;
        badged.surcharge_border_width = SurchargeBorderWidth::None;
        let vars = branding_variables(&badged);
        let width = vars
            .iter()
            .find(|(name, _)| *name == "--dp-surcharge-border-width")
            .map(|(_, v)| v.clone())
            .unwrap();
        assert_eq!(width, "0px");
    }

    /// An unset preset must decode as "not chosen", not as the fallback:
    /// a concrete value here would override every connector account already
    /// configured. Mutation: make `pick_optional_enum` fall back to the
    /// default preset — the first assertion fails.
    #[test]
    fn an_empty_airwallex_preset_stays_unchosen_through_a_round_trip() {
        let encoded = encode_branding_with_base(&default_branding(), None);
        let bag = encoded["sdk_ui_rules"]["branding"].clone();
        assert_eq!(bag["airwallexCardPreset"], "");

        let decoded = decode_branding(Some(&BrandingSource {
            sdk_ui_rules: Some(serde_json::from_value(bag).unwrap()),
            ..BrandingSource::default()
        }));
        assert_eq!(decoded.airwallex_card_preset, None);
        // …and the connector account is what decides instead.
        assert_eq!(
            resolve_airwallex_card_preset(None, Some("single_row")),
            AirwallexCardPreset::SingleRow
        );
        assert_eq!(
            resolve_airwallex_card_preset(None, None),
            AirwallexCardPreset::SplitFieldsLabelled
        );
    }

    /// Sections sort by the merchant's number, then by the catalogue's own
    /// order — never by chance. Mutation: drop the `section_position` tie-break
    /// from `compare_sections` and the two sharing 10 may swap.
    #[test]
    fn sections_sort_by_number_then_by_catalogue_order() {
        let mut order = default_method_section_order();
        order.insert("wallet".to_string(), 10);
        let mut ids = vec!["crypto", "wallet", "card", "made_up"];
        ids.sort_by(|a, b| compare_sections(a, b, &order));
        assert_eq!(ids, vec!["card", "wallet", "crypto", "made_up"]);
    }

    /// An overlong caption is cut to the cap, not thrown away: the same stored
    /// value has to survive in both codecs. Mutation: drop the caption instead
    /// of truncating it — the decode assertion finds no label at all.
    #[test]
    fn an_overlong_section_caption_is_truncated_not_dropped() {
        let long = "a".repeat(MAX_SECTION_LABEL_LENGTH + 1);
        let raw = format!(r#"{{"card":{{"en":"{long}","de":"   "}}}}"#);

        let decoded = decode_method_section_labels(Some(&raw));
        let card = decoded.get("card").expect("the section survives");
        assert_eq!(card["en"].chars().count(), MAX_SECTION_LABEL_LENGTH);
        assert_eq!(card["en"], "a".repeat(MAX_SECTION_LABEL_LENGTH));
        // A blank caption is not a caption.
        assert!(!card.contains_key("de"));

        // …and it round-trips through the encoder unchanged.
        let re_decoded =
            decode_method_section_labels(Some(&encode_method_section_labels(&decoded)));
        assert_eq!(re_decoded, decoded);

        // A bag of nothing but blanks stays absent rather than becoming `{}`.
        let blanks = decode_method_section_labels(Some(r#"{"card":{"en":"  "}}"#));
        assert!(blanks.is_empty());
    }

    /// A caption resolves for the locale, then any locale, then the caller's
    /// own name, then the id. Mutation: return the raw id before consulting
    /// `labels` — the first assertion fails.
    #[test]
    fn a_section_caption_resolves_through_its_locales() {
        let mut labels = MethodSectionLabels::new();
        labels.insert(
            "card".to_string(),
            BTreeMap::from([("de".to_string(), "Karte".to_string())]),
        );

        assert_eq!(section_label("card", "de-AT", &labels, None), "Karte");
        // No English caption: any written translation beats a blank heading.
        assert_eq!(section_label("card", "en", &labels, None), "Karte");
        // An uncaptioned section falls back to the caller's own name, then to
        // the id itself.
        assert_eq!(
            section_label("wallet", "en", &labels, Some("Wallets")),
            "Wallets"
        );
        assert_eq!(section_label("wallet", "en", &labels, None), "wallet");
        // An alias is stored and read under its canonical id.
        assert_eq!(section_label("card_redirect", "de", &labels, None), "Karte");
    }

    #[test]
    fn outlined_surfaces_get_a_real_border() {
        let b = CheckoutBranding {
            surface_style: SurfaceStyle::Outlined,
            border: "#ff0000".into(),
            ..default_branding()
        };
        let vars = branding_variables(&b);
        let border = vars
            .iter()
            .find(|(k, _)| *k == "--dp-surface-border")
            .map(|(_, v)| v.as_str())
            .unwrap();
        assert_eq!(border, "1px solid #ff0000");
        assert_eq!(
            vars.iter()
                .find(|(k, _)| *k == "--dp-shadow")
                .map(|(_, v)| v.as_str()),
            Some("none")
        );
    }

    #[test]
    fn branding_variables_css_renders_a_root_rule() {
        let css = branding_variables_css(&DEFAULT_BRANDING);
        assert!(css.starts_with(":root{--dp-primary:#1E4FEB;"), "{css}");
        assert!(
            css.ends_with("--dp-surface-border:1px solid transparent;}"),
            "{css}"
        );
    }

    // --- card forms, cancel link, notices --------------------------------

    /// Every new key with no source falls back to what its pane drew before
    /// the setting existed. Mutation: change any default below and this fails.
    #[test]
    fn card_form_and_cancel_link_defaults_reproduce_the_previous_drawing() {
        let b = &*DEFAULT_BRANDING;
        assert!(b.cancel_link_enabled);
        assert_eq!(b.cancel_link_position, CancelLinkPosition::Top);
        assert_eq!(b.cancel_link_style, CancelLinkStyle::Link);
        assert_eq!(b.stripe_theme, StripeTheme::Auto);
        assert_eq!(b.stripe_inputs, StripeInputStyle::Spaced);
        assert_eq!(b.stripe_labels, StripeLabelPlacement::Above);
        assert_eq!(b.stripe_spacing, StripeSpacing::Comfortable);
        assert_eq!(b.stripe_field_weight, CardFieldWeight::Medium);
        assert_eq!(b.stripe_focus_ring, CardFocusRing::Strong);
        assert!(!b.stripe_disable_animations);
        assert_eq!(b.paypal_card_layout, PaypalCardLayout::Split);
        assert_eq!(b.paypal_field_weight, CardFieldWeight::Regular);
        assert_eq!(b.mollie_focus_ring, CardFocusRing::Strong);
        assert_eq!(b.epayouts_label_style, PaypalLabelStyle::Above);
        assert_eq!(b.nomupay_form_style, NomupayFormStyle::Plain);
        assert!(b.nomupay_show_labels && b.nomupay_show_placeholders);
        assert!(!b.nomupay_show_cvv_hint);
        assert_eq!(b.nomupay_focus_ring, CardFocusRing::None);
        assert_eq!(b.nomupay_apple_pay_button_type, ApplePayButtonType::Pay);
        assert_eq!(
            b.nomupay_google_pay_button_color,
            GooglePayButtonColor::Auto
        );
        assert_eq!(b.micropayment_field_weight, CardFieldWeight::Regular);
        assert_eq!(b.whop_card_preset, WhopCardPreset::CardStacked);
        assert_eq!(b.whop_accent_color, WhopAccentColor::Auto);
        assert_eq!(b.whop_radius, WhopRadius::Checkout);
        assert_eq!(b.whop_shadow, WhopShadow::Soft);
        assert!(b.whop_method_icons);
        assert_eq!(b.whop_selection, WhopSelection::RadioTint);
        assert_eq!(decode_branding(Some(&source_with(json!({})))), *b);
    }

    #[test]
    fn decode_branding_reads_the_card_form_and_cancel_link_keys() {
        let b = decode_branding(Some(&source_with(json!({
            "cancelLinkEnabled": "false",
            "cancelLinkPosition": "bottom",
            "cancelLinkStyle": "button",
            "stripeTheme": "night",
            "stripeInputs": "condensed",
            "stripeLabels": "floating",
            "stripeSpacing": "spacious",
            "stripeFieldFontSize": "lg",
            "stripeDisableAnimations": "true",
            "paypalCardLayout": "stacked",
            "paypalLabelStyle": "none",
            "mollieFieldChrome": "filled",
            "micropaymentFocusRing": "subtle",
            "nomupayFormStyle": "card",
            "nomupayShowLabels": "false",
            "nomupayApplePayButtonStyle": "white-outline",
            "nomupayApplePayButtonType": "add-money",
            "nomupayGooglePayButtonColor": "default",
            "nomupayGooglePayButtonType": "checkout",
            "whopCardPreset": "tiles",
            "whopAccentColor": "crimson",
            "whopGrayColor": "sand",
            "whopBillingDetails": "full",
            "whopSeparated": "true",
            "whopEmailLabel": "floating",
            "whopRadius": "large",
            "whopShadow": "none",
            "whopMethodIcons": "false",
            "whopSelection": "tint",
            "stripeTheme_typo": "flat",
            "whopSelection_unknown": "x",
        }))));
        assert!(!b.cancel_link_enabled);
        assert_eq!(b.cancel_link_position, CancelLinkPosition::Bottom);
        assert_eq!(b.cancel_link_style, CancelLinkStyle::Button);
        assert_eq!(b.stripe_theme, StripeTheme::Night);
        assert_eq!(b.stripe_inputs, StripeInputStyle::Condensed);
        assert_eq!(b.stripe_labels, StripeLabelPlacement::Floating);
        assert_eq!(b.stripe_spacing, StripeSpacing::Spacious);
        assert_eq!(b.stripe_field_font_size, CardFieldFontSize::Lg);
        assert!(b.stripe_disable_animations);
        assert_eq!(b.paypal_card_layout, PaypalCardLayout::Stacked);
        assert_eq!(b.paypal_label_style, PaypalLabelStyle::None);
        assert_eq!(b.mollie_field_chrome, CardFieldChrome::Filled);
        assert_eq!(b.micropayment_focus_ring, CardFocusRing::Subtle);
        assert_eq!(b.nomupay_form_style, NomupayFormStyle::Card);
        assert!(!b.nomupay_show_labels);
        assert_eq!(
            b.nomupay_apple_pay_button_style,
            ApplePayButtonStyle::WhiteOutline
        );
        assert_eq!(
            b.nomupay_apple_pay_button_type,
            ApplePayButtonType::AddMoney
        );
        assert_eq!(
            b.nomupay_google_pay_button_color,
            GooglePayButtonColor::Default
        );
        assert_eq!(
            b.nomupay_google_pay_button_type,
            GooglePayButtonType::Checkout
        );
        assert_eq!(b.whop_card_preset, WhopCardPreset::Tiles);
        assert_eq!(b.whop_accent_color, WhopAccentColor::Crimson);
        assert_eq!(b.whop_gray_color, WhopGrayColor::Sand);
        assert_eq!(b.whop_billing_details, WhopBillingDetails::Full);
        assert!(b.whop_separated);
        assert_eq!(b.whop_email_label, WhopEmailLabel::Floating);
        assert_eq!(b.whop_radius, WhopRadius::Large);
        assert_eq!(b.whop_shadow, WhopShadow::None);
        assert!(!b.whop_method_icons);
        assert_eq!(b.whop_selection, WhopSelection::Tint);

        // A value outside the set falls back rather than failing the decode.
        let b = decode_branding(Some(&source_with(json!({
            "stripeTheme": "neon",
            "whopRadius": "pill",
        }))));
        assert_eq!(b.stripe_theme, StripeTheme::Auto);
        assert_eq!(b.whop_radius, WhopRadius::Checkout);
    }

    /// A look stored before e-Payouts had its own keys reads the PayPal
    /// values; its own keys win once written. Mutation: drop the fallback in
    /// `decode_branding` and the first half fails.
    #[test]
    fn epayouts_card_keys_fall_back_to_the_paypal_values() {
        let paypal_only = json!({
            "paypalCardLayout": "stacked",
            "paypalLabelStyle": "none",
            "paypalFieldChrome": "underline",
            "paypalFieldFontSize": "sm",
            "paypalFieldWeight": "semibold",
            "paypalFocusRing": "subtle",
            "paypalValidTint": "true",
        });
        let b = decode_branding(Some(&source_with(paypal_only.clone())));
        assert_eq!(b.epayouts_card_layout, PaypalCardLayout::Stacked);
        assert_eq!(b.epayouts_label_style, PaypalLabelStyle::None);
        assert_eq!(b.epayouts_field_chrome, CardFieldChrome::Underline);
        assert_eq!(b.epayouts_field_font_size, CardFieldFontSize::Sm);
        assert_eq!(b.epayouts_field_weight, CardFieldWeight::Semibold);
        assert_eq!(b.epayouts_focus_ring, CardFocusRing::Subtle);
        assert!(b.epayouts_valid_tint);

        let imported = parse_imported_branding(&paypal_only);
        assert_eq!(imported.epayouts_card_layout, PaypalCardLayout::Stacked);
        assert!(imported.epayouts_valid_tint);

        let mut own = paypal_only;
        own["epayoutsCardLayout"] = json!("split");
        own["epayoutsValidTint"] = json!("false");
        let b = decode_branding(Some(&source_with(own)));
        assert_eq!(b.epayouts_card_layout, PaypalCardLayout::Split);
        assert!(!b.epayouts_valid_tint);
        assert_eq!(b.paypal_card_layout, PaypalCardLayout::Stacked);
    }

    #[test]
    fn encode_branding_writes_the_new_keys_and_round_trips() {
        let mut b = default_branding();
        b.cancel_link_style = CancelLinkStyle::Button;
        b.stripe_theme = StripeTheme::Flat;
        b.paypal_valid_tint = true;
        b.epayouts_card_layout = PaypalCardLayout::Stacked;
        b.nomupay_apple_pay_button_type = ApplePayButtonType::TopUp;
        b.whop_accent_color = WhopAccentColor::Jade;
        b.whop_selection = WhopSelection::Radio;
        b.notices = vec![
            CheckoutNotice::new(
                "ship",
                NoticeSection::Payment,
                NoticeIcon::Truck,
                "Free shipping",
            )
            .translation("de", "Kostenloser Versand"),
        ];

        let e = encode_branding(&b);
        let bag = &e.sdk_ui_rules[BRANDING_GROUP_KEY];
        assert_eq!(bag["cancelLinkEnabled"], "true");
        assert_eq!(bag["cancelLinkStyle"], "button");
        assert_eq!(bag["stripeTheme"], "flat");
        assert_eq!(bag["paypalValidTint"], "true");
        assert_eq!(bag["epayoutsCardLayout"], "stacked");
        assert_eq!(bag["nomupayApplePayButtonType"], "top-up");
        assert_eq!(bag["whopAccentColor"], "jade");
        assert_eq!(bag["whopSelection"], "radio");
        assert_eq!(
            bag["notices"],
            r#"[{"id":"ship","section":"payment","icon":"truck","label":"Free shipping","labelTranslations":{"de":"Kostenloser Versand"}}]"#
        );
        assert!(
            !bag.contains_key("trustBadges"),
            "an empty badge list is not written"
        );

        let source: BrandingSource =
            serde_json::from_value(serde_json::to_value(&e).unwrap()).unwrap();
        assert_eq!(decode_branding(Some(&source)), b);

        // The export envelope carries the same fields and imports back.
        let export = build_branding_export_at(&b, 0);
        let raw = serde_json::to_value(&export).unwrap();
        assert_eq!(raw["branding"]["whopAccentColor"], "jade");
        assert_eq!(parse_imported_branding(&raw), b);
    }

    /// The key's presence is the shop's decision. Mutation: skip writing
    /// `notices` when the list is empty and the second decode re-adds the
    /// defaults.
    #[test]
    fn removing_every_notice_survives_a_save() {
        let mut b = default_branding();
        b.notices.clear();
        let bag = encode_branding(&b).sdk_ui_rules[BRANDING_GROUP_KEY].clone();
        assert_eq!(bag["notices"], "[]");
        let source = source_with(serde_json::to_value(&bag).unwrap());
        let decoded = decode_branding(Some(&source));
        assert!(decoded.notices.is_empty());
        assert!(decoded.trust_badges.is_empty());
    }

    /// JavaScript's `trim` strips U+FEFF, so a U+FEFF-only label is blank
    /// and takes no section slot. Mutation: put `str::trim` back at the label
    /// check — the blank notice takes a slot and the third real one is
    /// dropped.
    #[test]
    fn a_bom_only_notice_takes_no_section_slot() {
        let raw = json!([
            {"section": "summary", "label": "\u{FEFF}"},
            {"section": "summary", "label": "One"},
            {"section": "summary", "label": "Two"},
            {"section": "summary", "label": "Three"},
        ]);
        let notices = parse_notices_loose(Some(&raw)).unwrap();
        let labels: Vec<&str> = notices.iter().map(|n| n.label.as_str()).collect();
        assert_eq!(labels, ["One", "Two", "Three"]);
    }

    /// A U+FEFF-only translation is blank to JavaScript, so it is dropped.
    /// Mutation: put `str::trim` back in `parse_notice_translations` — the
    /// translation survives.
    #[test]
    fn a_bom_only_translation_is_dropped() {
        let raw = json!([{
            "section": "payment",
            "label": "Secure",
            "labelTranslations": {"de": "\u{FEFF}", "fr": "Sécurisé"}
        }]);
        let mut notices = parse_notices_loose(Some(&raw)).unwrap();
        assert_eq!(notices[0].label_translations.len(), 1);
        assert!(notices[0].label_translations.contains_key("fr"));
        // The encoder applies the same rule to a notice built in code.
        // Mutation: put `str::trim` back in `encode_notices` — `de` is sent.
        notices[0]
            .label_translations
            .insert("de".to_string(), "\u{FEFF}".to_string());
        let encoded: Value = serde_json::from_str(&encode_notices(&notices)).unwrap();
        assert!(encoded[0]["labelTranslations"].get("de").is_none());
        assert_eq!(encoded[0]["labelTranslations"]["fr"], "Sécurisé");
    }

    /// JavaScript's `trim` keeps U+0085 (NEL), which `str::trim` strips. A
    /// NEL-only label is therefore not blank, and a shown label keeps its NEL
    /// ends. Mutation: use `str::trim` in `js_trim` — both assertions fail.
    #[test]
    fn a_nel_surrounded_label_is_not_trimmed() {
        assert_eq!(js_trim("\u{0085}Fast\u{0085}"), "\u{0085}Fast\u{0085}");
        assert_eq!(js_trim("\u{FEFF} Fast\u{3000}"), "Fast");
        let raw = json!([
            {"section": "summary", "label": "\u{0085}"},
            {"section": "summary", "label": "\u{0085}Fast\u{0085}"},
        ]);
        let notices = parse_notices_loose(Some(&raw)).unwrap();
        assert_eq!(
            notices.len(),
            2,
            "a NEL-only label is not blank to JavaScript"
        );
        let shown = shown_notices(&notices, NoticeSection::Summary, None);
        assert_eq!(shown[1].text, "\u{0085}Fast\u{0085}");
    }

    #[test]
    fn decode_notices_normalizes_and_caps() {
        let long = "x".repeat(NOTICE_LABEL_MAX_LENGTH + 5);
        let raw = json!([
            {"id": "a b!", "section": "summary", "icon": "star", "label": long},
            {"id": "ab", "section": "summary", "icon": "nope", "label": "Dup id"},
            {"section": "nowhere", "label": "Unknown section"},
            {"section": "summary", "label": "Fourth, dropped"},
            {"section": "payment", "label": "   ", "labelTranslations": {"de": "Nur Deutsch", "fr": " "}},
            {"section": "payment", "label": "", "labelTranslations": {}},
            "not-an-object",
        ])
        .to_string();
        let notices = decode_notices(Some(&raw)).unwrap();
        assert_eq!(notices.len(), 4);

        assert_eq!(notices[0].id, "ab", "cleaned to [A-Za-z0-9_-]");
        assert_eq!(notices[0].icon, NoticeIcon::Star);
        assert_eq!(notices[0].label.chars().count(), NOTICE_LABEL_MAX_LENGTH);
        assert_eq!(notices[1].id, "notice-2", "a repeated id is replaced");
        assert_eq!(notices[1].icon, NOTICE_ICON_FALLBACK);
        assert_eq!(notices[2].section, NoticeSection::Summary);
        assert_eq!(notices[2].id, "notice-3");
        // Three in `summary` already: the fourth is dropped.
        assert_eq!(notices[3].section, NoticeSection::Payment);
        assert_eq!(
            notices[3].label_translations.len(),
            1,
            "blank override dropped"
        );

        assert_eq!(notice_text(&notices[3], Some("de-AT")), "Nur Deutsch");
        assert!(notice_text(&notices[3], Some("en")).trim().is_empty());
        let shown = shown_notices(&notices, NoticeSection::Payment, Some("en"));
        assert!(shown.is_empty(), "no text in this locale, nothing drawn");
        assert_eq!(notices_in(&notices, NoticeSection::Summary).len(), 3);

        assert_eq!(decode_notices(None), None);
        assert_eq!(decode_notices(Some("{}")), None, "not an array");
        assert_eq!(decode_notices(Some("broken")), None);
        assert_eq!(decode_notices(Some("[]")), Some(Vec::new()));
        assert_eq!(
            parse_notices_loose(Some(&json!([{"label": "Inline"}])))
                .unwrap()
                .len(),
            1
        );
    }

    /// Mutation: make `is_default_badge_set` return `false` for the stock or
    /// theme-tinted pair, and an untouched shop keeps its badges instead of
    /// getting notices.
    #[test]
    fn stock_badges_migrate_to_notices_and_configured_ones_stay() {
        let migrated = resolve_notices_and_badges(Some(DEFAULT_BADGES_DARK.clone()), None);
        assert!(migrated.trust_badges.is_empty());
        assert_eq!(migrated.notices, *DEFAULT_NOTICES);

        // A theme colouring: text #1e4feb, on a white surface mixed 8 % and
        // 30 % towards it.
        let tinted = vec![
            TrustBadge::new("secure", "Secure", "#1e4feb", "#edf1fd").border_color("#bccaf9"),
            TrustBadge::new("ssl", "256-bit SSL", "#1e4feb", "#edf1fd").border_color("#bccaf9"),
        ];
        assert!(is_default_badge_set(&tinted));

        let mut edited = DEFAULT_BADGES.clone();
        edited[0].label = "Safe".to_string();
        assert!(!is_default_badge_set(&edited));
        let kept = resolve_notices_and_badges(Some(edited.clone()), None);
        assert_eq!(kept.trust_badges, edited);
        assert!(kept.notices.is_empty());

        let mut recoloured = DEFAULT_BADGES.clone();
        recoloured[1].text_color = "#ff0000".to_string();
        assert!(!is_default_badge_set(&recoloured));
        assert!(!is_default_badge_set(&[]));

        // Saved notices decide, whatever the badges say.
        let decided = resolve_notices_and_badges(Some(DEFAULT_BADGES.clone()), Some(Vec::new()));
        assert_eq!(decided.trust_badges, *DEFAULT_BADGES);
        assert!(decided.notices.is_empty());
    }

    // --- enum wire values ------------------------------------------------

    #[test]
    fn enum_wire_values_survive_serde() {
        assert_eq!(
            serde_json::to_string(&FontFamily::DmSans).unwrap(),
            "\"dm-sans\""
        );
        assert_eq!(
            serde_json::to_string(&PaymentLayout::SpacedAccordion).unwrap(),
            "\"spaced_accordion\""
        );
        assert_eq!(
            serde_json::from_str::<FontFamily>("\"jetbrains-mono\"").unwrap(),
            FontFamily::JetbrainsMono
        );
        assert!(serde_json::from_str::<FontFamily>("\"comic-sans\"").is_err());
        assert_eq!(NonPillRadius::from_wire("pill"), None);
        assert_eq!(CornerRadius::from_wire("pill"), Some(CornerRadius::Pill));
        assert_eq!(
            CornerRadius::from(NonPillRadius::Large),
            CornerRadius::Large
        );
        assert_eq!(LogoShape::Circle.to_string(), "circle");
    }
}