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

use std::collections::BTreeMap;

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

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

/// How the focused external checkout charges a paned method. Decided
/// server-side; the browser never picks.
///
/// - [`Wallet`](NativePaneRail::Wallet) — the method rides inside Stripe's
///   `card` rail (Apple Pay, Google Pay, Link). The focused view charges the
///   **same** PaymentIntent the embedded checkout already holds, so no second
///   intent is ever created.
/// - [`Redirect`](NativePaneRail::Redirect) — the method has its own
///   `payment_method_types[]` entry. The focused view confirms through the
///   standard `/payments/{id}/confirm` rail and follows
///   `next_action.redirect_to_url`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NativePaneRail {
    Wallet,
    Redirect,
}

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

/// Where a pane's tile is offered. Wallet rail only — a redirect pane is
/// suppressed server-side, before any render knows whether it is framed, so
/// `embedded_only` there would leave the method unpayable at top level and the
/// router forces it back to `always`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum NativePaneVisibility {
    #[default]
    Always,
    EmbeddedOnly,
}

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

    /// Parse a stored wire value. Anything unrecognised degrades to
    /// [`Always`](Self::Always) rather than failing — matching the TypeScript
    /// codec.
    pub fn from_wire(raw: Option<&Value>) -> Self {
        match raw.and_then(Value::as_str) {
            Some("embedded_only") => Self::EmbeddedOnly,
            _ => Self::Always,
        }
    }
}

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

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

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

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

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

/// One resolved native pane as the buyer-facing checkout receives it on the
/// payment-link payload (`native_panes`). Labels are already localized for the
/// render's locale and icons already sanitized.
///
/// `rail` stays a plain string (`"wallet"` / `"redirect"`) so an unknown future
/// rail degrades readably instead of failing deserialisation.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct NativePaneView {
    pub method: String,
    /// `"wallet"` or `"redirect"` — see [`NativePaneRail`].
    pub rail: String,
    pub label: String,
    pub sublabel: String,
    pub category: String,
    pub icon: Option<String>,
    pub icon_svg: Option<String>,
    pub display_order: i64,
    /// Redirect rail only — echo verbatim on confirm, never derive.
    pub payment_method: Option<String>,
    /// Redirect rail only — echo verbatim on confirm, never derive.
    pub payment_method_type: Option<String>,
    /// Redirect rail only — echo verbatim on confirm, never derive.
    pub payment_method_data: Option<Value>,
    /// The confirm body needs the buyer's country: merged into
    /// `billing.address.country` and echoed into the single
    /// `payment_method_data` variant's `billing_country`.
    pub requires_billing_country: Option<bool>,
    /// `true` when the tile is only offered inside an iframe. Wallet rail only.
    pub embedded_only: Option<bool>,
    /// How the embedded checkout opens this tile's focused view (`"tab"` /
    /// `"popup"`). Absent on payloads from older backends — treat as `"tab"`.
    /// A plain string for the same reason as `rail`: an unknown future target
    /// degrades readably instead of failing deserialisation.
    pub open_in: Option<String>,
    /// Any additional fields present on the wire but not modeled here.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

/// One catalog entry: a method that may be promoted to a native pane, with the
/// defaults the editor shows as placeholders.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NativePaneMethodInfo {
    /// Catalog key (`apple_pay`, `klarna`, …).
    pub key: &'static str,
    /// How the focused checkout charges the method.
    pub rail: NativePaneRail,
    /// Catalog default label, shown as the editor's placeholder.
    pub default_label: &'static str,
    /// Catalog default sub-text.
    pub default_sublabel: &'static str,
    /// Catalog default section.
    pub default_category: &'static str,
    /// Catalog default icon key.
    pub default_icon: &'static str,
}

/// Methods that may be promoted to a native pane.
///
/// **The router owns this list** — `core::payment_link::native_panes::CATALOG`
/// in delopay-backend. This is a mirror so SDK consumers can validate or offer
/// the promotable methods without a round-trip.
pub const STRIPE_NATIVE_PANE_METHODS: &[NativePaneMethodInfo] = &[
    NativePaneMethodInfo {
        key: "apple_pay",
        rail: NativePaneRail::Wallet,
        default_label: "Apple Pay",
        default_sublabel: "Pay with Apple Pay",
        default_category: "wallet",
        default_icon: "apple",
    },
    NativePaneMethodInfo {
        key: "google_pay",
        rail: NativePaneRail::Wallet,
        default_label: "Google Pay",
        default_sublabel: "Pay with Google Pay",
        default_category: "wallet",
        default_icon: "google",
    },
    NativePaneMethodInfo {
        key: "link",
        rail: NativePaneRail::Wallet,
        default_label: "Link",
        default_sublabel: "Pay with saved details",
        default_category: "wallet",
        default_icon: "wallet",
    },
    NativePaneMethodInfo {
        key: "klarna",
        rail: NativePaneRail::Redirect,
        default_label: "Klarna",
        default_sublabel: "Pay later or in instalments",
        default_category: "bnpl",
        default_icon: "bnpl",
    },
    NativePaneMethodInfo {
        key: "affirm",
        rail: NativePaneRail::Redirect,
        default_label: "Affirm",
        default_sublabel: "Pay over time",
        default_category: "bnpl",
        default_icon: "bnpl",
    },
    NativePaneMethodInfo {
        key: "ideal",
        rail: NativePaneRail::Redirect,
        default_label: "iDEAL",
        default_sublabel: "Pay from your bank",
        default_category: "bank_redirect",
        default_icon: "bank",
    },
    // eps / p24 / bancontact were removed from the router catalog: Stripe
    // hard-requires billing fields the focused checkout never collects (full
    // name for EPS/Bancontact, email for Przelewy24), so their tiles could
    // never succeed. They may return behind billing-aware gating.
    NativePaneMethodInfo {
        key: "alipay",
        rail: NativePaneRail::Redirect,
        default_label: "Alipay",
        default_sublabel: "Pay with Alipay",
        default_category: "wallet",
        default_icon: "wallet",
    },
    NativePaneMethodInfo {
        key: "revolut_pay",
        rail: NativePaneRail::Redirect,
        default_label: "Revolut Pay",
        default_sublabel: "Pay with Revolut",
        default_category: "wallet",
        default_icon: "wallet",
    },
    NativePaneMethodInfo {
        key: "amazon_pay",
        rail: NativePaneRail::Redirect,
        default_label: "Amazon Pay",
        default_sublabel: "Pay with Amazon",
        default_category: "wallet",
        default_icon: "wallet",
    },
];

/// Built-in tile icon keys the buyer-facing checkout ships a glyph for.
pub const NATIVE_PANE_ICON_KEYS: &[&str] =
    &["wallet", "card", "bank", "apple", "google", "bnpl", "cash"];

/// Section keys the checkout knows a translated header for.
pub const NATIVE_PANE_CATEGORY_KEYS: &[&str] = &[
    "wallet",
    "card",
    "bnpl",
    "bank_redirect",
    "bank_transfer",
    "cash",
];

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

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

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

/// The catalog entry for `method`, or `None` when it is not promotable.
pub fn native_pane_method_info(method: &str) -> Option<&'static NativePaneMethodInfo> {
    STRIPE_NATIVE_PANE_METHODS.iter().find(|m| m.key == method)
}

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

/// A fresh enabled row for `method` with the catalog's default icon.
pub fn default_native_pane(method: &str) -> StripeNativePane {
    let info = native_pane_method_info(method);
    StripeNativePane {
        method: method.to_owned(),
        enabled: true,
        label: String::new(),
        label_translations: BTreeMap::new(),
        sublabel: None,
        sublabel_translations: BTreeMap::new(),
        category: String::new(),
        icon: info.map(|i| i.default_icon).unwrap_or_default().to_owned(),
        icon_svg: String::new(),
        display_order: 0,
        visibility: NativePaneVisibility::Always,
        open_in: NativePaneOpenTarget::Tab,
    }
}

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

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

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

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

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

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

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

/// Inputs for [`focused_checkout_url`].
#[derive(Debug, Clone, Copy)]
pub struct FocusedCheckoutUrlParams<'a> {
    /// Base URL of the DeloPay hosted checkout, e.g.
    /// [`https://checkout.delopay.net`](crate::CHECKOUT_URL).
    pub checkout_base_url: &'a str,
    pub merchant_id: &'a str,
    pub payment_id: &'a str,
    /// Native-pane method key to focus on (`apple_pay`, `klarna`, …).
    pub method: &'a str,
    /// Optional buyer locale, forwarded as `?locale=`.
    pub locale: Option<&'a str>,
    /// Set when the merchant's checkout-custom-field answers are already
    /// persisted on the payment — forwarded as `cf=1` so the focused view
    /// skips asking a second time. Purely a UI hint: the values live on the
    /// intent either way, and the backend only accepts the merchant's
    /// configured field keys from a client, so a wrongly-set flag can at worst
    /// skip an informational prompt.
    pub custom_fields_collected: bool,
}

/// Build the link to the **focused single-method checkout**: the DeloPay hosted
/// checkout rendered with one payment method, one button, no picker.
///
/// Two callers: the embedded checkout, which opens this in a new tab when a
/// buyer clicks a native pane tile, and a merchant running their own checkout,
/// who puts it behind their own button — the same mechanism without an iframe.
///
/// Open it **at the top level** (a new tab or a full-page navigation). The
/// whole point is that the top-level domain is the registered payment method
/// domain; rendering it in an iframe puts you back where you started. If you
/// open it with `window.open`, call that synchronously inside the click handler
/// or the popup blocker will eat it, and make sure any iframe you render
/// DeloPay in permits popups (`allow-popups`, plus
/// `allow-popups-to-escape-sandbox` under a restrictive `sandbox`).
pub fn focused_checkout_url(params: &FocusedCheckoutUrlParams<'_>) -> String {
    let base = params.checkout_base_url.trim_end_matches('/');
    let mut url = format!(
        "{base}/pay/{}/{}?pane={}",
        encode_path_segment(params.merchant_id),
        encode_path_segment(params.payment_id),
        encode_query_value(params.method),
    );
    if let Some(locale) = params.locale.filter(|l| !l.is_empty()) {
        url.push_str("&locale=");
        url.push_str(&encode_query_value(locale));
    }
    if params.custom_fields_collected {
        url.push_str("&cf=1");
    }
    url
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    #[test]
    fn encode_omits_empty_optional_fields() {
        let encoded = encode_native_panes(&[default_native_pane("apple_pay")]);
        let row = encoded[0].as_object().unwrap();
        assert!(!row.contains_key("label"));
        assert!(!row.contains_key("sublabel"));
        assert!(!row.contains_key("category"));
        assert!(!row.contains_key("icon_svg"));
        assert_eq!(row["method"], "apple_pay");
    }

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

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

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

    #[test]
    fn visibility_defaults_to_always_and_round_trips_embedded_only() {
        let decoded = decode_native_panes(&json!([{"method": "apple_pay"}])).unwrap();
        assert_eq!(decoded[0].visibility, NativePaneVisibility::Always);
        let mut pane = default_native_pane("apple_pay");
        pane.visibility = NativePaneVisibility::EmbeddedOnly;
        let round_tripped =
            decode_native_panes(&encode_native_panes(std::slice::from_ref(&pane))).unwrap();
        assert_eq!(
            round_tripped[0].visibility,
            NativePaneVisibility::EmbeddedOnly
        );
    }

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

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

    #[test]
    fn open_in_defaults_to_tab_and_round_trips_popup() {
        let decoded = decode_native_panes(&json!([{"method": "apple_pay"}])).unwrap();
        assert_eq!(decoded[0].open_in, NativePaneOpenTarget::Tab);
        let mut pane = default_native_pane("apple_pay");
        pane.open_in = NativePaneOpenTarget::Popup;
        let round_tripped =
            decode_native_panes(&encode_native_panes(std::slice::from_ref(&pane))).unwrap();
        assert_eq!(round_tripped[0].open_in, NativePaneOpenTarget::Popup);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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