@movmo_app/payments 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,8 +4,8 @@ PCI-safe card capture for Movmo UIs (`accounts-ui`, `flights-ui`) and airline pa
4
4
 
5
5
  ## What's in the box
6
6
 
7
- - **`<MovmoCardForm />`** — drop-in card-capture form (PCI-safe number + CVV iframes, single cardholder-name input, combined `MM / YY` expiry). The Save button is gated on Spreedly field validity; opt into auto-save via the `autoSave` prop. Tokenizes the card, then calls the Movmo API to save the vaulted card to the user's profile. Renders the detected card brand inline (Visa / MC / Amex / Discover) as the user types.
8
- - **`<PaymentMethodsManager />`** — full saved-cards UI: lists existing cards, lets the user set default / remove, and embeds `<MovmoCardForm />` for adding a new one. Renders a payment-type selector (Credit card + disabled "Coming soon" rows for PayPal / GooglePay / Klarna / ACH) by default; pass `paymentTypeSelector={false}` to hide it. Auto-saves the first card by default (`autoSaveFirstCard={true}` — matches flights-ui UX). Optional selection mode (`selectedId` + `onSelect`) for checkout flows.
7
+ - **`<MovmoCardForm />`** — drop-in card-capture form (PCI-safe number + CVV iframes, single cardholder-name input, combined `MM / YY` expiry). The Save button is gated on Spreedly field validity; opt into auto-save via the `autoSave` prop. Tokenizes the card, then calls the Movmo API to save the vaulted card to the user's profile. Renders the detected card brand inline (Visa / MC / Amex / Discover) as the user types. A field is only marked invalid once the user has left it ("touched") — inline messages appear under the number shell, one shared message under the expiry/CVV/postal row (whichever of those is invalid first in visual order), and under the name field, each wired to its input via `aria-describedby`. While `autoSave` is on, a live-region status line reads "Saving card…" during the save and otherwise nudges with the form's built-in hint copy ("Your card saves automatically once all fields are complete.") while required fields are still missing. Postal-code validation is international-friendly (3–10 letters/digits/spaces/hyphens, not US-only); ZIP+4 auto-hyphenation only kicks in for a complete 9-digit numeric US ZIP or a hyphen the user typed themselves. Pass `onValidationChange?: (state: CardValidationState) => void` to observe live validity (`{ valid, missing, touchedInvalid }`, field keys only — no PII) without wiring your own field-by-field logic.
8
+ - **`<PaymentMethodsManager />`** — full saved-cards UI: lists existing cards, lets the user set default / remove, and embeds `<MovmoCardForm />` for adding a new one. Renders a payment-type selector (Credit card + disabled "Coming soon" rows for PayPal / GooglePay / Klarna / ACH) by default; pass `paymentTypeSelector={false}` to hide it. Auto-saves the first card by default (`autoSaveFirstCard={true}` — matches flights-ui UX). Optional selection mode (`selectedId` + `onSelect`) for checkout flows. `onEvent` now also fires `'validation_error'` (`{ field_count, fields }`) once per touched-invalid streak on the embedded card form, re-arming once the user clears it.
9
9
  - **`useMovmoCardFields()`** — lower-level hook for partners composing their own form layout. Exposes per-field `validity` + detected `brand` so the consumer can gate its own submit button and render its own brand icon.
10
10
  - **`useUserPaymentMethods(userId)`** — fetches the saved-cards list with `{ items, status, error, refetch }`. Useful standalone (e.g., showing the selected card's last4 in a checkout summary).
11
11
  - **`useDeletePaymentMethod(userId)`** — exposes `{ deletePaymentMethod, status, error }`. Resolves on success, rejects on failure so callers can roll back optimistic updates.
@@ -108,3 +108,11 @@ pnpm --filter @movmo_app/payments storybook # → http://localhost:6007
108
108
  ```
109
109
 
110
110
  Storybook is the primary way to exercise the components on a laptop: it mocks both the underlying vault SDK and the `monolith-api` calls, so no vault credentials, no live backend, and no real card data are required. See `src/MovmoCardForm/__docs__/MovmoCardForm.stories.tsx` and `src/PaymentMethodsManager/__docs__/PaymentMethodsManager.stories.tsx` for the full state matrices.
111
+
112
+ ## Screenshot review
113
+
114
+ ```bash
115
+ pnpm --filter @movmo_app/payments screenshots
116
+ ```
117
+
118
+ Boots Storybook on port 6007 and drives it with Playwright to capture PNGs of the auto-save/validation stories into `screenshots/out/` for visual review — not a CI suite, no pixel assertions. The whole `screenshots/` directory (including the spec itself) is local-only and gitignored — it isn't part of the published package or the repo's git history. The canonical copy of the spec lives at `brain/scripts/payments-screenshot-capture.spec.ts`; copy it into `screenshots/capture.spec.ts` before running the command above. See `playwright.screenshots.config.ts` for the harness config.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Jt=Object.defineProperty;var Zt=(t,r,s)=>r in t?Jt(t,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[r]=s;var lt=(t,r,s)=>Zt(t,typeof r!="symbol"?r+"":r,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react");var pt={exports:{}},qe={};/**
1
+ "use strict";var ar=Object.defineProperty;var nr=(e,r,n)=>r in e?ar(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n;var qe=(e,r,n)=>nr(e,typeof r!="symbol"?r+"":r,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react");var vt={exports:{}},et={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.min.js
4
4
  *
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var wt;function Xt(){if(wt)return qe;wt=1;var t=n,r=Symbol.for("react.element"),s=Symbol.for("react.fragment"),o=Object.prototype.hasOwnProperty,l=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,c={key:!0,ref:!0,__self:!0,__source:!0};function f(x,m,R){var w,p={},v=null,E=null;R!==void 0&&(v=""+R),m.key!==void 0&&(v=""+m.key),m.ref!==void 0&&(E=m.ref);for(w in m)o.call(m,w)&&!c.hasOwnProperty(w)&&(p[w]=m[w]);if(x&&x.defaultProps)for(w in m=x.defaultProps,m)p[w]===void 0&&(p[w]=m[w]);return{$$typeof:r,type:x,key:v,ref:E,props:p,_owner:l.current}}return qe.Fragment=s,qe.jsx=f,qe.jsxs=f,qe}var Ke={};/**
9
+ */var Ct;function sr(){if(Ct)return et;Ct=1;var e=s,r=Symbol.for("react.element"),n=Symbol.for("react.fragment"),o=Object.prototype.hasOwnProperty,l=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,c={key:!0,ref:!0,__self:!0,__source:!0};function m(v,h,j){var _,w={},C=null,x=null;j!==void 0&&(C=""+j),h.key!==void 0&&(C=""+h.key),h.ref!==void 0&&(x=h.ref);for(_ in h)o.call(h,_)&&!c.hasOwnProperty(_)&&(w[_]=h[_]);if(v&&v.defaultProps)for(_ in h=v.defaultProps,h)w[_]===void 0&&(w[_]=h[_]);return{$$typeof:r,type:v,key:C,ref:x,props:w,_owner:l.current}}return et.Fragment=n,et.jsx=m,et.jsxs=m,et}var tt={};/**
10
10
  * @license React
11
11
  * react-jsx-runtime.development.js
12
12
  *
@@ -14,18 +14,18 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */var Et;function Qt(){return Et||(Et=1,process.env.NODE_ENV!=="production"&&function(){var t=n,r=Symbol.for("react.element"),s=Symbol.for("react.portal"),o=Symbol.for("react.fragment"),l=Symbol.for("react.strict_mode"),c=Symbol.for("react.profiler"),f=Symbol.for("react.provider"),x=Symbol.for("react.context"),m=Symbol.for("react.forward_ref"),R=Symbol.for("react.suspense"),w=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),v=Symbol.for("react.lazy"),E=Symbol.for("react.offscreen"),T=Symbol.iterator,se="@@iterator";function M(e){if(e===null||typeof e!="object")return null;var i=T&&e[T]||e[se];return typeof i=="function"?i:null}var C=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function b(e){{for(var i=arguments.length,d=new Array(i>1?i-1:0),y=1;y<i;y++)d[y-1]=arguments[y];Y("error",e,d)}}function Y(e,i,d){{var y=C.ReactDebugCurrentFrame,F=y.getStackAddendum();F!==""&&(i+="%s",d=d.concat([F]));var O=d.map(function(k){return String(k)});O.unshift("Warning: "+i),Function.prototype.apply.call(console[e],console,O)}}var ee=!1,ve=!1,ue=!1,te=!1,oe=!1,D;D=Symbol.for("react.module.reference");function j(e){return!!(typeof e=="string"||typeof e=="function"||e===o||e===c||oe||e===l||e===R||e===w||te||e===E||ee||ve||ue||typeof e=="object"&&e!==null&&(e.$$typeof===v||e.$$typeof===p||e.$$typeof===f||e.$$typeof===x||e.$$typeof===m||e.$$typeof===D||e.getModuleId!==void 0))}function fe(e,i,d){var y=e.displayName;if(y)return y;var F=i.displayName||i.name||"";return F!==""?d+"("+F+")":d}function Ee(e){return e.displayName||"Context"}function S(e){if(e==null)return null;if(typeof e.tag=="number"&&b("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case o:return"Fragment";case s:return"Portal";case c:return"Profiler";case l:return"StrictMode";case R:return"Suspense";case w:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case x:var i=e;return Ee(i)+".Consumer";case f:var d=e;return Ee(d._context)+".Provider";case m:return fe(e,e.render,"ForwardRef");case p:var y=e.displayName||null;return y!==null?y:S(e.type)||"Memo";case v:{var F=e,O=F._payload,k=F._init;try{return S(k(O))}catch{return null}}}return null}var g=Object.assign,h=0,N,U,K,me,G,re,H;function W(){}W.__reactDisabledLog=!0;function Z(){{if(h===0){N=console.log,U=console.info,K=console.warn,me=console.error,G=console.group,re=console.groupCollapsed,H=console.groupEnd;var e={configurable:!0,enumerable:!0,value:W,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}h++}}function je(){{if(h--,h===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:g({},e,{value:N}),info:g({},e,{value:U}),warn:g({},e,{value:K}),error:g({},e,{value:me}),group:g({},e,{value:G}),groupCollapsed:g({},e,{value:re}),groupEnd:g({},e,{value:H})})}h<0&&b("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var pe=C.ReactCurrentDispatcher,he;function ie(e,i,d){{if(he===void 0)try{throw Error()}catch(F){var y=F.stack.trim().match(/\n( *(at )?)/);he=y&&y[1]||""}return`
18
- `+he+e}}var ae=!1,_e;{var Fe=typeof WeakMap=="function"?WeakMap:Map;_e=new Fe}function le(e,i){if(!e||ae)return"";{var d=_e.get(e);if(d!==void 0)return d}var y;ae=!0;var F=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var O;O=pe.current,pe.current=null,Z();try{if(i){var k=function(){throw Error()};if(Object.defineProperty(k.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(k,[])}catch(ce){y=ce}Reflect.construct(e,[],k)}else{try{k.call()}catch(ce){y=ce}e.call(k.prototype)}}else{try{throw Error()}catch(ce){y=ce}e()}}catch(ce){if(ce&&y&&typeof ce.stack=="string"){for(var _=ce.stack.split(`
19
- `),ne=y.stack.split(`
20
- `),V=_.length-1,q=ne.length-1;V>=1&&q>=0&&_[V]!==ne[q];)q--;for(;V>=1&&q>=0;V--,q--)if(_[V]!==ne[q]){if(V!==1||q!==1)do if(V--,q--,q<0||_[V]!==ne[q]){var ye=`
21
- `+_[V].replace(" at new "," at ");return e.displayName&&ye.includes("<anonymous>")&&(ye=ye.replace("<anonymous>",e.displayName)),typeof e=="function"&&_e.set(e,ye),ye}while(V>=1&&q>=0);break}}}finally{ae=!1,pe.current=O,je(),Error.prepareStackTrace=F}var Oe=e?e.displayName||e.name:"",Pe=Oe?ie(Oe):"";return typeof e=="function"&&_e.set(e,Pe),Pe}function J(e,i,d){return le(e,!1)}function ge(e){var i=e.prototype;return!!(i&&i.isReactComponent)}function z(e,i,d){if(e==null)return"";if(typeof e=="function")return le(e,ge(e));if(typeof e=="string")return ie(e);switch(e){case R:return ie("Suspense");case w:return ie("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case m:return J(e.render);case p:return z(e.type,i,d);case v:{var y=e,F=y._payload,O=y._init;try{return z(O(F),i,d)}catch{}}}return""}var xe=Object.prototype.hasOwnProperty,Se={},we=C.ReactDebugCurrentFrame;function X(e){if(e){var i=e._owner,d=z(e.type,e._source,i?i.type:null);we.setExtraStackFrame(d)}else we.setExtraStackFrame(null)}function P(e,i,d,y,F){{var O=Function.call.bind(xe);for(var k in e)if(O(e,k)){var _=void 0;try{if(typeof e[k]!="function"){var ne=Error((y||"React class")+": "+d+" type `"+k+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[k]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw ne.name="Invariant Violation",ne}_=e[k](i,k,y,d,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(V){_=V}_&&!(_ instanceof Error)&&(X(F),b("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",y||"React class",d,k,typeof _),X(null)),_ instanceof Error&&!(_.message in Se)&&(Se[_.message]=!0,X(F),b("Failed %s type: %s",d,_.message),X(null))}}}var $=Array.isArray;function A(e){return $(e)}function de(e){{var i=typeof Symbol=="function"&&Symbol.toStringTag,d=i&&e[Symbol.toStringTag]||e.constructor.name||"Object";return d}}function ot(e){try{return Je(e),!1}catch{return!0}}function Je(e){return""+e}function We(e){if(ot(e))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",de(e)),Je(e)}var Ze=C.ReactCurrentOwner,Xe={key:!0,ref:!0,__self:!0,__source:!0},Le,Qe;function ze(e){if(xe.call(e,"ref")){var i=Object.getOwnPropertyDescriptor(e,"ref").get;if(i&&i.isReactWarning)return!1}return e.ref!==void 0}function et(e){if(xe.call(e,"key")){var i=Object.getOwnPropertyDescriptor(e,"key").get;if(i&&i.isReactWarning)return!1}return e.key!==void 0}function tt(e,i){typeof e.ref=="string"&&Ze.current}function rt(e,i){{var d=function(){Le||(Le=!0,b("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",i))};d.isReactWarning=!0,Object.defineProperty(e,"key",{get:d,configurable:!0})}}function Me(e,i){{var d=function(){Qe||(Qe=!0,b("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",i))};d.isReactWarning=!0,Object.defineProperty(e,"ref",{get:d,configurable:!0})}}var Be=function(e,i,d,y,F,O,k){var _={$$typeof:r,type:e,key:i,ref:d,props:k,_owner:O};return _._store={},Object.defineProperty(_._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(_,"_self",{configurable:!1,enumerable:!1,writable:!1,value:y}),Object.defineProperty(_,"_source",{configurable:!1,enumerable:!1,writable:!1,value:F}),Object.freeze&&(Object.freeze(_.props),Object.freeze(_)),_};function Ye(e,i,d,y,F){{var O,k={},_=null,ne=null;d!==void 0&&(We(d),_=""+d),et(i)&&(We(i.key),_=""+i.key),ze(i)&&(ne=i.ref,tt(i,F));for(O in i)xe.call(i,O)&&!Xe.hasOwnProperty(O)&&(k[O]=i[O]);if(e&&e.defaultProps){var V=e.defaultProps;for(O in V)k[O]===void 0&&(k[O]=V[O])}if(_||ne){var q=typeof e=="function"?e.displayName||e.name||"Unknown":e;_&&rt(k,q),ne&&Me(k,q)}return Be(e,_,ne,F,y,Ze.current,k)}}var ke=C.ReactCurrentOwner,at=C.ReactDebugCurrentFrame;function Re(e){if(e){var i=e._owner,d=z(e.type,e._source,i?i.type:null);at.setExtraStackFrame(d)}else at.setExtraStackFrame(null)}var u;u=!1;function B(e){return typeof e=="object"&&e!==null&&e.$$typeof===r}function I(){{if(ke.current){var e=S(ke.current.type);if(e)return`
17
+ */var Rt;function or(){return Rt||(Rt=1,process.env.NODE_ENV!=="production"&&function(){var e=s,r=Symbol.for("react.element"),n=Symbol.for("react.portal"),o=Symbol.for("react.fragment"),l=Symbol.for("react.strict_mode"),c=Symbol.for("react.profiler"),m=Symbol.for("react.provider"),v=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),j=Symbol.for("react.suspense"),_=Symbol.for("react.suspense_list"),w=Symbol.for("react.memo"),C=Symbol.for("react.lazy"),x=Symbol.for("react.offscreen"),P=Symbol.iterator,M="@@iterator";function I(t){if(t===null||typeof t!="object")return null;var i=P&&t[P]||t[M];return typeof i=="function"?i:null}var k=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function E(t){{for(var i=arguments.length,d=new Array(i>1?i-1:0),g=1;g<i;g++)d[g-1]=arguments[g];O("error",t,d)}}function O(t,i,d){{var g=k.ReactDebugCurrentFrame,F=g.getStackAddendum();F!==""&&(i+="%s",d=d.concat([F]));var W=d.map(function(N){return String(N)});W.unshift("Warning: "+i),Function.prototype.apply.call(console[t],console,W)}}var pe=!1,de=!1,we=!1,ue=!1,se=!1,Q;Q=Symbol.for("react.module.reference");function b(t){return!!(typeof t=="string"||typeof t=="function"||t===o||t===c||se||t===l||t===j||t===_||ue||t===x||pe||de||we||typeof t=="object"&&t!==null&&(t.$$typeof===C||t.$$typeof===w||t.$$typeof===m||t.$$typeof===v||t.$$typeof===h||t.$$typeof===Q||t.getModuleId!==void 0))}function ye(t,i,d){var g=t.displayName;if(g)return g;var F=i.displayName||i.name||"";return F!==""?d+"("+F+")":d}function _e(t){return t.displayName||"Context"}function z(t){if(t==null)return null;if(typeof t.tag=="number"&&E("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case o:return"Fragment";case n:return"Portal";case c:return"Profiler";case l:return"StrictMode";case j:return"Suspense";case _:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case v:var i=t;return _e(i)+".Consumer";case m:var d=t;return _e(d._context)+".Provider";case h:return ye(t,t.render,"ForwardRef");case w:var g=t.displayName||null;return g!==null?g:z(t.type)||"Memo";case C:{var F=t,W=F._payload,N=F._init;try{return z(N(W))}catch{return null}}}return null}var p=Object.assign,y=0,S,A,re,ae,q,G,V;function T(){}T.__reactDisabledLog=!0;function K(){{if(y===0){S=console.log,A=console.info,re=console.warn,ae=console.error,q=console.group,G=console.groupCollapsed,V=console.groupEnd;var t={configurable:!0,enumerable:!0,value:T,writable:!0};Object.defineProperties(console,{info:t,log:t,warn:t,error:t,group:t,groupCollapsed:t,groupEnd:t})}y++}}function Ce(){{if(y--,y===0){var t={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:p({},t,{value:S}),info:p({},t,{value:A}),warn:p({},t,{value:re}),error:p({},t,{value:ae}),group:p({},t,{value:q}),groupCollapsed:p({},t,{value:G}),groupEnd:p({},t,{value:V})})}y<0&&E("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ve=k.ReactCurrentDispatcher,J;function Ee(t,i,d){{if(J===void 0)try{throw Error()}catch(F){var g=F.stack.trim().match(/\n( *(at )?)/);J=g&&g[1]||""}return`
18
+ `+J+t}}var Z=!1,Pe;{var Re=typeof WeakMap=="function"?WeakMap:Map;Pe=new Re}function oe(t,i){if(!t||Z)return"";{var d=Pe.get(t);if(d!==void 0)return d}var g;Z=!0;var F=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var W;W=ve.current,ve.current=null,K();try{if(i){var N=function(){throw Error()};if(Object.defineProperty(N.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(N,[])}catch(fe){g=fe}Reflect.construct(t,[],N)}else{try{N.call()}catch(fe){g=fe}t.call(N.prototype)}}else{try{throw Error()}catch(fe){g=fe}t()}}catch(fe){if(fe&&g&&typeof fe.stack=="string"){for(var R=fe.stack.split(`
19
+ `),ce=g.stack.split(`
20
+ `),Y=R.length-1,H=ce.length-1;Y>=1&&H>=0&&R[Y]!==ce[H];)H--;for(;Y>=1&&H>=0;Y--,H--)if(R[Y]!==ce[H]){if(Y!==1||H!==1)do if(Y--,H--,H<0||R[Y]!==ce[H]){var be=`
21
+ `+R[Y].replace(" at new "," at ");return t.displayName&&be.includes("<anonymous>")&&(be=be.replace("<anonymous>",t.displayName)),typeof t=="function"&&Pe.set(t,be),be}while(Y>=1&&H>=0);break}}}finally{Z=!1,ve.current=W,Ce(),Error.prepareStackTrace=F}var He=t?t.displayName||t.name:"",Be=He?Ee(He):"";return typeof t=="function"&&Pe.set(t,Be),Be}function ee(t,i,d){return oe(t,!1)}function Te(t){var i=t.prototype;return!!(i&&i.isReactComponent)}function $(t,i,d){if(t==null)return"";if(typeof t=="function")return oe(t,Te(t));if(typeof t=="string")return Ee(t);switch(t){case j:return Ee("Suspense");case _:return Ee("SuspenseList")}if(typeof t=="object")switch(t.$$typeof){case h:return ee(t.render);case w:return $(t.type,i,d);case C:{var g=t,F=g._payload,W=g._init;try{return $(W(F),i,d)}catch{}}}return""}var ie=Object.prototype.hasOwnProperty,ke={},te=k.ReactDebugCurrentFrame;function je(t){if(t){var i=t._owner,d=$(t.type,t._source,i?i.type:null);te.setExtraStackFrame(d)}else te.setExtraStackFrame(null)}function Fe(t,i,d,g,F){{var W=Function.call.bind(ie);for(var N in t)if(W(t,N)){var R=void 0;try{if(typeof t[N]!="function"){var ce=Error((g||"React class")+": "+d+" type `"+N+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof t[N]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw ce.name="Invariant Violation",ce}R=t[N](i,N,g,d,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(Y){R=Y}R&&!(R instanceof Error)&&(je(F),E("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",g||"React class",d,N,typeof R),je(null)),R instanceof Error&&!(R.message in ke)&&(ke[R.message]=!0,je(F),E("Failed %s type: %s",d,R.message),je(null))}}}var he=Array.isArray;function ze(t){return he(t)}function ge(t){{var i=typeof Symbol=="function"&&Symbol.toStringTag,d=i&&t[Symbol.toStringTag]||t.constructor.name||"Object";return d}}function le(t){try{return Oe(t),!1}catch{return!0}}function Oe(t){return""+t}function We(t){if(le(t))return E("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ge(t)),Oe(t)}var Ae=k.ReactCurrentOwner,Le={key:!0,ref:!0,__self:!0,__source:!0},De,Ne;function f(t){if(ie.call(t,"ref")){var i=Object.getOwnPropertyDescriptor(t,"ref").get;if(i&&i.isReactWarning)return!1}return t.ref!==void 0}function D(t){if(ie.call(t,"key")){var i=Object.getOwnPropertyDescriptor(t,"key").get;if(i&&i.isReactWarning)return!1}return t.key!==void 0}function me(t,i){typeof t.ref=="string"&&Ae.current}function ne(t,i){{var d=function(){De||(De=!0,E("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",i))};d.isReactWarning=!0,Object.defineProperty(t,"key",{get:d,configurable:!0})}}function st(t,i){{var d=function(){Ne||(Ne=!0,E("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",i))};d.isReactWarning=!0,Object.defineProperty(t,"ref",{get:d,configurable:!0})}}var ot=function(t,i,d,g,F,W,N){var R={$$typeof:r,type:t,key:i,ref:d,props:N,_owner:W};return R._store={},Object.defineProperty(R._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(R,"_self",{configurable:!1,enumerable:!1,writable:!1,value:g}),Object.defineProperty(R,"_source",{configurable:!1,enumerable:!1,writable:!1,value:F}),Object.freeze&&(Object.freeze(R.props),Object.freeze(R)),R};function it(t,i,d,g,F){{var W,N={},R=null,ce=null;d!==void 0&&(We(d),R=""+d),D(i)&&(We(i.key),R=""+i.key),f(i)&&(ce=i.ref,me(i,F));for(W in i)ie.call(i,W)&&!Le.hasOwnProperty(W)&&(N[W]=i[W]);if(t&&t.defaultProps){var Y=t.defaultProps;for(W in Y)N[W]===void 0&&(N[W]=Y[W])}if(R||ce){var H=typeof t=="function"?t.displayName||t.name||"Unknown":t;R&&ne(N,H),ce&&st(N,H)}return ot(t,R,ce,F,g,Ae.current,N)}}var $e=k.ReactCurrentOwner,Ve=k.ReactDebugCurrentFrame;function Se(t){if(t){var i=t._owner,d=$(t.type,t._source,i?i.type:null);Ve.setExtraStackFrame(d)}else Ve.setExtraStackFrame(null)}var Ue;Ue=!1;function Qe(t){return typeof t=="object"&&t!==null&&t.$$typeof===r}function lt(){{if($e.current){var t=z($e.current.type);if(t)return`
22
22
 
23
- Check the render method of \``+e+"`."}return""}}function L(e){return""}var be={};function Ce(e){{var i=I();if(!i){var d=typeof e=="string"?e:e.displayName||e.name;d&&(i=`
23
+ Check the render method of \``+t+"`."}return""}}function u(t){return""}var B={};function L(t){{var i=lt();if(!i){var d=typeof t=="string"?t:t.displayName||t.name;d&&(i=`
24
24
 
25
- Check the top-level render call using <`+d+">.")}return i}}function Ve(e,i){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var d=Ce(i);if(be[d])return;be[d]=!0;var y="";e&&e._owner&&e._owner!==ke.current&&(y=" It was passed a child from "+S(e._owner.type)+"."),Re(e),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',d,y),Re(null)}}function gt(e,i){{if(typeof e!="object")return;if(A(e))for(var d=0;d<e.length;d++){var y=e[d];B(y)&&Ve(y,i)}else if(B(e))e._store&&(e._store.validated=!0);else if(e){var F=M(e);if(typeof F=="function"&&F!==e.entries)for(var O=F.call(e),k;!(k=O.next()).done;)B(k.value)&&Ve(k.value,i)}}}function zt(e){{var i=e.type;if(i==null||typeof i=="string")return;var d;if(typeof i=="function")d=i.propTypes;else if(typeof i=="object"&&(i.$$typeof===m||i.$$typeof===p))d=i.propTypes;else return;if(d){var y=S(i);P(d,e.props,"prop",y,e)}else if(i.PropTypes!==void 0&&!u){u=!0;var F=S(i);b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",F||"Unknown")}typeof i.getDefaultProps=="function"&&!i.getDefaultProps.isReactClassApproved&&b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Bt(e){{for(var i=Object.keys(e.props),d=0;d<i.length;d++){var y=i[d];if(y!=="children"&&y!=="key"){Re(e),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",y),Re(null);break}}e.ref!==null&&(Re(e),b("Invalid attribute `ref` supplied to `React.Fragment`."),Re(null))}}var xt={};function bt(e,i,d,y,F,O){{var k=j(e);if(!k){var _="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(_+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var ne=L();ne?_+=ne:_+=I();var V;e===null?V="null":A(e)?V="array":e!==void 0&&e.$$typeof===r?(V="<"+(S(e.type)||"Unknown")+" />",_=" Did you accidentally export a JSX literal instead of a component?"):V=typeof e,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",V,_)}var q=Ye(e,i,d,F,O);if(q==null)return q;if(k){var ye=i.children;if(ye!==void 0)if(y)if(A(ye)){for(var Oe=0;Oe<ye.length;Oe++)gt(ye[Oe],e);Object.freeze&&Object.freeze(ye)}else b("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else gt(ye,e)}if(xe.call(i,"key")){var Pe=S(e),ce=Object.keys(i).filter(function(Ht){return Ht!=="key"}),it=ce.length>0?"{key: someKey, "+ce.join(": ..., ")+": ...}":"{key: someKey}";if(!xt[Pe+it]){var Gt=ce.length>0?"{"+ce.join(": ..., ")+": ...}":"{}";b(`A props object containing a "key" prop is being spread into JSX:
25
+ Check the top-level render call using <`+d+">.")}return i}}function U(t,i){{if(!t._store||t._store.validated||t.key!=null)return;t._store.validated=!0;var d=L(i);if(B[d])return;B[d]=!0;var g="";t&&t._owner&&t._owner!==$e.current&&(g=" It was passed a child from "+z(t._owner.type)+"."),Se(t),E('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',d,g),Se(null)}}function xe(t,i){{if(typeof t!="object")return;if(ze(t))for(var d=0;d<t.length;d++){var g=t[d];Qe(g)&&U(g,i)}else if(Qe(t))t._store&&(t._store.validated=!0);else if(t){var F=I(t);if(typeof F=="function"&&F!==t.entries)for(var W=F.call(t),N;!(N=W.next()).done;)Qe(N.value)&&U(N.value,i)}}}function Me(t){{var i=t.type;if(i==null||typeof i=="string")return;var d;if(typeof i=="function")d=i.propTypes;else if(typeof i=="object"&&(i.$$typeof===h||i.$$typeof===w))d=i.propTypes;else return;if(d){var g=z(i);Fe(d,t.props,"prop",g,t)}else if(i.PropTypes!==void 0&&!Ue){Ue=!0;var F=z(i);E("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",F||"Unknown")}typeof i.getDefaultProps=="function"&&!i.getDefaultProps.isReactClassApproved&&E("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function ct(t){{for(var i=Object.keys(t.props),d=0;d<i.length;d++){var g=i[d];if(g!=="children"&&g!=="key"){Se(t),E("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",g),Se(null);break}}t.ref!==null&&(Se(t),E("Invalid attribute `ref` supplied to `React.Fragment`."),Se(null))}}var jt={};function _t(t,i,d,g,F,W){{var N=b(t);if(!N){var R="";(t===void 0||typeof t=="object"&&t!==null&&Object.keys(t).length===0)&&(R+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var ce=u();ce?R+=ce:R+=lt();var Y;t===null?Y="null":ze(t)?Y="array":t!==void 0&&t.$$typeof===r?(Y="<"+(z(t.type)||"Unknown")+" />",R=" Did you accidentally export a JSX literal instead of a component?"):Y=typeof t,E("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",Y,R)}var H=it(t,i,d,F,W);if(H==null)return H;if(N){var be=i.children;if(be!==void 0)if(g)if(ze(be)){for(var He=0;He<be.length;He++)xe(be[He],t);Object.freeze&&Object.freeze(be)}else E("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else xe(be,t)}if(ie.call(i,"key")){var Be=z(t),fe=Object.keys(i).filter(function(rr){return rr!=="key"}),mt=fe.length>0?"{key: someKey, "+fe.join(": ..., ")+": ...}":"{key: someKey}";if(!jt[Be+mt]){var tr=fe.length>0?"{"+fe.join(": ..., ")+": ...}":"{}";E(`A props object containing a "key" prop is being spread into JSX:
26
26
  let props = %s;
27
27
  <%s {...props} />
28
28
  React keys must be passed directly to JSX without using spread:
29
29
  let props = %s;
30
- <%s key={someKey} {...props} />`,it,Pe,Gt,Pe),xt[Pe+it]=!0}}return e===o?Bt(q):zt(q),q}}function Yt(e,i,d){return bt(e,i,d,!0)}function Vt(e,i,d){return bt(e,i,d,!1)}var qt=Vt,Kt=Yt;Ke.Fragment=o,Ke.jsx=qt,Ke.jsxs=Kt}()),Ke}process.env.NODE_ENV==="production"?pt.exports=Xt():pt.exports=Qt();var a=pt.exports;function Tt(t){var r,s,o="";if(typeof t=="string"||typeof t=="number")o+=t;else if(typeof t=="object")if(Array.isArray(t)){var l=t.length;for(r=0;r<l;r++)t[r]&&(s=Tt(t[r]))&&(o&&(o+=" "),o+=s)}else for(s in t)t[s]&&(o&&(o+=" "),o+=s);return o}function Q(){for(var t,r,s=0,o="",l=arguments.length;s<l;s++)(t=arguments[s])&&(r=Tt(t))&&(o&&(o+=" "),o+=r);return o}const er="https://core.spreedly.com/iframe/iframe-v1.min.js",tr="https://cdn.e2e.movmo.io";let De={};const rr=t=>{De={...De,...t}},ct=t=>{var s;const r=globalThis.process;return(s=r==null?void 0:r.env)==null?void 0:s[t]},Te=()=>({baseUrl:De.baseUrl??ct("REACT_APP_MOVMO_API_URL")??"",spreedlyScriptUrl:De.spreedlyScriptUrl??ct("REACT_APP_SPREEDLY_SCRIPT_URL")??er,iconCdnBaseUrl:De.iconCdnBaseUrl??ct("REACT_APP_MOVMO_ICON_CDN_URL")??tr,fetch:De.fetch??(typeof globalThis<"u"&&typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):(()=>{throw new Error("@movmo_app/payments: no fetch available")})())}),ht=t=>({id:t.id,last4:t.last4,brand:t.brand,expMonth:t.expMonth,expYear:t.expYear,isDefault:t.isDefault,vault:t.vault,cardholderName:t.cardholderName,zip:t.zip}),$e={Accept:"application/json","Content-Type":"application/json"},Ae=t=>{const{baseUrl:r}=Te();if(!r)throw new Error("@movmo_app/payments: baseUrl is not configured. Call setPaymentsConfig({ baseUrl }) at app boot, or set REACT_APP_MOVMO_API_URL.");return`${r}${t}`},Ue=(t,r)=>{const{fetch:s}=Te();return s(t,r)},Ie=async(t,r)=>{try{return(await t.json()).message||r}catch{return r}};let Ge=null;const yt=()=>{if(Ge)return Ge;const t=(async()=>{const r=await Ue(Ae("/v1/payments/tokenization-session"),{method:"GET",headers:$e,credentials:"include"});if(!r.ok)throw new Error(await Ie(r,`Failed to fetch tokenization session (${r.status})`));return await r.json()})();return Ge=t,t.finally(()=>{Ge===t&&(Ge=null)}).catch(()=>{}),t},ar=t=>typeof t.brand=="string"&&typeof t.last4=="string"&&typeof t.expMonth=="number"&&typeof t.expYear=="number",nr=async(t,r,s)=>{const o=await Ue(Ae(`/v1/users/${encodeURIComponent(t)}/payment-methods/from-token`),{method:"POST",headers:$e,credentials:"include",body:JSON.stringify({tokenizedPaymentMethodId:r,isDefault:s})});if(!o.ok)throw new Error(await Ie(o,`Failed to save payment method (${o.status})`));const l=await o.json();if(ar(l))return ht(l);const c=await Ue(Ae(`/v1/users/${encodeURIComponent(t)}/payment-methods/${encodeURIComponent(l.id)}`),{method:"GET",headers:$e,credentials:"include"});if(!c.ok)throw new Error(await Ie(c,`Failed to fetch saved payment method (${c.status})`));const f=await c.json();return ht(f)},sr=async(t,r)=>{if(!t)return[];const s=await Ue(Ae(`/v1/users/${encodeURIComponent(t)}/payment-methods`),{method:"GET",headers:$e,credentials:"include",signal:r});if(!s.ok)throw new Error(await Ie(s,`Failed to fetch payment methods (${s.status})`));return(await s.json()??[]).map(ht)},or=async(t,r)=>{const s=await Ue(Ae(`/v1/users/${encodeURIComponent(t)}/payment-methods/${encodeURIComponent(r)}`),{method:"DELETE",headers:$e,credentials:"include"});if(!s.ok)throw new Error(await Ie(s,`Failed to delete payment method (${s.status})`))},Ft=async(t,r,s)=>{const o=await Ue(Ae(`/v1/users/${encodeURIComponent(t)}/payment-methods/${encodeURIComponent(r)}`),{method:"PUT",headers:$e,credentials:"include",body:JSON.stringify(s)});if(!o.ok)throw new Error(await Ie(o,`Failed to update payment method (${o.status})`))},ir={visa:"visa",master:"mastercard",mastercard:"mastercard",american_express:"amex",amex:"amex",discover:"discover"},lr=28,Ne=({brand:t,className:r,width:s=46})=>{const o=t?ir[t.toLowerCase()]??"credit-card":"credit-card",l=Math.max(s,lr),c=Math.round(l*24/34),{iconCdnBaseUrl:f}=Te();return a.jsx("img",{src:`${f}/website/assets/icons/payments/${o}.svg`,alt:o==="credit-card"?"card":`${o} card`,"data-testid":`card-brand-${t.toLowerCase()}`,className:r,width:l,height:c,loading:"lazy"})};let He=null;const cr=()=>{if(typeof window>"u")return Promise.reject(new Error("Spreedly can only be loaded in a browser environment."));if(window.Spreedly)return Promise.resolve(window.Spreedly);if(He)return He;const{spreedlyScriptUrl:t}=Te();return He=new Promise((r,s)=>{const o=document.querySelector(`script[src="${t}"]`),l=()=>{window.Spreedly?r(window.Spreedly):s(new Error("Spreedly script loaded but window.Spreedly is undefined."))};if(o){if(window.Spreedly){l();return}o.addEventListener("load",l,{once:!0}),o.addEventListener("error",()=>{o.remove(),s(new Error("Failed to load Spreedly iframe script."))},{once:!0});return}const c=document.createElement("script");c.src=t,c.async=!0,c.onload=l,c.onerror=()=>{c.remove(),s(new Error("Failed to load Spreedly iframe script."))},document.head.appendChild(c)}).catch(r=>{throw He=null,r}),He};class nt extends Error{constructor(s,o){super(o instanceof Error?o.message:"Failed to initialize card form.");lt(this,"source");lt(this,"cause");this.name="InitError",this.source=s,this.cause=o}}const dr="movmo-card-number",ur="movmo-card-cvv",fr=t=>({first_name:t.firstName,last_name:t.lastName,month:t.month,year:t.year,...t.email?{email:t.email}:{},...t.zip?{zip:t.zip}:{}}),Wt=(t={})=>{const{numberEl:r=dr,cvvEl:s=ur,onCardTokenized:o,onFieldErrors:l,onValidityChange:c,onBrandChange:f}=t,[x,m]=n.useState("idle"),[R,w]=n.useState(null),[p,v]=n.useState(null),[E,T]=n.useState(null),[se,M]=n.useState({number:!1,cvv:!1}),[C,b]=n.useState(null),[Y,ee]=n.useState({number:!1,cvv:!1}),ve=n.useRef(null),ue=n.useRef(o),te=n.useRef(l),oe=n.useRef(c),D=n.useRef(f);n.useEffect(()=>{ue.current=o},[o]),n.useEffect(()=>{te.current=l},[l]),n.useEffect(()=>{oe.current=c},[c]),n.useEffect(()=>{D.current=f},[f]);const j=n.useRef({number:!1,cvv:!1});n.useEffect(()=>{let S=!1;return m("loading"),w(null),v(null),T(null),M({number:!1,cvv:!1}),b(null),j.current={number:!1,cvv:!1},(async()=>{try{const[g,h]=await Promise.all([yt().catch(N=>{throw new nt("tokenization-session",N)}),cr().catch(N=>{throw new nt("spreedly-script",N)})]);if(S)return;ve.current=h,h.on("ready",()=>{var N,U,K,me,G,re;if(!S){m("ready");try{(N=h.setFieldType)==null||N.call(h,"number","tel"),(U=h.setFieldType)==null||U.call(h,"cvv","tel")}catch(H){console.warn("@movmo_app/payments: setFieldType failed",H)}try{typeof h.setNumberFormat=="function"?h.setNumberFormat("prettyFormat"):console.warn("@movmo_app/payments: Spreedly.setNumberFormat is missing — card-number digits will not be space-grouped.")}catch(H){console.warn("@movmo_app/payments: setNumberFormat failed",H)}try{(K=h.setPlaceholder)==null||K.call(h,"number","Card number"),(me=h.setPlaceholder)==null||me.call(h,"cvv","CVV");const H='box-sizing: border-box;width: 100%;height: 100%;margin: 0;padding: 0;border: 0;background: transparent;outline: none;font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;font-size: 14px;font-weight: 400;line-height: 20px;color: rgb(28 25 23);letter-spacing: 0;vertical-align: middle;';(G=h.setStyle)==null||G.call(h,"number",H),(re=h.setStyle)==null||re.call(h,"cvv",H)}catch(H){console.warn("@movmo_app/payments: setPlaceholder/setStyle failed",H)}}}),h.on("paymentMethod",N=>{var U;(U=ue.current)==null||U.call(ue,N)}),h.on("errors",N=>{var U;(U=te.current)==null||U.call(te,N)}),h.on("fieldEvent",(N,U,K,me)=>{var H;if(S)return;if(U==="focus"){ee(W=>W[N]?W:{...W,[N]:!0});return}if(U==="blur"){ee(W=>W[N]?{...W,[N]:!1}:W);return}if(U!=="input")return;const G=me??{};if(N==="number"){if(G.numberLength===0)b(W=>{var Z;return W!==null&&((Z=D.current)==null||Z.call(D,null)),null});else if(G.cardType!==void 0){const W=G.cardType||null;b(Z=>{var je;return Z!==W&&((je=D.current)==null||je.call(D,W)),W})}}const re=N==="number"?typeof G.validNumber=="boolean"?G.validNumber:void 0:typeof G.validCvv=="boolean"?G.validCvv:void 0;if(typeof re=="boolean"){const W=j.current,Z=N==="number"?{...W,number:re}:{...W,cvv:re};(Z.number!==W.number||Z.cvv!==W.cvv)&&(j.current=Z,M(Z),(H=oe.current)==null||H.call(oe,Z))}}),h.on("consoleError",N=>{var K;const U=N instanceof Error?N.message:"An unexpected error occurred while securing your card.";(K=te.current)==null||K.call(te,[{message:U}])}),h.init(g.environmentKey,{numberEl:r,cvvEl:s,nonce:g.nonce,timestamp:String(g.timestamp),certificateToken:g.certificateToken,signature:g.signature})}catch(g){if(S)return;const h=g instanceof Error?g.message:"Failed to initialize card form.";w(h),v(g instanceof nt?g.source:"spreedly-script"),T(g instanceof nt?g.cause:g),m("error")}})(),()=>{var g,h;S=!0;try{(h=(g=ve.current)==null?void 0:g.removeHandlers)==null||h.call(g)}catch(N){console.warn("@movmo_app/payments: removeHandlers failed during cleanup",N)}ve.current=null}},[r,s]);const fe=n.useCallback(S=>{var g;(g=ve.current)==null||g.tokenizeCreditCard(fr(S))},[]),Ee=n.useCallback(S=>{var g,h;(h=(g=ve.current)==null?void 0:g.transferFocus)==null||h.call(g,S)},[]);return{status:x,error:R,errorSource:p,errorCause:E,tokenize:fe,validity:se,brand:C,focused:Y,focusField:Ee}},dt="h-11 w-full rounded-md border border-grayWarm-300 bg-white px-3 py-2 text-sm text-grayWarm-900 placeholder:text-grayWarm-400 outline-none focus:border-grayWarm-950 focus:shadow-[0_0_0_1px_#1c1917]",jt="flex h-11 w-full items-center gap-2 rounded-md border bg-white px-3 py-2 transition-shadow",_t="border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]",Ct="border-grayWarm-300",mr=t=>{const r=t.trim();if(!r)return{firstName:"",lastName:""};const s=r.lastIndexOf(" ");return s===-1?{firstName:r,lastName:""}:{firstName:r.slice(0,s).trim(),lastName:r.slice(s+1).trim()}},Mt=t=>{const r=t.replace(/\D/g,"");if(r.length<4)return{month:"",year:""};const s=r.slice(0,2),o=r.slice(2),l=o.length===2?`20${o}`:o.slice(0,4);return{month:s,year:l}},pr=t=>{const r=t.replace(/\D/g,"").slice(0,4);return r.length<=2?r:`${r.slice(0,2)} / ${r.slice(2)}`},ut=t=>{const{month:r,year:s}=Mt(t);if(!r||!s)return!1;const o=parseInt(r,10),l=parseInt(s,10);if(isNaN(o)||o<1||o>12)return!1;const c=new Date;return!(l<c.getFullYear()||l>c.getFullYear()+20||l===c.getFullYear()&&o<c.getMonth()+1)},ft=t=>/^\d{5}(-\d{4})?$/.test(t.trim()),hr=t=>{const r=t.replace(/[^\d]/g,"").slice(0,9);return r.length<=5?r:`${r.slice(0,5)}-${r.slice(5)}`},vt=({userId:t,onSuccess:r,onError:s,onErrorDetail:o,isDefault:l=!1,className:c,defaultCardholderName:f,defaultCardholderFirstName:x="",defaultCardholderLastName:m="",autoSave:R=!1,formId:w="movmo-card-form",hideInternalSaveButton:p=!1,onCanSubmitChange:v,onSavingChange:E,autoFocus:T})=>{const se=f??[x,m].filter(Boolean).join(" "),[M,C]=n.useState(se),[b,Y]=n.useState(""),[ee,ve]=n.useState(""),[ue,te]=n.useState("idle"),oe=n.useRef(!1),D=n.useRef(o);n.useEffect(()=>{D.current=o},[o]);const j=n.useCallback(async P=>{var $;te("saving");try{const A=await nr(t,P,l);te("ready"),r(A)}catch(A){const de=A instanceof Error?A.message:"Failed to save payment method.";te("ready"),oe.current=!1,s(de),($=D.current)==null||$.call(D,{source:"save-from-token",message:de,cause:A})}},[t,l,r,s]),fe=n.useCallback(P=>{var A;const $=P.map(de=>de.message).filter(Boolean).join("; ")||"Card validation failed.";te(de=>de==="tokenizing"?"ready":de),oe.current=!1,s($),(A=D.current)==null||A.call(D,{source:"card-tokenize",message:$})},[s]),Ee=n.useMemo(()=>({onCardTokenized:j,onFieldErrors:fe}),[j,fe]),{status:S,error:g,errorSource:h,errorCause:N,tokenize:U,validity:K,brand:me,focused:G,focusField:re}=Wt(Ee),H=n.useRef(!1);n.useEffect(()=>{!T||S!=="ready"||H.current||(H.current=!0,re(T))},[T,S,re]);const W=M.trim().split(/\s+/).length>=2,Z=ut(b),je=ft(ee),pe=n.useRef(!1),he=n.useRef(!1),ie=n.useRef(!1),ae=n.useRef(null),_e=n.useRef(null);n.useEffect(()=>{var P;K.cvv?he.current||(he.current=!0,(P=ae.current)==null||P.focus()):he.current=!1},[K.cvv]);const Fe=!W||!Z||!je||!K.number||!K.cvv,le=ue==="tokenizing"||ue==="saving",J=S==="ready"&&!le&&!Fe,ge=n.useRef(v);n.useEffect(()=>{ge.current=v},[v]),n.useEffect(()=>{var P;(P=ge.current)==null||P.call(ge,J)},[J]);const z=n.useRef(E);n.useEffect(()=>{z.current=E},[E]),n.useEffect(()=>{var P;(P=z.current)==null||P.call(z,le)},[le]);const xe=n.useCallback(()=>{const{firstName:P,lastName:$}=mr(M),{month:A,year:de}=Mt(b);te("tokenizing"),U({firstName:P,lastName:$,month:A,year:de,zip:ee.trim()})},[M,b,ee,U]);n.useEffect(()=>{if(!R||!J||oe.current)return;const P=setTimeout(()=>{oe.current=!0,xe()},1200);return()=>clearTimeout(P)},[R,J,xe]);const Se=P=>{P.preventDefault(),J&&xe()},we=S!=="ready"||le,X=n.useRef(s);return n.useEffect(()=>{X.current=s},[s]),n.useEffect(()=>{var P,$;g&&((P=X.current)==null||P.call(X,g),($=D.current)==null||$.call(D,{source:h??"spreedly-script",message:g,cause:N}))},[g,h,N]),a.jsxs("form",{id:w,onSubmit:Se,className:Q("flex w-full flex-col gap-3",c),"data-testid":"movmo-card-form",children:[a.jsxs("div",{children:[a.jsx("span",{id:"movmo-card-number-label",className:"sr-only",children:"Card number"}),a.jsxs("div",{className:Q(jt,G.number?_t:Ct),children:[a.jsx(Ne,{brand:me??"",width:32,className:"flex-shrink-0"}),a.jsxs("div",{className:"relative h-full flex-1",children:[a.jsx("div",{id:"movmo-card-number","aria-labelledby":"movmo-card-number-label","aria-busy":S!=="ready",className:"absolute inset-0","data-testid":"movmo-card-number-mount"}),S!=="ready"?a.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-2 left-0 right-2 animate-pulse rounded bg-grayWarm-200"}):null]})]})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{htmlFor:"movmo-card-expiry",className:"sr-only",children:"Expiry MM / YY"}),a.jsx("input",{id:"movmo-card-expiry",type:"text",inputMode:"numeric",autoComplete:"cc-exp",placeholder:"MM / YY",value:b,onChange:P=>{const $=pr(P.target.value);Y($),ut($)&&!pe.current?(pe.current=!0,re("cvv")):ut($)||(pe.current=!1)},className:Q(dt,b&&!Z&&"border-error-500"),disabled:we,required:!0,"data-testid":"movmo-card-expiry-input"})]}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{id:"movmo-card-cvv-label",className:"sr-only",children:"CVV"}),a.jsxs("div",{className:Q(jt,G.cvv?_t:Ct),children:[a.jsxs("div",{className:"relative h-full flex-1",children:[a.jsx("div",{id:"movmo-card-cvv","aria-labelledby":"movmo-card-cvv-label","aria-busy":S!=="ready",className:"absolute inset-0","data-testid":"movmo-card-cvv-mount"}),S!=="ready"?a.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-2 left-0 right-2 animate-pulse rounded bg-grayWarm-200"}):null]}),a.jsx("button",{type:"button","aria-label":"CVV help",tabIndex:-1,className:"flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full border border-grayWarm-300 text-xs text-grayWarm-500",title:me==="american_express"?"The 4 numbers on the front of your card.":"The 3 numbers on the back of your card.","data-testid":"movmo-cvv-help",children:"?"})]})]}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"movmo-card-zip",className:"sr-only",children:"ZIP code"}),a.jsx("input",{id:"movmo-card-zip",ref:ae,type:"text",inputMode:"numeric",autoComplete:"postal-code",placeholder:"ZIP code",value:ee,onChange:P=>{var A;const $=hr(P.target.value);ve($),ft($)&&!ie.current?(ie.current=!0,(A=_e.current)==null||A.focus()):ft($)||(ie.current=!1)},className:Q(dt,ee&&!je&&"border-error-500"),disabled:we,required:!0,"data-testid":"movmo-card-zip-input"})]})]}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"movmo-card-cardholder-name",className:"sr-only",children:"Cardholder name"}),a.jsx("input",{id:"movmo-card-cardholder-name",ref:_e,type:"text",autoComplete:"cc-name",placeholder:"Cardholder name",value:M,onChange:P=>C(P.target.value),className:dt,disabled:we,required:!0,"data-testid":"movmo-card-cardholder-name-input"})]}),!R&&!p?a.jsx("button",{type:"submit",disabled:!J,className:Q("inline-flex h-11 items-center justify-center rounded-md bg-brand-500 px-4 text-sm font-semibold text-white transition-colors hover:bg-brand-600","disabled:cursor-not-allowed disabled:bg-grayWarm-300 disabled:text-grayWarm-500"),"data-testid":"movmo-card-save",children:le?"Saving…":S==="loading"?"Loading…":"Save card"}):le&&R?a.jsx("p",{className:"text-center text-sm text-grayWarm-500","aria-live":"polite","data-testid":"movmo-card-autosaving",children:"Saving card…"}):null]})};vt.displayName="MovmoCardForm";const Ot=t=>{const[r,s]=n.useState("idle"),[o,l]=n.useState(null);return{deletePaymentMethod:n.useCallback(async f=>{s("pending"),l(null);try{await or(t,f),s("idle")}catch(x){const m=x instanceof Error?x.message:"Failed to delete payment method.";throw l(m),s("error"),x}},[t]),status:r,error:o}},Dt=t=>{const[r,s]=n.useState("idle"),[o,l]=n.useState(null);return{setDefault:n.useCallback(async f=>{s("pending"),l(null);try{await Ft(t,f,{isDefault:!0}),s("idle")}catch(x){const m=x instanceof Error?x.message:"Failed to set default payment method.";throw l(m),s("error"),x}},[t]),status:r,error:o}},$t=t=>{const[r,s]=n.useState("idle"),[o,l]=n.useState(null);return{updatePaymentMethod:n.useCallback(async(f,x)=>{s("pending"),l(null);try{await Ft(t,f,x),s("idle")}catch(m){const R=m instanceof Error?m.message:"Failed to update payment method.";throw l(R),s("error"),m}},[t]),status:r,error:o}},At=t=>{const[r,s]=n.useState([]),[o,l]=n.useState("idle"),[c,f]=n.useState(null),[x,m]=n.useState(0),R=n.useRef(null);n.useEffect(()=>{var v;if((v=R.current)==null||v.abort(),!t){R.current=null,s([]),f(null),l("ready");return}const p=new AbortController;return R.current=p,l("loading"),f(null),sr(t,p.signal).then(E=>{p.signal.aborted||(s(E),l("ready"))}).catch(E=>{if(p.signal.aborted||E instanceof DOMException&&E.name==="AbortError")return;const T=E instanceof Error?E.message:"Failed to fetch payment methods.";f(T),l("error")}),()=>{p.abort()}},[t,x]);const w=n.useCallback(()=>{m(p=>p+1)},[]);return{items:r,status:o,error:c,refetch:w}},Ut=({open:t,onClose:r,title:s,titleId:o,formId:l,saveDisabled:c,saveLabel:f="Save",isSaving:x=!1,testIdPrefix:m="payment-method",children:R})=>(n.useEffect(()=>{if(!t)return;const w=p=>{p.key==="Escape"&&r()};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[t,r]),n.useEffect(()=>{if(!t)return;const w=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=w}},[t]),t?a.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":o,className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4",onClick:w=>{w.target===w.currentTarget&&r()},"data-testid":`${m}-modal`,children:a.jsxs("div",{className:"flex max-h-full w-full max-w-md flex-col rounded-xl bg-white shadow-2xl",children:[a.jsxs("div",{className:"flex items-center gap-3 border-b border-grayWarm-200 px-4 py-3",children:[a.jsx("button",{type:"button",onClick:r,"aria-label":`Close ${s.toLowerCase()} dialog`,className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg bg-grayWarm-100 p-2 text-grayWarm-950 transition-colors hover:bg-grayWarm-200","data-testid":`${m}-close`,children:a.jsx("svg",{viewBox:"0 0 20 20",width:"20",height:"20","aria-hidden":"true",children:a.jsx("path",{d:"M5 5L15 15M15 5L5 15",stroke:"currentColor",strokeWidth:"1.67",strokeLinecap:"round",strokeLinejoin:"round"})})}),a.jsx("h2",{id:o,className:"flex-1 text-center text-base font-semibold text-grayWarm-900",children:s}),a.jsx("span",{"aria-hidden":"true",className:"h-9 w-9 flex-shrink-0"})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:R}),a.jsxs("div",{className:"flex gap-3 border-t border-grayWarm-200 p-4",children:[a.jsx("button",{type:"button",onClick:r,className:"inline-flex h-11 flex-1 items-center justify-center rounded-lg border border-grayWarm-300 px-4 text-sm font-semibold text-grayWarm-900 transition-colors hover:border-grayWarm-900 hover:shadow-[0_0_0_1px_#1c1917]","data-testid":`${m}-cancel`,children:"Cancel"}),a.jsx("button",{type:"submit",form:l,disabled:x?!1:c,"aria-disabled":x||c,"aria-busy":x,className:Q("inline-flex h-11 flex-1 items-center justify-center rounded-lg bg-brand-500 px-4 text-sm font-semibold text-white transition-colors",x?"cursor-not-allowed opacity-90 pointer-events-none":"hover:bg-brand-600 disabled:cursor-not-allowed disabled:bg-grayWarm-300 disabled:text-grayWarm-500"),"data-testid":`${m}-save`,children:x?a.jsxs(a.Fragment,{children:[a.jsxs("svg",{className:"h-[18px] w-[18px] animate-spin",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeOpacity:"0.25"}),a.jsx("path",{d:"M22 12a10 10 0 0 1-10 10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]}),a.jsx("span",{className:"sr-only",children:"Saving"})]}):f})]})]})}):null),yr=({open:t,onClose:r,formId:s,saveDisabled:o,saveLabel:l="Save",isSaving:c=!1,children:f})=>a.jsx(Ut,{open:t,onClose:r,title:"Add payment method",titleId:"movmo-add-payment-title",formId:s,saveDisabled:o,saveLabel:l,isSaving:c,testIdPrefix:"add-payment-method",children:f}),vr=(t,r)=>`${String(t).padStart(2,"0")}/${r}`,gr=t=>{if(!t)return"Card";const r=t.toLowerCase();return r==="amex"?"Amex":r.charAt(0).toUpperCase()+r.slice(1)},xr=({open:t,method:r,onClose:s,onSave:o,isSaving:l=!1,error:c=null})=>{const f=n.useId(),[x,m]=n.useState(""),[R,w]=n.useState("");if(n.useEffect(()=>{t&&r&&(m(r.cardholderName??""),w(r.zip??""))},[t,r]),!r)return null;const p=x.trim(),v=R.trim(),E=p!==(r.cardholderName??"").trim(),T=v!==(r.zip??"").trim(),se=E||T,M=(!E||p.length>0)&&(!T||/^[A-Za-z0-9 -]{3,20}$/.test(v)),C=!se||!M,b=Y=>{if(Y.preventDefault(),C||l)return;const ee={};E&&(ee.cardholderName=p),T&&(ee.zip=v),o(ee).catch(()=>{})};return a.jsxs(Ut,{open:t,onClose:s,title:"Edit payment method",titleId:"movmo-edit-payment-title",formId:f,saveDisabled:C,isSaving:l,testIdPrefix:"edit-payment-method",children:[a.jsxs("div",{className:"mb-4 flex items-start gap-3 rounded-lg bg-grayWarm-50 p-3","data-testid":"edit-payment-method-context",children:[a.jsx(Ne,{brand:r.brand,className:"flex-shrink-0"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"text-lg font-semibold text-grayWarm-950",children:[gr(r.brand)," •••• ",r.last4]}),a.jsxs("div",{className:"text-sm text-grayWarm-600",children:["Exp. ",vr(r.expMonth,r.expYear)]})]})]}),a.jsxs("form",{id:f,onSubmit:b,className:"flex flex-col gap-4",noValidate:!0,children:[a.jsxs("label",{className:"flex flex-col gap-1.5 text-sm font-medium text-grayWarm-700",children:["Cardholder name",a.jsx("input",{type:"text",autoComplete:"cc-name",value:x,onChange:Y=>m(Y.target.value),disabled:l,maxLength:255,"data-testid":"edit-payment-method-cardholder",className:"h-11 rounded-lg border border-grayWarm-300 px-3 text-base font-normal text-grayWarm-950 focus:border-grayWarm-950 focus:outline-none focus:ring-1 focus:ring-grayWarm-950"})]}),a.jsxs("label",{className:"flex flex-col gap-1.5 text-sm font-medium text-grayWarm-700",children:["Billing ZIP",a.jsx("input",{type:"text",inputMode:"numeric",autoComplete:"postal-code",value:R,onChange:Y=>w(Y.target.value),disabled:l,maxLength:20,"data-testid":"edit-payment-method-zip",className:"h-11 rounded-lg border border-grayWarm-300 px-3 text-base font-normal text-grayWarm-950 focus:border-grayWarm-950 focus:outline-none focus:ring-1 focus:ring-grayWarm-950"})]}),c?a.jsx("p",{role:"alert",className:"text-sm text-error-700","data-testid":"edit-payment-method-error",children:c}):null]})]})},br=t=>{if(!t)return"Card";const r=t.toLowerCase();return r==="amex"?"Amex":r.charAt(0).toUpperCase()+r.slice(1)},It=({method:t,trailing:r,onClick:s,cardLabelFormat:o="branded",className:l})=>a.jsxs("div",{className:Q("flex items-center gap-3",s&&"cursor-pointer",l),onClick:s,role:s?"button":void 0,tabIndex:s?0:void 0,onKeyDown:s?c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),s())}:void 0,"data-testid":`payment-method-preview-${t.id}`,children:[a.jsx(Ne,{brand:t.brand,width:34,className:"flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-lg font-semibold text-grayWarm-950",children:o==="masked"?`•••• ${t.last4}`:`${br(t.brand)} ${t.last4}`}),r]}),wr=(t,r,s=new Date)=>r<s.getFullYear()||r===s.getFullYear()&&t<s.getMonth()+1,kt=t=>{if(!t)return"Card";const r=t.toLowerCase();return r==="amex"?"Amex":r.charAt(0).toUpperCase()+r.slice(1)},Er=(t,r)=>`${String(t).padStart(2,"0")}/${r}`,jr=({method:t,selectable:r,selected:s,onSelect:o,onSetDefault:l,onRemove:c,onEdit:f,disabled:x,showDefaultBadge:m,hideSetDefaultMenuItem:R,cardLabelFormat:w="branded"})=>{const[p,v]=n.useState(!1),E=n.useRef(null),T=wr(t.expMonth,t.expYear);n.useEffect(()=>{if(!p)return;const M=C=>{var b;(b=E.current)!=null&&b.contains(C.target)||v(!1)};return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[p]);const se=()=>{r&&o&&!x&&o(t)};return a.jsxs("div",{className:Q("flex items-start gap-3 transition-colors",r?"rounded-lg border px-3 py-3":"py-4",r&&!x&&"cursor-pointer",r&&(s?"border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]":"border-grayWarm-200 hover:border-grayWarm-300")),onClick:se,"data-testid":`payment-method-row-${t.id}`,children:[r?a.jsx("input",{type:"radio",name:"movmo-payment-method",checked:s,onChange:()=>o==null?void 0:o(t),onClick:M=>M.stopPropagation(),"aria-label":`Select ${kt(t.brand)} ending ${t.last4}`,className:"mr-1 h-4 w-4 mt-2 cursor-pointer appearance-none rounded-full border-2 border-grayWarm-300 checked:border-[5px] checked:border-grayWarm-950 bg-white checked:bg-white focus:ring-0 focus:ring-offset-0",disabled:x}):null,a.jsx(Ne,{brand:t.brand,className:"flex-shrink-0"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx("span",{className:"text-lg font-semibold text-grayWarm-950",children:w==="masked"?`•••• ${t.last4}`:`${kt(t.brand)} ${t.last4}`}),m&&t.isDefault?a.jsx("span",{className:"inline-flex items-center rounded-full bg-success-50 px-2 py-0.5 text-xs font-semibold text-success-700","data-testid":`badge-default-${t.id}`,children:"Default"}):null,T?a.jsx("span",{className:"inline-flex items-center rounded-full bg-error-50 px-2 py-0.5 text-xs font-semibold text-error-700","data-testid":`badge-expired-${t.id}`,children:"Expired"}):null]}),a.jsxs("div",{className:Q("text-base",T?"text-grayWarm-400":"text-grayWarm-600"),children:["Exp. ",Er(t.expMonth,t.expYear)]})]}),a.jsxs("div",{className:"relative flex-shrink-0",ref:E,children:[a.jsx("button",{type:"button","aria-label":`Open actions for card ending ${t.last4}`,"aria-haspopup":"menu","aria-expanded":p,className:"rounded-lg p-2 text-grayWarm-600 transition-colors hover:bg-grayWarm-100 disabled:cursor-not-allowed disabled:opacity-50",disabled:x,onClick:M=>{M.stopPropagation(),v(C=>!C)},"data-testid":`menu-trigger-${t.id}`,children:a.jsx("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"currentColor","aria-hidden":"true",children:a.jsx("path",{d:"M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"})})}),p?a.jsxs("div",{role:"menu",className:Q("absolute z-10 whitespace-nowrap rounded-lg border border-grayWarm-200 bg-white py-1 shadow-lg",r?"bottom-full left-1/2 mb-2 -translate-x-1/2":"right-0 top-full mt-1"),onClick:M=>M.stopPropagation(),"data-testid":`menu-${t.id}`,children:[r?a.jsx("span",{"aria-hidden":"true",className:"absolute -bottom-1.5 left-1/2 h-3 w-3 -translate-x-1/2 rotate-45 border-b border-r border-grayWarm-200 bg-white"}):null,!t.isDefault&&!R?a.jsx("button",{type:"button",role:"menuitem",className:"block w-full px-4 py-1 text-left text-md font-semibold text-grayWarm-950 hover:text-grayWarm-700",onClick:()=>{v(!1),l(t)},"data-testid":`menu-set-default-${t.id}`,children:"Set as default"}):null,f&&t.vault==="spreedly"?a.jsx("button",{type:"button",role:"menuitem",className:"block w-full px-4 py-1 text-left text-md font-semibold text-grayWarm-950 hover:text-grayWarm-700",onClick:()=>{v(!1),f(t)},"data-testid":`menu-edit-${t.id}`,children:"Edit"}):null,a.jsx("button",{type:"button",role:"menuitem",className:"block w-full px-4 py-1 text-left text-md font-semibold text-error-700 hover:text-error-500",onClick:()=>{v(!1),c(t)},"data-testid":`menu-remove-${t.id}`,children:"Delete"})]}):null]})]})},_r=t=>`${Te().iconCdnBaseUrl}/website/assets/icons/payments/${t}.svg`,mt=({slug:t,alt:r})=>a.jsx("img",{src:_r(t),alt:r,height:20,loading:"lazy",style:{height:20,width:"auto"}}),st=({type:t,label:r,iconNode:s,disabled:o=!1})=>a.jsxs("label",{className:"flex cursor-pointer items-center gap-3 rounded-lg border border-grayWarm-200 px-4 py-3 transition-colors hover:border-grayWarm-300","data-testid":`payment-type-${t}`,children:[a.jsx("input",{type:"radio",name:"movmo-payment-type",value:t,disabled:o,onChange:()=>{},className:Q("h-4 w-4 accent-grayWarm-900",o?"cursor-not-allowed":"cursor-pointer"),"aria-label":r}),a.jsxs("span",{className:"flex flex-1 items-center gap-2 text-sm font-semibold text-grayWarm-900",children:[r,s]})]}),Rt=({selected:t,onSelect:r,creditCardBody:s,disabled:o=!1,className:l})=>{const c=t==="credit_card";return a.jsxs("div",{className:Q("flex w-full flex-col gap-3",l),children:[a.jsxs("label",{className:Q("flex cursor-pointer flex-col gap-3 rounded-lg border px-4 py-3 transition-colors",c?"border-grayWarm-900 shadow-[0_0_0_1px_#1c1917]":"border-grayWarm-200"),"data-testid":"payment-type-credit_card",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("input",{type:"radio",name:"movmo-payment-type",value:"credit_card",checked:c,disabled:o,onChange:()=>{o||r("credit_card")},className:Q("h-4 w-4 accent-grayWarm-900",o?"cursor-not-allowed":"cursor-pointer"),"aria-label":"Credit card"}),a.jsx("span",{className:"flex-1 text-sm font-semibold text-grayWarm-900",children:"Credit card"}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(Ne,{brand:"mastercard",width:28}),a.jsx(Ne,{brand:"visa",width:28}),a.jsx(Ne,{brand:"amex",width:28}),a.jsx(Ne,{brand:"discover",width:28})]})]}),c?a.jsx("div",{"data-testid":"payment-type-credit_card-body",children:s}):null]}),c?a.jsx("p",{className:"mt-2 text-sm font-semibold text-grayWarm-900","data-testid":"payment-type-other-options-header",children:"Other options"}):null,a.jsx(st,{type:"paypal",label:"PayPal",iconNode:a.jsx(mt,{slug:"paypal",alt:"PayPal"}),disabled:o}),a.jsx(st,{type:"googlepay",label:"GooglePay",iconNode:a.jsx(mt,{slug:"google-pay",alt:"GooglePay"}),disabled:o}),a.jsx(st,{type:"klarna",label:"Klarna",iconNode:a.jsx(mt,{slug:"klarna",alt:"Klarna"}),disabled:o}),a.jsx(st,{type:"ach",label:"Bank account (ACH)",iconNode:a.jsx("span",{className:"text-xs font-medium text-grayWarm-500",children:"Direct debit"}),disabled:o})]})},Nt="movmo-add-payment-form",Cr=t=>{console.error("@movmo_app/payments: failed to update payment method",t);const r=t instanceof Error?t.message.trim():"";return/spreedly-backed cards/i.test(r)?"This card's details can't be edited.":r||"Failed to update payment method."},St=t=>{const r=t.filter(o=>o.isDefault),s=t.filter(o=>!o.isDefault);return[...r,...s]},Pt=({withDefaultBadge:t=!1})=>a.jsxs("div",{className:"flex items-start justify-between py-4","data-testid":"payment-method-skeleton",children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"h-8 w-[46px] flex-shrink-0 animate-pulse rounded bg-grayWarm-200"}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"h-5 w-[120px] animate-pulse rounded bg-grayWarm-200"}),t?a.jsx("div",{className:"h-5 w-[56px] animate-pulse rounded-full bg-grayWarm-200"}):null]}),a.jsx("div",{className:"h-4 w-[100px] animate-pulse rounded bg-grayWarm-200"})]})]}),a.jsx("div",{className:"h-5 w-5 flex-shrink-0 animate-pulse rounded-full bg-grayWarm-200"})]}),Lt=({userId:t,defaultCardholderName:r,defaultCardholderFirstName:s,defaultCardholderLastName:o,selectedId:l,onSelect:c,onChange:f,onError:x,onEvent:m,paymentTypeSelector:R=!0,autoSaveFirstCard:w=!0,selectionSetsDefault:p=!1,showDefaultBadge:v=!0,collapsible:E=!1,cardLabelFormat:T="branded",className:se})=>{const{items:M,status:C,error:b,refetch:Y}=At(t),{deletePaymentMethod:ee,status:ve}=Ot(t),{setDefault:ue,status:te}=Dt(t),{updatePaymentMethod:oe,status:D}=$t(t),[j,fe]=n.useState([]),Ee=n.useRef(j);n.useEffect(()=>{Ee.current=j},[j]);const[S,g]=n.useState(null),[h,N]=n.useState(!1),[U,K]=n.useState(null),[me,G]=n.useState(!1),[re,H]=n.useState(!1),[W,Z]=n.useState(null),[je,pe]=n.useState(null),[he,ie]=n.useState(null),[ae,_e]=n.useState(!1),Fe=n.useRef(!1),le=n.useRef(x);n.useEffect(()=>{le.current=x},[x]);const J=n.useCallback(u=>{var B;(B=le.current)==null||B.call(le,u)},[]),ge=n.useRef(m);n.useEffect(()=>{ge.current=m},[m]);const z=n.useCallback((u,B)=>{var I;(I=ge.current)==null||I.call(ge,u,B)},[]),xe=n.useCallback(()=>{N(!1),K(null),ie(null)},[]),Se=r??([s,o].filter(Boolean).join(" ")||void 0);n.useEffect(()=>{C==="ready"&&fe(St(M))},[M,C]);const we=n.useRef(null);n.useEffect(()=>{if(C==="error"&&b){if(we.current===b)return;we.current=b,J({source:"list",message:b})}else C!=="error"&&(we.current=null)},[C,b,J]),n.useEffect(()=>{if(!c||Fe.current||C!=="ready"||j.length===0||l)return;Fe.current=!0,z("autoselected",{had_saved_methods:!0});const u=j.find(B=>B.isDefault)??j[0];c(u)},[c,C,j,l,z]);const X=n.useCallback(u=>{fe(B=>{const I=typeof u=="function"?u(B):u,L=St(I);return queueMicrotask(()=>f==null?void 0:f(L)),L})},[f]),P=ve==="pending"||te==="pending"||D==="pending",$=n.useCallback(async u=>{const B=j;g(null),X(I=>I.map(L=>({...L,isDefault:L.id===u.id})));try{await ue(u.id),Y(),z("set_default")}catch(I){fe(B),f==null||f(B);const L=I instanceof Error?I.message:"Failed to set default payment method.";g(L),J({source:"set-default",message:L,cause:I})}},[j,X,ue,Y,f,J,z]),A=n.useCallback(u=>{c==null||c(u),p&&(u.isDefault||$(u))},[c,p,$]),de=n.useCallback(u=>{z("selected",{method_count:j.length}),A(u)},[z,j,A]),ot=n.useCallback(async u=>{const B=j;g(null);const I=j.filter(Ce=>Ce.id!==u.id);X(()=>I);const L=u.id===l&&c?I.find(Ce=>Ce.isDefault)??I[0]??null:null;L&&A(L);const be=!!L&&p&&L!==null&&!L.isDefault;try{await ee(u.id),be||Y(),z("deleted",{remaining_count:I.length})}catch(Ce){fe(B),f==null||f(B);const Ve=Ce instanceof Error?Ce.message:"Failed to delete payment method.";g(Ve),J({source:"delete",message:Ve,cause:Ce})}},[j,X,ee,Y,f,l,c,A,p,J,z]),Je=n.useCallback(u=>{pe(null),Z(u)},[]),We=n.useCallback(()=>{Z(null),pe(null)},[]),Ze=n.useCallback(async u=>{if(!W)return;const B=W,I=j;pe(null),X(L=>L.map(be=>be.id===B.id?{...be,...u.cardholderName!==void 0?{cardholderName:u.cardholderName}:{},...u.zip!==void 0?{zip:u.zip}:{}}:be));try{await oe(B.id,u),We(),Y(),z("edited",{fields:Object.keys(u)})}catch(L){fe(I),f==null||f(I);const be=Cr(L);pe(be),J({source:"update",message:be,cause:L})}},[W,j,X,oe,Y,f,We,J,z]),Xe=n.useCallback(u=>{K(null),N(!1),ie(null),X(I=>[u,...I.filter(L=>L.id!==u.id)]),A(u),!!c&&p&&!u.isDefault||Y(),z("added",{method_count:Ee.current.length+1})},[X,Y,A,c,p,z]),Le=n.useCallback(u=>{K(u)},[]),Qe=C==="ready"&&j.length===0,ze=typeof c=="function",et=!ze&&!E,tt=j.length===0,rt=w&&j.length===0,Me=n.useCallback(u=>a.jsx(vt,{userId:t,isDefault:tt,defaultCardholderName:Se,autoSave:!u&&rt,hideInternalSaveButton:u,formId:u?Nt:void 0,onCanSubmitChange:u?G:void 0,onSavingChange:u?H:void 0,autoFocus:u?"number":void 0,onSuccess:Xe,onError:Le,onErrorDetail:J}),[t,tt,Se,rt,Xe,Le,J]),Be=n.useMemo(()=>Me(!1),[Me]),Ye=n.useMemo(()=>Me(!0),[Me]),ke=!t,at=n.useMemo(()=>R?a.jsx(Rt,{selected:he,onSelect:u=>ie(u),creditCardBody:Be,disabled:ke}):Be,[R,he,Be,ke]),Re=n.useMemo(()=>R?a.jsx(Rt,{selected:he,onSelect:u=>ie(u),creditCardBody:Ye,disabled:ke}):Ye,[R,he,Ye,ke]);return a.jsxs("div",{className:Q("flex w-full flex-col gap-4",se),"data-testid":"payment-methods-manager",children:[C==="loading"&&j.length===0?a.jsxs("div",{className:Q(et?"flex flex-col divide-y divide-grayWarm-200 rounded-xl border border-grayWarm-200 px-4 md:px-6":"flex flex-col gap-2"),"data-testid":"payment-methods-loading",children:[a.jsx(Pt,{withDefaultBadge:!0}),a.jsx(Pt,{})]}):null,C==="error"?a.jsxs("div",{role:"alert","aria-live":"polite",className:"flex items-center justify-between gap-3 rounded-md bg-error-50 p-3 text-sm text-error-700","data-testid":"payment-methods-list-error",children:[a.jsx("span",{children:b??"Failed to load payment methods."}),a.jsx("button",{type:"button",onClick:Y,className:"rounded-md border border-error-700 px-3 py-1 text-xs font-semibold text-error-700 hover:bg-error-50",children:"Retry"})]}):null,S?a.jsx("div",{role:"alert","aria-live":"polite",className:"rounded-md bg-error-50 p-3 text-sm text-error-700","data-testid":"payment-methods-mutation-error",children:S}):null,E&&j.length>0?a.jsx("div",{className:"border-t border-grayWarm-200 pt-4",children:a.jsxs("div",{className:"flex items-center justify-between","data-testid":ae?"payment-methods-drawer-header":"payment-methods-collapsed-preview",children:[ae?a.jsx("h3",{className:"text-md font-semibold text-grayWarm-950",children:"Payment methods"}):a.jsx(It,{method:j.find(u=>u.id===l)??j.find(u=>u.isDefault)??j[0],cardLabelFormat:T,className:"flex-1"}),a.jsx("button",{type:"button","aria-label":ae?"Collapse payment methods":"Expand payment methods","aria-expanded":ae,className:"bg-grayWarm-100 p-2 rounded-lg hover:bg-grayWarm-200 transition-colors",onClick:()=>_e(u=>!u),"data-testid":ae?"payment-methods-drawer-close":"payment-methods-drawer-open",children:a.jsx("img",{src:`${Te().iconCdnBaseUrl}/website/assets/icons/chevron-${ae?"up":"down"}-double.svg`,alt:"",className:"w-5 h-5"})})]})}):null,j.length>0&&(!E||ae)?a.jsx("div",{className:Q("flex flex-col",et?"rounded-xl border border-grayWarm-200 px-4 md:px-6 divide-y divide-grayWarm-200":"space-y-3"),children:j.map(u=>a.jsx(jr,{method:u,selectable:ze,selected:ze&&u.id===l,onSelect:de,onSetDefault:$,onRemove:ot,onEdit:Je,disabled:P,showDefaultBadge:v,hideSetDefaultMenuItem:p,cardLabelFormat:T},u.id))}):null,Qe?a.jsx("div",{"data-testid":"payment-methods-empty",children:at}):j.length>0&&(!E||ae)?a.jsx("button",{type:"button",onClick:()=>{K(null),ie(null),G(!1),N(!0)},onMouseEnter:()=>{yt().catch(()=>{})},onFocus:()=>{yt().catch(()=>{})},className:"self-start rounded-lg bg-brand-50 px-6 py-3 text-md font-semibold text-brand-600 transition-colors hover:bg-brand-100","data-testid":"payment-methods-add-trigger",children:"Add payment method"}):null,a.jsxs(yr,{open:h,onClose:xe,formId:Nt,saveDisabled:!me,isSaving:re,children:[Re,U?a.jsx("p",{role:"alert","aria-live":"polite",className:"mt-3 rounded-md bg-error-50 px-3 py-2 text-sm text-error-700","data-testid":"payment-methods-modal-error",children:U}):null]}),a.jsx(xr,{open:W!==null,method:W,onClose:We,onSave:Ze,isSaving:D==="pending",error:je})]})};Lt.displayName="PaymentMethodsManager";const kr="/v1/auth/",Rr="movmo_csrf_token",Nr=t=>{if(typeof document>"u")return null;const r=document.cookie?document.cookie.split(";"):[];for(const s of r){const o=s.trim();if(o.startsWith(t+"="))return decodeURIComponent(o.substring(t.length+1))}return null},Sr=t=>typeof t=="string"?t:t instanceof URL?t.href:t.url,Pr=()=>{if(typeof globalThis<"u"&&typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error("@movmo_app/payments: no global fetch available in this environment")},Tr=t=>{const{refreshSession:r,onRefreshFailed:s,csrfCookieName:o=Rr,extraHeaders:l,authPathFragment:c=kr,baseFetch:f=Pr(),readCookie:x=Nr}=t;let m=null;const R=()=>{if(m)return m;const p=(async()=>{await r()})();return m=p,p.finally(()=>{m===p&&(m=null)}).catch(()=>{}),p},w=(p,v)=>{const E=new Headers(v==null?void 0:v.headers),T=x(o);if(T&&!E.has("X-CSRF-Token")&&E.set("X-CSRF-Token",T),l){const se=l(p,v);for(const[M,C]of Object.entries(se))E.has(M)||E.set(M,C)}return{...v,headers:E,credentials:(v==null?void 0:v.credentials)??"include"}};return async function(v,E){const T=await f(v,w(v,E));if(Sr(v).includes(c)||T.status!==401&&T.status!==403)return T;try{await R()}catch(C){try{s(C)}catch(b){console.error("@movmo_app/payments: onRefreshFailed callback threw — auth retry path is misconfigured",b)}return T}try{return await f(v,w(v,E))}catch(C){return console.error("@movmo_app/payments: retry after token refresh failed — returning original response",C),T}}};exports.MovmoCardForm=vt;exports.PaymentMethodPreview=It;exports.PaymentMethodsManager=Lt;exports.createMovmoAuthFetch=Tr;exports.getPaymentsConfig=Te;exports.setPaymentsConfig=rr;exports.useDeletePaymentMethod=Ot;exports.useMovmoCardFields=Wt;exports.useSetDefaultPaymentMethod=Dt;exports.useUpdatePaymentMethod=$t;exports.useUserPaymentMethods=At;
30
+ <%s key={someKey} {...props} />`,mt,Be,tr,Be),jt[Be+mt]=!0}}return t===o?ct(H):Me(H),H}}function Zt(t,i,d){return _t(t,i,d,!0)}function Xt(t,i,d){return _t(t,i,d,!1)}var Qt=Xt,er=Zt;tt.Fragment=o,tt.jsx=Qt,tt.jsxs=er}()),tt}process.env.NODE_ENV==="production"?vt.exports=sr():vt.exports=or();var a=vt.exports;function Dt(e){var r,n,o="";if(typeof e=="string"||typeof e=="number")o+=e;else if(typeof e=="object")if(Array.isArray(e)){var l=e.length;for(r=0;r<l;r++)e[r]&&(n=Dt(e[r]))&&(o&&(o+=" "),o+=n)}else for(n in e)e[n]&&(o&&(o+=" "),o+=n);return o}function X(){for(var e,r,n=0,o="",l=arguments.length;n<l;n++)(e=arguments[n])&&(r=Dt(e))&&(o&&(o+=" "),o+=r);return o}const ir="https://core.spreedly.com/iframe/iframe-v1.min.js",lr="https://cdn.e2e.movmo.io";let Ge={};const cr=e=>{Ge={...Ge,...e}},ft=e=>{var n;const r=globalThis.process;return(n=r==null?void 0:r.env)==null?void 0:n[e]},Ye=()=>({baseUrl:Ge.baseUrl??ft("REACT_APP_MOVMO_API_URL")??"",spreedlyScriptUrl:Ge.spreedlyScriptUrl??ft("REACT_APP_SPREEDLY_SCRIPT_URL")??ir,iconCdnBaseUrl:Ge.iconCdnBaseUrl??ft("REACT_APP_MOVMO_ICON_CDN_URL")??lr,fetch:Ge.fetch??(typeof globalThis<"u"&&typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):(()=>{throw new Error("@movmo_app/payments: no fetch available")})())}),dr="recovery_cooldown",ur=(e,r)=>{if(!e)return"";const n=new Date(e);if(Number.isNaN(n.getTime()))return"";try{return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",timeZone:r}).format(n)}catch{return""}},mr=e=>{const r=ur(e??"");return r?`Account recovery is in progress. You can change payment methods after ${r}.`:"Account recovery is in progress. You can change payment methods once it ends."},gt=e=>({id:e.id,last4:e.last4,brand:e.brand,expMonth:e.expMonth,expYear:e.expYear,isDefault:e.isDefault,vault:e.vault,cardholderName:e.cardholderName,zip:e.zip}),Ke={Accept:"application/json","Content-Type":"application/json"},Je=e=>{const{baseUrl:r}=Ye();if(!r)throw new Error("@movmo_app/payments: baseUrl is not configured. Call setPaymentsConfig({ baseUrl }) at app boot, or set REACT_APP_MOVMO_API_URL.");return`${r}${e}`},Ze=(e,r)=>{const{fetch:n}=Ye();return n(e,r)};class wt extends Error{constructor(n,o){super(n);qe(this,"status");qe(this,"code");qe(this,"until");this.name="PaymentsApiError",this.status=o.status,this.code=o.code,this.until=o.until}}const fr=async e=>{try{const r=await e.json();if(typeof r!="object"||r===null)return{};const{message:n,code:o,until:l}=r;return{message:typeof n=="string"?n:void 0,code:typeof o=="string"?o:void 0,until:typeof l=="string"?l:void 0}}catch{return{}}},Xe=async(e,r)=>{const{message:n,code:o,until:l}=await fr(e),c=o===dr?mr(l):n||r;return new wt(c,{status:e.status,code:o,until:l})};let rt=null;const xt=()=>{if(rt)return rt;const e=(async()=>{const r=await Ze(Je("/v1/payments/tokenization-session"),{method:"GET",headers:Ke,credentials:"include"});if(!r.ok)throw await Xe(r,`Failed to fetch tokenization session (${r.status})`);return await r.json()})();return rt=e,e.finally(()=>{rt===e&&(rt=null)}).catch(()=>{}),e},pr=e=>typeof e.brand=="string"&&typeof e.last4=="string"&&typeof e.expMonth=="number"&&typeof e.expYear=="number",hr=async(e,r,n)=>{const o=await Ze(Je(`/v1/users/${encodeURIComponent(e)}/payment-methods/from-token`),{method:"POST",headers:Ke,credentials:"include",body:JSON.stringify({tokenizedPaymentMethodId:r,isDefault:n})});if(!o.ok)throw await Xe(o,`Failed to save payment method (${o.status})`);const l=await o.json();if(pr(l))return gt(l);const c=await Ze(Je(`/v1/users/${encodeURIComponent(e)}/payment-methods/${encodeURIComponent(l.id)}`),{method:"GET",headers:Ke,credentials:"include"});if(!c.ok)throw await Xe(c,`Failed to fetch saved payment method (${c.status})`);const m=await c.json();return gt(m)},yr=async(e,r)=>{if(!e)return[];const n=await Ze(Je(`/v1/users/${encodeURIComponent(e)}/payment-methods`),{method:"GET",headers:Ke,credentials:"include",signal:r});if(!n.ok)throw await Xe(n,`Failed to fetch payment methods (${n.status})`);return(await n.json()??[]).map(gt)},vr=async(e,r)=>{const n=await Ze(Je(`/v1/users/${encodeURIComponent(e)}/payment-methods/${encodeURIComponent(r)}`),{method:"DELETE",headers:Ke,credentials:"include"});if(!n.ok)throw await Xe(n,`Failed to delete payment method (${n.status})`)},$t=async(e,r,n)=>{const o=await Ze(Je(`/v1/users/${encodeURIComponent(e)}/payment-methods/${encodeURIComponent(r)}`),{method:"PUT",headers:Ke,credentials:"include",body:JSON.stringify(n)});if(!o.ok)throw await Xe(o,`Failed to update payment method (${o.status})`)},nt=(e,r,n)=>r instanceof wt?{source:e,message:r.message,cause:r,status:r.status,...r.code!==void 0?{code:r.code}:{},...r.until!==void 0?{until:r.until}:{}}:{source:e,message:r instanceof Error?r.message:n,cause:r},gr={visa:"visa",master:"mastercard",mastercard:"mastercard",american_express:"amex",amex:"amex",discover:"discover"},xr=28,Ie=({brand:e,className:r,width:n=46})=>{const o=e?gr[e.toLowerCase()]??"credit-card":"credit-card",l=Math.max(n,xr),c=Math.round(l*24/34),{iconCdnBaseUrl:m}=Ye();return a.jsx("img",{src:`${m}/website/assets/icons/payments/${o}.svg`,alt:o==="credit-card"?"card":`${o} card`,"data-testid":`card-brand-${e.toLowerCase()}`,className:r,width:l,height:c,loading:"lazy"})};let at=null;const br=()=>{if(typeof window>"u")return Promise.reject(new Error("Spreedly can only be loaded in a browser environment."));if(window.Spreedly)return Promise.resolve(window.Spreedly);if(at)return at;const{spreedlyScriptUrl:e}=Ye();return at=new Promise((r,n)=>{const o=document.querySelector(`script[src="${e}"]`),l=()=>{window.Spreedly?r(window.Spreedly):n(new Error("Spreedly script loaded but window.Spreedly is undefined."))};if(o){if(window.Spreedly){l();return}o.addEventListener("load",l,{once:!0}),o.addEventListener("error",()=>{o.remove(),n(new Error("Failed to load Spreedly iframe script."))},{once:!0});return}const c=document.createElement("script");c.src=e,c.async=!0,c.onload=l,c.onerror=()=>{c.remove(),n(new Error("Failed to load Spreedly iframe script."))},document.head.appendChild(c)}).catch(r=>{throw at=null,r}),at};class dt extends Error{constructor(n,o){super(o instanceof Error?o.message:"Failed to initialize card form.");qe(this,"source");qe(this,"cause");this.name="InitError",this.source=n,this.cause=o}}const wr="movmo-card-number",Er="movmo-card-cvv",jr=e=>({first_name:e.firstName,last_name:e.lastName,month:e.month,year:e.year,...e.email?{email:e.email}:{},...e.zip?{zip:e.zip}:{}}),Ut=(e={})=>{const{numberEl:r=wr,cvvEl:n=Er,onCardTokenized:o,onFieldErrors:l,onValidityChange:c,onBrandChange:m}=e,[v,h]=s.useState("idle"),[j,_]=s.useState(null),[w,C]=s.useState(null),[x,P]=s.useState(null),[M,I]=s.useState({number:!1,cvv:!1}),[k,E]=s.useState(null),[O,pe]=s.useState({number:!1,cvv:!1}),de=s.useRef(null),we=s.useRef(o),ue=s.useRef(l),se=s.useRef(c),Q=s.useRef(m);s.useEffect(()=>{we.current=o},[o]),s.useEffect(()=>{ue.current=l},[l]),s.useEffect(()=>{se.current=c},[c]),s.useEffect(()=>{Q.current=m},[m]);const b=s.useRef({number:!1,cvv:!1});s.useEffect(()=>{let z=!1;return h("loading"),_(null),C(null),P(null),I({number:!1,cvv:!1}),E(null),b.current={number:!1,cvv:!1},(async()=>{try{const[p,y]=await Promise.all([xt().catch(S=>{throw new dt("tokenization-session",S)}),br().catch(S=>{throw new dt("spreedly-script",S)})]);if(z)return;de.current=y,y.on("ready",()=>{var S,A,re,ae,q,G;if(!z){h("ready");try{(S=y.setFieldType)==null||S.call(y,"number","tel"),(A=y.setFieldType)==null||A.call(y,"cvv","tel")}catch(V){console.warn("@movmo_app/payments: setFieldType failed",V)}try{typeof y.setNumberFormat=="function"?y.setNumberFormat("prettyFormat"):console.warn("@movmo_app/payments: Spreedly.setNumberFormat is missing — card-number digits will not be space-grouped.")}catch(V){console.warn("@movmo_app/payments: setNumberFormat failed",V)}try{(re=y.setPlaceholder)==null||re.call(y,"number","Card number"),(ae=y.setPlaceholder)==null||ae.call(y,"cvv","CVV");const V='box-sizing: border-box;width: 100%;height: 100%;margin: 0;padding: 0;border: 0;background: transparent;outline: none;font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;font-size: 14px;font-weight: 400;line-height: 20px;color: rgb(28 25 23);letter-spacing: 0;vertical-align: middle;';(q=y.setStyle)==null||q.call(y,"number",V),(G=y.setStyle)==null||G.call(y,"cvv",V)}catch(V){console.warn("@movmo_app/payments: setPlaceholder/setStyle failed",V)}}}),y.on("paymentMethod",S=>{var A;(A=we.current)==null||A.call(we,S)}),y.on("errors",S=>{var A;(A=ue.current)==null||A.call(ue,S)}),y.on("fieldEvent",(S,A,re,ae)=>{var V;if(z)return;if(A==="focus"){pe(T=>T[S]?T:{...T,[S]:!0});return}if(A==="blur"){pe(T=>T[S]?{...T,[S]:!1}:T);return}if(A!=="input")return;const q=ae??{};if(S==="number"){if(q.numberLength===0)E(T=>{var K;return T!==null&&((K=Q.current)==null||K.call(Q,null)),null});else if(q.cardType!==void 0){const T=q.cardType||null;E(K=>{var Ce;return K!==T&&((Ce=Q.current)==null||Ce.call(Q,T)),T})}}const G=S==="number"?typeof q.validNumber=="boolean"?q.validNumber:void 0:typeof q.validCvv=="boolean"?q.validCvv:void 0;if(typeof G=="boolean"){const T=b.current,K=S==="number"?{...T,number:G}:{...T,cvv:G};(K.number!==T.number||K.cvv!==T.cvv)&&(b.current=K,I(K),(V=se.current)==null||V.call(se,K))}}),y.on("consoleError",S=>{var re;const A=S instanceof Error?S.message:"An unexpected error occurred while securing your card.";(re=ue.current)==null||re.call(ue,[{message:A}])}),y.init(p.environmentKey,{numberEl:r,cvvEl:n,nonce:p.nonce,timestamp:String(p.timestamp),certificateToken:p.certificateToken,signature:p.signature})}catch(p){if(z)return;const y=p instanceof Error?p.message:"Failed to initialize card form.";_(y),C(p instanceof dt?p.source:"spreedly-script"),P(p instanceof dt?p.cause:p),h("error")}})(),()=>{var p,y;z=!0;try{(y=(p=de.current)==null?void 0:p.removeHandlers)==null||y.call(p)}catch(S){console.warn("@movmo_app/payments: removeHandlers failed during cleanup",S)}de.current=null}},[r,n]);const ye=s.useCallback(z=>{var p;(p=de.current)==null||p.tokenizeCreditCard(jr(z))},[]),_e=s.useCallback(z=>{var p,y;(y=(p=de.current)==null?void 0:p.transferFocus)==null||y.call(p,z)},[]);return{status:v,error:j,errorSource:w,errorCause:x,tokenize:ye,validity:M,brand:k,focused:O,focusField:_e}},bt={number:"Enter your card number",expiry:"Enter a valid expiry date",cvv:"Enter the security code",zip:"Enter your postal code",name:"Enter first and last name as printed on the card"},_r="Your card saves automatically once all fields are complete.",It=e=>/^[A-Za-z0-9][A-Za-z0-9 -]{1,8}[A-Za-z0-9]$/.test(e.trim()),zt=e=>{const r=e.replace(/[^A-Za-z0-9 -]/g,"").slice(0,10);if(!/^[\d-]*$/.test(r))return r;const n=r.replace(/-+/g,"-").replace(/^-/,"");return n.includes("-")?n:n.length===9?`${n.slice(0,5)}-${n.slice(5)}`:n},Cr=({hookStatus:e,validity:r,nameValid:n,expiryValid:o,zipValid:l})=>{const c=e==="ready",m=[],v=h=>m.push({field:h,message:bt[h]});return c&&!r.number&&v("number"),o||v("expiry"),c&&!r.cvv&&v("cvv"),l||v("zip"),n||v("name"),m},pt="h-11 w-full rounded-md border bg-white px-3 py-2 text-sm text-grayWarm-900 placeholder:text-grayWarm-400 outline-none focus:border-grayWarm-950 focus:shadow-[0_0_0_1px_#1c1917]",kt="flex h-11 w-full items-center gap-2 rounded-md border bg-white px-3 py-2 transition-shadow",Nt="border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]",St="border-grayWarm-300",Pt="border-error-500",Rr={number:!1,expiry:!1,cvv:!1,zip:!1,name:!1},kr=e=>{const r=e.trim();if(!r)return{firstName:"",lastName:""};const n=r.lastIndexOf(" ");return n===-1?{firstName:r,lastName:""}:{firstName:r.slice(0,n).trim(),lastName:r.slice(n+1).trim()}},Lt=e=>{const r=e.replace(/\D/g,"");if(r.length<4)return{month:"",year:""};const n=r.slice(0,2),o=r.slice(2),l=o.length===2?`20${o}`:o.slice(0,4);return{month:n,year:l}},Nr=e=>{const r=e.replace(/\D/g,"").slice(0,4);return r.length<=2?r:`${r.slice(0,2)} / ${r.slice(2)}`},ht=e=>{const{month:r,year:n}=Lt(e);if(!r||!n)return!1;const o=parseInt(r,10),l=parseInt(n,10);if(isNaN(o)||o<1||o>12)return!1;const c=new Date;return!(l<c.getFullYear()||l>c.getFullYear()+20||l===c.getFullYear()&&o<c.getMonth()+1)},Et=({userId:e,onSuccess:r,onError:n,onErrorDetail:o,isDefault:l=!1,className:c,defaultCardholderName:m,defaultCardholderFirstName:v="",defaultCardholderLastName:h="",autoSave:j=!1,formId:_="movmo-card-form",hideInternalSaveButton:w=!1,onCanSubmitChange:C,onSavingChange:x,autoFocus:P,onValidationChange:M})=>{const I=m??[v,h].filter(Boolean).join(" "),[k,E]=s.useState(I),[O,pe]=s.useState(""),[de,we]=s.useState(""),[ue,se]=s.useState("idle"),Q=s.useRef(!1),b=s.useRef(o);s.useEffect(()=>{b.current=o},[o]);const ye=s.useCallback(async f=>{var D;se("saving");try{const me=await hr(e,f,l);se("ready"),r(me)}catch(me){const ne=me instanceof Error?me.message:"Failed to save payment method.";se("ready"),Q.current=!1,n(ne),(D=b.current)==null||D.call(b,{...nt("save-from-token",me,ne),message:ne})}},[e,l,r,n]),_e=s.useCallback(f=>{var me;const D=f.map(ne=>ne.message).filter(Boolean).join("; ")||"Card validation failed.";se(ne=>ne==="tokenizing"?"ready":ne),Q.current=!1,n(D),(me=b.current)==null||me.call(b,{source:"card-tokenize",message:D})},[n]),z=s.useMemo(()=>({onCardTokenized:ye,onFieldErrors:_e}),[ye,_e]),{status:p,error:y,errorSource:S,errorCause:A,tokenize:re,validity:ae,brand:q,focused:G,focusField:V}=Ut(z),T=s.useRef(!1);s.useEffect(()=>{!P||p!=="ready"||T.current||(T.current=!0,V(P))},[P,p,V]);const K=k.trim().split(/\s+/).length>=2,Ce=ht(O),ve=It(de),[J,Ee]=s.useState(Rr),Z=s.useCallback(f=>Ee(D=>D[f]?D:{...D,[f]:!0}),[]),Pe=s.useRef(G);s.useEffect(()=>{const f=Pe.current;Pe.current=G,f.number&&!G.number&&Z("number"),f.cvv&&!G.cvv&&Z("cvv")},[G,Z]);const Re=s.useMemo(()=>Cr({hookStatus:p,validity:ae,nameValid:K,expiryValid:Ce,zipValid:ve}),[p,ae,K,Ce,ve]),oe=f=>Re.some(D=>D.field===f),ee=s.useMemo(()=>Re.map(f=>f.field),[Re]),Te=s.useMemo(()=>ee.filter(f=>J[f]),[ee,J]),$=s.useRef(M);s.useEffect(()=>{$.current=M},[M]),s.useEffect(()=>{var f;(f=$.current)==null||f.call($,{valid:ee.length===0,missing:ee,touchedInvalid:Te})},[ee,Te]);const ie=J.number&&oe("number"),ke=J.name&&oe("name"),te=Re.find(f=>(f.field==="expiry"||f.field==="cvv"||f.field==="zip")&&J[f.field]),je=s.useRef(!1),Fe=s.useRef(!1),he=s.useRef(null);s.useEffect(()=>{var f;ae.cvv?Fe.current||(Fe.current=!0,(f=he.current)==null||f.focus()):Fe.current=!1},[ae.cvv]);const ze=!K||!Ce||!ve||!ae.number||!ae.cvv,ge=ue==="tokenizing"||ue==="saving",le=p==="ready"&&!ge&&!ze,Oe=s.useRef(C);s.useEffect(()=>{Oe.current=C},[C]),s.useEffect(()=>{var f;(f=Oe.current)==null||f.call(Oe,le)},[le]);const We=s.useRef(x);s.useEffect(()=>{We.current=x},[x]),s.useEffect(()=>{var f;(f=We.current)==null||f.call(We,ge)},[ge]);const Ae=s.useCallback(()=>{const{firstName:f,lastName:D}=kr(k),{month:me,year:ne}=Lt(O);se("tokenizing"),re({firstName:f,lastName:D,month:me,year:ne,zip:de.trim()})},[k,O,de,re]);s.useEffect(()=>{if(!j||!le||Q.current)return;const f=setTimeout(()=>{Q.current=!0,Ae()},1200);return()=>clearTimeout(f)},[j,le,Ae]);const Le=f=>{f.preventDefault(),le&&Ae()},De=p!=="ready"||ge,Ne=s.useRef(n);return s.useEffect(()=>{Ne.current=n},[n]),s.useEffect(()=>{var f,D;y&&((f=Ne.current)==null||f.call(Ne,y),(D=b.current)==null||D.call(b,{...nt(S??"spreedly-script",A,y),message:y}))},[y,S,A]),a.jsxs("form",{id:_,onSubmit:Le,className:X("flex w-full flex-col gap-3",c),"data-testid":"movmo-card-form",children:[a.jsxs("div",{children:[a.jsx("span",{id:"movmo-card-number-label",className:"sr-only",children:"Card number"}),a.jsxs("div",{className:X(kt,G.number?Nt:ie?Pt:St),"data-testid":"movmo-card-number-shell",children:[a.jsx(Ie,{brand:q??"",width:32,className:"flex-shrink-0"}),a.jsxs("div",{className:"relative h-full flex-1",children:[a.jsx("div",{id:"movmo-card-number","aria-labelledby":"movmo-card-number-label","aria-busy":p!=="ready","aria-describedby":ie?"movmo-card-number-error":void 0,className:"absolute inset-0","data-testid":"movmo-card-number-mount"}),p!=="ready"?a.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-2 left-0 right-2 animate-pulse rounded bg-grayWarm-200"}):null]})]}),ie&&a.jsx("p",{id:"movmo-card-number-error",className:"mt-1 text-xs text-error-700","data-testid":"movmo-card-number-error",children:bt.number})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{htmlFor:"movmo-card-expiry",className:"sr-only",children:"Expiry MM / YY"}),a.jsx("input",{id:"movmo-card-expiry",type:"text",inputMode:"numeric",autoComplete:"cc-exp",placeholder:"MM / YY",value:O,onChange:f=>{const D=Nr(f.target.value);pe(D),ht(D)&&!je.current?(je.current=!0,V("cvv")):ht(D)||(je.current=!1)},onBlur:()=>Z("expiry"),"aria-invalid":J.expiry&&oe("expiry"),"aria-describedby":(te==null?void 0:te.field)==="expiry"?"movmo-card-row-error":void 0,className:X(pt,J.expiry&&oe("expiry")?"border-error-500":"border-grayWarm-300"),disabled:De,required:!0,"data-testid":"movmo-card-expiry-input"})]}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{id:"movmo-card-cvv-label",className:"sr-only",children:"CVV"}),a.jsxs("div",{className:X(kt,G.cvv?Nt:J.cvv&&oe("cvv")?Pt:St),"data-testid":"movmo-card-cvv-shell",children:[a.jsxs("div",{className:"relative h-full flex-1",children:[a.jsx("div",{id:"movmo-card-cvv","aria-labelledby":"movmo-card-cvv-label","aria-busy":p!=="ready","aria-describedby":(te==null?void 0:te.field)==="cvv"?"movmo-card-row-error":void 0,className:"absolute inset-0","data-testid":"movmo-card-cvv-mount"}),p!=="ready"?a.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-2 left-0 right-2 animate-pulse rounded bg-grayWarm-200"}):null]}),a.jsx("button",{type:"button","aria-label":"CVV help",tabIndex:-1,className:"flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full border border-grayWarm-300 text-xs text-grayWarm-500",title:q==="american_express"?"The 4 numbers on the front of your card.":"The 3 numbers on the back of your card.","data-testid":"movmo-cvv-help",children:"?"})]})]}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"movmo-card-zip",className:"sr-only",children:"Postal code"}),a.jsx("input",{id:"movmo-card-zip",ref:he,type:"text",autoComplete:"postal-code",placeholder:"Postal code",value:de,onChange:f=>{we(zt(f.target.value))},onBlur:()=>Z("zip"),"aria-invalid":J.zip&&oe("zip"),"aria-describedby":(te==null?void 0:te.field)==="zip"?"movmo-card-row-error":void 0,className:X(pt,J.zip&&oe("zip")?"border-error-500":"border-grayWarm-300"),disabled:De,required:!0,"data-testid":"movmo-card-zip-input"})]})]}),te&&a.jsx("p",{id:"movmo-card-row-error",className:"mt-1 text-xs text-error-700","data-testid":"movmo-card-row-error",children:te.message})]}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"movmo-card-cardholder-name",className:"sr-only",children:"Cardholder name"}),a.jsx("input",{id:"movmo-card-cardholder-name",type:"text",autoComplete:"cc-name",placeholder:"Cardholder name",value:k,onChange:f=>E(f.target.value),onBlur:()=>Z("name"),"aria-invalid":ke,"aria-describedby":ke?"movmo-card-name-error":void 0,className:X(pt,ke?"border-error-500":"border-grayWarm-300"),disabled:De,required:!0,"data-testid":"movmo-card-cardholder-name-input"}),ke&&a.jsx("p",{id:"movmo-card-name-error",className:"mt-1 text-xs text-error-700","data-testid":"movmo-card-name-error",children:bt.name})]}),!j&&!w?a.jsx("button",{type:"submit",disabled:!le,className:X("inline-flex h-11 items-center justify-center rounded-md bg-brand-500 px-4 text-sm font-semibold text-white transition-colors hover:bg-brand-600","disabled:cursor-not-allowed disabled:bg-grayWarm-300 disabled:text-grayWarm-500"),"data-testid":"movmo-card-save",children:ge?"Saving…":p==="loading"?"Loading…":"Save card"}):j?a.jsx("div",{className:"text-center","aria-live":"polite","data-testid":"movmo-card-autosave-status",children:ge?a.jsx("p",{className:"text-sm text-grayWarm-500","data-testid":"movmo-card-autosaving",children:"Saving card…"}):Re.length>0?a.jsx("p",{className:"text-xs text-grayWarm-600","data-testid":"movmo-card-autosave-hint",children:_r}):null}):null]})};Et.displayName="MovmoCardForm";const Bt=e=>{const[r,n]=s.useState("idle"),[o,l]=s.useState(null);return{deletePaymentMethod:s.useCallback(async m=>{n("pending"),l(null);try{await vr(e,m),n("idle")}catch(v){const h=v instanceof Error?v.message:"Failed to delete payment method.";throw l(h),n("error"),v}},[e]),status:r,error:o}},Yt=e=>{const[r,n]=s.useState("idle"),[o,l]=s.useState(null);return{setDefault:s.useCallback(async m=>{n("pending"),l(null);try{await $t(e,m,{isDefault:!0}),n("idle")}catch(v){const h=v instanceof Error?v.message:"Failed to set default payment method.";throw l(h),n("error"),v}},[e]),status:r,error:o}},Vt=e=>{const[r,n]=s.useState("idle"),[o,l]=s.useState(null);return{updatePaymentMethod:s.useCallback(async(m,v)=>{n("pending"),l(null);try{await $t(e,m,v),n("idle")}catch(h){const j=h instanceof Error?h.message:"Failed to update payment method.";throw l(j),n("error"),h}},[e]),status:r,error:o}},Ht=e=>{const[r,n]=s.useState([]),[o,l]=s.useState("idle"),[c,m]=s.useState(null),[v,h]=s.useState(0),j=s.useRef(null);s.useEffect(()=>{var C;if((C=j.current)==null||C.abort(),!e){j.current=null,n([]),m(null),l("ready");return}const w=new AbortController;return j.current=w,l("loading"),m(null),yr(e,w.signal).then(x=>{w.signal.aborted||(n(x),l("ready"))}).catch(x=>{if(w.signal.aborted||x instanceof DOMException&&x.name==="AbortError")return;const P=x instanceof Error?x.message:"Failed to fetch payment methods.";m(P),l("error")}),()=>{w.abort()}},[e,v]);const _=s.useCallback(()=>{h(w=>w+1)},[]);return{items:r,status:o,error:c,refetch:_}},qt=({open:e,onClose:r,title:n,titleId:o,formId:l,saveDisabled:c,saveLabel:m="Save",isSaving:v=!1,testIdPrefix:h="payment-method",children:j})=>(s.useEffect(()=>{if(!e)return;const _=w=>{w.key==="Escape"&&r()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[e,r]),s.useEffect(()=>{if(!e)return;const _=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=_}},[e]),e?a.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":o,className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4",onClick:_=>{_.target===_.currentTarget&&r()},"data-testid":`${h}-modal`,children:a.jsxs("div",{className:"flex max-h-full w-full max-w-md flex-col rounded-xl bg-white shadow-2xl",children:[a.jsxs("div",{className:"flex items-center gap-3 border-b border-grayWarm-200 px-4 py-3",children:[a.jsx("button",{type:"button",onClick:r,"aria-label":`Close ${n.toLowerCase()} dialog`,className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg bg-grayWarm-100 p-2 text-grayWarm-950 transition-colors hover:bg-grayWarm-200","data-testid":`${h}-close`,children:a.jsx("svg",{viewBox:"0 0 20 20",width:"20",height:"20","aria-hidden":"true",children:a.jsx("path",{d:"M5 5L15 15M15 5L5 15",stroke:"currentColor",strokeWidth:"1.67",strokeLinecap:"round",strokeLinejoin:"round"})})}),a.jsx("h2",{id:o,className:"flex-1 text-center text-base font-semibold text-grayWarm-900",children:n}),a.jsx("span",{"aria-hidden":"true",className:"h-9 w-9 flex-shrink-0"})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:j}),a.jsxs("div",{className:"flex gap-3 border-t border-grayWarm-200 p-4",children:[a.jsx("button",{type:"button",onClick:r,className:"inline-flex h-11 flex-1 items-center justify-center rounded-lg border border-grayWarm-300 px-4 text-sm font-semibold text-grayWarm-900 transition-colors hover:border-grayWarm-900 hover:shadow-[0_0_0_1px_#1c1917]","data-testid":`${h}-cancel`,children:"Cancel"}),a.jsx("button",{type:"submit",form:l,disabled:v?!1:c,"aria-disabled":v||c,"aria-busy":v,className:X("inline-flex h-11 flex-1 items-center justify-center rounded-lg bg-brand-500 px-4 text-sm font-semibold text-white transition-colors",v?"cursor-not-allowed opacity-90 pointer-events-none":"hover:bg-brand-600 disabled:cursor-not-allowed disabled:bg-grayWarm-300 disabled:text-grayWarm-500"),"data-testid":`${h}-save`,children:v?a.jsxs(a.Fragment,{children:[a.jsxs("svg",{className:"h-[18px] w-[18px] animate-spin",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeOpacity:"0.25"}),a.jsx("path",{d:"M22 12a10 10 0 0 1-10 10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]}),a.jsx("span",{className:"sr-only",children:"Saving"})]}):m})]})]})}):null),Sr=({open:e,onClose:r,formId:n,saveDisabled:o,saveLabel:l="Save",isSaving:c=!1,children:m})=>a.jsx(qt,{open:e,onClose:r,title:"Add payment method",titleId:"movmo-add-payment-title",formId:n,saveDisabled:o,saveLabel:l,isSaving:c,testIdPrefix:"add-payment-method",children:m}),Pr=(e,r)=>`${String(e).padStart(2,"0")}/${r}`,Tr=e=>{if(!e)return"Card";const r=e.toLowerCase();return r==="amex"?"Amex":r.charAt(0).toUpperCase()+r.slice(1)},Fr=({open:e,method:r,onClose:n,onSave:o,isSaving:l=!1,error:c=null})=>{const m=s.useId(),[v,h]=s.useState(""),[j,_]=s.useState("");if(s.useEffect(()=>{e&&r&&(h(r.cardholderName??""),_(r.zip??""))},[e,r]),!r)return null;const w=v.trim(),C=j.trim(),x=w!==(r.cardholderName??"").trim(),P=C!==(r.zip??"").trim(),M=x||P,I=(!x||w.length>0)&&(!P||It(C)),k=!M||!I,E=O=>{if(O.preventDefault(),k||l)return;const pe={};x&&(pe.cardholderName=w),P&&(pe.zip=C),o(pe).catch(()=>{})};return a.jsxs(qt,{open:e,onClose:n,title:"Edit payment method",titleId:"movmo-edit-payment-title",formId:m,saveDisabled:k,isSaving:l,testIdPrefix:"edit-payment-method",children:[a.jsxs("div",{className:"mb-4 flex items-start gap-3 rounded-lg bg-grayWarm-50 p-3","data-testid":"edit-payment-method-context",children:[a.jsx(Ie,{brand:r.brand,className:"flex-shrink-0"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"text-lg font-semibold text-grayWarm-950",children:[Tr(r.brand)," •••• ",r.last4]}),a.jsxs("div",{className:"text-sm text-grayWarm-600",children:["Exp. ",Pr(r.expMonth,r.expYear)]})]})]}),a.jsxs("form",{id:m,onSubmit:E,className:"flex flex-col gap-4",noValidate:!0,children:[a.jsxs("label",{className:"flex flex-col gap-1.5 text-sm font-medium text-grayWarm-700",children:["Cardholder name",a.jsx("input",{type:"text",autoComplete:"cc-name",value:v,onChange:O=>h(O.target.value),disabled:l,maxLength:255,"data-testid":"edit-payment-method-cardholder",className:"h-11 rounded-lg border border-grayWarm-300 px-3 text-base font-normal text-grayWarm-950 focus:border-grayWarm-950 focus:outline-none focus:ring-1 focus:ring-grayWarm-950"})]}),a.jsxs("label",{className:"flex flex-col gap-1.5 text-sm font-medium text-grayWarm-700",children:["Postal code",a.jsx("input",{type:"text",autoComplete:"postal-code",value:j,onChange:O=>_(zt(O.target.value)),disabled:l,"data-testid":"edit-payment-method-zip",className:"h-11 rounded-lg border border-grayWarm-300 px-3 text-base font-normal text-grayWarm-950 focus:border-grayWarm-950 focus:outline-none focus:ring-1 focus:ring-grayWarm-950"})]}),c?a.jsx("p",{role:"alert",className:"text-sm text-error-700","data-testid":"edit-payment-method-error",children:c}):null]})]})},Or=e=>{if(!e)return"Card";const r=e.toLowerCase();return r==="amex"?"Amex":r.charAt(0).toUpperCase()+r.slice(1)},Gt=({method:e,trailing:r,onClick:n,cardLabelFormat:o="branded",className:l})=>a.jsxs("div",{className:X("flex items-center gap-3",n&&"cursor-pointer",l),onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:n?c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),n())}:void 0,"data-testid":`payment-method-preview-${e.id}`,children:[a.jsx(Ie,{brand:e.brand,width:34,className:"flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-lg font-semibold text-grayWarm-950",children:o==="masked"?`•••• ${e.last4}`:`${Or(e.brand)} ${e.last4}`}),r]}),Wr=(e,r,n=new Date)=>r<n.getFullYear()||r===n.getFullYear()&&e<n.getMonth()+1,Tt=e=>{if(!e)return"Card";const r=e.toLowerCase();return r==="amex"?"Amex":r.charAt(0).toUpperCase()+r.slice(1)},Mr=(e,r)=>`${String(e).padStart(2,"0")}/${r}`,Ar=({method:e,selectable:r,selected:n,onSelect:o,onSetDefault:l,onRemove:c,onEdit:m,disabled:v,showDefaultBadge:h,hideSetDefaultMenuItem:j,cardLabelFormat:_="branded"})=>{const[w,C]=s.useState(!1),x=s.useRef(null),P=Wr(e.expMonth,e.expYear);s.useEffect(()=>{if(!w)return;const I=k=>{var E;(E=x.current)!=null&&E.contains(k.target)||C(!1)};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[w]);const M=()=>{r&&o&&!v&&o(e)};return a.jsxs("div",{className:X("flex items-start gap-3 transition-colors",r?"rounded-lg border px-3 py-3":"py-4",r&&!v&&"cursor-pointer",r&&(n?"border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]":"border-grayWarm-200 hover:border-grayWarm-300")),onClick:M,"data-testid":`payment-method-row-${e.id}`,children:[r?a.jsx("input",{type:"radio",name:"movmo-payment-method",checked:n,onChange:()=>o==null?void 0:o(e),onClick:I=>I.stopPropagation(),"aria-label":`Select ${Tt(e.brand)} ending ${e.last4}`,className:"mr-1 h-4 w-4 mt-2 cursor-pointer appearance-none rounded-full border-2 border-grayWarm-300 checked:border-[5px] checked:border-grayWarm-950 bg-white checked:bg-white focus:ring-0 focus:ring-offset-0",disabled:v}):null,a.jsx(Ie,{brand:e.brand,className:"flex-shrink-0"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx("span",{className:"text-lg font-semibold text-grayWarm-950",children:_==="masked"?`•••• ${e.last4}`:`${Tt(e.brand)} ${e.last4}`}),h&&e.isDefault?a.jsx("span",{className:"inline-flex items-center rounded-full bg-success-50 px-2 py-0.5 text-xs font-semibold text-success-700","data-testid":`badge-default-${e.id}`,children:"Default"}):null,P?a.jsx("span",{className:"inline-flex items-center rounded-full bg-error-50 px-2 py-0.5 text-xs font-semibold text-error-700","data-testid":`badge-expired-${e.id}`,children:"Expired"}):null]}),a.jsxs("div",{className:X("text-base",P?"text-grayWarm-400":"text-grayWarm-600"),children:["Exp. ",Mr(e.expMonth,e.expYear)]})]}),a.jsxs("div",{className:"relative flex-shrink-0",ref:x,children:[a.jsx("button",{type:"button","aria-label":`Open actions for card ending ${e.last4}`,"aria-haspopup":"menu","aria-expanded":w,className:"rounded-lg p-2 text-grayWarm-600 transition-colors hover:bg-grayWarm-100 disabled:cursor-not-allowed disabled:opacity-50",disabled:v,onClick:I=>{I.stopPropagation(),C(k=>!k)},"data-testid":`menu-trigger-${e.id}`,children:a.jsx("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"currentColor","aria-hidden":"true",children:a.jsx("path",{d:"M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"})})}),w?a.jsxs("div",{role:"menu",className:X("absolute z-10 whitespace-nowrap rounded-lg border border-grayWarm-200 bg-white py-1 shadow-lg",r?"bottom-full left-1/2 mb-2 -translate-x-1/2":"right-0 top-full mt-1"),onClick:I=>I.stopPropagation(),"data-testid":`menu-${e.id}`,children:[r?a.jsx("span",{"aria-hidden":"true",className:"absolute -bottom-1.5 left-1/2 h-3 w-3 -translate-x-1/2 rotate-45 border-b border-r border-grayWarm-200 bg-white"}):null,!e.isDefault&&!j?a.jsx("button",{type:"button",role:"menuitem",className:"block w-full px-4 py-1 text-left text-md font-semibold text-grayWarm-950 hover:text-grayWarm-700",onClick:()=>{C(!1),l(e)},"data-testid":`menu-set-default-${e.id}`,children:"Set as default"}):null,m&&e.vault==="spreedly"?a.jsx("button",{type:"button",role:"menuitem",className:"block w-full px-4 py-1 text-left text-md font-semibold text-grayWarm-950 hover:text-grayWarm-700",onClick:()=>{C(!1),m(e)},"data-testid":`menu-edit-${e.id}`,children:"Edit"}):null,a.jsx("button",{type:"button",role:"menuitem",className:"block w-full px-4 py-1 text-left text-md font-semibold text-error-700 hover:text-error-500",onClick:()=>{C(!1),c(e)},"data-testid":`menu-remove-${e.id}`,children:"Delete"})]}):null]})]})},Dr=e=>`${Ye().iconCdnBaseUrl}/website/assets/icons/payments/${e}.svg`,yt=({slug:e,alt:r})=>a.jsx("img",{src:Dr(e),alt:r,height:20,loading:"lazy",style:{height:20,width:"auto"}}),ut=({type:e,label:r,iconNode:n,disabled:o=!1})=>a.jsxs("label",{className:"flex cursor-pointer items-center gap-3 rounded-lg border border-grayWarm-200 px-4 py-3 transition-colors hover:border-grayWarm-300","data-testid":`payment-type-${e}`,children:[a.jsx("input",{type:"radio",name:"movmo-payment-type",value:e,disabled:o,onChange:()=>{},className:X("h-4 w-4 accent-grayWarm-900",o?"cursor-not-allowed":"cursor-pointer"),"aria-label":r}),a.jsxs("span",{className:"flex flex-1 items-center gap-2 text-sm font-semibold text-grayWarm-900",children:[r,n]})]}),Ft=({selected:e,onSelect:r,creditCardBody:n,disabled:o=!1,className:l})=>{const c=e==="credit_card";return a.jsxs("div",{className:X("flex w-full flex-col gap-3",l),children:[a.jsxs("label",{className:X("flex cursor-pointer flex-col gap-3 rounded-lg border px-4 py-3 transition-colors",c?"border-grayWarm-900 shadow-[0_0_0_1px_#1c1917]":"border-grayWarm-200"),"data-testid":"payment-type-credit_card",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("input",{type:"radio",name:"movmo-payment-type",value:"credit_card",checked:c,disabled:o,onChange:()=>{o||r("credit_card")},className:X("h-4 w-4 accent-grayWarm-900",o?"cursor-not-allowed":"cursor-pointer"),"aria-label":"Credit card"}),a.jsx("span",{className:"flex-1 text-sm font-semibold text-grayWarm-900",children:"Credit card"}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(Ie,{brand:"mastercard",width:28}),a.jsx(Ie,{brand:"visa",width:28}),a.jsx(Ie,{brand:"amex",width:28}),a.jsx(Ie,{brand:"discover",width:28})]})]}),c?a.jsx("div",{"data-testid":"payment-type-credit_card-body",children:n}):null]}),c?a.jsx("p",{className:"mt-2 text-sm font-semibold text-grayWarm-900","data-testid":"payment-type-other-options-header",children:"Other options"}):null,a.jsx(ut,{type:"paypal",label:"PayPal",iconNode:a.jsx(yt,{slug:"paypal",alt:"PayPal"}),disabled:o}),a.jsx(ut,{type:"googlepay",label:"GooglePay",iconNode:a.jsx(yt,{slug:"google-pay",alt:"GooglePay"}),disabled:o}),a.jsx(ut,{type:"klarna",label:"Klarna",iconNode:a.jsx(yt,{slug:"klarna",alt:"Klarna"}),disabled:o}),a.jsx(ut,{type:"ach",label:"Bank account (ACH)",iconNode:a.jsx("span",{className:"text-xs font-medium text-grayWarm-500",children:"Direct debit"}),disabled:o})]})},Ot="movmo-add-payment-form",$r=e=>{console.error("@movmo_app/payments: failed to update payment method",e);const r=e instanceof Error?e.message.trim():"";return/spreedly-backed cards/i.test(r)?"This card's details can't be edited.":r||"Failed to update payment method."},Wt=e=>{const r=e.filter(o=>o.isDefault),n=e.filter(o=>!o.isDefault);return[...r,...n]},Mt=({message:e,testId:r})=>a.jsx("p",{role:"alert","aria-live":"polite",className:"mt-3 rounded-md bg-error-50 px-3 py-2 text-sm text-error-700","data-testid":r,children:e}),At=({withDefaultBadge:e=!1})=>a.jsxs("div",{className:"flex items-start justify-between py-4","data-testid":"payment-method-skeleton",children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"h-8 w-[46px] flex-shrink-0 animate-pulse rounded bg-grayWarm-200"}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"h-5 w-[120px] animate-pulse rounded bg-grayWarm-200"}),e?a.jsx("div",{className:"h-5 w-[56px] animate-pulse rounded-full bg-grayWarm-200"}):null]}),a.jsx("div",{className:"h-4 w-[100px] animate-pulse rounded bg-grayWarm-200"})]})]}),a.jsx("div",{className:"h-5 w-5 flex-shrink-0 animate-pulse rounded-full bg-grayWarm-200"})]}),Kt=({userId:e,defaultCardholderName:r,defaultCardholderFirstName:n,defaultCardholderLastName:o,selectedId:l,onSelect:c,onChange:m,onError:v,onEvent:h,paymentTypeSelector:j=!0,autoSaveFirstCard:_=!0,selectionSetsDefault:w=!1,showDefaultBadge:C=!0,collapsible:x=!1,cardLabelFormat:P="branded",className:M})=>{const{items:I,status:k,error:E,refetch:O}=Ht(e),{deletePaymentMethod:pe,status:de}=Bt(e),{setDefault:we,status:ue}=Yt(e),{updatePaymentMethod:se,status:Q}=Vt(e),[b,ye]=s.useState([]),_e=s.useRef(b);s.useEffect(()=>{_e.current=b},[b]);const[z,p]=s.useState(null),[y,S]=s.useState(!1),[A,re]=s.useState(null),[ae,q]=s.useState(!1),[G,V]=s.useState(!1),[T,K]=s.useState(null),[Ce,ve]=s.useState(null),[J,Ee]=s.useState(null),[Z,Pe]=s.useState(!1),Re=s.useRef(!1),oe=s.useRef(v);s.useEffect(()=>{oe.current=v},[v]);const ee=s.useCallback(u=>{var B;(B=oe.current)==null||B.call(oe,u)},[]),Te=s.useRef(h);s.useEffect(()=>{Te.current=h},[h]);const $=s.useCallback((u,B)=>{var L;(L=Te.current)==null||L.call(Te,u,B)},[]),ie=s.useRef(!1),ke=s.useCallback(u=>{if(u.touchedInvalid.length===0){ie.current=!1;return}ie.current||(ie.current=!0,$("validation_error",{field_count:u.touchedInvalid.length,fields:u.touchedInvalid}))},[$]),te=s.useCallback(()=>{S(!1),re(null),Ee(null),ie.current=!1},[]),je=r??([n,o].filter(Boolean).join(" ")||void 0);s.useEffect(()=>{k==="ready"&&ye(Wt(I))},[I,k]);const Fe=s.useRef(null);s.useEffect(()=>{if(k==="error"&&E){if(Fe.current===E)return;Fe.current=E,ee({source:"list",message:E})}else k!=="error"&&(Fe.current=null)},[k,E,ee]),s.useEffect(()=>{if(!c||Re.current||k!=="ready"||b.length===0||l)return;Re.current=!0,$("autoselected",{had_saved_methods:!0});const u=b.find(B=>B.isDefault)??b[0];c(u)},[c,k,b,l,$]);const he=s.useCallback(u=>{ye(B=>{const L=typeof u=="function"?u(B):u,U=Wt(L);return queueMicrotask(()=>m==null?void 0:m(U)),U})},[m]),ze=de==="pending"||ue==="pending"||Q==="pending",ge=s.useCallback(async u=>{const B=b;p(null),he(L=>L.map(U=>({...U,isDefault:U.id===u.id})));try{await we(u.id),O(),$("set_default")}catch(L){ye(B),m==null||m(B);const U=L instanceof Error?L.message:"Failed to set default payment method.";p(U),ee({...nt("set-default",L,"Failed to set default payment method."),message:U})}},[b,he,we,O,m,ee,$]),le=s.useCallback(u=>{c==null||c(u),w&&(u.isDefault||ge(u))},[c,w,ge]),Oe=s.useCallback(u=>{$("selected",{method_count:b.length}),le(u)},[$,b,le]),We=s.useCallback(async u=>{const B=b;p(null);const L=b.filter(Me=>Me.id!==u.id);he(()=>L);const U=u.id===l&&c?L.find(Me=>Me.isDefault)??L[0]??null:null;U&&le(U);const xe=!!U&&w&&U!==null&&!U.isDefault;try{await pe(u.id),xe||O(),$("deleted",{remaining_count:L.length})}catch(Me){ye(B),m==null||m(B);const ct=Me instanceof Error?Me.message:"Failed to delete payment method.";p(ct),ee({...nt("delete",Me,"Failed to delete payment method."),message:ct})}},[b,he,pe,O,m,l,c,le,w,ee,$]),Ae=s.useCallback(u=>{ve(null),K(u)},[]),Le=s.useCallback(()=>{K(null),ve(null)},[]),De=s.useCallback(async u=>{if(!T)return;const B=T,L=b;ve(null),he(U=>U.map(xe=>xe.id===B.id?{...xe,...u.cardholderName!==void 0?{cardholderName:u.cardholderName}:{},...u.zip!==void 0?{zip:u.zip}:{}}:xe));try{await se(B.id,u),Le(),O(),$("edited",{fields:Object.keys(u)})}catch(U){ye(L),m==null||m(L);const xe=$r(U);ve(xe),ee({...nt("update",U,xe),message:xe})}},[T,b,he,se,O,m,Le,ee,$]),Ne=s.useCallback(u=>{te(),he(L=>[u,...L.filter(U=>U.id!==u.id)]),le(u),!!c&&w&&!u.isDefault||O(),$("added",{method_count:_e.current.length+1})},[te,he,O,le,c,w,$]),f=s.useCallback(u=>{re(u)},[]),D=s.useCallback(u=>{V(u),u&&re(null)},[]),me=k==="ready"&&b.length===0,ne=typeof c=="function",st=!ne&&!x,ot=b.length===0,it=_&&b.length===0,$e=s.useCallback(u=>a.jsx(Et,{userId:e,isDefault:ot,defaultCardholderName:je,autoSave:!u&&it,hideInternalSaveButton:u,formId:u?Ot:void 0,onCanSubmitChange:u?q:void 0,onSavingChange:D,autoFocus:u?"number":void 0,onSuccess:Ne,onError:f,onErrorDetail:ee,onValidationChange:ke}),[e,ot,je,it,Ne,f,D,ee,ke]),Ve=s.useMemo(()=>$e(!1),[$e]),Se=s.useMemo(()=>$e(!0),[$e]),Ue=!e,Qe=s.useMemo(()=>j?a.jsx(Ft,{selected:J,onSelect:u=>Ee(u),creditCardBody:Ve,disabled:Ue}):Ve,[j,J,Ve,Ue]),lt=s.useMemo(()=>j?a.jsx(Ft,{selected:J,onSelect:u=>Ee(u),creditCardBody:Se,disabled:Ue}):Se,[j,J,Se,Ue]);return a.jsxs("div",{className:X("flex w-full flex-col gap-4",M),"data-testid":"payment-methods-manager",children:[k==="loading"&&b.length===0?a.jsxs("div",{className:X(st?"flex flex-col divide-y divide-grayWarm-200 rounded-xl border border-grayWarm-200 px-4 md:px-6":"flex flex-col gap-2"),"data-testid":"payment-methods-loading",children:[a.jsx(At,{withDefaultBadge:!0}),a.jsx(At,{})]}):null,k==="error"?a.jsxs("div",{role:"alert","aria-live":"polite",className:"flex items-center justify-between gap-3 rounded-md bg-error-50 p-3 text-sm text-error-700","data-testid":"payment-methods-list-error",children:[a.jsx("span",{children:E??"Failed to load payment methods."}),a.jsx("button",{type:"button",onClick:O,className:"rounded-md border border-error-700 px-3 py-1 text-xs font-semibold text-error-700 hover:bg-error-50",children:"Retry"})]}):null,z?a.jsx("div",{role:"alert","aria-live":"polite",className:"rounded-md bg-error-50 p-3 text-sm text-error-700","data-testid":"payment-methods-mutation-error",children:z}):null,x&&b.length>0?a.jsx("div",{className:"border-t border-grayWarm-200 pt-4",children:a.jsxs("div",{className:"flex items-center justify-between","data-testid":Z?"payment-methods-drawer-header":"payment-methods-collapsed-preview",children:[Z?a.jsx("h3",{className:"text-md font-semibold text-grayWarm-950",children:"Payment methods"}):a.jsx(Gt,{method:b.find(u=>u.id===l)??b.find(u=>u.isDefault)??b[0],cardLabelFormat:P,className:"flex-1"}),a.jsx("button",{type:"button","aria-label":Z?"Collapse payment methods":"Expand payment methods","aria-expanded":Z,className:"bg-grayWarm-100 p-2 rounded-lg hover:bg-grayWarm-200 transition-colors",onClick:()=>Pe(u=>!u),"data-testid":Z?"payment-methods-drawer-close":"payment-methods-drawer-open",children:a.jsx("img",{src:`${Ye().iconCdnBaseUrl}/website/assets/icons/chevron-${Z?"up":"down"}-double.svg`,alt:"",className:"w-5 h-5"})})]})}):null,b.length>0&&(!x||Z)?a.jsx("div",{className:X("flex flex-col",st?"rounded-xl border border-grayWarm-200 px-4 md:px-6 divide-y divide-grayWarm-200":"space-y-3"),children:b.map(u=>a.jsx(Ar,{method:u,selectable:ne,selected:ne&&u.id===l,onSelect:Oe,onSetDefault:ge,onRemove:We,onEdit:Ae,disabled:ze,showDefaultBadge:C,hideSetDefaultMenuItem:w,cardLabelFormat:P},u.id))}):null,me?a.jsxs("div",{"data-testid":"payment-methods-empty",children:[Qe,A&&!y?a.jsx(Mt,{message:A,testId:"payment-methods-inline-error"}):null]}):b.length>0&&(!x||Z)?a.jsx("button",{type:"button",onClick:()=>{re(null),Ee(null),q(!1),S(!0),ie.current=!1},onMouseEnter:()=>{xt().catch(()=>{})},onFocus:()=>{xt().catch(()=>{})},className:"self-start rounded-lg bg-brand-50 px-6 py-3 text-md font-semibold text-brand-600 transition-colors hover:bg-brand-100","data-testid":"payment-methods-add-trigger",children:"Add payment method"}):null,a.jsxs(Sr,{open:y,onClose:te,formId:Ot,saveDisabled:!ae,isSaving:G,children:[lt,A?a.jsx(Mt,{message:A,testId:"payment-methods-modal-error"}):null]}),a.jsx(Fr,{open:T!==null,method:T,onClose:Le,onSave:De,isSaving:Q==="pending",error:Ce})]})};Kt.displayName="PaymentMethodsManager";const Ur="/v1/auth/",Ir="movmo_csrf_token",Jt=new Set(["reauth_required","movmo_session_required","first_party_only","recovery_cooldown"]),zr=e=>{if(typeof document>"u")return null;const r=document.cookie?document.cookie.split(";"):[];for(const n of r){const o=n.trim();if(o.startsWith(e+"="))return decodeURIComponent(o.substring(e.length+1))}return null},Lr=e=>typeof e=="string"?e:e instanceof URL?e.href:e.url,Br=()=>{if(typeof globalThis<"u"&&typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error("@movmo_app/payments: no global fetch available in this environment")},Yr=e=>{const{refreshSession:r,onRefreshFailed:n,csrfCookieName:o=Ir,extraHeaders:l,authPathFragment:c=Ur,baseFetch:m=Br(),readCookie:v=zr}=e,h=new Set(e.noRefreshCodes??Jt);let j=null;const _=()=>{if(j)return j;const C=(async()=>{await r()})();return j=C,C.finally(()=>{j===C&&(j=null)}).catch(()=>{}),C},w=(C,x)=>{const P=new Headers(x==null?void 0:x.headers),M=v(o);if(M&&!P.has("X-CSRF-Token")&&P.set("X-CSRF-Token",M),l){const I=l(C,x);for(const[k,E]of Object.entries(I))P.has(k)||P.set(k,E)}return{...x,headers:P,credentials:(x==null?void 0:x.credentials)??"include"}};return async function(x,P){const M=await m(x,w(x,P));if(Lr(x).includes(c)||M.status!==401&&M.status!==403)return M;if(M.status===403)try{const E=await M.clone().json(),O=E==null?void 0:E.code;if(typeof O=="string"&&h.has(O))return M}catch{}try{await _()}catch(E){try{n(E)}catch(O){console.error("@movmo_app/payments: onRefreshFailed callback threw — auth retry path is misconfigured",O)}return M}try{return await m(x,w(x,P))}catch(E){return console.error("@movmo_app/payments: retry after token refresh failed — returning original response",E),M}}};exports.DEFAULT_NO_REFRESH_CODES=Jt;exports.MovmoCardForm=Et;exports.PaymentMethodPreview=Gt;exports.PaymentMethodsManager=Kt;exports.PaymentsApiError=wt;exports.createMovmoAuthFetch=Yr;exports.getPaymentsConfig=Ye;exports.setPaymentsConfig=cr;exports.useDeletePaymentMethod=Bt;exports.useMovmoCardFields=Ut;exports.useSetDefaultPaymentMethod=Yt;exports.useUpdatePaymentMethod=Vt;exports.useUserPaymentMethods=Ht;
31
31
  //# sourceMappingURL=index.cjs.js.map