@movmo_app/payments 0.4.0 → 0.5.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/dist/index.cjs.js +10 -10
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +81 -2
- package/dist/index.es.js +1053 -983
- package/dist/index.es.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react");var
|
|
1
|
+
"use strict";var Jt=Object.defineProperty;var Zt=(t,r,n)=>r in t?Jt(t,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[r]=n;var at=(t,r,n)=>Zt(t,typeof r!="symbol"?r+"":r,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react");var ct={exports:{}},Ye={};/**
|
|
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
|
|
9
|
+
*/var gt;function Xt(){if(gt)return Ye;gt=1;var t=s,r=Symbol.for("react.element"),n=Symbol.for("react.fragment"),o=Object.prototype.hasOwnProperty,l=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,d={key:!0,ref:!0,__self:!0,__source:!0};function f(g,m,F){var v,w={},p=null,j=null;F!==void 0&&(p=""+F),m.key!==void 0&&(p=""+m.key),m.ref!==void 0&&(j=m.ref);for(v in m)o.call(m,v)&&!d.hasOwnProperty(v)&&(w[v]=m[v]);if(g&&g.defaultProps)for(v in m=g.defaultProps,m)w[v]===void 0&&(w[v]=m[v]);return{$$typeof:r,type:g,key:p,ref:j,props:w,_owner:l.current}}return Ye.Fragment=n,Ye.jsx=f,Ye.jsxs=f,Ye}var Ve={};/**
|
|
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
|
|
18
|
-
`+
|
|
19
|
-
`),
|
|
20
|
-
`),
|
|
21
|
-
`+
|
|
17
|
+
*/var bt;function Qt(){return bt||(bt=1,process.env.NODE_ENV!=="production"&&function(){var t=s,r=Symbol.for("react.element"),n=Symbol.for("react.portal"),o=Symbol.for("react.fragment"),l=Symbol.for("react.strict_mode"),d=Symbol.for("react.profiler"),f=Symbol.for("react.provider"),g=Symbol.for("react.context"),m=Symbol.for("react.forward_ref"),F=Symbol.for("react.suspense"),v=Symbol.for("react.suspense_list"),w=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),j=Symbol.for("react.offscreen"),W=Symbol.iterator,ee="@@iterator";function C(e){if(e===null||typeof e!="object")return null;var i=W&&e[W]||e[ee];return typeof i=="function"?i:null}var S=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function E(e){{for(var i=arguments.length,c=new Array(i>1?i-1:0),y=1;y<i;y++)c[y-1]=arguments[y];re("error",e,c)}}function re(e,i,c){{var y=S.ReactDebugCurrentFrame,T=y.getStackAddendum();T!==""&&(i+="%s",c=c.concat([T]));var M=c.map(function(R){return String(R)});M.unshift("Warning: "+i),Function.prototype.apply.call(console[e],console,M)}}var Z=!1,de=!1,ye=!1,V=!1,ae=!1,x;x=Symbol.for("react.module.reference");function ne(e){return!!(typeof e=="string"||typeof e=="function"||e===o||e===d||ae||e===l||e===F||e===v||V||e===j||Z||de||ye||typeof e=="object"&&e!==null&&(e.$$typeof===p||e.$$typeof===w||e.$$typeof===f||e.$$typeof===g||e.$$typeof===m||e.$$typeof===x||e.getModuleId!==void 0))}function Ce(e,i,c){var y=e.displayName;if(y)return y;var T=i.displayName||i.name||"";return T!==""?c+"("+T+")":c}function ve(e){return e.displayName||"Context"}function P(e){if(e==null)return null;if(typeof e.tag=="number"&&E("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 n:return"Portal";case d:return"Profiler";case l:return"StrictMode";case F:return"Suspense";case v:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case g:var i=e;return ve(i)+".Consumer";case f:var c=e;return ve(c._context)+".Provider";case m:return Ce(e,e.render,"ForwardRef");case w:var y=e.displayName||null;return y!==null?y:P(e.type)||"Memo";case p:{var T=e,M=T._payload,R=T._init;try{return P(R(M))}catch{return null}}}return null}var b=Object.assign,h=0,k,A,J,ue,q,B,I;function O(){}O.__reactDisabledLog=!0;function L(){{if(h===0){k=console.log,A=console.info,J=console.warn,ue=console.error,q=console.group,B=console.groupCollapsed,I=console.groupEnd;var e={configurable:!0,enumerable:!0,value:O,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}h++}}function fe(){{if(h--,h===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:b({},e,{value:k}),info:b({},e,{value:A}),warn:b({},e,{value:J}),error:b({},e,{value:ue}),group:b({},e,{value:q}),groupCollapsed:b({},e,{value:B}),groupEnd:b({},e,{value:I})})}h<0&&E("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ce=S.ReactCurrentDispatcher,X;function je(e,i,c){{if(X===void 0)try{throw Error()}catch(T){var y=T.stack.trim().match(/\n( *(at )?)/);X=y&&y[1]||""}return`
|
|
18
|
+
`+X+e}}var ke=!1,me;{var se=typeof WeakMap=="function"?WeakMap:Map;me=new se}function xe(e,i){if(!e||ke)return"";{var c=me.get(e);if(c!==void 0)return c}var y;ke=!0;var T=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var M;M=ce.current,ce.current=null,L();try{if(i){var R=function(){throw Error()};if(Object.defineProperty(R.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(R,[])}catch(le){y=le}Reflect.construct(e,[],R)}else{try{R.call()}catch(le){y=le}e.call(R.prototype)}}else{try{throw Error()}catch(le){y=le}e()}}catch(le){if(le&&y&&typeof le.stack=="string"){for(var _=le.stack.split(`
|
|
19
|
+
`),te=y.stack.split(`
|
|
20
|
+
`),U=_.length-1,z=te.length-1;U>=1&&z>=0&&_[U]!==te[z];)z--;for(;U>=1&&z>=0;U--,z--)if(_[U]!==te[z]){if(U!==1||z!==1)do if(U--,z--,z<0||_[U]!==te[z]){var he=`
|
|
21
|
+
`+_[U].replace(" at new "," at ");return e.displayName&&he.includes("<anonymous>")&&(he=he.replace("<anonymous>",e.displayName)),typeof e=="function"&&me.set(e,he),he}while(U>=1&&z>=0);break}}}finally{ke=!1,ce.current=M,fe(),Error.prepareStackTrace=T}var Me=e?e.displayName||e.name:"",Pe=Me?je(Me):"";return typeof e=="function"&&me.set(e,Pe),Pe}function ge(e,i,c){return xe(e,!1)}function _e(e){var i=e.prototype;return!!(i&&i.isReactComponent)}function K(e,i,c){if(e==null)return"";if(typeof e=="function")return xe(e,_e(e));if(typeof e=="string")return je(e);switch(e){case F:return je("Suspense");case v:return je("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case m:return ge(e.render);case w:return K(e.type,i,c);case p:{var y=e,T=y._payload,M=y._init;try{return K(M(T),i,c)}catch{}}}return""}var be=Object.prototype.hasOwnProperty,Re={},pe=S.ReactDebugCurrentFrame;function we(e){if(e){var i=e._owner,c=K(e.type,e._source,i?i.type:null);pe.setExtraStackFrame(c)}else pe.setExtraStackFrame(null)}function N(e,i,c,y,T){{var M=Function.call.bind(be);for(var R in e)if(M(e,R)){var _=void 0;try{if(typeof e[R]!="function"){var te=Error((y||"React class")+": "+c+" type `"+R+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[R]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw te.name="Invariant Violation",te}_=e[R](i,R,y,c,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(U){_=U}_&&!(_ instanceof Error)&&(we(T),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).",y||"React class",c,R,typeof _),we(null)),_ instanceof Error&&!(_.message in Re)&&(Re[_.message]=!0,we(T),E("Failed %s type: %s",c,_.message),we(null))}}}var D=Array.isArray;function Y(e){return D(e)}function oe(e){{var i=typeof Symbol=="function"&&Symbol.toStringTag,c=i&&e[Symbol.toStringTag]||e.constructor.name||"Object";return c}}function Ge(e){try{return He(e),!1}catch{return!0}}function He(e){return""+e}function Fe(e){if(Ge(e))return E("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",oe(e)),He(e)}var Ie=S.ReactCurrentOwner,Je={key:!0,ref:!0,__self:!0,__source:!0},Le,Se;function ze(e){if(be.call(e,"ref")){var i=Object.getOwnPropertyDescriptor(e,"ref").get;if(i&&i.isReactWarning)return!1}return e.ref!==void 0}function Be(e){if(be.call(e,"key")){var i=Object.getOwnPropertyDescriptor(e,"key").get;if(i&&i.isReactWarning)return!1}return e.key!==void 0}function Qe(e,i){typeof e.ref=="string"&&Ie.current}function et(e,i){{var c=function(){Le||(Le=!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))};c.isReactWarning=!0,Object.defineProperty(e,"key",{get:c,configurable:!0})}}function u(e,i){{var c=function(){Se||(Se=!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))};c.isReactWarning=!0,Object.defineProperty(e,"ref",{get:c,configurable:!0})}}var G=function(e,i,c,y,T,M,R){var _={$$typeof:r,type:e,key:i,ref:c,props:R,_owner:M};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:T}),Object.freeze&&(Object.freeze(_.props),Object.freeze(_)),_};function H(e,i,c,y,T){{var M,R={},_=null,te=null;c!==void 0&&(Fe(c),_=""+c),Be(i)&&(Fe(i.key),_=""+i.key),ze(i)&&(te=i.ref,Qe(i,T));for(M in i)be.call(i,M)&&!Je.hasOwnProperty(M)&&(R[M]=i[M]);if(e&&e.defaultProps){var U=e.defaultProps;for(M in U)R[M]===void 0&&(R[M]=U[M])}if(_||te){var z=typeof e=="function"?e.displayName||e.name||"Unknown":e;_&&et(R,z),te&&u(R,z)}return G(e,_,te,T,y,Ie.current,R)}}var $=S.ReactCurrentOwner,Ee=S.ReactDebugCurrentFrame;function ie(e){if(e){var i=e._owner,c=K(e.type,e._source,i?i.type:null);Ee.setExtraStackFrame(c)}else Ee.setExtraStackFrame(null)}var We;We=!1;function tt(e){return typeof e=="object"&&e!==null&&e.$$typeof===r}function mt(){{if($.current){var e=P($.current.type);if(e)return`
|
|
22
22
|
|
|
23
|
-
Check the render method of \``+e+"`."}return""}}function
|
|
23
|
+
Check the render method of \``+e+"`."}return""}}function It(e){return""}var pt={};function Lt(e){{var i=mt();if(!i){var c=typeof e=="string"?e:e.displayName||e.name;c&&(i=`
|
|
24
24
|
|
|
25
|
-
Check the top-level render call using <`+c+">.")}return
|
|
25
|
+
Check the top-level render call using <`+c+">.")}return i}}function ht(e,i){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var c=Lt(i);if(pt[c])return;pt[c]=!0;var y="";e&&e._owner&&e._owner!==$.current&&(y=" It was passed a child from "+P(e._owner.type)+"."),ie(e),E('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',c,y),ie(null)}}function yt(e,i){{if(typeof e!="object")return;if(Y(e))for(var c=0;c<e.length;c++){var y=e[c];tt(y)&&ht(y,i)}else if(tt(e))e._store&&(e._store.validated=!0);else if(e){var T=C(e);if(typeof T=="function"&&T!==e.entries)for(var M=T.call(e),R;!(R=M.next()).done;)tt(R.value)&&ht(R.value,i)}}}function zt(e){{var i=e.type;if(i==null||typeof i=="string")return;var c;if(typeof i=="function")c=i.propTypes;else if(typeof i=="object"&&(i.$$typeof===m||i.$$typeof===w))c=i.propTypes;else return;if(c){var y=P(i);N(c,e.props,"prop",y,e)}else if(i.PropTypes!==void 0&&!We){We=!0;var T=P(i);E("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",T||"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 Bt(e){{for(var i=Object.keys(e.props),c=0;c<i.length;c++){var y=i[c];if(y!=="children"&&y!=="key"){ie(e),E("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",y),ie(null);break}}e.ref!==null&&(ie(e),E("Invalid attribute `ref` supplied to `React.Fragment`."),ie(null))}}var vt={};function xt(e,i,c,y,T,M){{var R=ne(e);if(!R){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 te=It();te?_+=te:_+=mt();var U;e===null?U="null":Y(e)?U="array":e!==void 0&&e.$$typeof===r?(U="<"+(P(e.type)||"Unknown")+" />",_=" Did you accidentally export a JSX literal instead of a component?"):U=typeof e,E("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",U,_)}var z=H(e,i,c,T,M);if(z==null)return z;if(R){var he=i.children;if(he!==void 0)if(y)if(Y(he)){for(var Me=0;Me<he.length;Me++)yt(he[Me],e);Object.freeze&&Object.freeze(he)}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 yt(he,e)}if(be.call(i,"key")){var Pe=P(e),le=Object.keys(i).filter(function(Ht){return Ht!=="key"}),rt=le.length>0?"{key: someKey, "+le.join(": ..., ")+": ...}":"{key: someKey}";if(!vt[Pe+rt]){var Gt=le.length>0?"{"+le.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} />`,et,Ne,qt,Ne),ht[Ne+et]=!0}}return e===i?Lt(Y):It(Y),Y}}function zt(e,o,c){return yt(e,o,c,!0)}function Bt(e,o,c){return yt(e,o,c,!1)}var Yt=Bt,Vt=zt;Ie.Fragment=i,Ie.jsx=Yt,Ie.jsxs=Vt}()),Ie}process.env.NODE_ENV==="production"?ot.exports=Gt():ot.exports=Ht();var a=ot.exports;function Nt(t){var r,n,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var l=t.length;for(r=0;r<l;r++)t[r]&&(n=Nt(t[r]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function J(){for(var t,r,n=0,i="",l=arguments.length;n<l;n++)(t=arguments[n])&&(r=Nt(t))&&(i&&(i+=" "),i+=r);return i}const Jt="https://core.spreedly.com/iframe/iframe-v1.min.js",Zt="https://cdn.e2e.movmo.io";let Fe={};const Xt=t=>{Fe={...Fe,...t}},tt=t=>{var n;const r=globalThis.process;return(n=r==null?void 0:r.env)==null?void 0:n[t]},ke=()=>({baseUrl:Fe.baseUrl??tt("REACT_APP_MOVMO_API_URL")??"",spreedlyScriptUrl:Fe.spreedlyScriptUrl??tt("REACT_APP_SPREEDLY_SCRIPT_URL")??Jt,iconCdnBaseUrl:Fe.iconCdnBaseUrl??tt("REACT_APP_MOVMO_ICON_CDN_URL")??Zt,fetch:Fe.fetch??(typeof globalThis<"u"&&typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):(()=>{throw new Error("@movmo_app/payments: no fetch available")})())}),it=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}),We={Accept:"application/json","Content-Type":"application/json"},Me=t=>{const{baseUrl:r}=ke();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}`},Oe=(t,r)=>{const{fetch:n}=ke();return n(t,r)},De=async(t,r)=>{try{return(await t.json()).message||r}catch{return r}};let Le=null;const lt=()=>{if(Le)return Le;const t=(async()=>{const r=await Oe(Me("/v1/payments/tokenization-session"),{method:"GET",headers:We,credentials:"include"});if(!r.ok)throw new Error(await De(r,`Failed to fetch tokenization session (${r.status})`));return await r.json()})();return Le=t,t.finally(()=>{Le===t&&(Le=null)}).catch(()=>{}),t},Qt=t=>typeof t.brand=="string"&&typeof t.last4=="string"&&typeof t.expMonth=="number"&&typeof t.expYear=="number",er=async(t,r,n)=>{const i=await Oe(Me(`/v1/users/${encodeURIComponent(t)}/payment-methods/from-token`),{method:"POST",headers:We,credentials:"include",body:JSON.stringify({tokenizedPaymentMethodId:r,isDefault:n})});if(!i.ok)throw new Error(await De(i,`Failed to save payment method (${i.status})`));const l=await i.json();if(Qt(l))return it(l);const d=await Oe(Me(`/v1/users/${encodeURIComponent(t)}/payment-methods/${encodeURIComponent(l.id)}`),{method:"GET",headers:We,credentials:"include"});if(!d.ok)throw new Error(await De(d,`Failed to fetch saved payment method (${d.status})`));const u=await d.json();return it(u)},tr=async(t,r)=>{const n=await Oe(Me(`/v1/users/${encodeURIComponent(t)}/payment-methods`),{method:"GET",headers:We,credentials:"include",signal:r});if(!n.ok)throw new Error(await De(n,`Failed to fetch payment methods (${n.status})`));return(await n.json()??[]).map(it)},rr=async(t,r)=>{const n=await Oe(Me(`/v1/users/${encodeURIComponent(t)}/payment-methods/${encodeURIComponent(r)}`),{method:"DELETE",headers:We,credentials:"include"});if(!n.ok)throw new Error(await De(n,`Failed to delete payment method (${n.status})`))},kt=async(t,r,n)=>{const i=await Oe(Me(`/v1/users/${encodeURIComponent(t)}/payment-methods/${encodeURIComponent(r)}`),{method:"PUT",headers:We,credentials:"include",body:JSON.stringify(n)});if(!i.ok)throw new Error(await De(i,`Failed to update payment method (${i.status})`))},ar={visa:"visa",master:"mastercard",mastercard:"mastercard",american_express:"amex",amex:"amex",discover:"discover"},nr=28,we=({brand:t,className:r,width:n=46})=>{const i=t?ar[t.toLowerCase()]??"credit-card":"credit-card",l=Math.max(n,nr),d=Math.round(l*24/34),{iconCdnBaseUrl:u}=ke();return a.jsx("img",{src:`${u}/website/assets/icons/payments/${i}.svg`,alt:i==="credit-card"?"card":`${i} card`,"data-testid":`card-brand-${t.toLowerCase()}`,className:r,width:l,height:d,loading:"lazy"})};let ze=null;const sr=()=>{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(ze)return ze;const{spreedlyScriptUrl:t}=ke();return ze=new Promise((r,n)=>{const i=document.querySelector(`script[src="${t}"]`),l=()=>{window.Spreedly?r(window.Spreedly):n(new Error("Spreedly script loaded but window.Spreedly is undefined."))};if(i){if(window.Spreedly){l();return}i.addEventListener("load",l,{once:!0}),i.addEventListener("error",()=>{i.remove(),n(new Error("Failed to load Spreedly iframe script."))},{once:!0});return}const d=document.createElement("script");d.src=t,d.async=!0,d.onload=l,d.onerror=()=>{d.remove(),n(new Error("Failed to load Spreedly iframe script."))},document.head.appendChild(d)}).catch(r=>{throw ze=null,r}),ze},or="movmo-card-number",ir="movmo-card-cvv",lr=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}:{}}),St=(t={})=>{const{numberEl:r=or,cvvEl:n=ir,onCardTokenized:i,onFieldErrors:l,onValidityChange:d,onBrandChange:u}=t,[x,m]=s.useState("idle"),[C,b]=s.useState(null),[h,v]=s.useState({number:!1,cvv:!1}),[E,S]=s.useState(null),[O,D]=s.useState({number:!1,cvv:!1}),g=s.useRef(null),R=s.useRef(i),$=s.useRef(l),Z=s.useRef(d),ae=s.useRef(u);s.useEffect(()=>{R.current=i},[i]),s.useEffect(()=>{$.current=l},[l]),s.useEffect(()=>{Z.current=d},[d]),s.useEffect(()=>{ae.current=u},[u]);const ne=s.useRef({number:!1,cvv:!1});s.useEffect(()=>{let L=!1;return m("loading"),b(null),v({number:!1,cvv:!1}),S(null),ne.current={number:!1,cvv:!1},(async()=>{try{const[T,p]=await Promise.all([lt(),sr()]);if(L)return;g.current=p,p.on("ready",()=>{var W,N,U,V,q,G;if(!L){m("ready");try{(W=p.setFieldType)==null||W.call(p,"number","tel"),(N=p.setFieldType)==null||N.call(p,"cvv","tel")}catch{}try{typeof p.setNumberFormat=="function"?p.setNumberFormat("prettyFormat"):console.warn("@movmo_app/payments: Spreedly.setNumberFormat is missing — card-number digits will not be space-grouped.")}catch(X){console.warn("@movmo_app/payments: setNumberFormat failed",X)}try{(U=p.setPlaceholder)==null||U.call(p,"number","Card number"),(V=p.setPlaceholder)==null||V.call(p,"cvv","CVV");const X='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=p.setStyle)==null||q.call(p,"number",X),(G=p.setStyle)==null||G.call(p,"cvv",X)}catch{}}}),p.on("paymentMethod",W=>{var N;(N=R.current)==null||N.call(R,W)}),p.on("errors",W=>{var N;(N=$.current)==null||N.call($,W)}),p.on("fieldEvent",(W,N,U,V)=>{var X;if(L)return;if(N==="focus"){D(M=>M[W]?M:{...M,[W]:!0});return}if(N==="blur"){D(M=>M[W]?{...M,[W]:!1}:M);return}if(N!=="input")return;const q=V??{};if(W==="number"){if(q.numberLength===0)S(M=>{var I;return M!==null&&((I=ae.current)==null||I.call(ae,null)),null});else if(q.cardType!==void 0){const M=q.cardType||null;S(I=>{var ue;return I!==M&&((ue=ae.current)==null||ue.call(ae,M)),M})}}const G=W==="number"?typeof q.validNumber=="boolean"?q.validNumber:void 0:typeof q.validCvv=="boolean"?q.validCvv:void 0;if(typeof G=="boolean"){const M=ne.current,I=W==="number"?{...M,number:G}:{...M,cvv:G};(I.number!==M.number||I.cvv!==M.cvv)&&(ne.current=I,v(I),(X=Z.current)==null||X.call(Z,I))}}),p.on("consoleError",W=>{var U;const N=W instanceof Error?W.message:"An unexpected error occurred while securing your card.";(U=$.current)==null||U.call($,[{message:N}])}),p.init(T.environmentKey,{numberEl:r,cvvEl:n,nonce:T.nonce,timestamp:String(T.timestamp),certificateToken:T.certificateToken,signature:T.signature})}catch(T){if(L)return;const p=T instanceof Error?T.message:"Failed to initialize card form.";b(p),m("error")}})(),()=>{var T,p;L=!0;try{(p=(T=g.current)==null?void 0:T.removeHandlers)==null||p.call(T)}catch{}g.current=null}},[r,n]);const de=s.useCallback(L=>{var T;(T=g.current)==null||T.tokenizeCreditCard(lr(L))},[]),P=s.useCallback(L=>{var T,p;(p=(T=g.current)==null?void 0:T.transferFocus)==null||p.call(T,L)},[]);return{status:x,error:C,tokenize:de,validity:h,brand:E,focused:O,focusField:P}},rt="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]",gt="flex h-11 w-full items-center gap-2 rounded-md border bg-white px-3 py-2 transition-shadow",bt="border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]",wt="border-grayWarm-300",cr=t=>{const r=t.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()}},Pt=t=>{const r=t.replace(/\D/g,"");if(r.length<4)return{month:"",year:""};const n=r.slice(0,2),i=r.slice(2),l=i.length===2?`20${i}`:i.slice(0,4);return{month:n,year:l}},dr=t=>{const r=t.replace(/\D/g,"").slice(0,4);return r.length<=2?r:`${r.slice(0,2)} / ${r.slice(2)}`},at=t=>{const{month:r,year:n}=Pt(t);if(!r||!n)return!1;const i=parseInt(r,10),l=parseInt(n,10);if(isNaN(i)||i<1||i>12)return!1;const d=new Date;return!(l<d.getFullYear()||l>d.getFullYear()+20||l===d.getFullYear()&&i<d.getMonth()+1)},nt=t=>/^\d{5}(-\d{4})?$/.test(t.trim()),ur=t=>{const r=t.replace(/[^\d]/g,"").slice(0,9);return r.length<=5?r:`${r.slice(0,5)}-${r.slice(5)}`},ct=({userId:t,onSuccess:r,onError:n,isDefault:i=!1,className:l,defaultCardholderName:d,defaultCardholderFirstName:u="",defaultCardholderLastName:x="",autoSave:m=!1,formId:C="movmo-card-form",hideInternalSaveButton:b=!1,onCanSubmitChange:h,onSavingChange:v,autoFocus:E})=>{const S=d??[u,x].filter(Boolean).join(" "),[O,D]=s.useState(S),[g,R]=s.useState(""),[$,Z]=s.useState(""),[ae,ne]=s.useState("idle"),de=s.useRef(!1),P=s.useCallback(async j=>{ne("saving");try{const A=await er(t,j,i);ne("ready"),r(A)}catch(A){const H=A instanceof Error?A.message:"Failed to save payment method.";ne("ready"),de.current=!1,n(H)}},[t,i,r,n]),L=s.useCallback(j=>{const A=j.map(H=>H.message).filter(Boolean).join("; ")||"Card validation failed.";ne(H=>H==="tokenizing"?"ready":H),de.current=!1,n(A)},[n]),T=s.useMemo(()=>({onCardTokenized:P,onFieldErrors:L}),[P,L]),{status:p,error:W,tokenize:N,validity:U,brand:V,focused:q,focusField:G}=St(T),X=s.useRef(!1);s.useEffect(()=>{!E||p!=="ready"||X.current||(X.current=!0,G(E))},[E,p,G]);const M=O.trim().split(/\s+/).length>=2,I=at(g),ue=nt($),xe=s.useRef(!1),fe=s.useRef(!1),he=s.useRef(!1),ye=s.useRef(null),Q=s.useRef(null);s.useEffect(()=>{var j;U.cvv?fe.current||(fe.current=!0,(j=ye.current)==null||j.focus()):fe.current=!1},[U.cvv]);const Ee=!M||!I||!ue||!U.number||!U.cvv,se=ae==="tokenizing"||ae==="saving",ie=p==="ready"&&!se&&!Ee,le=s.useRef(h);s.useEffect(()=>{le.current=h},[h]),s.useEffect(()=>{var j;(j=le.current)==null||j.call(le,ie)},[ie]);const ee=s.useRef(v);s.useEffect(()=>{ee.current=v},[v]),s.useEffect(()=>{var j;(j=ee.current)==null||j.call(ee,se)},[se]);const ge=s.useCallback(()=>{const{firstName:j,lastName:A}=cr(O),{month:H,year:ve}=Pt(g);ne("tokenizing"),N({firstName:j,lastName:A,month:H,year:ve,zip:$.trim()})},[O,g,$,N]);s.useEffect(()=>{if(!m||!ie||de.current)return;const j=setTimeout(()=>{de.current=!0,ge()},1200);return()=>clearTimeout(j)},[m,ie,ge]);const je=j=>{j.preventDefault(),ie&&ge()},me=p!=="ready"||se,pe=s.useRef(n);return s.useEffect(()=>{pe.current=n},[n]),s.useEffect(()=>{var j;W&&((j=pe.current)==null||j.call(pe,W))},[W]),a.jsxs("form",{id:C,onSubmit:je,className:J("flex w-full flex-col gap-3",l),"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:J(gt,q.number?bt:wt),children:[a.jsx(we,{brand:V??"",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",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]})]})]}),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:g,onChange:j=>{const A=dr(j.target.value);R(A),at(A)&&!xe.current?(xe.current=!0,G("cvv")):at(A)||(xe.current=!1)},className:J(rt,g&&!I&&"border-error-500"),disabled:me,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:J(gt,q.cvv?bt:wt),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",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:V==="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:ye,type:"text",inputMode:"numeric",autoComplete:"postal-code",placeholder:"ZIP code",value:$,onChange:j=>{var H;const A=ur(j.target.value);Z(A),nt(A)&&!he.current?(he.current=!0,(H=Q.current)==null||H.focus()):nt(A)||(he.current=!1)},className:J(rt,$&&!ue&&"border-error-500"),disabled:me,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:Q,type:"text",autoComplete:"cc-name",placeholder:"Cardholder name",value:O,onChange:j=>D(j.target.value),className:rt,disabled:me,required:!0,"data-testid":"movmo-card-cardholder-name-input"})]}),!m&&!b?a.jsx("button",{type:"submit",disabled:!ie,className:J("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:se?"Saving…":p==="loading"?"Loading…":"Save card"}):se&&m?a.jsx("p",{className:"text-center text-sm text-grayWarm-500","aria-live":"polite","data-testid":"movmo-card-autosaving",children:"Saving card…"}):null]})};ct.displayName="MovmoCardForm";const Tt=t=>{const[r,n]=s.useState("idle"),[i,l]=s.useState(null);return{deletePaymentMethod:s.useCallback(async u=>{n("pending"),l(null);try{await rr(t,u),n("idle")}catch(x){const m=x instanceof Error?x.message:"Failed to delete payment method.";throw l(m),n("error"),x}},[t]),status:r,error:i}},Ft=t=>{const[r,n]=s.useState("idle"),[i,l]=s.useState(null);return{setDefault:s.useCallback(async u=>{n("pending"),l(null);try{await kt(t,u,{isDefault:!0}),n("idle")}catch(x){const m=x instanceof Error?x.message:"Failed to set default payment method.";throw l(m),n("error"),x}},[t]),status:r,error:i}},Wt=t=>{const[r,n]=s.useState("idle"),[i,l]=s.useState(null);return{updatePaymentMethod:s.useCallback(async(u,x)=>{n("pending"),l(null);try{await kt(t,u,x),n("idle")}catch(m){const C=m instanceof Error?m.message:"Failed to update payment method.";throw l(C),n("error"),m}},[t]),status:r,error:i}},Mt=t=>{const[r,n]=s.useState([]),[i,l]=s.useState("idle"),[d,u]=s.useState(null),[x,m]=s.useState(0),C=s.useRef(null);s.useEffect(()=>{var v;(v=C.current)==null||v.abort();const h=new AbortController;return C.current=h,l("loading"),u(null),tr(t,h.signal).then(E=>{h.signal.aborted||(n(E),l("ready"))}).catch(E=>{if(h.signal.aborted||E instanceof DOMException&&E.name==="AbortError")return;const S=E instanceof Error?E.message:"Failed to fetch payment methods.";u(S),l("error")}),()=>{h.abort()}},[t,x]);const b=s.useCallback(()=>{m(h=>h+1)},[]);return{items:r,status:i,error:d,refetch:b}},Ot=({open:t,onClose:r,title:n,titleId:i,formId:l,saveDisabled:d,saveLabel:u="Save",isSaving:x=!1,testIdPrefix:m="payment-method",children:C})=>(s.useEffect(()=>{if(!t)return;const b=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[t,r]),s.useEffect(()=>{if(!t)return;const b=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=b}},[t]),t?a.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":i,className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4",onClick:b=>{b.target===b.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 ${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":`${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:i,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:C}),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:d,"aria-disabled":x||d,"aria-busy":x,className:J("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"})]}):u})]})]})}):null),fr=({open:t,onClose:r,formId:n,saveDisabled:i,saveLabel:l="Save",isSaving:d=!1,children:u})=>a.jsx(Ot,{open:t,onClose:r,title:"Add payment method",titleId:"movmo-add-payment-title",formId:n,saveDisabled:i,saveLabel:l,isSaving:d,testIdPrefix:"add-payment-method",children:u}),mr=(t,r)=>`${String(t).padStart(2,"0")}/${r}`,pr=t=>{if(!t)return"Card";const r=t.toLowerCase();return r==="amex"?"Amex":r.charAt(0).toUpperCase()+r.slice(1)},hr=({open:t,method:r,onClose:n,onSave:i,isSaving:l=!1,error:d=null})=>{const u=s.useId(),[x,m]=s.useState(""),[C,b]=s.useState("");if(s.useEffect(()=>{t&&r&&(m(r.cardholderName??""),b(r.zip??""))},[t,r]),!r)return null;const h=x.trim(),v=C.trim(),E=h!==(r.cardholderName??"").trim(),S=v!==(r.zip??"").trim(),O=E||S,D=(!E||h.length>0)&&(!S||/^[A-Za-z0-9 -]{3,20}$/.test(v)),g=!O||!D,R=$=>{if($.preventDefault(),g||l)return;const Z={};E&&(Z.cardholderName=h),S&&(Z.zip=v),i(Z).catch(()=>{})};return a.jsxs(Ot,{open:t,onClose:n,title:"Edit payment method",titleId:"movmo-edit-payment-title",formId:u,saveDisabled:g,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(we,{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:[pr(r.brand)," •••• ",r.last4]}),a.jsxs("div",{className:"text-sm text-grayWarm-600",children:["Exp. ",mr(r.expMonth,r.expYear)]})]})]}),a.jsxs("form",{id:u,onSubmit:R,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:$=>m($.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:C,onChange:$=>b($.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"})]}),d?a.jsx("p",{role:"alert",className:"text-sm text-error-700","data-testid":"edit-payment-method-error",children:d}):null]})]})},yr=t=>{if(!t)return"Card";const r=t.toLowerCase();return r==="amex"?"Amex":r.charAt(0).toUpperCase()+r.slice(1)},Dt=({method:t,trailing:r,onClick:n,cardLabelFormat:i="branded",className:l})=>a.jsxs("div",{className:J("flex items-center gap-3",n&&"cursor-pointer",l),onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:n?d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),n())}:void 0,"data-testid":`payment-method-preview-${t.id}`,children:[a.jsx(we,{brand:t.brand,width:34,className:"flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-lg font-semibold text-grayWarm-950",children:i==="masked"?`•••• ${t.last4}`:`${yr(t.brand)} ${t.last4}`}),r]}),vr=(t,r,n=new Date)=>r<n.getFullYear()||r===n.getFullYear()&&t<n.getMonth()+1,Et=t=>{if(!t)return"Card";const r=t.toLowerCase();return r==="amex"?"Amex":r.charAt(0).toUpperCase()+r.slice(1)},xr=(t,r)=>`${String(t).padStart(2,"0")}/${r}`,gr=({method:t,selectable:r,selected:n,onSelect:i,onSetDefault:l,onRemove:d,onEdit:u,disabled:x,showDefaultBadge:m,hideSetDefaultMenuItem:C,cardLabelFormat:b="branded"})=>{const[h,v]=s.useState(!1),E=s.useRef(null),S=vr(t.expMonth,t.expYear);s.useEffect(()=>{if(!h)return;const D=g=>{var R;(R=E.current)!=null&&R.contains(g.target)||v(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[h]);const O=()=>{r&&i&&!x&&i(t)};return a.jsxs("div",{className:J("flex items-start gap-3 transition-colors",r?"rounded-lg border px-3 py-3":"py-4",r&&!x&&"cursor-pointer",r&&(n?"border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]":"border-grayWarm-200 hover:border-grayWarm-300")),onClick:O,"data-testid":`payment-method-row-${t.id}`,children:[r?a.jsx("input",{type:"radio",name:"movmo-payment-method",checked:n,onChange:()=>i==null?void 0:i(t),onClick:D=>D.stopPropagation(),"aria-label":`Select ${Et(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(we,{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:b==="masked"?`•••• ${t.last4}`:`${Et(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,S?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:J("text-base",S?"text-grayWarm-400":"text-grayWarm-600"),children:["Exp. ",xr(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":h,className:"rounded-lg p-2 text-grayWarm-600 transition-colors hover:bg-grayWarm-100 disabled:cursor-not-allowed disabled:opacity-50",disabled:x,onClick:D=>{D.stopPropagation(),v(g=>!g)},"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"})})}),h?a.jsxs("div",{role:"menu",className:J("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:D=>D.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&&!C?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,u&&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),u(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),d(t)},"data-testid":`menu-remove-${t.id}`,children:"Delete"})]}):null]})]})},br=t=>`${ke().iconCdnBaseUrl}/website/assets/icons/payments/${t}.svg`,st=({slug:t,alt:r})=>a.jsx("img",{src:br(t),alt:r,height:20,loading:"lazy",style:{height:20,width:"auto"}}),Ge=({type:t,label:r,iconNode:n})=>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,onChange:()=>{},className:"h-4 w-4 cursor-pointer accent-grayWarm-900","aria-label":r}),a.jsxs("span",{className:"flex flex-1 items-center gap-2 text-sm font-semibold text-grayWarm-900",children:[r,n]})]}),jt=({selected:t,onSelect:r,creditCardBody:n,className:i})=>{const l=t==="credit_card";return a.jsxs("div",{className:J("flex w-full flex-col gap-3",i),children:[a.jsxs("label",{className:J("flex cursor-pointer flex-col gap-3 rounded-lg border px-4 py-3 transition-colors",l?"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:l,onChange:()=>r("credit_card"),className:"h-4 w-4 cursor-pointer accent-grayWarm-900","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(we,{brand:"mastercard",width:28}),a.jsx(we,{brand:"visa",width:28}),a.jsx(we,{brand:"amex",width:28}),a.jsx(we,{brand:"discover",width:28})]})]}),l?a.jsx("div",{"data-testid":"payment-type-credit_card-body",children:n}):null]}),l?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(Ge,{type:"paypal",label:"PayPal",iconNode:a.jsx(st,{slug:"paypal",alt:"PayPal"})}),a.jsx(Ge,{type:"googlepay",label:"GooglePay",iconNode:a.jsx(st,{slug:"google-pay",alt:"GooglePay"})}),a.jsx(Ge,{type:"klarna",label:"Klarna",iconNode:a.jsx(st,{slug:"klarna",alt:"Klarna"})}),a.jsx(Ge,{type:"ach",label:"Bank account (ACH)",iconNode:a.jsx("span",{className:"text-xs font-medium text-grayWarm-500",children:"Direct debit"})})]})},_t="movmo-add-payment-form",wr=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."},Ct=t=>{const r=t.filter(i=>i.isDefault),n=t.filter(i=>!i.isDefault);return[...r,...n]},Rt=({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"})]}),$t=({userId:t,defaultCardholderName:r,defaultCardholderFirstName:n,defaultCardholderLastName:i,selectedId:l,onSelect:d,onChange:u,paymentTypeSelector:x=!0,autoSaveFirstCard:m=!0,selectionSetsDefault:C=!1,showDefaultBadge:b=!0,collapsible:h=!1,cardLabelFormat:v="branded",className:E})=>{const{items:S,status:O,error:D,refetch:g}=Mt(t),{deletePaymentMethod:R,status:$}=Tt(t),{setDefault:Z,status:ae}=Ft(t),{updatePaymentMethod:ne,status:de}=Wt(t),[P,L]=s.useState([]),[T,p]=s.useState(null),[W,N]=s.useState(!1),[U,V]=s.useState(null),[q,G]=s.useState(!1),[X,M]=s.useState(!1),[I,ue]=s.useState(null),[xe,fe]=s.useState(null),[he,ye]=s.useState(null),[Q,Ee]=s.useState(!1),se=s.useRef(!1),ie=s.useCallback(()=>{N(!1),V(null),ye(null)},[]),le=r??([n,i].filter(Boolean).join(" ")||void 0);s.useEffect(()=>{O==="ready"&&L(Ct(S))},[S,O]),s.useEffect(()=>{if(!d||se.current||O!=="ready"||P.length===0||l)return;se.current=!0;const f=P.find(te=>te.isDefault)??P[0];d(f)},[d,O,P,l]);const ee=s.useCallback(f=>{L(te=>{const K=typeof f=="function"?f(te):f,z=Ct(K);return queueMicrotask(()=>u==null?void 0:u(z)),z})},[u]),ge=$==="pending"||ae==="pending"||de==="pending",je=s.useCallback(async f=>{const te=P;p(null),ee(K=>K.map(z=>({...z,isDefault:z.id===f.id})));try{await Z(f.id),g()}catch(K){L(te),u==null||u(te);const z=K instanceof Error?K.message:"Failed to set default payment method.";p(z)}},[P,ee,Z,g,u]),me=s.useCallback(f=>{d==null||d(f),C&&(f.isDefault||je(f))},[d,C,je]),pe=s.useCallback(async f=>{const te=P;p(null);const K=P.filter(be=>be.id!==f.id);ee(()=>K);const z=f.id===l&&d?K.find(be=>be.isDefault)??K[0]??null:null;z&&me(z);const Re=!!z&&C&&z!==null&&!z.isDefault;try{await R(f.id),Re||g()}catch(be){L(te),u==null||u(te);const Je=be instanceof Error?be.message:"Failed to delete payment method.";p(Je)}},[P,ee,R,g,u,l,d,me,C]),j=s.useCallback(f=>{fe(null),ue(f)},[]),A=s.useCallback(()=>{ue(null),fe(null)},[]),H=s.useCallback(async f=>{if(!I)return;const te=I,K=P;fe(null),ee(z=>z.map(Re=>Re.id===te.id?{...Re,...f.cardholderName!==void 0?{cardholderName:f.cardholderName}:{},...f.zip!==void 0?{zip:f.zip}:{}}:Re));try{await ne(te.id,f),A(),g()}catch(z){L(K),u==null||u(K),fe(wr(z))}},[I,P,ee,ne,g,u,A]),ve=s.useCallback(f=>{V(null),N(!1),ye(null),ee(K=>[f,...K.filter(z=>z.id!==f.id)]),me(f),!!d&&C&&!f.isDefault||g()},[ee,g,me,d,C]),Be=s.useCallback(f=>{V(f)},[]),He=O==="ready"&&P.length===0,_e=typeof d=="function",Ye=!_e&&!h,Ve=P.length===0,$e=m&&P.length===0,Ce=s.useCallback(f=>a.jsx(ct,{userId:t,isDefault:Ve,defaultCardholderName:le,autoSave:!f&&$e,hideInternalSaveButton:f,formId:f?_t:void 0,onCanSubmitChange:f?G:void 0,onSavingChange:f?M:void 0,autoFocus:f?"number":void 0,onSuccess:ve,onError:Be}),[t,Ve,le,$e,ve,Be]),Se=s.useMemo(()=>Ce(!1),[Ce]),Ae=s.useMemo(()=>Ce(!0),[Ce]),qe=s.useMemo(()=>x?a.jsx(jt,{selected:he,onSelect:f=>ye(f),creditCardBody:Se}):Se,[x,he,Se]),Ke=s.useMemo(()=>x?a.jsx(jt,{selected:he,onSelect:f=>ye(f),creditCardBody:Ae}):Ae,[x,he,Ae]);return a.jsxs("div",{className:J("flex w-full flex-col gap-4",E),"data-testid":"payment-methods-manager",children:[O==="loading"&&P.length===0?a.jsxs("div",{className:J(Ye?"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(Rt,{withDefaultBadge:!0}),a.jsx(Rt,{})]}):null,O==="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:D??"Failed to load payment methods."}),a.jsx("button",{type:"button",onClick:g,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,T?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:T}):null,h&&P.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":Q?"payment-methods-drawer-header":"payment-methods-collapsed-preview",children:[Q?a.jsx("h3",{className:"text-md font-semibold text-grayWarm-950",children:"Payment methods"}):a.jsx(Dt,{method:P.find(f=>f.id===l)??P.find(f=>f.isDefault)??P[0],cardLabelFormat:v,className:"flex-1"}),a.jsx("button",{type:"button","aria-label":Q?"Collapse payment methods":"Expand payment methods","aria-expanded":Q,className:"bg-grayWarm-100 p-2 rounded-lg hover:bg-grayWarm-200 transition-colors",onClick:()=>Ee(f=>!f),"data-testid":Q?"payment-methods-drawer-close":"payment-methods-drawer-open",children:a.jsx("img",{src:`${ke().iconCdnBaseUrl}/website/assets/icons/chevron-${Q?"up":"down"}-double.svg`,alt:"",className:"w-5 h-5"})})]})}):null,P.length>0&&(!h||Q)?a.jsx("div",{className:J("flex flex-col",Ye?"rounded-xl border border-grayWarm-200 px-4 md:px-6 divide-y divide-grayWarm-200":"space-y-3"),children:P.map(f=>a.jsx(gr,{method:f,selectable:_e,selected:_e&&f.id===l,onSelect:me,onSetDefault:je,onRemove:pe,onEdit:j,disabled:ge,showDefaultBadge:b,hideSetDefaultMenuItem:C,cardLabelFormat:v},f.id))}):null,He?a.jsx("div",{"data-testid":"payment-methods-empty",children:qe}):P.length>0&&(!h||Q)?a.jsx("button",{type:"button",onClick:()=>{V(null),ye(null),G(!1),N(!0)},onMouseEnter:()=>{lt().catch(()=>{})},onFocus:()=>{lt().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(fr,{open:W,onClose:ie,formId:_t,saveDisabled:!q,isSaving:X,children:[Ke,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(hr,{open:I!==null,method:I,onClose:A,onSave:H,isSaving:de==="pending",error:xe})]})};$t.displayName="PaymentMethodsManager";const Er="/v1/auth/",jr="movmo_csrf_token",_r=t=>{if(typeof document>"u")return null;const r=document.cookie?document.cookie.split(";"):[];for(const n of r){const i=n.trim();if(i.startsWith(t+"="))return decodeURIComponent(i.substring(t.length+1))}return null},Cr=t=>typeof t=="string"?t:t instanceof URL?t.href:t.url,Rr=()=>{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")},Nr=t=>{const{refreshSession:r,onRefreshFailed:n,csrfCookieName:i=jr,extraHeaders:l,authPathFragment:d=Er,baseFetch:u=Rr(),readCookie:x=_r}=t;let m=null;const C=()=>{if(m)return m;const h=(async()=>{await r()})();return m=h,h.finally(()=>{m===h&&(m=null)}).catch(()=>{}),h},b=(h,v)=>{const E=new Headers(v==null?void 0:v.headers),S=x(i);if(S&&!E.has("X-CSRF-Token")&&E.set("X-CSRF-Token",S),l){const O=l(h,v);for(const[D,g]of Object.entries(O))E.has(D)||E.set(D,g)}return{...v,headers:E,credentials:(v==null?void 0:v.credentials)??"include"}};return async function(v,E){const S=await u(v,b(v,E));if(Cr(v).includes(d)||S.status!==401&&S.status!==403)return S;try{await C()}catch(g){try{n(g)}catch(R){console.error("@movmo_app/payments: onRefreshFailed callback threw — auth retry path is misconfigured",R)}return S}try{return await u(v,b(v,E))}catch(g){return console.error("@movmo_app/payments: retry after token refresh failed — returning original response",g),S}}};exports.MovmoCardForm=ct;exports.PaymentMethodPreview=Dt;exports.PaymentMethodsManager=$t;exports.createMovmoAuthFetch=Nr;exports.getPaymentsConfig=ke;exports.setPaymentsConfig=Xt;exports.useDeletePaymentMethod=Tt;exports.useMovmoCardFields=St;exports.useSetDefaultPaymentMethod=Ft;exports.useUpdatePaymentMethod=Wt;exports.useUserPaymentMethods=Mt;
|
|
30
|
+
<%s key={someKey} {...props} />`,rt,Pe,Gt,Pe),vt[Pe+rt]=!0}}return e===o?Bt(z):zt(z),z}}function Yt(e,i,c){return xt(e,i,c,!0)}function Vt(e,i,c){return xt(e,i,c,!1)}var qt=Vt,Kt=Yt;Ve.Fragment=o,Ve.jsx=qt,Ve.jsxs=Kt}()),Ve}process.env.NODE_ENV==="production"?ct.exports=Xt():ct.exports=Qt();var a=ct.exports;function St(t){var r,n,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]&&(n=St(t[r]))&&(o&&(o+=" "),o+=n)}else for(n in t)t[n]&&(o&&(o+=" "),o+=n);return o}function Q(){for(var t,r,n=0,o="",l=arguments.length;n<l;n++)(t=arguments[n])&&(r=St(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 Oe={};const rr=t=>{Oe={...Oe,...t}},nt=t=>{var n;const r=globalThis.process;return(n=r==null?void 0:r.env)==null?void 0:n[t]},Te=()=>({baseUrl:Oe.baseUrl??nt("REACT_APP_MOVMO_API_URL")??"",spreedlyScriptUrl:Oe.spreedlyScriptUrl??nt("REACT_APP_SPREEDLY_SCRIPT_URL")??er,iconCdnBaseUrl:Oe.iconCdnBaseUrl??nt("REACT_APP_MOVMO_ICON_CDN_URL")??tr,fetch:Oe.fetch??(typeof globalThis<"u"&&typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):(()=>{throw new Error("@movmo_app/payments: no fetch available")})())}),dt=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"},De=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}`},Ae=(t,r)=>{const{fetch:n}=Te();return n(t,r)},Ue=async(t,r)=>{try{return(await t.json()).message||r}catch{return r}};let qe=null;const ut=()=>{if(qe)return qe;const t=(async()=>{const r=await Ae(De("/v1/payments/tokenization-session"),{method:"GET",headers:$e,credentials:"include"});if(!r.ok)throw new Error(await Ue(r,`Failed to fetch tokenization session (${r.status})`));return await r.json()})();return qe=t,t.finally(()=>{qe===t&&(qe=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,n)=>{const o=await Ae(De(`/v1/users/${encodeURIComponent(t)}/payment-methods/from-token`),{method:"POST",headers:$e,credentials:"include",body:JSON.stringify({tokenizedPaymentMethodId:r,isDefault:n})});if(!o.ok)throw new Error(await Ue(o,`Failed to save payment method (${o.status})`));const l=await o.json();if(ar(l))return dt(l);const d=await Ae(De(`/v1/users/${encodeURIComponent(t)}/payment-methods/${encodeURIComponent(l.id)}`),{method:"GET",headers:$e,credentials:"include"});if(!d.ok)throw new Error(await Ue(d,`Failed to fetch saved payment method (${d.status})`));const f=await d.json();return dt(f)},sr=async(t,r)=>{const n=await Ae(De(`/v1/users/${encodeURIComponent(t)}/payment-methods`),{method:"GET",headers:$e,credentials:"include",signal:r});if(!n.ok)throw new Error(await Ue(n,`Failed to fetch payment methods (${n.status})`));return(await n.json()??[]).map(dt)},or=async(t,r)=>{const n=await Ae(De(`/v1/users/${encodeURIComponent(t)}/payment-methods/${encodeURIComponent(r)}`),{method:"DELETE",headers:$e,credentials:"include"});if(!n.ok)throw new Error(await Ue(n,`Failed to delete payment method (${n.status})`))},Pt=async(t,r,n)=>{const o=await Ae(De(`/v1/users/${encodeURIComponent(t)}/payment-methods/${encodeURIComponent(r)}`),{method:"PUT",headers:$e,credentials:"include",body:JSON.stringify(n)});if(!o.ok)throw new Error(await Ue(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:n=46})=>{const o=t?ir[t.toLowerCase()]??"credit-card":"credit-card",l=Math.max(n,lr),d=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:d,loading:"lazy"})};let Ke=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(Ke)return Ke;const{spreedlyScriptUrl:t}=Te();return Ke=new Promise((r,n)=>{const o=document.querySelector(`script[src="${t}"]`),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 d=document.createElement("script");d.src=t,d.async=!0,d.onload=l,d.onerror=()=>{d.remove(),n(new Error("Failed to load Spreedly iframe script."))},document.head.appendChild(d)}).catch(r=>{throw Ke=null,r}),Ke};class Ze extends Error{constructor(n,o){super(o instanceof Error?o.message:"Failed to initialize card form.");at(this,"source");at(this,"cause");this.name="InitError",this.source=n,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}:{}}),Tt=(t={})=>{const{numberEl:r=dr,cvvEl:n=ur,onCardTokenized:o,onFieldErrors:l,onValidityChange:d,onBrandChange:f}=t,[g,m]=s.useState("idle"),[F,v]=s.useState(null),[w,p]=s.useState(null),[j,W]=s.useState(null),[ee,C]=s.useState({number:!1,cvv:!1}),[S,E]=s.useState(null),[re,Z]=s.useState({number:!1,cvv:!1}),de=s.useRef(null),ye=s.useRef(o),V=s.useRef(l),ae=s.useRef(d),x=s.useRef(f);s.useEffect(()=>{ye.current=o},[o]),s.useEffect(()=>{V.current=l},[l]),s.useEffect(()=>{ae.current=d},[d]),s.useEffect(()=>{x.current=f},[f]);const ne=s.useRef({number:!1,cvv:!1});s.useEffect(()=>{let P=!1;return m("loading"),v(null),p(null),W(null),C({number:!1,cvv:!1}),E(null),ne.current={number:!1,cvv:!1},(async()=>{try{const[b,h]=await Promise.all([ut().catch(k=>{throw new Ze("tokenization-session",k)}),cr().catch(k=>{throw new Ze("spreedly-script",k)})]);if(P)return;de.current=h,h.on("ready",()=>{var k,A,J,ue,q,B;if(!P){m("ready");try{(k=h.setFieldType)==null||k.call(h,"number","tel"),(A=h.setFieldType)==null||A.call(h,"cvv","tel")}catch(I){console.warn("@movmo_app/payments: setFieldType failed",I)}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(I){console.warn("@movmo_app/payments: setNumberFormat failed",I)}try{(J=h.setPlaceholder)==null||J.call(h,"number","Card number"),(ue=h.setPlaceholder)==null||ue.call(h,"cvv","CVV");const I='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=h.setStyle)==null||q.call(h,"number",I),(B=h.setStyle)==null||B.call(h,"cvv",I)}catch(I){console.warn("@movmo_app/payments: setPlaceholder/setStyle failed",I)}}}),h.on("paymentMethod",k=>{var A;(A=ye.current)==null||A.call(ye,k)}),h.on("errors",k=>{var A;(A=V.current)==null||A.call(V,k)}),h.on("fieldEvent",(k,A,J,ue)=>{var I;if(P)return;if(A==="focus"){Z(O=>O[k]?O:{...O,[k]:!0});return}if(A==="blur"){Z(O=>O[k]?{...O,[k]:!1}:O);return}if(A!=="input")return;const q=ue??{};if(k==="number"){if(q.numberLength===0)E(O=>{var L;return O!==null&&((L=x.current)==null||L.call(x,null)),null});else if(q.cardType!==void 0){const O=q.cardType||null;E(L=>{var fe;return L!==O&&((fe=x.current)==null||fe.call(x,O)),O})}}const B=k==="number"?typeof q.validNumber=="boolean"?q.validNumber:void 0:typeof q.validCvv=="boolean"?q.validCvv:void 0;if(typeof B=="boolean"){const O=ne.current,L=k==="number"?{...O,number:B}:{...O,cvv:B};(L.number!==O.number||L.cvv!==O.cvv)&&(ne.current=L,C(L),(I=ae.current)==null||I.call(ae,L))}}),h.on("consoleError",k=>{var J;const A=k instanceof Error?k.message:"An unexpected error occurred while securing your card.";(J=V.current)==null||J.call(V,[{message:A}])}),h.init(b.environmentKey,{numberEl:r,cvvEl:n,nonce:b.nonce,timestamp:String(b.timestamp),certificateToken:b.certificateToken,signature:b.signature})}catch(b){if(P)return;const h=b instanceof Error?b.message:"Failed to initialize card form.";v(h),p(b instanceof Ze?b.source:"spreedly-script"),W(b instanceof Ze?b.cause:b),m("error")}})(),()=>{var b,h;P=!0;try{(h=(b=de.current)==null?void 0:b.removeHandlers)==null||h.call(b)}catch(k){console.warn("@movmo_app/payments: removeHandlers failed during cleanup",k)}de.current=null}},[r,n]);const Ce=s.useCallback(P=>{var b;(b=de.current)==null||b.tokenizeCreditCard(fr(P))},[]),ve=s.useCallback(P=>{var b,h;(h=(b=de.current)==null?void 0:b.transferFocus)==null||h.call(b,P)},[]);return{status:g,error:F,errorSource:w,errorCause:j,tokenize:Ce,validity:ee,brand:S,focused:re,focusField:ve}},st="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]",wt="flex h-11 w-full items-center gap-2 rounded-md border bg-white px-3 py-2 transition-shadow",Et="border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]",jt="border-grayWarm-300",mr=t=>{const r=t.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()}},Ft=t=>{const r=t.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}},pr=t=>{const r=t.replace(/\D/g,"").slice(0,4);return r.length<=2?r:`${r.slice(0,2)} / ${r.slice(2)}`},ot=t=>{const{month:r,year:n}=Ft(t);if(!r||!n)return!1;const o=parseInt(r,10),l=parseInt(n,10);if(isNaN(o)||o<1||o>12)return!1;const d=new Date;return!(l<d.getFullYear()||l>d.getFullYear()+20||l===d.getFullYear()&&o<d.getMonth()+1)},it=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)}`},ft=({userId:t,onSuccess:r,onError:n,onErrorDetail:o,isDefault:l=!1,className:d,defaultCardholderName:f,defaultCardholderFirstName:g="",defaultCardholderLastName:m="",autoSave:F=!1,formId:v="movmo-card-form",hideInternalSaveButton:w=!1,onCanSubmitChange:p,onSavingChange:j,autoFocus:W})=>{const ee=f??[g,m].filter(Boolean).join(" "),[C,S]=s.useState(ee),[E,re]=s.useState(""),[Z,de]=s.useState(""),[ye,V]=s.useState("idle"),ae=s.useRef(!1),x=s.useRef(o);s.useEffect(()=>{x.current=o},[o]);const ne=s.useCallback(async N=>{var D;V("saving");try{const Y=await nr(t,N,l);V("ready"),r(Y)}catch(Y){const oe=Y instanceof Error?Y.message:"Failed to save payment method.";V("ready"),ae.current=!1,n(oe),(D=x.current)==null||D.call(x,{source:"save-from-token",message:oe,cause:Y})}},[t,l,r,n]),Ce=s.useCallback(N=>{var Y;const D=N.map(oe=>oe.message).filter(Boolean).join("; ")||"Card validation failed.";V(oe=>oe==="tokenizing"?"ready":oe),ae.current=!1,n(D),(Y=x.current)==null||Y.call(x,{source:"card-tokenize",message:D})},[n]),ve=s.useMemo(()=>({onCardTokenized:ne,onFieldErrors:Ce}),[ne,Ce]),{status:P,error:b,errorSource:h,errorCause:k,tokenize:A,validity:J,brand:ue,focused:q,focusField:B}=Tt(ve),I=s.useRef(!1);s.useEffect(()=>{!W||P!=="ready"||I.current||(I.current=!0,B(W))},[W,P,B]);const O=C.trim().split(/\s+/).length>=2,L=ot(E),fe=it(Z),ce=s.useRef(!1),X=s.useRef(!1),je=s.useRef(!1),ke=s.useRef(null),me=s.useRef(null);s.useEffect(()=>{var N;J.cvv?X.current||(X.current=!0,(N=ke.current)==null||N.focus()):X.current=!1},[J.cvv]);const se=!O||!L||!fe||!J.number||!J.cvv,xe=ye==="tokenizing"||ye==="saving",ge=P==="ready"&&!xe&&!se,_e=s.useRef(p);s.useEffect(()=>{_e.current=p},[p]),s.useEffect(()=>{var N;(N=_e.current)==null||N.call(_e,ge)},[ge]);const K=s.useRef(j);s.useEffect(()=>{K.current=j},[j]),s.useEffect(()=>{var N;(N=K.current)==null||N.call(K,xe)},[xe]);const be=s.useCallback(()=>{const{firstName:N,lastName:D}=mr(C),{month:Y,year:oe}=Ft(E);V("tokenizing"),A({firstName:N,lastName:D,month:Y,year:oe,zip:Z.trim()})},[C,E,Z,A]);s.useEffect(()=>{if(!F||!ge||ae.current)return;const N=setTimeout(()=>{ae.current=!0,be()},1200);return()=>clearTimeout(N)},[F,ge,be]);const Re=N=>{N.preventDefault(),ge&&be()},pe=P!=="ready"||xe,we=s.useRef(n);return s.useEffect(()=>{we.current=n},[n]),s.useEffect(()=>{var N,D;b&&((N=we.current)==null||N.call(we,b),(D=x.current)==null||D.call(x,{source:h??"spreedly-script",message:b,cause:k}))},[b,h,k]),a.jsxs("form",{id:v,onSubmit:Re,className:Q("flex w-full flex-col gap-3",d),"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(wt,q.number?Et:jt),children:[a.jsx(Ne,{brand:ue??"",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",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]})]})]}),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:E,onChange:N=>{const D=pr(N.target.value);re(D),ot(D)&&!ce.current?(ce.current=!0,B("cvv")):ot(D)||(ce.current=!1)},className:Q(st,E&&!L&&"border-error-500"),disabled:pe,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(wt,q.cvv?Et:jt),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",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:ue==="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:ke,type:"text",inputMode:"numeric",autoComplete:"postal-code",placeholder:"ZIP code",value:Z,onChange:N=>{var Y;const D=hr(N.target.value);de(D),it(D)&&!je.current?(je.current=!0,(Y=me.current)==null||Y.focus()):it(D)||(je.current=!1)},className:Q(st,Z&&!fe&&"border-error-500"),disabled:pe,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:me,type:"text",autoComplete:"cc-name",placeholder:"Cardholder name",value:C,onChange:N=>S(N.target.value),className:st,disabled:pe,required:!0,"data-testid":"movmo-card-cardholder-name-input"})]}),!F&&!w?a.jsx("button",{type:"submit",disabled:!ge,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:xe?"Saving…":P==="loading"?"Loading…":"Save card"}):xe&&F?a.jsx("p",{className:"text-center text-sm text-grayWarm-500","aria-live":"polite","data-testid":"movmo-card-autosaving",children:"Saving card…"}):null]})};ft.displayName="MovmoCardForm";const Wt=t=>{const[r,n]=s.useState("idle"),[o,l]=s.useState(null);return{deletePaymentMethod:s.useCallback(async f=>{n("pending"),l(null);try{await or(t,f),n("idle")}catch(g){const m=g instanceof Error?g.message:"Failed to delete payment method.";throw l(m),n("error"),g}},[t]),status:r,error:o}},Mt=t=>{const[r,n]=s.useState("idle"),[o,l]=s.useState(null);return{setDefault:s.useCallback(async f=>{n("pending"),l(null);try{await Pt(t,f,{isDefault:!0}),n("idle")}catch(g){const m=g instanceof Error?g.message:"Failed to set default payment method.";throw l(m),n("error"),g}},[t]),status:r,error:o}},Ot=t=>{const[r,n]=s.useState("idle"),[o,l]=s.useState(null);return{updatePaymentMethod:s.useCallback(async(f,g)=>{n("pending"),l(null);try{await Pt(t,f,g),n("idle")}catch(m){const F=m instanceof Error?m.message:"Failed to update payment method.";throw l(F),n("error"),m}},[t]),status:r,error:o}},$t=t=>{const[r,n]=s.useState([]),[o,l]=s.useState("idle"),[d,f]=s.useState(null),[g,m]=s.useState(0),F=s.useRef(null);s.useEffect(()=>{var p;(p=F.current)==null||p.abort();const w=new AbortController;return F.current=w,l("loading"),f(null),sr(t,w.signal).then(j=>{w.signal.aborted||(n(j),l("ready"))}).catch(j=>{if(w.signal.aborted||j instanceof DOMException&&j.name==="AbortError")return;const W=j instanceof Error?j.message:"Failed to fetch payment methods.";f(W),l("error")}),()=>{w.abort()}},[t,g]);const v=s.useCallback(()=>{m(w=>w+1)},[]);return{items:r,status:o,error:d,refetch:v}},Dt=({open:t,onClose:r,title:n,titleId:o,formId:l,saveDisabled:d,saveLabel:f="Save",isSaving:g=!1,testIdPrefix:m="payment-method",children:F})=>(s.useEffect(()=>{if(!t)return;const v=w=>{w.key==="Escape"&&r()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[t,r]),s.useEffect(()=>{if(!t)return;const v=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=v}},[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:v=>{v.target===v.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 ${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":`${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: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:F}),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:g?!1:d,"aria-disabled":g||d,"aria-busy":g,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",g?"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:g?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:n,saveDisabled:o,saveLabel:l="Save",isSaving:d=!1,children:f})=>a.jsx(Dt,{open:t,onClose:r,title:"Add payment method",titleId:"movmo-add-payment-title",formId:n,saveDisabled:o,saveLabel:l,isSaving:d,testIdPrefix:"add-payment-method",children:f}),vr=(t,r)=>`${String(t).padStart(2,"0")}/${r}`,xr=t=>{if(!t)return"Card";const r=t.toLowerCase();return r==="amex"?"Amex":r.charAt(0).toUpperCase()+r.slice(1)},gr=({open:t,method:r,onClose:n,onSave:o,isSaving:l=!1,error:d=null})=>{const f=s.useId(),[g,m]=s.useState(""),[F,v]=s.useState("");if(s.useEffect(()=>{t&&r&&(m(r.cardholderName??""),v(r.zip??""))},[t,r]),!r)return null;const w=g.trim(),p=F.trim(),j=w!==(r.cardholderName??"").trim(),W=p!==(r.zip??"").trim(),ee=j||W,C=(!j||w.length>0)&&(!W||/^[A-Za-z0-9 -]{3,20}$/.test(p)),S=!ee||!C,E=re=>{if(re.preventDefault(),S||l)return;const Z={};j&&(Z.cardholderName=w),W&&(Z.zip=p),o(Z).catch(()=>{})};return a.jsxs(Dt,{open:t,onClose:n,title:"Edit payment method",titleId:"movmo-edit-payment-title",formId:f,saveDisabled:S,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:[xr(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: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:g,onChange:re=>m(re.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:F,onChange:re=>v(re.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"})]}),d?a.jsx("p",{role:"alert",className:"text-sm text-error-700","data-testid":"edit-payment-method-error",children:d}):null]})]})},br=t=>{if(!t)return"Card";const r=t.toLowerCase();return r==="amex"?"Amex":r.charAt(0).toUpperCase()+r.slice(1)},At=({method:t,trailing:r,onClick:n,cardLabelFormat:o="branded",className:l})=>a.jsxs("div",{className:Q("flex items-center gap-3",n&&"cursor-pointer",l),onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:n?d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),n())}: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,n=new Date)=>r<n.getFullYear()||r===n.getFullYear()&&t<n.getMonth()+1,_t=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:n,onSelect:o,onSetDefault:l,onRemove:d,onEdit:f,disabled:g,showDefaultBadge:m,hideSetDefaultMenuItem:F,cardLabelFormat:v="branded"})=>{const[w,p]=s.useState(!1),j=s.useRef(null),W=wr(t.expMonth,t.expYear);s.useEffect(()=>{if(!w)return;const C=S=>{var E;(E=j.current)!=null&&E.contains(S.target)||p(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[w]);const ee=()=>{r&&o&&!g&&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&&!g&&"cursor-pointer",r&&(n?"border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]":"border-grayWarm-200 hover:border-grayWarm-300")),onClick:ee,"data-testid":`payment-method-row-${t.id}`,children:[r?a.jsx("input",{type:"radio",name:"movmo-payment-method",checked:n,onChange:()=>o==null?void 0:o(t),onClick:C=>C.stopPropagation(),"aria-label":`Select ${_t(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:g}):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:v==="masked"?`•••• ${t.last4}`:`${_t(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,W?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",W?"text-grayWarm-400":"text-grayWarm-600"),children:["Exp. ",Er(t.expMonth,t.expYear)]})]}),a.jsxs("div",{className:"relative flex-shrink-0",ref:j,children:[a.jsx("button",{type:"button","aria-label":`Open actions for card ending ${t.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:g,onClick:C=>{C.stopPropagation(),p(S=>!S)},"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"})})}),w?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:C=>C.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&&!F?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:()=>{p(!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:()=>{p(!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:()=>{p(!1),d(t)},"data-testid":`menu-remove-${t.id}`,children:"Delete"})]}):null]})]})},_r=t=>`${Te().iconCdnBaseUrl}/website/assets/icons/payments/${t}.svg`,lt=({slug:t,alt:r})=>a.jsx("img",{src:_r(t),alt:r,height:20,loading:"lazy",style:{height:20,width:"auto"}}),Xe=({type:t,label:r,iconNode:n})=>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,onChange:()=>{},className:"h-4 w-4 cursor-pointer accent-grayWarm-900","aria-label":r}),a.jsxs("span",{className:"flex flex-1 items-center gap-2 text-sm font-semibold text-grayWarm-900",children:[r,n]})]}),Ct=({selected:t,onSelect:r,creditCardBody:n,className:o})=>{const l=t==="credit_card";return a.jsxs("div",{className:Q("flex w-full flex-col gap-3",o),children:[a.jsxs("label",{className:Q("flex cursor-pointer flex-col gap-3 rounded-lg border px-4 py-3 transition-colors",l?"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:l,onChange:()=>r("credit_card"),className:"h-4 w-4 cursor-pointer accent-grayWarm-900","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})]})]}),l?a.jsx("div",{"data-testid":"payment-type-credit_card-body",children:n}):null]}),l?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(Xe,{type:"paypal",label:"PayPal",iconNode:a.jsx(lt,{slug:"paypal",alt:"PayPal"})}),a.jsx(Xe,{type:"googlepay",label:"GooglePay",iconNode:a.jsx(lt,{slug:"google-pay",alt:"GooglePay"})}),a.jsx(Xe,{type:"klarna",label:"Klarna",iconNode:a.jsx(lt,{slug:"klarna",alt:"Klarna"})}),a.jsx(Xe,{type:"ach",label:"Bank account (ACH)",iconNode:a.jsx("span",{className:"text-xs font-medium text-grayWarm-500",children:"Direct debit"})})]})},kt="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."},Rt=t=>{const r=t.filter(o=>o.isDefault),n=t.filter(o=>!o.isDefault);return[...r,...n]},Nt=({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"})]}),Ut=({userId:t,defaultCardholderName:r,defaultCardholderFirstName:n,defaultCardholderLastName:o,selectedId:l,onSelect:d,onChange:f,onError:g,paymentTypeSelector:m=!0,autoSaveFirstCard:F=!0,selectionSetsDefault:v=!1,showDefaultBadge:w=!0,collapsible:p=!1,cardLabelFormat:j="branded",className:W})=>{const{items:ee,status:C,error:S,refetch:E}=$t(t),{deletePaymentMethod:re,status:Z}=Wt(t),{setDefault:de,status:ye}=Mt(t),{updatePaymentMethod:V,status:ae}=Ot(t),[x,ne]=s.useState([]),[Ce,ve]=s.useState(null),[P,b]=s.useState(!1),[h,k]=s.useState(null),[A,J]=s.useState(!1),[ue,q]=s.useState(!1),[B,I]=s.useState(null),[O,L]=s.useState(null),[fe,ce]=s.useState(null),[X,je]=s.useState(!1),ke=s.useRef(!1),me=s.useRef(g);s.useEffect(()=>{me.current=g},[g]);const se=s.useCallback(u=>{var G;(G=me.current)==null||G.call(me,u)},[]),xe=s.useCallback(()=>{b(!1),k(null),ce(null)},[]),ge=r??([n,o].filter(Boolean).join(" ")||void 0);s.useEffect(()=>{C==="ready"&&ne(Rt(ee))},[ee,C]);const _e=s.useRef(null);s.useEffect(()=>{if(C==="error"&&S){if(_e.current===S)return;_e.current=S,se({source:"list",message:S})}else C!=="error"&&(_e.current=null)},[C,S,se]),s.useEffect(()=>{if(!d||ke.current||C!=="ready"||x.length===0||l)return;ke.current=!0;const u=x.find(G=>G.isDefault)??x[0];d(u)},[d,C,x,l]);const K=s.useCallback(u=>{ne(G=>{const H=typeof u=="function"?u(G):u,$=Rt(H);return queueMicrotask(()=>f==null?void 0:f($)),$})},[f]),be=Z==="pending"||ye==="pending"||ae==="pending",Re=s.useCallback(async u=>{const G=x;ve(null),K(H=>H.map($=>({...$,isDefault:$.id===u.id})));try{await de(u.id),E()}catch(H){ne(G),f==null||f(G);const $=H instanceof Error?H.message:"Failed to set default payment method.";ve($),se({source:"set-default",message:$,cause:H})}},[x,K,de,E,f,se]),pe=s.useCallback(u=>{d==null||d(u),v&&(u.isDefault||Re(u))},[d,v,Re]),we=s.useCallback(async u=>{const G=x;ve(null);const H=x.filter(ie=>ie.id!==u.id);K(()=>H);const $=u.id===l&&d?H.find(ie=>ie.isDefault)??H[0]??null:null;$&&pe($);const Ee=!!$&&v&&$!==null&&!$.isDefault;try{await re(u.id),Ee||E()}catch(ie){ne(G),f==null||f(G);const We=ie instanceof Error?ie.message:"Failed to delete payment method.";ve(We),se({source:"delete",message:We,cause:ie})}},[x,K,re,E,f,l,d,pe,v,se]),N=s.useCallback(u=>{L(null),I(u)},[]),D=s.useCallback(()=>{I(null),L(null)},[]),Y=s.useCallback(async u=>{if(!B)return;const G=B,H=x;L(null),K($=>$.map(Ee=>Ee.id===G.id?{...Ee,...u.cardholderName!==void 0?{cardholderName:u.cardholderName}:{},...u.zip!==void 0?{zip:u.zip}:{}}:Ee));try{await V(G.id,u),D(),E()}catch($){ne(H),f==null||f(H);const Ee=Cr($);L(Ee),se({source:"update",message:Ee,cause:$})}},[B,x,K,V,E,f,D,se]),oe=s.useCallback(u=>{k(null),b(!1),ce(null),K(H=>[u,...H.filter($=>$.id!==u.id)]),pe(u),!!d&&v&&!u.isDefault||E()},[K,E,pe,d,v]),Ge=s.useCallback(u=>{k(u)},[]),He=C==="ready"&&x.length===0,Fe=typeof d=="function",Ie=!Fe&&!p,Je=x.length===0,Le=F&&x.length===0,Se=s.useCallback(u=>a.jsx(ft,{userId:t,isDefault:Je,defaultCardholderName:ge,autoSave:!u&&Le,hideInternalSaveButton:u,formId:u?kt:void 0,onCanSubmitChange:u?J:void 0,onSavingChange:u?q:void 0,autoFocus:u?"number":void 0,onSuccess:oe,onError:Ge,onErrorDetail:se}),[t,Je,ge,Le,oe,Ge,se]),ze=s.useMemo(()=>Se(!1),[Se]),Be=s.useMemo(()=>Se(!0),[Se]),Qe=s.useMemo(()=>m?a.jsx(Ct,{selected:fe,onSelect:u=>ce(u),creditCardBody:ze}):ze,[m,fe,ze]),et=s.useMemo(()=>m?a.jsx(Ct,{selected:fe,onSelect:u=>ce(u),creditCardBody:Be}):Be,[m,fe,Be]);return a.jsxs("div",{className:Q("flex w-full flex-col gap-4",W),"data-testid":"payment-methods-manager",children:[C==="loading"&&x.length===0?a.jsxs("div",{className:Q(Ie?"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(Nt,{withDefaultBadge:!0}),a.jsx(Nt,{})]}):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:S??"Failed to load payment methods."}),a.jsx("button",{type:"button",onClick:E,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,Ce?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:Ce}):null,p&&x.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":X?"payment-methods-drawer-header":"payment-methods-collapsed-preview",children:[X?a.jsx("h3",{className:"text-md font-semibold text-grayWarm-950",children:"Payment methods"}):a.jsx(At,{method:x.find(u=>u.id===l)??x.find(u=>u.isDefault)??x[0],cardLabelFormat:j,className:"flex-1"}),a.jsx("button",{type:"button","aria-label":X?"Collapse payment methods":"Expand payment methods","aria-expanded":X,className:"bg-grayWarm-100 p-2 rounded-lg hover:bg-grayWarm-200 transition-colors",onClick:()=>je(u=>!u),"data-testid":X?"payment-methods-drawer-close":"payment-methods-drawer-open",children:a.jsx("img",{src:`${Te().iconCdnBaseUrl}/website/assets/icons/chevron-${X?"up":"down"}-double.svg`,alt:"",className:"w-5 h-5"})})]})}):null,x.length>0&&(!p||X)?a.jsx("div",{className:Q("flex flex-col",Ie?"rounded-xl border border-grayWarm-200 px-4 md:px-6 divide-y divide-grayWarm-200":"space-y-3"),children:x.map(u=>a.jsx(jr,{method:u,selectable:Fe,selected:Fe&&u.id===l,onSelect:pe,onSetDefault:Re,onRemove:we,onEdit:N,disabled:be,showDefaultBadge:w,hideSetDefaultMenuItem:v,cardLabelFormat:j},u.id))}):null,He?a.jsx("div",{"data-testid":"payment-methods-empty",children:Qe}):x.length>0&&(!p||X)?a.jsx("button",{type:"button",onClick:()=>{k(null),ce(null),J(!1),b(!0)},onMouseEnter:()=>{ut().catch(()=>{})},onFocus:()=>{ut().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:P,onClose:xe,formId:kt,saveDisabled:!A,isSaving:ue,children:[et,h?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:h}):null]}),a.jsx(gr,{open:B!==null,method:B,onClose:D,onSave:Y,isSaving:ae==="pending",error:O})]})};Ut.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 n of r){const o=n.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:n,csrfCookieName:o=Rr,extraHeaders:l,authPathFragment:d=kr,baseFetch:f=Pr(),readCookie:g=Nr}=t;let m=null;const F=()=>{if(m)return m;const w=(async()=>{await r()})();return m=w,w.finally(()=>{m===w&&(m=null)}).catch(()=>{}),w},v=(w,p)=>{const j=new Headers(p==null?void 0:p.headers),W=g(o);if(W&&!j.has("X-CSRF-Token")&&j.set("X-CSRF-Token",W),l){const ee=l(w,p);for(const[C,S]of Object.entries(ee))j.has(C)||j.set(C,S)}return{...p,headers:j,credentials:(p==null?void 0:p.credentials)??"include"}};return async function(p,j){const W=await f(p,v(p,j));if(Sr(p).includes(d)||W.status!==401&&W.status!==403)return W;try{await F()}catch(S){try{n(S)}catch(E){console.error("@movmo_app/payments: onRefreshFailed callback threw — auth retry path is misconfigured",E)}return W}try{return await f(p,v(p,j))}catch(S){return console.error("@movmo_app/payments: retry after token refresh failed — returning original response",S),W}}};exports.MovmoCardForm=ft;exports.PaymentMethodPreview=At;exports.PaymentMethodsManager=Ut;exports.createMovmoAuthFetch=Tr;exports.getPaymentsConfig=Te;exports.setPaymentsConfig=rr;exports.useDeletePaymentMethod=Wt;exports.useMovmoCardFields=Tt;exports.useSetDefaultPaymentMethod=Mt;exports.useUpdatePaymentMethod=Ot;exports.useUserPaymentMethods=$t;
|
|
31
31
|
//# sourceMappingURL=index.cjs.js.map
|