@movmo_app/payments 0.2.1 → 0.3.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 +9 -9
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +89 -0
- package/dist/index.es.js +821 -746
- package/dist/index.es.js.map +1 -1
- package/package.json +1 -1
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../../../../node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.production.min.js","../../../../node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.development.js","../../../../node_modules/.pnpm/react@18.3.1/node_modules/react/jsx-runtime.js","../../../../node_modules/.pnpm/clsx@2.1.1/node_modules/clsx/dist/clsx.mjs","../src/config.ts","../src/api.ts","../src/PaymentMethodsManager/cardBrandIcon.tsx","../src/loadSpreedlyScript.ts","../src/useMovmoCardFields.ts","../src/MovmoCardForm/MovmoCardForm.tsx","../src/useDeletePaymentMethod.ts","../src/useSetDefaultPaymentMethod.ts","../src/useUserPaymentMethods.ts","../src/PaymentMethodsManager/AddPaymentMethodModal.tsx","../src/PaymentMethodsManager/PaymentMethodPreview.tsx","../src/PaymentMethodsManager/isExpired.ts","../src/PaymentMethodsManager/PaymentMethodRow.tsx","../src/PaymentMethodsManager/PaymentTypeSelector.tsx","../src/PaymentMethodsManager/PaymentMethodsManager.tsx"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var f=require(\"react\"),k=Symbol.for(\"react.element\"),l=Symbol.for(\"react.fragment\"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};\nfunction q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=\"\"+g);void 0!==a.key&&(e=\"\"+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q;\n","/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n'use strict';\n\nvar React = require('react');\n\n// ATTENTION\n// When adding new symbols to this file,\n// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'\n// The Symbol used to tag the ReactElement-like types.\nvar REACT_ELEMENT_TYPE = Symbol.for('react.element');\nvar REACT_PORTAL_TYPE = Symbol.for('react.portal');\nvar REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');\nvar REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');\nvar REACT_PROFILER_TYPE = Symbol.for('react.profiler');\nvar REACT_PROVIDER_TYPE = Symbol.for('react.provider');\nvar REACT_CONTEXT_TYPE = Symbol.for('react.context');\nvar REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');\nvar REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');\nvar REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');\nvar REACT_MEMO_TYPE = Symbol.for('react.memo');\nvar REACT_LAZY_TYPE = Symbol.for('react.lazy');\nvar REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');\nvar MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\nfunction error(format) {\n {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n var argsWithFormat = args.map(function (item) {\n return String(item);\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\n }\n}\n\n// -----------------------------------------------------------------------------\n\nvar enableScopeAPI = false; // Experimental Create Event Handle API.\nvar enableCacheElement = false;\nvar enableTransitionTracing = false; // No known bugs, but needs performance testing\n\nvar enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber\n// stuff. Intended to enable React core members to more easily debug scheduling\n// issues in DEV builds.\n\nvar enableDebugTracing = false; // Track which Fiber(s) schedule render work.\n\nvar REACT_MODULE_REFERENCE;\n\n{\n REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');\n}\n\nfunction isValidElementType(type) {\n if (typeof type === 'string' || typeof type === 'function') {\n return true;\n } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).\n\n\n if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {\n return true;\n }\n\n if (typeof type === 'object' && type !== null) {\n if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object\n // types supported by any Flight configuration anywhere since\n // we don't know which Flight build this will end up being used\n // with.\n type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var displayName = outerType.displayName;\n\n if (displayName) {\n return displayName;\n }\n\n var functionName = innerType.displayName || innerType.name || '';\n return functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName;\n} // Keep in sync with react-reconciler/getComponentNameFromFiber\n\n\nfunction getContextName(type) {\n return type.displayName || 'Context';\n} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.\n\n\nfunction getComponentNameFromType(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return 'Profiler';\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n var context = type;\n return getContextName(context) + '.Consumer';\n\n case REACT_PROVIDER_TYPE:\n var provider = type;\n return getContextName(provider._context) + '.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n var outerName = type.displayName || null;\n\n if (outerName !== null) {\n return outerName;\n }\n\n return getComponentNameFromType(type.type) || 'Memo';\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n return getComponentNameFromType(init(payload));\n } catch (x) {\n return null;\n }\n }\n\n // eslint-disable-next-line no-fallthrough\n }\n }\n\n return null;\n}\n\nvar assign = Object.assign;\n\n// Helpers to patch console.logs to avoid logging during side-effect free\n// replaying on render function. This currently only patches the object\n// lazily which won't cover if the log function was extracted eagerly.\n// We could also eagerly patch the method.\nvar disabledDepth = 0;\nvar prevLog;\nvar prevInfo;\nvar prevWarn;\nvar prevError;\nvar prevGroup;\nvar prevGroupCollapsed;\nvar prevGroupEnd;\n\nfunction disabledLog() {}\n\ndisabledLog.__reactDisabledLog = true;\nfunction disableLogs() {\n {\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n prevLog = console.log;\n prevInfo = console.info;\n prevWarn = console.warn;\n prevError = console.error;\n prevGroup = console.group;\n prevGroupCollapsed = console.groupCollapsed;\n prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099\n\n var props = {\n configurable: true,\n enumerable: true,\n value: disabledLog,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n info: props,\n log: props,\n warn: props,\n error: props,\n group: props,\n groupCollapsed: props,\n groupEnd: props\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n disabledDepth++;\n }\n}\nfunction reenableLogs() {\n {\n disabledDepth--;\n\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n var props = {\n configurable: true,\n enumerable: true,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n log: assign({}, props, {\n value: prevLog\n }),\n info: assign({}, props, {\n value: prevInfo\n }),\n warn: assign({}, props, {\n value: prevWarn\n }),\n error: assign({}, props, {\n value: prevError\n }),\n group: assign({}, props, {\n value: prevGroup\n }),\n groupCollapsed: assign({}, props, {\n value: prevGroupCollapsed\n }),\n groupEnd: assign({}, props, {\n value: prevGroupEnd\n })\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n if (disabledDepth < 0) {\n error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');\n }\n }\n}\n\nvar ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;\nvar prefix;\nfunction describeBuiltInComponentFrame(name, source, ownerFn) {\n {\n if (prefix === undefined) {\n // Extract the VM specific prefix used by each line.\n try {\n throw Error();\n } catch (x) {\n var match = x.stack.trim().match(/\\n( *(at )?)/);\n prefix = match && match[1] || '';\n }\n } // We use the prefix to ensure our stacks line up with native stack frames.\n\n\n return '\\n' + prefix + name;\n }\n}\nvar reentry = false;\nvar componentFrameCache;\n\n{\n var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;\n componentFrameCache = new PossiblyWeakMap();\n}\n\nfunction describeNativeComponentFrame(fn, construct) {\n // If something asked for a stack inside a fake render, it should get ignored.\n if ( !fn || reentry) {\n return '';\n }\n\n {\n var frame = componentFrameCache.get(fn);\n\n if (frame !== undefined) {\n return frame;\n }\n }\n\n var control;\n reentry = true;\n var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.\n\n Error.prepareStackTrace = undefined;\n var previousDispatcher;\n\n {\n previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function\n // for warnings.\n\n ReactCurrentDispatcher.current = null;\n disableLogs();\n }\n\n try {\n // This should throw.\n if (construct) {\n // Something should be setting the props in the constructor.\n var Fake = function () {\n throw Error();\n }; // $FlowFixMe\n\n\n Object.defineProperty(Fake.prototype, 'props', {\n set: function () {\n // We use a throwing setter instead of frozen or non-writable props\n // because that won't throw in a non-strict mode function.\n throw Error();\n }\n });\n\n if (typeof Reflect === 'object' && Reflect.construct) {\n // We construct a different control for this case to include any extra\n // frames added by the construct call.\n try {\n Reflect.construct(Fake, []);\n } catch (x) {\n control = x;\n }\n\n Reflect.construct(fn, [], Fake);\n } else {\n try {\n Fake.call();\n } catch (x) {\n control = x;\n }\n\n fn.call(Fake.prototype);\n }\n } else {\n try {\n throw Error();\n } catch (x) {\n control = x;\n }\n\n fn();\n }\n } catch (sample) {\n // This is inlined manually because closure doesn't do it for us.\n if (sample && control && typeof sample.stack === 'string') {\n // This extracts the first frame from the sample that isn't also in the control.\n // Skipping one frame that we assume is the frame that calls the two.\n var sampleLines = sample.stack.split('\\n');\n var controlLines = control.stack.split('\\n');\n var s = sampleLines.length - 1;\n var c = controlLines.length - 1;\n\n while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {\n // We expect at least one stack frame to be shared.\n // Typically this will be the root most one. However, stack frames may be\n // cut off due to maximum stack limits. In this case, one maybe cut off\n // earlier than the other. We assume that the sample is longer or the same\n // and there for cut off earlier. So we should find the root most frame in\n // the sample somewhere in the control.\n c--;\n }\n\n for (; s >= 1 && c >= 0; s--, c--) {\n // Next we find the first one that isn't the same which should be the\n // frame that called our sample function and the control.\n if (sampleLines[s] !== controlLines[c]) {\n // In V8, the first line is describing the message but other VMs don't.\n // If we're about to return the first line, and the control is also on the same\n // line, that's a pretty good indicator that our sample threw at same line as\n // the control. I.e. before we entered the sample frame. So we ignore this result.\n // This can happen if you passed a class to function component, or non-function.\n if (s !== 1 || c !== 1) {\n do {\n s--;\n c--; // We may still have similar intermediate frames from the construct call.\n // The next one that isn't the same should be our match though.\n\n if (c < 0 || sampleLines[s] !== controlLines[c]) {\n // V8 adds a \"new\" prefix for native classes. Let's remove it to make it prettier.\n var _frame = '\\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled \"<anonymous>\"\n // but we have a user-provided \"displayName\"\n // splice it in to make the stack more readable.\n\n\n if (fn.displayName && _frame.includes('<anonymous>')) {\n _frame = _frame.replace('<anonymous>', fn.displayName);\n }\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, _frame);\n }\n } // Return the line we found.\n\n\n return _frame;\n }\n } while (s >= 1 && c >= 0);\n }\n\n break;\n }\n }\n }\n } finally {\n reentry = false;\n\n {\n ReactCurrentDispatcher.current = previousDispatcher;\n reenableLogs();\n }\n\n Error.prepareStackTrace = previousPrepareStackTrace;\n } // Fallback to just using the name if we couldn't make it throw.\n\n\n var name = fn ? fn.displayName || fn.name : '';\n var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, syntheticFrame);\n }\n }\n\n return syntheticFrame;\n}\nfunction describeFunctionComponentFrame(fn, source, ownerFn) {\n {\n return describeNativeComponentFrame(fn, false);\n }\n}\n\nfunction shouldConstruct(Component) {\n var prototype = Component.prototype;\n return !!(prototype && prototype.isReactComponent);\n}\n\nfunction describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {\n\n if (type == null) {\n return '';\n }\n\n if (typeof type === 'function') {\n {\n return describeNativeComponentFrame(type, shouldConstruct(type));\n }\n }\n\n if (typeof type === 'string') {\n return describeBuiltInComponentFrame(type);\n }\n\n switch (type) {\n case REACT_SUSPENSE_TYPE:\n return describeBuiltInComponentFrame('Suspense');\n\n case REACT_SUSPENSE_LIST_TYPE:\n return describeBuiltInComponentFrame('SuspenseList');\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_FORWARD_REF_TYPE:\n return describeFunctionComponentFrame(type.render);\n\n case REACT_MEMO_TYPE:\n // Memo may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n // Lazy may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);\n } catch (x) {}\n }\n }\n }\n\n return '';\n}\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar loggedTypeFailures = {};\nvar ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame.setExtraStackFrame(null);\n }\n }\n}\n\nfunction checkPropTypes(typeSpecs, values, location, componentName, element) {\n {\n // $FlowFixMe This is okay but Flow doesn't know it.\n var has = Function.call.bind(hasOwnProperty);\n\n for (var typeSpecName in typeSpecs) {\n if (has(typeSpecs, typeSpecName)) {\n var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n // eslint-disable-next-line react-internal/prod-error-codes\n var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');\n err.name = 'Invariant Violation';\n throw err;\n }\n\n error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');\n } catch (ex) {\n error$1 = ex;\n }\n\n if (error$1 && !(error$1 instanceof Error)) {\n setCurrentlyValidatingElement(element);\n\n error('%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).', componentName || 'React class', location, typeSpecName, typeof error$1);\n\n setCurrentlyValidatingElement(null);\n }\n\n if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error$1.message] = true;\n setCurrentlyValidatingElement(element);\n\n error('Failed %s type: %s', location, error$1.message);\n\n setCurrentlyValidatingElement(null);\n }\n }\n }\n }\n}\n\nvar isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare\n\nfunction isArray(a) {\n return isArrayImpl(a);\n}\n\n/*\n * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol\n * and Temporal.* types. See https://github.com/facebook/react/pull/22064.\n *\n * The functions in this module will throw an easier-to-understand,\n * easier-to-debug exception with a clear errors message message explaining the\n * problem. (Instead of a confusing exception thrown inside the implementation\n * of the `value` object).\n */\n// $FlowFixMe only called in DEV, so void return is not possible.\nfunction typeName(value) {\n {\n // toStringTag is needed for namespaced types like Temporal.Instant\n var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;\n var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';\n return type;\n }\n} // $FlowFixMe only called in DEV, so void return is not possible.\n\n\nfunction willCoercionThrow(value) {\n {\n try {\n testStringCoercion(value);\n return false;\n } catch (e) {\n return true;\n }\n }\n}\n\nfunction testStringCoercion(value) {\n // If you ended up here by following an exception call stack, here's what's\n // happened: you supplied an object or symbol value to React (as a prop, key,\n // DOM attribute, CSS property, string ref, etc.) and when React tried to\n // coerce it to a string using `'' + value`, an exception was thrown.\n //\n // The most common types that will cause this exception are `Symbol` instances\n // and Temporal objects like `Temporal.Instant`. But any object that has a\n // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this\n // exception. (Library authors do this to prevent users from using built-in\n // numeric operators like `+` or comparison operators like `>=` because custom\n // methods are needed to perform accurate arithmetic or comparison.)\n //\n // To fix the problem, coerce this object or symbol value to a string before\n // passing it to React. The most reliable way is usually `String(value)`.\n //\n // To find which value is throwing, check the browser or debugger console.\n // Before this exception was thrown, there should be `console.error` output\n // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the\n // problem and how that type was used: key, atrribute, input value prop, etc.\n // In most cases, this console output also shows the component and its\n // ancestor components where the exception happened.\n //\n // eslint-disable-next-line react-internal/safe-string-coercion\n return '' + value;\n}\nfunction checkKeyStringCoercion(value) {\n {\n if (willCoercionThrow(value)) {\n error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));\n\n return testStringCoercion(value); // throw (to help callers find troubleshooting comments)\n }\n }\n}\n\nvar ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;\nvar RESERVED_PROPS = {\n key: true,\n ref: true,\n __self: true,\n __source: true\n};\nvar specialPropKeyWarningShown;\nvar specialPropRefWarningShown;\nvar didWarnAboutStringRefs;\n\n{\n didWarnAboutStringRefs = {};\n}\n\nfunction hasValidRef(config) {\n {\n if (hasOwnProperty.call(config, 'ref')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.ref !== undefined;\n}\n\nfunction hasValidKey(config) {\n {\n if (hasOwnProperty.call(config, 'key')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'key').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.key !== undefined;\n}\n\nfunction warnIfStringRefCannotBeAutoConverted(config, self) {\n {\n if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {\n var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);\n\n if (!didWarnAboutStringRefs[componentName]) {\n error('Component \"%s\" contains the string ref \"%s\". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);\n\n didWarnAboutStringRefs[componentName] = true;\n }\n }\n }\n}\n\nfunction defineKeyPropWarningGetter(props, displayName) {\n {\n var warnAboutAccessingKey = function () {\n if (!specialPropKeyWarningShown) {\n specialPropKeyWarningShown = true;\n\n error('%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)', displayName);\n }\n };\n\n warnAboutAccessingKey.isReactWarning = true;\n Object.defineProperty(props, 'key', {\n get: warnAboutAccessingKey,\n configurable: true\n });\n }\n}\n\nfunction defineRefPropWarningGetter(props, displayName) {\n {\n var warnAboutAccessingRef = function () {\n if (!specialPropRefWarningShown) {\n specialPropRefWarningShown = true;\n\n error('%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)', displayName);\n }\n };\n\n warnAboutAccessingRef.isReactWarning = true;\n Object.defineProperty(props, 'ref', {\n get: warnAboutAccessingRef,\n configurable: true\n });\n }\n}\n/**\n * Factory method to create a new React element. This no longer adheres to\n * the class pattern, so do not use new to call it. Also, instanceof check\n * will not work. Instead test $$typeof field against Symbol.for('react.element') to check\n * if something is a React Element.\n *\n * @param {*} type\n * @param {*} props\n * @param {*} key\n * @param {string|object} ref\n * @param {*} owner\n * @param {*} self A *temporary* helper to detect places where `this` is\n * different from the `owner` when React.createElement is called, so that we\n * can warn. We want to get rid of owner and replace string `ref`s with arrow\n * functions, and as long as `this` and owner are the same, there will be no\n * change in behavior.\n * @param {*} source An annotation object (added by a transpiler or otherwise)\n * indicating filename, line number, and/or other information.\n * @internal\n */\n\n\nvar ReactElement = function (type, key, ref, self, source, owner, props) {\n var element = {\n // This tag allows us to uniquely identify this as a React Element\n $$typeof: REACT_ELEMENT_TYPE,\n // Built-in properties that belong on the element\n type: type,\n key: key,\n ref: ref,\n props: props,\n // Record the component responsible for creating this element.\n _owner: owner\n };\n\n {\n // The validation flag is currently mutative. We put it on\n // an external backing store so that we can freeze the whole object.\n // This can be replaced with a WeakMap once they are implemented in\n // commonly used development environments.\n element._store = {}; // To make comparing ReactElements easier for testing purposes, we make\n // the validation flag non-enumerable (where possible, which should\n // include every environment we run tests in), so the test framework\n // ignores it.\n\n Object.defineProperty(element._store, 'validated', {\n configurable: false,\n enumerable: false,\n writable: true,\n value: false\n }); // self and source are DEV only properties.\n\n Object.defineProperty(element, '_self', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: self\n }); // Two elements created in two different places should be considered\n // equal for testing purposes and therefore we hide it from enumeration.\n\n Object.defineProperty(element, '_source', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: source\n });\n\n if (Object.freeze) {\n Object.freeze(element.props);\n Object.freeze(element);\n }\n }\n\n return element;\n};\n/**\n * https://github.com/reactjs/rfcs/pull/107\n * @param {*} type\n * @param {object} props\n * @param {string} key\n */\n\nfunction jsxDEV(type, config, maybeKey, source, self) {\n {\n var propName; // Reserved names are extracted\n\n var props = {};\n var key = null;\n var ref = null; // Currently, key can be spread in as a prop. This causes a potential\n // issue if key is also explicitly declared (ie. <div {...props} key=\"Hi\" />\n // or <div key=\"Hi\" {...props} /> ). We want to deprecate key spread,\n // but as an intermediary step, we will use jsxDEV for everything except\n // <div {...props} key=\"Hi\" />, because we aren't currently able to tell if\n // key is explicitly declared to be undefined or not.\n\n if (maybeKey !== undefined) {\n {\n checkKeyStringCoercion(maybeKey);\n }\n\n key = '' + maybeKey;\n }\n\n if (hasValidKey(config)) {\n {\n checkKeyStringCoercion(config.key);\n }\n\n key = '' + config.key;\n }\n\n if (hasValidRef(config)) {\n ref = config.ref;\n warnIfStringRefCannotBeAutoConverted(config, self);\n } // Remaining properties are added to a new props object\n\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n props[propName] = config[propName];\n }\n } // Resolve default props\n\n\n if (type && type.defaultProps) {\n var defaultProps = type.defaultProps;\n\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n }\n\n if (key || ref) {\n var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;\n\n if (key) {\n defineKeyPropWarningGetter(props, displayName);\n }\n\n if (ref) {\n defineRefPropWarningGetter(props, displayName);\n }\n }\n\n return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);\n }\n}\n\nvar ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement$1(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame$1.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame$1.setExtraStackFrame(null);\n }\n }\n}\n\nvar propTypesMisspellWarningShown;\n\n{\n propTypesMisspellWarningShown = false;\n}\n/**\n * Verifies the object is a ReactElement.\n * See https://reactjs.org/docs/react-api.html#isvalidelement\n * @param {?object} object\n * @return {boolean} True if `object` is a ReactElement.\n * @final\n */\n\n\nfunction isValidElement(object) {\n {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n }\n}\n\nfunction getDeclarationErrorAddendum() {\n {\n if (ReactCurrentOwner$1.current) {\n var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);\n\n if (name) {\n return '\\n\\nCheck the render method of `' + name + '`.';\n }\n }\n\n return '';\n }\n}\n\nfunction getSourceInfoErrorAddendum(source) {\n {\n if (source !== undefined) {\n var fileName = source.fileName.replace(/^.*[\\\\\\/]/, '');\n var lineNumber = source.lineNumber;\n return '\\n\\nCheck your code at ' + fileName + ':' + lineNumber + '.';\n }\n\n return '';\n }\n}\n/**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n\nvar ownerHasKeyUseWarning = {};\n\nfunction getCurrentComponentErrorInfo(parentType) {\n {\n var info = getDeclarationErrorAddendum();\n\n if (!info) {\n var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;\n\n if (parentName) {\n info = \"\\n\\nCheck the top-level render call using <\" + parentName + \">.\";\n }\n }\n\n return info;\n }\n}\n/**\n * Warn if the element doesn't have an explicit key assigned to it.\n * This element is in an array. The array could grow and shrink or be\n * reordered. All children that haven't already been validated are required to\n * have a \"key\" property assigned to it. Error statuses are cached so a warning\n * will only be shown once.\n *\n * @internal\n * @param {ReactElement} element Element that requires a key.\n * @param {*} parentType element's parent's type.\n */\n\n\nfunction validateExplicitKey(element, parentType) {\n {\n if (!element._store || element._store.validated || element.key != null) {\n return;\n }\n\n element._store.validated = true;\n var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);\n\n if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a\n // property, it may be the creator of the child that's responsible for\n // assigning it a key.\n\n var childOwner = '';\n\n if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {\n // Give the component that originally created this child.\n childOwner = \" It was passed a child from \" + getComponentNameFromType(element._owner.type) + \".\";\n }\n\n setCurrentlyValidatingElement$1(element);\n\n error('Each child in a list should have a unique \"key\" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);\n\n setCurrentlyValidatingElement$1(null);\n }\n}\n/**\n * Ensure that every element either is passed in a static location, in an\n * array with an explicit keys property defined, or in an object literal\n * with valid key property.\n *\n * @internal\n * @param {ReactNode} node Statically passed child of any type.\n * @param {*} parentType node's parent's type.\n */\n\n\nfunction validateChildKeys(node, parentType) {\n {\n if (typeof node !== 'object') {\n return;\n }\n\n if (isArray(node)) {\n for (var i = 0; i < node.length; i++) {\n var child = node[i];\n\n if (isValidElement(child)) {\n validateExplicitKey(child, parentType);\n }\n }\n } else if (isValidElement(node)) {\n // This element was passed in a valid location.\n if (node._store) {\n node._store.validated = true;\n }\n } else if (node) {\n var iteratorFn = getIteratorFn(node);\n\n if (typeof iteratorFn === 'function') {\n // Entry iterators used to provide implicit keys,\n // but now we print a separate warning for them later.\n if (iteratorFn !== node.entries) {\n var iterator = iteratorFn.call(node);\n var step;\n\n while (!(step = iterator.next()).done) {\n if (isValidElement(step.value)) {\n validateExplicitKey(step.value, parentType);\n }\n }\n }\n }\n }\n }\n}\n/**\n * Given an element, validate that its props follow the propTypes definition,\n * provided by the type.\n *\n * @param {ReactElement} element\n */\n\n\nfunction validatePropTypes(element) {\n {\n var type = element.type;\n\n if (type === null || type === undefined || typeof type === 'string') {\n return;\n }\n\n var propTypes;\n\n if (typeof type === 'function') {\n propTypes = type.propTypes;\n } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.\n // Inner props are checked in the reconciler.\n type.$$typeof === REACT_MEMO_TYPE)) {\n propTypes = type.propTypes;\n } else {\n return;\n }\n\n if (propTypes) {\n // Intentionally inside to avoid triggering lazy initializers:\n var name = getComponentNameFromType(type);\n checkPropTypes(propTypes, element.props, 'prop', name, element);\n } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {\n propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:\n\n var _name = getComponentNameFromType(type);\n\n error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');\n }\n\n if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');\n }\n }\n}\n/**\n * Given a fragment, validate that it can only be provided with fragment props\n * @param {ReactElement} fragment\n */\n\n\nfunction validateFragmentProps(fragment) {\n {\n var keys = Object.keys(fragment.props);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n\n if (key !== 'children' && key !== 'key') {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);\n\n setCurrentlyValidatingElement$1(null);\n break;\n }\n }\n\n if (fragment.ref !== null) {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid attribute `ref` supplied to `React.Fragment`.');\n\n setCurrentlyValidatingElement$1(null);\n }\n }\n}\n\nvar didWarnAboutKeySpread = {};\nfunction jsxWithValidation(type, props, key, isStaticChildren, source, self) {\n {\n var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to\n // succeed and there will likely be errors in render.\n\n if (!validType) {\n var info = '';\n\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and named imports.\";\n }\n\n var sourceInfo = getSourceInfoErrorAddendum(source);\n\n if (sourceInfo) {\n info += sourceInfo;\n } else {\n info += getDeclarationErrorAddendum();\n }\n\n var typeString;\n\n if (type === null) {\n typeString = 'null';\n } else if (isArray(type)) {\n typeString = 'array';\n } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {\n typeString = \"<\" + (getComponentNameFromType(type.type) || 'Unknown') + \" />\";\n info = ' Did you accidentally export a JSX literal instead of a component?';\n } else {\n typeString = typeof type;\n }\n\n error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);\n }\n\n var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.\n // TODO: Drop this when these are no longer allowed as the type argument.\n\n if (element == null) {\n return element;\n } // Skip key warning if the type isn't valid since our key validation logic\n // doesn't expect a non-string/function type and can throw confusing errors.\n // We don't want exception behavior to differ between dev and prod.\n // (Rendering will throw with a helpful message and as soon as the type is\n // fixed, the key warnings will appear.)\n\n\n if (validType) {\n var children = props.children;\n\n if (children !== undefined) {\n if (isStaticChildren) {\n if (isArray(children)) {\n for (var i = 0; i < children.length; i++) {\n validateChildKeys(children[i], type);\n }\n\n if (Object.freeze) {\n Object.freeze(children);\n }\n } else {\n error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');\n }\n } else {\n validateChildKeys(children, type);\n }\n }\n }\n\n {\n if (hasOwnProperty.call(props, 'key')) {\n var componentName = getComponentNameFromType(type);\n var keys = Object.keys(props).filter(function (k) {\n return k !== 'key';\n });\n var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';\n\n if (!didWarnAboutKeySpread[componentName + beforeExample]) {\n var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';\n\n error('A props object containing a \"key\" prop is being spread into JSX:\\n' + ' let props = %s;\\n' + ' <%s {...props} />\\n' + 'React keys must be passed directly to JSX without using spread:\\n' + ' let props = %s;\\n' + ' <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);\n\n didWarnAboutKeySpread[componentName + beforeExample] = true;\n }\n }\n }\n\n if (type === REACT_FRAGMENT_TYPE) {\n validateFragmentProps(element);\n } else {\n validatePropTypes(element);\n }\n\n return element;\n }\n} // These two functions exist to still get child warnings in dev\n// even with the prod transform. This means that jsxDEV is purely\n// opt-in behavior for better messages but that we won't stop\n// giving you warnings if you use production apis.\n\nfunction jsxWithValidationStatic(type, props, key) {\n {\n return jsxWithValidation(type, props, key, true);\n }\n}\nfunction jsxWithValidationDynamic(type, props, key) {\n {\n return jsxWithValidation(type, props, key, false);\n }\n}\n\nvar jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.\n// for now we can ship identical prod functions\n\nvar jsxs = jsxWithValidationStatic ;\n\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsx;\nexports.jsxs = jsxs;\n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.min.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f)}else for(f in e)e[f]&&(n&&(n+=\" \"),n+=f);return n}export function clsx(){for(var e,t,f=0,n=\"\",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;","export interface PaymentsConfig {\n baseUrl: string;\n /**\n * Base URL for Movmo's payment-icon assets (Visa / MC / Amex / Discover SVGs\n * + PayPal / GooglePay / Klarna PNGs). Defaults to the e2e CDN; prod\n * consumers should override at boot once a prod CDN is set up.\n */\n iconCdnBaseUrl?: string;\n /**\n * Custom `fetch` impl used by every API call in this package. Defaults to\n * `globalThis.fetch`. Consumers that need auth-token refresh, CSRF-token\n * injection, or any other request-shaping logic should provide their own\n * wrapper here (e.g. one that retries on 401/403 after refreshing the\n * session cookie). The package never adds business headers — that's the\n * consumer's responsibility.\n */\n fetch?: typeof fetch;\n}\n\n/** @internal — surfaced as `PaymentsConfig & { spreedlyScriptUrl }` only for tests + the script loader. */\ninterface InternalPaymentsConfig extends PaymentsConfig {\n spreedlyScriptUrl: string;\n iconCdnBaseUrl: string;\n fetch: typeof fetch;\n}\n\nconst DEFAULT_SPREEDLY_SCRIPT_URL = 'https://core.spreedly.com/iframe/iframe-v1.min.js';\nconst DEFAULT_ICON_CDN_BASE_URL = 'https://cdn.e2e.movmo.io';\n\nlet overrides: Partial<InternalPaymentsConfig> = {};\n\nexport const setPaymentsConfig = (config: Partial<PaymentsConfig>): void => {\n overrides = { ...overrides, ...config };\n};\n\nconst readEnv = (key: string): string | undefined => {\n // `process.env` is the conventional carrier for `REACT_APP_*` config in\n // consumers built with CRA / Vite / Webpack — those bundlers replace\n // `process.env.X` at build time, so this is type-only access at runtime.\n const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;\n return proc?.env?.[key];\n};\n\nexport const getPaymentsConfig = (): InternalPaymentsConfig => ({\n baseUrl: overrides.baseUrl ?? readEnv('REACT_APP_MOVMO_API_URL') ?? '',\n spreedlyScriptUrl:\n overrides.spreedlyScriptUrl ??\n readEnv('REACT_APP_SPREEDLY_SCRIPT_URL') ??\n DEFAULT_SPREEDLY_SCRIPT_URL,\n iconCdnBaseUrl:\n overrides.iconCdnBaseUrl ??\n readEnv('REACT_APP_MOVMO_ICON_CDN_URL') ??\n DEFAULT_ICON_CDN_BASE_URL,\n fetch:\n overrides.fetch ??\n (typeof globalThis !== 'undefined' && typeof globalThis.fetch === 'function'\n ? globalThis.fetch.bind(globalThis)\n : (() => {\n throw new Error('@movmo_app/payments: no fetch available');\n })()),\n});\n\n/** Reset overrides — used by tests and Storybook decorators. */\nexport const __resetPaymentsConfig = (): void => {\n overrides = {};\n};\n","import { getPaymentsConfig } from './config';\nimport type { PaymentMethodSummary, TokenizationSession } from './types';\n\ninterface PaymentMethodResponse {\n id: string;\n last4: string;\n brand: string;\n expMonth: number;\n expYear: number;\n isDefault: boolean;\n}\n\nconst toSummary = (body: PaymentMethodResponse): PaymentMethodSummary => ({\n id: body.id,\n last4: body.last4,\n brand: body.brand,\n expMonth: body.expMonth,\n expYear: body.expYear,\n isDefault: body.isDefault,\n});\n\nconst jsonHeaders: HeadersInit = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n};\n\nconst apiUrl = (path: string): string => {\n const { baseUrl } = getPaymentsConfig();\n if (!baseUrl) {\n throw new Error(\n '@movmo_app/payments: baseUrl is not configured. Call setPaymentsConfig({ baseUrl }) at app boot, or set REACT_APP_MOVMO_API_URL.',\n );\n }\n return `${baseUrl}${path}`;\n};\n\n/** Runs every fetch through the consumer-supplied `fetch` (falls back to `globalThis.fetch`). */\nconst performFetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const { fetch: configuredFetch } = getPaymentsConfig();\n return configuredFetch(input, init);\n};\n\nconst readError = async (res: Response, fallback: string): Promise<string> => {\n try {\n const body = (await res.json()) as { message?: string };\n return body.message || fallback;\n } catch {\n return fallback;\n }\n};\n\n/**\n * In-flight request cache for the tokenization session. React 18 StrictMode\n * mounts useMovmoCardFields twice in development, and the modal+inline form\n * can both mount briefly during the initial loading flash. Without this, the\n * same GET fires 2-4 times back-to-back. Concurrent callers receive the same\n * promise; once it settles (success or failure) the cache is cleared.\n *\n * Important: clear via `.finally()` AFTER assigning the cache. A `try/finally`\n * inside the async IIFE would clear the slot synchronously when the body\n * throws (apiUrl baseUrl-guard), then the outer assignment overwrites the\n * null with the rejected promise — leaking it into the next caller.\n */\nlet inFlightTokenizationSession: Promise<TokenizationSession> | null = null;\n\nexport const fetchTokenizationSession = (): Promise<TokenizationSession> => {\n if (inFlightTokenizationSession) return inFlightTokenizationSession;\n const promise = (async () => {\n const res = await performFetch(apiUrl('/v1/payments/tokenization-session'), {\n method: 'GET',\n headers: jsonHeaders,\n credentials: 'include',\n });\n if (!res.ok) {\n throw new Error(\n await readError(res, `Failed to fetch tokenization session (${res.status})`),\n );\n }\n return (await res.json()) as TokenizationSession;\n })();\n inFlightTokenizationSession = promise;\n promise\n .finally(() => {\n // Only clear the slot if nothing newer has replaced it.\n if (inFlightTokenizationSession === promise) {\n inFlightTokenizationSession = null;\n }\n })\n .catch(() => {\n /* swallow — the original rejection still propagates via `promise` itself */\n });\n return promise;\n};\n\n/**\n * True when the response body has enough data to render a full\n * PaymentMethodSummary card row (brand + last4 + exp). monolith-api's POST\n * `/from-token` currently returns only `{ id }` — when that happens, the\n * caller of this helper falls back to a GET by id so the consumer never sees\n * a partial record (which would crash render with `brand.toLowerCase`).\n */\nconst isFullPaymentMethodBody = (\n body: Partial<PaymentMethodResponse> & { id: string },\n): body is PaymentMethodResponse =>\n typeof body.brand === 'string' &&\n typeof body.last4 === 'string' &&\n typeof body.expMonth === 'number' &&\n typeof body.expYear === 'number';\n\nexport const savePaymentMethodFromToken = async (\n userId: string,\n tokenizedPaymentMethodId: string,\n isDefault: boolean,\n): Promise<PaymentMethodSummary> => {\n const res = await performFetch(\n apiUrl(`/v1/users/${encodeURIComponent(userId)}/payment-methods/from-token`),\n {\n method: 'POST',\n headers: jsonHeaders,\n credentials: 'include',\n body: JSON.stringify({ tokenizedPaymentMethodId, isDefault }),\n },\n );\n if (!res.ok) {\n throw new Error(await readError(res, `Failed to save payment method (${res.status})`));\n }\n const body = (await res.json()) as Partial<PaymentMethodResponse> & { id: string };\n if (isFullPaymentMethodBody(body)) {\n return toSummary(body);\n }\n // monolith-api returned a thin `{ id }` — load the full record so the\n // consumer's optimistic-insert + row render has brand/last4/exp.\n const getRes = await performFetch(\n apiUrl(\n `/v1/users/${encodeURIComponent(userId)}/payment-methods/${encodeURIComponent(body.id)}`,\n ),\n {\n method: 'GET',\n headers: jsonHeaders,\n credentials: 'include',\n },\n );\n if (!getRes.ok) {\n throw new Error(\n await readError(getRes, `Failed to fetch saved payment method (${getRes.status})`),\n );\n }\n const fullBody = (await getRes.json()) as PaymentMethodResponse;\n return toSummary(fullBody);\n};\n\nexport const listPaymentMethods = async (userId: string): Promise<PaymentMethodSummary[]> => {\n const res = await performFetch(apiUrl(`/v1/users/${encodeURIComponent(userId)}/payment-methods`), {\n method: 'GET',\n headers: jsonHeaders,\n credentials: 'include',\n });\n if (!res.ok) {\n throw new Error(await readError(res, `Failed to fetch payment methods (${res.status})`));\n }\n const body = (await res.json()) as PaymentMethodResponse[] | null;\n // Drops legacy Stripe holdover fields (customerId, paymentMethodId, token)\n // that monolith-api still returns pre-MOVMO-368.\n return (body ?? []).map(toSummary);\n};\n\nexport const deletePaymentMethod = async (userId: string, methodId: string): Promise<void> => {\n const res = await performFetch(\n apiUrl(\n `/v1/users/${encodeURIComponent(userId)}/payment-methods/${encodeURIComponent(methodId)}`,\n ),\n {\n method: 'DELETE',\n headers: jsonHeaders,\n credentials: 'include',\n },\n );\n if (!res.ok) {\n throw new Error(await readError(res, `Failed to delete payment method (${res.status})`));\n }\n};\n\nexport const updatePaymentMethod = async (\n userId: string,\n methodId: string,\n patch: { isDefault?: boolean },\n): Promise<void> => {\n const res = await performFetch(\n apiUrl(\n `/v1/users/${encodeURIComponent(userId)}/payment-methods/${encodeURIComponent(methodId)}`,\n ),\n {\n method: 'PUT',\n headers: jsonHeaders,\n credentials: 'include',\n body: JSON.stringify(patch),\n },\n );\n if (!res.ok) {\n throw new Error(await readError(res, `Failed to update payment method (${res.status})`));\n }\n};\n","import type { ReactElement } from 'react';\n\nimport { getPaymentsConfig } from '../config';\n\n/**\n * Spreedly's BIN detection emits 'master' / 'american_express' / etc. — map\n * to the file slugs used on Movmo's icon CDN.\n */\nconst BRAND_SLUG: Record<string, string> = {\n visa: 'visa',\n master: 'mastercard',\n mastercard: 'mastercard',\n american_express: 'amex',\n amex: 'amex',\n discover: 'discover',\n};\n\ninterface CardBrandIconProps {\n brand: string;\n className?: string;\n /**\n * Size hint in px. Floored at MIN_RENDER_WIDTH so callers passing small\n * values (e.g. 24 from inside the card-number field shell) still get a\n * legible brand mark. Height auto-scales 24:34 to match the source SVG\n * viewBox so the glyph isn't distorted.\n */\n width?: number;\n}\n\n/** Anything below this looks too cramped against the SVGs' internal padding. */\nconst MIN_RENDER_WIDTH = 28;\n\n/**\n * Renders the official brand mark from Movmo's icon CDN\n * (`<iconCdnBaseUrl>/website/assets/icons/payments/<brand>.svg`).\n *\n * Brand is determined by Spreedly's hosted-fields BIN detection (the\n * `cardType` field on `fieldEvent` payloads — visa/master/american_express/\n * discover/etc.) — same approach Stripe uses. Unknown / not-yet-detected\n * brands render the generic `credit-card.svg` placeholder so the layout\n * doesn't collapse before the user has typed enough digits.\n */\nexport const CardBrandIcon = ({\n brand,\n className,\n width = 46,\n}: CardBrandIconProps): ReactElement => {\n const slug = brand ? (BRAND_SLUG[brand.toLowerCase()] ?? 'credit-card') : 'credit-card';\n const renderWidth = Math.max(width, MIN_RENDER_WIDTH);\n const renderHeight = Math.round((renderWidth * 24) / 34);\n const { iconCdnBaseUrl } = getPaymentsConfig();\n return (\n <img\n src={`${iconCdnBaseUrl}/website/assets/icons/payments/${slug}.svg`}\n alt={slug === 'credit-card' ? 'card' : `${slug} card`}\n data-testid={`card-brand-${brand.toLowerCase()}`}\n className={className}\n width={renderWidth}\n height={renderHeight}\n loading=\"lazy\"\n />\n );\n};\n","import type { SpreedlyGlobal } from './spreedly-global';\nimport { getPaymentsConfig } from './config';\n\nlet scriptPromise: Promise<SpreedlyGlobal> | null = null;\n\n/**\n * Idempotently inject the Spreedly iframe SDK script and resolve with the\n * `window.Spreedly` global. Subsequent calls return the same promise.\n */\nexport const loadSpreedlyScript = (): Promise<SpreedlyGlobal> => {\n if (typeof window === 'undefined') {\n return Promise.reject(new Error('Spreedly can only be loaded in a browser environment.'));\n }\n if (window.Spreedly) {\n return Promise.resolve(window.Spreedly);\n }\n if (scriptPromise) {\n return scriptPromise;\n }\n\n const { spreedlyScriptUrl } = getPaymentsConfig();\n\n scriptPromise = new Promise<SpreedlyGlobal>((resolve, reject) => {\n const existing = document.querySelector<HTMLScriptElement>(\n `script[src=\"${spreedlyScriptUrl}\"]`,\n );\n\n const onScriptLoad = () => {\n if (window.Spreedly) {\n resolve(window.Spreedly);\n } else {\n reject(new Error('Spreedly script loaded but window.Spreedly is undefined.'));\n }\n };\n\n if (existing) {\n if (window.Spreedly) {\n onScriptLoad();\n return;\n }\n existing.addEventListener('load', onScriptLoad, { once: true });\n existing.addEventListener(\n 'error',\n () => {\n existing.remove();\n reject(new Error('Failed to load Spreedly iframe script.'));\n },\n { once: true },\n );\n return;\n }\n\n const script = document.createElement('script');\n script.src = spreedlyScriptUrl;\n script.async = true;\n script.onload = onScriptLoad;\n script.onerror = () => {\n // Without removing the failed tag, the next call hits the `existing`\n // branch above and attaches listeners to a script that already errored —\n // the promise would never resolve.\n script.remove();\n reject(new Error('Failed to load Spreedly iframe script.'));\n };\n document.head.appendChild(script);\n }).catch((err) => {\n scriptPromise = null;\n throw err;\n });\n\n return scriptPromise;\n};\n\nexport const __resetSpreedlyScriptCache = (): void => {\n scriptPromise = null;\n};\n","import { useCallback, useEffect, useRef, useState } from 'react';\n\nimport { fetchTokenizationSession } from './api';\nimport { loadSpreedlyScript } from './loadSpreedlyScript';\nimport type { SpreedlyGlobal, SpreedlyTokenizeData } from './spreedly-global';\nimport type { CardFieldError } from './types';\n\nexport interface CardholderTokenizeData {\n firstName: string;\n lastName: string;\n /** Two-digit month, e.g. \"01\"–\"12\". */\n month: string;\n /** Four-digit year, e.g. \"2030\". */\n year: string;\n email?: string;\n zip?: string;\n}\n\nexport interface CardFieldValidity {\n /** True only when the card-number field has a complete, length-valid value. */\n number: boolean;\n /** True only when the CVV field has a complete value (3 or 4 digits). */\n cvv: boolean;\n}\n\n/**\n * Focus state of each Spreedly-hosted iframe. The browser's `focus-within`\n * CSS pseudo-class can't see across iframe boundaries, so the consumer needs\n * an explicit signal to render the \"active border\" on the iframe shell.\n */\nexport interface CardFieldFocus {\n number: boolean;\n cvv: boolean;\n}\n\nexport interface UseMovmoCardFieldsOptions {\n /** DOM element id where the card-number field mounts. Defaults to `movmo-card-number`. */\n numberEl?: string;\n /** DOM element id where the CVV field mounts. Defaults to `movmo-card-cvv`. */\n cvvEl?: string;\n onCardTokenized?: (token: string) => void;\n onFieldErrors?: (errors: CardFieldError[]) => void;\n /**\n * Fires whenever per-field validity changes (number length valid, CVV length valid).\n * Use to gate the save button at the form layer.\n */\n onValidityChange?: (validity: CardFieldValidity) => void;\n /**\n * Fires whenever the detected card brand changes (visa/master/american_express/discover/etc).\n * Use to render the brand icon inline with the card-number field.\n */\n onBrandChange?: (brand: string | null) => void;\n}\n\nexport interface UseMovmoCardFieldsResult {\n status: 'idle' | 'loading' | 'ready' | 'error';\n error: string | null;\n tokenize: (data: CardholderTokenizeData) => void;\n /** Latest validity snapshot — also pushed via `onValidityChange`. */\n validity: CardFieldValidity;\n /** Latest detected brand (or null if unknown). */\n brand: string | null;\n /**\n * Live focus state for each iframe. True while the user is editing that\n * field. Consumers use this to apply an \"active\" border on the iframe shell\n * (the browser's `:focus-within` CSS doesn't propagate across iframes).\n */\n focused: CardFieldFocus;\n /**\n * Programmatically move keyboard focus into one of the Spreedly iframes.\n * No-op when the hook is not in the `'ready'` state. Used to auto-advance\n * focus from an outer form input (e.g. expiry) into a hosted field (CVV).\n */\n focusField: (field: 'number' | 'cvv') => void;\n}\n\nconst DEFAULT_NUMBER_EL = 'movmo-card-number';\nconst DEFAULT_CVV_EL = 'movmo-card-cvv';\n\nconst toSdkPayload = (data: CardholderTokenizeData): SpreedlyTokenizeData => ({\n first_name: data.firstName,\n last_name: data.lastName,\n month: data.month,\n year: data.year,\n ...(data.email ? { email: data.email } : {}),\n ...(data.zip ? { zip: data.zip } : {}),\n});\n\n/**\n * Mounts PCI-safe card-capture fields into the DOM containers identified by\n * `numberEl` and `cvvEl`, fetches a signed tokenization session from\n * monolith-api, and exposes a `tokenize()` function that returns an opaque\n * vault token via the `onCardTokenized` callback.\n *\n * The vault implementation (Spreedly Hosted Fields) is intentionally not part\n * of the public surface — callers receive a vault-neutral token they hand back\n * to monolith-api, which derives card metadata server-side.\n */\nexport const useMovmoCardFields = (\n options: UseMovmoCardFieldsOptions = {},\n): UseMovmoCardFieldsResult => {\n const {\n numberEl = DEFAULT_NUMBER_EL,\n cvvEl = DEFAULT_CVV_EL,\n onCardTokenized,\n onFieldErrors,\n onValidityChange,\n onBrandChange,\n } = options;\n\n const [status, setStatus] = useState<UseMovmoCardFieldsResult['status']>('idle');\n const [error, setError] = useState<string | null>(null);\n const [validity, setValidity] = useState<CardFieldValidity>({ number: false, cvv: false });\n const [brand, setBrand] = useState<string | null>(null);\n const [focused, setFocused] = useState<CardFieldFocus>({ number: false, cvv: false });\n const spreedlyRef = useRef<SpreedlyGlobal | null>(null);\n\n const onCardTokenizedRef = useRef(onCardTokenized);\n const onFieldErrorsRef = useRef(onFieldErrors);\n const onValidityChangeRef = useRef(onValidityChange);\n const onBrandChangeRef = useRef(onBrandChange);\n useEffect(() => {\n onCardTokenizedRef.current = onCardTokenized;\n }, [onCardTokenized]);\n useEffect(() => {\n onFieldErrorsRef.current = onFieldErrors;\n }, [onFieldErrors]);\n useEffect(() => {\n onValidityChangeRef.current = onValidityChange;\n }, [onValidityChange]);\n useEffect(() => {\n onBrandChangeRef.current = onBrandChange;\n }, [onBrandChange]);\n\n // Latest validity is kept in a ref so the fieldEvent handler can read the\n // previous value without re-binding the listener on every state change.\n const validityRef = useRef<CardFieldValidity>({ number: false, cvv: false });\n\n useEffect(() => {\n let cancelled = false;\n setStatus('loading');\n setError(null);\n setValidity({ number: false, cvv: false });\n setBrand(null);\n validityRef.current = { number: false, cvv: false };\n\n (async () => {\n try {\n const [session, spreedly] = await Promise.all([\n fetchTokenizationSession(),\n loadSpreedlyScript(),\n ]);\n if (cancelled) return;\n\n // Assign the ref before registering handlers so the cleanup can always\n // call removeHandlers — even if unmount runs before the 'ready' event\n // fires. window.Spreedly is a module-scoped singleton, so leaked\n // handlers would otherwise fire on the next mount.\n spreedlyRef.current = spreedly;\n\n spreedly.on('ready', () => {\n if (cancelled) return;\n setStatus('ready');\n // Tell Spreedly the field expects digits — improves mobile\n // keyboard + lets the SDK apply numeric-friendly formatting.\n try {\n spreedly.setFieldType?.('number', 'tel');\n spreedly.setFieldType?.('cvv', 'tel');\n } catch {\n /* no-op */\n }\n // Pretty-format the card number into 4-digit groups as the user types.\n // Surface a console.warn when the Spreedly build doesn't expose the\n // method (silent no-op was hiding the cause of a \"no spaces in the\n // typed digits\" bug).\n try {\n if (typeof spreedly.setNumberFormat === 'function') {\n spreedly.setNumberFormat('prettyFormat');\n } else {\n console.warn(\n '@movmo_app/payments: Spreedly.setNumberFormat is missing — card-number digits will not be space-grouped.',\n );\n }\n } catch (err) {\n console.warn('@movmo_app/payments: setNumberFormat failed', err);\n }\n // Spreedly's hosted-fields iframes render *empty* by default — no\n // placeholder, no inherited styling. Without the calls below the\n // user sees a blank box and can't tell where to click. Mirror the\n // outer form's text-sm/grayWarm-900 styling exactly so the iframe\n // input visually matches the expiry, ZIP, and cardholder inputs.\n // `line-height: 20px` (Tailwind text-sm's line-height) +\n // `vertical-align: middle` keep the typed digits vertically\n // centered in the 28-px iframe content area (44px shell − py-2).\n try {\n spreedly.setPlaceholder?.('number', 'Card number');\n spreedly.setPlaceholder?.('cvv', 'CVV');\n const iframeFontStyle =\n 'box-sizing: border-box;' +\n 'width: 100%;' +\n 'height: 100%;' +\n 'margin: 0;' +\n 'padding: 0;' +\n 'border: 0;' +\n 'background: transparent;' +\n 'outline: none;' +\n 'font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif;' +\n 'font-size: 14px;' +\n 'font-weight: 400;' +\n 'line-height: 20px;' +\n 'color: rgb(28 25 23);' +\n 'letter-spacing: 0;' +\n 'vertical-align: middle;';\n spreedly.setStyle?.('number', iframeFontStyle);\n spreedly.setStyle?.('cvv', iframeFontStyle);\n } catch {\n /* no-op — older Spreedly builds may omit these helpers */\n }\n });\n\n spreedly.on('paymentMethod', (token) => {\n onCardTokenizedRef.current?.(token);\n });\n\n spreedly.on('errors', (errors) => {\n onFieldErrorsRef.current?.(errors);\n });\n\n // Spreedly's hosted-fields v1: fieldEvent fires with FOUR positional\n // args (name, type, activeEl, inputProperties). The `inputProperties`\n // object is only populated on `type === 'input'` — focus/blur/etc.\n // pass `{}`. Brand + validity all live on inputProperties.\n // See https://developer.spreedly.com/docs/iframe-events\n spreedly.on('fieldEvent', (name, type, _activeEl, inputProperties) => {\n if (cancelled) return;\n // Mirror iframe focus into React state so consumers can render an\n // active-border equivalent — `:focus-within` CSS doesn't cross\n // iframe boundaries.\n if (type === 'focus') {\n setFocused((prev) => (prev[name] ? prev : { ...prev, [name]: true }));\n return;\n }\n if (type === 'blur') {\n setFocused((prev) => (prev[name] ? { ...prev, [name]: false } : prev));\n return;\n }\n if (type !== 'input') return;\n const props = inputProperties ?? {};\n\n if (name === 'number') {\n // Spreedly only includes cardType once the BIN is unambiguous.\n // Treat absence as \"unknown\" but only after the user starts typing.\n if (props.numberLength === 0) {\n setBrand((prev) => {\n if (prev !== null) onBrandChangeRef.current?.(null);\n return null;\n });\n } else if (props.cardType !== undefined) {\n const next = props.cardType || null;\n setBrand((prev) => {\n if (prev !== next) onBrandChangeRef.current?.(next);\n return next;\n });\n }\n }\n\n const newValid =\n name === 'number'\n ? typeof props.validNumber === 'boolean'\n ? props.validNumber\n : undefined\n : typeof props.validCvv === 'boolean'\n ? props.validCvv\n : undefined;\n if (typeof newValid === 'boolean') {\n const prev = validityRef.current;\n const next: CardFieldValidity =\n name === 'number' ? { ...prev, number: newValid } : { ...prev, cvv: newValid };\n if (next.number !== prev.number || next.cvv !== prev.cvv) {\n validityRef.current = next;\n setValidity(next);\n onValidityChangeRef.current?.(next);\n }\n }\n });\n\n spreedly.on('consoleError', (err) => {\n // Without this, vault-internal failures during tokenizeCreditCard\n // leave consumers stuck in their 'tokenizing' state forever.\n const message =\n err instanceof Error\n ? err.message\n : 'An unexpected error occurred while securing your card.';\n onFieldErrorsRef.current?.([{ message }]);\n });\n\n spreedly.init(session.environmentKey, {\n numberEl,\n cvvEl,\n nonce: session.nonce,\n timestamp: String(session.timestamp),\n certificateToken: session.certificateToken,\n signature: session.signature,\n });\n } catch (err) {\n if (cancelled) return;\n const message = err instanceof Error ? err.message : 'Failed to initialize card form.';\n setError(message);\n setStatus('error');\n }\n })();\n\n return () => {\n cancelled = true;\n try {\n spreedlyRef.current?.removeHandlers?.();\n } catch {\n // best-effort cleanup\n }\n spreedlyRef.current = null;\n };\n }, [numberEl, cvvEl]);\n\n const tokenize = useCallback((data: CardholderTokenizeData) => {\n spreedlyRef.current?.tokenizeCreditCard(toSdkPayload(data));\n }, []);\n\n const focusField = useCallback((field: 'number' | 'cvv') => {\n spreedlyRef.current?.transferFocus?.(field);\n }, []);\n\n return { status, error, tokenize, validity, brand, focused, focusField };\n};\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport clsx from 'clsx';\n\nimport { savePaymentMethodFromToken } from '../api';\nimport { CardBrandIcon } from '../PaymentMethodsManager/cardBrandIcon';\nimport { useMovmoCardFields } from '../useMovmoCardFields';\nimport type { CardFieldError, CardFormStatus, PaymentMethodSummary } from '../types';\n\nexport interface MovmoCardFormProps {\n userId: string;\n onSuccess: (paymentMethod: PaymentMethodSummary) => void;\n onError: (error: string) => void;\n isDefault?: boolean;\n className?: string;\n /**\n * Pre-fills the cardholder name input. Cardholders aren't always the\n * logged-in user (spouse card, corporate card), so the field remains\n * editable — pass `user.fullName` as a sensible default.\n */\n defaultCardholderName?: string;\n /**\n * @deprecated Prefer `defaultCardholderName`. Concatenated with\n * `defaultCardholderLastName` to seed the single cardholder name field.\n */\n defaultCardholderFirstName?: string;\n /** @deprecated See `defaultCardholderFirstName`. */\n defaultCardholderLastName?: string;\n /**\n * When true, the form submits automatically the moment all fields are valid —\n * no Save button is rendered. Matches the flights-ui \"first card\" auto-save UX.\n * Defaults to `false`.\n */\n autoSave?: boolean;\n /**\n * HTML `id` for the underlying `<form>` element. Lets a parent (e.g. modal\n * footer) wire its own submit button via `<button type=\"submit\" form=\"...\">`\n * — useful when `hideInternalSaveButton` is true. Defaults to `movmo-card-form`.\n */\n formId?: string;\n /**\n * When true, the form omits its internal Save button. Use together with\n * `formId` to drive submit from a parent (e.g. a modal footer's Save button).\n */\n hideInternalSaveButton?: boolean;\n /**\n * Fires whenever the \"ready to submit\" state changes (all fields valid +\n * not in flight). Use to enable / disable an external Save button.\n */\n onCanSubmitChange?: (canSubmit: boolean) => void;\n /**\n * Fires whenever the form transitions in / out of the \"saving\" state\n * (tokenize call or save POST in flight). A parent rendering its own\n * Save button (e.g. a modal footer) uses this to swap the button label\n * for a spinner. The hook's loading state is internal and not surfaced\n * directly — this callback is the single source of truth.\n */\n onSavingChange?: (isSaving: boolean) => void;\n /**\n * When set, the named Spreedly hosted-fields iframe receives keyboard\n * focus the moment the field becomes ready. Use `\"number\"` for the\n * accounts-ui add-card modal so the user can start typing immediately.\n */\n autoFocus?: 'number' | 'cvv';\n}\n\n// Active border matches flights-ui: 1px gray-300 → thick grayWarm-950 ring on focus.\nconst fieldShellClass =\n '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]';\n\n// Base styling for the iframe shells. `:focus-within` can't observe focus\n// inside a cross-origin iframe, so the active-border classes are applied\n// conditionally based on the `focused` state from useMovmoCardFields.\nconst iframeShellClass =\n 'flex h-11 w-full items-center gap-2 rounded-md border bg-white px-3 py-2 transition-shadow';\nconst iframeShellActiveClass = 'border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]';\nconst iframeShellIdleClass = 'border-grayWarm-300';\n\nconst splitName = (full: string): { firstName: string; lastName: string } => {\n const trimmed = full.trim();\n if (!trimmed) return { firstName: '', lastName: '' };\n const lastSpace = trimmed.lastIndexOf(' ');\n if (lastSpace === -1) return { firstName: trimmed, lastName: '' };\n return {\n firstName: trimmed.slice(0, lastSpace).trim(),\n lastName: trimmed.slice(lastSpace + 1).trim(),\n };\n};\n\n/** Parses \"MM/YY\", \"MM / YY\", or \"MM/YYYY\" → { month, year } in Spreedly's expected shape. */\nconst parseExpiry = (raw: string): { month: string; year: string } => {\n const digits = raw.replace(/\\D/g, '');\n if (digits.length < 4) return { month: '', year: '' };\n const month = digits.slice(0, 2);\n const yearRaw = digits.slice(2);\n const year = yearRaw.length === 2 ? `20${yearRaw}` : yearRaw.slice(0, 4);\n return { month, year };\n};\n\nconst formatExpiryInput = (raw: string): string => {\n const digits = raw.replace(/\\D/g, '').slice(0, 4);\n if (digits.length <= 2) return digits;\n return `${digits.slice(0, 2)} / ${digits.slice(2)}`;\n};\n\nconst isExpiryValid = (raw: string): boolean => {\n const { month, year } = parseExpiry(raw);\n if (!month || !year) return false;\n const mm = parseInt(month, 10);\n const yyyy = parseInt(year, 10);\n if (isNaN(mm) || mm < 1 || mm > 12) return false;\n const now = new Date();\n if (yyyy < now.getFullYear() || yyyy > now.getFullYear() + 20) return false;\n if (yyyy === now.getFullYear() && mm < now.getMonth() + 1) return false;\n return true;\n};\n\n/** US ZIP — 5 digits, optionally followed by -4 (ZIP+4). */\nconst isZipValid = (raw: string): boolean => /^\\d{5}(-\\d{4})?$/.test(raw.trim());\n\nconst formatZipInput = (raw: string): string => {\n // Strip everything except digits + a single hyphen between groups.\n const digits = raw.replace(/[^\\d]/g, '').slice(0, 9);\n if (digits.length <= 5) return digits;\n return `${digits.slice(0, 5)}-${digits.slice(5)}`;\n};\n\nexport const MovmoCardForm = ({\n userId,\n onSuccess,\n onError,\n isDefault = false,\n className,\n defaultCardholderName,\n defaultCardholderFirstName = '',\n defaultCardholderLastName = '',\n autoSave = false,\n formId = 'movmo-card-form',\n hideInternalSaveButton = false,\n onCanSubmitChange,\n onSavingChange,\n autoFocus,\n}: MovmoCardFormProps) => {\n const seededName =\n defaultCardholderName ??\n [defaultCardholderFirstName, defaultCardholderLastName].filter(Boolean).join(' ');\n\n const [cardholderName, setCardholderName] = useState(seededName);\n const [expiry, setExpiry] = useState('');\n const [zip, setZip] = useState('');\n const [formStatus, setFormStatus] = useState<CardFormStatus>('idle');\n const autoSubmittedRef = useRef(false);\n\n const handleCardTokenized = useCallback(\n async (token: string) => {\n setFormStatus('saving');\n try {\n const summary = await savePaymentMethodFromToken(userId, token, isDefault);\n setFormStatus('ready');\n onSuccess(summary);\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Failed to save payment method.';\n setFormStatus('ready');\n autoSubmittedRef.current = false;\n onError(message);\n }\n },\n [userId, isDefault, onSuccess, onError],\n );\n\n const handleFieldErrors = useCallback(\n (errors: CardFieldError[]) => {\n const message =\n errors\n .map((e) => e.message)\n .filter(Boolean)\n .join('; ') || 'Card validation failed.';\n setFormStatus((prev) => (prev === 'tokenizing' ? 'ready' : prev));\n autoSubmittedRef.current = false;\n onError(message);\n },\n [onError],\n );\n\n const hookOptions = useMemo(\n () => ({\n onCardTokenized: handleCardTokenized,\n onFieldErrors: handleFieldErrors,\n }),\n [handleCardTokenized, handleFieldErrors],\n );\n\n const {\n status: hookStatus,\n error: hookError,\n tokenize,\n validity,\n brand,\n focused,\n focusField,\n } = useMovmoCardFields(hookOptions);\n\n // Move keyboard focus into the requested iframe the moment the hook is\n // ready. `autoFocus=\"number\"` from the parent (e.g. modal opens → form\n // mounts) means the user can start typing the card number immediately\n // instead of clicking the field first.\n const autoFocusedRef = useRef(false);\n useEffect(() => {\n if (!autoFocus || hookStatus !== 'ready' || autoFocusedRef.current) return;\n autoFocusedRef.current = true;\n focusField(autoFocus);\n }, [autoFocus, hookStatus, focusField]);\n\n const nameValid = cardholderName.trim().split(/\\s+/).length >= 2;\n const expiryValid = isExpiryValid(expiry);\n const zipValid = isZipValid(zip);\n const autoFocusedCvvRef = useRef(false);\n const autoFocusedZipRef = useRef(false);\n const autoFocusedNameRef = useRef(false);\n const zipInputRef = useRef<HTMLInputElement | null>(null);\n const cardholderNameInputRef = useRef<HTMLInputElement | null>(null);\n\n // Auto-advance from CVV iframe into the zip input the first time CVV\n // becomes valid. Mirrors the expiry → CVV jump. Ref resets when CVV\n // becomes invalid so editing back-and-forth still works.\n useEffect(() => {\n if (validity.cvv) {\n if (!autoFocusedZipRef.current) {\n autoFocusedZipRef.current = true;\n zipInputRef.current?.focus();\n }\n } else {\n autoFocusedZipRef.current = false;\n }\n }, [validity.cvv]);\n const formInvalid = !nameValid || !expiryValid || !zipValid || !validity.number || !validity.cvv;\n\n const isBusy = formStatus === 'tokenizing' || formStatus === 'saving';\n const canSubmit = hookStatus === 'ready' && !isBusy && !formInvalid;\n\n // Push canSubmit transitions to a parent (e.g. a modal footer's Save button).\n const onCanSubmitChangeRef = useRef(onCanSubmitChange);\n useEffect(() => {\n onCanSubmitChangeRef.current = onCanSubmitChange;\n }, [onCanSubmitChange]);\n useEffect(() => {\n onCanSubmitChangeRef.current?.(canSubmit);\n }, [canSubmit]);\n\n // Push the \"saving\" transition to a parent so a modal-footer Save button can\n // swap its label for a spinner. The ref pattern matches onCanSubmitChange.\n const onSavingChangeRef = useRef(onSavingChange);\n useEffect(() => {\n onSavingChangeRef.current = onSavingChange;\n }, [onSavingChange]);\n useEffect(() => {\n onSavingChangeRef.current?.(isBusy);\n }, [isBusy]);\n\n const submit = useCallback(() => {\n const { firstName, lastName } = splitName(cardholderName);\n const { month, year } = parseExpiry(expiry);\n setFormStatus('tokenizing');\n tokenize({ firstName, lastName, month, year, zip: zip.trim() });\n }, [cardholderName, expiry, zip, tokenize]);\n\n // Auto-save: debounced so the form doesn't submit mid-keystroke. The\n // form's name-validity rule is loose on purpose (any \"First Last\" passes),\n // so without a debounce the submit fires the moment the user types their\n // last-name's first letter — disabling the input and freezing the rest of\n // their typing. 1200ms is long enough that natural cadence won't trip it,\n // short enough that a paused-and-done user sees the save promptly.\n useEffect(() => {\n if (!autoSave) return;\n if (!canSubmit) return;\n if (autoSubmittedRef.current) return;\n const timer = setTimeout(() => {\n autoSubmittedRef.current = true;\n submit();\n }, 1200);\n return () => clearTimeout(timer);\n }, [autoSave, canSubmit, submit]);\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault();\n if (!canSubmit) return;\n submit();\n };\n\n const inputsDisabled = hookStatus !== 'ready' || isBusy;\n\n // Propagate Spreedly-init failures (e.g. \"Failed to fetch tokenization\n // session\") to the parent so the manager-level banner renders them too.\n // Without this, hookErrors would be lost when the inline error <p> is\n // removed below.\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n useEffect(() => {\n if (hookError) onErrorRef.current?.(hookError);\n }, [hookError]);\n\n return (\n <form\n id={formId}\n onSubmit={handleSubmit}\n className={clsx('flex w-full flex-col gap-3', className)}\n data-testid=\"movmo-card-form\"\n >\n {/* Card number — Spreedly iframe inside a shell with brand icon inline */}\n <div>\n <span id=\"movmo-card-number-label\" className=\"sr-only\">\n Card number\n </span>\n <div\n className={clsx(\n iframeShellClass,\n focused.number ? iframeShellActiveClass : iframeShellIdleClass,\n )}\n >\n <CardBrandIcon brand={brand ?? ''} width={32} className=\"flex-shrink-0\" />\n {/*\n * Skeleton bar lives as a SIBLING (not child) of the Spreedly mount\n * div. Spreedly injects an `<iframe>` into the mount on `init` and\n * removes it on `removeHandlers`; if React owns children inside the\n * mount during that window, React's reconciler races with Spreedly\n * over `removeChild` and throws `NotFoundError: The node to be\n * removed is not a child of this node`. Keeping the mount div\n * empty of React children avoids that fight.\n */}\n <div className=\"relative h-full flex-1\">\n <div\n id=\"movmo-card-number\"\n aria-labelledby=\"movmo-card-number-label\"\n aria-busy={hookStatus !== 'ready'}\n className=\"absolute inset-0\"\n data-testid=\"movmo-card-number-mount\"\n />\n {hookStatus !== 'ready' ? (\n <div\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute inset-y-2 left-0 right-2 animate-pulse rounded bg-grayWarm-200\"\n />\n ) : null}\n </div>\n </div>\n </div>\n\n {/* Expiry + CVV + ZIP row */}\n <div className=\"grid grid-cols-3 gap-3\">\n <div>\n <label htmlFor=\"movmo-card-expiry\" className=\"sr-only\">\n Expiry MM / YY\n </label>\n <input\n id=\"movmo-card-expiry\"\n type=\"text\"\n inputMode=\"numeric\"\n autoComplete=\"cc-exp\"\n placeholder=\"MM / YY\"\n value={expiry}\n onChange={(e) => {\n const next = formatExpiryInput(e.target.value);\n setExpiry(next);\n // Auto-advance to CVV the first time expiry becomes valid. The\n // ref lets the user edit-back-and-forth without re-stealing focus.\n if (isExpiryValid(next) && !autoFocusedCvvRef.current) {\n autoFocusedCvvRef.current = true;\n focusField('cvv');\n } else if (!isExpiryValid(next)) {\n autoFocusedCvvRef.current = false;\n }\n }}\n className={clsx(fieldShellClass, expiry && !expiryValid && 'border-error-500')}\n disabled={inputsDisabled}\n required\n data-testid=\"movmo-card-expiry-input\"\n />\n </div>\n <div className=\"relative\">\n <span id=\"movmo-card-cvv-label\" className=\"sr-only\">\n CVV\n </span>\n <div\n className={clsx(\n iframeShellClass,\n focused.cvv ? iframeShellActiveClass : iframeShellIdleClass,\n )}\n >\n {/* Skeleton sibling pattern — see card-number comment above. */}\n <div className=\"relative h-full flex-1\">\n <div\n id=\"movmo-card-cvv\"\n aria-labelledby=\"movmo-card-cvv-label\"\n aria-busy={hookStatus !== 'ready'}\n className=\"absolute inset-0\"\n data-testid=\"movmo-card-cvv-mount\"\n />\n {hookStatus !== 'ready' ? (\n <div\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute inset-y-2 left-0 right-2 animate-pulse rounded bg-grayWarm-200\"\n />\n ) : null}\n </div>\n <button\n type=\"button\"\n aria-label=\"CVV help\"\n tabIndex={-1}\n className=\"flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full border border-grayWarm-300 text-xs text-grayWarm-500\"\n title={\n brand === 'american_express'\n ? 'The 4 numbers on the front of your card.'\n : 'The 3 numbers on the back of your card.'\n }\n data-testid=\"movmo-cvv-help\"\n >\n ?\n </button>\n </div>\n </div>\n <div>\n {/*\n Spreedly doesn't require zip at tokenization, but US issuers'\n AVS will decline most card-not-present charges without it (and\n including AVS lowers interchange + chargeback risk), so collect\n it up front.\n */}\n <label htmlFor=\"movmo-card-zip\" className=\"sr-only\">\n ZIP code\n </label>\n <input\n id=\"movmo-card-zip\"\n ref={zipInputRef}\n type=\"text\"\n inputMode=\"numeric\"\n autoComplete=\"postal-code\"\n placeholder=\"ZIP code\"\n value={zip}\n onChange={(e) => {\n const next = formatZipInput(e.target.value);\n setZip(next);\n if (isZipValid(next) && !autoFocusedNameRef.current) {\n autoFocusedNameRef.current = true;\n cardholderNameInputRef.current?.focus();\n } else if (!isZipValid(next)) {\n autoFocusedNameRef.current = false;\n }\n }}\n className={clsx(fieldShellClass, zip && !zipValid && 'border-error-500')}\n disabled={inputsDisabled}\n required\n data-testid=\"movmo-card-zip-input\"\n />\n </div>\n </div>\n\n {/* Cardholder name — single field, Figma-aligned */}\n <div>\n <label htmlFor=\"movmo-card-cardholder-name\" className=\"sr-only\">\n Cardholder name\n </label>\n <input\n id=\"movmo-card-cardholder-name\"\n ref={cardholderNameInputRef}\n type=\"text\"\n autoComplete=\"cc-name\"\n placeholder=\"Cardholder name\"\n value={cardholderName}\n onChange={(e) => setCardholderName(e.target.value)}\n className={fieldShellClass}\n disabled={inputsDisabled}\n required\n data-testid=\"movmo-card-cardholder-name-input\"\n />\n </div>\n\n {/*\n * No inline error banner here — errors are propagated to the parent\n * via `onError` (API failures) and the hookError useEffect above\n * (Spreedly init failures). The parent's PaymentMethodsManager owns\n * the single error banner with role=\"alert\" + aria-live, avoiding\n * the duplicate-error UX (per ux-design-advisor: WCAG 4.1.3 — two\n * role=\"alert\" nodes on the same string announces twice).\n */}\n\n {!autoSave && !hideInternalSaveButton ? (\n <button\n type=\"submit\"\n disabled={!canSubmit}\n className={clsx(\n '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',\n 'disabled:cursor-not-allowed disabled:bg-grayWarm-300 disabled:text-grayWarm-500',\n )}\n data-testid=\"movmo-card-save\"\n >\n {isBusy ? 'Saving…' : hookStatus === 'loading' ? 'Loading…' : 'Save card'}\n </button>\n ) : isBusy && autoSave ? (\n // In autoSave mode (empty-state inline form, no Save button at all),\n // surface the in-flight state as inline text. The modal flow uses a\n // spinner inside the modal-footer Save button instead — see\n // AddPaymentMethodModal.isSaving.\n <p\n className=\"text-center text-sm text-grayWarm-500\"\n aria-live=\"polite\"\n data-testid=\"movmo-card-autosaving\"\n >\n Saving card…\n </p>\n ) : null}\n </form>\n );\n};\n\nMovmoCardForm.displayName = 'MovmoCardForm';\n\nexport default MovmoCardForm;\n","import { useCallback, useState } from 'react';\n\nimport { deletePaymentMethod as deletePaymentMethodApi } from './api';\n\nexport type UseDeletePaymentMethodStatus = 'idle' | 'pending' | 'error';\n\nexport interface UseDeletePaymentMethodResult {\n deletePaymentMethod: (methodId: string) => Promise<void>;\n status: UseDeletePaymentMethodStatus;\n error: string | null;\n}\n\n/**\n * Calls `DELETE /v1/users/:userId/payment-methods/:methodId`.\n *\n * The hook owns the network call + status; consumers own list state so they\n * can apply optimistic updates / rollback at their layer. The returned promise\n * resolves on success and rejects on failure so callers can roll back.\n */\nexport const useDeletePaymentMethod = (userId: string): UseDeletePaymentMethodResult => {\n const [status, setStatus] = useState<UseDeletePaymentMethodStatus>('idle');\n const [error, setError] = useState<string | null>(null);\n\n const deletePaymentMethod = useCallback(\n async (methodId: string): Promise<void> => {\n setStatus('pending');\n setError(null);\n try {\n await deletePaymentMethodApi(userId, methodId);\n setStatus('idle');\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Failed to delete payment method.';\n setError(message);\n setStatus('error');\n throw err;\n }\n },\n [userId],\n );\n\n return { deletePaymentMethod, status, error };\n};\n","import { useCallback, useState } from 'react';\n\nimport { updatePaymentMethod } from './api';\n\nexport type UseSetDefaultPaymentMethodStatus = 'idle' | 'pending' | 'error';\n\nexport interface UseSetDefaultPaymentMethodResult {\n setDefault: (methodId: string) => Promise<void>;\n status: UseSetDefaultPaymentMethodStatus;\n error: string | null;\n}\n\n/**\n * Calls `PUT /v1/users/:userId/payment-methods/:methodId` with\n * `{ isDefault: true }`. Server clears the previous default automatically.\n *\n * The hook owns the network call + status; consumers own list state so they\n * can apply optimistic updates / rollback at their layer. The returned promise\n * resolves on success and rejects on failure so callers can roll back.\n */\nexport const useSetDefaultPaymentMethod = (userId: string): UseSetDefaultPaymentMethodResult => {\n const [status, setStatus] = useState<UseSetDefaultPaymentMethodStatus>('idle');\n const [error, setError] = useState<string | null>(null);\n\n const setDefault = useCallback(\n async (methodId: string): Promise<void> => {\n setStatus('pending');\n setError(null);\n try {\n await updatePaymentMethod(userId, methodId, { isDefault: true });\n setStatus('idle');\n } catch (err) {\n const message =\n err instanceof Error ? err.message : 'Failed to set default payment method.';\n setError(message);\n setStatus('error');\n throw err;\n }\n },\n [userId],\n );\n\n return { setDefault, status, error };\n};\n","import { useCallback, useEffect, useRef, useState } from 'react';\n\nimport { listPaymentMethods } from './api';\nimport type { PaymentMethodSummary } from './types';\n\nexport type UseUserPaymentMethodsStatus = 'idle' | 'loading' | 'ready' | 'error';\n\nexport interface UseUserPaymentMethodsResult {\n items: PaymentMethodSummary[];\n status: UseUserPaymentMethodsStatus;\n error: string | null;\n /** Re-issues the GET request. Cancels any in-flight request first. */\n refetch: () => void;\n}\n\n/**\n * Fetches a user's saved payment methods from monolith-api.\n *\n * Auto-runs on mount and whenever `userId` changes. Cancels the in-flight\n * request on unmount or refetch so consumers don't see stale results land\n * after a navigation. Status mirrors `useMovmoCardFields`:\n * `idle` → `loading` → `ready | error`.\n */\nexport const useUserPaymentMethods = (userId: string): UseUserPaymentMethodsResult => {\n const [items, setItems] = useState<PaymentMethodSummary[]>([]);\n const [status, setStatus] = useState<UseUserPaymentMethodsStatus>('idle');\n const [error, setError] = useState<string | null>(null);\n const [tick, setTick] = useState(0);\n const abortRef = useRef<AbortController | null>(null);\n\n useEffect(() => {\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n setStatus('loading');\n setError(null);\n\n listPaymentMethods(userId)\n .then((result) => {\n if (controller.signal.aborted) return;\n setItems(result);\n setStatus('ready');\n })\n .catch((err: unknown) => {\n if (controller.signal.aborted) return;\n const message = err instanceof Error ? err.message : 'Failed to fetch payment methods.';\n setError(message);\n setStatus('error');\n });\n\n return () => {\n controller.abort();\n };\n }, [userId, tick]);\n\n const refetch = useCallback(() => {\n setTick((n) => n + 1);\n }, []);\n\n return { items, status, error, refetch };\n};\n","import { useEffect, type ReactNode } from 'react';\nimport clsx from 'clsx';\n\ninterface AddPaymentMethodModalProps {\n open: boolean;\n onClose: () => void;\n /**\n * HTML form id rendered inside the modal. The modal's Save button uses\n * `<button type=\"submit\" form={formId}>` so the consumer doesn't need to\n * thread a submit ref.\n */\n formId: string;\n /** Save button disabled state — track the form's `canSubmit`. */\n saveDisabled: boolean;\n /** Save button label override (default: \"Save\"). */\n saveLabel?: string;\n /**\n * When true, replace the Save button's label with a centered spinner,\n * mark the button `aria-busy`, and prevent further clicks. Matches the\n * flights-ui house style for primary-action buttons during an in-flight\n * mutation (see ux-design-advisor's call).\n */\n isSaving?: boolean;\n children: ReactNode;\n}\n\n/**\n * Vault-neutral modal wrapper for the add-payment flow. Matches the chrome\n * in Figma node 2871-52148: X close in the top-left, \"Add payment method\"\n * title, body slot, Cancel + Save footer. The Save button is wired via the\n * HTML form attribute so the parent doesn't need a submit ref.\n *\n * No external modal library — the consumer's own modal infrastructure can\n * later replace this if needed, but the package stays dep-free.\n */\nexport const AddPaymentMethodModal = ({\n open,\n onClose,\n formId,\n saveDisabled,\n saveLabel = 'Save',\n isSaving = false,\n children,\n}: AddPaymentMethodModalProps) => {\n // Close on Escape key (consistent with native <dialog>).\n useEffect(() => {\n if (!open) return;\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') onClose();\n };\n document.addEventListener('keydown', onKey);\n return () => document.removeEventListener('keydown', onKey);\n }, [open, onClose]);\n\n // Lock body scroll while open so the page doesn't shift behind the overlay.\n useEffect(() => {\n if (!open) return;\n const prev = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n return () => {\n document.body.style.overflow = prev;\n };\n }, [open]);\n\n if (!open) return null;\n\n return (\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby=\"movmo-add-payment-title\"\n className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4\"\n onClick={(e) => {\n // Backdrop click closes — don't close when clicking inside the panel.\n if (e.target === e.currentTarget) onClose();\n }}\n data-testid=\"add-payment-method-modal\"\n >\n <div className=\"flex max-h-full w-full max-w-md flex-col rounded-xl bg-white shadow-2xl\">\n <div className=\"flex items-center gap-3 border-b border-grayWarm-200 px-4 py-3\">\n <button\n type=\"button\"\n onClick={onClose}\n aria-label=\"Close add-payment dialog\"\n // Matches Figma node 2871-51397: 36×36 filled grayWarm-100\n // button, rounded-lg, no border, 20×20 dark X glyph.\n 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\"\n data-testid=\"add-payment-method-close\"\n >\n <svg viewBox=\"0 0 20 20\" width=\"20\" height=\"20\" aria-hidden=\"true\">\n <path\n d=\"M5 5L15 15M15 5L5 15\"\n stroke=\"currentColor\"\n strokeWidth=\"1.67\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n </button>\n <h2\n id=\"movmo-add-payment-title\"\n className=\"flex-1 text-center text-base font-semibold text-grayWarm-900\"\n >\n Add payment method\n </h2>\n {/* Spacer balances the close button so the title stays centered. */}\n <span aria-hidden=\"true\" className=\"h-9 w-9 flex-shrink-0\" />\n </div>\n\n <div className=\"flex-1 overflow-y-auto p-4\">{children}</div>\n\n <div className=\"flex gap-3 border-t border-grayWarm-200 p-4\">\n <button\n type=\"button\"\n onClick={onClose}\n 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]\"\n data-testid=\"add-payment-method-cancel\"\n >\n Cancel\n </button>\n <button\n type=\"submit\"\n form={formId}\n // While saving, the button stays brand-500 (active state — the\n // disabled gray would read as \"rejected\"), but `aria-disabled`\n // + pointer-events-none prevent re-submit. Don't set the\n // disabled attribute when saving: it would trigger the\n // disabled:bg-grayWarm-300 class.\n disabled={isSaving ? false : saveDisabled}\n aria-disabled={isSaving || saveDisabled}\n aria-busy={isSaving}\n className={clsx(\n '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',\n isSaving\n ? 'cursor-not-allowed opacity-90 pointer-events-none'\n : 'hover:bg-brand-600 disabled:cursor-not-allowed disabled:bg-grayWarm-300 disabled:text-grayWarm-500',\n )}\n data-testid=\"add-payment-method-save\"\n >\n {isSaving ? (\n <>\n {/*\n * Inline SVG ring + Tailwind animate-spin. Avoids adding\n * react-spinners as a runtime dep on this package. Matches\n * the visual weight of flights-ui's ClipLoader at size=18.\n */}\n <svg\n className=\"h-[18px] w-[18px] animate-spin\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n aria-hidden=\"true\"\n >\n <circle\n cx=\"12\"\n cy=\"12\"\n r=\"10\"\n stroke=\"currentColor\"\n strokeWidth=\"3\"\n strokeOpacity=\"0.25\"\n />\n <path\n d=\"M22 12a10 10 0 0 1-10 10\"\n stroke=\"currentColor\"\n strokeWidth=\"3\"\n strokeLinecap=\"round\"\n />\n </svg>\n <span className=\"sr-only\">Saving card</span>\n </>\n ) : (\n saveLabel\n )}\n </button>\n </div>\n </div>\n </div>\n );\n};\n","import clsx from 'clsx';\n\nimport type { PaymentMethodSummary } from '../types';\nimport { CardBrandIcon } from './cardBrandIcon';\n\nconst prettyBrand = (brand: string | null | undefined): string => {\n if (!brand) return 'Card';\n const key = brand.toLowerCase();\n if (key === 'amex') return 'Amex';\n return key.charAt(0).toUpperCase() + key.slice(1);\n};\n\nexport interface PaymentMethodPreviewProps {\n /**\n * The card to render. Consumers typically derive this from\n * `useUserPaymentMethods(userId)` — e.g. the selected card in a checkout\n * drawer, or the default card on a summary line.\n */\n method: PaymentMethodSummary;\n /** Trailing slot — flights-ui drops an expand-chevron button here. */\n trailing?: React.ReactNode;\n /** Whole-row click handler — typically toggles the drawer open. */\n onClick?: () => void;\n /**\n * Controls how the card label is rendered.\n * - `'branded'` (default): \"Visa 4242\" — brand name + last4\n * - `'masked'`: \"•••• 4242\" — masked bullets + last4 (flights-ui collapsed-drawer style)\n */\n cardLabelFormat?: 'masked' | 'branded';\n className?: string;\n}\n\n/**\n * Compact preview of a single saved card: brand icon + label. Used by\n * consumers (e.g. flights-ui's collapsed checkout drawer) to show the\n * currently-selected card outside the full `<PaymentMethodsManager />`\n * list view. Keeps the brand-icon styling consistent with the expanded list.\n *\n * Brand icon is sized to match flights-ui main's `w-[34px]` collapsed view.\n * No vertical padding — the parent controls spacing.\n */\nexport const PaymentMethodPreview = ({\n method,\n trailing,\n onClick,\n cardLabelFormat = 'branded',\n className,\n}: PaymentMethodPreviewProps) => (\n <div\n className={clsx('flex items-center gap-3', onClick && 'cursor-pointer', className)}\n onClick={onClick}\n role={onClick ? 'button' : undefined}\n tabIndex={onClick ? 0 : undefined}\n onKeyDown={\n onClick\n ? (e) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n onClick();\n }\n }\n : undefined\n }\n data-testid={`payment-method-preview-${method.id}`}\n >\n <CardBrandIcon brand={method.brand} width={34} className=\"flex-shrink-0\" />\n <span className=\"flex-1 text-lg font-semibold text-grayWarm-950\">\n {cardLabelFormat === 'masked'\n ? `•••• ${method.last4}`\n : `${prettyBrand(method.brand)} ${method.last4}`}\n </span>\n {trailing}\n </div>\n);\n","/**\n * True when a card's printed expiration has already passed.\n * `expMonth` is 1-12, `expYear` is the 4-digit year.\n */\nexport const isExpired = (expMonth: number, expYear: number, now: Date = new Date()): boolean =>\n expYear < now.getFullYear() || (expYear === now.getFullYear() && expMonth < now.getMonth() + 1);\n","import { useEffect, useRef, useState } from 'react';\nimport clsx from 'clsx';\n\nimport type { PaymentMethodSummary } from '../types';\nimport { CardBrandIcon } from './cardBrandIcon';\nimport { isExpired } from './isExpired';\n\nexport interface PaymentMethodRowProps {\n method: PaymentMethodSummary;\n /** When true, render a radio input and treat the whole row as selectable. */\n selectable: boolean;\n selected: boolean;\n onSelect?: (method: PaymentMethodSummary) => void;\n onSetDefault: (method: PaymentMethodSummary) => void;\n onRemove: (method: PaymentMethodSummary) => void;\n /** Disable the menu actions while a mutation is in flight. */\n disabled: boolean;\n /** When true, render the green \"Default\" pill on the default card. */\n showDefaultBadge: boolean;\n /**\n * When true, hide the \"Set as default\" menu item — the parent has wired\n * row-selection to also set the default (flights-ui's checkout UX), so\n * the menu entry would be redundant.\n */\n hideSetDefaultMenuItem: boolean;\n /**\n * Controls how the card label is rendered next to the brand icon.\n * - `'branded'` (default): \"Visa 4242\" — brand name + last4\n * - `'masked'`: \"•••• 4242\" — masked bullets + last4 (flights-ui checkout style)\n */\n cardLabelFormat?: 'masked' | 'branded';\n}\n\nconst prettyBrand = (brand: string | null | undefined): string => {\n if (!brand) return 'Card';\n const key = brand.toLowerCase();\n if (key === 'amex') return 'Amex';\n return key.charAt(0).toUpperCase() + key.slice(1);\n};\n\nconst formatExpiry = (expMonth: number, expYear: number): string =>\n `${String(expMonth).padStart(2, '0')}/${expYear}`;\n\nexport const PaymentMethodRow = ({\n method,\n selectable,\n selected,\n onSelect,\n onSetDefault,\n onRemove,\n disabled,\n showDefaultBadge,\n hideSetDefaultMenuItem,\n cardLabelFormat = 'branded',\n}: PaymentMethodRowProps) => {\n const [menuOpen, setMenuOpen] = useState(false);\n const menuContainerRef = useRef<HTMLDivElement | null>(null);\n const expired = isExpired(method.expMonth, method.expYear);\n\n useEffect(() => {\n if (!menuOpen) return;\n const onDocClick = (e: MouseEvent) => {\n if (!menuContainerRef.current?.contains(e.target as Node)) setMenuOpen(false);\n };\n document.addEventListener('mousedown', onDocClick);\n return () => document.removeEventListener('mousedown', onDocClick);\n }, [menuOpen]);\n\n const handleRowClick = () => {\n if (selectable && onSelect && !disabled) onSelect(method);\n };\n\n return (\n <div\n className={clsx(\n // items-start + per-element mt offsets so the radio, brand icon, and\n // label all read as one horizontal line, with the Exp text directly\n // below the label in the same column. Matches main's flights-ui +\n // accounts-ui row layout (both use items-start).\n 'flex items-start gap-3 transition-colors',\n selectable ? 'rounded-lg border px-3 py-3' : 'py-4',\n selectable && !disabled && 'cursor-pointer',\n selectable &&\n (selected\n ? 'border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]'\n : 'border-grayWarm-200 hover:border-grayWarm-300'),\n )}\n onClick={handleRowClick}\n data-testid={`payment-method-row-${method.id}`}\n >\n {selectable ? (\n <input\n type=\"radio\"\n name=\"movmo-payment-method\"\n checked={selected}\n onChange={() => onSelect?.(method)}\n onClick={(e) => e.stopPropagation()}\n aria-label={`Select ${prettyBrand(method.brand)} ending ${method.last4}`}\n // mt-2 pushes the 16px radio down so its vertical center sits on the\n // label's text baseline (matches main's mt-2 trick — items-start by\n // itself would top-align the radio with the brand icon's top, which\n // looks too high relative to the label).\n 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\"\n disabled={disabled}\n />\n ) : null}\n\n <CardBrandIcon brand={method.brand} className=\"flex-shrink-0\" />\n\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <span className=\"text-lg font-semibold text-grayWarm-950\">\n {cardLabelFormat === 'masked'\n ? `•••• ${method.last4}`\n : `${prettyBrand(method.brand)} ${method.last4}`}\n </span>\n {showDefaultBadge && method.isDefault ? (\n <span\n className=\"inline-flex items-center rounded-full bg-success-50 px-2 py-0.5 text-xs font-semibold text-success-700\"\n data-testid={`badge-default-${method.id}`}\n >\n Default\n </span>\n ) : null}\n {expired ? (\n <span\n className=\"inline-flex items-center rounded-full bg-error-50 px-2 py-0.5 text-xs font-semibold text-error-700\"\n data-testid={`badge-expired-${method.id}`}\n >\n Expired\n </span>\n ) : null}\n </div>\n <div className={clsx('text-base', expired ? 'text-grayWarm-400' : 'text-grayWarm-600')}>\n Exp. {formatExpiry(method.expMonth, method.expYear)}\n </div>\n </div>\n\n <div className=\"relative flex-shrink-0\" ref={menuContainerRef}>\n <button\n type=\"button\"\n aria-label={`Open actions for card ending ${method.last4}`}\n aria-haspopup=\"menu\"\n aria-expanded={menuOpen}\n className=\"rounded-lg p-2 text-grayWarm-600 transition-colors hover:bg-grayWarm-100 disabled:cursor-not-allowed disabled:opacity-50\"\n disabled={disabled}\n onClick={(e) => {\n e.stopPropagation();\n setMenuOpen((open) => !open);\n }}\n data-testid={`menu-trigger-${method.id}`}\n >\n <svg\n viewBox=\"0 0 24 24\"\n width=\"20\"\n height=\"20\"\n fill=\"currentColor\"\n aria-hidden=\"true\"\n >\n <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\" />\n </svg>\n </button>\n {menuOpen ? (\n <div\n role=\"menu\"\n className={clsx(\n 'absolute z-10 whitespace-nowrap rounded-lg border border-grayWarm-200 bg-white py-1 shadow-lg',\n // selectable mode (flights-ui): the row has a thick border that a\n // top-aligned dropdown would crash through. Float the menu ABOVE\n // the trigger button, horizontally centered, with a small tail\n // pointing back down at the dots. Matches main's flights-ui menu.\n // non-selectable mode (accounts-ui): no per-row border to\n // overlap; keep the menu below + right-aligned.\n selectable\n ? 'bottom-full left-1/2 mb-2 -translate-x-1/2'\n : 'right-0 top-full mt-1',\n )}\n onClick={(e) => e.stopPropagation()}\n data-testid={`menu-${method.id}`}\n >\n {selectable ? (\n // Tail: 8px square rotated 45° so its bottom-right corner\n // becomes a downward-pointing tip. Bottom + right borders of\n // the square form the menu's continuous border.\n <span\n aria-hidden=\"true\"\n 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\"\n />\n ) : null}\n {!method.isDefault && !hideSetDefaultMenuItem ? (\n <button\n type=\"button\"\n role=\"menuitem\"\n className=\"block w-full px-4 py-1 text-left text-md font-semibold text-grayWarm-950 hover:text-grayWarm-700\"\n onClick={() => {\n setMenuOpen(false);\n onSetDefault(method);\n }}\n data-testid={`menu-set-default-${method.id}`}\n >\n Set as default\n </button>\n ) : null}\n <button\n type=\"button\"\n role=\"menuitem\"\n className=\"block w-full px-4 py-1 text-left text-md font-semibold text-error-700 hover:text-error-500\"\n onClick={() => {\n setMenuOpen(false);\n onRemove(method);\n }}\n data-testid={`menu-remove-${method.id}`}\n >\n Delete\n </button>\n </div>\n ) : null}\n </div>\n </div>\n );\n};\n","import type { ReactNode } from 'react';\nimport clsx from 'clsx';\n\nimport { getPaymentsConfig } from '../config';\nimport { CardBrandIcon } from './cardBrandIcon';\n\nconst altIconUrl = (slug: string): string =>\n `${getPaymentsConfig().iconCdnBaseUrl}/website/assets/icons/payments/${slug}.svg`;\n\nconst AltIcon = ({ slug, alt }: { slug: string; alt: string }) => (\n <img\n src={altIconUrl(slug)}\n alt={alt}\n height={20}\n loading=\"lazy\"\n style={{ height: 20, width: 'auto' }}\n />\n);\n\n/**\n * The full set of payment types Movmo plans to support. Only `credit_card` is\n * functional today — the rest render as disabled \"Coming soon\" rows so the\n * consumer-facing UX matches the existing flights-ui design without shipping\n * dead UX behind a working radio.\n */\nexport type PaymentType = 'credit_card' | 'paypal' | 'googlepay' | 'klarna' | 'ach';\n\nexport interface PaymentTypeSelectorProps {\n /**\n * The currently-selected payment type, or `null` when nothing is selected\n * yet (the per-Figma empty state — user must click a row to expand its body).\n * Today only 'credit_card' is functional; the others render disabled.\n */\n selected: PaymentType | null;\n onSelect: (type: PaymentType) => void;\n /** Slot rendered below the Credit Card option when it's selected. */\n creditCardBody: ReactNode;\n className?: string;\n}\n\nconst OtherOptionRow = ({\n type,\n label,\n iconNode,\n}: {\n type: PaymentType;\n label: string;\n iconNode: ReactNode;\n}) => (\n // Alt payment types are visible + clickable but don't yet do anything —\n // the click is intentionally a no-op so the row looks identical to the\n // (future) functional state without faking selection.\n <label\n className=\"flex cursor-pointer items-center gap-3 rounded-lg border border-grayWarm-200 px-4 py-3 transition-colors hover:border-grayWarm-300\"\n data-testid={`payment-type-${type}`}\n >\n <input\n type=\"radio\"\n name=\"movmo-payment-type\"\n value={type}\n onChange={() => {\n /* TODO: wire when this provider lands */\n }}\n className=\"h-4 w-4 cursor-pointer accent-grayWarm-900\"\n aria-label={label}\n />\n <span className=\"flex flex-1 items-center gap-2 text-sm font-semibold text-grayWarm-900\">\n {label}\n {iconNode}\n </span>\n </label>\n);\n\nexport const PaymentTypeSelector = ({\n selected,\n onSelect,\n creditCardBody,\n className,\n}: PaymentTypeSelectorProps) => {\n const isCreditCardSelected = selected === 'credit_card';\n\n return (\n <div className={clsx('flex w-full flex-col gap-3', className)}>\n <label\n className={clsx(\n 'flex cursor-pointer flex-col gap-3 rounded-lg border px-4 py-3 transition-colors',\n isCreditCardSelected\n ? 'border-grayWarm-900 shadow-[0_0_0_1px_#1c1917]'\n : 'border-grayWarm-200',\n )}\n data-testid=\"payment-type-credit_card\"\n >\n <div className=\"flex items-center gap-3\">\n <input\n type=\"radio\"\n name=\"movmo-payment-type\"\n value=\"credit_card\"\n checked={isCreditCardSelected}\n onChange={() => onSelect('credit_card')}\n className=\"h-4 w-4 cursor-pointer accent-grayWarm-900\"\n aria-label=\"Credit card\"\n />\n <span className=\"flex-1 text-sm font-semibold text-grayWarm-900\">Credit card</span>\n <div className=\"flex items-center gap-1.5\">\n <CardBrandIcon brand=\"mastercard\" width={28} />\n <CardBrandIcon brand=\"visa\" width={28} />\n <CardBrandIcon brand=\"amex\" width={28} />\n <CardBrandIcon brand=\"discover\" width={28} />\n </div>\n </div>\n {isCreditCardSelected ? (\n <div data-testid=\"payment-type-credit_card-body\">{creditCardBody}</div>\n ) : null}\n </label>\n\n {/* Per Figma: the \"Other options\" section header only appears once the\n Credit card row is selected (i.e. the form is expanded). In the empty\n state the four type rows just stack without a header. */}\n {isCreditCardSelected ? (\n <p\n className=\"mt-2 text-sm font-semibold text-grayWarm-900\"\n data-testid=\"payment-type-other-options-header\"\n >\n Other options\n </p>\n ) : null}\n\n <OtherOptionRow\n type=\"paypal\"\n label=\"PayPal\"\n iconNode={<AltIcon slug=\"paypal\" alt=\"PayPal\" />}\n />\n <OtherOptionRow\n type=\"googlepay\"\n label=\"GooglePay\"\n iconNode={<AltIcon slug=\"google-pay\" alt=\"GooglePay\" />}\n />\n <OtherOptionRow\n type=\"klarna\"\n label=\"Klarna\"\n iconNode={<AltIcon slug=\"klarna\" alt=\"Klarna\" />}\n />\n <OtherOptionRow\n type=\"ach\"\n label=\"Bank account (ACH)\"\n iconNode={<span className=\"text-xs font-medium text-grayWarm-500\">Direct debit</span>}\n />\n </div>\n );\n};\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport clsx from 'clsx';\n\nimport { fetchTokenizationSession } from '../api';\nimport { getPaymentsConfig } from '../config';\nimport { MovmoCardForm } from '../MovmoCardForm/MovmoCardForm';\nimport type { PaymentMethodSummary } from '../types';\nimport { useDeletePaymentMethod } from '../useDeletePaymentMethod';\nimport { useSetDefaultPaymentMethod } from '../useSetDefaultPaymentMethod';\nimport { useUserPaymentMethods } from '../useUserPaymentMethods';\nimport { AddPaymentMethodModal } from './AddPaymentMethodModal';\nimport { PaymentMethodPreview } from './PaymentMethodPreview';\nimport { PaymentMethodRow } from './PaymentMethodRow';\nimport { PaymentTypeSelector, type PaymentType } from './PaymentTypeSelector';\n\nconst ADD_PAYMENT_FORM_ID = 'movmo-add-payment-form';\n\nexport interface PaymentMethodsManagerProps {\n userId: string;\n /**\n * Pre-fill the single cardholder-name input in the add-card form.\n * Falls back to `defaultCardholderFirstName + \" \" + defaultCardholderLastName`\n * for backward compatibility with the legacy MovmoCardForm props.\n */\n defaultCardholderName?: string;\n /** @deprecated Use `defaultCardholderName`. */\n defaultCardholderFirstName?: string;\n /** @deprecated Use `defaultCardholderName`. */\n defaultCardholderLastName?: string;\n /** Selection (opt-in). When `onSelect` is provided, each row renders a radio. */\n selectedId?: string;\n onSelect?: (method: PaymentMethodSummary) => void;\n /** Fires when the list state changes (add, delete, set-default). */\n onChange?: (items: PaymentMethodSummary[]) => void;\n /**\n * Show the Credit card / PayPal / GooglePay / Klarna / ACH radios above\n * the card-capture form. Only Credit card is functional today; the others\n * render as \"Coming soon\" to match the existing flights-ui design without\n * dropping the visual cues. Defaults to `true`. accounts-ui can opt out\n * by passing `false`.\n */\n paymentTypeSelector?: boolean;\n /**\n * When `true` AND the user has zero saved cards, the card form auto-submits\n * the moment all fields are valid. Matches the flights-ui first-card UX.\n * Defaults to `true`.\n */\n autoSaveFirstCard?: boolean;\n /**\n * When `true`, clicking a row both fires `onSelect` AND sets that method\n * as the default (the flights-ui checkout model: \"selected = default\").\n * Also hides the \"Set as default\" menu item since the row click already\n * does it. Requires `onSelect` to be useful. Defaults to `false`.\n */\n selectionSetsDefault?: boolean;\n /**\n * Render the green \"Default\" pill on the default row. accounts-ui keeps\n * this on; flights-ui passes `false` (the thick selected-border alone\n * communicates default since `selectionSetsDefault` couples the two).\n * Defaults to `true`.\n */\n showDefaultBadge?: boolean;\n /**\n * When `true` AND the user has at least one saved card, the list collapses\n * into a compact preview row with a chevron-down toggle. Expanding shows the\n * full list + Add button. Defaults to `false` (accounts-ui behaviour).\n * flights-ui passes `true`.\n */\n collapsible?: boolean;\n /**\n * Controls the card label format inside rows.\n * - `'branded'` (default): \"Visa 4242\" — brand name + last4\n * - `'masked'`: \"•••• 4242\" — masked bullets + last4 (flights-ui style)\n */\n cardLabelFormat?: 'masked' | 'branded';\n className?: string;\n}\n\nconst sortDefaultFirst = (items: PaymentMethodSummary[]): PaymentMethodSummary[] => {\n const defaults = items.filter((m) => m.isDefault);\n const rest = items.filter((m) => !m.isDefault);\n return [...defaults, ...rest];\n};\n\n/**\n * Skeleton sized to match the real row (PaymentMethodRow) so the layout\n * doesn't reflow when data lands. Dimensions mirror the accounts-ui main-\n * branch loading state: 46x32 card icon, 120x20 brand+last4 line, optional\n * 56x20 rounded-full \"Default\" pill on the first row, 100x16 expiry, 20x20\n * circular menu trigger.\n */\nconst SkeletonRow = ({ withDefaultBadge = false }: { withDefaultBadge?: boolean }) => (\n <div\n className=\"flex items-start justify-between py-4\"\n data-testid=\"payment-method-skeleton\"\n >\n <div className=\"flex items-start gap-3\">\n <div className=\"h-8 w-[46px] flex-shrink-0 animate-pulse rounded bg-grayWarm-200\" />\n <div className=\"space-y-2\">\n <div className=\"flex items-center gap-2\">\n <div className=\"h-5 w-[120px] animate-pulse rounded bg-grayWarm-200\" />\n {withDefaultBadge ? (\n <div className=\"h-5 w-[56px] animate-pulse rounded-full bg-grayWarm-200\" />\n ) : null}\n </div>\n <div className=\"h-4 w-[100px] animate-pulse rounded bg-grayWarm-200\" />\n </div>\n </div>\n <div className=\"h-5 w-5 flex-shrink-0 animate-pulse rounded-full bg-grayWarm-200\" />\n </div>\n);\n\nexport const PaymentMethodsManager = ({\n userId,\n defaultCardholderName,\n defaultCardholderFirstName,\n defaultCardholderLastName,\n selectedId,\n onSelect,\n onChange,\n paymentTypeSelector = true,\n autoSaveFirstCard = true,\n selectionSetsDefault = false,\n showDefaultBadge = true,\n collapsible = false,\n cardLabelFormat = 'branded',\n className,\n}: PaymentMethodsManagerProps) => {\n const { items: fetched, status, error: fetchError, refetch } = useUserPaymentMethods(userId);\n const { deletePaymentMethod, status: deleteStatus } = useDeletePaymentMethod(userId);\n const { setDefault, status: setDefaultStatus } = useSetDefaultPaymentMethod(userId);\n\n // Local mirror of the list so the manager can apply optimistic updates and\n // roll them back on API failure without waiting for a refetch.\n const [items, setItems] = useState<PaymentMethodSummary[]>([]);\n const [mutationError, setMutationError] = useState<string | null>(null);\n const [modalOpen, setModalOpen] = useState(false);\n const [formError, setFormError] = useState<string | null>(null);\n const [formCanSubmit, setFormCanSubmit] = useState(false);\n const [formIsSaving, setFormIsSaving] = useState(false);\n // Empty state per Figma node 1536-21454: no payment type selected by\n // default. The user must click the Credit card radio to expand the form.\n const [paymentType, setPaymentType] = useState<PaymentType | null>(null);\n // Collapsible drawer: collapsed by default when there are saved cards.\n const [drawerOpen, setDrawerOpen] = useState(false);\n // Auto-select default: fire once per mount. Ref prevents repeat fires if\n // the parent deliberately clears selectedId after initial selection.\n const autoSelectedRef = useRef(false);\n\n const closeModal = useCallback(() => {\n setModalOpen(false);\n setFormError(null);\n setPaymentType(null);\n }, []);\n\n const seededCardholderName =\n defaultCardholderName ??\n ([defaultCardholderFirstName, defaultCardholderLastName].filter(Boolean).join(' ') ||\n undefined);\n\n useEffect(() => {\n if (status === 'ready') setItems(sortDefaultFirst(fetched));\n }, [fetched, status]);\n\n // Issue 1 — Auto-select the default on first load when selection is wired\n // and no card is selected yet. The ref guard fires this exactly once per\n // mount so the parent retains control after the initial selection.\n useEffect(() => {\n if (!onSelect) return;\n if (autoSelectedRef.current) return;\n if (status !== 'ready') return;\n if (items.length === 0) return;\n if (selectedId) return; // parent already has a selection\n autoSelectedRef.current = true;\n const defaultItem = items.find((m) => m.isDefault) ?? items[0];\n onSelect(defaultItem);\n }, [onSelect, status, items, selectedId]);\n\n const updateItems = useCallback(\n (next: PaymentMethodSummary[] | ((prev: PaymentMethodSummary[]) => PaymentMethodSummary[])) => {\n setItems((prev) => {\n const resolved = typeof next === 'function' ? next(prev) : next;\n const sorted = sortDefaultFirst(resolved);\n onChange?.(sorted);\n return sorted;\n });\n },\n [onChange],\n );\n\n const mutationsBusy = deleteStatus === 'pending' || setDefaultStatus === 'pending';\n\n const handleSetDefault = useCallback(\n async (method: PaymentMethodSummary) => {\n const snapshot = items;\n setMutationError(null);\n updateItems((prev) => prev.map((m) => ({ ...m, isDefault: m.id === method.id })));\n try {\n await setDefault(method.id);\n refetch();\n } catch (err) {\n setItems(snapshot);\n onChange?.(snapshot);\n const message =\n err instanceof Error ? err.message : 'Failed to set default payment method.';\n setMutationError(message);\n }\n },\n [items, updateItems, setDefault, refetch, onChange],\n );\n\n /**\n * Wrap the consumer's onSelect: forward it, then (when wired) optimistically\n * promote the chosen card to default via the same flow as the explicit\n * setDefault menu. flights-ui's checkout uses this so a single row click\n * does both.\n */\n const handleSelect = useCallback(\n (method: PaymentMethodSummary) => {\n onSelect?.(method);\n if (!selectionSetsDefault) return;\n if (method.isDefault) return; // already the default — no PUT needed\n void handleSetDefault(method);\n },\n [onSelect, selectionSetsDefault, handleSetDefault],\n );\n\n const handleRemove = useCallback(\n async (method: PaymentMethodSummary) => {\n const snapshot = items;\n setMutationError(null);\n const remaining = items.filter((m) => m.id !== method.id);\n updateItems(() => remaining);\n\n // If the deleted card was the selected one, hand the selection off to\n // the next-best candidate (the remaining default; failing that, the\n // first remaining card). Without this, the parent's selectedPaymentMethod\n // stays pinned to the deleted card — flights-ui's Book button check\n // (`!!selectedPaymentMethod`) would stay enabled even though the user\n // can no longer pay with that card, and collapsing the drawer would\n // show a different card than what's actually \"selected\" upstream\n // (the manager's local fallback for display masks the mismatch).\n //\n // If `remaining` is empty there's nothing to select — the consumer's\n // own state (PaymentContext) still holds the deleted card, but the\n // next on-mount auto-select pass will reseed it once a card exists.\n // Adding nullable onSelect support is a follow-up if a consumer hits\n // the \"deleted last card mid-flow\" case in practice.\n const nextSelection =\n method.id === selectedId && onSelect\n ? remaining.find((m) => m.isDefault) ?? remaining[0] ?? null\n : null;\n if (nextSelection) handleSelect(nextSelection);\n\n // Skip the local refetch when handleSelect's promote-to-default branch\n // will fire its own refetch after the PUT settles (flights-ui case\n // where the hand-off becomes the new default). Otherwise we'd\n // double-GET /payment-methods — same pattern as handleCardAdded.\n const willPromoteToDefault =\n Boolean(nextSelection) &&\n selectionSetsDefault &&\n nextSelection !== null &&\n !nextSelection.isDefault;\n\n try {\n await deletePaymentMethod(method.id);\n if (!willPromoteToDefault) refetch();\n } catch (err) {\n setItems(snapshot);\n onChange?.(snapshot);\n const message = err instanceof Error ? err.message : 'Failed to delete payment method.';\n setMutationError(message);\n }\n },\n [\n items,\n updateItems,\n deletePaymentMethod,\n refetch,\n onChange,\n selectedId,\n onSelect,\n handleSelect,\n selectionSetsDefault,\n ],\n );\n\n const handleCardAdded = useCallback(\n (newMethod: PaymentMethodSummary) => {\n setFormError(null);\n setModalOpen(false);\n setPaymentType(null);\n updateItems((prev) => [newMethod, ...prev.filter((m) => m.id !== newMethod.id)]);\n // Selection-mode consumers (flights-ui checkout) expect the\n // just-added card to be active — the user added it RIGHT NOW to pay\n // with it. Matches Delta / United / Booking.com checkout flows.\n // accounts-ui doesn't pass onSelect, so handleSelect is a no-op\n // there — the new card sits in the list and the existing default\n // stays default (correct for a profile-management context).\n // Routing through handleSelect also fires the selectionSetsDefault\n // promotion path so flights-ui's \"selected = default\" coupling\n // applies without a duplicate code path.\n handleSelect(newMethod);\n // Reconcile with server. Skip when handleSelect's set-default branch\n // will fire its own refetch after the PUT settles (i.e. flights-ui\n // mode + new card isn't already default): otherwise we double-GET\n // /payment-methods, once here and once when setDefault resolves.\n const willPromoteToDefault =\n Boolean(onSelect) && selectionSetsDefault && !newMethod.isDefault;\n if (!willPromoteToDefault) refetch();\n },\n [updateItems, refetch, handleSelect, onSelect, selectionSetsDefault],\n );\n\n const handleFormError = useCallback((message: string) => {\n setFormError(message);\n }, []);\n\n const empty = status === 'ready' && items.length === 0;\n const selectable = typeof onSelect === 'function';\n // In collapsible mode we never want the outer rounded-card wrapper — the\n // section already has a border-t divider at the Payments.tsx level.\n const showOuterCard = !selectable && !collapsible;\n // First card becomes the default automatically (matches existing UX).\n const addAsDefault = items.length === 0;\n const shouldAutoSave = autoSaveFirstCard && items.length === 0;\n\n /**\n * When the form is rendered inline (empty state), we use the empty-state\n * defaults: auto-save the first card, internal Save button visible.\n * When rendered inside the modal, we suppress the internal Save button\n * and disable auto-save — the modal footer drives submit.\n */\n const buildCardForm = useCallback(\n (inModal: boolean) => (\n <MovmoCardForm\n userId={userId}\n isDefault={addAsDefault}\n defaultCardholderName={seededCardholderName}\n autoSave={!inModal && shouldAutoSave}\n hideInternalSaveButton={inModal}\n formId={inModal ? ADD_PAYMENT_FORM_ID : undefined}\n onCanSubmitChange={inModal ? setFormCanSubmit : undefined}\n // Track in-flight tokenize / save so the modal-footer Save button\n // can swap its label for a spinner. autoSave (inline empty-state)\n // surfaces the in-flight state via inline text instead.\n onSavingChange={inModal ? setFormIsSaving : undefined}\n // Modal-mounted form: focus the card-number iframe immediately so\n // the user can start typing without an extra click.\n autoFocus={inModal ? 'number' : undefined}\n onSuccess={handleCardAdded}\n onError={handleFormError}\n />\n ),\n [userId, addAsDefault, seededCardholderName, shouldAutoSave, handleCardAdded, handleFormError],\n );\n\n const inlineCardForm = useMemo(() => buildCardForm(false), [buildCardForm]);\n const modalCardForm = useMemo(() => buildCardForm(true), [buildCardForm]);\n\n /** Wraps the card form in the payment-type selector when enabled. */\n const inlineAddBody = useMemo(() => {\n if (!paymentTypeSelector) return inlineCardForm;\n return (\n <PaymentTypeSelector\n selected={paymentType}\n onSelect={(t) => setPaymentType(t)}\n creditCardBody={inlineCardForm}\n />\n );\n }, [paymentTypeSelector, paymentType, inlineCardForm]);\n\n const modalAddBody = useMemo(() => {\n if (!paymentTypeSelector) return modalCardForm;\n return (\n <PaymentTypeSelector\n selected={paymentType}\n onSelect={(t) => setPaymentType(t)}\n creditCardBody={modalCardForm}\n />\n );\n }, [paymentTypeSelector, paymentType, modalCardForm]);\n\n return (\n <div\n className={clsx('flex w-full flex-col gap-4', className)}\n data-testid=\"payment-methods-manager\"\n >\n {status === 'loading' && items.length === 0 ? (\n // Only show the skeleton on first load — during a silent refetch\n // (e.g. after set-default or delete optimistic mutations), the user\n // already sees the correct optimistic list and a skeleton flash\n // here would be jarring.\n <div\n className={clsx(\n // Match the real-list shell so layout doesn't reflow when data\n // arrives. In selection mode the outer card is suppressed too.\n showOuterCard\n ? 'flex flex-col divide-y divide-grayWarm-200 rounded-xl border border-grayWarm-200 px-4 md:px-6'\n : 'flex flex-col gap-2',\n )}\n data-testid=\"payment-methods-loading\"\n >\n <SkeletonRow withDefaultBadge />\n <SkeletonRow />\n </div>\n ) : null}\n\n {status === 'error' ? (\n <div\n role=\"alert\"\n aria-live=\"polite\"\n className=\"flex items-center justify-between gap-3 rounded-md bg-error-50 p-3 text-sm text-error-700\"\n data-testid=\"payment-methods-list-error\"\n >\n <span>{fetchError ?? 'Failed to load payment methods.'}</span>\n <button\n type=\"button\"\n onClick={refetch}\n className=\"rounded-md border border-error-700 px-3 py-1 text-xs font-semibold text-error-700 hover:bg-error-50\"\n >\n Retry\n </button>\n </div>\n ) : null}\n\n {mutationError ? (\n <div\n role=\"alert\"\n aria-live=\"polite\"\n className=\"rounded-md bg-error-50 p-3 text-sm text-error-700\"\n data-testid=\"payment-methods-mutation-error\"\n >\n {mutationError}\n </div>\n ) : null}\n\n {/*\n * Collapsible header: ONE container holding either the collapsed\n * preview row or the expanded \"Payment methods\" h3 + chevron-up.\n * Shared `border-t pt-4` here means the divider line + the chevron\n * button's y-position stays fixed when toggling drawerOpen, so the\n * UI doesn't jump (Issue #5). Matches flights-ui main's pattern.\n */}\n {collapsible && items.length > 0 ? (\n <div className=\"border-t border-grayWarm-200 pt-4\">\n <div\n className=\"flex items-center justify-between\"\n data-testid={\n drawerOpen\n ? 'payment-methods-drawer-header'\n : 'payment-methods-collapsed-preview'\n }\n >\n {drawerOpen ? (\n <h3 className=\"text-md font-semibold text-grayWarm-950\">\n Payment methods\n </h3>\n ) : (\n <PaymentMethodPreview\n method={\n items.find((m) => m.id === selectedId) ??\n items.find((m) => m.isDefault) ??\n items[0]\n }\n cardLabelFormat={cardLabelFormat}\n className=\"flex-1\"\n />\n )}\n <button\n type=\"button\"\n aria-label={\n drawerOpen ? 'Collapse payment methods' : 'Expand payment methods'\n }\n aria-expanded={drawerOpen}\n className=\"bg-grayWarm-100 p-2 rounded-lg hover:bg-grayWarm-200 transition-colors\"\n onClick={() => setDrawerOpen((open) => !open)}\n data-testid={\n drawerOpen\n ? 'payment-methods-drawer-close'\n : 'payment-methods-drawer-open'\n }\n >\n {/*\n * Matches flights-ui main's URLS.icons.doubleDownArrows /\n * doubleUpArrows. Sourced from the configurable iconCdnBaseUrl\n * so the package doesn't hardcode a host.\n */}\n <img\n src={`${getPaymentsConfig().iconCdnBaseUrl}/website/assets/icons/chevron-${\n drawerOpen ? 'up' : 'down'\n }-double.svg`}\n alt=\"\"\n className=\"w-5 h-5\"\n />\n </button>\n </div>\n </div>\n ) : null}\n\n {/* ── Row list: shown always in non-collapsible mode, or when drawer is open ── */}\n {items.length > 0 && (!collapsible || drawerOpen) ? (\n <div\n className={clsx(\n 'flex flex-col',\n // accounts-ui (non-selectable, non-collapsible): rounded outer card\n // with divide-y separators between rows.\n // flights-ui (selectable or collapsible): bare space-y-3 gap between\n // per-row bordered tiles; no outer card chrome.\n showOuterCard\n ? 'rounded-xl border border-grayWarm-200 px-4 md:px-6 divide-y divide-grayWarm-200'\n : 'space-y-3',\n )}\n >\n {items.map((method) => (\n <PaymentMethodRow\n key={method.id}\n method={method}\n selectable={selectable}\n selected={selectable && method.id === selectedId}\n onSelect={handleSelect}\n onSetDefault={handleSetDefault}\n onRemove={handleRemove}\n disabled={mutationsBusy}\n showDefaultBadge={showDefaultBadge}\n hideSetDefaultMenuItem={selectionSetsDefault}\n cardLabelFormat={cardLabelFormat}\n />\n ))}\n </div>\n ) : null}\n\n {empty ? (\n // Empty state: render the add-card body inline (per Figma 1536-21454).\n <div data-testid=\"payment-methods-empty\">{inlineAddBody}</div>\n ) : items.length > 0 && (!collapsible || drawerOpen) ? (\n // Keep the Add button visible during silent refetches (status flips\n // back to 'loading' transiently after set-default / delete).\n // In collapsible mode only show the Add button when the drawer is open.\n <button\n type=\"button\"\n onClick={() => {\n setFormError(null);\n setPaymentType(null);\n setFormCanSubmit(false);\n setModalOpen(true);\n }}\n // Prefetch the tokenization session on hover / keyboard focus.\n // Combined with the in-flight cache in api.ts, this means the\n // modal's MovmoCardForm awaits an already-warm promise — most\n // users won't see the 600-1500ms blank-shell window. Safe to\n // fire-and-forget: errors here are surfaced when the modal-\n // mounted form retries on mount.\n onMouseEnter={() => {\n void fetchTokenizationSession().catch(() => {\n /* prefetch is best-effort — modal mount path will retry */\n });\n }}\n onFocus={() => {\n void fetchTokenizationSession().catch(() => {\n /* prefetch is best-effort — modal mount path will retry */\n });\n }}\n 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\"\n data-testid=\"payment-methods-add-trigger\"\n >\n Add payment method\n </button>\n ) : null}\n\n <AddPaymentMethodModal\n open={modalOpen}\n onClose={closeModal}\n formId={ADD_PAYMENT_FORM_ID}\n saveDisabled={!formCanSubmit}\n isSaving={formIsSaving}\n >\n {modalAddBody}\n {formError ? (\n // Single source of truth for save-time errors (API failures + hook\n // init failures forwarded from MovmoCardForm.onError). MovmoCardForm\n // intentionally does NOT render its own banner — two role=\"alert\"\n // nodes on the same string is a WCAG 4.1.3 violation (announced\n // twice). aria-live=\"polite\" so SR users hear new errors but the\n // announcement doesn't interrupt their current input.\n <p\n role=\"alert\"\n aria-live=\"polite\"\n className=\"mt-3 rounded-md bg-error-50 px-3 py-2 text-sm text-error-700\"\n data-testid=\"payment-methods-modal-error\"\n >\n {formError}\n </p>\n ) : null}\n </AddPaymentMethodModal>\n </div>\n );\n};\n\nPaymentMethodsManager.displayName = 'PaymentMethodsManager';\n\nexport default PaymentMethodsManager;\n"],"names":["f","require$$0","k","l","m","n","p","q","c","a","g","b","d","e","h","reactJsxRuntime_production_min","React","REACT_ELEMENT_TYPE","REACT_PORTAL_TYPE","REACT_FRAGMENT_TYPE","REACT_STRICT_MODE_TYPE","REACT_PROFILER_TYPE","REACT_PROVIDER_TYPE","REACT_CONTEXT_TYPE","REACT_FORWARD_REF_TYPE","REACT_SUSPENSE_TYPE","REACT_SUSPENSE_LIST_TYPE","REACT_MEMO_TYPE","REACT_LAZY_TYPE","REACT_OFFSCREEN_TYPE","MAYBE_ITERATOR_SYMBOL","FAUX_ITERATOR_SYMBOL","getIteratorFn","maybeIterable","maybeIterator","ReactSharedInternals","error","format","_len2","args","_key2","printWarning","level","ReactDebugCurrentFrame","stack","argsWithFormat","item","enableScopeAPI","enableCacheElement","enableTransitionTracing","enableLegacyHidden","enableDebugTracing","REACT_MODULE_REFERENCE","isValidElementType","type","getWrappedName","outerType","innerType","wrapperName","displayName","functionName","getContextName","getComponentNameFromType","context","provider","outerName","lazyComponent","payload","init","assign","disabledDepth","prevLog","prevInfo","prevWarn","prevError","prevGroup","prevGroupCollapsed","prevGroupEnd","disabledLog","disableLogs","props","reenableLogs","ReactCurrentDispatcher","prefix","describeBuiltInComponentFrame","name","source","ownerFn","x","match","reentry","componentFrameCache","PossiblyWeakMap","describeNativeComponentFrame","fn","construct","frame","control","previousPrepareStackTrace","previousDispatcher","Fake","sample","sampleLines","controlLines","s","_frame","syntheticFrame","describeFunctionComponentFrame","shouldConstruct","Component","prototype","describeUnknownElementTypeFrameInDEV","hasOwnProperty","loggedTypeFailures","setCurrentlyValidatingElement","element","owner","checkPropTypes","typeSpecs","values","location","componentName","has","typeSpecName","error$1","err","ex","isArrayImpl","isArray","typeName","value","hasToStringTag","willCoercionThrow","testStringCoercion","checkKeyStringCoercion","ReactCurrentOwner","RESERVED_PROPS","specialPropKeyWarningShown","specialPropRefWarningShown","hasValidRef","config","getter","hasValidKey","warnIfStringRefCannotBeAutoConverted","self","defineKeyPropWarningGetter","warnAboutAccessingKey","defineRefPropWarningGetter","warnAboutAccessingRef","ReactElement","key","ref","jsxDEV","maybeKey","propName","defaultProps","ReactCurrentOwner$1","ReactDebugCurrentFrame$1","setCurrentlyValidatingElement$1","propTypesMisspellWarningShown","isValidElement","object","getDeclarationErrorAddendum","getSourceInfoErrorAddendum","ownerHasKeyUseWarning","getCurrentComponentErrorInfo","parentType","info","parentName","validateExplicitKey","currentComponentErrorInfo","childOwner","validateChildKeys","node","child","iteratorFn","iterator","step","validatePropTypes","propTypes","_name","validateFragmentProps","fragment","keys","didWarnAboutKeySpread","jsxWithValidation","isStaticChildren","validType","sourceInfo","typeString","children","i","beforeExample","afterExample","jsxWithValidationStatic","jsxWithValidationDynamic","jsx","jsxs","reactJsxRuntime_development","jsxRuntimeModule","require$$1","r","o","clsx","DEFAULT_SPREEDLY_SCRIPT_URL","DEFAULT_ICON_CDN_BASE_URL","overrides","setPaymentsConfig","readEnv","proc","_a","getPaymentsConfig","toSummary","body","jsonHeaders","apiUrl","path","baseUrl","performFetch","input","configuredFetch","readError","res","fallback","inFlightTokenizationSession","fetchTokenizationSession","promise","isFullPaymentMethodBody","savePaymentMethodFromToken","userId","tokenizedPaymentMethodId","isDefault","getRes","fullBody","listPaymentMethods","deletePaymentMethod","methodId","updatePaymentMethod","patch","BRAND_SLUG","MIN_RENDER_WIDTH","CardBrandIcon","brand","className","width","slug","renderWidth","renderHeight","iconCdnBaseUrl","scriptPromise","loadSpreedlyScript","spreedlyScriptUrl","resolve","reject","existing","onScriptLoad","script","DEFAULT_NUMBER_EL","DEFAULT_CVV_EL","toSdkPayload","data","useMovmoCardFields","options","numberEl","cvvEl","onCardTokenized","onFieldErrors","onValidityChange","onBrandChange","status","setStatus","useState","setError","validity","setValidity","setBrand","focused","setFocused","spreedlyRef","useRef","onCardTokenizedRef","onFieldErrorsRef","onValidityChangeRef","onBrandChangeRef","useEffect","validityRef","cancelled","session","spreedly","_b","_c","_d","iframeFontStyle","_e","_f","token","errors","_activeEl","inputProperties","prev","next","newValid","message","tokenize","useCallback","focusField","field","fieldShellClass","iframeShellClass","iframeShellActiveClass","iframeShellIdleClass","splitName","full","trimmed","lastSpace","parseExpiry","raw","digits","month","yearRaw","year","formatExpiryInput","isExpiryValid","mm","yyyy","now","isZipValid","formatZipInput","MovmoCardForm","onSuccess","onError","defaultCardholderName","defaultCardholderFirstName","defaultCardholderLastName","autoSave","formId","hideInternalSaveButton","onCanSubmitChange","onSavingChange","autoFocus","seededName","cardholderName","setCardholderName","expiry","setExpiry","zip","setZip","formStatus","setFormStatus","autoSubmittedRef","handleCardTokenized","summary","handleFieldErrors","hookOptions","useMemo","hookStatus","hookError","autoFocusedRef","nameValid","expiryValid","zipValid","autoFocusedCvvRef","autoFocusedZipRef","autoFocusedNameRef","zipInputRef","cardholderNameInputRef","formInvalid","isBusy","canSubmit","onCanSubmitChangeRef","onSavingChangeRef","submit","firstName","lastName","timer","handleSubmit","inputsDisabled","onErrorRef","useDeletePaymentMethod","deletePaymentMethodApi","useSetDefaultPaymentMethod","useUserPaymentMethods","items","setItems","tick","setTick","abortRef","controller","result","refetch","AddPaymentMethodModal","open","onClose","saveDisabled","saveLabel","isSaving","onKey","Fragment","prettyBrand","PaymentMethodPreview","method","trailing","onClick","cardLabelFormat","isExpired","expMonth","expYear","formatExpiry","PaymentMethodRow","selectable","selected","onSelect","onSetDefault","onRemove","disabled","showDefaultBadge","hideSetDefaultMenuItem","menuOpen","setMenuOpen","menuContainerRef","expired","onDocClick","handleRowClick","altIconUrl","AltIcon","alt","OtherOptionRow","label","iconNode","PaymentTypeSelector","creditCardBody","isCreditCardSelected","ADD_PAYMENT_FORM_ID","sortDefaultFirst","defaults","rest","SkeletonRow","withDefaultBadge","PaymentMethodsManager","selectedId","onChange","paymentTypeSelector","autoSaveFirstCard","selectionSetsDefault","collapsible","fetched","fetchError","deleteStatus","setDefault","setDefaultStatus","mutationError","setMutationError","modalOpen","setModalOpen","formError","setFormError","formCanSubmit","setFormCanSubmit","formIsSaving","setFormIsSaving","paymentType","setPaymentType","drawerOpen","setDrawerOpen","autoSelectedRef","closeModal","seededCardholderName","defaultItem","updateItems","resolved","sorted","mutationsBusy","handleSetDefault","snapshot","handleSelect","handleRemove","remaining","nextSelection","willPromoteToDefault","handleCardAdded","newMethod","handleFormError","empty","showOuterCard","addAsDefault","shouldAutoSave","buildCardForm","inModal","inlineCardForm","modalCardForm","inlineAddBody","t","modalAddBody"],"mappings":";;;;;;;;;;;;;;;AASa,MAAIA,IAAEC,IAAiBC,IAAE,OAAO,IAAI,eAAe,GAAEC,IAAE,OAAO,IAAI,g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,cACb,UAAA;AAAA,YAAA;AAAA,UAAA;AAAA,YAGC;AAAA,QAEJ5B,gBAAAA,EAAAA;AAAAA,UAACiM;AAAA,UAAA;AAAA,YACC,MAAM8D;AAAA,YACN,SAASa;AAAA,YACT,QAAQjC;AAAA,YACR,cAAc,CAACwB;AAAA,YACf,UAAUE;AAAA,YAET,UAAA;AAAA,cAAAkC;AAAA,cACAtC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAOClQ,gBAAAA,EAAAA;AAAAA,kBAAC;AAAA,kBAAA;AAAA,oBACC,MAAK;AAAA,oBACL,aAAU;AAAA,oBACV,WAAU;AAAA,oBACV,eAAY;AAAA,oBAEX,UAAAkQ;AAAA,kBAAA;AAAA,gBAAA;AAAA,kBAED;AAAA,YAAA;AAAA,UAAA;AAAA,QAAA;AAAA,MACN;AAAA,IAAA;AAAA,EAAA;AAGN;AAEAhB,GAAsB,cAAc;","x_google_ignoreList":[0,1,2,3]}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../../../../node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.production.min.js","../../../../node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.development.js","../../../../node_modules/.pnpm/react@18.3.1/node_modules/react/jsx-runtime.js","../../../../node_modules/.pnpm/clsx@2.1.1/node_modules/clsx/dist/clsx.mjs","../src/config.ts","../src/api.ts","../src/PaymentMethodsManager/cardBrandIcon.tsx","../src/loadSpreedlyScript.ts","../src/useMovmoCardFields.ts","../src/MovmoCardForm/MovmoCardForm.tsx","../src/useDeletePaymentMethod.ts","../src/useSetDefaultPaymentMethod.ts","../src/useUserPaymentMethods.ts","../src/PaymentMethodsManager/AddPaymentMethodModal.tsx","../src/PaymentMethodsManager/PaymentMethodPreview.tsx","../src/PaymentMethodsManager/isExpired.ts","../src/PaymentMethodsManager/PaymentMethodRow.tsx","../src/PaymentMethodsManager/PaymentTypeSelector.tsx","../src/PaymentMethodsManager/PaymentMethodsManager.tsx","../src/createMovmoAuthFetch.ts"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var f=require(\"react\"),k=Symbol.for(\"react.element\"),l=Symbol.for(\"react.fragment\"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};\nfunction q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=\"\"+g);void 0!==a.key&&(e=\"\"+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q;\n","/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n'use strict';\n\nvar React = require('react');\n\n// ATTENTION\n// When adding new symbols to this file,\n// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'\n// The Symbol used to tag the ReactElement-like types.\nvar REACT_ELEMENT_TYPE = Symbol.for('react.element');\nvar REACT_PORTAL_TYPE = Symbol.for('react.portal');\nvar REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');\nvar REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');\nvar REACT_PROFILER_TYPE = Symbol.for('react.profiler');\nvar REACT_PROVIDER_TYPE = Symbol.for('react.provider');\nvar REACT_CONTEXT_TYPE = Symbol.for('react.context');\nvar REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');\nvar REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');\nvar REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');\nvar REACT_MEMO_TYPE = Symbol.for('react.memo');\nvar REACT_LAZY_TYPE = Symbol.for('react.lazy');\nvar REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');\nvar MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\nfunction error(format) {\n {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n var argsWithFormat = args.map(function (item) {\n return String(item);\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\n }\n}\n\n// -----------------------------------------------------------------------------\n\nvar enableScopeAPI = false; // Experimental Create Event Handle API.\nvar enableCacheElement = false;\nvar enableTransitionTracing = false; // No known bugs, but needs performance testing\n\nvar enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber\n// stuff. Intended to enable React core members to more easily debug scheduling\n// issues in DEV builds.\n\nvar enableDebugTracing = false; // Track which Fiber(s) schedule render work.\n\nvar REACT_MODULE_REFERENCE;\n\n{\n REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');\n}\n\nfunction isValidElementType(type) {\n if (typeof type === 'string' || typeof type === 'function') {\n return true;\n } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).\n\n\n if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {\n return true;\n }\n\n if (typeof type === 'object' && type !== null) {\n if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object\n // types supported by any Flight configuration anywhere since\n // we don't know which Flight build this will end up being used\n // with.\n type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var displayName = outerType.displayName;\n\n if (displayName) {\n return displayName;\n }\n\n var functionName = innerType.displayName || innerType.name || '';\n return functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName;\n} // Keep in sync with react-reconciler/getComponentNameFromFiber\n\n\nfunction getContextName(type) {\n return type.displayName || 'Context';\n} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.\n\n\nfunction getComponentNameFromType(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return 'Profiler';\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n var context = type;\n return getContextName(context) + '.Consumer';\n\n case REACT_PROVIDER_TYPE:\n var provider = type;\n return getContextName(provider._context) + '.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n var outerName = type.displayName || null;\n\n if (outerName !== null) {\n return outerName;\n }\n\n return getComponentNameFromType(type.type) || 'Memo';\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n return getComponentNameFromType(init(payload));\n } catch (x) {\n return null;\n }\n }\n\n // eslint-disable-next-line no-fallthrough\n }\n }\n\n return null;\n}\n\nvar assign = Object.assign;\n\n// Helpers to patch console.logs to avoid logging during side-effect free\n// replaying on render function. This currently only patches the object\n// lazily which won't cover if the log function was extracted eagerly.\n// We could also eagerly patch the method.\nvar disabledDepth = 0;\nvar prevLog;\nvar prevInfo;\nvar prevWarn;\nvar prevError;\nvar prevGroup;\nvar prevGroupCollapsed;\nvar prevGroupEnd;\n\nfunction disabledLog() {}\n\ndisabledLog.__reactDisabledLog = true;\nfunction disableLogs() {\n {\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n prevLog = console.log;\n prevInfo = console.info;\n prevWarn = console.warn;\n prevError = console.error;\n prevGroup = console.group;\n prevGroupCollapsed = console.groupCollapsed;\n prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099\n\n var props = {\n configurable: true,\n enumerable: true,\n value: disabledLog,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n info: props,\n log: props,\n warn: props,\n error: props,\n group: props,\n groupCollapsed: props,\n groupEnd: props\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n disabledDepth++;\n }\n}\nfunction reenableLogs() {\n {\n disabledDepth--;\n\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n var props = {\n configurable: true,\n enumerable: true,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n log: assign({}, props, {\n value: prevLog\n }),\n info: assign({}, props, {\n value: prevInfo\n }),\n warn: assign({}, props, {\n value: prevWarn\n }),\n error: assign({}, props, {\n value: prevError\n }),\n group: assign({}, props, {\n value: prevGroup\n }),\n groupCollapsed: assign({}, props, {\n value: prevGroupCollapsed\n }),\n groupEnd: assign({}, props, {\n value: prevGroupEnd\n })\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n if (disabledDepth < 0) {\n error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');\n }\n }\n}\n\nvar ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;\nvar prefix;\nfunction describeBuiltInComponentFrame(name, source, ownerFn) {\n {\n if (prefix === undefined) {\n // Extract the VM specific prefix used by each line.\n try {\n throw Error();\n } catch (x) {\n var match = x.stack.trim().match(/\\n( *(at )?)/);\n prefix = match && match[1] || '';\n }\n } // We use the prefix to ensure our stacks line up with native stack frames.\n\n\n return '\\n' + prefix + name;\n }\n}\nvar reentry = false;\nvar componentFrameCache;\n\n{\n var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;\n componentFrameCache = new PossiblyWeakMap();\n}\n\nfunction describeNativeComponentFrame(fn, construct) {\n // If something asked for a stack inside a fake render, it should get ignored.\n if ( !fn || reentry) {\n return '';\n }\n\n {\n var frame = componentFrameCache.get(fn);\n\n if (frame !== undefined) {\n return frame;\n }\n }\n\n var control;\n reentry = true;\n var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.\n\n Error.prepareStackTrace = undefined;\n var previousDispatcher;\n\n {\n previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function\n // for warnings.\n\n ReactCurrentDispatcher.current = null;\n disableLogs();\n }\n\n try {\n // This should throw.\n if (construct) {\n // Something should be setting the props in the constructor.\n var Fake = function () {\n throw Error();\n }; // $FlowFixMe\n\n\n Object.defineProperty(Fake.prototype, 'props', {\n set: function () {\n // We use a throwing setter instead of frozen or non-writable props\n // because that won't throw in a non-strict mode function.\n throw Error();\n }\n });\n\n if (typeof Reflect === 'object' && Reflect.construct) {\n // We construct a different control for this case to include any extra\n // frames added by the construct call.\n try {\n Reflect.construct(Fake, []);\n } catch (x) {\n control = x;\n }\n\n Reflect.construct(fn, [], Fake);\n } else {\n try {\n Fake.call();\n } catch (x) {\n control = x;\n }\n\n fn.call(Fake.prototype);\n }\n } else {\n try {\n throw Error();\n } catch (x) {\n control = x;\n }\n\n fn();\n }\n } catch (sample) {\n // This is inlined manually because closure doesn't do it for us.\n if (sample && control && typeof sample.stack === 'string') {\n // This extracts the first frame from the sample that isn't also in the control.\n // Skipping one frame that we assume is the frame that calls the two.\n var sampleLines = sample.stack.split('\\n');\n var controlLines = control.stack.split('\\n');\n var s = sampleLines.length - 1;\n var c = controlLines.length - 1;\n\n while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {\n // We expect at least one stack frame to be shared.\n // Typically this will be the root most one. However, stack frames may be\n // cut off due to maximum stack limits. In this case, one maybe cut off\n // earlier than the other. We assume that the sample is longer or the same\n // and there for cut off earlier. So we should find the root most frame in\n // the sample somewhere in the control.\n c--;\n }\n\n for (; s >= 1 && c >= 0; s--, c--) {\n // Next we find the first one that isn't the same which should be the\n // frame that called our sample function and the control.\n if (sampleLines[s] !== controlLines[c]) {\n // In V8, the first line is describing the message but other VMs don't.\n // If we're about to return the first line, and the control is also on the same\n // line, that's a pretty good indicator that our sample threw at same line as\n // the control. I.e. before we entered the sample frame. So we ignore this result.\n // This can happen if you passed a class to function component, or non-function.\n if (s !== 1 || c !== 1) {\n do {\n s--;\n c--; // We may still have similar intermediate frames from the construct call.\n // The next one that isn't the same should be our match though.\n\n if (c < 0 || sampleLines[s] !== controlLines[c]) {\n // V8 adds a \"new\" prefix for native classes. Let's remove it to make it prettier.\n var _frame = '\\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled \"<anonymous>\"\n // but we have a user-provided \"displayName\"\n // splice it in to make the stack more readable.\n\n\n if (fn.displayName && _frame.includes('<anonymous>')) {\n _frame = _frame.replace('<anonymous>', fn.displayName);\n }\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, _frame);\n }\n } // Return the line we found.\n\n\n return _frame;\n }\n } while (s >= 1 && c >= 0);\n }\n\n break;\n }\n }\n }\n } finally {\n reentry = false;\n\n {\n ReactCurrentDispatcher.current = previousDispatcher;\n reenableLogs();\n }\n\n Error.prepareStackTrace = previousPrepareStackTrace;\n } // Fallback to just using the name if we couldn't make it throw.\n\n\n var name = fn ? fn.displayName || fn.name : '';\n var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, syntheticFrame);\n }\n }\n\n return syntheticFrame;\n}\nfunction describeFunctionComponentFrame(fn, source, ownerFn) {\n {\n return describeNativeComponentFrame(fn, false);\n }\n}\n\nfunction shouldConstruct(Component) {\n var prototype = Component.prototype;\n return !!(prototype && prototype.isReactComponent);\n}\n\nfunction describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {\n\n if (type == null) {\n return '';\n }\n\n if (typeof type === 'function') {\n {\n return describeNativeComponentFrame(type, shouldConstruct(type));\n }\n }\n\n if (typeof type === 'string') {\n return describeBuiltInComponentFrame(type);\n }\n\n switch (type) {\n case REACT_SUSPENSE_TYPE:\n return describeBuiltInComponentFrame('Suspense');\n\n case REACT_SUSPENSE_LIST_TYPE:\n return describeBuiltInComponentFrame('SuspenseList');\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_FORWARD_REF_TYPE:\n return describeFunctionComponentFrame(type.render);\n\n case REACT_MEMO_TYPE:\n // Memo may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n // Lazy may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);\n } catch (x) {}\n }\n }\n }\n\n return '';\n}\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar loggedTypeFailures = {};\nvar ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame.setExtraStackFrame(null);\n }\n }\n}\n\nfunction checkPropTypes(typeSpecs, values, location, componentName, element) {\n {\n // $FlowFixMe This is okay but Flow doesn't know it.\n var has = Function.call.bind(hasOwnProperty);\n\n for (var typeSpecName in typeSpecs) {\n if (has(typeSpecs, typeSpecName)) {\n var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n // eslint-disable-next-line react-internal/prod-error-codes\n var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');\n err.name = 'Invariant Violation';\n throw err;\n }\n\n error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');\n } catch (ex) {\n error$1 = ex;\n }\n\n if (error$1 && !(error$1 instanceof Error)) {\n setCurrentlyValidatingElement(element);\n\n error('%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).', componentName || 'React class', location, typeSpecName, typeof error$1);\n\n setCurrentlyValidatingElement(null);\n }\n\n if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error$1.message] = true;\n setCurrentlyValidatingElement(element);\n\n error('Failed %s type: %s', location, error$1.message);\n\n setCurrentlyValidatingElement(null);\n }\n }\n }\n }\n}\n\nvar isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare\n\nfunction isArray(a) {\n return isArrayImpl(a);\n}\n\n/*\n * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol\n * and Temporal.* types. See https://github.com/facebook/react/pull/22064.\n *\n * The functions in this module will throw an easier-to-understand,\n * easier-to-debug exception with a clear errors message message explaining the\n * problem. (Instead of a confusing exception thrown inside the implementation\n * of the `value` object).\n */\n// $FlowFixMe only called in DEV, so void return is not possible.\nfunction typeName(value) {\n {\n // toStringTag is needed for namespaced types like Temporal.Instant\n var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;\n var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';\n return type;\n }\n} // $FlowFixMe only called in DEV, so void return is not possible.\n\n\nfunction willCoercionThrow(value) {\n {\n try {\n testStringCoercion(value);\n return false;\n } catch (e) {\n return true;\n }\n }\n}\n\nfunction testStringCoercion(value) {\n // If you ended up here by following an exception call stack, here's what's\n // happened: you supplied an object or symbol value to React (as a prop, key,\n // DOM attribute, CSS property, string ref, etc.) and when React tried to\n // coerce it to a string using `'' + value`, an exception was thrown.\n //\n // The most common types that will cause this exception are `Symbol` instances\n // and Temporal objects like `Temporal.Instant`. But any object that has a\n // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this\n // exception. (Library authors do this to prevent users from using built-in\n // numeric operators like `+` or comparison operators like `>=` because custom\n // methods are needed to perform accurate arithmetic or comparison.)\n //\n // To fix the problem, coerce this object or symbol value to a string before\n // passing it to React. The most reliable way is usually `String(value)`.\n //\n // To find which value is throwing, check the browser or debugger console.\n // Before this exception was thrown, there should be `console.error` output\n // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the\n // problem and how that type was used: key, atrribute, input value prop, etc.\n // In most cases, this console output also shows the component and its\n // ancestor components where the exception happened.\n //\n // eslint-disable-next-line react-internal/safe-string-coercion\n return '' + value;\n}\nfunction checkKeyStringCoercion(value) {\n {\n if (willCoercionThrow(value)) {\n error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));\n\n return testStringCoercion(value); // throw (to help callers find troubleshooting comments)\n }\n }\n}\n\nvar ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;\nvar RESERVED_PROPS = {\n key: true,\n ref: true,\n __self: true,\n __source: true\n};\nvar specialPropKeyWarningShown;\nvar specialPropRefWarningShown;\nvar didWarnAboutStringRefs;\n\n{\n didWarnAboutStringRefs = {};\n}\n\nfunction hasValidRef(config) {\n {\n if (hasOwnProperty.call(config, 'ref')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.ref !== undefined;\n}\n\nfunction hasValidKey(config) {\n {\n if (hasOwnProperty.call(config, 'key')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'key').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.key !== undefined;\n}\n\nfunction warnIfStringRefCannotBeAutoConverted(config, self) {\n {\n if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {\n var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);\n\n if (!didWarnAboutStringRefs[componentName]) {\n error('Component \"%s\" contains the string ref \"%s\". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);\n\n didWarnAboutStringRefs[componentName] = true;\n }\n }\n }\n}\n\nfunction defineKeyPropWarningGetter(props, displayName) {\n {\n var warnAboutAccessingKey = function () {\n if (!specialPropKeyWarningShown) {\n specialPropKeyWarningShown = true;\n\n error('%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)', displayName);\n }\n };\n\n warnAboutAccessingKey.isReactWarning = true;\n Object.defineProperty(props, 'key', {\n get: warnAboutAccessingKey,\n configurable: true\n });\n }\n}\n\nfunction defineRefPropWarningGetter(props, displayName) {\n {\n var warnAboutAccessingRef = function () {\n if (!specialPropRefWarningShown) {\n specialPropRefWarningShown = true;\n\n error('%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)', displayName);\n }\n };\n\n warnAboutAccessingRef.isReactWarning = true;\n Object.defineProperty(props, 'ref', {\n get: warnAboutAccessingRef,\n configurable: true\n });\n }\n}\n/**\n * Factory method to create a new React element. This no longer adheres to\n * the class pattern, so do not use new to call it. Also, instanceof check\n * will not work. Instead test $$typeof field against Symbol.for('react.element') to check\n * if something is a React Element.\n *\n * @param {*} type\n * @param {*} props\n * @param {*} key\n * @param {string|object} ref\n * @param {*} owner\n * @param {*} self A *temporary* helper to detect places where `this` is\n * different from the `owner` when React.createElement is called, so that we\n * can warn. We want to get rid of owner and replace string `ref`s with arrow\n * functions, and as long as `this` and owner are the same, there will be no\n * change in behavior.\n * @param {*} source An annotation object (added by a transpiler or otherwise)\n * indicating filename, line number, and/or other information.\n * @internal\n */\n\n\nvar ReactElement = function (type, key, ref, self, source, owner, props) {\n var element = {\n // This tag allows us to uniquely identify this as a React Element\n $$typeof: REACT_ELEMENT_TYPE,\n // Built-in properties that belong on the element\n type: type,\n key: key,\n ref: ref,\n props: props,\n // Record the component responsible for creating this element.\n _owner: owner\n };\n\n {\n // The validation flag is currently mutative. We put it on\n // an external backing store so that we can freeze the whole object.\n // This can be replaced with a WeakMap once they are implemented in\n // commonly used development environments.\n element._store = {}; // To make comparing ReactElements easier for testing purposes, we make\n // the validation flag non-enumerable (where possible, which should\n // include every environment we run tests in), so the test framework\n // ignores it.\n\n Object.defineProperty(element._store, 'validated', {\n configurable: false,\n enumerable: false,\n writable: true,\n value: false\n }); // self and source are DEV only properties.\n\n Object.defineProperty(element, '_self', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: self\n }); // Two elements created in two different places should be considered\n // equal for testing purposes and therefore we hide it from enumeration.\n\n Object.defineProperty(element, '_source', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: source\n });\n\n if (Object.freeze) {\n Object.freeze(element.props);\n Object.freeze(element);\n }\n }\n\n return element;\n};\n/**\n * https://github.com/reactjs/rfcs/pull/107\n * @param {*} type\n * @param {object} props\n * @param {string} key\n */\n\nfunction jsxDEV(type, config, maybeKey, source, self) {\n {\n var propName; // Reserved names are extracted\n\n var props = {};\n var key = null;\n var ref = null; // Currently, key can be spread in as a prop. This causes a potential\n // issue if key is also explicitly declared (ie. <div {...props} key=\"Hi\" />\n // or <div key=\"Hi\" {...props} /> ). We want to deprecate key spread,\n // but as an intermediary step, we will use jsxDEV for everything except\n // <div {...props} key=\"Hi\" />, because we aren't currently able to tell if\n // key is explicitly declared to be undefined or not.\n\n if (maybeKey !== undefined) {\n {\n checkKeyStringCoercion(maybeKey);\n }\n\n key = '' + maybeKey;\n }\n\n if (hasValidKey(config)) {\n {\n checkKeyStringCoercion(config.key);\n }\n\n key = '' + config.key;\n }\n\n if (hasValidRef(config)) {\n ref = config.ref;\n warnIfStringRefCannotBeAutoConverted(config, self);\n } // Remaining properties are added to a new props object\n\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n props[propName] = config[propName];\n }\n } // Resolve default props\n\n\n if (type && type.defaultProps) {\n var defaultProps = type.defaultProps;\n\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n }\n\n if (key || ref) {\n var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;\n\n if (key) {\n defineKeyPropWarningGetter(props, displayName);\n }\n\n if (ref) {\n defineRefPropWarningGetter(props, displayName);\n }\n }\n\n return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);\n }\n}\n\nvar ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement$1(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame$1.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame$1.setExtraStackFrame(null);\n }\n }\n}\n\nvar propTypesMisspellWarningShown;\n\n{\n propTypesMisspellWarningShown = false;\n}\n/**\n * Verifies the object is a ReactElement.\n * See https://reactjs.org/docs/react-api.html#isvalidelement\n * @param {?object} object\n * @return {boolean} True if `object` is a ReactElement.\n * @final\n */\n\n\nfunction isValidElement(object) {\n {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n }\n}\n\nfunction getDeclarationErrorAddendum() {\n {\n if (ReactCurrentOwner$1.current) {\n var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);\n\n if (name) {\n return '\\n\\nCheck the render method of `' + name + '`.';\n }\n }\n\n return '';\n }\n}\n\nfunction getSourceInfoErrorAddendum(source) {\n {\n if (source !== undefined) {\n var fileName = source.fileName.replace(/^.*[\\\\\\/]/, '');\n var lineNumber = source.lineNumber;\n return '\\n\\nCheck your code at ' + fileName + ':' + lineNumber + '.';\n }\n\n return '';\n }\n}\n/**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n\nvar ownerHasKeyUseWarning = {};\n\nfunction getCurrentComponentErrorInfo(parentType) {\n {\n var info = getDeclarationErrorAddendum();\n\n if (!info) {\n var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;\n\n if (parentName) {\n info = \"\\n\\nCheck the top-level render call using <\" + parentName + \">.\";\n }\n }\n\n return info;\n }\n}\n/**\n * Warn if the element doesn't have an explicit key assigned to it.\n * This element is in an array. The array could grow and shrink or be\n * reordered. All children that haven't already been validated are required to\n * have a \"key\" property assigned to it. Error statuses are cached so a warning\n * will only be shown once.\n *\n * @internal\n * @param {ReactElement} element Element that requires a key.\n * @param {*} parentType element's parent's type.\n */\n\n\nfunction validateExplicitKey(element, parentType) {\n {\n if (!element._store || element._store.validated || element.key != null) {\n return;\n }\n\n element._store.validated = true;\n var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);\n\n if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a\n // property, it may be the creator of the child that's responsible for\n // assigning it a key.\n\n var childOwner = '';\n\n if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {\n // Give the component that originally created this child.\n childOwner = \" It was passed a child from \" + getComponentNameFromType(element._owner.type) + \".\";\n }\n\n setCurrentlyValidatingElement$1(element);\n\n error('Each child in a list should have a unique \"key\" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);\n\n setCurrentlyValidatingElement$1(null);\n }\n}\n/**\n * Ensure that every element either is passed in a static location, in an\n * array with an explicit keys property defined, or in an object literal\n * with valid key property.\n *\n * @internal\n * @param {ReactNode} node Statically passed child of any type.\n * @param {*} parentType node's parent's type.\n */\n\n\nfunction validateChildKeys(node, parentType) {\n {\n if (typeof node !== 'object') {\n return;\n }\n\n if (isArray(node)) {\n for (var i = 0; i < node.length; i++) {\n var child = node[i];\n\n if (isValidElement(child)) {\n validateExplicitKey(child, parentType);\n }\n }\n } else if (isValidElement(node)) {\n // This element was passed in a valid location.\n if (node._store) {\n node._store.validated = true;\n }\n } else if (node) {\n var iteratorFn = getIteratorFn(node);\n\n if (typeof iteratorFn === 'function') {\n // Entry iterators used to provide implicit keys,\n // but now we print a separate warning for them later.\n if (iteratorFn !== node.entries) {\n var iterator = iteratorFn.call(node);\n var step;\n\n while (!(step = iterator.next()).done) {\n if (isValidElement(step.value)) {\n validateExplicitKey(step.value, parentType);\n }\n }\n }\n }\n }\n }\n}\n/**\n * Given an element, validate that its props follow the propTypes definition,\n * provided by the type.\n *\n * @param {ReactElement} element\n */\n\n\nfunction validatePropTypes(element) {\n {\n var type = element.type;\n\n if (type === null || type === undefined || typeof type === 'string') {\n return;\n }\n\n var propTypes;\n\n if (typeof type === 'function') {\n propTypes = type.propTypes;\n } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.\n // Inner props are checked in the reconciler.\n type.$$typeof === REACT_MEMO_TYPE)) {\n propTypes = type.propTypes;\n } else {\n return;\n }\n\n if (propTypes) {\n // Intentionally inside to avoid triggering lazy initializers:\n var name = getComponentNameFromType(type);\n checkPropTypes(propTypes, element.props, 'prop', name, element);\n } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {\n propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:\n\n var _name = getComponentNameFromType(type);\n\n error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');\n }\n\n if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');\n }\n }\n}\n/**\n * Given a fragment, validate that it can only be provided with fragment props\n * @param {ReactElement} fragment\n */\n\n\nfunction validateFragmentProps(fragment) {\n {\n var keys = Object.keys(fragment.props);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n\n if (key !== 'children' && key !== 'key') {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);\n\n setCurrentlyValidatingElement$1(null);\n break;\n }\n }\n\n if (fragment.ref !== null) {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid attribute `ref` supplied to `React.Fragment`.');\n\n setCurrentlyValidatingElement$1(null);\n }\n }\n}\n\nvar didWarnAboutKeySpread = {};\nfunction jsxWithValidation(type, props, key, isStaticChildren, source, self) {\n {\n var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to\n // succeed and there will likely be errors in render.\n\n if (!validType) {\n var info = '';\n\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and named imports.\";\n }\n\n var sourceInfo = getSourceInfoErrorAddendum(source);\n\n if (sourceInfo) {\n info += sourceInfo;\n } else {\n info += getDeclarationErrorAddendum();\n }\n\n var typeString;\n\n if (type === null) {\n typeString = 'null';\n } else if (isArray(type)) {\n typeString = 'array';\n } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {\n typeString = \"<\" + (getComponentNameFromType(type.type) || 'Unknown') + \" />\";\n info = ' Did you accidentally export a JSX literal instead of a component?';\n } else {\n typeString = typeof type;\n }\n\n error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);\n }\n\n var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.\n // TODO: Drop this when these are no longer allowed as the type argument.\n\n if (element == null) {\n return element;\n } // Skip key warning if the type isn't valid since our key validation logic\n // doesn't expect a non-string/function type and can throw confusing errors.\n // We don't want exception behavior to differ between dev and prod.\n // (Rendering will throw with a helpful message and as soon as the type is\n // fixed, the key warnings will appear.)\n\n\n if (validType) {\n var children = props.children;\n\n if (children !== undefined) {\n if (isStaticChildren) {\n if (isArray(children)) {\n for (var i = 0; i < children.length; i++) {\n validateChildKeys(children[i], type);\n }\n\n if (Object.freeze) {\n Object.freeze(children);\n }\n } else {\n error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');\n }\n } else {\n validateChildKeys(children, type);\n }\n }\n }\n\n {\n if (hasOwnProperty.call(props, 'key')) {\n var componentName = getComponentNameFromType(type);\n var keys = Object.keys(props).filter(function (k) {\n return k !== 'key';\n });\n var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';\n\n if (!didWarnAboutKeySpread[componentName + beforeExample]) {\n var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';\n\n error('A props object containing a \"key\" prop is being spread into JSX:\\n' + ' let props = %s;\\n' + ' <%s {...props} />\\n' + 'React keys must be passed directly to JSX without using spread:\\n' + ' let props = %s;\\n' + ' <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);\n\n didWarnAboutKeySpread[componentName + beforeExample] = true;\n }\n }\n }\n\n if (type === REACT_FRAGMENT_TYPE) {\n validateFragmentProps(element);\n } else {\n validatePropTypes(element);\n }\n\n return element;\n }\n} // These two functions exist to still get child warnings in dev\n// even with the prod transform. This means that jsxDEV is purely\n// opt-in behavior for better messages but that we won't stop\n// giving you warnings if you use production apis.\n\nfunction jsxWithValidationStatic(type, props, key) {\n {\n return jsxWithValidation(type, props, key, true);\n }\n}\nfunction jsxWithValidationDynamic(type, props, key) {\n {\n return jsxWithValidation(type, props, key, false);\n }\n}\n\nvar jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.\n// for now we can ship identical prod functions\n\nvar jsxs = jsxWithValidationStatic ;\n\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsx;\nexports.jsxs = jsxs;\n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.min.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f)}else for(f in e)e[f]&&(n&&(n+=\" \"),n+=f);return n}export function clsx(){for(var e,t,f=0,n=\"\",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;","export interface PaymentsConfig {\n baseUrl: string;\n /**\n * Base URL for Movmo's payment-icon assets (Visa / MC / Amex / Discover SVGs\n * + PayPal / GooglePay / Klarna PNGs). Defaults to the e2e CDN; prod\n * consumers should override at boot once a prod CDN is set up.\n */\n iconCdnBaseUrl?: string;\n /**\n * Custom `fetch` impl used by every API call in this package. Defaults to\n * `globalThis.fetch`. Consumers that need auth-token refresh, CSRF-token\n * injection, or any other request-shaping logic should provide their own\n * wrapper here (e.g. one that retries on 401/403 after refreshing the\n * session cookie). The package never adds business headers — that's the\n * consumer's responsibility.\n */\n fetch?: typeof fetch;\n}\n\n/** @internal — surfaced as `PaymentsConfig & { spreedlyScriptUrl }` only for tests + the script loader. */\ninterface InternalPaymentsConfig extends PaymentsConfig {\n spreedlyScriptUrl: string;\n iconCdnBaseUrl: string;\n fetch: typeof fetch;\n}\n\nconst DEFAULT_SPREEDLY_SCRIPT_URL = 'https://core.spreedly.com/iframe/iframe-v1.min.js';\nconst DEFAULT_ICON_CDN_BASE_URL = 'https://cdn.e2e.movmo.io';\n\nlet overrides: Partial<InternalPaymentsConfig> = {};\n\nexport const setPaymentsConfig = (config: Partial<PaymentsConfig>): void => {\n overrides = { ...overrides, ...config };\n};\n\nconst readEnv = (key: string): string | undefined => {\n // `process.env` is the conventional carrier for `REACT_APP_*` config in\n // consumers built with CRA / Vite / Webpack — those bundlers replace\n // `process.env.X` at build time, so this is type-only access at runtime.\n const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;\n return proc?.env?.[key];\n};\n\nexport const getPaymentsConfig = (): InternalPaymentsConfig => ({\n baseUrl: overrides.baseUrl ?? readEnv('REACT_APP_MOVMO_API_URL') ?? '',\n spreedlyScriptUrl:\n overrides.spreedlyScriptUrl ??\n readEnv('REACT_APP_SPREEDLY_SCRIPT_URL') ??\n DEFAULT_SPREEDLY_SCRIPT_URL,\n iconCdnBaseUrl:\n overrides.iconCdnBaseUrl ??\n readEnv('REACT_APP_MOVMO_ICON_CDN_URL') ??\n DEFAULT_ICON_CDN_BASE_URL,\n fetch:\n overrides.fetch ??\n (typeof globalThis !== 'undefined' && typeof globalThis.fetch === 'function'\n ? globalThis.fetch.bind(globalThis)\n : (() => {\n throw new Error('@movmo_app/payments: no fetch available');\n })()),\n});\n\n/** Reset overrides — used by tests and Storybook decorators. */\nexport const __resetPaymentsConfig = (): void => {\n overrides = {};\n};\n","import { getPaymentsConfig } from './config';\nimport type { PaymentMethodSummary, TokenizationSession } from './types';\n\ninterface PaymentMethodResponse {\n id: string;\n last4: string;\n brand: string;\n expMonth: number;\n expYear: number;\n isDefault: boolean;\n}\n\nconst toSummary = (body: PaymentMethodResponse): PaymentMethodSummary => ({\n id: body.id,\n last4: body.last4,\n brand: body.brand,\n expMonth: body.expMonth,\n expYear: body.expYear,\n isDefault: body.isDefault,\n});\n\nconst jsonHeaders: HeadersInit = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n};\n\nconst apiUrl = (path: string): string => {\n const { baseUrl } = getPaymentsConfig();\n if (!baseUrl) {\n throw new Error(\n '@movmo_app/payments: baseUrl is not configured. Call setPaymentsConfig({ baseUrl }) at app boot, or set REACT_APP_MOVMO_API_URL.',\n );\n }\n return `${baseUrl}${path}`;\n};\n\n/** Runs every fetch through the consumer-supplied `fetch` (falls back to `globalThis.fetch`). */\nconst performFetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const { fetch: configuredFetch } = getPaymentsConfig();\n return configuredFetch(input, init);\n};\n\nconst readError = async (res: Response, fallback: string): Promise<string> => {\n try {\n const body = (await res.json()) as { message?: string };\n return body.message || fallback;\n } catch {\n return fallback;\n }\n};\n\n/**\n * In-flight request cache for the tokenization session. React 18 StrictMode\n * mounts useMovmoCardFields twice in development, and the modal+inline form\n * can both mount briefly during the initial loading flash. Without this, the\n * same GET fires 2-4 times back-to-back. Concurrent callers receive the same\n * promise; once it settles (success or failure) the cache is cleared.\n *\n * Important: clear via `.finally()` AFTER assigning the cache. A `try/finally`\n * inside the async IIFE would clear the slot synchronously when the body\n * throws (apiUrl baseUrl-guard), then the outer assignment overwrites the\n * null with the rejected promise — leaking it into the next caller.\n */\nlet inFlightTokenizationSession: Promise<TokenizationSession> | null = null;\n\nexport const fetchTokenizationSession = (): Promise<TokenizationSession> => {\n if (inFlightTokenizationSession) return inFlightTokenizationSession;\n const promise = (async () => {\n const res = await performFetch(apiUrl('/v1/payments/tokenization-session'), {\n method: 'GET',\n headers: jsonHeaders,\n credentials: 'include',\n });\n if (!res.ok) {\n throw new Error(\n await readError(res, `Failed to fetch tokenization session (${res.status})`),\n );\n }\n return (await res.json()) as TokenizationSession;\n })();\n inFlightTokenizationSession = promise;\n promise\n .finally(() => {\n // Only clear the slot if nothing newer has replaced it.\n if (inFlightTokenizationSession === promise) {\n inFlightTokenizationSession = null;\n }\n })\n .catch(() => {\n /* swallow — the original rejection still propagates via `promise` itself */\n });\n return promise;\n};\n\n/**\n * True when the response body has enough data to render a full\n * PaymentMethodSummary card row (brand + last4 + exp). monolith-api's POST\n * `/from-token` currently returns only `{ id }` — when that happens, the\n * caller of this helper falls back to a GET by id so the consumer never sees\n * a partial record (which would crash render with `brand.toLowerCase`).\n */\nconst isFullPaymentMethodBody = (\n body: Partial<PaymentMethodResponse> & { id: string },\n): body is PaymentMethodResponse =>\n typeof body.brand === 'string' &&\n typeof body.last4 === 'string' &&\n typeof body.expMonth === 'number' &&\n typeof body.expYear === 'number';\n\nexport const savePaymentMethodFromToken = async (\n userId: string,\n tokenizedPaymentMethodId: string,\n isDefault: boolean,\n): Promise<PaymentMethodSummary> => {\n const res = await performFetch(\n apiUrl(`/v1/users/${encodeURIComponent(userId)}/payment-methods/from-token`),\n {\n method: 'POST',\n headers: jsonHeaders,\n credentials: 'include',\n body: JSON.stringify({ tokenizedPaymentMethodId, isDefault }),\n },\n );\n if (!res.ok) {\n throw new Error(await readError(res, `Failed to save payment method (${res.status})`));\n }\n const body = (await res.json()) as Partial<PaymentMethodResponse> & { id: string };\n if (isFullPaymentMethodBody(body)) {\n return toSummary(body);\n }\n // monolith-api returned a thin `{ id }` — load the full record so the\n // consumer's optimistic-insert + row render has brand/last4/exp.\n const getRes = await performFetch(\n apiUrl(\n `/v1/users/${encodeURIComponent(userId)}/payment-methods/${encodeURIComponent(body.id)}`,\n ),\n {\n method: 'GET',\n headers: jsonHeaders,\n credentials: 'include',\n },\n );\n if (!getRes.ok) {\n throw new Error(\n await readError(getRes, `Failed to fetch saved payment method (${getRes.status})`),\n );\n }\n const fullBody = (await getRes.json()) as PaymentMethodResponse;\n return toSummary(fullBody);\n};\n\nexport const listPaymentMethods = async (\n userId: string,\n signal?: AbortSignal,\n): Promise<PaymentMethodSummary[]> => {\n const res = await performFetch(apiUrl(`/v1/users/${encodeURIComponent(userId)}/payment-methods`), {\n method: 'GET',\n headers: jsonHeaders,\n credentials: 'include',\n signal,\n });\n if (!res.ok) {\n throw new Error(await readError(res, `Failed to fetch payment methods (${res.status})`));\n }\n const body = (await res.json()) as PaymentMethodResponse[] | null;\n // Drops legacy Stripe holdover fields (customerId, paymentMethodId, token)\n // that monolith-api still returns pre-MOVMO-368.\n return (body ?? []).map(toSummary);\n};\n\nexport const deletePaymentMethod = async (userId: string, methodId: string): Promise<void> => {\n const res = await performFetch(\n apiUrl(\n `/v1/users/${encodeURIComponent(userId)}/payment-methods/${encodeURIComponent(methodId)}`,\n ),\n {\n method: 'DELETE',\n headers: jsonHeaders,\n credentials: 'include',\n },\n );\n if (!res.ok) {\n throw new Error(await readError(res, `Failed to delete payment method (${res.status})`));\n }\n};\n\nexport const updatePaymentMethod = async (\n userId: string,\n methodId: string,\n patch: { isDefault?: boolean },\n): Promise<void> => {\n const res = await performFetch(\n apiUrl(\n `/v1/users/${encodeURIComponent(userId)}/payment-methods/${encodeURIComponent(methodId)}`,\n ),\n {\n method: 'PUT',\n headers: jsonHeaders,\n credentials: 'include',\n body: JSON.stringify(patch),\n },\n );\n if (!res.ok) {\n throw new Error(await readError(res, `Failed to update payment method (${res.status})`));\n }\n};\n","import type { ReactElement } from 'react';\n\nimport { getPaymentsConfig } from '../config';\n\n/**\n * Spreedly's BIN detection emits 'master' / 'american_express' / etc. — map\n * to the file slugs used on Movmo's icon CDN.\n */\nconst BRAND_SLUG: Record<string, string> = {\n visa: 'visa',\n master: 'mastercard',\n mastercard: 'mastercard',\n american_express: 'amex',\n amex: 'amex',\n discover: 'discover',\n};\n\ninterface CardBrandIconProps {\n brand: string;\n className?: string;\n /**\n * Size hint in px. Floored at MIN_RENDER_WIDTH so callers passing small\n * values (e.g. 24 from inside the card-number field shell) still get a\n * legible brand mark. Height auto-scales 24:34 to match the source SVG\n * viewBox so the glyph isn't distorted.\n */\n width?: number;\n}\n\n/** Anything below this looks too cramped against the SVGs' internal padding. */\nconst MIN_RENDER_WIDTH = 28;\n\n/**\n * Renders the official brand mark from Movmo's icon CDN\n * (`<iconCdnBaseUrl>/website/assets/icons/payments/<brand>.svg`).\n *\n * Brand is determined by Spreedly's hosted-fields BIN detection (the\n * `cardType` field on `fieldEvent` payloads — visa/master/american_express/\n * discover/etc.) — same approach Stripe uses. Unknown / not-yet-detected\n * brands render the generic `credit-card.svg` placeholder so the layout\n * doesn't collapse before the user has typed enough digits.\n */\nexport const CardBrandIcon = ({\n brand,\n className,\n width = 46,\n}: CardBrandIconProps): ReactElement => {\n const slug = brand ? (BRAND_SLUG[brand.toLowerCase()] ?? 'credit-card') : 'credit-card';\n const renderWidth = Math.max(width, MIN_RENDER_WIDTH);\n const renderHeight = Math.round((renderWidth * 24) / 34);\n const { iconCdnBaseUrl } = getPaymentsConfig();\n return (\n <img\n src={`${iconCdnBaseUrl}/website/assets/icons/payments/${slug}.svg`}\n alt={slug === 'credit-card' ? 'card' : `${slug} card`}\n data-testid={`card-brand-${brand.toLowerCase()}`}\n className={className}\n width={renderWidth}\n height={renderHeight}\n loading=\"lazy\"\n />\n );\n};\n","import type { SpreedlyGlobal } from './spreedly-global';\nimport { getPaymentsConfig } from './config';\n\nlet scriptPromise: Promise<SpreedlyGlobal> | null = null;\n\n/**\n * Idempotently inject the Spreedly iframe SDK script and resolve with the\n * `window.Spreedly` global. Subsequent calls return the same promise.\n */\nexport const loadSpreedlyScript = (): Promise<SpreedlyGlobal> => {\n if (typeof window === 'undefined') {\n return Promise.reject(new Error('Spreedly can only be loaded in a browser environment.'));\n }\n if (window.Spreedly) {\n return Promise.resolve(window.Spreedly);\n }\n if (scriptPromise) {\n return scriptPromise;\n }\n\n const { spreedlyScriptUrl } = getPaymentsConfig();\n\n scriptPromise = new Promise<SpreedlyGlobal>((resolve, reject) => {\n const existing = document.querySelector<HTMLScriptElement>(\n `script[src=\"${spreedlyScriptUrl}\"]`,\n );\n\n const onScriptLoad = () => {\n if (window.Spreedly) {\n resolve(window.Spreedly);\n } else {\n reject(new Error('Spreedly script loaded but window.Spreedly is undefined.'));\n }\n };\n\n if (existing) {\n if (window.Spreedly) {\n onScriptLoad();\n return;\n }\n existing.addEventListener('load', onScriptLoad, { once: true });\n existing.addEventListener(\n 'error',\n () => {\n existing.remove();\n reject(new Error('Failed to load Spreedly iframe script.'));\n },\n { once: true },\n );\n return;\n }\n\n const script = document.createElement('script');\n script.src = spreedlyScriptUrl;\n script.async = true;\n script.onload = onScriptLoad;\n script.onerror = () => {\n // Without removing the failed tag, the next call hits the `existing`\n // branch above and attaches listeners to a script that already errored —\n // the promise would never resolve.\n script.remove();\n reject(new Error('Failed to load Spreedly iframe script.'));\n };\n document.head.appendChild(script);\n }).catch((err) => {\n scriptPromise = null;\n throw err;\n });\n\n return scriptPromise;\n};\n\nexport const __resetSpreedlyScriptCache = (): void => {\n scriptPromise = null;\n};\n","import { useCallback, useEffect, useRef, useState } from 'react';\n\nimport { fetchTokenizationSession } from './api';\nimport { loadSpreedlyScript } from './loadSpreedlyScript';\nimport type { SpreedlyGlobal, SpreedlyTokenizeData } from './spreedly-global';\nimport type { CardFieldError } from './types';\n\nexport interface CardholderTokenizeData {\n firstName: string;\n lastName: string;\n /** Two-digit month, e.g. \"01\"–\"12\". */\n month: string;\n /** Four-digit year, e.g. \"2030\". */\n year: string;\n email?: string;\n zip?: string;\n}\n\nexport interface CardFieldValidity {\n /** True only when the card-number field has a complete, length-valid value. */\n number: boolean;\n /** True only when the CVV field has a complete value (3 or 4 digits). */\n cvv: boolean;\n}\n\n/**\n * Focus state of each Spreedly-hosted iframe. The browser's `focus-within`\n * CSS pseudo-class can't see across iframe boundaries, so the consumer needs\n * an explicit signal to render the \"active border\" on the iframe shell.\n */\nexport interface CardFieldFocus {\n number: boolean;\n cvv: boolean;\n}\n\nexport interface UseMovmoCardFieldsOptions {\n /** DOM element id where the card-number field mounts. Defaults to `movmo-card-number`. */\n numberEl?: string;\n /** DOM element id where the CVV field mounts. Defaults to `movmo-card-cvv`. */\n cvvEl?: string;\n onCardTokenized?: (token: string) => void;\n onFieldErrors?: (errors: CardFieldError[]) => void;\n /**\n * Fires whenever per-field validity changes (number length valid, CVV length valid).\n * Use to gate the save button at the form layer.\n */\n onValidityChange?: (validity: CardFieldValidity) => void;\n /**\n * Fires whenever the detected card brand changes (visa/master/american_express/discover/etc).\n * Use to render the brand icon inline with the card-number field.\n */\n onBrandChange?: (brand: string | null) => void;\n}\n\nexport interface UseMovmoCardFieldsResult {\n status: 'idle' | 'loading' | 'ready' | 'error';\n error: string | null;\n tokenize: (data: CardholderTokenizeData) => void;\n /** Latest validity snapshot — also pushed via `onValidityChange`. */\n validity: CardFieldValidity;\n /** Latest detected brand (or null if unknown). */\n brand: string | null;\n /**\n * Live focus state for each iframe. True while the user is editing that\n * field. Consumers use this to apply an \"active\" border on the iframe shell\n * (the browser's `:focus-within` CSS doesn't propagate across iframes).\n */\n focused: CardFieldFocus;\n /**\n * Programmatically move keyboard focus into one of the Spreedly iframes.\n * No-op when the hook is not in the `'ready'` state. Used to auto-advance\n * focus from an outer form input (e.g. expiry) into a hosted field (CVV).\n */\n focusField: (field: 'number' | 'cvv') => void;\n}\n\nconst DEFAULT_NUMBER_EL = 'movmo-card-number';\nconst DEFAULT_CVV_EL = 'movmo-card-cvv';\n\nconst toSdkPayload = (data: CardholderTokenizeData): SpreedlyTokenizeData => ({\n first_name: data.firstName,\n last_name: data.lastName,\n month: data.month,\n year: data.year,\n ...(data.email ? { email: data.email } : {}),\n ...(data.zip ? { zip: data.zip } : {}),\n});\n\n/**\n * Mounts PCI-safe card-capture fields into the DOM containers identified by\n * `numberEl` and `cvvEl`, fetches a signed tokenization session from\n * monolith-api, and exposes a `tokenize()` function that returns an opaque\n * vault token via the `onCardTokenized` callback.\n *\n * The vault implementation (Spreedly Hosted Fields) is intentionally not part\n * of the public surface — callers receive a vault-neutral token they hand back\n * to monolith-api, which derives card metadata server-side.\n */\nexport const useMovmoCardFields = (\n options: UseMovmoCardFieldsOptions = {},\n): UseMovmoCardFieldsResult => {\n const {\n numberEl = DEFAULT_NUMBER_EL,\n cvvEl = DEFAULT_CVV_EL,\n onCardTokenized,\n onFieldErrors,\n onValidityChange,\n onBrandChange,\n } = options;\n\n const [status, setStatus] = useState<UseMovmoCardFieldsResult['status']>('idle');\n const [error, setError] = useState<string | null>(null);\n const [validity, setValidity] = useState<CardFieldValidity>({ number: false, cvv: false });\n const [brand, setBrand] = useState<string | null>(null);\n const [focused, setFocused] = useState<CardFieldFocus>({ number: false, cvv: false });\n const spreedlyRef = useRef<SpreedlyGlobal | null>(null);\n\n const onCardTokenizedRef = useRef(onCardTokenized);\n const onFieldErrorsRef = useRef(onFieldErrors);\n const onValidityChangeRef = useRef(onValidityChange);\n const onBrandChangeRef = useRef(onBrandChange);\n useEffect(() => {\n onCardTokenizedRef.current = onCardTokenized;\n }, [onCardTokenized]);\n useEffect(() => {\n onFieldErrorsRef.current = onFieldErrors;\n }, [onFieldErrors]);\n useEffect(() => {\n onValidityChangeRef.current = onValidityChange;\n }, [onValidityChange]);\n useEffect(() => {\n onBrandChangeRef.current = onBrandChange;\n }, [onBrandChange]);\n\n // Latest validity is kept in a ref so the fieldEvent handler can read the\n // previous value without re-binding the listener on every state change.\n const validityRef = useRef<CardFieldValidity>({ number: false, cvv: false });\n\n useEffect(() => {\n let cancelled = false;\n setStatus('loading');\n setError(null);\n setValidity({ number: false, cvv: false });\n setBrand(null);\n validityRef.current = { number: false, cvv: false };\n\n (async () => {\n try {\n const [session, spreedly] = await Promise.all([\n fetchTokenizationSession(),\n loadSpreedlyScript(),\n ]);\n if (cancelled) return;\n\n // Assign the ref before registering handlers so the cleanup can always\n // call removeHandlers — even if unmount runs before the 'ready' event\n // fires. window.Spreedly is a module-scoped singleton, so leaked\n // handlers would otherwise fire on the next mount.\n spreedlyRef.current = spreedly;\n\n spreedly.on('ready', () => {\n if (cancelled) return;\n setStatus('ready');\n // Tell Spreedly the field expects digits — improves mobile\n // keyboard + lets the SDK apply numeric-friendly formatting.\n try {\n spreedly.setFieldType?.('number', 'tel');\n spreedly.setFieldType?.('cvv', 'tel');\n } catch {\n /* no-op */\n }\n // Pretty-format the card number into 4-digit groups as the user types.\n // Surface a console.warn when the Spreedly build doesn't expose the\n // method (silent no-op was hiding the cause of a \"no spaces in the\n // typed digits\" bug).\n try {\n if (typeof spreedly.setNumberFormat === 'function') {\n spreedly.setNumberFormat('prettyFormat');\n } else {\n console.warn(\n '@movmo_app/payments: Spreedly.setNumberFormat is missing — card-number digits will not be space-grouped.',\n );\n }\n } catch (err) {\n console.warn('@movmo_app/payments: setNumberFormat failed', err);\n }\n // Spreedly's hosted-fields iframes render *empty* by default — no\n // placeholder, no inherited styling. Without the calls below the\n // user sees a blank box and can't tell where to click. Mirror the\n // outer form's text-sm/grayWarm-900 styling exactly so the iframe\n // input visually matches the expiry, ZIP, and cardholder inputs.\n // `line-height: 20px` (Tailwind text-sm's line-height) +\n // `vertical-align: middle` keep the typed digits vertically\n // centered in the 28-px iframe content area (44px shell − py-2).\n try {\n spreedly.setPlaceholder?.('number', 'Card number');\n spreedly.setPlaceholder?.('cvv', 'CVV');\n const iframeFontStyle =\n 'box-sizing: border-box;' +\n 'width: 100%;' +\n 'height: 100%;' +\n 'margin: 0;' +\n 'padding: 0;' +\n 'border: 0;' +\n 'background: transparent;' +\n 'outline: none;' +\n 'font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif;' +\n 'font-size: 14px;' +\n 'font-weight: 400;' +\n 'line-height: 20px;' +\n 'color: rgb(28 25 23);' +\n 'letter-spacing: 0;' +\n 'vertical-align: middle;';\n spreedly.setStyle?.('number', iframeFontStyle);\n spreedly.setStyle?.('cvv', iframeFontStyle);\n } catch {\n /* no-op — older Spreedly builds may omit these helpers */\n }\n });\n\n spreedly.on('paymentMethod', (token) => {\n onCardTokenizedRef.current?.(token);\n });\n\n spreedly.on('errors', (errors) => {\n onFieldErrorsRef.current?.(errors);\n });\n\n // Spreedly's hosted-fields v1: fieldEvent fires with FOUR positional\n // args (name, type, activeEl, inputProperties). The `inputProperties`\n // object is only populated on `type === 'input'` — focus/blur/etc.\n // pass `{}`. Brand + validity all live on inputProperties.\n // See https://developer.spreedly.com/docs/iframe-events\n spreedly.on('fieldEvent', (name, type, _activeEl, inputProperties) => {\n if (cancelled) return;\n // Mirror iframe focus into React state so consumers can render an\n // active-border equivalent — `:focus-within` CSS doesn't cross\n // iframe boundaries.\n if (type === 'focus') {\n setFocused((prev) => (prev[name] ? prev : { ...prev, [name]: true }));\n return;\n }\n if (type === 'blur') {\n setFocused((prev) => (prev[name] ? { ...prev, [name]: false } : prev));\n return;\n }\n if (type !== 'input') return;\n const props = inputProperties ?? {};\n\n if (name === 'number') {\n // Spreedly only includes cardType once the BIN is unambiguous.\n // Treat absence as \"unknown\" but only after the user starts typing.\n if (props.numberLength === 0) {\n setBrand((prev) => {\n if (prev !== null) onBrandChangeRef.current?.(null);\n return null;\n });\n } else if (props.cardType !== undefined) {\n const next = props.cardType || null;\n setBrand((prev) => {\n if (prev !== next) onBrandChangeRef.current?.(next);\n return next;\n });\n }\n }\n\n const newValid =\n name === 'number'\n ? typeof props.validNumber === 'boolean'\n ? props.validNumber\n : undefined\n : typeof props.validCvv === 'boolean'\n ? props.validCvv\n : undefined;\n if (typeof newValid === 'boolean') {\n const prev = validityRef.current;\n const next: CardFieldValidity =\n name === 'number' ? { ...prev, number: newValid } : { ...prev, cvv: newValid };\n if (next.number !== prev.number || next.cvv !== prev.cvv) {\n validityRef.current = next;\n setValidity(next);\n onValidityChangeRef.current?.(next);\n }\n }\n });\n\n spreedly.on('consoleError', (err) => {\n // Without this, vault-internal failures during tokenizeCreditCard\n // leave consumers stuck in their 'tokenizing' state forever.\n const message =\n err instanceof Error\n ? err.message\n : 'An unexpected error occurred while securing your card.';\n onFieldErrorsRef.current?.([{ message }]);\n });\n\n spreedly.init(session.environmentKey, {\n numberEl,\n cvvEl,\n nonce: session.nonce,\n timestamp: String(session.timestamp),\n certificateToken: session.certificateToken,\n signature: session.signature,\n });\n } catch (err) {\n if (cancelled) return;\n const message = err instanceof Error ? err.message : 'Failed to initialize card form.';\n setError(message);\n setStatus('error');\n }\n })();\n\n return () => {\n cancelled = true;\n try {\n spreedlyRef.current?.removeHandlers?.();\n } catch {\n // best-effort cleanup\n }\n spreedlyRef.current = null;\n };\n }, [numberEl, cvvEl]);\n\n const tokenize = useCallback((data: CardholderTokenizeData) => {\n spreedlyRef.current?.tokenizeCreditCard(toSdkPayload(data));\n }, []);\n\n const focusField = useCallback((field: 'number' | 'cvv') => {\n spreedlyRef.current?.transferFocus?.(field);\n }, []);\n\n return { status, error, tokenize, validity, brand, focused, focusField };\n};\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport clsx from 'clsx';\n\nimport { savePaymentMethodFromToken } from '../api';\nimport { CardBrandIcon } from '../PaymentMethodsManager/cardBrandIcon';\nimport { useMovmoCardFields } from '../useMovmoCardFields';\nimport type { CardFieldError, CardFormStatus, PaymentMethodSummary } from '../types';\n\nexport interface MovmoCardFormProps {\n userId: string;\n onSuccess: (paymentMethod: PaymentMethodSummary) => void;\n onError: (error: string) => void;\n isDefault?: boolean;\n className?: string;\n /**\n * Pre-fills the cardholder name input. Cardholders aren't always the\n * logged-in user (spouse card, corporate card), so the field remains\n * editable — pass `user.fullName` as a sensible default.\n */\n defaultCardholderName?: string;\n /**\n * @deprecated Prefer `defaultCardholderName`. Concatenated with\n * `defaultCardholderLastName` to seed the single cardholder name field.\n */\n defaultCardholderFirstName?: string;\n /** @deprecated See `defaultCardholderFirstName`. */\n defaultCardholderLastName?: string;\n /**\n * When true, the form submits automatically the moment all fields are valid —\n * no Save button is rendered. Matches the flights-ui \"first card\" auto-save UX.\n * Defaults to `false`.\n */\n autoSave?: boolean;\n /**\n * HTML `id` for the underlying `<form>` element. Lets a parent (e.g. modal\n * footer) wire its own submit button via `<button type=\"submit\" form=\"...\">`\n * — useful when `hideInternalSaveButton` is true. Defaults to `movmo-card-form`.\n */\n formId?: string;\n /**\n * When true, the form omits its internal Save button. Use together with\n * `formId` to drive submit from a parent (e.g. a modal footer's Save button).\n */\n hideInternalSaveButton?: boolean;\n /**\n * Fires whenever the \"ready to submit\" state changes (all fields valid +\n * not in flight). Use to enable / disable an external Save button.\n */\n onCanSubmitChange?: (canSubmit: boolean) => void;\n /**\n * Fires whenever the form transitions in / out of the \"saving\" state\n * (tokenize call or save POST in flight). A parent rendering its own\n * Save button (e.g. a modal footer) uses this to swap the button label\n * for a spinner. The hook's loading state is internal and not surfaced\n * directly — this callback is the single source of truth.\n */\n onSavingChange?: (isSaving: boolean) => void;\n /**\n * When set, the named Spreedly hosted-fields iframe receives keyboard\n * focus the moment the field becomes ready. Use `\"number\"` for the\n * accounts-ui add-card modal so the user can start typing immediately.\n */\n autoFocus?: 'number' | 'cvv';\n}\n\n// Active border matches flights-ui: 1px gray-300 → thick grayWarm-950 ring on focus.\nconst fieldShellClass =\n '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]';\n\n// Base styling for the iframe shells. `:focus-within` can't observe focus\n// inside a cross-origin iframe, so the active-border classes are applied\n// conditionally based on the `focused` state from useMovmoCardFields.\nconst iframeShellClass =\n 'flex h-11 w-full items-center gap-2 rounded-md border bg-white px-3 py-2 transition-shadow';\nconst iframeShellActiveClass = 'border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]';\nconst iframeShellIdleClass = 'border-grayWarm-300';\n\nconst splitName = (full: string): { firstName: string; lastName: string } => {\n const trimmed = full.trim();\n if (!trimmed) return { firstName: '', lastName: '' };\n const lastSpace = trimmed.lastIndexOf(' ');\n if (lastSpace === -1) return { firstName: trimmed, lastName: '' };\n return {\n firstName: trimmed.slice(0, lastSpace).trim(),\n lastName: trimmed.slice(lastSpace + 1).trim(),\n };\n};\n\n/** Parses \"MM/YY\", \"MM / YY\", or \"MM/YYYY\" → { month, year } in Spreedly's expected shape. */\nconst parseExpiry = (raw: string): { month: string; year: string } => {\n const digits = raw.replace(/\\D/g, '');\n if (digits.length < 4) return { month: '', year: '' };\n const month = digits.slice(0, 2);\n const yearRaw = digits.slice(2);\n const year = yearRaw.length === 2 ? `20${yearRaw}` : yearRaw.slice(0, 4);\n return { month, year };\n};\n\nconst formatExpiryInput = (raw: string): string => {\n const digits = raw.replace(/\\D/g, '').slice(0, 4);\n if (digits.length <= 2) return digits;\n return `${digits.slice(0, 2)} / ${digits.slice(2)}`;\n};\n\nconst isExpiryValid = (raw: string): boolean => {\n const { month, year } = parseExpiry(raw);\n if (!month || !year) return false;\n const mm = parseInt(month, 10);\n const yyyy = parseInt(year, 10);\n if (isNaN(mm) || mm < 1 || mm > 12) return false;\n const now = new Date();\n if (yyyy < now.getFullYear() || yyyy > now.getFullYear() + 20) return false;\n if (yyyy === now.getFullYear() && mm < now.getMonth() + 1) return false;\n return true;\n};\n\n/** US ZIP — 5 digits, optionally followed by -4 (ZIP+4). */\nconst isZipValid = (raw: string): boolean => /^\\d{5}(-\\d{4})?$/.test(raw.trim());\n\nconst formatZipInput = (raw: string): string => {\n // Strip everything except digits + a single hyphen between groups.\n const digits = raw.replace(/[^\\d]/g, '').slice(0, 9);\n if (digits.length <= 5) return digits;\n return `${digits.slice(0, 5)}-${digits.slice(5)}`;\n};\n\nexport const MovmoCardForm = ({\n userId,\n onSuccess,\n onError,\n isDefault = false,\n className,\n defaultCardholderName,\n defaultCardholderFirstName = '',\n defaultCardholderLastName = '',\n autoSave = false,\n formId = 'movmo-card-form',\n hideInternalSaveButton = false,\n onCanSubmitChange,\n onSavingChange,\n autoFocus,\n}: MovmoCardFormProps) => {\n const seededName =\n defaultCardholderName ??\n [defaultCardholderFirstName, defaultCardholderLastName].filter(Boolean).join(' ');\n\n const [cardholderName, setCardholderName] = useState(seededName);\n const [expiry, setExpiry] = useState('');\n const [zip, setZip] = useState('');\n const [formStatus, setFormStatus] = useState<CardFormStatus>('idle');\n const autoSubmittedRef = useRef(false);\n\n const handleCardTokenized = useCallback(\n async (token: string) => {\n setFormStatus('saving');\n try {\n const summary = await savePaymentMethodFromToken(userId, token, isDefault);\n setFormStatus('ready');\n onSuccess(summary);\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Failed to save payment method.';\n setFormStatus('ready');\n autoSubmittedRef.current = false;\n onError(message);\n }\n },\n [userId, isDefault, onSuccess, onError],\n );\n\n const handleFieldErrors = useCallback(\n (errors: CardFieldError[]) => {\n const message =\n errors\n .map((e) => e.message)\n .filter(Boolean)\n .join('; ') || 'Card validation failed.';\n setFormStatus((prev) => (prev === 'tokenizing' ? 'ready' : prev));\n autoSubmittedRef.current = false;\n onError(message);\n },\n [onError],\n );\n\n const hookOptions = useMemo(\n () => ({\n onCardTokenized: handleCardTokenized,\n onFieldErrors: handleFieldErrors,\n }),\n [handleCardTokenized, handleFieldErrors],\n );\n\n const {\n status: hookStatus,\n error: hookError,\n tokenize,\n validity,\n brand,\n focused,\n focusField,\n } = useMovmoCardFields(hookOptions);\n\n // Move keyboard focus into the requested iframe the moment the hook is\n // ready. `autoFocus=\"number\"` from the parent (e.g. modal opens → form\n // mounts) means the user can start typing the card number immediately\n // instead of clicking the field first.\n const autoFocusedRef = useRef(false);\n useEffect(() => {\n if (!autoFocus || hookStatus !== 'ready' || autoFocusedRef.current) return;\n autoFocusedRef.current = true;\n focusField(autoFocus);\n }, [autoFocus, hookStatus, focusField]);\n\n const nameValid = cardholderName.trim().split(/\\s+/).length >= 2;\n const expiryValid = isExpiryValid(expiry);\n const zipValid = isZipValid(zip);\n const autoFocusedCvvRef = useRef(false);\n const autoFocusedZipRef = useRef(false);\n const autoFocusedNameRef = useRef(false);\n const zipInputRef = useRef<HTMLInputElement | null>(null);\n const cardholderNameInputRef = useRef<HTMLInputElement | null>(null);\n\n // Auto-advance from CVV iframe into the zip input the first time CVV\n // becomes valid. Mirrors the expiry → CVV jump. Ref resets when CVV\n // becomes invalid so editing back-and-forth still works.\n useEffect(() => {\n if (validity.cvv) {\n if (!autoFocusedZipRef.current) {\n autoFocusedZipRef.current = true;\n zipInputRef.current?.focus();\n }\n } else {\n autoFocusedZipRef.current = false;\n }\n }, [validity.cvv]);\n const formInvalid = !nameValid || !expiryValid || !zipValid || !validity.number || !validity.cvv;\n\n const isBusy = formStatus === 'tokenizing' || formStatus === 'saving';\n const canSubmit = hookStatus === 'ready' && !isBusy && !formInvalid;\n\n // Push canSubmit transitions to a parent (e.g. a modal footer's Save button).\n const onCanSubmitChangeRef = useRef(onCanSubmitChange);\n useEffect(() => {\n onCanSubmitChangeRef.current = onCanSubmitChange;\n }, [onCanSubmitChange]);\n useEffect(() => {\n onCanSubmitChangeRef.current?.(canSubmit);\n }, [canSubmit]);\n\n // Push the \"saving\" transition to a parent so a modal-footer Save button can\n // swap its label for a spinner. The ref pattern matches onCanSubmitChange.\n const onSavingChangeRef = useRef(onSavingChange);\n useEffect(() => {\n onSavingChangeRef.current = onSavingChange;\n }, [onSavingChange]);\n useEffect(() => {\n onSavingChangeRef.current?.(isBusy);\n }, [isBusy]);\n\n const submit = useCallback(() => {\n const { firstName, lastName } = splitName(cardholderName);\n const { month, year } = parseExpiry(expiry);\n setFormStatus('tokenizing');\n tokenize({ firstName, lastName, month, year, zip: zip.trim() });\n }, [cardholderName, expiry, zip, tokenize]);\n\n // Auto-save: debounced so the form doesn't submit mid-keystroke. The\n // form's name-validity rule is loose on purpose (any \"First Last\" passes),\n // so without a debounce the submit fires the moment the user types their\n // last-name's first letter — disabling the input and freezing the rest of\n // their typing. 1200ms is long enough that natural cadence won't trip it,\n // short enough that a paused-and-done user sees the save promptly.\n useEffect(() => {\n if (!autoSave) return;\n if (!canSubmit) return;\n if (autoSubmittedRef.current) return;\n const timer = setTimeout(() => {\n autoSubmittedRef.current = true;\n submit();\n }, 1200);\n return () => clearTimeout(timer);\n }, [autoSave, canSubmit, submit]);\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault();\n if (!canSubmit) return;\n submit();\n };\n\n const inputsDisabled = hookStatus !== 'ready' || isBusy;\n\n // Propagate Spreedly-init failures (e.g. \"Failed to fetch tokenization\n // session\") to the parent so the manager-level banner renders them too.\n // Without this, hookErrors would be lost when the inline error <p> is\n // removed below.\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n useEffect(() => {\n if (hookError) onErrorRef.current?.(hookError);\n }, [hookError]);\n\n return (\n <form\n id={formId}\n onSubmit={handleSubmit}\n className={clsx('flex w-full flex-col gap-3', className)}\n data-testid=\"movmo-card-form\"\n >\n {/* Card number — Spreedly iframe inside a shell with brand icon inline */}\n <div>\n <span id=\"movmo-card-number-label\" className=\"sr-only\">\n Card number\n </span>\n <div\n className={clsx(\n iframeShellClass,\n focused.number ? iframeShellActiveClass : iframeShellIdleClass,\n )}\n >\n <CardBrandIcon brand={brand ?? ''} width={32} className=\"flex-shrink-0\" />\n {/*\n * Skeleton bar lives as a SIBLING (not child) of the Spreedly mount\n * div. Spreedly injects an `<iframe>` into the mount on `init` and\n * removes it on `removeHandlers`; if React owns children inside the\n * mount during that window, React's reconciler races with Spreedly\n * over `removeChild` and throws `NotFoundError: The node to be\n * removed is not a child of this node`. Keeping the mount div\n * empty of React children avoids that fight.\n */}\n <div className=\"relative h-full flex-1\">\n <div\n id=\"movmo-card-number\"\n aria-labelledby=\"movmo-card-number-label\"\n aria-busy={hookStatus !== 'ready'}\n className=\"absolute inset-0\"\n data-testid=\"movmo-card-number-mount\"\n />\n {hookStatus !== 'ready' ? (\n <div\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute inset-y-2 left-0 right-2 animate-pulse rounded bg-grayWarm-200\"\n />\n ) : null}\n </div>\n </div>\n </div>\n\n {/* Expiry + CVV + ZIP row */}\n <div className=\"grid grid-cols-3 gap-3\">\n <div>\n <label htmlFor=\"movmo-card-expiry\" className=\"sr-only\">\n Expiry MM / YY\n </label>\n <input\n id=\"movmo-card-expiry\"\n type=\"text\"\n inputMode=\"numeric\"\n autoComplete=\"cc-exp\"\n placeholder=\"MM / YY\"\n value={expiry}\n onChange={(e) => {\n const next = formatExpiryInput(e.target.value);\n setExpiry(next);\n // Auto-advance to CVV the first time expiry becomes valid. The\n // ref lets the user edit-back-and-forth without re-stealing focus.\n if (isExpiryValid(next) && !autoFocusedCvvRef.current) {\n autoFocusedCvvRef.current = true;\n focusField('cvv');\n } else if (!isExpiryValid(next)) {\n autoFocusedCvvRef.current = false;\n }\n }}\n className={clsx(fieldShellClass, expiry && !expiryValid && 'border-error-500')}\n disabled={inputsDisabled}\n required\n data-testid=\"movmo-card-expiry-input\"\n />\n </div>\n <div className=\"relative\">\n <span id=\"movmo-card-cvv-label\" className=\"sr-only\">\n CVV\n </span>\n <div\n className={clsx(\n iframeShellClass,\n focused.cvv ? iframeShellActiveClass : iframeShellIdleClass,\n )}\n >\n {/* Skeleton sibling pattern — see card-number comment above. */}\n <div className=\"relative h-full flex-1\">\n <div\n id=\"movmo-card-cvv\"\n aria-labelledby=\"movmo-card-cvv-label\"\n aria-busy={hookStatus !== 'ready'}\n className=\"absolute inset-0\"\n data-testid=\"movmo-card-cvv-mount\"\n />\n {hookStatus !== 'ready' ? (\n <div\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute inset-y-2 left-0 right-2 animate-pulse rounded bg-grayWarm-200\"\n />\n ) : null}\n </div>\n <button\n type=\"button\"\n aria-label=\"CVV help\"\n tabIndex={-1}\n className=\"flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full border border-grayWarm-300 text-xs text-grayWarm-500\"\n title={\n brand === 'american_express'\n ? 'The 4 numbers on the front of your card.'\n : 'The 3 numbers on the back of your card.'\n }\n data-testid=\"movmo-cvv-help\"\n >\n ?\n </button>\n </div>\n </div>\n <div>\n {/*\n Spreedly doesn't require zip at tokenization, but US issuers'\n AVS will decline most card-not-present charges without it (and\n including AVS lowers interchange + chargeback risk), so collect\n it up front.\n */}\n <label htmlFor=\"movmo-card-zip\" className=\"sr-only\">\n ZIP code\n </label>\n <input\n id=\"movmo-card-zip\"\n ref={zipInputRef}\n type=\"text\"\n inputMode=\"numeric\"\n autoComplete=\"postal-code\"\n placeholder=\"ZIP code\"\n value={zip}\n onChange={(e) => {\n const next = formatZipInput(e.target.value);\n setZip(next);\n if (isZipValid(next) && !autoFocusedNameRef.current) {\n autoFocusedNameRef.current = true;\n cardholderNameInputRef.current?.focus();\n } else if (!isZipValid(next)) {\n autoFocusedNameRef.current = false;\n }\n }}\n className={clsx(fieldShellClass, zip && !zipValid && 'border-error-500')}\n disabled={inputsDisabled}\n required\n data-testid=\"movmo-card-zip-input\"\n />\n </div>\n </div>\n\n {/* Cardholder name — single field, Figma-aligned */}\n <div>\n <label htmlFor=\"movmo-card-cardholder-name\" className=\"sr-only\">\n Cardholder name\n </label>\n <input\n id=\"movmo-card-cardholder-name\"\n ref={cardholderNameInputRef}\n type=\"text\"\n autoComplete=\"cc-name\"\n placeholder=\"Cardholder name\"\n value={cardholderName}\n onChange={(e) => setCardholderName(e.target.value)}\n className={fieldShellClass}\n disabled={inputsDisabled}\n required\n data-testid=\"movmo-card-cardholder-name-input\"\n />\n </div>\n\n {/*\n * No inline error banner here — errors are propagated to the parent\n * via `onError` (API failures) and the hookError useEffect above\n * (Spreedly init failures). The parent's PaymentMethodsManager owns\n * the single error banner with role=\"alert\" + aria-live, avoiding\n * the duplicate-error UX (per ux-design-advisor: WCAG 4.1.3 — two\n * role=\"alert\" nodes on the same string announces twice).\n */}\n\n {!autoSave && !hideInternalSaveButton ? (\n <button\n type=\"submit\"\n disabled={!canSubmit}\n className={clsx(\n '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',\n 'disabled:cursor-not-allowed disabled:bg-grayWarm-300 disabled:text-grayWarm-500',\n )}\n data-testid=\"movmo-card-save\"\n >\n {isBusy ? 'Saving…' : hookStatus === 'loading' ? 'Loading…' : 'Save card'}\n </button>\n ) : isBusy && autoSave ? (\n // In autoSave mode (empty-state inline form, no Save button at all),\n // surface the in-flight state as inline text. The modal flow uses a\n // spinner inside the modal-footer Save button instead — see\n // AddPaymentMethodModal.isSaving.\n <p\n className=\"text-center text-sm text-grayWarm-500\"\n aria-live=\"polite\"\n data-testid=\"movmo-card-autosaving\"\n >\n Saving card…\n </p>\n ) : null}\n </form>\n );\n};\n\nMovmoCardForm.displayName = 'MovmoCardForm';\n\nexport default MovmoCardForm;\n","import { useCallback, useState } from 'react';\n\nimport { deletePaymentMethod as deletePaymentMethodApi } from './api';\n\nexport type UseDeletePaymentMethodStatus = 'idle' | 'pending' | 'error';\n\nexport interface UseDeletePaymentMethodResult {\n deletePaymentMethod: (methodId: string) => Promise<void>;\n status: UseDeletePaymentMethodStatus;\n error: string | null;\n}\n\n/**\n * Calls `DELETE /v1/users/:userId/payment-methods/:methodId`.\n *\n * The hook owns the network call + status; consumers own list state so they\n * can apply optimistic updates / rollback at their layer. The returned promise\n * resolves on success and rejects on failure so callers can roll back.\n */\nexport const useDeletePaymentMethod = (userId: string): UseDeletePaymentMethodResult => {\n const [status, setStatus] = useState<UseDeletePaymentMethodStatus>('idle');\n const [error, setError] = useState<string | null>(null);\n\n const deletePaymentMethod = useCallback(\n async (methodId: string): Promise<void> => {\n setStatus('pending');\n setError(null);\n try {\n await deletePaymentMethodApi(userId, methodId);\n setStatus('idle');\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Failed to delete payment method.';\n setError(message);\n setStatus('error');\n throw err;\n }\n },\n [userId],\n );\n\n return { deletePaymentMethod, status, error };\n};\n","import { useCallback, useState } from 'react';\n\nimport { updatePaymentMethod } from './api';\n\nexport type UseSetDefaultPaymentMethodStatus = 'idle' | 'pending' | 'error';\n\nexport interface UseSetDefaultPaymentMethodResult {\n setDefault: (methodId: string) => Promise<void>;\n status: UseSetDefaultPaymentMethodStatus;\n error: string | null;\n}\n\n/**\n * Calls `PUT /v1/users/:userId/payment-methods/:methodId` with\n * `{ isDefault: true }`. Server clears the previous default automatically.\n *\n * The hook owns the network call + status; consumers own list state so they\n * can apply optimistic updates / rollback at their layer. The returned promise\n * resolves on success and rejects on failure so callers can roll back.\n */\nexport const useSetDefaultPaymentMethod = (userId: string): UseSetDefaultPaymentMethodResult => {\n const [status, setStatus] = useState<UseSetDefaultPaymentMethodStatus>('idle');\n const [error, setError] = useState<string | null>(null);\n\n const setDefault = useCallback(\n async (methodId: string): Promise<void> => {\n setStatus('pending');\n setError(null);\n try {\n await updatePaymentMethod(userId, methodId, { isDefault: true });\n setStatus('idle');\n } catch (err) {\n const message =\n err instanceof Error ? err.message : 'Failed to set default payment method.';\n setError(message);\n setStatus('error');\n throw err;\n }\n },\n [userId],\n );\n\n return { setDefault, status, error };\n};\n","import { useCallback, useEffect, useRef, useState } from 'react';\n\nimport { listPaymentMethods } from './api';\nimport type { PaymentMethodSummary } from './types';\n\nexport type UseUserPaymentMethodsStatus = 'idle' | 'loading' | 'ready' | 'error';\n\nexport interface UseUserPaymentMethodsResult {\n items: PaymentMethodSummary[];\n status: UseUserPaymentMethodsStatus;\n error: string | null;\n /** Re-issues the GET request. Cancels any in-flight request first. */\n refetch: () => void;\n}\n\n/**\n * Fetches a user's saved payment methods from monolith-api.\n *\n * Auto-runs on mount and whenever `userId` changes. Cancels the in-flight\n * request on unmount or refetch so consumers don't see stale results land\n * after a navigation. Status mirrors `useMovmoCardFields`:\n * `idle` → `loading` → `ready | error`.\n */\nexport const useUserPaymentMethods = (userId: string): UseUserPaymentMethodsResult => {\n const [items, setItems] = useState<PaymentMethodSummary[]>([]);\n const [status, setStatus] = useState<UseUserPaymentMethodsStatus>('idle');\n const [error, setError] = useState<string | null>(null);\n const [tick, setTick] = useState(0);\n const abortRef = useRef<AbortController | null>(null);\n\n useEffect(() => {\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n setStatus('loading');\n setError(null);\n\n // Pass controller.signal so React 18 StrictMode's double-mount (and any\n // mid-flight refetch) actually cancels the in-flight HTTP request instead\n // of letting both calls land server-side and only discarding the result.\n listPaymentMethods(userId, controller.signal)\n .then((result) => {\n if (controller.signal.aborted) return;\n setItems(result);\n setStatus('ready');\n })\n .catch((err: unknown) => {\n if (controller.signal.aborted) return;\n // DOMException 'AbortError' surfaces when the signal aborts mid-fetch\n // before our explicit guard above can run — swallow it the same way.\n if (err instanceof DOMException && err.name === 'AbortError') return;\n const message = err instanceof Error ? err.message : 'Failed to fetch payment methods.';\n setError(message);\n setStatus('error');\n });\n\n return () => {\n controller.abort();\n };\n }, [userId, tick]);\n\n const refetch = useCallback(() => {\n setTick((n) => n + 1);\n }, []);\n\n return { items, status, error, refetch };\n};\n","import { useEffect, type ReactNode } from 'react';\nimport clsx from 'clsx';\n\ninterface AddPaymentMethodModalProps {\n open: boolean;\n onClose: () => void;\n /**\n * HTML form id rendered inside the modal. The modal's Save button uses\n * `<button type=\"submit\" form={formId}>` so the consumer doesn't need to\n * thread a submit ref.\n */\n formId: string;\n /** Save button disabled state — track the form's `canSubmit`. */\n saveDisabled: boolean;\n /** Save button label override (default: \"Save\"). */\n saveLabel?: string;\n /**\n * When true, replace the Save button's label with a centered spinner,\n * mark the button `aria-busy`, and prevent further clicks. Matches the\n * flights-ui house style for primary-action buttons during an in-flight\n * mutation (see ux-design-advisor's call).\n */\n isSaving?: boolean;\n children: ReactNode;\n}\n\n/**\n * Vault-neutral modal wrapper for the add-payment flow. Matches the chrome\n * in Figma node 2871-52148: X close in the top-left, \"Add payment method\"\n * title, body slot, Cancel + Save footer. The Save button is wired via the\n * HTML form attribute so the parent doesn't need a submit ref.\n *\n * No external modal library — the consumer's own modal infrastructure can\n * later replace this if needed, but the package stays dep-free.\n */\nexport const AddPaymentMethodModal = ({\n open,\n onClose,\n formId,\n saveDisabled,\n saveLabel = 'Save',\n isSaving = false,\n children,\n}: AddPaymentMethodModalProps) => {\n // Close on Escape key (consistent with native <dialog>).\n useEffect(() => {\n if (!open) return;\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') onClose();\n };\n document.addEventListener('keydown', onKey);\n return () => document.removeEventListener('keydown', onKey);\n }, [open, onClose]);\n\n // Lock body scroll while open so the page doesn't shift behind the overlay.\n useEffect(() => {\n if (!open) return;\n const prev = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n return () => {\n document.body.style.overflow = prev;\n };\n }, [open]);\n\n if (!open) return null;\n\n return (\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby=\"movmo-add-payment-title\"\n className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4\"\n onClick={(e) => {\n // Backdrop click closes — don't close when clicking inside the panel.\n if (e.target === e.currentTarget) onClose();\n }}\n data-testid=\"add-payment-method-modal\"\n >\n <div className=\"flex max-h-full w-full max-w-md flex-col rounded-xl bg-white shadow-2xl\">\n <div className=\"flex items-center gap-3 border-b border-grayWarm-200 px-4 py-3\">\n <button\n type=\"button\"\n onClick={onClose}\n aria-label=\"Close add-payment dialog\"\n // Matches Figma node 2871-51397: 36×36 filled grayWarm-100\n // button, rounded-lg, no border, 20×20 dark X glyph.\n 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\"\n data-testid=\"add-payment-method-close\"\n >\n <svg viewBox=\"0 0 20 20\" width=\"20\" height=\"20\" aria-hidden=\"true\">\n <path\n d=\"M5 5L15 15M15 5L5 15\"\n stroke=\"currentColor\"\n strokeWidth=\"1.67\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n </button>\n <h2\n id=\"movmo-add-payment-title\"\n className=\"flex-1 text-center text-base font-semibold text-grayWarm-900\"\n >\n Add payment method\n </h2>\n {/* Spacer balances the close button so the title stays centered. */}\n <span aria-hidden=\"true\" className=\"h-9 w-9 flex-shrink-0\" />\n </div>\n\n <div className=\"flex-1 overflow-y-auto p-4\">{children}</div>\n\n <div className=\"flex gap-3 border-t border-grayWarm-200 p-4\">\n <button\n type=\"button\"\n onClick={onClose}\n 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]\"\n data-testid=\"add-payment-method-cancel\"\n >\n Cancel\n </button>\n <button\n type=\"submit\"\n form={formId}\n // While saving, the button stays brand-500 (active state — the\n // disabled gray would read as \"rejected\"), but `aria-disabled`\n // + pointer-events-none prevent re-submit. Don't set the\n // disabled attribute when saving: it would trigger the\n // disabled:bg-grayWarm-300 class.\n disabled={isSaving ? false : saveDisabled}\n aria-disabled={isSaving || saveDisabled}\n aria-busy={isSaving}\n className={clsx(\n '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',\n isSaving\n ? 'cursor-not-allowed opacity-90 pointer-events-none'\n : 'hover:bg-brand-600 disabled:cursor-not-allowed disabled:bg-grayWarm-300 disabled:text-grayWarm-500',\n )}\n data-testid=\"add-payment-method-save\"\n >\n {isSaving ? (\n <>\n {/*\n * Inline SVG ring + Tailwind animate-spin. Avoids adding\n * react-spinners as a runtime dep on this package. Matches\n * the visual weight of flights-ui's ClipLoader at size=18.\n */}\n <svg\n className=\"h-[18px] w-[18px] animate-spin\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n aria-hidden=\"true\"\n >\n <circle\n cx=\"12\"\n cy=\"12\"\n r=\"10\"\n stroke=\"currentColor\"\n strokeWidth=\"3\"\n strokeOpacity=\"0.25\"\n />\n <path\n d=\"M22 12a10 10 0 0 1-10 10\"\n stroke=\"currentColor\"\n strokeWidth=\"3\"\n strokeLinecap=\"round\"\n />\n </svg>\n <span className=\"sr-only\">Saving card</span>\n </>\n ) : (\n saveLabel\n )}\n </button>\n </div>\n </div>\n </div>\n );\n};\n","import clsx from 'clsx';\n\nimport type { PaymentMethodSummary } from '../types';\nimport { CardBrandIcon } from './cardBrandIcon';\n\nconst prettyBrand = (brand: string | null | undefined): string => {\n if (!brand) return 'Card';\n const key = brand.toLowerCase();\n if (key === 'amex') return 'Amex';\n return key.charAt(0).toUpperCase() + key.slice(1);\n};\n\nexport interface PaymentMethodPreviewProps {\n /**\n * The card to render. Consumers typically derive this from\n * `useUserPaymentMethods(userId)` — e.g. the selected card in a checkout\n * drawer, or the default card on a summary line.\n */\n method: PaymentMethodSummary;\n /** Trailing slot — flights-ui drops an expand-chevron button here. */\n trailing?: React.ReactNode;\n /** Whole-row click handler — typically toggles the drawer open. */\n onClick?: () => void;\n /**\n * Controls how the card label is rendered.\n * - `'branded'` (default): \"Visa 4242\" — brand name + last4\n * - `'masked'`: \"•••• 4242\" — masked bullets + last4 (flights-ui collapsed-drawer style)\n */\n cardLabelFormat?: 'masked' | 'branded';\n className?: string;\n}\n\n/**\n * Compact preview of a single saved card: brand icon + label. Used by\n * consumers (e.g. flights-ui's collapsed checkout drawer) to show the\n * currently-selected card outside the full `<PaymentMethodsManager />`\n * list view. Keeps the brand-icon styling consistent with the expanded list.\n *\n * Brand icon is sized to match flights-ui main's `w-[34px]` collapsed view.\n * No vertical padding — the parent controls spacing.\n */\nexport const PaymentMethodPreview = ({\n method,\n trailing,\n onClick,\n cardLabelFormat = 'branded',\n className,\n}: PaymentMethodPreviewProps) => (\n <div\n className={clsx('flex items-center gap-3', onClick && 'cursor-pointer', className)}\n onClick={onClick}\n role={onClick ? 'button' : undefined}\n tabIndex={onClick ? 0 : undefined}\n onKeyDown={\n onClick\n ? (e) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n onClick();\n }\n }\n : undefined\n }\n data-testid={`payment-method-preview-${method.id}`}\n >\n <CardBrandIcon brand={method.brand} width={34} className=\"flex-shrink-0\" />\n <span className=\"flex-1 text-lg font-semibold text-grayWarm-950\">\n {cardLabelFormat === 'masked'\n ? `•••• ${method.last4}`\n : `${prettyBrand(method.brand)} ${method.last4}`}\n </span>\n {trailing}\n </div>\n);\n","/**\n * True when a card's printed expiration has already passed.\n * `expMonth` is 1-12, `expYear` is the 4-digit year.\n */\nexport const isExpired = (expMonth: number, expYear: number, now: Date = new Date()): boolean =>\n expYear < now.getFullYear() || (expYear === now.getFullYear() && expMonth < now.getMonth() + 1);\n","import { useEffect, useRef, useState } from 'react';\nimport clsx from 'clsx';\n\nimport type { PaymentMethodSummary } from '../types';\nimport { CardBrandIcon } from './cardBrandIcon';\nimport { isExpired } from './isExpired';\n\nexport interface PaymentMethodRowProps {\n method: PaymentMethodSummary;\n /** When true, render a radio input and treat the whole row as selectable. */\n selectable: boolean;\n selected: boolean;\n onSelect?: (method: PaymentMethodSummary) => void;\n onSetDefault: (method: PaymentMethodSummary) => void;\n onRemove: (method: PaymentMethodSummary) => void;\n /** Disable the menu actions while a mutation is in flight. */\n disabled: boolean;\n /** When true, render the green \"Default\" pill on the default card. */\n showDefaultBadge: boolean;\n /**\n * When true, hide the \"Set as default\" menu item — the parent has wired\n * row-selection to also set the default (flights-ui's checkout UX), so\n * the menu entry would be redundant.\n */\n hideSetDefaultMenuItem: boolean;\n /**\n * Controls how the card label is rendered next to the brand icon.\n * - `'branded'` (default): \"Visa 4242\" — brand name + last4\n * - `'masked'`: \"•••• 4242\" — masked bullets + last4 (flights-ui checkout style)\n */\n cardLabelFormat?: 'masked' | 'branded';\n}\n\nconst prettyBrand = (brand: string | null | undefined): string => {\n if (!brand) return 'Card';\n const key = brand.toLowerCase();\n if (key === 'amex') return 'Amex';\n return key.charAt(0).toUpperCase() + key.slice(1);\n};\n\nconst formatExpiry = (expMonth: number, expYear: number): string =>\n `${String(expMonth).padStart(2, '0')}/${expYear}`;\n\nexport const PaymentMethodRow = ({\n method,\n selectable,\n selected,\n onSelect,\n onSetDefault,\n onRemove,\n disabled,\n showDefaultBadge,\n hideSetDefaultMenuItem,\n cardLabelFormat = 'branded',\n}: PaymentMethodRowProps) => {\n const [menuOpen, setMenuOpen] = useState(false);\n const menuContainerRef = useRef<HTMLDivElement | null>(null);\n const expired = isExpired(method.expMonth, method.expYear);\n\n useEffect(() => {\n if (!menuOpen) return;\n const onDocClick = (e: MouseEvent) => {\n if (!menuContainerRef.current?.contains(e.target as Node)) setMenuOpen(false);\n };\n document.addEventListener('mousedown', onDocClick);\n return () => document.removeEventListener('mousedown', onDocClick);\n }, [menuOpen]);\n\n const handleRowClick = () => {\n if (selectable && onSelect && !disabled) onSelect(method);\n };\n\n return (\n <div\n className={clsx(\n // items-start + per-element mt offsets so the radio, brand icon, and\n // label all read as one horizontal line, with the Exp text directly\n // below the label in the same column. Matches main's flights-ui +\n // accounts-ui row layout (both use items-start).\n 'flex items-start gap-3 transition-colors',\n selectable ? 'rounded-lg border px-3 py-3' : 'py-4',\n selectable && !disabled && 'cursor-pointer',\n selectable &&\n (selected\n ? 'border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]'\n : 'border-grayWarm-200 hover:border-grayWarm-300'),\n )}\n onClick={handleRowClick}\n data-testid={`payment-method-row-${method.id}`}\n >\n {selectable ? (\n <input\n type=\"radio\"\n name=\"movmo-payment-method\"\n checked={selected}\n onChange={() => onSelect?.(method)}\n onClick={(e) => e.stopPropagation()}\n aria-label={`Select ${prettyBrand(method.brand)} ending ${method.last4}`}\n // mt-2 pushes the 16px radio down so its vertical center sits on the\n // label's text baseline (matches main's mt-2 trick — items-start by\n // itself would top-align the radio with the brand icon's top, which\n // looks too high relative to the label).\n 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\"\n disabled={disabled}\n />\n ) : null}\n\n <CardBrandIcon brand={method.brand} className=\"flex-shrink-0\" />\n\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <span className=\"text-lg font-semibold text-grayWarm-950\">\n {cardLabelFormat === 'masked'\n ? `•••• ${method.last4}`\n : `${prettyBrand(method.brand)} ${method.last4}`}\n </span>\n {showDefaultBadge && method.isDefault ? (\n <span\n className=\"inline-flex items-center rounded-full bg-success-50 px-2 py-0.5 text-xs font-semibold text-success-700\"\n data-testid={`badge-default-${method.id}`}\n >\n Default\n </span>\n ) : null}\n {expired ? (\n <span\n className=\"inline-flex items-center rounded-full bg-error-50 px-2 py-0.5 text-xs font-semibold text-error-700\"\n data-testid={`badge-expired-${method.id}`}\n >\n Expired\n </span>\n ) : null}\n </div>\n <div className={clsx('text-base', expired ? 'text-grayWarm-400' : 'text-grayWarm-600')}>\n Exp. {formatExpiry(method.expMonth, method.expYear)}\n </div>\n </div>\n\n <div className=\"relative flex-shrink-0\" ref={menuContainerRef}>\n <button\n type=\"button\"\n aria-label={`Open actions for card ending ${method.last4}`}\n aria-haspopup=\"menu\"\n aria-expanded={menuOpen}\n className=\"rounded-lg p-2 text-grayWarm-600 transition-colors hover:bg-grayWarm-100 disabled:cursor-not-allowed disabled:opacity-50\"\n disabled={disabled}\n onClick={(e) => {\n e.stopPropagation();\n setMenuOpen((open) => !open);\n }}\n data-testid={`menu-trigger-${method.id}`}\n >\n <svg\n viewBox=\"0 0 24 24\"\n width=\"20\"\n height=\"20\"\n fill=\"currentColor\"\n aria-hidden=\"true\"\n >\n <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\" />\n </svg>\n </button>\n {menuOpen ? (\n <div\n role=\"menu\"\n className={clsx(\n 'absolute z-10 whitespace-nowrap rounded-lg border border-grayWarm-200 bg-white py-1 shadow-lg',\n // selectable mode (flights-ui): the row has a thick border that a\n // top-aligned dropdown would crash through. Float the menu ABOVE\n // the trigger button, horizontally centered, with a small tail\n // pointing back down at the dots. Matches main's flights-ui menu.\n // non-selectable mode (accounts-ui): no per-row border to\n // overlap; keep the menu below + right-aligned.\n selectable\n ? 'bottom-full left-1/2 mb-2 -translate-x-1/2'\n : 'right-0 top-full mt-1',\n )}\n onClick={(e) => e.stopPropagation()}\n data-testid={`menu-${method.id}`}\n >\n {selectable ? (\n // Tail: 8px square rotated 45° so its bottom-right corner\n // becomes a downward-pointing tip. Bottom + right borders of\n // the square form the menu's continuous border.\n <span\n aria-hidden=\"true\"\n 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\"\n />\n ) : null}\n {!method.isDefault && !hideSetDefaultMenuItem ? (\n <button\n type=\"button\"\n role=\"menuitem\"\n className=\"block w-full px-4 py-1 text-left text-md font-semibold text-grayWarm-950 hover:text-grayWarm-700\"\n onClick={() => {\n setMenuOpen(false);\n onSetDefault(method);\n }}\n data-testid={`menu-set-default-${method.id}`}\n >\n Set as default\n </button>\n ) : null}\n <button\n type=\"button\"\n role=\"menuitem\"\n className=\"block w-full px-4 py-1 text-left text-md font-semibold text-error-700 hover:text-error-500\"\n onClick={() => {\n setMenuOpen(false);\n onRemove(method);\n }}\n data-testid={`menu-remove-${method.id}`}\n >\n Delete\n </button>\n </div>\n ) : null}\n </div>\n </div>\n );\n};\n","import type { ReactNode } from 'react';\nimport clsx from 'clsx';\n\nimport { getPaymentsConfig } from '../config';\nimport { CardBrandIcon } from './cardBrandIcon';\n\nconst altIconUrl = (slug: string): string =>\n `${getPaymentsConfig().iconCdnBaseUrl}/website/assets/icons/payments/${slug}.svg`;\n\nconst AltIcon = ({ slug, alt }: { slug: string; alt: string }) => (\n <img\n src={altIconUrl(slug)}\n alt={alt}\n height={20}\n loading=\"lazy\"\n style={{ height: 20, width: 'auto' }}\n />\n);\n\n/**\n * The full set of payment types Movmo plans to support. Only `credit_card` is\n * functional today — the rest render as disabled \"Coming soon\" rows so the\n * consumer-facing UX matches the existing flights-ui design without shipping\n * dead UX behind a working radio.\n */\nexport type PaymentType = 'credit_card' | 'paypal' | 'googlepay' | 'klarna' | 'ach';\n\nexport interface PaymentTypeSelectorProps {\n /**\n * The currently-selected payment type, or `null` when nothing is selected\n * yet (the per-Figma empty state — user must click a row to expand its body).\n * Today only 'credit_card' is functional; the others render disabled.\n */\n selected: PaymentType | null;\n onSelect: (type: PaymentType) => void;\n /** Slot rendered below the Credit Card option when it's selected. */\n creditCardBody: ReactNode;\n className?: string;\n}\n\nconst OtherOptionRow = ({\n type,\n label,\n iconNode,\n}: {\n type: PaymentType;\n label: string;\n iconNode: ReactNode;\n}) => (\n // Alt payment types are visible + clickable but don't yet do anything —\n // the click is intentionally a no-op so the row looks identical to the\n // (future) functional state without faking selection.\n <label\n className=\"flex cursor-pointer items-center gap-3 rounded-lg border border-grayWarm-200 px-4 py-3 transition-colors hover:border-grayWarm-300\"\n data-testid={`payment-type-${type}`}\n >\n <input\n type=\"radio\"\n name=\"movmo-payment-type\"\n value={type}\n onChange={() => {\n /* TODO: wire when this provider lands */\n }}\n className=\"h-4 w-4 cursor-pointer accent-grayWarm-900\"\n aria-label={label}\n />\n <span className=\"flex flex-1 items-center gap-2 text-sm font-semibold text-grayWarm-900\">\n {label}\n {iconNode}\n </span>\n </label>\n);\n\nexport const PaymentTypeSelector = ({\n selected,\n onSelect,\n creditCardBody,\n className,\n}: PaymentTypeSelectorProps) => {\n const isCreditCardSelected = selected === 'credit_card';\n\n return (\n <div className={clsx('flex w-full flex-col gap-3', className)}>\n <label\n className={clsx(\n 'flex cursor-pointer flex-col gap-3 rounded-lg border px-4 py-3 transition-colors',\n isCreditCardSelected\n ? 'border-grayWarm-900 shadow-[0_0_0_1px_#1c1917]'\n : 'border-grayWarm-200',\n )}\n data-testid=\"payment-type-credit_card\"\n >\n <div className=\"flex items-center gap-3\">\n <input\n type=\"radio\"\n name=\"movmo-payment-type\"\n value=\"credit_card\"\n checked={isCreditCardSelected}\n onChange={() => onSelect('credit_card')}\n className=\"h-4 w-4 cursor-pointer accent-grayWarm-900\"\n aria-label=\"Credit card\"\n />\n <span className=\"flex-1 text-sm font-semibold text-grayWarm-900\">Credit card</span>\n <div className=\"flex items-center gap-1.5\">\n <CardBrandIcon brand=\"mastercard\" width={28} />\n <CardBrandIcon brand=\"visa\" width={28} />\n <CardBrandIcon brand=\"amex\" width={28} />\n <CardBrandIcon brand=\"discover\" width={28} />\n </div>\n </div>\n {isCreditCardSelected ? (\n <div data-testid=\"payment-type-credit_card-body\">{creditCardBody}</div>\n ) : null}\n </label>\n\n {/* Per Figma: the \"Other options\" section header only appears once the\n Credit card row is selected (i.e. the form is expanded). In the empty\n state the four type rows just stack without a header. */}\n {isCreditCardSelected ? (\n <p\n className=\"mt-2 text-sm font-semibold text-grayWarm-900\"\n data-testid=\"payment-type-other-options-header\"\n >\n Other options\n </p>\n ) : null}\n\n <OtherOptionRow\n type=\"paypal\"\n label=\"PayPal\"\n iconNode={<AltIcon slug=\"paypal\" alt=\"PayPal\" />}\n />\n <OtherOptionRow\n type=\"googlepay\"\n label=\"GooglePay\"\n iconNode={<AltIcon slug=\"google-pay\" alt=\"GooglePay\" />}\n />\n <OtherOptionRow\n type=\"klarna\"\n label=\"Klarna\"\n iconNode={<AltIcon slug=\"klarna\" alt=\"Klarna\" />}\n />\n <OtherOptionRow\n type=\"ach\"\n label=\"Bank account (ACH)\"\n iconNode={<span className=\"text-xs font-medium text-grayWarm-500\">Direct debit</span>}\n />\n </div>\n );\n};\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport clsx from 'clsx';\n\nimport { fetchTokenizationSession } from '../api';\nimport { getPaymentsConfig } from '../config';\nimport { MovmoCardForm } from '../MovmoCardForm/MovmoCardForm';\nimport type { PaymentMethodSummary } from '../types';\nimport { useDeletePaymentMethod } from '../useDeletePaymentMethod';\nimport { useSetDefaultPaymentMethod } from '../useSetDefaultPaymentMethod';\nimport { useUserPaymentMethods } from '../useUserPaymentMethods';\nimport { AddPaymentMethodModal } from './AddPaymentMethodModal';\nimport { PaymentMethodPreview } from './PaymentMethodPreview';\nimport { PaymentMethodRow } from './PaymentMethodRow';\nimport { PaymentTypeSelector, type PaymentType } from './PaymentTypeSelector';\n\nconst ADD_PAYMENT_FORM_ID = 'movmo-add-payment-form';\n\nexport interface PaymentMethodsManagerProps {\n userId: string;\n /**\n * Pre-fill the single cardholder-name input in the add-card form.\n * Falls back to `defaultCardholderFirstName + \" \" + defaultCardholderLastName`\n * for backward compatibility with the legacy MovmoCardForm props.\n */\n defaultCardholderName?: string;\n /** @deprecated Use `defaultCardholderName`. */\n defaultCardholderFirstName?: string;\n /** @deprecated Use `defaultCardholderName`. */\n defaultCardholderLastName?: string;\n /** Selection (opt-in). When `onSelect` is provided, each row renders a radio. */\n selectedId?: string;\n onSelect?: (method: PaymentMethodSummary) => void;\n /** Fires when the list state changes (add, delete, set-default). */\n onChange?: (items: PaymentMethodSummary[]) => void;\n /**\n * Show the Credit card / PayPal / GooglePay / Klarna / ACH radios above\n * the card-capture form. Only Credit card is functional today; the others\n * render as \"Coming soon\" to match the existing flights-ui design without\n * dropping the visual cues. Defaults to `true`. accounts-ui can opt out\n * by passing `false`.\n */\n paymentTypeSelector?: boolean;\n /**\n * When `true` AND the user has zero saved cards, the card form auto-submits\n * the moment all fields are valid. Matches the flights-ui first-card UX.\n * Defaults to `true`.\n */\n autoSaveFirstCard?: boolean;\n /**\n * When `true`, clicking a row both fires `onSelect` AND sets that method\n * as the default (the flights-ui checkout model: \"selected = default\").\n * Also hides the \"Set as default\" menu item since the row click already\n * does it. Requires `onSelect` to be useful. Defaults to `false`.\n */\n selectionSetsDefault?: boolean;\n /**\n * Render the green \"Default\" pill on the default row. accounts-ui keeps\n * this on; flights-ui passes `false` (the thick selected-border alone\n * communicates default since `selectionSetsDefault` couples the two).\n * Defaults to `true`.\n */\n showDefaultBadge?: boolean;\n /**\n * When `true` AND the user has at least one saved card, the list collapses\n * into a compact preview row with a chevron-down toggle. Expanding shows the\n * full list + Add button. Defaults to `false` (accounts-ui behaviour).\n * flights-ui passes `true`.\n */\n collapsible?: boolean;\n /**\n * Controls the card label format inside rows.\n * - `'branded'` (default): \"Visa 4242\" — brand name + last4\n * - `'masked'`: \"•••• 4242\" — masked bullets + last4 (flights-ui style)\n */\n cardLabelFormat?: 'masked' | 'branded';\n className?: string;\n}\n\nconst sortDefaultFirst = (items: PaymentMethodSummary[]): PaymentMethodSummary[] => {\n const defaults = items.filter((m) => m.isDefault);\n const rest = items.filter((m) => !m.isDefault);\n return [...defaults, ...rest];\n};\n\n/**\n * Skeleton sized to match the real row (PaymentMethodRow) so the layout\n * doesn't reflow when data lands. Dimensions mirror the accounts-ui main-\n * branch loading state: 46x32 card icon, 120x20 brand+last4 line, optional\n * 56x20 rounded-full \"Default\" pill on the first row, 100x16 expiry, 20x20\n * circular menu trigger.\n */\nconst SkeletonRow = ({ withDefaultBadge = false }: { withDefaultBadge?: boolean }) => (\n <div\n className=\"flex items-start justify-between py-4\"\n data-testid=\"payment-method-skeleton\"\n >\n <div className=\"flex items-start gap-3\">\n <div className=\"h-8 w-[46px] flex-shrink-0 animate-pulse rounded bg-grayWarm-200\" />\n <div className=\"space-y-2\">\n <div className=\"flex items-center gap-2\">\n <div className=\"h-5 w-[120px] animate-pulse rounded bg-grayWarm-200\" />\n {withDefaultBadge ? (\n <div className=\"h-5 w-[56px] animate-pulse rounded-full bg-grayWarm-200\" />\n ) : null}\n </div>\n <div className=\"h-4 w-[100px] animate-pulse rounded bg-grayWarm-200\" />\n </div>\n </div>\n <div className=\"h-5 w-5 flex-shrink-0 animate-pulse rounded-full bg-grayWarm-200\" />\n </div>\n);\n\nexport const PaymentMethodsManager = ({\n userId,\n defaultCardholderName,\n defaultCardholderFirstName,\n defaultCardholderLastName,\n selectedId,\n onSelect,\n onChange,\n paymentTypeSelector = true,\n autoSaveFirstCard = true,\n selectionSetsDefault = false,\n showDefaultBadge = true,\n collapsible = false,\n cardLabelFormat = 'branded',\n className,\n}: PaymentMethodsManagerProps) => {\n const { items: fetched, status, error: fetchError, refetch } = useUserPaymentMethods(userId);\n const { deletePaymentMethod, status: deleteStatus } = useDeletePaymentMethod(userId);\n const { setDefault, status: setDefaultStatus } = useSetDefaultPaymentMethod(userId);\n\n // Local mirror of the list so the manager can apply optimistic updates and\n // roll them back on API failure without waiting for a refetch.\n const [items, setItems] = useState<PaymentMethodSummary[]>([]);\n const [mutationError, setMutationError] = useState<string | null>(null);\n const [modalOpen, setModalOpen] = useState(false);\n const [formError, setFormError] = useState<string | null>(null);\n const [formCanSubmit, setFormCanSubmit] = useState(false);\n const [formIsSaving, setFormIsSaving] = useState(false);\n // Empty state per Figma node 1536-21454: no payment type selected by\n // default. The user must click the Credit card radio to expand the form.\n const [paymentType, setPaymentType] = useState<PaymentType | null>(null);\n // Collapsible drawer: collapsed by default when there are saved cards.\n const [drawerOpen, setDrawerOpen] = useState(false);\n // Auto-select default: fire once per mount. Ref prevents repeat fires if\n // the parent deliberately clears selectedId after initial selection.\n const autoSelectedRef = useRef(false);\n\n const closeModal = useCallback(() => {\n setModalOpen(false);\n setFormError(null);\n setPaymentType(null);\n }, []);\n\n const seededCardholderName =\n defaultCardholderName ??\n ([defaultCardholderFirstName, defaultCardholderLastName].filter(Boolean).join(' ') ||\n undefined);\n\n useEffect(() => {\n if (status === 'ready') setItems(sortDefaultFirst(fetched));\n }, [fetched, status]);\n\n // Issue 1 — Auto-select the default on first load when selection is wired\n // and no card is selected yet. The ref guard fires this exactly once per\n // mount so the parent retains control after the initial selection.\n useEffect(() => {\n if (!onSelect) return;\n if (autoSelectedRef.current) return;\n if (status !== 'ready') return;\n if (items.length === 0) return;\n if (selectedId) return; // parent already has a selection\n autoSelectedRef.current = true;\n const defaultItem = items.find((m) => m.isDefault) ?? items[0];\n onSelect(defaultItem);\n }, [onSelect, status, items, selectedId]);\n\n const updateItems = useCallback(\n (next: PaymentMethodSummary[] | ((prev: PaymentMethodSummary[]) => PaymentMethodSummary[])) => {\n setItems((prev) => {\n const resolved = typeof next === 'function' ? next(prev) : next;\n const sorted = sortDefaultFirst(resolved);\n // Defer the consumer's onChange so it doesn't run inside React's\n // updater function (which executes during render). Calling a parent\n // component's setState during render triggers a \"Cannot update a\n // component while rendering a different component\" warning in dev\n // and is undefined behavior in React 18 concurrent mode.\n queueMicrotask(() => onChange?.(sorted));\n return sorted;\n });\n },\n [onChange],\n );\n\n const mutationsBusy = deleteStatus === 'pending' || setDefaultStatus === 'pending';\n\n const handleSetDefault = useCallback(\n async (method: PaymentMethodSummary) => {\n const snapshot = items;\n setMutationError(null);\n updateItems((prev) => prev.map((m) => ({ ...m, isDefault: m.id === method.id })));\n try {\n await setDefault(method.id);\n refetch();\n } catch (err) {\n setItems(snapshot);\n onChange?.(snapshot);\n const message =\n err instanceof Error ? err.message : 'Failed to set default payment method.';\n setMutationError(message);\n }\n },\n [items, updateItems, setDefault, refetch, onChange],\n );\n\n /**\n * Wrap the consumer's onSelect: forward it, then (when wired) optimistically\n * promote the chosen card to default via the same flow as the explicit\n * setDefault menu. flights-ui's checkout uses this so a single row click\n * does both.\n */\n const handleSelect = useCallback(\n (method: PaymentMethodSummary) => {\n onSelect?.(method);\n if (!selectionSetsDefault) return;\n if (method.isDefault) return; // already the default — no PUT needed\n void handleSetDefault(method);\n },\n [onSelect, selectionSetsDefault, handleSetDefault],\n );\n\n const handleRemove = useCallback(\n async (method: PaymentMethodSummary) => {\n const snapshot = items;\n setMutationError(null);\n const remaining = items.filter((m) => m.id !== method.id);\n updateItems(() => remaining);\n\n // If the deleted card was the selected one, hand the selection off to\n // the next-best candidate (the remaining default; failing that, the\n // first remaining card). Without this, the parent's selectedPaymentMethod\n // stays pinned to the deleted card — flights-ui's Book button check\n // (`!!selectedPaymentMethod`) would stay enabled even though the user\n // can no longer pay with that card, and collapsing the drawer would\n // show a different card than what's actually \"selected\" upstream\n // (the manager's local fallback for display masks the mismatch).\n //\n // If `remaining` is empty there's nothing to select — the consumer's\n // own state (PaymentContext) still holds the deleted card, but the\n // next on-mount auto-select pass will reseed it once a card exists.\n // Adding nullable onSelect support is a follow-up if a consumer hits\n // the \"deleted last card mid-flow\" case in practice.\n const nextSelection =\n method.id === selectedId && onSelect\n ? remaining.find((m) => m.isDefault) ?? remaining[0] ?? null\n : null;\n if (nextSelection) handleSelect(nextSelection);\n\n // Skip the local refetch when handleSelect's promote-to-default branch\n // will fire its own refetch after the PUT settles (flights-ui case\n // where the hand-off becomes the new default). Otherwise we'd\n // double-GET /payment-methods — same pattern as handleCardAdded.\n const willPromoteToDefault =\n Boolean(nextSelection) &&\n selectionSetsDefault &&\n nextSelection !== null &&\n !nextSelection.isDefault;\n\n try {\n await deletePaymentMethod(method.id);\n if (!willPromoteToDefault) refetch();\n } catch (err) {\n setItems(snapshot);\n onChange?.(snapshot);\n const message = err instanceof Error ? err.message : 'Failed to delete payment method.';\n setMutationError(message);\n }\n },\n [\n items,\n updateItems,\n deletePaymentMethod,\n refetch,\n onChange,\n selectedId,\n onSelect,\n handleSelect,\n selectionSetsDefault,\n ],\n );\n\n const handleCardAdded = useCallback(\n (newMethod: PaymentMethodSummary) => {\n setFormError(null);\n setModalOpen(false);\n setPaymentType(null);\n updateItems((prev) => [newMethod, ...prev.filter((m) => m.id !== newMethod.id)]);\n // Selection-mode consumers (flights-ui checkout) expect the\n // just-added card to be active — the user added it RIGHT NOW to pay\n // with it. Matches Delta / United / Booking.com checkout flows.\n // accounts-ui doesn't pass onSelect, so handleSelect is a no-op\n // there — the new card sits in the list and the existing default\n // stays default (correct for a profile-management context).\n // Routing through handleSelect also fires the selectionSetsDefault\n // promotion path so flights-ui's \"selected = default\" coupling\n // applies without a duplicate code path.\n handleSelect(newMethod);\n // Reconcile with server. Skip when handleSelect's set-default branch\n // will fire its own refetch after the PUT settles (i.e. flights-ui\n // mode + new card isn't already default): otherwise we double-GET\n // /payment-methods, once here and once when setDefault resolves.\n const willPromoteToDefault =\n Boolean(onSelect) && selectionSetsDefault && !newMethod.isDefault;\n if (!willPromoteToDefault) refetch();\n },\n [updateItems, refetch, handleSelect, onSelect, selectionSetsDefault],\n );\n\n const handleFormError = useCallback((message: string) => {\n setFormError(message);\n }, []);\n\n const empty = status === 'ready' && items.length === 0;\n const selectable = typeof onSelect === 'function';\n // In collapsible mode we never want the outer rounded-card wrapper — the\n // section already has a border-t divider at the Payments.tsx level.\n const showOuterCard = !selectable && !collapsible;\n // First card becomes the default automatically (matches existing UX).\n const addAsDefault = items.length === 0;\n const shouldAutoSave = autoSaveFirstCard && items.length === 0;\n\n /**\n * When the form is rendered inline (empty state), we use the empty-state\n * defaults: auto-save the first card, internal Save button visible.\n * When rendered inside the modal, we suppress the internal Save button\n * and disable auto-save — the modal footer drives submit.\n */\n const buildCardForm = useCallback(\n (inModal: boolean) => (\n <MovmoCardForm\n userId={userId}\n isDefault={addAsDefault}\n defaultCardholderName={seededCardholderName}\n autoSave={!inModal && shouldAutoSave}\n hideInternalSaveButton={inModal}\n formId={inModal ? ADD_PAYMENT_FORM_ID : undefined}\n onCanSubmitChange={inModal ? setFormCanSubmit : undefined}\n // Track in-flight tokenize / save so the modal-footer Save button\n // can swap its label for a spinner. autoSave (inline empty-state)\n // surfaces the in-flight state via inline text instead.\n onSavingChange={inModal ? setFormIsSaving : undefined}\n // Modal-mounted form: focus the card-number iframe immediately so\n // the user can start typing without an extra click.\n autoFocus={inModal ? 'number' : undefined}\n onSuccess={handleCardAdded}\n onError={handleFormError}\n />\n ),\n [userId, addAsDefault, seededCardholderName, shouldAutoSave, handleCardAdded, handleFormError],\n );\n\n const inlineCardForm = useMemo(() => buildCardForm(false), [buildCardForm]);\n const modalCardForm = useMemo(() => buildCardForm(true), [buildCardForm]);\n\n /** Wraps the card form in the payment-type selector when enabled. */\n const inlineAddBody = useMemo(() => {\n if (!paymentTypeSelector) return inlineCardForm;\n return (\n <PaymentTypeSelector\n selected={paymentType}\n onSelect={(t) => setPaymentType(t)}\n creditCardBody={inlineCardForm}\n />\n );\n }, [paymentTypeSelector, paymentType, inlineCardForm]);\n\n const modalAddBody = useMemo(() => {\n if (!paymentTypeSelector) return modalCardForm;\n return (\n <PaymentTypeSelector\n selected={paymentType}\n onSelect={(t) => setPaymentType(t)}\n creditCardBody={modalCardForm}\n />\n );\n }, [paymentTypeSelector, paymentType, modalCardForm]);\n\n return (\n <div\n className={clsx('flex w-full flex-col gap-4', className)}\n data-testid=\"payment-methods-manager\"\n >\n {status === 'loading' && items.length === 0 ? (\n // Only show the skeleton on first load — during a silent refetch\n // (e.g. after set-default or delete optimistic mutations), the user\n // already sees the correct optimistic list and a skeleton flash\n // here would be jarring.\n <div\n className={clsx(\n // Match the real-list shell so layout doesn't reflow when data\n // arrives. In selection mode the outer card is suppressed too.\n showOuterCard\n ? 'flex flex-col divide-y divide-grayWarm-200 rounded-xl border border-grayWarm-200 px-4 md:px-6'\n : 'flex flex-col gap-2',\n )}\n data-testid=\"payment-methods-loading\"\n >\n <SkeletonRow withDefaultBadge />\n <SkeletonRow />\n </div>\n ) : null}\n\n {status === 'error' ? (\n <div\n role=\"alert\"\n aria-live=\"polite\"\n className=\"flex items-center justify-between gap-3 rounded-md bg-error-50 p-3 text-sm text-error-700\"\n data-testid=\"payment-methods-list-error\"\n >\n <span>{fetchError ?? 'Failed to load payment methods.'}</span>\n <button\n type=\"button\"\n onClick={refetch}\n className=\"rounded-md border border-error-700 px-3 py-1 text-xs font-semibold text-error-700 hover:bg-error-50\"\n >\n Retry\n </button>\n </div>\n ) : null}\n\n {mutationError ? (\n <div\n role=\"alert\"\n aria-live=\"polite\"\n className=\"rounded-md bg-error-50 p-3 text-sm text-error-700\"\n data-testid=\"payment-methods-mutation-error\"\n >\n {mutationError}\n </div>\n ) : null}\n\n {/*\n * Collapsible header: ONE container holding either the collapsed\n * preview row or the expanded \"Payment methods\" h3 + chevron-up.\n * Shared `border-t pt-4` here means the divider line + the chevron\n * button's y-position stays fixed when toggling drawerOpen, so the\n * UI doesn't jump (Issue #5). Matches flights-ui main's pattern.\n */}\n {collapsible && items.length > 0 ? (\n <div className=\"border-t border-grayWarm-200 pt-4\">\n <div\n className=\"flex items-center justify-between\"\n data-testid={\n drawerOpen\n ? 'payment-methods-drawer-header'\n : 'payment-methods-collapsed-preview'\n }\n >\n {drawerOpen ? (\n <h3 className=\"text-md font-semibold text-grayWarm-950\">\n Payment methods\n </h3>\n ) : (\n <PaymentMethodPreview\n method={\n items.find((m) => m.id === selectedId) ??\n items.find((m) => m.isDefault) ??\n items[0]\n }\n cardLabelFormat={cardLabelFormat}\n className=\"flex-1\"\n />\n )}\n <button\n type=\"button\"\n aria-label={\n drawerOpen ? 'Collapse payment methods' : 'Expand payment methods'\n }\n aria-expanded={drawerOpen}\n className=\"bg-grayWarm-100 p-2 rounded-lg hover:bg-grayWarm-200 transition-colors\"\n onClick={() => setDrawerOpen((open) => !open)}\n data-testid={\n drawerOpen\n ? 'payment-methods-drawer-close'\n : 'payment-methods-drawer-open'\n }\n >\n {/*\n * Matches flights-ui main's URLS.icons.doubleDownArrows /\n * doubleUpArrows. Sourced from the configurable iconCdnBaseUrl\n * so the package doesn't hardcode a host.\n */}\n <img\n src={`${getPaymentsConfig().iconCdnBaseUrl}/website/assets/icons/chevron-${\n drawerOpen ? 'up' : 'down'\n }-double.svg`}\n alt=\"\"\n className=\"w-5 h-5\"\n />\n </button>\n </div>\n </div>\n ) : null}\n\n {/* ── Row list: shown always in non-collapsible mode, or when drawer is open ── */}\n {items.length > 0 && (!collapsible || drawerOpen) ? (\n <div\n className={clsx(\n 'flex flex-col',\n // accounts-ui (non-selectable, non-collapsible): rounded outer card\n // with divide-y separators between rows.\n // flights-ui (selectable or collapsible): bare space-y-3 gap between\n // per-row bordered tiles; no outer card chrome.\n showOuterCard\n ? 'rounded-xl border border-grayWarm-200 px-4 md:px-6 divide-y divide-grayWarm-200'\n : 'space-y-3',\n )}\n >\n {items.map((method) => (\n <PaymentMethodRow\n key={method.id}\n method={method}\n selectable={selectable}\n selected={selectable && method.id === selectedId}\n onSelect={handleSelect}\n onSetDefault={handleSetDefault}\n onRemove={handleRemove}\n disabled={mutationsBusy}\n showDefaultBadge={showDefaultBadge}\n hideSetDefaultMenuItem={selectionSetsDefault}\n cardLabelFormat={cardLabelFormat}\n />\n ))}\n </div>\n ) : null}\n\n {empty ? (\n // Empty state: render the add-card body inline (per Figma 1536-21454).\n <div data-testid=\"payment-methods-empty\">{inlineAddBody}</div>\n ) : items.length > 0 && (!collapsible || drawerOpen) ? (\n // Keep the Add button visible during silent refetches (status flips\n // back to 'loading' transiently after set-default / delete).\n // In collapsible mode only show the Add button when the drawer is open.\n <button\n type=\"button\"\n onClick={() => {\n setFormError(null);\n setPaymentType(null);\n setFormCanSubmit(false);\n setModalOpen(true);\n }}\n // Prefetch the tokenization session on hover / keyboard focus.\n // Combined with the in-flight cache in api.ts, this means the\n // modal's MovmoCardForm awaits an already-warm promise — most\n // users won't see the 600-1500ms blank-shell window. Safe to\n // fire-and-forget: errors here are surfaced when the modal-\n // mounted form retries on mount.\n onMouseEnter={() => {\n void fetchTokenizationSession().catch(() => {\n /* prefetch is best-effort — modal mount path will retry */\n });\n }}\n onFocus={() => {\n void fetchTokenizationSession().catch(() => {\n /* prefetch is best-effort — modal mount path will retry */\n });\n }}\n 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\"\n data-testid=\"payment-methods-add-trigger\"\n >\n Add payment method\n </button>\n ) : null}\n\n <AddPaymentMethodModal\n open={modalOpen}\n onClose={closeModal}\n formId={ADD_PAYMENT_FORM_ID}\n saveDisabled={!formCanSubmit}\n isSaving={formIsSaving}\n >\n {modalAddBody}\n {formError ? (\n // Single source of truth for save-time errors (API failures + hook\n // init failures forwarded from MovmoCardForm.onError). MovmoCardForm\n // intentionally does NOT render its own banner — two role=\"alert\"\n // nodes on the same string is a WCAG 4.1.3 violation (announced\n // twice). aria-live=\"polite\" so SR users hear new errors but the\n // announcement doesn't interrupt their current input.\n <p\n role=\"alert\"\n aria-live=\"polite\"\n className=\"mt-3 rounded-md bg-error-50 px-3 py-2 text-sm text-error-700\"\n data-testid=\"payment-methods-modal-error\"\n >\n {formError}\n </p>\n ) : null}\n </AddPaymentMethodModal>\n </div>\n );\n};\n\nPaymentMethodsManager.displayName = 'PaymentMethodsManager';\n\nexport default PaymentMethodsManager;\n","/**\n * Auth-aware `fetch` wrapper for `@movmo_app/payments`. The package's API\n * helpers call through `getPaymentsConfig().fetch`, bypassing whatever axios\n * interceptor stack the consumer wires up. Without this wrapper:\n *\n * - Session cookie expiry → silent 401/403 (no refresh, no logout).\n * - State-mutating endpoints → 403 because the CSRF cookie isn't echoed.\n * - Local-dev / multi-tenant flows → missing per-request headers like\n * `X-Movmo-Proxy-Auth` or `movmo-customer-id`.\n *\n * This factory replaces a ~95-line `paymentsFetch.ts` copy that was\n * duplicated across consumer apps. The contract:\n *\n * 1. CSRF token from `csrfCookieName` is set on every request as\n * `X-CSRF-Token` (matching the axios interceptor's unconditional set).\n * 2. `extraHeaders(input, init)` is invoked per-request to allow dynamic\n * headers (proxy-auth, customer id, etc.). Headers the caller already\n * set on `init.headers` win — `extraHeaders` only fills gaps.\n * 3. `credentials: 'include'` is forced so the session cookie travels.\n * 4. On a 401/403 from a non-auth endpoint, the wrapper calls\n * `refreshSession()` once (concurrent failures share one in-flight\n * promise) and retries the original request. If refresh ITSELF fails,\n * `onRefreshFailed(err)` fires so the consumer can drive a sign-out —\n * silently swallowing here would strand the user on a broken page.\n * Failures on the *retry* fetch are logged and the original response is\n * returned so the SDK still sees a Response to render an error from.\n * 5. The original fetch's network errors (offline, CORS, DNS) propagate.\n * Only retry-path failures are caught; pre-refresh errors are left for\n * the consumer to surface.\n *\n * The duplicated copies that this replaces both silently swallowed refresh\n * failure (see review issue #1 on both PR #47 + PR #180). Making\n * `onRefreshFailed` *required* enforces at the type level that consumers\n * wire up a logout path.\n */\n\n/** Default substring used to identify the auth-refresh path that must skip the refresh-on-401 retry loop. */\nconst DEFAULT_AUTH_PATH_FRAGMENT = '/v1/auth/';\nconst DEFAULT_CSRF_COOKIE = 'movmo_csrf_token';\n\nexport interface CreateMovmoAuthFetchOptions {\n /**\n * Refreshes the session cookie. Called once on the first 401/403; concurrent\n * 401/403s share the same in-flight promise. Resolved value is ignored — the\n * wrapper only cares about success vs. rejection. Must rotate the session\n * cookie (and CSRF cookie, if applicable) such that a retry with the same\n * request will succeed.\n */\n refreshSession: () => Promise<unknown>;\n /**\n * Fired when `refreshSession()` itself rejects. The consumer MUST treat this\n * as a terminal auth failure and trigger a sign-out + redirect — otherwise\n * the user is stranded on a broken page with `authState.isAuthenticated`\n * still true.\n *\n * Receives the underlying rejection so the consumer can log it.\n */\n onRefreshFailed: (error: unknown) => void;\n /**\n * Cookie name carrying the CSRF token. Defaults to `movmo_csrf_token`.\n */\n csrfCookieName?: string;\n /**\n * Optional per-request header builder. Evaluated on every call (not cached)\n * so dynamically-changing headers (e.g. `movmo-customer-id` driven by a\n * route param) reflect the current value. Headers the caller already set\n * on `init.headers` always win — `extraHeaders` only fills gaps.\n */\n extraHeaders?: (input: RequestInfo | URL, init?: RequestInit) => Record<string, string>;\n /**\n * Substring used to detect requests that must NOT trigger the refresh\n * retry — typically the auth-refresh endpoint itself, to avoid an\n * infinite recursion when refresh returns 401. Defaults to `/v1/auth/`.\n */\n authPathFragment?: string;\n /**\n * Underlying fetch impl. Defaults to `globalThis.fetch.bind(globalThis)`.\n * Override only for tests or non-browser environments.\n */\n baseFetch?: typeof fetch;\n /**\n * Cookie reader. Defaults to reading `document.cookie`. Override only in\n * non-browser test environments — the default works in jsdom.\n */\n readCookie?: (name: string) => string | null;\n}\n\nconst defaultReadCookie = (name: string): string | null => {\n if (typeof document === 'undefined') return null;\n const cookies = document.cookie ? document.cookie.split(';') : [];\n for (const cookie of cookies) {\n const trimmed = cookie.trim();\n if (trimmed.startsWith(name + '=')) {\n return decodeURIComponent(trimmed.substring(name.length + 1));\n }\n }\n return null;\n};\n\nconst urlString = (input: RequestInfo | URL): string => {\n if (typeof input === 'string') return input;\n if (input instanceof URL) return input.href;\n return input.url;\n};\n\nconst defaultBaseFetch = (): typeof fetch => {\n if (typeof globalThis !== 'undefined' && typeof globalThis.fetch === 'function') {\n return globalThis.fetch.bind(globalThis);\n }\n throw new Error('@movmo_app/payments: no global fetch available in this environment');\n};\n\n/**\n * Builds an auth-aware `fetch` that the payments package (or any other\n * consumer that registers it via `setPaymentsConfig({ fetch })`) can call.\n * See file header for the full contract.\n */\nexport const createMovmoAuthFetch = (options: CreateMovmoAuthFetchOptions): typeof fetch => {\n const {\n refreshSession,\n onRefreshFailed,\n csrfCookieName = DEFAULT_CSRF_COOKIE,\n extraHeaders,\n authPathFragment = DEFAULT_AUTH_PATH_FRAGMENT,\n baseFetch = defaultBaseFetch(),\n readCookie = defaultReadCookie,\n } = options;\n\n // Module-scoped (per-factory) lock that coalesces concurrent 401/403s into\n // one refresh call. Cleared in `.finally()` AFTER assignment — a try/finally\n // inside the body would clear it synchronously on synchronous throws and\n // leak the rejected promise back to the next caller.\n let refreshInFlight: Promise<void> | null = null;\n\n const performRefresh = (): Promise<void> => {\n if (refreshInFlight) return refreshInFlight;\n const promise = (async () => {\n await refreshSession();\n })();\n refreshInFlight = promise;\n promise\n .finally(() => {\n if (refreshInFlight === promise) refreshInFlight = null;\n })\n .catch(() => {\n /* swallow on the dangling chain — rejection still propagates via `promise` */\n });\n return promise;\n };\n\n const buildInit = (input: RequestInfo | URL, init?: RequestInit): RequestInit => {\n const headers = new Headers(init?.headers);\n const csrf = readCookie(csrfCookieName);\n if (csrf && !headers.has('X-CSRF-Token')) {\n headers.set('X-CSRF-Token', csrf);\n }\n if (extraHeaders) {\n const extras = extraHeaders(input, init);\n for (const [k, v] of Object.entries(extras)) {\n if (!headers.has(k)) headers.set(k, v);\n }\n }\n return {\n ...init,\n headers,\n credentials: init?.credentials ?? 'include',\n };\n };\n\n return async function movmoAuthFetch(input, init) {\n // First attempt — network errors here propagate. Swallowing them would\n // leave the SDK with no Response to render an error from AND no thrown\n // error to catch, producing a silent hang.\n const initialRes = await baseFetch(input, buildInit(input, init));\n\n const url = urlString(input);\n const isAuthPath = url.includes(authPathFragment);\n if (isAuthPath || (initialRes.status !== 401 && initialRes.status !== 403)) {\n return initialRes;\n }\n\n // First narrow catch: refresh itself failed → must drive logout, then\n // return the original 401/403 so the SDK still surfaces a structured\n // error. Returning the un-retried response is intentional — re-throwing\n // would force every caller to also catch, and the 401 body is what they\n // expected to handle anyway.\n try {\n await performRefresh();\n } catch (refreshError) {\n try {\n onRefreshFailed(refreshError);\n } catch (callbackError) {\n // Don't let a misbehaving onRefreshFailed callback take down the\n // wrapper. Log so the regression is visible in dev tools.\n // eslint-disable-next-line no-console\n console.error(\n '@movmo_app/payments: onRefreshFailed callback threw — auth retry path is misconfigured',\n callbackError,\n );\n }\n return initialRes;\n }\n\n // Second narrow catch: refresh succeeded but the retry-network call\n // failed (offline, CORS, DNS). Log it and return the original 401/403 so\n // the SDK has *something* to render an error from. We don't propagate\n // here because the consumer's primary failure surface is the 401, not\n // the retry's transient network blip.\n try {\n return await baseFetch(input, buildInit(input, init));\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\n '@movmo_app/payments: retry after token refresh failed — returning original response',\n retryError,\n );\n return initialRes;\n }\n };\n};\n"],"names":["f","require$$0","k","l","m","n","p","q","c","a","g","b","d","e","h","reactJsxRuntime_production_min","React","REACT_ELEMENT_TYPE","REACT_PORTAL_TYPE","REACT_FRAGMENT_TYPE","REACT_STRICT_MODE_TYPE","REACT_PROFILER_TYPE","REACT_PROVIDER_TYPE","REACT_CONTEXT_TYPE","REACT_FORWARD_REF_TYPE","REACT_SUSPENSE_TYPE","REACT_SUSPENSE_LIST_TYPE","REACT_MEMO_TYPE","REACT_LAZY_TYPE","REACT_OFFSCREEN_TYPE","MAYBE_ITERATOR_SYMBOL","FAUX_ITERATOR_SYMBOL","getIteratorFn","maybeIterable","maybeIterator","ReactSharedInternals","error","format","_len2","args","_key2","printWarning","level","ReactDebugCurrentFrame","stack","argsWithFormat","item","enableScopeAPI","enableCacheElement","enableTransitionTracing","enableLegacyHidden","enableDebugTracing","REACT_MODULE_REFERENCE","isValidElementType","type","getWrappedName","outerType","innerType","wrapperName","displayName","functionName","getContextName","getComponentNameFromType","context","provider","outerName","lazyComponent","payload","init","assign","disabledDepth","prevLog","prevInfo","prevWarn","prevError","prevGroup","prevGroupCollapsed","prevGroupEnd","disabledLog","disableLogs","props","reenableLogs","ReactCurrentDispatcher","prefix","describeBuiltInComponentFrame","name","source","ownerFn","x","match","reentry","componentFrameCache","PossiblyWeakMap","describeNativeComponentFrame","fn","construct","frame","control","previousPrepareStackTrace","previousDispatcher","Fake","sample","sampleLines","controlLines","s","_frame","syntheticFrame","describeFunctionComponentFrame","shouldConstruct","Component","prototype","describeUnknownElementTypeFrameInDEV","hasOwnProperty","loggedTypeFailures","setCurrentlyValidatingElement","element","owner","checkPropTypes","typeSpecs","values","location","componentName","has","typeSpecName","error$1","err","ex","isArrayImpl","isArray","typeName","value","hasToStringTag","willCoercionThrow","testStringCoercion","checkKeyStringCoercion","ReactCurrentOwner","RESERVED_PROPS","specialPropKeyWarningShown","specialPropRefWarningShown","hasValidRef","config","getter","hasValidKey","warnIfStringRefCannotBeAutoConverted","self","defineKeyPropWarningGetter","warnAboutAccessingKey","defineRefPropWarningGetter","warnAboutAccessingRef","ReactElement","key","ref","jsxDEV","maybeKey","propName","defaultProps","ReactCurrentOwner$1","ReactDebugCurrentFrame$1","setCurrentlyValidatingElement$1","propTypesMisspellWarningShown","isValidElement","object","getDeclarationErrorAddendum","getSourceInfoErrorAddendum","ownerHasKeyUseWarning","getCurrentComponentErrorInfo","parentType","info","parentName","validateExplicitKey","currentComponentErrorInfo","childOwner","validateChildKeys","node","child","iteratorFn","iterator","step","validatePropTypes","propTypes","_name","validateFragmentProps","fragment","keys","didWarnAboutKeySpread","jsxWithValidation","isStaticChildren","validType","sourceInfo","typeString","children","i","beforeExample","afterExample","jsxWithValidationStatic","jsxWithValidationDynamic","jsx","jsxs","reactJsxRuntime_development","jsxRuntimeModule","require$$1","r","o","clsx","DEFAULT_SPREEDLY_SCRIPT_URL","DEFAULT_ICON_CDN_BASE_URL","overrides","setPaymentsConfig","readEnv","proc","_a","getPaymentsConfig","toSummary","body","jsonHeaders","apiUrl","path","baseUrl","performFetch","input","configuredFetch","readError","res","fallback","inFlightTokenizationSession","fetchTokenizationSession","promise","isFullPaymentMethodBody","savePaymentMethodFromToken","userId","tokenizedPaymentMethodId","isDefault","getRes","fullBody","listPaymentMethods","signal","deletePaymentMethod","methodId","updatePaymentMethod","patch","BRAND_SLUG","MIN_RENDER_WIDTH","CardBrandIcon","brand","className","width","slug","renderWidth","renderHeight","iconCdnBaseUrl","scriptPromise","loadSpreedlyScript","spreedlyScriptUrl","resolve","reject","existing","onScriptLoad","script","DEFAULT_NUMBER_EL","DEFAULT_CVV_EL","toSdkPayload","data","useMovmoCardFields","options","numberEl","cvvEl","onCardTokenized","onFieldErrors","onValidityChange","onBrandChange","status","setStatus","useState","setError","validity","setValidity","setBrand","focused","setFocused","spreedlyRef","useRef","onCardTokenizedRef","onFieldErrorsRef","onValidityChangeRef","onBrandChangeRef","useEffect","validityRef","cancelled","session","spreedly","_b","_c","_d","iframeFontStyle","_e","_f","token","errors","_activeEl","inputProperties","prev","next","newValid","message","tokenize","useCallback","focusField","field","fieldShellClass","iframeShellClass","iframeShellActiveClass","iframeShellIdleClass","splitName","full","trimmed","lastSpace","parseExpiry","raw","digits","month","yearRaw","year","formatExpiryInput","isExpiryValid","mm","yyyy","now","isZipValid","formatZipInput","MovmoCardForm","onSuccess","onError","defaultCardholderName","defaultCardholderFirstName","defaultCardholderLastName","autoSave","formId","hideInternalSaveButton","onCanSubmitChange","onSavingChange","autoFocus","seededName","cardholderName","setCardholderName","expiry","setExpiry","zip","setZip","formStatus","setFormStatus","autoSubmittedRef","handleCardTokenized","summary","handleFieldErrors","hookOptions","useMemo","hookStatus","hookError","autoFocusedRef","nameValid","expiryValid","zipValid","autoFocusedCvvRef","autoFocusedZipRef","autoFocusedNameRef","zipInputRef","cardholderNameInputRef","formInvalid","isBusy","canSubmit","onCanSubmitChangeRef","onSavingChangeRef","submit","firstName","lastName","timer","handleSubmit","inputsDisabled","onErrorRef","useDeletePaymentMethod","deletePaymentMethodApi","useSetDefaultPaymentMethod","useUserPaymentMethods","items","setItems","tick","setTick","abortRef","controller","result","refetch","AddPaymentMethodModal","open","onClose","saveDisabled","saveLabel","isSaving","onKey","Fragment","prettyBrand","PaymentMethodPreview","method","trailing","onClick","cardLabelFormat","isExpired","expMonth","expYear","formatExpiry","PaymentMethodRow","selectable","selected","onSelect","onSetDefault","onRemove","disabled","showDefaultBadge","hideSetDefaultMenuItem","menuOpen","setMenuOpen","menuContainerRef","expired","onDocClick","handleRowClick","altIconUrl","AltIcon","alt","OtherOptionRow","label","iconNode","PaymentTypeSelector","creditCardBody","isCreditCardSelected","ADD_PAYMENT_FORM_ID","sortDefaultFirst","defaults","rest","SkeletonRow","withDefaultBadge","PaymentMethodsManager","selectedId","onChange","paymentTypeSelector","autoSaveFirstCard","selectionSetsDefault","collapsible","fetched","fetchError","deleteStatus","setDefault","setDefaultStatus","mutationError","setMutationError","modalOpen","setModalOpen","formError","setFormError","formCanSubmit","setFormCanSubmit","formIsSaving","setFormIsSaving","paymentType","setPaymentType","drawerOpen","setDrawerOpen","autoSelectedRef","closeModal","seededCardholderName","defaultItem","updateItems","resolved","sorted","mutationsBusy","handleSetDefault","snapshot","handleSelect","handleRemove","remaining","nextSelection","willPromoteToDefault","handleCardAdded","newMethod","handleFormError","empty","showOuterCard","addAsDefault","shouldAutoSave","buildCardForm","inModal","inlineCardForm","modalCardForm","inlineAddBody","t","modalAddBody","DEFAULT_AUTH_PATH_FRAGMENT","DEFAULT_CSRF_COOKIE","defaultReadCookie","cookies","cookie","urlString","defaultBaseFetch","createMovmoAuthFetch","refreshSession","onRefreshFailed","csrfCookieName","extraHeaders","authPathFragment","baseFetch","readCookie","refreshInFlight","performRefresh","buildInit","headers","csrf","extras","v","initialRes","refreshError","callbackError","retryError"],"mappings":";;;;;;;;;;;;;;;AASa,MAAIA,IAAEC,IAAiBC,IAAE,OAAO,IAAI,eAAe,GAAEC,IAAE,OAAO,IAAI,gBAAgB,GAAEC,IAAE,OAAO,UAAU,gBAAeC,IAAEL,EAAE,mDAAmD,mBAAkBM,IAAE,EAAC,KAAI,IAAG,KAAI,IAAG,QAAO,IAAG,UAAS,GAAE;AAClP,WAASC,EAAEC,GAAEC,GAAEC,GAAE;AAAC,QAAIC,GAAEC,IAAE,CAAA,GAAGC,IAAE,MAAKC,IAAE;AAAK,IAASJ,MAAT,WAAaG,IAAE,KAAGH,IAAYD,EAAE,QAAX,WAAiBI,IAAE,KAAGJ,EAAE,MAAcA,EAAE,QAAX,WAAiBK,IAAEL,EAAE;AAAK,SAAIE,KAAKF,EAAE,CAAAL,EAAE,KAAKK,GAAEE,CAAC,KAAG,CAACL,EAAE,eAAeK,CAAC,MAAIC,EAAED,CAAC,IAAEF,EAAEE,CAAC;AAAG,QAAGH,KAAGA,EAAE,aAAa,MAAIG,KAAKF,IAAED,EAAE,cAAaC,EAAE,CAASG,EAAED,CAAC,MAAZ,WAAgBC,EAAED,CAAC,IAAEF,EAAEE,CAAC;AAAG,WAAM,EAAC,UAAST,GAAE,MAAKM,GAAE,KAAIK,GAAE,KAAIC,GAAE,OAAMF,GAAE,QAAOP,EAAE,QAAO;AAAA,EAAC;AAAC,SAAAU,cAAiBZ,GAAEY,GAAA,MAAYR,GAAEQ,GAAA,OAAaR;;;;;;;;;;;;;;wBCEtW,QAAQ,IAAI,aAAa,gBAC1B,WAAW;AAGd,QAAIS,IAAQf,IAMRgB,IAAqB,OAAO,IAAI,eAAe,GAC/CC,IAAoB,O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