@flopay/react 1.18.1 → 1.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -0
- package/dist/flopay-checkout.d.ts +12 -2
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +7 -7
- package/dist/split-card-form.d.ts +11 -1
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Vd=Object.create;var fi=Object.defineProperty;var Wd=Object.getOwnPropertyDescriptor;var $d=Object.getOwnPropertyNames;var Hd=Object.getPrototypeOf,Kd=Object.prototype.hasOwnProperty;var Gd=(e,t)=>{for(var r in t)fi(e,r,{get:t[r],enumerable:!0})},Zl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of $d(t))!Kd.call(e,a)&&a!==r&&fi(e,a,{get:()=>t[a],enumerable:!(n=Wd(t,a))||n.enumerable});return e};var Es=(e,t,r)=>(r=e!=null?Vd(Hd(e)):{},Zl(t||!e||!e.__esModule?fi(r,"default",{value:e,enumerable:!0}):r,e)),Yd=e=>Zl(fi({},"__esModule",{value:!0}),e);var Dp={};Gd(Dp,{DirectPayPalButton:()=>Da,FloPayAutomaticPaymentButton:()=>id,FloPayCardSetup:()=>sd,FloPayCardSetupError:()=>ei,FloPayCheckout:()=>Gi,FloPayPaymentMethodSetup:()=>Pd,FloPayProvider:()=>Na,SplitCardForm:()=>Wi,VaultCardFields:()=>_o,dropThirdPartyOnlyError:()=>Cd.dropThirdPartyOnlyError,useCheckout:()=>uc,useFloPay:()=>uo,usePayPalFloPay:()=>vi});module.exports=Yd(Dp);var Cd=require("@flopay/shared");var Yi=require("@flopay/js"),Ir=require("@flopay/shared"),pt=require("react");var Zt=require("react/jsx-runtime");function Xd(){return(0,Zt.jsxs)(Zt.Fragment,{children:[(0,Zt.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,Zt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Zt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Zt.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,Zt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Jd(){return(0,Zt.jsx)(Zt.Fragment,{children:"Go back"})}function Zd(){return(0,Zt.jsx)(Zt.Fragment,{children:"Secure card checkout"})}function na(e){return e!==void 0&&(e===""||e===null||e===!1)}function oa({content:e}){return(0,Zt.jsx)(Zt.Fragment,{children:e===void 0?(0,Zt.jsx)(Xd,{}):e})}function aa({content:e}){return(0,Zt.jsx)(Zt.Fragment,{children:e===void 0?(0,Zt.jsx)(Jd,{}):e})}function Ma({content:e}){return(0,Zt.jsx)(Zt.Fragment,{children:e===void 0?(0,Zt.jsx)(Zd,{}):e})}var _t=require("@flopay/shared"),Un=require("@flopay/shared"),la=require("@flopay/shared"),Fo=require("@flopay/shared");function _s(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof _t.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Qd(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function Ql(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,_t.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,_t.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function ec(e,t){if(t&&(!(e instanceof _t.FloPayError)||e.type==="authentication_error"))return _s(e);if(!(e instanceof _t.FloPayError&&Qd(e))){if(!t&&!(e instanceof _t.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,_t.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof _t.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof _t.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function ia(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let d={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,_t.isCardHolderNamePlaceholder)(d.firstName,d.lastName);if(!(0,_t.isValidEmail)(d.email))return Promise.reject(new _t.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[w,h]of Object.entries(d)){if(p&&w.endsWith("Name")||typeof h!="string")continue;let g=h.trim();g&&(m[w]=g)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function tc(e,t){if(!t)return e;if(!e)return t;let r;return"checkoutMetadata"in t?r=t:"checkoutMetadata"in e&&(r=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...r?{checkoutMetadata:r.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Is(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function rc(e,t){let r=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],n=r.reduce((s,d)=>s+(d.overrideAmount??d.totalAmount??0),0),a=e.currency??r.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(n*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:r.map((s,d)=>({uuid:`synthetic-${s.type??"item"}-${d}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??a,metadata:s.metadata??null}))}}function Ts(e,t){return t?{...e,...t}:e}function kr(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,s=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,d=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...s?{declineCode:s}:{},...d?{sessionId:d}:{}}}var nc=new WeakMap;function oc(e,t){return typeof e=="object"&&e!==null&&nc.set(e,t?{sessionId:t}:{}),e}function ac(e){return typeof e=="object"&&e!==null?nc.get(e):void 0}function Ro(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function so(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function lo(e){return e?.status==="authorized"||e?.status==="complete"}function ko(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,a=r?.status==="authorized"||n==="AUTHORIZED";return a||r?.status==="completed"||n==="SUCCESS"?{...t,status:a?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function ic(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function gi(e){let t=ic(e);return new _t.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function hi(e){return e instanceof _t.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function sa(e){return ic(e)?new _t.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new _t.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new _t.FloPayError(_t.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function Aa(e,t){return e==="processing"||(0,_t.isMoneySettledOutcome)(e,t)}function sc(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function lc(e,t){let r=e;if((0,_t.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:d}=await r.retrieveSetupIntent(t);if(d)throw new _t.FloPayError(d.message??"Failed to retrieve setup intent.","api_error",{...d.code?{code:d.code}:{}});return s??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new _t.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var eu=["apple_pay","google_pay"];function cc(e,t="automatic",r){let n=(0,_t.resolveSetupFutureUsage)(r,eu,"wallet");return{...(0,_t.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var tu=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Ms(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:tu.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function xa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var mo=require("@flopay/js"),se=require("@flopay/shared"),R=Es(require("react"),1);var As=require("react"),Rn=(0,As.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),zn=(0,As.createContext)({session:null,loading:!1,error:null});var ki=require("@flopay/js"),ze=require("@flopay/shared"),gc=require("@paypal/paypal-js"),E=require("react");var Pi=require("@flopay/shared"),qn=require("react"),kn=require("@flopay/shared"),co=require("react/jsx-runtime");function ca(){let[e,t]=(0,qn.useState)(null),r=(0,qn.useRef)(null),n=(0,qn.useRef)(0),a=(0,qn.useCallback)((d,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:d,identity:p}),new Promise(m=>{r.current=m})),[]),s=(0,qn.useCallback)(d=>{let p=r.current;r.current=null,t(null),p?.(d)},[]);return(0,qn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function da({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[d,p]=(0,qn.useState)(e.email?.trim()??""),m=(0,Pi.isValidEmail)(d.trim());return(0,co.jsxs)("div",{"data-testid":s,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,co.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,co.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,co.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:d,onChange:w=>p(w.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,co.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,co.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,co.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,Pi.compactBuyerIdentity)({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var _e=require("@flopay/shared");var dc=require("@flopay/shared"),Fa=require("react");function uo(){return(0,Fa.useContext)(Rn).flopay}function vi(){return(0,Fa.useContext)(Rn).paypalFlopay??null}function uc(){return(0,Fa.useContext)(zn)}function pc(){return(0,Fa.useContext)(Rn).billingApiUrl||(0,dc.resolveBillingApiUrl)()}var ru=require("@flopay/shared"),Jn=require("@flopay/shared"),Zn=require("@flopay/shared");var ua=require("@flopay/shared"),Oo=require("react");var Ci=require("react"),Bo=typeof window>"u"?Ci.useEffect:Ci.useLayoutEffect;var xs=require("@flopay/shared");function pa(e,t){let r=(0,Oo.useRef)(e);r.current=e;let n=(0,Oo.useRef)(new Set),a=(0,Oo.useRef)(t),s=(0,Oo.useRef)(t);return Bo(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,Oo.useCallback)(d=>{if(s.current!==t)return;let p=(0,ua.projectFloInstrument)(d);if(p){if(ua.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,ua.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var He=require("@flopay/shared");var yc=require("react"),Ba=(0,yc.createContext)(null);function bi(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Si="provider.callback.ignored";function wi(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var nu=Symbol.for("@flopay/js.telemetry.bridge.v1"),ou=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function au(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function iu(e){let t=au(),r=(a,s)=>a?a.bind(e):s,n=r(e.now,t.now);return{error:r(e.error,t.error),log:r(e.log,t.log),performance:r(e.performance,t.performance),terminal:r(e.terminal,t.terminal),now:n,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,n()-a),setCheckoutContext:r(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:r(e.beginCheckout,t.beginCheckout),disable:r(e.disable,t.disable),subscribe:r(e.subscribe,t.subscribe),flush:r(e.flush,t.flush),destroy:r(e.destroy,t.destroy)}}function Ri(e){let t=globalThis[ou];return iu(t?.(e)??{})}function Er(e){if(e)return e[nu]}var hr=require("react");function Oa(e,t){let r=(0,hr.useRef)(0),n=(0,hr.useRef)(null),a=(0,hr.useRef)(null),s=(0,hr.useRef)(e),d=(0,hr.useRef)(t?.onHandoffObserved),p=(0,hr.useRef)(t?.defersMissingTerminal),m=(0,hr.useRef)(t?.onMissingTerminalDeferred);(0,hr.useEffect)(()=>{s.current=e,d.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let w=(0,hr.useCallback)((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),h=(0,hr.useCallback)(f=>{w();let H=r.current+1;return r.current=H,n.current=null,a.current={generation:H,method:f,timer:null,yieldedControl:!1},H},[w]),g=(0,hr.useCallback)(f=>{let H=a.current;return f!==void 0&&H?.generation!==f?!1:(w(H),a.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[w]),_=(0,hr.useCallback)(f=>{let H=a.current,Y=f??H?.generation??r.current;(f===void 0||H?.generation===f)&&(w(H),a.current=null),n.current=Y},[w]),V=(0,hr.useCallback)(f=>n.current===(f??r.current),[]),W=(0,hr.useCallback)(f=>a.current?.generation===f&&n.current!==f,[]),k=(0,hr.useCallback)(()=>{let f=a.current;f&&(w(f),!f.yieldedControl&&(f.yieldedControl=!0,d.current?.(f.method)))},[w]),A=(0,hr.useCallback)(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(w(f),f.timer=setTimeout(()=>{if(f.timer=null,a.current?.generation===f.generation){if(p.current?.(f.method)){m.current?.(f.method,f.generation);return}a.current=null,n.current=f.generation,s.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},_e.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[w]);return(0,hr.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?A():k()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",k),window.addEventListener("focus",A),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",k),window.removeEventListener("focus",A),w()}},[w,k,A]),{startAttempt:h,finishAttempt:g,invalidateAttempt:_,isAttemptInvalidated:V,isAttemptCurrent:W,generationRef:r}}var En=require("react/jsx-runtime"),Ei=45,su=1e3,lu=11e3,mc="paypal_intent_settled",cu={width:"100%",minHeight:Ei,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},du={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function uu(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:du[e.kind]??null}}function fc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,_e.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function pu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function hc({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:d,environment:p,currency:m,isSubscription:w,providerObjectType:h,approvalPresentation:g,onTokenizedBody:_,onComplete:V,onErrorChange:W,onDecline:k,onCancel:A,onTechnicalFailure:f,isProcessing:H=!1,onLoadStateChange:Y,onInitializationStateChange:b,allowAutomaticRetry:be=!0,onButtonClick:x,runBeforeButtonClick:oe,session:ge,existingOrderId:Ie,telemetry:ce,telemetryContext:Rt,onInstrument:mt,debug:q=!1}){let Ve=uo(),We=pa(mt,e),Ne=(0,E.useMemo)(()=>{if(Ve)return null;let P=Ri({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:ze.SDK_VERSION,enabled:ce!==!1});return P.setCheckoutContext(Rt??{}),P.beginCheckout(Rt??{}),P},[r,Ve,ce,Rt?.checkoutMode,Rt?.layout]),ve=(0,E.useMemo)(()=>Er(Ve),[Ve]);(0,E.useEffect)(()=>()=>{Ne&&Ne.flush().catch(()=>{}).finally(()=>Ne.destroy())},[Ne]);let G=(0,E.useMemo)(()=>({error:P=>{ve?ve.error(P):Ne?.error(P),We({class:"technical_error",errorCode:P.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":P.errorCode,requestCategory:P.requestCategory,provider:P.provider})},log:P=>{ve?ve.log(P):Ne?.log(P),We({class:"lifecycle",name:P.name,provider:P.provider})},performance:P=>{ve?ve.performance(P):Ne?.performance(P)},terminal:P=>{ve?ve.terminal(P):Ne?.terminal(P)},startTiming:()=>ve?.now()??Ne?.now()??0,elapsed:P=>ve?.elapsed(P)??Math.max(0,(Ne?.now()??P)-P)}),[We,ve,Ne]),K=(0,E.useRef)(null),Ze=(0,E.useRef)(0),Se=(0,E.useRef)(null),qe=(0,E.useRef)(null),Z=(0,E.useRef)(null),j=(0,E.useContext)(Ba),he=(0,E.useRef)(null);he.current||(he.current=bi());let X=j??he.current,Pt=(0,E.useRef)(null),pe=(0,E.useRef)(!1),[we,Ae]=(0,E.useState)(!1),[Ce,kt]=(0,E.useState)(!1),[Pe,Be]=(0,E.useState)(0),at=(0,E.useRef)(0),[yt,Mt]=(0,E.useState)(!1),le=(0,E.useRef)(!1),It=(0,E.useRef)(!1),[Vt,xe]=(0,E.useState)(!1),[Oe,Ke]=(0,E.useState)(!1),{request:vt,collect:it,finish:ft}=ca(),Lt=(0,E.useRef)({sessionId:e,required:(0,ze.paypalProviderIdentityRequired)(n,ge)});Lt.current.sessionId!==e&&(Lt.current={sessionId:e,required:(0,ze.paypalProviderIdentityRequired)(n,ge)});let Qe=Lt.current.required,st=(0,E.useMemo)(()=>r.replace(/\/+$/,""),[r]),Ot=ge?.gateways?.paypal?.providerObjectType??h,et=Ot??(w?"subscription":"order"),[re]=(0,E.useState)(Jn.detectPayPalEnvironment),v=ge?.gateways?.paypal?.approvalPresentation??g,Q=(0,Zn.resolvePayPalPresentationMode)(re,v==="app_switch"?"app_switch":void 0,et),ee=(0,ze.usesPayPalVaultedChannel)(Ot),$=(0,E.useMemo)(()=>JSON.stringify([st,d,m,p??"",et,ee,Q,e,Ie??""]),[st,d,m,p,Ie,et,ee,Q,e]),nt=(0,E.useRef)($),u=nt.current!==$,F=(0,E.useRef)(q),D=(0,E.useRef)(null),[L,T]=(0,E.useState)([]),I=(0,E.useCallback)(P=>{F.current&&T(xt=>[...xt,`${new Date().toISOString().slice(11,23)} ${P}`])},[]);(0,E.useEffect)(()=>{F.current=q,q&&I("debug:enabled"),D.current?.setEnabled(q)},[I,q]);let Ct=(0,E.useRef)(_),Mr=(0,E.useRef)(V),bt=(0,E.useRef)(W),un=(0,E.useRef)(k),gt=(0,E.useRef)(A),vr=(0,E.useRef)(f),At=(0,E.useRef)(x),Ar=(0,E.useRef)(Y),Cr=(0,E.useRef)(b),Xt=(0,E.useRef)(s),Jr=(0,E.useRef)(oe),xr=(0,E.useRef)(ge),Ur=(0,E.useRef)(n),pn=(0,E.useRef)(a),Fr=(0,E.useRef)(t),Wt=(0,E.useRef)(null),br=(0,E.useRef)(new Map),Tt=(0,E.useRef)(new Map),St=(0,E.useRef)(!1),lt=(0,E.useRef)(e);lt.current=e;let[yn]=(0,E.useState)(wi);(0,E.useEffect)(()=>(St.current=!0,()=>{St.current=!1}),[]),(0,E.useEffect)(()=>{Ct.current=_},[_]),(0,E.useEffect)(()=>{Xt.current=s},[s]),(0,E.useEffect)(()=>{Mr.current=V},[V]),(0,E.useEffect)(()=>{bt.current=W},[W]),(0,E.useEffect)(()=>{un.current=k},[k]),(0,E.useEffect)(()=>{gt.current=A},[A]),(0,E.useEffect)(()=>{vr.current=f},[f]),(0,E.useEffect)(()=>{At.current=x},[x]),(0,E.useEffect)(()=>{Ar.current=Y},[Y]),(0,E.useEffect)(()=>{Cr.current=b},[b]),(0,E.useEffect)(()=>{Jr.current=oe},[oe]),(0,E.useEffect)(()=>{xr.current=ge},[ge]),(0,E.useEffect)(()=>{Ur.current=n},[n]),(0,E.useEffect)(()=>{pn.current=a},[a]),(0,E.useEffect)(()=>{Fr.current=t},[t]),(0,E.useEffect)(()=>{at.current=Pe},[Pe]),(0,E.useEffect)(()=>{yt&&Pt.current?.focus()},[yt,Pe]);let ur=(0,E.useCallback)(()=>{window.setTimeout(()=>{Pt.current?.focus()},0)},[]),zr=(0,E.useCallback)(()=>{Ae(!1),Be(P=>P+1)},[]),An=(0,E.useCallback)(()=>{Mt(!1),(K.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??K.current)?.focus?.()},[]);(0,E.useEffect)(()=>{!we||!pe.current||(pe.current=!1,An())},[An,we,Pe]);let mn=(0,E.useCallback)((P,xt)=>{let te=xt?.popupBlocked??(0,_e.isPopupBlockedError)(P);te&&X.markBlocked();let ae=(0,_e.buildExternalMethodRecoveryMessage)("PayPal",te,re.inAppBrowser),zt=vr.current;if(zt){let Ft=te&&re.inAppBrowser?new ze.FloPayError(ae,"api_error",{code:xt?.code??"paypal_popup_blocked"}):P;zt("paypal",Ft,xt);return}if(P instanceof ze.FloPayError&&P.code==="checkout_processing_timeout"){bt.current?.(P.message);return}bt.current?.(ae)},[X,re.inAppBrowser]),qr=(0,E.useCallback)(P=>{let xt=Se.current,te=qe.current;xt===null||!te||(G.log({...te,popupCapability:X.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:P}),G.performance({...te,popupCapability:X.current(),stage:"overlay_return",durationMs:G.elapsed(xt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:P}),Se.current=null)},[X,G]),fn=(0,E.useCallback)((P,xt,te)=>{let ae=qe.current;qr("overlay_timeout"),ae&&G.error({...ae,popupCapability:X.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),mn(xt,{...te,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Q,terminalReason:"overlay_timeout"}),Mt(!0),zr(),ur()},[qr,ur,mn,X,Q,zr,G]),gn=(0,E.useCallback)(()=>{X.markAvailable();let P=qe.current;P&&(Z.current=P.attempt,G.log({...P,popupCapability:X.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[X,G]),pr=(0,E.useCallback)(()=>!0,[]),tr=(0,E.useCallback)(()=>{let P=qe.current;if(!P)return;let xt=Se.current;G.performance({...P,popupCapability:X.current(),stage:"overlay_return",durationMs:xt===null?0:G.elapsed(xt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[X,G]),{finishAttempt:on,generationRef:Zr,invalidateAttempt:rr,isAttemptCurrent:Qt,isAttemptInvalidated:Sr,startAttempt:jr}=Oa(fn,{onHandoffObserved:gn,defersMissingTerminal:pr,onMissingTerminalDeferred:tr}),yr=(0,E.useCallback)(()=>(Mt(!1),jr("paypal")),[jr]),wr=(0,E.useCallback)(P=>{rr(P?.generation),P?.showRetry&&Mt(!0),P?.remount&&zr(),P?.focus!==!1&&ur()},[ur,rr,zr]),$r=P=>{let xt=Wt.current;return xt&&Tt.current.set(P,xt),P};(0,E.useEffect)(()=>{nt.current!==$&&(nt.current=$,le.current=!1,It.current=!1,Ae(!1),kt(!1),xe(!1),Cr.current?.("loading"))},[$]),(0,E.useEffect)(()=>{(0,He.invokeMerchantCallback)(()=>Ar.current?.(we&&!Vt))},[we,Vt]);let Br=(0,ze.normalizeGatewayEnvironment)(p);(0,E.useEffect)(()=>{let P={attempt:Zr.current+1,inAppBrowser:re.inAppBrowser,appFamily:re.appFamily,popupCapability:X.current(),presentationMode:Q},xt=()=>({...qe.current??P,popupCapability:X.current()}),te={error:C=>G.error({...C,...xt()}),log:C=>G.log({...C,...xt()}),performance:C=>G.performance({...C,...xt()}),terminal:C=>G.terminal({...C,...xt()}),startTiming:G.startTiming,elapsed:G.elapsed},ae=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",zt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(I(`mount clientId=${ae} env=${p??"(unset)"}\u2192${Br??"live"} ccy=${m} sub=${w}`),I(`ua=${zt.slice(0,80)}${zt.length>80?"\u2026":""}`),!d){I("FAIL: clientId empty \u2014 gateway misconfigured"),xe(!0),te.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!K.current){I("FAIL: containerRef not attached");return}Ze.current=te.startTiming(),te.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ft=!1,nr=!1,Xe=()=>Ft||nr,mr=C=>{let y=St.current,M=y?C:"torn_down";y&&I(`onError ignored reason=${M}`),yn.take(lt.current)&&te.log({name:Si,stage:"provider_ready",reason:M,provider:"paypal",paymentMethodCategory:"paypal"})},Je=()=>lt.current===e?"stale_attempt":"session_changed",no=ee?et:void 0,go,jo=!1,xn=()=>{go=(0,ze.generateIdempotencyKey)(),go||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),jo=!0},hn=null,an=!1,Qr=null,or=!1,Fn=()=>{!Qr||or||(or=!0,Qr.close().catch(()=>{}))},Rr=!1,$n=!1,ht=K.current,Vr=null,Bn=null,oo=[],sn=null,Pn=!1,ho=!1,Po=null,vn=C=>{if(!C||typeof C.getBoundingClientRect!="function")return"(no rect)";let y=C.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},ao=C=>{if(!C)return"(empty)";try{let y=new URL(C,typeof window>"u"?"https://localhost":window.location.href),M=y.pathname.toLowerCase();return M.includes("checkcaptcha")||M.includes("captcha")?`CAPTCHA(${y.host}${M})`:M.includes("risk")||M.includes("challenge")?`RISK(${y.host}${M})`:M.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${M}`.slice(0,100)}catch{return C.slice(0,80)}},Vo=C=>{let y=C.getAttribute("src"),M=C.getAttribute("srcdoc"),ke=C.getAttribute("name"),Te=C.getAttribute("sandbox"),ie=[];return y&&ie.push(`src=${ao(y)}`),M&&ie.push(`srcdoc[${M.length}ch]`),!y&&!M&&ie.push("src=(empty) srcdoc=(empty)"),ke&&ie.push(`name=${ke.slice(0,40)}`),Te!==null&&ie.push(`sandbox="${Te.slice(0,40)}"`),ie.join(" ")},va=C=>{if(!(C instanceof HTMLIFrameElement))return"";try{let y=C.contentDocument;if(!y)return"cd=null";let M=y.body?.children.length??0,ke=y.body?.innerHTML.length??0,Te=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${M}children,${ke}ch] head[${Te}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},Cn=[],Hn=C=>{if(Xe())return;let y=C.message??String(C.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(I(`window:error ${y.slice(0,140)}`),Cn.push(y))},vo=C=>{if(Xe())return;let y=C.reason instanceof Error?C.reason.message:String(C.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(I(`window:rejection ${y.slice(0,140)}`),Cn.push(y))},Nt={value:0},Kn=()=>{Vr?.disconnect(),Vr=null,Bn?.disconnect(),Bn=null;for(let C of oo.splice(0))clearTimeout(C);ho=!1,Pn&&typeof window<"u"&&(window.removeEventListener("error",Hn),window.removeEventListener("unhandledrejection",vo)),Pn=!1},bn=()=>{if(!(Pn||Xe()||Rr)){if(Pn=!0,Cn.length=0,Nt.value=0,typeof window<"u"&&(window.addEventListener("error",Hn),window.addEventListener("unhandledrejection",vo)),typeof PerformanceObserver<"u")try{Bn=new PerformanceObserver(C=>{if(!Xe())for(let y of C.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;Nt.value+=1;let M=Math.round(y.duration);I(`net ${M}ms ${y.name.slice(0,90)}`)}}),Bn.observe({type:"resource",buffered:!0})}catch{}Po?.()}},On=()=>{sn&&(clearTimeout(sn),sn=null)},Hr=()=>{Kn(),On()},ct={setEnabled:C=>{C?bn():Kn()}};D.current=ct,F.current&&bn();let ar=ze.isPayPalTeardownMessage,Kt=C=>{if(Xe()||ar(C))return;let y=(0,Fo.applyFriendlyMessageOverride)(C)??C;(0,He.invokeMerchantCallback)(()=>bt.current?.(y))},B=(C,y)=>{if(Ft||an)return;an=!0,nr=!0,Hr(),Fn();let M=uu({kind:C,generationActive:!0,automaticRetryAllowed:be,automaticRetryUsed:le.current});if(M.action==="retry"){le.current=!0,Ae(!1),Ke(!1),kt(!0),Cr.current?.("retrying"),hn=setTimeout(()=>{Ft||Be(ke=>ke+1)},su);return}if(Ae(!1),Ke(!1),kt(!1),xe(!0),M.action!=="ignore"){if(Cr.current?.("exhausted"),M.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",y);return}if(M.report){let ke=(0,_e.classifyExternalMethodFailure)({code:fc(C,y),message:y},{inAppBrowser:re.inAppBrowser,handoffObserved:!1});ke.popupBlocked&&X.markBlocked(),te.error({errorCode:ke.popupBlocked?ke.errorCode:M.report.errorCode,stage:M.report.stage,operationOutcome:M.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:ke.terminalReason})}It.current||(It.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",fc(C,y)))}};xe(!1);let U=async(C,y=Wt.current)=>{if(Xe())return;let M=y?.sessionId??e;if(Ct.current){await Ct.current(C,{sessionId:M,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let ke=te.startTiming();te.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Te=()=>{te.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"processing",durationMs:te.elapsed(ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ie=(0,ze.buildPayPalProcessPaymentRequest)({body:C,sessionId:M,nonce:y?.nonce??Fr.current,accountPatch:y?.accountPatch,session:xr.current,email:Ur.current}),Ee=await new ki.PaymentAPI(st,{telemetry:!1}).processPayment(ie.userId,ie.params);if(Ee.ok){if(nr||Ft&&St.current)return;Te(),te.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,He.invokeMerchantCallback)(()=>Mr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Xe())return;let $t=await Ee.json().catch(()=>null),Ht=(0,ze.describePayPalProcessFailure)($t),ut=Ht.message;Te(),Ee.status===400&&(typeof $t?.declineCode=="string"||!Array.isArray($t?.fields))?te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Ee.status===400||Ee.status===422?te.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):te.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:pu(Ee.status),failureCategory:Ee.status>=500?"server_error":void 0}),Kt(ut),(0,He.invokeMerchantCallback)(()=>un.current?.(kr("paypal",ut,{code:Ht.code,declineCode:Ht.declineCode})));return}catch(ie){if(Xe())return;Te(),te.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Me=(0,ze.friendlyPayPalFailureMessage)(ie instanceof Error?ie.message:void 0);Kt(Me),(0,He.invokeMerchantCallback)(()=>un.current?.(kr("paypal",Me)));return}},ne=()=>new ze.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),me=C=>Xe()?Promise.reject(ne()):Promise.resolve(C),Ut=async C=>{if(C.ok){te.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,He.invokeMerchantCallback)(()=>Mr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let y=await C.json().catch(()=>null),M=(0,ze.describePayPalProcessFailure)(y);te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,He.invokeMerchantCallback)(()=>un.current?.(kr("paypal",M.message,{code:M.code,declineCode:M.declineCode})))},Jt=()=>{let C=Wt.current;qr("approved"),C&&(br.current.delete(C.surfaceKey),on(C.generation)),Wt.current=null},Fe=async C=>{if(Xe())throw ne();jo||xn();let y=Wt.current,M=y?.sessionId??e,ke=y?.nonce??Fr.current;te.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Te;try{Te=await new ki.PaymentAPI(st,{telemetry:!1}).createSessionIntent(M,ke??"",(0,ze.buildPayPalSessionIntentRequest)(no),{idempotencyKey:go})}catch(ie){throw te.error({...(0,ze.classifyTelemetryFailure)(ie,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ie}if(Xe())throw ne();if((0,ze.isSettledSessionIntent)(Te))throw await Ut(Te.response),Jt(),new ze.FloPayError("PayPal checkout already settled.","api_error",{code:mc});if(Te.provider!=="paypal"||Te.providerObjectType!==et)throw new Error(C);return te.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Te.providerObjectId},dt=(C,y)=>{let M=y?.nonce??Fr.current;if(!M)return;let ke=y?.sessionId??e,Te=(0,ze.resolvePayPalDeclineReason)(C);new ki.PaymentAPI(st,{telemetry:!1}).reportSessionIntentDecline(ke,M,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Te}).catch(()=>{})},z=Pe;I("loadScript:scheduled (deferred 1 tick)");let Ge=null,Re=setTimeout(()=>{if(Ft){I("loadScript:skipped (cancelled before defer ran)");return}I("loadScript:start");let C=Br==="live"?"production":Br,y={};et==="subscription"?y={intent:"subscription",vault:!0}:et==="order"&&(y={intent:"capture"}),Ge=(0,gc.loadScript)({clientId:d,currency:m,...y,...C?{environment:C}:{},...C==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let M=!1;Ge.then(ke=>{if(M=!0,I(`loadScript:resolved inactive=${Xe()} ns=${!!ke} buttons=${!!ke?.Buttons}`),Xe())return;if(!ke?.Buttons){I("FAIL: namespace missing Buttons factory"),B("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}te.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"provider_ready",durationMs:te.elapsed(Ze.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),te.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Te=async(ue,ye)=>{if(Xe()||at.current!==z)return;let $e=ue.vaultSetupToken??ue.subscriptionID??ue.orderID??"",tt=$e?Tt.current.get($e):br.current.get(z);if(!(!tt||!Qt(tt.generation))&&on(tt.generation)){Tt.current.delete($e),br.current.delete(tt.surfaceKey),qr("approved");try{if(Ke(!0),(0,He.invokeMerchantCallback)(()=>bt.current?.(null)),!$e)throw new ze.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let De=(0,ze.resolvePayPalApprovalIdentity)({accountPatch:tt.accountPatch,email:Ur.current,billingName:pn.current,session:xr.current});if((0,ze.needsPayPalPayerDetails)(De))try{De=(0,ze.mergePayPalPayerIdentity)(De,await ye?.order?.get?.())}catch{}if((Xt.current||Qe)&&!(0,ze.isValidEmail)(De.email)){let Yt=await it("PayPal",De);if(!Yt)return;De=Yt}(0,ze.isValidEmail)(De.email)&&(tt.accountPatch=(0,kn.compactBuyerIdentity)({...tt.accountPatch,...De}),await Xt.current?.(De));let en=(0,ze.buildPayPalTokenizedBody)($e,no);await U(en,tt)}catch(De){Kt(De instanceof Error?De.message:"PayPal capture failed.")}finally{Xe()||Ke(!1)}}},ie=ue=>{let ye=Ie?()=>me(Ie):()=>Fe(ue);return async()=>$r(await ye())},Me=ke.Buttons({style:{layout:"horizontal",height:Ei,tagline:!1},...Q==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ue,ye)=>{if(Xe()){await ye.reject();return}xn();let $e=Jr.current,tt={};if($e)try{let Yt=await $e("paypal");if(Xe()){await ye.reject();return}if(!Yt.proceed){Wt.current=null,br.current.delete(z),await ye.reject();return}tt={sessionId:Yt.sessionId,accountPatch:Yt.accountPatch,nonce:Yt.nonce}}catch(Yt){I(`onClick:runBeforeButtonClick rejected msg=${(Yt instanceof Error?Yt.message:String(Yt)).slice(0,120)}`),Wt.current=null,br.current.delete(z),await ye.reject();return}(0,He.invokeMerchantCallback)(()=>At.current?.("paypal"));let De=yr(),en={generation:De,surfaceKey:z,...tt};Wt.current=en,br.current.set(z,en),qe.current={...P,attempt:De},await ye.resolve(),te.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Se.current=te.startTiming()},createOrder:et==="order"?ie("Failed to create PayPal order."):void 0,createSubscription:et==="subscription"?ie("Failed to create PayPal subscription."):void 0,createVaultSetupToken:et==="setup_token"?async()=>$r(await Fe("Failed to create PayPal setup token.")):void 0,onApprove:Te,onCancel:()=>{if(Xe())return;let ue=br.current.get(z)??Wt.current,ye=ue&&Qt(ue.generation)?(0,ze.buildPayPalCancelEvent)(ue.sessionId??e,no):null;ue&&br.current.delete(ue.surfaceKey),Wt.current=null,qr("cancelled"),te.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),pe.current=!0,wr({generation:ue?.generation,remount:!0,focus:!1}),ye&&(0,He.invokeMerchantCallback)(()=>gt.current?.(ye))},onError:ue=>{if(ue instanceof ze.FloPayError&&ue.code===mc)return;let ye=ue instanceof Error?ue.message:"PayPal failed to render.";if(Xe()||at.current!==z){ar(ye)||mr(Je());return}if(Rr){let $e=br.current.get(z)??Wt.current;if(!$e||!Qt($e.generation)){if(ar(ye)){!$e&&!Sr()&&on();return}mr($e||Sr()?"stale_attempt":"no_current_attempt");return}if(I(`onError rendered=${Rr} msg=${ye.slice(0,120)}`),ar(ye)){on($e.generation);return}let{errorCode:tt,popupBlocked:De,providerDeclined:en,terminalReason:Yt}=(0,_e.classifyExternalMethodFailure)(ue,{inAppBrowser:re.inAppBrowser,handoffObserved:Z.current===$e.generation});if(De&&X.markBlocked(),qr(Yt),en){te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Yt}),dt(ue,$e),(0,He.invokeMerchantCallback)(()=>un.current?.(kr("paypal",ye))),br.current.delete($e.surfaceKey),Wt.current=null,on($e.generation);return}te.error({errorCode:tt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Yt}),br.current.delete($e.surfaceKey),Wt.current=null,wr({generation:$e.generation,remount:!0,showRetry:!0,focus:!0}),mn(ue,{code:"paypal_runtime_failed",popupBlocked:De,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Q,terminalReason:Yt});return}I(`onError rendered=${Rr} msg=${ye.slice(0,120)}`),B(ar(ye)?"teardown":"pre_ready_callback",ye)}}),Ee=Me.isEligible();if(I(`isEligible=${Ee}`),te.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Ee){Ae(!1),B("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}$n=!0,Qr=Me,Po=()=>{if(!Pn||ho||Xe()||Rr)return;ho=!0,I(`container:dims ${vn(ht)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Vr=new MutationObserver(ye=>{if(!Xe()){for(let $e of ye)if($e.type==="childList")$e.addedNodes.forEach(tt=>{if(!(tt instanceof Element))return;let De=tt.tagName.toLowerCase(),en=(tt.getAttribute("title")??"").slice(0,40),Yt=De==="iframe"?` ${Vo(tt)}`:"";I(`child+ ${De}${en?` title="${en}"`:""}${Yt} dims=${vn(tt)}`)});else if($e.type==="attributes"&&$e.target instanceof Element){let tt=$e.target;if(tt.tagName.toLowerCase()!=="iframe")continue;let De=$e.attributeName;(De==="src"||De==="srcdoc")&&I(`attr~ iframe ${De}=${De==="srcdoc"?`[${(tt.getAttribute("srcdoc")??"").length}ch]`:ao(tt.getAttribute("src"))} dims=${vn(tt)}`)}}}),Vr.observe(ht,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ue=ye=>{if(Xe()||Rr)return;let $e=ht.querySelectorAll("iframe"),tt=typeof document<"u"&&"hasStorageAccess"in document;I(`watchdog:${ye} container=${vn(ht)} children=${ht.childElementCount} iframes=${$e.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${tt} paypalNetRequests=${Nt.value}`),$e.forEach((De,en)=>{let Yt=(De.getAttribute("title")??"").slice(0,40);I(` iframe[${en}] ${vn(De)}${Yt?` title="${Yt}"`:""} ${Vo(De)}`);let Wo=va(De);Wo&&I(` ${Wo}`)}),Cn.length===0&&I(" (no PayPal/zoid window errors captured)")};oo.push(setTimeout(()=>ue("3s"),3e3)),oo.push(setTimeout(()=>ue("8s"),8e3)),oo.push(setTimeout(()=>ue("15s"),15e3))},Po(),I("render:start");let Ht=te.startTiming();sn=setTimeout(()=>{Xe()||Rr||(I("watchdog:11s retryable render timeout"),B("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},lu);let ut=Me.render(ht);(async()=>{try{if(await ut,I(`render:resolved inactive=${Xe()}`),Hr(),Xe()){Fn();return}Rr=!0,Ae(!0),kt(!1),Cr.current?.("ready"),te.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"checkout_render",durationMs:te.elapsed(Ht),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ue){let ye=ue instanceof Error?ue.message:"PayPal failed to render.";I(`render:rejected msg=${ye.slice(0,120)}`),Hr(),B(ar(ye)?"teardown":"render_rejected",ye)}})()}).catch(ke=>{let Te=ke instanceof Error?ke.message:"PayPal operation failed.";I(`provider:failed msg=${Te.slice(0,120)}`);let ie="script_rejected";M&&ar(Te)?ie="teardown":M&&$n&&(ie="render_rejected"),B(ie,Te)})},0);return()=>{Ft=!0,clearTimeout(Re),hn&&clearTimeout(hn),Hr(),D.current===ct&&(D.current=null),Fn(),Se.current=null,qe.current=null}},[be,st,d,m,p,et,Q,ee,e,Ie,Pe,G,it,Qe,I,qr]);let Or=q?(0,En.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Vt?"#fef2f2":"#f3f4f6",border:`1px solid ${Vt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${we} failed=${Vt})`,L.length===0?`
|
|
1
|
+
"use strict";var Gd=Object.create;var fi=Object.defineProperty;var Yd=Object.getOwnPropertyDescriptor;var Xd=Object.getOwnPropertyNames;var Jd=Object.getPrototypeOf,Zd=Object.prototype.hasOwnProperty;var Qd=(e,t)=>{for(var r in t)fi(e,r,{get:t[r],enumerable:!0})},nc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Xd(t))!Zd.call(e,a)&&a!==r&&fi(e,a,{get:()=>t[a],enumerable:!(n=Yd(t,a))||n.enumerable});return e};var Ms=(e,t,r)=>(r=e!=null?Gd(Jd(e)):{},nc(t||!e||!e.__esModule?fi(r,"default",{value:e,enumerable:!0}):r,e)),eu=e=>nc(fi({},"__esModule",{value:!0}),e);var qp={};Qd(qp,{DirectPayPalButton:()=>Da,FloPayAutomaticPaymentButton:()=>ud,FloPayCardSetup:()=>pd,FloPayCardSetupError:()=>ei,FloPayCheckout:()=>Gi,FloPayPaymentMethodSetup:()=>wd,FloPayProvider:()=>Na,SplitCardForm:()=>Wi,VaultCardFields:()=>Eo,dropThirdPartyOnlyError:()=>kd.dropThirdPartyOnlyError,useCheckout:()=>gc,useFloPay:()=>co,usePayPalFloPay:()=>vi});module.exports=eu(qp);var kd=require("@flopay/shared");var Yi=require("@flopay/js"),kr=require("@flopay/shared"),dt=require("react");var er=require("react/jsx-runtime");function tu(){return(0,er.jsxs)(er.Fragment,{children:[(0,er.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,er.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,er.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,er.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,er.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function ru(){return(0,er.jsx)(er.Fragment,{children:"Go back"})}function nu(){return(0,er.jsx)(er.Fragment,{children:"Secure card checkout"})}function na(e){return e!==void 0&&(e===""||e===null||e===!1)}function oa({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(tu,{}):e})}function aa({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(ru,{}):e})}function Ma({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(nu,{}):e})}var It=require("@flopay/shared"),Fn=require("@flopay/shared"),la=require("@flopay/shared"),Oo=require("@flopay/shared");function As(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof It.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function ou(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function oc(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,It.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,It.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function ac(e,t){if(t&&(!(e instanceof It.FloPayError)||e.type==="authentication_error"))return As(e);if(!(e instanceof It.FloPayError&&ou(e))){if(!t&&!(e instanceof It.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,It.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof It.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof It.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function ia(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let d={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,It.isCardHolderNamePlaceholder)(d.firstName,d.lastName);if(!(0,It.isValidEmail)(d.email))return Promise.reject(new It.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[S,P]of Object.entries(d)){if(p&&S.endsWith("Name")||typeof P!="string")continue;let g=P.trim();g&&(y[S]=g)}return a=e.claimCheckoutSession(t,r,{accountData:y}),a.catch(()=>{}),a}}function ic(e,t){if(!t)return e;if(!e)return t;let r;return"checkoutMetadata"in t?r=t:"checkoutMetadata"in e&&(r=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...r?{checkoutMetadata:r.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function xs(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function sc(e,t){let r=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],n=r.reduce((s,d)=>s+(d.overrideAmount??d.totalAmount??0),0),a=e.currency??r.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(n*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:r.map((s,d)=>({uuid:`synthetic-${s.type??"item"}-${d}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??a,metadata:s.metadata??null}))}}function Fs(e,t){return t?{...e,...t}:e}function Sr(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,s=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,d=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...s?{declineCode:s}:{},...d?{sessionId:d}:{}}}var lc=new WeakMap;function cc(e,t){return typeof e=="object"&&e!==null&&lc.set(e,t?{sessionId:t}:{}),e}function dc(e){return typeof e=="object"&&e!==null?lc.get(e):void 0}function wo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function io(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function so(e){return e?.status==="authorized"||e?.status==="complete"}function Ro(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,a=r?.status==="authorized"||n==="AUTHORIZED";return a||r?.status==="completed"||n==="SUCCESS"?{...t,status:a?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function uc(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function gi(e){let t=uc(e);return new It.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function hi(e){return e instanceof It.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function sa(e){return uc(e)?new It.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new It.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new It.FloPayError(It.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function Aa(e,t){return e==="processing"||(0,It.isMoneySettledOutcome)(e,t)}function pc(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function yc(e,t){let r=e;if((0,It.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:d}=await r.retrieveSetupIntent(t);if(d)throw new It.FloPayError(d.message??"Failed to retrieve setup intent.","api_error",{...d.code?{code:d.code}:{}});return s??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new It.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var au=["apple_pay","google_pay"];function mc(e,t="automatic",r){let n=(0,It.resolveSetupFutureUsage)(r,au,"wallet");return{...(0,It.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var iu=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Bs(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:iu.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function xa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var yo=require("@flopay/js"),de=require("@flopay/shared"),w=Ms(require("react"),1);var Os=require("react"),vn=(0,Os.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Bn=(0,Os.createContext)({session:null,loading:!1,error:null});var ki=require("@flopay/js"),je=require("@flopay/shared"),bc=require("@paypal/paypal-js"),E=require("react");var Pi=require("@flopay/shared"),On=require("react"),Cn=require("@flopay/shared"),lo=require("react/jsx-runtime");function ca(){let[e,t]=(0,On.useState)(null),r=(0,On.useRef)(null),n=(0,On.useRef)(0),a=(0,On.useCallback)((d,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:d,identity:p}),new Promise(y=>{r.current=y})),[]),s=(0,On.useCallback)(d=>{let p=r.current;r.current=null,t(null),p?.(d)},[]);return(0,On.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function da({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[d,p]=(0,On.useState)(e.email?.trim()??""),y=(0,Pi.isValidEmail)(d.trim());return(0,lo.jsxs)("div",{"data-testid":s,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,lo.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,lo.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,lo.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:d,onChange:S=>p(S.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,lo.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,lo.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,lo.jsxs)("button",{type:"button",disabled:!y||a,onClick:()=>{r((0,Pi.compactBuyerIdentity)({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var we=require("@flopay/shared");var fc=require("@flopay/shared"),Fa=require("react");function co(){return(0,Fa.useContext)(vn).flopay}function vi(){return(0,Fa.useContext)(vn).paypalFlopay??null}function gc(){return(0,Fa.useContext)(Bn)}function hc(){return(0,Fa.useContext)(vn).billingApiUrl||(0,fc.resolveBillingApiUrl)()}var su=require("@flopay/shared"),Xn=require("@flopay/shared"),Jn=require("@flopay/shared");var ua=require("@flopay/shared"),Lo=require("react");var Ci=require("react"),Do=typeof window>"u"?Ci.useEffect:Ci.useLayoutEffect;var Ds=require("@flopay/shared");function pa(e,t){let r=(0,Lo.useRef)(e);r.current=e;let n=(0,Lo.useRef)(new Set),a=(0,Lo.useRef)(t),s=(0,Lo.useRef)(t);return Do(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,Lo.useCallback)(d=>{if(s.current!==t)return;let p=(0,ua.projectFloInstrument)(d);if(p){if(ua.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,ua.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Qe=require("@flopay/shared");var Pc=require("react"),Ba=(0,Pc.createContext)(null);function bi(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Si="provider.callback.ignored";function wi(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var lu=Symbol.for("@flopay/js.telemetry.bridge.v1"),cu=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function du(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function uu(e){let t=du(),r=(a,s)=>a?a.bind(e):s,n=r(e.now,t.now);return{error:r(e.error,t.error),log:r(e.log,t.log),performance:r(e.performance,t.performance),terminal:r(e.terminal,t.terminal),now:n,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,n()-a),setCheckoutContext:r(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:r(e.beginCheckout,t.beginCheckout),disable:r(e.disable,t.disable),subscribe:r(e.subscribe,t.subscribe),flush:r(e.flush,t.flush),destroy:r(e.destroy,t.destroy)}}function Ri(e){let t=globalThis[cu];return uu(t?.(e)??{})}function wr(e){if(e)return e[lu]}var gr=require("react");function Oa(e,t){let r=(0,gr.useRef)(0),n=(0,gr.useRef)(null),a=(0,gr.useRef)(null),s=(0,gr.useRef)(e),d=(0,gr.useRef)(t?.onHandoffObserved),p=(0,gr.useRef)(t?.defersMissingTerminal),y=(0,gr.useRef)(t?.onMissingTerminalDeferred);(0,gr.useEffect)(()=>{s.current=e,d.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,y.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let S=(0,gr.useCallback)((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),P=(0,gr.useCallback)(f=>{S();let H=r.current+1;return r.current=H,n.current=null,a.current={generation:H,method:f,timer:null,yieldedControl:!1},H},[S]),g=(0,gr.useCallback)(f=>{let H=a.current;return f!==void 0&&H?.generation!==f?!1:(S(H),a.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[S]),_=(0,gr.useCallback)(f=>{let H=a.current,X=f??H?.generation??r.current;(f===void 0||H?.generation===f)&&(S(H),a.current=null),n.current=X},[S]),W=(0,gr.useCallback)(f=>n.current===(f??r.current),[]),$=(0,gr.useCallback)(f=>a.current?.generation===f&&n.current!==f,[]),R=(0,gr.useCallback)(()=>{let f=a.current;f&&(S(f),!f.yieldedControl&&(f.yieldedControl=!0,d.current?.(f.method)))},[S]),x=(0,gr.useCallback)(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(S(f),f.timer=setTimeout(()=>{if(f.timer=null,a.current?.generation===f.generation){if(p.current?.(f.method)){y.current?.(f.method,f.generation);return}a.current=null,n.current=f.generation,s.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},we.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[S]);return(0,gr.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?x():R()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",R),window.addEventListener("focus",x),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",R),window.removeEventListener("focus",x),S()}},[S,R,x]),{startAttempt:P,finishAttempt:g,invalidateAttempt:_,isAttemptInvalidated:W,isAttemptCurrent:$,generationRef:r}}var bn=require("react/jsx-runtime"),Ei=45,pu=1e3,yu=11e3,vc="paypal_intent_settled",mu={width:"100%",minHeight:Ei,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},fu={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function gu(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:fu[e.kind]??null}}function Cc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,we.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function hu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Sc({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:d,environment:p,currency:y,isSubscription:S,providerObjectType:P,approvalPresentation:g,onTokenizedBody:_,onComplete:W,onErrorChange:$,onDecline:R,onCancel:x,onTechnicalFailure:f,isProcessing:H=!1,onLoadStateChange:X,onInitializationStateChange:v,allowAutomaticRetry:be=!0,onButtonClick:F,runBeforeButtonClick:oe,session:he,existingOrderId:Re,telemetry:pe,telemetryContext:kt,onInstrument:mt,debug:j=!1}){let Je=co(),Ze=pa(mt,e),Le=(0,E.useMemo)(()=>{if(Je)return null;let L=Ri({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:je.SDK_VERSION,enabled:pe!==!1});return L.setCheckoutContext(kt??{}),L.beginCheckout(kt??{}),L},[r,Je,pe,kt?.checkoutMode,kt?.layout]),ve=(0,E.useMemo)(()=>wr(Je),[Je]);(0,E.useEffect)(()=>()=>{Le&&Le.flush().catch(()=>{}).finally(()=>Le.destroy())},[Le]);let Y=(0,E.useMemo)(()=>({error:L=>{ve?ve.error(L):Le?.error(L),Ze({class:"technical_error",errorCode:L.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":L.errorCode,requestCategory:L.requestCategory,provider:L.provider})},log:L=>{ve?ve.log(L):Le?.log(L),Ze({class:"lifecycle",name:L.name,provider:L.provider})},performance:L=>{ve?ve.performance(L):Le?.performance(L)},terminal:L=>{ve?ve.terminal(L):Le?.terminal(L)},startTiming:()=>ve?.now()??Le?.now()??0,elapsed:L=>ve?.elapsed(L)??Math.max(0,(Le?.now()??L)-L)}),[Ze,ve,Le]),K=(0,E.useRef)(null),rt=(0,E.useRef)(0),Se=(0,E.useRef)(null),Ke=(0,E.useRef)(null),ee=(0,E.useRef)(null),V=(0,E.useContext)(Ba),Pe=(0,E.useRef)(null);Pe.current||(Pe.current=bi());let J=V??Pe.current,ut=(0,E.useRef)(null),ye=(0,E.useRef)(!1),[ke,xe]=(0,E.useState)(!1),[_e,vt]=(0,E.useState)(!1),[Ne,ft]=(0,E.useState)(0),Ve=(0,E.useRef)(0),[We,Mt]=(0,E.useState)(!1),Lt=(0,E.useRef)(!1),Ft=(0,E.useRef)(!1),[le,Ee]=(0,E.useState)(!1),[$e,Ct]=(0,E.useState)(!1),{request:bt,collect:st,finish:pt}=ca(),At=(0,E.useRef)({sessionId:e,required:(0,je.paypalProviderIdentityRequired)(n,he)});At.current.sessionId!==e&&(At.current={sessionId:e,required:(0,je.paypalProviderIdentityRequired)(n,he)});let xt=At.current.required,lt=(0,E.useMemo)(()=>r.replace(/\/+$/,""),[r]),gt=he?.gateways?.paypal?.providerObjectType??P,G=gt??(S?"subscription":"order"),[Jt]=(0,E.useState)(Xn.detectPayPalEnvironment),B=he?.gateways?.paypal?.approvalPresentation??g,C=(0,Jn.resolvePayPalPresentationMode)(Jt,B==="app_switch"?"app_switch":void 0,G),ce=(0,je.usesPayPalVaultedChannel)(gt),Z=(0,E.useMemo)(()=>JSON.stringify([lt,d,y,p??"",G,ce,C,e,Re??""]),[lt,d,y,p,Re,G,ce,C,e]),ae=(0,E.useRef)(Z),u=ae.current!==Z,M=(0,E.useRef)(j),I=(0,E.useRef)(null),[ie,U]=(0,E.useState)([]),k=(0,E.useCallback)(L=>{M.current&&U(ht=>[...ht,`${new Date().toISOString().slice(11,23)} ${L}`])},[]);(0,E.useEffect)(()=>{M.current=j,j&&k("debug:enabled"),I.current?.setEnabled(j)},[k,j]);let tt=(0,E.useRef)(_),Ht=(0,E.useRef)(W),Kt=(0,E.useRef)($),Vr=(0,E.useRef)(R),He=(0,E.useRef)(x),Un=(0,E.useRef)(f),Pr=(0,E.useRef)(F),vr=(0,E.useRef)(X),Et=(0,E.useRef)(v),jt=(0,E.useRef)(s),Or=(0,E.useRef)(oe),Qr=(0,E.useRef)(he),Dr=(0,E.useRef)(n),Ar=(0,E.useRef)(a),xr=(0,E.useRef)(t),tr=(0,E.useRef)(null),Gt=(0,E.useRef)(new Map),or=(0,E.useRef)(new Map),St=(0,E.useRef)(!1),Fe=(0,E.useRef)(e);Fe.current=e;let[un]=(0,E.useState)(wi);(0,E.useEffect)(()=>(St.current=!0,()=>{St.current=!1}),[]),(0,E.useEffect)(()=>{tt.current=_},[_]),(0,E.useEffect)(()=>{jt.current=s},[s]),(0,E.useEffect)(()=>{Ht.current=W},[W]),(0,E.useEffect)(()=>{Kt.current=$},[$]),(0,E.useEffect)(()=>{Vr.current=R},[R]),(0,E.useEffect)(()=>{He.current=x},[x]),(0,E.useEffect)(()=>{Un.current=f},[f]),(0,E.useEffect)(()=>{Pr.current=F},[F]),(0,E.useEffect)(()=>{vr.current=X},[X]),(0,E.useEffect)(()=>{Et.current=v},[v]),(0,E.useEffect)(()=>{Or.current=oe},[oe]),(0,E.useEffect)(()=>{Qr.current=he},[he]),(0,E.useEffect)(()=>{Dr.current=n},[n]),(0,E.useEffect)(()=>{Ar.current=a},[a]),(0,E.useEffect)(()=>{xr.current=t},[t]),(0,E.useEffect)(()=>{Ve.current=Ne},[Ne]),(0,E.useEffect)(()=>{We&&ut.current?.focus()},[We,Ne]);let Vt=(0,E.useCallback)(()=>{window.setTimeout(()=>{ut.current?.focus()},0)},[]),Lr=(0,E.useCallback)(()=>{xe(!1),ft(L=>L+1)},[]),Wr=(0,E.useCallback)(()=>{Mt(!1),(K.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??K.current)?.focus?.()},[]);(0,E.useEffect)(()=>{!ke||!ye.current||(ye.current=!1,Wr())},[Wr,ke,Ne]);let pn=(0,E.useCallback)((L,ht)=>{let T=ht?.popupBlocked??(0,we.isPopupBlockedError)(L);T&&J.markBlocked();let Ie=(0,we.buildExternalMethodRecoveryMessage)("PayPal",T,Jt.inAppBrowser),Tt=Un.current;if(Tt){let Pt=T&&Jt.inAppBrowser?new je.FloPayError(Ie,"api_error",{code:ht?.code??"paypal_popup_blocked"}):L;Tt("paypal",Pt,ht);return}if(L instanceof je.FloPayError&&L.code==="checkout_processing_timeout"){Kt.current?.(L.message);return}Kt.current?.(Ie)},[J,Jt.inAppBrowser]),$r=(0,E.useCallback)(L=>{let ht=Se.current,T=Ke.current;ht===null||!T||(Y.log({...T,popupCapability:J.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),Y.performance({...T,popupCapability:J.current(),stage:"overlay_return",durationMs:Y.elapsed(ht),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),Se.current=null)},[J,Y]),zn=(0,E.useCallback)((L,ht,T)=>{let Ie=Ke.current;$r("overlay_timeout"),Ie&&Y.error({...Ie,popupCapability:J.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),pn(ht,{...T,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:C,terminalReason:"overlay_timeout"}),Mt(!0),Lr(),Vt()},[$r,Vt,pn,J,C,Lr,Y]),En=(0,E.useCallback)(()=>{J.markAvailable();let L=Ke.current;L&&(ee.current=L.attempt,Y.log({...L,popupCapability:J.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[J,Y]),Cr=(0,E.useCallback)(()=>!0,[]),br=(0,E.useCallback)(()=>{let L=Ke.current;if(!L)return;let ht=Se.current;Y.performance({...L,popupCapability:J.current(),stage:"overlay_return",durationMs:ht===null?0:Y.elapsed(ht),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[J,Y]),{finishAttempt:Nr,generationRef:en,invalidateAttempt:Hr,isAttemptCurrent:Ur,isAttemptInvalidated:pr,startAttempt:ar}=Oa(zn,{onHandoffObserved:En,defersMissingTerminal:Cr,onMissingTerminalDeferred:br}),ir=(0,E.useCallback)(()=>(Mt(!1),ar("paypal")),[ar]),rr=(0,E.useCallback)(L=>{Hr(L?.generation),L?.showRetry&&Mt(!0),L?.remount&&Lr(),L?.focus!==!1&&Vt()},[Vt,Hr,Lr]),Kr=L=>{let ht=tr.current;return ht&&or.current.set(L,ht),L};(0,E.useEffect)(()=>{ae.current!==Z&&(ae.current=Z,Lt.current=!1,Ft.current=!1,xe(!1),vt(!1),Ee(!1),Et.current?.("loading"))},[Z]),(0,E.useEffect)(()=>{(0,Qe.invokeMerchantCallback)(()=>vr.current?.(ke&&!le))},[ke,le]);let Gr=(0,je.normalizeGatewayEnvironment)(p);(0,E.useEffect)(()=>{let L={attempt:en.current+1,inAppBrowser:Jt.inAppBrowser,appFamily:Jt.appFamily,popupCapability:J.current(),presentationMode:C},ht=()=>({...Ke.current??L,popupCapability:J.current()}),T={error:h=>Y.error({...h,...ht()}),log:h=>Y.log({...h,...ht()}),performance:h=>Y.performance({...h,...ht()}),terminal:h=>Y.terminal({...h,...ht()}),startTiming:Y.startTiming,elapsed:Y.elapsed},Ie=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",Tt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(k(`mount clientId=${Ie} env=${p??"(unset)"}\u2192${Gr??"live"} ccy=${y} sub=${S}`),k(`ua=${Tt.slice(0,80)}${Tt.length>80?"\u2026":""}`),!d){k("FAIL: clientId empty \u2014 gateway misconfigured"),Ee(!0),T.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!K.current){k("FAIL: containerRef not attached");return}rt.current=T.startTiming(),T.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Pt=!1,Yt=!1,Ge=()=>Pt||Yt,qn=h=>{let m=St.current,N=m?h:"torn_down";m&&k(`onError ignored reason=${N}`),un.take(Fe.current)&&T.log({name:Si,stage:"provider_ready",reason:N,provider:"paypal",paymentMethodCategory:"paypal"})},ro=()=>Fe.current===e?"stale_attempt":"session_changed",Fr=ce?G:void 0,Be,fo=!1,_o=()=>{Be=(0,je.generateIdempotencyKey)(),Be||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),fo=!0},Io=null,_n=!1,yn=null,sn=!1,tn=()=>{!yn||sn||(sn=!0,yn.close().catch(()=>{}))},Wt=!1,jn=!1,Br=K.current,mn=null,Ue=null,qr=[],In=null,Vn=!1,fn=!1,Wn=null,$n=h=>{if(!h||typeof h.getBoundingClientRect!="function")return"(no rect)";let m=h.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},To=h=>{if(!h)return"(empty)";try{let m=new URL(h,typeof window>"u"?"https://localhost":window.location.href),N=m.pathname.toLowerCase();return N.includes("checkcaptcha")||N.includes("captcha")?`CAPTCHA(${m.host}${N})`:N.includes("risk")||N.includes("challenge")?`RISK(${m.host}${N})`:N.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${N}`.slice(0,100)}catch{return h.slice(0,80)}},no=h=>{let m=h.getAttribute("src"),N=h.getAttribute("srcdoc"),A=h.getAttribute("name"),te=h.getAttribute("sandbox"),Te=[];return m&&Te.push(`src=${To(m)}`),N&&Te.push(`srcdoc[${N.length}ch]`),!m&&!N&&Te.push("src=(empty) srcdoc=(empty)"),A&&Te.push(`name=${A.slice(0,40)}`),te!==null&&Te.push(`sandbox="${te.slice(0,40)}"`),Te.join(" ")},go=h=>{if(!(h instanceof HTMLIFrameElement))return"";try{let m=h.contentDocument;if(!m)return"cd=null";let N=m.body?.children.length??0,A=m.body?.innerHTML.length??0,te=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${N}children,${A}ch] head[${te}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},ho=[],Wo=h=>{if(Ge())return;let m=h.message??String(h.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(k(`window:error ${m.slice(0,140)}`),ho.push(m))},Hn=h=>{if(Ge())return;let m=h.reason instanceof Error?h.reason.message:String(h.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(k(`window:rejection ${m.slice(0,140)}`),ho.push(m))},Tn={value:0},Po=()=>{mn?.disconnect(),mn=null,Ue?.disconnect(),Ue=null;for(let h of qr.splice(0))clearTimeout(h);fn=!1,Vn&&typeof window<"u"&&(window.removeEventListener("error",Wo),window.removeEventListener("unhandledrejection",Hn)),Vn=!1},Nt=()=>{if(!(Vn||Ge()||Wt)){if(Vn=!0,ho.length=0,Tn.value=0,typeof window<"u"&&(window.addEventListener("error",Wo),window.addEventListener("unhandledrejection",Hn)),typeof PerformanceObserver<"u")try{Ue=new PerformanceObserver(h=>{if(!Ge())for(let m of h.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;Tn.value+=1;let N=Math.round(m.duration);k(`net ${N}ms ${m.name.slice(0,90)}`)}}),Ue.observe({type:"resource",buffered:!0})}catch{}Wn?.()}},oo=()=>{In&&(clearTimeout(In),In=null)},rn=()=>{Po(),oo()},gn={setEnabled:h=>{h?Nt():Po()}};I.current=gn,M.current&&Nt();let _r=je.isPayPalTeardownMessage,ot=h=>{if(Ge()||_r(h))return;let m=(0,Oo.applyFriendlyMessageOverride)(h)??h;(0,Qe.invokeMerchantCallback)(()=>Kt.current?.(m))},yr=(h,m)=>{if(Pt||_n)return;_n=!0,Yt=!0,rn(),tn();let N=gu({kind:h,generationActive:!0,automaticRetryAllowed:be,automaticRetryUsed:Lt.current});if(N.action==="retry"){Lt.current=!0,xe(!1),Ct(!1),vt(!0),Et.current?.("retrying"),Io=setTimeout(()=>{Pt||ft(A=>A+1)},pu);return}if(xe(!1),Ct(!1),vt(!1),Ee(!0),N.action!=="ignore"){if(Et.current?.("exhausted"),N.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",m);return}if(N.report){let A=(0,we.classifyExternalMethodFailure)({code:Cc(h,m),message:m},{inAppBrowser:Jt.inAppBrowser,handoffObserved:!1});A.popupBlocked&&J.markBlocked(),T.error({errorCode:A.popupBlocked?A.errorCode:N.report.errorCode,stage:N.report.stage,operationOutcome:N.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:A.terminalReason})}Ft.current||(Ft.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Cc(h,m)))}};Ee(!1);let Zt=async(h,m=tr.current)=>{if(Ge())return;let N=m?.sessionId??e;if(tt.current){await tt.current(h,{sessionId:N,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let A=T.startTiming();T.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let te=()=>{T.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),T.performance({stage:"processing",durationMs:T.elapsed(A),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Te=(0,je.buildPayPalProcessPaymentRequest)({body:h,sessionId:N,nonce:m?.nonce??xr.current,accountPatch:m?.accountPatch,session:Qr.current,email:Dr.current}),Me=await new ki.PaymentAPI(lt,{telemetry:!1}).processPayment(Te.userId,Te.params);if(Me.ok){if(Yt||Pt&&St.current)return;te(),T.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Qe.invokeMerchantCallback)(()=>Ht.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ge())return;let Oe=await Me.json().catch(()=>null),ze=(0,je.describePayPalProcessFailure)(Oe),qt=ze.message;te(),Me.status===400&&(typeof Oe?.declineCode=="string"||!Array.isArray(Oe?.fields))?T.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Me.status===400||Me.status===422?T.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):T.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:hu(Me.status),failureCategory:Me.status>=500?"server_error":void 0}),ot(qt),(0,Qe.invokeMerchantCallback)(()=>Vr.current?.(Sr("paypal",qt,{code:ze.code,declineCode:ze.declineCode})));return}catch(Te){if(Ge())return;te(),T.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Rt=(0,je.friendlyPayPalFailureMessage)(Te instanceof Error?Te.message:void 0);ot(Rt),(0,Qe.invokeMerchantCallback)(()=>Vr.current?.(Sr("paypal",Rt)));return}},D=()=>new je.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),q=h=>Ge()?Promise.reject(D()):Promise.resolve(h),se=async h=>{if(h.ok){T.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Qe.invokeMerchantCallback)(()=>Ht.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let m=await h.json().catch(()=>null),N=(0,je.describePayPalProcessFailure)(m);T.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Qe.invokeMerchantCallback)(()=>Vr.current?.(Sr("paypal",N.message,{code:N.code,declineCode:N.declineCode})))},fe=()=>{let h=tr.current;$r("approved"),h&&(Gt.current.delete(h.surfaceKey),Nr(h.generation)),tr.current=null},Ot=async h=>{if(Ge())throw D();fo||_o();let m=tr.current,N=m?.sessionId??e,A=m?.nonce??xr.current;T.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let te;try{te=await new ki.PaymentAPI(lt,{telemetry:!1}).createSessionIntent(N,A??"",(0,je.buildPayPalSessionIntentRequest)(Fr),{idempotencyKey:Be})}catch(Te){throw T.error({...(0,je.classifyTelemetryFailure)(Te,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Te}if(Ge())throw D();if((0,je.isSettledSessionIntent)(te))throw await se(te.response),fe(),new je.FloPayError("PayPal checkout already settled.","api_error",{code:vc});if(te.provider!=="paypal"||te.providerObjectType!==G)throw new Error(h);return T.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),te.providerObjectId},Qt=(h,m)=>{let N=m?.nonce??xr.current;if(!N)return;let A=m?.sessionId??e,te=(0,je.resolvePayPalDeclineReason)(h);new ki.PaymentAPI(lt,{telemetry:!1}).reportSessionIntentDecline(A,N,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:te}).catch(()=>{})},me=Ne;k("loadScript:scheduled (deferred 1 tick)");let at=null,re=setTimeout(()=>{if(Pt){k("loadScript:skipped (cancelled before defer ran)");return}k("loadScript:start");let h=Gr==="live"?"production":Gr,m={};G==="subscription"?m={intent:"subscription",vault:!0}:G==="order"&&(m={intent:"capture"}),at=(0,bc.loadScript)({clientId:d,currency:y,...m,...h?{environment:h}:{},...h==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let N=!1;at.then(A=>{if(N=!0,k(`loadScript:resolved inactive=${Ge()} ns=${!!A} buttons=${!!A?.Buttons}`),Ge())return;if(!A?.Buttons){k("FAIL: namespace missing Buttons factory"),yr("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}T.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),T.performance({stage:"provider_ready",durationMs:T.elapsed(rt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),T.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let te=async(Ae,ne)=>{if(Ge()||Ve.current!==me)return;let ue=Ae.vaultSetupToken??Ae.subscriptionID??Ae.orderID??"",Ce=ue?or.current.get(ue):Gt.current.get(me);if(!(!Ce||!Ur(Ce.generation))&&Nr(Ce.generation)){or.current.delete(ue),Gt.current.delete(Ce.surfaceKey),$r("approved");try{if(Ct(!0),(0,Qe.invokeMerchantCallback)(()=>Kt.current?.(null)),!ue)throw new je.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ye=(0,je.resolvePayPalApprovalIdentity)({accountPatch:Ce.accountPatch,email:Dr.current,billingName:Ar.current,session:Qr.current});if((0,je.needsPayPalPayerDetails)(Ye))try{Ye=(0,je.mergePayPalPayerIdentity)(Ye,await ne?.order?.get?.())}catch{}if((jt.current||xt)&&!(0,je.isValidEmail)(Ye.email)){let yt=await st("PayPal",Ye);if(!yt)return;Ye=yt}(0,je.isValidEmail)(Ye.email)&&(Ce.accountPatch=(0,Cn.compactBuyerIdentity)({...Ce.accountPatch,...Ye}),await jt.current?.(Ye));let $t=(0,je.buildPayPalTokenizedBody)(ue,Fr);await Zt($t,Ce)}catch(Ye){ot(Ye instanceof Error?Ye.message:"PayPal capture failed.")}finally{Ge()||Ct(!1)}}},Te=Ae=>{let ne=Re?()=>q(Re):()=>Ot(Ae);return async()=>Kr(await ne())},Rt=A.Buttons({style:{layout:"horizontal",height:Ei,tagline:!1},...C==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Ae,ne)=>{if(Ge()){await ne.reject();return}_o();let ue=Or.current,Ce={};if(ue)try{let yt=await ue("paypal");if(Ge()){await ne.reject();return}if(!yt.proceed){tr.current=null,Gt.current.delete(me),await ne.reject();return}Ce={sessionId:yt.sessionId,accountPatch:yt.accountPatch,nonce:yt.nonce}}catch(yt){k(`onClick:runBeforeButtonClick rejected msg=${(yt instanceof Error?yt.message:String(yt)).slice(0,120)}`),tr.current=null,Gt.current.delete(me),await ne.reject();return}(0,Qe.invokeMerchantCallback)(()=>Pr.current?.("paypal"));let Ye=ir(),$t={generation:Ye,surfaceKey:me,...Ce};tr.current=$t,Gt.current.set(me,$t),Ke.current={...L,attempt:Ye},await ne.resolve(),T.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),T.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Se.current=T.startTiming()},createOrder:G==="order"?Te("Failed to create PayPal order."):void 0,createSubscription:G==="subscription"?Te("Failed to create PayPal subscription."):void 0,createVaultSetupToken:G==="setup_token"?async()=>Kr(await Ot("Failed to create PayPal setup token.")):void 0,onApprove:te,onCancel:()=>{if(Ge())return;let Ae=Gt.current.get(me)??tr.current,ne=Ae&&Ur(Ae.generation)?(0,je.buildPayPalCancelEvent)(Ae.sessionId??e,Fr):null;Ae&&Gt.current.delete(Ae.surfaceKey),tr.current=null,$r("cancelled"),T.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ye.current=!0,rr({generation:Ae?.generation,remount:!0,focus:!1}),ne&&(0,Qe.invokeMerchantCallback)(()=>He.current?.(ne))},onError:Ae=>{if(Ae instanceof je.FloPayError&&Ae.code===vc)return;let ne=Ae instanceof Error?Ae.message:"PayPal failed to render.";if(Ge()||Ve.current!==me){_r(ne)||qn(ro());return}if(Wt){let ue=Gt.current.get(me)??tr.current;if(!ue||!Ur(ue.generation)){if(_r(ne)){!ue&&!pr()&&Nr();return}qn(ue||pr()?"stale_attempt":"no_current_attempt");return}if(k(`onError rendered=${Wt} msg=${ne.slice(0,120)}`),_r(ne)){Nr(ue.generation);return}let{errorCode:Ce,popupBlocked:Ye,providerDeclined:$t,terminalReason:yt}=(0,we.classifyExternalMethodFailure)(Ae,{inAppBrowser:Jt.inAppBrowser,handoffObserved:ee.current===ue.generation});if(Ye&&J.markBlocked(),$r(yt),$t){T.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:yt}),Qt(Ae,ue),(0,Qe.invokeMerchantCallback)(()=>Vr.current?.(Sr("paypal",ne))),Gt.current.delete(ue.surfaceKey),tr.current=null,Nr(ue.generation);return}T.error({errorCode:Ce,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:yt}),Gt.current.delete(ue.surfaceKey),tr.current=null,rr({generation:ue.generation,remount:!0,showRetry:!0,focus:!0}),pn(Ae,{code:"paypal_runtime_failed",popupBlocked:Ye,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:C,terminalReason:yt});return}k(`onError rendered=${Wt} msg=${ne.slice(0,120)}`),yr(_r(ne)?"teardown":"pre_ready_callback",ne)}}),Me=Rt.isEligible();if(k(`isEligible=${Me}`),T.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Me){xe(!1),yr("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}jn=!0,yn=Rt,Wn=()=>{if(!Vn||fn||Ge()||Wt)return;fn=!0,k(`container:dims ${$n(Br)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(mn=new MutationObserver(ne=>{if(!Ge()){for(let ue of ne)if(ue.type==="childList")ue.addedNodes.forEach(Ce=>{if(!(Ce instanceof Element))return;let Ye=Ce.tagName.toLowerCase(),$t=(Ce.getAttribute("title")??"").slice(0,40),yt=Ye==="iframe"?` ${no(Ce)}`:"";k(`child+ ${Ye}${$t?` title="${$t}"`:""}${yt} dims=${$n(Ce)}`)});else if(ue.type==="attributes"&&ue.target instanceof Element){let Ce=ue.target;if(Ce.tagName.toLowerCase()!=="iframe")continue;let Ye=ue.attributeName;(Ye==="src"||Ye==="srcdoc")&&k(`attr~ iframe ${Ye}=${Ye==="srcdoc"?`[${(Ce.getAttribute("srcdoc")??"").length}ch]`:To(Ce.getAttribute("src"))} dims=${$n(Ce)}`)}}}),mn.observe(Br,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ae=ne=>{if(Ge()||Wt)return;let ue=Br.querySelectorAll("iframe"),Ce=typeof document<"u"&&"hasStorageAccess"in document;k(`watchdog:${ne} container=${$n(Br)} children=${Br.childElementCount} iframes=${ue.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Ce} paypalNetRequests=${Tn.value}`),ue.forEach((Ye,$t)=>{let yt=(Ye.getAttribute("title")??"").slice(0,40);k(` iframe[${$t}] ${$n(Ye)}${yt?` title="${yt}"`:""} ${no(Ye)}`);let va=go(Ye);va&&k(` ${va}`)}),ho.length===0&&k(" (no PayPal/zoid window errors captured)")};qr.push(setTimeout(()=>Ae("3s"),3e3)),qr.push(setTimeout(()=>Ae("8s"),8e3)),qr.push(setTimeout(()=>Ae("15s"),15e3))},Wn(),k("render:start");let ze=T.startTiming();In=setTimeout(()=>{Ge()||Wt||(k("watchdog:11s retryable render timeout"),yr("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},yu);let qt=Rt.render(Br);(async()=>{try{if(await qt,k(`render:resolved inactive=${Ge()}`),rn(),Ge()){tn();return}Wt=!0,xe(!0),vt(!1),Et.current?.("ready"),T.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),T.performance({stage:"checkout_render",durationMs:T.elapsed(ze),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Ae){let ne=Ae instanceof Error?Ae.message:"PayPal failed to render.";k(`render:rejected msg=${ne.slice(0,120)}`),rn(),yr(_r(ne)?"teardown":"render_rejected",ne)}})()}).catch(A=>{let te=A instanceof Error?A.message:"PayPal operation failed.";k(`provider:failed msg=${te.slice(0,120)}`);let Te="script_rejected";N&&_r(te)?Te="teardown":N&&jn&&(Te="render_rejected"),yr(Te,te)})},0);return()=>{Pt=!0,clearTimeout(re),Io&&clearTimeout(Io),rn(),I.current===gn&&(I.current=null),tn(),Se.current=null,Ke.current=null}},[be,lt,d,y,p,G,C,ce,e,Re,Ne,Y,st,xt,k,$r]);let zr=j?(0,bn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:le?"#fef2f2":"#f3f4f6",border:`1px solid ${le?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${ke} failed=${le})`,ie.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return
|
|
3
|
+
${ie.join(`
|
|
4
|
+
`)}`]}):null;return le&&!u?j?(0,bn.jsx)("div",{children:zr}):null:(0,bn.jsxs)("div",{children:[zr,bt&&(0,bn.jsx)(da,{identity:bt.identity,methodLabel:bt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:pt,onCancel:()=>pt(null)}),(0,bn.jsxs)("div",{"aria-hidden":_e||bt?!0:void 0,style:_e||bt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ei},children:[!ke&&!_e&&(0,bn.jsx)("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),(0,bn.jsx)("div",{ref:K,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ei,display:"flex",opacity:ke?1:0},"aria-busy":$e||H},Ne)]},Ne),We&&(0,bn.jsx)("button",{ref:ut,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Wr,style:mu,children:"Try PayPal again"})]})}function Da(e){return(0,bn.jsx)(Sc,{...e})}function wc(e){return(0,bn.jsx)(Sc,{...e})}var La=require("react/jsx-runtime");function ya({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,La.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...r?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...n??{}},children:[r&&(0,La.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,La.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var wt=require("@flopay/shared");var Rc=new Set;function Pu(){return globalThis.process?.env?.NODE_ENV==="production"}function kc(e,t){Rc.has(e)||Pu()||(Rc.add(e),console.warn(t))}function Ec(){kc("automatic-payment-button-inline-create","[FloPay] FloPayAutomaticPaymentButton: creating the session from inline props is deprecated and may be downgraded to a Full checkout. Mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and pass `getSession` instead.")}function _c(){kc("checkout-keyless-create","[FloPay] FloPayCheckout: `createSession` with checkoutMode confirm/auto is deprecated and may be downgraded to a Full checkout. For one-click, mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and use FloPayAutomaticPaymentButton `getSession`.")}var hr=require("react/jsx-runtime");var vu={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function on({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:s="PAYMENT FAILED",successNote:d="You will be automatically redirected, do not close or navigate away from this window.",theme:p=vu}){let y={fontSize:13,color:p.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,hr.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,hr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...p.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,hr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,hr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,hr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:p.spinnerTrackColor,strokeWidth:"3"}),(0,hr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:p.spinnerAccentColor})]}),e==="success"&&(0,hr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,hr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,hr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,hr.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,hr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,hr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,hr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,hr.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,hr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:p.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(a??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&s]}),e==="success"&&d!==null&&(0,hr.jsx)("p",{style:y,children:d}),e==="error"&&t&&(0,hr.jsx)("p",{style:y,children:t}),(0,hr.jsx)("style",{children:`
|
|
5
5
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
6
6
|
@keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
|
|
7
7
|
@keyframes flopay-draw { to { stroke-dashoffset: 0; } }
|
|
8
8
|
@keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
|
|
9
|
-
`})]})})}var _i=require("@flopay/shared"),_r=require("react");var wc=require("react/jsx-runtime");function Na({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,d]=(0,_r.useState)(e instanceof Promise?null:e),[p,m]=(0,_r.useState)(t instanceof Promise||!t?null:t),w=(0,_r.useRef)(null),h=(0,_r.useRef)(null),g=pa(n),_=(0,_r.useCallback)(k=>{(0,_i.isCardFieldsInstrumentSource)(k)||g(k)},[g]);(0,_r.useEffect)(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),(0,_r.useEffect)(()=>{s&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,s]),(0,_r.useEffect)(()=>{if(s)return Er(s)?.subscribe?.(_)},[_,s]),(0,_r.useEffect)(()=>{if(!(!p||p===s))return Er(p)?.subscribe?.(_)},[_,s,p]),(0,_r.useEffect)(()=>{if(!s)return;let k=Er(s);return w.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,_r.useEffect)(()=>{let k=!1;return e instanceof Promise?e.then(A=>{k||d(A)},()=>{k||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{k=!0}},[g,e]),(0,_r.useEffect)(()=>{let k=!1;if(!t){m(null);return}return t instanceof Promise?t.then(A=>{k||m(A)},()=>{k||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{k=!0}},[g,t]),(0,_r.useEffect)(()=>{if(!s||h.current===s)return;h.current=s;let k=Er(s);k?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(w.current??0),durationMode:"machine"})},[g,s]);let V=(0,_i.resolveBillingApiUrl)(r?.billingApiUrl),W=(0,_r.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:V,emitInstrument:g}),[s,p,V,g]);return(0,wc.jsx)(Rn.Provider,{value:W,children:a})}var jn=require("@flopay/shared");async function Ii(e,t){e.current?.abort();let r=new AbortController;e.current=r;try{return await t(r.signal)}finally{e.current===r&&(e.current=null)}}var Gr=require("@flopay/js"),je=require("@flopay/shared");var qa="card";async function fu(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:d}=await e.retrieveSetupIntent(t);return{error:d,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:n,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:n??null}}async function gu(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:d,error:p}=await e.confirmCardSetup(t,r);return{error:p,intent:d??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:s}=await e.confirmCardPayment(t,r);return{error:s,intent:a??null}}function ma(e){return new je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function hu(){return new je.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function za(e,t){return Object.assign(e,{checkoutMethod:t})}function po(e,t){let r=e instanceof je.FloPayError?e:new je.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Ua(e,t){try{return await e()}catch(r){throw po(r,t)}}function kc(e){return!e?.type||!e.threeDSecureToken||(0,je.isMerchantAuthRequired)(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Ec(e){return(0,Gr.runSavedCardChallenge)(e)}function ja(e,t,r,n=!0){let a={release:()=>{}};if(!n)return a;try{let s=new Gr.PaymentAPI(e),d=(0,Gr.beginSavedCardChallengeTelemetry)(s,t,r);return d?{telemetry:d,release:()=>{setTimeout(()=>{try{s.destroy()}catch{}},0)}}:a}catch{return a}}async function fa(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,d=new Gr.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,Gr.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:h=>Qn({type:h.declineReason??"authorization_declined",gatewayErrorCode:h.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},d)}catch(h){if(a.aborted||h instanceof Error&&h.name==="AbortError")throw h instanceof je.FloPayError&&h.code==="three_ds_aborted"?h:ma(h);if(!(h instanceof je.FloPayError)||h.code!=="three_ds_timeout"&&h.code!=="checkout_processing_timeout")throw h;try{m=await d.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(_){if(a.aborted)throw ma(_);if(!(_ instanceof je.FloPayError)||_.code!=="checkout_processing_timeout")throw _}let g=m&&ko(m,t.session);if(!lo(g)&&g?.status!=="expired"){if(t.telemetry){let _=new Gr.PaymentAPI(r);try{_.reportThreeDsAbandoned(n)}finally{_.destroy()}}throw hu()}}let w=m&&ko(m,t.session);if(!lo(w))throw sa(w);return{...so(w,n),checkoutMethod:"card"}}function _c(e){return new je.FloPayError("This payment needs your card details. Please complete your payment below.","authentication_error",{code:je.MERCHANT_AUTH_REQUIRED_CODE,...e===void 0?{}:{statusCode:e}})}function Qn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card");if((0,je.isMerchantAuthRequired)(e))return za(_c(),n);let a=e?.message??t,s=(0,Fo.applyFriendlyMessageOverride)(a)??a,d=za(new je.FloPayError(s,"api_error",{code:e?.code??(0,je.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,je.normalizeCheckoutFailureOutcome)(e?.type)??(e?.type==="paypal_direct_required"?"paypal_direct_required":void 0)??e?.gatewayErrorCode}),n);return e?.orderId&&(d.orderId=e.orderId),d}function Fs(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ti(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Ic(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ti(a)))return a;let n=e?.data;if(n&&typeof n=="object"){let a=n,s=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let p of s)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||Ti(p)))return p;let d=a.gateways;if(d&&typeof d=="object"){let p=d.stripe;if(p&&typeof p=="object"){let m=p,w=[m.stripeClientSecret,m.clientSecret];for(let h of w)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||Ti(h)))return h}}}}async function Pu({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Ic(n,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let p=(await new Gr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(Ti(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function ga({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:d}){let p=e.replace(/\/+$/,""),m=t??r.id,w=n??r.clientSecret,h=r.customer?.id??r.accountData?.userId??"",g=r.customer?.email??r.accountData?.email??"",_=r.customer?.firstName??r.accountData?.firstName??"",V=r.customer?.lastName??r.accountData?.lastName??"",W=r.customer?.country??r.accountData?.country??void 0,k=r.customer?.zip??r.accountData?.zip??void 0,f=await new Gr.PaymentAPI(p,d===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:m,nonce:w,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:h,email:g,firstName:_,lastName:V,country:W,zip:k},returnUrl:s??Fs(r)});if(f.ok){let Y=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,je.isAuthorizationOnlySession)(r)||Y?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof Y?.paymentId=="string"?Y.paymentId:r.paymentId,sessionId:typeof Y?.sessionId=="string"?Y.sessionId:m,authorizationExpiresAt:typeof Y?.authorizationExpiresAt=="string"?Y.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:xa(a),checkoutMethod:Rc(a,r)}};let b=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...b?{paymentIntentId:b}:{},paymentMethodId:xa(a),checkoutMethod:Rc(a,r)}}}let H;try{H=await f.json()}catch(Y){throw new je.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:Y})}if((0,je.isMerchantAuthRequired)(H))throw za(_c(f.status),"card");if(H?.type==="3ds_required"&&typeof H.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:H.nextActionRedirectUrl};if(H?.type==="paypal_redirect_required"||H?.type==="3ds_required"){let Y=Ic(H);if(!Y)throw new je.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:H.type,threeDSecureToken:Y,paymentMethodId:H.paymentMethodId}}if(H?.gatewayErrorCode==="authentication_required"){let Y=await Pu({billingApiUrl:p,sessionId:m,nonce:w,responseJson:H});if(Y)return Y;throw za(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw vu(H,f.status)}function vu(e,t){let r=new je.FloPayError(e?.message??"Payment failed. Please try again.","api_error",{code:e?.code??e?.gatewayErrorCode,declineCode:e?.declineCode??e?.gatewayDeclineReason,statusCode:t});return Object.assign(r,{telemetryOutcome:(0,je.classifyPaymentRejection)(t,e)})}async function Mi(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:m,signal:w}){let h=t?.getRawProvider();if(!h)throw po(new je.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw za(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=(0,je.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,V=e.paymentMethodId,W=await Ua(()=>fu(h,e.threeDSecureToken,g),"card");if(W){if(W.error)throw po(new je.FloPayError(W.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:W.error.code}),"card");let A=W.intent;!V&&A?.payment_method&&(typeof A.payment_method=="string"?V=A.payment_method:"id"in A.payment_method&&(V=A.payment_method.id??void 0))}let k=V?await Ua(()=>gu(h,e.threeDSecureToken,{payment_method:V,return_url:p??Fs(d)??window.location.href},g),"card"):null;if(k){if(k.error)throw po(new je.FloPayError(k.error.message??"3DS authentication failed.","api_error",{code:k.error.code}),"card");_=k.intent}else{let A=await Ua(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(A.error)throw po(new je.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");_=(g?A.setupIntent:A.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let A=await ga({billingApiUrl:a,sessionId:s,session:d,telemetry:m,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:p});return A.type==="success"?{...A.result,paymentIntentId:A.result.paymentIntentId??_.id,paymentMethodId:A.result.paymentMethodId??V}:A.type==="next_action_required"?fa(A,{billingApiUrl:a,sessionId:s??d.id,session:d,signal:w}):Mi(A,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:m,signal:w})}throw po(new je.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(r??t)?.getRawProvider();if(!g)throw po(new je.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:V}=await Ua(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(V)throw po(new je.FloPayError(V.message??"PayPal authorization failed.","api_error",{code:V.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await Ua(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??Fs(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(_)throw po(new je.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new je.FloPayError("Unsupported payment redirect state.","api_error")}function Va(e){if(e instanceof je.FloPayError){let n=(0,Fo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new je.FloPayError(n,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",r=(0,Fo.applyFriendlyMessageOverride)(t)??t;return new je.FloPayError(r,"api_error")}function Bs(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,je.isMountableVaultBlock)(e.data.session?.vault)||(0,Un.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new je.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Rc(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,Un.canRecoverHostedCardForm)(t)?"card":void 0}async function Os({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let s=t&&t!==e?t:void 0,[d,p]=await Promise.all([(0,Gr.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,Gr.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(w=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",w),null)):Promise.resolve(null)]);if(!d)throw new je.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return s?m=p:t&&(m=d),{flopay:d,paypalFlopay:m}}var Wn=require("@flopay/js"),c=require("@flopay/shared"),lr=require("@stripe/react-stripe-js"),o=Es(require("react"),1);function Do(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Ai(e,t){if(e)return{error:r=>e.error(Do(t,r)),log:r=>e.log(Do(t,r)),performance:r=>e.performance(Do(t,r)),terminal:r=>e.terminal(Do(t,r)),now:()=>e.now(),elapsed:r=>e.elapsed(r),setCheckoutContext:r=>e.setCheckoutContext(r),beginCheckout:r=>e.beginCheckout(r),disable:()=>e.disable(),subscribe:r=>e.subscribe(r),flush:()=>e.flush(),destroy:()=>e.destroy()}}var Lo=require("react"),No=require("react/jsx-runtime"),Tc="More payment options",Cu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},bu={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function Ds({label:e,open:t,showLink:r,onOpen:n,color:a,fontFamily:s,children:d}){let p=(0,Lo.useId)(),m=(0,Lo.useRef)(null),w=(0,Lo.useRef)(!1);return(0,Lo.useEffect)(()=>{t&&w.current&&m.current?.focus()},[t]),(0,No.jsxs)(No.Fragment,{children:[!t&&r&&(0,No.jsx)("button",{type:"button","data-testid":"flopay-more-payment-options","aria-expanded":!1,"aria-controls":p,onClick:()=>{w.current=!0,n()},style:{alignSelf:"center",margin:0,padding:"0.25rem 0",border:0,background:"none",cursor:"pointer",color:a,fontFamily:s,fontSize:"0.9rem",fontWeight:500,textDecoration:"underline",textUnderlineOffset:"0.2em"},children:e}),(0,No.jsx)("div",{id:p,ref:m,role:"group","aria-label":e,tabIndex:t?-1:void 0,"data-testid":"flopay-more-payment-options-section",style:t?bu:Cu,children:d})]})}var yo=require("@flopay/shared"),Ac=require("react");var Mc={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var Lr=require("react/jsx-runtime"),Su=`
|
|
9
|
+
`})]})})}var _i=require("@flopay/shared"),Rr=require("react");var Ic=require("react/jsx-runtime");function Na({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,d]=(0,Rr.useState)(e instanceof Promise?null:e),[p,y]=(0,Rr.useState)(t instanceof Promise||!t?null:t),S=(0,Rr.useRef)(null),P=(0,Rr.useRef)(null),g=pa(n),_=(0,Rr.useCallback)(R=>{(0,_i.isCardFieldsInstrumentSource)(R)||g(R)},[g]);(0,Rr.useEffect)(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),(0,Rr.useEffect)(()=>{s&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,s]),(0,Rr.useEffect)(()=>{if(s)return wr(s)?.subscribe?.(_)},[_,s]),(0,Rr.useEffect)(()=>{if(!(!p||p===s))return wr(p)?.subscribe?.(_)},[_,s,p]),(0,Rr.useEffect)(()=>{if(!s)return;let R=wr(s);return S.current=R?.beginCheckout()??R?.now()??0,R?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{R?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Rr.useEffect)(()=>{let R=!1;return e instanceof Promise?e.then(x=>{R||d(x)},()=>{R||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{R=!0}},[g,e]),(0,Rr.useEffect)(()=>{let R=!1;if(!t){y(null);return}return t instanceof Promise?t.then(x=>{R||y(x)},()=>{R||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{R=!0}},[g,t]),(0,Rr.useEffect)(()=>{if(!s||P.current===s)return;P.current=s;let R=wr(s);R?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),R?.performance({stage:"checkout_render",durationMs:R.elapsed(S.current??0),durationMode:"machine"})},[g,s]);let W=(0,_i.resolveBillingApiUrl)(r?.billingApiUrl),$=(0,Rr.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:W,emitInstrument:g}),[s,p,W,g]);return(0,Ic.jsx)(vn.Provider,{value:$,children:a})}var Dn=require("@flopay/shared");async function Ii(e,t){e.current?.abort();let r=new AbortController;e.current=r;try{return await t(r.signal)}finally{e.current===r&&(e.current=null)}}var Xr=require("@flopay/js"),Xe=require("@flopay/shared");var qa="card";async function Cu(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:d}=await e.retrieveSetupIntent(t);return{error:d,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:n,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:n??null}}async function bu(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:d,error:p}=await e.confirmCardSetup(t,r);return{error:p,intent:d??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:s}=await e.confirmCardPayment(t,r);return{error:s,intent:a??null}}function ma(e){return new Xe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Su(){return new Xe.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function za(e,t){return Object.assign(e,{checkoutMethod:t})}function uo(e,t){let r=e instanceof Xe.FloPayError?e:new Xe.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Ua(e,t){try{return await e()}catch(r){throw uo(r,t)}}function Mc(e){return!e?.type||!e.threeDSecureToken||(0,Xe.isMerchantAuthRequired)(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Ac(e){return(0,Xr.runSavedCardChallenge)(e)}function ja(e,t,r,n=!0){let a={release:()=>{}};if(!n)return a;try{let s=new Xr.PaymentAPI(e),d=(0,Xr.beginSavedCardChallengeTelemetry)(s,t,r);return d?{telemetry:d,release:()=>{setTimeout(()=>{try{s.destroy()}catch{}},0)}}:a}catch{return a}}async function fa(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,d=new Xr.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,y;try{y=await(0,Xr.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:P=>Zn({type:P.declineReason??"authorization_declined",gatewayErrorCode:P.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},d)}catch(P){if(a.aborted||P instanceof Error&&P.name==="AbortError")throw P instanceof Xe.FloPayError&&P.code==="three_ds_aborted"?P:ma(P);if(!(P instanceof Xe.FloPayError)||P.code!=="three_ds_timeout"&&P.code!=="checkout_processing_timeout")throw P;try{y=await d.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(_){if(a.aborted)throw ma(_);if(!(_ instanceof Xe.FloPayError)||_.code!=="checkout_processing_timeout")throw _}let g=y&&Ro(y,t.session);if(!so(g)&&g?.status!=="expired"){if(t.telemetry){let _=new Xr.PaymentAPI(r);try{_.reportThreeDsAbandoned(n)}finally{_.destroy()}}throw Su()}}let S=y&&Ro(y,t.session);if(!so(S))throw sa(S);return{...io(S,n),checkoutMethod:"card"}}function xc(e){return new Xe.FloPayError("This payment needs your card details. Please complete your payment below.","authentication_error",{code:Xe.MERCHANT_AUTH_REQUIRED_CODE,...e===void 0?{}:{statusCode:e}})}function Zn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card");if((0,Xe.isMerchantAuthRequired)(e))return za(xc(),n);let a=e?.message??t,s=(0,Oo.applyFriendlyMessageOverride)(a)??a,d=za(new Xe.FloPayError(s,"api_error",{code:e?.code??(0,Xe.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Xe.normalizeCheckoutFailureOutcome)(e?.type)??(e?.type==="paypal_direct_required"?"paypal_direct_required":void 0)??e?.gatewayErrorCode}),n);return e?.orderId&&(d.orderId=e.orderId),d}function Ls(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ti(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Fc(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ti(a)))return a;let n=e?.data;if(n&&typeof n=="object"){let a=n,s=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let p of s)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||Ti(p)))return p;let d=a.gateways;if(d&&typeof d=="object"){let p=d.stripe;if(p&&typeof p=="object"){let y=p,S=[y.stripeClientSecret,y.clientSecret];for(let P of S)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||Ti(P)))return P}}}}async function wu({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Fc(n,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let p=(await new Xr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(Ti(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function ga({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:d}){let p=e.replace(/\/+$/,""),y=t??r.id,S=n??r.clientSecret,P=r.customer?.id??r.accountData?.userId??"",g=r.customer?.email??r.accountData?.email??"",_=r.customer?.firstName??r.accountData?.firstName??"",W=r.customer?.lastName??r.accountData?.lastName??"",$=r.customer?.country??r.accountData?.country??void 0,R=r.customer?.zip??r.accountData?.zip??void 0,f=await new Xr.PaymentAPI(p,d===!1?{telemetry:!1}:void 0).processPayment(P,{sessionId:y,nonce:S,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:P,email:g,firstName:_,lastName:W,country:$,zip:R},returnUrl:s??Ls(r)});if(f.ok){let X=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,Xe.isAuthorizationOnlySession)(r)||X?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof X?.paymentId=="string"?X.paymentId:r.paymentId,sessionId:typeof X?.sessionId=="string"?X.sessionId:y,authorizationExpiresAt:typeof X?.authorizationExpiresAt=="string"?X.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:xa(a),checkoutMethod:Tc(a,r)}};let v=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...v?{paymentIntentId:v}:{},paymentMethodId:xa(a),checkoutMethod:Tc(a,r)}}}let H;try{H=await f.json()}catch(X){throw new Xe.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:X})}if((0,Xe.isMerchantAuthRequired)(H))throw za(xc(f.status),"card");if(H?.type==="3ds_required"&&typeof H.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:H.nextActionRedirectUrl};if(H?.type==="paypal_redirect_required"||H?.type==="3ds_required"){let X=Fc(H);if(!X)throw new Xe.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:H.type,threeDSecureToken:X,paymentMethodId:H.paymentMethodId}}if(H?.gatewayErrorCode==="authentication_required"){let X=await wu({billingApiUrl:p,sessionId:y,nonce:S,responseJson:H});if(X)return X;throw za(new Xe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw Ru(H,f.status)}function Ru(e,t){let r=new Xe.FloPayError(e?.message??"Payment failed. Please try again.","api_error",{code:e?.code??e?.gatewayErrorCode,declineCode:e?.declineCode??e?.gatewayDeclineReason,statusCode:t});return Object.assign(r,{telemetryOutcome:(0,Xe.classifyPaymentRejection)(t,e)})}async function Mi(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:y,signal:S}){let P=t?.getRawProvider();if(!P)throw uo(new Xe.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw za(new Xe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=(0,Xe.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,W=e.paymentMethodId,$=await Ua(()=>Cu(P,e.threeDSecureToken,g),"card");if($){if($.error)throw uo(new Xe.FloPayError($.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:$.error.code}),"card");let x=$.intent;!W&&x?.payment_method&&(typeof x.payment_method=="string"?W=x.payment_method:"id"in x.payment_method&&(W=x.payment_method.id??void 0))}let R=W?await Ua(()=>bu(P,e.threeDSecureToken,{payment_method:W,return_url:p??Ls(d)??window.location.href},g),"card"):null;if(R){if(R.error)throw uo(new Xe.FloPayError(R.error.message??"3DS authentication failed.","api_error",{code:R.error.code}),"card");_=R.intent}else{let x=await Ua(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(x.error)throw uo(new Xe.FloPayError(x.error.message??"3DS authentication failed.","api_error",{code:x.error.code}),"card");_=(g?x.setupIntent:x.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let x=await ga({billingApiUrl:a,sessionId:s,session:d,telemetry:y,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:p});return x.type==="success"?{...x.result,paymentIntentId:x.result.paymentIntentId??_.id,paymentMethodId:x.result.paymentMethodId??W}:x.type==="next_action_required"?fa(x,{billingApiUrl:a,sessionId:s??d.id,session:d,signal:S}):Mi(x,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:y,signal:S})}throw uo(new Xe.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(r??t)?.getRawProvider();if(!g)throw uo(new Xe.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:W}=await Ua(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(W)throw uo(new Xe.FloPayError(W.message??"PayPal authorization failed.","api_error",{code:W.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await Ua(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??Ls(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(_)throw uo(new Xe.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Xe.FloPayError("Unsupported payment redirect state.","api_error")}function Va(e){if(e instanceof Xe.FloPayError){let n=(0,Oo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new Xe.FloPayError(n,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",r=(0,Oo.applyFriendlyMessageOverride)(t)??t;return new Xe.FloPayError(r,"api_error")}function Ns(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,Xe.isMountableVaultBlock)(e.data.session?.vault)||(0,Fn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new Xe.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Tc(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,Fn.canRecoverHostedCardForm)(t)?"card":void 0}async function Us({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let s=t&&t!==e?t:void 0,[d,p]=await Promise.all([(0,Xr.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,Xr.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);if(!d)throw new Xe.FloPayError("The payment provider did not initialize.","authentication_error");let y=null;return s?y=p:t&&(y=d),{flopay:d,paypalFlopay:y}}var Nn=require("@flopay/js"),c=require("@flopay/shared"),cr=require("@stripe/react-stripe-js"),o=Ms(require("react"),1);function No(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Ai(e,t){if(e)return{error:r=>e.error(No(t,r)),log:r=>e.log(No(t,r)),performance:r=>e.performance(No(t,r)),terminal:r=>e.terminal(No(t,r)),now:()=>e.now(),elapsed:r=>e.elapsed(r),setCheckoutContext:r=>e.setCheckoutContext(r),beginCheckout:r=>e.beginCheckout(r),disable:()=>e.disable(),subscribe:r=>e.subscribe(r),flush:()=>e.flush(),destroy:()=>e.destroy()}}var Uo=require("react"),zo=require("react/jsx-runtime"),Bc="More payment options",ku={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Eu={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function zs({label:e,open:t,showLink:r,onOpen:n,color:a,fontFamily:s,children:d}){let p=(0,Uo.useId)(),y=(0,Uo.useRef)(null),S=(0,Uo.useRef)(!1);return(0,Uo.useEffect)(()=>{t&&S.current&&y.current?.focus()},[t]),(0,zo.jsxs)(zo.Fragment,{children:[!t&&r&&(0,zo.jsx)("button",{type:"button","data-testid":"flopay-more-payment-options","aria-expanded":!1,"aria-controls":p,onClick:()=>{S.current=!0,n()},style:{alignSelf:"center",margin:0,padding:"0.25rem 0",border:0,background:"none",cursor:"pointer",color:a,fontFamily:s,fontSize:"0.9rem",fontWeight:500,textDecoration:"underline",textUnderlineOffset:"0.2em"},children:e}),(0,zo.jsx)("div",{id:p,ref:y,role:"group","aria-label":e,tabIndex:t?-1:void 0,"data-testid":"flopay-more-payment-options-section",style:t?Eu:ku,children:d})]})}var po=require("@flopay/shared"),Dc=require("react");var Oc={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var Tr=require("react/jsx-runtime"),_u=`
|
|
10
10
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
11
11
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
12
12
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -27,7 +27,7 @@ ${L.join(`
|
|
|
27
27
|
0% { opacity: 1; transform: translateX(0) scale(1); }
|
|
28
28
|
100% { opacity: 0; transform: translateX(16px) scale(0.97); }
|
|
29
29
|
}
|
|
30
|
-
`,Eo=44;function ha(){return(0,Lr.jsx)("style",{children:Su})}function Wa(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function $a({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Lr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Lr.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:r,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,Lr.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:n})]})}function Ha(e){return e!=="unavailable"&&e!=="load_error"}function xi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:d,backgroundColor:p,borderColor:m,textColor:w,borderRadius:h,fontFamily:g}){let _=(0,yo.resolveStripeMethodBrandVariant)(e,t),V=Mc[e],[W,k]=(0,Ac.useState)(!1),A=!!V&&!W,f=_?.backgroundColor??p??"#ffffff",H=_?.borderColor??m??"#d1d5db",Y=_?.textColor??w??"#262833";return(0,Lr.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&d()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Eo,padding:"0 1rem",backgroundColor:f,color:Y,border:`1px solid ${H}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:g,cursor:r||n?"not-allowed":"pointer",opacity:n&&!r?.55:1,animation:r?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,Lr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,yo.getStripeMethodDisplayName)(e)}\u2026`}):(0,Lr.jsxs)(Lr.Fragment,{children:[(0,Lr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,yo.hasVendoredStripeMethodLogo)(e)?8:0},children:[A?(0,Lr.jsx)("img",{src:V,alt:"","aria-hidden":"true",onError:()=>k(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!A&&_?.logoSvg?(0,Lr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:_.logoSvg}}):null,(0,Lr.jsx)("span",{children:(0,yo.getStripeMethodDisplayName)(e)})]}),s&&(0,Lr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:Y,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,Lr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Fi(e){let t=new Set(e.map(yo.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var Bi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},Oi={type:"accordion",defaultCollapsed:!1,radios:"never"};function Di({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:d,children:p}){return(0,Lr.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:a,color:"white",border:"none",borderRadius:s,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...d??{}},children:p})}var Ls=require("react/jsx-runtime"),wu=["first","second","third","fourth"];function Ns({rows:e,borderRadius:t}){return(0,Ls.jsx)("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:wu.slice(0,Math.max(1,e)).map(r=>(0,Ls.jsx)("div",{style:{height:Eo,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},r))})}var Fc=require("@flopay/js"),Li=require("@flopay/shared"),Ni=require("react"),Ru=1500,xc=new Set;function Bc(e){for(let t of e)xc.has(t)||(xc.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function ku(e){if(e!=null)try{return JSON.stringify(e)}catch{return Bc(["the rules could not be sent (they are not plain data), so the default layout applies."]),"{}"}}var Eu={order:[...Li.DEFAULT_PAYMENT_METHOD_ORDER],moreOptions:[]};function Oc({rules:e,sessionId:t,nonce:r,billingApiUrl:n,waitForSession:a}){let s=ku(e),[d,p]=(0,Ni.useState)(null);return(0,Ni.useEffect)(()=>{if(s===void 0||a)return;let m=JSON.parse(s),w=!1,h=W=>{w||(w=!0,p(W))},g=()=>h((0,Li.resolveDefaultPaymentMethodLayout)(m));if(!t||!r||!n){g();return}let _=new AbortController,V=setTimeout(()=>{g(),_.abort()},Ru);return new Fc.PaymentAPI(n,{telemetry:!1}).resolvePaymentMethodLayout(t,r,m,{signal:_.signal}).then(W=>{if(!W){g();return}w||Bc(W.warnings),h({order:W.order,moreOptions:W.moreOptions})}).catch(g).finally(()=>clearTimeout(V)),()=>{w=!0,clearTimeout(V),_.abort()}},[s,t,r,n,a]),s===void 0?Eu:d}var dn=require("react");var Ka=require("@flopay/shared"),_u=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function Iu(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return _u.has(t.charAt(0).toLowerCase()+t.slice(1))}function Tu(e,t){return typeof t=="number"&&t!==0&&!Iu(e)?`${t}px`:String(t).trim()}function Dc(e,t){if(e.style.cssText="",!!t){for(let[r,n]of Object.entries(t))if(!(n==null||n==="")){if(r.startsWith("--")){e.style.setProperty(r,String(n));continue}e.style[r]=Tu(r,n)}}}var Uo=require("react/jsx-runtime"),Us=new WeakSet;function _o({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:d,containerStyle:p,onReady:m,onError:w,onValidation:h}){let g=(0,dn.useRef)(null),_=(0,dn.useRef)(m),V=(0,dn.useRef)(w),W=(0,dn.useRef)(h);_.current=m,V.current=w,W.current=h;let k=(0,dn.useRef)(s);k.current=s;let A=(0,dn.useRef)(null),f=d??void 0,H=(0,dn.useRef)(f);H.current=f;let Y=(0,dn.useRef)(void 0);return(0,dn.useEffect)(()=>{let b=g.current;if(!b)return;let be=!0,x=!1,oe=()=>{!be||x||(x=!0,_.current?.())},ge=e.on("ready",()=>{oe()}),Ie=e.on("error",q=>{V.current?.(q.message??"There was a problem loading the secure card form.")}),ce=e.on("validation",q=>{W.current?.(q.message??null)}),Rt=H.current??(Us.has(e)?null:void 0),mt={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...k.current?{theme:k.current}:{},...Rt===void 0?{}:{submitLabel:Rt}};return A.current=k.current??null,Y.current=H.current,H.current!==void 0&&Us.add(e),e.mount(b,mt).then(()=>{oe()}).catch(q=>{be&&V.current?.(q instanceof Error?q.message:"Failed to load the secure card form.")}),()=>{be=!1,ge(),Ie(),ce(),e.unmount()}},[e,t,r,n,a]),Bo(()=>{let b=g.current;b&&Dc(b,p)},[p]),(0,dn.useEffect)(()=>{s!==void 0&&(s===null&&A.current===null||(A.current=s,e.applyTheme?.(s)))},[e,s]),(0,dn.useEffect)(()=>{f!==Y.current&&(Y.current=f,f!==void 0&&Us.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,Uo.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields"})}function Ga({label:e}){return(0,Uo.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,Uo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,Uo.jsx)("span",{children:e}),(0,Uo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var Xs=require("@flopay/shared"),l=require("react/jsx-runtime"),eo="flopay_stripe_resume",Lc="flopay_wallet_resume",Kc="fw1",Mu="fw2",Gc=300*1e3,Au=900,xu="express_checkout_click_timeout",Fu=25e3,Bu=25e3,Ou=1e4,Vn={provider:"paypal",paymentMethodCategory:"paypal"},Du="x-flopay-process-result-source",Lu="status";async function Nu(e,t,r){try{let n=(await e.getUnifiedCheckoutSession(t,r)).data.session;if(n?.status==="complete")return null;if(n?.status==="authorized")return{status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}}catch{}}var Ui={},Xa=class{constructor(t){this.reason=t}};function Uu(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function cr(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function Ks(e){return`${Mu}:${e}`}function zi(e){return cr(Ks(e))}function qi(e,t){if(typeof window>"u")return null;let r=Ks(e);try{let n=localStorage.getItem(r);if(!n)return null;let a=JSON.parse(n);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>Gc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(zi(e),null):a}catch{return zi(e),null}}function zu(e){return cr(Ks(e.sessionId),e)}function Nc(e,t,r){let n=qi(e,t);return!n||n.clientSecret!==r?!1:zi(e)}function zs(e,t,r){if(typeof window>"u")return;qi(e,t)?.clientSecret===r&&zi(e)}function qu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function qs(e,t,r){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let n=r?e.status==="succeeded":Aa(e.status),a=qu(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Uc(e,t,r){let n=null;try{return await Promise.race([lc(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Ou),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function ju(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Yc(e){return e instanceof c.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ji(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Wn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw Yc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var js=c.STRIPE_PAYPAL_RESUME_KEY,Ya=new Map,Vu=250,zc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Wu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Gs(e,t,r,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:r,requestCategory:"provider_sdk",...n?{terminalReason:n}:{}})}async function Vi({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new Wn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function $u(e){return e instanceof c.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Xc({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,la.splitFullName)(r),d=s.firstName?s:(0,la.splitFullName)(n?.name);return(0,kn.compactBuyerIdentity)({email:(0,c.isValidEmail)(a)?a:n?.email?.trim(),firstName:d.firstName,lastName:d.lastName})}async function Hu({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let d=Xc({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,c.isValidEmail)(d.email)?d:s(a,d)}var Ja=180,qc=`flopay-card-enter ${Ja}ms cubic-bezier(0, 0, 0.2, 1) both`,jc=`flopay-card-exit ${Ja}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Ku=`flopay-buttons-enter ${Ja}ms cubic-bezier(0, 0, 0.2, 1) both`,Gu=`flopay-buttons-exit ${Ja}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Yu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ys(e){return(0,c.derivePrimaryTileStyle)(e)}var Xu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Ju(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var Ws={width:"100%",minHeight:Eo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Vc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function $s(e){return e==="paypal"?"PayPal":(0,c.getStripeMethodDisplayName)(e)}function Zu(e){let t=(0,c.getPostalCodeExample)(e);return`Enter a valid ${(0,c.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Qu(e,t,r){let n=(0,c.isPostalCodeSupported)(e),a=t.trim(),s=r&&n,d=s&&!a,p=s&&!!a&&!(0,c.isValidPostalCode)(e,a);return{visible:r,supported:n,required:s,empty:d,malformed:p}}function ep(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,c.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function tp(e){return typeof e=="number"?`${e}px`:e}var rp=["number","expiry","cvv","name"];function np(e){if(e===null||typeof e!="object")return null;let t={};for(let r of rp){let n=e[r];typeof n=="string"&&(t[r]=n)}return JSON.stringify(t)}function Wi(e){return(0,l.jsx)(ip,{...e})}function Wc({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:d=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:w,runBeforeButtonClick:h,billingName:g,onBuyerIdentityReady:_,onLoadStateChange:V,placeholderBorderRadius:W,popupCapabilityOwner:k,externalTelemetryContext:A,presentationMode:f}){let H=uo(),{emitInstrument:Y}=(0,o.useContext)(Rn),b=(0,lr.useStripe)(),be=(0,lr.useElements)(),x=(0,o.useMemo)(()=>Ai(Er(H),A),[A,H]),[oe,ge]=(0,o.useState)("loading");(0,o.useEffect)(()=>{V?.(oe)},[oe,V]);let[Ie,ce]=(0,o.useState)(!1),Rt=(0,o.useRef)(!1),mt=!(0,c.isValidEmail)(r?.trim())||!g?.trim(),{request:q,collect:Ve,finish:We}=ca(),Ne=(0,o.useRef)(!1),ve=(0,o.useRef)(null),G=(0,o.useRef)(null),[K,Ze]=(0,o.useState)(0),[Se,qe]=(0,o.useState)(!1),Z=(0,o.useRef)(!1),j=(0,o.useRef)(new Map),{startAttempt:he,finishAttempt:X,invalidateAttempt:Pt,isAttemptInvalidated:pe,isAttemptCurrent:we,generationRef:Ae}=Oa((xe,Oe,Ke)=>{w?.(xe,Oe,{...Ke,popupBlocked:Ke?.popupBlocked??(0,_e.isPopupBlockedError)(Oe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),qe(!0),Ze(vt=>vt+1)},{onHandoffObserved:()=>{k.markAvailable(),x?.log({name:"provider.popup.opened",stage:"overlay_open",...Vn,attempt:Ae.current})}});(0,o.useEffect)(()=>{Se&&G.current?.focus()},[Se,K]);let Ce=(0,o.useCallback)(()=>{Ze(xe=>xe+1)},[]),kt=(0,o.useCallback)((xe,Oe,Ke)=>{Pt(Ke),w?.("paypal",xe,{code:Oe,popupBlocked:(0,_e.isPopupBlockedError)(xe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),qe(!0),Ce()},[Pt,w,f,Ce]),Pe=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ve.current?.querySelector("iframe")??ve.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Z.current&&(Z.current=!1,Pe())},[Pe,K]);let Be=(0,o.useCallback)(()=>{qe(!1),s?.(null),Pe()},[Pe,s]);(0,o.useEffect)(()=>{if(!b||Ne.current)return;let[xe,Oe,Ke]=(0,c.readStripeRedirectParams)();if(!xe||!Oe)return;let vt=(0,c.readMatchingStripePayPalContinuation)(Oe);if(!vt)return;Ne.current=!0;let it=!0,ft=Ya.get(Oe);ft||(ft=Ke==="failed"?Promise.resolve(null):Promise.resolve().then(()=>b.retrievePaymentIntent(Oe)),Ya.set(Oe,ft));let Lt={accountPatch:vt.accountPatch,sessionId:vt.sessionId,nonce:vt.nonce},Qe=()=>{x?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Vn,requestCategory:"provider_sdk"})};return x?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Vn}),(async()=>{try{ce(!0);let de=await ft;if(!it)return;if(de?.error){Ya.delete(Oe),Qe(),s?.(de.error.message??"Failed to retrieve PayPal payment status.");return}if((0,c.clearStripePayPalReturn)(),Ya.delete(Oe),Ke==="failed"){let et="PayPal payment was declined. Please try again.";x?.terminal({outcome:"payment_declined",...Vn,terminalReason:"provider_declined"}),s?.(et),m?.(kr("paypal",et));return}let Ot=de?.paymentIntent;if(Ot&&Ot.id!==xe){Qe(),s?.("Failed to match the returned PayPal payment.");return}if(Ot&&(Ot.status==="requires_capture"||Ot.status==="succeeded")){let et=typeof Ot.payment_method=="string"?Ot.payment_method:Ot.payment_method?.id;a({id:et??Ot.id,type:"card",threeDSecureActionResultTokenId:Ot.id,isPaypal:!0},{...Lt,presentationMode:"redirect"})}else{let et="PayPal payment was not completed. Please try again.";x?.terminal({outcome:Ot?.status==="canceled"?"payment_cancelled":"payment_declined",...Vn,terminalReason:Ot?.status==="canceled"?"cancelled":"provider_declined"}),s?.(et),m?.(kr("paypal",et))}}catch(de){if(!it)return;Ya.delete(Oe),Qe(),s?.(de instanceof Error?de.message:"Failed to complete PayPal payment.")}finally{it&&ce(!1)}})(),()=>{it=!1,Ne.current=!1}},[b,a,s,m,x]);let at=(0,o.useCallback)(async(xe=!1)=>{let Oe=h?await h("paypal"):{proceed:!0};if(!Oe.proceed)return j.current.delete(K),!1;let Ke=he("paypal");return j.current.set(K,{generation:Ke,accountPatch:Oe.accountPatch,sessionId:Oe.sessionId,nonce:Oe.nonce}),qe(!1),x?.log({name:`provider.${xe?"redirect.started":"handoff.requested"}`,stage:xe?"redirect":"overlay_open",...Vn,attempt:Ke}),p?.("paypal"),!0},[p,x,h,he,K]),yt=(0,o.useCallback)(async xe=>{if(d||Ie||!await at()){xe.reject();return}xe.resolve()},[d,at,Ie]),Mt=(0,o.useCallback)(async xe=>{if(!b||!be)return;let Oe=j.current.get(K);if(Oe&&!we(Oe.generation)){j.current.delete(K);return}if(!Oe&&pe()||Oe&&!X(Oe.generation))return;Oe||X();let Ke=Oe??null;if(j.current.delete(K),!Ke&&h){let st=await h("paypal");if(!st.proceed){xe.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Ke={accountPatch:st.accountPatch,sessionId:st.sessionId,nonce:st.nonce}}let vt=Ke?.sessionId??e,it=Ke?.nonce??t,ft=await Hu({event:xe,prepared:Ke,email:r,billingName:g,methodLabel:"PayPal",collect:Ve});if(!ft){xe.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Lt=ft.email,Qe={...Ke?.accountPatch,...(0,kn.compactBuyerIdentity)(ft,!0)};try{if(ce(!0),s?.(null),!vt||!(0,c.isValidEmail)(Lt))throw new Error("Missing sessionId or email for PayPal payment");await _?.(ft);let st=b.createPaymentMethod,{error:de,paymentMethod:Ot}=await st({type:"paypal"});if(de){kt(de,"stripe_paypal_create_payment_method_failed",Oe?.generation),xe.paymentFailed({reason:"fail"});return}let et=await ji(n,Y,vt,it??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Ot?.id??null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(et)){xe.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:Qe,paymentMethodCategory:"paypal",presentationMode:f,sessionId:vt,nonce:it,settledProcessResponse:et.response});return}if(et.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let re=et.clientSecret,v={return_url:(0,c.stripeRedirectReturnUrl)()};if(Ot?.id&&(v.payment_method=Ot.id),!cr(js,{clientSecret:re,sessionId:vt,nonce:it,accountPatch:Qe})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:ee,paymentIntent:$}=await b.confirmPayment({clientSecret:re,confirmParams:v,redirect:"if_required"});if(ee){if(cr(js),(0,_e.isProviderDecline)(ee)){let u=ee.message??"Your payment was declined.";x?.terminal({outcome:"payment_declined",...Vn,terminalReason:"provider_declined"}),s?.(u),m?.(kr("paypal",u,{code:(0,_e.getProviderErrorCode)(ee),declineCode:(0,_e.getProviderDeclineCode)(ee)})),await Vi({billingApiUrl:n,sessionId:vt,nonce:it,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,_e.getProviderErrorCode)(ee)??"provider_declined"}})}else kt(ee,"stripe_paypal_confirm_failed",Oe?.generation);return}cr(js);let nt=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;a({id:nt??$?.id,type:"card",threeDSecureActionResultTokenId:$?.id,isPaypal:!0},{accountPatch:Qe,paymentMethodCategory:"paypal",presentationMode:f,sessionId:vt,nonce:it});return}catch(st){kt(st,"stripe_paypal_failed",Oe?.generation)}finally{ce(!1)}},[b,be,e,t,r,g,Ve,_,n,Y,a,s,m,h,kt,X,we,pe,x,f,K]),le=(0,o.useCallback)(async()=>{if(!(Rt.current||d||Ie||!b||!be)){Rt.current=!0,ce(!0);try{if(!await at(!0))return;await Mt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Rt.current=!1,ce(!1)}}},[be,Mt,d,at,b,Ie]),It=f==="redirect"?(0,l.jsx)("button",{type:"button",disabled:d||Ie,onClick:()=>{le()},style:{width:"100%",minHeight:Eo,border:"1px solid #d1d5db",borderRadius:W??8,background:"#ffc439",color:"#111827",cursor:d||Ie?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,l.jsx)(lr.ExpressCheckoutElement,{onReady:xe=>ge(Wa(xe,["paypal"])),onLoadError:()=>{ge("load_error"),Gs(x,"paypal","paypal","provider_error")},onClick:yt,onConfirm:Mt,onCancel:()=>{let xe=j.current.get(K);j.current.delete(K),x?.terminal({outcome:"payment_cancelled",...Vn,terminalReason:"cancelled",...xe?{attempt:xe.generation}:{}}),Pt(xe?.generation),qe(!1),Z.current=!0,Ce()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:mt,emailRequired:mt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},K),Vt=(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{ref:ve,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Se&&(0,l.jsx)("button",{ref:G,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Be,style:Ws,children:"Try PayPal again"}),q&&(0,l.jsx)(da,{identity:q.identity,methodLabel:q.methodLabel,onComplete:We,onCancel:()=>We(null)},q.id),(0,l.jsx)("div",{style:{display:q?"none":void 0},children:It})]}),Ie&&!q&&(0,l.jsx)(rn,{status:"processing"})]});return f==="redirect"?Vt:(0,l.jsx)($a,{state:oe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:W,children:Vt})}function Vs(e){return e==="apple_pay"||e==="google_pay"}var op=200;function ap({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,c.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function $c({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:d,onErrorChange:p,onButtonClick:m,onDecline:w,onTechnicalFailure:h,runBeforeButtonClick:g,billingName:_,onBuyerIdentityReady:V,onLoadStateChange:W,placeholderBorderRadius:k,popupCapabilityOwner:A,externalTelemetryContext:f}){let H=uo(),{emitInstrument:Y}=(0,o.useContext)(Rn),b=(0,lr.useStripe)(),be=(0,lr.useElements)(),x=(0,o.useMemo)(()=>Ai(Er(H),f),[f,H]),[oe,ge]=(0,o.useState)("loading");(0,o.useEffect)(()=>{W?.(oe)},[oe,W]);let[Ie,ce]=(0,o.useState)(!1);(0,o.useEffect)(()=>{qe.current=Ie},[Ie]);let Rt=(0,o.useRef)(!(0,c.isValidEmail)(r?.trim())||!_?.trim()).current,{request:mt,collect:q,finish:Ve}=ca(),We=(0,o.useRef)(null),Ne=(0,o.useRef)(null),[ve,G]=(0,o.useState)(0),[K,Ze]=(0,o.useState)(()=>(0,c.shouldPreferWalletPopup)()),Se=(0,o.useRef)(K),qe=(0,o.useRef)(!1),[Z,j]=(0,o.useState)(!1),[he,X]=(0,o.useState)(()=>qi(e,t)?"blocked":"idle"),[Pt,pe]=(0,o.useState)("google_pay"),we=(0,o.useRef)(null),Ae=(0,o.useRef)(!0),Ce=(0,o.useRef)(!1),kt=(0,o.useRef)("google_pay"),Pe=(0,o.useRef)("google_pay"),Be=(0,o.useRef)(null),at=(0,o.useRef)(null),yt=(0,o.useRef)(new Set),Mt=(0,o.useRef)(null),le=(0,o.useRef)(null);(0,o.useEffect)(()=>(Ae.current=!0,()=>{Ae.current=!1;for(let u of yt.current)window.clearTimeout(u);yt.current.clear()}),[]);let It=(0,o.useRef)(new Map),{startAttempt:Vt,finishAttempt:xe,invalidateAttempt:Oe,isAttemptInvalidated:Ke,isAttemptCurrent:vt,generationRef:it}=Oa((u,F,D)=>{h?.(u,F,{...D,popupBlocked:D?.popupBlocked??(0,_e.isPopupBlockedError)(F),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),pe(u),j(!0),G(L=>L+1)},{onHandoffObserved:u=>{le.current=it.current,A.markAvailable(),x?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:it.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})},defersMissingTerminal:Vs,onMissingTerminalDeferred:(u,F)=>{let D=x?.now()??globalThis.performance?.now()??Date.now(),L=Mt.current,T=L?.generation===F?L.startedAt:D;x?.performance({stage:"overlay_return",durationMs:Math.max(0,D-T),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:F,...Vs(u)?{walletType:u}:{}}),x?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{Z&&Ne.current?.focus()},[Z,ve]);let ft=(0,o.useRef)(0),Lt=(0,o.useRef)(!1),Qe=(0,o.useCallback)(()=>{if(ft.current>0){Lt.current=!0;return}G(u=>u+1)},[]),st=(0,o.useCallback)(()=>{ft.current-=1,!(ft.current>0||!Lt.current)&&(Lt.current=!1,Ae.current&&G(u=>u+1))},[]),de=(0,o.useCallback)((u,F,D,L,T=!1)=>{Oe(L),h?.(u,F,{code:D,popupBlocked:(0,_e.isPopupBlockedError)(F),telemetryReported:T,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),pe(u),j(!0),Qe()},[Oe,h,Qe]),Ot=(0,o.useCallback)(u=>{x?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...Vs(u)?{walletType:u}:{}}),h?.(u,new Error("The wallet click was not ready within the time the wallet allows."),{code:xu,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),pe(u),j(!0)},[h,x]),et=(0,o.useCallback)(()=>{window.setTimeout(()=>{(We.current?.querySelector("iframe")??We.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Ce.current&&(Ce.current=!1,et())},[et,ve]);let re=(0,o.useCallback)(()=>{j(!1),p?.(null),et()},[et,p]),v=(0,o.useCallback)(()=>{we.current?.()},[]);(0,o.useEffect)(()=>{let u=null,F=()=>{u=null;let L=(0,c.shouldPreferWalletPopup)();L!==Se.current&&(Se.current=L,Ze(L),!qe.current&&!vt(it.current)&&Qe())},D=()=>{u!==null&&window.clearTimeout(u),u=window.setTimeout(F,op)};return window.addEventListener("resize",D),()=>{window.removeEventListener("resize",D),u!==null&&window.clearTimeout(u)}},[it,vt,Qe]),(0,o.useEffect)(()=>{let u=qi(e,t);if(!u)return;let F=!1,D=!1,L=async()=>{if(!D){D=!0,F||X("checking");try{let T=await Uc(b,u.clientSecret,yt.current);if(F)return;let I=qs(T,u.providerObjectId,(0,c.isSetupIntentClientSecret)(u.clientSecret));if(I.kind==="confirmed"){if(!Nc(e,t,u.clientSecret))return;we.current=null,X("idle"),d({id:I.paymentMethodId,type:"card",threeDSecureActionResultTokenId:I.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(I.kind==="terminal"){zs(e,t,u.clientSecret),we.current=null,X("idle"),pe(u.paymentMethodType),j(!0),Qe();return}X("blocked")}catch{F||X("blocked")}finally{D=!1}}};return we.current=L,X("blocked"),()=>{F=!0,we.current===L&&(we.current=null)}},[t,d,Qe,e,b]);let Q=(0,o.useCallback)(async u=>{let F=!1,D=!1,L=St=>{F||D||(F=!0,u.paymentFailed({reason:"fail",...St?{message:St}:{}}))};if(!b||!be){L();return}let T=It.current.get(ve);if(T&&!vt(T.generation)){It.current.delete(ve),L();return}if(!T&&Ke()){L();return}if(T&&!xe(T.generation)){L();return}T||(xe(),Lt.current=!1);let I=u.expressPaymentType??T?.method??kt.current,Ct=T??null,Mr=Vc(I),bt;I==="apple_pay"?bt="apple_pay":I==="google_pay"&&(bt="google_pay");let un=T?.generation??it.current,gt=x,vr=gt?.now()??globalThis.performance?.now()??Date.now(),At=new AbortController,Ar=!1,Cr=!1,Xt=null,Jr=e,xr="processing",Ur="other",pn="provider_runtime",Fr,Wt=new Promise((St,lt)=>{Fr=lt}),br=window.setTimeout(()=>{Ar=!0,At.abort(),Fr(Ui)},Fu),Tt=async(St,lt,yn)=>{xr=St,Ur=lt,pn=lt==="intent_create"||lt==="session_claim"?"transport_error":"provider_runtime";let ur=gt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([yn,Wt])}finally{let zr=gt?.now()??globalThis.performance?.now()??Date.now();gt?.performance({stage:St,durationMs:Math.max(0,zr-ur),durationMode:"machine",requestCategory:lt,paymentMethodCategory:"wallet",provider:"stripe",...Ar?{statusClass:"timeout"}:{}})}};try{if(ce(!0),p?.(null),!Ct&&g){let ae=await Tt("processing","other",g(Mr));if(!ae.proceed){L();return}Ct={accountPatch:ae.accountPatch,sessionId:ae.sessionId,nonce:ae.nonce}}let St=Ct?.sessionId??e;Jr=St;let lt=Ct?.nonce??t,yn=Be.current??Ct?.accountPatch,ur=Xc({event:u,fallbackEmail:yn?.email??r,fallbackName:[yn?.firstName,yn?.lastName].join(" ").trim()||_});if(!(0,c.isValidEmail)(ur.email)){L("Buyer details are required."),q($s(I),ur).then(ae=>{ae&&(Be.current=ae)});return}Be.current=null;let zr={...Ct?.accountPatch,...(0,kn.compactBuyerIdentity)(ur,!0)};await Tt("processing","session_claim",Promise.resolve(V?.(ur)));let{error:An}=await Tt("tokenization","provider_sdk",be.submit());if(An){L(),de(I,An,"stripe_wallet_submit_failed",T?.generation);return}if(!St)throw new Error("Missing sessionId or email for payment.");let mn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I,paymentMethodId:null,intentKind:a},qr=JSON.stringify({sessionId:St,nonce:lt??"",request:mn}),fn=at.current,gn=fn?.retryIdentity===qr?fn.authorizationAttemptId:(0,c.randomUuidV4)();at.current={authorizationAttemptId:gn,retryIdentity:qr};let pr=await Tt("processing","intent_create",ji(n,Y,St,lt??"",{...mn,authorizationAttemptId:gn},{signal:At.signal}));if((0,c.isSettledSessionIntent)(pr)){L(),d({type:"card",paymentMethodType:I},{accountPatch:zr,paymentMethodCategory:"wallet",sessionId:St,nonce:lt,settledProcessResponse:pr.response});return}if(pr.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let tr=pr.clientSecret,on=zu({createdAt:Date.now(),sessionId:St,...lt?{nonce:lt}:{},clientSecret:tr,providerObjectId:pr.providerObjectId,paymentMethodType:I,accountPatch:zr});window.clearTimeout(br),Cr=!0,gt?.performance({stage:"callback",durationMs:Math.max(0,(gt?.now()??globalThis.performance?.now()??Date.now())-vr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Zr=gt?.now()??globalThis.performance?.now()??Date.now(),rr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...bt?{walletType:bt}:{},attempt:un},Qt=!1,Sr=null;gt?.log({name:"payment.provider_confirmation.started",...rr}),Xt=window.setTimeout(()=>{Xt!==null&&yt.current.delete(Xt),Qt=!0;let ae=gt?.now()??globalThis.performance?.now()??Date.now();gt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...rr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ae-Zr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),gt?.flush?.().catch(()=>{}),Sr?.()},Bu),yt.current.add(Xt);let jr=(ae,zt)=>{Xt!==null&&(window.clearTimeout(Xt),yt.current.delete(Xt),Xt=null);let Ft=gt?.now()??globalThis.performance?.now()??Date.now(),nr=Math.max(0,Ft-Zr),Xe=ae;Qt&&(ae==="resolved"?Xe="resolved_late":ae==="returned_error"?Xe="returned_error_late":Xe="rejected_late");let mr=zt??(ae==="resolved"?"approved":"provider_error");return gt?.log({name:"payment.provider_confirmation.returned",...rr,operationOutcome:Xe,terminalReason:mr}),gt?.performance({...rr,durationMs:nr,durationMode:"buyer",operationOutcome:Xe,terminalReason:mr}),{durationMs:nr,operationOutcome:Xe,terminalReason:mr}},yr=!1,wr=!1,$r=ae=>{if(!ae||typeof ae!="object")return null;let zt=ae;if(zt.error)return null;let Ft=zt.setupIntent??zt.paymentIntent,nr=qs(Ft??null,void 0,!!zt.setupIntent);return nr.kind==="confirmed"?nr:null},Br=ae=>{if(yr||T&&it.current!==T.generation)return;let zt=$r(ae);if(!zt)return;if(on&&!Nc(St,lt,tr)){yr=!0;return}let{intentId:Ft,paymentMethodId:nr}=zt;yr=!0,wr=!0,at.current=null,we.current=null,Ae.current&&(X("idle"),ce(!1));let Xe=`${Kc}:${St}`;cr(Xe,{createdAt:Date.now(),sessionId:St,nonce:lt,accountPatch:zr,paymentMethodId:nr,providerIntentId:Ft,paymentMethodType:I});try{d({id:nr,type:"card",threeDSecureActionResultTokenId:Ft},{accountPatch:zr,paymentMethodCategory:"wallet",sessionId:St,nonce:lt})}finally{cr(Xe)}},Or=!1;Sr=async()=>{if(!(Or||yr||wr)){Or=!0,Ae.current&&X("checking");try{let ae=await Uc(b,tr,yt.current);if(yr||wr)return;let zt=(0,c.isSetupIntentClientSecret)(tr),Ft=qs(ae,pr.providerObjectId,zt);if(Ft.kind==="confirmed"){Br(zt?{setupIntent:ae}:{paymentIntent:ae});return}if(Ft.kind==="terminal"){if(wr=!0,zs(St,lt,tr),at.current=null,we.current=null,!Ae.current)return;X("idle"),L(),de(I,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",T?.generation,!0);return}Ae.current&&!wr&&(X("blocked"),ce(!1))}catch{Ae.current&&!wr&&(X("blocked"),ce(!1))}finally{Or=!1}}},we.current=Sr;let P,xt;try{D=!0,ft.current+=1;let ae;try{ae=await((0,c.isSetupIntentClientSecret)(tr)?b.confirmSetup({elements:be,clientSecret:tr,redirect:"if_required"}):b.confirmPayment({elements:be,clientSecret:tr,redirect:"if_required"}))}finally{st()}if(!ae||typeof ae!="object")throw new Xa(Uu(ae));if(P=ae,!P.error&&!$r(P))throw new Xa("confirmation_result_unconfirmed");xt=jr(P.error?"returned_error":"resolved",P.error&&(0,_e.isProviderDecline)(P.error)?"provider_declined":void 0)}catch(ae){let zt=ae instanceof Xa?ae.reason:void 0,Ft=zt!==void 0,nr=jr(Ft?"returned_error":"rejected");if(gt?.error({...Ft?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:zt}:Ms(ae),...rr,operationOutcome:nr.operationOutcome,durationMs:nr.durationMs,statusClass:"unknown",terminalReason:nr.terminalReason}),!Ae.current||yr)return;await Sr?.();return}let te=P.error;if(te){if(!Ae.current||yr)return;if((0,_e.isProviderDecline)(te)){wr=!0,zs(St,lt,tr),at.current=null,we.current=null,X("idle"),It.current.get(ve)===T&&It.current.delete(ve);let ae=te.message??"Your payment was declined.";p?.(ae),w?.(kr(Mr,ae,{code:(0,_e.getProviderErrorCode)(te),declineCode:(0,_e.getProviderDeclineCode)(te)})),Vi({billingApiUrl:n,sessionId:St,nonce:lt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I,providerDeclineReason:(0,_e.getProviderErrorCode)(te)??"provider_declined",...pr.intentKind==="payment"&&pr.providerObjectId.startsWith("pi_")?{providerIntentId:pr.providerObjectId}:{}}})}else gt?.error({...Ms(te),...rr,operationOutcome:xt.operationOutcome,durationMs:xt.durationMs,statusClass:"unknown",terminalReason:xt.terminalReason}),await Sr?.();return}if(Br(P),!yr)throw new Error("Invalid provider returned for APM intent")}catch(St){if(St===Ui){let lt=gt?.now()??globalThis.performance?.now()??Date.now();gt?.error({errorCode:ju(Ur),stage:xr,requestCategory:Ur,paymentMethodCategory:"wallet",provider:"stripe",...bt?{walletType:bt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Jr,durationMs:Math.max(0,lt-vr),statusClass:"timeout",failureCategory:pn,attempt:un,terminalReason:"provider_error"}),gt?.flush?.().catch(()=>{})}L(),de(I,St,St===Ui?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",T?.generation,St===Ui)}finally{if(window.clearTimeout(br),Xt!==null&&(window.clearTimeout(Xt),yt.current.delete(Xt)),!Cr){let St=gt?.now()??globalThis.performance?.now()??Date.now();gt?.performance({stage:"callback",durationMs:Math.max(0,St-vr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Ar?{statusClass:"timeout"}:{}})}Ae.current&&ce(!1)}},[b,be,e,t,r,_,q,V,n,Y,a,d,p,w,g,de,st,xe,vt,Ke,it,x,ve]),ee=(0,o.useMemo)(()=>Fi(s),[s]),$=(0,o.useMemo)(()=>s.map(c.stripeExpressMethodToOptionKey),[s]),nt=(0,o.useMemo)(()=>(0,l.jsx)(lr.ExpressCheckoutElement,{onReady:u=>{ge(Wa(u,$))},onLoadError:u=>{ge("load_error"),Gs(x,"stripe","wallet","provider_error")},onClick:async u=>{let F=x?.now()??globalThis.performance?.now()??Date.now();kt.current=u.expressPaymentType,Pe.current=Vc(u.expressPaymentType);let D=!0,L=window.setTimeout(()=>{D=!1,u.reject(),Ot(u.expressPaymentType)},Au),T=g?await g(Pe.current,{abandoned:()=>!D}):{proceed:!0};if(window.clearTimeout(L),!D)return;if(!T.proceed){It.current.delete(ve),u.reject();return}let I=Vt(u.expressPaymentType);Lt.current=!1,Mt.current={generation:I,startedAt:F},It.current.set(ve,{generation:I,method:u.expressPaymentType,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),j(!1),x?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:I,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),m?.(Pe.current),u.resolve()},onConfirm:Q,onCancel:()=>{let u=It.current.get(ve);It.current.delete(ve);let F=Mt.current,D=x?.now()??globalThis.performance?.now()??Date.now();if(u&&F?.generation===u.generation&&(0,c.isWalletSheetRefusedForWindowSize)({method:u.method,elapsedMs:D-F.startedAt,handoffObserved:le.current===u.generation})){x?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:u.generation,walletType:"google_pay"}),at.current=null,de(u.method,new Error("The browser window is too small for the Google Pay sheet."),c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,u.generation,!0);return}x?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),Oe(u?.generation),at.current=null,j(!1),Ce.current=!0,Qe()},options:{...Bi,paymentMethods:ee,emailRequired:Rt,billingAddressRequired:Rt}},ve),[$,ee,Q,Oe,m,Rt,de,Ot,Qe,g,Vt,ve,x]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)($a,{state:oe,placeholderTestId:"flopay-wallet-placeholder",borderRadius:k,children:(0,l.jsxs)("div",{ref:We,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Z&&(0,l.jsxs)("button",{ref:Ne,type:"button","data-testid":"flopay-wallet-retry-button",onClick:re,style:Ws,children:["Try ",$s(Pt)," again"]}),he!=="idle"&&(0,l.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,l.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,l.jsx)("button",{type:"button",onClick:v,disabled:he==="checking",style:Ws,children:he==="checking"?"Checking payment status\u2026":"Check payment status"})]}),mt&&(0,l.jsx)(da,{identity:mt.identity,methodLabel:mt.methodLabel,onComplete:Ve,onCancel:()=>Ve(null)},mt.id),(0,l.jsxs)("div",{style:{display:mt||he!=="idle"?"none":void 0},children:[(0,l.jsx)(ap,{active:K}),nt]})]})}),Ie&&(0,l.jsx)(rn,{status:"processing"})]})}function Jc(e,t,r){let n=(0,c.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function Hs({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:d,onTokenizedBody:p,onErrorChange:m,onDecline:w,onCancel:h,runBeforeButtonClick:g,onButtonClick:_,isProcessing:V,submitButtonColor:W,submitButtonBorderRadius:k,submitButtonStyle:A,errorText:f}){let H=uo(),{emitInstrument:Y}=(0,o.useContext)(Rn),b=(0,lr.useStripe)(),be=(0,lr.useElements)(),[x,oe]=(0,o.useState)(!1),ge=(0,o.useRef)(!1),[Ie,ce]=(0,o.useState)(!1),[Rt,mt]=(0,o.useState)("loading"),[q,Ve]=(0,o.useState)(""),We=!(0,c.isValidEmail)(n?.trim()),Ne=!We||(0,c.isValidEmail)(q.trim()),ve=(0,o.useCallback)(async()=>{if(!b||!be||V||ge.current||!Ie)return;ge.current=!0,oe(!0);let G=g?await g("card"):{proceed:!0};if(!G.proceed){ge.current=!1,oe(!1);return}_?.("card");let K=G.sessionId??t,Ze=G.nonce??r,Se=(0,la.splitFullName)(a?.trim()),qe=(0,kn.compactBuyerIdentity)({email:G.accountPatch?.email?.trim()||n?.trim()||q.trim(),firstName:G.accountPatch?.firstName?.trim()||Se.firstName,lastName:G.accountPatch?.lastName?.trim()||Se.lastName}),Z=qe.email,j=(0,kn.compactBuyerIdentity)({...G.accountPatch,...qe});try{if(m?.(null),!(0,c.isValidEmail)(Z))throw new Error("A valid email address is required for payment.");await s?.(qe);let he=await be.submit();if(he.error){m?.(he.error.message??"Payment failed.");return}let X=[qe.firstName,qe.lastName].filter(Boolean).join(" "),Pt=await b.createPaymentMethod({elements:be,params:{billing_details:{email:Z,...X?{name:X}:{}}}});if(Pt.error||!Pt.paymentMethod){m?.(Pt.error?.message??"Failed to create payment method.");return}let pe=Pt.paymentMethod;if(!K||!Z)throw new Error("Missing sessionId or email for payment.");let we=pe.type||e,Ae=await ji(d,Y,K,Ze??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:we,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(Ae)){p({type:"card",gateway:"stripe",paymentMethodType:we},{accountPatch:j,paymentMethodCategory:"apm",sessionId:K,nonce:Ze,settledProcessResponse:Ae.response});return}if(Ae.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ce=Ae.clientSecret;cr(eo,{clientSecret:Ce,sessionId:K,nonce:Ze,accountPatch:j,paymentMethodId:pe.id,paymentMethodType:pe.type??e,gateway:"stripe"});let{error:kt,paymentIntent:Pe}=await b.confirmPayment({clientSecret:Ce,confirmParams:{return_url:window.location.href,payment_method:pe.id},redirect:"if_required"});if(kt){cr(eo);let yt=kt.message??"Payment failed.";m?.(yt),w?.(kr("card",yt,{code:kt.code})),await Vi({billingApiUrl:d,sessionId:K,nonce:Ze,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:kt.code??"provider_declined"}});return}let Be=Pe?.status;if(!Aa(Be)){cr(eo);let yt=Be==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(yt),w?.(kr("card",yt,{code:Be??"missing_payment_intent"}));return}cr(eo);let at=typeof Pe?.payment_method=="string"?Pe.payment_method:Pe?.payment_method?.id;p({id:at??pe.id,type:"card",threeDSecureActionResultTokenId:Pe?.id,gateway:"stripe",paymentMethodType:pe.type??e},{accountPatch:j,paymentMethodCategory:"apm",sessionId:K,nonce:Ze})}catch(he){m?.(he instanceof Error?he.message:"Payment failed. Please try again.")}finally{ge.current=!1,oe(!1)}},[b,be,V,Ie,g,_,t,r,n,a,q,s,d,Y,e,p,m,w]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[We&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:We&&(0,l.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,l.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:q,onChange:G=>Ve(G.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(lr.PaymentElement,{onReady:()=>mt("ready"),onLoadError:()=>{mt("load_error"),Gs(Er(H),"stripe","apm")},onChange:G=>{ce(!!G.complete)},options:{layout:Oi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,c.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,l.jsx)(Di,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ve()},disabled:!Ie||!Ne||x||V||Rt!=="ready",color:W,borderRadius:k,style:A,children:x?"Processing\u2026":`Pay with ${(0,c.getStripeMethodDisplayName)(e)}`}),f&&(0,l.jsx)(ya,{margin:"0.75rem 0 0",children:f})]})}function Hc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:d,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:w,onTokenizedBody:h,onErrorChange:g,onButtonClick:_,onDecline:V,runBeforeButtonClick:W,onLoadStateChange:k,isProcessing:A=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:H=8,submitButtonStyle:Y,buttonAppearance:b,themeId:be,onExpandApm:x,expandedApmMethod:oe}){let{emitInstrument:ge}=(0,o.useContext)(Rn),[Ie,ce]=(0,o.useState)(null),[Rt,mt]=(0,o.useState)(null),q=(0,o.useRef)(!1),{request:Ve,collect:We,finish:Ne}=ca();(0,o.useEffect)(()=>{d.length>0&&p?k?.("ready"):p||k?.("loading")},[d.length,p,k]);let ve=(0,o.useCallback)(async Z=>{if(!p||q.current||A)return;q.current=!0,mt(Z);let j=W?await W("card"):{proceed:!0};if(!j.proceed){q.current=!1,mt(null);return}_?.("card");let he=j.sessionId??e,X=j.nonce??t,Pt=(0,la.splitFullName)([j.accountPatch?.firstName,j.accountPatch?.lastName].filter(Boolean).join(" ")||n),pe=(0,kn.compactBuyerIdentity)({email:j.accountPatch?.email?.trim()||r?.trim(),firstName:j.accountPatch?.firstName?.trim()||Pt.firstName,lastName:j.accountPatch?.lastName?.trim()||Pt.lastName});if(!(0,c.isValidEmail)(pe.email)){mt(null);let Ce=await We((0,c.getStripeMethodDisplayName)(Z),pe);if(!Ce){q.current=!1;return}pe=Ce,mt(Z)}let we=pe.email,Ae=(0,kn.compactBuyerIdentity)({...j.accountPatch,...pe});try{if(g?.(null),!he||!(0,c.isValidEmail)(we))throw new Error("Missing sessionId or email for payment.");await a?.(pe);let Ce=await ji(s,ge,he,X??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(Ce)){h({type:"card",gateway:"stripe",paymentMethodType:Z},{accountPatch:Ae,paymentMethodCategory:"apm",sessionId:he,nonce:X,settledProcessResponse:Ce.response});return}if(Ce.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let kt=Ce.clientSecret;cr(eo,{clientSecret:kt,sessionId:he,nonce:X,accountPatch:Ae,paymentMethodType:Z,gateway:"stripe"});let{error:Pe,paymentIntent:Be}=await p.confirmPayment({clientSecret:kt,confirmParams:{return_url:window.location.href,payment_method_data:{type:Z,billing_details:{name:[pe.firstName,pe.lastName].filter(Boolean).join(" "),...we?{email:we}:{}}}},redirect:"if_required"});if(Pe){cr(eo);let Mt=Pe.message??"Payment failed.";g?.(Mt),V?.(kr("card",Mt,{code:Pe.code})),await Vi({billingApiUrl:s,sessionId:he,nonce:X,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,providerDeclineReason:Pe.code??"provider_declined"}});return}let at=Be?.status;if(!Aa(at)){cr(eo);let Mt=at==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(Mt),V?.(kr("card",Mt,{code:at??"missing_payment_intent"}));return}cr(eo);let yt=typeof Be?.payment_method=="string"?Be.payment_method:Be?.payment_method?.id;h({id:yt??Be?.id,type:"card",threeDSecureActionResultTokenId:Be?.id,gateway:"stripe",paymentMethodType:Z},{accountPatch:Ae,paymentMethodCategory:"apm",sessionId:he,nonce:X})}catch(Ce){g?.(Ce instanceof Error?Ce.message:"Payment failed. Please try again.")}finally{q.current=!1,mt(null)}},[p,A,W,_,e,t,r,We,s,ge,n,a,h,g,V]),[G,K]=(0,o.useState)(null),Ze=x?oe??null:G,Se=(0,o.useCallback)(Z=>{q.current||A||Ze&&Ze!==Z||((0,c.needsStripeMethodExplicitConfirm)(Z)?x?x(Z):K(Z):ve(Z))},[Ze,A,ve,x]),qe=(0,o.useMemo)(()=>G?Jc(m,G,w):null,[G,m,w]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ve?(0,l.jsx)(da,{identity:Ve.identity,methodLabel:Ve.methodLabel,onComplete:Ne,onCancel:()=>Ne(null)},Ve.id):d.map(Z=>{let j=oe===Z,he=Rt===Z,X=Rt!==null&&Rt!==Z||oe!=null&&oe!==Z;return(0,l.jsxs)(o.default.Fragment,{children:[(0,l.jsx)(xi,{method:Z,themeId:be,submitting:he,disabled:X,highlighted:j,hasNextStep:(0,c.needsStripeMethodExplicitConfirm)(Z),onClick:()=>Se(Z),backgroundColor:b?.backgroundColor,borderColor:b?.borderColor,textColor:b?.textColor,borderRadius:b?.borderRadius,fontFamily:b?.fontFamily}),!x&&G===Z&&qe&&p&&(0,l.jsx)(lr.Elements,{stripe:p,options:qe,children:(0,l.jsx)(Hs,{method:Z,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:h,onErrorChange:g,onDecline:V,onCancel:()=>K(null),runBeforeButtonClick:W,onButtonClick:_,isProcessing:A,submitButtonColor:f,submitButtonBorderRadius:H,submitButtonStyle:Y})},Z)]},Z)})})}function ip({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:d,onError:p,onDecline:m,onCancel:w,onTokenizedBody:h,firstName:g,lastName:_,chv:V,className:W,submitLabel:k,isProcessing:A,error:f,onErrorChange:H,showPayPal:Y=!0,showStripe:b=!0,walletPresentation:be="auto",enabledPaymentMethods:x,enabledPaymentMethodCountries:oe,showApplePay:ge=!0,showGooglePay:Ie=!0,layout:ce="default",paymentMethodLayout:Rt,moreOptionsLabel:mt,theme:q,buttonsTheme:Ve,buttonsStyles:We,appearance:Ne,cardButtonContent:ve,cardBackButtonContent:G,cardTitleContent:K,showSecurityFooter:Ze,onButtonClick:Se,onBeforeButtonClick:qe,onBuyerIdentityReady:Z,enableAVS:j,cardFieldOrder:he,showCardBrandIcons:X,cardFieldPlaceholders:Pt,cardAutoFocus:pe,onCardFieldsReady:we,onCardFieldsFailed:Ae,cardFieldsTimeoutMs:Ce,cardPreFormSlot:kt,avsLayout:Pe="row",country:Be,zip:at,addressLine1:yt,addressLine2:Mt,city:le,state:It,onCountryChange:Vt,onZipChange:xe,avsCheck:Oe,checkoutType:Ke,checkoutLayout:vt,totalAmount:it=0,currency:ft="usd",initialCardOpen:Lt=!1,directPaypal:Qe,isSubscription:st=!1,session:de,dataAttachmentPending:Ot=!1,dataAttachmentRequiresIdentity:et=!1,debug:re=!1}){let v=uo(),Q=vi(),ee=(0,o.useContext)(zn),{emitInstrument:$}=(0,o.useContext)(Rn),nt=(0,o.useRef)(null);nt.current||(nt.current=bi());let u=nt.current,[,F]=(0,o.useState)(0),D=(0,o.useRef)(null);D.current||(D.current=(0,Jn.detectPayPalEnvironment)());let L=D.current,T=(0,o.useMemo)(()=>({browser:L,capability:u,presentationMode:"popup"}),[L,u]),I=de??ee.session,Ct=(0,o.useMemo)(()=>({futureUse:I?.futureUse,futureUseUnsupported:I?.futureUseUnsupported}),[I?.futureUse,I?.futureUseUnsupported]),Mr=I?.gateways?.paypal?.providerObjectType??Qe?.providerObjectType,bt=Ot||ee.claimPending===!0,un=et||ee.claimRequiresIdentity===!0,gt=bt&&!un,vr=pc(),At=r||vr,Ar=Oc({rules:Rt,sessionId:e,nonce:t,billingApiUrl:At,waitForSession:gt}),Cr=Ar?.order??null,[Xt,Jr]=(0,o.useState)(!1),xr=(0,o.useMemo)(()=>Cr?(0,c.keyPaymentMethodOrder)(Cr):null,[Cr]),Ur=Cr!==null&&(0,c.isCardFormFirst)(Cr),[pn,Fr]=(0,o.useState)(!1),[Wt,br]=(0,o.useState)(null),[Tt,St]=(0,o.useState)(Be??""),[lt,yn]=(0,o.useState)(at??""),[ur,zr]=(0,o.useState)(yt??""),[An,mn]=(0,o.useState)(Mt??""),[qr,fn]=(0,o.useState)(le??""),[gn,pr]=(0,o.useState)(It??""),[tr,on]=(0,o.useState)(""),[Zr,rr]=(0,o.useState)({}),Qt=(0,o.useRef)(at??""),Sr=(0,o.useRef)(Be??""),jr=(0,o.useRef)(yt??""),yr=(0,o.useRef)(Mt??""),wr=(0,o.useRef)(le??""),$r=(0,o.useRef)(It??""),Br=(0,o.useRef)(""),Or=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(S,N,fe,J,Le)=>{if(Or.current[S])return;let qt=N?.trim();!qt||qt===fe.current||(fe.current=qt,J(qt),Le?.(qt))};i("country",Be,Sr,St,Vt),i("zip",at,Qt,yn,xe),i("addressLine1",yt,jr,zr),i("addressLine2",Mt,yr,mn),i("city",le,wr,fn),i("state",It,$r,pr)},[Be,at,yt,Mt,le,It,Vt,xe]);let P=(0,o.useMemo)(()=>(0,c.resolveAVSConfig)(j),[j]),xt=P!==null,te=(0,o.useMemo)(()=>(0,c.isAuthorizationOnlySession)(de),[de]),ae=(0,c.isMountableVaultBlock)(de?.vault),zt=!!de?.gateways?.pcivault,Ft=(0,Un.hasServerSideCardGateway)(de),Xe=!!(de?.gateways?.stripe?.enabledPaymentMethods??x)?.includes("card")||(0,Un.canRecoverHostedCardForm)(de),mr=ae||Xe||zt,Je=!!(b&&mr&&e),[no,go]=(0,o.useState)(()=>ce!=="buttons"||Lt?e??null:null),[jo,xn]=(0,o.useState)(0),hn=ce!=="buttons"||Lt||!!e&&no===e,an=de?.captureMethod,Qr=(0,o.useRef)(v);(0,o.useEffect)(()=>{Qr.current=v},[v]);let or=(0,o.useRef)(Ce);or.current=Ce;let Fn=(0,o.useRef)({onCardFieldsReady:we,onCardFieldsFailed:Ae,emitInstrument:$});Fn.current={onCardFieldsReady:we,onCardFieldsFailed:Ae,emitInstrument:$};let[Rr,$n]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!Je||!e||!hn){$n(null);return}let i=Qr.current?Qr.current.cardCapture({sessionId:e,captureMethod:an,cardFieldsTimeoutMs:or.current}):new Wn.PciVaultCardCapture({sessionId:e,captureMethod:an,billingApiUrl:At,telemetry:n,cardFieldsTimeoutMs:or.current}),S=i.onCardFields?.(N=>{let fe=Fn.current;fe.emitInstrument?.((0,c.cardFieldsInstrumentSource)(N)),N.type==="card_fields_ready"?(0,c.invokeMerchantCallback)(()=>fe.onCardFieldsReady?.(N)):(0,c.invokeMerchantCallback)(()=>fe.onCardFieldsFailed?.(N))});return $n({sessionId:e,captureMethod:an,billingApiUrl:At,telemetry:n,capture:i}),()=>{S?.(),i.unmount()}},[Je,e,hn,an,At,n]);let ht=Je&&e&&hn&&Rr?.sessionId===e&&Rr.captureMethod===an&&Rr.billingApiUrl===At&&Rr.telemetry===n?Rr.capture:null,Vr=(0,o.useMemo)(()=>{let i=Tt,S=P?(0,c.isAVSFieldVisible)(P.postal_code,i):!1;return Qu(i,lt,S)},[P,Tt,lt]),{avsInvalid:Bn,invalidAvsFields:oo}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Je||!P)return{avsInvalid:!1,invalidAvsFields:i};let S=Tt,N=(Le,qt)=>(0,c.isAVSFieldVisible)(Le,S)&&!qt.trim(),fe={line1:N(P.address_line_1,ur),city:N(P.city,qr),state:N(P.state,gn),zip:Vr.empty||Vr.malformed};return{avsInvalid:fe.line1||fe.city||fe.state||fe.zip,invalidAvsFields:fe}},[Je,P,Tt,ur,qr,gn,Vr]),[sn,Pn]=(0,o.useState)(!1),[ho,Po]=(0,o.useState)(!1),[vn,ao]=(0,o.useState)(!1),[Vo,va]=(0,o.useState)({line1:!1,city:!1,state:!1}),Cn=(0,o.useRef)(!1),Hn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),vo=(0,o.useRef)(!1),Nt=(0,o.useCallback)(i=>{Hn.current[i]=!0,vo.current=!0},[]),Kn=(0,o.useCallback)(i=>!Cn.current&&Hn.current[i],[]),bn=(0,o.useCallback)(i=>{Kn(i)&&va(S=>S[i]?S:{...S,[i]:!0})},[Kn]),[On,Hr]=(0,o.useState)(()=>(0,c.resolveVaultMountOptions)(de?.vault,{billingApiUrl:At,sessionId:e,nonce:t})),[ct,ar]=(0,o.useState)(Lt&&mr?"card":"buttons"),[Kt,B]=(0,o.useState)(null),U=ct==="expanding"||ct==="card",ne=de?.gateways?.stripe&&!Ft?"stripe":void 0,me=(0,o.useCallback)(()=>{$?.({class:"card_surface",provider:ne})},[ne,$]),Ut=(0,o.useCallback)(()=>{Jr(!0),$?.({class:"more_options"})},[$]),Jt=(0,o.useRef)(null),Fe=(0,o.useCallback)(i=>{Jt.current&&clearTimeout(Jt.current),Jt.current=setTimeout(()=>{Jt.current=null,i()},Ja)},[]);(0,o.useEffect)(()=>()=>{Jt.current&&clearTimeout(Jt.current)},[]);let dt=(0,o.useRef)(!1),[z,Ge]=(0,o.useState)(0),Re=(0,o.useRef)(null),C=(0,o.useCallback)(()=>{me(),go(e??null),dt.current&&(dt.current=!1,Ge(i=>i+1)),xn(i=>i+1),ar("expanding"),Fe(()=>ar("card"))},[Fe,me,e]),y=(0,o.useCallback)(()=>{ar("collapsing"),Fe(()=>ar("buttons"))},[Fe]),M=(0,o.useCallback)(i=>{B(i),ar("apm-expanding"),Fe(()=>ar("apm-form"))},[Fe]),ke=(0,o.useCallback)(()=>{ar("apm-collapsing"),Fe(()=>{ar("buttons"),B(null)})},[Fe]);(0,o.useEffect)(()=>{ce==="buttons"&&Lt&&mr&&(go(e??null),ar("card"))},[ce,Lt,mr,e]);let[Te,ie]=(0,o.useState)(null),Me=(0,o.useRef)(null),[Ee,$t]=(0,o.useState)(0);(0,o.useEffect)(()=>{Ee!==0&&Me.current?.focus()},[Ee]);let Ht=(0,o.useRef)(!1),ut=(0,o.useRef)(null),ue=(0,o.useRef)("idle"),[ye,$e]=(0,o.useState)(!1),tt=(0,o.useRef)(ye);tt.current=ye;let[De,en]=(0,o.useState)(()=>Qe?.existingOrderId?{orderId:Qe.existingOrderId,attempts:1}:null),Yt=(0,o.useRef)(De);(0,o.useEffect)(()=>{Yt.current=De},[De]);let Wo=(0,o.useRef)(null),bd=(0,o.useMemo)(()=>{if(Z||ee.claimBuyerIdentity||de?.buyerIdentified!==!1||!e||!t)return;let i=`${At}|${e}|${t}`;Wo.current?.key!==i&&(Wo.current={key:i,claim:ia(new Wn.PaymentAPI(At,{telemetry:!1}),e,t,{...s?{userId:s}:{},...g?{firstName:g}:{},..._?{lastName:_}:{}})});let S=Wo.current.claim;return async N=>{await S(N)}},[Z,ee.claimBuyerIdentity,de?.buyerIdentified,e,t,At,s,g,_]),Sn=Z??ee.claimBuyerIdentity??bd,Dn=f??Wt,$o=(0,o.useMemo)(()=>(0,c.resolveTheme)(q),[q]),rt=(0,o.useMemo)(()=>{let i=$o?.buttonsLayout??(0,c.resolveButtonsLayoutTheme)(Ve);return We?{...i,...We,cardButton:{...i.cardButton,...We.cardButton},cardFormContainer:{...i.cardFormContainer,...We.cardFormContainer},backButton:{...i.backButton,...We.backButton},backButtonIcon:{...i.backButtonIcon,...We.backButtonIcon},submitButton:{...i.submitButton,...We.submitButton},title:{...i.title,...We.title}}:i},[$o,Ve,We]),Ho=Ne??$o?.appearance,Sd=(0,o.useMemo)(()=>(0,c.computeVaultCardThemeColors)({appearance:Ho,buttonsStyles:rt,layout:ce}),[Ho,rt,ce]),wd=ee.inlineSessionPatchProcessing??!1,ir=(A??pn)||wd,Co=At.replace(/\/+$/,""),Bt=(0,o.useMemo)(()=>Ts({userId:s,email:a,firstName:g,lastName:_,country:Be,zip:at},Zr),[s,a,g,_,Be,at,Zr]),Ko=[Bt.firstName,Bt.lastName].filter(i=>!!i?.trim()).join(" "),ll=!(0,c.isValidEmail)(Bt.email?.trim()),Qi=(0,o.useRef)(null);Je&&Qi.current===null&&(Qi.current=ll);let bo=Je&&(Qi.current??ll),es=(0,o.useMemo)(()=>ep(tr,bo),[tr,bo]),Go=es.empty||es.malformed,ln=(0,o.useMemo)(()=>v?v.getRawProvider():null,[v]),cl=(0,o.useMemo)(()=>Q?Q.getRawProvider():null,[Q]),Ca=it||100,Yo=ft.toLowerCase(),ts=(0,o.useMemo)(()=>Ho?(0,Wn.toStripeAppearance)(Ho):null,[Ho]),Xo=ts,dl=(0,o.useMemo)(()=>{let i=ts??{},S=i.rules??{};return{...i,rules:{...S,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...S[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...S[".AccordionItemContents"]??{}}}}},[ts]),ul=(0,o.useMemo)(()=>({...cc(it,I?.captureMethod,Ct),currency:Yo,...Xo?{appearance:Xo}:null}),[it,Yo,I?.captureMethod,Ct,Xo]),rs=(0,c.resolveSetupFutureUsage)(Ct,"paypal","paypal"),pl=(0,o.useMemo)(()=>({mode:"payment",amount:Ca,currency:Yo,captureMethod:"manual",...rs?{setupFutureUsage:rs}:null,...Xo?{appearance:Xo}:null}),[Ca,Yo,rs,Xo]),Ue=(0,o.useCallback)(i=>{br(i),H?.(i)},[H]),yl=(0,o.useRef)(0);(0,o.useEffect)(()=>{z!==yl.current&&(yl.current=z,Ue(null))},[z,Ue]);let ns=(0,o.useRef)(""),[ml,Rd]=(0,o.useState)(!1),os=(0,o.useCallback)(()=>{Rd(!0)},[]);(0,o.useEffect)(()=>{if(!Je||!bo||!Sn||!ml||Go||ns.current)return;let i=(0,kn.compactBuyerIdentity)({email:(0,c.isValidEmail)(Bt.email?.trim())?Bt.email?.trim():Br.current.trim(),firstName:Bt.firstName?.trim(),lastName:Bt.lastName?.trim()});ns.current=JSON.stringify(i),rr(S=>({...S,...i})),Promise.resolve(Sn(i)).catch(S=>{ns.current="",Ue(S instanceof Error?S.message:"Failed to attach buyer details.")})},[Je,bo,Sn,ml,Go,Bt.email,Bt.firstName,Bt.lastName,Ue]),(0,o.useEffect)(()=>{if(!Je||!ht)return;let i=pe!==!1&&P==null&&!bo;ht.setCardFieldOrder?.(he??null,i)},[Je,ht,he,pe,P,bo]),(0,o.useEffect)(()=>{!Je||!ht||ht.setCardBrandIcons?.(X===!0)},[Je,ht,X]);let as=np(Pt),is=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(!(!Je||!ht)){if(as===null){if(is.current!==ht)return;is.current=null,ht.setCardFieldPlaceholders?.(void 0);return}is.current=ht,ht.setCardFieldPlaceholders?.(JSON.parse(as))}},[Je,ht,as]),(0,o.useEffect)(()=>{(ct==="expanding"||ct==="collapsing"||ct==="apm-expanding"||ct==="apm-collapsing")&&Ue(null)},[ct,Ue]);let Gn=(0,o.useCallback)((i,S,N)=>{m?.(kr(i,S,N))},[m]),fl=(0,o.useRef)(ct);fl.current=ct;let[gl]=(0,o.useState)(wi),hl=(0,o.useCallback)(()=>{let i=fl.current;if(ce==="buttons"&&(i==="card"||i==="expanding"))return!0;let S=ue.current;return S==="validation-window"||S==="processing"||tt.current},[ce]),Pl=(0,o.useCallback)((i,S,N)=>{gl.take(e)&&Er(v)?.log(Do({...T,presentationMode:N?.presentationMode??"popup"},{name:Si,stage:"recovery",reason:"other_method_active",provider:N?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:N?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[T,v,gl,e]),ri=(0,o.useCallback)((i,S,N)=>{N?.telemetryReported||Er(v)?.error(Do({...T,presentationMode:N?.presentationMode??"popup"},{errorCode:S?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:N?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:N?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:N?.terminalReason??(S?"popup_blocked":"provider_error")}))},[T,v]),Jo=(0,o.useCallback)((i,S,N)=>{let fe=N?.popupBlocked??(0,_e.isPopupBlockedError)(S);if(hl()){ri(i,fe,N),Pl(i,S,N);return}if(S instanceof c.FloPayError&&S.code==="checkout_processing_timeout"){ri(i,!1,N),ie(null),ce==="buttons"&&(ar("buttons"),B(null)),Ue(S.message),p?.(S);return}fe&&u.markBlocked()&&F(Et=>Et+1);let J=$s(i),Le=N?.code===c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,c.buildWalletSheetWindowMessage)(J):(0,_e.buildExternalMethodRecoveryMessage)(J,fe,L.inAppBrowser),qt=(0,_e.getProviderErrorCode)(S),jt=(qt?.toLowerCase()==="error"?void 0:qt)??(0,_e.sanitizeExternalFailureCode)(N?.code)??"external_payment_method_failed",ot=new c.FloPayError(Le,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:jt,popupBlocked:fe,inAppBrowser:L.inAppBrowser,appFamily:L.appFamily,popupCapability:u.current(),presentationMode:N?.presentationMode??"popup"}});ri(i,fe,N),ie(null),ce==="buttons"&&(ar("buttons"),B(null)),Ue(Le),p?.(ot),console.error("[FloPay] External payment method failed:",{method:i,code:jt,popupBlocked:fe})},[L,hl,ce,p,u,Pl,ri,Ue]);(0,o.useEffect)(()=>{if(!Je||!e){Hr(null);return}let i={billingApiUrl:Co,sessionId:e,nonce:t},S=(0,c.resolveVaultMountOptions)(de?.vault,i);if(S){Hr(S);return}if(!hn){Hr(null);return}let N=`${Co}\0${e}\0${t??""}`,fe=Re.current;if(fe&&fe.key===N){Hr(fe.mount);return}Hr(null);let J=!0;return new Wn.PaymentAPI(Co).getVaultCapture(e,t).then(Le=>{if(!J)return;let qt=(0,c.resolveVaultMountOptions)(Le,i);qt?.verificationRequired&&!Le.html&&(Re.current={key:N,mount:qt}),qt?Hr(qt):Ue("Failed to load the secure card form.")}).catch(Le=>{J&&Ue(Le instanceof Error?Le.message:"Failed to load the secure card form.")}),()=>{J=!1}},[Je,hn,jo,e,de?.vault,Co,t,Ue]);let Ln=(0,o.useRef)({onComplete:d,onError:p,updateError:Ue,emitDecline:Gn,resolvedAccount:Bt,avsConfig:P,avsCheckProp:Oe,sessionId:e,nonce:t,baseUrl:Co,captureMethod:de?.captureMethod,paymentId:de?.paymentId,authorizationExpiresAt:de?.authorizationExpiresAt,serverSideCardGateway:Ft});Ln.current={onComplete:d,onError:p,updateError:Ue,emitDecline:Gn,resolvedAccount:Bt,avsConfig:P,avsCheckProp:Oe,sessionId:e,nonce:t,baseUrl:Co,captureMethod:de?.captureMethod,paymentId:de?.paymentId,authorizationExpiresAt:de?.authorizationExpiresAt,serverSideCardGateway:Ft};let ss=(0,o.useRef)(!1),vl=(0,o.useCallback)(()=>{let i=Ln.current,S=i.resolvedAccount.email?.trim(),N=(0,c.isValidEmail)(S)?S:Br.current.trim();if(!(0,c.isValidEmail)(N))return null;let fe=i.resolvedAccount.firstName?.trim(),J=i.resolvedAccount.lastName?.trim(),Le=Sr.current.trim()||i.resolvedAccount.country?.trim()||"",qt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.state,Le):!1,jt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_1,Le):!1,ot=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.postal_code,Le):!1,Et=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.city,Le):!1,Dt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_2,Le):!1,fr=jt&&!qt&&ot?(0,c.getStateFromPostalCode)(Le,(Qt.current??"").trim()):null,cn=qt?$r.current:fr;return{accountData:{userId:i.resolvedAccount.userId??"",email:N,...fe?{firstName:fe}:{},...J?{lastName:J}:{},...ot&&Qt.current?{zip:Qt.current}:{},...Et&&wr.current?{city:wr.current}:{},...cn?{state:cn}:{},...jt&&jr.current?{addressLine1:jr.current}:{},...Dt&&yr.current?{addressLine2:yr.current}:{},...Le?{country:Le}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,c.isAVSFieldVisible)(i.avsConfig.country,Le),postal_code:ot,address_line_1:jt,address_line_2:Dt,city:Et,state:qt}}:{}}},[]),Cl=(0,o.useRef)(bt);Cl.current=bt,(0,o.useEffect)(()=>{bt||Dn!==zc||Ln.current.updateError(null)},[bt,Dn]),(0,o.useEffect)(()=>{!Je||!ht||ht.setSubmitGate?.(Bn||bt||Go||ye)},[Je,ht,Bn,bt,Go,ye]),(0,o.useEffect)(()=>{if(!Je||!ht)return;ss.current=!1;let i=null,S=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,ue.current="idle",ie(null)},400)},N=ht.on("submitting",()=>{Pn(!0),ut.current&&clearTimeout(ut.current),ue.current="validation-window",ut.current=setTimeout(()=>{ut.current=null,ue.current==="validation-window"&&(ue.current="processing")},Vu),ie("processing");let ot=Ln.current;if(!ot.sessionId||!ot.nonce)return;let Et=vl();if(!Et){ot.updateError("Enter a valid email address."),ue.current="idle",ie(null);return}new Wn.PaymentAPI(ot.baseUrl).patchAccountSnapshot(ot.sessionId,ot.nonce,Et,{telemetryMode:"best_effort"}).catch(Dt=>{if(!$u(Dt))return;let fr=Dt instanceof Error?Dt.message:"Please check your billing address and try again.";ot.updateError(fr),ue.current="idle",ie(null),ot.onError?.(Dt instanceof c.FloPayError?Dt:new c.FloPayError(fr,"api_error"))})}),fe=ht.on("complete",ot=>{(0,jn.markSessionRecentlyCompleted)(ot.sessionId??Ln.current.sessionId),ue.current="terminal",$e(!1),ie("success"),setTimeout(()=>{if(ss.current)return;ss.current=!0;let Et=Ln.current,Dt=(0,c.isAuthorizationOnlySession)(Et)||ot.outcome==="authorized",fr=Et.serverSideCardGateway?{}:{paymentIntentId:ot.intentId};Ln.current.onComplete?.(Dt?{status:"authorized",...fr,paymentId:ot.paymentId??Et.paymentId,sessionId:ot.sessionId??Et.sessionId,authorizationExpiresAt:ot.authorizationExpiresAt??Et.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...fr,checkoutMethod:"card"})},600)}),J=ht.on("decline",ot=>{let Et=Ln.current,Dt=ot.message??"Your payment was declined. Please try another card or contact your bank.";ue.current="terminal",$e(!1),Et.updateError(Dt),ie("error");let fr=ot.failureOutcome??(0,c.normalizeCheckoutFailureOutcome)(ot.declineReason)??"authorization_declined";Et.emitDecline("card",Dt,{code:fr,declineCode:fr}),S()}),Le=ht.on("error",ot=>{let Et=Ln.current,Dt=(0,c.buyerEmailRequiredPrompt)(ot.vaultOutcome);if(Dt!==null){i&&(clearTimeout(i),i=null),ue.current="idle",$e(!1),Et.updateError(Dt),ie(null),$t(cn=>cn+1),Et.onError?.(new c.FloPayError(Dt,"api_error",{code:c.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let fr=ot.message??"There was a problem processing your payment. Please try again.";ue.current="terminal",$e(!1),Et.updateError(fr),ie("error"),Et.onError?.(new c.FloPayError(fr,"api_error",{code:ot.failureOutcome??"capture_failed"})),S()}),qt=ht.on("challenge_dismissed",()=>{ut.current&&(clearTimeout(ut.current),ut.current=null),ue.current="processing",$e(!0),ie(null)}),jt=ht.on("blocked",()=>{if(tt.current){Ln.current.updateError(Wu);return}if(!Cl.current){Pn(!0);return}os(),Ln.current.updateError(zc)});return()=>{i&&(clearTimeout(i),i=null),ut.current&&(clearTimeout(ut.current),ut.current=null),ue.current="idle",$e(!1),ie(null),N(),fe(),J(),Le(),qt(),jt()}},[Je,ht,os,vl]);let Yn=!!Qe?.clientId,ba=Array.isArray(x),ni=ba&&x.length>0,bl=ba&&x.includes("paypal"),oi=(0,o.useRef)(null);oi.current===null&&(oi.current=(0,c.hasMatchingStripePayPalReturn)());let Zo=oi.current?"redirect":(0,Zn.resolveStripePayPalPresentation)(L,be,u.current()),{expressMethods:ai,paymentElementMethods:ls}=(0,o.useMemo)(()=>(0,c.partitionStripeMethods)(x,{excludePaypal:Yn}),[x,Yn]),Sl=Yn||!!Q||bl&&Zo==="redirect",kd=(0,o.useMemo)(()=>Sl?ai.filter(i=>i!=="paypal"):ai,[ai,Sl]),Ed=(0,o.useMemo)(()=>{let i=[];return ge&&i.push("apple_pay"),Ie&&i.push("google_pay"),i},[ge,Ie]),Qo=ba?kd:Ed,_d=b&&Qo.length>0,wl=xt?Tt:Be,ii=(0,o.useMemo)(()=>(0,c.filterStripeMethodsByCountryGate)(ls,wl,oe),[ls,wl,oe]),cs=(0,o.useMemo)(()=>({mode:"payment",amount:Ca,currency:Yo,paymentMethodCreation:"manual",appearance:dl}),[Ca,Yo,dl]),[ds,Rl]=(0,o.useState)("loading"),[us,kl]=(0,o.useState)("loading"),[ps,El]=(0,o.useState)("loading"),[Id,ys]=(0,o.useState)(!1),[_l,ms]=(0,o.useState)("loading"),[fs,Td]=(0,o.useState)();(0,o.useEffect)(()=>{Td((0,Jn.detectPayPalEnvironment)())},[]);let si=fs?.inAppBrowser,li=fs?(0,Zn.resolvePayPalPresentationMode)(fs,Qe?.approvalPresentation,Mr??(st?"subscription":"order")):"popup",Il=Y&&(Yn||(ba?bl:si===!1)),Md=L.inAppBrowser&&u.current()==="blocked",Tl=b&&_d&&!Md,Io=(!gt||!!ee.waitForDataAttachment)&&Il&&Yn,gs=_l==="retrying"||_l==="exhausted",Sa=null;b&&(Q?Sa=cl:Zo==="redirect"&&(Sa=ln));let Ml=(0,o.useMemo)(()=>({...T,presentationMode:Zo}),[T,Zo]),To=!gt&&Il&&!!Sa&&(!Yn||gs),So=!gt&&Tl&&!!ln,Mo=!gt&&b&&ni&&ii.length>0&&!!ln,Ad=Io&&!gs?Id:To&&Ha(ds),xd=So&&Ha(us),Fd=Mo&&ps!=="load_error",Al=[Io||To,So,Mo,Je].filter(Boolean).length,Bd={card:Je,paypal:Io&&!gs||To&&Ha(ds),wallets:So&&Ha(us),apms:Mo&&ps!=="load_error"},xl=i=>Bd[i],Fl=i=>i==="loading"||i==="ready",Bl=Io||To&&Fl(ds)||So&&Fl(us)||Mo&&ps!=="load_error",ci=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!ci.current){if(!b&&!Y){ci.current=!0;let i=new c.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),Ue(i.message)}else if(!b&&Y&&!Yn){ci.current=!0;let i=new c.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(i),Ue(i.message)}else if(si!==void 0&&!gt&&!mr&&!Bl){ci.current=!0;let i=new c.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});p?.(i),Ue(i.message)}}},[b,Y,Yn,si,gt,mr,Bl,p,Ue]);let Ol=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(Ol.current||!ni)return;let i=[];ge!==!0&&i.push("showApplePay"),Ie!==!0&&i.push("showGooglePay"),i.length!==0&&(Ol.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[ni,ge,Ie]);let Dl=(0,o.useCallback)((i,S,N)=>ee.applyInlineSessionPatch?ee.applyInlineSessionPatch(i).then(fe=>({error:null,sessionId:fe.sessionId||e,nonce:fe.session?.clientSecret||t})).catch(fe=>{let J=(0,c.normalizeBeforeButtonClickError)(S,fe);return N?.abandoned?.()||(Ue(J.message),p?.(J)),{error:J,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ee.applyInlineSessionPatch,t,p,e,Ue]),Nn=(0,o.useCallback)(async(i,S)=>{if(i!=="card"&>&&await ee.waitForDataAttachment?.(),!qe)return{proceed:!0};try{let N=await qe({method:i,sessionId:e||void 0,createSession:ee.inlineSessionDraft});if(N===!1)return{proceed:!1};if(N&&typeof N=="object"){N.account&&rr(J=>({...J??{},...N.account}));let fe=await Dl(N,i,S);return fe.error?{proceed:!1,accountPatch:N.account}:{proceed:!0,accountPatch:N.account,sessionId:fe.sessionId,nonce:fe.nonce}}return{proceed:!0}}catch(N){if(!S?.abandoned?.()){let fe=(0,c.normalizeBeforeButtonClickError)(i,N);Ue(fe.message),p?.(fe)}return{proceed:!1}}},[Dl,ee.inlineSessionDraft,ee.waitForDataAttachment,gt,qe,p,e,Ue]),Ll=(0,o.useCallback)(async(i,S)=>{if(Ht.current)return;Ht.current=!0,Fr(!0),ie("processing"),Ue(null);let N=S?.sessionId??e,fe=S?.nonce??t,J=Ts(Bt,S?.accountPatch),Le=S?.completionPaymentMethodId??xa(i),qt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,jt=Yu(i),ot=S?.presentationMode?Ai(Er(v),{...T,presentationMode:S.presentationMode}):void 0,Et=()=>{$?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:jt}),ot?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Vn,requestCategory:"process_payment"})};try{let Dt=new Wn.PaymentAPI(Co),cn=S?.settledProcessResponse??await Dt.processPayment(J.userId??"",{sessionId:N,nonce:fe,paymentMethodCategory:S?.paymentMethodCategory??Ju(i),tokenizedData:qt,accountData:{...S?.accountPatch,userId:J.userId??"",email:J.email??"",firstName:J.firstName||void 0,lastName:J.lastName||void 0,...(0,c.buildProcessPaymentAvsAccount)({avsConfig:P,country:Sr.current,zip:Qt.current,city:wr.current,state:$r.current,addressLine1:jr.current,addressLine2:yr.current})},...(0,c.buildCheckoutProcessMetadata)({chv:V,avsCheck:Oe,checkoutType:Ke,checkoutLayout:vt,avsConfig:P,country:Sr.current})}),mi=async Dr=>{let Ao=(0,c.isAuthorizationOnlySession)(de)||Dr?.status==="authorized";(0,jn.markSessionRecentlyCompleted)(N),ot?.terminal({outcome:"payment_succeeded",...Vn}),ie("success"),en(null),await new Promise(Ta=>setTimeout(Ta,600));let Xn;typeof Dr?.paymentId=="string"?Xn=Dr.paymentId:de?.paymentId&&(Xn=de.paymentId);let xo;typeof Dr?.authorizationExpiresAt=="string"?xo=Dr.authorizationExpiresAt:de?.authorizationExpiresAt&&(xo=de.authorizationExpiresAt),d?.(Ao?{status:"authorized",...Xn===void 0?{}:{paymentId:Xn},sessionId:typeof Dr?.sessionId=="string"?Dr.sessionId:N,...xo===void 0?{}:{authorizationExpiresAt:xo},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Le,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Le,checkoutMethod:i.isPaypal?"paypal":"card"})};if(cn.ok){await mi(cn.status===204?null:await cn.json().catch(()=>null));return}let gr=await cn.json().catch(()=>null);if(gr?.type==="paypal_redirect_required"){let Dr=gr.threeDSecureToken,Ao=gr.paymentMethodId||i.id||"";if(!v||!Dr){ie("error"),Ue("PayPal authorization required but no token provided.");return}try{let Xn=Q?.getRawProvider();if(!Xn){Ue("PayPal is not available.");return}let xo={return_url:window.location.href};Ao&&(xo.payment_method=Ao);let{error:Ta}=await Xn.confirmPayment({clientSecret:Dr,confirmParams:xo,redirect:"if_required"});if(Ta){ie("error");let Jl=Ta.message??"PayPal payment failed.";Ue(Jl),Gn("paypal",Jl,{code:Ta.code})}}catch(Xn){ie("error"),Ue(Xn instanceof Error?Xn.message:"PayPal authorization failed.")}return}if(gr?.type==="paypal_direct_required"){let Dr=gr.orderId;if(!Dr){ie("error"),Ue("PayPal retry required but no order id provided.");return}let Ao=Yt.current?.attempts??0;if(Ao>=2){ie("error"),Ue("PayPal payment could not be completed after multiple attempts."),Gn("paypal","paypal_direct_required retry limit exceeded");return}ys(!1),ms("loading"),en({orderId:Dr,attempts:Ao+1}),ie(null);return}if(cn.headers.get(Du)===Lu){let Dr=await Nu(Dt,N,fe);if(Dr!==void 0){await mi(Dr);return}}(0,c.classifyPaymentRejection)(cn.status,gr)?ot?.terminal({outcome:"payment_declined",...Vn,terminalReason:"provider_declined"}):Et(),ie("error");let Xl=gr?.message??"Payment failed. Please try again.";Ue(Xl),Gn(i.isPaypal?"paypal":"card",Xl,{code:gr?.code??gr?.gatewayErrorCode,declineCode:gr?.declineCode??gr?.gatewayDeclineReason}),await new Promise(Dr=>setTimeout(Dr,400))}catch(Dt){Yc(Dt)||Et(),ie("error"),Ue(Dt instanceof Error?Dt.message:"An unexpected error occurred"),await new Promise(fr=>setTimeout(fr,400))}finally{Fr(!1),ie(null),Ht.current=!1}},[Co,e,t,Bt,P,Oe,Ke,vt,V,v,Q,de,d,Ue,Gn,$,T]),tn=(0,o.useCallback)((i,S)=>{h&&!S?.settledProcessResponse?h(i):Ll(i,S)},[h,Ll]),wa=`${Kc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(wa);if(!i)return;let S;try{S=JSON.parse(i)}catch{cr(wa);return}if(!S||typeof S.createdAt!="number"||Date.now()-S.createdAt<0||Date.now()-S.createdAt>Gc||typeof S.paymentMethodId!="string"||typeof S.providerIntentId!="string"||typeof S.paymentMethodType!="string"||S.sessionId!==e||!t||S.nonce!==t||!Qo.includes(S.paymentMethodType)){cr(wa);return}cr(wa),tn({id:S.paymentMethodId,type:"card",threeDSecureActionResultTokenId:S.providerIntentId,gateway:"stripe",paymentMethodType:S.paymentMethodType},{...S.accountPatch?{accountPatch:S.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[tn,t,e,wa,Qo]);let Nl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Nl.current)return;let[i,S,N]=(0,c.readStripeRedirectParams)();if(!i||!S||oi.current||!v)return;let fe=v.getRawProvider();if(!fe)return;let J=Et=>{let Dt=localStorage.getItem(Et);if(!Dt)return null;try{return JSON.parse(Dt)}catch{return cr(Et),null}},Le=J(eo)??J(Lc),qt;if(Le?.clientSecret){if(Le.clientSecret!==S)return;qt={...Le.accountPatch?{accountPatch:Le.accountPatch}:{},...Le.sessionId?{sessionId:Le.sessionId}:{},...Le.nonce?{nonce:Le.nonce}:{}}}else if(Le?.sessionId&&Le.sessionId!==e)return;Nl.current=!0,cr(eo),cr(Lc),window.history.replaceState({},"",(0,c.stripeRedirectReturnUrl)());let jt=Le?.paymentMethodType??Le?.tokenType??"card",ot="card";(async()=>{if(N==="failed"){let gr="Payment was declined. Please try again.";Ue(gr),Gn(ot,gr);return}let{paymentIntent:Et,error:Dt}=await fe.retrievePaymentIntent(S);if(Dt){let gr=Dt.message??"Failed to retrieve payment status.";Ue(gr),Gn(ot,gr,{code:Dt.code});return}let fr=Et?.status,cn=Aa(fr);if(!Et||!cn){let gr=fr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ue(gr),Gn(ot,gr,{code:fr??"missing_payment_intent"});return}let mi=typeof Et.payment_method=="string"?Et.payment_method:Et.payment_method?.id;tn({id:mi??Le?.paymentMethodId??Le?.tokenId??Et.id,type:"card",threeDSecureActionResultTokenId:Et.id,gateway:Le?.gateway??"stripe",paymentMethodType:jt},qt)})()},[e,tn,v,Ue,Gn]);let hs=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(Je||v!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Ra=ce==="buttons",Kr=Ho?.variables,Od=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ps=Kr?.colorBackground,Dd=Ps&&!Od.has(Ps)?Ps:void 0,ka=rt.cardInputBorder??(Ra?"#e5e7eb":"#A4A4FF"),Ul=Kr?.colorDanger??"#dc2626",er=i=>oo[i]&&(Vo[i]||sn),di=Go&&(vn||sn),wn=i=>i?Ul:ka,ui=(Vr.malformed||Vr.empty)&&(ho||sn),Ld=wn(ui),vs=rt.cardFormContainer?.backgroundColor??Dd??(Ra?"white":"#EDEDFF"),ea=rt.cardInputBackground??Kr?.colorBackground??"white",Cs=na(G),zl=na(K),ta=rt.nameInput,ql=rt.cardInputFontSize??tp(ta?.fontSize)??Kr?.fontSizeBase??"16px",jl=typeof ta?.fontFamily=="string"?ta.fontFamily:Kr?.fontFamily??"Poppins, sans-serif",Vl=(0,c.toCssWeight)(ta?.fontWeight)??400,Nd=rt.cardInputColor??(typeof ta?.color=="string"?ta.color:void 0)??Kr?.colorText??"#262833",Ud=rt.cardInputPlaceholderColor??"#9ca3af",sr=Kr?.borderRadius??"8px",io=Kr?.borderRadius??rt.cardButton?.borderRadius??sr,wo=Kr?.colorPrimary??"#4A49FF",zd=Kr?.colorPrimaryHover??(0,c.darkenHex)(wo,.12),bs=Kr?.colorText??"#262833",Ss={fontSize:ql,fontFamily:jl,fontWeight:Vl,color:Nd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ea={marginTop:"0.375rem",...Ss,fontSize:"0.75rem",lineHeight:1.4,color:Ul},qd={"--flopay-input-placeholder-color":Ud,"--flopay-input-font-size":ql,"--flopay-input-font-family":jl,"--flopay-input-font-weight":String(Vl)},_a=rt.cardFormContainer??{},ws=_a.padding??(Ra?"0":"1rem"),Rs=_a.borderRadius??sr,jd=ht&&On?(0,l.jsx)(_o,{capture:ht,html:On.html,messageToken:On.messageToken,expectedOrigin:On.expectedOrigin,verificationRequired:On.verificationRequired,theme:Sd,submitLabel:k,onReady:()=>{if(!bo&&!P||typeof document>"u"||pe===!1)return;let i=()=>{let N=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(N){Cn.current=!0;try{N.focus()}finally{Cn.current=!1}}};vo.current||i()},onError:i=>{i&&On.verificationRequired&&ue.current==="idle"&&(dt.current=!0),Ue(i)},onValidation:i=>{let S=ue.current;(S==="idle"||S==="validation-window")&&(Ue(i),i&&ue.current==="validation-window"&&(ut.current&&(clearTimeout(ut.current),ut.current=null),ue.current="idle",ie(null)))}},z):(0,l.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ks=(0,l.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&me()},style:{backgroundColor:vs,borderRadius:Rs,..._a,padding:ws,...qd,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
|
|
30
|
+
`,ko=44;function ha(){return(0,Tr.jsx)("style",{children:_u})}function Wa(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function $a({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Tr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Tr.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:r,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,Tr.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:n})]})}function Ha(e){return e!=="unavailable"&&e!=="load_error"}function xi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:d,backgroundColor:p,borderColor:y,textColor:S,borderRadius:P,fontFamily:g}){let _=(0,po.resolveStripeMethodBrandVariant)(e,t),W=Oc[e],[$,R]=(0,Dc.useState)(!1),x=!!W&&!$,f=_?.backgroundColor??p??"#ffffff",H=_?.borderColor??y??"#d1d5db",X=_?.textColor??S??"#262833";return(0,Tr.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&d()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ko,padding:"0 1rem",backgroundColor:f,color:X,border:`1px solid ${H}`,borderRadius:P??8,fontSize:"0.95rem",fontWeight:600,fontFamily:g,cursor:r||n?"not-allowed":"pointer",opacity:n&&!r?.55:1,animation:r?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,Tr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,po.getStripeMethodDisplayName)(e)}\u2026`}):(0,Tr.jsxs)(Tr.Fragment,{children:[(0,Tr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,po.hasVendoredStripeMethodLogo)(e)?8:0},children:[x?(0,Tr.jsx)("img",{src:W,alt:"","aria-hidden":"true",onError:()=>R(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!x&&_?.logoSvg?(0,Tr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:_.logoSvg}}):null,(0,Tr.jsx)("span",{children:(0,po.getStripeMethodDisplayName)(e)})]}),s&&(0,Tr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:X,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,Tr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Fi(e){let t=new Set(e.map(po.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var Bi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},Oi={type:"accordion",defaultCollapsed:!1,radios:"never"};function Di({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:d,children:p}){return(0,Tr.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:a,color:"white",border:"none",borderRadius:s,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...d??{}},children:p})}var qs=require("react/jsx-runtime"),Iu=["first","second","third","fourth"];function js({rows:e,borderRadius:t}){return(0,qs.jsx)("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Iu.slice(0,Math.max(1,e)).map(r=>(0,qs.jsx)("div",{style:{height:ko,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},r))})}var Nc=require("@flopay/js"),Li=require("@flopay/shared"),Ni=require("react"),Tu=1500,Lc=new Set;function Uc(e){for(let t of e)Lc.has(t)||(Lc.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function Mu(e){if(e!=null)try{return JSON.stringify(e)}catch{return Uc(["the rules could not be sent (they are not plain data), so the default layout applies."]),"{}"}}var Au={order:[...Li.DEFAULT_PAYMENT_METHOD_ORDER],moreOptions:[]};function zc({rules:e,sessionId:t,nonce:r,billingApiUrl:n,waitForSession:a}){let s=Mu(e),[d,p]=(0,Ni.useState)(null);return(0,Ni.useEffect)(()=>{if(s===void 0||a)return;let y=JSON.parse(s),S=!1,P=$=>{S||(S=!0,p($))},g=()=>P((0,Li.resolveDefaultPaymentMethodLayout)(y));if(!t||!r||!n){g();return}let _=new AbortController,W=setTimeout(()=>{g(),_.abort()},Tu);return new Nc.PaymentAPI(n,{telemetry:!1}).resolvePaymentMethodLayout(t,r,y,{signal:_.signal}).then($=>{if(!$){g();return}S||Uc($.warnings),P({order:$.order,moreOptions:$.moreOptions})}).catch(g).finally(()=>clearTimeout(W)),()=>{S=!0,clearTimeout(W),_.abort()}},[s,t,r,n,a]),s===void 0?Au:d}var dn=require("react");var Ka=require("@flopay/shared"),xu=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function Fu(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return xu.has(t.charAt(0).toLowerCase()+t.slice(1))}function Bu(e,t){return typeof t=="number"&&t!==0&&!Fu(e)?`${t}px`:String(t).trim()}function qc(e,t){if(e.style.cssText="",!!t){for(let[r,n]of Object.entries(t))if(!(n==null||n==="")){if(r.startsWith("--")){e.style.setProperty(r,String(n));continue}e.style[r]=Bu(r,n)}}}var qo=require("react/jsx-runtime"),Vs=new WeakSet;function Eo({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:d,containerStyle:p,onReady:y,onError:S,onValidation:P}){let g=(0,dn.useRef)(null),_=(0,dn.useRef)(y),W=(0,dn.useRef)(S),$=(0,dn.useRef)(P);_.current=y,W.current=S,$.current=P;let R=(0,dn.useRef)(s);R.current=s;let x=(0,dn.useRef)(null),f=d??void 0,H=(0,dn.useRef)(f);H.current=f;let X=(0,dn.useRef)(void 0);return(0,dn.useEffect)(()=>{let v=g.current;if(!v)return;let be=!0,F=!1,oe=()=>{!be||F||(F=!0,_.current?.())},he=e.on("ready",()=>{oe()}),Re=e.on("error",j=>{W.current?.(j.message??"There was a problem loading the secure card form.")}),pe=e.on("validation",j=>{$.current?.(j.message??null)}),kt=H.current??(Vs.has(e)?null:void 0),mt={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...R.current?{theme:R.current}:{},...kt===void 0?{}:{submitLabel:kt}};return x.current=R.current??null,X.current=H.current,H.current!==void 0&&Vs.add(e),e.mount(v,mt).then(()=>{oe()}).catch(j=>{be&&W.current?.(j instanceof Error?j.message:"Failed to load the secure card form.")}),()=>{be=!1,he(),Re(),pe(),e.unmount()}},[e,t,r,n,a]),Do(()=>{let v=g.current;v&&qc(v,p)},[p]),(0,dn.useEffect)(()=>{s!==void 0&&(s===null&&x.current===null||(x.current=s,e.applyTheme?.(s)))},[e,s]),(0,dn.useEffect)(()=>{f!==X.current&&(X.current=f,f!==void 0&&Vs.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,qo.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields"})}function Ga({label:e}){return(0,qo.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,qo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,qo.jsx)("span",{children:e}),(0,qo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var el=require("@flopay/shared"),l=require("react/jsx-runtime"),Qn="flopay_stripe_resume",jc="flopay_wallet_resume",Zc="fw1",Ou="fw2",Qc=300*1e3,Du=900,Lu="express_checkout_click_timeout",Nu=25e3,Uu=25e3,zu=1e4,Ln={provider:"paypal",paymentMethodCategory:"paypal"},qu="x-flopay-process-result-source",ju="status";async function Vu(e,t,r){try{let n=(await e.getUnifiedCheckoutSession(t,r)).data.session;if(n?.status==="complete")return null;if(n?.status==="authorized")return{status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}}catch{}}var Ui={},Xa=class{constructor(t){this.reason=t}};function Wu(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function dr(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function Js(e){return`${Ou}:${e}`}function zi(e){return dr(Js(e))}function qi(e,t){if(typeof window>"u")return null;let r=Js(e);try{let n=localStorage.getItem(r);if(!n)return null;let a=JSON.parse(n);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>Qc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(zi(e),null):a}catch{return zi(e),null}}function $u(e){return dr(Js(e.sessionId),e)}function Vc(e,t,r){let n=qi(e,t);return!n||n.clientSecret!==r?!1:zi(e)}function Ws(e,t,r){if(typeof window>"u")return;qi(e,t)?.clientSecret===r&&zi(e)}function Hu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function $s(e,t,r){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let n=r?e.status==="succeeded":Aa(e.status),a=Hu(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Wc(e,t,r){let n=null;try{return await Promise.race([yc(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},zu),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Ku(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function ed(e){return e instanceof c.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ji(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Nn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw ed(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var Hs=c.STRIPE_PAYPAL_RESUME_KEY,Ya=new Map,Gu=250,$c="Just a moment \u2014 we are finalizing your order. Please press pay again.",Yu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Zs(e,t,r,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:r,requestCategory:"provider_sdk",...n?{terminalReason:n}:{}})}async function Vi({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new Nn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Xu(e){return e instanceof c.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function td({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,la.splitFullName)(r),d=s.firstName?s:(0,la.splitFullName)(n?.name);return(0,Cn.compactBuyerIdentity)({email:(0,c.isValidEmail)(a)?a:n?.email?.trim(),firstName:d.firstName,lastName:d.lastName})}async function Ju({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let d=td({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,c.isValidEmail)(d.email)?d:s(a,d)}var Ja=180,Hc=`flopay-card-enter ${Ja}ms cubic-bezier(0, 0, 0.2, 1) both`,Kc=`flopay-card-exit ${Ja}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Zu=`flopay-buttons-enter ${Ja}ms cubic-bezier(0, 0, 0.2, 1) both`,Qu=`flopay-buttons-exit ${Ja}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function ep(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Qs(e){return(0,c.derivePrimaryTileStyle)(e)}var tp={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function rp(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var Gs={width:"100%",minHeight:ko,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Gc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ys(e){return e==="paypal"?"PayPal":(0,c.getStripeMethodDisplayName)(e)}function np(e){let t=(0,c.getPostalCodeExample)(e);return`Enter a valid ${(0,c.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function op(e,t,r){let n=(0,c.isPostalCodeSupported)(e),a=t.trim(),s=r&&n,d=s&&!a,p=s&&!!a&&!(0,c.isValidPostalCode)(e,a);return{visible:r,supported:n,required:s,empty:d,malformed:p}}function ap(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,c.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function ip(e){return typeof e=="number"?`${e}px`:e}var sp=["number","expiry","cvv","name"];function lp(e){if(e===null||typeof e!="object")return null;let t={};for(let r of sp){let n=e[r];typeof n=="string"&&(t[r]=n)}return JSON.stringify(t)}function Wi(e){return(0,l.jsx)(up,{...e})}function Yc({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:d=!1,onButtonClick:p,onDecline:y,onTechnicalFailure:S,runBeforeButtonClick:P,billingName:g,onBuyerIdentityReady:_,onLoadStateChange:W,placeholderBorderRadius:$,popupCapabilityOwner:R,externalTelemetryContext:x,presentationMode:f}){let H=co(),{emitInstrument:X}=(0,o.useContext)(vn),v=(0,cr.useStripe)(),be=(0,cr.useElements)(),F=(0,o.useMemo)(()=>Ai(wr(H),x),[x,H]),[oe,he]=(0,o.useState)("loading");(0,o.useEffect)(()=>{W?.(oe)},[oe,W]);let[Re,pe]=(0,o.useState)(!1),kt=(0,o.useRef)(!1),mt=!(0,c.isValidEmail)(r?.trim())||!g?.trim(),{request:j,collect:Je,finish:Ze}=ca(),Le=(0,o.useRef)(!1),ve=(0,o.useRef)(null),Y=(0,o.useRef)(null),[K,rt]=(0,o.useState)(0),[Se,Ke]=(0,o.useState)(!1),ee=(0,o.useRef)(!1),V=(0,o.useRef)(new Map),{startAttempt:Pe,finishAttempt:J,invalidateAttempt:ut,isAttemptInvalidated:ye,isAttemptCurrent:ke,generationRef:xe}=Oa((Ee,$e,Ct)=>{S?.(Ee,$e,{...Ct,popupBlocked:Ct?.popupBlocked??(0,we.isPopupBlockedError)($e),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),Ke(!0),rt(bt=>bt+1)},{onHandoffObserved:()=>{R.markAvailable(),F?.log({name:"provider.popup.opened",stage:"overlay_open",...Ln,attempt:xe.current})}});(0,o.useEffect)(()=>{Se&&Y.current?.focus()},[Se,K]);let _e=(0,o.useCallback)(()=>{rt(Ee=>Ee+1)},[]),vt=(0,o.useCallback)((Ee,$e,Ct)=>{ut(Ct),S?.("paypal",Ee,{code:$e,popupBlocked:(0,we.isPopupBlockedError)(Ee),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),Ke(!0),_e()},[ut,S,f,_e]),Ne=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ve.current?.querySelector("iframe")??ve.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{ee.current&&(ee.current=!1,Ne())},[Ne,K]);let ft=(0,o.useCallback)(()=>{Ke(!1),s?.(null),Ne()},[Ne,s]);(0,o.useEffect)(()=>{if(!v||Le.current)return;let[Ee,$e,Ct]=(0,c.readStripeRedirectParams)();if(!Ee||!$e)return;let bt=(0,c.readMatchingStripePayPalContinuation)($e);if(!bt)return;Le.current=!0;let st=!0,pt=Ya.get($e);pt||(pt=Ct==="failed"?Promise.resolve(null):Promise.resolve().then(()=>v.retrievePaymentIntent($e)),Ya.set($e,pt));let At={accountPatch:bt.accountPatch,sessionId:bt.sessionId,nonce:bt.nonce},xt=()=>{F?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Ln,requestCategory:"provider_sdk"})};return F?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Ln}),(async()=>{try{pe(!0);let ct=await pt;if(!st)return;if(ct?.error){Ya.delete($e),xt(),s?.(ct.error.message??"Failed to retrieve PayPal payment status.");return}if((0,c.clearStripePayPalReturn)(),Ya.delete($e),Ct==="failed"){let G="PayPal payment was declined. Please try again.";F?.terminal({outcome:"payment_declined",...Ln,terminalReason:"provider_declined"}),s?.(G),y?.(Sr("paypal",G));return}let gt=ct?.paymentIntent;if(gt&>.id!==Ee){xt(),s?.("Failed to match the returned PayPal payment.");return}if(gt&&(gt.status==="requires_capture"||gt.status==="succeeded")){let G=typeof gt.payment_method=="string"?gt.payment_method:gt.payment_method?.id;a({id:G??gt.id,type:"card",threeDSecureActionResultTokenId:gt.id,isPaypal:!0},{...At,presentationMode:"redirect"})}else{let G="PayPal payment was not completed. Please try again.";F?.terminal({outcome:gt?.status==="canceled"?"payment_cancelled":"payment_declined",...Ln,terminalReason:gt?.status==="canceled"?"cancelled":"provider_declined"}),s?.(G),y?.(Sr("paypal",G))}}catch(ct){if(!st)return;Ya.delete($e),xt(),s?.(ct instanceof Error?ct.message:"Failed to complete PayPal payment.")}finally{st&&pe(!1)}})(),()=>{st=!1,Le.current=!1}},[v,a,s,y,F]);let Ve=(0,o.useCallback)(async(Ee=!1)=>{let $e=P?await P("paypal"):{proceed:!0};if(!$e.proceed)return V.current.delete(K),!1;let Ct=Pe("paypal");return V.current.set(K,{generation:Ct,accountPatch:$e.accountPatch,sessionId:$e.sessionId,nonce:$e.nonce}),Ke(!1),F?.log({name:`provider.${Ee?"redirect.started":"handoff.requested"}`,stage:Ee?"redirect":"overlay_open",...Ln,attempt:Ct}),p?.("paypal"),!0},[p,F,P,Pe,K]),We=(0,o.useCallback)(async Ee=>{if(d||Re||!await Ve()){Ee.reject();return}Ee.resolve()},[d,Ve,Re]),Mt=(0,o.useCallback)(async Ee=>{if(!v||!be)return;let $e=V.current.get(K);if($e&&!ke($e.generation)){V.current.delete(K);return}if(!$e&&ye()||$e&&!J($e.generation))return;$e||J();let Ct=$e??null;if(V.current.delete(K),!Ct&&P){let lt=await P("paypal");if(!lt.proceed){Ee.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Ct={accountPatch:lt.accountPatch,sessionId:lt.sessionId,nonce:lt.nonce}}let bt=Ct?.sessionId??e,st=Ct?.nonce??t,pt=await Ju({event:Ee,prepared:Ct,email:r,billingName:g,methodLabel:"PayPal",collect:Je});if(!pt){Ee.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let At=pt.email,xt={...Ct?.accountPatch,...(0,Cn.compactBuyerIdentity)(pt,!0)};try{if(pe(!0),s?.(null),!bt||!(0,c.isValidEmail)(At))throw new Error("Missing sessionId or email for PayPal payment");await _?.(pt);let lt=v.createPaymentMethod,{error:ct,paymentMethod:gt}=await lt({type:"paypal"});if(ct){vt(ct,"stripe_paypal_create_payment_method_failed",$e?.generation),Ee.paymentFailed({reason:"fail"});return}let G=await ji(n,X,bt,st??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:gt?.id??null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(G)){Ee.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:xt,paymentMethodCategory:"paypal",presentationMode:f,sessionId:bt,nonce:st,settledProcessResponse:G.response});return}if(G.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Jt=G.clientSecret,B={return_url:(0,c.stripeRedirectReturnUrl)()};if(gt?.id&&(B.payment_method=gt.id),!dr(Hs,{clientSecret:Jt,sessionId:bt,nonce:st,accountPatch:xt})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:ce,paymentIntent:Z}=await v.confirmPayment({clientSecret:Jt,confirmParams:B,redirect:"if_required"});if(ce){if(dr(Hs),(0,we.isProviderDecline)(ce)){let u=ce.message??"Your payment was declined.";F?.terminal({outcome:"payment_declined",...Ln,terminalReason:"provider_declined"}),s?.(u),y?.(Sr("paypal",u,{code:(0,we.getProviderErrorCode)(ce),declineCode:(0,we.getProviderDeclineCode)(ce)})),await Vi({billingApiUrl:n,sessionId:bt,nonce:st,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,we.getProviderErrorCode)(ce)??"provider_declined"}})}else vt(ce,"stripe_paypal_confirm_failed",$e?.generation);return}dr(Hs);let ae=typeof Z?.payment_method=="string"?Z.payment_method:Z?.payment_method?.id;a({id:ae??Z?.id,type:"card",threeDSecureActionResultTokenId:Z?.id,isPaypal:!0},{accountPatch:xt,paymentMethodCategory:"paypal",presentationMode:f,sessionId:bt,nonce:st});return}catch(lt){vt(lt,"stripe_paypal_failed",$e?.generation)}finally{pe(!1)}},[v,be,e,t,r,g,Je,_,n,X,a,s,y,P,vt,J,ke,ye,F,f,K]),Lt=(0,o.useCallback)(async()=>{if(!(kt.current||d||Re||!v||!be)){kt.current=!0,pe(!0);try{if(!await Ve(!0))return;await Mt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{kt.current=!1,pe(!1)}}},[be,Mt,d,Ve,v,Re]),Ft=f==="redirect"?(0,l.jsx)("button",{type:"button",disabled:d||Re,onClick:()=>{Lt()},style:{width:"100%",minHeight:ko,border:"1px solid #d1d5db",borderRadius:$??8,background:"#ffc439",color:"#111827",cursor:d||Re?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,l.jsx)(cr.ExpressCheckoutElement,{onReady:Ee=>he(Wa(Ee,["paypal"])),onLoadError:()=>{he("load_error"),Zs(F,"paypal","paypal","provider_error")},onClick:We,onConfirm:Mt,onCancel:()=>{let Ee=V.current.get(K);V.current.delete(K),F?.terminal({outcome:"payment_cancelled",...Ln,terminalReason:"cancelled",...Ee?{attempt:Ee.generation}:{}}),ut(Ee?.generation),Ke(!1),ee.current=!0,_e()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:mt,emailRequired:mt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},K),le=(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{ref:ve,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Se&&(0,l.jsx)("button",{ref:Y,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ft,style:Gs,children:"Try PayPal again"}),j&&(0,l.jsx)(da,{identity:j.identity,methodLabel:j.methodLabel,onComplete:Ze,onCancel:()=>Ze(null)},j.id),(0,l.jsx)("div",{style:{display:j?"none":void 0},children:Ft})]}),Re&&!j&&(0,l.jsx)(on,{status:"processing"})]});return f==="redirect"?le:(0,l.jsx)($a,{state:oe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:$,children:le})}function Ks(e){return e==="apple_pay"||e==="google_pay"}var cp=200;function dp({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,c.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function Xc({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:d,onErrorChange:p,onButtonClick:y,onDecline:S,onTechnicalFailure:P,runBeforeButtonClick:g,billingName:_,onBuyerIdentityReady:W,onLoadStateChange:$,placeholderBorderRadius:R,popupCapabilityOwner:x,externalTelemetryContext:f}){let H=co(),{emitInstrument:X}=(0,o.useContext)(vn),v=(0,cr.useStripe)(),be=(0,cr.useElements)(),F=(0,o.useMemo)(()=>Ai(wr(H),f),[f,H]),[oe,he]=(0,o.useState)("loading");(0,o.useEffect)(()=>{$?.(oe)},[oe,$]);let[Re,pe]=(0,o.useState)(!1);(0,o.useEffect)(()=>{Ke.current=Re},[Re]);let kt=(0,o.useRef)(!(0,c.isValidEmail)(r?.trim())||!_?.trim()).current,{request:mt,collect:j,finish:Je}=ca(),Ze=(0,o.useRef)(null),Le=(0,o.useRef)(null),[ve,Y]=(0,o.useState)(0),[K,rt]=(0,o.useState)(()=>(0,c.shouldPreferWalletPopup)()),Se=(0,o.useRef)(K),Ke=(0,o.useRef)(!1),[ee,V]=(0,o.useState)(!1),[Pe,J]=(0,o.useState)(()=>qi(e,t)?"blocked":"idle"),[ut,ye]=(0,o.useState)("google_pay"),ke=(0,o.useRef)(null),xe=(0,o.useRef)(!0),_e=(0,o.useRef)(!1),vt=(0,o.useRef)("google_pay"),Ne=(0,o.useRef)("google_pay"),ft=(0,o.useRef)(null),Ve=(0,o.useRef)(null),We=(0,o.useRef)(new Set),Mt=(0,o.useRef)(null),Lt=(0,o.useRef)(null);(0,o.useEffect)(()=>(xe.current=!0,()=>{xe.current=!1;for(let u of We.current)window.clearTimeout(u);We.current.clear()}),[]);let Ft=(0,o.useRef)(new Map),{startAttempt:le,finishAttempt:Ee,invalidateAttempt:$e,isAttemptInvalidated:Ct,isAttemptCurrent:bt,generationRef:st}=Oa((u,M,I)=>{P?.(u,M,{...I,popupBlocked:I?.popupBlocked??(0,we.isPopupBlockedError)(M),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ye(u),V(!0),Y(ie=>ie+1)},{onHandoffObserved:u=>{Lt.current=st.current,x.markAvailable(),F?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:st.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})},defersMissingTerminal:Ks,onMissingTerminalDeferred:(u,M)=>{let I=F?.now()??globalThis.performance?.now()??Date.now(),ie=Mt.current,U=ie?.generation===M?ie.startedAt:I;F?.performance({stage:"overlay_return",durationMs:Math.max(0,I-U),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:M,...Ks(u)?{walletType:u}:{}}),F?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{ee&&Le.current?.focus()},[ee,ve]);let pt=(0,o.useRef)(0),At=(0,o.useRef)(!1),xt=(0,o.useCallback)(()=>{if(pt.current>0){At.current=!0;return}Y(u=>u+1)},[]),lt=(0,o.useCallback)(()=>{pt.current-=1,!(pt.current>0||!At.current)&&(At.current=!1,xe.current&&Y(u=>u+1))},[]),ct=(0,o.useCallback)((u,M,I,ie,U=!1)=>{$e(ie),P?.(u,M,{code:I,popupBlocked:(0,we.isPopupBlockedError)(M),telemetryReported:U,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ye(u),V(!0),xt()},[$e,P,xt]),gt=(0,o.useCallback)(u=>{F?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...Ks(u)?{walletType:u}:{}}),P?.(u,new Error("The wallet click was not ready within the time the wallet allows."),{code:Lu,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ye(u),V(!0)},[P,F]),G=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Ze.current?.querySelector("iframe")??Ze.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{_e.current&&(_e.current=!1,G())},[G,ve]);let Jt=(0,o.useCallback)(()=>{V(!1),p?.(null),G()},[G,p]),B=(0,o.useCallback)(()=>{ke.current?.()},[]);(0,o.useEffect)(()=>{let u=null,M=()=>{u=null;let ie=(0,c.shouldPreferWalletPopup)();ie!==Se.current&&(Se.current=ie,rt(ie),!Ke.current&&!bt(st.current)&&xt())},I=()=>{u!==null&&window.clearTimeout(u),u=window.setTimeout(M,cp)};return window.addEventListener("resize",I),()=>{window.removeEventListener("resize",I),u!==null&&window.clearTimeout(u)}},[st,bt,xt]),(0,o.useEffect)(()=>{let u=qi(e,t);if(!u)return;let M=!1,I=!1,ie=async()=>{if(!I){I=!0,M||J("checking");try{let U=await Wc(v,u.clientSecret,We.current);if(M)return;let k=$s(U,u.providerObjectId,(0,c.isSetupIntentClientSecret)(u.clientSecret));if(k.kind==="confirmed"){if(!Vc(e,t,u.clientSecret))return;ke.current=null,J("idle"),d({id:k.paymentMethodId,type:"card",threeDSecureActionResultTokenId:k.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(k.kind==="terminal"){Ws(e,t,u.clientSecret),ke.current=null,J("idle"),ye(u.paymentMethodType),V(!0),xt();return}J("blocked")}catch{M||J("blocked")}finally{I=!1}}};return ke.current=ie,J("blocked"),()=>{M=!0,ke.current===ie&&(ke.current=null)}},[t,d,xt,e,v]);let C=(0,o.useCallback)(async u=>{let M=!1,I=!1,ie=St=>{M||I||(M=!0,u.paymentFailed({reason:"fail",...St?{message:St}:{}}))};if(!v||!be){ie();return}let U=Ft.current.get(ve);if(U&&!bt(U.generation)){Ft.current.delete(ve),ie();return}if(!U&&Ct()){ie();return}if(U&&!Ee(U.generation)){ie();return}U||(Ee(),At.current=!1);let k=u.expressPaymentType??U?.method??vt.current,tt=U??null,Ht=Gc(k),Kt;k==="apple_pay"?Kt="apple_pay":k==="google_pay"&&(Kt="google_pay");let Vr=U?.generation??st.current,He=F,Un=He?.now()??globalThis.performance?.now()??Date.now(),Pr=new AbortController,vr=!1,Et=!1,jt=null,Or=e,Qr="processing",Dr="other",Ar="provider_runtime",xr,tr=new Promise((St,Fe)=>{xr=Fe}),Gt=window.setTimeout(()=>{vr=!0,Pr.abort(),xr(Ui)},Nu),or=async(St,Fe,un)=>{Qr=St,Dr=Fe,Ar=Fe==="intent_create"||Fe==="session_claim"?"transport_error":"provider_runtime";let Vt=He?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([un,tr])}finally{let Lr=He?.now()??globalThis.performance?.now()??Date.now();He?.performance({stage:St,durationMs:Math.max(0,Lr-Vt),durationMode:"machine",requestCategory:Fe,paymentMethodCategory:"wallet",provider:"stripe",...vr?{statusClass:"timeout"}:{}})}};try{if(pe(!0),p?.(null),!tt&&g){let Ie=await or("processing","other",g(Ht));if(!Ie.proceed){ie();return}tt={accountPatch:Ie.accountPatch,sessionId:Ie.sessionId,nonce:Ie.nonce}}let St=tt?.sessionId??e;Or=St;let Fe=tt?.nonce??t,un=ft.current??tt?.accountPatch,Vt=td({event:u,fallbackEmail:un?.email??r,fallbackName:[un?.firstName,un?.lastName].join(" ").trim()||_});if(!(0,c.isValidEmail)(Vt.email)){ie("Buyer details are required."),j(Ys(k),Vt).then(Ie=>{Ie&&(ft.current=Ie)});return}ft.current=null;let Lr={...tt?.accountPatch,...(0,Cn.compactBuyerIdentity)(Vt,!0)};await or("processing","session_claim",Promise.resolve(W?.(Vt)));let{error:Wr}=await or("tokenization","provider_sdk",be.submit());if(Wr){ie(),ct(k,Wr,"stripe_wallet_submit_failed",U?.generation);return}if(!St)throw new Error("Missing sessionId or email for payment.");let pn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:k,paymentMethodId:null,intentKind:a},$r=JSON.stringify({sessionId:St,nonce:Fe??"",request:pn}),zn=Ve.current,En=zn?.retryIdentity===$r?zn.authorizationAttemptId:(0,c.randomUuidV4)();Ve.current={authorizationAttemptId:En,retryIdentity:$r};let Cr=await or("processing","intent_create",ji(n,X,St,Fe??"",{...pn,authorizationAttemptId:En},{signal:Pr.signal}));if((0,c.isSettledSessionIntent)(Cr)){ie(),d({type:"card",paymentMethodType:k},{accountPatch:Lr,paymentMethodCategory:"wallet",sessionId:St,nonce:Fe,settledProcessResponse:Cr.response});return}if(Cr.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let br=Cr.clientSecret,Nr=$u({createdAt:Date.now(),sessionId:St,...Fe?{nonce:Fe}:{},clientSecret:br,providerObjectId:Cr.providerObjectId,paymentMethodType:k,accountPatch:Lr});window.clearTimeout(Gt),Et=!0,He?.performance({stage:"callback",durationMs:Math.max(0,(He?.now()??globalThis.performance?.now()??Date.now())-Un),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let en=He?.now()??globalThis.performance?.now()??Date.now(),Hr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Kt?{walletType:Kt}:{},attempt:Vr},Ur=!1,pr=null;He?.log({name:"payment.provider_confirmation.started",...Hr}),jt=window.setTimeout(()=>{jt!==null&&We.current.delete(jt),Ur=!0;let Ie=He?.now()??globalThis.performance?.now()??Date.now();He?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Hr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Ie-en),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),He?.flush?.().catch(()=>{}),pr?.()},Uu),We.current.add(jt);let ar=(Ie,Tt)=>{jt!==null&&(window.clearTimeout(jt),We.current.delete(jt),jt=null);let Pt=He?.now()??globalThis.performance?.now()??Date.now(),Yt=Math.max(0,Pt-en),Ge=Ie;Ur&&(Ie==="resolved"?Ge="resolved_late":Ie==="returned_error"?Ge="returned_error_late":Ge="rejected_late");let qn=Tt??(Ie==="resolved"?"approved":"provider_error");return He?.log({name:"payment.provider_confirmation.returned",...Hr,operationOutcome:Ge,terminalReason:qn}),He?.performance({...Hr,durationMs:Yt,durationMode:"buyer",operationOutcome:Ge,terminalReason:qn}),{durationMs:Yt,operationOutcome:Ge,terminalReason:qn}},ir=!1,rr=!1,Kr=Ie=>{if(!Ie||typeof Ie!="object")return null;let Tt=Ie;if(Tt.error)return null;let Pt=Tt.setupIntent??Tt.paymentIntent,Yt=$s(Pt??null,void 0,!!Tt.setupIntent);return Yt.kind==="confirmed"?Yt:null},Gr=Ie=>{if(ir||U&&st.current!==U.generation)return;let Tt=Kr(Ie);if(!Tt)return;if(Nr&&!Vc(St,Fe,br)){ir=!0;return}let{intentId:Pt,paymentMethodId:Yt}=Tt;ir=!0,rr=!0,Ve.current=null,ke.current=null,xe.current&&(J("idle"),pe(!1));let Ge=`${Zc}:${St}`;dr(Ge,{createdAt:Date.now(),sessionId:St,nonce:Fe,accountPatch:Lr,paymentMethodId:Yt,providerIntentId:Pt,paymentMethodType:k});try{d({id:Yt,type:"card",threeDSecureActionResultTokenId:Pt},{accountPatch:Lr,paymentMethodCategory:"wallet",sessionId:St,nonce:Fe})}finally{dr(Ge)}},zr=!1;pr=async()=>{if(!(zr||ir||rr)){zr=!0,xe.current&&J("checking");try{let Ie=await Wc(v,br,We.current);if(ir||rr)return;let Tt=(0,c.isSetupIntentClientSecret)(br),Pt=$s(Ie,Cr.providerObjectId,Tt);if(Pt.kind==="confirmed"){Gr(Tt?{setupIntent:Ie}:{paymentIntent:Ie});return}if(Pt.kind==="terminal"){if(rr=!0,Ws(St,Fe,br),Ve.current=null,ke.current=null,!xe.current)return;J("idle"),ie(),ct(k,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",U?.generation,!0);return}xe.current&&!rr&&(J("blocked"),pe(!1))}catch{xe.current&&!rr&&(J("blocked"),pe(!1))}finally{zr=!1}}},ke.current=pr;let L,ht;try{I=!0,pt.current+=1;let Ie;try{Ie=await((0,c.isSetupIntentClientSecret)(br)?v.confirmSetup({elements:be,clientSecret:br,redirect:"if_required"}):v.confirmPayment({elements:be,clientSecret:br,redirect:"if_required"}))}finally{lt()}if(!Ie||typeof Ie!="object")throw new Xa(Wu(Ie));if(L=Ie,!L.error&&!Kr(L))throw new Xa("confirmation_result_unconfirmed");ht=ar(L.error?"returned_error":"resolved",L.error&&(0,we.isProviderDecline)(L.error)?"provider_declined":void 0)}catch(Ie){let Tt=Ie instanceof Xa?Ie.reason:void 0,Pt=Tt!==void 0,Yt=ar(Pt?"returned_error":"rejected");if(He?.error({...Pt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Tt}:Bs(Ie),...Hr,operationOutcome:Yt.operationOutcome,durationMs:Yt.durationMs,statusClass:"unknown",terminalReason:Yt.terminalReason}),!xe.current||ir)return;await pr?.();return}let T=L.error;if(T){if(!xe.current||ir)return;if((0,we.isProviderDecline)(T)){rr=!0,Ws(St,Fe,br),Ve.current=null,ke.current=null,J("idle"),Ft.current.get(ve)===U&&Ft.current.delete(ve);let Ie=T.message??"Your payment was declined.";p?.(Ie),S?.(Sr(Ht,Ie,{code:(0,we.getProviderErrorCode)(T),declineCode:(0,we.getProviderDeclineCode)(T)})),Vi({billingApiUrl:n,sessionId:St,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:k,providerDeclineReason:(0,we.getProviderErrorCode)(T)??"provider_declined",...Cr.intentKind==="payment"&&Cr.providerObjectId.startsWith("pi_")?{providerIntentId:Cr.providerObjectId}:{}}})}else He?.error({...Bs(T),...Hr,operationOutcome:ht.operationOutcome,durationMs:ht.durationMs,statusClass:"unknown",terminalReason:ht.terminalReason}),await pr?.();return}if(Gr(L),!ir)throw new Error("Invalid provider returned for APM intent")}catch(St){if(St===Ui){let Fe=He?.now()??globalThis.performance?.now()??Date.now();He?.error({errorCode:Ku(Dr),stage:Qr,requestCategory:Dr,paymentMethodCategory:"wallet",provider:"stripe",...Kt?{walletType:Kt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Or,durationMs:Math.max(0,Fe-Un),statusClass:"timeout",failureCategory:Ar,attempt:Vr,terminalReason:"provider_error"}),He?.flush?.().catch(()=>{})}ie(),ct(k,St,St===Ui?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",U?.generation,St===Ui)}finally{if(window.clearTimeout(Gt),jt!==null&&(window.clearTimeout(jt),We.current.delete(jt)),!Et){let St=He?.now()??globalThis.performance?.now()??Date.now();He?.performance({stage:"callback",durationMs:Math.max(0,St-Un),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...vr?{statusClass:"timeout"}:{}})}xe.current&&pe(!1)}},[v,be,e,t,r,_,j,W,n,X,a,d,p,S,g,ct,lt,Ee,bt,Ct,st,F,ve]),ce=(0,o.useMemo)(()=>Fi(s),[s]),Z=(0,o.useMemo)(()=>s.map(c.stripeExpressMethodToOptionKey),[s]),ae=(0,o.useMemo)(()=>(0,l.jsx)(cr.ExpressCheckoutElement,{onReady:u=>{he(Wa(u,Z))},onLoadError:u=>{he("load_error"),Zs(F,"stripe","wallet","provider_error")},onClick:async u=>{let M=F?.now()??globalThis.performance?.now()??Date.now();vt.current=u.expressPaymentType,Ne.current=Gc(u.expressPaymentType);let I=!0,ie=window.setTimeout(()=>{I=!1,u.reject(),gt(u.expressPaymentType)},Du),U=g?await g(Ne.current,{abandoned:()=>!I}):{proceed:!0};if(window.clearTimeout(ie),!I)return;if(!U.proceed){Ft.current.delete(ve),u.reject();return}let k=le(u.expressPaymentType);At.current=!1,Mt.current={generation:k,startedAt:M},Ft.current.set(ve,{generation:k,method:u.expressPaymentType,accountPatch:U.accountPatch,sessionId:U.sessionId,nonce:U.nonce}),V(!1),F?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:k,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),y?.(Ne.current),u.resolve()},onConfirm:C,onCancel:()=>{let u=Ft.current.get(ve);Ft.current.delete(ve);let M=Mt.current,I=F?.now()??globalThis.performance?.now()??Date.now();if(u&&M?.generation===u.generation&&(0,c.isWalletSheetRefusedForWindowSize)({method:u.method,elapsedMs:I-M.startedAt,handoffObserved:Lt.current===u.generation})){F?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:u.generation,walletType:"google_pay"}),Ve.current=null,ct(u.method,new Error("The browser window is too small for the Google Pay sheet."),c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,u.generation,!0);return}F?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),$e(u?.generation),Ve.current=null,V(!1),_e.current=!0,xt()},options:{...Bi,paymentMethods:ce,emailRequired:kt,billingAddressRequired:kt}},ve),[Z,ce,C,$e,y,kt,ct,gt,xt,g,le,ve,F]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)($a,{state:oe,placeholderTestId:"flopay-wallet-placeholder",borderRadius:R,children:(0,l.jsxs)("div",{ref:Ze,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[ee&&(0,l.jsxs)("button",{ref:Le,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Jt,style:Gs,children:["Try ",Ys(ut)," again"]}),Pe!=="idle"&&(0,l.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,l.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,l.jsx)("button",{type:"button",onClick:B,disabled:Pe==="checking",style:Gs,children:Pe==="checking"?"Checking payment status\u2026":"Check payment status"})]}),mt&&(0,l.jsx)(da,{identity:mt.identity,methodLabel:mt.methodLabel,onComplete:Je,onCancel:()=>Je(null)},mt.id),(0,l.jsxs)("div",{style:{display:mt||Pe!=="idle"?"none":void 0},children:[(0,l.jsx)(dp,{active:K}),ae]})]})}),Re&&(0,l.jsx)(on,{status:"processing"})]})}function rd(e,t,r){let n=(0,c.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function Xs({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:d,onTokenizedBody:p,onErrorChange:y,onDecline:S,onCancel:P,runBeforeButtonClick:g,onButtonClick:_,isProcessing:W,submitButtonColor:$,submitButtonBorderRadius:R,submitButtonStyle:x,errorText:f}){let H=co(),{emitInstrument:X}=(0,o.useContext)(vn),v=(0,cr.useStripe)(),be=(0,cr.useElements)(),[F,oe]=(0,o.useState)(!1),he=(0,o.useRef)(!1),[Re,pe]=(0,o.useState)(!1),[kt,mt]=(0,o.useState)("loading"),[j,Je]=(0,o.useState)(""),Ze=!(0,c.isValidEmail)(n?.trim()),Le=!Ze||(0,c.isValidEmail)(j.trim()),ve=(0,o.useCallback)(async()=>{if(!v||!be||W||he.current||!Re)return;he.current=!0,oe(!0);let Y=g?await g("card"):{proceed:!0};if(!Y.proceed){he.current=!1,oe(!1);return}_?.("card");let K=Y.sessionId??t,rt=Y.nonce??r,Se=(0,la.splitFullName)(a?.trim()),Ke=(0,Cn.compactBuyerIdentity)({email:Y.accountPatch?.email?.trim()||n?.trim()||j.trim(),firstName:Y.accountPatch?.firstName?.trim()||Se.firstName,lastName:Y.accountPatch?.lastName?.trim()||Se.lastName}),ee=Ke.email,V=(0,Cn.compactBuyerIdentity)({...Y.accountPatch,...Ke});try{if(y?.(null),!(0,c.isValidEmail)(ee))throw new Error("A valid email address is required for payment.");await s?.(Ke);let Pe=await be.submit();if(Pe.error){y?.(Pe.error.message??"Payment failed.");return}let J=[Ke.firstName,Ke.lastName].filter(Boolean).join(" "),ut=await v.createPaymentMethod({elements:be,params:{billing_details:{email:ee,...J?{name:J}:{}}}});if(ut.error||!ut.paymentMethod){y?.(ut.error?.message??"Failed to create payment method.");return}let ye=ut.paymentMethod;if(!K||!ee)throw new Error("Missing sessionId or email for payment.");let ke=ye.type||e,xe=await ji(d,X,K,rt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ke,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(xe)){p({type:"card",gateway:"stripe",paymentMethodType:ke},{accountPatch:V,paymentMethodCategory:"apm",sessionId:K,nonce:rt,settledProcessResponse:xe.response});return}if(xe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let _e=xe.clientSecret;dr(Qn,{clientSecret:_e,sessionId:K,nonce:rt,accountPatch:V,paymentMethodId:ye.id,paymentMethodType:ye.type??e,gateway:"stripe"});let{error:vt,paymentIntent:Ne}=await v.confirmPayment({clientSecret:_e,confirmParams:{return_url:window.location.href,payment_method:ye.id},redirect:"if_required"});if(vt){dr(Qn);let We=vt.message??"Payment failed.";y?.(We),S?.(Sr("card",We,{code:vt.code})),await Vi({billingApiUrl:d,sessionId:K,nonce:rt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:vt.code??"provider_declined"}});return}let ft=Ne?.status;if(!Aa(ft)){dr(Qn);let We=ft==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(We),S?.(Sr("card",We,{code:ft??"missing_payment_intent"}));return}dr(Qn);let Ve=typeof Ne?.payment_method=="string"?Ne.payment_method:Ne?.payment_method?.id;p({id:Ve??ye.id,type:"card",threeDSecureActionResultTokenId:Ne?.id,gateway:"stripe",paymentMethodType:ye.type??e},{accountPatch:V,paymentMethodCategory:"apm",sessionId:K,nonce:rt})}catch(Pe){y?.(Pe instanceof Error?Pe.message:"Payment failed. Please try again.")}finally{he.current=!1,oe(!1)}},[v,be,W,Re,g,_,t,r,n,a,j,s,d,X,e,p,y,S]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Ze&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Ze&&(0,l.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,l.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:j,onChange:Y=>Je(Y.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(cr.PaymentElement,{onReady:()=>mt("ready"),onLoadError:()=>{mt("load_error"),Zs(wr(H),"stripe","apm")},onChange:Y=>{pe(!!Y.complete)},options:{layout:Oi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,c.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,l.jsx)(Di,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ve()},disabled:!Re||!Le||F||W||kt!=="ready",color:$,borderRadius:R,style:x,children:F?"Processing\u2026":`Pay with ${(0,c.getStripeMethodDisplayName)(e)}`}),f&&(0,l.jsx)(ya,{margin:"0.75rem 0 0",children:f})]})}function Jc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:d,stripeInstance:p,paymentElementBaseOptions:y,futureUseSession:S,onTokenizedBody:P,onErrorChange:g,onButtonClick:_,onDecline:W,runBeforeButtonClick:$,onLoadStateChange:R,isProcessing:x=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:H=8,submitButtonStyle:X,buttonAppearance:v,themeId:be,onExpandApm:F,expandedApmMethod:oe}){let{emitInstrument:he}=(0,o.useContext)(vn),[Re,pe]=(0,o.useState)(null),[kt,mt]=(0,o.useState)(null),j=(0,o.useRef)(!1),{request:Je,collect:Ze,finish:Le}=ca();(0,o.useEffect)(()=>{d.length>0&&p?R?.("ready"):p||R?.("loading")},[d.length,p,R]);let ve=(0,o.useCallback)(async ee=>{if(!p||j.current||x)return;j.current=!0,mt(ee);let V=$?await $("card"):{proceed:!0};if(!V.proceed){j.current=!1,mt(null);return}_?.("card");let Pe=V.sessionId??e,J=V.nonce??t,ut=(0,la.splitFullName)([V.accountPatch?.firstName,V.accountPatch?.lastName].filter(Boolean).join(" ")||n),ye=(0,Cn.compactBuyerIdentity)({email:V.accountPatch?.email?.trim()||r?.trim(),firstName:V.accountPatch?.firstName?.trim()||ut.firstName,lastName:V.accountPatch?.lastName?.trim()||ut.lastName});if(!(0,c.isValidEmail)(ye.email)){mt(null);let _e=await Ze((0,c.getStripeMethodDisplayName)(ee),ye);if(!_e){j.current=!1;return}ye=_e,mt(ee)}let ke=ye.email,xe=(0,Cn.compactBuyerIdentity)({...V.accountPatch,...ye});try{if(g?.(null),!Pe||!(0,c.isValidEmail)(ke))throw new Error("Missing sessionId or email for payment.");await a?.(ye);let _e=await ji(s,he,Pe,J??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(_e)){P({type:"card",gateway:"stripe",paymentMethodType:ee},{accountPatch:xe,paymentMethodCategory:"apm",sessionId:Pe,nonce:J,settledProcessResponse:_e.response});return}if(_e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let vt=_e.clientSecret;dr(Qn,{clientSecret:vt,sessionId:Pe,nonce:J,accountPatch:xe,paymentMethodType:ee,gateway:"stripe"});let{error:Ne,paymentIntent:ft}=await p.confirmPayment({clientSecret:vt,confirmParams:{return_url:window.location.href,payment_method_data:{type:ee,billing_details:{name:[ye.firstName,ye.lastName].filter(Boolean).join(" "),...ke?{email:ke}:{}}}},redirect:"if_required"});if(Ne){dr(Qn);let Mt=Ne.message??"Payment failed.";g?.(Mt),W?.(Sr("card",Mt,{code:Ne.code})),await Vi({billingApiUrl:s,sessionId:Pe,nonce:J,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,providerDeclineReason:Ne.code??"provider_declined"}});return}let Ve=ft?.status;if(!Aa(Ve)){dr(Qn);let Mt=Ve==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(Mt),W?.(Sr("card",Mt,{code:Ve??"missing_payment_intent"}));return}dr(Qn);let We=typeof ft?.payment_method=="string"?ft.payment_method:ft?.payment_method?.id;P({id:We??ft?.id,type:"card",threeDSecureActionResultTokenId:ft?.id,gateway:"stripe",paymentMethodType:ee},{accountPatch:xe,paymentMethodCategory:"apm",sessionId:Pe,nonce:J})}catch(_e){g?.(_e instanceof Error?_e.message:"Payment failed. Please try again.")}finally{j.current=!1,mt(null)}},[p,x,$,_,e,t,r,Ze,s,he,n,a,P,g,W]),[Y,K]=(0,o.useState)(null),rt=F?oe??null:Y,Se=(0,o.useCallback)(ee=>{j.current||x||rt&&rt!==ee||((0,c.needsStripeMethodExplicitConfirm)(ee)?F?F(ee):K(ee):ve(ee))},[rt,x,ve,F]),Ke=(0,o.useMemo)(()=>Y?rd(y,Y,S):null,[Y,y,S]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Je?(0,l.jsx)(da,{identity:Je.identity,methodLabel:Je.methodLabel,onComplete:Le,onCancel:()=>Le(null)},Je.id):d.map(ee=>{let V=oe===ee,Pe=kt===ee,J=kt!==null&&kt!==ee||oe!=null&&oe!==ee;return(0,l.jsxs)(o.default.Fragment,{children:[(0,l.jsx)(xi,{method:ee,themeId:be,submitting:Pe,disabled:J,highlighted:V,hasNextStep:(0,c.needsStripeMethodExplicitConfirm)(ee),onClick:()=>Se(ee),backgroundColor:v?.backgroundColor,borderColor:v?.borderColor,textColor:v?.textColor,borderRadius:v?.borderRadius,fontFamily:v?.fontFamily}),!F&&Y===ee&&Ke&&p&&(0,l.jsx)(cr.Elements,{stripe:p,options:Ke,children:(0,l.jsx)(Xs,{method:ee,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:P,onErrorChange:g,onDecline:W,onCancel:()=>K(null),runBeforeButtonClick:$,onButtonClick:_,isProcessing:x,submitButtonColor:f,submitButtonBorderRadius:H,submitButtonStyle:X})},ee)]},ee)})})}function up({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:d,onError:p,onDecline:y,onCancel:S,onTokenizedBody:P,firstName:g,lastName:_,chv:W,className:$,submitLabel:R,isProcessing:x,error:f,onErrorChange:H,showPayPal:X=!0,showStripe:v=!0,walletPresentation:be="auto",enabledPaymentMethods:F,enabledPaymentMethodCountries:oe,showApplePay:he=!0,showGooglePay:Re=!0,layout:pe="default",paymentMethodLayout:kt,moreOptionsLabel:mt,theme:j,buttonsTheme:Je,buttonsStyles:Ze,appearance:Le,cardButtonContent:ve,cardBackButtonContent:Y,cardTitleContent:K,showSecurityFooter:rt,onButtonClick:Se,onBeforeButtonClick:Ke,onBuyerIdentityReady:ee,enableAVS:V,cardFieldOrder:Pe,showCardBrandIcons:J,showCardFieldLabels:ut,cardFieldLabels:ye,cardFieldPlaceholders:ke,cardAutoFocus:xe,onCardFieldsReady:_e,onCardFieldsFailed:vt,cardFieldsTimeoutMs:Ne,cardPreFormSlot:ft,avsLayout:Ve="row",country:We,zip:Mt,addressLine1:Lt,addressLine2:Ft,city:le,state:Ee,onCountryChange:$e,onZipChange:Ct,avsCheck:bt,checkoutType:st,checkoutLayout:pt,totalAmount:At=0,currency:xt="usd",initialCardOpen:lt=!1,directPaypal:ct,isSubscription:gt=!1,session:G,dataAttachmentPending:Jt=!1,dataAttachmentRequiresIdentity:B=!1,debug:C=!1}){let ce=co(),Z=vi(),ae=(0,o.useContext)(Bn),{emitInstrument:u}=(0,o.useContext)(vn),M=(0,o.useRef)(null);M.current||(M.current=bi());let I=M.current,[,ie]=(0,o.useState)(0),U=(0,o.useRef)(null);U.current||(U.current=(0,Xn.detectPayPalEnvironment)());let k=U.current,tt=(0,o.useMemo)(()=>({browser:k,capability:I,presentationMode:"popup"}),[k,I]),Ht=G??ae.session,Kt=(0,o.useMemo)(()=>({futureUse:Ht?.futureUse,futureUseUnsupported:Ht?.futureUseUnsupported}),[Ht?.futureUse,Ht?.futureUseUnsupported]),Vr=Ht?.gateways?.paypal?.providerObjectType??ct?.providerObjectType,He=Jt||ae.claimPending===!0,Un=B||ae.claimRequiresIdentity===!0,Pr=He&&!Un,vr=hc(),Et=r||vr,jt=zc({rules:kt,sessionId:e,nonce:t,billingApiUrl:Et,waitForSession:Pr}),Or=jt?.order??null,[Qr,Dr]=(0,o.useState)(!1),Ar=(0,o.useMemo)(()=>Or?(0,c.keyPaymentMethodOrder)(Or):null,[Or]),xr=Or!==null&&(0,c.isCardFormFirst)(Or),[tr,Gt]=(0,o.useState)(!1),[or,St]=(0,o.useState)(null),[Fe,un]=(0,o.useState)(We??""),[Vt,Lr]=(0,o.useState)(Mt??""),[Wr,pn]=(0,o.useState)(Lt??""),[$r,zn]=(0,o.useState)(Ft??""),[En,Cr]=(0,o.useState)(le??""),[br,Nr]=(0,o.useState)(Ee??""),[en,Hr]=(0,o.useState)(""),[Ur,pr]=(0,o.useState)({}),ar=(0,o.useRef)(Mt??""),ir=(0,o.useRef)(We??""),rr=(0,o.useRef)(Lt??""),Kr=(0,o.useRef)(Ft??""),Gr=(0,o.useRef)(le??""),zr=(0,o.useRef)(Ee??""),L=(0,o.useRef)(""),ht=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(b,z,ge,Q,De)=>{if(ht.current[b])return;let Ut=z?.trim();!Ut||Ut===ge.current||(ge.current=Ut,Q(Ut),De?.(Ut))};i("country",We,ir,un,$e),i("zip",Mt,ar,Lr,Ct),i("addressLine1",Lt,rr,pn),i("addressLine2",Ft,Kr,zn),i("city",le,Gr,Cr),i("state",Ee,zr,Nr)},[We,Mt,Lt,Ft,le,Ee,$e,Ct]);let T=(0,o.useMemo)(()=>(0,c.resolveAVSConfig)(V),[V]),Ie=T!==null,Tt=(0,o.useMemo)(()=>(0,c.isAuthorizationOnlySession)(G),[G]),Pt=(0,c.isMountableVaultBlock)(G?.vault),Yt=!!G?.gateways?.pcivault,Ge=(0,Fn.hasServerSideCardGateway)(G),ro=!!(G?.gateways?.stripe?.enabledPaymentMethods??F)?.includes("card")||(0,Fn.canRecoverHostedCardForm)(G),Fr=Pt||ro||Yt,Be=!!(v&&Fr&&e),[fo,_o]=(0,o.useState)(()=>pe!=="buttons"||lt?e??null:null),[Io,_n]=(0,o.useState)(0),yn=pe!=="buttons"||lt||!!e&&fo===e,sn=G?.captureMethod,tn=(0,o.useRef)(ce);(0,o.useEffect)(()=>{tn.current=ce},[ce]);let Wt=(0,o.useRef)(Ne);Wt.current=Ne;let jn=(0,o.useRef)({onCardFieldsReady:_e,onCardFieldsFailed:vt,emitInstrument:u});jn.current={onCardFieldsReady:_e,onCardFieldsFailed:vt,emitInstrument:u};let[Br,mn]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!Be||!e||!yn){mn(null);return}let i=tn.current?tn.current.cardCapture({sessionId:e,captureMethod:sn,cardFieldsTimeoutMs:Wt.current}):new Nn.PciVaultCardCapture({sessionId:e,captureMethod:sn,billingApiUrl:Et,telemetry:n,cardFieldsTimeoutMs:Wt.current}),b=i.onCardFields?.(z=>{let ge=jn.current;ge.emitInstrument?.((0,c.cardFieldsInstrumentSource)(z)),z.type==="card_fields_ready"?(0,c.invokeMerchantCallback)(()=>ge.onCardFieldsReady?.(z)):(0,c.invokeMerchantCallback)(()=>ge.onCardFieldsFailed?.(z))});return mn({sessionId:e,captureMethod:sn,billingApiUrl:Et,telemetry:n,capture:i}),()=>{b?.(),i.unmount()}},[Be,e,yn,sn,Et,n]);let Ue=Be&&e&&yn&&Br?.sessionId===e&&Br.captureMethod===sn&&Br.billingApiUrl===Et&&Br.telemetry===n?Br.capture:null,qr=(0,o.useMemo)(()=>{let i=Fe,b=T?(0,c.isAVSFieldVisible)(T.postal_code,i):!1;return op(i,Vt,b)},[T,Fe,Vt]),{avsInvalid:In,invalidAvsFields:Vn}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Be||!T)return{avsInvalid:!1,invalidAvsFields:i};let b=Fe,z=(De,Ut)=>(0,c.isAVSFieldVisible)(De,b)&&!Ut.trim(),ge={line1:z(T.address_line_1,Wr),city:z(T.city,En),state:z(T.state,br),zip:qr.empty||qr.malformed};return{avsInvalid:ge.line1||ge.city||ge.state||ge.zip,invalidAvsFields:ge}},[Be,T,Fe,Wr,En,br,qr]),[fn,Wn]=(0,o.useState)(!1),[$n,To]=(0,o.useState)(!1),[no,go]=(0,o.useState)(!1),[ho,Wo]=(0,o.useState)({line1:!1,city:!1,state:!1}),Hn=(0,o.useRef)(!1),Tn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Po=(0,o.useRef)(!1),Nt=(0,o.useCallback)(i=>{Tn.current[i]=!0,Po.current=!0},[]),oo=(0,o.useCallback)(i=>!Hn.current&&Tn.current[i],[]),rn=(0,o.useCallback)(i=>{oo(i)&&Wo(b=>b[i]?b:{...b,[i]:!0})},[oo]),[gn,_r]=(0,o.useState)(()=>(0,c.resolveVaultMountOptions)(G?.vault,{billingApiUrl:Et,sessionId:e,nonce:t})),[ot,yr]=(0,o.useState)(lt&&Fr?"card":"buttons"),[Zt,D]=(0,o.useState)(null),q=ot==="expanding"||ot==="card",se=G?.gateways?.stripe&&!Ge?"stripe":void 0,fe=(0,o.useCallback)(()=>{u?.({class:"card_surface",provider:se})},[se,u]),Ot=(0,o.useCallback)(()=>{Dr(!0),u?.({class:"more_options"})},[u]),Qt=(0,o.useRef)(null),me=(0,o.useCallback)(i=>{Qt.current&&clearTimeout(Qt.current),Qt.current=setTimeout(()=>{Qt.current=null,i()},Ja)},[]);(0,o.useEffect)(()=>()=>{Qt.current&&clearTimeout(Qt.current)},[]);let at=(0,o.useRef)(!1),[re,h]=(0,o.useState)(0),m=(0,o.useRef)(null),N=(0,o.useCallback)(()=>{fe(),_o(e??null),at.current&&(at.current=!1,h(i=>i+1)),_n(i=>i+1),yr("expanding"),me(()=>yr("card"))},[me,fe,e]),A=(0,o.useCallback)(()=>{yr("collapsing"),me(()=>yr("buttons"))},[me]),te=(0,o.useCallback)(i=>{D(i),yr("apm-expanding"),me(()=>yr("apm-form"))},[me]),Te=(0,o.useCallback)(()=>{yr("apm-collapsing"),me(()=>{yr("buttons"),D(null)})},[me]);(0,o.useEffect)(()=>{pe==="buttons"&<&&Fr&&(_o(e??null),yr("card"))},[pe,lt,Fr,e]);let[Rt,Me]=(0,o.useState)(null),Oe=(0,o.useRef)(null),[ze,qt]=(0,o.useState)(0);(0,o.useEffect)(()=>{ze!==0&&Oe.current?.focus()},[ze]);let Ae=(0,o.useRef)(!1),ne=(0,o.useRef)(null),ue=(0,o.useRef)("idle"),[Ce,Ye]=(0,o.useState)(!1),$t=(0,o.useRef)(Ce);$t.current=Ce;let[yt,va]=(0,o.useState)(()=>ct?.existingOrderId?{orderId:ct.existingOrderId,attempts:1}:null),pl=(0,o.useRef)(yt);(0,o.useEffect)(()=>{pl.current=yt},[yt]);let Qi=(0,o.useRef)(null),Ed=(0,o.useMemo)(()=>{if(ee||ae.claimBuyerIdentity||G?.buyerIdentified!==!1||!e||!t)return;let i=`${Et}|${e}|${t}`;Qi.current?.key!==i&&(Qi.current={key:i,claim:ia(new Nn.PaymentAPI(Et,{telemetry:!1}),e,t,{...s?{userId:s}:{},...g?{firstName:g}:{},..._?{lastName:_}:{}})});let b=Qi.current.claim;return async z=>{await b(z)}},[ee,ae.claimBuyerIdentity,G?.buyerIdentified,e,t,Et,s,g,_]),hn=ee??ae.claimBuyerIdentity??Ed,Mn=f??or,$o=(0,o.useMemo)(()=>(0,c.resolveTheme)(j),[j]),nt=(0,o.useMemo)(()=>{let i=$o?.buttonsLayout??(0,c.resolveButtonsLayoutTheme)(Je);return Ze?{...i,...Ze,cardButton:{...i.cardButton,...Ze.cardButton},cardFormContainer:{...i.cardFormContainer,...Ze.cardFormContainer},backButton:{...i.backButton,...Ze.backButton},backButtonIcon:{...i.backButtonIcon,...Ze.backButtonIcon},submitButton:{...i.submitButton,...Ze.submitButton},title:{...i.title,...Ze.title}}:i},[$o,Je,Ze]),Ho=Le??$o?.appearance,_d=(0,o.useMemo)(()=>(0,c.computeVaultCardThemeColors)({appearance:Ho,buttonsStyles:nt,layout:pe}),[Ho,nt,pe]),Id=ae.inlineSessionPatchProcessing??!1,sr=(x??tr)||Id,vo=Et.replace(/\/+$/,""),Bt=(0,o.useMemo)(()=>Fs({userId:s,email:a,firstName:g,lastName:_,country:We,zip:Mt},Ur),[s,a,g,_,We,Mt,Ur]),Ko=[Bt.firstName,Bt.lastName].filter(i=>!!i?.trim()).join(" "),yl=!(0,c.isValidEmail)(Bt.email?.trim()),es=(0,o.useRef)(null);Be&&es.current===null&&(es.current=yl);let Co=Be&&(es.current??yl),ts=(0,o.useMemo)(()=>ap(en,Co),[en,Co]),Go=ts.empty||ts.malformed,ln=(0,o.useMemo)(()=>ce?ce.getRawProvider():null,[ce]),ml=(0,o.useMemo)(()=>Z?Z.getRawProvider():null,[Z]),Ca=At||100,Yo=xt.toLowerCase(),rs=(0,o.useMemo)(()=>Ho?(0,Nn.toStripeAppearance)(Ho):null,[Ho]),Xo=rs,fl=(0,o.useMemo)(()=>{let i=rs??{},b=i.rules??{};return{...i,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[rs]),gl=(0,o.useMemo)(()=>({...mc(At,Ht?.captureMethod,Kt),currency:Yo,...Xo?{appearance:Xo}:null}),[At,Yo,Ht?.captureMethod,Kt,Xo]),ns=(0,c.resolveSetupFutureUsage)(Kt,"paypal","paypal"),hl=(0,o.useMemo)(()=>({mode:"payment",amount:Ca,currency:Yo,captureMethod:"manual",...ns?{setupFutureUsage:ns}:null,...Xo?{appearance:Xo}:null}),[Ca,Yo,ns,Xo]),qe=(0,o.useCallback)(i=>{St(i),H?.(i)},[H]),Pl=(0,o.useRef)(0);(0,o.useEffect)(()=>{re!==Pl.current&&(Pl.current=re,qe(null))},[re,qe]);let os=(0,o.useRef)(""),[vl,Td]=(0,o.useState)(!1),as=(0,o.useCallback)(()=>{Td(!0)},[]);(0,o.useEffect)(()=>{if(!Be||!Co||!hn||!vl||Go||os.current)return;let i=(0,Cn.compactBuyerIdentity)({email:(0,c.isValidEmail)(Bt.email?.trim())?Bt.email?.trim():L.current.trim(),firstName:Bt.firstName?.trim(),lastName:Bt.lastName?.trim()});os.current=JSON.stringify(i),pr(b=>({...b,...i})),Promise.resolve(hn(i)).catch(b=>{os.current="",qe(b instanceof Error?b.message:"Failed to attach buyer details.")})},[Be,Co,hn,vl,Go,Bt.email,Bt.firstName,Bt.lastName,qe]),(0,o.useEffect)(()=>{if(!Be||!Ue)return;let i=xe!==!1&&T==null&&!Co;Ue.setCardFieldOrder?.(Pe??null,i)},[Be,Ue,Pe,xe,T,Co]),(0,o.useEffect)(()=>{!Be||!Ue||Ue.setCardBrandIcons?.(J===!0)},[Be,Ue,J]);let is=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(!(!Be||!Ue)){if(ut===void 0){if(is.current!==Ue)return;is.current=null,Ue.setShowCardFieldLabels?.(!1);return}is.current=Ue,Ue.setShowCardFieldLabels?.(ut===!0)}},[Be,Ue,ut]);let ss=ye===void 0?void 0:JSON.stringify((0,c.buildCardFieldLabelsPayload)(ye)),ls=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(!(!Be||!Ue)){if(ss===void 0){if(ls.current!==Ue)return;ls.current=null,Ue.setCardFieldLabels?.(null);return}ls.current=Ue,Ue.setCardFieldLabels?.(JSON.parse(ss))}},[Be,Ue,ss]);let cs=lp(ke),ds=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(!(!Be||!Ue)){if(cs===null){if(ds.current!==Ue)return;ds.current=null,Ue.setCardFieldPlaceholders?.(void 0);return}ds.current=Ue,Ue.setCardFieldPlaceholders?.(JSON.parse(cs))}},[Be,Ue,cs]),(0,o.useEffect)(()=>{(ot==="expanding"||ot==="collapsing"||ot==="apm-expanding"||ot==="apm-collapsing")&&qe(null)},[ot,qe]);let Kn=(0,o.useCallback)((i,b,z)=>{y?.(Sr(i,b,z))},[y]),Cl=(0,o.useRef)(ot);Cl.current=ot;let[bl]=(0,o.useState)(wi),Sl=(0,o.useCallback)(()=>{let i=Cl.current;if(pe==="buttons"&&(i==="card"||i==="expanding"))return!0;let b=ue.current;return b==="validation-window"||b==="processing"||$t.current},[pe]),wl=(0,o.useCallback)((i,b,z)=>{bl.take(e)&&wr(ce)?.log(No({...tt,presentationMode:z?.presentationMode??"popup"},{name:Si,stage:"recovery",reason:"other_method_active",provider:z?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:z?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[tt,ce,bl,e]),ri=(0,o.useCallback)((i,b,z)=>{z?.telemetryReported||wr(ce)?.error(No({...tt,presentationMode:z?.presentationMode??"popup"},{errorCode:b?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:z?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:z?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:z?.terminalReason??(b?"popup_blocked":"provider_error")}))},[tt,ce]),Jo=(0,o.useCallback)((i,b,z)=>{let ge=z?.popupBlocked??(0,we.isPopupBlockedError)(b);if(Sl()){ri(i,ge,z),wl(i,b,z);return}if(b instanceof c.FloPayError&&b.code==="checkout_processing_timeout"){ri(i,!1,z),Me(null),pe==="buttons"&&(yr("buttons"),D(null)),qe(b.message),p?.(b);return}ge&&I.markBlocked()&&ie(_t=>_t+1);let Q=Ys(i),De=z?.code===c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,c.buildWalletSheetWindowMessage)(Q):(0,we.buildExternalMethodRecoveryMessage)(Q,ge,k.inAppBrowser),Ut=(0,we.getProviderErrorCode)(b),zt=(Ut?.toLowerCase()==="error"?void 0:Ut)??(0,we.sanitizeExternalFailureCode)(z?.code)??"external_payment_method_failed",it=new c.FloPayError(De,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:zt,popupBlocked:ge,inAppBrowser:k.inAppBrowser,appFamily:k.appFamily,popupCapability:I.current(),presentationMode:z?.presentationMode??"popup"}});ri(i,ge,z),Me(null),pe==="buttons"&&(yr("buttons"),D(null)),qe(De),p?.(it),console.error("[FloPay] External payment method failed:",{method:i,code:zt,popupBlocked:ge})},[k,Sl,pe,p,I,wl,ri,qe]);(0,o.useEffect)(()=>{if(!Be||!e){_r(null);return}let i={billingApiUrl:vo,sessionId:e,nonce:t},b=(0,c.resolveVaultMountOptions)(G?.vault,i);if(b){_r(b);return}if(!yn){_r(null);return}let z=`${vo}\0${e}\0${t??""}`,ge=m.current;if(ge&&ge.key===z){_r(ge.mount);return}_r(null);let Q=!0;return new Nn.PaymentAPI(vo).getVaultCapture(e,t).then(De=>{if(!Q)return;let Ut=(0,c.resolveVaultMountOptions)(De,i);Ut?.verificationRequired&&!De.html&&(m.current={key:z,mount:Ut}),Ut?_r(Ut):qe("Failed to load the secure card form.")}).catch(De=>{Q&&qe(De instanceof Error?De.message:"Failed to load the secure card form.")}),()=>{Q=!1}},[Be,yn,Io,e,G?.vault,vo,t,qe]);let An=(0,o.useRef)({onComplete:d,onError:p,updateError:qe,emitDecline:Kn,resolvedAccount:Bt,avsConfig:T,avsCheckProp:bt,sessionId:e,nonce:t,baseUrl:vo,captureMethod:G?.captureMethod,paymentId:G?.paymentId,authorizationExpiresAt:G?.authorizationExpiresAt,serverSideCardGateway:Ge});An.current={onComplete:d,onError:p,updateError:qe,emitDecline:Kn,resolvedAccount:Bt,avsConfig:T,avsCheckProp:bt,sessionId:e,nonce:t,baseUrl:vo,captureMethod:G?.captureMethod,paymentId:G?.paymentId,authorizationExpiresAt:G?.authorizationExpiresAt,serverSideCardGateway:Ge};let us=(0,o.useRef)(!1),Rl=(0,o.useCallback)(()=>{let i=An.current,b=i.resolvedAccount.email?.trim(),z=(0,c.isValidEmail)(b)?b:L.current.trim();if(!(0,c.isValidEmail)(z))return null;let ge=i.resolvedAccount.firstName?.trim(),Q=i.resolvedAccount.lastName?.trim(),De=ir.current.trim()||i.resolvedAccount.country?.trim()||"",Ut=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.state,De):!1,zt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_1,De):!1,it=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.postal_code,De):!1,_t=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.city,De):!1,Dt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_2,De):!1,mr=zt&&!Ut&&it?(0,c.getStateFromPostalCode)(De,(ar.current??"").trim()):null,cn=Ut?zr.current:mr;return{accountData:{userId:i.resolvedAccount.userId??"",email:z,...ge?{firstName:ge}:{},...Q?{lastName:Q}:{},...it&&ar.current?{zip:ar.current}:{},..._t&&Gr.current?{city:Gr.current}:{},...cn?{state:cn}:{},...zt&&rr.current?{addressLine1:rr.current}:{},...Dt&&Kr.current?{addressLine2:Kr.current}:{},...De?{country:De}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,c.isAVSFieldVisible)(i.avsConfig.country,De),postal_code:it,address_line_1:zt,address_line_2:Dt,city:_t,state:Ut}}:{}}},[]),kl=(0,o.useRef)(He);kl.current=He,(0,o.useEffect)(()=>{He||Mn!==$c||An.current.updateError(null)},[He,Mn]),(0,o.useEffect)(()=>{!Be||!Ue||Ue.setSubmitGate?.(In||He||Go||Ce)},[Be,Ue,In,He,Go,Ce]),(0,o.useEffect)(()=>{if(!Be||!Ue)return;us.current=!1;let i=null,b=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,ue.current="idle",Me(null)},400)},z=Ue.on("submitting",()=>{Wn(!0),ne.current&&clearTimeout(ne.current),ue.current="validation-window",ne.current=setTimeout(()=>{ne.current=null,ue.current==="validation-window"&&(ue.current="processing")},Gu),Me("processing");let it=An.current;if(!it.sessionId||!it.nonce)return;let _t=Rl();if(!_t){it.updateError("Enter a valid email address."),ue.current="idle",Me(null);return}new Nn.PaymentAPI(it.baseUrl).patchAccountSnapshot(it.sessionId,it.nonce,_t,{telemetryMode:"best_effort"}).catch(Dt=>{if(!Xu(Dt))return;let mr=Dt instanceof Error?Dt.message:"Please check your billing address and try again.";it.updateError(mr),ue.current="idle",Me(null),it.onError?.(Dt instanceof c.FloPayError?Dt:new c.FloPayError(mr,"api_error"))})}),ge=Ue.on("complete",it=>{(0,Dn.markSessionRecentlyCompleted)(it.sessionId??An.current.sessionId),ue.current="terminal",Ye(!1),Me("success"),setTimeout(()=>{if(us.current)return;us.current=!0;let _t=An.current,Dt=(0,c.isAuthorizationOnlySession)(_t)||it.outcome==="authorized",mr=_t.serverSideCardGateway?{}:{paymentIntentId:it.intentId};An.current.onComplete?.(Dt?{status:"authorized",...mr,paymentId:it.paymentId??_t.paymentId,sessionId:it.sessionId??_t.sessionId,authorizationExpiresAt:it.authorizationExpiresAt??_t.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...mr,checkoutMethod:"card"})},600)}),Q=Ue.on("decline",it=>{let _t=An.current,Dt=it.message??"Your payment was declined. Please try another card or contact your bank.";ue.current="terminal",Ye(!1),_t.updateError(Dt),Me("error");let mr=it.failureOutcome??(0,c.normalizeCheckoutFailureOutcome)(it.declineReason)??"authorization_declined";_t.emitDecline("card",Dt,{code:mr,declineCode:mr}),b()}),De=Ue.on("error",it=>{let _t=An.current,Dt=(0,c.buyerEmailRequiredPrompt)(it.vaultOutcome);if(Dt!==null){i&&(clearTimeout(i),i=null),ue.current="idle",Ye(!1),_t.updateError(Dt),Me(null),qt(cn=>cn+1),_t.onError?.(new c.FloPayError(Dt,"api_error",{code:c.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let mr=it.message??"There was a problem processing your payment. Please try again.";ue.current="terminal",Ye(!1),_t.updateError(mr),Me("error"),_t.onError?.(new c.FloPayError(mr,"api_error",{code:it.failureOutcome??"capture_failed"})),b()}),Ut=Ue.on("challenge_dismissed",()=>{ne.current&&(clearTimeout(ne.current),ne.current=null),ue.current="processing",Ye(!0),Me(null)}),zt=Ue.on("blocked",()=>{if($t.current){An.current.updateError(Yu);return}if(!kl.current){Wn(!0);return}as(),An.current.updateError($c)});return()=>{i&&(clearTimeout(i),i=null),ne.current&&(clearTimeout(ne.current),ne.current=null),ue.current="idle",Ye(!1),Me(null),z(),ge(),Q(),De(),Ut(),zt()}},[Be,Ue,as,Rl]);let Gn=!!ct?.clientId,ba=Array.isArray(F),ni=ba&&F.length>0,El=ba&&F.includes("paypal"),oi=(0,o.useRef)(null);oi.current===null&&(oi.current=(0,c.hasMatchingStripePayPalReturn)());let Zo=oi.current?"redirect":(0,Jn.resolveStripePayPalPresentation)(k,be,I.current()),{expressMethods:ai,paymentElementMethods:ps}=(0,o.useMemo)(()=>(0,c.partitionStripeMethods)(F,{excludePaypal:Gn}),[F,Gn]),_l=Gn||!!Z||El&&Zo==="redirect",Md=(0,o.useMemo)(()=>_l?ai.filter(i=>i!=="paypal"):ai,[ai,_l]),Ad=(0,o.useMemo)(()=>{let i=[];return he&&i.push("apple_pay"),Re&&i.push("google_pay"),i},[he,Re]),Qo=ba?Md:Ad,xd=v&&Qo.length>0,Il=Ie?Fe:We,ii=(0,o.useMemo)(()=>(0,c.filterStripeMethodsByCountryGate)(ps,Il,oe),[ps,Il,oe]),ys=(0,o.useMemo)(()=>({mode:"payment",amount:Ca,currency:Yo,paymentMethodCreation:"manual",appearance:fl}),[Ca,Yo,fl]),[ms,Tl]=(0,o.useState)("loading"),[fs,Ml]=(0,o.useState)("loading"),[gs,Al]=(0,o.useState)("loading"),[Fd,hs]=(0,o.useState)(!1),[xl,Ps]=(0,o.useState)("loading"),[vs,Bd]=(0,o.useState)();(0,o.useEffect)(()=>{Bd((0,Xn.detectPayPalEnvironment)())},[]);let si=vs?.inAppBrowser,li=vs?(0,Jn.resolvePayPalPresentationMode)(vs,ct?.approvalPresentation,Vr??(gt?"subscription":"order")):"popup",Fl=X&&(Gn||(ba?El:si===!1)),Od=k.inAppBrowser&&I.current()==="blocked",Bl=v&&xd&&!Od,Mo=(!Pr||!!ae.waitForDataAttachment)&&Fl&&Gn,Cs=xl==="retrying"||xl==="exhausted",Sa=null;v&&(Z?Sa=ml:Zo==="redirect"&&(Sa=ln));let Ol=(0,o.useMemo)(()=>({...tt,presentationMode:Zo}),[tt,Zo]),Ao=!Pr&&Fl&&!!Sa&&(!Gn||Cs),bo=!Pr&&Bl&&!!ln,xo=!Pr&&v&&ni&&ii.length>0&&!!ln,Dd=Mo&&!Cs?Fd:Ao&&Ha(ms),Ld=bo&&Ha(fs),Nd=xo&&gs!=="load_error",Dl=[Mo||Ao,bo,xo,Be].filter(Boolean).length,Ud={card:Be,paypal:Mo&&!Cs||Ao&&Ha(ms),wallets:bo&&Ha(fs),apms:xo&&gs!=="load_error"},Ll=i=>Ud[i],Nl=i=>i==="loading"||i==="ready",Ul=Mo||Ao&&Nl(ms)||bo&&Nl(fs)||xo&&gs!=="load_error",ci=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!ci.current){if(!v&&!X){ci.current=!0;let i=new c.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),qe(i.message)}else if(!v&&X&&!Gn){ci.current=!0;let i=new c.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(i),qe(i.message)}else if(si!==void 0&&!Pr&&!Fr&&!Ul){ci.current=!0;let i=new c.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});p?.(i),qe(i.message)}}},[v,X,Gn,si,Pr,Fr,Ul,p,qe]);let zl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(zl.current||!ni)return;let i=[];he!==!0&&i.push("showApplePay"),Re!==!0&&i.push("showGooglePay"),i.length!==0&&(zl.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[ni,he,Re]);let ql=(0,o.useCallback)((i,b,z)=>ae.applyInlineSessionPatch?ae.applyInlineSessionPatch(i).then(ge=>({error:null,sessionId:ge.sessionId||e,nonce:ge.session?.clientSecret||t})).catch(ge=>{let Q=(0,c.normalizeBeforeButtonClickError)(b,ge);return z?.abandoned?.()||(qe(Q.message),p?.(Q)),{error:Q,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ae.applyInlineSessionPatch,t,p,e,qe]),xn=(0,o.useCallback)(async(i,b)=>{if(i!=="card"&&Pr&&await ae.waitForDataAttachment?.(),!Ke)return{proceed:!0};try{let z=await Ke({method:i,sessionId:e||void 0,createSession:ae.inlineSessionDraft});if(z===!1)return{proceed:!1};if(z&&typeof z=="object"){z.account&&pr(Q=>({...Q??{},...z.account}));let ge=await ql(z,i,b);return ge.error?{proceed:!1,accountPatch:z.account}:{proceed:!0,accountPatch:z.account,sessionId:ge.sessionId,nonce:ge.nonce}}return{proceed:!0}}catch(z){if(!b?.abandoned?.()){let ge=(0,c.normalizeBeforeButtonClickError)(i,z);qe(ge.message),p?.(ge)}return{proceed:!1}}},[ql,ae.inlineSessionDraft,ae.waitForDataAttachment,Pr,Ke,p,e,qe]),jl=(0,o.useCallback)(async(i,b)=>{if(Ae.current)return;Ae.current=!0,Gt(!0),Me("processing"),qe(null);let z=b?.sessionId??e,ge=b?.nonce??t,Q=Fs(Bt,b?.accountPatch),De=b?.completionPaymentMethodId??xa(i),Ut=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,zt=ep(i),it=b?.presentationMode?Ai(wr(ce),{...tt,presentationMode:b.presentationMode}):void 0,_t=()=>{u?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:zt}),it?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Ln,requestCategory:"process_payment"})};try{let Dt=new Nn.PaymentAPI(vo),cn=b?.settledProcessResponse??await Dt.processPayment(Q.userId??"",{sessionId:z,nonce:ge,paymentMethodCategory:b?.paymentMethodCategory??rp(i),tokenizedData:Ut,accountData:{...b?.accountPatch,userId:Q.userId??"",email:Q.email??"",firstName:Q.firstName||void 0,lastName:Q.lastName||void 0,...(0,c.buildProcessPaymentAvsAccount)({avsConfig:T,country:ir.current,zip:ar.current,city:Gr.current,state:zr.current,addressLine1:rr.current,addressLine2:Kr.current})},...(0,c.buildCheckoutProcessMetadata)({chv:W,avsCheck:bt,checkoutType:st,checkoutLayout:pt,avsConfig:T,country:ir.current})}),mi=async Ir=>{let Fo=(0,c.isAuthorizationOnlySession)(G)||Ir?.status==="authorized";(0,Dn.markSessionRecentlyCompleted)(z),it?.terminal({outcome:"payment_succeeded",...Ln}),Me("success"),va(null),await new Promise(Ta=>setTimeout(Ta,600));let Yn;typeof Ir?.paymentId=="string"?Yn=Ir.paymentId:G?.paymentId&&(Yn=G.paymentId);let Bo;typeof Ir?.authorizationExpiresAt=="string"?Bo=Ir.authorizationExpiresAt:G?.authorizationExpiresAt&&(Bo=G.authorizationExpiresAt),d?.(Fo?{status:"authorized",...Yn===void 0?{}:{paymentId:Yn},sessionId:typeof Ir?.sessionId=="string"?Ir.sessionId:z,...Bo===void 0?{}:{authorizationExpiresAt:Bo},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:i.isPaypal?"paypal":"card"})};if(cn.ok){await mi(cn.status===204?null:await cn.json().catch(()=>null));return}let fr=await cn.json().catch(()=>null);if(fr?.type==="paypal_redirect_required"){let Ir=fr.threeDSecureToken,Fo=fr.paymentMethodId||i.id||"";if(!ce||!Ir){Me("error"),qe("PayPal authorization required but no token provided.");return}try{let Yn=Z?.getRawProvider();if(!Yn){qe("PayPal is not available.");return}let Bo={return_url:window.location.href};Fo&&(Bo.payment_method=Fo);let{error:Ta}=await Yn.confirmPayment({clientSecret:Ir,confirmParams:Bo,redirect:"if_required"});if(Ta){Me("error");let rc=Ta.message??"PayPal payment failed.";qe(rc),Kn("paypal",rc,{code:Ta.code})}}catch(Yn){Me("error"),qe(Yn instanceof Error?Yn.message:"PayPal authorization failed.")}return}if(fr?.type==="paypal_direct_required"){let Ir=fr.orderId;if(!Ir){Me("error"),qe("PayPal retry required but no order id provided.");return}let Fo=pl.current?.attempts??0;if(Fo>=2){Me("error"),qe("PayPal payment could not be completed after multiple attempts."),Kn("paypal","paypal_direct_required retry limit exceeded");return}hs(!1),Ps("loading"),va({orderId:Ir,attempts:Fo+1}),Me(null);return}if(cn.headers.get(qu)===ju){let Ir=await Vu(Dt,z,ge);if(Ir!==void 0){await mi(Ir);return}}(0,c.classifyPaymentRejection)(cn.status,fr)?it?.terminal({outcome:"payment_declined",...Ln,terminalReason:"provider_declined"}):_t(),Me("error");let tc=fr?.message??"Payment failed. Please try again.";qe(tc),Kn(i.isPaypal?"paypal":"card",tc,{code:fr?.code??fr?.gatewayErrorCode,declineCode:fr?.declineCode??fr?.gatewayDeclineReason}),await new Promise(Ir=>setTimeout(Ir,400))}catch(Dt){ed(Dt)||_t(),Me("error"),qe(Dt instanceof Error?Dt.message:"An unexpected error occurred"),await new Promise(mr=>setTimeout(mr,400))}finally{Gt(!1),Me(null),Ae.current=!1}},[vo,e,t,Bt,T,bt,st,pt,W,ce,Z,G,d,qe,Kn,u,tt]),nn=(0,o.useCallback)((i,b)=>{P&&!b?.settledProcessResponse?P(i):jl(i,b)},[P,jl]),wa=`${Zc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(wa);if(!i)return;let b;try{b=JSON.parse(i)}catch{dr(wa);return}if(!b||typeof b.createdAt!="number"||Date.now()-b.createdAt<0||Date.now()-b.createdAt>Qc||typeof b.paymentMethodId!="string"||typeof b.providerIntentId!="string"||typeof b.paymentMethodType!="string"||b.sessionId!==e||!t||b.nonce!==t||!Qo.includes(b.paymentMethodType)){dr(wa);return}dr(wa),nn({id:b.paymentMethodId,type:"card",threeDSecureActionResultTokenId:b.providerIntentId,gateway:"stripe",paymentMethodType:b.paymentMethodType},{...b.accountPatch?{accountPatch:b.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[nn,t,e,wa,Qo]);let Vl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Vl.current)return;let[i,b,z]=(0,c.readStripeRedirectParams)();if(!i||!b||oi.current||!ce)return;let ge=ce.getRawProvider();if(!ge)return;let Q=_t=>{let Dt=localStorage.getItem(_t);if(!Dt)return null;try{return JSON.parse(Dt)}catch{return dr(_t),null}},De=Q(Qn)??Q(jc),Ut;if(De?.clientSecret){if(De.clientSecret!==b)return;Ut={...De.accountPatch?{accountPatch:De.accountPatch}:{},...De.sessionId?{sessionId:De.sessionId}:{},...De.nonce?{nonce:De.nonce}:{}}}else if(De?.sessionId&&De.sessionId!==e)return;Vl.current=!0,dr(Qn),dr(jc),window.history.replaceState({},"",(0,c.stripeRedirectReturnUrl)());let zt=De?.paymentMethodType??De?.tokenType??"card",it="card";(async()=>{if(z==="failed"){let fr="Payment was declined. Please try again.";qe(fr),Kn(it,fr);return}let{paymentIntent:_t,error:Dt}=await ge.retrievePaymentIntent(b);if(Dt){let fr=Dt.message??"Failed to retrieve payment status.";qe(fr),Kn(it,fr,{code:Dt.code});return}let mr=_t?.status,cn=Aa(mr);if(!_t||!cn){let fr=mr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";qe(fr),Kn(it,fr,{code:mr??"missing_payment_intent"});return}let mi=typeof _t.payment_method=="string"?_t.payment_method:_t.payment_method?.id;nn({id:mi??De?.paymentMethodId??De?.tokenId??_t.id,type:"card",threeDSecureActionResultTokenId:_t.id,gateway:De?.gateway??"stripe",paymentMethodType:zt},Ut)})()},[e,nn,ce,qe,Kn]);let bs=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(Be||ce!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Ra=pe==="buttons",Yr=Ho?.variables,zd=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ss=Yr?.colorBackground,qd=Ss&&!zd.has(Ss)?Ss:void 0,ka=nt.cardInputBorder??(Ra?"#e5e7eb":"#A4A4FF"),Wl=Yr?.colorDanger??"#dc2626",nr=i=>Vn[i]&&(ho[i]||fn),di=Go&&(no||fn),Pn=i=>i?Wl:ka,ui=(qr.malformed||qr.empty)&&($n||fn),jd=Pn(ui),ws=nt.cardFormContainer?.backgroundColor??qd??(Ra?"white":"#EDEDFF"),ea=nt.cardInputBackground??Yr?.colorBackground??"white",Rs=na(Y),$l=na(K),ta=nt.nameInput,Hl=nt.cardInputFontSize??ip(ta?.fontSize)??Yr?.fontSizeBase??"16px",Kl=typeof ta?.fontFamily=="string"?ta.fontFamily:Yr?.fontFamily??"Poppins, sans-serif",Gl=(0,c.toCssWeight)(ta?.fontWeight)??400,Vd=nt.cardInputColor??(typeof ta?.color=="string"?ta.color:void 0)??Yr?.colorText??"#262833",Wd=nt.cardInputPlaceholderColor??"#9ca3af",lr=Yr?.borderRadius??"8px",ao=Yr?.borderRadius??nt.cardButton?.borderRadius??lr,So=Yr?.colorPrimary??"#4A49FF",$d=Yr?.colorPrimaryHover??(0,c.darkenHex)(So,.12),ks=Yr?.colorText??"#262833",Es={fontSize:Hl,fontFamily:Kl,fontWeight:Gl,color:Vd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ea={marginTop:"0.375rem",...Es,fontSize:"0.75rem",lineHeight:1.4,color:Wl},Hd={"--flopay-input-placeholder-color":Wd,"--flopay-input-font-size":Hl,"--flopay-input-font-family":Kl,"--flopay-input-font-weight":String(Gl)},_a=nt.cardFormContainer??{},_s=_a.padding??(Ra?"0":"1rem"),Is=_a.borderRadius??lr,Kd=Ue&&gn?(0,l.jsx)(Eo,{capture:Ue,html:gn.html,messageToken:gn.messageToken,expectedOrigin:gn.expectedOrigin,verificationRequired:gn.verificationRequired,theme:_d,submitLabel:R,onReady:()=>{if(!Co&&!T||typeof document>"u"||xe===!1)return;let i=()=>{let z=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(z){Hn.current=!0;try{z.focus()}finally{Hn.current=!1}}};Po.current||i()},onError:i=>{i&&gn.verificationRequired&&ue.current==="idle"&&(at.current=!0),qe(i)},onValidation:i=>{let b=ue.current;(b==="idle"||b==="validation-window")&&(qe(i),i&&ue.current==="validation-window"&&(ne.current&&(clearTimeout(ne.current),ne.current=null),ue.current="idle",Me(null)))}},re):(0,l.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Ts=(0,l.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&fe()},style:{backgroundColor:ws,borderRadius:Is,..._a,padding:_s,...Hd,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
|
|
31
31
|
.flopay-shared-input::placeholder {
|
|
32
32
|
color: var(--flopay-input-placeholder-color);
|
|
33
33
|
opacity: 1;
|
|
@@ -35,13 +35,13 @@ ${L.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),Ra&&U&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Je?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:y,style:{display:"inline-flex",alignItems:"center",gap:Cs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:rt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...rt.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...rt.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(aa,{content:G})]}),zl?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:rt.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...rt.title},children:(0,l.jsx)(Ma,{content:K})})]}),!Ra&&!zl&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:bs,order:Je?-3:0,...rt.title},children:(0,l.jsx)(Ma,{content:K})}),Je&&kt&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:kt}),Je&&bo&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:ea,border:`1px solid ${wn(di)}`,borderRadius:sr,padding:"10px"},children:(0,l.jsx)("input",{ref:Me,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:tr,onChange:i=>{Nt("email"),Br.current=i.target.value,on(i.target.value)},onPointerDown:()=>Nt("email"),onKeyDown:()=>Nt("email"),onBlur:()=>{Kn("email")&&ao(!0),Go||os()},disabled:ir,required:!0,"aria-invalid":di||void 0,"aria-describedby":di?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ss}})}),di&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Ea,children:es.empty?"Email address is required":"Enter a valid email address"})]}),P&&(0,l.jsx)("div",{style:{order:Je?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Tt,S=(J=!1)=>({backgroundColor:ea,border:`1px solid ${wn(J)}`,borderRadius:sr,marginTop:"0.5rem",padding:"10px"}),N=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ss}),fe=(0,c.getStateOptions)(i);return(0,l.jsxs)(l.Fragment,{children:[(0,c.isAVSFieldVisible)(P.address_line_1,i)&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{style:S(er("line1")),children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:ur,onChange:J=>{Nt("line1"),Or.current.addressLine1=!0,jr.current=J.target.value,zr(J.target.value)},onPointerDown:()=>Nt("line1"),onKeyDown:()=>Nt("line1"),onBlur:()=>bn("line1"),disabled:ir,required:!0,"aria-invalid":er("line1")||void 0,"aria-describedby":er("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:N()})}),er("line1")&&(0,l.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Ea,children:"Street address is required"})]}),(0,c.isAVSFieldVisible)(P.address_line_2,i)&&(0,l.jsx)("div",{style:S(),children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:An,onChange:J=>{Or.current.addressLine2=!0,yr.current=J.target.value,mn(J.target.value)},disabled:ir,"data-testid":"flopay-address-line2",style:N()})}),((0,c.isAVSFieldVisible)(P.city,i)||(0,c.isAVSFieldVisible)(P.state,i))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(P.city,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:ea,borderTop:`1px solid ${wn(er("city"))}`,borderRight:`1px solid ${wn(er("city"))}`,borderBottom:`1px solid ${wn(er("city"))}`,borderLeft:`1px solid ${wn(er("city"))}`,padding:"10px",borderTopLeftRadius:sr,borderBottomLeftRadius:sr,...(0,c.isAVSFieldVisible)(P.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:sr}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:qr,onChange:J=>{Nt("city"),Or.current.city=!0,wr.current=J.target.value,fn(J.target.value)},onPointerDown:()=>Nt("city"),onKeyDown:()=>Nt("city"),onBlur:()=>bn("city"),disabled:ir,required:!0,"aria-invalid":er("city")||void 0,"aria-describedby":er("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:N()})}),(0,c.isAVSFieldVisible)(P.state,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:ea,borderTop:`1px solid ${wn(er("state"))}`,borderRight:`1px solid ${wn(er("state"))}`,borderBottom:`1px solid ${wn(er("state"))}`,borderLeft:`1px solid ${wn(er("state"))}`,padding:"10px",borderTopRightRadius:sr,borderBottomRightRadius:sr,...(0,c.isAVSFieldVisible)(P.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${wn(er("state")||er("city"))}`}:{borderRadius:sr}},children:fe?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:gn,onChange:J=>{Nt("state"),Or.current.state=!0,$r.current=J.target.value,pr(J.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>bn("state"),disabled:ir,autoComplete:"billing address-level1",required:!0,"aria-invalid":er("state")||void 0,"aria-describedby":er("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...N(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,c.getStateLabel)(i)}),fe.map(J=>(0,l.jsx)("option",{value:J.code,children:J.name},J.code))]}):(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,c.getStateLabel)(i),autoComplete:"billing address-level1",value:gn,onChange:J=>{Nt("state"),Or.current.state=!0,$r.current=J.target.value,pr(J.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>bn("state"),disabled:ir,required:!0,"aria-invalid":er("state")||void 0,"aria-describedby":er("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:N()})})]}),er("city")&&(0,l.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Ea,children:"City is required"}),er("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Ea,children:[(0,c.getStateLabel)(i)," is required"]}),((0,c.isAVSFieldVisible)(P.country,i)||(0,c.isAVSFieldVisible)(P.postal_code,i))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:Pe==="column"?"column":"row",gap:Pe==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(P.country,i)&&(0,l.jsx)("div",{style:{flex:Pe==="row"?1:void 0,backgroundColor:ea,borderTop:`1px solid ${ka}`,borderRight:`1px solid ${ka}`,borderBottom:`1px solid ${ka}`,borderLeft:`1px solid ${ka}`,padding:"10px",...Pe==="row"&&(0,c.isAVSFieldVisible)(P.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:sr,borderBottomLeftRadius:sr,borderRight:"none"}:{borderRadius:sr}},children:(0,l.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Tt,onChange:J=>{Or.current.country=!0,Sr.current=J.target.value,St(J.target.value),Vt?.(J.target.value),$r.current="",pr("")},disabled:ir,autoComplete:"billing country","data-testid":"flopay-country",style:{...N(),cursor:"pointer"},children:[Tt===""?(0,l.jsx)("option",{value:"",children:"Select country"}):null,c.COUNTRY_OPTIONS.map(J=>(0,l.jsxs)("option",{value:J.code,children:[J.flag," ",J.name]},J.code))]})}),(0,c.isAVSFieldVisible)(P.postal_code,i)&&(0,l.jsx)("div",{style:{flex:Pe==="row"?1:void 0,backgroundColor:ea,border:`1px solid ${Ld}`,padding:"10px",...Pe==="row"&&(0,c.isAVSFieldVisible)(P.country,i)?{borderRadius:"0",borderTopRightRadius:sr,borderBottomRightRadius:sr}:{borderRadius:sr}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,c.getPostalCodeLabel)(Tt),autoComplete:"billing postal-code",value:lt,onChange:J=>{Nt("zip"),Or.current.zip=!0,Qt.current=J.target.value,yn(J.target.value),xe?.(J.target.value)},onPointerDown:()=>Nt("zip"),onKeyDown:()=>Nt("zip"),onBlur:()=>{Kn("zip")&&Po(!0)},disabled:ir,required:Vr.required,"aria-invalid":ui||void 0,"aria-describedby":ui?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:N()})})]}),ui&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Ea,children:Vr.empty?`${(0,c.getPostalCodeLabel)(i)} is required`:Zu(i)})]})})()}),Je&&jd,Dn&&(0,l.jsx)(ya,{margin:"0.75rem 0",styleOverride:rt.errorBanner,children:Dn})]}),pi={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},Wl=i=>re?!Y||!Yn?(0,l.jsx)("pre",{"data-testid":i,style:pi,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:pi,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${Y}`,` directPaypalConfigured=${Yn}`,` inAppBrowserDetected=${String(si)}`,` shouldRenderDirectPayPal=${Io}`,` shouldRenderStripePayPal=${To}`,` hasPaypalStripeInstance=${!!cl}`].join(`
|
|
39
|
-
`)}):null
|
|
40
|
-
`)}):null,Hl=ct==="apm-expanding"||ct==="apm-form"||ct==="apm-collapsing",ra;ct==="apm-expanding"?ra=qc:ct==="apm-collapsing"&&(ra=jc);let yi=Kt?Jc(cs,Kt,Ct):null,Kl={label:mt||Tc,open:Xt,onOpen:Ut,color:wo,fontFamily:Kr?.fontFamily};if(ce==="buttons"){let i=ct==="buttons"||ct==="expanding"||ct==="apm-expanding",S=ct==="expanding"||ct==="card"||ct==="collapsing",N=ve===void 0?{boxSizing:"border-box",height:Eo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},fe;ct==="expanding"||ct==="apm-expanding"?fe=Gu:(ct==="collapsing"||ct==="apm-collapsing")&&(fe=Ku);let J;ct==="expanding"?J=qc:ct==="collapsing"&&(J=jc);let Le=Ar&&(0,c.placePaymentMethodGroups)(Ar,{canHide:()=>!0,available:xl}),qt={paypal:(0,l.jsxs)(l.Fragment,{children:[Io&&Qe&&(0,l.jsxs)(l.Fragment,{children:[De&&(0,l.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,l.jsx)(Ba.Provider,{value:u,children:(0,l.jsx)(Da,{sessionId:e,nonce:t,billingApiUrl:At,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:Sn,clientId:Qe.clientId,environment:Qe.environment,currency:ft.toUpperCase(),isSubscription:st,providerObjectType:Mr,approvalPresentation:li==="popup"?void 0:li,onTokenizedBody:tn,onComplete:d,onErrorChange:Ue,onDecline:m,onCancel:w,onTechnicalFailure:Jo,onButtonClick:Se,runBeforeButtonClick:Nn,isProcessing:ir,onLoadStateChange:ys,onInitializationStateChange:ms,session:I,existingOrderId:De?.orderId,debug:re},De?.orderId??"fresh")})]}),To&&(0,l.jsx)(lr.Elements,{stripe:Sa,options:pl,children:(0,l.jsx)(Wc,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,onTokenizedBody:tn,onErrorChange:Ue,isProcessing:ir,onButtonClick:Se,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:Rl,placeholderBorderRadius:io,popupCapabilityOwner:u,externalTelemetryContext:Ml,presentationMode:Zo})})]}),wallets:(0,l.jsxs)(l.Fragment,{children:[So?(0,l.jsx)(lr.Elements,{stripe:ln,options:ul,children:(0,l.jsx)($c,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,intentKind:it>0?"payment":"setup",expressMethods:Qo,onTokenizedBody:tn,onErrorChange:Ue,onButtonClick:Se,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:kl,placeholderBorderRadius:io,popupCapabilityOwner:u,externalTelemetryContext:T})}):null,!So&&Tl?(0,l.jsx)("div",{style:{height:Eo,borderRadius:io,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:(0,l.jsx)(l.Fragment,{children:Mo&&(0,l.jsx)(Hc,{sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,paymentElementMethods:ii,stripeInstance:ln,paymentElementBaseOptions:cs,futureUseSession:Ct,onTokenizedBody:tn,onErrorChange:Ue,onButtonClick:Se,onDecline:m,runBeforeButtonClick:Nn,onLoadStateChange:El,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,onExpandApm:M,expandedApmMethod:Kt,themeId:q,buttonAppearance:{backgroundColor:rt.cardButton?.backgroundColor,borderColor:rt.cardInputBorder,textColor:rt.cardButton?.color,borderRadius:io}})}),card:(0,l.jsx)(l.Fragment,{children:Je&&(0,l.jsx)("button",{type:"button",onClick:async()=>{ir||!(await Nn("card")).proceed||(Se?.("card"),C())},disabled:ir,style:{width:"100%",...N,...rt.cardButton,...Ys({themeBundle:$o,resolvedPrimaryColor:wo,resolvedBorderRadius:sr,submitButtonStyle:rt.submitButton,explicitPrimaryColor:Kr?.colorPrimary}),fontSize:rt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ir?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ir?.6:1},onMouseEnter:jt=>{!ir&&($o||Kr?.colorPrimary)&&(jt.currentTarget.style.backgroundColor=zd)},onMouseLeave:jt=>{($o||Kr?.colorPrimary)&&(jt.currentTarget.style.backgroundColor=wo)},onMouseDown:jt=>{jt.currentTarget.style.transform="scale(0.985)"},onMouseUp:jt=>{jt.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(oa,{content:ve})})})};return(0,l.jsxs)("form",{onSubmit:hs,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),Te&&(0,l.jsx)(rn,{status:Te,errorMessage:Dn,authorized:te}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!fe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!fe?Xu:{},...fe?{animation:fe,pointerEvents:"none"}:{}},children:[Wl("flopay-direct-paypal-gate-debug"),$l("flopay-stripe-gate-debug"),xr&&Le?(0,l.jsxs)(l.Fragment,{children:[xr.filter(({group:jt})=>Le.inView.includes(jt)).map(({group:jt,key:ot})=>(0,l.jsx)(o.default.Fragment,{children:qt[jt]},ot)),Le.behindLink.length>0&&(0,l.jsx)(Ds,{...Kl,showLink:Le.showLink,children:xr.filter(({group:jt})=>Le.behindLink.includes(jt)).map(({group:jt,key:ot})=>(0,l.jsx)(o.default.Fragment,{children:qt[jt]},ot))})]}):(0,l.jsx)(Ns,{rows:Al,borderRadius:io}),Dn&&ct==="buttons"&&(0,l.jsx)(ya,{margin:"0.25rem 0",styleOverride:rt.errorBanner,children:Dn})]}),Je&&S&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...J?{animation:J}:{},...ct==="collapsing"?{pointerEvents:"none"}:{}},children:ks}),b&&Hl&&Kt&&yi&&ln&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...ra?{animation:ra}:{},...ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:vs,borderRadius:Rs,..._a,padding:ws},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:ke,style:{display:"inline-flex",alignItems:"center",gap:Cs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:rt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...rt.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...rt.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(aa,{content:G})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:rt.titleFontSize??"1.05rem",color:bs,paddingRight:80,...rt.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(Kt)}`})]}),(0,l.jsx)(lr.Elements,{stripe:ln,options:yi,children:(0,l.jsx)(Hs,{method:Kt,sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,onTokenizedBody:tn,onErrorChange:Ue,onDecline:m,onCancel:ke,runBeforeButtonClick:Nn,onButtonClick:Se,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,errorText:Dn})},Kt)]})})]})]})}if(Hl&&Kt&&yi&&ln&&b)return(0,l.jsxs)("form",{onSubmit:hs,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),Te&&(0,l.jsx)(rn,{status:Te,errorMessage:Dn,authorized:te}),(0,l.jsx)("div",{style:{...ra?{animation:ra}:{},...ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:vs,borderRadius:Rs,..._a,padding:ws},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:ke,style:{display:"inline-flex",alignItems:"center",gap:Cs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:rt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...rt.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...rt.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(aa,{content:G})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:rt.titleFontSize??"1.05rem",color:bs,paddingRight:80,...rt.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(Kt)}`})]}),(0,l.jsx)(lr.Elements,{stripe:ln,options:yi,children:(0,l.jsx)(Hs,{method:Kt,sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,onTokenizedBody:tn,onErrorChange:Ue,onDecline:m,onCancel:ke,runBeforeButtonClick:Nn,onButtonClick:Se,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,errorText:Dn})},Kt)]})})]});let Gl=xd||Ad||Fd,Ia=Ar&&(0,c.placePaymentMethodGroups)(Ar,{canHide:i=>i!=="card",available:xl}),Yl={paypal:(0,l.jsxs)(l.Fragment,{children:[Io&&Qe&&(0,l.jsxs)(l.Fragment,{children:[De&&(0,l.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,l.jsx)(Ba.Provider,{value:u,children:(0,l.jsx)(Da,{sessionId:e,nonce:t,billingApiUrl:At,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:Sn,clientId:Qe.clientId,environment:Qe.environment,currency:ft.toUpperCase(),isSubscription:st,providerObjectType:Mr,approvalPresentation:li==="popup"?void 0:li,onTokenizedBody:tn,onComplete:d,onErrorChange:Ue,onDecline:m,onCancel:w,onTechnicalFailure:Jo,onButtonClick:Se,runBeforeButtonClick:Nn,isProcessing:ir,onLoadStateChange:ys,onInitializationStateChange:ms,session:I,existingOrderId:De?.orderId,debug:re},De?.orderId??"fresh")})]}),To&&(0,l.jsx)(lr.Elements,{stripe:Sa,options:pl,children:(0,l.jsx)(Wc,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,onTokenizedBody:tn,onErrorChange:Ue,isProcessing:ir,onButtonClick:Se,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:Rl,placeholderBorderRadius:io,popupCapabilityOwner:u,externalTelemetryContext:Ml,presentationMode:Zo})})]}),wallets:(0,l.jsx)(l.Fragment,{children:So&&(0,l.jsx)(lr.Elements,{stripe:ln,options:ul,children:(0,l.jsx)($c,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,intentKind:it>0?"payment":"setup",expressMethods:Qo,onTokenizedBody:tn,onErrorChange:Ue,onButtonClick:Se,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:kl,placeholderBorderRadius:io,popupCapabilityOwner:u,externalTelemetryContext:T})})}),apms:(0,l.jsx)(l.Fragment,{children:Mo&&(0,l.jsx)(Hc,{sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:At,paymentElementMethods:ii,stripeInstance:ln,paymentElementBaseOptions:cs,futureUseSession:Ct,onTokenizedBody:tn,onErrorChange:Ue,onButtonClick:Se,onDecline:m,runBeforeButtonClick:Nn,onLoadStateChange:El,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,themeId:q,onExpandApm:M,expandedApmMethod:Kt,buttonAppearance:{backgroundColor:rt.cardButton?.backgroundColor,borderColor:rt.cardInputBorder,textColor:rt.cardButton?.color,borderRadius:io}})})};return(0,l.jsxs)("form",{onSubmit:hs,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),Te&&(0,l.jsx)(rn,{status:Te,errorMessage:Dn,authorized:te}),xr===null?(0,l.jsx)(Ns,{rows:Al,borderRadius:io}):(0,l.jsxs)(l.Fragment,{children:[Ur&&Je&&ks,Ur&&Je&&Gl&&(0,l.jsx)(Ga,{label:"or pay another way"}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Wl("flopay-direct-paypal-gate-debug-default"),$l("flopay-stripe-gate-debug-default"),xr.map(({group:i,key:S})=>i==="card"||!Ia?.inView.includes(i)?null:(0,l.jsx)(o.default.Fragment,{children:Yl[i]},S)),Ia&&Ia.behindLink.length>0&&(0,l.jsx)(Ds,{...Kl,showLink:Ia.showLink,children:xr.map(({group:i,key:S})=>Ia.behindLink.includes(i)&&i!=="card"?(0,l.jsx)(o.default.Fragment,{children:Yl[i]},S):null)})]}),!Ur&&Je&&Gl&&(0,l.jsx)(Ga,{label:"or pay with card"}),!Ur&&Je&&ks]})]})}var O=require("react/jsx-runtime"),zo=44,rl="flopay_checkout_saved_payment_resume",sp="paypal_resume_nonce_missing",Ki=new Map,$i=new Map;function Zc(e,t){t.settled&&t.consumers===0&&Ki.get(e)===t&&Ki.delete(e)}function lp(e,t,r){let n=$i.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};$i.set(e,s);let d=()=>{$i.get(e)===s&&$i.delete(e)};return a.then(d,d),a}function Za(e){return new Promise(t=>setTimeout(t,e))}function Hi(e,t,r){let n=Ri({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:se.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Qa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Js(e,t,r,n,a,s){let d=Hi(e,t,r);d.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Qa(d)}function Qc(e,t,r,n){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:t,...n===void 0?{}:{attempt:n},statusClass:"2xx"})}function ed(e,t,r,n,a){let s=(0,se.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:r,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:r,attempt:a,statusClass:s.statusClass}),t instanceof se.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof se.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):s.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...s,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function Zs(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,se.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var cp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function dp(e){return new mo.FloPay(cp,{publishableKey:"provider_unavailable",...e})}async function Qs(e,t){let{publishableKey:r,paypalPublishableKey:n}=Bs(e);return{...await Os({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function nl(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function up(){if(!nl())return null;try{let e=window.sessionStorage.getItem(rl);return e?JSON.parse(e):null}catch{return null}}function td(e){if(nl())try{window.sessionStorage.setItem(rl,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function el(){if(nl())try{window.sessionStorage.removeItem(rl)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function pp(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],r=!1;for(let n of t)e.searchParams.has(n)&&(e.searchParams.delete(n),r=!0);r&&window.history.replaceState(window.history.state,"",e.toString())}function rd(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function tl(e,t){return(0,se.resolveCheckoutLogLayout)(!!e,t)}function yp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function nd(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function mp(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function Gi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:d,loading:p,error:m,onComplete:w,onError:h,onInstrument:g,onDecline:_,onCancel:V,onCountryChange:W,onZipChange:k,showPayPal:A=!0,showStripe:f=!0,walletPresentation:H="auto",enabledPaymentMethods:Y,showApplePay:b=!0,showGooglePay:be=!0,debug:x=!1,layout:oe,paymentMethodLayout:ge,moreOptionsLabel:Ie,theme:ce,buttonsTheme:Rt,buttonsStyles:mt,cardButtonContent:q,cardBackButtonContent:Ve,cardTitleContent:We,showSecurityFooter:Ne,onButtonClick:ve,onBeforeButtonClick:G,enableAVS:K,cardFieldOrder:Ze,showCardBrandIcons:Se,cardFieldPlaceholders:qe,cardAutoFocus:Z,onCardFieldsReady:j,onCardFieldsFailed:he,cardFieldsTimeoutMs:X,cardPreFormSlot:Pt,avsLayout:pe,submitLabel:we,className:Ae,initialErrorMessage:Ce=null,initialPayPalOrderId:kt,children:Pe,checkoutMode:Be,confirmLabel:at,renderConfirmButton:yt,onSessionCompleted:Mt}){let le=(0,se.resolveBillingApiUrl)(n),It=(0,R.useMemo)(()=>(0,se.resolveTheme)(ce),[ce]),Vt=s??It?.appearance,xe=r?"embedded_checkout":"standard_checkout",Oe=tl(Pe,oe),[Ke,vt]=(0,R.useState)(null),[it,ft]=(0,R.useState)(null),Lt=(0,R.useRef)(null),Qe=(0,R.useRef)(null),st=(0,R.useRef)(0),[de,Ot]=(0,R.useState)(null),et=(0,R.useRef)(null),[re,v]=(0,R.useState)(null),Q=(0,R.useMemo)(()=>r?(0,wt.serializeCreateParams)(r):"",[r]),ee=r?`create:${Q}`:`session:${e??""}`,$=nd(re),nt=(0,R.useRef)(new Set),u=(0,R.useRef)(ee),F=(0,R.useRef)(ee);Bo(()=>{F.current=ee,u.current!==ee&&(u.current=ee,nt.current.clear())},[ee]);let D=(0,R.useCallback)(B=>{if(F.current===ee){if(xs.FLO_INSTRUMENT_ONCE_NAMES.has(B.name)){if(nt.current.has(B.name))return;nt.current.add(B.name)}(0,He.invokeMerchantCallback)(()=>g?.(B))}},[ee,g]),L=pa(D,ee),T=(0,R.useRef)(!1),I=(0,R.useCallback)(B=>{if(T.current)return;let U=B.gateway||!$?B:{...B,gateway:$};D(U)},[D,$]);(0,R.useEffect)(()=>{L({class:"lifecycle",name:"checkout.mount"})},[L]);let[Ct,Mr]=(0,R.useState)(e??""),bt=e??Ct,un=r?"":bt,[gt,vr]=(0,R.useState)(!0),[At,Ar]=(0,R.useState)(null),[Cr,Xt]=(0,R.useState)(0),[Jr,xr]=(0,R.useState)("full"),[Ur,pn]=(0,R.useState)(!1),[Fr,Wt]=(0,R.useState)(Ce),[br,Tt]=(0,R.useState)(null),[St,lt]=(0,R.useState)(null),[yn,ur]=(0,R.useState)(!1),[zr,An]=(0,R.useState)(void 0),[mn,qr]=(0,R.useState)(""),[fn,gn]=(0,R.useState)(!1),[pr,tr]=(0,R.useState)(!1),[on,Zr]=(0,R.useState)(!1),rr=(0,R.useRef)(null),Qt=(0,R.useRef)(0),Sr=(0,R.useRef)(void 0),[jr,yr]=(0,R.useState)("loading"),[wr,$r]=(0,R.useState)(0),Br=(0,R.useRef)(!1),Or=(0,R.useRef)(!1),P=(0,R.useRef)(!1),xt=(0,R.useRef)(null),te=(0,R.useRef)(null),ae=(0,R.useMemo)(()=>({checkoutMode:Be??Jr,layout:yp(Pe,oe)}),[Be,Pe,Jr,oe]),zt=(0,R.useRef)(w);zt.current=w;let Ft=(0,R.useRef)(h);Ft.current=h;let nr=(0,R.useRef)(_);nr.current=_;let Xe=(0,R.useCallback)(B=>Ii(xt,async U=>{try{return await B(U)}catch(ne){throw U.aborted?ma(ne):ne}}),[]);(0,R.useEffect)(()=>()=>{xt.current?.abort(),xt.current=null},[]);let mr=(0,R.useCallback)((B,U)=>{Lt.current=B,ft(B),et.current=U,Ot(U)},[]),Je=(0,R.useCallback)(()=>{let B=Qe.current;B&&(Qe.current=null,B.destroy())},[]);(0,R.useEffect)(()=>{Er(it)?.setCheckoutContext(ae),de&&de!==it&&Er(de)?.setCheckoutContext(ae)},[it,de,ae]);let no=(0,R.useRef)(Mt);no.current=Mt;let go=(0,R.useCallback)(B=>{yr(B),!(B!=="exhausted"||P.current)&&(P.current=!0,Ft.current?.(new se.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),jo=(0,R.useCallback)(()=>{yr("retrying"),$r(B=>B+1)},[]);(0,R.useEffect)(()=>{yr("loading"),$r(0),P.current=!1},[bt]),(0,R.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:se.SDK_VERSION,checkout_type:xe,checkout_layout:Oe,billing_api_url:le})},[Oe,xe,le]);let xn=(0,R.useMemo)(()=>r?(0,wt.serializeCreateParams)(r,!0):"",[r]),hn=(0,R.useMemo)(()=>mn===xn?zr:void 0,[zr,mn,xn]),an=(0,R.useMemo)(()=>r?Is(r,hn):void 0,[r,hn]),Qr=Be??an?.checkoutMode??"full",or=(0,R.useMemo)(()=>an?{...an,checkoutMode:Qr}:void 0,[an,Qr]);(0,R.useEffect)(()=>{An(void 0),qr(xn),Sr.current=void 0,rr.current=null,Zr(!1)},[xn]),(0,R.useEffect)(()=>{Wt(Ce)},[Ce]);let Fn=(0,R.useCallback)((B,U,ne)=>{(0,He.invokeMerchantCallback)(()=>{nr.current?.(kr(B,U,ne))})},[]),Rr=(0,R.useCallback)(async(B,U)=>{Wt(null),lt(null),ur(!1),Tt("processing");let ne=U?.sessionId??B.id,me=B.clientSecret||t,Ut=nd(B),Jt=Lt.current??et.current,Fe=Er(Jt),dt=Jt?null:Hi(le,a,ae),z={log:Me=>{Fe?Fe.log(Me):dt?.log(Me)},error:Me=>{Fe?Fe.error(Me):dt?.error(Me)},terminal:Me=>{Fe?Fe.terminal(Me):dt?.terminal(Me)},performance:Me=>{Fe?Fe.performance(Me):dt?.performance(Me)},now:()=>Fe?.now()??dt?.now()??0,elapsed:Me=>Fe?.elapsed(Me)??Math.max(0,(dt?.now()??Me)-Me)},Ge=z.now(),Re=!!(U?.initialAutoProcessingError||U?.initialAutoProcessingPending),C=!1,y,M=()=>{C||(C=!0,Re=!0,y=z.now(),z.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ke=!1,Te=()=>{ke||(ke=!0,z.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),z.performance({stage:"processing",durationMs:z.elapsed(Ge),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),y!==void 0&&z.performance({stage:"recovery",durationMs:z.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}))};z.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),T.current=!0;try{z.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{T.current=!1}L({class:"lifecycle",name:"payment.processing.started",provider:Ut}),Re&&M();let ie;try{let Me=kc(U?.initialAutoProcessingError),Ee=U?.initialAutoProcessingError?.type==="3ds_required"&&!(0,se.isMerchantAuthRequired)(U.initialAutoProcessingError)&&!U.initialAutoProcessingError.threeDSecureToken&&U.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:U.initialAutoProcessingError.nextActionRedirectUrl}:null,$t,Ht=ut=>{M();let ue=ja(le,ne,B,a!==!1);return Xe(ye=>fa(ut,{billingApiUrl:le,sessionId:ne,nonce:me,session:B,signal:ye,...ue.telemetry?{challengeTelemetry:ue.telemetry}:{}})).finally(ue.release)};if(Ee)$t=await Ht(Ee);else if(Me)M(),Me.type==="paypal_redirect_required"&&te.current?.publishableKey&&td({sessionId:ne,publishableKey:te.current.publishableKey,paypalPublishableKey:te.current.paypalPublishableKey,nonce:me}),$t=await Xe(ut=>Mi(Me,{flopay:Lt.current,paypalFlopay:et.current,attempt3DS:U?.attempt3DS,billingApiUrl:le,sessionId:ne,session:B,telemetry:!1,signal:ut})),Me.type==="paypal_redirect_required"&&el();else if(U?.initialAutoProcessingPending){let ut=U.initialAutoProcessingPending,ue=new mo.PaymentAPI(le,{telemetry:!1}),ye=await Xe(De=>ue.waitForCheckoutSessionCompletion(ut.sessionId,{initialDelayMs:ut.retryAfterMs,nonce:me,statusUrl:ut.statusUrl,signal:De})),$e=ko(ye,B),tt=ye.autoProcessingError?.type==="3ds_required"&&ye.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ye.autoProcessingError.nextActionRedirectUrl}:null;if(tt)$t=await Ht(tt);else{if(!lo($e))throw sa($e);$t=so($e,ne)}}else{if(U?.initialAutoProcessingError)throw Qn(U.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:U.initialAutoProcessingError.checkoutMethod});if(U?.fromCreateSession)return U?.fallbackToFull&&(xr("full"),rd("full")),!1;{let ut=await ga({billingApiUrl:le,sessionId:ne,session:B,nonce:me,telemetry:!1});ut.type==="success"?$t=ut.result:ut.type==="next_action_required"?$t=await Ht(ut):(M(),ut.type==="paypal_redirect_required"&&te.current?.publishableKey&&td({sessionId:ne,publishableKey:te.current.publishableKey,paypalPublishableKey:te.current.paypalPublishableKey,nonce:me}),$t=await Xe(ue=>Mi(ut,{flopay:Lt.current,paypalFlopay:et.current,attempt3DS:U?.attempt3DS,billingApiUrl:le,sessionId:ne,session:B,telemetry:!1,signal:ue})),ut.type==="paypal_redirect_required"&&el())}}ne&&(0,jn.markSessionRecentlyCompleted)(ne),Te(),Re&&(z.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),z.terminal({outcome:$t.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),ur($t.status==="authorized"),Tt("success"),await Za(600),ie=()=>zt.current?.($t)}catch(Me){let Ee=Ro(Va(Me),ne);if(Ee.code==="three_ds_aborted")return!1;let $t=Ee.checkoutMethod??qa;Wt(Ee.message),lt(Ee.message),ur(!1),U?.fallbackToFull&&(z.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),xr("full"),rd("full")),Te();let Ht=Ee.statusCode===void 0?void 0:(0,se.telemetryStatusClass)(Ee.statusCode,"unknown"),ut=Ht==="4xx"?{requestCategory:"process_payment",statusClass:Ht}:{},ue=Ht===void 0||Ht==="4xx";if((0,se.isExpectedPaymentDecline)(Ee))z.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ut});else if(ue&&(Ee.telemetryOutcome==="validation_rejected"||Ee.type==="validation_error"))z.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ut});else{let tt=(0,se.classifyTelemetryFailure)(Me,Re?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),De=Ee.telemetryRequestCategory??"process_payment";T.current=!0;try{z.error({...tt,...Ee.telemetryFailureCategory?{failureCategory:Ee.telemetryFailureCategory}:{},stage:Re?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:De})}finally{T.current=!1}L({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:De,provider:Ut})}return(0,se.isDeclineCallbackFailure)(Ee)?Fn($t,Ee,{code:Ee.code,declineCode:Ee.declineCode}):(0,He.invokeMerchantCallback)(()=>Ft.current?.(Ee)),Tt("error"),await Promise.allSettled([Za(400),U?.ensureProvidersReady?U.ensureProvidersReady():Promise.resolve()]),Re&&(z.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Te(),dt&&Qa(dt),Tt(null),lt(null)}return(0,He.invokeMerchantCallback)(ie),!0},[Fn,L,t,le,Xe,a,ae]);(0,R.useEffect)(()=>{if(typeof window>"u"||Or.current)return;let B=new URLSearchParams(window.location.search),U=B.get("payment_intent_client_secret");if(!U)return;let ne=up();ne&&(Or.current=!0,(async()=>{await Promise.resolve();let me,Ut=0;Wt(null),lt(null),Tt("processing"),pn(!0);try{if(B.get("redirect_status")==="failed")throw Object.assign(new se.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Jt,paypalFlopay:Fe}=await Os({publishableKey:ne.publishableKey,paypalPublishableKey:ne.paypalPublishableKey,billingApiUrl:le,locale:d,telemetry:a});me=Er(Fe??Jt),me?.setCheckoutContext(ae),Ut=me?.now()??0,me?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),me?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let dt=(Fe??Jt)?.getRawProvider();if(!dt)throw Object.assign(new se.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:z,error:Ge}=await dt.retrievePaymentIntent(U);if(Ge)throw Object.assign(new se.FloPayError(Ge.message??"Failed to retrieve PayPal payment status.","api_error",{code:Ge.code}),{checkoutMethod:"paypal"});let Re=sc(z?.status);if(!z||Re==="failed")throw Object.assign(new se.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let C=typeof z.payment_method=="string"?z.payment_method:z.payment_method?.id,y=Re;if(ne.sessionId){let M=ne.nonce||t;if(!M)throw Object.assign(new se.FloPayError("Unable to resume the PayPal payment: the checkout session nonce is missing.","validation_error",{code:sp}),{checkoutMethod:"paypal"});let ie=(await new mo.PaymentAPI(le,{telemetry:!1}).getUnifiedCheckoutSession(ne.sessionId,M)).data.session;if(ie&&ie.status!=="complete"){let Me=await ga({billingApiUrl:le,sessionId:ne.sessionId,session:ie,nonce:M,telemetry:!1,tokenizedData:{id:C??z.id,type:"card",threeDSecureActionResultTokenId:z.id,isPaypal:!0}});if(Me.type!=="success")throw Object.assign(new se.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});y=Me.result.status}}ne.sessionId&&(0,jn.markSessionRecentlyCompleted)(ne.sessionId),me?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),me?.performance({stage:"redirect_resume",durationMs:me.elapsed(Ut),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),me?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Tt("success"),await Za(600),(0,He.invokeMerchantCallback)(()=>zt.current?.({status:y,paymentIntentId:z.id,paymentMethodId:C,checkoutMethod:"paypal"}))}catch(Jt){let Fe=Ro(Va(Jt),ne.sessionId),dt=Fe.checkoutMethod??"paypal",z=(0,se.isExpectedPaymentDecline)(Fe);if(me)me.performance({stage:"redirect_resume",durationMs:me.elapsed(Ut),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),z?me.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):me.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(z){let Ge=Hi(le,a,ae);Ge.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Qa(Ge)}else Js(le,a,ae,"REDIRECT_RESUME_FAILED","redirect_resume");Wt(Fe.message),lt(Fe.message),(0,se.isDeclineCallbackFailure)(Fe)?Fn(dt,Fe,{code:Fe.code,declineCode:Fe.declineCode}):(0,He.invokeMerchantCallback)(()=>Ft.current?.(Fe)),Tt("error"),await Za(400)}finally{el(),pp(),Tt(null),lt(null),pn(!1)}})())},[Fn,d,t,le,a,ae]);let $n=(0,R.useRef)(null),ht=(0,R.useMemo)(()=>or?(0,wt.serializeCreateParams)(or):"",[or]),Vr=(0,R.useRef)(or);Vr.current=or,(0,R.useEffect)(()=>{Mr(e??"")},[e]),(0,R.useEffect)(()=>{Br.current=!1,Wt(Ce),lt(null),ur(!1),Tt(null)},[ht,Ce,e]);async function Bn(B,U,ne){let me=Hi(le,a,ae),Ut=new mo.PaymentAPI(le,{telemetry:!1}),Jt=!1;try{let Fe=B.idempotencyKey===void 0?void 0:(0,se.resolveIdempotencyKey)(B.idempotencyKey),dt=(0,wt.readCachedInlineSession)(U,ne),z=(0,wt.readCachedInlineIdempotencyKey)(U,ne);dt?.canonicalIdentity===ne&&z&&z.canonicalIdentity===void 0&&((0,wt.persistCachedInlineIdempotencyKey)(U,ne,z.idempotencyKey),z={...z,canonicalIdentity:ne});let Ge=Fe??(z?.canonicalIdentity===ne?z.idempotencyKey:void 0),Re,C=!1;me.log({name:dt?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let y=dt?.sid??null,M=null,ke,Te,ie=!1;if(y)try{M=await Ut.getUnifiedCheckoutSession(y,dt?.nonce),dt&&dt.canonicalIdentity===void 0&&((0,wt.legacyCachedSessionMatchesDraft)(M.data.session,B)?((0,wt.persistCachedInlineSession)(U,ne,y,dt.nonce??M.data.session?.clientSecret),z&&z.canonicalIdentity===void 0&&((0,wt.persistCachedInlineIdempotencyKey)(U,ne,z.idempotencyKey),Ge??(Ge=z.idempotencyKey))):((0,wt.clearCachedInlineCheckout)(U,ne),z=null,Ge=Fe,y=null,M=null));let Ee=M?.data.session?.status,$t=M?.data.session,Ht=$t?.clientSecret||dt?.nonce;if(y&&$t?.buyerIdentified===!1&&Ht&&(Te=ia(Ut,y,Ht,B.account)),y&&M&&Ee==="complete"){if((0,jn.wasSessionRecentlyCompleted)(y))return{sid:y,result:M};(0,wt.clearCachedInlineCheckout)(U,ne),y=null,M=null,C=!0}}catch{me.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),dt?.canonicalIdentity===void 0?((0,wt.clearCachedInlineCheckout)(U,ne),Ge=Fe):(0,wt.clearCachedInlineSession)(U,ne),y=null}if(!y){!Fe&&(C||!Ge)&&(Ge=(0,se.resolveIdempotencyKey)(),Re=Ge),Ge&&(0,wt.persistCachedInlineIdempotencyKey)(U,ne,Ge);let Ee=me.now(),$t=0;me.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ht={...B,idempotencyKey:Ge,avsCheck:!!K,avsConfig:typeof K=="object"?K:void 0,checkoutType:"embedded_checkout",checkoutLayout:tl(Pe,oe)};Object.defineProperty(Ht,mo.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ye=>{$t=Math.max($t,ye)}}});let ut=()=>{Qc(me,"session_create",Ee,$t)},ue=ye=>{ed(me,ye,"session_create",Ee,$t)&&L({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(B.checkoutMode==="confirm"||B.checkoutMode==="auto")&&Sc();try{if((0,se.isDetachedSessionEligible)(Ht)){let ye=await Ut.createDetachedSession(Ht);ye.claimed.catch(()=>{}),M=ye.shell,y=ye.sessionId,Te=ye.claim;let $e=me.now();me.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ke=ye.claimed.then(tt=>{let De=tt.data.session?.id??ye.sessionId;return De&&(0,wt.persistCachedInlineSession)(U,ne,De,tt.data.session?.clientSecret??ye.nonce),Qc(me,"session_claim",$e),ut(),tt},tt=>{throw(0,wt.clearCachedInlineSession)(U,ne),ed(me,tt,"session_claim",$e,0)&&L({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),tt}).finally(()=>Qa(me)),ke.catch(()=>{}),Jt=!0,me.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),me.performance({stage:"session_shell",durationMs:me.now()-Ee,durationMode:"machine",requestCategory:"session_create",attempt:$t,statusClass:"2xx",paymentMethodCategory:"card"})}else M=await Ut.createAndFetchSession(Ht),ut()}catch(ye){throw ue(ye),ye}y=M.data.session?.id??y??"",y&&!ke&&(0,wt.persistCachedInlineSession)(U,ne,y,M.data.session?.clientSecret)}let Me=M?.data.session;return!Te&&y&&Me?.buyerIdentified===!1&&Me.clientSecret&&(Te=ia(Ut,y,Me.clientSecret,B.account)),{sid:y??"",result:M,sdkGeneratedIdempotencyKey:Re,...ke?{claimed:ke}:{},...Te?{claim:Te}:{},...ie?{claimRequiresIdentity:!0}:{}}}finally{Jt||Qa(me)}}let oo=(0,R.useRef)(Bn);Bo(()=>{oo.current=Bn},[Bn]);let sn=(0,R.useCallback)(async(B,U)=>{let ne=Vr.current;if(!ne)throw new se.FloPayError("createSession is required to bootstrap checkout.","validation_error");let me=Is(ne,B),Ut=(0,wt.serializeCreateParams)(me),Jt=(0,wt.hashCreateParams)(me),Fe=Ki.get(Ut);if(!Fe){let Ge={canonicalIdentity:Ut,promise:oo.current(me,Jt,Ut),consumers:0,settled:!1};Fe=Ge,Ki.set(Ut,Ge);let Re=()=>{Ge.settled=!0,Zc(Ut,Ge)};Ge.promise.then(Re,Re)}Fe.consumers+=1;let dt=!1,z=()=>{dt||(dt=!0,Fe.consumers-=1,Zc(Ut,Fe))};U?.(z);try{let Ge=await Fe.promise;$n.current=Ut,B&&(qr(xn),An(Me=>tc(Me,B)));let{sid:Re,result:C,claimed:y,claim:M,claimRequiresIdentity:ke}=Ge;if(Sr.current=M,Zr(ke===!0),vt(C),C.data.session&&v(C.data.session),Re&&Mr(Re),y){Qt.current+=1;let Me=Qt.current;rr.current=y,tr(!0),y.then(Ee=>{Qt.current===Me&&(rr.current===y&&(rr.current=null),vt(Ee),Ee.data.session&&v(Ee.data.session),tr(!1),Zr(!1))},Ee=>{Qt.current===Me&&(rr.current===y&&(rr.current=null),tr(!1),Zr(!1),Ar(Ee instanceof se.FloPayError?Ee:new se.FloPayError(Ee instanceof Error?Ee.message:"Failed to create session","api_error")))})}else Qt.current+=1,rr.current=null,tr(!1),Zr(!1);let{flopay:Te,paypalFlopay:ie}=await Qs(C,{billingApiUrl:le,locale:d,telemetry:a}).catch(Me=>{throw oc(Me,Re||C.data.session?.id)});return mr(Te,ie),vr(!1),Ge}catch(Ge){throw $n.current===Ut&&($n.current=null),Ge}finally{U||z()}},[xn,mr,d,le,a]),Pn=(0,R.useRef)(Rr);Pn.current=Rr;let ho=(0,R.useRef)(sn);ho.current=sn;let Po=(0,R.useCallback)(async B=>{if(!mp(B)||fn)return{sessionId:Ct,session:re};gn(!0);try{let U=await sn(B);return{sessionId:U.sid,session:U.result.data.session??null}}finally{gn(!1)}},[sn,fn,Ct,re]),vn=(0,R.useCallback)(async B=>{let U=Sr.current;if(!U)return;let ne=Qt.current,me=await U(B);Qt.current===ne&&(vt(me),me.data.session&&v(me.data.session))},[]),ao=(0,R.useCallback)(async()=>{await rr.current},[]),Vo=(0,R.useCallback)(async()=>(await ao(),{proceed:!0}),[ao]);(0,R.useEffect)(()=>{let B=!1,U,ne=++st.current;Je(),Ar(null),Xt(0);let me=()=>{B=!0,st.current===ne&&(st.current+=1,Je())},Ut=Vr.current;if(ht&&Ut)return xr(Qr),vr(!1),$n.current===ht?me:(v(rc(Ut,Be)),(async()=>{let dt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),z=Qr==="auto"&&!Br.current&&!dt;z&&(Wt(null),lt(null),Tt("processing"));let Ge=!1;try{let Re=await ho.current(void 0,ke=>{U=ke});Ge=!0;let C=Re.result.data.session??null;te.current=Bs(Re.result);let y=Zs(Re.result),M=(0,jn.wasSessionRecentlyCompleted)(Re.sid||C?.id);if(!B&&z&&C&&!y&&!M){Br.current=!0,await lp(ht,Re.sdkGeneratedIdempotencyKey,()=>Pn.current(C,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:Re.result.autoProcessingError,initialAutoProcessingPending:Re.result.autoProcessingPending,autoProcessingAttempted:Re.result.autoProcessingAttempted,sessionId:Re.sid||C.id}));return}!B&&z&&((y||M)&&(Br.current=!0),Tt(null),lt(null))}catch(Re){if(B)return;let C=hi(Re);if(z&&C==="session_auto_completed"){Br.current=!0,Tt("success"),await Za(600),B||((0,He.invokeMerchantCallback)(()=>{zt.current?.({status:"succeeded"})}),Tt(null),lt(null));return}if(z&&(Tt(null),lt(null)),!Ge){let M=ac(Re),ke=(0,se.toPublicCheckoutInitError)(Re,M?{stage:"provider_load",provider:"stripe",...M}:{stage:"session_request"});(M||!(Re instanceof se.FloPayError))&&(0,He.invokeMerchantCallback)(()=>Ft.current?.(ke)),Ar(ke);return}let y=Re instanceof se.FloPayError?Re:new se.FloPayError(Re instanceof Error?Re.message:"Failed to create session","api_error");Ar(y)}finally{U?.(),U=void 0}})(),()=>{me(),U?.()});vr(!0);async function Jt(){let dt=!1,z=!1,Ge=null;try{let Re=new mo.PaymentAPI(le,{telemetry:!1}),C=await Re.getUnifiedCheckoutSession(bt,t);if(z=!0,Ge=C,B)return;vt(C);let y=C.data.session??null;if(v(y),!y)throw new se.FloPayError("No session data returned","api_error");let M=y.checkoutMode;if(M==="setup")throw new se.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(y.status==="authorized"){vr(!1),(0,He.invokeMerchantCallback)(()=>{zt.current?.(so(y,bt)),no.current?.(y.successUrl??"")});return}if(y.status==="complete"){vr(!1),(0,He.invokeMerchantCallback)(()=>{no.current?.(y.successUrl??"")});return}if(y.status==="expired")throw gi(y);dt=!0;let ke=Be??M??"full";xr(ke),Qt.current+=1;let Te=y.clientSecret||t;Sr.current=y.buyerIdentified===!1&&Te?ia(Re,bt,Te,{...y.customer?.id?{userId:y.customer.id}:{}}):void 0,tr(!1),Zr(!1);let ie=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Me=Zs(C);if(ke==="auto"&&!Br.current&&!ie&&!Me){Br.current=!0;let Ee=Fe(C);try{if(await Pn.current(y,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Ee,sessionId:bt||y.id}),B)return;await Ee,B||vr(!1);return}catch{if(B)return;await Ee,B||vr(!1);return}}await Fe(C),B||vr(!1)}catch(Re){if(B)return;let C=ec(Re,dt);if(dt&&L({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),C){let{errorCode:Te,stage:ie,...Me}=C;Js(le,a,ae,Te,ie,Me)}if(C?.stage==="provider_load"&&(Be??Ge?.data.session?.checkoutMode??"full")==="full"&&Ql(Ge,A,f)){let Te=dp({billingApiUrl:le,locale:d,telemetry:a});Qe.current=Te,mr(Te,null),Xt(1),vr(!1);return}let y=C?.stage==="provider_load",M="session_request";y?M="provider_load":z&&(M="post_session");let ke=(0,se.toPublicCheckoutInitError)(Re,{stage:M,provider:"stripe",sessionId:bt||void 0});(y||!(Re instanceof se.FloPayError))&&(0,He.invokeMerchantCallback)(()=>Ft.current?.(ke)),Ar(ke),vr(!1)}}async function Fe(dt){let{flopay:z,paypalFlopay:Ge,...Re}=await Qs(dt,{billingApiUrl:le,locale:d,telemetry:a});te.current={publishableKey:Re.publishableKey,paypalPublishableKey:Re.paypalPublishableKey},mr(z,Ge),Xt(0)}return Jt(),me},[Be,ht,Qr,un,t,A,f]);let va=(0,R.useCallback)(async()=>{if(!Ke||Cr!==1)return;let B=st.current;Xt(2);try{let{flopay:U,paypalFlopay:ne}=await Qs(Ke,{billingApiUrl:le,locale:d,telemetry:a});if(st.current!==B)return;Je(),mr(U,ne),Xt(0)}catch(U){if(st.current!==B)return;let{errorCode:ne,stage:me,...Ut}=_s(U);Js(le,a,ae,ne,me,Ut)}},[Je,mr,d,Cr,le,a,ae,Ke]),Cn=!!(bt&&(re?.clientSecret||t)),Hn=Ur||!Cn,vo=(0,R.useCallback)(async()=>{if(!(Ur||!Cn||!re)){pn(!0),Wt(null);try{await Rr(re,{attempt3DS:!0,fallbackToFull:!0,sessionId:bt||re.id})}finally{pn(!1)}}},[bt,Ur,Cn,Rr,re]),Nt=(0,se.resolveDirectPaypalConfig)(Ke?.data.paypal,kt),Kn=Zs(Ke),bn=(0,R.useMemo)(()=>{if(!(!Ke||!re||!Ke.data.stripe?.publishableKey))return{billingApiUrl:le}},[Ke,re,le]),On=!!(r&&!Pe&&oe==="buttons"&&G&&Qr==="full"),Hr=!!(bt&&((0,se.isMountableVaultBlock)(re?.vault)||(0,Un.canRecoverHostedCardForm)(re))),ct=(0,R.useMemo)(()=>({session:re,loading:gt,error:At,checkoutMode:Jr,inlineSessionDraft:or,applyInlineSessionPatch:On?Po:void 0,inlineSessionPatchProcessing:fn,claimPending:pr,claimRequiresIdentity:on,claimBuyerIdentity:vn,waitForDataAttachment:ao}),[re,gt,At,Jr,or,On,Po,fn,pr,on,vn,ao]),ar=!!r&&oe==="buttons"&&!Kn&&!Hr&&(!it||!bn),Kt=br?(0,O.jsx)(rn,{status:br,errorMessage:St,authorized:yn}):null;if(gt&&!Hr){if(p)return(0,O.jsxs)(O.Fragment,{children:[p,Kt]});if(oe==="buttons"){let B=It?.buttonsLayout?.cardButton?.borderRadius??It?.appearance.variables?.borderRadius??8,U=ne=>(0,O.jsx)("div",{style:{height:ne,borderRadius:B,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[A&&U(zo),f&&(b||be)&&U(zo),f&&U(zo),(0,O.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Kt]})}return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,O.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,O.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Kt]})}return At?m?(0,O.jsx)(zn.Provider,{value:ct,children:m(At)}):(0,O.jsx)(zn.Provider,{value:ct,children:(0,O.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:At.message})}):ar?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(zn.Provider,{value:ct,children:(0,O.jsx)(gp,{onButtonClick:ve,paymentMethodLayout:ge,showPayPal:A,showStripe:f,showApplePay:b,showGooglePay:be,theme:ce,buttonsTheme:Rt,buttonsStyles:mt,cardButtonContent:q,cardBackButtonContent:Ve,cardTitleContent:We})}),Kt]}):Kn&&re&&Nt?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(zn.Provider,{value:ct,children:(0,O.jsxs)("div",{className:Ae,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Fr&&(0,O.jsx)(ya,{icon:!1,children:Fr}),jr==="retrying"&&(0,O.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),jr==="exhausted"&&(0,O.jsxs)("div",{role:"alert",children:[(0,O.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,O.jsx)("button",{type:"button",onClick:jo,children:"Retry PayPal"})]}),jr!=="exhausted"&&(0,O.jsx)("div",{"aria-hidden":jr==="retrying"?!0:void 0,style:jr==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,O.jsx)(Pc,{sessionId:bt,nonce:re.clientSecret||void 0,billingApiUrl:le,email:re.customer?.email||or?.account?.email,billingName:[re.customer?.firstName,re.customer?.lastName].filter(Boolean).join(" ")||[or?.account?.firstName,or?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:vn,clientId:Nt.clientId,environment:Nt.environment,currency:(re.currency??"usd").toUpperCase(),isSubscription:re.mode==="subscription",providerObjectType:Nt.providerObjectType,approvalPresentation:Nt.approvalPresentation,existingOrderId:Nt.existingOrderId,onComplete:w,onErrorChange:Wt,onDecline:_,onCancel:V,onButtonClick:ve,runBeforeButtonClick:Vo,onInitializationStateChange:go,allowAutomaticRetry:wr===0,session:re,telemetry:a,telemetryContext:ae,onInstrument:I,debug:x},`${ee}:paypal-init-${wr}`)})]})}),Kt]}):Jr==="confirm"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(zn.Provider,{value:ct,children:(0,O.jsx)(Na,{flopay:it,paypalFlopay:de,options:bn??{billingApiUrl:le},onInstrument:I,children:(0,O.jsxs)("div",{className:Ae,children:[Fr&&(0,O.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Fr}),yt?yt({onConfirm:vo,isProcessing:Hn}):(0,O.jsx)("button",{type:"button",onClick:vo,disabled:Hn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Hn?"not-allowed":"pointer",opacity:Hn?.6:1},children:Ur?"Processing...":at??"Confirm Purchase"})]})},ee)}),Kt]}):(!it||!bn)&&!(Hr&&Jr==="full")?(0,O.jsx)(O.Fragment,{children:Kt}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(zn.Provider,{value:ct,children:(0,O.jsxs)(Na,{flopay:it,paypalFlopay:de,options:bn??{billingApiUrl:le},onInstrument:I,children:[Cr===1&&(0,O.jsx)("button",{type:"button",onClick:va,children:"Retry payment methods"}),Pe?(0,O.jsxs)(O.Fragment,{children:[Fr&&(0,O.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Fr}),(0,O.jsx)(fp,{sessionId:bt,nonce:re?.clientSecret||void 0,billingApiUrl:le,session:re,submitLabel:we,walletPresentation:H,paymentMethodLayout:ge,moreOptionsLabel:Ie,children:Pe})]}):(0,O.jsx)(Wi,{sessionId:bt,nonce:re?.clientSecret||void 0,telemetry:a,email:re?.customer?.email||or?.account?.email,userId:re?.customer?.id||or?.account?.userId,firstName:re?.customer?.firstName||or?.account?.firstName,lastName:re?.customer?.lastName||or?.account?.lastName,totalAmount:re?Math.round((0,se.buildCheckoutDisplayData)(re).total*100):0,currency:re?.currency?.toLowerCase()??"usd",onComplete:w,onError:h,onDecline:_,onCancel:V,error:Fr,onErrorChange:Wt,showPayPal:A,showStripe:f,walletPresentation:H,enabledPaymentMethods:Cr?[]:Y??Ke?.data.stripe?.enabledPaymentMethods??re?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ke?.data.stripe?.enabledPaymentMethodCountries,showApplePay:b,showGooglePay:be,layout:oe,paymentMethodLayout:ge,moreOptionsLabel:Ie,theme:ce,buttonsTheme:Rt,buttonsStyles:mt,appearance:Vt,cardButtonContent:q,cardBackButtonContent:Ve,cardTitleContent:We,onButtonClick:ve,onBeforeButtonClick:G,onBuyerIdentityReady:vn,enableAVS:K,...Ze?{cardFieldOrder:Ze}:{},...Se===void 0?{}:{showCardBrandIcons:Se},...qe===void 0?{}:{cardFieldPlaceholders:qe},...Z===void 0?{}:{cardAutoFocus:Z},...j?{onCardFieldsReady:j}:{},...he?{onCardFieldsFailed:he}:{},...X===void 0?{}:{cardFieldsTimeoutMs:X},...Pt?{cardPreFormSlot:Pt}:{},avsLayout:pe,country:re?.customer?.country,city:re?.customer?.city,state:re?.customer?.state,onCountryChange:W,onZipChange:k,avsCheck:!!K,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:tl(Pe,oe),className:Ae,submitLabel:we,directPaypal:Nt,isSubscription:re?.mode==="subscription",session:re,dataAttachmentPending:pr,dataAttachmentRequiresIdentity:on,debug:x})]},ee)}),Kt]})}function fp({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,paymentMethodLayout:d,moreOptionsLabel:p,children:m}){return(0,O.jsx)(O.Fragment,{children:R.default.Children.map(m,w=>{if(!R.default.isValidElement(w))return w;let h=w.props,g={};return h.sessionId||(g.sessionId=e),!h.nonce&&t&&(g.nonce=t),h.billingApiUrl||(g.billingApiUrl=r),h.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),h.walletPresentation===void 0&&(g.walletPresentation=s),h.paymentMethodLayout===void 0&&d!==void 0&&(g.paymentMethodLayout=d),h.moreOptionsLabel===void 0&&p!==void 0&&(g.moreOptionsLabel=p),n?.customer&&(h.email||(g.email=n.customer.email),h.userId||(g.userId=n.customer.id),h.firstName||(g.firstName=n.customer.firstName),h.lastName||(g.lastName=n.customer.lastName)),Object.keys(g).length===0?w:R.default.cloneElement(w,g)})})}function gp({onButtonClick:e,paymentMethodLayout:t,showPayPal:r,showStripe:n=!0,showApplePay:a,showGooglePay:s,theme:d,buttonsTheme:p,buttonsStyles:m,cardButtonContent:w,cardBackButtonContent:h,cardTitleContent:g}){let[_,V]=(0,R.useState)(!1),W=(0,R.useMemo)(()=>(0,se.resolveTheme)(d),[d]),k=(0,R.useMemo)(()=>{let b=W?.buttonsLayout??(0,se.resolveButtonsLayoutTheme)(p);return m?{...b,...m,cardButton:{...b.cardButton,...m.cardButton},cardFormContainer:{...b.cardFormContainer,...m.cardFormContainer},backButton:{...b.backButton,...m.backButton},backButtonIcon:{...b.backButtonIcon,...m.backButtonIcon},submitButton:{...b.submitButton,...m.submitButton},title:{...b.title,...m.title}}:b},[W,p,m]),A=W?.buttonsLayout?.cardButton?.borderRadius??W?.appearance.variables?.borderRadius??8,f=b=>(0,O.jsx)("div",{style:{height:b,borderRadius:A,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),H=w===void 0?{boxSizing:"border-box",height:zo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let b=k.cardInputBorder??"#e5e7eb",be=k.cardInputBackground??"white",x=na(h),oe=na(g);return(0,O.jsxs)("div",{style:{backgroundColor:k.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...k.cardFormContainer},children:[(0,O.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,O.jsxs)("button",{type:"button",onClick:()=>V(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:x?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...k.backButton},children:[(0,O.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...k.backButtonIcon},children:(0,O.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,O.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,O.jsx)(aa,{content:h})]}),oe?(0,O.jsx)("div",{style:{flex:1}}):(0,O.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...k.title},children:(0,O.jsx)(Ma,{content:g})})]}),(0,O.jsx)("div",{style:{backgroundColor:be,border:`1px solid ${b}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsxs)("div",{style:{display:"flex"},children:[(0,O.jsx)("div",{style:{flex:1,backgroundColor:be,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsx)("div",{style:{flex:1,backgroundColor:be,borderTop:"none",borderRight:`1px solid ${b}`,borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,O.jsx)("div",{style:{backgroundColor:be,border:`1px solid ${b}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...k.submitButton,opacity:.5}}),(0,O.jsx)("style",{children:`
|
|
38
|
+
`}),Ra&&q&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Be?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:A,style:{display:"inline-flex",alignItems:"center",gap:Rs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:nt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...nt.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...nt.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(aa,{content:Y})]}),$l?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:nt.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...nt.title},children:(0,l.jsx)(Ma,{content:K})})]}),!Ra&&!$l&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ks,order:Be?-3:0,...nt.title},children:(0,l.jsx)(Ma,{content:K})}),Be&&ft&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:ft}),Be&&Co&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:ea,border:`1px solid ${Pn(di)}`,borderRadius:lr,padding:"10px"},children:(0,l.jsx)("input",{ref:Oe,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:en,onChange:i=>{Nt("email"),L.current=i.target.value,Hr(i.target.value)},onPointerDown:()=>Nt("email"),onKeyDown:()=>Nt("email"),onBlur:()=>{oo("email")&&go(!0),Go||as()},disabled:sr,required:!0,"aria-invalid":di||void 0,"aria-describedby":di?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Es}})}),di&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Ea,children:ts.empty?"Email address is required":"Enter a valid email address"})]}),T&&(0,l.jsx)("div",{style:{order:Be?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Fe,b=(Q=!1)=>({backgroundColor:ea,border:`1px solid ${Pn(Q)}`,borderRadius:lr,marginTop:"0.5rem",padding:"10px"}),z=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Es}),ge=(0,c.getStateOptions)(i);return(0,l.jsxs)(l.Fragment,{children:[(0,c.isAVSFieldVisible)(T.address_line_1,i)&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{style:b(nr("line1")),children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Wr,onChange:Q=>{Nt("line1"),ht.current.addressLine1=!0,rr.current=Q.target.value,pn(Q.target.value)},onPointerDown:()=>Nt("line1"),onKeyDown:()=>Nt("line1"),onBlur:()=>rn("line1"),disabled:sr,required:!0,"aria-invalid":nr("line1")||void 0,"aria-describedby":nr("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:z()})}),nr("line1")&&(0,l.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Ea,children:"Street address is required"})]}),(0,c.isAVSFieldVisible)(T.address_line_2,i)&&(0,l.jsx)("div",{style:b(),children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:$r,onChange:Q=>{ht.current.addressLine2=!0,Kr.current=Q.target.value,zn(Q.target.value)},disabled:sr,"data-testid":"flopay-address-line2",style:z()})}),((0,c.isAVSFieldVisible)(T.city,i)||(0,c.isAVSFieldVisible)(T.state,i))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(T.city,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:ea,borderTop:`1px solid ${Pn(nr("city"))}`,borderRight:`1px solid ${Pn(nr("city"))}`,borderBottom:`1px solid ${Pn(nr("city"))}`,borderLeft:`1px solid ${Pn(nr("city"))}`,padding:"10px",borderTopLeftRadius:lr,borderBottomLeftRadius:lr,...(0,c.isAVSFieldVisible)(T.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:lr}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:En,onChange:Q=>{Nt("city"),ht.current.city=!0,Gr.current=Q.target.value,Cr(Q.target.value)},onPointerDown:()=>Nt("city"),onKeyDown:()=>Nt("city"),onBlur:()=>rn("city"),disabled:sr,required:!0,"aria-invalid":nr("city")||void 0,"aria-describedby":nr("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:z()})}),(0,c.isAVSFieldVisible)(T.state,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:ea,borderTop:`1px solid ${Pn(nr("state"))}`,borderRight:`1px solid ${Pn(nr("state"))}`,borderBottom:`1px solid ${Pn(nr("state"))}`,borderLeft:`1px solid ${Pn(nr("state"))}`,padding:"10px",borderTopRightRadius:lr,borderBottomRightRadius:lr,...(0,c.isAVSFieldVisible)(T.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Pn(nr("state")||nr("city"))}`}:{borderRadius:lr}},children:ge?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:br,onChange:Q=>{Nt("state"),ht.current.state=!0,zr.current=Q.target.value,Nr(Q.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>rn("state"),disabled:sr,autoComplete:"billing address-level1",required:!0,"aria-invalid":nr("state")||void 0,"aria-describedby":nr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...z(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,c.getStateLabel)(i)}),ge.map(Q=>(0,l.jsx)("option",{value:Q.code,children:Q.name},Q.code))]}):(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,c.getStateLabel)(i),autoComplete:"billing address-level1",value:br,onChange:Q=>{Nt("state"),ht.current.state=!0,zr.current=Q.target.value,Nr(Q.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>rn("state"),disabled:sr,required:!0,"aria-invalid":nr("state")||void 0,"aria-describedby":nr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:z()})})]}),nr("city")&&(0,l.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Ea,children:"City is required"}),nr("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Ea,children:[(0,c.getStateLabel)(i)," is required"]}),((0,c.isAVSFieldVisible)(T.country,i)||(0,c.isAVSFieldVisible)(T.postal_code,i))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:Ve==="column"?"column":"row",gap:Ve==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(T.country,i)&&(0,l.jsx)("div",{style:{flex:Ve==="row"?1:void 0,backgroundColor:ea,borderTop:`1px solid ${ka}`,borderRight:`1px solid ${ka}`,borderBottom:`1px solid ${ka}`,borderLeft:`1px solid ${ka}`,padding:"10px",...Ve==="row"&&(0,c.isAVSFieldVisible)(T.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:lr,borderBottomLeftRadius:lr,borderRight:"none"}:{borderRadius:lr}},children:(0,l.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Fe,onChange:Q=>{ht.current.country=!0,ir.current=Q.target.value,un(Q.target.value),$e?.(Q.target.value),zr.current="",Nr("")},disabled:sr,autoComplete:"billing country","data-testid":"flopay-country",style:{...z(),cursor:"pointer"},children:[Fe===""?(0,l.jsx)("option",{value:"",children:"Select country"}):null,c.COUNTRY_OPTIONS.map(Q=>(0,l.jsxs)("option",{value:Q.code,children:[Q.flag," ",Q.name]},Q.code))]})}),(0,c.isAVSFieldVisible)(T.postal_code,i)&&(0,l.jsx)("div",{style:{flex:Ve==="row"?1:void 0,backgroundColor:ea,border:`1px solid ${jd}`,padding:"10px",...Ve==="row"&&(0,c.isAVSFieldVisible)(T.country,i)?{borderRadius:"0",borderTopRightRadius:lr,borderBottomRightRadius:lr}:{borderRadius:lr}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,c.getPostalCodeLabel)(Fe),autoComplete:"billing postal-code",value:Vt,onChange:Q=>{Nt("zip"),ht.current.zip=!0,ar.current=Q.target.value,Lr(Q.target.value),Ct?.(Q.target.value)},onPointerDown:()=>Nt("zip"),onKeyDown:()=>Nt("zip"),onBlur:()=>{oo("zip")&&To(!0)},disabled:sr,required:qr.required,"aria-invalid":ui||void 0,"aria-describedby":ui?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:z()})})]}),ui&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Ea,children:qr.empty?`${(0,c.getPostalCodeLabel)(i)} is required`:np(i)})]})})()}),Be&&Kd,Mn&&(0,l.jsx)(ya,{margin:"0.75rem 0",styleOverride:nt.errorBanner,children:Mn})]}),pi={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},Yl=i=>C?!X||!Gn?(0,l.jsx)("pre",{"data-testid":i,style:pi,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:pi,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${X}`,` directPaypalConfigured=${Gn}`,` inAppBrowserDetected=${String(si)}`,` shouldRenderDirectPayPal=${Mo}`,` shouldRenderStripePayPal=${Ao}`,` hasPaypalStripeInstance=${!!ml}`].join(`
|
|
39
|
+
`)}):null,Xl=i=>C?!v||!ln?(0,l.jsx)("pre",{"data-testid":i,style:pi,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:pi,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${v}`,` currency=${xt}`,` amountInCents=${Ca}`,` enabledPaymentMethods: ${JSON.stringify(F??[])}`,` enabledPaymentMethodsProvided=${ba}`,` hasEnabledMethods=${ni}`,` expressMethods: ${JSON.stringify(ai)}`,` walletExpressMethods: ${JSON.stringify(Qo)}`,` paymentElementMethods: ${JSON.stringify(ps)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ii)}`,` hasStripeInstance=${!!ln}`,` shouldRenderWallets=${bo}`,` shouldRenderPaymentElement=${xo}`].join(`
|
|
40
|
+
`)}):null,Jl=ot==="apm-expanding"||ot==="apm-form"||ot==="apm-collapsing",ra;ot==="apm-expanding"?ra=Hc:ot==="apm-collapsing"&&(ra=Kc);let yi=Zt?rd(ys,Zt,Kt):null,Zl={label:mt||Bc,open:Qr,onOpen:Ot,color:So,fontFamily:Yr?.fontFamily};if(pe==="buttons"){let i=ot==="buttons"||ot==="expanding"||ot==="apm-expanding",b=ot==="expanding"||ot==="card"||ot==="collapsing",z=ve===void 0?{boxSizing:"border-box",height:ko,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ge;ot==="expanding"||ot==="apm-expanding"?ge=Qu:(ot==="collapsing"||ot==="apm-collapsing")&&(ge=Zu);let Q;ot==="expanding"?Q=Hc:ot==="collapsing"&&(Q=Kc);let De=jt&&(0,c.placePaymentMethodGroups)(jt,{canHide:()=>!0,available:Ll}),Ut={paypal:(0,l.jsxs)(l.Fragment,{children:[Mo&&ct&&(0,l.jsxs)(l.Fragment,{children:[yt&&(0,l.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,l.jsx)(Ba.Provider,{value:I,children:(0,l.jsx)(Da,{sessionId:e,nonce:t,billingApiUrl:Et,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:hn,clientId:ct.clientId,environment:ct.environment,currency:xt.toUpperCase(),isSubscription:gt,providerObjectType:Vr,approvalPresentation:li==="popup"?void 0:li,onTokenizedBody:nn,onComplete:d,onErrorChange:qe,onDecline:y,onCancel:S,onTechnicalFailure:Jo,onButtonClick:Se,runBeforeButtonClick:xn,isProcessing:sr,onLoadStateChange:hs,onInitializationStateChange:Ps,session:Ht,existingOrderId:yt?.orderId,debug:C},yt?.orderId??"fresh")})]}),Ao&&(0,l.jsx)(cr.Elements,{stripe:Sa,options:hl,children:(0,l.jsx)(Yc,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:hn,billingApiUrl:Et,onTokenizedBody:nn,onErrorChange:qe,isProcessing:sr,onButtonClick:Se,onDecline:y,onTechnicalFailure:Jo,runBeforeButtonClick:xn,onLoadStateChange:Tl,placeholderBorderRadius:ao,popupCapabilityOwner:I,externalTelemetryContext:Ol,presentationMode:Zo})})]}),wallets:(0,l.jsxs)(l.Fragment,{children:[bo?(0,l.jsx)(cr.Elements,{stripe:ln,options:gl,children:(0,l.jsx)(Xc,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:hn,billingApiUrl:Et,intentKind:At>0?"payment":"setup",expressMethods:Qo,onTokenizedBody:nn,onErrorChange:qe,onButtonClick:Se,onDecline:y,onTechnicalFailure:Jo,runBeforeButtonClick:xn,onLoadStateChange:Ml,placeholderBorderRadius:ao,popupCapabilityOwner:I,externalTelemetryContext:tt})}):null,!bo&&Bl?(0,l.jsx)("div",{style:{height:ko,borderRadius:ao,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:(0,l.jsx)(l.Fragment,{children:xo&&(0,l.jsx)(Jc,{sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:hn,billingApiUrl:Et,paymentElementMethods:ii,stripeInstance:ln,paymentElementBaseOptions:ys,futureUseSession:Kt,onTokenizedBody:nn,onErrorChange:qe,onButtonClick:Se,onDecline:y,runBeforeButtonClick:xn,onLoadStateChange:Al,isProcessing:sr,submitButtonColor:So,submitButtonBorderRadius:lr,submitButtonStyle:nt.submitButton,onExpandApm:te,expandedApmMethod:Zt,themeId:j,buttonAppearance:{backgroundColor:nt.cardButton?.backgroundColor,borderColor:nt.cardInputBorder,textColor:nt.cardButton?.color,borderRadius:ao}})}),card:(0,l.jsx)(l.Fragment,{children:Be&&(0,l.jsx)("button",{type:"button",onClick:async()=>{sr||!(await xn("card")).proceed||(Se?.("card"),N())},disabled:sr,style:{width:"100%",...z,...nt.cardButton,...Qs({themeBundle:$o,resolvedPrimaryColor:So,resolvedBorderRadius:lr,submitButtonStyle:nt.submitButton,explicitPrimaryColor:Yr?.colorPrimary}),fontSize:nt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:sr?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:sr?.6:1},onMouseEnter:zt=>{!sr&&($o||Yr?.colorPrimary)&&(zt.currentTarget.style.backgroundColor=$d)},onMouseLeave:zt=>{($o||Yr?.colorPrimary)&&(zt.currentTarget.style.backgroundColor=So)},onMouseDown:zt=>{zt.currentTarget.style.transform="scale(0.985)"},onMouseUp:zt=>{zt.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(oa,{content:ve})})})};return(0,l.jsxs)("form",{onSubmit:bs,className:$,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),Rt&&(0,l.jsx)(on,{status:Rt,errorMessage:Mn,authorized:Tt}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!ge?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!ge?tp:{},...ge?{animation:ge,pointerEvents:"none"}:{}},children:[Yl("flopay-direct-paypal-gate-debug"),Xl("flopay-stripe-gate-debug"),Ar&&De?(0,l.jsxs)(l.Fragment,{children:[Ar.filter(({group:zt})=>De.inView.includes(zt)).map(({group:zt,key:it})=>(0,l.jsx)(o.default.Fragment,{children:Ut[zt]},it)),De.behindLink.length>0&&(0,l.jsx)(zs,{...Zl,showLink:De.showLink,children:Ar.filter(({group:zt})=>De.behindLink.includes(zt)).map(({group:zt,key:it})=>(0,l.jsx)(o.default.Fragment,{children:Ut[zt]},it))})]}):(0,l.jsx)(js,{rows:Dl,borderRadius:ao}),Mn&&ot==="buttons"&&(0,l.jsx)(ya,{margin:"0.25rem 0",styleOverride:nt.errorBanner,children:Mn})]}),Be&&b&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Q?{animation:Q}:{},...ot==="collapsing"?{pointerEvents:"none"}:{}},children:Ts}),v&&Jl&&Zt&&yi&&ln&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...ra?{animation:ra}:{},...ot==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:ws,borderRadius:Is,..._a,padding:_s},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Te,style:{display:"inline-flex",alignItems:"center",gap:Rs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:nt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...nt.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...nt.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(aa,{content:Y})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:nt.titleFontSize??"1.05rem",color:ks,paddingRight:80,...nt.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(Zt)}`})]}),(0,l.jsx)(cr.Elements,{stripe:ln,options:yi,children:(0,l.jsx)(Xs,{method:Zt,sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:hn,billingApiUrl:Et,onTokenizedBody:nn,onErrorChange:qe,onDecline:y,onCancel:Te,runBeforeButtonClick:xn,onButtonClick:Se,isProcessing:sr,submitButtonColor:So,submitButtonBorderRadius:lr,submitButtonStyle:nt.submitButton,errorText:Mn})},Zt)]})})]})]})}if(Jl&&Zt&&yi&&ln&&v)return(0,l.jsxs)("form",{onSubmit:bs,className:$,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),Rt&&(0,l.jsx)(on,{status:Rt,errorMessage:Mn,authorized:Tt}),(0,l.jsx)("div",{style:{...ra?{animation:ra}:{},...ot==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:ws,borderRadius:Is,..._a,padding:_s},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Te,style:{display:"inline-flex",alignItems:"center",gap:Rs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:nt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...nt.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...nt.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(aa,{content:Y})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:nt.titleFontSize??"1.05rem",color:ks,paddingRight:80,...nt.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(Zt)}`})]}),(0,l.jsx)(cr.Elements,{stripe:ln,options:yi,children:(0,l.jsx)(Xs,{method:Zt,sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:hn,billingApiUrl:Et,onTokenizedBody:nn,onErrorChange:qe,onDecline:y,onCancel:Te,runBeforeButtonClick:xn,onButtonClick:Se,isProcessing:sr,submitButtonColor:So,submitButtonBorderRadius:lr,submitButtonStyle:nt.submitButton,errorText:Mn})},Zt)]})})]});let Ql=Ld||Dd||Nd,Ia=jt&&(0,c.placePaymentMethodGroups)(jt,{canHide:i=>i!=="card",available:Ll}),ec={paypal:(0,l.jsxs)(l.Fragment,{children:[Mo&&ct&&(0,l.jsxs)(l.Fragment,{children:[yt&&(0,l.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,l.jsx)(Ba.Provider,{value:I,children:(0,l.jsx)(Da,{sessionId:e,nonce:t,billingApiUrl:Et,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:hn,clientId:ct.clientId,environment:ct.environment,currency:xt.toUpperCase(),isSubscription:gt,providerObjectType:Vr,approvalPresentation:li==="popup"?void 0:li,onTokenizedBody:nn,onComplete:d,onErrorChange:qe,onDecline:y,onCancel:S,onTechnicalFailure:Jo,onButtonClick:Se,runBeforeButtonClick:xn,isProcessing:sr,onLoadStateChange:hs,onInitializationStateChange:Ps,session:Ht,existingOrderId:yt?.orderId,debug:C},yt?.orderId??"fresh")})]}),Ao&&(0,l.jsx)(cr.Elements,{stripe:Sa,options:hl,children:(0,l.jsx)(Yc,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:hn,billingApiUrl:Et,onTokenizedBody:nn,onErrorChange:qe,isProcessing:sr,onButtonClick:Se,onDecline:y,onTechnicalFailure:Jo,runBeforeButtonClick:xn,onLoadStateChange:Tl,placeholderBorderRadius:ao,popupCapabilityOwner:I,externalTelemetryContext:Ol,presentationMode:Zo})})]}),wallets:(0,l.jsx)(l.Fragment,{children:bo&&(0,l.jsx)(cr.Elements,{stripe:ln,options:gl,children:(0,l.jsx)(Xc,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:hn,billingApiUrl:Et,intentKind:At>0?"payment":"setup",expressMethods:Qo,onTokenizedBody:nn,onErrorChange:qe,onButtonClick:Se,onDecline:y,onTechnicalFailure:Jo,runBeforeButtonClick:xn,onLoadStateChange:Ml,placeholderBorderRadius:ao,popupCapabilityOwner:I,externalTelemetryContext:tt})})}),apms:(0,l.jsx)(l.Fragment,{children:xo&&(0,l.jsx)(Jc,{sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Et,paymentElementMethods:ii,stripeInstance:ln,paymentElementBaseOptions:ys,futureUseSession:Kt,onTokenizedBody:nn,onErrorChange:qe,onButtonClick:Se,onDecline:y,runBeforeButtonClick:xn,onLoadStateChange:Al,isProcessing:sr,submitButtonColor:So,submitButtonBorderRadius:lr,submitButtonStyle:nt.submitButton,themeId:j,onExpandApm:te,expandedApmMethod:Zt,buttonAppearance:{backgroundColor:nt.cardButton?.backgroundColor,borderColor:nt.cardInputBorder,textColor:nt.cardButton?.color,borderRadius:ao}})})};return(0,l.jsxs)("form",{onSubmit:bs,className:$,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),Rt&&(0,l.jsx)(on,{status:Rt,errorMessage:Mn,authorized:Tt}),Ar===null?(0,l.jsx)(js,{rows:Dl,borderRadius:ao}):(0,l.jsxs)(l.Fragment,{children:[xr&&Be&&Ts,xr&&Be&&Ql&&(0,l.jsx)(Ga,{label:"or pay another way"}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Yl("flopay-direct-paypal-gate-debug-default"),Xl("flopay-stripe-gate-debug-default"),Ar.map(({group:i,key:b})=>i==="card"||!Ia?.inView.includes(i)?null:(0,l.jsx)(o.default.Fragment,{children:ec[i]},b)),Ia&&Ia.behindLink.length>0&&(0,l.jsx)(zs,{...Zl,showLink:Ia.showLink,children:Ar.map(({group:i,key:b})=>Ia.behindLink.includes(i)&&i!=="card"?(0,l.jsx)(o.default.Fragment,{children:ec[i]},b):null)})]}),!xr&&Be&&Ql&&(0,l.jsx)(Ga,{label:"or pay with card"}),!xr&&Be&&Ts]})]})}var O=require("react/jsx-runtime"),jo=44,il="flopay_checkout_saved_payment_resume",pp="paypal_resume_nonce_missing",Ki=new Map,$i=new Map;function nd(e,t){t.settled&&t.consumers===0&&Ki.get(e)===t&&Ki.delete(e)}function yp(e,t,r){let n=$i.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};$i.set(e,s);let d=()=>{$i.get(e)===s&&$i.delete(e)};return a.then(d,d),a}function Za(e){return new Promise(t=>setTimeout(t,e))}function Hi(e,t,r){let n=Ri({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:de.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Qa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function tl(e,t,r,n,a,s){let d=Hi(e,t,r);d.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Qa(d)}function od(e,t,r,n){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:t,...n===void 0?{}:{attempt:n},statusClass:"2xx"})}function ad(e,t,r,n,a){let s=(0,de.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:r,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:r,attempt:a,statusClass:s.statusClass}),t instanceof de.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof de.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):s.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...s,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function rl(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,de.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var mp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function fp(e){return new yo.FloPay(mp,{publishableKey:"provider_unavailable",...e})}async function nl(e,t){let{publishableKey:r,paypalPublishableKey:n}=Ns(e);return{...await Us({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function sl(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function gp(){if(!sl())return null;try{let e=window.sessionStorage.getItem(il);return e?JSON.parse(e):null}catch{return null}}function id(e){if(sl())try{window.sessionStorage.setItem(il,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ol(){if(sl())try{window.sessionStorage.removeItem(il)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function hp(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],r=!1;for(let n of t)e.searchParams.has(n)&&(e.searchParams.delete(n),r=!0);r&&window.history.replaceState(window.history.state,"",e.toString())}function sd(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function al(e,t){return(0,de.resolveCheckoutLogLayout)(!!e,t)}function Pp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function ld(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function vp(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function Gi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:d,loading:p,error:y,onComplete:S,onError:P,onInstrument:g,onDecline:_,onCancel:W,onCountryChange:$,onZipChange:R,showPayPal:x=!0,showStripe:f=!0,walletPresentation:H="auto",enabledPaymentMethods:X,showApplePay:v=!0,showGooglePay:be=!0,debug:F=!1,layout:oe,paymentMethodLayout:he,moreOptionsLabel:Re,theme:pe,buttonsTheme:kt,buttonsStyles:mt,cardButtonContent:j,cardBackButtonContent:Je,cardTitleContent:Ze,showSecurityFooter:Le,onButtonClick:ve,onBeforeButtonClick:Y,enableAVS:K,cardFieldOrder:rt,showCardBrandIcons:Se,showCardFieldLabels:Ke,cardFieldLabels:ee,cardFieldPlaceholders:V,cardAutoFocus:Pe,onCardFieldsReady:J,onCardFieldsFailed:ut,cardFieldsTimeoutMs:ye,cardPreFormSlot:ke,avsLayout:xe,submitLabel:_e,className:vt,initialErrorMessage:Ne=null,initialPayPalOrderId:ft,children:Ve,checkoutMode:We,confirmLabel:Mt,renderConfirmButton:Lt,onSessionCompleted:Ft}){let le=(0,de.resolveBillingApiUrl)(n),Ee=(0,w.useMemo)(()=>(0,de.resolveTheme)(pe),[pe]),$e=s??Ee?.appearance,Ct=r?"embedded_checkout":"standard_checkout",bt=al(Ve,oe),[st,pt]=(0,w.useState)(null),[At,xt]=(0,w.useState)(null),lt=(0,w.useRef)(null),ct=(0,w.useRef)(null),gt=(0,w.useRef)(0),[G,Jt]=(0,w.useState)(null),B=(0,w.useRef)(null),[C,ce]=(0,w.useState)(null),Z=(0,w.useMemo)(()=>r?(0,wt.serializeCreateParams)(r):"",[r]),ae=r?`create:${Z}`:`session:${e??""}`,u=ld(C),M=(0,w.useRef)(new Set),I=(0,w.useRef)(ae),ie=(0,w.useRef)(ae);Do(()=>{ie.current=ae,I.current!==ae&&(I.current=ae,M.current.clear())},[ae]);let U=(0,w.useCallback)(D=>{if(ie.current===ae){if(Ds.FLO_INSTRUMENT_ONCE_NAMES.has(D.name)){if(M.current.has(D.name))return;M.current.add(D.name)}(0,Qe.invokeMerchantCallback)(()=>g?.(D))}},[ae,g]),k=pa(U,ae),tt=(0,w.useRef)(!1),Ht=(0,w.useCallback)(D=>{if(tt.current)return;let q=D.gateway||!u?D:{...D,gateway:u};U(q)},[U,u]);(0,w.useEffect)(()=>{k({class:"lifecycle",name:"checkout.mount"})},[k]);let[Kt,Vr]=(0,w.useState)(e??""),He=e??Kt,Un=r?"":He,[Pr,vr]=(0,w.useState)(!0),[Et,jt]=(0,w.useState)(null),[Or,Qr]=(0,w.useState)(0),[Dr,Ar]=(0,w.useState)("full"),[xr,tr]=(0,w.useState)(!1),[Gt,or]=(0,w.useState)(Ne),[St,Fe]=(0,w.useState)(null),[un,Vt]=(0,w.useState)(null),[Lr,Wr]=(0,w.useState)(!1),[pn,$r]=(0,w.useState)(void 0),[zn,En]=(0,w.useState)(""),[Cr,br]=(0,w.useState)(!1),[Nr,en]=(0,w.useState)(!1),[Hr,Ur]=(0,w.useState)(!1),pr=(0,w.useRef)(null),ar=(0,w.useRef)(0),ir=(0,w.useRef)(void 0),[rr,Kr]=(0,w.useState)("loading"),[Gr,zr]=(0,w.useState)(0),L=(0,w.useRef)(!1),ht=(0,w.useRef)(!1),T=(0,w.useRef)(!1),Ie=(0,w.useRef)(null),Tt=(0,w.useRef)(null),Pt=(0,w.useMemo)(()=>({checkoutMode:We??Dr,layout:Pp(Ve,oe)}),[We,Ve,Dr,oe]),Yt=(0,w.useRef)(S);Yt.current=S;let Ge=(0,w.useRef)(P);Ge.current=P;let qn=(0,w.useRef)(_);qn.current=_;let ro=(0,w.useCallback)(D=>Ii(Ie,async q=>{try{return await D(q)}catch(se){throw q.aborted?ma(se):se}}),[]);(0,w.useEffect)(()=>()=>{Ie.current?.abort(),Ie.current=null},[]);let Fr=(0,w.useCallback)((D,q)=>{lt.current=D,xt(D),B.current=q,Jt(q)},[]),Be=(0,w.useCallback)(()=>{let D=ct.current;D&&(ct.current=null,D.destroy())},[]);(0,w.useEffect)(()=>{wr(At)?.setCheckoutContext(Pt),G&&G!==At&&wr(G)?.setCheckoutContext(Pt)},[At,G,Pt]);let fo=(0,w.useRef)(Ft);fo.current=Ft;let _o=(0,w.useCallback)(D=>{Kr(D),!(D!=="exhausted"||T.current)&&(T.current=!0,Ge.current?.(new de.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Io=(0,w.useCallback)(()=>{Kr("retrying"),zr(D=>D+1)},[]);(0,w.useEffect)(()=>{Kr("loading"),zr(0),T.current=!1},[He]),(0,w.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:de.SDK_VERSION,checkout_type:Ct,checkout_layout:bt,billing_api_url:le})},[bt,Ct,le]);let _n=(0,w.useMemo)(()=>r?(0,wt.serializeCreateParams)(r,!0):"",[r]),yn=(0,w.useMemo)(()=>zn===_n?pn:void 0,[pn,zn,_n]),sn=(0,w.useMemo)(()=>r?xs(r,yn):void 0,[r,yn]),tn=We??sn?.checkoutMode??"full",Wt=(0,w.useMemo)(()=>sn?{...sn,checkoutMode:tn}:void 0,[sn,tn]);(0,w.useEffect)(()=>{$r(void 0),En(_n),ir.current=void 0,pr.current=null,Ur(!1)},[_n]),(0,w.useEffect)(()=>{or(Ne)},[Ne]);let jn=(0,w.useCallback)((D,q,se)=>{(0,Qe.invokeMerchantCallback)(()=>{qn.current?.(Sr(D,q,se))})},[]),Br=(0,w.useCallback)(async(D,q)=>{or(null),Vt(null),Wr(!1),Fe("processing");let se=q?.sessionId??D.id,fe=D.clientSecret||t,Ot=ld(D),Qt=lt.current??B.current,me=wr(Qt),at=Qt?null:Hi(le,a,Pt),re={log:Oe=>{me?me.log(Oe):at?.log(Oe)},error:Oe=>{me?me.error(Oe):at?.error(Oe)},terminal:Oe=>{me?me.terminal(Oe):at?.terminal(Oe)},performance:Oe=>{me?me.performance(Oe):at?.performance(Oe)},now:()=>me?.now()??at?.now()??0,elapsed:Oe=>me?.elapsed(Oe)??Math.max(0,(at?.now()??Oe)-Oe)},h=re.now(),m=!!(q?.initialAutoProcessingError||q?.initialAutoProcessingPending),N=!1,A,te=()=>{N||(N=!0,m=!0,A=re.now(),re.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Te=!1,Rt=()=>{Te||(Te=!0,re.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),re.performance({stage:"processing",durationMs:re.elapsed(h),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),A!==void 0&&re.performance({stage:"recovery",durationMs:re.elapsed(A),durationMode:"machine",paymentMethodCategory:"saved"}))};re.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),tt.current=!0;try{re.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{tt.current=!1}k({class:"lifecycle",name:"payment.processing.started",provider:Ot}),m&&te();let Me;try{let Oe=Mc(q?.initialAutoProcessingError),ze=q?.initialAutoProcessingError?.type==="3ds_required"&&!(0,de.isMerchantAuthRequired)(q.initialAutoProcessingError)&&!q.initialAutoProcessingError.threeDSecureToken&&q.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:q.initialAutoProcessingError.nextActionRedirectUrl}:null,qt,Ae=ne=>{te();let ue=ja(le,se,D,a!==!1);return ro(Ce=>fa(ne,{billingApiUrl:le,sessionId:se,nonce:fe,session:D,signal:Ce,...ue.telemetry?{challengeTelemetry:ue.telemetry}:{}})).finally(ue.release)};if(ze)qt=await Ae(ze);else if(Oe)te(),Oe.type==="paypal_redirect_required"&&Tt.current?.publishableKey&&id({sessionId:se,publishableKey:Tt.current.publishableKey,paypalPublishableKey:Tt.current.paypalPublishableKey,nonce:fe}),qt=await ro(ne=>Mi(Oe,{flopay:lt.current,paypalFlopay:B.current,attempt3DS:q?.attempt3DS,billingApiUrl:le,sessionId:se,session:D,telemetry:!1,signal:ne})),Oe.type==="paypal_redirect_required"&&ol();else if(q?.initialAutoProcessingPending){let ne=q.initialAutoProcessingPending,ue=new yo.PaymentAPI(le,{telemetry:!1}),Ce=await ro(yt=>ue.waitForCheckoutSessionCompletion(ne.sessionId,{initialDelayMs:ne.retryAfterMs,nonce:fe,statusUrl:ne.statusUrl,signal:yt})),Ye=Ro(Ce,D),$t=Ce.autoProcessingError?.type==="3ds_required"&&Ce.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Ce.autoProcessingError.nextActionRedirectUrl}:null;if($t)qt=await Ae($t);else{if(!so(Ye))throw sa(Ye);qt=io(Ye,se)}}else{if(q?.initialAutoProcessingError)throw Zn(q.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:q.initialAutoProcessingError.checkoutMethod});if(q?.fromCreateSession)return q?.fallbackToFull&&(Ar("full"),sd("full")),!1;{let ne=await ga({billingApiUrl:le,sessionId:se,session:D,nonce:fe,telemetry:!1});ne.type==="success"?qt=ne.result:ne.type==="next_action_required"?qt=await Ae(ne):(te(),ne.type==="paypal_redirect_required"&&Tt.current?.publishableKey&&id({sessionId:se,publishableKey:Tt.current.publishableKey,paypalPublishableKey:Tt.current.paypalPublishableKey,nonce:fe}),qt=await ro(ue=>Mi(ne,{flopay:lt.current,paypalFlopay:B.current,attempt3DS:q?.attempt3DS,billingApiUrl:le,sessionId:se,session:D,telemetry:!1,signal:ue})),ne.type==="paypal_redirect_required"&&ol())}}se&&(0,Dn.markSessionRecentlyCompleted)(se),Rt(),m&&(re.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),re.terminal({outcome:qt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Wr(qt.status==="authorized"),Fe("success"),await Za(600),Me=()=>Yt.current?.(qt)}catch(Oe){let ze=wo(Va(Oe),se);if(ze.code==="three_ds_aborted")return!1;let qt=ze.checkoutMethod??qa;or(ze.message),Vt(ze.message),Wr(!1),q?.fallbackToFull&&(re.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Ar("full"),sd("full")),Rt();let Ae=ze.statusCode===void 0?void 0:(0,de.telemetryStatusClass)(ze.statusCode,"unknown"),ne=Ae==="4xx"?{requestCategory:"process_payment",statusClass:Ae}:{},ue=Ae===void 0||Ae==="4xx";if((0,de.isExpectedPaymentDecline)(ze))re.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ne});else if(ue&&(ze.telemetryOutcome==="validation_rejected"||ze.type==="validation_error"))re.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ne});else{let $t=(0,de.classifyTelemetryFailure)(Oe,m?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),yt=ze.telemetryRequestCategory??"process_payment";tt.current=!0;try{re.error({...$t,...ze.telemetryFailureCategory?{failureCategory:ze.telemetryFailureCategory}:{},stage:m?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:yt})}finally{tt.current=!1}k({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:yt,provider:Ot})}return(0,de.isDeclineCallbackFailure)(ze)?jn(qt,ze,{code:ze.code,declineCode:ze.declineCode}):(0,Qe.invokeMerchantCallback)(()=>Ge.current?.(ze)),Fe("error"),await Promise.allSettled([Za(400),q?.ensureProvidersReady?q.ensureProvidersReady():Promise.resolve()]),m&&(re.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Rt(),at&&Qa(at),Fe(null),Vt(null)}return(0,Qe.invokeMerchantCallback)(Me),!0},[jn,k,t,le,ro,a,Pt]);(0,w.useEffect)(()=>{if(typeof window>"u"||ht.current)return;let D=new URLSearchParams(window.location.search),q=D.get("payment_intent_client_secret");if(!q)return;let se=gp();se&&(ht.current=!0,(async()=>{await Promise.resolve();let fe,Ot=0;or(null),Vt(null),Fe("processing"),tr(!0);try{if(D.get("redirect_status")==="failed")throw Object.assign(new de.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Qt,paypalFlopay:me}=await Us({publishableKey:se.publishableKey,paypalPublishableKey:se.paypalPublishableKey,billingApiUrl:le,locale:d,telemetry:a});fe=wr(me??Qt),fe?.setCheckoutContext(Pt),Ot=fe?.now()??0,fe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let at=(me??Qt)?.getRawProvider();if(!at)throw Object.assign(new de.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:re,error:h}=await at.retrievePaymentIntent(q);if(h)throw Object.assign(new de.FloPayError(h.message??"Failed to retrieve PayPal payment status.","api_error",{code:h.code}),{checkoutMethod:"paypal"});let m=pc(re?.status);if(!re||m==="failed")throw Object.assign(new de.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let N=typeof re.payment_method=="string"?re.payment_method:re.payment_method?.id,A=m;if(se.sessionId){let te=se.nonce||t;if(!te)throw Object.assign(new de.FloPayError("Unable to resume the PayPal payment: the checkout session nonce is missing.","validation_error",{code:pp}),{checkoutMethod:"paypal"});let Me=(await new yo.PaymentAPI(le,{telemetry:!1}).getUnifiedCheckoutSession(se.sessionId,te)).data.session;if(Me&&Me.status!=="complete"){let Oe=await ga({billingApiUrl:le,sessionId:se.sessionId,session:Me,nonce:te,telemetry:!1,tokenizedData:{id:N??re.id,type:"card",threeDSecureActionResultTokenId:re.id,isPaypal:!0}});if(Oe.type!=="success")throw Object.assign(new de.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});A=Oe.result.status}}se.sessionId&&(0,Dn.markSessionRecentlyCompleted)(se.sessionId),fe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.performance({stage:"redirect_resume",durationMs:fe.elapsed(Ot),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Fe("success"),await Za(600),(0,Qe.invokeMerchantCallback)(()=>Yt.current?.({status:A,paymentIntentId:re.id,paymentMethodId:N,checkoutMethod:"paypal"}))}catch(Qt){let me=wo(Va(Qt),se.sessionId),at=me.checkoutMethod??"paypal",re=(0,de.isExpectedPaymentDecline)(me);if(fe)fe.performance({stage:"redirect_resume",durationMs:fe.elapsed(Ot),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),re?fe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):fe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(re){let h=Hi(le,a,Pt);h.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Qa(h)}else tl(le,a,Pt,"REDIRECT_RESUME_FAILED","redirect_resume");or(me.message),Vt(me.message),(0,de.isDeclineCallbackFailure)(me)?jn(at,me,{code:me.code,declineCode:me.declineCode}):(0,Qe.invokeMerchantCallback)(()=>Ge.current?.(me)),Fe("error"),await Za(400)}finally{ol(),hp(),Fe(null),Vt(null),tr(!1)}})())},[jn,d,t,le,a,Pt]);let mn=(0,w.useRef)(null),Ue=(0,w.useMemo)(()=>Wt?(0,wt.serializeCreateParams)(Wt):"",[Wt]),qr=(0,w.useRef)(Wt);qr.current=Wt,(0,w.useEffect)(()=>{Vr(e??"")},[e]),(0,w.useEffect)(()=>{L.current=!1,or(Ne),Vt(null),Wr(!1),Fe(null)},[Ue,Ne,e]);async function In(D,q,se){let fe=Hi(le,a,Pt),Ot=new yo.PaymentAPI(le,{telemetry:!1}),Qt=!1;try{let me=D.idempotencyKey===void 0?void 0:(0,de.resolveIdempotencyKey)(D.idempotencyKey),at=(0,wt.readCachedInlineSession)(q,se),re=(0,wt.readCachedInlineIdempotencyKey)(q,se);at?.canonicalIdentity===se&&re&&re.canonicalIdentity===void 0&&((0,wt.persistCachedInlineIdempotencyKey)(q,se,re.idempotencyKey),re={...re,canonicalIdentity:se});let h=me??(re?.canonicalIdentity===se?re.idempotencyKey:void 0),m,N=!1;fe.log({name:at?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let A=at?.sid??null,te=null,Te,Rt,Me=!1;if(A)try{te=await Ot.getUnifiedCheckoutSession(A,at?.nonce),at&&at.canonicalIdentity===void 0&&((0,wt.legacyCachedSessionMatchesDraft)(te.data.session,D)?((0,wt.persistCachedInlineSession)(q,se,A,at.nonce??te.data.session?.clientSecret),re&&re.canonicalIdentity===void 0&&((0,wt.persistCachedInlineIdempotencyKey)(q,se,re.idempotencyKey),h??(h=re.idempotencyKey))):((0,wt.clearCachedInlineCheckout)(q,se),re=null,h=me,A=null,te=null));let ze=te?.data.session?.status,qt=te?.data.session,Ae=qt?.clientSecret||at?.nonce;if(A&&qt?.buyerIdentified===!1&&Ae&&(Rt=ia(Ot,A,Ae,D.account)),A&&te&&ze==="complete"){if((0,Dn.wasSessionRecentlyCompleted)(A))return{sid:A,result:te};(0,wt.clearCachedInlineCheckout)(q,se),A=null,te=null,N=!0}}catch{fe.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),at?.canonicalIdentity===void 0?((0,wt.clearCachedInlineCheckout)(q,se),h=me):(0,wt.clearCachedInlineSession)(q,se),A=null}if(!A){!me&&(N||!h)&&(h=(0,de.resolveIdempotencyKey)(),m=h),h&&(0,wt.persistCachedInlineIdempotencyKey)(q,se,h);let ze=fe.now(),qt=0;fe.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ae={...D,idempotencyKey:h,avsCheck:!!K,avsConfig:typeof K=="object"?K:void 0,checkoutType:"embedded_checkout",checkoutLayout:al(Ve,oe)};Object.defineProperty(Ae,yo.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Ce=>{qt=Math.max(qt,Ce)}}});let ne=()=>{od(fe,"session_create",ze,qt)},ue=Ce=>{ad(fe,Ce,"session_create",ze,qt)&&k({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(D.checkoutMode==="confirm"||D.checkoutMode==="auto")&&_c();try{if((0,de.isDetachedSessionEligible)(Ae)){let Ce=await Ot.createDetachedSession(Ae);Ce.claimed.catch(()=>{}),te=Ce.shell,A=Ce.sessionId,Rt=Ce.claim;let Ye=fe.now();fe.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Te=Ce.claimed.then($t=>{let yt=$t.data.session?.id??Ce.sessionId;return yt&&(0,wt.persistCachedInlineSession)(q,se,yt,$t.data.session?.clientSecret??Ce.nonce),od(fe,"session_claim",Ye),ne(),$t},$t=>{throw(0,wt.clearCachedInlineSession)(q,se),ad(fe,$t,"session_claim",Ye,0)&&k({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),$t}).finally(()=>Qa(fe)),Te.catch(()=>{}),Qt=!0,fe.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),fe.performance({stage:"session_shell",durationMs:fe.now()-ze,durationMode:"machine",requestCategory:"session_create",attempt:qt,statusClass:"2xx",paymentMethodCategory:"card"})}else te=await Ot.createAndFetchSession(Ae),ne()}catch(Ce){throw ue(Ce),Ce}A=te.data.session?.id??A??"",A&&!Te&&(0,wt.persistCachedInlineSession)(q,se,A,te.data.session?.clientSecret)}let Oe=te?.data.session;return!Rt&&A&&Oe?.buyerIdentified===!1&&Oe.clientSecret&&(Rt=ia(Ot,A,Oe.clientSecret,D.account)),{sid:A??"",result:te,sdkGeneratedIdempotencyKey:m,...Te?{claimed:Te}:{},...Rt?{claim:Rt}:{},...Me?{claimRequiresIdentity:!0}:{}}}finally{Qt||Qa(fe)}}let Vn=(0,w.useRef)(In);Do(()=>{Vn.current=In},[In]);let fn=(0,w.useCallback)(async(D,q)=>{let se=qr.current;if(!se)throw new de.FloPayError("createSession is required to bootstrap checkout.","validation_error");let fe=xs(se,D),Ot=(0,wt.serializeCreateParams)(fe),Qt=(0,wt.hashCreateParams)(fe),me=Ki.get(Ot);if(!me){let h={canonicalIdentity:Ot,promise:Vn.current(fe,Qt,Ot),consumers:0,settled:!1};me=h,Ki.set(Ot,h);let m=()=>{h.settled=!0,nd(Ot,h)};h.promise.then(m,m)}me.consumers+=1;let at=!1,re=()=>{at||(at=!0,me.consumers-=1,nd(Ot,me))};q?.(re);try{let h=await me.promise;mn.current=Ot,D&&(En(_n),$r(Oe=>ic(Oe,D)));let{sid:m,result:N,claimed:A,claim:te,claimRequiresIdentity:Te}=h;if(ir.current=te,Ur(Te===!0),pt(N),N.data.session&&ce(N.data.session),m&&Vr(m),A){ar.current+=1;let Oe=ar.current;pr.current=A,en(!0),A.then(ze=>{ar.current===Oe&&(pr.current===A&&(pr.current=null),pt(ze),ze.data.session&&ce(ze.data.session),en(!1),Ur(!1))},ze=>{ar.current===Oe&&(pr.current===A&&(pr.current=null),en(!1),Ur(!1),jt(ze instanceof de.FloPayError?ze:new de.FloPayError(ze instanceof Error?ze.message:"Failed to create session","api_error")))})}else ar.current+=1,pr.current=null,en(!1),Ur(!1);let{flopay:Rt,paypalFlopay:Me}=await nl(N,{billingApiUrl:le,locale:d,telemetry:a}).catch(Oe=>{throw cc(Oe,m||N.data.session?.id)});return Fr(Rt,Me),vr(!1),h}catch(h){throw mn.current===Ot&&(mn.current=null),h}finally{q||re()}},[_n,Fr,d,le,a]),Wn=(0,w.useRef)(Br);Wn.current=Br;let $n=(0,w.useRef)(fn);$n.current=fn;let To=(0,w.useCallback)(async D=>{if(!vp(D)||Cr)return{sessionId:Kt,session:C};br(!0);try{let q=await fn(D);return{sessionId:q.sid,session:q.result.data.session??null}}finally{br(!1)}},[fn,Cr,Kt,C]),no=(0,w.useCallback)(async D=>{let q=ir.current;if(!q)return;let se=ar.current,fe=await q(D);ar.current===se&&(pt(fe),fe.data.session&&ce(fe.data.session))},[]),go=(0,w.useCallback)(async()=>{await pr.current},[]),ho=(0,w.useCallback)(async()=>(await go(),{proceed:!0}),[go]);(0,w.useEffect)(()=>{let D=!1,q,se=++gt.current;Be(),jt(null),Qr(0);let fe=()=>{D=!0,gt.current===se&&(gt.current+=1,Be())},Ot=qr.current;if(Ue&&Ot)return Ar(tn),vr(!1),mn.current===Ue?fe:(ce(sc(Ot,We)),(async()=>{let at=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),re=tn==="auto"&&!L.current&&!at;re&&(or(null),Vt(null),Fe("processing"));let h=!1;try{let m=await $n.current(void 0,Te=>{q=Te});h=!0;let N=m.result.data.session??null;Tt.current=Ns(m.result);let A=rl(m.result),te=(0,Dn.wasSessionRecentlyCompleted)(m.sid||N?.id);if(!D&&re&&N&&!A&&!te){L.current=!0,await yp(Ue,m.sdkGeneratedIdempotencyKey,()=>Wn.current(N,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:m.result.autoProcessingError,initialAutoProcessingPending:m.result.autoProcessingPending,autoProcessingAttempted:m.result.autoProcessingAttempted,sessionId:m.sid||N.id}));return}!D&&re&&((A||te)&&(L.current=!0),Fe(null),Vt(null))}catch(m){if(D)return;let N=hi(m);if(re&&N==="session_auto_completed"){L.current=!0,Fe("success"),await Za(600),D||((0,Qe.invokeMerchantCallback)(()=>{Yt.current?.({status:"succeeded"})}),Fe(null),Vt(null));return}if(re&&(Fe(null),Vt(null)),!h){let te=dc(m),Te=(0,de.toPublicCheckoutInitError)(m,te?{stage:"provider_load",provider:"stripe",...te}:{stage:"session_request"});(te||!(m instanceof de.FloPayError))&&(0,Qe.invokeMerchantCallback)(()=>Ge.current?.(Te)),jt(Te);return}let A=m instanceof de.FloPayError?m:new de.FloPayError(m instanceof Error?m.message:"Failed to create session","api_error");jt(A)}finally{q?.(),q=void 0}})(),()=>{fe(),q?.()});vr(!0);async function Qt(){let at=!1,re=!1,h=null;try{let m=new yo.PaymentAPI(le,{telemetry:!1}),N=await m.getUnifiedCheckoutSession(He,t);if(re=!0,h=N,D)return;pt(N);let A=N.data.session??null;if(ce(A),!A)throw new de.FloPayError("No session data returned","api_error");let te=A.checkoutMode;if(te==="setup")throw new de.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(A.status==="authorized"){vr(!1),(0,Qe.invokeMerchantCallback)(()=>{Yt.current?.(io(A,He)),fo.current?.(A.successUrl??"")});return}if(A.status==="complete"){vr(!1),(0,Qe.invokeMerchantCallback)(()=>{fo.current?.(A.successUrl??"")});return}if(A.status==="expired")throw gi(A);at=!0;let Te=We??te??"full";Ar(Te),ar.current+=1;let Rt=A.clientSecret||t;ir.current=A.buyerIdentified===!1&&Rt?ia(m,He,Rt,{...A.customer?.id?{userId:A.customer.id}:{}}):void 0,en(!1),Ur(!1);let Me=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Oe=rl(N);if(Te==="auto"&&!L.current&&!Me&&!Oe){L.current=!0;let ze=me(N);try{if(await Wn.current(A,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ze,sessionId:He||A.id}),D)return;await ze,D||vr(!1);return}catch{if(D)return;await ze,D||vr(!1);return}}await me(N),D||vr(!1)}catch(m){if(D)return;let N=ac(m,at);if(at&&k({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),N){let{errorCode:Rt,stage:Me,...Oe}=N;tl(le,a,Pt,Rt,Me,Oe)}if(N?.stage==="provider_load"&&(We??h?.data.session?.checkoutMode??"full")==="full"&&oc(h,x,f)){let Rt=fp({billingApiUrl:le,locale:d,telemetry:a});ct.current=Rt,Fr(Rt,null),Qr(1),vr(!1);return}let A=N?.stage==="provider_load",te="session_request";A?te="provider_load":re&&(te="post_session");let Te=(0,de.toPublicCheckoutInitError)(m,{stage:te,provider:"stripe",sessionId:He||void 0});(A||!(m instanceof de.FloPayError))&&(0,Qe.invokeMerchantCallback)(()=>Ge.current?.(Te)),jt(Te),vr(!1)}}async function me(at){let{flopay:re,paypalFlopay:h,...m}=await nl(at,{billingApiUrl:le,locale:d,telemetry:a});Tt.current={publishableKey:m.publishableKey,paypalPublishableKey:m.paypalPublishableKey},Fr(re,h),Qr(0)}return Qt(),fe},[We,Ue,tn,Un,t,x,f]);let Wo=(0,w.useCallback)(async()=>{if(!st||Or!==1)return;let D=gt.current;Qr(2);try{let{flopay:q,paypalFlopay:se}=await nl(st,{billingApiUrl:le,locale:d,telemetry:a});if(gt.current!==D)return;Be(),Fr(q,se),Qr(0)}catch(q){if(gt.current!==D)return;let{errorCode:se,stage:fe,...Ot}=As(q);tl(le,a,Pt,se,fe,Ot)}},[Be,Fr,d,Or,le,a,Pt,st]),Hn=!!(He&&(C?.clientSecret||t)),Tn=xr||!Hn,Po=(0,w.useCallback)(async()=>{if(!(xr||!Hn||!C)){tr(!0),or(null);try{await Br(C,{attempt3DS:!0,fallbackToFull:!0,sessionId:He||C.id})}finally{tr(!1)}}},[He,xr,Hn,Br,C]),Nt=(0,de.resolveDirectPaypalConfig)(st?.data.paypal,ft),oo=rl(st),rn=(0,w.useMemo)(()=>{if(!(!st||!C||!st.data.stripe?.publishableKey))return{billingApiUrl:le}},[st,C,le]),gn=!!(r&&!Ve&&oe==="buttons"&&Y&&tn==="full"),_r=!!(He&&((0,de.isMountableVaultBlock)(C?.vault)||(0,Fn.canRecoverHostedCardForm)(C))),ot=(0,w.useMemo)(()=>({session:C,loading:Pr,error:Et,checkoutMode:Dr,inlineSessionDraft:Wt,applyInlineSessionPatch:gn?To:void 0,inlineSessionPatchProcessing:Cr,claimPending:Nr,claimRequiresIdentity:Hr,claimBuyerIdentity:no,waitForDataAttachment:go}),[C,Pr,Et,Dr,Wt,gn,To,Cr,Nr,Hr,no,go]),yr=!!r&&oe==="buttons"&&!oo&&!_r&&(!At||!rn),Zt=St?(0,O.jsx)(on,{status:St,errorMessage:un,authorized:Lr}):null;if(Pr&&!_r){if(p)return(0,O.jsxs)(O.Fragment,{children:[p,Zt]});if(oe==="buttons"){let D=Ee?.buttonsLayout?.cardButton?.borderRadius??Ee?.appearance.variables?.borderRadius??8,q=se=>(0,O.jsx)("div",{style:{height:se,borderRadius:D,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[x&&q(jo),f&&(v||be)&&q(jo),f&&q(jo),(0,O.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Zt]})}return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,O.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,O.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Zt]})}return Et?y?(0,O.jsx)(Bn.Provider,{value:ot,children:y(Et)}):(0,O.jsx)(Bn.Provider,{value:ot,children:(0,O.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Et.message})}):yr?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Bn.Provider,{value:ot,children:(0,O.jsx)(bp,{onButtonClick:ve,paymentMethodLayout:he,showPayPal:x,showStripe:f,showApplePay:v,showGooglePay:be,theme:pe,buttonsTheme:kt,buttonsStyles:mt,cardButtonContent:j,cardBackButtonContent:Je,cardTitleContent:Ze})}),Zt]}):oo&&C&&Nt?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Bn.Provider,{value:ot,children:(0,O.jsxs)("div",{className:vt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Gt&&(0,O.jsx)(ya,{icon:!1,children:Gt}),rr==="retrying"&&(0,O.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),rr==="exhausted"&&(0,O.jsxs)("div",{role:"alert",children:[(0,O.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,O.jsx)("button",{type:"button",onClick:Io,children:"Retry PayPal"})]}),rr!=="exhausted"&&(0,O.jsx)("div",{"aria-hidden":rr==="retrying"?!0:void 0,style:rr==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,O.jsx)(wc,{sessionId:He,nonce:C.clientSecret||void 0,billingApiUrl:le,email:C.customer?.email||Wt?.account?.email,billingName:[C.customer?.firstName,C.customer?.lastName].filter(Boolean).join(" ")||[Wt?.account?.firstName,Wt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:no,clientId:Nt.clientId,environment:Nt.environment,currency:(C.currency??"usd").toUpperCase(),isSubscription:C.mode==="subscription",providerObjectType:Nt.providerObjectType,approvalPresentation:Nt.approvalPresentation,existingOrderId:Nt.existingOrderId,onComplete:S,onErrorChange:or,onDecline:_,onCancel:W,onButtonClick:ve,runBeforeButtonClick:ho,onInitializationStateChange:_o,allowAutomaticRetry:Gr===0,session:C,telemetry:a,telemetryContext:Pt,onInstrument:Ht,debug:F},`${ae}:paypal-init-${Gr}`)})]})}),Zt]}):Dr==="confirm"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Bn.Provider,{value:ot,children:(0,O.jsx)(Na,{flopay:At,paypalFlopay:G,options:rn??{billingApiUrl:le},onInstrument:Ht,children:(0,O.jsxs)("div",{className:vt,children:[Gt&&(0,O.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Gt}),Lt?Lt({onConfirm:Po,isProcessing:Tn}):(0,O.jsx)("button",{type:"button",onClick:Po,disabled:Tn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Tn?"not-allowed":"pointer",opacity:Tn?.6:1},children:xr?"Processing...":Mt??"Confirm Purchase"})]})},ae)}),Zt]}):(!At||!rn)&&!(_r&&Dr==="full")?(0,O.jsx)(O.Fragment,{children:Zt}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Bn.Provider,{value:ot,children:(0,O.jsxs)(Na,{flopay:At,paypalFlopay:G,options:rn??{billingApiUrl:le},onInstrument:Ht,children:[Or===1&&(0,O.jsx)("button",{type:"button",onClick:Wo,children:"Retry payment methods"}),Ve?(0,O.jsxs)(O.Fragment,{children:[Gt&&(0,O.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Gt}),(0,O.jsx)(Cp,{sessionId:He,nonce:C?.clientSecret||void 0,billingApiUrl:le,session:C,submitLabel:_e,walletPresentation:H,paymentMethodLayout:he,moreOptionsLabel:Re,children:Ve})]}):(0,O.jsx)(Wi,{sessionId:He,nonce:C?.clientSecret||void 0,telemetry:a,email:C?.customer?.email||Wt?.account?.email,userId:C?.customer?.id||Wt?.account?.userId,firstName:C?.customer?.firstName||Wt?.account?.firstName,lastName:C?.customer?.lastName||Wt?.account?.lastName,totalAmount:C?Math.round((0,de.buildCheckoutDisplayData)(C).total*100):0,currency:C?.currency?.toLowerCase()??"usd",onComplete:S,onError:P,onDecline:_,onCancel:W,error:Gt,onErrorChange:or,showPayPal:x,showStripe:f,walletPresentation:H,enabledPaymentMethods:Or?[]:X??st?.data.stripe?.enabledPaymentMethods??C?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:st?.data.stripe?.enabledPaymentMethodCountries,showApplePay:v,showGooglePay:be,layout:oe,paymentMethodLayout:he,moreOptionsLabel:Re,theme:pe,buttonsTheme:kt,buttonsStyles:mt,appearance:$e,cardButtonContent:j,cardBackButtonContent:Je,cardTitleContent:Ze,onButtonClick:ve,onBeforeButtonClick:Y,onBuyerIdentityReady:no,enableAVS:K,...rt?{cardFieldOrder:rt}:{},...Se===void 0?{}:{showCardBrandIcons:Se},...Ke===void 0?{}:{showCardFieldLabels:Ke},...ee===void 0?{}:{cardFieldLabels:ee},...V===void 0?{}:{cardFieldPlaceholders:V},...Pe===void 0?{}:{cardAutoFocus:Pe},...J?{onCardFieldsReady:J}:{},...ut?{onCardFieldsFailed:ut}:{},...ye===void 0?{}:{cardFieldsTimeoutMs:ye},...ke?{cardPreFormSlot:ke}:{},avsLayout:xe,country:C?.customer?.country,city:C?.customer?.city,state:C?.customer?.state,onCountryChange:$,onZipChange:R,avsCheck:!!K,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:al(Ve,oe),className:vt,submitLabel:_e,directPaypal:Nt,isSubscription:C?.mode==="subscription",session:C,dataAttachmentPending:Nr,dataAttachmentRequiresIdentity:Hr,debug:F})]},ae)}),Zt]})}function Cp({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,paymentMethodLayout:d,moreOptionsLabel:p,children:y}){return(0,O.jsx)(O.Fragment,{children:w.default.Children.map(y,S=>{if(!w.default.isValidElement(S))return S;let P=S.props,g={};return P.sessionId||(g.sessionId=e),!P.nonce&&t&&(g.nonce=t),P.billingApiUrl||(g.billingApiUrl=r),P.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),P.walletPresentation===void 0&&(g.walletPresentation=s),P.paymentMethodLayout===void 0&&d!==void 0&&(g.paymentMethodLayout=d),P.moreOptionsLabel===void 0&&p!==void 0&&(g.moreOptionsLabel=p),n?.customer&&(P.email||(g.email=n.customer.email),P.userId||(g.userId=n.customer.id),P.firstName||(g.firstName=n.customer.firstName),P.lastName||(g.lastName=n.customer.lastName)),Object.keys(g).length===0?S:w.default.cloneElement(S,g)})})}function bp({onButtonClick:e,paymentMethodLayout:t,showPayPal:r,showStripe:n=!0,showApplePay:a,showGooglePay:s,theme:d,buttonsTheme:p,buttonsStyles:y,cardButtonContent:S,cardBackButtonContent:P,cardTitleContent:g}){let[_,W]=(0,w.useState)(!1),$=(0,w.useMemo)(()=>(0,de.resolveTheme)(d),[d]),R=(0,w.useMemo)(()=>{let v=$?.buttonsLayout??(0,de.resolveButtonsLayoutTheme)(p);return y?{...v,...y,cardButton:{...v.cardButton,...y.cardButton},cardFormContainer:{...v.cardFormContainer,...y.cardFormContainer},backButton:{...v.backButton,...y.backButton},backButtonIcon:{...v.backButtonIcon,...y.backButtonIcon},submitButton:{...v.submitButton,...y.submitButton},title:{...v.title,...y.title}}:v},[$,p,y]),x=$?.buttonsLayout?.cardButton?.borderRadius??$?.appearance.variables?.borderRadius??8,f=v=>(0,O.jsx)("div",{style:{height:v,borderRadius:x,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),H=S===void 0?{boxSizing:"border-box",height:jo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let v=R.cardInputBorder??"#e5e7eb",be=R.cardInputBackground??"white",F=na(P),oe=na(g);return(0,O.jsxs)("div",{style:{backgroundColor:R.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...R.cardFormContainer},children:[(0,O.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,O.jsxs)("button",{type:"button",onClick:()=>W(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:F?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...R.backButton},children:[(0,O.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...R.backButtonIcon},children:(0,O.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,O.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,O.jsx)(aa,{content:P})]}),oe?(0,O.jsx)("div",{style:{flex:1}}):(0,O.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...R.title},children:(0,O.jsx)(Ma,{content:g})})]}),(0,O.jsx)("div",{style:{backgroundColor:be,border:`1px solid ${v}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsxs)("div",{style:{display:"flex"},children:[(0,O.jsx)("div",{style:{flex:1,backgroundColor:be,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsx)("div",{style:{flex:1,backgroundColor:be,borderTop:"none",borderRight:`1px solid ${v}`,borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,O.jsx)("div",{style:{backgroundColor:be,border:`1px solid ${v}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...R.submitButton,opacity:.5}}),(0,O.jsx)("style",{children:`
|
|
41
41
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
42
42
|
@keyframes flopay-interim-expand {
|
|
43
43
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
44
44
|
40% { opacity: 1; }
|
|
45
45
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
46
46
|
}
|
|
47
|
-
`})]})}let Y={paypal:r&&f(zo),wallets:n&&(a||s)&&f(zo),card:n&&(t?f(zo):(0,O.jsx)("button",{type:"button",onClick:()=>{e?.("card"),V(!0)},style:{width:"100%",...H,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:k.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...k.cardButton},onMouseDown:b=>{b.currentTarget.style.transform="scale(0.985)"},onMouseUp:b=>{b.currentTarget.style.transform="scale(1)"},children:(0,O.jsx)(oa,{content:w})}))};return(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[se.DEFAULT_PAYMENT_METHOD_ORDER.map(b=>(0,O.jsx)(R.default.Fragment,{children:Y[b]},b)),(0,O.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var In=require("react/jsx-runtime"),hp=44;function od(e){return new Promise(t=>setTimeout(t,e))}var ad=15e3;function ol(e,t){return new Ir.FloPayError(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function Pp(e,t){return new Promise((r,n)=>{let a=()=>n(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(s=>{t.removeEventListener("abort",a),r(s)},s=>{t.removeEventListener("abort",a),n(s)})})}function vp(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function Cp(e,t){return e instanceof Ir.FloPayError?e:new Ir.FloPayError(e instanceof Error?e.message:t,"api_error")}function bp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Sp(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function id({sessionId:e,nonce:t,createSession:r,getSession:n,paymentMethodId:a,checkoutMethod:s,clientId:d,products:p,items:m,subscriptions:w,account:h,successUrl:g,cancelUrl:_,couponCodes:V,tagsData:W,utmMetadata:k,billingApiUrl:A,locale:f,theme:H,appearance:Y,buttonsTheme:b,buttonsStyles:be,onSuccess:x,onError:oe,onDecline:ge,children:Ie,disabled:ce=!1,type:Rt="button",style:mt,...q}){let Ve=(0,pt.useMemo)(()=>(0,Ir.resolveBillingApiUrl)(A),[A]),We=(0,pt.useMemo)(()=>Sp({createSession:r,clientId:d,products:p,items:m,subscriptions:w,account:h,successUrl:g,cancelUrl:_,couponCodes:V,tagsData:W,utmMetadata:k}),[h,_,d,V,r,p,m,w,g,W,k]),[Ne,ve]=(0,pt.useState)(!1),[G,K]=(0,pt.useState)(null),[Ze,Se]=(0,pt.useState)(null),[qe,Z]=(0,pt.useState)(!1),[j,he]=(0,pt.useState)(null),[X,Pt]=(0,pt.useState)(null),pe=(0,pt.useRef)(!0),we=(0,pt.useRef)(null),Ae=(0,pt.useRef)(null),Ce=(0,pt.useRef)(!1),kt=(0,pt.useRef)(X),Pe=(0,pt.useRef)(x),Be=(0,pt.useRef)(oe),at=(0,pt.useRef)(ge),yt=(0,pt.useCallback)(v=>Ii(we,async Q=>{try{return await v(Q)}catch(ee){throw Q.aborted?ma(ee):ee}}),[]);(0,pt.useEffect)(()=>{kt.current=X},[X]),(0,pt.useEffect)(()=>{Pe.current=x},[x]),(0,pt.useEffect)(()=>{Be.current=oe},[oe]),(0,pt.useEffect)(()=>{at.current=ge},[ge]),(0,pt.useEffect)(()=>(pe.current=!0,()=>{pe.current=!1,we.current?.abort(),Ae.current?.abort()}),[]),(0,pt.useEffect)(()=>{if(typeof window>"u")return;let v=Q=>{Q.key==="Escape"&&Pt(null)};return window.addEventListener("keydown",v),()=>{window.removeEventListener("keydown",v)}},[]);let Mt=(0,pt.useCallback)((v,Q=qa)=>{at.current?.(kr(Q,v,{code:v.code,declineCode:v.declineCode}))},[]),le=(0,pt.useCallback)(async v=>{pe.current&&(Se(null),Z(v.result.status==="authorized"),K("success"),await od(600),pe.current&&(0,He.invokeMerchantCallback)(()=>Pe.current?.(v)))},[]),It=(0,pt.useCallback)(async(v,Q)=>{if(!pe.current)return;!!Q?.emitDecline&&(0,Ir.isDeclineCallbackFailure)(v)?Mt(v,Q?.method):Be.current?.(v),Se(v.message),Z(!1),K("error"),await od(400)},[Mt]),Vt=(0,pt.useCallback)(async(v,Q,ee)=>{let $=v.data.session??null;if(!$)throw Ro(new Ir.FloPayError("No session data returned","api_error"),Q);let nt=ee?.nonce||$.clientSecret||t;if(lo($)){await le({result:so($,Q),session:$,sessionId:$.id||Q,autoCompleted:!1});return}if($.status==="expired")throw Ro(gi($),$.id||Q);try{if(v.autoProcessingPending){let F=v.autoProcessingPending,D=new Yi.PaymentAPI(Ve),L=await yt(Ct=>D.waitForCheckoutSessionCompletion(F.sessionId,{initialDelayMs:F.retryAfterMs,nonce:nt,statusUrl:F.statusUrl,signal:Ct})),T=ko(L,$),I=L.autoProcessingError?.type==="3ds_required"&&!(0,Ir.isMerchantAuthRequired)(L.autoProcessingError)&&L.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:L.autoProcessingError.nextActionRedirectUrl}:null;if(I&&Q&&nt){let Ct=ja(Ve,Q,$),Mr=await yt(bt=>fa(I,{billingApiUrl:Ve,sessionId:Q,nonce:nt,session:$,signal:bt,telemetry:!0,...Ct.telemetry?{challengeTelemetry:Ct.telemetry}:{}})).finally(Ct.release);await le({result:Mr,session:$,sessionId:$.id||Q,autoCompleted:!1});return}if(L.autoProcessingError)throw Qn(L.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:L.autoProcessingError.checkoutMethod});if(!lo(T))throw sa(T);await le({result:so(T,Q),session:T,sessionId:T.id||Q,autoCompleted:!1});return}if(v.autoProcessingError){let F=v.autoProcessingError.nextActionRedirectUrl;if(v.autoProcessingError.type==="3ds_required"&&!(0,Ir.isMerchantAuthRequired)(v.autoProcessingError)&&F&&Q&&nt){let D=await yt(Ct=>Ec({billingApiUrl:Ve,sessionId:Q,nonce:nt,nextActionRedirectUrl:F,signal:Ct}));if(D.status==="declined")throw Qn({type:D.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:D.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:v.autoProcessingError.checkoutMethod});let T=await new Yi.PaymentAPI(Ve).waitForCheckoutSessionCompletion(Q,{initialDelayMs:0,nonce:nt}),I=ko(T,$);if(!lo(I))throw Qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:v.autoProcessingError.checkoutMethod});await le({result:so(I,Q),session:I,sessionId:I.id||Q,autoCompleted:!1});return}throw Qn(v.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:v.autoProcessingError.checkoutMethod})}if(ee?.fromCreateSession&&v.autoProcessingAttempted===!0)throw Qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let u=await ga({billingApiUrl:Ve,sessionId:Q??$.id,session:$,nonce:nt});if(u.type==="next_action_required"&&nt){let F=Q??$.id,D=ja(Ve,F,$),L=await yt(T=>fa(u,{billingApiUrl:Ve,sessionId:F,nonce:nt,session:$,signal:T,telemetry:!0,...D.telemetry?{challengeTelemetry:D.telemetry}:{}})).finally(D.release);await le({result:L,session:$,sessionId:$.id||F,autoCompleted:!1});return}if(u.type!=="success")throw Qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await le({result:u.result,session:$,sessionId:$.id||Q,autoCompleted:!1})}catch(u){let F=$.id||Q,D=Ro(Va(u),F);if(D.code==="three_ds_aborted")return;if(D.code==="checkout_processing_timeout"){if(!pe.current)return;he(D.message),(0,He.invokeMerchantCallback)(()=>Be.current?.(D));return}await It(D,{emitDecline:!0,method:D.checkoutMethod??qa}),bp(D,F)&&F&&pe.current&&Pt({sessionId:F,errorMessage:D.message,nonce:nt||void 0,payPalOrderId:D.orderId})}},[t,Ve,yt,It,le]),xe=(0,pt.useCallback)(async v=>{let Q=new AbortController;Ae.current=Q;let ee=!1,$=setTimeout(()=>{ee=!0,Q.abort()},ad);try{let nt=await Pp((async()=>v({signal:Q.signal}))(),Q.signal);if(!pe.current)return null;if(!vp(nt))throw ol("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:nt.sessionId,nonce:nt.nonce}}catch(nt){if(!pe.current)return null;throw nt instanceof Ir.FloPayError&&nt.code==="session_fetch_failed"?nt:ee?ol(`getSession did not resolve within ${ad/1e3} seconds.`):ol("Could not fetch the one-click session.",nt)}finally{clearTimeout($),Ae.current===Q&&(Ae.current=null)}},[]),Oe=(0,pt.useCallback)(async v=>{if(q.onClick?.(v),v.defaultPrevented||ce||Ne||(Pt(null),he(null),Ce.current))return;let Q=[e,n,We].filter(Boolean).length;if(Q>1){let ee=new Ir.FloPayError("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await It(ee),pe.current&&(K(null),Se(null));return}if(Q===0){let ee=new Ir.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await It(ee),pe.current&&(K(null),Se(null));return}Ce.current=!0,ve(!0),Se(null),Z(!1),K("processing");try{let ee=new Yi.PaymentAPI(Ve);if(e){let $=await ee.getUnifiedCheckoutSession(e,t);await Vt($,e);return}if(n){let $=await xe(n);if(!$)return;let nt=await ee.getUnifiedCheckoutSession($.sessionId,$.nonce);await Vt(nt,$.sessionId,{nonce:$.nonce});return}bc();try{let $=await ee.createAndFetchSession({...We});await Vt($,$.data.session?.id??null,{fromCreateSession:!0})}catch($){if(hi($)==="session_auto_completed"){await le({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw $}}catch(ee){await It(Ro(Cp(ee,"Automatic payment failed. Please try again."),e))}finally{Ce.current=!1,pe.current&&(K(null),Se(null),ve(!1))}},[q.onClick,We,ce,xe,n,Ne,t,Vt,Ve,e,It,le]),Ke=(0,pt.useCallback)(v=>{let Q=kt.current;Pt(null),Pe.current?.({result:v,session:null,sessionId:Q?.sessionId??null,autoCompleted:!1})},[]),vt=(0,pt.useCallback)(v=>{Be.current?.(v)},[]),it=(0,pt.useCallback)(v=>{at.current?.(v)},[]),ft=(0,pt.useMemo)(()=>(0,Ir.resolveTheme)(H),[H]),Lt=(0,pt.useMemo)(()=>{let v=ft?.buttonsLayout??(0,Ir.resolveButtonsLayoutTheme)(b);return be?{...v,...be,cardButton:{...v.cardButton,...be.cardButton}}:v},[ft,b,be]),Qe=(0,pt.useMemo)(()=>{let v=ft?.appearance;return Y?v?{...v,...Y,variables:{...v.variables,...Y.variables}}:Y:v},[Y,ft]),st=Qe?.variables,de=st?.colorPrimary??"#4A49FF",Ot=st?.colorPrimaryHover??(0,Xs.darkenHex)(de,.12),et=st?.borderRadius??"8px";return(0,In.jsxs)(In.Fragment,{children:[(0,In.jsx)("button",{...q,type:Rt,onClick:Oe,disabled:ce||Ne,"aria-busy":Ne,style:{width:"100%",...Ie===void 0?{boxSizing:"border-box",height:hp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Lt.cardButton,...Ys({themeBundle:ft,resolvedPrimaryColor:de,resolvedBorderRadius:et,submitButtonStyle:Lt.submitButton,explicitPrimaryColor:st?.colorPrimary}),fontSize:Lt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ce||Ne?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ce||Ne?.6:1,...mt},onMouseEnter:v=>{q.onMouseEnter?.(v),!v.defaultPrevented&&!ce&&!Ne&&(ft||st?.colorPrimary)&&(v.currentTarget.style.backgroundColor=Ot)},onMouseLeave:v=>{q.onMouseLeave?.(v),!v.defaultPrevented&&(ft||st?.colorPrimary)&&(v.currentTarget.style.backgroundColor=de)},onMouseDown:v=>{q.onMouseDown?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(0.985)")},onMouseUp:v=>{q.onMouseUp?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(1)")},children:(0,In.jsx)(oa,{content:Ie})}),j&&(0,In.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:j}),G&&(0,In.jsx)(rn,{status:G,errorMessage:Ze,authorized:qe}),X&&(0,In.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:v=>{v.target===v.currentTarget&&Pt(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,In.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,In.jsx)(Gi,{sessionId:X.sessionId,nonce:X.nonce,checkoutMode:"full",billingApiUrl:Ve,locale:f,theme:H,...Qe?{appearance:Qe}:{},buttonsTheme:b,buttonsStyles:be,initialErrorMessage:X.errorMessage,initialPayPalOrderId:X.payPalOrderId,cardTitleContent:null,onComplete:Ke,onError:vt,onDecline:it})})})]})}var Ji=require("@flopay/js/card-setup"),Yr=require("@flopay/shared"),Gt=require("react");var al=require("@flopay/shared"),wp=require("@flopay/shared");function Xi(e){let t=(0,al.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var to=require("react/jsx-runtime"),ei=class extends Yr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function fo(e,t={}){let r=e instanceof Yr.FloPayError?e:void 0,n=r?.statusCode,a=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new ei(r?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),r?.type??"api_error",{code:t.code??r?.code??"card_setup_load_failed",retryable:a,...r?.param?{param:r.param}:{},...n===void 0?{}:{statusCode:n}})}function sd({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:d,buttonsStyles:p,loading:m=null,onReady:w,onComplete:h,onDecline:g,onCancel:_,onValidation:V,onError:W}){let[k,A]=(0,Gt.useState)(null),[f,H]=(0,Gt.useState)(null),[Y,b]=(0,Gt.useState)(null),[be,x]=(0,Gt.useState)(null),[oe,ge]=(0,Gt.useState)(null),Ie=(0,Gt.useRef)(!1),ce=(0,Gt.useRef)(!1),{vaultTheme:Rt,surface:mt,overlayTheme:q}=(0,Gt.useMemo)(()=>Xi({theme:a,appearance:d,buttonsStyles:p}),[a,d,p]),Ve=(0,Gt.useMemo)(()=>(0,Ka.mergeCardSetupSurface)(mt,s),[mt,s]),We=(0,Gt.useRef)(w),Ne=(0,Gt.useRef)(W),ve=(0,Gt.useRef)(h),G=(0,Gt.useRef)(g),K=(0,Gt.useRef)(_),Ze=(0,Gt.useRef)(V),Se=(0,Gt.useRef)(!1),qe=(0,Gt.useRef)(!1),Z=(0,Gt.useRef)(0);return We.current=w,Ne.current=W,ve.current=h,G.current=g,K.current=_,Ze.current=V,(0,Gt.useEffect)(()=>{let j=Z.current+1;return Z.current=j,()=>{queueMicrotask(()=>{Z.current===j&&(Se.current||qe.current||(qe.current=!0,(0,He.invokeMerchantCallback)(()=>{K.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Gt.useEffect)(()=>{let j=!0,he=(0,Yr.resolveBillingApiUrl)(r),X=new Ji.PaymentAPI(he,{telemetry:n});return A(null),H(null),b(null),Se.current=!1,qe.current=!1,(async()=>{try{if(!e.trim())throw new Yr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Yr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Pt=await X.getUnifiedCheckoutSession(e,t);if(!j)return;let pe=Pt.data.session;if(!pe||!(0,Yr.isCardSetupCheckoutSession)(pe))throw new Yr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let we=pe.vault;(0,Yr.isMountableVaultBlock)(we)||(we=await X.getVaultCapture(e,t));let Ae=(0,Yr.resolveVaultMountOptions)(we,{billingApiUrl:he,sessionId:e,nonce:t});if(!Ae)throw new Yr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!j)return;H(Ae),A(new Ji.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(Pt){if(!j)return;let pe=fo(Pt);Se.current=!0,b(pe),(0,He.invokeMerchantCallback)(()=>Ne.current?.(pe))}})(),()=>{j=!1,X.destroy()}},[r,t,e,n]),(0,Gt.useEffect)(()=>{if(!k)return;let j=!1;ce.current=!1,Ie.current=!1;let he=k.on("submitting",()=>{Ie.current=!0,ge(null),x("processing")}),X=k.on("complete",we=>{Se.current=!0,Ie.current=!1,x("success"),(async()=>(await new Promise(Ae=>setTimeout(Ae,600)),!ce.current&&(ce.current=!0,(0,He.invokeMerchantCallback)(()=>{ve.current?.({status:"succeeded",sessionId:e,...we.paymentMethod?{paymentMethod:we.paymentMethod}:{}})}),j||x(null))))()}),Pt=k.on("decline",we=>{Se.current=!0,Ie.current=!1,ge(we.message??null),x("error"),(0,He.invokeMerchantCallback)(()=>{G.current?.({status:"declined",sessionId:e,...we.declineReason?{reason:we.declineReason}:{},...we.message?{message:we.message}:{}})}),(async()=>(await new Promise(Ae=>setTimeout(Ae,400)),j||x(null)))()}),pe=k.on("challenge_dismissed",()=>{x(null)});return()=>{j=!0,he(),X(),Pt(),pe()}},[k,e]),Y?(0,to.jsx)("div",{role:"alert",children:Y.message}):!k||!f?.html?(0,to.jsx)(to.Fragment,{children:m}):(0,to.jsxs)(to.Fragment,{children:[be&&(0,to.jsx)(rn,{status:be,errorMessage:oe,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...q?{theme:q}:{}}),(0,to.jsx)(_o,{capture:k,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,verificationRequired:f.verificationRequired,theme:Rt,containerStyle:Ve,onReady:()=>{(0,He.invokeMerchantCallback)(()=>We.current?.())},onValidation:j=>{(0,He.invokeMerchantCallback)(()=>Ze.current?.(j))},onError:j=>{if(!j)return;Ie.current&&(Ie.current=!1,ge(j),x("error"),setTimeout(()=>x(null),400));let he=fo(new Error(j),{code:"card_setup_widget_failed",retryable:!0});(0,He.invokeMerchantCallback)(()=>Ne.current?.(he))}})]})}var ld=require("@flopay/js/card-setup"),Tn=require("@flopay/shared"),cd=require("@paypal/paypal-js"),qo=require("react");var ud=require("react/jsx-runtime");function dd({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:d,customer:{userId:p,email:m},onSubmitting:w,onConfirmed:h,onFailed:g,onAbandoned:_}){let V=(0,qo.useRef)(null),W=(0,qo.useRef)({onSubmitting:w,onConfirmed:h,onFailed:g,onAbandoned:_});W.current={onSubmitting:w,onConfirmed:h,onFailed:g,onAbandoned:_};let[k]=(0,qo.useState)(()=>(0,Jn.detectPayPalEnvironment)().inAppBrowser);return(0,qo.useEffect)(()=>{let A=!0,f,H=new ld.PaymentAPI(s,{telemetry:d}),Y={userId:p,email:m};return(async()=>{try{let b=await(0,cd.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),be=V.current;if(!A||!be)return;if(!b?.Buttons)throw new Tn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let x=b.Buttons({createVaultSetupToken:async()=>{W.current.onSubmitting();let oe=await H.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Tn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,Tn.isSettledSessionIntent)(oe))throw(0,Tn.settledSessionIntentError)(n);if(oe.provider!=="paypal"||oe.providerObjectType!=="setup_token")throw new Tn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return oe.providerObjectId},onApprove:async oe=>{let ge=oe.vaultSetupToken;if(!ge)throw new Tn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let Ie=await H.processPayment(Y.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:ge,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Tn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:Y});if(!Ie.ok)throw new Tn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:Ie.status});A&&W.current.onConfirmed()},onCancel:()=>{A&&W.current.onAbandoned()},onError:oe=>{if(!A)return;let{popupBlocked:ge}=(0,_e.classifyExternalMethodFailure)(oe,{inAppBrowser:k,handoffObserved:!1});W.current.onFailed(ge?new Error((0,_e.buildExternalMethodRecoveryMessage)("PayPal",!0,k)):oe,{code:ge?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>x.close(),await x.render(be)}catch(b){if(!A)return;W.current.onFailed(b,{code:"paypal_unavailable",retryable:!0})}})(),()=>{A=!1,f?.().catch(()=>{}),H.destroy()}},[s,e,r,m,t,k,a,n,d,p]),(0,ud.jsx)("div",{ref:V,"data-flopay-paypal-setup":""})}var yd=require("@flopay/js/card-setup"),Mn=require("@flopay/shared"),ro=require("@stripe/react-stripe-js"),md=require("@stripe/stripe-js"),Xr=require("react");var Wr=require("react/jsx-runtime"),fd={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},il=new Map;function Rp(e){let t=il.get(e);if(t)return t;let r=(0,md.loadStripe)(e).catch(n=>{throw il.delete(e),n});return il.set(e,r),r}function kp(e){return e?(0,Mn.toStripeAppearance)(e):void 0}function Ep(e){return(0,_e.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function pd(e){return e==="paypal"?"PayPal":(0,Mn.getStripeMethodDisplayName)(e)}function _p(){return typeof window>"u"?"":window.location.href}var Ip={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function gd(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:d}=e,[p]=(0,Xr.useState)(()=>Rp(t)),m=(0,Xr.useMemo)(()=>{let w=kp(d),h=(0,Mn.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:fd[r]?.types??[r],...h?{setupFutureUsage:h}:{},...w?{appearance:w}:{}}},[d,n,a,s,r]);return(0,Wr.jsx)(ro.Elements,{stripe:p,options:m,children:(0,Wr.jsx)(Tp,{...e})})}function Tp({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:d,themeId:p,buttonsLayout:m,onSubmitting:w,onConfirmed:h,onDeclined:g,onFailed:_,onValidation:V,onUnavailable:W}){let k=(0,ro.useStripe)(),A=(0,ro.useElements)(),[f,H]=(0,Xr.useState)(!1),[Y,b]=(0,Xr.useState)("loading"),[be,x]=(0,Xr.useState)(!1),[oe,ge]=(0,Xr.useState)(!1),Ie=(0,Xr.useRef)(!1),[ce]=(0,Xr.useState)(()=>(0,Jn.detectPayPalEnvironment)()),[Rt,mt]=(0,Xr.useState)(!1),q=(0,Xr.useCallback)((K,Ze)=>{if((0,_e.classifyExternalMethodFailure)(K,{inAppBrowser:ce.inAppBrowser,handoffObserved:!1}).popupBlocked){mt(!0),_(new Error((0,_e.buildExternalMethodRecoveryMessage)(pd(e),!0,ce.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}_(Ze.message===void 0?K:new Error(Ze.message),{code:Ze.code,retryable:!0})},[ce.inAppBrowser,e,_]),Ve=(0,Xr.useCallback)(async K=>{let Ze=!1,Se=!1,qe=()=>{!K||Ze||Se||(Se=!0,K.paymentFailed({reason:"fail"}))};if(!k||!A||Ie.current){qe();return}Ie.current=!0,H(!0);try{let Z=await A.submit();if(Z.error){qe(),V(Z.error.message??null);return}w();let j=await new yd.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,Mn.isSettledSessionIntent)(j))throw(0,Mn.settledSessionIntentError)(r);if(j.provider!=="stripe"||j.intentKind!=="setup")throw new Mn.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Ze=!0;let he=await k.confirmSetup({elements:A,clientSecret:j.clientSecret,confirmParams:{return_url:_p()},redirect:"if_required"});if(he.error){Ep(he.error)?g({...he.error.decline_code||he.error.code?{reason:he.error.decline_code??he.error.code}:{},...he.error.message?{message:he.error.message}:{}}):q(he.error,{code:"payment_method_setup_provider_failed",message:he.error.message??"The payment method could not be saved."});return}h()}catch(Z){qe(),q(Z,{code:"payment_method_setup_failed"})}finally{Ie.current=!1,H(!1)}},[a,t,A,e,n,h,g,w,V,q,r,k,s]),We=fd[e]?.wallet,Ne=We==="paypal"&&(0,Zn.resolveStripePayPalPresentation)(ce,"auto",Rt?"blocked":ce.popupCapability)==="redirect",ve=d?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&We&&!Ne)return(0,Wr.jsxs)(Wr.Fragment,{children:[(0,Wr.jsx)(ha,{}),(0,Wr.jsx)($a,{state:Y,borderRadius:ve,children:(0,Wr.jsx)(ro.ExpressCheckoutElement,{options:{...Bi,paymentMethods:Fi([e])},onReady:K=>{let Ze=Wa(K,[We]);b(Ze),Ze==="unavailable"&&W()},onLoadError:()=>{b("load_error"),W()},onConfirm:K=>{Ve(K)}})})]});let G=pd(e);return(0,Wr.jsxs)(Wr.Fragment,{children:[be?(0,Wr.jsx)(xi,{method:e,themeId:p,hasNextStep:!0,highlighted:oe,disabled:f,onClick:()=>ge(K=>!K),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:ve}):null,(0,Wr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!oe,style:oe?{display:"flex",flexDirection:"column"}:Ip,children:[(0,Wr.jsx)(ro.PaymentElement,{options:{layout:Oi},onReady:()=>x(!0),onLoadError:()=>W(),onChange:K=>{K.complete&&V(null)}}),(0,Wr.jsx)(Di,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!k||!A||f||!oe,onClick:()=>{Ve()},color:d?.variables?.colorPrimary??"#4A49FF",borderRadius:d?.variables?.borderRadius??"8px",style:m?.submitButton,children:f?"Saving\u2026":`Save ${G}`})]})]})}var ti=require("@flopay/js/card-setup"),Tr=require("@flopay/shared"),Ye=Es(require("react"),1);var Pa=require("@flopay/js/card-setup"),Nr=require("@flopay/shared");var dr=require("react/jsx-runtime"),Mp=15,Ap=2e3;function xp(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function sl(e){return new Promise(t=>setTimeout(t,e))}async function Fp(e,t,r){if(!t.trim())throw new Tr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new Tr.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),a=n.data.session;if(!a||!(0,Tr.isCardSetupCheckoutSession)(a))throw new Tr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Nr.readSetupAdvertisement)(n);if(!(0,Nr.advertisesAnyMethod)(s)){let{skippedForMissingCurrency:d}=s,p=d.length>0?`FloPay: this setup session advertises only Stripe methods (${d.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new Tr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function Bp(e,t,r,n,a){let s=t.vault??null;(0,Tr.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let d=(0,Tr.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!d)throw new Tr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return d}var Zi=class extends Ye.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function hd({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:d="modern-light",containerStyle:p,appearance:m,buttonsStyles:w,loading:h=null,onReady:g,onComplete:_,onDecline:V,onCancel:W,onValidation:k,onError:A}){let[f]=(0,Ye.useState)(Pa.readSetupRedirectReturn),[H,Y]=(0,Ye.useState)(null),[b,be]=(0,Ye.useState)(!1),[x,oe]=(0,Ye.useState)(null),[ge,Ie]=(0,Ye.useState)(null),[ce,Rt]=(0,Ye.useState)(null),[mt,q]=(0,Ye.useState)(null),[Ve,We]=(0,Ye.useState)(()=>new Set),Ne=(0,Ye.useRef)(Ve),ve=(0,Ye.useRef)(null);ve.current=H;let G=(0,Ye.useRef)(!1),K=(0,Ye.useRef)(!1),Ze=(0,Ye.useRef)(!1),Se=(0,Ye.useRef)(!1),qe=(0,Ye.useRef)(0),Z=(0,Ye.useRef)(0),j=(0,Ye.useRef)(!1),{vaultTheme:he,surface:X,overlayTheme:Pt,appearance:pe,buttonsLayout:we}=(0,Ye.useMemo)(()=>Xi({theme:d,appearance:m,buttonsStyles:w}),[d,m,w]),Ae=(0,Ye.useMemo)(()=>(0,Ka.mergeCardSetupSurface)(X,p),[X,p]),Ce=(0,Ye.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:g,onComplete:_,onDecline:V,onCancel:W,onValidation:k,onError:A});Ce.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:g,onComplete:_,onDecline:V,onCancel:W,onValidation:k,onError:A},(0,Ye.useEffect)(()=>{j.current=!0;let u=qe.current+1;return qe.current=u,()=>{j.current=!1,Z.current+=1,queueMicrotask(()=>{qe.current===u&&(Ze.current||Se.current||(Se.current=!0,(0,He.invokeMerchantCallback)(()=>{Ce.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let kt=(0,Ye.useCallback)((u,F)=>{Ze.current=!0,G.current=!1,q({status:"success",wording:u,message:null}),(async()=>(await sl(600),!K.current&&(K.current=!0,(0,He.invokeMerchantCallback)(()=>{Ce.current.onComplete?.({status:"succeeded",sessionId:Ce.current.sessionId,...F?{paymentMethod:F}:{}})}),j.current&&q(null))))()},[]),Pe=(0,Ye.useCallback)((u,F)=>{Ze.current=!0,G.current=!1,q({status:"error",wording:u,message:F.message??null}),(0,He.invokeMerchantCallback)(()=>{Ce.current.onDecline?.({status:"declined",sessionId:Ce.current.sessionId,...F.reason?{reason:F.reason}:{},...F.message?{message:F.message}:{}})}),(async()=>(await sl(400),j.current&&q(null)))()},[]),Be=(0,Ye.useCallback)((u,F)=>{G.current?(G.current=!1,q({status:"error",wording:u,message:F.message}),setTimeout(()=>{j.current&&q(null)},400)):q(null),(0,He.invokeMerchantCallback)(()=>Ce.current.onError?.(F))},[]),at=(0,Ye.useCallback)(async u=>{let F=Z.current+1;Z.current=F;let D=()=>!j.current||F!==Z.current;G.current=!0,q({status:"processing",wording:"payment_method",message:null});let L=new ti.PaymentAPI((0,Tr.resolveBillingApiUrl)(Ce.current.billingApiUrl),{telemetry:Ce.current.telemetry});try{for(let T=0;T<Mp;T+=1){if((T>0||u.waitFirst)&&await sl(Ap),D())return;let I=await L.getUnifiedCheckoutSession(Ce.current.sessionId,Ce.current.nonce);if(D())return;let Ct=I.data.session?.status;if(Ct==="complete"){be(!0),kt("payment_method");return}if(Ct==="expired")throw new Tr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Tr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(T){if(D())return;let I=T instanceof Tr.FloPayError&&T.code==="payment_method_setup_unverified";Be("payment_method",fo(T,I?{retryable:!0}:{}))}finally{L.destroy()}},[Be,kt]);(0,Ye.useEffect)(()=>{let u=!0,F=(0,Tr.resolveBillingApiUrl)(a),D=new ti.PaymentAPI(F,{telemetry:s});Y(null),be(!1),oe(null),Ie(null),Rt(null);let L=new Set;return Ne.current=L,We(L),Ze.current=!1,Se.current=!1,K.current=!1,(async()=>{try{let{session:T,advertisement:I}=await Fp(D,r,n);if(!u)return;let Ct={advertisement:I,customer:xp(T),...T.futureUse?{futureUse:T.futureUse}:{},...T.futureUseUnsupported?{futureUseUnsupported:T.futureUseUnsupported}:{}};if(f){if((0,Pa.clearSetupRedirectParams)(),T.status==="complete"){be(!0),Y(Ct),kt("payment_method");return}f.failed?Pe("payment_method",{reason:"redirect_failed"}):at({waitFirst:!0})}let Mr=I.card?await Bp(D,T,r,n,F):null;if(!u)return;Y(Ct),Mr&&(Ie(Mr),oe(new ti.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(T){if(!u)return;let I=fo(T);Ze.current=!0,Rt(I),(0,He.invokeMerchantCallback)(()=>Ce.current.onError?.(I))}})(),()=>{u=!1,D.destroy()}},[a,n,f,Pe,kt,r,s,at]),(0,Ye.useEffect)(()=>{if(!x)return;G.current=!1;let u=x.on("submitting",()=>{G.current=!0,q({status:"processing",wording:"card",message:null})}),F=x.on("complete",T=>{kt("card",T.paymentMethod)}),D=x.on("decline",T=>{Pe("card",{...T.declineReason?{reason:T.declineReason}:{},...T.message?{message:T.message}:{}})}),L=x.on("challenge_dismissed",()=>{q(null)});return()=>{u(),F(),D(),L()}},[x,Pe,kt]);let yt=(0,Ye.useCallback)((u,F,D)=>{if(D.retryable){Be("payment_method",fo(F,D));return}if(Ne.current.has(u))return;let L=new Set(Ne.current);L.add(u),Ne.current=L,We(L);let T=ve.current?.advertisement,I=T?(0,Nr.advertisedMethodKeys)(T).some(Ct=>!L.has(Ct)):!1;Be("payment_method",fo(F,{code:D.code,retryable:I}))},[Be]),Mt=(0,Ye.useMemo)(()=>({onSubmitting:()=>{G.current=!0,q({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{at({waitFirst:!1})},onDeclined:u=>Pe("payment_method",u),onValidation:u=>{(0,He.invokeMerchantCallback)(()=>Ce.current.onValidation?.(u))},onAbandoned:()=>{G.current=!1,q(null)}}),[Pe,at]),le=(0,Ye.useRef)(yt);le.current=yt;let It=(0,Ye.useRef)(new Map),Vt=u=>{let F=It.current.get(u);if(F)return F;let D=(L,T)=>le.current(u,L,T);return It.current.set(u,D),D},xe=(0,Ye.useCallback)(u=>{if(Ne.current.has(u))return;let F=new Set(Ne.current);F.add(u),Ne.current=F,We(F);let D=ve.current?.advertisement;D&&(0,Nr.advertisedMethodKeys)(D).some(T=>!F.has(T))||Be("payment_method",fo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[Be]),Oe=(0,Ye.useRef)(xe);Oe.current=xe;let Ke=(0,Ye.useRef)(new Map),vt=u=>{let F=Ke.current.get(u);if(F)return F;let D=()=>Oe.current(u);return Ke.current.set(u,D),D},it=mt?(0,dr.jsx)(rn,{status:mt.status,errorMessage:mt.message,...(0,Nr.setupOverlayLabels)(mt.wording),successNote:null,...Pt?{theme:Pt}:{}}):null;if(ce)return(0,dr.jsx)("div",{role:"alert",children:ce.message});if(!H||b)return(0,dr.jsxs)(dr.Fragment,{children:[it,H?null:h]});let{advertisement:ft,customer:Lt,futureUse:Qe,futureUseUnsupported:st}=H,de=(0,Tr.resolveBillingApiUrl)(a),Ot=s===void 0?{}:{telemetry:s},et=ft.stripe.filter(({method:u})=>!Ve.has(u)),re=Ve.has("paypal")?null:ft.paypal,v=!!(ft.card&&x&&ge?.html),Q=({method:u,publishableKey:F,currency:D})=>(0,dr.jsx)("div",{"data-flopay-payment-method":u,style:{display:"contents"},children:(0,dr.jsx)(Zi,{onFailed:Vt(u),children:(0,dr.jsx)(Ye.Suspense,{fallback:null,children:(0,dr.jsx)(e,{method:u,category:(0,Nr.stripeMethodCategory)(u),publishableKey:F,currency:D,...Qe?{futureUse:Qe}:{},...st?{futureUseUnsupported:st}:{},sessionId:r,nonce:n,billingApiUrl:de,...Ot,...pe?{appearance:pe}:{},...we?{buttonsLayout:we}:{},...typeof d=="string"?{themeId:d}:{},...Mt,onFailed:Vt(u),onUnavailable:vt(u)})})})},u),ee=et.filter(({method:u})=>(0,Nr.stripeMethodCategory)(u)==="wallet"),$=et.filter(({method:u})=>(0,Nr.stripeMethodCategory)(u)!=="wallet"),nt=et.length>0||re!==null;return(0,dr.jsxs)(dr.Fragment,{children:[it,nt?(0,dr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ee.map(Q),re?(0,dr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,dr.jsx)(Zi,{onFailed:Vt("paypal"),children:(0,dr.jsx)(Ye.Suspense,{fallback:null,children:(0,dr.jsx)(t,{clientId:re.clientId,...re.environment?{environment:re.environment}:{},...ft.currency?{currency:ft.currency}:{},sessionId:r,nonce:n,billingApiUrl:de,customer:Lt,...Ot,...Mt,onFailed:Vt("paypal"),onUnavailable:vt("paypal")})})})}):null,$.map(Q)]}):null,v&&nt?(0,dr.jsx)(Ga,{label:"or add a card"}):null,v&&x&&ge?.html?(0,dr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,dr.jsx)(_o,{capture:x,html:ge.html,messageToken:ge.messageToken,expectedOrigin:ge.expectedOrigin,verificationRequired:ge.verificationRequired,theme:he,containerStyle:Ae,onReady:()=>{(0,He.invokeMerchantCallback)(()=>Ce.current.onReady?.())},onValidation:u=>{(0,He.invokeMerchantCallback)(()=>Ce.current.onValidation?.(u))},onError:u=>{u&&Be("card",fo(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var vd=require("react/jsx-runtime"),Op={StripeSetupMethod:gd,PayPalSetupMethod:dd};function Pd(e){return(0,vd.jsx)(hd,{...e,branches:Op})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}let X={paypal:r&&f(jo),wallets:n&&(a||s)&&f(jo),card:n&&(t?f(jo):(0,O.jsx)("button",{type:"button",onClick:()=>{e?.("card"),W(!0)},style:{width:"100%",...H,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:R.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...R.cardButton},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.985)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:(0,O.jsx)(oa,{content:S})}))};return(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[de.DEFAULT_PAYMENT_METHOD_ORDER.map(v=>(0,O.jsx)(w.default.Fragment,{children:X[v]},v)),(0,O.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var wn=require("react/jsx-runtime"),Sp=44;function cd(e){return new Promise(t=>setTimeout(t,e))}var dd=15e3;function ll(e,t){return new kr.FloPayError(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function wp(e,t){return new Promise((r,n)=>{let a=()=>n(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(s=>{t.removeEventListener("abort",a),r(s)},s=>{t.removeEventListener("abort",a),n(s)})})}function Rp(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function kp(e,t){return e instanceof kr.FloPayError?e:new kr.FloPayError(e instanceof Error?e.message:t,"api_error")}function Ep(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function _p(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function ud({sessionId:e,nonce:t,createSession:r,getSession:n,paymentMethodId:a,checkoutMethod:s,clientId:d,products:p,items:y,subscriptions:S,account:P,successUrl:g,cancelUrl:_,couponCodes:W,tagsData:$,utmMetadata:R,billingApiUrl:x,locale:f,theme:H,appearance:X,buttonsTheme:v,buttonsStyles:be,onSuccess:F,onError:oe,onDecline:he,children:Re,disabled:pe=!1,type:kt="button",style:mt,...j}){let Je=(0,dt.useMemo)(()=>(0,kr.resolveBillingApiUrl)(x),[x]),Ze=(0,dt.useMemo)(()=>_p({createSession:r,clientId:d,products:p,items:y,subscriptions:S,account:P,successUrl:g,cancelUrl:_,couponCodes:W,tagsData:$,utmMetadata:R}),[P,_,d,W,r,p,y,S,g,$,R]),[Le,ve]=(0,dt.useState)(!1),[Y,K]=(0,dt.useState)(null),[rt,Se]=(0,dt.useState)(null),[Ke,ee]=(0,dt.useState)(!1),[V,Pe]=(0,dt.useState)(null),[J,ut]=(0,dt.useState)(null),ye=(0,dt.useRef)(!0),ke=(0,dt.useRef)(null),xe=(0,dt.useRef)(null),_e=(0,dt.useRef)(!1),vt=(0,dt.useRef)(J),Ne=(0,dt.useRef)(F),ft=(0,dt.useRef)(oe),Ve=(0,dt.useRef)(he),We=(0,dt.useCallback)(B=>Ii(ke,async C=>{try{return await B(C)}catch(ce){throw C.aborted?ma(ce):ce}}),[]);(0,dt.useEffect)(()=>{vt.current=J},[J]),(0,dt.useEffect)(()=>{Ne.current=F},[F]),(0,dt.useEffect)(()=>{ft.current=oe},[oe]),(0,dt.useEffect)(()=>{Ve.current=he},[he]),(0,dt.useEffect)(()=>(ye.current=!0,()=>{ye.current=!1,ke.current?.abort(),xe.current?.abort()}),[]),(0,dt.useEffect)(()=>{if(typeof window>"u")return;let B=C=>{C.key==="Escape"&&ut(null)};return window.addEventListener("keydown",B),()=>{window.removeEventListener("keydown",B)}},[]);let Mt=(0,dt.useCallback)((B,C=qa)=>{Ve.current?.(Sr(C,B,{code:B.code,declineCode:B.declineCode}))},[]),Lt=(0,dt.useCallback)(async B=>{ye.current&&(Se(null),ee(B.result.status==="authorized"),K("success"),await cd(600),ye.current&&(0,Qe.invokeMerchantCallback)(()=>Ne.current?.(B)))},[]),Ft=(0,dt.useCallback)(async(B,C)=>{if(!ye.current)return;!!C?.emitDecline&&(0,kr.isDeclineCallbackFailure)(B)?Mt(B,C?.method):ft.current?.(B),Se(B.message),ee(!1),K("error"),await cd(400)},[Mt]),le=(0,dt.useCallback)(async(B,C,ce)=>{let Z=B.data.session??null;if(!Z)throw wo(new kr.FloPayError("No session data returned","api_error"),C);let ae=ce?.nonce||Z.clientSecret||t;if(so(Z)){await Lt({result:io(Z,C),session:Z,sessionId:Z.id||C,autoCompleted:!1});return}if(Z.status==="expired")throw wo(gi(Z),Z.id||C);try{if(B.autoProcessingPending){let M=B.autoProcessingPending,I=new Yi.PaymentAPI(Je),ie=await We(tt=>I.waitForCheckoutSessionCompletion(M.sessionId,{initialDelayMs:M.retryAfterMs,nonce:ae,statusUrl:M.statusUrl,signal:tt})),U=Ro(ie,Z),k=ie.autoProcessingError?.type==="3ds_required"&&!(0,kr.isMerchantAuthRequired)(ie.autoProcessingError)&&ie.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ie.autoProcessingError.nextActionRedirectUrl}:null;if(k&&C&&ae){let tt=ja(Je,C,Z),Ht=await We(Kt=>fa(k,{billingApiUrl:Je,sessionId:C,nonce:ae,session:Z,signal:Kt,telemetry:!0,...tt.telemetry?{challengeTelemetry:tt.telemetry}:{}})).finally(tt.release);await Lt({result:Ht,session:Z,sessionId:Z.id||C,autoCompleted:!1});return}if(ie.autoProcessingError)throw Zn(ie.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:ie.autoProcessingError.checkoutMethod});if(!so(U))throw sa(U);await Lt({result:io(U,C),session:U,sessionId:U.id||C,autoCompleted:!1});return}if(B.autoProcessingError){let M=B.autoProcessingError.nextActionRedirectUrl;if(B.autoProcessingError.type==="3ds_required"&&!(0,kr.isMerchantAuthRequired)(B.autoProcessingError)&&M&&C&&ae){let I=await We(tt=>Ac({billingApiUrl:Je,sessionId:C,nonce:ae,nextActionRedirectUrl:M,signal:tt}));if(I.status==="declined")throw Zn({type:I.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:I.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:B.autoProcessingError.checkoutMethod});let U=await new Yi.PaymentAPI(Je).waitForCheckoutSessionCompletion(C,{initialDelayMs:0,nonce:ae}),k=Ro(U,Z);if(!so(k))throw Zn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:B.autoProcessingError.checkoutMethod});await Lt({result:io(k,C),session:k,sessionId:k.id||C,autoCompleted:!1});return}throw Zn(B.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:B.autoProcessingError.checkoutMethod})}if(ce?.fromCreateSession&&B.autoProcessingAttempted===!0)throw Zn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let u=await ga({billingApiUrl:Je,sessionId:C??Z.id,session:Z,nonce:ae});if(u.type==="next_action_required"&&ae){let M=C??Z.id,I=ja(Je,M,Z),ie=await We(U=>fa(u,{billingApiUrl:Je,sessionId:M,nonce:ae,session:Z,signal:U,telemetry:!0,...I.telemetry?{challengeTelemetry:I.telemetry}:{}})).finally(I.release);await Lt({result:ie,session:Z,sessionId:Z.id||M,autoCompleted:!1});return}if(u.type!=="success")throw Zn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Lt({result:u.result,session:Z,sessionId:Z.id||C,autoCompleted:!1})}catch(u){let M=Z.id||C,I=wo(Va(u),M);if(I.code==="three_ds_aborted")return;if(I.code==="checkout_processing_timeout"){if(!ye.current)return;Pe(I.message),(0,Qe.invokeMerchantCallback)(()=>ft.current?.(I));return}await Ft(I,{emitDecline:!0,method:I.checkoutMethod??qa}),Ep(I,M)&&M&&ye.current&&ut({sessionId:M,errorMessage:I.message,nonce:ae||void 0,payPalOrderId:I.orderId})}},[t,Je,We,Ft,Lt]),Ee=(0,dt.useCallback)(async B=>{let C=new AbortController;xe.current=C;let ce=!1,Z=setTimeout(()=>{ce=!0,C.abort()},dd);try{let ae=await wp((async()=>B({signal:C.signal}))(),C.signal);if(!ye.current)return null;if(!Rp(ae))throw ll("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:ae.sessionId,nonce:ae.nonce}}catch(ae){if(!ye.current)return null;throw ae instanceof kr.FloPayError&&ae.code==="session_fetch_failed"?ae:ce?ll(`getSession did not resolve within ${dd/1e3} seconds.`):ll("Could not fetch the one-click session.",ae)}finally{clearTimeout(Z),xe.current===C&&(xe.current=null)}},[]),$e=(0,dt.useCallback)(async B=>{if(j.onClick?.(B),B.defaultPrevented||pe||Le||(ut(null),Pe(null),_e.current))return;let C=[e,n,Ze].filter(Boolean).length;if(C>1){let ce=new kr.FloPayError("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await Ft(ce),ye.current&&(K(null),Se(null));return}if(C===0){let ce=new kr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Ft(ce),ye.current&&(K(null),Se(null));return}_e.current=!0,ve(!0),Se(null),ee(!1),K("processing");try{let ce=new Yi.PaymentAPI(Je);if(e){let Z=await ce.getUnifiedCheckoutSession(e,t);await le(Z,e);return}if(n){let Z=await Ee(n);if(!Z)return;let ae=await ce.getUnifiedCheckoutSession(Z.sessionId,Z.nonce);await le(ae,Z.sessionId,{nonce:Z.nonce});return}Ec();try{let Z=await ce.createAndFetchSession({...Ze});await le(Z,Z.data.session?.id??null,{fromCreateSession:!0})}catch(Z){if(hi(Z)==="session_auto_completed"){await Lt({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Z}}catch(ce){await Ft(wo(kp(ce,"Automatic payment failed. Please try again."),e))}finally{_e.current=!1,ye.current&&(K(null),Se(null),ve(!1))}},[j.onClick,Ze,pe,Ee,n,Le,t,le,Je,e,Ft,Lt]),Ct=(0,dt.useCallback)(B=>{let C=vt.current;ut(null),Ne.current?.({result:B,session:null,sessionId:C?.sessionId??null,autoCompleted:!1})},[]),bt=(0,dt.useCallback)(B=>{ft.current?.(B)},[]),st=(0,dt.useCallback)(B=>{Ve.current?.(B)},[]),pt=(0,dt.useMemo)(()=>(0,kr.resolveTheme)(H),[H]),At=(0,dt.useMemo)(()=>{let B=pt?.buttonsLayout??(0,kr.resolveButtonsLayoutTheme)(v);return be?{...B,...be,cardButton:{...B.cardButton,...be.cardButton}}:B},[pt,v,be]),xt=(0,dt.useMemo)(()=>{let B=pt?.appearance;return X?B?{...B,...X,variables:{...B.variables,...X.variables}}:X:B},[X,pt]),lt=xt?.variables,ct=lt?.colorPrimary??"#4A49FF",gt=lt?.colorPrimaryHover??(0,el.darkenHex)(ct,.12),G=lt?.borderRadius??"8px";return(0,wn.jsxs)(wn.Fragment,{children:[(0,wn.jsx)("button",{...j,type:kt,onClick:$e,disabled:pe||Le,"aria-busy":Le,style:{width:"100%",...Re===void 0?{boxSizing:"border-box",height:Sp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...At.cardButton,...Qs({themeBundle:pt,resolvedPrimaryColor:ct,resolvedBorderRadius:G,submitButtonStyle:At.submitButton,explicitPrimaryColor:lt?.colorPrimary}),fontSize:At.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:pe||Le?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:pe||Le?.6:1,...mt},onMouseEnter:B=>{j.onMouseEnter?.(B),!B.defaultPrevented&&!pe&&!Le&&(pt||lt?.colorPrimary)&&(B.currentTarget.style.backgroundColor=gt)},onMouseLeave:B=>{j.onMouseLeave?.(B),!B.defaultPrevented&&(pt||lt?.colorPrimary)&&(B.currentTarget.style.backgroundColor=ct)},onMouseDown:B=>{j.onMouseDown?.(B),B.defaultPrevented||(B.currentTarget.style.transform="scale(0.985)")},onMouseUp:B=>{j.onMouseUp?.(B),B.defaultPrevented||(B.currentTarget.style.transform="scale(1)")},children:(0,wn.jsx)(oa,{content:Re})}),V&&(0,wn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:V}),Y&&(0,wn.jsx)(on,{status:Y,errorMessage:rt,authorized:Ke}),J&&(0,wn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:B=>{B.target===B.currentTarget&&ut(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,wn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,wn.jsx)(Gi,{sessionId:J.sessionId,nonce:J.nonce,checkoutMode:"full",billingApiUrl:Je,locale:f,theme:H,...xt?{appearance:xt}:{},buttonsTheme:v,buttonsStyles:be,initialErrorMessage:J.errorMessage,initialPayPalOrderId:J.payPalOrderId,cardTitleContent:null,onComplete:Ct,onError:bt,onDecline:st})})})]})}var Ji=require("@flopay/js/card-setup"),Jr=require("@flopay/shared"),Xt=require("react");var cl=require("@flopay/shared"),Ip=require("@flopay/shared");function Xi(e){let t=(0,cl.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var eo=require("react/jsx-runtime"),ei=class extends Jr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function mo(e,t={}){let r=e instanceof Jr.FloPayError?e:void 0,n=r?.statusCode,a=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new ei(r?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),r?.type??"api_error",{code:t.code??r?.code??"card_setup_load_failed",retryable:a,...r?.param?{param:r.param}:{},...n===void 0?{}:{statusCode:n}})}function pd({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:d,buttonsStyles:p,loading:y=null,onReady:S,onComplete:P,onDecline:g,onCancel:_,onValidation:W,onError:$}){let[R,x]=(0,Xt.useState)(null),[f,H]=(0,Xt.useState)(null),[X,v]=(0,Xt.useState)(null),[be,F]=(0,Xt.useState)(null),[oe,he]=(0,Xt.useState)(null),Re=(0,Xt.useRef)(!1),pe=(0,Xt.useRef)(!1),{vaultTheme:kt,surface:mt,overlayTheme:j}=(0,Xt.useMemo)(()=>Xi({theme:a,appearance:d,buttonsStyles:p}),[a,d,p]),Je=(0,Xt.useMemo)(()=>(0,Ka.mergeCardSetupSurface)(mt,s),[mt,s]),Ze=(0,Xt.useRef)(S),Le=(0,Xt.useRef)($),ve=(0,Xt.useRef)(P),Y=(0,Xt.useRef)(g),K=(0,Xt.useRef)(_),rt=(0,Xt.useRef)(W),Se=(0,Xt.useRef)(!1),Ke=(0,Xt.useRef)(!1),ee=(0,Xt.useRef)(0);return Ze.current=S,Le.current=$,ve.current=P,Y.current=g,K.current=_,rt.current=W,(0,Xt.useEffect)(()=>{let V=ee.current+1;return ee.current=V,()=>{queueMicrotask(()=>{ee.current===V&&(Se.current||Ke.current||(Ke.current=!0,(0,Qe.invokeMerchantCallback)(()=>{K.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Xt.useEffect)(()=>{let V=!0,Pe=(0,Jr.resolveBillingApiUrl)(r),J=new Ji.PaymentAPI(Pe,{telemetry:n});return x(null),H(null),v(null),Se.current=!1,Ke.current=!1,(async()=>{try{if(!e.trim())throw new Jr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Jr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ut=await J.getUnifiedCheckoutSession(e,t);if(!V)return;let ye=ut.data.session;if(!ye||!(0,Jr.isCardSetupCheckoutSession)(ye))throw new Jr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let ke=ye.vault;(0,Jr.isMountableVaultBlock)(ke)||(ke=await J.getVaultCapture(e,t));let xe=(0,Jr.resolveVaultMountOptions)(ke,{billingApiUrl:Pe,sessionId:e,nonce:t});if(!xe)throw new Jr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!V)return;H(xe),x(new Ji.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(ut){if(!V)return;let ye=mo(ut);Se.current=!0,v(ye),(0,Qe.invokeMerchantCallback)(()=>Le.current?.(ye))}})(),()=>{V=!1,J.destroy()}},[r,t,e,n]),(0,Xt.useEffect)(()=>{if(!R)return;let V=!1;pe.current=!1,Re.current=!1;let Pe=R.on("submitting",()=>{Re.current=!0,he(null),F("processing")}),J=R.on("complete",ke=>{Se.current=!0,Re.current=!1,F("success"),(async()=>(await new Promise(xe=>setTimeout(xe,600)),!pe.current&&(pe.current=!0,(0,Qe.invokeMerchantCallback)(()=>{ve.current?.({status:"succeeded",sessionId:e,...ke.paymentMethod?{paymentMethod:ke.paymentMethod}:{}})}),V||F(null))))()}),ut=R.on("decline",ke=>{Se.current=!0,Re.current=!1,he(ke.message??null),F("error"),(0,Qe.invokeMerchantCallback)(()=>{Y.current?.({status:"declined",sessionId:e,...ke.declineReason?{reason:ke.declineReason}:{},...ke.message?{message:ke.message}:{}})}),(async()=>(await new Promise(xe=>setTimeout(xe,400)),V||F(null)))()}),ye=R.on("challenge_dismissed",()=>{F(null)});return()=>{V=!0,Pe(),J(),ut(),ye()}},[R,e]),X?(0,eo.jsx)("div",{role:"alert",children:X.message}):!R||!f?.html?(0,eo.jsx)(eo.Fragment,{children:y}):(0,eo.jsxs)(eo.Fragment,{children:[be&&(0,eo.jsx)(on,{status:be,errorMessage:oe,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...j?{theme:j}:{}}),(0,eo.jsx)(Eo,{capture:R,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,verificationRequired:f.verificationRequired,theme:kt,containerStyle:Je,onReady:()=>{(0,Qe.invokeMerchantCallback)(()=>Ze.current?.())},onValidation:V=>{(0,Qe.invokeMerchantCallback)(()=>rt.current?.(V))},onError:V=>{if(!V)return;Re.current&&(Re.current=!1,he(V),F("error"),setTimeout(()=>F(null),400));let Pe=mo(new Error(V),{code:"card_setup_widget_failed",retryable:!0});(0,Qe.invokeMerchantCallback)(()=>Le.current?.(Pe))}})]})}var yd=require("@flopay/js/card-setup"),Rn=require("@flopay/shared"),md=require("@paypal/paypal-js"),Vo=require("react");var gd=require("react/jsx-runtime");function fd({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:d,customer:{userId:p,email:y},onSubmitting:S,onConfirmed:P,onFailed:g,onAbandoned:_}){let W=(0,Vo.useRef)(null),$=(0,Vo.useRef)({onSubmitting:S,onConfirmed:P,onFailed:g,onAbandoned:_});$.current={onSubmitting:S,onConfirmed:P,onFailed:g,onAbandoned:_};let[R]=(0,Vo.useState)(()=>(0,Xn.detectPayPalEnvironment)().inAppBrowser);return(0,Vo.useEffect)(()=>{let x=!0,f,H=new yd.PaymentAPI(s,{telemetry:d}),X={userId:p,email:y};return(async()=>{try{let v=await(0,md.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),be=W.current;if(!x||!be)return;if(!v?.Buttons)throw new Rn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let F=v.Buttons({createVaultSetupToken:async()=>{$.current.onSubmitting();let oe=await H.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Rn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,Rn.isSettledSessionIntent)(oe))throw(0,Rn.settledSessionIntentError)(n);if(oe.provider!=="paypal"||oe.providerObjectType!=="setup_token")throw new Rn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return oe.providerObjectId},onApprove:async oe=>{let he=oe.vaultSetupToken;if(!he)throw new Rn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let Re=await H.processPayment(X.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:he,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Rn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:X});if(!Re.ok)throw new Rn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:Re.status});x&&$.current.onConfirmed()},onCancel:()=>{x&&$.current.onAbandoned()},onError:oe=>{if(!x)return;let{popupBlocked:he}=(0,we.classifyExternalMethodFailure)(oe,{inAppBrowser:R,handoffObserved:!1});$.current.onFailed(he?new Error((0,we.buildExternalMethodRecoveryMessage)("PayPal",!0,R)):oe,{code:he?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>F.close(),await F.render(be)}catch(v){if(!x)return;$.current.onFailed(v,{code:"paypal_unavailable",retryable:!0})}})(),()=>{x=!1,f?.().catch(()=>{}),H.destroy()}},[s,e,r,y,t,R,a,n,d,p]),(0,gd.jsx)("div",{ref:W,"data-flopay-paypal-setup":""})}var Pd=require("@flopay/js/card-setup"),kn=require("@flopay/shared"),to=require("@stripe/react-stripe-js"),vd=require("@stripe/stripe-js"),Zr=require("react");var jr=require("react/jsx-runtime"),Cd={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},dl=new Map;function Tp(e){let t=dl.get(e);if(t)return t;let r=(0,vd.loadStripe)(e).catch(n=>{throw dl.delete(e),n});return dl.set(e,r),r}function Mp(e){return e?(0,kn.toStripeAppearance)(e):void 0}function Ap(e){return(0,we.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function hd(e){return e==="paypal"?"PayPal":(0,kn.getStripeMethodDisplayName)(e)}function xp(){return typeof window>"u"?"":window.location.href}var Fp={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function bd(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:d}=e,[p]=(0,Zr.useState)(()=>Tp(t)),y=(0,Zr.useMemo)(()=>{let S=Mp(d),P=(0,kn.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:Cd[r]?.types??[r],...P?{setupFutureUsage:P}:{},...S?{appearance:S}:{}}},[d,n,a,s,r]);return(0,jr.jsx)(to.Elements,{stripe:p,options:y,children:(0,jr.jsx)(Bp,{...e})})}function Bp({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:d,themeId:p,buttonsLayout:y,onSubmitting:S,onConfirmed:P,onDeclined:g,onFailed:_,onValidation:W,onUnavailable:$}){let R=(0,to.useStripe)(),x=(0,to.useElements)(),[f,H]=(0,Zr.useState)(!1),[X,v]=(0,Zr.useState)("loading"),[be,F]=(0,Zr.useState)(!1),[oe,he]=(0,Zr.useState)(!1),Re=(0,Zr.useRef)(!1),[pe]=(0,Zr.useState)(()=>(0,Xn.detectPayPalEnvironment)()),[kt,mt]=(0,Zr.useState)(!1),j=(0,Zr.useCallback)((K,rt)=>{if((0,we.classifyExternalMethodFailure)(K,{inAppBrowser:pe.inAppBrowser,handoffObserved:!1}).popupBlocked){mt(!0),_(new Error((0,we.buildExternalMethodRecoveryMessage)(hd(e),!0,pe.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}_(rt.message===void 0?K:new Error(rt.message),{code:rt.code,retryable:!0})},[pe.inAppBrowser,e,_]),Je=(0,Zr.useCallback)(async K=>{let rt=!1,Se=!1,Ke=()=>{!K||rt||Se||(Se=!0,K.paymentFailed({reason:"fail"}))};if(!R||!x||Re.current){Ke();return}Re.current=!0,H(!0);try{let ee=await x.submit();if(ee.error){Ke(),W(ee.error.message??null);return}S();let V=await new Pd.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,kn.isSettledSessionIntent)(V))throw(0,kn.settledSessionIntentError)(r);if(V.provider!=="stripe"||V.intentKind!=="setup")throw new kn.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});rt=!0;let Pe=await R.confirmSetup({elements:x,clientSecret:V.clientSecret,confirmParams:{return_url:xp()},redirect:"if_required"});if(Pe.error){Ap(Pe.error)?g({...Pe.error.decline_code||Pe.error.code?{reason:Pe.error.decline_code??Pe.error.code}:{},...Pe.error.message?{message:Pe.error.message}:{}}):j(Pe.error,{code:"payment_method_setup_provider_failed",message:Pe.error.message??"The payment method could not be saved."});return}P()}catch(ee){Ke(),j(ee,{code:"payment_method_setup_failed"})}finally{Re.current=!1,H(!1)}},[a,t,x,e,n,P,g,S,W,j,r,R,s]),Ze=Cd[e]?.wallet,Le=Ze==="paypal"&&(0,Jn.resolveStripePayPalPresentation)(pe,"auto",kt?"blocked":pe.popupCapability)==="redirect",ve=d?.variables?.borderRadius??y?.cardButton?.borderRadius??8;if(t==="wallet"&&Ze&&!Le)return(0,jr.jsxs)(jr.Fragment,{children:[(0,jr.jsx)(ha,{}),(0,jr.jsx)($a,{state:X,borderRadius:ve,children:(0,jr.jsx)(to.ExpressCheckoutElement,{options:{...Bi,paymentMethods:Fi([e])},onReady:K=>{let rt=Wa(K,[Ze]);v(rt),rt==="unavailable"&&$()},onLoadError:()=>{v("load_error"),$()},onConfirm:K=>{Je(K)}})})]});let Y=hd(e);return(0,jr.jsxs)(jr.Fragment,{children:[be?(0,jr.jsx)(xi,{method:e,themeId:p,hasNextStep:!0,highlighted:oe,disabled:f,onClick:()=>he(K=>!K),backgroundColor:y?.cardButton?.backgroundColor,borderColor:y?.cardInputBorder,textColor:y?.cardButton?.color,borderRadius:ve}):null,(0,jr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!oe,style:oe?{display:"flex",flexDirection:"column"}:Fp,children:[(0,jr.jsx)(to.PaymentElement,{options:{layout:Oi},onReady:()=>F(!0),onLoadError:()=>$(),onChange:K=>{K.complete&&W(null)}}),(0,jr.jsx)(Di,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!R||!x||f||!oe,onClick:()=>{Je()},color:d?.variables?.colorPrimary??"#4A49FF",borderRadius:d?.variables?.borderRadius??"8px",style:y?.submitButton,children:f?"Saving\u2026":`Save ${Y}`})]})]})}var ti=require("@flopay/js/card-setup"),Er=require("@flopay/shared"),et=Ms(require("react"),1);var Pa=require("@flopay/js/card-setup"),Mr=require("@flopay/shared");var ur=require("react/jsx-runtime"),Op=15,Dp=2e3;function Lp(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function ul(e){return new Promise(t=>setTimeout(t,e))}async function Np(e,t,r){if(!t.trim())throw new Er.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new Er.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),a=n.data.session;if(!a||!(0,Er.isCardSetupCheckoutSession)(a))throw new Er.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Mr.readSetupAdvertisement)(n);if(!(0,Mr.advertisesAnyMethod)(s)){let{skippedForMissingCurrency:d}=s,p=d.length>0?`FloPay: this setup session advertises only Stripe methods (${d.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new Er.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function Up(e,t,r,n,a){let s=t.vault??null;(0,Er.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let d=(0,Er.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!d)throw new Er.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return d}var Zi=class extends et.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function Sd({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:d="modern-light",containerStyle:p,appearance:y,buttonsStyles:S,loading:P=null,onReady:g,onComplete:_,onDecline:W,onCancel:$,onValidation:R,onError:x}){let[f]=(0,et.useState)(Pa.readSetupRedirectReturn),[H,X]=(0,et.useState)(null),[v,be]=(0,et.useState)(!1),[F,oe]=(0,et.useState)(null),[he,Re]=(0,et.useState)(null),[pe,kt]=(0,et.useState)(null),[mt,j]=(0,et.useState)(null),[Je,Ze]=(0,et.useState)(()=>new Set),Le=(0,et.useRef)(Je),ve=(0,et.useRef)(null);ve.current=H;let Y=(0,et.useRef)(!1),K=(0,et.useRef)(!1),rt=(0,et.useRef)(!1),Se=(0,et.useRef)(!1),Ke=(0,et.useRef)(0),ee=(0,et.useRef)(0),V=(0,et.useRef)(!1),{vaultTheme:Pe,surface:J,overlayTheme:ut,appearance:ye,buttonsLayout:ke}=(0,et.useMemo)(()=>Xi({theme:d,appearance:y,buttonsStyles:S}),[d,y,S]),xe=(0,et.useMemo)(()=>(0,Ka.mergeCardSetupSurface)(J,p),[J,p]),_e=(0,et.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:g,onComplete:_,onDecline:W,onCancel:$,onValidation:R,onError:x});_e.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:g,onComplete:_,onDecline:W,onCancel:$,onValidation:R,onError:x},(0,et.useEffect)(()=>{V.current=!0;let u=Ke.current+1;return Ke.current=u,()=>{V.current=!1,ee.current+=1,queueMicrotask(()=>{Ke.current===u&&(rt.current||Se.current||(Se.current=!0,(0,Qe.invokeMerchantCallback)(()=>{_e.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let vt=(0,et.useCallback)((u,M)=>{rt.current=!0,Y.current=!1,j({status:"success",wording:u,message:null}),(async()=>(await ul(600),!K.current&&(K.current=!0,(0,Qe.invokeMerchantCallback)(()=>{_e.current.onComplete?.({status:"succeeded",sessionId:_e.current.sessionId,...M?{paymentMethod:M}:{}})}),V.current&&j(null))))()},[]),Ne=(0,et.useCallback)((u,M)=>{rt.current=!0,Y.current=!1,j({status:"error",wording:u,message:M.message??null}),(0,Qe.invokeMerchantCallback)(()=>{_e.current.onDecline?.({status:"declined",sessionId:_e.current.sessionId,...M.reason?{reason:M.reason}:{},...M.message?{message:M.message}:{}})}),(async()=>(await ul(400),V.current&&j(null)))()},[]),ft=(0,et.useCallback)((u,M)=>{Y.current?(Y.current=!1,j({status:"error",wording:u,message:M.message}),setTimeout(()=>{V.current&&j(null)},400)):j(null),(0,Qe.invokeMerchantCallback)(()=>_e.current.onError?.(M))},[]),Ve=(0,et.useCallback)(async u=>{let M=ee.current+1;ee.current=M;let I=()=>!V.current||M!==ee.current;Y.current=!0,j({status:"processing",wording:"payment_method",message:null});let ie=new ti.PaymentAPI((0,Er.resolveBillingApiUrl)(_e.current.billingApiUrl),{telemetry:_e.current.telemetry});try{for(let U=0;U<Op;U+=1){if((U>0||u.waitFirst)&&await ul(Dp),I())return;let k=await ie.getUnifiedCheckoutSession(_e.current.sessionId,_e.current.nonce);if(I())return;let tt=k.data.session?.status;if(tt==="complete"){be(!0),vt("payment_method");return}if(tt==="expired")throw new Er.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Er.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(U){if(I())return;let k=U instanceof Er.FloPayError&&U.code==="payment_method_setup_unverified";ft("payment_method",mo(U,k?{retryable:!0}:{}))}finally{ie.destroy()}},[ft,vt]);(0,et.useEffect)(()=>{let u=!0,M=(0,Er.resolveBillingApiUrl)(a),I=new ti.PaymentAPI(M,{telemetry:s});X(null),be(!1),oe(null),Re(null),kt(null);let ie=new Set;return Le.current=ie,Ze(ie),rt.current=!1,Se.current=!1,K.current=!1,(async()=>{try{let{session:U,advertisement:k}=await Np(I,r,n);if(!u)return;let tt={advertisement:k,customer:Lp(U),...U.futureUse?{futureUse:U.futureUse}:{},...U.futureUseUnsupported?{futureUseUnsupported:U.futureUseUnsupported}:{}};if(f){if((0,Pa.clearSetupRedirectParams)(),U.status==="complete"){be(!0),X(tt),vt("payment_method");return}f.failed?Ne("payment_method",{reason:"redirect_failed"}):Ve({waitFirst:!0})}let Ht=k.card?await Up(I,U,r,n,M):null;if(!u)return;X(tt),Ht&&(Re(Ht),oe(new ti.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(U){if(!u)return;let k=mo(U);rt.current=!0,kt(k),(0,Qe.invokeMerchantCallback)(()=>_e.current.onError?.(k))}})(),()=>{u=!1,I.destroy()}},[a,n,f,Ne,vt,r,s,Ve]),(0,et.useEffect)(()=>{if(!F)return;Y.current=!1;let u=F.on("submitting",()=>{Y.current=!0,j({status:"processing",wording:"card",message:null})}),M=F.on("complete",U=>{vt("card",U.paymentMethod)}),I=F.on("decline",U=>{Ne("card",{...U.declineReason?{reason:U.declineReason}:{},...U.message?{message:U.message}:{}})}),ie=F.on("challenge_dismissed",()=>{j(null)});return()=>{u(),M(),I(),ie()}},[F,Ne,vt]);let We=(0,et.useCallback)((u,M,I)=>{if(I.retryable){ft("payment_method",mo(M,I));return}if(Le.current.has(u))return;let ie=new Set(Le.current);ie.add(u),Le.current=ie,Ze(ie);let U=ve.current?.advertisement,k=U?(0,Mr.advertisedMethodKeys)(U).some(tt=>!ie.has(tt)):!1;ft("payment_method",mo(M,{code:I.code,retryable:k}))},[ft]),Mt=(0,et.useMemo)(()=>({onSubmitting:()=>{Y.current=!0,j({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Ve({waitFirst:!1})},onDeclined:u=>Ne("payment_method",u),onValidation:u=>{(0,Qe.invokeMerchantCallback)(()=>_e.current.onValidation?.(u))},onAbandoned:()=>{Y.current=!1,j(null)}}),[Ne,Ve]),Lt=(0,et.useRef)(We);Lt.current=We;let Ft=(0,et.useRef)(new Map),le=u=>{let M=Ft.current.get(u);if(M)return M;let I=(ie,U)=>Lt.current(u,ie,U);return Ft.current.set(u,I),I},Ee=(0,et.useCallback)(u=>{if(Le.current.has(u))return;let M=new Set(Le.current);M.add(u),Le.current=M,Ze(M);let I=ve.current?.advertisement;I&&(0,Mr.advertisedMethodKeys)(I).some(U=>!M.has(U))||ft("payment_method",mo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ft]),$e=(0,et.useRef)(Ee);$e.current=Ee;let Ct=(0,et.useRef)(new Map),bt=u=>{let M=Ct.current.get(u);if(M)return M;let I=()=>$e.current(u);return Ct.current.set(u,I),I},st=mt?(0,ur.jsx)(on,{status:mt.status,errorMessage:mt.message,...(0,Mr.setupOverlayLabels)(mt.wording),successNote:null,...ut?{theme:ut}:{}}):null;if(pe)return(0,ur.jsx)("div",{role:"alert",children:pe.message});if(!H||v)return(0,ur.jsxs)(ur.Fragment,{children:[st,H?null:P]});let{advertisement:pt,customer:At,futureUse:xt,futureUseUnsupported:lt}=H,ct=(0,Er.resolveBillingApiUrl)(a),gt=s===void 0?{}:{telemetry:s},G=pt.stripe.filter(({method:u})=>!Je.has(u)),Jt=Je.has("paypal")?null:pt.paypal,B=!!(pt.card&&F&&he?.html),C=({method:u,publishableKey:M,currency:I})=>(0,ur.jsx)("div",{"data-flopay-payment-method":u,style:{display:"contents"},children:(0,ur.jsx)(Zi,{onFailed:le(u),children:(0,ur.jsx)(et.Suspense,{fallback:null,children:(0,ur.jsx)(e,{method:u,category:(0,Mr.stripeMethodCategory)(u),publishableKey:M,currency:I,...xt?{futureUse:xt}:{},...lt?{futureUseUnsupported:lt}:{},sessionId:r,nonce:n,billingApiUrl:ct,...gt,...ye?{appearance:ye}:{},...ke?{buttonsLayout:ke}:{},...typeof d=="string"?{themeId:d}:{},...Mt,onFailed:le(u),onUnavailable:bt(u)})})})},u),ce=G.filter(({method:u})=>(0,Mr.stripeMethodCategory)(u)==="wallet"),Z=G.filter(({method:u})=>(0,Mr.stripeMethodCategory)(u)!=="wallet"),ae=G.length>0||Jt!==null;return(0,ur.jsxs)(ur.Fragment,{children:[st,ae?(0,ur.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ce.map(C),Jt?(0,ur.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,ur.jsx)(Zi,{onFailed:le("paypal"),children:(0,ur.jsx)(et.Suspense,{fallback:null,children:(0,ur.jsx)(t,{clientId:Jt.clientId,...Jt.environment?{environment:Jt.environment}:{},...pt.currency?{currency:pt.currency}:{},sessionId:r,nonce:n,billingApiUrl:ct,customer:At,...gt,...Mt,onFailed:le("paypal"),onUnavailable:bt("paypal")})})})}):null,Z.map(C)]}):null,B&&ae?(0,ur.jsx)(Ga,{label:"or add a card"}):null,B&&F&&he?.html?(0,ur.jsx)("div",{"data-flopay-payment-method":"card",children:(0,ur.jsx)(Eo,{capture:F,html:he.html,messageToken:he.messageToken,expectedOrigin:he.expectedOrigin,verificationRequired:he.verificationRequired,theme:Pe,containerStyle:xe,onReady:()=>{(0,Qe.invokeMerchantCallback)(()=>_e.current.onReady?.())},onValidation:u=>{(0,Qe.invokeMerchantCallback)(()=>_e.current.onValidation?.(u))},onError:u=>{u&&ft("card",mo(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Rd=require("react/jsx-runtime"),zp={StripeSetupMethod:bd,PayPalSetupMethod:fd};function wd(e){return(0,Rd.jsx)(Sd,{...e,branches:zp})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|