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