@flopay/react 1.14.14 → 1.15.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 +28 -0
- package/dist/flopay-checkout.d.ts +12 -2
- package/dist/index.cjs +9 -9
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +7 -7
- package/dist/payment-method-layout-placeholder.d.ts +10 -0
- package/dist/split-card-form.d.ts +18 -1
- package/dist/use-payment-method-layout.d.ts +21 -0
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Qc=Object.create;var Za=Object.defineProperty;var ed=Object.getOwnPropertyDescriptor;var td=Object.getOwnPropertyNames;var rd=Object.getPrototypeOf,nd=Object.prototype.hasOwnProperty;var od=(e,t)=>{for(var r in t)Za(e,r,{get:t[r],enumerable:!0})},Sl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of td(t))!nd.call(e,a)&&a!==r&&Za(e,a,{get:()=>t[a],enumerable:!(n=ed(t,a))||n.enumerable});return e};var Qi=(e,t,r)=>(r=e!=null?Qc(rd(e)):{},Sl(t||!e||!e.__esModule?Za(r,"default",{value:e,enumerable:!0}):r,e)),ad=e=>Sl(Za({},"__esModule",{value:!0}),e);var Fu={};od(Fu,{DirectPayPalButton:()=>Sa,FloPayAutomaticPaymentButton:()=>Cc,FloPayCardSetup:()=>bc,FloPayCardSetupError:()=>La,FloPayCheckout:()=>Ti,FloPayPaymentMethodSetup:()=>Ac,FloPayProvider:()=>Ra,SplitCardForm:()=>ki,VaultCardFields:()=>ho,dropThirdPartyOnlyError:()=>Bc.dropThirdPartyOnlyError,useCheckout:()=>Dl,useFloPay:()=>io,usePayPalFloPay:()=>ri});module.exports=ad(Fu);var Bc=require("@flopay/shared");var Mi=require("@flopay/js"),Rn=require("@flopay/shared"),ht=require("react");var er=require("react/jsx-runtime");function id(){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 sd(){return(0,er.jsx)(er.Fragment,{children:"Go back"})}function ld(){return(0,er.jsx)(er.Fragment,{children:"Secure card checkout"})}function zo(e){return e!==void 0&&(e===""||e===null||e===!1)}function qo({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(id,{}):e})}function jo({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(sd,{}):e})}function ga({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(ld,{}):e})}var bt=require("@flopay/shared"),Dn=require("@flopay/shared"),$o=require("@flopay/shared"),So=require("@flopay/shared");function es(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof bt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function cd(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 wl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,bt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,bt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function Rl(e,t){if(t&&(!(e instanceof bt.FloPayError)||e.type==="authentication_error"))return es(e);if(!(e instanceof bt.FloPayError&&cd(e))){if(!t&&!(e instanceof bt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,bt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof bt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof bt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Vo(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let c={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,bt.isCardHolderNamePlaceholder)(c.firstName,c.lastName);if(!(0,bt.isValidEmail)(c.email))return Promise.reject(new bt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[g,E]of Object.entries(c)){if(p&&g.endsWith("Name")||typeof E!="string")continue;let R=E.trim();R&&(y[g]=R)}return a=e.claimCheckoutSession(t,r,{accountData:y}),a.catch(()=>{}),a}}function kl(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 ts(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 El(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,c)=>s+(c.overrideAmount??c.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,c)=>({uuid:`synthetic-${s.type??"item"}-${c}`,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 rs(e,t){return t?{...e,...t}:e}function wr(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,c=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...s?{declineCode:s}:{},...c?{sessionId:c}:{}}}var Il=new WeakMap;function _l(e,t){return typeof e=="object"&&e!==null&&Il.set(e,t?{sessionId:t}:{}),e}function Tl(e){return typeof e=="object"&&e!==null?Il.get(e):void 0}function fo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function no(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function oo(e){return e?.status==="authorized"||e?.status==="complete"}function go(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 Ml(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Qa(e){let t=Ml(e);return new bt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ei(e){return e instanceof bt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Wo(e){return Ml(e)?new bt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new bt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new bt.FloPayError(bt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ha(e,t){return e==="processing"||(0,bt.isMoneySettledOutcome)(e,t)}function xl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Al(e,t){let r=e;if((0,bt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:c}=await r.retrieveSetupIntent(t);if(c)throw new bt.FloPayError(c.message??"Failed to retrieve setup intent.","api_error",{...c.code?{code:c.code}:{}});return s??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new bt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var dd=["apple_pay","google_pay"];function Fl(e,t="automatic",r){let n=(0,bt.resolveSetupFutureUsage)(r,dd,"wallet");return{...(0,bt.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var ud=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function ns(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:ud.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Pa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var co=require("@flopay/js"),Ne=require("@flopay/shared"),P=Qi(require("react"),1);var os=require("react"),vn=(0,os.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),On=(0,os.createContext)({session:null,loading:!1,error:null});var li=require("@flopay/js"),qe=require("@flopay/shared"),zl=require("@paypal/paypal-js"),k=require("react");var ti=require("@flopay/shared"),Ln=require("react"),Cn=require("@flopay/shared"),ao=require("react/jsx-runtime");function Ho(){let[e,t]=(0,Ln.useState)(null),r=(0,Ln.useRef)(null),n=(0,Ln.useRef)(0),a=(0,Ln.useCallback)((c,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:c,identity:p}),new Promise(y=>{r.current=y})),[]),s=(0,Ln.useCallback)(c=>{let p=r.current;r.current=null,t(null),p?.(c)},[]);return(0,Ln.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function Ko({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[c,p]=(0,Ln.useState)(e.email?.trim()??""),y=(0,ti.isValidEmail)(c.trim());return(0,ao.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,ao.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,ao.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,ao.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:c,onChange:g=>p(g.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,ao.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,ao.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,ao.jsxs)("button",{type:"button",disabled:!y||a,onClick:()=>{r((0,ti.compactBuyerIdentity)({...e,email:c.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var we=require("@flopay/shared");var Bl=require("@flopay/shared"),va=require("react");function io(){return(0,va.useContext)(vn).flopay}function ri(){return(0,va.useContext)(vn).paypalFlopay??null}function Dl(){return(0,va.useContext)(On)}function Ol(){return(0,va.useContext)(vn).billingApiUrl||(0,Bl.resolveBillingApiUrl)()}var pd=require("@flopay/shared"),Gn=require("@flopay/shared"),Yn=require("@flopay/shared");var Go=require("@flopay/shared"),Ro=require("react");var ni=require("react"),wo=typeof window>"u"?ni.useEffect:ni.useLayoutEffect;var as=require("@flopay/shared");function Yo(e,t){let r=(0,Ro.useRef)(e);r.current=e;let n=(0,Ro.useRef)(new Set),a=(0,Ro.useRef)(t),s=(0,Ro.useRef)(t);return wo(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,Ro.useCallback)(c=>{if(s.current!==t)return;let p=(0,Go.projectFloInstrument)(c);if(p){if(Go.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,Go.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Xe=require("@flopay/shared");var Ll=require("react"),Ca=(0,Ll.createContext)(null);function oi(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var ai="provider.callback.ignored";function ii(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var md=Symbol.for("@flopay/js.telemetry.bridge.v1"),yd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function fd(){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 gd(e){let t=fd(),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 si(e){let t=globalThis[yd];return gd(t?.(e)??{})}function Rr(e){if(e)return e[md]}var gr=require("react");function ba(e,t){let r=(0,gr.useRef)(0),n=(0,gr.useRef)(null),a=(0,gr.useRef)(null),s=(0,gr.useRef)(e),c=(0,gr.useRef)(t?.onHandoffObserved),p=(0,gr.useRef)(t?.defersMissingTerminal),y=(0,gr.useRef)(t?.onMissingTerminalDeferred);(0,gr.useEffect)(()=>{s.current=e,c.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,y.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let g=(0,gr.useCallback)((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),E=(0,gr.useCallback)(f=>{g();let h=r.current+1;return r.current=h,n.current=null,a.current={generation:h,method:f,timer:null,yieldedControl:!1},h},[g]),R=(0,gr.useCallback)(f=>{let h=a.current;return f!==void 0&&h?.generation!==f?!1:(g(h),a.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[g]),_=(0,gr.useCallback)(f=>{let h=a.current,ge=f??h?.generation??r.current;(f===void 0||h?.generation===f)&&(g(h),a.current=null),n.current=ge},[g]),H=(0,gr.useCallback)(f=>n.current===(f??r.current),[]),T=(0,gr.useCallback)(f=>a.current?.generation===f&&n.current!==f,[]),Y=(0,gr.useCallback)(()=>{let f=a.current;f&&(g(f),!f.yieldedControl&&(f.yieldedControl=!0,c.current?.(f.method)))},[g]),B=(0,gr.useCallback)(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(g(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))},[g]);return(0,gr.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?B():Y()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",Y),window.addEventListener("focus",B),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",Y),window.removeEventListener("focus",B),g()}},[g,Y,B]),{startAttempt:E,finishAttempt:R,invalidateAttempt:_,isAttemptInvalidated:H,isAttemptCurrent:T,generationRef:r}}var bn=require("react/jsx-runtime"),ci=45,hd=1e3,Pd=11e3,Nl="paypal_intent_settled",vd={width:"100%",minHeight:ci,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"},Cd={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 bd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Cd[e.kind]??null}}function Ul(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,we.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function Sd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function ql({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:c,environment:p,currency:y,isSubscription:g,providerObjectType:E,approvalPresentation:R,onTokenizedBody:_,onComplete:H,onErrorChange:T,onDecline:Y,onCancel:B,onTechnicalFailure:f,isProcessing:h=!1,onLoadStateChange:ge,onInitializationStateChange:S,allowAutomaticRetry:Me=!0,onButtonClick:A,runBeforeButtonClick:ie,session:he,existingOrderId:fe,telemetry:Re,telemetryContext:ct,onInstrument:Ke,debug:F=!1}){let St=io(),et=Yo(Ke,e),Ue=(0,k.useMemo)(()=>{if(St)return null;let K=si({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:qe.SDK_VERSION,enabled:Re!==!1});return K.setCheckoutContext(ct??{}),K.beginCheckout(ct??{}),K},[r,St,Re,ct?.checkoutMode,ct?.layout]),ye=(0,k.useMemo)(()=>Rr(St),[St]);(0,k.useEffect)(()=>()=>{Ue&&Ue.flush().catch(()=>{}).finally(()=>Ue.destroy())},[Ue]);let J=(0,k.useMemo)(()=>({error:K=>{ye?ye.error(K):Ue?.error(K),et({class:"technical_error",errorCode:K.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":K.errorCode,requestCategory:K.requestCategory,provider:K.provider})},log:K=>{ye?ye.log(K):Ue?.log(K),et({class:"lifecycle",name:K.name,provider:K.provider})},performance:K=>{ye?ye.performance(K):Ue?.performance(K)},terminal:K=>{ye?ye.terminal(K):Ue?.terminal(K)},startTiming:()=>ye?.now()??Ue?.now()??0,elapsed:K=>ye?.elapsed(K)??Math.max(0,(Ue?.now()??K)-K)}),[et,ye,Ue]),W=(0,k.useRef)(null),Fe=(0,k.useRef)(0),dt=(0,k.useRef)(null),We=(0,k.useRef)(null),Z=(0,k.useRef)(null),L=(0,k.useContext)(Ca),le=(0,k.useRef)(null);le.current||(le.current=oi());let j=L??le.current,Se=(0,k.useRef)(null),xe=(0,k.useRef)(!1),[Pe,Be]=(0,k.useState)(!1),[M,nt]=(0,k.useState)(!1),[je,ut]=(0,k.useState)(0),Ge=(0,k.useRef)(0),[$e,Rt]=(0,k.useState)(!1),Ot=(0,k.useRef)(!1),zt=(0,k.useRef)(!1),[Ft,ue]=(0,k.useState)(!1),[pe,X]=(0,k.useState)(!1),{request:Pt,collect:pt,finish:V}=Ho(),rt=(0,k.useRef)({sessionId:e,required:(0,qe.paypalProviderIdentityRequired)(n,he)});rt.current.sessionId!==e&&(rt.current={sessionId:e,required:(0,qe.paypalProviderIdentityRequired)(n,he)});let wt=rt.current.required,ke=(0,k.useMemo)(()=>r.replace(/\/+$/,""),[r]),U=he?.gateways?.paypal?.providerObjectType??E,ne=U??(g?"subscription":"order"),[Ae]=(0,k.useState)(Gn.detectPayPalEnvironment),Dt=he?.gateways?.paypal?.approvalPresentation??R,ot=(0,Yn.resolvePayPalPresentationMode)(Ae,Dt==="app_switch"?"app_switch":void 0,ne),De=(0,qe.usesPayPalVaultedChannel)(U),Oe=(0,k.useMemo)(()=>JSON.stringify([ke,c,y,p??"",ne,De,ot,e,fe??""]),[ke,c,y,p,fe,ne,De,ot,e]),_t=(0,k.useRef)(Oe),u=_t.current!==Oe,C=(0,k.useRef)(F),Q=(0,k.useRef)(null),[ce,N]=(0,k.useState)([]),w=(0,k.useCallback)(K=>{C.current&&N(Nt=>[...Nt,`${new Date().toISOString().slice(11,23)} ${K}`])},[]);(0,k.useEffect)(()=>{C.current=F,F&&w("debug:enabled"),Q.current?.setEnabled(F)},[w,F]);let qt=(0,k.useRef)(_),Ar=(0,k.useRef)(H),mr=(0,k.useRef)(T),Fr=(0,k.useRef)(Y),st=(0,k.useRef)(B),Gr=(0,k.useRef)(f),Yr=(0,k.useRef)(A),Br=(0,k.useRef)(ge),Xt=(0,k.useRef)(S),ar=(0,k.useRef)(s),tr=(0,k.useRef)(ie),In=(0,k.useRef)(he),Jt=(0,k.useRef)(n),qn=(0,k.useRef)(a),Dr=(0,k.useRef)(t),Zt=(0,k.useRef)(null),ir=(0,k.useRef)(new Map),nn=(0,k.useRef)(new Map),mt=(0,k.useRef)(!1),Tt=(0,k.useRef)(e);Tt.current=e;let[Or]=(0,k.useState)(ii);(0,k.useEffect)(()=>(mt.current=!0,()=>{mt.current=!1}),[]),(0,k.useEffect)(()=>{qt.current=_},[_]),(0,k.useEffect)(()=>{ar.current=s},[s]),(0,k.useEffect)(()=>{Ar.current=H},[H]),(0,k.useEffect)(()=>{mr.current=T},[T]),(0,k.useEffect)(()=>{Fr.current=Y},[Y]),(0,k.useEffect)(()=>{st.current=B},[B]),(0,k.useEffect)(()=>{Gr.current=f},[f]),(0,k.useEffect)(()=>{Yr.current=A},[A]),(0,k.useEffect)(()=>{Br.current=ge},[ge]),(0,k.useEffect)(()=>{Xt.current=S},[S]),(0,k.useEffect)(()=>{tr.current=ie},[ie]),(0,k.useEffect)(()=>{In.current=he},[he]),(0,k.useEffect)(()=>{Jt.current=n},[n]),(0,k.useEffect)(()=>{qn.current=a},[a]),(0,k.useEffect)(()=>{Dr.current=t},[t]),(0,k.useEffect)(()=>{Ge.current=je},[je]),(0,k.useEffect)(()=>{$e&&Se.current?.focus()},[$e,je]);let sr=(0,k.useCallback)(()=>{window.setTimeout(()=>{Se.current?.focus()},0)},[]),Qt=(0,k.useCallback)(()=>{Be(!1),ut(K=>K+1)},[]),zr=(0,k.useCallback)(()=>{Rt(!1),(W.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??W.current)?.focus?.()},[]);(0,k.useEffect)(()=>{!Pe||!xe.current||(xe.current=!1,zr())},[zr,Pe,je]);let Pr=(0,k.useCallback)((K,Nt)=>{let ae=Nt?.popupBlocked??(0,we.isPopupBlockedError)(K);ae&&j.markBlocked();let Ht=(0,we.buildExternalMethodRecoveryMessage)("PayPal",ae,Ae.inAppBrowser),Gt=Gr.current;if(Gt){let be=ae&&Ae.inAppBrowser?new qe.FloPayError(Ht,"api_error",{code:Nt?.code??"paypal_popup_blocked"}):K;Gt("paypal",be,Nt);return}if(K instanceof qe.FloPayError&&K.code==="checkout_processing_timeout"){mr.current?.(K.message);return}mr.current?.(Ht)},[j,Ae.inAppBrowser]),jt=(0,k.useCallback)(K=>{let Nt=dt.current,ae=We.current;Nt===null||!ae||(J.log({...ae,popupCapability:j.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:K}),J.performance({...ae,popupCapability:j.current(),stage:"overlay_return",durationMs:J.elapsed(Nt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:K}),dt.current=null)},[j,J]),Lr=(0,k.useCallback)((K,Nt,ae)=>{let Ht=We.current;jt("overlay_timeout"),Ht&&J.error({...Ht,popupCapability:j.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Pr(Nt,{...ae,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ot,terminalReason:"overlay_timeout"}),Rt(!0),Qt(),sr()},[jt,sr,Pr,j,ot,Qt,J]),Er=(0,k.useCallback)(()=>{j.markAvailable();let K=We.current;K&&(Z.current=K.attempt,J.log({...K,popupCapability:j.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[j,J]),{finishAttempt:Ce,generationRef:Nr,invalidateAttempt:_n,isAttemptCurrent:Tn,isAttemptInvalidated:vr,startAttempt:pn}=ba(Lr,{onHandoffObserved:Er}),mn=(0,k.useCallback)(()=>(Rt(!1),pn("paypal")),[pn]),Mn=(0,k.useCallback)(K=>{_n(K?.generation),K?.showRetry&&Rt(!0),K?.remount&&Qt(),K?.focus!==!1&&sr()},[sr,_n,Qt]),Lt=K=>{let Nt=Zt.current;return Nt&&nn.current.set(K,Nt),K};(0,k.useEffect)(()=>{_t.current!==Oe&&(_t.current=Oe,Ot.current=!1,zt.current=!1,Be(!1),nt(!1),ue(!1),Xt.current?.("loading"))},[Oe]),(0,k.useEffect)(()=>{(0,Xe.invokeMerchantCallback)(()=>Br.current?.(Pe&&!Ft))},[Pe,Ft]);let ve=(0,qe.normalizeGatewayEnvironment)(p);(0,k.useEffect)(()=>{let K={attempt:Nr.current+1,inAppBrowser:Ae.inAppBrowser,appFamily:Ae.appFamily,popupCapability:j.current(),presentationMode:ot},Nt=()=>({...We.current??K,popupCapability:j.current()}),ae={error:x=>J.error({...x,...Nt()}),log:x=>J.log({...x,...Nt()}),performance:x=>J.performance({...x,...Nt()}),terminal:x=>J.terminal({...x,...Nt()}),startTiming:J.startTiming,elapsed:J.elapsed},Ht=c?`${c.slice(0,6)}\u2026(len ${c.length})`:"(empty)",Gt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(w(`mount clientId=${Ht} env=${p??"(unset)"}\u2192${ve??"live"} ccy=${y} sub=${g}`),w(`ua=${Gt.slice(0,80)}${Gt.length>80?"\u2026":""}`),!c){w("FAIL: clientId empty \u2014 gateway misconfigured"),ue(!0),ae.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(!W.current){w("FAIL: containerRef not attached");return}Fe.current=ae.startTiming(),ae.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let be=!1,Ut=!1,tt=()=>be||Ut,at=x=>{let m=mt.current,I=m?x:"torn_down";m&&w(`onError ignored reason=${I}`),Or.take(Tt.current)&&ae.log({name:ai,stage:"provider_ready",reason:I,provider:"paypal",paymentMethodCategory:"paypal"})},rr=()=>Tt.current===e?"stale_attempt":"session_changed",Vr=De?ne:void 0,yn,lr=!1,jn=()=>{yn=(0,qe.generateIdempotencyKey)(),yn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),lr=!0},Vn=null,eo=!1,xn=null,po=!1,to=()=>{!xn||po||(po=!0,xn.close().catch(()=>{}))},an=!1,An=!1,sn=W.current,Wn=null,Vt=null,Xr=[],Jr=null,Zr=!1,fn=!1,yt=null,nr=x=>{if(!x||typeof x.getBoundingClientRect!="function")return"(no rect)";let m=x.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},Ir=x=>{if(!x)return"(empty)";try{let m=new URL(x,typeof window>"u"?"https://localhost":window.location.href),I=m.pathname.toLowerCase();return I.includes("checkcaptcha")||I.includes("captcha")?`CAPTCHA(${m.host}${I})`:I.includes("risk")||I.includes("challenge")?`RISK(${m.host}${I})`:I.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${I}`.slice(0,100)}catch{return x.slice(0,80)}},Wr=x=>{let m=x.getAttribute("src"),I=x.getAttribute("srcdoc"),Le=x.getAttribute("name"),Ze=x.getAttribute("sandbox"),He=[];return m&&He.push(`src=${Ir(m)}`),I&&He.push(`srcdoc[${I.length}ch]`),!m&&!I&&He.push("src=(empty) srcdoc=(empty)"),Le&&He.push(`name=${Le.slice(0,40)}`),Ze!==null&&He.push(`sandbox="${Ze.slice(0,40)}"`),He.join(" ")},_o=x=>{if(!(x instanceof HTMLIFrameElement))return"";try{let m=x.contentDocument;if(!m)return"cd=null";let I=m.body?.children.length??0,Le=m.body?.innerHTML.length??0,Ze=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${I}children,${Le}ch] head[${Ze}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},gn=[],ro=x=>{if(tt())return;let m=x.message??String(x.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(w(`window:error ${m.slice(0,140)}`),gn.push(m))},ln=x=>{if(tt())return;let m=x.reason instanceof Error?x.reason.message:String(x.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(w(`window:rejection ${m.slice(0,140)}`),gn.push(m))},Cr={value:0},mo=()=>{Wn?.disconnect(),Wn=null,Vt?.disconnect(),Vt=null;for(let x of Xr.splice(0))clearTimeout(x);fn=!1,Zr&&typeof window<"u"&&(window.removeEventListener("error",ro),window.removeEventListener("unhandledrejection",ln)),Zr=!1},qr=()=>{if(!(Zr||tt()||an)){if(Zr=!0,gn.length=0,Cr.value=0,typeof window<"u"&&(window.addEventListener("error",ro),window.addEventListener("unhandledrejection",ln)),typeof PerformanceObserver<"u")try{Vt=new PerformanceObserver(x=>{if(!tt())for(let m of x.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;Cr.value+=1;let I=Math.round(m.duration);w(`net ${I}ms ${m.name.slice(0,90)}`)}}),Vt.observe({type:"resource",buffered:!0})}catch{}yt?.()}},z=()=>{Jr&&(clearTimeout(Jr),Jr=null)},O=()=>{mo(),z()},se={setEnabled:x=>{x?qr():mo()}};Q.current=se,C.current&&qr();let me=qe.isPayPalTeardownMessage,kt=x=>{if(tt()||me(x))return;let m=(0,So.applyFriendlyMessageOverride)(x)??x;(0,Xe.invokeMerchantCallback)(()=>mr.current?.(m))},Wt=(x,m)=>{if(be||eo)return;eo=!0,Ut=!0,O(),to();let I=bd({kind:x,generationActive:!0,automaticRetryAllowed:Me,automaticRetryUsed:Ot.current});if(I.action==="retry"){Ot.current=!0,Be(!1),X(!1),nt(!0),Xt.current?.("retrying"),Vn=setTimeout(()=>{be||ut(Le=>Le+1)},hd);return}if(Be(!1),X(!1),nt(!1),ue(!0),I.action!=="ignore"){if(Xt.current?.("exhausted"),I.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",m);return}if(I.report){let Le=(0,we.classifyExternalMethodFailure)({code:Ul(x,m),message:m},{inAppBrowser:Ae.inAppBrowser,handoffObserved:!1});Le.popupBlocked&&j.markBlocked(),ae.error({errorCode:Le.popupBlocked?Le.errorCode:I.report.errorCode,stage:I.report.stage,operationOutcome:I.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:Le.terminalReason})}zt.current||(zt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Ul(x,m)))}};ue(!1);let Ve=async(x,m=Zt.current)=>{if(tt())return;let I=m?.sessionId??e;if(qt.current){await qt.current(x,{sessionId:I,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let Le=ae.startTiming();ae.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Ze=()=>{ae.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ae.performance({stage:"processing",durationMs:ae.elapsed(Le),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let He=(0,qe.buildPayPalProcessPaymentRequest)({body:x,sessionId:I,nonce:m?.nonce??Dr.current,accountPatch:m?.accountPatch,session:In.current,email:Jt.current}),Ye=await new li.PaymentAPI(ke,{telemetry:!1}).processPayment(He.userId,He.params);if(Ye.ok){if(Ut||be&&mt.current)return;Ze(),ae.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Xe.invokeMerchantCallback)(()=>Ar.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(tt())return;let br=await Ye.json().catch(()=>null),de=(0,qe.describePayPalProcessFailure)(br),Sr=de.message;Ze(),Ye.status===400&&(typeof br?.declineCode=="string"||!Array.isArray(br?.fields))?ae.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Ye.status===400||Ye.status===422?ae.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):ae.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Sd(Ye.status),failureCategory:Ye.status>=500?"server_error":void 0}),kt(Sr),(0,Xe.invokeMerchantCallback)(()=>Fr.current?.(wr("paypal",Sr,{code:de.code,declineCode:de.declineCode})));return}catch(He){if(tt())return;Ze(),ae.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let It=(0,qe.friendlyPayPalFailureMessage)(He instanceof Error?He.message:void 0);kt(It),(0,Xe.invokeMerchantCallback)(()=>Fr.current?.(wr("paypal",It)));return}},oe=()=>new qe.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),te=x=>tt()?Promise.reject(oe()):Promise.resolve(x),Je=async x=>{if(x.ok){ae.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Xe.invokeMerchantCallback)(()=>Ar.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let m=await x.json().catch(()=>null),I=(0,qe.describePayPalProcessFailure)(m);ae.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Xe.invokeMerchantCallback)(()=>Fr.current?.(wr("paypal",I.message,{code:I.code,declineCode:I.declineCode})))},Ee=()=>{let x=Zt.current;jt("approved"),x&&(ir.current.delete(x.surfaceKey),Ce(x.generation)),Zt.current=null},it=async x=>{if(tt())throw oe();lr||jn();let m=Zt.current,I=m?.sessionId??e,Le=m?.nonce??Dr.current;ae.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Ze;try{Ze=await new li.PaymentAPI(ke,{telemetry:!1}).createSessionIntent(I,Le??"",(0,qe.buildPayPalSessionIntentRequest)(Vr),{idempotencyKey:yn})}catch(He){throw ae.error({...(0,qe.classifyTelemetryFailure)(He,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),He}if(tt())throw oe();if((0,qe.isSettledSessionIntent)(Ze))throw await Je(Ze.response),Ee(),new qe.FloPayError("PayPal checkout already settled.","api_error",{code:Nl});if(Ze.provider!=="paypal"||Ze.providerObjectType!==ne)throw new Error(x);return ae.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Ze.providerObjectId},q=(x,m)=>{let I=m?.nonce??Dr.current;if(!I)return;let Le=m?.sessionId??e,Ze=(0,qe.resolvePayPalDeclineReason)(x);new li.PaymentAPI(ke,{telemetry:!1}).reportSessionIntentDecline(Le,I,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ze}).catch(()=>{})},ee=je;w("loadScript:scheduled (deferred 1 tick)");let Bt=null,Et=setTimeout(()=>{if(be){w("loadScript:skipped (cancelled before defer ran)");return}w("loadScript:start");let x=ve==="live"?"production":ve,m={};ne==="subscription"?m={intent:"subscription",vault:!0}:ne==="order"&&(m={intent:"capture"}),Bt=(0,zl.loadScript)({clientId:c,currency:y,...m,...x?{environment:x}:{},...x==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let I=!1;Bt.then(Le=>{if(I=!0,w(`loadScript:resolved inactive=${tt()} ns=${!!Le} buttons=${!!Le?.Buttons}`),tt())return;if(!Le?.Buttons){w("FAIL: namespace missing Buttons factory"),Wt("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}ae.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),ae.performance({stage:"provider_ready",durationMs:ae.elapsed(Fe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ae.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Ze=async(Mt,xt)=>{if(tt()||Ge.current!==ee)return;let Ie=Mt.vaultSetupToken??Mt.subscriptionID??Mt.orderID??"",vt=Ie?nn.current.get(Ie):ir.current.get(ee);if(!(!vt||!Tn(vt.generation))&&Ce(vt.generation)){nn.current.delete(Ie),ir.current.delete(vt.surfaceKey),jt("approved");try{if(X(!0),(0,Xe.invokeMerchantCallback)(()=>mr.current?.(null)),!Ie)throw new qe.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let re=(0,qe.resolvePayPalApprovalIdentity)({accountPatch:vt.accountPatch,email:Jt.current,billingName:qn.current,session:In.current});if((0,qe.needsPayPalPayerDetails)(re))try{re=(0,qe.mergePayPalPayerIdentity)(re,await xt?.order?.get?.())}catch{}if((ar.current||wt)&&!(0,qe.isValidEmail)(re.email)){let Yt=await pt("PayPal",re);if(!Yt)return;re=Yt}(0,qe.isValidEmail)(re.email)&&(vt.accountPatch=(0,Cn.compactBuyerIdentity)({...vt.accountPatch,...re}),await ar.current?.(re));let _r=(0,qe.buildPayPalTokenizedBody)(Ie,Vr);await Ve(_r,vt)}catch(re){kt(re instanceof Error?re.message:"PayPal capture failed.")}finally{tt()||X(!1)}}},He=Mt=>{let xt=fe?()=>te(fe):()=>it(Mt);return async()=>Lt(await xt())},It=Le.Buttons({style:{layout:"horizontal",height:ci,tagline:!1},...ot==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Mt,xt)=>{if(tt()){await xt.reject();return}jn();let Ie=tr.current,vt={};if(Ie)try{let Yt=await Ie("paypal");if(tt()){await xt.reject();return}if(!Yt.proceed){Zt.current=null,ir.current.delete(ee),await xt.reject();return}vt={sessionId:Yt.sessionId,accountPatch:Yt.accountPatch,nonce:Yt.nonce}}catch(Yt){w(`onClick:runBeforeButtonClick rejected msg=${(Yt instanceof Error?Yt.message:String(Yt)).slice(0,120)}`),Zt.current=null,ir.current.delete(ee),await xt.reject();return}(0,Xe.invokeMerchantCallback)(()=>Yr.current?.("paypal"));let re=mn(),_r={generation:re,surfaceKey:ee,...vt};Zt.current=_r,ir.current.set(ee,_r),We.current={...K,attempt:re},await xt.resolve(),ae.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ae.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),dt.current=ae.startTiming()},createOrder:ne==="order"?He("Failed to create PayPal order."):void 0,createSubscription:ne==="subscription"?He("Failed to create PayPal subscription."):void 0,createVaultSetupToken:ne==="setup_token"?async()=>Lt(await it("Failed to create PayPal setup token.")):void 0,onApprove:Ze,onCancel:()=>{if(tt())return;let Mt=ir.current.get(ee)??Zt.current,xt=Mt&&Tn(Mt.generation)?(0,qe.buildPayPalCancelEvent)(Mt.sessionId??e,Vr):null;Mt&&ir.current.delete(Mt.surfaceKey),Zt.current=null,jt("cancelled"),ae.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),xe.current=!0,Mn({generation:Mt?.generation,remount:!0,focus:!1}),xt&&(0,Xe.invokeMerchantCallback)(()=>st.current?.(xt))},onError:Mt=>{if(Mt instanceof qe.FloPayError&&Mt.code===Nl)return;let xt=Mt instanceof Error?Mt.message:"PayPal failed to render.";if(tt()||Ge.current!==ee){me(xt)||at(rr());return}if(an){let Ie=ir.current.get(ee)??Zt.current;if(!Ie||!Tn(Ie.generation)){if(me(xt)){!Ie&&!vr()&&Ce();return}at(Ie||vr()?"stale_attempt":"no_current_attempt");return}if(w(`onError rendered=${an} msg=${xt.slice(0,120)}`),me(xt)){Ce(Ie.generation);return}let{errorCode:vt,popupBlocked:re,providerDeclined:_r,terminalReason:Yt}=(0,we.classifyExternalMethodFailure)(Mt,{inAppBrowser:Ae.inAppBrowser,handoffObserved:Z.current===Ie.generation});if(re&&j.markBlocked(),jt(Yt),_r){ae.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Yt}),q(Mt,Ie),(0,Xe.invokeMerchantCallback)(()=>Fr.current?.(wr("paypal",xt))),ir.current.delete(Ie.surfaceKey),Zt.current=null,Ce(Ie.generation);return}ae.error({errorCode:vt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Yt}),ir.current.delete(Ie.surfaceKey),Zt.current=null,Mn({generation:Ie.generation,remount:!0,showRetry:!0,focus:!0}),Pr(Mt,{code:"paypal_runtime_failed",popupBlocked:re,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ot,terminalReason:Yt});return}w(`onError rendered=${an} msg=${xt.slice(0,120)}`),Wt(me(xt)?"teardown":"pre_ready_callback",xt)}}),Ye=It.isEligible();if(w(`isEligible=${Ye}`),ae.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Ye){Be(!1),Wt("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}An=!0,xn=It,yt=()=>{if(!Zr||fn||tt()||an)return;fn=!0,w(`container:dims ${nr(sn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Wn=new MutationObserver(xt=>{if(!tt()){for(let Ie of xt)if(Ie.type==="childList")Ie.addedNodes.forEach(vt=>{if(!(vt instanceof Element))return;let re=vt.tagName.toLowerCase(),_r=(vt.getAttribute("title")??"").slice(0,40),Yt=re==="iframe"?` ${Wr(vt)}`:"";w(`child+ ${re}${_r?` title="${_r}"`:""}${Yt} dims=${nr(vt)}`)});else if(Ie.type==="attributes"&&Ie.target instanceof Element){let vt=Ie.target;if(vt.tagName.toLowerCase()!=="iframe")continue;let re=Ie.attributeName;(re==="src"||re==="srcdoc")&&w(`attr~ iframe ${re}=${re==="srcdoc"?`[${(vt.getAttribute("srcdoc")??"").length}ch]`:Ir(vt.getAttribute("src"))} dims=${nr(vt)}`)}}}),Wn.observe(sn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Mt=xt=>{if(tt()||an)return;let Ie=sn.querySelectorAll("iframe"),vt=typeof document<"u"&&"hasStorageAccess"in document;w(`watchdog:${xt} container=${nr(sn)} children=${sn.childElementCount} iframes=${Ie.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${vt} paypalNetRequests=${Cr.value}`),Ie.forEach((re,_r)=>{let Yt=(re.getAttribute("title")??"").slice(0,40);w(` iframe[${_r}] ${nr(re)}${Yt?` title="${Yt}"`:""} ${Wr(re)}`);let To=_o(re);To&&w(` ${To}`)}),gn.length===0&&w(" (no PayPal/zoid window errors captured)")};Xr.push(setTimeout(()=>Mt("3s"),3e3)),Xr.push(setTimeout(()=>Mt("8s"),8e3)),Xr.push(setTimeout(()=>Mt("15s"),15e3))},yt(),w("render:start");let de=ae.startTiming();Jr=setTimeout(()=>{tt()||an||(w("watchdog:11s retryable render timeout"),Wt("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Pd);let Sr=It.render(sn);(async()=>{try{if(await Sr,w(`render:resolved inactive=${tt()}`),O(),tt()){to();return}an=!0,Be(!0),nt(!1),Xt.current?.("ready"),ae.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),ae.performance({stage:"checkout_render",durationMs:ae.elapsed(de),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Mt){let xt=Mt instanceof Error?Mt.message:"PayPal failed to render.";w(`render:rejected msg=${xt.slice(0,120)}`),O(),Wt(me(xt)?"teardown":"render_rejected",xt)}})()}).catch(Le=>{let Ze=Le instanceof Error?Le.message:"PayPal operation failed.";w(`provider:failed msg=${Ze.slice(0,120)}`);let He="script_rejected";I&&me(Ze)?He="teardown":I&&An&&(He="render_rejected"),Wt(He,Ze)})},0);return()=>{be=!0,clearTimeout(Et),Vn&&clearTimeout(Vn),O(),Q.current===se&&(Q.current=null),to(),dt.current=null,We.current=null}},[Me,ke,c,y,p,ne,ot,De,e,fe,je,J,pt,wt,w,jt]);let on=F?(0,bn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ft?"#fef2f2":"#f3f4f6",border:`1px solid ${Ft?"#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=${Pe} failed=${Ft})`,ce.length===0?`
|
|
1
|
+
"use strict";var md=Object.create;var ti=Object.defineProperty;var fd=Object.getOwnPropertyDescriptor;var gd=Object.getOwnPropertyNames;var hd=Object.getPrototypeOf,Pd=Object.prototype.hasOwnProperty;var vd=(e,t)=>{for(var r in t)ti(e,r,{get:t[r],enumerable:!0})},xl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of gd(t))!Pd.call(e,a)&&a!==r&&ti(e,a,{get:()=>t[a],enumerable:!(n=fd(t,a))||n.enumerable});return e};var as=(e,t,r)=>(r=e!=null?md(hd(e)):{},xl(t||!e||!e.__esModule?ti(r,"default",{value:e,enumerable:!0}):r,e)),Cd=e=>xl(ti({},"__esModule",{value:!0}),e);var Ju={};vd(Ju,{DirectPayPalButton:()=>Ra,FloPayAutomaticPaymentButton:()=>Bc,FloPayCardSetup:()=>Dc,FloPayCardSetupError:()=>za,FloPayCheckout:()=>Fi,FloPayPaymentMethodSetup:()=>Hc,FloPayProvider:()=>Ea,SplitCardForm:()=>Ti,VaultCardFields:()=>wo,dropThirdPartyOnlyError:()=>Gc.dropThirdPartyOnlyError,useCheckout:()=>$l,useFloPay:()=>co,usePayPalFloPay:()=>ai});module.exports=Cd(Ju);var Gc=require("@flopay/shared");var Bi=require("@flopay/js"),_n=require("@flopay/shared"),gt=require("react");var er=require("react/jsx-runtime");function bd(){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 Sd(){return(0,er.jsx)(er.Fragment,{children:"Go back"})}function wd(){return(0,er.jsx)(er.Fragment,{children:"Secure card checkout"})}function Ko(e){return e!==void 0&&(e===""||e===null||e===!1)}function Go({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(bd,{}):e})}function Yo({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(Sd,{}):e})}function Pa({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(wd,{}):e})}var wt=require("@flopay/shared"),Nn=require("@flopay/shared"),Zo=require("@flopay/shared"),Io=require("@flopay/shared");function is(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof wt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Rd(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 Fl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,wt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,wt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function Bl(e,t){if(t&&(!(e instanceof wt.FloPayError)||e.type==="authentication_error"))return is(e);if(!(e instanceof wt.FloPayError&&Rd(e))){if(!t&&!(e instanceof wt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,wt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof wt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof wt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Xo(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,wt.isCardHolderNamePlaceholder)(d.firstName,d.lastName);if(!(0,wt.isValidEmail)(d.email))return Promise.reject(new wt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[b,v]of Object.entries(d)){if(p&&b.endsWith("Name")||typeof v!="string")continue;let S=v.trim();S&&(y[b]=S)}return a=e.claimCheckoutSession(t,r,{accountData:y}),a.catch(()=>{}),a}}function Dl(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 ss(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 Ol(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 ls(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 Ll=new WeakMap;function Nl(e,t){return typeof e=="object"&&e!==null&&Ll.set(e,t?{sessionId:t}:{}),e}function Ul(e){return typeof e=="object"&&e!==null?Ll.get(e):void 0}function Co(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 bo(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 zl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ri(e){let t=zl(e);return new wt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ni(e){return e instanceof wt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Jo(e){return zl(e)?new wt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new wt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new wt.FloPayError(wt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function va(e,t){return e==="processing"||(0,wt.isMoneySettledOutcome)(e,t)}function ql(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function jl(e,t){let r=e;if((0,wt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:d}=await r.retrieveSetupIntent(t);if(d)throw new wt.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 wt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var kd=["apple_pay","google_pay"];function Vl(e,t="automatic",r){let n=(0,wt.resolveSetupFutureUsage)(r,kd,"wallet");return{...(0,wt.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var Ed=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function cs(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:Ed.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Ca(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"),Me=require("@flopay/shared"),R=as(require("react"),1);var ds=require("react"),Sn=(0,ds.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Un=(0,ds.createContext)({session:null,loading:!1,error:null});var ui=require("@flopay/js"),Ue=require("@flopay/shared"),Xl=require("@paypal/paypal-js"),k=require("react");var oi=require("@flopay/shared"),zn=require("react"),wn=require("@flopay/shared"),lo=require("react/jsx-runtime");function Qo(){let[e,t]=(0,zn.useState)(null),r=(0,zn.useRef)(null),n=(0,zn.useRef)(0),a=(0,zn.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,zn.useCallback)(d=>{let p=r.current;r.current=null,t(null),p?.(d)},[]);return(0,zn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function ea({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[d,p]=(0,zn.useState)(e.email?.trim()??""),y=(0,oi.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:b=>p(b.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,oi.compactBuyerIdentity)({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Re=require("@flopay/shared");var Wl=require("@flopay/shared"),ba=require("react");function co(){return(0,ba.useContext)(Sn).flopay}function ai(){return(0,ba.useContext)(Sn).paypalFlopay??null}function $l(){return(0,ba.useContext)(Un)}function Hl(){return(0,ba.useContext)(Sn).billingApiUrl||(0,Wl.resolveBillingApiUrl)()}var _d=require("@flopay/shared"),Gn=require("@flopay/shared"),Yn=require("@flopay/shared");var ta=require("@flopay/shared"),Mo=require("react");var ii=require("react"),To=typeof window>"u"?ii.useEffect:ii.useLayoutEffect;var us=require("@flopay/shared");function ra(e,t){let r=(0,Mo.useRef)(e);r.current=e;let n=(0,Mo.useRef)(new Set),a=(0,Mo.useRef)(t),s=(0,Mo.useRef)(t);return To(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,Mo.useCallback)(d=>{if(s.current!==t)return;let p=(0,ta.projectFloInstrument)(d);if(p){if(ta.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,ta.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Ge=require("@flopay/shared");var Kl=require("react"),Sa=(0,Kl.createContext)(null);function si(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var li="provider.callback.ignored";function ci(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var Id=Symbol.for("@flopay/js.telemetry.bridge.v1"),Td=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Md(){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 Ad(e){let t=Md(),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 di(e){let t=globalThis[Td];return Ad(t?.(e)??{})}function Er(e){if(e)return e[Id]}var vr=require("react");function wa(e,t){let r=(0,vr.useRef)(0),n=(0,vr.useRef)(null),a=(0,vr.useRef)(null),s=(0,vr.useRef)(e),d=(0,vr.useRef)(t?.onHandoffObserved),p=(0,vr.useRef)(t?.defersMissingTerminal),y=(0,vr.useRef)(t?.onMissingTerminalDeferred);(0,vr.useEffect)(()=>{s.current=e,d.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,y.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let b=(0,vr.useCallback)((g=a.current)=>{g?.timer&&(clearTimeout(g.timer),g.timer=null)},[]),v=(0,vr.useCallback)(g=>{b();let O=r.current+1;return r.current=O,n.current=null,a.current={generation:O,method:g,timer:null,yieldedControl:!1},O},[b]),S=(0,vr.useCallback)(g=>{let O=a.current;return g!==void 0&&O?.generation!==g?!1:(b(O),a.current=null,(g===void 0||n.current===g)&&(n.current=null),!0)},[b]),E=(0,vr.useCallback)(g=>{let O=a.current,ke=g??O?.generation??r.current;(g===void 0||O?.generation===g)&&(b(O),a.current=null),n.current=ke},[b]),V=(0,vr.useCallback)(g=>n.current===(g??r.current),[]),x=(0,vr.useCallback)(g=>a.current?.generation===g&&n.current!==g,[]),D=(0,vr.useCallback)(()=>{let g=a.current;g&&(b(g),!g.yieldedControl&&(g.yieldedControl=!0,d.current?.(g.method)))},[b]),A=(0,vr.useCallback)(()=>{let g=a.current;!g?.yieldedControl||document.visibilityState!=="visible"||(b(g),g.timer=setTimeout(()=>{if(g.timer=null,a.current?.generation===g.generation){if(p.current?.(g.method)){y.current?.(g.method,g.generation);return}a.current=null,n.current=g.generation,s.current(g.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},Re.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[b]);return(0,vr.useEffect)(()=>{let g=()=>{document.visibilityState==="visible"?A():D()};return document.addEventListener("visibilitychange",g),window.addEventListener("blur",D),window.addEventListener("focus",A),()=>{document.removeEventListener("visibilitychange",g),window.removeEventListener("blur",D),window.removeEventListener("focus",A),b()}},[b,D,A]),{startAttempt:v,finishAttempt:S,invalidateAttempt:E,isAttemptInvalidated:V,isAttemptCurrent:x,generationRef:r}}var Rn=require("react/jsx-runtime"),pi=45,xd=1e3,Fd=11e3,Gl="paypal_intent_settled",Bd={width:"100%",minHeight:pi,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"},Dd={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 Od(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Dd[e.kind]??null}}function Yl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,Re.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function Ld(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Jl({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:d,environment:p,currency:y,isSubscription:b,providerObjectType:v,approvalPresentation:S,onTokenizedBody:E,onComplete:V,onErrorChange:x,onDecline:D,onCancel:A,onTechnicalFailure:g,isProcessing:O=!1,onLoadStateChange:ke,onInitializationStateChange:m,allowAutomaticRetry:me=!0,onButtonClick:_,runBeforeButtonClick:ne,session:fe,existingOrderId:ce,telemetry:Ee,telemetryContext:vt,onInstrument:ze,debug:L=!1}){let Ye=co(),at=ra(ze,e),qe=(0,k.useMemo)(()=>{if(Ye)return null;let C=di({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:Ue.SDK_VERSION,enabled:Ee!==!1});return C.setCheckoutContext(vt??{}),C.beginCheckout(vt??{}),C},[r,Ye,Ee,vt?.checkoutMode,vt?.layout]),ye=(0,k.useMemo)(()=>Er(Ye),[Ye]);(0,k.useEffect)(()=>()=>{qe&&qe.flush().catch(()=>{}).finally(()=>qe.destroy())},[qe]);let N=(0,k.useMemo)(()=>({error:C=>{ye?ye.error(C):qe?.error(C),at({class:"technical_error",errorCode:C.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":C.errorCode,requestCategory:C.requestCategory,provider:C.provider})},log:C=>{ye?ye.log(C):qe?.log(C),at({class:"lifecycle",name:C.name,provider:C.provider})},performance:C=>{ye?ye.performance(C):qe?.performance(C)},terminal:C=>{ye?ye.terminal(C):qe?.terminal(C)},startTiming:()=>ye?.now()??qe?.now()??0,elapsed:C=>ye?.elapsed(C)??Math.max(0,(qe?.now()??C)-C)}),[at,ye,qe]),le=(0,k.useRef)(null),de=(0,k.useRef)(0),rt=(0,k.useRef)(null),je=(0,k.useRef)(null),Q=(0,k.useRef)(null),W=(0,k.useContext)(Sa),ee=(0,k.useRef)(null);ee.current||(ee.current=si());let te=W??ee.current,ve=(0,k.useRef)(null),ue=(0,k.useRef)(!1),[pe,Fe]=(0,k.useState)(!1),[ge,H]=(0,k.useState)(!1),[Be,ut]=(0,k.useState)(0),Xe=(0,k.useRef)(0),[nt,it]=(0,k.useState)(!1),or=(0,k.useRef)(!1),_t=(0,k.useRef)(!1),[qt,Ce]=(0,k.useState)(!1),[oe,Ze]=(0,k.useState)(!1),{request:J,collect:Ct,finish:Rt}=Qo(),se=(0,k.useRef)({sessionId:e,required:(0,Ue.paypalProviderIdentityRequired)(n,fe)});se.current.sessionId!==e&&(se.current={sessionId:e,required:(0,Ue.paypalProviderIdentityRequired)(n,fe)});let De=se.current.required,It=(0,k.useMemo)(()=>r.replace(/\/+$/,""),[r]),U=fe?.gateways?.paypal?.providerObjectType??v,he=U??(b?"subscription":"order"),[ae]=(0,k.useState)(Gn.detectPayPalEnvironment),Wt=fe?.gateways?.paypal?.approvalPresentation??S,Bt=(0,Yn.resolvePayPalPresentationMode)(ae,Wt==="app_switch"?"app_switch":void 0,he),Ae=(0,Ue.usesPayPalVaultedChannel)(U),be=(0,k.useMemo)(()=>JSON.stringify([It,d,y,p??"",he,Ae,Bt,e,ce??""]),[It,d,y,p,ce,he,Ae,Bt,e]),bt=(0,k.useRef)(be),u=bt.current!==be,B=(0,k.useRef)(L),I=(0,k.useRef)(null),[xe,z]=(0,k.useState)([]),F=(0,k.useCallback)(C=>{B.current&&z(kt=>[...kt,`${new Date().toISOString().slice(11,23)} ${C}`])},[]);(0,k.useEffect)(()=>{B.current=L,L&&F("debug:enabled"),I.current?.setEnabled(L)},[F,L]);let $e=(0,k.useRef)(E),ar=(0,k.useRef)(V),tr=(0,k.useRef)(x),br=(0,k.useRef)(D),Tt=(0,k.useRef)(A),Zr=(0,k.useRef)(g),pn=(0,k.useRef)(_),sn=(0,k.useRef)(ke),jt=(0,k.useRef)(m),Dt=(0,k.useRef)(s),yn=(0,k.useRef)(ne),Yt=(0,k.useRef)(fe),ln=(0,k.useRef)(n),pr=(0,k.useRef)(a),Mn=(0,k.useRef)(t),Jt=(0,k.useRef)(null),ir=(0,k.useRef)(new Map),Qr=(0,k.useRef)(new Map),ot=(0,k.useRef)(!1),At=(0,k.useRef)(e);At.current=e;let[Or]=(0,k.useState)(ci);(0,k.useEffect)(()=>(ot.current=!0,()=>{ot.current=!1}),[]),(0,k.useEffect)(()=>{$e.current=E},[E]),(0,k.useEffect)(()=>{Dt.current=s},[s]),(0,k.useEffect)(()=>{ar.current=V},[V]),(0,k.useEffect)(()=>{tr.current=x},[x]),(0,k.useEffect)(()=>{br.current=D},[D]),(0,k.useEffect)(()=>{Tt.current=A},[A]),(0,k.useEffect)(()=>{Zr.current=g},[g]),(0,k.useEffect)(()=>{pn.current=_},[_]),(0,k.useEffect)(()=>{sn.current=ke},[ke]),(0,k.useEffect)(()=>{jt.current=m},[m]),(0,k.useEffect)(()=>{yn.current=ne},[ne]),(0,k.useEffect)(()=>{Yt.current=fe},[fe]),(0,k.useEffect)(()=>{ln.current=n},[n]),(0,k.useEffect)(()=>{pr.current=a},[a]),(0,k.useEffect)(()=>{Mn.current=t},[t]),(0,k.useEffect)(()=>{Xe.current=Be},[Be]),(0,k.useEffect)(()=>{nt&&ve.current?.focus()},[nt,Be]);let Lr=(0,k.useCallback)(()=>{window.setTimeout(()=>{ve.current?.focus()},0)},[]),Ir=(0,k.useCallback)(()=>{Fe(!1),ut(C=>C+1)},[]),jr=(0,k.useCallback)(()=>{it(!1),(le.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??le.current)?.focus?.()},[]);(0,k.useEffect)(()=>{!pe||!ue.current||(ue.current=!1,jr())},[jr,pe,Be]);let Fr=(0,k.useCallback)((C,kt)=>{let ie=kt?.popupBlocked??(0,Re.isPopupBlockedError)(C);ie&&te.markBlocked();let _e=(0,Re.buildExternalMethodRecoveryMessage)("PayPal",ie,ae.inAppBrowser),Ut=Zr.current;if(Ut){let Ot=ie&&ae.inAppBrowser?new Ue.FloPayError(_e,"api_error",{code:kt?.code??"paypal_popup_blocked"}):C;Ut("paypal",Ot,kt);return}if(C instanceof Ue.FloPayError&&C.code==="checkout_processing_timeout"){tr.current?.(C.message);return}tr.current?.(_e)},[te,ae.inAppBrowser]),Zt=(0,k.useCallback)(C=>{let kt=rt.current,ie=je.current;kt===null||!ie||(N.log({...ie,popupCapability:te.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:C}),N.performance({...ie,popupCapability:te.current(),stage:"overlay_return",durationMs:N.elapsed(kt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:C}),rt.current=null)},[te,N]),Sr=(0,k.useCallback)((C,kt,ie)=>{let _e=je.current;Zt("overlay_timeout"),_e&&N.error({..._e,popupCapability:te.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Fr(kt,{...ie,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Bt,terminalReason:"overlay_timeout"}),it(!0),Ir(),Lr()},[Zt,Lr,Fr,te,Bt,Ir,N]),wr=(0,k.useCallback)(()=>{te.markAvailable();let C=je.current;C&&(Q.current=C.attempt,N.log({...C,popupCapability:te.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[te,N]),rr=(0,k.useCallback)(()=>!0,[]),Xt=(0,k.useCallback)(()=>{let C=je.current;if(!C)return;let kt=rt.current;N.performance({...C,popupCapability:te.current(),stage:"overlay_return",durationMs:kt===null?0:N.elapsed(kt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[te,N]),{finishAttempt:Vr,generationRef:Nr,invalidateAttempt:He,isAttemptCurrent:Ur,isAttemptInvalidated:Wr,startAttempt:An}=wa(Sr,{onHandoffObserved:wr,defersMissingTerminal:rr,onMissingTerminalDeferred:Xt}),zr=(0,k.useCallback)(()=>(it(!1),An("paypal")),[An]),Qt=(0,k.useCallback)(C=>{He(C?.generation),C?.showRetry&&it(!0),C?.remount&&Ir(),C?.focus!==!1&&Lr()},[Lr,He,Ir]),sr=C=>{let kt=Jt.current;return kt&&Qr.current.set(C,kt),C};(0,k.useEffect)(()=>{bt.current!==be&&(bt.current=be,or.current=!1,_t.current=!1,Fe(!1),H(!1),Ce(!1),jt.current?.("loading"))},[be]),(0,k.useEffect)(()=>{(0,Ge.invokeMerchantCallback)(()=>sn.current?.(pe&&!qt))},[pe,qt]);let en=(0,Ue.normalizeGatewayEnvironment)(p);(0,k.useEffect)(()=>{let C={attempt:Nr.current+1,inAppBrowser:ae.inAppBrowser,appFamily:ae.appFamily,popupCapability:te.current(),presentationMode:Bt},kt=()=>({...je.current??C,popupCapability:te.current()}),ie={error:P=>N.error({...P,...kt()}),log:P=>N.log({...P,...kt()}),performance:P=>N.performance({...P,...kt()}),terminal:P=>N.terminal({...P,...kt()}),startTiming:N.startTiming,elapsed:N.elapsed},_e=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",Ut=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(F(`mount clientId=${_e} env=${p??"(unset)"}\u2192${en??"live"} ccy=${y} sub=${b}`),F(`ua=${Ut.slice(0,80)}${Ut.length>80?"\u2026":""}`),!d){F("FAIL: clientId empty \u2014 gateway misconfigured"),Ce(!0),ie.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(!le.current){F("FAIL: containerRef not attached");return}de.current=ie.startTiming(),ie.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ot=!1,$t=!1,We=()=>Ot||$t,$r=P=>{let f=ot.current,G=f?P:"torn_down";f&&F(`onError ignored reason=${G}`),Or.take(At.current)&&ie.log({name:li,stage:"provider_ready",reason:G,provider:"paypal",paymentMethodCategory:"paypal"})},eo=()=>At.current===e?"stale_attempt":"session_changed",zt=Ae?he:void 0,Vt,Wn=!1,to=()=>{Vt=(0,Ue.generateIdempotencyKey)(),Vt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Wn=!0},mn=null,xn=!1,ro=null,fo=!1,go=()=>{!ro||fo||(fo=!0,ro.close().catch(()=>{}))},Hr=!1,ho=!1,Fn=le.current,Bn=null,fn=null,gn=[],Ht=null,hn=!1,Pn=!1,Kr=null,Gr=P=>{if(!P||typeof P.getBoundingClientRect!="function")return"(no rect)";let f=P.getBoundingClientRect();return`${Math.round(f.width)}\xD7${Math.round(f.height)}`},Qe=P=>{if(!P)return"(empty)";try{let f=new URL(P,typeof window>"u"?"https://localhost":window.location.href),G=f.pathname.toLowerCase();return G.includes("checkcaptcha")||G.includes("captcha")?`CAPTCHA(${f.host}${G})`:G.includes("risk")||G.includes("challenge")?`RISK(${f.host}${G})`:G.includes("smart/buttons")?`smart-buttons(${f.host})`:`${f.host}${G}`.slice(0,100)}catch{return P.slice(0,80)}},Br=P=>{let f=P.getAttribute("src"),G=P.getAttribute("srcdoc"),Ie=P.getAttribute("name"),Le=P.getAttribute("sandbox"),dt=[];return f&&dt.push(`src=${Qe(f)}`),G&&dt.push(`srcdoc[${G.length}ch]`),!f&&!G&&dt.push("src=(empty) srcdoc=(empty)"),Ie&&dt.push(`name=${Ie.slice(0,40)}`),Le!==null&&dt.push(`sandbox="${Le.slice(0,40)}"`),dt.join(" ")},Rr=P=>{if(!(P instanceof HTMLIFrameElement))return"";try{let f=P.contentDocument;if(!f)return"cd=null";let G=f.body?.children.length??0,Ie=f.body?.innerHTML.length??0,Le=f.head?.innerHTML.length??0;return`cd=same-origin readyState=${f.readyState} body[${G}children,${Ie}ch] head[${Le}ch]`}catch(f){return`cd=cross-origin(${f.message.slice(0,30)})`}},vn=[],Po=P=>{if(We())return;let f=P.message??String(P.error??"(no message)");f&&(f.toLowerCase().includes("paypal")||f.toLowerCase().includes("zoid")||f.toLowerCase().includes("postrobot")||f.toLowerCase().includes("storage"))&&(F(`window:error ${f.slice(0,140)}`),vn.push(f))},Cn=P=>{if(We())return;let f=P.reason instanceof Error?P.reason.message:String(P.reason??"(no reason)");f&&(f.toLowerCase().includes("paypal")||f.toLowerCase().includes("zoid")||f.toLowerCase().includes("postrobot")||f.toLowerCase().includes("storage"))&&(F(`window:rejection ${f.slice(0,140)}`),vn.push(f))},no={value:0},Tr=()=>{Bn?.disconnect(),Bn=null,fn?.disconnect(),fn=null;for(let P of gn.splice(0))clearTimeout(P);Pn=!1,hn&&typeof window<"u"&&(window.removeEventListener("error",Po),window.removeEventListener("unhandledrejection",Cn)),hn=!1},T=()=>{if(!(hn||We()||Hr)){if(hn=!0,vn.length=0,no.value=0,typeof window<"u"&&(window.addEventListener("error",Po),window.addEventListener("unhandledrejection",Cn)),typeof PerformanceObserver<"u")try{fn=new PerformanceObserver(P=>{if(!We())for(let f of P.getEntries()){if(!f.name.toLowerCase().includes("paypal"))continue;no.value+=1;let G=Math.round(f.duration);F(`net ${G}ms ${f.name.slice(0,90)}`)}}),fn.observe({type:"resource",buffered:!0})}catch{}Kr?.()}},q=()=>{Ht&&(clearTimeout(Ht),Ht=null)},Z=()=>{Tr(),q()},Se={setEnabled:P=>{P?T():Tr()}};I.current=Se,B.current&&T();let pt=Ue.isPayPalTeardownMessage,mr=P=>{if(We()||pt(P))return;let f=(0,Io.applyFriendlyMessageOverride)(P)??P;(0,Ge.invokeMerchantCallback)(()=>tr.current?.(f))},Ve=(P,f)=>{if(Ot||xn)return;xn=!0,$t=!0,Z(),go();let G=Od({kind:P,generationActive:!0,automaticRetryAllowed:me,automaticRetryUsed:or.current});if(G.action==="retry"){or.current=!0,Fe(!1),Ze(!1),H(!0),jt.current?.("retrying"),mn=setTimeout(()=>{Ot||ut(Ie=>Ie+1)},xd);return}if(Fe(!1),Ze(!1),H(!1),Ce(!0),G.action!=="ignore"){if(jt.current?.("exhausted"),G.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",f);return}if(G.report){let Ie=(0,Re.classifyExternalMethodFailure)({code:Yl(P,f),message:f},{inAppBrowser:ae.inAppBrowser,handoffObserved:!1});Ie.popupBlocked&&te.markBlocked(),ie.error({errorCode:Ie.popupBlocked?Ie.errorCode:G.report.errorCode,stage:G.report.stage,operationOutcome:G.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:Ie.terminalReason})}_t.current||(_t.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Yl(P,f)))}};Ce(!1);let st=async(P,f=Jt.current)=>{if(We())return;let G=f?.sessionId??e;if($e.current){await $e.current(P,{sessionId:G,accountPatch:f?.accountPatch,nonce:f?.nonce});return}let Ie=ie.startTiming();ie.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Le=()=>{ie.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ie.performance({stage:"processing",durationMs:ie.elapsed(Ie),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let dt=(0,Ue.buildPayPalProcessPaymentRequest)({body:P,sessionId:G,nonce:f?.nonce??Mn.current,accountPatch:f?.accountPatch,session:Yt.current,email:ln.current}),fr=await new ui.PaymentAPI(It,{telemetry:!1}).processPayment(dt.userId,dt.params);if(fr.ok){if($t||Ot&&ot.current)return;Le(),ie.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ge.invokeMerchantCallback)(()=>ar.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(We())return;let Lt=await fr.json().catch(()=>null),Kt=(0,Ue.describePayPalProcessFailure)(Lt),Dn=Kt.message;Le(),fr.status===400&&(typeof Lt?.declineCode=="string"||!Array.isArray(Lt?.fields))?ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):fr.status===400||fr.status===422?ie.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):ie.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Ld(fr.status),failureCategory:fr.status>=500?"server_error":void 0}),mr(Dn),(0,Ge.invokeMerchantCallback)(()=>br.current?.(kr("paypal",Dn,{code:Kt.code,declineCode:Kt.declineCode})));return}catch(dt){if(We())return;Le(),ie.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Et=(0,Ue.friendlyPayPalFailureMessage)(dt instanceof Error?dt.message:void 0);mr(Et),(0,Ge.invokeMerchantCallback)(()=>br.current?.(kr("paypal",Et)));return}},Y=()=>new Ue.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Oe=P=>We()?Promise.reject(Y()):Promise.resolve(P),j=async P=>{if(P.ok){ie.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ge.invokeMerchantCallback)(()=>ar.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let f=await P.json().catch(()=>null),G=(0,Ue.describePayPalProcessFailure)(f);ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ge.invokeMerchantCallback)(()=>br.current?.(kr("paypal",G.message,{code:G.code,declineCode:G.declineCode})))},ct=()=>{let P=Jt.current;Zt("approved"),P&&(ir.current.delete(P.surfaceKey),Vr(P.generation)),Jt.current=null},re=async P=>{if(We())throw Y();Wn||to();let f=Jt.current,G=f?.sessionId??e,Ie=f?.nonce??Mn.current;ie.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Le;try{Le=await new ui.PaymentAPI(It,{telemetry:!1}).createSessionIntent(G,Ie??"",(0,Ue.buildPayPalSessionIntentRequest)(zt),{idempotencyKey:Vt})}catch(dt){throw ie.error({...(0,Ue.classifyTelemetryFailure)(dt,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),dt}if(We())throw Y();if((0,Ue.isSettledSessionIntent)(Le))throw await j(Le.response),ct(),new Ue.FloPayError("PayPal checkout already settled.","api_error",{code:Gl});if(Le.provider!=="paypal"||Le.providerObjectType!==he)throw new Error(P);return ie.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Le.providerObjectId},et=(P,f)=>{let G=f?.nonce??Mn.current;if(!G)return;let Ie=f?.sessionId??e,Le=(0,Ue.resolvePayPalDeclineReason)(P);new ui.PaymentAPI(It,{telemetry:!1}).reportSessionIntentDecline(Ie,G,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Le}).catch(()=>{})},ht=Be;F("loadScript:scheduled (deferred 1 tick)");let tt=null,Mt=setTimeout(()=>{if(Ot){F("loadScript:skipped (cancelled before defer ran)");return}F("loadScript:start");let P=en==="live"?"production":en,f={};he==="subscription"?f={intent:"subscription",vault:!0}:he==="order"&&(f={intent:"capture"}),tt=(0,Xl.loadScript)({clientId:d,currency:y,...f,...P?{environment:P}:{},...P==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let G=!1;tt.then(Ie=>{if(G=!0,F(`loadScript:resolved inactive=${We()} ns=${!!Ie} buttons=${!!Ie?.Buttons}`),We())return;if(!Ie?.Buttons){F("FAIL: namespace missing Buttons factory"),Ve("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}ie.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),ie.performance({stage:"provider_ready",durationMs:ie.elapsed(de.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ie.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Le=async($,Pt)=>{if(We()||Xe.current!==ht)return;let xt=$.vaultSetupToken??$.subscriptionID??$.orderID??"",Nt=xt?Qr.current.get(xt):ir.current.get(ht);if(!(!Nt||!Ur(Nt.generation))&&Vr(Nt.generation)){Qr.current.delete(xt),ir.current.delete(Nt.surfaceKey),Zt("approved");try{if(Ze(!0),(0,Ge.invokeMerchantCallback)(()=>tr.current?.(null)),!xt)throw new Ue.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let we=(0,Ue.resolvePayPalApprovalIdentity)({accountPatch:Nt.accountPatch,email:ln.current,billingName:pr.current,session:Yt.current});if((0,Ue.needsPayPalPayerDetails)(we))try{we=(0,Ue.mergePayPalPayerIdentity)(we,await Pt?.order?.get?.())}catch{}if((Dt.current||De)&&!(0,Ue.isValidEmail)(we.email)){let Pe=await Ct("PayPal",we);if(!Pe)return;we=Pe}(0,Ue.isValidEmail)(we.email)&&(Nt.accountPatch=(0,wn.compactBuyerIdentity)({...Nt.accountPatch,...we}),await Dt.current?.(we));let gr=(0,Ue.buildPayPalTokenizedBody)(xt,zt);await st(gr,Nt)}catch(we){mr(we instanceof Error?we.message:"PayPal capture failed.")}finally{We()||Ze(!1)}}},dt=$=>{let Pt=ce?()=>Oe(ce):()=>re($);return async()=>sr(await Pt())},Et=Ie.Buttons({style:{layout:"horizontal",height:pi,tagline:!1},...Bt==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async($,Pt)=>{if(We()){await Pt.reject();return}to();let xt=yn.current,Nt={};if(xt)try{let Pe=await xt("paypal");if(We()){await Pt.reject();return}if(!Pe.proceed){Jt.current=null,ir.current.delete(ht),await Pt.reject();return}Nt={sessionId:Pe.sessionId,accountPatch:Pe.accountPatch,nonce:Pe.nonce}}catch(Pe){F(`onClick:runBeforeButtonClick rejected msg=${(Pe instanceof Error?Pe.message:String(Pe)).slice(0,120)}`),Jt.current=null,ir.current.delete(ht),await Pt.reject();return}(0,Ge.invokeMerchantCallback)(()=>pn.current?.("paypal"));let we=zr(),gr={generation:we,surfaceKey:ht,...Nt};Jt.current=gr,ir.current.set(ht,gr),je.current={...C,attempt:we},await Pt.resolve(),ie.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ie.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),rt.current=ie.startTiming()},createOrder:he==="order"?dt("Failed to create PayPal order."):void 0,createSubscription:he==="subscription"?dt("Failed to create PayPal subscription."):void 0,createVaultSetupToken:he==="setup_token"?async()=>sr(await re("Failed to create PayPal setup token.")):void 0,onApprove:Le,onCancel:()=>{if(We())return;let $=ir.current.get(ht)??Jt.current,Pt=$&&Ur($.generation)?(0,Ue.buildPayPalCancelEvent)($.sessionId??e,zt):null;$&&ir.current.delete($.surfaceKey),Jt.current=null,Zt("cancelled"),ie.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ue.current=!0,Qt({generation:$?.generation,remount:!0,focus:!1}),Pt&&(0,Ge.invokeMerchantCallback)(()=>Tt.current?.(Pt))},onError:$=>{if($ instanceof Ue.FloPayError&&$.code===Gl)return;let Pt=$ instanceof Error?$.message:"PayPal failed to render.";if(We()||Xe.current!==ht){pt(Pt)||$r(eo());return}if(Hr){let xt=ir.current.get(ht)??Jt.current;if(!xt||!Ur(xt.generation)){if(pt(Pt)){!xt&&!Wr()&&Vr();return}$r(xt||Wr()?"stale_attempt":"no_current_attempt");return}if(F(`onError rendered=${Hr} msg=${Pt.slice(0,120)}`),pt(Pt)){Vr(xt.generation);return}let{errorCode:Nt,popupBlocked:we,providerDeclined:gr,terminalReason:Pe}=(0,Re.classifyExternalMethodFailure)($,{inAppBrowser:ae.inAppBrowser,handoffObserved:Q.current===xt.generation});if(we&&te.markBlocked(),Zt(Pe),gr){ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Pe}),et($,xt),(0,Ge.invokeMerchantCallback)(()=>br.current?.(kr("paypal",Pt))),ir.current.delete(xt.surfaceKey),Jt.current=null,Vr(xt.generation);return}ie.error({errorCode:Nt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Pe}),ir.current.delete(xt.surfaceKey),Jt.current=null,Qt({generation:xt.generation,remount:!0,showRetry:!0,focus:!0}),Fr($,{code:"paypal_runtime_failed",popupBlocked:we,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Bt,terminalReason:Pe});return}F(`onError rendered=${Hr} msg=${Pt.slice(0,120)}`),Ve(pt(Pt)?"teardown":"pre_ready_callback",Pt)}}),fr=Et.isEligible();if(F(`isEligible=${fr}`),ie.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!fr){Fe(!1),Ve("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}ho=!0,ro=Et,Kr=()=>{if(!hn||Pn||We()||Hr)return;Pn=!0,F(`container:dims ${Gr(Fn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Bn=new MutationObserver(Pt=>{if(!We()){for(let xt of Pt)if(xt.type==="childList")xt.addedNodes.forEach(Nt=>{if(!(Nt instanceof Element))return;let we=Nt.tagName.toLowerCase(),gr=(Nt.getAttribute("title")??"").slice(0,40),Pe=we==="iframe"?` ${Br(Nt)}`:"";F(`child+ ${we}${gr?` title="${gr}"`:""}${Pe} dims=${Gr(Nt)}`)});else if(xt.type==="attributes"&&xt.target instanceof Element){let Nt=xt.target;if(Nt.tagName.toLowerCase()!=="iframe")continue;let we=xt.attributeName;(we==="src"||we==="srcdoc")&&F(`attr~ iframe ${we}=${we==="srcdoc"?`[${(Nt.getAttribute("srcdoc")??"").length}ch]`:Qe(Nt.getAttribute("src"))} dims=${Gr(Nt)}`)}}}),Bn.observe(Fn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let $=Pt=>{if(We()||Hr)return;let xt=Fn.querySelectorAll("iframe"),Nt=typeof document<"u"&&"hasStorageAccess"in document;F(`watchdog:${Pt} container=${Gr(Fn)} children=${Fn.childElementCount} iframes=${xt.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Nt} paypalNetRequests=${no.value}`),xt.forEach((we,gr)=>{let Pe=(we.getAttribute("title")??"").slice(0,40);F(` iframe[${gr}] ${Gr(we)}${Pe?` title="${Pe}"`:""} ${Br(we)}`);let oo=Rr(we);oo&&F(` ${oo}`)}),vn.length===0&&F(" (no PayPal/zoid window errors captured)")};gn.push(setTimeout(()=>$("3s"),3e3)),gn.push(setTimeout(()=>$("8s"),8e3)),gn.push(setTimeout(()=>$("15s"),15e3))},Kr(),F("render:start");let Kt=ie.startTiming();Ht=setTimeout(()=>{We()||Hr||(F("watchdog:11s retryable render timeout"),Ve("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Fd);let Dn=Et.render(Fn);(async()=>{try{if(await Dn,F(`render:resolved inactive=${We()}`),Z(),We()){go();return}Hr=!0,Fe(!0),H(!1),jt.current?.("ready"),ie.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),ie.performance({stage:"checkout_render",durationMs:ie.elapsed(Kt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch($){let Pt=$ instanceof Error?$.message:"PayPal failed to render.";F(`render:rejected msg=${Pt.slice(0,120)}`),Z(),Ve(pt(Pt)?"teardown":"render_rejected",Pt)}})()}).catch(Ie=>{let Le=Ie instanceof Error?Ie.message:"PayPal operation failed.";F(`provider:failed msg=${Le.slice(0,120)}`);let dt="script_rejected";G&&pt(Le)?dt="teardown":G&&ho&&(dt="render_rejected"),Ve(dt,Le)})},0);return()=>{Ot=!0,clearTimeout(Mt),mn&&clearTimeout(mn),Z(),I.current===Se&&(I.current=null),go(),rt.current=null,je.current=null}},[me,It,d,y,p,he,Bt,Ae,e,ce,Be,N,Ct,De,F,Zt]);let yr=L?(0,Rn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:qt?"#fef2f2":"#f3f4f6",border:`1px solid ${qt?"#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=${pe} failed=${qt})`,xe.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return
|
|
3
|
+
${xe.join(`
|
|
4
|
+
`)}`]}):null;return qt&&!u?L?(0,Rn.jsx)("div",{children:yr}):null:(0,Rn.jsxs)("div",{children:[yr,J&&(0,Rn.jsx)(ea,{identity:J.identity,methodLabel:J.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Rt,onCancel:()=>Rt(null)}),(0,Rn.jsxs)("div",{"aria-hidden":ge||J?!0:void 0,style:ge||J?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:pi},children:[!pe&&!ge&&(0,Rn.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,Rn.jsx)("div",{ref:le,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:pi,display:"flex",opacity:pe?1:0},"aria-busy":oe||O},Be)]},Be),nt&&(0,Rn.jsx)("button",{ref:ve,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:jr,style:Bd,children:"Try PayPal again"})]})}function Ra(e){return(0,Rn.jsx)(Jl,{...e})}function Zl(e){return(0,Rn.jsx)(Jl,{...e})}var ka=require("react/jsx-runtime");function na({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,ka.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,ka.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,ka.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 ft=require("@flopay/shared");var Cr=require("react/jsx-runtime");var Nd={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=Nd}){let y={fontSize:13,color:p.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,Cr.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,Cr.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,Cr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Cr.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,Cr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:p.spinnerTrackColor,strokeWidth:"3"}),(0,Cr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:p.spinnerAccentColor})]}),e==="success"&&(0,Cr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Cr.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,Cr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Cr.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,Cr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Cr.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,Cr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Cr.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,Cr.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,Cr.jsx)("p",{style:y,children:d}),e==="error"&&t&&(0,Cr.jsx)("p",{style:y,children:t}),(0,Cr.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 Vl=require("@flopay/shared"),Ur=require("react");var Wl=require("react/jsx-runtime");function Ra({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,c]=(0,Ur.useState)(e instanceof Promise?null:e),[p,y]=(0,Ur.useState)(t instanceof Promise||!t?null:t),g=(0,Ur.useRef)(null),E=(0,Ur.useRef)(null),R=Yo(n);(0,Ur.useEffect)(()=>{R({class:"lifecycle",name:"checkout.mount"})},[R]),(0,Ur.useEffect)(()=>{s&&R({class:"lifecycle",name:"sdk.initialize.ready"})},[R,s]),(0,Ur.useEffect)(()=>{if(s)return Rr(s)?.subscribe?.(R)},[R,s]),(0,Ur.useEffect)(()=>{if(!(!p||p===s))return Rr(p)?.subscribe?.(R)},[R,s,p]),(0,Ur.useEffect)(()=>{if(!s)return;let T=Rr(s);return g.current=T?.beginCheckout()??T?.now()??0,T?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{T?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Ur.useEffect)(()=>{let T=!1;return e instanceof Promise?e.then(Y=>{T||c(Y)},()=>{T||R({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):c(e),()=>{T=!0}},[R,e]),(0,Ur.useEffect)(()=>{let T=!1;if(!t){y(null);return}return t instanceof Promise?t.then(Y=>{T||y(Y)},()=>{T||R({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{T=!0}},[R,t]),(0,Ur.useEffect)(()=>{if(!s||E.current===s)return;E.current=s;let T=Rr(s);T?.log({name:"checkout.rendered",stage:"checkout_render"}),R({class:"lifecycle",name:"checkout.rendered"}),T?.performance({stage:"checkout_render",durationMs:T.elapsed(g.current??0),durationMode:"machine"})},[R,s]);let _=(0,Vl.resolveBillingApiUrl)(r?.billingApiUrl),H=(0,Ur.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:_,emitInstrument:R}),[s,p,_,R]);return(0,Wl.jsx)(vn.Provider,{value:H,children:a})}var Nn=require("@flopay/shared");async function di(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 $r=require("@flopay/js"),lt=require("@flopay/shared");var Ea="card";async function Rd(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:c}=await e.retrieveSetupIntent(t);return{error:c,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 kd(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:p}=await e.confirmCardSetup(t,r);return{error:p,intent:c??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 Jo(e){return new lt.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ed(){return new lt.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function ss(e,t){return Object.assign(e,{checkoutMethod:t})}function so(e,t){let r=e instanceof lt.FloPayError?e:new lt.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 ka(e,t){try{return await e()}catch(r){throw so(r,t)}}function Hl(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Kl(e){return(0,$r.runSavedCardChallenge)(e)}function Ia(e,t,r,n=!0){let a={release:()=>{}};if(!n)return a;try{let s=new $r.PaymentAPI(e),c=(0,$r.beginSavedCardChallengeTelemetry)(s,t,r);return c?{telemetry:c,release:()=>{setTimeout(()=>{try{s.destroy()}catch{}},0)}}:a}catch{return a}}async function Zo(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,c=new $r.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,y;try{y=await(0,$r.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:E=>Xn({type:E.declineReason??"authorization_declined",gatewayErrorCode:E.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},c)}catch(E){if(a.aborted||E instanceof Error&&E.name==="AbortError")throw E instanceof lt.FloPayError&&E.code==="three_ds_aborted"?E:Jo(E);if(!(E instanceof lt.FloPayError)||E.code!=="three_ds_timeout"&&E.code!=="checkout_processing_timeout")throw E;try{y=await c.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(_){if(a.aborted)throw Jo(_);if(!(_ instanceof lt.FloPayError)||_.code!=="checkout_processing_timeout")throw _}let R=y&&go(y,t.session);if(!oo(R)&&R?.status!=="expired"){if(t.telemetry){let _=new $r.PaymentAPI(r);try{_.reportThreeDsAbandoned(n)}finally{_.destroy()}}throw Ed()}}let g=y&&go(y,t.session);if(!oo(g))throw Wo(g);return{...no(g,n),checkoutMethod:"card"}}function Xn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,s=(0,So.applyFriendlyMessageOverride)(a)??a,c=ss(new lt.FloPayError(s,"api_error",{code:e?.code??(0,lt.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,lt.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(c.orderId=e.orderId),c}function is(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ui(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Gl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||ui(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||ui(p)))return p;let c=a.gateways;if(c&&typeof c=="object"){let p=c.stripe;if(p&&typeof p=="object"){let y=p,g=[y.stripeClientSecret,y.clientSecret];for(let E of g)if(typeof E=="string"&&E.length>0&&(!t?.requirePaymentIntentClientSecret||ui(E)))return E}}}}async function Id({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Gl(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 $r.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(ui(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function Qo({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:c}){let p=e.replace(/\/+$/,""),y=t??r.id,g=n??r.clientSecret,E=r.customer?.id??r.accountData?.userId??"",R=r.customer?.email??r.accountData?.email??"",_=r.customer?.firstName??r.accountData?.firstName??"",H=r.customer?.lastName??r.accountData?.lastName??"",T=r.customer?.country??r.accountData?.country??void 0,Y=r.customer?.zip??r.accountData?.zip??void 0,f=await new $r.PaymentAPI(p,c===!1?{telemetry:!1}:void 0).processPayment(E,{sessionId:y,nonce:g,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:E,email:R,firstName:_,lastName:H,country:T,zip:Y},returnUrl:s??is(r)});if(f.ok){let S=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,lt.isAuthorizationOnlySession)(r)||S?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof S?.paymentId=="string"?S.paymentId:r.paymentId,sessionId:typeof S?.sessionId=="string"?S.sessionId:y,authorizationExpiresAt:typeof S?.authorizationExpiresAt=="string"?S.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:Pa(a),checkoutMethod:$l(a,r)}};let Me=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Me?{paymentIntentId:Me}:{},paymentMethodId:Pa(a),checkoutMethod:$l(a,r)}}}let h;try{h=await f.json()}catch(S){throw new lt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:S})}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 S=Gl(h);if(!S)throw new lt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:h.type,threeDSecureToken:S,paymentMethodId:h.paymentMethodId}}if(h?.gatewayErrorCode==="authentication_required"){let S=await Id({billingApiUrl:p,sessionId:y,nonce:g,responseJson:h});if(S)return S;throw ss(new lt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ge=new lt.FloPayError(h?.message??"Payment failed. Please try again.","api_error",{code:h?.code??h?.gatewayErrorCode,declineCode:h?.declineCode??h?.gatewayDeclineReason,statusCode:f.status});throw Object.assign(ge,{telemetryOutcome:(0,lt.classifyPaymentRejection)(f.status,h)})}async function pi(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:c,returnUrl:p,telemetry:y,signal:g}){let E=t?.getRawProvider();if(!E)throw so(new lt.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw ss(new lt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let R=(0,lt.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,H=e.paymentMethodId,T=await ka(()=>Rd(E,e.threeDSecureToken,R),"card");if(T){if(T.error)throw so(new lt.FloPayError(T.error.message??`Failed to retrieve 3DS ${R?"setup":"payment"} status.`,"api_error",{code:T.error.code}),"card");let B=T.intent;!H&&B?.payment_method&&(typeof B.payment_method=="string"?H=B.payment_method:"id"in B.payment_method&&(H=B.payment_method.id??void 0))}let Y=H?await ka(()=>kd(E,e.threeDSecureToken,{payment_method:H,return_url:p??is(c)??window.location.href},R),"card"):null;if(Y){if(Y.error)throw so(new lt.FloPayError(Y.error.message??"3DS authentication failed.","api_error",{code:Y.error.code}),"card");_=Y.intent}else{let B=await ka(()=>E.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(B.error)throw so(new lt.FloPayError(B.error.message??"3DS authentication failed.","api_error",{code:B.error.code}),"card");_=(R?B.setupIntent:B.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let B=await Qo({billingApiUrl:a,sessionId:s,session:c,telemetry:y,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:p});return B.type==="success"?{...B.result,paymentIntentId:B.result.paymentIntentId??_.id,paymentMethodId:B.result.paymentMethodId??H}:B.type==="next_action_required"?Zo(B,{billingApiUrl:a,sessionId:s??c.id,session:c,signal:g}):pi(B,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:c,returnUrl:p,telemetry:y,signal:g})}throw so(new lt.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let R=(r??t)?.getRawProvider();if(!R)throw so(new lt.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:H}=await ka(()=>R.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(H)throw so(new lt.FloPayError(H.message??"PayPal authorization failed.","api_error",{code:H.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await ka(()=>R.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??is(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(_)throw so(new lt.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new lt.FloPayError("Unsupported payment redirect state.","api_error")}function _a(e){if(e instanceof lt.FloPayError){let n=(0,So.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new lt.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,So.applyFriendlyMessageOverride)(t)??t;return new lt.FloPayError(r,"api_error")}function ls(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,lt.isMountableVaultBlock)(e.data.session?.vault)||(0,Dn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new lt.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 $l(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,Dn.canRecoverHostedCardForm)(t)?"card":void 0}async function cs({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,[c,p]=await Promise.all([(0,$r.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,$r.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(g=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",g),null)):Promise.resolve(null)]);if(!c)throw new lt.FloPayError("The payment provider did not initialize.","authentication_error");let y=null;return s?y=p:t&&(y=c),{flopay:c,paypalFlopay:y}}var zn=require("@flopay/js"),l=require("@flopay/shared"),dr=require("@stripe/react-stripe-js"),o=Qi(require("react"),1);function ko(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function mi(e,t){if(e)return{error:r=>e.error(ko(t,r)),log:r=>e.log(ko(t,r)),performance:r=>e.performance(ko(t,r)),terminal:r=>e.terminal(ko(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("@flopay/shared"),Xl=require("react");var Yl={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 Mr=require("react/jsx-runtime"),_d=`
|
|
9
|
+
`})]})})}var Ql=require("@flopay/shared"),Dr=require("react");var ec=require("react/jsx-runtime");function Ea({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,d]=(0,Dr.useState)(e instanceof Promise?null:e),[p,y]=(0,Dr.useState)(t instanceof Promise||!t?null:t),b=(0,Dr.useRef)(null),v=(0,Dr.useRef)(null),S=ra(n);(0,Dr.useEffect)(()=>{S({class:"lifecycle",name:"checkout.mount"})},[S]),(0,Dr.useEffect)(()=>{s&&S({class:"lifecycle",name:"sdk.initialize.ready"})},[S,s]),(0,Dr.useEffect)(()=>{if(s)return Er(s)?.subscribe?.(S)},[S,s]),(0,Dr.useEffect)(()=>{if(!(!p||p===s))return Er(p)?.subscribe?.(S)},[S,s,p]),(0,Dr.useEffect)(()=>{if(!s)return;let x=Er(s);return b.current=x?.beginCheckout()??x?.now()??0,x?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{x?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Dr.useEffect)(()=>{let x=!1;return e instanceof Promise?e.then(D=>{x||d(D)},()=>{x||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{x=!0}},[S,e]),(0,Dr.useEffect)(()=>{let x=!1;if(!t){y(null);return}return t instanceof Promise?t.then(D=>{x||y(D)},()=>{x||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{x=!0}},[S,t]),(0,Dr.useEffect)(()=>{if(!s||v.current===s)return;v.current=s;let x=Er(s);x?.log({name:"checkout.rendered",stage:"checkout_render"}),S({class:"lifecycle",name:"checkout.rendered"}),x?.performance({stage:"checkout_render",durationMs:x.elapsed(b.current??0),durationMode:"machine"})},[S,s]);let E=(0,Ql.resolveBillingApiUrl)(r?.billingApiUrl),V=(0,Dr.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:E,emitInstrument:S}),[s,p,E,S]);return(0,ec.jsx)(Sn.Provider,{value:V,children:a})}var qn=require("@flopay/shared");async function yi(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 Yr=require("@flopay/js"),lt=require("@flopay/shared");var Ia="card";async function Ud(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 zd(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 oa(e){return new lt.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function qd(){return new lt.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function ys(e,t){return Object.assign(e,{checkoutMethod:t})}function uo(e,t){let r=e instanceof lt.FloPayError?e:new lt.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 _a(e,t){try{return await e()}catch(r){throw uo(r,t)}}function rc(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function nc(e){return(0,Yr.runSavedCardChallenge)(e)}function Ta(e,t,r,n=!0){let a={release:()=>{}};if(!n)return a;try{let s=new Yr.PaymentAPI(e),d=(0,Yr.beginSavedCardChallengeTelemetry)(s,t,r);return d?{telemetry:d,release:()=>{setTimeout(()=>{try{s.destroy()}catch{}},0)}}:a}catch{return a}}async function aa(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,d=new Yr.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,y;try{y=await(0,Yr.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:v=>Xn({type:v.declineReason??"authorization_declined",gatewayErrorCode:v.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},d)}catch(v){if(a.aborted||v instanceof Error&&v.name==="AbortError")throw v instanceof lt.FloPayError&&v.code==="three_ds_aborted"?v:oa(v);if(!(v instanceof lt.FloPayError)||v.code!=="three_ds_timeout"&&v.code!=="checkout_processing_timeout")throw v;try{y=await d.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(E){if(a.aborted)throw oa(E);if(!(E instanceof lt.FloPayError)||E.code!=="checkout_processing_timeout")throw E}let S=y&&bo(y,t.session);if(!so(S)&&S?.status!=="expired"){if(t.telemetry){let E=new Yr.PaymentAPI(r);try{E.reportThreeDsAbandoned(n)}finally{E.destroy()}}throw qd()}}let b=y&&bo(y,t.session);if(!so(b))throw Jo(b);return{...io(b,n),checkoutMethod:"card"}}function Xn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,s=(0,Io.applyFriendlyMessageOverride)(a)??a,d=ys(new lt.FloPayError(s,"api_error",{code:e?.code??(0,lt.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,lt.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(d.orderId=e.orderId),d}function ps(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function mi(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function oc(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||mi(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||mi(p)))return p;let d=a.gateways;if(d&&typeof d=="object"){let p=d.stripe;if(p&&typeof p=="object"){let y=p,b=[y.stripeClientSecret,y.clientSecret];for(let v of b)if(typeof v=="string"&&v.length>0&&(!t?.requirePaymentIntentClientSecret||mi(v)))return v}}}}async function jd({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=oc(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 Yr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(mi(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function ia({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:d}){let p=e.replace(/\/+$/,""),y=t??r.id,b=n??r.clientSecret,v=r.customer?.id??r.accountData?.userId??"",S=r.customer?.email??r.accountData?.email??"",E=r.customer?.firstName??r.accountData?.firstName??"",V=r.customer?.lastName??r.accountData?.lastName??"",x=r.customer?.country??r.accountData?.country??void 0,D=r.customer?.zip??r.accountData?.zip??void 0,g=await new Yr.PaymentAPI(p,d===!1?{telemetry:!1}:void 0).processPayment(v,{sessionId:y,nonce:b,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:v,email:S,firstName:E,lastName:V,country:x,zip:D},returnUrl:s??ps(r)});if(g.ok){let m=typeof g.json=="function"?await g.json().catch(()=>null):null;if((0,lt.isAuthorizationOnlySession)(r)||m?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof m?.paymentId=="string"?m.paymentId:r.paymentId,sessionId:typeof m?.sessionId=="string"?m.sessionId:y,authorizationExpiresAt:typeof m?.authorizationExpiresAt=="string"?m.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:Ca(a),checkoutMethod:tc(a,r)}};let me=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...me?{paymentIntentId:me}:{},paymentMethodId:Ca(a),checkoutMethod:tc(a,r)}}}let O;try{O=await g.json()}catch(m){throw new lt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:g.status,cause:m})}if(O?.type==="3ds_required"&&typeof O.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:O.nextActionRedirectUrl};if(O?.type==="paypal_redirect_required"||O?.type==="3ds_required"){let m=oc(O);if(!m)throw new lt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:g.status});return{type:O.type,threeDSecureToken:m,paymentMethodId:O.paymentMethodId}}if(O?.gatewayErrorCode==="authentication_required"){let m=await jd({billingApiUrl:p,sessionId:y,nonce:b,responseJson:O});if(m)return m;throw ys(new lt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ke=new lt.FloPayError(O?.message??"Payment failed. Please try again.","api_error",{code:O?.code??O?.gatewayErrorCode,declineCode:O?.declineCode??O?.gatewayDeclineReason,statusCode:g.status});throw Object.assign(ke,{telemetryOutcome:(0,lt.classifyPaymentRejection)(g.status,O)})}async function fi(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:y,signal:b}){let v=t?.getRawProvider();if(!v)throw uo(new lt.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw ys(new lt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let S=(0,lt.isSetupIntentClientSecret)(e.threeDSecureToken),E=null,V=e.paymentMethodId,x=await _a(()=>Ud(v,e.threeDSecureToken,S),"card");if(x){if(x.error)throw uo(new lt.FloPayError(x.error.message??`Failed to retrieve 3DS ${S?"setup":"payment"} status.`,"api_error",{code:x.error.code}),"card");let A=x.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 D=V?await _a(()=>zd(v,e.threeDSecureToken,{payment_method:V,return_url:p??ps(d)??window.location.href},S),"card"):null;if(D){if(D.error)throw uo(new lt.FloPayError(D.error.message??"3DS authentication failed.","api_error",{code:D.error.code}),"card");E=D.intent}else{let A=await _a(()=>v.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(A.error)throw uo(new lt.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");E=(S?A.setupIntent:A.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let A=await ia({billingApiUrl:a,sessionId:s,session:d,telemetry:y,tokenizedData:{id:E.id,type:"card",threeDSecureActionResultTokenId:E.id},returnUrl:p});return A.type==="success"?{...A.result,paymentIntentId:A.result.paymentIntentId??E.id,paymentMethodId:A.result.paymentMethodId??V}:A.type==="next_action_required"?aa(A,{billingApiUrl:a,sessionId:s??d.id,session:d,signal:b}):fi(A,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:y,signal:b})}throw uo(new lt.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let S=(r??t)?.getRawProvider();if(!S)throw uo(new lt.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:V}=await _a(()=>S.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(V)throw uo(new lt.FloPayError(V.message??"PayPal authorization failed.","api_error",{code:V.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:E}=await _a(()=>S.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??ps(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(E)throw uo(new lt.FloPayError(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new lt.FloPayError("Unsupported payment redirect state.","api_error")}function Ma(e){if(e instanceof lt.FloPayError){let n=(0,Io.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new lt.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,Io.applyFriendlyMessageOverride)(t)??t;return new lt.FloPayError(r,"api_error")}function ms(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,lt.isMountableVaultBlock)(e.data.session?.vault)||(0,Nn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new lt.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,Nn.canRecoverHostedCardForm)(t)?"card":void 0}async function fs({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,Yr.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,Yr.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(b=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",b),null)):Promise.resolve(null)]);if(!d)throw new lt.FloPayError("The payment provider did not initialize.","authentication_error");let y=null;return s?y=p:t&&(y=d),{flopay:d,paypalFlopay:y}}var Vn=require("@flopay/js"),c=require("@flopay/shared"),cr=require("@stripe/react-stripe-js"),o=as(require("react"),1);function Ao(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function gi(e,t){if(e)return{error:r=>e.error(Ao(t,r)),log:r=>e.log(Ao(t,r)),performance:r=>e.performance(Ao(t,r)),terminal:r=>e.terminal(Ao(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 po=require("@flopay/shared"),ic=require("react");var ac={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 Ar=require("react/jsx-runtime"),Vd=`
|
|
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 @@ ${ce.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
|
-
`,ea=44;function ta(){return(0,Mr.jsx)("style",{children:_d})}function Ta(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function Ma({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Mr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Mr.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,Mr.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 ds(e){return e!=="unavailable"&&e!=="load_error"}function yi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:c,backgroundColor:p,borderColor:y,textColor:g,borderRadius:E,fontFamily:R}){let _=(0,lo.resolveStripeMethodBrandVariant)(e,t),H=Yl[e],[T,Y]=(0,Xl.useState)(!1),B=!!H&&!T,f=_?.backgroundColor??p??"#ffffff",h=_?.borderColor??y??"#d1d5db",ge=_?.textColor??g??"#262833";return(0,Mr.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&c()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ea,padding:"0 1rem",backgroundColor:f,color:ge,border:`1px solid ${h}`,borderRadius:E??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,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,Mr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,lo.getStripeMethodDisplayName)(e)}\u2026`}):(0,Mr.jsxs)(Mr.Fragment,{children:[(0,Mr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,lo.hasVendoredStripeMethodLogo)(e)?8:0},children:[B?(0,Mr.jsx)("img",{src:H,alt:"","aria-hidden":"true",onError:()=>Y(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!B&&_?.logoSvg?(0,Mr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:_.logoSvg}}):null,(0,Mr.jsx)("span",{children:(0,lo.getStripeMethodDisplayName)(e)})]}),s&&(0,Mr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:ge,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,Mr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function fi(e){let t=new Set(e.map(lo.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var gi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},hi={type:"accordion",defaultCollapsed:!1,radios:"never"};function Pi({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:c,children:p}){return(0,Mr.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",...c??{}},children:p})}var un=require("react");var xa=require("@flopay/shared"),Td=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 Md(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Td.has(t.charAt(0).toLowerCase()+t.slice(1))}function xd(e,t){return typeof t=="number"&&t!==0&&!Md(e)?`${t}px`:String(t).trim()}function Jl(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]=xd(r,n)}}}var Eo=require("react/jsx-runtime"),us=new WeakSet;function ho({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:c,containerStyle:p,onReady:y,onError:g,onValidation:E}){let R=(0,un.useRef)(null),_=(0,un.useRef)(y),H=(0,un.useRef)(g),T=(0,un.useRef)(E);_.current=y,H.current=g,T.current=E;let Y=(0,un.useRef)(s);Y.current=s;let B=(0,un.useRef)(null),f=c??void 0,h=(0,un.useRef)(f);h.current=f;let ge=(0,un.useRef)(void 0);return(0,un.useEffect)(()=>{let S=R.current;if(!S)return;let Me=!0,A=!1,ie=()=>{!Me||A||(A=!0,_.current?.())},he=e.on("ready",()=>{ie()}),fe=e.on("error",F=>{H.current?.(F.message??"There was a problem loading the secure card form.")}),Re=e.on("validation",F=>{T.current?.(F.message??null)}),ct=h.current??(us.has(e)?null:void 0),Ke={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...Y.current?{theme:Y.current}:{},...ct===void 0?{}:{submitLabel:ct}};return B.current=Y.current??null,ge.current=h.current,h.current!==void 0&&us.add(e),e.mount(S,Ke).then(()=>{ie()}).catch(F=>{Me&&H.current?.(F instanceof Error?F.message:"Failed to load the secure card form.")}),()=>{Me=!1,he(),fe(),Re(),e.unmount()}},[e,t,r,n,a]),wo(()=>{let S=R.current;S&&Jl(S,p)},[p]),(0,un.useEffect)(()=>{s!==void 0&&(s===null&&B.current===null||(B.current=s,e.applyTheme?.(s)))},[e,s]),(0,un.useEffect)(()=>{f!==ge.current&&(ge.current=f,f!==void 0&&us.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,Eo.jsx)("div",{ref:R,"data-testid":"flopay-vault-card-fields"})}function vi({label:e}){return(0,Eo.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,Eo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,Eo.jsx)("span",{children:e}),(0,Eo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var Ss=require("@flopay/shared"),d=require("react/jsx-runtime"),Jn="flopay_stripe_resume",Zl="flopay_wallet_resume",lc="fw1",Ad="fw2",cc=300*1e3,Fd=900,Bd="express_checkout_click_timeout",Dd=25e3,Od=25e3,Ld=1e4,Un={provider:"paypal",paymentMethodCategory:"paypal"},Nd="x-flopay-process-result-source",Ud="status";async function zd(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 Ci={},Fa=class{constructor(t){this.reason=t}};function qd(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function ur(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 vs(e){return`${Ad}:${e}`}function bi(e){return ur(vs(e))}function Si(e,t){if(typeof window>"u")return null;let r=vs(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>cc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(bi(e),null):a}catch{return bi(e),null}}function jd(e){return ur(vs(e.sessionId),e)}function Ql(e,t,r){let n=Si(e,t);return!n||n.clientSecret!==r?!1:bi(e)}function ps(e,t,r){if(typeof window>"u")return;Si(e,t)?.clientSecret===r&&bi(e)}function Vd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ms(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":ha(e.status),a=Vd(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function ec(e,t,r){let n=null;try{return await Promise.race([Al(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Ld),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Wd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function dc(e){return e instanceof l.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function wi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new zn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw dc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var ys=l.STRIPE_PAYPAL_RESUME_KEY,Aa=new Map,$d=250,tc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Hd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Cs(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 Ri({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new zn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Kd(e){return e instanceof l.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function uc({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,$o.splitFullName)(r),c=s.firstName?s:(0,$o.splitFullName)(n?.name);return(0,Cn.compactBuyerIdentity)({email:(0,l.isValidEmail)(a)?a:n?.email?.trim(),firstName:c.firstName,lastName:c.lastName})}async function Gd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let c=uc({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,l.isValidEmail)(c.email)?c:s(a,c)}var Ba=180,rc=`flopay-card-enter ${Ba}ms cubic-bezier(0, 0, 0.2, 1) both`,nc=`flopay-card-exit ${Ba}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Yd=`flopay-buttons-enter ${Ba}ms cubic-bezier(0, 0, 0.2, 1) both`,Xd=`flopay-buttons-exit ${Ba}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Jd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function bs(e){return(0,l.derivePrimaryTileStyle)(e)}var Zd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Qd(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:ea,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 oc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function hs(e){return e==="paypal"?"PayPal":(0,l.getStripeMethodDisplayName)(e)}function eu(e){let t=(0,l.getPostalCodeExample)(e);return`Enter a valid ${(0,l.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function tu(e,t,r){let n=(0,l.isPostalCodeSupported)(e),a=t.trim(),s=r&&n,c=s&&!a,p=s&&!!a&&!(0,l.isValidPostalCode)(e,a);return{visible:r,supported:n,required:s,empty:c,malformed:p}}function ru(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,l.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function nu(e){return typeof e=="number"?`${e}px`:e}function ki(e){return(0,d.jsx)(iu,{...e})}function ac({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:c=!1,onButtonClick:p,onDecline:y,onTechnicalFailure:g,runBeforeButtonClick:E,billingName:R,onBuyerIdentityReady:_,onLoadStateChange:H,placeholderBorderRadius:T,popupCapabilityOwner:Y,externalTelemetryContext:B,presentationMode:f}){let h=io(),{emitInstrument:ge}=(0,o.useContext)(vn),S=(0,dr.useStripe)(),Me=(0,dr.useElements)(),A=(0,o.useMemo)(()=>mi(Rr(h),B),[B,h]),[ie,he]=(0,o.useState)("loading");(0,o.useEffect)(()=>{H?.(ie)},[ie,H]);let[fe,Re]=(0,o.useState)(!1),ct=(0,o.useRef)(!1),Ke=!(0,l.isValidEmail)(r?.trim())||!R?.trim(),{request:F,collect:St,finish:et}=Ho(),Ue=(0,o.useRef)(!1),ye=(0,o.useRef)(null),J=(0,o.useRef)(null),[W,Fe]=(0,o.useState)(0),[dt,We]=(0,o.useState)(!1),Z=(0,o.useRef)(!1),L=(0,o.useRef)(new Map),{startAttempt:le,finishAttempt:j,invalidateAttempt:Se,isAttemptInvalidated:xe,isAttemptCurrent:Pe,generationRef:Be}=ba((ue,pe,X)=>{g?.(ue,pe,{...X,popupBlocked:X?.popupBlocked??(0,we.isPopupBlockedError)(pe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),We(!0),Fe(Pt=>Pt+1)},{onHandoffObserved:()=>{Y.markAvailable(),A?.log({name:"provider.popup.opened",stage:"overlay_open",...Un,attempt:Be.current})}});(0,o.useEffect)(()=>{dt&&J.current?.focus()},[dt,W]);let M=(0,o.useCallback)(()=>{Fe(ue=>ue+1)},[]),nt=(0,o.useCallback)((ue,pe,X)=>{Se(X),g?.("paypal",ue,{code:pe,popupBlocked:(0,we.isPopupBlockedError)(ue),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),We(!0),M()},[Se,g,f,M]),je=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ye.current?.querySelector("iframe")??ye.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Z.current&&(Z.current=!1,je())},[je,W]);let ut=(0,o.useCallback)(()=>{We(!1),s?.(null),je()},[je,s]);(0,o.useEffect)(()=>{if(!S||Ue.current)return;let[ue,pe,X]=(0,l.readStripeRedirectParams)();if(!ue||!pe)return;let Pt=(0,l.readMatchingStripePayPalContinuation)(pe);if(!Pt)return;Ue.current=!0;let pt=!0,V=Aa.get(pe);V||(V=X==="failed"?Promise.resolve(null):Promise.resolve().then(()=>S.retrievePaymentIntent(pe)),Aa.set(pe,V));let rt={accountPatch:Pt.accountPatch,sessionId:Pt.sessionId,nonce:Pt.nonce},wt=()=>{A?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Un,requestCategory:"provider_sdk"})};return A?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Un}),(async()=>{try{Re(!0);let v=await V;if(!pt)return;if(v?.error){Aa.delete(pe),wt(),s?.(v.error.message??"Failed to retrieve PayPal payment status.");return}if((0,l.clearStripePayPalReturn)(),Aa.delete(pe),X==="failed"){let ne="PayPal payment was declined. Please try again.";A?.terminal({outcome:"payment_declined",...Un,terminalReason:"provider_declined"}),s?.(ne),y?.(wr("paypal",ne));return}let U=v?.paymentIntent;if(U&&U.id!==ue){wt(),s?.("Failed to match the returned PayPal payment.");return}if(U&&(U.status==="requires_capture"||U.status==="succeeded")){let ne=typeof U.payment_method=="string"?U.payment_method:U.payment_method?.id;a({id:ne??U.id,type:"card",threeDSecureActionResultTokenId:U.id,isPaypal:!0},{...rt,presentationMode:"redirect"})}else{let ne="PayPal payment was not completed. Please try again.";A?.terminal({outcome:U?.status==="canceled"?"payment_cancelled":"payment_declined",...Un,terminalReason:U?.status==="canceled"?"cancelled":"provider_declined"}),s?.(ne),y?.(wr("paypal",ne))}}catch(v){if(!pt)return;Aa.delete(pe),wt(),s?.(v instanceof Error?v.message:"Failed to complete PayPal payment.")}finally{pt&&Re(!1)}})(),()=>{pt=!1,Ue.current=!1}},[S,a,s,y,A]);let Ge=(0,o.useCallback)(async(ue=!1)=>{let pe=E?await E("paypal"):{proceed:!0};if(!pe.proceed)return L.current.delete(W),!1;let X=le("paypal");return L.current.set(W,{generation:X,accountPatch:pe.accountPatch,sessionId:pe.sessionId,nonce:pe.nonce}),We(!1),A?.log({name:`provider.${ue?"redirect.started":"handoff.requested"}`,stage:ue?"redirect":"overlay_open",...Un,attempt:X}),p?.("paypal"),!0},[p,A,E,le,W]),$e=(0,o.useCallback)(async ue=>{if(c||fe||!await Ge()){ue.reject();return}ue.resolve()},[c,Ge,fe]),Rt=(0,o.useCallback)(async ue=>{if(!S||!Me)return;let pe=L.current.get(W);if(pe&&!Pe(pe.generation)){L.current.delete(W);return}if(!pe&&xe()||pe&&!j(pe.generation))return;pe||j();let X=pe??null;if(L.current.delete(W),!X&&E){let ke=await E("paypal");if(!ke.proceed){ue.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}X={accountPatch:ke.accountPatch,sessionId:ke.sessionId,nonce:ke.nonce}}let Pt=X?.sessionId??e,pt=X?.nonce??t,V=await Gd({event:ue,prepared:X,email:r,billingName:R,methodLabel:"PayPal",collect:St});if(!V){ue.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let rt=V.email,wt={...X?.accountPatch,...(0,Cn.compactBuyerIdentity)(V,!0)};try{if(Re(!0),s?.(null),!Pt||!(0,l.isValidEmail)(rt))throw new Error("Missing sessionId or email for PayPal payment");await _?.(V);let ke=S.createPaymentMethod,{error:v,paymentMethod:U}=await ke({type:"paypal"});if(v){nt(v,"stripe_paypal_create_payment_method_failed",pe?.generation),ue.paymentFailed({reason:"fail"});return}let ne=await wi(n,ge,Pt,pt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:U?.id??null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(ne)){ue.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:wt,paymentMethodCategory:"paypal",presentationMode:f,sessionId:Pt,nonce:pt,settledProcessResponse:ne.response});return}if(ne.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ae=ne.clientSecret,Dt={return_url:(0,l.stripeRedirectReturnUrl)()};if(U?.id&&(Dt.payment_method=U.id),!ur(ys,{clientSecret:Ae,sessionId:Pt,nonce:pt,accountPatch:wt})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:De,paymentIntent:Oe}=await S.confirmPayment({clientSecret:Ae,confirmParams:Dt,redirect:"if_required"});if(De){if(ur(ys),(0,we.isProviderDecline)(De)){let u=De.message??"Your payment was declined.";A?.terminal({outcome:"payment_declined",...Un,terminalReason:"provider_declined"}),s?.(u),y?.(wr("paypal",u,{code:(0,we.getProviderErrorCode)(De),declineCode:(0,we.getProviderDeclineCode)(De)})),await Ri({billingApiUrl:n,sessionId:Pt,nonce:pt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,we.getProviderErrorCode)(De)??"provider_declined"}})}else nt(De,"stripe_paypal_confirm_failed",pe?.generation);return}ur(ys);let _t=typeof Oe?.payment_method=="string"?Oe.payment_method:Oe?.payment_method?.id;a({id:_t??Oe?.id,type:"card",threeDSecureActionResultTokenId:Oe?.id,isPaypal:!0},{accountPatch:wt,paymentMethodCategory:"paypal",presentationMode:f,sessionId:Pt,nonce:pt});return}catch(ke){nt(ke,"stripe_paypal_failed",pe?.generation)}finally{Re(!1)}},[S,Me,e,t,r,R,St,_,n,ge,a,s,y,E,nt,j,Pe,xe,A,f,W]),Ot=(0,o.useCallback)(async()=>{if(!(ct.current||c||fe||!S||!Me)){ct.current=!0,Re(!0);try{if(!await Ge(!0))return;await Rt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{ct.current=!1,Re(!1)}}},[Me,Rt,c,Ge,S,fe]),zt=f==="redirect"?(0,d.jsx)("button",{type:"button",disabled:c||fe,onClick:()=>{Ot()},style:{width:"100%",minHeight:ea,border:"1px solid #d1d5db",borderRadius:T??8,background:"#ffc439",color:"#111827",cursor:c||fe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(dr.ExpressCheckoutElement,{onReady:ue=>he(Ta(ue,["paypal"])),onLoadError:()=>{he("load_error"),Cs(A,"paypal","paypal","provider_error")},onClick:$e,onConfirm:Rt,onCancel:()=>{let ue=L.current.get(W);L.current.delete(W),A?.terminal({outcome:"payment_cancelled",...Un,terminalReason:"cancelled",...ue?{attempt:ue.generation}:{}}),Se(ue?.generation),We(!1),Z.current=!0,M()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Ke,emailRequired:Ke,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},W),Ft=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{ref:ye,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[dt&&(0,d.jsx)("button",{ref:J,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ut,style:gs,children:"Try PayPal again"}),F&&(0,d.jsx)(Ko,{identity:F.identity,methodLabel:F.methodLabel,onComplete:et,onCancel:()=>et(null)},F.id),(0,d.jsx)("div",{style:{display:F?"none":void 0},children:zt})]}),fe&&!F&&(0,d.jsx)(tn,{status:"processing"})]});return f==="redirect"?Ft:(0,d.jsx)(Ma,{state:ie,placeholderTestId:"flopay-paypal-placeholder",borderRadius:T,children:Ft})}function fs(e){return e==="apple_pay"||e==="google_pay"}var ou=200;function au({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,l.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function ic({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:c,onErrorChange:p,onButtonClick:y,onDecline:g,onTechnicalFailure:E,runBeforeButtonClick:R,billingName:_,onBuyerIdentityReady:H,onLoadStateChange:T,placeholderBorderRadius:Y,popupCapabilityOwner:B,externalTelemetryContext:f}){let h=io(),{emitInstrument:ge}=(0,o.useContext)(vn),S=(0,dr.useStripe)(),Me=(0,dr.useElements)(),A=(0,o.useMemo)(()=>mi(Rr(h),f),[f,h]),[ie,he]=(0,o.useState)("loading");(0,o.useEffect)(()=>{T?.(ie)},[ie,T]);let[fe,Re]=(0,o.useState)(!1);(0,o.useEffect)(()=>{We.current=fe},[fe]);let ct=(0,o.useRef)(!(0,l.isValidEmail)(r?.trim())||!_?.trim()).current,{request:Ke,collect:F,finish:St}=Ho(),et=(0,o.useRef)(null),Ue=(0,o.useRef)(null),[ye,J]=(0,o.useState)(0),[W,Fe]=(0,o.useState)(()=>(0,l.shouldPreferWalletPopup)()),dt=(0,o.useRef)(W),We=(0,o.useRef)(!1),[Z,L]=(0,o.useState)(!1),[le,j]=(0,o.useState)(()=>Si(e,t)?"blocked":"idle"),[Se,xe]=(0,o.useState)("google_pay"),Pe=(0,o.useRef)(null),Be=(0,o.useRef)(!0),M=(0,o.useRef)(!1),nt=(0,o.useRef)("google_pay"),je=(0,o.useRef)("google_pay"),ut=(0,o.useRef)(null),Ge=(0,o.useRef)(null),$e=(0,o.useRef)(new Set),Rt=(0,o.useRef)(null),Ot=(0,o.useRef)(null);(0,o.useEffect)(()=>(Be.current=!0,()=>{Be.current=!1;for(let u of $e.current)window.clearTimeout(u);$e.current.clear()}),[]);let zt=(0,o.useRef)(new Map),{startAttempt:Ft,finishAttempt:ue,invalidateAttempt:pe,isAttemptInvalidated:X,isAttemptCurrent:Pt,generationRef:pt}=ba((u,C,Q)=>{E?.(u,C,{...Q,popupBlocked:Q?.popupBlocked??(0,we.isPopupBlockedError)(C),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),xe(u),L(!0),J(ce=>ce+1)},{onHandoffObserved:u=>{Ot.current=pt.current,B.markAvailable(),A?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:pt.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})},defersMissingTerminal:fs,onMissingTerminalDeferred:(u,C)=>{let Q=A?.now()??globalThis.performance?.now()??Date.now(),ce=Rt.current,N=ce?.generation===C?ce.startedAt:Q;A?.performance({stage:"overlay_return",durationMs:Math.max(0,Q-N),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:C,...fs(u)?{walletType:u}:{}}),A?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{Z&&Ue.current?.focus()},[Z,ye]);let V=(0,o.useRef)(0),rt=(0,o.useRef)(!1),wt=(0,o.useCallback)(()=>{if(V.current>0){rt.current=!0;return}J(u=>u+1)},[]),ke=(0,o.useCallback)(()=>{V.current-=1,!(V.current>0||!rt.current)&&(rt.current=!1,Be.current&&J(u=>u+1))},[]),v=(0,o.useCallback)((u,C,Q,ce,N=!1)=>{pe(ce),E?.(u,C,{code:Q,popupBlocked:(0,we.isPopupBlockedError)(C),telemetryReported:N,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),xe(u),L(!0),wt()},[pe,E,wt]),U=(0,o.useCallback)(u=>{A?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...fs(u)?{walletType:u}:{}}),E?.(u,new Error("The wallet click was not ready within the time the wallet allows."),{code:Bd,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),xe(u),L(!0)},[E,A]),ne=(0,o.useCallback)(()=>{window.setTimeout(()=>{(et.current?.querySelector("iframe")??et.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{M.current&&(M.current=!1,ne())},[ne,ye]);let Ae=(0,o.useCallback)(()=>{L(!1),p?.(null),ne()},[ne,p]),Dt=(0,o.useCallback)(()=>{Pe.current?.()},[]);(0,o.useEffect)(()=>{let u=null,C=()=>{u=null;let ce=(0,l.shouldPreferWalletPopup)();ce!==dt.current&&(dt.current=ce,Fe(ce),!We.current&&!Pt(pt.current)&&wt())},Q=()=>{u!==null&&window.clearTimeout(u),u=window.setTimeout(C,ou)};return window.addEventListener("resize",Q),()=>{window.removeEventListener("resize",Q),u!==null&&window.clearTimeout(u)}},[pt,Pt,wt]),(0,o.useEffect)(()=>{let u=Si(e,t);if(!u)return;let C=!1,Q=!1,ce=async()=>{if(!Q){Q=!0,C||j("checking");try{let N=await ec(S,u.clientSecret,$e.current);if(C)return;let w=ms(N,u.providerObjectId,(0,l.isSetupIntentClientSecret)(u.clientSecret));if(w.kind==="confirmed"){if(!Ql(e,t,u.clientSecret))return;Pe.current=null,j("idle"),c({id:w.paymentMethodId,type:"card",threeDSecureActionResultTokenId:w.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(w.kind==="terminal"){ps(e,t,u.clientSecret),Pe.current=null,j("idle"),xe(u.paymentMethodType),L(!0),wt();return}j("blocked")}catch{C||j("blocked")}finally{Q=!1}}};return Pe.current=ce,j("blocked"),()=>{C=!0,Pe.current===ce&&(Pe.current=null)}},[t,c,wt,e,S]);let ot=(0,o.useCallback)(async u=>{let C=!1,Q=!1,ce=mt=>{C||Q||(C=!0,u.paymentFailed({reason:"fail",...mt?{message:mt}:{}}))};if(!S||!Me){ce();return}let N=zt.current.get(ye);if(N&&!Pt(N.generation)){zt.current.delete(ye),ce();return}if(!N&&X()){ce();return}if(N&&!ue(N.generation)){ce();return}N||(ue(),rt.current=!1);let w=u.expressPaymentType??N?.method??nt.current,qt=N??null,Ar=oc(w),mr;w==="apple_pay"?mr="apple_pay":w==="google_pay"&&(mr="google_pay");let Fr=N?.generation??pt.current,st=A,Gr=st?.now()??globalThis.performance?.now()??Date.now(),Yr=new AbortController,Br=!1,Xt=!1,ar=null,tr=e,In="processing",Jt="other",qn="provider_runtime",Dr,Zt=new Promise((mt,Tt)=>{Dr=Tt}),ir=window.setTimeout(()=>{Br=!0,Yr.abort(),Dr(Ci)},Dd),nn=async(mt,Tt,Or)=>{In=mt,Jt=Tt,qn=Tt==="intent_create"||Tt==="session_claim"?"transport_error":"provider_runtime";let sr=st?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Or,Zt])}finally{let Qt=st?.now()??globalThis.performance?.now()??Date.now();st?.performance({stage:mt,durationMs:Math.max(0,Qt-sr),durationMode:"machine",requestCategory:Tt,paymentMethodCategory:"wallet",provider:"stripe",...Br?{statusClass:"timeout"}:{}})}};try{if(Re(!0),p?.(null),!qt&&R){let be=await nn("processing","other",R(Ar));if(!be.proceed){ce();return}qt={accountPatch:be.accountPatch,sessionId:be.sessionId,nonce:be.nonce}}let mt=qt?.sessionId??e;tr=mt;let Tt=qt?.nonce??t,Or=ut.current??qt?.accountPatch,sr=uc({event:u,fallbackEmail:Or?.email??r,fallbackName:[Or?.firstName,Or?.lastName].join(" ").trim()||_});if(!(0,l.isValidEmail)(sr.email)){ce("Buyer details are required."),F(hs(w),sr).then(be=>{be&&(ut.current=be)});return}ut.current=null;let Qt={...qt?.accountPatch,...(0,Cn.compactBuyerIdentity)(sr,!0)};await nn("processing","session_claim",Promise.resolve(H?.(sr)));let{error:zr}=await nn("tokenization","provider_sdk",Me.submit());if(zr){ce(),v(w,zr,"stripe_wallet_submit_failed",N?.generation);return}if(!mt)throw new Error("Missing sessionId or email for payment.");let Pr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:w,paymentMethodId:null,intentKind:a},jt=JSON.stringify({sessionId:mt,nonce:Tt??"",request:Pr}),Lr=Ge.current,Er=Lr?.retryIdentity===jt?Lr.authorizationAttemptId:(0,l.randomUuidV4)();Ge.current={authorizationAttemptId:Er,retryIdentity:jt};let Ce=await nn("processing","intent_create",wi(n,ge,mt,Tt??"",{...Pr,authorizationAttemptId:Er},{signal:Yr.signal}));if((0,l.isSettledSessionIntent)(Ce)){ce(),c({type:"card",paymentMethodType:w},{accountPatch:Qt,paymentMethodCategory:"wallet",sessionId:mt,nonce:Tt,settledProcessResponse:Ce.response});return}if(Ce.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Nr=Ce.clientSecret,_n=jd({createdAt:Date.now(),sessionId:mt,...Tt?{nonce:Tt}:{},clientSecret:Nr,providerObjectId:Ce.providerObjectId,paymentMethodType:w,accountPatch:Qt});window.clearTimeout(ir),Xt=!0,st?.performance({stage:"callback",durationMs:Math.max(0,(st?.now()??globalThis.performance?.now()??Date.now())-Gr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Tn=st?.now()??globalThis.performance?.now()??Date.now(),vr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...mr?{walletType:mr}:{},attempt:Fr},pn=!1,mn=null;st?.log({name:"payment.provider_confirmation.started",...vr}),ar=window.setTimeout(()=>{ar!==null&&$e.current.delete(ar),pn=!0;let be=st?.now()??globalThis.performance?.now()??Date.now();st?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...vr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,be-Tn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),st?.flush?.().catch(()=>{}),mn?.()},Od),$e.current.add(ar);let Mn=(be,Ut)=>{ar!==null&&(window.clearTimeout(ar),$e.current.delete(ar),ar=null);let tt=st?.now()??globalThis.performance?.now()??Date.now(),at=Math.max(0,tt-Tn),rr=be;pn&&(be==="resolved"?rr="resolved_late":be==="returned_error"?rr="returned_error_late":rr="rejected_late");let Vr=Ut??(be==="resolved"?"approved":"provider_error");return st?.log({name:"payment.provider_confirmation.returned",...vr,operationOutcome:rr,terminalReason:Vr}),st?.performance({...vr,durationMs:at,durationMode:"buyer",operationOutcome:rr,terminalReason:Vr}),{durationMs:at,operationOutcome:rr,terminalReason:Vr}},Lt=!1,ve=!1,on=be=>{if(!be||typeof be!="object")return null;let Ut=be;if(Ut.error)return null;let tt=Ut.setupIntent??Ut.paymentIntent,at=ms(tt??null,void 0,!!Ut.setupIntent);return at.kind==="confirmed"?at:null},K=be=>{if(Lt||N&&pt.current!==N.generation)return;let Ut=on(be);if(!Ut)return;if(_n&&!Ql(mt,Tt,Nr)){Lt=!0;return}let{intentId:tt,paymentMethodId:at}=Ut;Lt=!0,ve=!0,Ge.current=null,Pe.current=null,Be.current&&(j("idle"),Re(!1));let rr=`${lc}:${mt}`;ur(rr,{createdAt:Date.now(),sessionId:mt,nonce:Tt,accountPatch:Qt,paymentMethodId:at,providerIntentId:tt,paymentMethodType:w});try{c({id:at,type:"card",threeDSecureActionResultTokenId:tt},{accountPatch:Qt,paymentMethodCategory:"wallet",sessionId:mt,nonce:Tt})}finally{ur(rr)}},Nt=!1;mn=async()=>{if(!(Nt||Lt||ve)){Nt=!0,Be.current&&j("checking");try{let be=await ec(S,Nr,$e.current);if(Lt||ve)return;let Ut=(0,l.isSetupIntentClientSecret)(Nr),tt=ms(be,Ce.providerObjectId,Ut);if(tt.kind==="confirmed"){K(Ut?{setupIntent:be}:{paymentIntent:be});return}if(tt.kind==="terminal"){if(ve=!0,ps(mt,Tt,Nr),Ge.current=null,Pe.current=null,!Be.current)return;j("idle"),ce(),v(w,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",N?.generation,!0);return}Be.current&&!ve&&(j("blocked"),Re(!1))}catch{Be.current&&!ve&&(j("blocked"),Re(!1))}finally{Nt=!1}}},Pe.current=mn;let ae,Ht;try{Q=!0,V.current+=1;let be;try{be=await((0,l.isSetupIntentClientSecret)(Nr)?S.confirmSetup({elements:Me,clientSecret:Nr,redirect:"if_required"}):S.confirmPayment({elements:Me,clientSecret:Nr,redirect:"if_required"}))}finally{ke()}if(!be||typeof be!="object")throw new Fa(qd(be));if(ae=be,!ae.error&&!on(ae))throw new Fa("confirmation_result_unconfirmed");Ht=Mn(ae.error?"returned_error":"resolved",ae.error&&(0,we.isProviderDecline)(ae.error)?"provider_declined":void 0)}catch(be){let Ut=be instanceof Fa?be.reason:void 0,tt=Ut!==void 0,at=Mn(tt?"returned_error":"rejected");if(st?.error({...tt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Ut}:ns(be),...vr,operationOutcome:at.operationOutcome,durationMs:at.durationMs,statusClass:"unknown",terminalReason:at.terminalReason}),!Be.current||Lt)return;await mn?.();return}let Gt=ae.error;if(Gt){if(!Be.current||Lt)return;if((0,we.isProviderDecline)(Gt)){ve=!0,ps(mt,Tt,Nr),Ge.current=null,Pe.current=null,j("idle"),zt.current.get(ye)===N&&zt.current.delete(ye);let be=Gt.message??"Your payment was declined.";p?.(be),g?.(wr(Ar,be,{code:(0,we.getProviderErrorCode)(Gt),declineCode:(0,we.getProviderDeclineCode)(Gt)})),Ri({billingApiUrl:n,sessionId:mt,nonce:Tt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:w,providerDeclineReason:(0,we.getProviderErrorCode)(Gt)??"provider_declined",...Ce.intentKind==="payment"&&Ce.providerObjectId.startsWith("pi_")?{providerIntentId:Ce.providerObjectId}:{}}})}else st?.error({...ns(Gt),...vr,operationOutcome:Ht.operationOutcome,durationMs:Ht.durationMs,statusClass:"unknown",terminalReason:Ht.terminalReason}),await mn?.();return}if(K(ae),!Lt)throw new Error("Invalid provider returned for APM intent")}catch(mt){if(mt===Ci){let Tt=st?.now()??globalThis.performance?.now()??Date.now();st?.error({errorCode:Wd(Jt),stage:In,requestCategory:Jt,paymentMethodCategory:"wallet",provider:"stripe",...mr?{walletType:mr}:{},operationOutcome:"watchdog_expired",checkoutSessionId:tr,durationMs:Math.max(0,Tt-Gr),statusClass:"timeout",failureCategory:qn,attempt:Fr,terminalReason:"provider_error"}),st?.flush?.().catch(()=>{})}ce(),v(w,mt,mt===Ci?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",N?.generation,mt===Ci)}finally{if(window.clearTimeout(ir),ar!==null&&(window.clearTimeout(ar),$e.current.delete(ar)),!Xt){let mt=st?.now()??globalThis.performance?.now()??Date.now();st?.performance({stage:"callback",durationMs:Math.max(0,mt-Gr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Br?{statusClass:"timeout"}:{}})}Be.current&&Re(!1)}},[S,Me,e,t,r,_,F,H,n,ge,a,c,p,g,R,v,ke,ue,Pt,X,pt,A,ye]),De=(0,o.useMemo)(()=>fi(s),[s]),Oe=(0,o.useMemo)(()=>s.map(l.stripeExpressMethodToOptionKey),[s]),_t=(0,o.useMemo)(()=>(0,d.jsx)(dr.ExpressCheckoutElement,{onReady:u=>{he(Ta(u,Oe))},onLoadError:u=>{he("load_error"),Cs(A,"stripe","wallet","provider_error")},onClick:async u=>{let C=A?.now()??globalThis.performance?.now()??Date.now();nt.current=u.expressPaymentType,je.current=oc(u.expressPaymentType);let Q=!0,ce=window.setTimeout(()=>{Q=!1,u.reject(),U(u.expressPaymentType)},Fd),N=R?await R(je.current,{abandoned:()=>!Q}):{proceed:!0};if(window.clearTimeout(ce),!Q)return;if(!N.proceed){zt.current.delete(ye),u.reject();return}let w=Ft(u.expressPaymentType);rt.current=!1,Rt.current={generation:w,startedAt:C},zt.current.set(ye,{generation:w,method:u.expressPaymentType,accountPatch:N.accountPatch,sessionId:N.sessionId,nonce:N.nonce}),L(!1),A?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:w,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),y?.(je.current),u.resolve()},onConfirm:ot,onCancel:()=>{let u=zt.current.get(ye);zt.current.delete(ye);let C=Rt.current,Q=A?.now()??globalThis.performance?.now()??Date.now();if(u&&C?.generation===u.generation&&(0,l.isWalletSheetRefusedForWindowSize)({method:u.method,elapsedMs:Q-C.startedAt,handoffObserved:Ot.current===u.generation})){A?.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"}),Ge.current=null,v(u.method,new Error("The browser window is too small for the Google Pay sheet."),l.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,u.generation,!0);return}A?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),pe(u?.generation),Ge.current=null,L(!1),M.current=!0,wt()},options:{...gi,paymentMethods:De,emailRequired:ct,billingAddressRequired:ct}},ye),[Oe,De,ot,pe,y,ct,v,U,wt,R,Ft,ye,A]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Ma,{state:ie,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Y,children:(0,d.jsxs)("div",{ref:et,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Z&&(0,d.jsxs)("button",{ref:Ue,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ae,style:gs,children:["Try ",hs(Se)," again"]}),le!=="idle"&&(0,d.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,d.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,d.jsx)("button",{type:"button",onClick:Dt,disabled:le==="checking",style:gs,children:le==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ke&&(0,d.jsx)(Ko,{identity:Ke.identity,methodLabel:Ke.methodLabel,onComplete:St,onCancel:()=>St(null)},Ke.id),(0,d.jsxs)("div",{style:{display:Ke||le!=="idle"?"none":void 0},children:[(0,d.jsx)(au,{active:W}),_t]})]})}),fe&&(0,d.jsx)(tn,{status:"processing"})]})}function pc(e,t,r){let n=(0,l.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function Ps({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:c,onTokenizedBody:p,onErrorChange:y,onDecline:g,onCancel:E,runBeforeButtonClick:R,onButtonClick:_,isProcessing:H,submitButtonColor:T,submitButtonBorderRadius:Y,submitButtonStyle:B,errorText:f}){let h=io(),{emitInstrument:ge}=(0,o.useContext)(vn),S=(0,dr.useStripe)(),Me=(0,dr.useElements)(),[A,ie]=(0,o.useState)(!1),he=(0,o.useRef)(!1),[fe,Re]=(0,o.useState)(!1),[ct,Ke]=(0,o.useState)("loading"),[F,St]=(0,o.useState)(""),et=!(0,l.isValidEmail)(n?.trim()),Ue=!et||(0,l.isValidEmail)(F.trim()),ye=(0,o.useCallback)(async()=>{if(!S||!Me||H||he.current||!fe)return;he.current=!0,ie(!0);let J=R?await R("card"):{proceed:!0};if(!J.proceed){he.current=!1,ie(!1);return}_?.("card");let W=J.sessionId??t,Fe=J.nonce??r,dt=(0,$o.splitFullName)(a?.trim()),We=(0,Cn.compactBuyerIdentity)({email:J.accountPatch?.email?.trim()||n?.trim()||F.trim(),firstName:J.accountPatch?.firstName?.trim()||dt.firstName,lastName:J.accountPatch?.lastName?.trim()||dt.lastName}),Z=We.email,L=(0,Cn.compactBuyerIdentity)({...J.accountPatch,...We});try{if(y?.(null),!(0,l.isValidEmail)(Z))throw new Error("A valid email address is required for payment.");await s?.(We);let le=await Me.submit();if(le.error){y?.(le.error.message??"Payment failed.");return}let j=[We.firstName,We.lastName].filter(Boolean).join(" "),Se=await S.createPaymentMethod({elements:Me,params:{billing_details:{email:Z,...j?{name:j}:{}}}});if(Se.error||!Se.paymentMethod){y?.(Se.error?.message??"Failed to create payment method.");return}let xe=Se.paymentMethod;if(!W||!Z)throw new Error("Missing sessionId or email for payment.");let Pe=xe.type||e,Be=await wi(c,ge,W,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Pe,paymentMethodId:null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(Be)){p({type:"card",gateway:"stripe",paymentMethodType:Pe},{accountPatch:L,paymentMethodCategory:"apm",sessionId:W,nonce:Fe,settledProcessResponse:Be.response});return}if(Be.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let M=Be.clientSecret;ur(Jn,{clientSecret:M,sessionId:W,nonce:Fe,accountPatch:L,paymentMethodId:xe.id,paymentMethodType:xe.type??e,gateway:"stripe"});let{error:nt,paymentIntent:je}=await S.confirmPayment({clientSecret:M,confirmParams:{return_url:window.location.href,payment_method:xe.id},redirect:"if_required"});if(nt){ur(Jn);let $e=nt.message??"Payment failed.";y?.($e),g?.(wr("card",$e,{code:nt.code})),await Ri({billingApiUrl:c,sessionId:W,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:nt.code??"provider_declined"}});return}let ut=je?.status;if(!ha(ut)){ur(Jn);let $e=ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.($e),g?.(wr("card",$e,{code:ut??"missing_payment_intent"}));return}ur(Jn);let Ge=typeof je?.payment_method=="string"?je.payment_method:je?.payment_method?.id;p({id:Ge??xe.id,type:"card",threeDSecureActionResultTokenId:je?.id,gateway:"stripe",paymentMethodType:xe.type??e},{accountPatch:L,paymentMethodCategory:"apm",sessionId:W,nonce:Fe})}catch(le){y?.(le instanceof Error?le.message:"Payment failed. Please try again.")}finally{he.current=!1,ie(!1)}},[S,Me,H,fe,R,_,t,r,n,a,F,s,c,ge,e,p,y,g]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[et&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:et&&(0,d.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,d.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:F,onChange:J=>St(J.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(dr.PaymentElement,{onReady:()=>Ke("ready"),onLoadError:()=>{Ke("load_error"),Cs(Rr(h),"stripe","apm")},onChange:J=>{Re(!!J.complete)},options:{layout:hi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,l.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,d.jsx)(Pi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ye()},disabled:!fe||!Ue||A||H||ct!=="ready",color:T,borderRadius:Y,style:B,children:A?"Processing\u2026":`Pay with ${(0,l.getStripeMethodDisplayName)(e)}`}),f&&(0,d.jsx)(Xo,{margin:"0.75rem 0 0",children:f})]})}function sc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:c,stripeInstance:p,paymentElementBaseOptions:y,futureUseSession:g,onTokenizedBody:E,onErrorChange:R,onButtonClick:_,onDecline:H,runBeforeButtonClick:T,onLoadStateChange:Y,isProcessing:B=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:h=8,submitButtonStyle:ge,buttonAppearance:S,themeId:Me,onExpandApm:A,expandedApmMethod:ie}){let{emitInstrument:he}=(0,o.useContext)(vn),[fe,Re]=(0,o.useState)(null),[ct,Ke]=(0,o.useState)(null),F=(0,o.useRef)(!1),{request:St,collect:et,finish:Ue}=Ho();(0,o.useEffect)(()=>{c.length>0&&p?Y?.("ready"):p||Y?.("loading")},[c.length,p,Y]);let ye=(0,o.useCallback)(async Z=>{if(!p||F.current||B)return;F.current=!0,Ke(Z);let L=T?await T("card"):{proceed:!0};if(!L.proceed){F.current=!1,Ke(null);return}_?.("card");let le=L.sessionId??e,j=L.nonce??t,Se=(0,$o.splitFullName)([L.accountPatch?.firstName,L.accountPatch?.lastName].filter(Boolean).join(" ")||n),xe=(0,Cn.compactBuyerIdentity)({email:L.accountPatch?.email?.trim()||r?.trim(),firstName:L.accountPatch?.firstName?.trim()||Se.firstName,lastName:L.accountPatch?.lastName?.trim()||Se.lastName});if(!(0,l.isValidEmail)(xe.email)){Ke(null);let M=await et((0,l.getStripeMethodDisplayName)(Z),xe);if(!M){F.current=!1;return}xe=M,Ke(Z)}let Pe=xe.email,Be=(0,Cn.compactBuyerIdentity)({...L.accountPatch,...xe});try{if(R?.(null),!le||!(0,l.isValidEmail)(Pe))throw new Error("Missing sessionId or email for payment.");await a?.(xe);let M=await wi(s,he,le,j??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,paymentMethodId:null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(M)){E({type:"card",gateway:"stripe",paymentMethodType:Z},{accountPatch:Be,paymentMethodCategory:"apm",sessionId:le,nonce:j,settledProcessResponse:M.response});return}if(M.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let nt=M.clientSecret;ur(Jn,{clientSecret:nt,sessionId:le,nonce:j,accountPatch:Be,paymentMethodType:Z,gateway:"stripe"});let{error:je,paymentIntent:ut}=await p.confirmPayment({clientSecret:nt,confirmParams:{return_url:window.location.href,payment_method_data:{type:Z,billing_details:{name:[xe.firstName,xe.lastName].filter(Boolean).join(" "),...Pe?{email:Pe}:{}}}},redirect:"if_required"});if(je){ur(Jn);let Rt=je.message??"Payment failed.";R?.(Rt),H?.(wr("card",Rt,{code:je.code})),await Ri({billingApiUrl:s,sessionId:le,nonce:j,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,providerDeclineReason:je.code??"provider_declined"}});return}let Ge=ut?.status;if(!ha(Ge)){ur(Jn);let Rt=Ge==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";R?.(Rt),H?.(wr("card",Rt,{code:Ge??"missing_payment_intent"}));return}ur(Jn);let $e=typeof ut?.payment_method=="string"?ut.payment_method:ut?.payment_method?.id;E({id:$e??ut?.id,type:"card",threeDSecureActionResultTokenId:ut?.id,gateway:"stripe",paymentMethodType:Z},{accountPatch:Be,paymentMethodCategory:"apm",sessionId:le,nonce:j})}catch(M){R?.(M instanceof Error?M.message:"Payment failed. Please try again.")}finally{F.current=!1,Ke(null)}},[p,B,T,_,e,t,r,et,s,he,n,a,E,R,H]),[J,W]=(0,o.useState)(null),Fe=A?ie??null:J,dt=(0,o.useCallback)(Z=>{F.current||B||Fe&&Fe!==Z||((0,l.needsStripeMethodExplicitConfirm)(Z)?A?A(Z):W(Z):ye(Z))},[Fe,B,ye,A]),We=(0,o.useMemo)(()=>J?pc(y,J,g):null,[J,y,g]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:St?(0,d.jsx)(Ko,{identity:St.identity,methodLabel:St.methodLabel,onComplete:Ue,onCancel:()=>Ue(null)},St.id):c.map(Z=>{let L=ie===Z,le=ct===Z,j=ct!==null&&ct!==Z||ie!=null&&ie!==Z;return(0,d.jsxs)(o.default.Fragment,{children:[(0,d.jsx)(yi,{method:Z,themeId:Me,submitting:le,disabled:j,highlighted:L,hasNextStep:(0,l.needsStripeMethodExplicitConfirm)(Z),onClick:()=>dt(Z),backgroundColor:S?.backgroundColor,borderColor:S?.borderColor,textColor:S?.textColor,borderRadius:S?.borderRadius,fontFamily:S?.fontFamily}),!A&&J===Z&&We&&p&&(0,d.jsx)(dr.Elements,{stripe:p,options:We,children:(0,d.jsx)(Ps,{method:Z,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:E,onErrorChange:R,onDecline:H,onCancel:()=>W(null),runBeforeButtonClick:T,onButtonClick:_,isProcessing:B,submitButtonColor:f,submitButtonBorderRadius:h,submitButtonStyle:ge})},Z)]},Z)})})}function iu({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:c,onError:p,onDecline:y,onCancel:g,onTokenizedBody:E,firstName:R,lastName:_,chv:H,className:T,submitLabel:Y,isProcessing:B,error:f,onErrorChange:h,showPayPal:ge=!0,showStripe:S=!0,walletPresentation:Me="auto",enabledPaymentMethods:A,enabledPaymentMethodCountries:ie,showApplePay:he=!0,showGooglePay:fe=!0,layout:Re="default",theme:ct,buttonsTheme:Ke,buttonsStyles:F,appearance:St,cardButtonContent:et,cardBackButtonContent:Ue,cardTitleContent:ye,showSecurityFooter:J,onButtonClick:W,onBeforeButtonClick:Fe,onBuyerIdentityReady:dt,enableAVS:We,cardFieldOrder:Z,cardAutoFocus:L,cardPreFormSlot:le,avsLayout:j="row",country:Se,zip:xe,addressLine1:Pe,addressLine2:Be,city:M,state:nt,onCountryChange:je,onZipChange:ut,avsCheck:Ge,checkoutType:$e,checkoutLayout:Rt,totalAmount:Ot=0,currency:zt="usd",initialCardOpen:Ft=!1,directPaypal:ue,isSubscription:pe=!1,session:X,dataAttachmentPending:Pt=!1,dataAttachmentRequiresIdentity:pt=!1,debug:V=!1}){let rt=io(),wt=ri(),ke=(0,o.useContext)(On),{emitInstrument:v}=(0,o.useContext)(vn),U=(0,o.useRef)(null);U.current||(U.current=oi());let ne=U.current,[,Ae]=(0,o.useState)(0),Dt=(0,o.useRef)(null);Dt.current||(Dt.current=(0,Gn.detectPayPalEnvironment)());let ot=Dt.current,De=(0,o.useMemo)(()=>({browser:ot,capability:ne,presentationMode:"popup"}),[ot,ne]),Oe=X??ke.session,_t=(0,o.useMemo)(()=>({futureUse:Oe?.futureUse,futureUseUnsupported:Oe?.futureUseUnsupported}),[Oe?.futureUse,Oe?.futureUseUnsupported]),u=Oe?.gateways?.paypal?.providerObjectType??ue?.providerObjectType,C=Pt||ke.claimPending===!0,Q=pt||ke.claimRequiresIdentity===!0,ce=C&&!Q,N=Ol(),w=r||N,[qt,Ar]=(0,o.useState)(!1),[mr,Fr]=(0,o.useState)(null),[st,Gr]=(0,o.useState)(Se??""),[Yr,Br]=(0,o.useState)(xe??""),[Xt,ar]=(0,o.useState)(Pe??""),[tr,In]=(0,o.useState)(Be??""),[Jt,qn]=(0,o.useState)(M??""),[Dr,Zt]=(0,o.useState)(nt??""),[ir,nn]=(0,o.useState)(""),[mt,Tt]=(0,o.useState)({}),Or=(0,o.useRef)(xe??""),sr=(0,o.useRef)(Se??""),Qt=(0,o.useRef)(Pe??""),zr=(0,o.useRef)(Be??""),Pr=(0,o.useRef)(M??""),jt=(0,o.useRef)(nt??""),Lr=(0,o.useRef)(""),Er=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(b,$,_e,G,Te)=>{if(Er.current[b])return;let $t=$?.trim();!$t||$t===_e.current||(_e.current=$t,G($t),Te?.($t))};i("country",Se,sr,Gr,je),i("zip",xe,Or,Br,ut),i("addressLine1",Pe,Qt,ar),i("addressLine2",Be,zr,In),i("city",M,Pr,qn),i("state",nt,jt,Zt)},[Se,xe,Pe,Be,M,nt,je,ut]);let Ce=(0,o.useMemo)(()=>(0,l.resolveAVSConfig)(We),[We]),Nr=Ce!==null,_n=(0,o.useMemo)(()=>(0,l.isAuthorizationOnlySession)(X),[X]),Tn=(0,l.isMountableVaultBlock)(X?.vault),vr=!!X?.gateways?.pcivault,pn=(0,Dn.hasServerSideCardGateway)(X),Mn=!!(X?.gateways?.stripe?.enabledPaymentMethods??A)?.includes("card")||(0,Dn.canRecoverHostedCardForm)(X),Lt=Tn||Mn||vr,ve=!!(S&&Lt&&e),[on,K]=(0,o.useState)(()=>Re!=="buttons"||Ft?e??null:null),[Nt,ae]=(0,o.useState)(0),Ht=Re!=="buttons"||Ft||!!e&&on===e,Gt=X?.captureMethod,be=(0,o.useRef)(rt);(0,o.useEffect)(()=>{be.current=rt},[rt]);let[Ut,tt]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!ve||!e||!Ht){tt(null);return}let i=be.current?be.current.cardCapture({sessionId:e,captureMethod:Gt}):new zn.PciVaultCardCapture({sessionId:e,captureMethod:Gt,billingApiUrl:w,telemetry:n});return tt({sessionId:e,captureMethod:Gt,billingApiUrl:w,telemetry:n,capture:i}),()=>{i.unmount()}},[ve,e,Ht,Gt,w,n]);let at=ve&&e&&Ht&&Ut?.sessionId===e&&Ut.captureMethod===Gt&&Ut.billingApiUrl===w&&Ut.telemetry===n?Ut.capture:null,rr=(0,o.useMemo)(()=>{let i=st,b=Ce?(0,l.isAVSFieldVisible)(Ce.postal_code,i):!1;return tu(i,Yr,b)},[Ce,st,Yr]),{avsInvalid:Vr,invalidAvsFields:yn}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!ve||!Ce)return{avsInvalid:!1,invalidAvsFields:i};let b=st,$=(Te,$t)=>(0,l.isAVSFieldVisible)(Te,b)&&!$t.trim(),_e={line1:$(Ce.address_line_1,Xt),city:$(Ce.city,Jt),state:$(Ce.state,Dr),zip:rr.empty||rr.malformed};return{avsInvalid:_e.line1||_e.city||_e.state||_e.zip,invalidAvsFields:_e}},[ve,Ce,st,Xt,Jt,Dr,rr]),[lr,jn]=(0,o.useState)(!1),[Vn,eo]=(0,o.useState)(!1),[xn,po]=(0,o.useState)(!1),[to,an]=(0,o.useState)({line1:!1,city:!1,state:!1}),An=(0,o.useRef)(!1),sn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Wn=(0,o.useRef)(!1),Vt=(0,o.useCallback)(i=>{sn.current[i]=!0,Wn.current=!0},[]),Xr=(0,o.useCallback)(i=>!An.current&&sn.current[i],[]),Jr=(0,o.useCallback)(i=>{Xr(i)&&an(b=>b[i]?b:{...b,[i]:!0})},[Xr]),[Zr,fn]=(0,o.useState)(()=>(0,l.resolveVaultMountOptions)(X?.vault,{billingApiUrl:w,sessionId:e,nonce:t})),[yt,nr]=(0,o.useState)(Ft&&Lt?"card":"buttons"),[Ir,Wr]=(0,o.useState)(null),_o=yt==="expanding"||yt==="card",gn=X?.gateways?.stripe&&!pn?"stripe":void 0,ro=(0,o.useCallback)(()=>{v?.({class:"card_surface",provider:gn})},[gn,v]),ln=(0,o.useRef)(null),Cr=(0,o.useCallback)(i=>{ln.current&&clearTimeout(ln.current),ln.current=setTimeout(()=>{ln.current=null,i()},Ba)},[]);(0,o.useEffect)(()=>()=>{ln.current&&clearTimeout(ln.current)},[]);let mo=(0,o.useRef)(!1),[qr,z]=(0,o.useState)(0),O=(0,o.useRef)(null),se=(0,o.useCallback)(()=>{ro(),K(e??null),mo.current&&(mo.current=!1,z(i=>i+1)),ae(i=>i+1),nr("expanding"),Cr(()=>nr("card"))},[Cr,ro,e]),me=(0,o.useCallback)(()=>{nr("collapsing"),Cr(()=>nr("buttons"))},[Cr]),kt=(0,o.useCallback)(i=>{Wr(i),nr("apm-expanding"),Cr(()=>nr("apm-form"))},[Cr]),Wt=(0,o.useCallback)(()=>{nr("apm-collapsing"),Cr(()=>{nr("buttons"),Wr(null)})},[Cr]);(0,o.useEffect)(()=>{Re==="buttons"&&Ft&&Lt&&(K(e??null),nr("card"))},[Re,Ft,Lt,e]);let[Ve,oe]=(0,o.useState)(null),te=(0,o.useRef)(null),[Je,Ee]=(0,o.useState)(0);(0,o.useEffect)(()=>{Je!==0&&te.current?.focus()},[Je]);let it=(0,o.useRef)(!1),q=(0,o.useRef)(null),ee=(0,o.useRef)("idle"),[Bt,Et]=(0,o.useState)(!1),x=(0,o.useRef)(Bt);x.current=Bt;let[m,I]=(0,o.useState)(()=>ue?.existingOrderId?{orderId:ue.existingOrderId,attempts:1}:null),Le=(0,o.useRef)(m);(0,o.useEffect)(()=>{Le.current=m},[m]);let Ze=(0,o.useRef)(null),He=(0,o.useMemo)(()=>{if(dt||ke.claimBuyerIdentity||X?.buyerIdentified!==!1||!e||!t)return;let i=`${w}|${e}|${t}`;Ze.current?.key!==i&&(Ze.current={key:i,claim:Vo(new zn.PaymentAPI(w,{telemetry:!1}),e,t,{...s?{userId:s}:{},...R?{firstName:R}:{},..._?{lastName:_}:{}})});let b=Ze.current.claim;return async $=>{await b($)}},[dt,ke.claimBuyerIdentity,X?.buyerIdentified,e,t,w,s,R,_]),It=dt??ke.claimBuyerIdentity??He,Ye=f??mr,br=(0,o.useMemo)(()=>(0,l.resolveTheme)(ct),[ct]),de=(0,o.useMemo)(()=>{let i=br?.buttonsLayout??(0,l.resolveButtonsLayoutTheme)(Ke);return F?{...i,...F,cardButton:{...i.cardButton,...F.cardButton},cardFormContainer:{...i.cardFormContainer,...F.cardFormContainer},backButton:{...i.backButton,...F.backButton},backButtonIcon:{...i.backButtonIcon,...F.backButtonIcon},submitButton:{...i.submitButton,...F.submitButton},title:{...i.title,...F.title}}:i},[br,Ke,F]),Sr=St??br?.appearance,Mt=(0,o.useMemo)(()=>(0,l.computeVaultCardThemeColors)({appearance:Sr,buttonsStyles:de,layout:Re}),[Sr,de,Re]),xt=ke.inlineSessionPatchProcessing??!1,Ie=(B??qt)||xt,vt=w.replace(/\/+$/,""),re=(0,o.useMemo)(()=>rs({userId:s,email:a,firstName:R,lastName:_,country:Se,zip:xe},mt),[s,a,R,_,Se,xe,mt]),_r=[re.firstName,re.lastName].filter(i=>!!i?.trim()).join(" "),Yt=!(0,l.isValidEmail)(re.email?.trim()),To=(0,o.useRef)(null);ve&&To.current===null&&(To.current=Yt);let yo=ve&&(To.current??Yt),Bi=(0,o.useMemo)(()=>ru(ir,yo),[ir,yo]),Mo=Bi.empty||Bi.malformed,cn=(0,o.useMemo)(()=>rt?rt.getRawProvider():null,[rt]),Fs=(0,o.useMemo)(()=>wt?wt.getRawProvider():null,[wt]),oa=Ot||100,xo=zt.toLowerCase(),Di=(0,o.useMemo)(()=>Sr?(0,zn.toStripeAppearance)(Sr):null,[Sr]),Ao=Di,Bs=(0,o.useMemo)(()=>{let i=Di??{},b=i.rules??{};return{...i,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[Di]),Ds=(0,o.useMemo)(()=>({...Fl(Ot,Oe?.captureMethod,_t),currency:xo,...Ao?{appearance:Ao}:null}),[Ot,xo,Oe?.captureMethod,_t,Ao]),Oi=(0,l.resolveSetupFutureUsage)(_t,"paypal","paypal"),Os=(0,o.useMemo)(()=>({mode:"payment",amount:oa,currency:xo,captureMethod:"manual",...Oi?{setupFutureUsage:Oi}:null,...Ao?{appearance:Ao}:null}),[oa,xo,Oi,Ao]),ze=(0,o.useCallback)(i=>{Fr(i),h?.(i)},[h]),Ls=(0,o.useRef)(0);(0,o.useEffect)(()=>{qr!==Ls.current&&(Ls.current=qr,ze(null))},[qr,ze]);let Li=(0,o.useRef)(""),[Ns,Dc]=(0,o.useState)(!1),Ni=(0,o.useCallback)(()=>{Dc(!0)},[]);(0,o.useEffect)(()=>{if(!ve||!yo||!It||!Ns||Mo||Li.current)return;let i=(0,Cn.compactBuyerIdentity)({email:(0,l.isValidEmail)(re.email?.trim())?re.email?.trim():Lr.current.trim(),firstName:re.firstName?.trim(),lastName:re.lastName?.trim()});Li.current=JSON.stringify(i),Tt(b=>({...b,...i})),Promise.resolve(It(i)).catch(b=>{Li.current="",ze(b instanceof Error?b.message:"Failed to attach buyer details.")})},[ve,yo,It,Ns,Mo,re.email,re.firstName,re.lastName,ze]),(0,o.useEffect)(()=>{if(!ve||!at)return;let i=L!==!1&&Ce==null&&!yo;at.setCardFieldOrder?.(Z??null,i)},[ve,at,Z,L,Ce,yo]),(0,o.useEffect)(()=>{(yt==="expanding"||yt==="collapsing"||yt==="apm-expanding"||yt==="apm-collapsing")&&ze(null)},[yt,ze]);let $n=(0,o.useCallback)((i,b,$)=>{y?.(wr(i,b,$))},[y]),Us=(0,o.useRef)(yt);Us.current=yt;let[zs]=(0,o.useState)(ii),qs=(0,o.useCallback)(()=>{let i=Us.current;if(Re==="buttons"&&(i==="card"||i==="expanding"))return!0;let b=ee.current;return b==="validation-window"||b==="processing"||x.current},[Re]),js=(0,o.useCallback)((i,b,$)=>{zs.take(e)&&Rr(rt)?.log(ko({...De,presentationMode:$?.presentationMode??"popup"},{name:ai,stage:"recovery",reason:"other_method_active",provider:$?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:$?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[De,rt,zs,e]),Ua=(0,o.useCallback)((i,b,$)=>{$?.telemetryReported||Rr(rt)?.error(ko({...De,presentationMode:$?.presentationMode??"popup"},{errorCode:b?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:$?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:$?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:$?.terminalReason??(b?"popup_blocked":"provider_error")}))},[De,rt]),Fo=(0,o.useCallback)((i,b,$)=>{let _e=$?.popupBlocked??(0,we.isPopupBlockedError)(b);if(qs()){Ua(i,_e,$),js(i,b,$);return}if(b instanceof l.FloPayError&&b.code==="checkout_processing_timeout"){Ua(i,!1,$),oe(null),Re==="buttons"&&(nr("buttons"),Wr(null)),ze(b.message),p?.(b);return}_e&&ne.markBlocked()&&Ae(Ct=>Ct+1);let G=hs(i),Te=$?.code===l.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,l.buildWalletSheetWindowMessage)(G):(0,we.buildExternalMethodRecoveryMessage)(G,_e,ot.inAppBrowser),$t=(0,we.getProviderErrorCode)(b),Pn=($t?.toLowerCase()==="error"?void 0:$t)??(0,we.sanitizeExternalFailureCode)($?.code)??"external_payment_method_failed",ft=new l.FloPayError(Te,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:Pn,popupBlocked:_e,inAppBrowser:ot.inAppBrowser,appFamily:ot.appFamily,popupCapability:ne.current(),presentationMode:$?.presentationMode??"popup"}});Ua(i,_e,$),oe(null),Re==="buttons"&&(nr("buttons"),Wr(null)),ze(Te),p?.(ft),console.error("[FloPay] External payment method failed:",{method:i,code:Pn,popupBlocked:_e})},[ot,qs,Re,p,ne,js,Ua,ze]);(0,o.useEffect)(()=>{if(!ve||!e){fn(null);return}let i={billingApiUrl:vt,sessionId:e,nonce:t},b=(0,l.resolveVaultMountOptions)(X?.vault,i);if(b){fn(b);return}if(!Ht){fn(null);return}let $=`${vt}\0${e}\0${t??""}`,_e=O.current;if(_e&&_e.key===$){fn(_e.mount);return}fn(null);let G=!0;return new zn.PaymentAPI(vt).getVaultCapture(e,t).then(Te=>{if(!G)return;let $t=(0,l.resolveVaultMountOptions)(Te,i);$t?.verificationRequired&&!Te.html&&(O.current={key:$,mount:$t}),$t?fn($t):ze("Failed to load the secure card form.")}).catch(Te=>{G&&ze(Te instanceof Error?Te.message:"Failed to load the secure card form.")}),()=>{G=!1}},[ve,Ht,Nt,e,X?.vault,vt,t,ze]);let Fn=(0,o.useRef)({onComplete:c,onError:p,updateError:ze,emitDecline:$n,resolvedAccount:re,avsConfig:Ce,avsCheckProp:Ge,sessionId:e,nonce:t,baseUrl:vt,captureMethod:X?.captureMethod,paymentId:X?.paymentId,authorizationExpiresAt:X?.authorizationExpiresAt,serverSideCardGateway:pn});Fn.current={onComplete:c,onError:p,updateError:ze,emitDecline:$n,resolvedAccount:re,avsConfig:Ce,avsCheckProp:Ge,sessionId:e,nonce:t,baseUrl:vt,captureMethod:X?.captureMethod,paymentId:X?.paymentId,authorizationExpiresAt:X?.authorizationExpiresAt,serverSideCardGateway:pn};let Ui=(0,o.useRef)(!1),Vs=(0,o.useCallback)(()=>{let i=Fn.current,b=i.resolvedAccount.email?.trim(),$=(0,l.isValidEmail)(b)?b:Lr.current.trim();if(!(0,l.isValidEmail)($))return null;let _e=i.resolvedAccount.firstName?.trim(),G=i.resolvedAccount.lastName?.trim(),Te=sr.current.trim()||i.resolvedAccount.country?.trim()||"",$t=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.state,Te):!1,Pn=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.address_line_1,Te):!1,ft=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.postal_code,Te):!1,Ct=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.city,Te):!1,At=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.address_line_2,Te):!1,yr=Pn&&!$t&&ft?(0,l.getStateFromPostalCode)(Te,(Or.current??"").trim()):null,dn=$t?jt.current:yr;return{accountData:{userId:i.resolvedAccount.userId??"",email:$,..._e?{firstName:_e}:{},...G?{lastName:G}:{},...ft&&Or.current?{zip:Or.current}:{},...Ct&&Pr.current?{city:Pr.current}:{},...dn?{state:dn}:{},...Pn&&Qt.current?{addressLine1:Qt.current}:{},...At&&zr.current?{addressLine2:zr.current}:{},...Te?{country:Te}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,l.isAVSFieldVisible)(i.avsConfig.country,Te),postal_code:ft,address_line_1:Pn,address_line_2:At,city:Ct,state:$t}}:{}}},[]),Ws=(0,o.useRef)(C);Ws.current=C,(0,o.useEffect)(()=>{C||Ye!==tc||Fn.current.updateError(null)},[C,Ye]),(0,o.useEffect)(()=>{!ve||!at||at.setSubmitGate?.(Vr||C||Mo||Bt)},[ve,at,Vr,C,Mo,Bt]),(0,o.useEffect)(()=>{if(!ve||!at)return;Ui.current=!1;let i=null,b=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,ee.current="idle",oe(null)},400)},$=at.on("submitting",()=>{jn(!0),q.current&&clearTimeout(q.current),ee.current="validation-window",q.current=setTimeout(()=>{q.current=null,ee.current==="validation-window"&&(ee.current="processing")},$d),oe("processing");let ft=Fn.current;if(!ft.sessionId||!ft.nonce)return;let Ct=Vs();if(!Ct){ft.updateError("Enter a valid email address."),ee.current="idle",oe(null);return}new zn.PaymentAPI(ft.baseUrl).patchAccountSnapshot(ft.sessionId,ft.nonce,Ct,{telemetryMode:"best_effort"}).catch(At=>{if(!Kd(At))return;let yr=At instanceof Error?At.message:"Please check your billing address and try again.";ft.updateError(yr),ee.current="idle",oe(null),ft.onError?.(At instanceof l.FloPayError?At:new l.FloPayError(yr,"api_error"))})}),_e=at.on("complete",ft=>{(0,Nn.markSessionRecentlyCompleted)(ft.sessionId??Fn.current.sessionId),ee.current="terminal",Et(!1),oe("success"),setTimeout(()=>{if(Ui.current)return;Ui.current=!0;let Ct=Fn.current,At=(0,l.isAuthorizationOnlySession)(Ct)||ft.outcome==="authorized",yr=Ct.serverSideCardGateway?{}:{paymentIntentId:ft.intentId};Fn.current.onComplete?.(At?{status:"authorized",...yr,paymentId:ft.paymentId??Ct.paymentId,sessionId:ft.sessionId??Ct.sessionId,authorizationExpiresAt:ft.authorizationExpiresAt??Ct.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...yr,checkoutMethod:"card"})},600)}),G=at.on("decline",ft=>{let Ct=Fn.current,At=ft.message??"Your payment was declined. Please try another card or contact your bank.";ee.current="terminal",Et(!1),Ct.updateError(At),oe("error");let yr=ft.failureOutcome??(0,l.normalizeCheckoutFailureOutcome)(ft.declineReason)??"authorization_declined";Ct.emitDecline("card",At,{code:yr,declineCode:yr}),b()}),Te=at.on("error",ft=>{let Ct=Fn.current,At=(0,l.buyerEmailRequiredPrompt)(ft.vaultOutcome);if(At!==null){i&&(clearTimeout(i),i=null),ee.current="idle",Et(!1),Ct.updateError(At),oe(null),Ee(dn=>dn+1),Ct.onError?.(new l.FloPayError(At,"api_error",{code:l.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let yr=ft.message??"There was a problem processing your payment. Please try again.";ee.current="terminal",Et(!1),Ct.updateError(yr),oe("error"),Ct.onError?.(new l.FloPayError(yr,"api_error",{code:ft.failureOutcome??"capture_failed"})),b()}),$t=at.on("challenge_dismissed",()=>{q.current&&(clearTimeout(q.current),q.current=null),ee.current="processing",Et(!0),oe(null)}),Pn=at.on("blocked",()=>{if(x.current){Fn.current.updateError(Hd);return}if(!Ws.current){jn(!0);return}Ni(),Fn.current.updateError(tc)});return()=>{i&&(clearTimeout(i),i=null),q.current&&(clearTimeout(q.current),q.current=null),ee.current="idle",Et(!1),oe(null),$(),_e(),G(),Te(),$t(),Pn()}},[ve,at,Ni,Vs]);let Hn=!!ue?.clientId,aa=Array.isArray(A),za=aa&&A.length>0,$s=aa&&A.includes("paypal"),qa=(0,o.useRef)(null);qa.current===null&&(qa.current=(0,l.hasMatchingStripePayPalReturn)());let Bo=qa.current?"redirect":(0,Yn.resolveStripePayPalPresentation)(ot,Me,ne.current()),{expressMethods:ja,paymentElementMethods:zi}=(0,o.useMemo)(()=>(0,l.partitionStripeMethods)(A,{excludePaypal:Hn}),[A,Hn]),Hs=Hn||!!wt||$s&&Bo==="redirect",Oc=(0,o.useMemo)(()=>Hs?ja.filter(i=>i!=="paypal"):ja,[ja,Hs]),Lc=(0,o.useMemo)(()=>{let i=[];return he&&i.push("apple_pay"),fe&&i.push("google_pay"),i},[he,fe]),Do=aa?Oc:Lc,Nc=S&&Do.length>0,Ks=Nr?st:Se,Va=(0,o.useMemo)(()=>(0,l.filterStripeMethodsByCountryGate)(zi,Ks,ie),[zi,Ks,ie]),qi=(0,o.useMemo)(()=>({mode:"payment",amount:oa,currency:xo,paymentMethodCreation:"manual",appearance:Bs}),[oa,xo,Bs]),[Gs,Ys]=(0,o.useState)("loading"),[Xs,Js]=(0,o.useState)("loading"),[Zs,Qs]=(0,o.useState)("loading"),[Uc,ji]=(0,o.useState)(!1),[el,Vi]=(0,o.useState)("loading"),[Wi,zc]=(0,o.useState)();(0,o.useEffect)(()=>{zc((0,Gn.detectPayPalEnvironment)())},[]);let Wa=Wi?.inAppBrowser,$a=Wi?(0,Yn.resolvePayPalPresentationMode)(Wi,ue?.approvalPresentation,u??(pe?"subscription":"order")):"popup",tl=ge&&(Hn||(aa?$s:Wa===!1)),qc=ot.inAppBrowser&&ne.current()==="blocked",rl=S&&Nc&&!qc,ia=(!ce||!!ke.waitForDataAttachment)&&tl&&Hn,nl=el==="retrying"||el==="exhausted",sa=null;S&&(wt?sa=Fs:Bo==="redirect"&&(sa=cn));let ol=(0,o.useMemo)(()=>({...De,presentationMode:Bo}),[De,Bo]),la=!ce&&tl&&!!sa&&(!Hn||nl),Oo=!ce&&rl&&!!cn,ca=!ce&&S&&za&&Va.length>0&&!!cn,jc=ia&&!nl?Uc:la&&ds(Gs),Vc=Oo&&ds(Xs),Wc=ca&&Zs!=="load_error",al=i=>i==="loading"||i==="ready",il=ia||la&&al(Gs)||Oo&&al(Xs)||ca&&Zs!=="load_error",Ha=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Ha.current){if(!S&&!ge){Ha.current=!0;let i=new l.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),ze(i.message)}else if(!S&&ge&&!Hn){Ha.current=!0;let i=new l.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(i),ze(i.message)}else if(Wa!==void 0&&!ce&&!Lt&&!il){Ha.current=!0;let i=new l.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),ze(i.message)}}},[S,ge,Hn,Wa,ce,Lt,il,p,ze]);let sl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(sl.current||!za)return;let i=[];he!==!0&&i.push("showApplePay"),fe!==!0&&i.push("showGooglePay"),i.length!==0&&(sl.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.`))},[za,he,fe]);let ll=(0,o.useCallback)((i,b,$)=>ke.applyInlineSessionPatch?ke.applyInlineSessionPatch(i).then(_e=>({error:null,sessionId:_e.sessionId||e,nonce:_e.session?.clientSecret||t})).catch(_e=>{let G=(0,l.normalizeBeforeButtonClickError)(b,_e);return $?.abandoned?.()||(ze(G.message),p?.(G)),{error:G,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ke.applyInlineSessionPatch,t,p,e,ze]),Bn=(0,o.useCallback)(async(i,b)=>{if(i!=="card"&&ce&&await ke.waitForDataAttachment?.(),!Fe)return{proceed:!0};try{let $=await Fe({method:i,sessionId:e||void 0,createSession:ke.inlineSessionDraft});if($===!1)return{proceed:!1};if($&&typeof $=="object"){$.account&&Tt(G=>({...G??{},...$.account}));let _e=await ll($,i,b);return _e.error?{proceed:!1,accountPatch:$.account}:{proceed:!0,accountPatch:$.account,sessionId:_e.sessionId,nonce:_e.nonce}}return{proceed:!0}}catch($){if(!b?.abandoned?.()){let _e=(0,l.normalizeBeforeButtonClickError)(i,$);ze(_e.message),p?.(_e)}return{proceed:!1}}},[ll,ke.inlineSessionDraft,ke.waitForDataAttachment,ce,Fe,p,e,ze]),cl=(0,o.useCallback)(async(i,b)=>{if(it.current)return;it.current=!0,Ar(!0),oe("processing"),ze(null);let $=b?.sessionId??e,_e=b?.nonce??t,G=rs(re,b?.accountPatch),Te=b?.completionPaymentMethodId??Pa(i),$t=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,Pn=Jd(i),ft=b?.presentationMode?mi(Rr(rt),{...De,presentationMode:b.presentationMode}):void 0,Ct=()=>{v?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Pn}),ft?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Un,requestCategory:"process_payment"})};try{let At=new zn.PaymentAPI(vt),dn=b?.settledProcessResponse??await At.processPayment(G.userId??"",{sessionId:$,nonce:_e,paymentMethodCategory:b?.paymentMethodCategory??Qd(i),tokenizedData:$t,accountData:{...b?.accountPatch,userId:G.userId??"",email:G.email??"",firstName:G.firstName||void 0,lastName:G.lastName||void 0,...(0,l.buildProcessPaymentAvsAccount)({avsConfig:Ce,country:sr.current,zip:Or.current,city:Pr.current,state:jt.current,addressLine1:Qt.current,addressLine2:zr.current})},...(0,l.buildCheckoutProcessMetadata)({chv:H,avsCheck:Ge,checkoutType:$e,checkoutLayout:Rt,avsConfig:Ce,country:sr.current})}),Ja=async Tr=>{let Co=(0,l.isAuthorizationOnlySession)(X)||Tr?.status==="authorized";(0,Nn.markSessionRecentlyCompleted)($),ft?.terminal({outcome:"payment_succeeded",...Un}),oe("success"),I(null),await new Promise(fa=>setTimeout(fa,600));let Kn;typeof Tr?.paymentId=="string"?Kn=Tr.paymentId:X?.paymentId&&(Kn=X.paymentId);let bo;typeof Tr?.authorizationExpiresAt=="string"?bo=Tr.authorizationExpiresAt:X?.authorizationExpiresAt&&(bo=X.authorizationExpiresAt),c?.(Co?{status:"authorized",...Kn===void 0?{}:{paymentId:Kn},sessionId:typeof Tr?.sessionId=="string"?Tr.sessionId:$,...bo===void 0?{}:{authorizationExpiresAt:bo},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Te,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Te,checkoutMethod:i.isPaypal?"paypal":"card"})};if(dn.ok){await Ja(dn.status===204?null:await dn.json().catch(()=>null));return}let fr=await dn.json().catch(()=>null);if(fr?.type==="paypal_redirect_required"){let Tr=fr.threeDSecureToken,Co=fr.paymentMethodId||i.id||"";if(!rt||!Tr){oe("error"),ze("PayPal authorization required but no token provided.");return}try{let Kn=wt?.getRawProvider();if(!Kn){ze("PayPal is not available.");return}let bo={return_url:window.location.href};Co&&(bo.payment_method=Co);let{error:fa}=await Kn.confirmPayment({clientSecret:Tr,confirmParams:bo,redirect:"if_required"});if(fa){oe("error");let bl=fa.message??"PayPal payment failed.";ze(bl),$n("paypal",bl,{code:fa.code})}}catch(Kn){oe("error"),ze(Kn instanceof Error?Kn.message:"PayPal authorization failed.")}return}if(fr?.type==="paypal_direct_required"){let Tr=fr.orderId;if(!Tr){oe("error"),ze("PayPal retry required but no order id provided.");return}let Co=Le.current?.attempts??0;if(Co>=2){oe("error"),ze("PayPal payment could not be completed after multiple attempts."),$n("paypal","paypal_direct_required retry limit exceeded");return}ji(!1),Vi("loading"),I({orderId:Tr,attempts:Co+1}),oe(null);return}if(dn.headers.get(Nd)===Ud){let Tr=await zd(At,$,_e);if(Tr!==void 0){await Ja(Tr);return}}(0,l.classifyPaymentRejection)(dn.status,fr)?ft?.terminal({outcome:"payment_declined",...Un,terminalReason:"provider_declined"}):Ct(),oe("error");let Cl=fr?.message??"Payment failed. Please try again.";ze(Cl),$n(i.isPaypal?"paypal":"card",Cl,{code:fr?.code??fr?.gatewayErrorCode,declineCode:fr?.declineCode??fr?.gatewayDeclineReason}),await new Promise(Tr=>setTimeout(Tr,400))}catch(At){dc(At)||Ct(),oe("error"),ze(At instanceof Error?At.message:"An unexpected error occurred"),await new Promise(yr=>setTimeout(yr,400))}finally{Ar(!1),oe(null),it.current=!1}},[vt,e,t,re,Ce,Ge,$e,Rt,H,rt,wt,X,c,ze,$n,v,De]),Qr=(0,o.useCallback)((i,b)=>{E&&!b?.settledProcessResponse?E(i):cl(i,b)},[E,cl]),da=`${lc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(da);if(!i)return;let b;try{b=JSON.parse(i)}catch{ur(da);return}if(!b||typeof b.createdAt!="number"||Date.now()-b.createdAt<0||Date.now()-b.createdAt>cc||typeof b.paymentMethodId!="string"||typeof b.providerIntentId!="string"||typeof b.paymentMethodType!="string"||b.sessionId!==e||!t||b.nonce!==t||!Do.includes(b.paymentMethodType)){ur(da);return}ur(da),Qr({id:b.paymentMethodId,type:"card",threeDSecureActionResultTokenId:b.providerIntentId,gateway:"stripe",paymentMethodType:b.paymentMethodType},{...b.accountPatch?{accountPatch:b.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Qr,t,e,da,Do]);let dl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||dl.current)return;let[i,b,$]=(0,l.readStripeRedirectParams)();if(!i||!b||qa.current||!rt)return;let _e=rt.getRawProvider();if(!_e)return;let G=Ct=>{let At=localStorage.getItem(Ct);if(!At)return null;try{return JSON.parse(At)}catch{return ur(Ct),null}},Te=G(Jn)??G(Zl),$t;if(Te?.clientSecret){if(Te.clientSecret!==b)return;$t={...Te.accountPatch?{accountPatch:Te.accountPatch}:{},...Te.sessionId?{sessionId:Te.sessionId}:{},...Te.nonce?{nonce:Te.nonce}:{}}}else if(Te?.sessionId&&Te.sessionId!==e)return;dl.current=!0,ur(Jn),ur(Zl),window.history.replaceState({},"",(0,l.stripeRedirectReturnUrl)());let Pn=Te?.paymentMethodType??Te?.tokenType??"card",ft="card";(async()=>{if($==="failed"){let fr="Payment was declined. Please try again.";ze(fr),$n(ft,fr);return}let{paymentIntent:Ct,error:At}=await _e.retrievePaymentIntent(b);if(At){let fr=At.message??"Failed to retrieve payment status.";ze(fr),$n(ft,fr,{code:At.code});return}let yr=Ct?.status,dn=ha(yr);if(!Ct||!dn){let fr=yr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ze(fr),$n(ft,fr,{code:yr??"missing_payment_intent"});return}let Ja=typeof Ct.payment_method=="string"?Ct.payment_method:Ct.payment_method?.id;Qr({id:Ja??Te?.paymentMethodId??Te?.tokenId??Ct.id,type:"card",threeDSecureActionResultTokenId:Ct.id,gateway:Te?.gateway??"stripe",paymentMethodType:Pn},$t)})()},[e,Qr,rt,ze,$n]);let $i=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(ve||rt!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ua=Re==="buttons",en=Sr?.variables,$c=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Hi=en?.colorBackground,Hc=Hi&&!$c.has(Hi)?Hi:void 0,pa=de.cardInputBorder??(ua?"#e5e7eb":"#A4A4FF"),ul=en?.colorDanger??"#dc2626",or=i=>yn[i]&&(to[i]||lr),Ka=Mo&&(xn||lr),hn=i=>i?ul:pa,Ga=(rr.malformed||rr.empty)&&(Vn||lr),Kc=hn(Ga),Ki=de.cardFormContainer?.backgroundColor??Hc??(ua?"white":"#EDEDFF"),Lo=de.cardInputBackground??en?.colorBackground??"white",Gi=zo(Ue),pl=zo(ye),No=de.nameInput,ml=de.cardInputFontSize??nu(No?.fontSize)??en?.fontSizeBase??"16px",yl=typeof No?.fontFamily=="string"?No.fontFamily:en?.fontFamily??"Poppins, sans-serif",fl=(0,l.toCssWeight)(No?.fontWeight)??400,Gc=de.cardInputColor??(typeof No?.color=="string"?No.color:void 0)??en?.colorText??"#262833",Yc=de.cardInputPlaceholderColor??"#9ca3af",cr=en?.borderRadius??"8px",Po=en?.borderRadius??de.cardButton?.borderRadius??cr,vo=en?.colorPrimary??"#4A49FF",Xc=en?.colorPrimaryHover??(0,l.darkenHex)(vo,.12),Yi=en?.colorText??"#262833",Xi={fontSize:ml,fontFamily:yl,fontWeight:fl,color:Gc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ma={marginTop:"0.375rem",...Xi,fontSize:"0.75rem",lineHeight:1.4,color:ul},Jc={"--flopay-input-placeholder-color":Yc,"--flopay-input-font-size":ml,"--flopay-input-font-family":yl,"--flopay-input-font-weight":String(fl)},ya=de.cardFormContainer??{},Ji=ya.padding??(ua?"0":"1rem"),Zi=ya.borderRadius??cr,Zc=at&&Zr?(0,d.jsx)(ho,{capture:at,html:Zr.html,messageToken:Zr.messageToken,expectedOrigin:Zr.expectedOrigin,verificationRequired:Zr.verificationRequired,theme:Mt,submitLabel:Y,onReady:()=>{if(!yo&&!Ce||typeof document>"u"||L===!1)return;let i=()=>{let $=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if($){An.current=!0;try{$.focus()}finally{An.current=!1}}};Wn.current||i()},onError:i=>{i&&Zr.verificationRequired&&ee.current==="idle"&&(mo.current=!0),ze(i)},onValidation:i=>{let b=ee.current;(b==="idle"||b==="validation-window")&&(ze(i),i&&ee.current==="validation-window"&&(q.current&&(clearTimeout(q.current),q.current=null),ee.current="idle",oe(null)))}},qr):(0,d.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"}),gl=(0,d.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&ro()},style:{backgroundColor:Ki,borderRadius:Zi,...ya,padding:Ji,...Jc,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
|
|
30
|
+
`,So=44;function sa(){return(0,Ar.jsx)("style",{children:Vd})}function Aa(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function xa({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Ar.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Ar.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,Ar.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 gs(e){return e!=="unavailable"&&e!=="load_error"}function hi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:d,backgroundColor:p,borderColor:y,textColor:b,borderRadius:v,fontFamily:S}){let E=(0,po.resolveStripeMethodBrandVariant)(e,t),V=ac[e],[x,D]=(0,ic.useState)(!1),A=!!V&&!x,g=E?.backgroundColor??p??"#ffffff",O=E?.borderColor??y??"#d1d5db",ke=E?.textColor??b??"#262833";return(0,Ar.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:So,padding:"0 1rem",backgroundColor:g,color:ke,border:`1px solid ${O}`,borderRadius:v??8,fontSize:"0.95rem",fontWeight:600,fontFamily:S,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,Ar.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,po.getStripeMethodDisplayName)(e)}\u2026`}):(0,Ar.jsxs)(Ar.Fragment,{children:[(0,Ar.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,po.hasVendoredStripeMethodLogo)(e)?8:0},children:[A?(0,Ar.jsx)("img",{src:V,alt:"","aria-hidden":"true",onError:()=>D(!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&&E?.logoSvg?(0,Ar.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:E.logoSvg}}):null,(0,Ar.jsx)("span",{children:(0,po.getStripeMethodDisplayName)(e)})]}),s&&(0,Ar.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:ke,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,Ar.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Pi(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 vi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},Ci={type:"accordion",defaultCollapsed:!1,radios:"never"};function bi({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:d,children:p}){return(0,Ar.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 hs=require("react/jsx-runtime"),Wd=["first","second","third","fourth"];function Ps({rows:e,borderRadius:t}){return(0,hs.jsx)("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Wd.slice(0,Math.max(1,e)).map(r=>(0,hs.jsx)("div",{style:{height:So,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},r))})}var lc=require("@flopay/js"),Si=require("@flopay/shared"),wi=require("react"),$d=1500,sc=new Set;function cc(e){for(let t of e)sc.has(t)||(sc.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function Hd(e){if(e!=null)try{return JSON.stringify(e)}catch{return cc(["the rules could not be sent (they are not plain data), so the default layout applies."]),"{}"}}function dc({rules:e,sessionId:t,nonce:r,billingApiUrl:n}){let a=Hd(e),[s,d]=(0,wi.useState)(null);return(0,wi.useEffect)(()=>{if(a===void 0)return;let p=JSON.parse(a),y=!1,b=V=>{y||(y=!0,d(V))},v=()=>b((0,Si.resolvePaymentMethodOrder)(p.order));if(!t||!r||!n){v();return}let S=new AbortController,E=setTimeout(()=>{v(),S.abort()},$d);return new lc.PaymentAPI(n,{telemetry:!1}).resolvePaymentMethodLayout(t,r,p,{signal:S.signal}).then(V=>{if(!V){v();return}y||cc(V.warnings),b(V.order)}).catch(v).finally(()=>clearTimeout(E)),()=>{y=!0,clearTimeout(E),S.abort()}},[a,t,r,n]),a===void 0?Si.DEFAULT_PAYMENT_METHOD_ORDER:s}var un=require("react");var Fa=require("@flopay/shared"),Kd=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 Gd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Kd.has(t.charAt(0).toLowerCase()+t.slice(1))}function Yd(e,t){return typeof t=="number"&&t!==0&&!Gd(e)?`${t}px`:String(t).trim()}function uc(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]=Yd(r,n)}}}var xo=require("react/jsx-runtime"),vs=new WeakSet;function wo({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:d,containerStyle:p,onReady:y,onError:b,onValidation:v}){let S=(0,un.useRef)(null),E=(0,un.useRef)(y),V=(0,un.useRef)(b),x=(0,un.useRef)(v);E.current=y,V.current=b,x.current=v;let D=(0,un.useRef)(s);D.current=s;let A=(0,un.useRef)(null),g=d??void 0,O=(0,un.useRef)(g);O.current=g;let ke=(0,un.useRef)(void 0);return(0,un.useEffect)(()=>{let m=S.current;if(!m)return;let me=!0,_=!1,ne=()=>{!me||_||(_=!0,E.current?.())},fe=e.on("ready",()=>{ne()}),ce=e.on("error",L=>{V.current?.(L.message??"There was a problem loading the secure card form.")}),Ee=e.on("validation",L=>{x.current?.(L.message??null)}),vt=O.current??(vs.has(e)?null:void 0),ze={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...D.current?{theme:D.current}:{},...vt===void 0?{}:{submitLabel:vt}};return A.current=D.current??null,ke.current=O.current,O.current!==void 0&&vs.add(e),e.mount(m,ze).then(()=>{ne()}).catch(L=>{me&&V.current?.(L instanceof Error?L.message:"Failed to load the secure card form.")}),()=>{me=!1,fe(),ce(),Ee(),e.unmount()}},[e,t,r,n,a]),To(()=>{let m=S.current;m&&uc(m,p)},[p]),(0,un.useEffect)(()=>{s!==void 0&&(s===null&&A.current===null||(A.current=s,e.applyTheme?.(s)))},[e,s]),(0,un.useEffect)(()=>{g!==ke.current&&(ke.current=g,g!==void 0&&vs.add(e),e.setSubmitLabel?.(g??null))},[e,g]),(0,xo.jsx)("div",{ref:S,"data-testid":"flopay-vault-card-fields"})}function Ba({label:e}){return(0,xo.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,xo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,xo.jsx)("span",{children:e}),(0,xo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var Ms=require("@flopay/shared"),l=require("react/jsx-runtime"),Jn="flopay_stripe_resume",pc="flopay_wallet_resume",Sc="fw1",Xd="fw2",wc=300*1e3,Jd=900,Zd="express_checkout_click_timeout",Qd=25e3,eu=25e3,tu=1e4,jn={provider:"paypal",paymentMethodCategory:"paypal"},ru="x-flopay-process-result-source",nu="status";async function ou(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 Ri={},Oa=class{constructor(t){this.reason=t}};function au(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 _s(e){return`${Xd}:${e}`}function ki(e){return dr(_s(e))}function Ei(e,t){if(typeof window>"u")return null;let r=_s(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>wc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(ki(e),null):a}catch{return ki(e),null}}function iu(e){return dr(_s(e.sessionId),e)}function yc(e,t,r){let n=Ei(e,t);return!n||n.clientSecret!==r?!1:ki(e)}function Cs(e,t,r){if(typeof window>"u")return;Ei(e,t)?.clientSecret===r&&ki(e)}function su(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function bs(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":va(e.status),a=su(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function mc(e,t,r){let n=null;try{return await Promise.race([jl(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},tu),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function lu(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Rc(e){return e instanceof c.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function _i(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Vn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw Rc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var Ss=c.STRIPE_PAYPAL_RESUME_KEY,Da=new Map,cu=250,fc="Just a moment \u2014 we are finalizing your order. Please press pay again.",du="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Is(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 Ii({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new Vn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function uu(e){return e instanceof c.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function kc({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,Zo.splitFullName)(r),d=s.firstName?s:(0,Zo.splitFullName)(n?.name);return(0,wn.compactBuyerIdentity)({email:(0,c.isValidEmail)(a)?a:n?.email?.trim(),firstName:d.firstName,lastName:d.lastName})}async function pu({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let d=kc({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 La=180,gc=`flopay-card-enter ${La}ms cubic-bezier(0, 0, 0.2, 1) both`,hc=`flopay-card-exit ${La}ms cubic-bezier(0.4, 0, 0.2, 1) both`,yu=`flopay-buttons-enter ${La}ms cubic-bezier(0, 0, 0.2, 1) both`,mu=`flopay-buttons-exit ${La}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function fu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ts(e){return(0,c.derivePrimaryTileStyle)(e)}var gu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function hu(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 Rs={width:"100%",minHeight:So,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 Pc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ks(e){return e==="paypal"?"PayPal":(0,c.getStripeMethodDisplayName)(e)}function Pu(e){let t=(0,c.getPostalCodeExample)(e);return`Enter a valid ${(0,c.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function vu(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 Cu(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 bu(e){return typeof e=="number"?`${e}px`:e}function Ti(e){return(0,l.jsx)(Ru,{...e})}function vc({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:d=!1,onButtonClick:p,onDecline:y,onTechnicalFailure:b,runBeforeButtonClick:v,billingName:S,onBuyerIdentityReady:E,onLoadStateChange:V,placeholderBorderRadius:x,popupCapabilityOwner:D,externalTelemetryContext:A,presentationMode:g}){let O=co(),{emitInstrument:ke}=(0,o.useContext)(Sn),m=(0,cr.useStripe)(),me=(0,cr.useElements)(),_=(0,o.useMemo)(()=>gi(Er(O),A),[A,O]),[ne,fe]=(0,o.useState)("loading");(0,o.useEffect)(()=>{V?.(ne)},[ne,V]);let[ce,Ee]=(0,o.useState)(!1),vt=(0,o.useRef)(!1),ze=!(0,c.isValidEmail)(r?.trim())||!S?.trim(),{request:L,collect:Ye,finish:at}=Qo(),qe=(0,o.useRef)(!1),ye=(0,o.useRef)(null),N=(0,o.useRef)(null),[le,de]=(0,o.useState)(0),[rt,je]=(0,o.useState)(!1),Q=(0,o.useRef)(!1),W=(0,o.useRef)(new Map),{startAttempt:ee,finishAttempt:te,invalidateAttempt:ve,isAttemptInvalidated:ue,isAttemptCurrent:pe,generationRef:Fe}=wa((Ce,oe,Ze)=>{b?.(Ce,oe,{...Ze,popupBlocked:Ze?.popupBlocked??(0,Re.isPopupBlockedError)(oe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:g,terminalReason:"overlay_timeout"}),je(!0),de(J=>J+1)},{onHandoffObserved:()=>{D.markAvailable(),_?.log({name:"provider.popup.opened",stage:"overlay_open",...jn,attempt:Fe.current})}});(0,o.useEffect)(()=>{rt&&N.current?.focus()},[rt,le]);let ge=(0,o.useCallback)(()=>{de(Ce=>Ce+1)},[]),H=(0,o.useCallback)((Ce,oe,Ze)=>{ve(Ze),b?.("paypal",Ce,{code:oe,popupBlocked:(0,Re.isPopupBlockedError)(Ce),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:g}),je(!0),ge()},[ve,b,g,ge]),Be=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ye.current?.querySelector("iframe")??ye.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Q.current&&(Q.current=!1,Be())},[Be,le]);let ut=(0,o.useCallback)(()=>{je(!1),s?.(null),Be()},[Be,s]);(0,o.useEffect)(()=>{if(!m||qe.current)return;let[Ce,oe,Ze]=(0,c.readStripeRedirectParams)();if(!Ce||!oe)return;let J=(0,c.readMatchingStripePayPalContinuation)(oe);if(!J)return;qe.current=!0;let Ct=!0,Rt=Da.get(oe);Rt||(Rt=Ze==="failed"?Promise.resolve(null):Promise.resolve().then(()=>m.retrievePaymentIntent(oe)),Da.set(oe,Rt));let se={accountPatch:J.accountPatch,sessionId:J.sessionId,nonce:J.nonce},De=()=>{_?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...jn,requestCategory:"provider_sdk"})};return _?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...jn}),(async()=>{try{Ee(!0);let h=await Rt;if(!Ct)return;if(h?.error){Da.delete(oe),De(),s?.(h.error.message??"Failed to retrieve PayPal payment status.");return}if((0,c.clearStripePayPalReturn)(),Da.delete(oe),Ze==="failed"){let he="PayPal payment was declined. Please try again.";_?.terminal({outcome:"payment_declined",...jn,terminalReason:"provider_declined"}),s?.(he),y?.(kr("paypal",he));return}let U=h?.paymentIntent;if(U&&U.id!==Ce){De(),s?.("Failed to match the returned PayPal payment.");return}if(U&&(U.status==="requires_capture"||U.status==="succeeded")){let he=typeof U.payment_method=="string"?U.payment_method:U.payment_method?.id;a({id:he??U.id,type:"card",threeDSecureActionResultTokenId:U.id,isPaypal:!0},{...se,presentationMode:"redirect"})}else{let he="PayPal payment was not completed. Please try again.";_?.terminal({outcome:U?.status==="canceled"?"payment_cancelled":"payment_declined",...jn,terminalReason:U?.status==="canceled"?"cancelled":"provider_declined"}),s?.(he),y?.(kr("paypal",he))}}catch(h){if(!Ct)return;Da.delete(oe),De(),s?.(h instanceof Error?h.message:"Failed to complete PayPal payment.")}finally{Ct&&Ee(!1)}})(),()=>{Ct=!1,qe.current=!1}},[m,a,s,y,_]);let Xe=(0,o.useCallback)(async(Ce=!1)=>{let oe=v?await v("paypal"):{proceed:!0};if(!oe.proceed)return W.current.delete(le),!1;let Ze=ee("paypal");return W.current.set(le,{generation:Ze,accountPatch:oe.accountPatch,sessionId:oe.sessionId,nonce:oe.nonce}),je(!1),_?.log({name:`provider.${Ce?"redirect.started":"handoff.requested"}`,stage:Ce?"redirect":"overlay_open",...jn,attempt:Ze}),p?.("paypal"),!0},[p,_,v,ee,le]),nt=(0,o.useCallback)(async Ce=>{if(d||ce||!await Xe()){Ce.reject();return}Ce.resolve()},[d,Xe,ce]),it=(0,o.useCallback)(async Ce=>{if(!m||!me)return;let oe=W.current.get(le);if(oe&&!pe(oe.generation)){W.current.delete(le);return}if(!oe&&ue()||oe&&!te(oe.generation))return;oe||te();let Ze=oe??null;if(W.current.delete(le),!Ze&&v){let It=await v("paypal");if(!It.proceed){Ce.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Ze={accountPatch:It.accountPatch,sessionId:It.sessionId,nonce:It.nonce}}let J=Ze?.sessionId??e,Ct=Ze?.nonce??t,Rt=await pu({event:Ce,prepared:Ze,email:r,billingName:S,methodLabel:"PayPal",collect:Ye});if(!Rt){Ce.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let se=Rt.email,De={...Ze?.accountPatch,...(0,wn.compactBuyerIdentity)(Rt,!0)};try{if(Ee(!0),s?.(null),!J||!(0,c.isValidEmail)(se))throw new Error("Missing sessionId or email for PayPal payment");await E?.(Rt);let It=m.createPaymentMethod,{error:h,paymentMethod:U}=await It({type:"paypal"});if(h){H(h,"stripe_paypal_create_payment_method_failed",oe?.generation),Ce.paymentFailed({reason:"fail"});return}let he=await _i(n,ke,J,Ct??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:U?.id??null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(he)){Ce.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:De,paymentMethodCategory:"paypal",presentationMode:g,sessionId:J,nonce:Ct,settledProcessResponse:he.response});return}if(he.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ae=he.clientSecret,Wt={return_url:(0,c.stripeRedirectReturnUrl)()};if(U?.id&&(Wt.payment_method=U.id),!dr(Ss,{clientSecret:ae,sessionId:J,nonce:Ct,accountPatch:De})&&g==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Ae,paymentIntent:be}=await m.confirmPayment({clientSecret:ae,confirmParams:Wt,redirect:"if_required"});if(Ae){if(dr(Ss),(0,Re.isProviderDecline)(Ae)){let u=Ae.message??"Your payment was declined.";_?.terminal({outcome:"payment_declined",...jn,terminalReason:"provider_declined"}),s?.(u),y?.(kr("paypal",u,{code:(0,Re.getProviderErrorCode)(Ae),declineCode:(0,Re.getProviderDeclineCode)(Ae)})),await Ii({billingApiUrl:n,sessionId:J,nonce:Ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,Re.getProviderErrorCode)(Ae)??"provider_declined"}})}else H(Ae,"stripe_paypal_confirm_failed",oe?.generation);return}dr(Ss);let bt=typeof be?.payment_method=="string"?be.payment_method:be?.payment_method?.id;a({id:bt??be?.id,type:"card",threeDSecureActionResultTokenId:be?.id,isPaypal:!0},{accountPatch:De,paymentMethodCategory:"paypal",presentationMode:g,sessionId:J,nonce:Ct});return}catch(It){H(It,"stripe_paypal_failed",oe?.generation)}finally{Ee(!1)}},[m,me,e,t,r,S,Ye,E,n,ke,a,s,y,v,H,te,pe,ue,_,g,le]),or=(0,o.useCallback)(async()=>{if(!(vt.current||d||ce||!m||!me)){vt.current=!0,Ee(!0);try{if(!await Xe(!0))return;await it({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{vt.current=!1,Ee(!1)}}},[me,it,d,Xe,m,ce]),_t=g==="redirect"?(0,l.jsx)("button",{type:"button",disabled:d||ce,onClick:()=>{or()},style:{width:"100%",minHeight:So,border:"1px solid #d1d5db",borderRadius:x??8,background:"#ffc439",color:"#111827",cursor:d||ce?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,l.jsx)(cr.ExpressCheckoutElement,{onReady:Ce=>fe(Aa(Ce,["paypal"])),onLoadError:()=>{fe("load_error"),Is(_,"paypal","paypal","provider_error")},onClick:nt,onConfirm:it,onCancel:()=>{let Ce=W.current.get(le);W.current.delete(le),_?.terminal({outcome:"payment_cancelled",...jn,terminalReason:"cancelled",...Ce?{attempt:Ce.generation}:{}}),ve(Ce?.generation),je(!1),Q.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ze,emailRequired:ze,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},le),qt=(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{ref:ye,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[rt&&(0,l.jsx)("button",{ref:N,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ut,style:Rs,children:"Try PayPal again"}),L&&(0,l.jsx)(ea,{identity:L.identity,methodLabel:L.methodLabel,onComplete:at,onCancel:()=>at(null)},L.id),(0,l.jsx)("div",{style:{display:L?"none":void 0},children:_t})]}),ce&&!L&&(0,l.jsx)(on,{status:"processing"})]});return g==="redirect"?qt:(0,l.jsx)(xa,{state:ne,placeholderTestId:"flopay-paypal-placeholder",borderRadius:x,children:qt})}function ws(e){return e==="apple_pay"||e==="google_pay"}var Su=200;function wu({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,c.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function Cc({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:d,onErrorChange:p,onButtonClick:y,onDecline:b,onTechnicalFailure:v,runBeforeButtonClick:S,billingName:E,onBuyerIdentityReady:V,onLoadStateChange:x,placeholderBorderRadius:D,popupCapabilityOwner:A,externalTelemetryContext:g}){let O=co(),{emitInstrument:ke}=(0,o.useContext)(Sn),m=(0,cr.useStripe)(),me=(0,cr.useElements)(),_=(0,o.useMemo)(()=>gi(Er(O),g),[g,O]),[ne,fe]=(0,o.useState)("loading");(0,o.useEffect)(()=>{x?.(ne)},[ne,x]);let[ce,Ee]=(0,o.useState)(!1);(0,o.useEffect)(()=>{je.current=ce},[ce]);let vt=(0,o.useRef)(!(0,c.isValidEmail)(r?.trim())||!E?.trim()).current,{request:ze,collect:L,finish:Ye}=Qo(),at=(0,o.useRef)(null),qe=(0,o.useRef)(null),[ye,N]=(0,o.useState)(0),[le,de]=(0,o.useState)(()=>(0,c.shouldPreferWalletPopup)()),rt=(0,o.useRef)(le),je=(0,o.useRef)(!1),[Q,W]=(0,o.useState)(!1),[ee,te]=(0,o.useState)(()=>Ei(e,t)?"blocked":"idle"),[ve,ue]=(0,o.useState)("google_pay"),pe=(0,o.useRef)(null),Fe=(0,o.useRef)(!0),ge=(0,o.useRef)(!1),H=(0,o.useRef)("google_pay"),Be=(0,o.useRef)("google_pay"),ut=(0,o.useRef)(null),Xe=(0,o.useRef)(null),nt=(0,o.useRef)(new Set),it=(0,o.useRef)(null),or=(0,o.useRef)(null);(0,o.useEffect)(()=>(Fe.current=!0,()=>{Fe.current=!1;for(let u of nt.current)window.clearTimeout(u);nt.current.clear()}),[]);let _t=(0,o.useRef)(new Map),{startAttempt:qt,finishAttempt:Ce,invalidateAttempt:oe,isAttemptInvalidated:Ze,isAttemptCurrent:J,generationRef:Ct}=wa((u,B,I)=>{v?.(u,B,{...I,popupBlocked:I?.popupBlocked??(0,Re.isPopupBlockedError)(B),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ue(u),W(!0),N(xe=>xe+1)},{onHandoffObserved:u=>{or.current=Ct.current,A.markAvailable(),_?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Ct.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})},defersMissingTerminal:ws,onMissingTerminalDeferred:(u,B)=>{let I=_?.now()??globalThis.performance?.now()??Date.now(),xe=it.current,z=xe?.generation===B?xe.startedAt:I;_?.performance({stage:"overlay_return",durationMs:Math.max(0,I-z),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:B,...ws(u)?{walletType:u}:{}}),_?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{Q&&qe.current?.focus()},[Q,ye]);let Rt=(0,o.useRef)(0),se=(0,o.useRef)(!1),De=(0,o.useCallback)(()=>{if(Rt.current>0){se.current=!0;return}N(u=>u+1)},[]),It=(0,o.useCallback)(()=>{Rt.current-=1,!(Rt.current>0||!se.current)&&(se.current=!1,Fe.current&&N(u=>u+1))},[]),h=(0,o.useCallback)((u,B,I,xe,z=!1)=>{oe(xe),v?.(u,B,{code:I,popupBlocked:(0,Re.isPopupBlockedError)(B),telemetryReported:z,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ue(u),W(!0),De()},[oe,v,De]),U=(0,o.useCallback)(u=>{_?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...ws(u)?{walletType:u}:{}}),v?.(u,new Error("The wallet click was not ready within the time the wallet allows."),{code:Zd,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ue(u),W(!0)},[v,_]),he=(0,o.useCallback)(()=>{window.setTimeout(()=>{(at.current?.querySelector("iframe")??at.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{ge.current&&(ge.current=!1,he())},[he,ye]);let ae=(0,o.useCallback)(()=>{W(!1),p?.(null),he()},[he,p]),Wt=(0,o.useCallback)(()=>{pe.current?.()},[]);(0,o.useEffect)(()=>{let u=null,B=()=>{u=null;let xe=(0,c.shouldPreferWalletPopup)();xe!==rt.current&&(rt.current=xe,de(xe),!je.current&&!J(Ct.current)&&De())},I=()=>{u!==null&&window.clearTimeout(u),u=window.setTimeout(B,Su)};return window.addEventListener("resize",I),()=>{window.removeEventListener("resize",I),u!==null&&window.clearTimeout(u)}},[Ct,J,De]),(0,o.useEffect)(()=>{let u=Ei(e,t);if(!u)return;let B=!1,I=!1,xe=async()=>{if(!I){I=!0,B||te("checking");try{let z=await mc(m,u.clientSecret,nt.current);if(B)return;let F=bs(z,u.providerObjectId,(0,c.isSetupIntentClientSecret)(u.clientSecret));if(F.kind==="confirmed"){if(!yc(e,t,u.clientSecret))return;pe.current=null,te("idle"),d({id:F.paymentMethodId,type:"card",threeDSecureActionResultTokenId:F.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(F.kind==="terminal"){Cs(e,t,u.clientSecret),pe.current=null,te("idle"),ue(u.paymentMethodType),W(!0),De();return}te("blocked")}catch{B||te("blocked")}finally{I=!1}}};return pe.current=xe,te("blocked"),()=>{B=!0,pe.current===xe&&(pe.current=null)}},[t,d,De,e,m]);let Bt=(0,o.useCallback)(async u=>{let B=!1,I=!1,xe=ot=>{B||I||(B=!0,u.paymentFailed({reason:"fail",...ot?{message:ot}:{}}))};if(!m||!me){xe();return}let z=_t.current.get(ye);if(z&&!J(z.generation)){_t.current.delete(ye),xe();return}if(!z&&Ze()){xe();return}if(z&&!Ce(z.generation)){xe();return}z||(Ce(),se.current=!1);let F=u.expressPaymentType??z?.method??H.current,$e=z??null,ar=Pc(F),tr;F==="apple_pay"?tr="apple_pay":F==="google_pay"&&(tr="google_pay");let br=z?.generation??Ct.current,Tt=_,Zr=Tt?.now()??globalThis.performance?.now()??Date.now(),pn=new AbortController,sn=!1,jt=!1,Dt=null,yn=e,Yt="processing",ln="other",pr="provider_runtime",Mn,Jt=new Promise((ot,At)=>{Mn=At}),ir=window.setTimeout(()=>{sn=!0,pn.abort(),Mn(Ri)},Qd),Qr=async(ot,At,Or)=>{Yt=ot,ln=At,pr=At==="intent_create"||At==="session_claim"?"transport_error":"provider_runtime";let Lr=Tt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Or,Jt])}finally{let Ir=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.performance({stage:ot,durationMs:Math.max(0,Ir-Lr),durationMode:"machine",requestCategory:At,paymentMethodCategory:"wallet",provider:"stripe",...sn?{statusClass:"timeout"}:{}})}};try{if(Ee(!0),p?.(null),!$e&&S){let _e=await Qr("processing","other",S(ar));if(!_e.proceed){xe();return}$e={accountPatch:_e.accountPatch,sessionId:_e.sessionId,nonce:_e.nonce}}let ot=$e?.sessionId??e;yn=ot;let At=$e?.nonce??t,Or=ut.current??$e?.accountPatch,Lr=kc({event:u,fallbackEmail:Or?.email??r,fallbackName:[Or?.firstName,Or?.lastName].join(" ").trim()||E});if(!(0,c.isValidEmail)(Lr.email)){xe("Buyer details are required."),L(ks(F),Lr).then(_e=>{_e&&(ut.current=_e)});return}ut.current=null;let Ir={...$e?.accountPatch,...(0,wn.compactBuyerIdentity)(Lr,!0)};await Qr("processing","session_claim",Promise.resolve(V?.(Lr)));let{error:jr}=await Qr("tokenization","provider_sdk",me.submit());if(jr){xe(),h(F,jr,"stripe_wallet_submit_failed",z?.generation);return}if(!ot)throw new Error("Missing sessionId or email for payment.");let Fr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:F,paymentMethodId:null,intentKind:a},Zt=JSON.stringify({sessionId:ot,nonce:At??"",request:Fr}),Sr=Xe.current,wr=Sr?.retryIdentity===Zt?Sr.authorizationAttemptId:(0,c.randomUuidV4)();Xe.current={authorizationAttemptId:wr,retryIdentity:Zt};let rr=await Qr("processing","intent_create",_i(n,ke,ot,At??"",{...Fr,authorizationAttemptId:wr},{signal:pn.signal}));if((0,c.isSettledSessionIntent)(rr)){xe(),d({type:"card",paymentMethodType:F},{accountPatch:Ir,paymentMethodCategory:"wallet",sessionId:ot,nonce:At,settledProcessResponse:rr.response});return}if(rr.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Xt=rr.clientSecret,Vr=iu({createdAt:Date.now(),sessionId:ot,...At?{nonce:At}:{},clientSecret:Xt,providerObjectId:rr.providerObjectId,paymentMethodType:F,accountPatch:Ir});window.clearTimeout(ir),jt=!0,Tt?.performance({stage:"callback",durationMs:Math.max(0,(Tt?.now()??globalThis.performance?.now()??Date.now())-Zr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Nr=Tt?.now()??globalThis.performance?.now()??Date.now(),He={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...tr?{walletType:tr}:{},attempt:br},Ur=!1,Wr=null;Tt?.log({name:"payment.provider_confirmation.started",...He}),Dt=window.setTimeout(()=>{Dt!==null&&nt.current.delete(Dt),Ur=!0;let _e=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...He,operationOutcome:"watchdog_expired",durationMs:Math.max(0,_e-Nr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Tt?.flush?.().catch(()=>{}),Wr?.()},eu),nt.current.add(Dt);let An=(_e,Ut)=>{Dt!==null&&(window.clearTimeout(Dt),nt.current.delete(Dt),Dt=null);let Ot=Tt?.now()??globalThis.performance?.now()??Date.now(),$t=Math.max(0,Ot-Nr),We=_e;Ur&&(_e==="resolved"?We="resolved_late":_e==="returned_error"?We="returned_error_late":We="rejected_late");let $r=Ut??(_e==="resolved"?"approved":"provider_error");return Tt?.log({name:"payment.provider_confirmation.returned",...He,operationOutcome:We,terminalReason:$r}),Tt?.performance({...He,durationMs:$t,durationMode:"buyer",operationOutcome:We,terminalReason:$r}),{durationMs:$t,operationOutcome:We,terminalReason:$r}},zr=!1,Qt=!1,sr=_e=>{if(!_e||typeof _e!="object")return null;let Ut=_e;if(Ut.error)return null;let Ot=Ut.setupIntent??Ut.paymentIntent,$t=bs(Ot??null,void 0,!!Ut.setupIntent);return $t.kind==="confirmed"?$t:null},en=_e=>{if(zr||z&&Ct.current!==z.generation)return;let Ut=sr(_e);if(!Ut)return;if(Vr&&!yc(ot,At,Xt)){zr=!0;return}let{intentId:Ot,paymentMethodId:$t}=Ut;zr=!0,Qt=!0,Xe.current=null,pe.current=null,Fe.current&&(te("idle"),Ee(!1));let We=`${Sc}:${ot}`;dr(We,{createdAt:Date.now(),sessionId:ot,nonce:At,accountPatch:Ir,paymentMethodId:$t,providerIntentId:Ot,paymentMethodType:F});try{d({id:$t,type:"card",threeDSecureActionResultTokenId:Ot},{accountPatch:Ir,paymentMethodCategory:"wallet",sessionId:ot,nonce:At})}finally{dr(We)}},yr=!1;Wr=async()=>{if(!(yr||zr||Qt)){yr=!0,Fe.current&&te("checking");try{let _e=await mc(m,Xt,nt.current);if(zr||Qt)return;let Ut=(0,c.isSetupIntentClientSecret)(Xt),Ot=bs(_e,rr.providerObjectId,Ut);if(Ot.kind==="confirmed"){en(Ut?{setupIntent:_e}:{paymentIntent:_e});return}if(Ot.kind==="terminal"){if(Qt=!0,Cs(ot,At,Xt),Xe.current=null,pe.current=null,!Fe.current)return;te("idle"),xe(),h(F,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",z?.generation,!0);return}Fe.current&&!Qt&&(te("blocked"),Ee(!1))}catch{Fe.current&&!Qt&&(te("blocked"),Ee(!1))}finally{yr=!1}}},pe.current=Wr;let C,kt;try{I=!0,Rt.current+=1;let _e;try{_e=await((0,c.isSetupIntentClientSecret)(Xt)?m.confirmSetup({elements:me,clientSecret:Xt,redirect:"if_required"}):m.confirmPayment({elements:me,clientSecret:Xt,redirect:"if_required"}))}finally{It()}if(!_e||typeof _e!="object")throw new Oa(au(_e));if(C=_e,!C.error&&!sr(C))throw new Oa("confirmation_result_unconfirmed");kt=An(C.error?"returned_error":"resolved",C.error&&(0,Re.isProviderDecline)(C.error)?"provider_declined":void 0)}catch(_e){let Ut=_e instanceof Oa?_e.reason:void 0,Ot=Ut!==void 0,$t=An(Ot?"returned_error":"rejected");if(Tt?.error({...Ot?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Ut}:cs(_e),...He,operationOutcome:$t.operationOutcome,durationMs:$t.durationMs,statusClass:"unknown",terminalReason:$t.terminalReason}),!Fe.current||zr)return;await Wr?.();return}let ie=C.error;if(ie){if(!Fe.current||zr)return;if((0,Re.isProviderDecline)(ie)){Qt=!0,Cs(ot,At,Xt),Xe.current=null,pe.current=null,te("idle"),_t.current.get(ye)===z&&_t.current.delete(ye);let _e=ie.message??"Your payment was declined.";p?.(_e),b?.(kr(ar,_e,{code:(0,Re.getProviderErrorCode)(ie),declineCode:(0,Re.getProviderDeclineCode)(ie)})),Ii({billingApiUrl:n,sessionId:ot,nonce:At,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:F,providerDeclineReason:(0,Re.getProviderErrorCode)(ie)??"provider_declined",...rr.intentKind==="payment"&&rr.providerObjectId.startsWith("pi_")?{providerIntentId:rr.providerObjectId}:{}}})}else Tt?.error({...cs(ie),...He,operationOutcome:kt.operationOutcome,durationMs:kt.durationMs,statusClass:"unknown",terminalReason:kt.terminalReason}),await Wr?.();return}if(en(C),!zr)throw new Error("Invalid provider returned for APM intent")}catch(ot){if(ot===Ri){let At=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.error({errorCode:lu(ln),stage:Yt,requestCategory:ln,paymentMethodCategory:"wallet",provider:"stripe",...tr?{walletType:tr}:{},operationOutcome:"watchdog_expired",checkoutSessionId:yn,durationMs:Math.max(0,At-Zr),statusClass:"timeout",failureCategory:pr,attempt:br,terminalReason:"provider_error"}),Tt?.flush?.().catch(()=>{})}xe(),h(F,ot,ot===Ri?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",z?.generation,ot===Ri)}finally{if(window.clearTimeout(ir),Dt!==null&&(window.clearTimeout(Dt),nt.current.delete(Dt)),!jt){let ot=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.performance({stage:"callback",durationMs:Math.max(0,ot-Zr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...sn?{statusClass:"timeout"}:{}})}Fe.current&&Ee(!1)}},[m,me,e,t,r,E,L,V,n,ke,a,d,p,b,S,h,It,Ce,J,Ze,Ct,_,ye]),Ae=(0,o.useMemo)(()=>Pi(s),[s]),be=(0,o.useMemo)(()=>s.map(c.stripeExpressMethodToOptionKey),[s]),bt=(0,o.useMemo)(()=>(0,l.jsx)(cr.ExpressCheckoutElement,{onReady:u=>{fe(Aa(u,be))},onLoadError:u=>{fe("load_error"),Is(_,"stripe","wallet","provider_error")},onClick:async u=>{let B=_?.now()??globalThis.performance?.now()??Date.now();H.current=u.expressPaymentType,Be.current=Pc(u.expressPaymentType);let I=!0,xe=window.setTimeout(()=>{I=!1,u.reject(),U(u.expressPaymentType)},Jd),z=S?await S(Be.current,{abandoned:()=>!I}):{proceed:!0};if(window.clearTimeout(xe),!I)return;if(!z.proceed){_t.current.delete(ye),u.reject();return}let F=qt(u.expressPaymentType);se.current=!1,it.current={generation:F,startedAt:B},_t.current.set(ye,{generation:F,method:u.expressPaymentType,accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}),W(!1),_?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:F,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),y?.(Be.current),u.resolve()},onConfirm:Bt,onCancel:()=>{let u=_t.current.get(ye);_t.current.delete(ye);let B=it.current,I=_?.now()??globalThis.performance?.now()??Date.now();if(u&&B?.generation===u.generation&&(0,c.isWalletSheetRefusedForWindowSize)({method:u.method,elapsedMs:I-B.startedAt,handoffObserved:or.current===u.generation})){_?.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"}),Xe.current=null,h(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}_?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),oe(u?.generation),Xe.current=null,W(!1),ge.current=!0,De()},options:{...vi,paymentMethods:Ae,emailRequired:vt,billingAddressRequired:vt}},ye),[be,Ae,Bt,oe,y,vt,h,U,De,S,qt,ye,_]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(xa,{state:ne,placeholderTestId:"flopay-wallet-placeholder",borderRadius:D,children:(0,l.jsxs)("div",{ref:at,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Q&&(0,l.jsxs)("button",{ref:qe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ae,style:Rs,children:["Try ",ks(ve)," again"]}),ee!=="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:Wt,disabled:ee==="checking",style:Rs,children:ee==="checking"?"Checking payment status\u2026":"Check payment status"})]}),ze&&(0,l.jsx)(ea,{identity:ze.identity,methodLabel:ze.methodLabel,onComplete:Ye,onCancel:()=>Ye(null)},ze.id),(0,l.jsxs)("div",{style:{display:ze||ee!=="idle"?"none":void 0},children:[(0,l.jsx)(wu,{active:le}),bt]})]})}),ce&&(0,l.jsx)(on,{status:"processing"})]})}function Ec(e,t,r){let n=(0,c.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function Es({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:d,onTokenizedBody:p,onErrorChange:y,onDecline:b,onCancel:v,runBeforeButtonClick:S,onButtonClick:E,isProcessing:V,submitButtonColor:x,submitButtonBorderRadius:D,submitButtonStyle:A,errorText:g}){let O=co(),{emitInstrument:ke}=(0,o.useContext)(Sn),m=(0,cr.useStripe)(),me=(0,cr.useElements)(),[_,ne]=(0,o.useState)(!1),fe=(0,o.useRef)(!1),[ce,Ee]=(0,o.useState)(!1),[vt,ze]=(0,o.useState)("loading"),[L,Ye]=(0,o.useState)(""),at=!(0,c.isValidEmail)(n?.trim()),qe=!at||(0,c.isValidEmail)(L.trim()),ye=(0,o.useCallback)(async()=>{if(!m||!me||V||fe.current||!ce)return;fe.current=!0,ne(!0);let N=S?await S("card"):{proceed:!0};if(!N.proceed){fe.current=!1,ne(!1);return}E?.("card");let le=N.sessionId??t,de=N.nonce??r,rt=(0,Zo.splitFullName)(a?.trim()),je=(0,wn.compactBuyerIdentity)({email:N.accountPatch?.email?.trim()||n?.trim()||L.trim(),firstName:N.accountPatch?.firstName?.trim()||rt.firstName,lastName:N.accountPatch?.lastName?.trim()||rt.lastName}),Q=je.email,W=(0,wn.compactBuyerIdentity)({...N.accountPatch,...je});try{if(y?.(null),!(0,c.isValidEmail)(Q))throw new Error("A valid email address is required for payment.");await s?.(je);let ee=await me.submit();if(ee.error){y?.(ee.error.message??"Payment failed.");return}let te=[je.firstName,je.lastName].filter(Boolean).join(" "),ve=await m.createPaymentMethod({elements:me,params:{billing_details:{email:Q,...te?{name:te}:{}}}});if(ve.error||!ve.paymentMethod){y?.(ve.error?.message??"Failed to create payment method.");return}let ue=ve.paymentMethod;if(!le||!Q)throw new Error("Missing sessionId or email for payment.");let pe=ue.type||e,Fe=await _i(d,ke,le,de??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:pe,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(Fe)){p({type:"card",gateway:"stripe",paymentMethodType:pe},{accountPatch:W,paymentMethodCategory:"apm",sessionId:le,nonce:de,settledProcessResponse:Fe.response});return}if(Fe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ge=Fe.clientSecret;dr(Jn,{clientSecret:ge,sessionId:le,nonce:de,accountPatch:W,paymentMethodId:ue.id,paymentMethodType:ue.type??e,gateway:"stripe"});let{error:H,paymentIntent:Be}=await m.confirmPayment({clientSecret:ge,confirmParams:{return_url:window.location.href,payment_method:ue.id},redirect:"if_required"});if(H){dr(Jn);let nt=H.message??"Payment failed.";y?.(nt),b?.(kr("card",nt,{code:H.code})),await Ii({billingApiUrl:d,sessionId:le,nonce:de,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:H.code??"provider_declined"}});return}let ut=Be?.status;if(!va(ut)){dr(Jn);let nt=ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(nt),b?.(kr("card",nt,{code:ut??"missing_payment_intent"}));return}dr(Jn);let Xe=typeof Be?.payment_method=="string"?Be.payment_method:Be?.payment_method?.id;p({id:Xe??ue.id,type:"card",threeDSecureActionResultTokenId:Be?.id,gateway:"stripe",paymentMethodType:ue.type??e},{accountPatch:W,paymentMethodCategory:"apm",sessionId:le,nonce:de})}catch(ee){y?.(ee instanceof Error?ee.message:"Payment failed. Please try again.")}finally{fe.current=!1,ne(!1)}},[m,me,V,ce,S,E,t,r,n,a,L,s,d,ke,e,p,y,b]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[at&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:at&&(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:L,onChange:N=>Ye(N.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(cr.PaymentElement,{onReady:()=>ze("ready"),onLoadError:()=>{ze("load_error"),Is(Er(O),"stripe","apm")},onChange:N=>{Ee(!!N.complete)},options:{layout:Ci,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,c.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,l.jsx)(bi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ye()},disabled:!ce||!qe||_||V||vt!=="ready",color:x,borderRadius:D,style:A,children:_?"Processing\u2026":`Pay with ${(0,c.getStripeMethodDisplayName)(e)}`}),g&&(0,l.jsx)(na,{margin:"0.75rem 0 0",children:g})]})}function bc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:d,stripeInstance:p,paymentElementBaseOptions:y,futureUseSession:b,onTokenizedBody:v,onErrorChange:S,onButtonClick:E,onDecline:V,runBeforeButtonClick:x,onLoadStateChange:D,isProcessing:A=!1,submitButtonColor:g="#4A49FF",submitButtonBorderRadius:O=8,submitButtonStyle:ke,buttonAppearance:m,themeId:me,onExpandApm:_,expandedApmMethod:ne}){let{emitInstrument:fe}=(0,o.useContext)(Sn),[ce,Ee]=(0,o.useState)(null),[vt,ze]=(0,o.useState)(null),L=(0,o.useRef)(!1),{request:Ye,collect:at,finish:qe}=Qo();(0,o.useEffect)(()=>{d.length>0&&p?D?.("ready"):p||D?.("loading")},[d.length,p,D]);let ye=(0,o.useCallback)(async Q=>{if(!p||L.current||A)return;L.current=!0,ze(Q);let W=x?await x("card"):{proceed:!0};if(!W.proceed){L.current=!1,ze(null);return}E?.("card");let ee=W.sessionId??e,te=W.nonce??t,ve=(0,Zo.splitFullName)([W.accountPatch?.firstName,W.accountPatch?.lastName].filter(Boolean).join(" ")||n),ue=(0,wn.compactBuyerIdentity)({email:W.accountPatch?.email?.trim()||r?.trim(),firstName:W.accountPatch?.firstName?.trim()||ve.firstName,lastName:W.accountPatch?.lastName?.trim()||ve.lastName});if(!(0,c.isValidEmail)(ue.email)){ze(null);let ge=await at((0,c.getStripeMethodDisplayName)(Q),ue);if(!ge){L.current=!1;return}ue=ge,ze(Q)}let pe=ue.email,Fe=(0,wn.compactBuyerIdentity)({...W.accountPatch,...ue});try{if(S?.(null),!ee||!(0,c.isValidEmail)(pe))throw new Error("Missing sessionId or email for payment.");await a?.(ue);let ge=await _i(s,fe,ee,te??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(ge)){v({type:"card",gateway:"stripe",paymentMethodType:Q},{accountPatch:Fe,paymentMethodCategory:"apm",sessionId:ee,nonce:te,settledProcessResponse:ge.response});return}if(ge.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let H=ge.clientSecret;dr(Jn,{clientSecret:H,sessionId:ee,nonce:te,accountPatch:Fe,paymentMethodType:Q,gateway:"stripe"});let{error:Be,paymentIntent:ut}=await p.confirmPayment({clientSecret:H,confirmParams:{return_url:window.location.href,payment_method_data:{type:Q,billing_details:{name:[ue.firstName,ue.lastName].filter(Boolean).join(" "),...pe?{email:pe}:{}}}},redirect:"if_required"});if(Be){dr(Jn);let it=Be.message??"Payment failed.";S?.(it),V?.(kr("card",it,{code:Be.code})),await Ii({billingApiUrl:s,sessionId:ee,nonce:te,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,providerDeclineReason:Be.code??"provider_declined"}});return}let Xe=ut?.status;if(!va(Xe)){dr(Jn);let it=Xe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(it),V?.(kr("card",it,{code:Xe??"missing_payment_intent"}));return}dr(Jn);let nt=typeof ut?.payment_method=="string"?ut.payment_method:ut?.payment_method?.id;v({id:nt??ut?.id,type:"card",threeDSecureActionResultTokenId:ut?.id,gateway:"stripe",paymentMethodType:Q},{accountPatch:Fe,paymentMethodCategory:"apm",sessionId:ee,nonce:te})}catch(ge){S?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{L.current=!1,ze(null)}},[p,A,x,E,e,t,r,at,s,fe,n,a,v,S,V]),[N,le]=(0,o.useState)(null),de=_?ne??null:N,rt=(0,o.useCallback)(Q=>{L.current||A||de&&de!==Q||((0,c.needsStripeMethodExplicitConfirm)(Q)?_?_(Q):le(Q):ye(Q))},[de,A,ye,_]),je=(0,o.useMemo)(()=>N?Ec(y,N,b):null,[N,y,b]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ye?(0,l.jsx)(ea,{identity:Ye.identity,methodLabel:Ye.methodLabel,onComplete:qe,onCancel:()=>qe(null)},Ye.id):d.map(Q=>{let W=ne===Q,ee=vt===Q,te=vt!==null&&vt!==Q||ne!=null&&ne!==Q;return(0,l.jsxs)(o.default.Fragment,{children:[(0,l.jsx)(hi,{method:Q,themeId:me,submitting:ee,disabled:te,highlighted:W,hasNextStep:(0,c.needsStripeMethodExplicitConfirm)(Q),onClick:()=>rt(Q),backgroundColor:m?.backgroundColor,borderColor:m?.borderColor,textColor:m?.textColor,borderRadius:m?.borderRadius,fontFamily:m?.fontFamily}),!_&&N===Q&&je&&p&&(0,l.jsx)(cr.Elements,{stripe:p,options:je,children:(0,l.jsx)(Es,{method:Q,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:v,onErrorChange:S,onDecline:V,onCancel:()=>le(null),runBeforeButtonClick:x,onButtonClick:E,isProcessing:A,submitButtonColor:g,submitButtonBorderRadius:O,submitButtonStyle:ke})},Q)]},Q)})})}function Ru({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:d,onError:p,onDecline:y,onCancel:b,onTokenizedBody:v,firstName:S,lastName:E,chv:V,className:x,submitLabel:D,isProcessing:A,error:g,onErrorChange:O,showPayPal:ke=!0,showStripe:m=!0,walletPresentation:me="auto",enabledPaymentMethods:_,enabledPaymentMethodCountries:ne,showApplePay:fe=!0,showGooglePay:ce=!0,layout:Ee="default",paymentMethodLayout:vt,theme:ze,buttonsTheme:L,buttonsStyles:Ye,appearance:at,cardButtonContent:qe,cardBackButtonContent:ye,cardTitleContent:N,showSecurityFooter:le,onButtonClick:de,onBeforeButtonClick:rt,onBuyerIdentityReady:je,enableAVS:Q,cardFieldOrder:W,cardAutoFocus:ee,cardPreFormSlot:te,avsLayout:ve="row",country:ue,zip:pe,addressLine1:Fe,addressLine2:ge,city:H,state:Be,onCountryChange:ut,onZipChange:Xe,avsCheck:nt,checkoutType:it,checkoutLayout:or,totalAmount:_t=0,currency:qt="usd",initialCardOpen:Ce=!1,directPaypal:oe,isSubscription:Ze=!1,session:J,dataAttachmentPending:Ct=!1,dataAttachmentRequiresIdentity:Rt=!1,debug:se=!1}){let De=co(),It=ai(),h=(0,o.useContext)(Un),{emitInstrument:U}=(0,o.useContext)(Sn),he=(0,o.useRef)(null);he.current||(he.current=si());let ae=he.current,[,Wt]=(0,o.useState)(0),Bt=(0,o.useRef)(null);Bt.current||(Bt.current=(0,Gn.detectPayPalEnvironment)());let Ae=Bt.current,be=(0,o.useMemo)(()=>({browser:Ae,capability:ae,presentationMode:"popup"}),[Ae,ae]),bt=J??h.session,u=(0,o.useMemo)(()=>({futureUse:bt?.futureUse,futureUseUnsupported:bt?.futureUseUnsupported}),[bt?.futureUse,bt?.futureUseUnsupported]),B=bt?.gateways?.paypal?.providerObjectType??oe?.providerObjectType,I=Ct||h.claimPending===!0,xe=Rt||h.claimRequiresIdentity===!0,z=I&&!xe,F=Hl(),$e=r||F,ar=dc({rules:vt,sessionId:e,nonce:t,billingApiUrl:$e}),tr=(0,o.useMemo)(()=>ar?(0,c.keyPaymentMethodOrder)(ar):null,[ar]),br=ar!==null&&(0,c.isCardFormFirst)(ar),[Tt,Zr]=(0,o.useState)(!1),[pn,sn]=(0,o.useState)(null),[jt,Dt]=(0,o.useState)(ue??""),[yn,Yt]=(0,o.useState)(pe??""),[ln,pr]=(0,o.useState)(Fe??""),[Mn,Jt]=(0,o.useState)(ge??""),[ir,Qr]=(0,o.useState)(H??""),[ot,At]=(0,o.useState)(Be??""),[Or,Lr]=(0,o.useState)(""),[Ir,jr]=(0,o.useState)({}),Fr=(0,o.useRef)(pe??""),Zt=(0,o.useRef)(ue??""),Sr=(0,o.useRef)(Fe??""),wr=(0,o.useRef)(ge??""),rr=(0,o.useRef)(H??""),Xt=(0,o.useRef)(Be??""),Vr=(0,o.useRef)(""),Nr=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(w,K,Te,X,Ke)=>{if(Nr.current[w])return;let yt=K?.trim();!yt||yt===Te.current||(Te.current=yt,X(yt),Ke?.(yt))};i("country",ue,Zt,Dt,ut),i("zip",pe,Fr,Yt,Xe),i("addressLine1",Fe,Sr,pr),i("addressLine2",ge,wr,Jt),i("city",H,rr,Qr),i("state",Be,Xt,At)},[ue,pe,Fe,ge,H,Be,ut,Xe]);let He=(0,o.useMemo)(()=>(0,c.resolveAVSConfig)(Q),[Q]),Ur=He!==null,Wr=(0,o.useMemo)(()=>(0,c.isAuthorizationOnlySession)(J),[J]),An=(0,c.isMountableVaultBlock)(J?.vault),zr=!!J?.gateways?.pcivault,Qt=(0,Nn.hasServerSideCardGateway)(J),en=!!(J?.gateways?.stripe?.enabledPaymentMethods??_)?.includes("card")||(0,Nn.canRecoverHostedCardForm)(J),yr=An||en||zr,C=!!(m&&yr&&e),[kt,ie]=(0,o.useState)(()=>Ee!=="buttons"||Ce?e??null:null),[_e,Ut]=(0,o.useState)(0),Ot=Ee!=="buttons"||Ce||!!e&&kt===e,$t=J?.captureMethod,We=(0,o.useRef)(De);(0,o.useEffect)(()=>{We.current=De},[De]);let[$r,eo]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!C||!e||!Ot){eo(null);return}let i=We.current?We.current.cardCapture({sessionId:e,captureMethod:$t}):new Vn.PciVaultCardCapture({sessionId:e,captureMethod:$t,billingApiUrl:$e,telemetry:n});return eo({sessionId:e,captureMethod:$t,billingApiUrl:$e,telemetry:n,capture:i}),()=>{i.unmount()}},[C,e,Ot,$t,$e,n]);let zt=C&&e&&Ot&&$r?.sessionId===e&&$r.captureMethod===$t&&$r.billingApiUrl===$e&&$r.telemetry===n?$r.capture:null,Vt=(0,o.useMemo)(()=>{let i=jt,w=He?(0,c.isAVSFieldVisible)(He.postal_code,i):!1;return vu(i,yn,w)},[He,jt,yn]),{avsInvalid:Wn,invalidAvsFields:to}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!C||!He)return{avsInvalid:!1,invalidAvsFields:i};let w=jt,K=(Ke,yt)=>(0,c.isAVSFieldVisible)(Ke,w)&&!yt.trim(),Te={line1:K(He.address_line_1,ln),city:K(He.city,ir),state:K(He.state,ot),zip:Vt.empty||Vt.malformed};return{avsInvalid:Te.line1||Te.city||Te.state||Te.zip,invalidAvsFields:Te}},[C,He,jt,ln,ir,ot,Vt]),[mn,xn]=(0,o.useState)(!1),[ro,fo]=(0,o.useState)(!1),[go,Hr]=(0,o.useState)(!1),[ho,Fn]=(0,o.useState)({line1:!1,city:!1,state:!1}),Bn=(0,o.useRef)(!1),fn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),gn=(0,o.useRef)(!1),Ht=(0,o.useCallback)(i=>{fn.current[i]=!0,gn.current=!0},[]),hn=(0,o.useCallback)(i=>!Bn.current&&fn.current[i],[]),Pn=(0,o.useCallback)(i=>{hn(i)&&Fn(w=>w[i]?w:{...w,[i]:!0})},[hn]),[Kr,Gr]=(0,o.useState)(()=>(0,c.resolveVaultMountOptions)(J?.vault,{billingApiUrl:$e,sessionId:e,nonce:t})),[Qe,Br]=(0,o.useState)(Ce&&yr?"card":"buttons"),[Rr,vn]=(0,o.useState)(null),Po=Qe==="expanding"||Qe==="card",Cn=J?.gateways?.stripe&&!Qt?"stripe":void 0,no=(0,o.useCallback)(()=>{U?.({class:"card_surface",provider:Cn})},[Cn,U]),Tr=(0,o.useRef)(null),T=(0,o.useCallback)(i=>{Tr.current&&clearTimeout(Tr.current),Tr.current=setTimeout(()=>{Tr.current=null,i()},La)},[]);(0,o.useEffect)(()=>()=>{Tr.current&&clearTimeout(Tr.current)},[]);let q=(0,o.useRef)(!1),[Z,Se]=(0,o.useState)(0),pt=(0,o.useRef)(null),mr=(0,o.useCallback)(()=>{no(),ie(e??null),q.current&&(q.current=!1,Se(i=>i+1)),Ut(i=>i+1),Br("expanding"),T(()=>Br("card"))},[T,no,e]),Ve=(0,o.useCallback)(()=>{Br("collapsing"),T(()=>Br("buttons"))},[T]),st=(0,o.useCallback)(i=>{vn(i),Br("apm-expanding"),T(()=>Br("apm-form"))},[T]),Y=(0,o.useCallback)(()=>{Br("apm-collapsing"),T(()=>{Br("buttons"),vn(null)})},[T]);(0,o.useEffect)(()=>{Ee==="buttons"&&Ce&&yr&&(ie(e??null),Br("card"))},[Ee,Ce,yr,e]);let[Oe,j]=(0,o.useState)(null),ct=(0,o.useRef)(null),[re,et]=(0,o.useState)(0);(0,o.useEffect)(()=>{re!==0&&ct.current?.focus()},[re]);let ht=(0,o.useRef)(!1),tt=(0,o.useRef)(null),Mt=(0,o.useRef)("idle"),[P,f]=(0,o.useState)(!1),G=(0,o.useRef)(P);G.current=P;let[Ie,Le]=(0,o.useState)(()=>oe?.existingOrderId?{orderId:oe.existingOrderId,attempts:1}:null),dt=(0,o.useRef)(Ie);(0,o.useEffect)(()=>{dt.current=Ie},[Ie]);let Et=(0,o.useRef)(null),fr=(0,o.useMemo)(()=>{if(je||h.claimBuyerIdentity||J?.buyerIdentified!==!1||!e||!t)return;let i=`${$e}|${e}|${t}`;Et.current?.key!==i&&(Et.current={key:i,claim:Xo(new Vn.PaymentAPI($e,{telemetry:!1}),e,t,{...s?{userId:s}:{},...S?{firstName:S}:{},...E?{lastName:E}:{}})});let w=Et.current.claim;return async K=>{await w(K)}},[je,h.claimBuyerIdentity,J?.buyerIdentified,e,t,$e,s,S,E]),Lt=je??h.claimBuyerIdentity??fr,Kt=g??pn,Dn=(0,o.useMemo)(()=>(0,c.resolveTheme)(ze),[ze]),$=(0,o.useMemo)(()=>{let i=Dn?.buttonsLayout??(0,c.resolveButtonsLayoutTheme)(L);return Ye?{...i,...Ye,cardButton:{...i.cardButton,...Ye.cardButton},cardFormContainer:{...i.cardFormContainer,...Ye.cardFormContainer},backButton:{...i.backButton,...Ye.backButton},backButtonIcon:{...i.backButtonIcon,...Ye.backButtonIcon},submitButton:{...i.submitButton,...Ye.submitButton},title:{...i.title,...Ye.title}}:i},[Dn,L,Ye]),Pt=at??Dn?.appearance,xt=(0,o.useMemo)(()=>(0,c.computeVaultCardThemeColors)({appearance:Pt,buttonsStyles:$,layout:Ee}),[Pt,$,Ee]),Nt=h.inlineSessionPatchProcessing??!1,we=(A??Tt)||Nt,gr=$e.replace(/\/+$/,""),Pe=(0,o.useMemo)(()=>ls({userId:s,email:a,firstName:S,lastName:E,country:ue,zip:pe},Ir),[s,a,S,E,ue,pe,Ir]),oo=[Pe.firstName,Pe.lastName].filter(i=>!!i?.trim()).join(" "),qs=!(0,c.isValidEmail)(Pe.email?.trim()),Ni=(0,o.useRef)(null);C&&Ni.current===null&&(Ni.current=qs);let vo=C&&(Ni.current??qs),Ui=(0,o.useMemo)(()=>Cu(Or,vo),[Or,vo]),Do=Ui.empty||Ui.malformed,cn=(0,o.useMemo)(()=>De?De.getRawProvider():null,[De]),js=(0,o.useMemo)(()=>It?It.getRawProvider():null,[It]),ca=_t||100,Oo=qt.toLowerCase(),zi=(0,o.useMemo)(()=>Pt?(0,Vn.toStripeAppearance)(Pt):null,[Pt]),Lo=zi,Vs=(0,o.useMemo)(()=>{let i=zi??{},w=i.rules??{};return{...i,rules:{...w,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...w[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...w[".AccordionItemContents"]??{}}}}},[zi]),Ws=(0,o.useMemo)(()=>({...Vl(_t,bt?.captureMethod,u),currency:Oo,...Lo?{appearance:Lo}:null}),[_t,Oo,bt?.captureMethod,u,Lo]),qi=(0,c.resolveSetupFutureUsage)(u,"paypal","paypal"),$s=(0,o.useMemo)(()=>({mode:"payment",amount:ca,currency:Oo,captureMethod:"manual",...qi?{setupFutureUsage:qi}:null,...Lo?{appearance:Lo}:null}),[ca,Oo,qi,Lo]),Ne=(0,o.useCallback)(i=>{sn(i),O?.(i)},[O]),Hs=(0,o.useRef)(0);(0,o.useEffect)(()=>{Z!==Hs.current&&(Hs.current=Z,Ne(null))},[Z,Ne]);let ji=(0,o.useRef)(""),[Ks,Yc]=(0,o.useState)(!1),Vi=(0,o.useCallback)(()=>{Yc(!0)},[]);(0,o.useEffect)(()=>{if(!C||!vo||!Lt||!Ks||Do||ji.current)return;let i=(0,wn.compactBuyerIdentity)({email:(0,c.isValidEmail)(Pe.email?.trim())?Pe.email?.trim():Vr.current.trim(),firstName:Pe.firstName?.trim(),lastName:Pe.lastName?.trim()});ji.current=JSON.stringify(i),jr(w=>({...w,...i})),Promise.resolve(Lt(i)).catch(w=>{ji.current="",Ne(w instanceof Error?w.message:"Failed to attach buyer details.")})},[C,vo,Lt,Ks,Do,Pe.email,Pe.firstName,Pe.lastName,Ne]),(0,o.useEffect)(()=>{if(!C||!zt)return;let i=ee!==!1&&He==null&&!vo;zt.setCardFieldOrder?.(W??null,i)},[C,zt,W,ee,He,vo]),(0,o.useEffect)(()=>{(Qe==="expanding"||Qe==="collapsing"||Qe==="apm-expanding"||Qe==="apm-collapsing")&&Ne(null)},[Qe,Ne]);let $n=(0,o.useCallback)((i,w,K)=>{y?.(kr(i,w,K))},[y]),Gs=(0,o.useRef)(Qe);Gs.current=Qe;let[Ys]=(0,o.useState)(ci),Xs=(0,o.useCallback)(()=>{let i=Gs.current;if(Ee==="buttons"&&(i==="card"||i==="expanding"))return!0;let w=Mt.current;return w==="validation-window"||w==="processing"||G.current},[Ee]),Js=(0,o.useCallback)((i,w,K)=>{Ys.take(e)&&Er(De)?.log(Ao({...be,presentationMode:K?.presentationMode??"popup"},{name:li,stage:"recovery",reason:"other_method_active",provider:K?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:K?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[be,De,Ys,e]),ja=(0,o.useCallback)((i,w,K)=>{K?.telemetryReported||Er(De)?.error(Ao({...be,presentationMode:K?.presentationMode??"popup"},{errorCode:w?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:K?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:K?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:K?.terminalReason??(w?"popup_blocked":"provider_error")}))},[be,De]),No=(0,o.useCallback)((i,w,K)=>{let Te=K?.popupBlocked??(0,Re.isPopupBlockedError)(w);if(Xs()){ja(i,Te,K),Js(i,w,K);return}if(w instanceof c.FloPayError&&w.code==="checkout_processing_timeout"){ja(i,!1,K),j(null),Ee==="buttons"&&(Br("buttons"),vn(null)),Ne(w.message),p?.(w);return}Te&&ae.markBlocked()&&Wt(St=>St+1);let X=ks(i),Ke=K?.code===c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,c.buildWalletSheetWindowMessage)(X):(0,Re.buildExternalMethodRecoveryMessage)(X,Te,Ae.inAppBrowser),yt=(0,Re.getProviderErrorCode)(w),nn=(yt?.toLowerCase()==="error"?void 0:yt)??(0,Re.sanitizeExternalFailureCode)(K?.code)??"external_payment_method_failed",mt=new c.FloPayError(Ke,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:nn,popupBlocked:Te,inAppBrowser:Ae.inAppBrowser,appFamily:Ae.appFamily,popupCapability:ae.current(),presentationMode:K?.presentationMode??"popup"}});ja(i,Te,K),j(null),Ee==="buttons"&&(Br("buttons"),vn(null)),Ne(Ke),p?.(mt),console.error("[FloPay] External payment method failed:",{method:i,code:nn,popupBlocked:Te})},[Ae,Xs,Ee,p,ae,Js,ja,Ne]);(0,o.useEffect)(()=>{if(!C||!e){Gr(null);return}let i={billingApiUrl:gr,sessionId:e,nonce:t},w=(0,c.resolveVaultMountOptions)(J?.vault,i);if(w){Gr(w);return}if(!Ot){Gr(null);return}let K=`${gr}\0${e}\0${t??""}`,Te=pt.current;if(Te&&Te.key===K){Gr(Te.mount);return}Gr(null);let X=!0;return new Vn.PaymentAPI(gr).getVaultCapture(e,t).then(Ke=>{if(!X)return;let yt=(0,c.resolveVaultMountOptions)(Ke,i);yt?.verificationRequired&&!Ke.html&&(pt.current={key:K,mount:yt}),yt?Gr(yt):Ne("Failed to load the secure card form.")}).catch(Ke=>{X&&Ne(Ke instanceof Error?Ke.message:"Failed to load the secure card form.")}),()=>{X=!1}},[C,Ot,_e,e,J?.vault,gr,t,Ne]);let On=(0,o.useRef)({onComplete:d,onError:p,updateError:Ne,emitDecline:$n,resolvedAccount:Pe,avsConfig:He,avsCheckProp:nt,sessionId:e,nonce:t,baseUrl:gr,captureMethod:J?.captureMethod,paymentId:J?.paymentId,authorizationExpiresAt:J?.authorizationExpiresAt,serverSideCardGateway:Qt});On.current={onComplete:d,onError:p,updateError:Ne,emitDecline:$n,resolvedAccount:Pe,avsConfig:He,avsCheckProp:nt,sessionId:e,nonce:t,baseUrl:gr,captureMethod:J?.captureMethod,paymentId:J?.paymentId,authorizationExpiresAt:J?.authorizationExpiresAt,serverSideCardGateway:Qt};let Wi=(0,o.useRef)(!1),Zs=(0,o.useCallback)(()=>{let i=On.current,w=i.resolvedAccount.email?.trim(),K=(0,c.isValidEmail)(w)?w:Vr.current.trim();if(!(0,c.isValidEmail)(K))return null;let Te=i.resolvedAccount.firstName?.trim(),X=i.resolvedAccount.lastName?.trim(),Ke=Zt.current.trim()||i.resolvedAccount.country?.trim()||"",yt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.state,Ke):!1,nn=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_1,Ke):!1,mt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.postal_code,Ke):!1,St=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.city,Ke):!1,Ft=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_2,Ke):!1,hr=nn&&!yt&&mt?(0,c.getStateFromPostalCode)(Ke,(Fr.current??"").trim()):null,dn=yt?Xt.current:hr;return{accountData:{userId:i.resolvedAccount.userId??"",email:K,...Te?{firstName:Te}:{},...X?{lastName:X}:{},...mt&&Fr.current?{zip:Fr.current}:{},...St&&rr.current?{city:rr.current}:{},...dn?{state:dn}:{},...nn&&Sr.current?{addressLine1:Sr.current}:{},...Ft&&wr.current?{addressLine2:wr.current}:{},...Ke?{country:Ke}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,c.isAVSFieldVisible)(i.avsConfig.country,Ke),postal_code:mt,address_line_1:nn,address_line_2:Ft,city:St,state:yt}}:{}}},[]),Qs=(0,o.useRef)(I);Qs.current=I,(0,o.useEffect)(()=>{I||Kt!==fc||On.current.updateError(null)},[I,Kt]),(0,o.useEffect)(()=>{!C||!zt||zt.setSubmitGate?.(Wn||I||Do||P)},[C,zt,Wn,I,Do,P]),(0,o.useEffect)(()=>{if(!C||!zt)return;Wi.current=!1;let i=null,w=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,Mt.current="idle",j(null)},400)},K=zt.on("submitting",()=>{xn(!0),tt.current&&clearTimeout(tt.current),Mt.current="validation-window",tt.current=setTimeout(()=>{tt.current=null,Mt.current==="validation-window"&&(Mt.current="processing")},cu),j("processing");let mt=On.current;if(!mt.sessionId||!mt.nonce)return;let St=Zs();if(!St){mt.updateError("Enter a valid email address."),Mt.current="idle",j(null);return}new Vn.PaymentAPI(mt.baseUrl).patchAccountSnapshot(mt.sessionId,mt.nonce,St,{telemetryMode:"best_effort"}).catch(Ft=>{if(!uu(Ft))return;let hr=Ft instanceof Error?Ft.message:"Please check your billing address and try again.";mt.updateError(hr),Mt.current="idle",j(null),mt.onError?.(Ft instanceof c.FloPayError?Ft:new c.FloPayError(hr,"api_error"))})}),Te=zt.on("complete",mt=>{(0,qn.markSessionRecentlyCompleted)(mt.sessionId??On.current.sessionId),Mt.current="terminal",f(!1),j("success"),setTimeout(()=>{if(Wi.current)return;Wi.current=!0;let St=On.current,Ft=(0,c.isAuthorizationOnlySession)(St)||mt.outcome==="authorized",hr=St.serverSideCardGateway?{}:{paymentIntentId:mt.intentId};On.current.onComplete?.(Ft?{status:"authorized",...hr,paymentId:mt.paymentId??St.paymentId,sessionId:mt.sessionId??St.sessionId,authorizationExpiresAt:mt.authorizationExpiresAt??St.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...hr,checkoutMethod:"card"})},600)}),X=zt.on("decline",mt=>{let St=On.current,Ft=mt.message??"Your payment was declined. Please try another card or contact your bank.";Mt.current="terminal",f(!1),St.updateError(Ft),j("error");let hr=mt.failureOutcome??(0,c.normalizeCheckoutFailureOutcome)(mt.declineReason)??"authorization_declined";St.emitDecline("card",Ft,{code:hr,declineCode:hr}),w()}),Ke=zt.on("error",mt=>{let St=On.current,Ft=(0,c.buyerEmailRequiredPrompt)(mt.vaultOutcome);if(Ft!==null){i&&(clearTimeout(i),i=null),Mt.current="idle",f(!1),St.updateError(Ft),j(null),et(dn=>dn+1),St.onError?.(new c.FloPayError(Ft,"api_error",{code:c.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let hr=mt.message??"There was a problem processing your payment. Please try again.";Mt.current="terminal",f(!1),St.updateError(hr),j("error"),St.onError?.(new c.FloPayError(hr,"api_error",{code:mt.failureOutcome??"capture_failed"})),w()}),yt=zt.on("challenge_dismissed",()=>{tt.current&&(clearTimeout(tt.current),tt.current=null),Mt.current="processing",f(!0),j(null)}),nn=zt.on("blocked",()=>{if(G.current){On.current.updateError(du);return}if(!Qs.current){xn(!0);return}Vi(),On.current.updateError(fc)});return()=>{i&&(clearTimeout(i),i=null),tt.current&&(clearTimeout(tt.current),tt.current=null),Mt.current="idle",f(!1),j(null),K(),Te(),X(),Ke(),yt(),nn()}},[C,zt,Vi,Zs]);let Hn=!!oe?.clientId,da=Array.isArray(_),Va=da&&_.length>0,el=da&&_.includes("paypal"),Wa=(0,o.useRef)(null);Wa.current===null&&(Wa.current=(0,c.hasMatchingStripePayPalReturn)());let Uo=Wa.current?"redirect":(0,Yn.resolveStripePayPalPresentation)(Ae,me,ae.current()),{expressMethods:$a,paymentElementMethods:$i}=(0,o.useMemo)(()=>(0,c.partitionStripeMethods)(_,{excludePaypal:Hn}),[_,Hn]),tl=Hn||!!It||el&&Uo==="redirect",Xc=(0,o.useMemo)(()=>tl?$a.filter(i=>i!=="paypal"):$a,[$a,tl]),Jc=(0,o.useMemo)(()=>{let i=[];return fe&&i.push("apple_pay"),ce&&i.push("google_pay"),i},[fe,ce]),zo=da?Xc:Jc,Zc=m&&zo.length>0,rl=Ur?jt:ue,Ha=(0,o.useMemo)(()=>(0,c.filterStripeMethodsByCountryGate)($i,rl,ne),[$i,rl,ne]),Hi=(0,o.useMemo)(()=>({mode:"payment",amount:ca,currency:Oo,paymentMethodCreation:"manual",appearance:Vs}),[ca,Oo,Vs]),[nl,ol]=(0,o.useState)("loading"),[al,il]=(0,o.useState)("loading"),[sl,ll]=(0,o.useState)("loading"),[Qc,Ki]=(0,o.useState)(!1),[cl,Gi]=(0,o.useState)("loading"),[Yi,ed]=(0,o.useState)();(0,o.useEffect)(()=>{ed((0,Gn.detectPayPalEnvironment)())},[]);let Ka=Yi?.inAppBrowser,Ga=Yi?(0,Yn.resolvePayPalPresentationMode)(Yi,oe?.approvalPresentation,B??(Ze?"subscription":"order")):"popup",dl=ke&&(Hn||(da?el:Ka===!1)),td=Ae.inAppBrowser&&ae.current()==="blocked",ul=m&&Zc&&!td,qo=(!z||!!h.waitForDataAttachment)&&dl&&Hn,pl=cl==="retrying"||cl==="exhausted",ua=null;m&&(It?ua=js:Uo==="redirect"&&(ua=cn));let yl=(0,o.useMemo)(()=>({...be,presentationMode:Uo}),[be,Uo]),jo=!z&&dl&&!!ua&&(!Hn||pl),Ro=!z&&ul&&!!cn,Vo=!z&&m&&Va&&Ha.length>0&&!!cn,rd=qo&&!pl?Qc:jo&&gs(nl),nd=Ro&&gs(al),od=Vo&&sl!=="load_error",ml=[qo||jo,Ro,Vo,C].filter(Boolean).length,fl=i=>i==="loading"||i==="ready",gl=qo||jo&&fl(nl)||Ro&&fl(al)||Vo&&sl!=="load_error",Ya=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Ya.current){if(!m&&!ke){Ya.current=!0;let i=new c.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),Ne(i.message)}else if(!m&&ke&&!Hn){Ya.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),Ne(i.message)}else if(Ka!==void 0&&!z&&!yr&&!gl){Ya.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),Ne(i.message)}}},[m,ke,Hn,Ka,z,yr,gl,p,Ne]);let hl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(hl.current||!Va)return;let i=[];fe!==!0&&i.push("showApplePay"),ce!==!0&&i.push("showGooglePay"),i.length!==0&&(hl.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.`))},[Va,fe,ce]);let Pl=(0,o.useCallback)((i,w,K)=>h.applyInlineSessionPatch?h.applyInlineSessionPatch(i).then(Te=>({error:null,sessionId:Te.sessionId||e,nonce:Te.session?.clientSecret||t})).catch(Te=>{let X=(0,c.normalizeBeforeButtonClickError)(w,Te);return K?.abandoned?.()||(Ne(X.message),p?.(X)),{error:X,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[h.applyInlineSessionPatch,t,p,e,Ne]),Ln=(0,o.useCallback)(async(i,w)=>{if(i!=="card"&&z&&await h.waitForDataAttachment?.(),!rt)return{proceed:!0};try{let K=await rt({method:i,sessionId:e||void 0,createSession:h.inlineSessionDraft});if(K===!1)return{proceed:!1};if(K&&typeof K=="object"){K.account&&jr(X=>({...X??{},...K.account}));let Te=await Pl(K,i,w);return Te.error?{proceed:!1,accountPatch:K.account}:{proceed:!0,accountPatch:K.account,sessionId:Te.sessionId,nonce:Te.nonce}}return{proceed:!0}}catch(K){if(!w?.abandoned?.()){let Te=(0,c.normalizeBeforeButtonClickError)(i,K);Ne(Te.message),p?.(Te)}return{proceed:!1}}},[Pl,h.inlineSessionDraft,h.waitForDataAttachment,z,rt,p,e,Ne]),vl=(0,o.useCallback)(async(i,w)=>{if(ht.current)return;ht.current=!0,Zr(!0),j("processing"),Ne(null);let K=w?.sessionId??e,Te=w?.nonce??t,X=ls(Pe,w?.accountPatch),Ke=w?.completionPaymentMethodId??Ca(i),yt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,nn=fu(i),mt=w?.presentationMode?gi(Er(De),{...be,presentationMode:w.presentationMode}):void 0,St=()=>{U?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:nn}),mt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...jn,requestCategory:"process_payment"})};try{let Ft=new Vn.PaymentAPI(gr),dn=w?.settledProcessResponse??await Ft.processPayment(X.userId??"",{sessionId:K,nonce:Te,paymentMethodCategory:w?.paymentMethodCategory??hu(i),tokenizedData:yt,accountData:{...w?.accountPatch,userId:X.userId??"",email:X.email??"",firstName:X.firstName||void 0,lastName:X.lastName||void 0,...(0,c.buildProcessPaymentAvsAccount)({avsConfig:He,country:Zt.current,zip:Fr.current,city:rr.current,state:Xt.current,addressLine1:Sr.current,addressLine2:wr.current})},...(0,c.buildCheckoutProcessMetadata)({chv:V,avsCheck:nt,checkoutType:it,checkoutLayout:or,avsConfig:He,country:Zt.current})}),ei=async Mr=>{let Eo=(0,c.isAuthorizationOnlySession)(J)||Mr?.status==="authorized";(0,qn.markSessionRecentlyCompleted)(K),mt?.terminal({outcome:"payment_succeeded",...jn}),j("success"),Le(null),await new Promise(ha=>setTimeout(ha,600));let Kn;typeof Mr?.paymentId=="string"?Kn=Mr.paymentId:J?.paymentId&&(Kn=J.paymentId);let _o;typeof Mr?.authorizationExpiresAt=="string"?_o=Mr.authorizationExpiresAt:J?.authorizationExpiresAt&&(_o=J.authorizationExpiresAt),d?.(Eo?{status:"authorized",...Kn===void 0?{}:{paymentId:Kn},sessionId:typeof Mr?.sessionId=="string"?Mr.sessionId:K,..._o===void 0?{}:{authorizationExpiresAt:_o},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Ke,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Ke,checkoutMethod:i.isPaypal?"paypal":"card"})};if(dn.ok){await ei(dn.status===204?null:await dn.json().catch(()=>null));return}let Pr=await dn.json().catch(()=>null);if(Pr?.type==="paypal_redirect_required"){let Mr=Pr.threeDSecureToken,Eo=Pr.paymentMethodId||i.id||"";if(!De||!Mr){j("error"),Ne("PayPal authorization required but no token provided.");return}try{let Kn=It?.getRawProvider();if(!Kn){Ne("PayPal is not available.");return}let _o={return_url:window.location.href};Eo&&(_o.payment_method=Eo);let{error:ha}=await Kn.confirmPayment({clientSecret:Mr,confirmParams:_o,redirect:"if_required"});if(ha){j("error");let Al=ha.message??"PayPal payment failed.";Ne(Al),$n("paypal",Al,{code:ha.code})}}catch(Kn){j("error"),Ne(Kn instanceof Error?Kn.message:"PayPal authorization failed.")}return}if(Pr?.type==="paypal_direct_required"){let Mr=Pr.orderId;if(!Mr){j("error"),Ne("PayPal retry required but no order id provided.");return}let Eo=dt.current?.attempts??0;if(Eo>=2){j("error"),Ne("PayPal payment could not be completed after multiple attempts."),$n("paypal","paypal_direct_required retry limit exceeded");return}Ki(!1),Gi("loading"),Le({orderId:Mr,attempts:Eo+1}),j(null);return}if(dn.headers.get(ru)===nu){let Mr=await ou(Ft,K,Te);if(Mr!==void 0){await ei(Mr);return}}(0,c.classifyPaymentRejection)(dn.status,Pr)?mt?.terminal({outcome:"payment_declined",...jn,terminalReason:"provider_declined"}):St(),j("error");let Ml=Pr?.message??"Payment failed. Please try again.";Ne(Ml),$n(i.isPaypal?"paypal":"card",Ml,{code:Pr?.code??Pr?.gatewayErrorCode,declineCode:Pr?.declineCode??Pr?.gatewayDeclineReason}),await new Promise(Mr=>setTimeout(Mr,400))}catch(Ft){Rc(Ft)||St(),j("error"),Ne(Ft instanceof Error?Ft.message:"An unexpected error occurred"),await new Promise(hr=>setTimeout(hr,400))}finally{Zr(!1),j(null),ht.current=!1}},[gr,e,t,Pe,He,nt,it,or,V,De,It,J,d,Ne,$n,U,be]),tn=(0,o.useCallback)((i,w)=>{v&&!w?.settledProcessResponse?v(i):vl(i,w)},[v,vl]),pa=`${Sc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(pa);if(!i)return;let w;try{w=JSON.parse(i)}catch{dr(pa);return}if(!w||typeof w.createdAt!="number"||Date.now()-w.createdAt<0||Date.now()-w.createdAt>wc||typeof w.paymentMethodId!="string"||typeof w.providerIntentId!="string"||typeof w.paymentMethodType!="string"||w.sessionId!==e||!t||w.nonce!==t||!zo.includes(w.paymentMethodType)){dr(pa);return}dr(pa),tn({id:w.paymentMethodId,type:"card",threeDSecureActionResultTokenId:w.providerIntentId,gateway:"stripe",paymentMethodType:w.paymentMethodType},{...w.accountPatch?{accountPatch:w.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[tn,t,e,pa,zo]);let Cl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Cl.current)return;let[i,w,K]=(0,c.readStripeRedirectParams)();if(!i||!w||Wa.current||!De)return;let Te=De.getRawProvider();if(!Te)return;let X=St=>{let Ft=localStorage.getItem(St);if(!Ft)return null;try{return JSON.parse(Ft)}catch{return dr(St),null}},Ke=X(Jn)??X(pc),yt;if(Ke?.clientSecret){if(Ke.clientSecret!==w)return;yt={...Ke.accountPatch?{accountPatch:Ke.accountPatch}:{},...Ke.sessionId?{sessionId:Ke.sessionId}:{},...Ke.nonce?{nonce:Ke.nonce}:{}}}else if(Ke?.sessionId&&Ke.sessionId!==e)return;Cl.current=!0,dr(Jn),dr(pc),window.history.replaceState({},"",(0,c.stripeRedirectReturnUrl)());let nn=Ke?.paymentMethodType??Ke?.tokenType??"card",mt="card";(async()=>{if(K==="failed"){let Pr="Payment was declined. Please try again.";Ne(Pr),$n(mt,Pr);return}let{paymentIntent:St,error:Ft}=await Te.retrievePaymentIntent(w);if(Ft){let Pr=Ft.message??"Failed to retrieve payment status.";Ne(Pr),$n(mt,Pr,{code:Ft.code});return}let hr=St?.status,dn=va(hr);if(!St||!dn){let Pr=hr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ne(Pr),$n(mt,Pr,{code:hr??"missing_payment_intent"});return}let ei=typeof St.payment_method=="string"?St.payment_method:St.payment_method?.id;tn({id:ei??Ke?.paymentMethodId??Ke?.tokenId??St.id,type:"card",threeDSecureActionResultTokenId:St.id,gateway:Ke?.gateway??"stripe",paymentMethodType:nn},yt)})()},[e,tn,De,Ne,$n]);let Xi=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(C||De!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ya=Ee==="buttons",rn=Pt?.variables,ad=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ji=rn?.colorBackground,id=Ji&&!ad.has(Ji)?Ji:void 0,ma=$.cardInputBorder??(ya?"#e5e7eb":"#A4A4FF"),bl=rn?.colorDanger??"#dc2626",nr=i=>to[i]&&(ho[i]||mn),Xa=Do&&(go||mn),bn=i=>i?bl:ma,Ja=(Vt.malformed||Vt.empty)&&(ro||mn),sd=bn(Ja),Zi=$.cardFormContainer?.backgroundColor??id??(ya?"white":"#EDEDFF"),Wo=$.cardInputBackground??rn?.colorBackground??"white",Qi=Ko(ye),Sl=Ko(N),$o=$.nameInput,wl=$.cardInputFontSize??bu($o?.fontSize)??rn?.fontSizeBase??"16px",Rl=typeof $o?.fontFamily=="string"?$o.fontFamily:rn?.fontFamily??"Poppins, sans-serif",kl=(0,c.toCssWeight)($o?.fontWeight)??400,ld=$.cardInputColor??(typeof $o?.color=="string"?$o.color:void 0)??rn?.colorText??"#262833",cd=$.cardInputPlaceholderColor??"#9ca3af",lr=rn?.borderRadius??"8px",ao=rn?.borderRadius??$.cardButton?.borderRadius??lr,ko=rn?.colorPrimary??"#4A49FF",dd=rn?.colorPrimaryHover??(0,c.darkenHex)(ko,.12),es=rn?.colorText??"#262833",ts={fontSize:wl,fontFamily:Rl,fontWeight:kl,color:ld,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},fa={marginTop:"0.375rem",...ts,fontSize:"0.75rem",lineHeight:1.4,color:bl},ud={"--flopay-input-placeholder-color":cd,"--flopay-input-font-size":wl,"--flopay-input-font-family":Rl,"--flopay-input-font-weight":String(kl)},ga=$.cardFormContainer??{},rs=ga.padding??(ya?"0":"1rem"),ns=ga.borderRadius??lr,pd=zt&&Kr?(0,l.jsx)(wo,{capture:zt,html:Kr.html,messageToken:Kr.messageToken,expectedOrigin:Kr.expectedOrigin,verificationRequired:Kr.verificationRequired,theme:xt,submitLabel:D,onReady:()=>{if(!vo&&!He||typeof document>"u"||ee===!1)return;let i=()=>{let K=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(K){Bn.current=!0;try{K.focus()}finally{Bn.current=!1}}};gn.current||i()},onError:i=>{i&&Kr.verificationRequired&&Mt.current==="idle"&&(q.current=!0),Ne(i)},onValidation:i=>{let w=Mt.current;(w==="idle"||w==="validation-window")&&(Ne(i),i&&Mt.current==="validation-window"&&(tt.current&&(clearTimeout(tt.current),tt.current=null),Mt.current="idle",j(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"}),os=(0,l.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&no()},style:{backgroundColor:Zi,borderRadius:ns,...ga,padding:rs,...ud,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 @@ ${ce.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),ua&&_o&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ve?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:me,style:{display:"inline-flex",alignItems:"center",gap:Gi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:de.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...de.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...de.backButtonIcon},children:(0,d.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,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(jo,{content:Ue})]}),pl?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:de.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...de.title},children:(0,d.jsx)(ga,{content:ye})})]}),!ua&&!pl&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Yi,order:ve?-3:0,...de.title},children:(0,d.jsx)(ga,{content:ye})}),ve&&le&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:le}),ve&&yo&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:Lo,border:`1px solid ${hn(Ka)}`,borderRadius:cr,padding:"10px"},children:(0,d.jsx)("input",{ref:te,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:ir,onChange:i=>{Vt("email"),Lr.current=i.target.value,nn(i.target.value)},onPointerDown:()=>Vt("email"),onKeyDown:()=>Vt("email"),onBlur:()=>{Xr("email")&&po(!0),Mo||Ni()},disabled:Ie,required:!0,"aria-invalid":Ka||void 0,"aria-describedby":Ka?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Xi}})}),Ka&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ma,children:Bi.empty?"Email address is required":"Enter a valid email address"})]}),Ce&&(0,d.jsx)("div",{style:{order:ve?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=st,b=(G=!1)=>({backgroundColor:Lo,border:`1px solid ${hn(G)}`,borderRadius:cr,marginTop:"0.5rem",padding:"10px"}),$=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Xi}),_e=(0,l.getStateOptions)(i);return(0,d.jsxs)(d.Fragment,{children:[(0,l.isAVSFieldVisible)(Ce.address_line_1,i)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:b(or("line1")),children:(0,d.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:Xt,onChange:G=>{Vt("line1"),Er.current.addressLine1=!0,Qt.current=G.target.value,ar(G.target.value)},onPointerDown:()=>Vt("line1"),onKeyDown:()=>Vt("line1"),onBlur:()=>Jr("line1"),disabled:Ie,required:!0,"aria-invalid":or("line1")||void 0,"aria-describedby":or("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:$()})}),or("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ma,children:"Street address is required"})]}),(0,l.isAVSFieldVisible)(Ce.address_line_2,i)&&(0,d.jsx)("div",{style:b(),children:(0,d.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:tr,onChange:G=>{Er.current.addressLine2=!0,zr.current=G.target.value,In(G.target.value)},disabled:Ie,"data-testid":"flopay-address-line2",style:$()})}),((0,l.isAVSFieldVisible)(Ce.city,i)||(0,l.isAVSFieldVisible)(Ce.state,i))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Ce.city,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Lo,borderTop:`1px solid ${hn(or("city"))}`,borderRight:`1px solid ${hn(or("city"))}`,borderBottom:`1px solid ${hn(or("city"))}`,borderLeft:`1px solid ${hn(or("city"))}`,padding:"10px",borderTopLeftRadius:cr,borderBottomLeftRadius:cr,...(0,l.isAVSFieldVisible)(Ce.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:cr}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Jt,onChange:G=>{Vt("city"),Er.current.city=!0,Pr.current=G.target.value,qn(G.target.value)},onPointerDown:()=>Vt("city"),onKeyDown:()=>Vt("city"),onBlur:()=>Jr("city"),disabled:Ie,required:!0,"aria-invalid":or("city")||void 0,"aria-describedby":or("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:$()})}),(0,l.isAVSFieldVisible)(Ce.state,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Lo,borderTop:`1px solid ${hn(or("state"))}`,borderRight:`1px solid ${hn(or("state"))}`,borderBottom:`1px solid ${hn(or("state"))}`,borderLeft:`1px solid ${hn(or("state"))}`,padding:"10px",borderTopRightRadius:cr,borderBottomRightRadius:cr,...(0,l.isAVSFieldVisible)(Ce.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${hn(or("state")||or("city"))}`}:{borderRadius:cr}},children:_e?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Dr,onChange:G=>{Vt("state"),Er.current.state=!0,jt.current=G.target.value,Zt(G.target.value)},onPointerDown:()=>Vt("state"),onKeyDown:()=>Vt("state"),onBlur:()=>Jr("state"),disabled:Ie,autoComplete:"billing address-level1",required:!0,"aria-invalid":or("state")||void 0,"aria-describedby":or("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...$(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,l.getStateLabel)(i)}),_e.map(G=>(0,d.jsx)("option",{value:G.code,children:G.name},G.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,l.getStateLabel)(i),autoComplete:"billing address-level1",value:Dr,onChange:G=>{Vt("state"),Er.current.state=!0,jt.current=G.target.value,Zt(G.target.value)},onPointerDown:()=>Vt("state"),onKeyDown:()=>Vt("state"),onBlur:()=>Jr("state"),disabled:Ie,required:!0,"aria-invalid":or("state")||void 0,"aria-describedby":or("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:$()})})]}),or("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ma,children:"City is required"}),or("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ma,children:[(0,l.getStateLabel)(i)," is required"]}),((0,l.isAVSFieldVisible)(Ce.country,i)||(0,l.isAVSFieldVisible)(Ce.postal_code,i))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:j==="column"?"column":"row",gap:j==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Ce.country,i)&&(0,d.jsx)("div",{style:{flex:j==="row"?1:void 0,backgroundColor:Lo,borderTop:`1px solid ${pa}`,borderRight:`1px solid ${pa}`,borderBottom:`1px solid ${pa}`,borderLeft:`1px solid ${pa}`,padding:"10px",...j==="row"&&(0,l.isAVSFieldVisible)(Ce.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:cr,borderBottomLeftRadius:cr,borderRight:"none"}:{borderRadius:cr}},children:(0,d.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:st,onChange:G=>{Er.current.country=!0,sr.current=G.target.value,Gr(G.target.value),je?.(G.target.value),jt.current="",Zt("")},disabled:Ie,autoComplete:"billing country","data-testid":"flopay-country",style:{...$(),cursor:"pointer"},children:[st===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,l.COUNTRY_OPTIONS.map(G=>(0,d.jsxs)("option",{value:G.code,children:[G.flag," ",G.name]},G.code))]})}),(0,l.isAVSFieldVisible)(Ce.postal_code,i)&&(0,d.jsx)("div",{style:{flex:j==="row"?1:void 0,backgroundColor:Lo,border:`1px solid ${Kc}`,padding:"10px",...j==="row"&&(0,l.isAVSFieldVisible)(Ce.country,i)?{borderRadius:"0",borderTopRightRadius:cr,borderBottomRightRadius:cr}:{borderRadius:cr}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,l.getPostalCodeLabel)(st),autoComplete:"billing postal-code",value:Yr,onChange:G=>{Vt("zip"),Er.current.zip=!0,Or.current=G.target.value,Br(G.target.value),ut?.(G.target.value)},onPointerDown:()=>Vt("zip"),onKeyDown:()=>Vt("zip"),onBlur:()=>{Xr("zip")&&eo(!0)},disabled:Ie,required:rr.required,"aria-invalid":Ga||void 0,"aria-describedby":Ga?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:$()})})]}),Ga&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ma,children:rr.empty?`${(0,l.getPostalCodeLabel)(i)} is required`:eu(i)})]})})()}),ve&&Zc,Ye&&(0,d.jsx)(Xo,{margin:"0.75rem 0",styleOverride:de.errorBanner,children:Ye})]}),Ya={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"},hl=i=>V?!ge||!Hn?(0,d.jsx)("pre",{"data-testid":i,style:Ya,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":i,style:Ya,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ge}`,` directPaypalConfigured=${Hn}`,` inAppBrowserDetected=${String(Wa)}`,` shouldRenderDirectPayPal=${ia}`,` shouldRenderStripePayPal=${la}`,` hasPaypalStripeInstance=${!!Fs}`].join(`
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,vl=yt==="apm-expanding"||yt==="apm-form"||yt==="apm-collapsing",Uo;yt==="apm-expanding"?Uo=rc:yt==="apm-collapsing"&&(Uo=nc);let Xa=Ir?pc(qi,Ir,_t):null;if(Re==="buttons"){let i=yt==="buttons"||yt==="expanding"||yt==="apm-expanding",b=yt==="expanding"||yt==="card"||yt==="collapsing",$=et===void 0?{boxSizing:"border-box",height:ea,padding:"0 1rem"}:{padding:"0.9rem 1rem"},_e;yt==="expanding"||yt==="apm-expanding"?_e=Xd:(yt==="collapsing"||yt==="apm-collapsing")&&(_e=Yd);let G;return yt==="expanding"?G=rc:yt==="collapsing"&&(G=nc),(0,d.jsxs)("form",{onSubmit:$i,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ta,{}),Ve&&(0,d.jsx)(tn,{status:Ve,errorMessage:Ye,authorized:_n}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!_e?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!_e?Zd:{},..._e?{animation:_e,pointerEvents:"none"}:{}},children:[hl("flopay-direct-paypal-gate-debug"),Pl("flopay-stripe-gate-debug"),ia&&ue&&(0,d.jsxs)(d.Fragment,{children:[m&&(0,d.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,d.jsx)(Ca.Provider,{value:ne,children:(0,d.jsx)(Sa,{sessionId:e,nonce:t,billingApiUrl:w,email:re.email,billingName:_r||void 0,onBuyerIdentityReady:It,clientId:ue.clientId,environment:ue.environment,currency:zt.toUpperCase(),isSubscription:pe,providerObjectType:u,approvalPresentation:$a==="popup"?void 0:$a,onTokenizedBody:Qr,onComplete:c,onErrorChange:ze,onDecline:y,onCancel:g,onTechnicalFailure:Fo,onButtonClick:W,runBeforeButtonClick:Bn,isProcessing:Ie,onLoadStateChange:ji,onInitializationStateChange:Vi,session:Oe,existingOrderId:m?.orderId,debug:V},m?.orderId??"fresh")})]}),la&&(0,d.jsx)(dr.Elements,{stripe:sa,options:Os,children:(0,d.jsx)(ac,{sessionId:e,nonce:t,email:re.email,billingName:_r||void 0,onBuyerIdentityReady:It,billingApiUrl:w,onTokenizedBody:Qr,onErrorChange:ze,isProcessing:Ie,onButtonClick:W,onDecline:y,onTechnicalFailure:Fo,runBeforeButtonClick:Bn,onLoadStateChange:Ys,placeholderBorderRadius:Po,popupCapabilityOwner:ne,externalTelemetryContext:ol,presentationMode:Bo})}),Oo?(0,d.jsx)(dr.Elements,{stripe:cn,options:Ds,children:(0,d.jsx)(ic,{sessionId:e,nonce:t,email:re.email,billingName:_r||void 0,onBuyerIdentityReady:It,billingApiUrl:w,intentKind:Ot>0?"payment":"setup",expressMethods:Do,onTokenizedBody:Qr,onErrorChange:ze,onButtonClick:W,onDecline:y,onTechnicalFailure:Fo,runBeforeButtonClick:Bn,onLoadStateChange:Js,placeholderBorderRadius:Po,popupCapabilityOwner:ne,externalTelemetryContext:De})}):null,!Oo&&rl?(0,d.jsx)("div",{style:{height:ea,borderRadius:Po,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ca&&(0,d.jsx)(sc,{sessionId:e,nonce:t,email:re.email,billingName:[re.firstName,re.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:It,billingApiUrl:w,paymentElementMethods:Va,stripeInstance:cn,paymentElementBaseOptions:qi,futureUseSession:_t,onTokenizedBody:Qr,onErrorChange:ze,onButtonClick:W,onDecline:y,runBeforeButtonClick:Bn,onLoadStateChange:Qs,isProcessing:Ie,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:de.submitButton,onExpandApm:kt,expandedApmMethod:Ir,themeId:ct,buttonAppearance:{backgroundColor:de.cardButton?.backgroundColor,borderColor:de.cardInputBorder,textColor:de.cardButton?.color,borderRadius:Po}}),ve&&(0,d.jsx)("button",{type:"button",onClick:async()=>{Ie||!(await Bn("card")).proceed||(W?.("card"),se())},disabled:Ie,style:{width:"100%",...$,...de.cardButton,...bs({themeBundle:br,resolvedPrimaryColor:vo,resolvedBorderRadius:cr,submitButtonStyle:de.submitButton,explicitPrimaryColor:en?.colorPrimary}),fontSize:de.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ie?"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:Ie?.6:1},onMouseEnter:Te=>{!Ie&&(br||en?.colorPrimary)&&(Te.currentTarget.style.backgroundColor=Xc)},onMouseLeave:Te=>{(br||en?.colorPrimary)&&(Te.currentTarget.style.backgroundColor=vo)},onMouseDown:Te=>{Te.currentTarget.style.transform="scale(0.985)"},onMouseUp:Te=>{Te.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(qo,{content:et})}),Ye&&yt==="buttons"&&(0,d.jsx)(Xo,{margin:"0.25rem 0",styleOverride:de.errorBanner,children:Ye})]}),ve&&b&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...G?{animation:G}:{},...yt==="collapsing"?{pointerEvents:"none"}:{}},children:gl}),S&&vl&&Ir&&Xa&&cn&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Uo?{animation:Uo}:{},...yt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Ki,borderRadius:Zi,...ya,padding:Ji},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:Gi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:de.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...de.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...de.backButtonIcon},children:(0,d.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,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(jo,{content:Ue})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:de.titleFontSize??"1.05rem",color:Yi,paddingRight:80,...de.title},children:`Pay with ${(0,l.getStripeMethodDisplayName)(Ir)}`})]}),(0,d.jsx)(dr.Elements,{stripe:cn,options:Xa,children:(0,d.jsx)(Ps,{method:Ir,sessionId:e,nonce:t,email:re.email,billingName:[re.firstName,re.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:It,billingApiUrl:w,onTokenizedBody:Qr,onErrorChange:ze,onDecline:y,onCancel:Wt,runBeforeButtonClick:Bn,onButtonClick:W,isProcessing:Ie,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:de.submitButton,errorText:Ye})},Ir)]})})]})]})}return vl&&Ir&&Xa&&cn&&S?(0,d.jsxs)("form",{onSubmit:$i,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ta,{}),Ve&&(0,d.jsx)(tn,{status:Ve,errorMessage:Ye,authorized:_n}),(0,d.jsx)("div",{style:{...Uo?{animation:Uo}:{},...yt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Ki,borderRadius:Zi,...ya,padding:Ji},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:Gi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:de.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...de.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...de.backButtonIcon},children:(0,d.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,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(jo,{content:Ue})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:de.titleFontSize??"1.05rem",color:Yi,paddingRight:80,...de.title},children:`Pay with ${(0,l.getStripeMethodDisplayName)(Ir)}`})]}),(0,d.jsx)(dr.Elements,{stripe:cn,options:Xa,children:(0,d.jsx)(Ps,{method:Ir,sessionId:e,nonce:t,email:re.email,billingName:[re.firstName,re.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:It,billingApiUrl:w,onTokenizedBody:Qr,onErrorChange:ze,onDecline:y,onCancel:Wt,runBeforeButtonClick:Bn,onButtonClick:W,isProcessing:Ie,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:de.submitButton,errorText:Ye})},Ir)]})})]}):(0,d.jsxs)("form",{onSubmit:$i,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ta,{}),Ve&&(0,d.jsx)(tn,{status:Ve,errorMessage:Ye,authorized:_n}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[hl("flopay-direct-paypal-gate-debug-default"),Pl("flopay-stripe-gate-debug-default"),ia&&ue&&(0,d.jsxs)(d.Fragment,{children:[m&&(0,d.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,d.jsx)(Ca.Provider,{value:ne,children:(0,d.jsx)(Sa,{sessionId:e,nonce:t,billingApiUrl:w,email:re.email,billingName:_r||void 0,onBuyerIdentityReady:It,clientId:ue.clientId,environment:ue.environment,currency:zt.toUpperCase(),isSubscription:pe,providerObjectType:u,approvalPresentation:$a==="popup"?void 0:$a,onTokenizedBody:Qr,onComplete:c,onErrorChange:ze,onDecline:y,onCancel:g,onTechnicalFailure:Fo,onButtonClick:W,runBeforeButtonClick:Bn,isProcessing:Ie,onLoadStateChange:ji,onInitializationStateChange:Vi,session:Oe,existingOrderId:m?.orderId,debug:V},m?.orderId??"fresh")})]}),la&&(0,d.jsx)(dr.Elements,{stripe:sa,options:Os,children:(0,d.jsx)(ac,{sessionId:e,nonce:t,email:re.email,billingName:_r||void 0,onBuyerIdentityReady:It,billingApiUrl:w,onTokenizedBody:Qr,onErrorChange:ze,isProcessing:Ie,onButtonClick:W,onDecline:y,onTechnicalFailure:Fo,runBeforeButtonClick:Bn,onLoadStateChange:Ys,placeholderBorderRadius:Po,popupCapabilityOwner:ne,externalTelemetryContext:ol,presentationMode:Bo})}),Oo&&(0,d.jsx)(dr.Elements,{stripe:cn,options:Ds,children:(0,d.jsx)(ic,{sessionId:e,nonce:t,email:re.email,billingName:_r||void 0,onBuyerIdentityReady:It,billingApiUrl:w,intentKind:Ot>0?"payment":"setup",expressMethods:Do,onTokenizedBody:Qr,onErrorChange:ze,onButtonClick:W,onDecline:y,onTechnicalFailure:Fo,runBeforeButtonClick:Bn,onLoadStateChange:Js,placeholderBorderRadius:Po,popupCapabilityOwner:ne,externalTelemetryContext:De})}),ca&&(0,d.jsx)(sc,{sessionId:e,nonce:t,email:re.email,billingName:[re.firstName,re.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:w,paymentElementMethods:Va,stripeInstance:cn,paymentElementBaseOptions:qi,futureUseSession:_t,onTokenizedBody:Qr,onErrorChange:ze,onButtonClick:W,onDecline:y,runBeforeButtonClick:Bn,onLoadStateChange:Qs,isProcessing:Ie,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:de.submitButton,themeId:ct,onExpandApm:kt,expandedApmMethod:Ir,buttonAppearance:{backgroundColor:de.cardButton?.backgroundColor,borderColor:de.cardInputBorder,textColor:de.cardButton?.color,borderRadius:Po}})]}),ve&&(Vc||jc||Wc)&&(0,d.jsx)(vi,{label:"or pay with card"}),ve&&gl]})}var D=require("react/jsx-runtime"),ra=44,_s="flopay_checkout_saved_payment_resume",_i=new Map,Ei=new Map;function mc(e,t){t.settled&&t.consumers===0&&_i.get(e)===t&&_i.delete(e)}function su(e,t,r){let n=Ei.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};Ei.set(e,s);let c=()=>{Ei.get(e)===s&&Ei.delete(e)};return a.then(c,c),a}function Da(e){return new Promise(t=>setTimeout(t,e))}function Ii(e,t,r){let n=si({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ne.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Oa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ws(e,t,r,n,a,s){let c=Ii(e,t,r);c.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Oa(c)}function yc(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 fc(e,t,r,n,a){let s=(0,Ne.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 Ne.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof Ne.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 Rs(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,Ne.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var lu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function cu(e){return new co.FloPay(lu,{publishableKey:"provider_unavailable",...e})}async function ks(e,t){let{publishableKey:r,paypalPublishableKey:n}=ls(e);return{...await cs({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function Ts(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function du(){if(!Ts())return null;try{let e=window.sessionStorage.getItem(_s);return e?JSON.parse(e):null}catch{return null}}function gc(e){if(Ts())try{window.sessionStorage.setItem(_s,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Es(){if(Ts())try{window.sessionStorage.removeItem(_s)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function uu(){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 hc(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 Is(e,t){return(0,Ne.resolveCheckoutLogLayout)(!!e,t)}function pu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Pc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function mu(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 Ti({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:c,loading:p,error:y,onComplete:g,onError:E,onInstrument:R,onDecline:_,onCancel:H,onCountryChange:T,onZipChange:Y,showPayPal:B=!0,showStripe:f=!0,walletPresentation:h="auto",enabledPaymentMethods:ge,showApplePay:S=!0,showGooglePay:Me=!0,debug:A=!1,layout:ie,theme:he,buttonsTheme:fe,buttonsStyles:Re,cardButtonContent:ct,cardBackButtonContent:Ke,cardTitleContent:F,showSecurityFooter:St,onButtonClick:et,onBeforeButtonClick:Ue,enableAVS:ye,cardFieldOrder:J,cardAutoFocus:W,cardPreFormSlot:Fe,avsLayout:dt,submitLabel:We,className:Z,initialErrorMessage:L=null,initialPayPalOrderId:le,children:j,checkoutMode:Se,confirmLabel:xe,renderConfirmButton:Pe,onSessionCompleted:Be}){let M=(0,Ne.resolveBillingApiUrl)(n),nt=(0,P.useMemo)(()=>(0,Ne.resolveTheme)(he),[he]),je=s??nt?.appearance,ut=r?"embedded_checkout":"standard_checkout",Ge=Is(j,ie),[$e,Rt]=(0,P.useState)(null),[Ot,zt]=(0,P.useState)(null),Ft=(0,P.useRef)(null),ue=(0,P.useRef)(null),pe=(0,P.useRef)(0),[X,Pt]=(0,P.useState)(null),pt=(0,P.useRef)(null),[V,rt]=(0,P.useState)(null),wt=(0,P.useMemo)(()=>r?(0,gt.serializeCreateParams)(r):"",[r]),ke=r?`create:${wt}`:`session:${e??""}`,v=Pc(V),U=(0,P.useRef)(new Set),ne=(0,P.useRef)(ke),Ae=(0,P.useRef)(ke);wo(()=>{Ae.current=ke,ne.current!==ke&&(ne.current=ke,U.current.clear())},[ke]);let Dt=(0,P.useCallback)(z=>{if(Ae.current===ke){if(as.FLO_INSTRUMENT_ONCE_NAMES.has(z.name)){if(U.current.has(z.name))return;U.current.add(z.name)}(0,Xe.invokeMerchantCallback)(()=>R?.(z))}},[ke,R]),ot=Yo(Dt,ke),De=(0,P.useRef)(!1),Oe=(0,P.useCallback)(z=>{if(De.current)return;let O=z.gateway||!v?z:{...z,gateway:v};Dt(O)},[Dt,v]);(0,P.useEffect)(()=>{ot({class:"lifecycle",name:"checkout.mount"})},[ot]);let[_t,u]=(0,P.useState)(e??""),C=e??_t,Q=r?"":C,[ce,N]=(0,P.useState)(!0),[w,qt]=(0,P.useState)(null),[Ar,mr]=(0,P.useState)(0),[Fr,st]=(0,P.useState)("full"),[Gr,Yr]=(0,P.useState)(!1),[Br,Xt]=(0,P.useState)(L),[ar,tr]=(0,P.useState)(null),[In,Jt]=(0,P.useState)(null),[qn,Dr]=(0,P.useState)(!1),[Zt,ir]=(0,P.useState)(void 0),[nn,mt]=(0,P.useState)(""),[Tt,Or]=(0,P.useState)(!1),[sr,Qt]=(0,P.useState)(!1),[zr,Pr]=(0,P.useState)(!1),jt=(0,P.useRef)(null),Lr=(0,P.useRef)(0),Er=(0,P.useRef)(void 0),[Ce,Nr]=(0,P.useState)("loading"),[_n,Tn]=(0,P.useState)(0),vr=(0,P.useRef)(!1),pn=(0,P.useRef)(!1),mn=(0,P.useRef)(!1),Mn=(0,P.useRef)(null),Lt=(0,P.useRef)(null),ve=(0,P.useMemo)(()=>({checkoutMode:Se??Fr,layout:pu(j,ie)}),[Se,j,Fr,ie]),on=(0,P.useRef)(g);on.current=g;let K=(0,P.useRef)(E);K.current=E;let Nt=(0,P.useRef)(_);Nt.current=_;let ae=(0,P.useCallback)(z=>di(Mn,async O=>{try{return await z(O)}catch(se){throw O.aborted?Jo(se):se}}),[]);(0,P.useEffect)(()=>()=>{Mn.current?.abort(),Mn.current=null},[]);let Ht=(0,P.useCallback)((z,O)=>{Ft.current=z,zt(z),pt.current=O,Pt(O)},[]),Gt=(0,P.useCallback)(()=>{let z=ue.current;z&&(ue.current=null,z.destroy())},[]);(0,P.useEffect)(()=>{Rr(Ot)?.setCheckoutContext(ve),X&&X!==Ot&&Rr(X)?.setCheckoutContext(ve)},[Ot,X,ve]);let be=(0,P.useRef)(Be);be.current=Be;let Ut=(0,P.useCallback)(z=>{Nr(z),!(z!=="exhausted"||mn.current)&&(mn.current=!0,K.current?.(new Ne.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),tt=(0,P.useCallback)(()=>{Nr("retrying"),Tn(z=>z+1)},[]);(0,P.useEffect)(()=>{Nr("loading"),Tn(0),mn.current=!1},[C]),(0,P.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ne.SDK_VERSION,checkout_type:ut,checkout_layout:Ge,billing_api_url:M})},[Ge,ut,M]);let at=(0,P.useMemo)(()=>r?(0,gt.serializeCreateParams)(r,!0):"",[r]),rr=(0,P.useMemo)(()=>nn===at?Zt:void 0,[Zt,nn,at]),Vr=(0,P.useMemo)(()=>r?ts(r,rr):void 0,[r,rr]),yn=Se??Vr?.checkoutMode??"full",lr=(0,P.useMemo)(()=>Vr?{...Vr,checkoutMode:yn}:void 0,[Vr,yn]);(0,P.useEffect)(()=>{ir(void 0),mt(at),Er.current=void 0,jt.current=null,Pr(!1)},[at]),(0,P.useEffect)(()=>{Xt(L)},[L]);let jn=(0,P.useCallback)((z,O,se)=>{(0,Xe.invokeMerchantCallback)(()=>{Nt.current?.(wr(z,O,se))})},[]),Vn=(0,P.useCallback)(async(z,O)=>{Xt(null),Jt(null),Dr(!1),tr("processing");let se=O?.sessionId??z.id,me=z.clientSecret||t,kt=Pc(z),Wt=Ft.current??pt.current,Ve=Rr(Wt),oe=Wt?null:Ii(M,a,ve),te={log:m=>{Ve?Ve.log(m):oe?.log(m)},error:m=>{Ve?Ve.error(m):oe?.error(m)},terminal:m=>{Ve?Ve.terminal(m):oe?.terminal(m)},performance:m=>{Ve?Ve.performance(m):oe?.performance(m)},now:()=>Ve?.now()??oe?.now()??0,elapsed:m=>Ve?.elapsed(m)??Math.max(0,(oe?.now()??m)-m)},Je=te.now(),Ee=!!(O?.initialAutoProcessingError||O?.initialAutoProcessingPending),it=!1,q,ee=()=>{it||(it=!0,Ee=!0,q=te.now(),te.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Bt=!1,Et=()=>{Bt||(Bt=!0,te.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),te.performance({stage:"processing",durationMs:te.elapsed(Je),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),q!==void 0&&te.performance({stage:"recovery",durationMs:te.elapsed(q),durationMode:"machine",paymentMethodCategory:"saved"}))};te.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),De.current=!0;try{te.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{De.current=!1}ot({class:"lifecycle",name:"payment.processing.started",provider:kt}),Ee&&ee();let x;try{let m=Hl(O?.initialAutoProcessingError),I=O?.initialAutoProcessingError?.type==="3ds_required"&&!O.initialAutoProcessingError.threeDSecureToken&&O.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:O.initialAutoProcessingError.nextActionRedirectUrl}:null,Le,Ze=He=>{ee();let It=Ia(M,se,z,a!==!1);return ae(Ye=>Zo(He,{billingApiUrl:M,sessionId:se,nonce:me,session:z,signal:Ye,...It.telemetry?{challengeTelemetry:It.telemetry}:{}})).finally(It.release)};if(I)Le=await Ze(I);else if(m)ee(),m.type==="paypal_redirect_required"&&Lt.current?.publishableKey&&gc({sessionId:se,publishableKey:Lt.current.publishableKey,paypalPublishableKey:Lt.current.paypalPublishableKey}),Le=await ae(He=>pi(m,{flopay:Ft.current,paypalFlopay:pt.current,attempt3DS:O?.attempt3DS,billingApiUrl:M,sessionId:se,session:z,telemetry:!1,signal:He})),m.type==="paypal_redirect_required"&&Es();else if(O?.initialAutoProcessingPending){let He=O.initialAutoProcessingPending,It=new co.PaymentAPI(M,{telemetry:!1}),Ye=await ae(Sr=>It.waitForCheckoutSessionCompletion(He.sessionId,{initialDelayMs:He.retryAfterMs,nonce:me,statusUrl:He.statusUrl,signal:Sr})),br=go(Ye,z),de=Ye.autoProcessingError?.type==="3ds_required"&&Ye.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Ye.autoProcessingError.nextActionRedirectUrl}:null;if(de)Le=await Ze(de);else{if(!oo(br))throw Wo(br);Le=no(br,se)}}else{if(O?.initialAutoProcessingError)throw Xn(O.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:O.initialAutoProcessingError.checkoutMethod});if(O?.fromCreateSession)return O?.fallbackToFull&&(st("full"),hc("full")),!1;{let He=await Qo({billingApiUrl:M,sessionId:se,session:z,nonce:me,telemetry:!1});He.type==="success"?Le=He.result:He.type==="next_action_required"?Le=await Ze(He):(ee(),He.type==="paypal_redirect_required"&&Lt.current?.publishableKey&&gc({sessionId:se,publishableKey:Lt.current.publishableKey,paypalPublishableKey:Lt.current.paypalPublishableKey}),Le=await ae(It=>pi(He,{flopay:Ft.current,paypalFlopay:pt.current,attempt3DS:O?.attempt3DS,billingApiUrl:M,sessionId:se,session:z,telemetry:!1,signal:It})),He.type==="paypal_redirect_required"&&Es())}}se&&(0,Nn.markSessionRecentlyCompleted)(se),Et(),Ee&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),te.terminal({outcome:Le.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Dr(Le.status==="authorized"),tr("success"),await Da(600),x=()=>on.current?.(Le)}catch(m){let I=fo(_a(m),se);if(I.code==="three_ds_aborted")return!1;let Le=I.checkoutMethod??Ea;Xt(I.message),Jt(I.message),Dr(!1),O?.fallbackToFull&&(te.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),st("full"),hc("full")),Et();let Ze=I.statusCode===void 0?void 0:(0,Ne.telemetryStatusClass)(I.statusCode,"unknown"),He=Ze==="4xx"?{requestCategory:"process_payment",statusClass:Ze}:{},It=Ze===void 0||Ze==="4xx";if(It&&(I.telemetryOutcome==="payment_declined"||!!(I.declineCode||I.code?.toLowerCase().includes("declin"))))te.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...He});else if(It&&(I.telemetryOutcome==="validation_rejected"||I.type==="validation_error"))te.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...He});else{let de=(0,Ne.classifyTelemetryFailure)(m,Ee?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Sr=I.telemetryRequestCategory??"process_payment";De.current=!0;try{te.error({...de,...I.telemetryFailureCategory?{failureCategory:I.telemetryFailureCategory}:{},stage:Ee?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Sr})}finally{De.current=!1}ot({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Sr,provider:kt})}return(0,Xe.invokeMerchantCallback)(()=>K.current?.(I)),jn(Le,I,{code:I.code,declineCode:I.declineCode}),tr("error"),await Promise.allSettled([Da(400),O?.ensureProvidersReady?O.ensureProvidersReady():Promise.resolve()]),Ee&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Et(),oe&&Oa(oe),tr(null),Jt(null)}return(0,Xe.invokeMerchantCallback)(x),!0},[jn,ot,t,M,ae,a,ve]);(0,P.useEffect)(()=>{if(typeof window>"u"||pn.current)return;let z=new URLSearchParams(window.location.search),O=z.get("payment_intent_client_secret");if(!O)return;let se=du();se&&(pn.current=!0,(async()=>{let me,kt=0;Xt(null),Jt(null),tr("processing"),Yr(!0);try{if(z.get("redirect_status")==="failed")throw Object.assign(new Ne.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Wt,paypalFlopay:Ve}=await cs({publishableKey:se.publishableKey,paypalPublishableKey:se.paypalPublishableKey,billingApiUrl:M,locale:c,telemetry:a});me=Rr(Ve??Wt),me?.setCheckoutContext(ve),kt=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 oe=(Ve??Wt)?.getRawProvider();if(!oe)throw Object.assign(new Ne.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:te,error:Je}=await oe.retrievePaymentIntent(O);if(Je)throw Object.assign(new Ne.FloPayError(Je.message??"Failed to retrieve PayPal payment status.","api_error",{code:Je.code}),{checkoutMethod:"paypal"});let Ee=xl(te?.status);if(!te||Ee==="failed")throw Object.assign(new Ne.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let it=typeof te.payment_method=="string"?te.payment_method:te.payment_method?.id,q=Ee;if(se.sessionId){let Et=(await new co.PaymentAPI(M,{telemetry:!1}).getUnifiedCheckoutSession(se.sessionId)).data.session;if(Et&&Et.status!=="complete"){let x=await Qo({billingApiUrl:M,sessionId:se.sessionId,session:Et,telemetry:!1,tokenizedData:{id:it??te.id,type:"card",threeDSecureActionResultTokenId:te.id,isPaypal:!0}});if(x.type!=="success")throw Object.assign(new Ne.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});q=x.result.status}}se.sessionId&&(0,Nn.markSessionRecentlyCompleted)(se.sessionId),me?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),me?.performance({stage:"redirect_resume",durationMs:me.elapsed(kt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),me?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),tr("success"),await Da(600),(0,Xe.invokeMerchantCallback)(()=>on.current?.({status:q,paymentIntentId:te.id,paymentMethodId:it,checkoutMethod:"paypal"}))}catch(Wt){let Ve=fo(_a(Wt),se.sessionId),oe=Ve.checkoutMethod??"paypal",te=!!(Ve.declineCode||Ve.code?.toLowerCase().includes("declin"));if(me)me.performance({stage:"redirect_resume",durationMs:me.elapsed(kt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),te?me.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):me.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(te){let Je=Ii(M,a,ve);Je.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Oa(Je)}else ws(M,a,ve,"REDIRECT_RESUME_FAILED","redirect_resume");Xt(Ve.message),Jt(Ve.message),(0,Xe.invokeMerchantCallback)(()=>K.current?.(Ve)),jn(oe,Ve,{code:Ve.code,declineCode:Ve.declineCode}),tr("error"),await Da(400)}finally{Es(),uu(),tr(null),Jt(null),Yr(!1)}})())},[jn,c,M,a,ve]);let eo=(0,P.useRef)(null),xn=(0,P.useMemo)(()=>lr?(0,gt.serializeCreateParams)(lr):"",[lr]),po=(0,P.useRef)(lr);po.current=lr,(0,P.useEffect)(()=>{u(e??"")},[e]),(0,P.useEffect)(()=>{vr.current=!1,Xt(L),Jt(null),Dr(!1),tr(null)},[xn,L,e]);async function to(z,O,se){let me=Ii(M,a,ve),kt=new co.PaymentAPI(M,{telemetry:!1}),Wt=!1;try{let Ve=z.idempotencyKey===void 0?void 0:(0,Ne.resolveIdempotencyKey)(z.idempotencyKey),oe=(0,gt.readCachedInlineSession)(O,se),te=(0,gt.readCachedInlineIdempotencyKey)(O,se);oe?.canonicalIdentity===se&&te&&te.canonicalIdentity===void 0&&((0,gt.persistCachedInlineIdempotencyKey)(O,se,te.idempotencyKey),te={...te,canonicalIdentity:se});let Je=Ve??(te?.canonicalIdentity===se?te.idempotencyKey:void 0),Ee,it=!1;me.log({name:oe?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let q=oe?.sid??null,ee=null,Bt,Et,x=!1;if(q)try{ee=await kt.getUnifiedCheckoutSession(q,oe?.nonce),oe&&oe.canonicalIdentity===void 0&&((0,gt.legacyCachedSessionMatchesDraft)(ee.data.session,z)?((0,gt.persistCachedInlineSession)(O,se,q,oe.nonce??ee.data.session?.clientSecret),te&&te.canonicalIdentity===void 0&&((0,gt.persistCachedInlineIdempotencyKey)(O,se,te.idempotencyKey),Je??(Je=te.idempotencyKey))):((0,gt.clearCachedInlineCheckout)(O,se),te=null,Je=Ve,q=null,ee=null));let I=ee?.data.session?.status,Le=ee?.data.session,Ze=Le?.clientSecret||oe?.nonce;if(q&&Le?.buyerIdentified===!1&&Ze&&(Et=Vo(kt,q,Ze,z.account)),q&&ee&&I==="complete"){if((0,Nn.wasSessionRecentlyCompleted)(q))return{sid:q,result:ee};(0,gt.clearCachedInlineCheckout)(O,se),q=null,ee=null,it=!0}}catch{me.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),oe?.canonicalIdentity===void 0?((0,gt.clearCachedInlineCheckout)(O,se),Je=Ve):(0,gt.clearCachedInlineSession)(O,se),q=null}if(!q){!Ve&&(it||!Je)&&(Je=(0,Ne.resolveIdempotencyKey)(),Ee=Je),Je&&(0,gt.persistCachedInlineIdempotencyKey)(O,se,Je);let I=me.now(),Le=0;me.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ze={...z,idempotencyKey:Je,avsCheck:!!ye,avsConfig:typeof ye=="object"?ye:void 0,checkoutType:"embedded_checkout",checkoutLayout:Is(j,ie)};Object.defineProperty(Ze,co.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Ye=>{Le=Math.max(Le,Ye)}}});let He=()=>{yc(me,"session_create",I,Le)},It=Ye=>{fc(me,Ye,"session_create",I,Le)&&ot({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,Ne.isDetachedSessionEligible)(Ze)){let Ye=await kt.createDetachedSession(Ze);Ye.claimed.catch(()=>{}),ee=Ye.shell,q=Ye.sessionId,Et=Ye.claim;let br=me.now();me.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Bt=Ye.claimed.then(de=>{let Sr=de.data.session?.id??Ye.sessionId;return Sr&&(0,gt.persistCachedInlineSession)(O,se,Sr,de.data.session?.clientSecret??Ye.nonce),yc(me,"session_claim",br),He(),de},de=>{throw(0,gt.clearCachedInlineSession)(O,se),fc(me,de,"session_claim",br,0)&&ot({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),de}).finally(()=>Oa(me)),Bt.catch(()=>{}),Wt=!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()-I,durationMode:"machine",requestCategory:"session_create",attempt:Le,statusClass:"2xx",paymentMethodCategory:"card"})}else ee=await kt.createAndFetchSession(Ze),He()}catch(Ye){throw It(Ye),Ye}q=ee.data.session?.id??q??"",q&&!Bt&&(0,gt.persistCachedInlineSession)(O,se,q,ee.data.session?.clientSecret)}let m=ee?.data.session;return!Et&&q&&m?.buyerIdentified===!1&&m.clientSecret&&(Et=Vo(kt,q,m.clientSecret,z.account)),{sid:q??"",result:ee,sdkGeneratedIdempotencyKey:Ee,...Bt?{claimed:Bt}:{},...Et?{claim:Et}:{},...x?{claimRequiresIdentity:!0}:{}}}finally{Wt||Oa(me)}}let an=(0,P.useRef)(to);wo(()=>{an.current=to},[to]);let An=(0,P.useCallback)(async(z,O)=>{let se=po.current;if(!se)throw new Ne.FloPayError("createSession is required to bootstrap checkout.","validation_error");let me=ts(se,z),kt=(0,gt.serializeCreateParams)(me),Wt=(0,gt.hashCreateParams)(me),Ve=_i.get(kt);if(!Ve){let Je={canonicalIdentity:kt,promise:an.current(me,Wt,kt),consumers:0,settled:!1};Ve=Je,_i.set(kt,Je);let Ee=()=>{Je.settled=!0,mc(kt,Je)};Je.promise.then(Ee,Ee)}Ve.consumers+=1;let oe=!1,te=()=>{oe||(oe=!0,Ve.consumers-=1,mc(kt,Ve))};O?.(te);try{let Je=await Ve.promise;eo.current=kt,z&&(mt(at),ir(m=>kl(m,z)));let{sid:Ee,result:it,claimed:q,claim:ee,claimRequiresIdentity:Bt}=Je;if(Er.current=ee,Pr(Bt===!0),Rt(it),it.data.session&&rt(it.data.session),Ee&&u(Ee),q){Lr.current+=1;let m=Lr.current;jt.current=q,Qt(!0),q.then(I=>{Lr.current===m&&(jt.current===q&&(jt.current=null),Rt(I),I.data.session&&rt(I.data.session),Qt(!1),Pr(!1))},I=>{Lr.current===m&&(jt.current===q&&(jt.current=null),Qt(!1),Pr(!1),qt(I instanceof Ne.FloPayError?I:new Ne.FloPayError(I instanceof Error?I.message:"Failed to create session","api_error")))})}else Lr.current+=1,jt.current=null,Qt(!1),Pr(!1);let{flopay:Et,paypalFlopay:x}=await ks(it,{billingApiUrl:M,locale:c,telemetry:a}).catch(m=>{throw _l(m,Ee||it.data.session?.id)});return Ht(Et,x),N(!1),Je}catch(Je){throw eo.current===kt&&(eo.current=null),Je}finally{O||te()}},[at,Ht,c,M,a]),sn=(0,P.useRef)(Vn);sn.current=Vn;let Wn=(0,P.useRef)(An);Wn.current=An;let Vt=(0,P.useCallback)(async z=>{if(!mu(z)||Tt)return{sessionId:_t,session:V};Or(!0);try{let O=await An(z);return{sessionId:O.sid,session:O.result.data.session??null}}finally{Or(!1)}},[An,Tt,_t,V]),Xr=(0,P.useCallback)(async z=>{let O=Er.current;if(!O)return;let se=Lr.current,me=await O(z);Lr.current===se&&(Rt(me),me.data.session&&rt(me.data.session))},[]),Jr=(0,P.useCallback)(async()=>{await jt.current},[]),Zr=(0,P.useCallback)(async()=>(await Jr(),{proceed:!0}),[Jr]);(0,P.useEffect)(()=>{let z=!1,O,se=++pe.current;Gt(),qt(null),mr(0);let me=()=>{z=!0,pe.current===se&&(pe.current+=1,Gt())},kt=po.current;if(xn&&kt)return st(yn),N(!1),eo.current===xn?me:(rt(El(kt,Se)),(async()=>{let oe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),te=yn==="auto"&&!vr.current&&!oe;te&&(Xt(null),Jt(null),tr("processing"));let Je=!1;try{let Ee=await Wn.current(void 0,Bt=>{O=Bt});Je=!0;let it=Ee.result.data.session??null;Lt.current=ls(Ee.result);let q=Rs(Ee.result),ee=(0,Nn.wasSessionRecentlyCompleted)(Ee.sid||it?.id);if(!z&&te&&it&&!q&&!ee){vr.current=!0,await su(xn,Ee.sdkGeneratedIdempotencyKey,()=>sn.current(it,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:Ee.result.autoProcessingError,initialAutoProcessingPending:Ee.result.autoProcessingPending,autoProcessingAttempted:Ee.result.autoProcessingAttempted,sessionId:Ee.sid||it.id}));return}!z&&te&&((q||ee)&&(vr.current=!0),tr(null),Jt(null))}catch(Ee){if(z)return;let it=ei(Ee);if(te&&it==="session_auto_completed"){vr.current=!0,tr("success"),await Da(600),z||((0,Xe.invokeMerchantCallback)(()=>{on.current?.({status:"succeeded"})}),tr(null),Jt(null));return}if(te&&(tr(null),Jt(null)),!Je){let ee=Tl(Ee),Bt=(0,Ne.toPublicCheckoutInitError)(Ee,ee?{stage:"provider_load",provider:"stripe",...ee}:{stage:"session_request"});(ee||!(Ee instanceof Ne.FloPayError))&&(0,Xe.invokeMerchantCallback)(()=>K.current?.(Bt)),qt(Bt);return}let q=Ee instanceof Ne.FloPayError?Ee:new Ne.FloPayError(Ee instanceof Error?Ee.message:"Failed to create session","api_error");qt(q)}finally{O?.(),O=void 0}})(),()=>{me(),O?.()});N(!0);async function Wt(){let oe=!1,te=!1,Je=null;try{let Ee=new co.PaymentAPI(M,{telemetry:!1}),it=await Ee.getUnifiedCheckoutSession(C,t);if(te=!0,Je=it,z)return;Rt(it);let q=it.data.session??null;if(rt(q),!q)throw new Ne.FloPayError("No session data returned","api_error");let ee=q.checkoutMode;if(ee==="setup")throw new Ne.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(q.status==="authorized"){N(!1),(0,Xe.invokeMerchantCallback)(()=>{on.current?.(no(q,C)),be.current?.(q.successUrl??"")});return}if(q.status==="complete"){N(!1),(0,Xe.invokeMerchantCallback)(()=>{be.current?.(q.successUrl??"")});return}if(q.status==="expired")throw Qa(q);oe=!0;let Bt=Se??ee??"full";st(Bt),Lr.current+=1;let Et=q.clientSecret||t;Er.current=q.buyerIdentified===!1&&Et?Vo(Ee,C,Et,{...q.customer?.id?{userId:q.customer.id}:{}}):void 0,Qt(!1),Pr(!1);let x=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),m=Rs(it);if(Bt==="auto"&&!vr.current&&!x&&!m){vr.current=!0;let I=Ve(it);try{if(await sn.current(q,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>I,sessionId:C||q.id}),z)return;await I,z||N(!1);return}catch{if(z)return;await I,z||N(!1);return}}await Ve(it),z||N(!1)}catch(Ee){if(z)return;let it=Rl(Ee,oe);if(oe&&ot({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),it){let{errorCode:Et,stage:x,...m}=it;ws(M,a,ve,Et,x,m)}if(it?.stage==="provider_load"&&(Se??Je?.data.session?.checkoutMode??"full")==="full"&&wl(Je,B,f)){let Et=cu({billingApiUrl:M,locale:c,telemetry:a});ue.current=Et,Ht(Et,null),mr(1),N(!1);return}let q=it?.stage==="provider_load",ee="session_request";q?ee="provider_load":te&&(ee="post_session");let Bt=(0,Ne.toPublicCheckoutInitError)(Ee,{stage:ee,provider:"stripe",sessionId:C||void 0});(q||!(Ee instanceof Ne.FloPayError))&&(0,Xe.invokeMerchantCallback)(()=>K.current?.(Bt)),qt(Bt),N(!1)}}async function Ve(oe){let{flopay:te,paypalFlopay:Je,...Ee}=await ks(oe,{billingApiUrl:M,locale:c,telemetry:a});Lt.current={publishableKey:Ee.publishableKey,paypalPublishableKey:Ee.paypalPublishableKey},Ht(te,Je),mr(0)}return Wt(),me},[Se,xn,yn,Q,t,B,f]);let fn=(0,P.useCallback)(async()=>{if(!$e||Ar!==1)return;let z=pe.current;mr(2);try{let{flopay:O,paypalFlopay:se}=await ks($e,{billingApiUrl:M,locale:c,telemetry:a});if(pe.current!==z)return;Gt(),Ht(O,se),mr(0)}catch(O){if(pe.current!==z)return;let{errorCode:se,stage:me,...kt}=es(O);ws(M,a,ve,se,me,kt)}},[Gt,Ht,c,Ar,M,a,ve,$e]),yt=!!(C&&(V?.clientSecret||t)),nr=Gr||!yt,Ir=(0,P.useCallback)(async()=>{if(!(Gr||!yt||!V)){Yr(!0),Xt(null);try{await Vn(V,{attempt3DS:!0,fallbackToFull:!0,sessionId:C||V.id})}finally{Yr(!1)}}},[C,Gr,yt,Vn,V]),Wr=(0,Ne.resolveDirectPaypalConfig)($e?.data.paypal,le),_o=Rs($e),gn=(0,P.useMemo)(()=>{if(!(!$e||!V||!$e.data.stripe?.publishableKey))return{billingApiUrl:M}},[$e,V,M]),ro=!!(r&&!j&&ie==="buttons"&&Ue&&yn==="full"),ln=!!(C&&((0,Ne.isMountableVaultBlock)(V?.vault)||(0,Dn.canRecoverHostedCardForm)(V))),Cr=(0,P.useMemo)(()=>({session:V,loading:ce,error:w,checkoutMode:Fr,inlineSessionDraft:lr,applyInlineSessionPatch:ro?Vt:void 0,inlineSessionPatchProcessing:Tt,claimPending:sr,claimRequiresIdentity:zr,claimBuyerIdentity:Xr,waitForDataAttachment:Jr}),[V,ce,w,Fr,lr,ro,Vt,Tt,sr,zr,Xr,Jr]),mo=!!r&&ie==="buttons"&&!_o&&!ln&&(!Ot||!gn),qr=ar?(0,D.jsx)(tn,{status:ar,errorMessage:In,authorized:qn}):null;if(ce&&!ln){if(p)return(0,D.jsxs)(D.Fragment,{children:[p,qr]});if(ie==="buttons"){let z=nt?.buttonsLayout?.cardButton?.borderRadius??nt?.appearance.variables?.borderRadius??8,O=se=>(0,D.jsx)("div",{style:{height:se,borderRadius:z,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,D.jsxs)(D.Fragment,{children:[(0,D.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[B&&O(ra),f&&(S||Me)&&O(ra),f&&O(ra),(0,D.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),qr]})}return(0,D.jsxs)(D.Fragment,{children:[(0,D.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,D.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,D.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),qr]})}return w?y?(0,D.jsx)(On.Provider,{value:Cr,children:y(w)}):(0,D.jsx)(On.Provider,{value:Cr,children:(0,D.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:w.message})}):mo?(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(On.Provider,{value:Cr,children:(0,D.jsx)(fu,{onButtonClick:et,showPayPal:B,showStripe:f,showApplePay:S,showGooglePay:Me,theme:he,buttonsTheme:fe,buttonsStyles:Re,cardButtonContent:ct,cardBackButtonContent:Ke,cardTitleContent:F})}),qr]}):_o&&V&&Wr?(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(On.Provider,{value:Cr,children:(0,D.jsxs)("div",{className:Z,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Br&&(0,D.jsx)(Xo,{icon:!1,children:Br}),Ce==="retrying"&&(0,D.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ce==="exhausted"&&(0,D.jsxs)("div",{role:"alert",children:[(0,D.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,D.jsx)("button",{type:"button",onClick:tt,children:"Retry PayPal"})]}),Ce!=="exhausted"&&(0,D.jsx)("div",{"aria-hidden":Ce==="retrying"?!0:void 0,style:Ce==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,D.jsx)(jl,{sessionId:C,nonce:V.clientSecret||void 0,billingApiUrl:M,email:V.customer?.email||lr?.account?.email,billingName:[V.customer?.firstName,V.customer?.lastName].filter(Boolean).join(" ")||[lr?.account?.firstName,lr?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Xr,clientId:Wr.clientId,environment:Wr.environment,currency:(V.currency??"usd").toUpperCase(),isSubscription:V.mode==="subscription",providerObjectType:Wr.providerObjectType,approvalPresentation:Wr.approvalPresentation,existingOrderId:Wr.existingOrderId,onComplete:g,onErrorChange:Xt,onDecline:_,onCancel:H,onButtonClick:et,runBeforeButtonClick:Zr,onInitializationStateChange:Ut,allowAutomaticRetry:_n===0,session:V,telemetry:a,telemetryContext:ve,onInstrument:Oe,debug:A},`${ke}:paypal-init-${_n}`)})]})}),qr]}):Fr==="confirm"?(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(On.Provider,{value:Cr,children:(0,D.jsx)(Ra,{flopay:Ot,paypalFlopay:X,options:gn??{billingApiUrl:M},onInstrument:Oe,children:(0,D.jsxs)("div",{className:Z,children:[Br&&(0,D.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Br}),Pe?Pe({onConfirm:Ir,isProcessing:nr}):(0,D.jsx)("button",{type:"button",onClick:Ir,disabled:nr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:nr?"not-allowed":"pointer",opacity:nr?.6:1},children:Gr?"Processing...":xe??"Confirm Purchase"})]})},ke)}),qr]}):(!Ot||!gn)&&!(ln&&Fr==="full")?(0,D.jsx)(D.Fragment,{children:qr}):(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(On.Provider,{value:Cr,children:(0,D.jsxs)(Ra,{flopay:Ot,paypalFlopay:X,options:gn??{billingApiUrl:M},onInstrument:Oe,children:[Ar===1&&(0,D.jsx)("button",{type:"button",onClick:fn,children:"Retry payment methods"}),j?(0,D.jsxs)(D.Fragment,{children:[Br&&(0,D.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Br}),(0,D.jsx)(yu,{sessionId:C,nonce:V?.clientSecret||void 0,billingApiUrl:M,session:V,submitLabel:We,walletPresentation:h,children:j})]}):(0,D.jsx)(ki,{sessionId:C,nonce:V?.clientSecret||void 0,telemetry:a,email:V?.customer?.email||lr?.account?.email,userId:V?.customer?.id||lr?.account?.userId,firstName:V?.customer?.firstName||lr?.account?.firstName,lastName:V?.customer?.lastName||lr?.account?.lastName,totalAmount:V?Math.round((0,Ne.buildCheckoutDisplayData)(V).total*100):0,currency:V?.currency?.toLowerCase()??"usd",onComplete:g,onError:E,onDecline:_,onCancel:H,error:Br,onErrorChange:Xt,showPayPal:B,showStripe:f,walletPresentation:h,enabledPaymentMethods:Ar?[]:ge??$e?.data.stripe?.enabledPaymentMethods??V?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:$e?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:Me,layout:ie,theme:he,buttonsTheme:fe,buttonsStyles:Re,appearance:je,cardButtonContent:ct,cardBackButtonContent:Ke,cardTitleContent:F,onButtonClick:et,onBeforeButtonClick:Ue,onBuyerIdentityReady:Xr,enableAVS:ye,...J?{cardFieldOrder:J}:{},...W===void 0?{}:{cardAutoFocus:W},...Fe?{cardPreFormSlot:Fe}:{},avsLayout:dt,country:V?.customer?.country,city:V?.customer?.city,state:V?.customer?.state,onCountryChange:T,onZipChange:Y,avsCheck:!!ye,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Is(j,ie),className:Z,submitLabel:We,directPaypal:Wr,isSubscription:V?.mode==="subscription",session:V,dataAttachmentPending:sr,dataAttachmentRequiresIdentity:zr,debug:A})]},ke)}),qr]})}function yu({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,children:c}){return(0,D.jsx)(D.Fragment,{children:P.default.Children.map(c,p=>{if(!P.default.isValidElement(p))return p;let y=p.props,g={};return y.sessionId||(g.sessionId=e),!y.nonce&&t&&(g.nonce=t),y.billingApiUrl||(g.billingApiUrl=r),y.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),y.walletPresentation===void 0&&(g.walletPresentation=s),n?.customer&&(y.email||(g.email=n.customer.email),y.userId||(g.userId=n.customer.id),y.firstName||(g.firstName=n.customer.firstName),y.lastName||(g.lastName=n.customer.lastName)),Object.keys(g).length===0?p:P.default.cloneElement(p,g)})})}function fu({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:s,buttonsTheme:c,buttonsStyles:p,cardButtonContent:y,cardBackButtonContent:g,cardTitleContent:E}){let[R,_]=(0,P.useState)(!1),H=(0,P.useMemo)(()=>(0,Ne.resolveTheme)(s),[s]),T=(0,P.useMemo)(()=>{let h=H?.buttonsLayout??(0,Ne.resolveButtonsLayoutTheme)(c);return p?{...h,...p,cardButton:{...h.cardButton,...p.cardButton},cardFormContainer:{...h.cardFormContainer,...p.cardFormContainer},backButton:{...h.backButton,...p.backButton},backButtonIcon:{...h.backButtonIcon,...p.backButtonIcon},submitButton:{...h.submitButton,...p.submitButton},title:{...h.title,...p.title}}:h},[H,c,p]),Y=H?.buttonsLayout?.cardButton?.borderRadius??H?.appearance.variables?.borderRadius??8,B=h=>(0,D.jsx)("div",{style:{height:h,borderRadius:Y,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),f=y===void 0?{boxSizing:"border-box",height:ra,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let h=T.cardInputBorder??"#e5e7eb",ge=T.cardInputBackground??"white",S=zo(g),Me=zo(E);return(0,D.jsxs)("div",{style:{backgroundColor:T.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...T.cardFormContainer},children:[(0,D.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,D.jsxs)("button",{type:"button",onClick:()=>_(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:S?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...T.backButton},children:[(0,D.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...T.backButtonIcon},children:(0,D.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,D.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,D.jsx)(jo,{content:g})]}),Me?(0,D.jsx)("div",{style:{flex:1}}):(0,D.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...T.title},children:(0,D.jsx)(ga,{content:E})})]}),(0,D.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${h}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,D.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,D.jsxs)("div",{style:{display:"flex"},children:[(0,D.jsx)("div",{style:{flex:1,backgroundColor:ge,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,D.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,D.jsx)("div",{style:{flex:1,backgroundColor:ge,borderTop:"none",borderRight:`1px solid ${h}`,borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,D.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,D.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${h}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,D.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,D.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...T.submitButton,opacity:.5}}),(0,D.jsx)("style",{children:`
|
|
38
|
+
`}),ya&&Po&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:C?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:Ve,style:{display:"inline-flex",alignItems:"center",gap:Qi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:$.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...$.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",...$.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)(Yo,{content:ye})]}),Sl?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:$.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...$.title},children:(0,l.jsx)(Pa,{content:N})})]}),!ya&&!Sl&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:es,order:C?-3:0,...$.title},children:(0,l.jsx)(Pa,{content:N})}),C&&te&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:te}),C&&vo&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:Wo,border:`1px solid ${bn(Xa)}`,borderRadius:lr,padding:"10px"},children:(0,l.jsx)("input",{ref:ct,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Or,onChange:i=>{Ht("email"),Vr.current=i.target.value,Lr(i.target.value)},onPointerDown:()=>Ht("email"),onKeyDown:()=>Ht("email"),onBlur:()=>{hn("email")&&Hr(!0),Do||Vi()},disabled:we,required:!0,"aria-invalid":Xa||void 0,"aria-describedby":Xa?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...ts}})}),Xa&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:fa,children:Ui.empty?"Email address is required":"Enter a valid email address"})]}),He&&(0,l.jsx)("div",{style:{order:C?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=jt,w=(X=!1)=>({backgroundColor:Wo,border:`1px solid ${bn(X)}`,borderRadius:lr,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ts}),Te=(0,c.getStateOptions)(i);return(0,l.jsxs)(l.Fragment,{children:[(0,c.isAVSFieldVisible)(He.address_line_1,i)&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{style:w(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:ln,onChange:X=>{Ht("line1"),Nr.current.addressLine1=!0,Sr.current=X.target.value,pr(X.target.value)},onPointerDown:()=>Ht("line1"),onKeyDown:()=>Ht("line1"),onBlur:()=>Pn("line1"),disabled:we,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:K()})}),nr("line1")&&(0,l.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:fa,children:"Street address is required"})]}),(0,c.isAVSFieldVisible)(He.address_line_2,i)&&(0,l.jsx)("div",{style:w(),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:Mn,onChange:X=>{Nr.current.addressLine2=!0,wr.current=X.target.value,Jt(X.target.value)},disabled:we,"data-testid":"flopay-address-line2",style:K()})}),((0,c.isAVSFieldVisible)(He.city,i)||(0,c.isAVSFieldVisible)(He.state,i))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(He.city,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Wo,borderTop:`1px solid ${bn(nr("city"))}`,borderRight:`1px solid ${bn(nr("city"))}`,borderBottom:`1px solid ${bn(nr("city"))}`,borderLeft:`1px solid ${bn(nr("city"))}`,padding:"10px",borderTopLeftRadius:lr,borderBottomLeftRadius:lr,...(0,c.isAVSFieldVisible)(He.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:ir,onChange:X=>{Ht("city"),Nr.current.city=!0,rr.current=X.target.value,Qr(X.target.value)},onPointerDown:()=>Ht("city"),onKeyDown:()=>Ht("city"),onBlur:()=>Pn("city"),disabled:we,required:!0,"aria-invalid":nr("city")||void 0,"aria-describedby":nr("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:K()})}),(0,c.isAVSFieldVisible)(He.state,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Wo,borderTop:`1px solid ${bn(nr("state"))}`,borderRight:`1px solid ${bn(nr("state"))}`,borderBottom:`1px solid ${bn(nr("state"))}`,borderLeft:`1px solid ${bn(nr("state"))}`,padding:"10px",borderTopRightRadius:lr,borderBottomRightRadius:lr,...(0,c.isAVSFieldVisible)(He.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${bn(nr("state")||nr("city"))}`}:{borderRadius:lr}},children:Te?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:ot,onChange:X=>{Ht("state"),Nr.current.state=!0,Xt.current=X.target.value,At(X.target.value)},onPointerDown:()=>Ht("state"),onKeyDown:()=>Ht("state"),onBlur:()=>Pn("state"),disabled:we,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:{...K(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,c.getStateLabel)(i)}),Te.map(X=>(0,l.jsx)("option",{value:X.code,children:X.name},X.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:ot,onChange:X=>{Ht("state"),Nr.current.state=!0,Xt.current=X.target.value,At(X.target.value)},onPointerDown:()=>Ht("state"),onKeyDown:()=>Ht("state"),onBlur:()=>Pn("state"),disabled:we,required:!0,"aria-invalid":nr("state")||void 0,"aria-describedby":nr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:K()})})]}),nr("city")&&(0,l.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:fa,children:"City is required"}),nr("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:fa,children:[(0,c.getStateLabel)(i)," is required"]}),((0,c.isAVSFieldVisible)(He.country,i)||(0,c.isAVSFieldVisible)(He.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)(He.country,i)&&(0,l.jsx)("div",{style:{flex:ve==="row"?1:void 0,backgroundColor:Wo,borderTop:`1px solid ${ma}`,borderRight:`1px solid ${ma}`,borderBottom:`1px solid ${ma}`,borderLeft:`1px solid ${ma}`,padding:"10px",...ve==="row"&&(0,c.isAVSFieldVisible)(He.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:jt,onChange:X=>{Nr.current.country=!0,Zt.current=X.target.value,Dt(X.target.value),ut?.(X.target.value),Xt.current="",At("")},disabled:we,autoComplete:"billing country","data-testid":"flopay-country",style:{...K(),cursor:"pointer"},children:[jt===""?(0,l.jsx)("option",{value:"",children:"Select country"}):null,c.COUNTRY_OPTIONS.map(X=>(0,l.jsxs)("option",{value:X.code,children:[X.flag," ",X.name]},X.code))]})}),(0,c.isAVSFieldVisible)(He.postal_code,i)&&(0,l.jsx)("div",{style:{flex:ve==="row"?1:void 0,backgroundColor:Wo,border:`1px solid ${sd}`,padding:"10px",...ve==="row"&&(0,c.isAVSFieldVisible)(He.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)(jt),autoComplete:"billing postal-code",value:yn,onChange:X=>{Ht("zip"),Nr.current.zip=!0,Fr.current=X.target.value,Yt(X.target.value),Xe?.(X.target.value)},onPointerDown:()=>Ht("zip"),onKeyDown:()=>Ht("zip"),onBlur:()=>{hn("zip")&&fo(!0)},disabled:we,required:Vt.required,"aria-invalid":Ja||void 0,"aria-describedby":Ja?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),Ja&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:fa,children:Vt.empty?`${(0,c.getPostalCodeLabel)(i)} is required`:Pu(i)})]})})()}),C&&pd,Kt&&(0,l.jsx)(na,{margin:"0.75rem 0",styleOverride:$.errorBanner,children:Kt})]}),Za={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"},El=i=>se?!ke||!Hn?(0,l.jsx)("pre",{"data-testid":i,style:Za,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:Za,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ke}`,` directPaypalConfigured=${Hn}`,` inAppBrowserDetected=${String(Ka)}`,` shouldRenderDirectPayPal=${qo}`,` shouldRenderStripePayPal=${jo}`,` hasPaypalStripeInstance=${!!js}`].join(`
|
|
39
|
+
`)}):null,_l=i=>se?!m||!cn?(0,l.jsx)("pre",{"data-testid":i,style:Za,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:Za,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${m}`,` currency=${qt}`,` amountInCents=${ca}`,` enabledPaymentMethods: ${JSON.stringify(_??[])}`,` enabledPaymentMethodsProvided=${da}`,` hasEnabledMethods=${Va}`,` expressMethods: ${JSON.stringify($a)}`,` walletExpressMethods: ${JSON.stringify(zo)}`,` paymentElementMethods: ${JSON.stringify($i)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ha)}`,` hasStripeInstance=${!!cn}`,` shouldRenderWallets=${Ro}`,` shouldRenderPaymentElement=${Vo}`].join(`
|
|
40
|
+
`)}):null,Il=Qe==="apm-expanding"||Qe==="apm-form"||Qe==="apm-collapsing",Ho;Qe==="apm-expanding"?Ho=gc:Qe==="apm-collapsing"&&(Ho=hc);let Qa=Rr?Ec(Hi,Rr,u):null;if(Ee==="buttons"){let i=Qe==="buttons"||Qe==="expanding"||Qe==="apm-expanding",w=Qe==="expanding"||Qe==="card"||Qe==="collapsing",K=qe===void 0?{boxSizing:"border-box",height:So,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Te;Qe==="expanding"||Qe==="apm-expanding"?Te=mu:(Qe==="collapsing"||Qe==="apm-collapsing")&&(Te=yu);let X;Qe==="expanding"?X=gc:Qe==="collapsing"&&(X=hc);let Ke={paypal:(0,l.jsxs)(l.Fragment,{children:[qo&&oe&&(0,l.jsxs)(l.Fragment,{children:[Ie&&(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)(Sa.Provider,{value:ae,children:(0,l.jsx)(Ra,{sessionId:e,nonce:t,billingApiUrl:$e,email:Pe.email,billingName:oo||void 0,onBuyerIdentityReady:Lt,clientId:oe.clientId,environment:oe.environment,currency:qt.toUpperCase(),isSubscription:Ze,providerObjectType:B,approvalPresentation:Ga==="popup"?void 0:Ga,onTokenizedBody:tn,onComplete:d,onErrorChange:Ne,onDecline:y,onCancel:b,onTechnicalFailure:No,onButtonClick:de,runBeforeButtonClick:Ln,isProcessing:we,onLoadStateChange:Ki,onInitializationStateChange:Gi,session:bt,existingOrderId:Ie?.orderId,debug:se},Ie?.orderId??"fresh")})]}),jo&&(0,l.jsx)(cr.Elements,{stripe:ua,options:$s,children:(0,l.jsx)(vc,{sessionId:e,nonce:t,email:Pe.email,billingName:oo||void 0,onBuyerIdentityReady:Lt,billingApiUrl:$e,onTokenizedBody:tn,onErrorChange:Ne,isProcessing:we,onButtonClick:de,onDecline:y,onTechnicalFailure:No,runBeforeButtonClick:Ln,onLoadStateChange:ol,placeholderBorderRadius:ao,popupCapabilityOwner:ae,externalTelemetryContext:yl,presentationMode:Uo})})]}),wallets:(0,l.jsxs)(l.Fragment,{children:[Ro?(0,l.jsx)(cr.Elements,{stripe:cn,options:Ws,children:(0,l.jsx)(Cc,{sessionId:e,nonce:t,email:Pe.email,billingName:oo||void 0,onBuyerIdentityReady:Lt,billingApiUrl:$e,intentKind:_t>0?"payment":"setup",expressMethods:zo,onTokenizedBody:tn,onErrorChange:Ne,onButtonClick:de,onDecline:y,onTechnicalFailure:No,runBeforeButtonClick:Ln,onLoadStateChange:il,placeholderBorderRadius:ao,popupCapabilityOwner:ae,externalTelemetryContext:be})}):null,!Ro&&ul?(0,l.jsx)("div",{style:{height:So,borderRadius:ao,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:(0,l.jsx)(l.Fragment,{children:Vo&&(0,l.jsx)(bc,{sessionId:e,nonce:t,email:Pe.email,billingName:[Pe.firstName,Pe.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Lt,billingApiUrl:$e,paymentElementMethods:Ha,stripeInstance:cn,paymentElementBaseOptions:Hi,futureUseSession:u,onTokenizedBody:tn,onErrorChange:Ne,onButtonClick:de,onDecline:y,runBeforeButtonClick:Ln,onLoadStateChange:ll,isProcessing:we,submitButtonColor:ko,submitButtonBorderRadius:lr,submitButtonStyle:$.submitButton,onExpandApm:st,expandedApmMethod:Rr,themeId:ze,buttonAppearance:{backgroundColor:$.cardButton?.backgroundColor,borderColor:$.cardInputBorder,textColor:$.cardButton?.color,borderRadius:ao}})}),card:(0,l.jsx)(l.Fragment,{children:C&&(0,l.jsx)("button",{type:"button",onClick:async()=>{we||!(await Ln("card")).proceed||(de?.("card"),mr())},disabled:we,style:{width:"100%",...K,...$.cardButton,...Ts({themeBundle:Dn,resolvedPrimaryColor:ko,resolvedBorderRadius:lr,submitButtonStyle:$.submitButton,explicitPrimaryColor:rn?.colorPrimary}),fontSize:$.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:we?"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:we?.6:1},onMouseEnter:yt=>{!we&&(Dn||rn?.colorPrimary)&&(yt.currentTarget.style.backgroundColor=dd)},onMouseLeave:yt=>{(Dn||rn?.colorPrimary)&&(yt.currentTarget.style.backgroundColor=ko)},onMouseDown:yt=>{yt.currentTarget.style.transform="scale(0.985)"},onMouseUp:yt=>{yt.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(Go,{content:qe})})})};return(0,l.jsxs)("form",{onSubmit:Xi,className:x,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(sa,{}),Oe&&(0,l.jsx)(on,{status:Oe,errorMessage:Kt,authorized:Wr}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Te?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Te?gu:{},...Te?{animation:Te,pointerEvents:"none"}:{}},children:[El("flopay-direct-paypal-gate-debug"),_l("flopay-stripe-gate-debug"),tr?tr.map(({group:yt,key:nn})=>(0,l.jsx)(o.default.Fragment,{children:Ke[yt]},nn)):(0,l.jsx)(Ps,{rows:ml,borderRadius:ao}),Kt&&Qe==="buttons"&&(0,l.jsx)(na,{margin:"0.25rem 0",styleOverride:$.errorBanner,children:Kt})]}),C&&w&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...X?{animation:X}:{},...Qe==="collapsing"?{pointerEvents:"none"}:{}},children:os}),m&&Il&&Rr&&Qa&&cn&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Ho?{animation:Ho}:{},...Qe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Zi,borderRadius:ns,...ga,padding:rs},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:Y,style:{display:"inline-flex",alignItems:"center",gap:Qi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:$.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...$.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",...$.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)(Yo,{content:ye})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:$.titleFontSize??"1.05rem",color:es,paddingRight:80,...$.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(Rr)}`})]}),(0,l.jsx)(cr.Elements,{stripe:cn,options:Qa,children:(0,l.jsx)(Es,{method:Rr,sessionId:e,nonce:t,email:Pe.email,billingName:[Pe.firstName,Pe.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Lt,billingApiUrl:$e,onTokenizedBody:tn,onErrorChange:Ne,onDecline:y,onCancel:Y,runBeforeButtonClick:Ln,onButtonClick:de,isProcessing:we,submitButtonColor:ko,submitButtonBorderRadius:lr,submitButtonStyle:$.submitButton,errorText:Kt})},Rr)]})})]})]})}if(Il&&Rr&&Qa&&cn&&m)return(0,l.jsxs)("form",{onSubmit:Xi,className:x,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(sa,{}),Oe&&(0,l.jsx)(on,{status:Oe,errorMessage:Kt,authorized:Wr}),(0,l.jsx)("div",{style:{...Ho?{animation:Ho}:{},...Qe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Zi,borderRadius:ns,...ga,padding:rs},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:Y,style:{display:"inline-flex",alignItems:"center",gap:Qi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:$.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...$.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",...$.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)(Yo,{content:ye})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:$.titleFontSize??"1.05rem",color:es,paddingRight:80,...$.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(Rr)}`})]}),(0,l.jsx)(cr.Elements,{stripe:cn,options:Qa,children:(0,l.jsx)(Es,{method:Rr,sessionId:e,nonce:t,email:Pe.email,billingName:[Pe.firstName,Pe.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Lt,billingApiUrl:$e,onTokenizedBody:tn,onErrorChange:Ne,onDecline:y,onCancel:Y,runBeforeButtonClick:Ln,onButtonClick:de,isProcessing:we,submitButtonColor:ko,submitButtonBorderRadius:lr,submitButtonStyle:$.submitButton,errorText:Kt})},Rr)]})})]});let Tl=nd||rd||od,yd={paypal:(0,l.jsxs)(l.Fragment,{children:[qo&&oe&&(0,l.jsxs)(l.Fragment,{children:[Ie&&(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)(Sa.Provider,{value:ae,children:(0,l.jsx)(Ra,{sessionId:e,nonce:t,billingApiUrl:$e,email:Pe.email,billingName:oo||void 0,onBuyerIdentityReady:Lt,clientId:oe.clientId,environment:oe.environment,currency:qt.toUpperCase(),isSubscription:Ze,providerObjectType:B,approvalPresentation:Ga==="popup"?void 0:Ga,onTokenizedBody:tn,onComplete:d,onErrorChange:Ne,onDecline:y,onCancel:b,onTechnicalFailure:No,onButtonClick:de,runBeforeButtonClick:Ln,isProcessing:we,onLoadStateChange:Ki,onInitializationStateChange:Gi,session:bt,existingOrderId:Ie?.orderId,debug:se},Ie?.orderId??"fresh")})]}),jo&&(0,l.jsx)(cr.Elements,{stripe:ua,options:$s,children:(0,l.jsx)(vc,{sessionId:e,nonce:t,email:Pe.email,billingName:oo||void 0,onBuyerIdentityReady:Lt,billingApiUrl:$e,onTokenizedBody:tn,onErrorChange:Ne,isProcessing:we,onButtonClick:de,onDecline:y,onTechnicalFailure:No,runBeforeButtonClick:Ln,onLoadStateChange:ol,placeholderBorderRadius:ao,popupCapabilityOwner:ae,externalTelemetryContext:yl,presentationMode:Uo})})]}),wallets:(0,l.jsx)(l.Fragment,{children:Ro&&(0,l.jsx)(cr.Elements,{stripe:cn,options:Ws,children:(0,l.jsx)(Cc,{sessionId:e,nonce:t,email:Pe.email,billingName:oo||void 0,onBuyerIdentityReady:Lt,billingApiUrl:$e,intentKind:_t>0?"payment":"setup",expressMethods:zo,onTokenizedBody:tn,onErrorChange:Ne,onButtonClick:de,onDecline:y,onTechnicalFailure:No,runBeforeButtonClick:Ln,onLoadStateChange:il,placeholderBorderRadius:ao,popupCapabilityOwner:ae,externalTelemetryContext:be})})}),apms:(0,l.jsx)(l.Fragment,{children:Vo&&(0,l.jsx)(bc,{sessionId:e,nonce:t,email:Pe.email,billingName:[Pe.firstName,Pe.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:$e,paymentElementMethods:Ha,stripeInstance:cn,paymentElementBaseOptions:Hi,futureUseSession:u,onTokenizedBody:tn,onErrorChange:Ne,onButtonClick:de,onDecline:y,runBeforeButtonClick:Ln,onLoadStateChange:ll,isProcessing:we,submitButtonColor:ko,submitButtonBorderRadius:lr,submitButtonStyle:$.submitButton,themeId:ze,onExpandApm:st,expandedApmMethod:Rr,buttonAppearance:{backgroundColor:$.cardButton?.backgroundColor,borderColor:$.cardInputBorder,textColor:$.cardButton?.color,borderRadius:ao}})})};return(0,l.jsxs)("form",{onSubmit:Xi,className:x,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(sa,{}),Oe&&(0,l.jsx)(on,{status:Oe,errorMessage:Kt,authorized:Wr}),tr===null?(0,l.jsx)(Ps,{rows:ml,borderRadius:ao}):(0,l.jsxs)(l.Fragment,{children:[br&&C&&os,br&&C&&Tl&&(0,l.jsx)(Ba,{label:"or pay another way"}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[El("flopay-direct-paypal-gate-debug-default"),_l("flopay-stripe-gate-debug-default"),tr.map(({group:i,key:w})=>i==="card"?null:(0,l.jsx)(o.default.Fragment,{children:yd[i]},w))]}),!br&&C&&Tl&&(0,l.jsx)(Ba,{label:"or pay with card"}),!br&&C&&os]})]})}var M=require("react/jsx-runtime"),Fo=44,Os="flopay_checkout_saved_payment_resume",xi=new Map,Mi=new Map;function _c(e,t){t.settled&&t.consumers===0&&xi.get(e)===t&&xi.delete(e)}function ku(e,t,r){let n=Mi.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};Mi.set(e,s);let d=()=>{Mi.get(e)===s&&Mi.delete(e)};return a.then(d,d),a}function Na(e){return new Promise(t=>setTimeout(t,e))}function Ai(e,t,r){let n=di({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Me.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Ua(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function As(e,t,r,n,a,s){let d=Ai(e,t,r);d.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Ua(d)}function Ic(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 Tc(e,t,r,n,a){let s=(0,Me.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 Me.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof Me.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 xs(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,Me.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var Eu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function _u(e){return new yo.FloPay(Eu,{publishableKey:"provider_unavailable",...e})}async function Fs(e,t){let{publishableKey:r,paypalPublishableKey:n}=ms(e);return{...await fs({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function Ls(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Iu(){if(!Ls())return null;try{let e=window.sessionStorage.getItem(Os);return e?JSON.parse(e):null}catch{return null}}function Mc(e){if(Ls())try{window.sessionStorage.setItem(Os,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Bs(){if(Ls())try{window.sessionStorage.removeItem(Os)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Tu(){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 Ac(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 Ds(e,t){return(0,Me.resolveCheckoutLogLayout)(!!e,t)}function Mu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function xc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Au(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 Fi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:d,loading:p,error:y,onComplete:b,onError:v,onInstrument:S,onDecline:E,onCancel:V,onCountryChange:x,onZipChange:D,showPayPal:A=!0,showStripe:g=!0,walletPresentation:O="auto",enabledPaymentMethods:ke,showApplePay:m=!0,showGooglePay:me=!0,debug:_=!1,layout:ne,paymentMethodLayout:fe,theme:ce,buttonsTheme:Ee,buttonsStyles:vt,cardButtonContent:ze,cardBackButtonContent:L,cardTitleContent:Ye,showSecurityFooter:at,onButtonClick:qe,onBeforeButtonClick:ye,enableAVS:N,cardFieldOrder:le,cardAutoFocus:de,cardPreFormSlot:rt,avsLayout:je,submitLabel:Q,className:W,initialErrorMessage:ee=null,initialPayPalOrderId:te,children:ve,checkoutMode:ue,confirmLabel:pe,renderConfirmButton:Fe,onSessionCompleted:ge}){let H=(0,Me.resolveBillingApiUrl)(n),Be=(0,R.useMemo)(()=>(0,Me.resolveTheme)(ce),[ce]),ut=s??Be?.appearance,Xe=r?"embedded_checkout":"standard_checkout",nt=Ds(ve,ne),[it,or]=(0,R.useState)(null),[_t,qt]=(0,R.useState)(null),Ce=(0,R.useRef)(null),oe=(0,R.useRef)(null),Ze=(0,R.useRef)(0),[J,Ct]=(0,R.useState)(null),Rt=(0,R.useRef)(null),[se,De]=(0,R.useState)(null),It=(0,R.useMemo)(()=>r?(0,ft.serializeCreateParams)(r):"",[r]),h=r?`create:${It}`:`session:${e??""}`,U=xc(se),he=(0,R.useRef)(new Set),ae=(0,R.useRef)(h),Wt=(0,R.useRef)(h);To(()=>{Wt.current=h,ae.current!==h&&(ae.current=h,he.current.clear())},[h]);let Bt=(0,R.useCallback)(T=>{if(Wt.current===h){if(us.FLO_INSTRUMENT_ONCE_NAMES.has(T.name)){if(he.current.has(T.name))return;he.current.add(T.name)}(0,Ge.invokeMerchantCallback)(()=>S?.(T))}},[h,S]),Ae=ra(Bt,h),be=(0,R.useRef)(!1),bt=(0,R.useCallback)(T=>{if(be.current)return;let q=T.gateway||!U?T:{...T,gateway:U};Bt(q)},[Bt,U]);(0,R.useEffect)(()=>{Ae({class:"lifecycle",name:"checkout.mount"})},[Ae]);let[u,B]=(0,R.useState)(e??""),I=e??u,xe=r?"":I,[z,F]=(0,R.useState)(!0),[$e,ar]=(0,R.useState)(null),[tr,br]=(0,R.useState)(0),[Tt,Zr]=(0,R.useState)("full"),[pn,sn]=(0,R.useState)(!1),[jt,Dt]=(0,R.useState)(ee),[yn,Yt]=(0,R.useState)(null),[ln,pr]=(0,R.useState)(null),[Mn,Jt]=(0,R.useState)(!1),[ir,Qr]=(0,R.useState)(void 0),[ot,At]=(0,R.useState)(""),[Or,Lr]=(0,R.useState)(!1),[Ir,jr]=(0,R.useState)(!1),[Fr,Zt]=(0,R.useState)(!1),Sr=(0,R.useRef)(null),wr=(0,R.useRef)(0),rr=(0,R.useRef)(void 0),[Xt,Vr]=(0,R.useState)("loading"),[Nr,He]=(0,R.useState)(0),Ur=(0,R.useRef)(!1),Wr=(0,R.useRef)(!1),An=(0,R.useRef)(!1),zr=(0,R.useRef)(null),Qt=(0,R.useRef)(null),sr=(0,R.useMemo)(()=>({checkoutMode:ue??Tt,layout:Mu(ve,ne)}),[ue,ve,Tt,ne]),en=(0,R.useRef)(b);en.current=b;let yr=(0,R.useRef)(v);yr.current=v;let C=(0,R.useRef)(E);C.current=E;let kt=(0,R.useCallback)(T=>yi(zr,async q=>{try{return await T(q)}catch(Z){throw q.aborted?oa(Z):Z}}),[]);(0,R.useEffect)(()=>()=>{zr.current?.abort(),zr.current=null},[]);let ie=(0,R.useCallback)((T,q)=>{Ce.current=T,qt(T),Rt.current=q,Ct(q)},[]),_e=(0,R.useCallback)(()=>{let T=oe.current;T&&(oe.current=null,T.destroy())},[]);(0,R.useEffect)(()=>{Er(_t)?.setCheckoutContext(sr),J&&J!==_t&&Er(J)?.setCheckoutContext(sr)},[_t,J,sr]);let Ut=(0,R.useRef)(ge);Ut.current=ge;let Ot=(0,R.useCallback)(T=>{Vr(T),!(T!=="exhausted"||An.current)&&(An.current=!0,yr.current?.(new Me.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),$t=(0,R.useCallback)(()=>{Vr("retrying"),He(T=>T+1)},[]);(0,R.useEffect)(()=>{Vr("loading"),He(0),An.current=!1},[I]),(0,R.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Me.SDK_VERSION,checkout_type:Xe,checkout_layout:nt,billing_api_url:H})},[nt,Xe,H]);let We=(0,R.useMemo)(()=>r?(0,ft.serializeCreateParams)(r,!0):"",[r]),$r=(0,R.useMemo)(()=>ot===We?ir:void 0,[ir,ot,We]),eo=(0,R.useMemo)(()=>r?ss(r,$r):void 0,[r,$r]),zt=ue??eo?.checkoutMode??"full",Vt=(0,R.useMemo)(()=>eo?{...eo,checkoutMode:zt}:void 0,[eo,zt]);(0,R.useEffect)(()=>{Qr(void 0),At(We),rr.current=void 0,Sr.current=null,Zt(!1)},[We]),(0,R.useEffect)(()=>{Dt(ee)},[ee]);let Wn=(0,R.useCallback)((T,q,Z)=>{(0,Ge.invokeMerchantCallback)(()=>{C.current?.(kr(T,q,Z))})},[]),to=(0,R.useCallback)(async(T,q)=>{Dt(null),pr(null),Jt(!1),Yt("processing");let Z=q?.sessionId??T.id,Se=T.clientSecret||t,pt=xc(T),mr=Ce.current??Rt.current,Ve=Er(mr),st=mr?null:Ai(H,a,sr),Y={log:P=>{Ve?Ve.log(P):st?.log(P)},error:P=>{Ve?Ve.error(P):st?.error(P)},terminal:P=>{Ve?Ve.terminal(P):st?.terminal(P)},performance:P=>{Ve?Ve.performance(P):st?.performance(P)},now:()=>Ve?.now()??st?.now()??0,elapsed:P=>Ve?.elapsed(P)??Math.max(0,(st?.now()??P)-P)},Oe=Y.now(),j=!!(q?.initialAutoProcessingError||q?.initialAutoProcessingPending),ct=!1,re,et=()=>{ct||(ct=!0,j=!0,re=Y.now(),Y.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),Y.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ht=!1,tt=()=>{ht||(ht=!0,Y.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),Y.performance({stage:"processing",durationMs:Y.elapsed(Oe),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),re!==void 0&&Y.performance({stage:"recovery",durationMs:Y.elapsed(re),durationMode:"machine",paymentMethodCategory:"saved"}))};Y.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),be.current=!0;try{Y.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{be.current=!1}Ae({class:"lifecycle",name:"payment.processing.started",provider:pt}),j&&et();let Mt;try{let P=rc(q?.initialAutoProcessingError),f=q?.initialAutoProcessingError?.type==="3ds_required"&&!q.initialAutoProcessingError.threeDSecureToken&&q.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:q.initialAutoProcessingError.nextActionRedirectUrl}:null,G,Ie=Le=>{et();let dt=Ta(H,Z,T,a!==!1);return kt(Et=>aa(Le,{billingApiUrl:H,sessionId:Z,nonce:Se,session:T,signal:Et,...dt.telemetry?{challengeTelemetry:dt.telemetry}:{}})).finally(dt.release)};if(f)G=await Ie(f);else if(P)et(),P.type==="paypal_redirect_required"&&Qt.current?.publishableKey&&Mc({sessionId:Z,publishableKey:Qt.current.publishableKey,paypalPublishableKey:Qt.current.paypalPublishableKey}),G=await kt(Le=>fi(P,{flopay:Ce.current,paypalFlopay:Rt.current,attempt3DS:q?.attempt3DS,billingApiUrl:H,sessionId:Z,session:T,telemetry:!1,signal:Le})),P.type==="paypal_redirect_required"&&Bs();else if(q?.initialAutoProcessingPending){let Le=q.initialAutoProcessingPending,dt=new yo.PaymentAPI(H,{telemetry:!1}),Et=await kt(Kt=>dt.waitForCheckoutSessionCompletion(Le.sessionId,{initialDelayMs:Le.retryAfterMs,nonce:Se,statusUrl:Le.statusUrl,signal:Kt})),fr=bo(Et,T),Lt=Et.autoProcessingError?.type==="3ds_required"&&Et.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Et.autoProcessingError.nextActionRedirectUrl}:null;if(Lt)G=await Ie(Lt);else{if(!so(fr))throw Jo(fr);G=io(fr,Z)}}else{if(q?.initialAutoProcessingError)throw Xn(q.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:q.initialAutoProcessingError.checkoutMethod});if(q?.fromCreateSession)return q?.fallbackToFull&&(Zr("full"),Ac("full")),!1;{let Le=await ia({billingApiUrl:H,sessionId:Z,session:T,nonce:Se,telemetry:!1});Le.type==="success"?G=Le.result:Le.type==="next_action_required"?G=await Ie(Le):(et(),Le.type==="paypal_redirect_required"&&Qt.current?.publishableKey&&Mc({sessionId:Z,publishableKey:Qt.current.publishableKey,paypalPublishableKey:Qt.current.paypalPublishableKey}),G=await kt(dt=>fi(Le,{flopay:Ce.current,paypalFlopay:Rt.current,attempt3DS:q?.attempt3DS,billingApiUrl:H,sessionId:Z,session:T,telemetry:!1,signal:dt})),Le.type==="paypal_redirect_required"&&Bs())}}Z&&(0,qn.markSessionRecentlyCompleted)(Z),tt(),j&&(Y.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Y.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),Y.terminal({outcome:G.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Jt(G.status==="authorized"),Yt("success"),await Na(600),Mt=()=>en.current?.(G)}catch(P){let f=Co(Ma(P),Z);if(f.code==="three_ds_aborted")return!1;let G=f.checkoutMethod??Ia;Dt(f.message),pr(f.message),Jt(!1),q?.fallbackToFull&&(Y.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Zr("full"),Ac("full")),tt();let Ie=f.statusCode===void 0?void 0:(0,Me.telemetryStatusClass)(f.statusCode,"unknown"),Le=Ie==="4xx"?{requestCategory:"process_payment",statusClass:Ie}:{},dt=Ie===void 0||Ie==="4xx";if(dt&&(f.telemetryOutcome==="payment_declined"||!!(f.declineCode||f.code?.toLowerCase().includes("declin"))))Y.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Le});else if(dt&&(f.telemetryOutcome==="validation_rejected"||f.type==="validation_error"))Y.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Le});else{let Lt=(0,Me.classifyTelemetryFailure)(P,j?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Kt=f.telemetryRequestCategory??"process_payment";be.current=!0;try{Y.error({...Lt,...f.telemetryFailureCategory?{failureCategory:f.telemetryFailureCategory}:{},stage:j?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Kt})}finally{be.current=!1}Ae({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Kt,provider:pt})}return(0,Ge.invokeMerchantCallback)(()=>yr.current?.(f)),Wn(G,f,{code:f.code,declineCode:f.declineCode}),Yt("error"),await Promise.allSettled([Na(400),q?.ensureProvidersReady?q.ensureProvidersReady():Promise.resolve()]),j&&(Y.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Y.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{tt(),st&&Ua(st),Yt(null),pr(null)}return(0,Ge.invokeMerchantCallback)(Mt),!0},[Wn,Ae,t,H,kt,a,sr]);(0,R.useEffect)(()=>{if(typeof window>"u"||Wr.current)return;let T=new URLSearchParams(window.location.search),q=T.get("payment_intent_client_secret");if(!q)return;let Z=Iu();Z&&(Wr.current=!0,(async()=>{let Se,pt=0;Dt(null),pr(null),Yt("processing"),sn(!0);try{if(T.get("redirect_status")==="failed")throw Object.assign(new Me.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:mr,paypalFlopay:Ve}=await fs({publishableKey:Z.publishableKey,paypalPublishableKey:Z.paypalPublishableKey,billingApiUrl:H,locale:d,telemetry:a});Se=Er(Ve??mr),Se?.setCheckoutContext(sr),pt=Se?.now()??0,Se?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Se?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let st=(Ve??mr)?.getRawProvider();if(!st)throw Object.assign(new Me.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:Y,error:Oe}=await st.retrievePaymentIntent(q);if(Oe)throw Object.assign(new Me.FloPayError(Oe.message??"Failed to retrieve PayPal payment status.","api_error",{code:Oe.code}),{checkoutMethod:"paypal"});let j=ql(Y?.status);if(!Y||j==="failed")throw Object.assign(new Me.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let ct=typeof Y.payment_method=="string"?Y.payment_method:Y.payment_method?.id,re=j;if(Z.sessionId){let tt=(await new yo.PaymentAPI(H,{telemetry:!1}).getUnifiedCheckoutSession(Z.sessionId)).data.session;if(tt&&tt.status!=="complete"){let Mt=await ia({billingApiUrl:H,sessionId:Z.sessionId,session:tt,telemetry:!1,tokenizedData:{id:ct??Y.id,type:"card",threeDSecureActionResultTokenId:Y.id,isPaypal:!0}});if(Mt.type!=="success")throw Object.assign(new Me.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});re=Mt.result.status}}Z.sessionId&&(0,qn.markSessionRecentlyCompleted)(Z.sessionId),Se?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Se?.performance({stage:"redirect_resume",durationMs:Se.elapsed(pt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Se?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Yt("success"),await Na(600),(0,Ge.invokeMerchantCallback)(()=>en.current?.({status:re,paymentIntentId:Y.id,paymentMethodId:ct,checkoutMethod:"paypal"}))}catch(mr){let Ve=Co(Ma(mr),Z.sessionId),st=Ve.checkoutMethod??"paypal",Y=!!(Ve.declineCode||Ve.code?.toLowerCase().includes("declin"));if(Se)Se.performance({stage:"redirect_resume",durationMs:Se.elapsed(pt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Y?Se.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Se.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(Y){let Oe=Ai(H,a,sr);Oe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ua(Oe)}else As(H,a,sr,"REDIRECT_RESUME_FAILED","redirect_resume");Dt(Ve.message),pr(Ve.message),(0,Ge.invokeMerchantCallback)(()=>yr.current?.(Ve)),Wn(st,Ve,{code:Ve.code,declineCode:Ve.declineCode}),Yt("error"),await Na(400)}finally{Bs(),Tu(),Yt(null),pr(null),sn(!1)}})())},[Wn,d,H,a,sr]);let mn=(0,R.useRef)(null),xn=(0,R.useMemo)(()=>Vt?(0,ft.serializeCreateParams)(Vt):"",[Vt]),ro=(0,R.useRef)(Vt);ro.current=Vt,(0,R.useEffect)(()=>{B(e??"")},[e]),(0,R.useEffect)(()=>{Ur.current=!1,Dt(ee),pr(null),Jt(!1),Yt(null)},[xn,ee,e]);async function fo(T,q,Z){let Se=Ai(H,a,sr),pt=new yo.PaymentAPI(H,{telemetry:!1}),mr=!1;try{let Ve=T.idempotencyKey===void 0?void 0:(0,Me.resolveIdempotencyKey)(T.idempotencyKey),st=(0,ft.readCachedInlineSession)(q,Z),Y=(0,ft.readCachedInlineIdempotencyKey)(q,Z);st?.canonicalIdentity===Z&&Y&&Y.canonicalIdentity===void 0&&((0,ft.persistCachedInlineIdempotencyKey)(q,Z,Y.idempotencyKey),Y={...Y,canonicalIdentity:Z});let Oe=Ve??(Y?.canonicalIdentity===Z?Y.idempotencyKey:void 0),j,ct=!1;Se.log({name:st?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let re=st?.sid??null,et=null,ht,tt,Mt=!1;if(re)try{et=await pt.getUnifiedCheckoutSession(re,st?.nonce),st&&st.canonicalIdentity===void 0&&((0,ft.legacyCachedSessionMatchesDraft)(et.data.session,T)?((0,ft.persistCachedInlineSession)(q,Z,re,st.nonce??et.data.session?.clientSecret),Y&&Y.canonicalIdentity===void 0&&((0,ft.persistCachedInlineIdempotencyKey)(q,Z,Y.idempotencyKey),Oe??(Oe=Y.idempotencyKey))):((0,ft.clearCachedInlineCheckout)(q,Z),Y=null,Oe=Ve,re=null,et=null));let f=et?.data.session?.status,G=et?.data.session,Ie=G?.clientSecret||st?.nonce;if(re&&G?.buyerIdentified===!1&&Ie&&(tt=Xo(pt,re,Ie,T.account)),re&&et&&f==="complete"){if((0,qn.wasSessionRecentlyCompleted)(re))return{sid:re,result:et};(0,ft.clearCachedInlineCheckout)(q,Z),re=null,et=null,ct=!0}}catch{Se.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),st?.canonicalIdentity===void 0?((0,ft.clearCachedInlineCheckout)(q,Z),Oe=Ve):(0,ft.clearCachedInlineSession)(q,Z),re=null}if(!re){!Ve&&(ct||!Oe)&&(Oe=(0,Me.resolveIdempotencyKey)(),j=Oe),Oe&&(0,ft.persistCachedInlineIdempotencyKey)(q,Z,Oe);let f=Se.now(),G=0;Se.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ie={...T,idempotencyKey:Oe,avsCheck:!!N,avsConfig:typeof N=="object"?N:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ds(ve,ne)};Object.defineProperty(Ie,yo.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Et=>{G=Math.max(G,Et)}}});let Le=()=>{Ic(Se,"session_create",f,G)},dt=Et=>{Tc(Se,Et,"session_create",f,G)&&Ae({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,Me.isDetachedSessionEligible)(Ie)){let Et=await pt.createDetachedSession(Ie);Et.claimed.catch(()=>{}),et=Et.shell,re=Et.sessionId,tt=Et.claim;let fr=Se.now();Se.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ht=Et.claimed.then(Lt=>{let Kt=Lt.data.session?.id??Et.sessionId;return Kt&&(0,ft.persistCachedInlineSession)(q,Z,Kt,Lt.data.session?.clientSecret??Et.nonce),Ic(Se,"session_claim",fr),Le(),Lt},Lt=>{throw(0,ft.clearCachedInlineSession)(q,Z),Tc(Se,Lt,"session_claim",fr,0)&&Ae({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Lt}).finally(()=>Ua(Se)),ht.catch(()=>{}),mr=!0,Se.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Se.performance({stage:"session_shell",durationMs:Se.now()-f,durationMode:"machine",requestCategory:"session_create",attempt:G,statusClass:"2xx",paymentMethodCategory:"card"})}else et=await pt.createAndFetchSession(Ie),Le()}catch(Et){throw dt(Et),Et}re=et.data.session?.id??re??"",re&&!ht&&(0,ft.persistCachedInlineSession)(q,Z,re,et.data.session?.clientSecret)}let P=et?.data.session;return!tt&&re&&P?.buyerIdentified===!1&&P.clientSecret&&(tt=Xo(pt,re,P.clientSecret,T.account)),{sid:re??"",result:et,sdkGeneratedIdempotencyKey:j,...ht?{claimed:ht}:{},...tt?{claim:tt}:{},...Mt?{claimRequiresIdentity:!0}:{}}}finally{mr||Ua(Se)}}let go=(0,R.useRef)(fo);To(()=>{go.current=fo},[fo]);let Hr=(0,R.useCallback)(async(T,q)=>{let Z=ro.current;if(!Z)throw new Me.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Se=ss(Z,T),pt=(0,ft.serializeCreateParams)(Se),mr=(0,ft.hashCreateParams)(Se),Ve=xi.get(pt);if(!Ve){let Oe={canonicalIdentity:pt,promise:go.current(Se,mr,pt),consumers:0,settled:!1};Ve=Oe,xi.set(pt,Oe);let j=()=>{Oe.settled=!0,_c(pt,Oe)};Oe.promise.then(j,j)}Ve.consumers+=1;let st=!1,Y=()=>{st||(st=!0,Ve.consumers-=1,_c(pt,Ve))};q?.(Y);try{let Oe=await Ve.promise;mn.current=pt,T&&(At(We),Qr(P=>Dl(P,T)));let{sid:j,result:ct,claimed:re,claim:et,claimRequiresIdentity:ht}=Oe;if(rr.current=et,Zt(ht===!0),or(ct),ct.data.session&&De(ct.data.session),j&&B(j),re){wr.current+=1;let P=wr.current;Sr.current=re,jr(!0),re.then(f=>{wr.current===P&&(Sr.current===re&&(Sr.current=null),or(f),f.data.session&&De(f.data.session),jr(!1),Zt(!1))},f=>{wr.current===P&&(Sr.current===re&&(Sr.current=null),jr(!1),Zt(!1),ar(f instanceof Me.FloPayError?f:new Me.FloPayError(f instanceof Error?f.message:"Failed to create session","api_error")))})}else wr.current+=1,Sr.current=null,jr(!1),Zt(!1);let{flopay:tt,paypalFlopay:Mt}=await Fs(ct,{billingApiUrl:H,locale:d,telemetry:a}).catch(P=>{throw Nl(P,j||ct.data.session?.id)});return ie(tt,Mt),F(!1),Oe}catch(Oe){throw mn.current===pt&&(mn.current=null),Oe}finally{q||Y()}},[We,ie,d,H,a]),ho=(0,R.useRef)(to);ho.current=to;let Fn=(0,R.useRef)(Hr);Fn.current=Hr;let Bn=(0,R.useCallback)(async T=>{if(!Au(T)||Or)return{sessionId:u,session:se};Lr(!0);try{let q=await Hr(T);return{sessionId:q.sid,session:q.result.data.session??null}}finally{Lr(!1)}},[Hr,Or,u,se]),fn=(0,R.useCallback)(async T=>{let q=rr.current;if(!q)return;let Z=wr.current,Se=await q(T);wr.current===Z&&(or(Se),Se.data.session&&De(Se.data.session))},[]),gn=(0,R.useCallback)(async()=>{await Sr.current},[]),Ht=(0,R.useCallback)(async()=>(await gn(),{proceed:!0}),[gn]);(0,R.useEffect)(()=>{let T=!1,q,Z=++Ze.current;_e(),ar(null),br(0);let Se=()=>{T=!0,Ze.current===Z&&(Ze.current+=1,_e())},pt=ro.current;if(xn&&pt)return Zr(zt),F(!1),mn.current===xn?Se:(De(Ol(pt,ue)),(async()=>{let st=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Y=zt==="auto"&&!Ur.current&&!st;Y&&(Dt(null),pr(null),Yt("processing"));let Oe=!1;try{let j=await Fn.current(void 0,ht=>{q=ht});Oe=!0;let ct=j.result.data.session??null;Qt.current=ms(j.result);let re=xs(j.result),et=(0,qn.wasSessionRecentlyCompleted)(j.sid||ct?.id);if(!T&&Y&&ct&&!re&&!et){Ur.current=!0,await ku(xn,j.sdkGeneratedIdempotencyKey,()=>ho.current(ct,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:j.result.autoProcessingError,initialAutoProcessingPending:j.result.autoProcessingPending,autoProcessingAttempted:j.result.autoProcessingAttempted,sessionId:j.sid||ct.id}));return}!T&&Y&&((re||et)&&(Ur.current=!0),Yt(null),pr(null))}catch(j){if(T)return;let ct=ni(j);if(Y&&ct==="session_auto_completed"){Ur.current=!0,Yt("success"),await Na(600),T||((0,Ge.invokeMerchantCallback)(()=>{en.current?.({status:"succeeded"})}),Yt(null),pr(null));return}if(Y&&(Yt(null),pr(null)),!Oe){let et=Ul(j),ht=(0,Me.toPublicCheckoutInitError)(j,et?{stage:"provider_load",provider:"stripe",...et}:{stage:"session_request"});(et||!(j instanceof Me.FloPayError))&&(0,Ge.invokeMerchantCallback)(()=>yr.current?.(ht)),ar(ht);return}let re=j instanceof Me.FloPayError?j:new Me.FloPayError(j instanceof Error?j.message:"Failed to create session","api_error");ar(re)}finally{q?.(),q=void 0}})(),()=>{Se(),q?.()});F(!0);async function mr(){let st=!1,Y=!1,Oe=null;try{let j=new yo.PaymentAPI(H,{telemetry:!1}),ct=await j.getUnifiedCheckoutSession(I,t);if(Y=!0,Oe=ct,T)return;or(ct);let re=ct.data.session??null;if(De(re),!re)throw new Me.FloPayError("No session data returned","api_error");let et=re.checkoutMode;if(et==="setup")throw new Me.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(re.status==="authorized"){F(!1),(0,Ge.invokeMerchantCallback)(()=>{en.current?.(io(re,I)),Ut.current?.(re.successUrl??"")});return}if(re.status==="complete"){F(!1),(0,Ge.invokeMerchantCallback)(()=>{Ut.current?.(re.successUrl??"")});return}if(re.status==="expired")throw ri(re);st=!0;let ht=ue??et??"full";Zr(ht),wr.current+=1;let tt=re.clientSecret||t;rr.current=re.buyerIdentified===!1&&tt?Xo(j,I,tt,{...re.customer?.id?{userId:re.customer.id}:{}}):void 0,jr(!1),Zt(!1);let Mt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),P=xs(ct);if(ht==="auto"&&!Ur.current&&!Mt&&!P){Ur.current=!0;let f=Ve(ct);try{if(await ho.current(re,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>f,sessionId:I||re.id}),T)return;await f,T||F(!1);return}catch{if(T)return;await f,T||F(!1);return}}await Ve(ct),T||F(!1)}catch(j){if(T)return;let ct=Bl(j,st);if(st&&Ae({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ct){let{errorCode:tt,stage:Mt,...P}=ct;As(H,a,sr,tt,Mt,P)}if(ct?.stage==="provider_load"&&(ue??Oe?.data.session?.checkoutMode??"full")==="full"&&Fl(Oe,A,g)){let tt=_u({billingApiUrl:H,locale:d,telemetry:a});oe.current=tt,ie(tt,null),br(1),F(!1);return}let re=ct?.stage==="provider_load",et="session_request";re?et="provider_load":Y&&(et="post_session");let ht=(0,Me.toPublicCheckoutInitError)(j,{stage:et,provider:"stripe",sessionId:I||void 0});(re||!(j instanceof Me.FloPayError))&&(0,Ge.invokeMerchantCallback)(()=>yr.current?.(ht)),ar(ht),F(!1)}}async function Ve(st){let{flopay:Y,paypalFlopay:Oe,...j}=await Fs(st,{billingApiUrl:H,locale:d,telemetry:a});Qt.current={publishableKey:j.publishableKey,paypalPublishableKey:j.paypalPublishableKey},ie(Y,Oe),br(0)}return mr(),Se},[ue,xn,zt,xe,t,A,g]);let hn=(0,R.useCallback)(async()=>{if(!it||tr!==1)return;let T=Ze.current;br(2);try{let{flopay:q,paypalFlopay:Z}=await Fs(it,{billingApiUrl:H,locale:d,telemetry:a});if(Ze.current!==T)return;_e(),ie(q,Z),br(0)}catch(q){if(Ze.current!==T)return;let{errorCode:Z,stage:Se,...pt}=is(q);As(H,a,sr,Z,Se,pt)}},[_e,ie,d,tr,H,a,sr,it]),Pn=!!(I&&(se?.clientSecret||t)),Kr=pn||!Pn,Gr=(0,R.useCallback)(async()=>{if(!(pn||!Pn||!se)){sn(!0),Dt(null);try{await to(se,{attempt3DS:!0,fallbackToFull:!0,sessionId:I||se.id})}finally{sn(!1)}}},[I,pn,Pn,to,se]),Qe=(0,Me.resolveDirectPaypalConfig)(it?.data.paypal,te),Br=xs(it),Rr=(0,R.useMemo)(()=>{if(!(!it||!se||!it.data.stripe?.publishableKey))return{billingApiUrl:H}},[it,se,H]),vn=!!(r&&!ve&&ne==="buttons"&&ye&&zt==="full"),Po=!!(I&&((0,Me.isMountableVaultBlock)(se?.vault)||(0,Nn.canRecoverHostedCardForm)(se))),Cn=(0,R.useMemo)(()=>({session:se,loading:z,error:$e,checkoutMode:Tt,inlineSessionDraft:Vt,applyInlineSessionPatch:vn?Bn:void 0,inlineSessionPatchProcessing:Or,claimPending:Ir,claimRequiresIdentity:Fr,claimBuyerIdentity:fn,waitForDataAttachment:gn}),[se,z,$e,Tt,Vt,vn,Bn,Or,Ir,Fr,fn,gn]),no=!!r&&ne==="buttons"&&!Br&&!Po&&(!_t||!Rr),Tr=yn?(0,M.jsx)(on,{status:yn,errorMessage:ln,authorized:Mn}):null;if(z&&!Po){if(p)return(0,M.jsxs)(M.Fragment,{children:[p,Tr]});if(ne==="buttons"){let T=Be?.buttonsLayout?.cardButton?.borderRadius??Be?.appearance.variables?.borderRadius??8,q=Z=>(0,M.jsx)("div",{style:{height:Z,borderRadius:T,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[A&&q(Fo),g&&(m||me)&&q(Fo),g&&q(Fo),(0,M.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Tr]})}return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,M.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,M.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Tr]})}return $e?y?(0,M.jsx)(Un.Provider,{value:Cn,children:y($e)}):(0,M.jsx)(Un.Provider,{value:Cn,children:(0,M.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:$e.message})}):no?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(Un.Provider,{value:Cn,children:(0,M.jsx)(Fu,{onButtonClick:qe,paymentMethodLayout:fe,showPayPal:A,showStripe:g,showApplePay:m,showGooglePay:me,theme:ce,buttonsTheme:Ee,buttonsStyles:vt,cardButtonContent:ze,cardBackButtonContent:L,cardTitleContent:Ye})}),Tr]}):Br&&se&&Qe?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(Un.Provider,{value:Cn,children:(0,M.jsxs)("div",{className:W,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jt&&(0,M.jsx)(na,{icon:!1,children:jt}),Xt==="retrying"&&(0,M.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Xt==="exhausted"&&(0,M.jsxs)("div",{role:"alert",children:[(0,M.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,M.jsx)("button",{type:"button",onClick:$t,children:"Retry PayPal"})]}),Xt!=="exhausted"&&(0,M.jsx)("div",{"aria-hidden":Xt==="retrying"?!0:void 0,style:Xt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,M.jsx)(Zl,{sessionId:I,nonce:se.clientSecret||void 0,billingApiUrl:H,email:se.customer?.email||Vt?.account?.email,billingName:[se.customer?.firstName,se.customer?.lastName].filter(Boolean).join(" ")||[Vt?.account?.firstName,Vt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:fn,clientId:Qe.clientId,environment:Qe.environment,currency:(se.currency??"usd").toUpperCase(),isSubscription:se.mode==="subscription",providerObjectType:Qe.providerObjectType,approvalPresentation:Qe.approvalPresentation,existingOrderId:Qe.existingOrderId,onComplete:b,onErrorChange:Dt,onDecline:E,onCancel:V,onButtonClick:qe,runBeforeButtonClick:Ht,onInitializationStateChange:Ot,allowAutomaticRetry:Nr===0,session:se,telemetry:a,telemetryContext:sr,onInstrument:bt,debug:_},`${h}:paypal-init-${Nr}`)})]})}),Tr]}):Tt==="confirm"?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(Un.Provider,{value:Cn,children:(0,M.jsx)(Ea,{flopay:_t,paypalFlopay:J,options:Rr??{billingApiUrl:H},onInstrument:bt,children:(0,M.jsxs)("div",{className:W,children:[jt&&(0,M.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:jt}),Fe?Fe({onConfirm:Gr,isProcessing:Kr}):(0,M.jsx)("button",{type:"button",onClick:Gr,disabled:Kr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Kr?"not-allowed":"pointer",opacity:Kr?.6:1},children:pn?"Processing...":pe??"Confirm Purchase"})]})},h)}),Tr]}):(!_t||!Rr)&&!(Po&&Tt==="full")?(0,M.jsx)(M.Fragment,{children:Tr}):(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(Un.Provider,{value:Cn,children:(0,M.jsxs)(Ea,{flopay:_t,paypalFlopay:J,options:Rr??{billingApiUrl:H},onInstrument:bt,children:[tr===1&&(0,M.jsx)("button",{type:"button",onClick:hn,children:"Retry payment methods"}),ve?(0,M.jsxs)(M.Fragment,{children:[jt&&(0,M.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:jt}),(0,M.jsx)(xu,{sessionId:I,nonce:se?.clientSecret||void 0,billingApiUrl:H,session:se,submitLabel:Q,walletPresentation:O,paymentMethodLayout:fe,children:ve})]}):(0,M.jsx)(Ti,{sessionId:I,nonce:se?.clientSecret||void 0,telemetry:a,email:se?.customer?.email||Vt?.account?.email,userId:se?.customer?.id||Vt?.account?.userId,firstName:se?.customer?.firstName||Vt?.account?.firstName,lastName:se?.customer?.lastName||Vt?.account?.lastName,totalAmount:se?Math.round((0,Me.buildCheckoutDisplayData)(se).total*100):0,currency:se?.currency?.toLowerCase()??"usd",onComplete:b,onError:v,onDecline:E,onCancel:V,error:jt,onErrorChange:Dt,showPayPal:A,showStripe:g,walletPresentation:O,enabledPaymentMethods:tr?[]:ke??it?.data.stripe?.enabledPaymentMethods??se?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:it?.data.stripe?.enabledPaymentMethodCountries,showApplePay:m,showGooglePay:me,layout:ne,paymentMethodLayout:fe,theme:ce,buttonsTheme:Ee,buttonsStyles:vt,appearance:ut,cardButtonContent:ze,cardBackButtonContent:L,cardTitleContent:Ye,onButtonClick:qe,onBeforeButtonClick:ye,onBuyerIdentityReady:fn,enableAVS:N,...le?{cardFieldOrder:le}:{},...de===void 0?{}:{cardAutoFocus:de},...rt?{cardPreFormSlot:rt}:{},avsLayout:je,country:se?.customer?.country,city:se?.customer?.city,state:se?.customer?.state,onCountryChange:x,onZipChange:D,avsCheck:!!N,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Ds(ve,ne),className:W,submitLabel:Q,directPaypal:Qe,isSubscription:se?.mode==="subscription",session:se,dataAttachmentPending:Ir,dataAttachmentRequiresIdentity:Fr,debug:_})]},h)}),Tr]})}function xu({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,paymentMethodLayout:d,children:p}){return(0,M.jsx)(M.Fragment,{children:R.default.Children.map(p,y=>{if(!R.default.isValidElement(y))return y;let b=y.props,v={};return b.sessionId||(v.sessionId=e),!b.nonce&&t&&(v.nonce=t),b.billingApiUrl||(v.billingApiUrl=r),b.submitLabel===void 0&&a!==void 0&&(v.submitLabel=a),b.walletPresentation===void 0&&(v.walletPresentation=s),b.paymentMethodLayout===void 0&&d!==void 0&&(v.paymentMethodLayout=d),n?.customer&&(b.email||(v.email=n.customer.email),b.userId||(v.userId=n.customer.id),b.firstName||(v.firstName=n.customer.firstName),b.lastName||(v.lastName=n.customer.lastName)),Object.keys(v).length===0?y:R.default.cloneElement(y,v)})})}function Fu({onButtonClick:e,paymentMethodLayout:t,showPayPal:r,showStripe:n=!0,showApplePay:a,showGooglePay:s,theme:d,buttonsTheme:p,buttonsStyles:y,cardButtonContent:b,cardBackButtonContent:v,cardTitleContent:S}){let[E,V]=(0,R.useState)(!1),x=(0,R.useMemo)(()=>(0,Me.resolveTheme)(d),[d]),D=(0,R.useMemo)(()=>{let m=x?.buttonsLayout??(0,Me.resolveButtonsLayoutTheme)(p);return y?{...m,...y,cardButton:{...m.cardButton,...y.cardButton},cardFormContainer:{...m.cardFormContainer,...y.cardFormContainer},backButton:{...m.backButton,...y.backButton},backButtonIcon:{...m.backButtonIcon,...y.backButtonIcon},submitButton:{...m.submitButton,...y.submitButton},title:{...m.title,...y.title}}:m},[x,p,y]),A=x?.buttonsLayout?.cardButton?.borderRadius??x?.appearance.variables?.borderRadius??8,g=m=>(0,M.jsx)("div",{style:{height:m,borderRadius:A,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),O=b===void 0?{boxSizing:"border-box",height:Fo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(E){let m=D.cardInputBorder??"#e5e7eb",me=D.cardInputBackground??"white",_=Ko(v),ne=Ko(S);return(0,M.jsxs)("div",{style:{backgroundColor:D.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...D.cardFormContainer},children:[(0,M.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,M.jsxs)("button",{type:"button",onClick:()=>V(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:_?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...D.backButton},children:[(0,M.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...D.backButtonIcon},children:(0,M.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,M.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,M.jsx)(Yo,{content:v})]}),ne?(0,M.jsx)("div",{style:{flex:1}}):(0,M.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...D.title},children:(0,M.jsx)(Pa,{content:S})})]}),(0,M.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${m}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,M.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,M.jsxs)("div",{style:{display:"flex"},children:[(0,M.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${m}`,borderLeft:`1px solid ${m}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,M.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,M.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:`1px solid ${m}`,borderBottom:`1px solid ${m}`,borderLeft:`1px solid ${m}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,M.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,M.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${m}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,M.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,M.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...D.submitButton,opacity:.5}}),(0,M.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
|
-
`})]})}return(0,D.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&B(ra),r&&(n||a)&&B(ra),r&&(0,D.jsx)("button",{type:"button",onClick:()=>{e?.("card"),_(!0)},style:{width:"100%",...f,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:T.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,...T.cardButton},onMouseDown:h=>{h.currentTarget.style.transform="scale(0.985)"},onMouseUp:h=>{h.currentTarget.style.transform="scale(1)"},children:(0,D.jsx)(qo,{content:y})}),(0,D.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var wn=require("react/jsx-runtime"),gu=44;function vc(e){return new Promise(t=>setTimeout(t,e))}function hu(e,t){return e instanceof Rn.FloPayError?e:new Rn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Pu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function vu(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 Cc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:s,products:c,items:p,subscriptions:y,account:g,successUrl:E,cancelUrl:R,couponCodes:_,tagsData:H,utmMetadata:T,billingApiUrl:Y,locale:B,theme:f,appearance:h,buttonsTheme:ge,buttonsStyles:S,onSuccess:Me,onError:A,onDecline:ie,children:he,disabled:fe=!1,type:Re="button",style:ct,...Ke}){let F=(0,ht.useMemo)(()=>(0,Rn.resolveBillingApiUrl)(Y),[Y]),St=(0,ht.useMemo)(()=>vu({createSession:r,clientId:s,products:c,items:p,subscriptions:y,account:g,successUrl:E,cancelUrl:R,couponCodes:_,tagsData:H,utmMetadata:T}),[g,R,s,_,r,c,p,y,E,H,T]),[et,Ue]=(0,ht.useState)(!1),[ye,J]=(0,ht.useState)(null),[W,Fe]=(0,ht.useState)(null),[dt,We]=(0,ht.useState)(!1),[Z,L]=(0,ht.useState)(null),[le,j]=(0,ht.useState)(null),Se=(0,ht.useRef)(!0),xe=(0,ht.useRef)(null),Pe=(0,ht.useRef)(le),Be=(0,ht.useRef)(Me),M=(0,ht.useRef)(A),nt=(0,ht.useRef)(ie),je=(0,ht.useCallback)(v=>di(xe,async U=>{try{return await v(U)}catch(ne){throw U.aborted?Jo(ne):ne}}),[]);(0,ht.useEffect)(()=>{Pe.current=le},[le]),(0,ht.useEffect)(()=>{Be.current=Me},[Me]),(0,ht.useEffect)(()=>{M.current=A},[A]),(0,ht.useEffect)(()=>{nt.current=ie},[ie]),(0,ht.useEffect)(()=>(Se.current=!0,()=>{Se.current=!1,xe.current?.abort()}),[]),(0,ht.useEffect)(()=>{if(typeof window>"u")return;let v=U=>{U.key==="Escape"&&j(null)};return window.addEventListener("keydown",v),()=>{window.removeEventListener("keydown",v)}},[]);let ut=(0,ht.useCallback)((v,U=Ea)=>{nt.current?.(wr(U,v,{code:v.code,declineCode:v.declineCode}))},[]),Ge=(0,ht.useCallback)(async v=>{Se.current&&(Fe(null),We(v.result.status==="authorized"),J("success"),await vc(600),Se.current&&(0,Xe.invokeMerchantCallback)(()=>Be.current?.(v)))},[]),$e=(0,ht.useCallback)(async(v,U)=>{Se.current&&(M.current?.(v),U?.emitDecline&&ut(v,U.method),Fe(v.message),We(!1),J("error"),await vc(400))},[ut]),Rt=(0,ht.useCallback)(async(v,U,ne)=>{let Ae=v.data.session??null;if(!Ae)throw fo(new Rn.FloPayError("No session data returned","api_error"),U);let Dt=Ae.clientSecret||t;if(oo(Ae)){await Ge({result:no(Ae,U),session:Ae,sessionId:Ae.id||U,autoCompleted:!1});return}if(Ae.status==="expired")throw fo(Qa(Ae),Ae.id||U);try{if(v.autoProcessingPending){let De=v.autoProcessingPending,Oe=new Mi.PaymentAPI(F),_t=await je(Q=>Oe.waitForCheckoutSessionCompletion(De.sessionId,{initialDelayMs:De.retryAfterMs,nonce:Dt,statusUrl:De.statusUrl,signal:Q})),u=go(_t,Ae),C=_t.autoProcessingError?.type==="3ds_required"&&_t.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:_t.autoProcessingError.nextActionRedirectUrl}:null;if(C&&U&&Dt){let Q=Ia(F,U,Ae),ce=await je(N=>Zo(C,{billingApiUrl:F,sessionId:U,nonce:Dt,session:Ae,signal:N,telemetry:!0,...Q.telemetry?{challengeTelemetry:Q.telemetry}:{}})).finally(Q.release);await Ge({result:ce,session:Ae,sessionId:Ae.id||U,autoCompleted:!1});return}if(_t.autoProcessingError)throw Xn(_t.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:_t.autoProcessingError.checkoutMethod});if(!oo(u))throw Wo(u);await Ge({result:no(u,U),session:u,sessionId:u.id||U,autoCompleted:!1});return}if(v.autoProcessingError){let De=v.autoProcessingError.nextActionRedirectUrl;if(v.autoProcessingError.type==="3ds_required"&&De&&U&&Dt){let Oe=await je(Q=>Kl({billingApiUrl:F,sessionId:U,nonce:Dt,nextActionRedirectUrl:De,signal:Q}));if(Oe.status==="declined")throw Xn({type:Oe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Oe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:v.autoProcessingError.checkoutMethod});let u=await new Mi.PaymentAPI(F).waitForCheckoutSessionCompletion(U,{initialDelayMs:0,nonce:Dt}),C=go(u,Ae);if(!oo(C))throw Xn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:v.autoProcessingError.checkoutMethod});await Ge({result:no(C,U),session:C,sessionId:C.id||U,autoCompleted:!1});return}throw Xn(v.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:v.autoProcessingError.checkoutMethod})}if(ne?.fromCreateSession&&v.autoProcessingAttempted===!0)throw Xn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ot=await Qo({billingApiUrl:F,sessionId:U??Ae.id,session:Ae,nonce:Dt});if(ot.type==="next_action_required"&&Dt){let De=U??Ae.id,Oe=Ia(F,De,Ae),_t=await je(u=>Zo(ot,{billingApiUrl:F,sessionId:De,nonce:Dt,session:Ae,signal:u,telemetry:!0,...Oe.telemetry?{challengeTelemetry:Oe.telemetry}:{}})).finally(Oe.release);await Ge({result:_t,session:Ae,sessionId:Ae.id||De,autoCompleted:!1});return}if(ot.type!=="success")throw Xn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ge({result:ot.result,session:Ae,sessionId:Ae.id||U,autoCompleted:!1})}catch(ot){let De=Ae.id||U,Oe=fo(_a(ot),De);if(Oe.code==="three_ds_aborted")return;if(Oe.code==="checkout_processing_timeout"){if(!Se.current)return;L(Oe.message),(0,Xe.invokeMerchantCallback)(()=>M.current?.(Oe));return}await $e(Oe,{emitDecline:!0,method:Oe.checkoutMethod??Ea}),Pu(Oe,De)&&De&&Se.current&&j({sessionId:De,errorMessage:Oe.message,nonce:Dt||void 0,payPalOrderId:Oe.orderId})}},[t,F,je,$e,Ge]),Ot=(0,ht.useCallback)(async v=>{if(Ke.onClick?.(v),!(v.defaultPrevented||fe||et)){if(j(null),L(null),e&&St){let U=new Rn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await $e(U),Se.current&&(J(null),Fe(null));return}if(!e&&!St){let U=new Rn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $e(U),Se.current&&(J(null),Fe(null));return}Ue(!0),Fe(null),We(!1),J("processing");try{let U=new Mi.PaymentAPI(F);if(e){let ne=await U.getUnifiedCheckoutSession(e,t);await Rt(ne,e);return}try{let ne=await U.createAndFetchSession({...St});await Rt(ne,ne.data.session?.id??null,{fromCreateSession:!0})}catch(ne){if(ei(ne)==="session_auto_completed"){await Ge({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw ne}}catch(U){await $e(fo(hu(U,"Automatic payment failed. Please try again."),e))}finally{Se.current&&(J(null),Fe(null),Ue(!1))}}},[Ke.onClick,St,fe,et,t,Rt,F,e,$e,Ge]),zt=(0,ht.useCallback)(v=>{let U=Pe.current;j(null),Be.current?.({result:v,session:null,sessionId:U?.sessionId??null,autoCompleted:!1})},[]),Ft=(0,ht.useCallback)(v=>{M.current?.(v)},[]),ue=(0,ht.useCallback)(v=>{nt.current?.(v)},[]),pe=(0,ht.useMemo)(()=>(0,Rn.resolveTheme)(f),[f]),X=(0,ht.useMemo)(()=>{let v=pe?.buttonsLayout??(0,Rn.resolveButtonsLayoutTheme)(ge);return S?{...v,...S,cardButton:{...v.cardButton,...S.cardButton}}:v},[pe,ge,S]),Pt=(0,ht.useMemo)(()=>{let v=pe?.appearance;return h?v?{...v,...h,variables:{...v.variables,...h.variables}}:h:v},[h,pe]),pt=Pt?.variables,V=pt?.colorPrimary??"#4A49FF",rt=pt?.colorPrimaryHover??(0,Ss.darkenHex)(V,.12),wt=pt?.borderRadius??"8px";return(0,wn.jsxs)(wn.Fragment,{children:[(0,wn.jsx)("button",{...Ke,type:Re,onClick:Ot,disabled:fe||et,"aria-busy":et,style:{width:"100%",...he===void 0?{boxSizing:"border-box",height:gu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...X.cardButton,...bs({themeBundle:pe,resolvedPrimaryColor:V,resolvedBorderRadius:wt,submitButtonStyle:X.submitButton,explicitPrimaryColor:pt?.colorPrimary}),fontSize:X.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:fe||et?"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:fe||et?.6:1,...ct},onMouseEnter:v=>{Ke.onMouseEnter?.(v),!v.defaultPrevented&&!fe&&!et&&(pe||pt?.colorPrimary)&&(v.currentTarget.style.backgroundColor=rt)},onMouseLeave:v=>{Ke.onMouseLeave?.(v),!v.defaultPrevented&&(pe||pt?.colorPrimary)&&(v.currentTarget.style.backgroundColor=V)},onMouseDown:v=>{Ke.onMouseDown?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(0.985)")},onMouseUp:v=>{Ke.onMouseUp?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(1)")},children:(0,wn.jsx)(qo,{content:he})}),Z&&(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:Z}),ye&&(0,wn.jsx)(tn,{status:ye,errorMessage:W,authorized:dt}),le&&(0,wn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:v=>{v.target===v.currentTarget&&j(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)(Ti,{sessionId:le.sessionId,nonce:le.nonce,checkoutMode:"full",billingApiUrl:F,locale:B,theme:f,...Pt?{appearance:Pt}:{},buttonsTheme:ge,buttonsStyles:S,initialErrorMessage:le.errorMessage,initialPayPalOrderId:le.payPalOrderId,cardTitleContent:null,onComplete:zt,onError:Ft,onDecline:ue})})})]})}var Ai=require("@flopay/js/card-setup"),Hr=require("@flopay/shared"),Kt=require("react");var Ms=require("@flopay/shared"),Cu=require("@flopay/shared");function xi(e){let t=(0,Ms.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Zn=require("react/jsx-runtime"),La=class extends Hr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function uo(e,t={}){let r=e instanceof Hr.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 La(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 bc({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:c,buttonsStyles:p,loading:y=null,onReady:g,onComplete:E,onDecline:R,onCancel:_,onValidation:H,onError:T}){let[Y,B]=(0,Kt.useState)(null),[f,h]=(0,Kt.useState)(null),[ge,S]=(0,Kt.useState)(null),[Me,A]=(0,Kt.useState)(null),[ie,he]=(0,Kt.useState)(null),fe=(0,Kt.useRef)(!1),Re=(0,Kt.useRef)(!1),{vaultTheme:ct,surface:Ke,overlayTheme:F}=(0,Kt.useMemo)(()=>xi({theme:a,appearance:c,buttonsStyles:p}),[a,c,p]),St=(0,Kt.useMemo)(()=>(0,xa.mergeCardSetupSurface)(Ke,s),[Ke,s]),et=(0,Kt.useRef)(g),Ue=(0,Kt.useRef)(T),ye=(0,Kt.useRef)(E),J=(0,Kt.useRef)(R),W=(0,Kt.useRef)(_),Fe=(0,Kt.useRef)(H),dt=(0,Kt.useRef)(!1),We=(0,Kt.useRef)(!1),Z=(0,Kt.useRef)(0);return et.current=g,Ue.current=T,ye.current=E,J.current=R,W.current=_,Fe.current=H,(0,Kt.useEffect)(()=>{let L=Z.current+1;return Z.current=L,()=>{queueMicrotask(()=>{Z.current===L&&(dt.current||We.current||(We.current=!0,(0,Xe.invokeMerchantCallback)(()=>{W.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Kt.useEffect)(()=>{let L=!0,le=(0,Hr.resolveBillingApiUrl)(r),j=new Ai.PaymentAPI(le,{telemetry:n});return B(null),h(null),S(null),dt.current=!1,We.current=!1,(async()=>{try{if(!e.trim())throw new Hr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Hr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Se=await j.getUnifiedCheckoutSession(e,t);if(!L)return;let xe=Se.data.session;if(!xe||!(0,Hr.isCardSetupCheckoutSession)(xe))throw new Hr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Pe=xe.vault;(0,Hr.isMountableVaultBlock)(Pe)||(Pe=await j.getVaultCapture(e,t));let Be=(0,Hr.resolveVaultMountOptions)(Pe,{billingApiUrl:le,sessionId:e,nonce:t});if(!Be)throw new Hr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!L)return;h(Be),B(new Ai.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(Se){if(!L)return;let xe=uo(Se);dt.current=!0,S(xe),(0,Xe.invokeMerchantCallback)(()=>Ue.current?.(xe))}})(),()=>{L=!1,j.destroy()}},[r,t,e,n]),(0,Kt.useEffect)(()=>{if(!Y)return;let L=!1;Re.current=!1,fe.current=!1;let le=Y.on("submitting",()=>{fe.current=!0,he(null),A("processing")}),j=Y.on("complete",Pe=>{dt.current=!0,fe.current=!1,A("success"),(async()=>(await new Promise(Be=>setTimeout(Be,600)),!Re.current&&(Re.current=!0,(0,Xe.invokeMerchantCallback)(()=>{ye.current?.({status:"succeeded",sessionId:e,...Pe.paymentMethod?{paymentMethod:Pe.paymentMethod}:{}})}),L||A(null))))()}),Se=Y.on("decline",Pe=>{dt.current=!0,fe.current=!1,he(Pe.message??null),A("error"),(0,Xe.invokeMerchantCallback)(()=>{J.current?.({status:"declined",sessionId:e,...Pe.declineReason?{reason:Pe.declineReason}:{},...Pe.message?{message:Pe.message}:{}})}),(async()=>(await new Promise(Be=>setTimeout(Be,400)),L||A(null)))()}),xe=Y.on("challenge_dismissed",()=>{A(null)});return()=>{L=!0,le(),j(),Se(),xe()}},[Y,e]),ge?(0,Zn.jsx)("div",{role:"alert",children:ge.message}):!Y||!f?.html?(0,Zn.jsx)(Zn.Fragment,{children:y}):(0,Zn.jsxs)(Zn.Fragment,{children:[Me&&(0,Zn.jsx)(tn,{status:Me,errorMessage:ie,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...F?{theme:F}:{}}),(0,Zn.jsx)(ho,{capture:Y,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,verificationRequired:f.verificationRequired,theme:ct,containerStyle:St,onReady:()=>{(0,Xe.invokeMerchantCallback)(()=>et.current?.())},onValidation:L=>{(0,Xe.invokeMerchantCallback)(()=>Fe.current?.(L))},onError:L=>{if(!L)return;fe.current&&(fe.current=!1,he(L),A("error"),setTimeout(()=>A(null),400));let le=uo(new Error(L),{code:"card_setup_widget_failed",retryable:!0});(0,Xe.invokeMerchantCallback)(()=>Ue.current?.(le))}})]})}var Sc=require("@flopay/js/card-setup"),kn=require("@flopay/shared"),wc=require("@paypal/paypal-js"),Io=require("react");var kc=require("react/jsx-runtime");function Rc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:c,customer:{userId:p,email:y},onSubmitting:g,onConfirmed:E,onFailed:R,onAbandoned:_}){let H=(0,Io.useRef)(null),T=(0,Io.useRef)({onSubmitting:g,onConfirmed:E,onFailed:R,onAbandoned:_});T.current={onSubmitting:g,onConfirmed:E,onFailed:R,onAbandoned:_};let[Y]=(0,Io.useState)(()=>(0,Gn.detectPayPalEnvironment)().inAppBrowser);return(0,Io.useEffect)(()=>{let B=!0,f,h=new Sc.PaymentAPI(s,{telemetry:c}),ge={userId:p,email:y};return(async()=>{try{let S=await(0,wc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),Me=H.current;if(!B||!Me)return;if(!S?.Buttons)throw new kn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let A=S.Buttons({createVaultSetupToken:async()=>{T.current.onSubmitting();let ie=await h.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:kn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,kn.isSettledSessionIntent)(ie))throw(0,kn.settledSessionIntentError)(n);if(ie.provider!=="paypal"||ie.providerObjectType!=="setup_token")throw new kn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return ie.providerObjectId},onApprove:async ie=>{let he=ie.vaultSetupToken;if(!he)throw new kn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let fe=await h.processPayment(ge.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:he,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:kn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:ge});if(!fe.ok)throw new kn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:fe.status});B&&T.current.onConfirmed()},onCancel:()=>{B&&T.current.onAbandoned()},onError:ie=>{if(!B)return;let{popupBlocked:he}=(0,we.classifyExternalMethodFailure)(ie,{inAppBrowser:Y,handoffObserved:!1});T.current.onFailed(he?new Error((0,we.buildExternalMethodRecoveryMessage)("PayPal",!0,Y)):ie,{code:he?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>A.close(),await A.render(Me)}catch(S){if(!B)return;T.current.onFailed(S,{code:"paypal_unavailable",retryable:!0})}})(),()=>{B=!1,f?.().catch(()=>{}),h.destroy()}},[s,e,r,y,t,Y,a,n,c,p]),(0,kc.jsx)("div",{ref:H,"data-flopay-paypal-setup":""})}var Ic=require("@flopay/js/card-setup"),En=require("@flopay/shared"),Qn=require("@stripe/react-stripe-js"),_c=require("@stripe/stripe-js"),Kr=require("react");var jr=require("react/jsx-runtime"),Tc={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"}},xs=new Map;function bu(e){let t=xs.get(e);if(t)return t;let r=(0,_c.loadStripe)(e).catch(n=>{throw xs.delete(e),n});return xs.set(e,r),r}function Su(e){return e?(0,En.toStripeAppearance)(e):void 0}function wu(e){return(0,we.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function Ec(e){return e==="paypal"?"PayPal":(0,En.getStripeMethodDisplayName)(e)}function Ru(){return typeof window>"u"?"":window.location.href}var ku={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function Mc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:c}=e,[p]=(0,Kr.useState)(()=>bu(t)),y=(0,Kr.useMemo)(()=>{let g=Su(c),E=(0,En.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:Tc[r]?.types??[r],...E?{setupFutureUsage:E}:{},...g?{appearance:g}:{}}},[c,n,a,s,r]);return(0,jr.jsx)(Qn.Elements,{stripe:p,options:y,children:(0,jr.jsx)(Eu,{...e})})}function Eu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:c,themeId:p,buttonsLayout:y,onSubmitting:g,onConfirmed:E,onDeclined:R,onFailed:_,onValidation:H,onUnavailable:T}){let Y=(0,Qn.useStripe)(),B=(0,Qn.useElements)(),[f,h]=(0,Kr.useState)(!1),[ge,S]=(0,Kr.useState)("loading"),[Me,A]=(0,Kr.useState)(!1),[ie,he]=(0,Kr.useState)(!1),fe=(0,Kr.useRef)(!1),[Re]=(0,Kr.useState)(()=>(0,Gn.detectPayPalEnvironment)()),[ct,Ke]=(0,Kr.useState)(!1),F=(0,Kr.useCallback)((W,Fe)=>{if((0,we.classifyExternalMethodFailure)(W,{inAppBrowser:Re.inAppBrowser,handoffObserved:!1}).popupBlocked){Ke(!0),_(new Error((0,we.buildExternalMethodRecoveryMessage)(Ec(e),!0,Re.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}_(Fe.message===void 0?W:new Error(Fe.message),{code:Fe.code,retryable:!0})},[Re.inAppBrowser,e,_]),St=(0,Kr.useCallback)(async W=>{let Fe=!1,dt=!1,We=()=>{!W||Fe||dt||(dt=!0,W.paymentFailed({reason:"fail"}))};if(!Y||!B||fe.current){We();return}fe.current=!0,h(!0);try{let Z=await B.submit();if(Z.error){We(),H(Z.error.message??null);return}g();let L=await new Ic.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,En.isSettledSessionIntent)(L))throw(0,En.settledSessionIntentError)(r);if(L.provider!=="stripe"||L.intentKind!=="setup")throw new En.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Fe=!0;let le=await Y.confirmSetup({elements:B,clientSecret:L.clientSecret,confirmParams:{return_url:Ru()},redirect:"if_required"});if(le.error){wu(le.error)?R({...le.error.decline_code||le.error.code?{reason:le.error.decline_code??le.error.code}:{},...le.error.message?{message:le.error.message}:{}}):F(le.error,{code:"payment_method_setup_provider_failed",message:le.error.message??"The payment method could not be saved."});return}E()}catch(Z){We(),F(Z,{code:"payment_method_setup_failed"})}finally{fe.current=!1,h(!1)}},[a,t,B,e,n,E,R,g,H,F,r,Y,s]),et=Tc[e]?.wallet,Ue=et==="paypal"&&(0,Yn.resolveStripePayPalPresentation)(Re,"auto",ct?"blocked":Re.popupCapability)==="redirect",ye=c?.variables?.borderRadius??y?.cardButton?.borderRadius??8;if(t==="wallet"&&et&&!Ue)return(0,jr.jsxs)(jr.Fragment,{children:[(0,jr.jsx)(ta,{}),(0,jr.jsx)(Ma,{state:ge,borderRadius:ye,children:(0,jr.jsx)(Qn.ExpressCheckoutElement,{options:{...gi,paymentMethods:fi([e])},onReady:W=>{let Fe=Ta(W,[et]);S(Fe),Fe==="unavailable"&&T()},onLoadError:()=>{S("load_error"),T()},onConfirm:W=>{St(W)}})})]});let J=Ec(e);return(0,jr.jsxs)(jr.Fragment,{children:[Me?(0,jr.jsx)(yi,{method:e,themeId:p,hasNextStep:!0,highlighted:ie,disabled:f,onClick:()=>he(W=>!W),backgroundColor:y?.cardButton?.backgroundColor,borderColor:y?.cardInputBorder,textColor:y?.cardButton?.color,borderRadius:ye}):null,(0,jr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ie,style:ie?{display:"flex",flexDirection:"column"}:ku,children:[(0,jr.jsx)(Qn.PaymentElement,{options:{layout:hi},onReady:()=>A(!0),onLoadError:()=>T(),onChange:W=>{W.complete&&H(null)}}),(0,jr.jsx)(Pi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!Y||!B||f||!ie,onClick:()=>{St()},color:c?.variables?.colorPrimary??"#4A49FF",borderRadius:c?.variables?.borderRadius??"8px",style:y?.submitButton,children:f?"Saving\u2026":`Save ${J}`})]})]})}var Na=require("@flopay/js/card-setup"),kr=require("@flopay/shared"),Qe=Qi(require("react"),1);var na=require("@flopay/js/card-setup"),xr=require("@flopay/shared");var pr=require("react/jsx-runtime"),Iu=15,_u=2e3;function Tu(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function As(e){return new Promise(t=>setTimeout(t,e))}async function Mu(e,t,r){if(!t.trim())throw new kr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new kr.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,kr.isCardSetupCheckoutSession)(a))throw new kr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,xr.readSetupAdvertisement)(n);if(!(0,xr.advertisesAnyMethod)(s)){let{skippedForMissingCurrency:c}=s,p=c.length>0?`FloPay: this setup session advertises only Stripe methods (${c.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 kr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function xu(e,t,r,n,a){let s=t.vault??null;(0,kr.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let c=(0,kr.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!c)throw new kr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return c}var Fi=class extends Qe.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 xc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:c="modern-light",containerStyle:p,appearance:y,buttonsStyles:g,loading:E=null,onReady:R,onComplete:_,onDecline:H,onCancel:T,onValidation:Y,onError:B}){let[f]=(0,Qe.useState)(na.readSetupRedirectReturn),[h,ge]=(0,Qe.useState)(null),[S,Me]=(0,Qe.useState)(!1),[A,ie]=(0,Qe.useState)(null),[he,fe]=(0,Qe.useState)(null),[Re,ct]=(0,Qe.useState)(null),[Ke,F]=(0,Qe.useState)(null),[St,et]=(0,Qe.useState)(()=>new Set),Ue=(0,Qe.useRef)(St),ye=(0,Qe.useRef)(null);ye.current=h;let J=(0,Qe.useRef)(!1),W=(0,Qe.useRef)(!1),Fe=(0,Qe.useRef)(!1),dt=(0,Qe.useRef)(!1),We=(0,Qe.useRef)(0),Z=(0,Qe.useRef)(0),L=(0,Qe.useRef)(!1),{vaultTheme:le,surface:j,overlayTheme:Se,appearance:xe,buttonsLayout:Pe}=(0,Qe.useMemo)(()=>xi({theme:c,appearance:y,buttonsStyles:g}),[c,y,g]),Be=(0,Qe.useMemo)(()=>(0,xa.mergeCardSetupSurface)(j,p),[j,p]),M=(0,Qe.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:R,onComplete:_,onDecline:H,onCancel:T,onValidation:Y,onError:B});M.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:R,onComplete:_,onDecline:H,onCancel:T,onValidation:Y,onError:B},(0,Qe.useEffect)(()=>{L.current=!0;let u=We.current+1;return We.current=u,()=>{L.current=!1,Z.current+=1,queueMicrotask(()=>{We.current===u&&(Fe.current||dt.current||(dt.current=!0,(0,Xe.invokeMerchantCallback)(()=>{M.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let nt=(0,Qe.useCallback)((u,C)=>{Fe.current=!0,J.current=!1,F({status:"success",wording:u,message:null}),(async()=>(await As(600),!W.current&&(W.current=!0,(0,Xe.invokeMerchantCallback)(()=>{M.current.onComplete?.({status:"succeeded",sessionId:M.current.sessionId,...C?{paymentMethod:C}:{}})}),L.current&&F(null))))()},[]),je=(0,Qe.useCallback)((u,C)=>{Fe.current=!0,J.current=!1,F({status:"error",wording:u,message:C.message??null}),(0,Xe.invokeMerchantCallback)(()=>{M.current.onDecline?.({status:"declined",sessionId:M.current.sessionId,...C.reason?{reason:C.reason}:{},...C.message?{message:C.message}:{}})}),(async()=>(await As(400),L.current&&F(null)))()},[]),ut=(0,Qe.useCallback)((u,C)=>{J.current?(J.current=!1,F({status:"error",wording:u,message:C.message}),setTimeout(()=>{L.current&&F(null)},400)):F(null),(0,Xe.invokeMerchantCallback)(()=>M.current.onError?.(C))},[]),Ge=(0,Qe.useCallback)(async u=>{let C=Z.current+1;Z.current=C;let Q=()=>!L.current||C!==Z.current;J.current=!0,F({status:"processing",wording:"payment_method",message:null});let ce=new Na.PaymentAPI((0,kr.resolveBillingApiUrl)(M.current.billingApiUrl),{telemetry:M.current.telemetry});try{for(let N=0;N<Iu;N+=1){if((N>0||u.waitFirst)&&await As(_u),Q())return;let w=await ce.getUnifiedCheckoutSession(M.current.sessionId,M.current.nonce);if(Q())return;let qt=w.data.session?.status;if(qt==="complete"){Me(!0),nt("payment_method");return}if(qt==="expired")throw new kr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new kr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(N){if(Q())return;let w=N instanceof kr.FloPayError&&N.code==="payment_method_setup_unverified";ut("payment_method",uo(N,w?{retryable:!0}:{}))}finally{ce.destroy()}},[ut,nt]);(0,Qe.useEffect)(()=>{let u=!0,C=(0,kr.resolveBillingApiUrl)(a),Q=new Na.PaymentAPI(C,{telemetry:s});ge(null),Me(!1),ie(null),fe(null),ct(null);let ce=new Set;return Ue.current=ce,et(ce),Fe.current=!1,dt.current=!1,W.current=!1,(async()=>{try{let{session:N,advertisement:w}=await Mu(Q,r,n);if(!u)return;let qt={advertisement:w,customer:Tu(N),...N.futureUse?{futureUse:N.futureUse}:{},...N.futureUseUnsupported?{futureUseUnsupported:N.futureUseUnsupported}:{}};if(f){if((0,na.clearSetupRedirectParams)(),N.status==="complete"){Me(!0),ge(qt),nt("payment_method");return}f.failed?je("payment_method",{reason:"redirect_failed"}):Ge({waitFirst:!0})}let Ar=w.card?await xu(Q,N,r,n,C):null;if(!u)return;ge(qt),Ar&&(fe(Ar),ie(new Na.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(N){if(!u)return;let w=uo(N);Fe.current=!0,ct(w),(0,Xe.invokeMerchantCallback)(()=>M.current.onError?.(w))}})(),()=>{u=!1,Q.destroy()}},[a,n,f,je,nt,r,s,Ge]),(0,Qe.useEffect)(()=>{if(!A)return;J.current=!1;let u=A.on("submitting",()=>{J.current=!0,F({status:"processing",wording:"card",message:null})}),C=A.on("complete",N=>{nt("card",N.paymentMethod)}),Q=A.on("decline",N=>{je("card",{...N.declineReason?{reason:N.declineReason}:{},...N.message?{message:N.message}:{}})}),ce=A.on("challenge_dismissed",()=>{F(null)});return()=>{u(),C(),Q(),ce()}},[A,je,nt]);let $e=(0,Qe.useCallback)((u,C,Q)=>{if(Q.retryable){ut("payment_method",uo(C,Q));return}if(Ue.current.has(u))return;let ce=new Set(Ue.current);ce.add(u),Ue.current=ce,et(ce);let N=ye.current?.advertisement,w=N?(0,xr.advertisedMethodKeys)(N).some(qt=>!ce.has(qt)):!1;ut("payment_method",uo(C,{code:Q.code,retryable:w}))},[ut]),Rt=(0,Qe.useMemo)(()=>({onSubmitting:()=>{J.current=!0,F({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Ge({waitFirst:!1})},onDeclined:u=>je("payment_method",u),onValidation:u=>{(0,Xe.invokeMerchantCallback)(()=>M.current.onValidation?.(u))},onAbandoned:()=>{J.current=!1,F(null)}}),[je,Ge]),Ot=(0,Qe.useRef)($e);Ot.current=$e;let zt=(0,Qe.useRef)(new Map),Ft=u=>{let C=zt.current.get(u);if(C)return C;let Q=(ce,N)=>Ot.current(u,ce,N);return zt.current.set(u,Q),Q},ue=(0,Qe.useCallback)(u=>{if(Ue.current.has(u))return;let C=new Set(Ue.current);C.add(u),Ue.current=C,et(C);let Q=ye.current?.advertisement;Q&&(0,xr.advertisedMethodKeys)(Q).some(N=>!C.has(N))||ut("payment_method",uo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ut]),pe=(0,Qe.useRef)(ue);pe.current=ue;let X=(0,Qe.useRef)(new Map),Pt=u=>{let C=X.current.get(u);if(C)return C;let Q=()=>pe.current(u);return X.current.set(u,Q),Q},pt=Ke?(0,pr.jsx)(tn,{status:Ke.status,errorMessage:Ke.message,...(0,xr.setupOverlayLabels)(Ke.wording),successNote:null,...Se?{theme:Se}:{}}):null;if(Re)return(0,pr.jsx)("div",{role:"alert",children:Re.message});if(!h||S)return(0,pr.jsxs)(pr.Fragment,{children:[pt,h?null:E]});let{advertisement:V,customer:rt,futureUse:wt,futureUseUnsupported:ke}=h,v=(0,kr.resolveBillingApiUrl)(a),U=s===void 0?{}:{telemetry:s},ne=V.stripe.filter(({method:u})=>!St.has(u)),Ae=St.has("paypal")?null:V.paypal,Dt=!!(V.card&&A&&he?.html),ot=({method:u,publishableKey:C,currency:Q})=>(0,pr.jsx)("div",{"data-flopay-payment-method":u,style:{display:"contents"},children:(0,pr.jsx)(Fi,{onFailed:Ft(u),children:(0,pr.jsx)(Qe.Suspense,{fallback:null,children:(0,pr.jsx)(e,{method:u,category:(0,xr.stripeMethodCategory)(u),publishableKey:C,currency:Q,...wt?{futureUse:wt}:{},...ke?{futureUseUnsupported:ke}:{},sessionId:r,nonce:n,billingApiUrl:v,...U,...xe?{appearance:xe}:{},...Pe?{buttonsLayout:Pe}:{},...typeof c=="string"?{themeId:c}:{},...Rt,onFailed:Ft(u),onUnavailable:Pt(u)})})})},u),De=ne.filter(({method:u})=>(0,xr.stripeMethodCategory)(u)==="wallet"),Oe=ne.filter(({method:u})=>(0,xr.stripeMethodCategory)(u)!=="wallet"),_t=ne.length>0||Ae!==null;return(0,pr.jsxs)(pr.Fragment,{children:[pt,_t?(0,pr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[De.map(ot),Ae?(0,pr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,pr.jsx)(Fi,{onFailed:Ft("paypal"),children:(0,pr.jsx)(Qe.Suspense,{fallback:null,children:(0,pr.jsx)(t,{clientId:Ae.clientId,...Ae.environment?{environment:Ae.environment}:{},...V.currency?{currency:V.currency}:{},sessionId:r,nonce:n,billingApiUrl:v,customer:rt,...U,...Rt,onFailed:Ft("paypal"),onUnavailable:Pt("paypal")})})})}):null,Oe.map(ot)]}):null,Dt&&_t?(0,pr.jsx)(vi,{label:"or add a card"}):null,Dt&&A&&he?.html?(0,pr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,pr.jsx)(ho,{capture:A,html:he.html,messageToken:he.messageToken,expectedOrigin:he.expectedOrigin,verificationRequired:he.verificationRequired,theme:le,containerStyle:Be,onReady:()=>{(0,Xe.invokeMerchantCallback)(()=>M.current.onReady?.())},onValidation:u=>{(0,Xe.invokeMerchantCallback)(()=>M.current.onValidation?.(u))},onError:u=>{u&&ut("card",uo(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Fc=require("react/jsx-runtime"),Au={StripeSetupMethod:Mc,PayPalSetupMethod:Rc};function Ac(e){return(0,Fc.jsx)(xc,{...e,branches:Au})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}let ke={paypal:r&&g(Fo),wallets:n&&(a||s)&&g(Fo),card:n&&(t?g(Fo):(0,M.jsx)("button",{type:"button",onClick:()=>{e?.("card"),V(!0)},style:{width:"100%",...O,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:D.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,...D.cardButton},onMouseDown:m=>{m.currentTarget.style.transform="scale(0.985)"},onMouseUp:m=>{m.currentTarget.style.transform="scale(1)"},children:(0,M.jsx)(Go,{content:b})}))};return(0,M.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Me.DEFAULT_PAYMENT_METHOD_ORDER.map(m=>(0,M.jsx)(R.default.Fragment,{children:ke[m]},m)),(0,M.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var En=require("react/jsx-runtime"),Bu=44;function Fc(e){return new Promise(t=>setTimeout(t,e))}function Du(e,t){return e instanceof _n.FloPayError?e:new _n.FloPayError(e instanceof Error?e.message:t,"api_error")}function Ou(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Lu(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 Bc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:s,products:d,items:p,subscriptions:y,account:b,successUrl:v,cancelUrl:S,couponCodes:E,tagsData:V,utmMetadata:x,billingApiUrl:D,locale:A,theme:g,appearance:O,buttonsTheme:ke,buttonsStyles:m,onSuccess:me,onError:_,onDecline:ne,children:fe,disabled:ce=!1,type:Ee="button",style:vt,...ze}){let L=(0,gt.useMemo)(()=>(0,_n.resolveBillingApiUrl)(D),[D]),Ye=(0,gt.useMemo)(()=>Lu({createSession:r,clientId:s,products:d,items:p,subscriptions:y,account:b,successUrl:v,cancelUrl:S,couponCodes:E,tagsData:V,utmMetadata:x}),[b,S,s,E,r,d,p,y,v,V,x]),[at,qe]=(0,gt.useState)(!1),[ye,N]=(0,gt.useState)(null),[le,de]=(0,gt.useState)(null),[rt,je]=(0,gt.useState)(!1),[Q,W]=(0,gt.useState)(null),[ee,te]=(0,gt.useState)(null),ve=(0,gt.useRef)(!0),ue=(0,gt.useRef)(null),pe=(0,gt.useRef)(ee),Fe=(0,gt.useRef)(me),ge=(0,gt.useRef)(_),H=(0,gt.useRef)(ne),Be=(0,gt.useCallback)(h=>yi(ue,async U=>{try{return await h(U)}catch(he){throw U.aborted?oa(he):he}}),[]);(0,gt.useEffect)(()=>{pe.current=ee},[ee]),(0,gt.useEffect)(()=>{Fe.current=me},[me]),(0,gt.useEffect)(()=>{ge.current=_},[_]),(0,gt.useEffect)(()=>{H.current=ne},[ne]),(0,gt.useEffect)(()=>(ve.current=!0,()=>{ve.current=!1,ue.current?.abort()}),[]),(0,gt.useEffect)(()=>{if(typeof window>"u")return;let h=U=>{U.key==="Escape"&&te(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let ut=(0,gt.useCallback)((h,U=Ia)=>{H.current?.(kr(U,h,{code:h.code,declineCode:h.declineCode}))},[]),Xe=(0,gt.useCallback)(async h=>{ve.current&&(de(null),je(h.result.status==="authorized"),N("success"),await Fc(600),ve.current&&(0,Ge.invokeMerchantCallback)(()=>Fe.current?.(h)))},[]),nt=(0,gt.useCallback)(async(h,U)=>{ve.current&&(ge.current?.(h),U?.emitDecline&&ut(h,U.method),de(h.message),je(!1),N("error"),await Fc(400))},[ut]),it=(0,gt.useCallback)(async(h,U,he)=>{let ae=h.data.session??null;if(!ae)throw Co(new _n.FloPayError("No session data returned","api_error"),U);let Wt=ae.clientSecret||t;if(so(ae)){await Xe({result:io(ae,U),session:ae,sessionId:ae.id||U,autoCompleted:!1});return}if(ae.status==="expired")throw Co(ri(ae),ae.id||U);try{if(h.autoProcessingPending){let Ae=h.autoProcessingPending,be=new Bi.PaymentAPI(L),bt=await Be(I=>be.waitForCheckoutSessionCompletion(Ae.sessionId,{initialDelayMs:Ae.retryAfterMs,nonce:Wt,statusUrl:Ae.statusUrl,signal:I})),u=bo(bt,ae),B=bt.autoProcessingError?.type==="3ds_required"&&bt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:bt.autoProcessingError.nextActionRedirectUrl}:null;if(B&&U&&Wt){let I=Ta(L,U,ae),xe=await Be(z=>aa(B,{billingApiUrl:L,sessionId:U,nonce:Wt,session:ae,signal:z,telemetry:!0,...I.telemetry?{challengeTelemetry:I.telemetry}:{}})).finally(I.release);await Xe({result:xe,session:ae,sessionId:ae.id||U,autoCompleted:!1});return}if(bt.autoProcessingError)throw Xn(bt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:bt.autoProcessingError.checkoutMethod});if(!so(u))throw Jo(u);await Xe({result:io(u,U),session:u,sessionId:u.id||U,autoCompleted:!1});return}if(h.autoProcessingError){let Ae=h.autoProcessingError.nextActionRedirectUrl;if(h.autoProcessingError.type==="3ds_required"&&Ae&&U&&Wt){let be=await Be(I=>nc({billingApiUrl:L,sessionId:U,nonce:Wt,nextActionRedirectUrl:Ae,signal:I}));if(be.status==="declined")throw Xn({type:be.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:be.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let u=await new Bi.PaymentAPI(L).waitForCheckoutSessionCompletion(U,{initialDelayMs:0,nonce:Wt}),B=bo(u,ae);if(!so(B))throw Xn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await Xe({result:io(B,U),session:B,sessionId:B.id||U,autoCompleted:!1});return}throw Xn(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(he?.fromCreateSession&&h.autoProcessingAttempted===!0)throw Xn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Bt=await ia({billingApiUrl:L,sessionId:U??ae.id,session:ae,nonce:Wt});if(Bt.type==="next_action_required"&&Wt){let Ae=U??ae.id,be=Ta(L,Ae,ae),bt=await Be(u=>aa(Bt,{billingApiUrl:L,sessionId:Ae,nonce:Wt,session:ae,signal:u,telemetry:!0,...be.telemetry?{challengeTelemetry:be.telemetry}:{}})).finally(be.release);await Xe({result:bt,session:ae,sessionId:ae.id||Ae,autoCompleted:!1});return}if(Bt.type!=="success")throw Xn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Xe({result:Bt.result,session:ae,sessionId:ae.id||U,autoCompleted:!1})}catch(Bt){let Ae=ae.id||U,be=Co(Ma(Bt),Ae);if(be.code==="three_ds_aborted")return;if(be.code==="checkout_processing_timeout"){if(!ve.current)return;W(be.message),(0,Ge.invokeMerchantCallback)(()=>ge.current?.(be));return}await nt(be,{emitDecline:!0,method:be.checkoutMethod??Ia}),Ou(be,Ae)&&Ae&&ve.current&&te({sessionId:Ae,errorMessage:be.message,nonce:Wt||void 0,payPalOrderId:be.orderId})}},[t,L,Be,nt,Xe]),or=(0,gt.useCallback)(async h=>{if(ze.onClick?.(h),!(h.defaultPrevented||ce||at)){if(te(null),W(null),e&&Ye){let U=new _n.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await nt(U),ve.current&&(N(null),de(null));return}if(!e&&!Ye){let U=new _n.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await nt(U),ve.current&&(N(null),de(null));return}qe(!0),de(null),je(!1),N("processing");try{let U=new Bi.PaymentAPI(L);if(e){let he=await U.getUnifiedCheckoutSession(e,t);await it(he,e);return}try{let he=await U.createAndFetchSession({...Ye});await it(he,he.data.session?.id??null,{fromCreateSession:!0})}catch(he){if(ni(he)==="session_auto_completed"){await Xe({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw he}}catch(U){await nt(Co(Du(U,"Automatic payment failed. Please try again."),e))}finally{ve.current&&(N(null),de(null),qe(!1))}}},[ze.onClick,Ye,ce,at,t,it,L,e,nt,Xe]),_t=(0,gt.useCallback)(h=>{let U=pe.current;te(null),Fe.current?.({result:h,session:null,sessionId:U?.sessionId??null,autoCompleted:!1})},[]),qt=(0,gt.useCallback)(h=>{ge.current?.(h)},[]),Ce=(0,gt.useCallback)(h=>{H.current?.(h)},[]),oe=(0,gt.useMemo)(()=>(0,_n.resolveTheme)(g),[g]),Ze=(0,gt.useMemo)(()=>{let h=oe?.buttonsLayout??(0,_n.resolveButtonsLayoutTheme)(ke);return m?{...h,...m,cardButton:{...h.cardButton,...m.cardButton}}:h},[oe,ke,m]),J=(0,gt.useMemo)(()=>{let h=oe?.appearance;return O?h?{...h,...O,variables:{...h.variables,...O.variables}}:O:h},[O,oe]),Ct=J?.variables,Rt=Ct?.colorPrimary??"#4A49FF",se=Ct?.colorPrimaryHover??(0,Ms.darkenHex)(Rt,.12),De=Ct?.borderRadius??"8px";return(0,En.jsxs)(En.Fragment,{children:[(0,En.jsx)("button",{...ze,type:Ee,onClick:or,disabled:ce||at,"aria-busy":at,style:{width:"100%",...fe===void 0?{boxSizing:"border-box",height:Bu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Ze.cardButton,...Ts({themeBundle:oe,resolvedPrimaryColor:Rt,resolvedBorderRadius:De,submitButtonStyle:Ze.submitButton,explicitPrimaryColor:Ct?.colorPrimary}),fontSize:Ze.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ce||at?"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||at?.6:1,...vt},onMouseEnter:h=>{ze.onMouseEnter?.(h),!h.defaultPrevented&&!ce&&!at&&(oe||Ct?.colorPrimary)&&(h.currentTarget.style.backgroundColor=se)},onMouseLeave:h=>{ze.onMouseLeave?.(h),!h.defaultPrevented&&(oe||Ct?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Rt)},onMouseDown:h=>{ze.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{ze.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,En.jsx)(Go,{content:fe})}),Q&&(0,En.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Q}),ye&&(0,En.jsx)(on,{status:ye,errorMessage:le,authorized:rt}),ee&&(0,En.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&te(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,En.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,En.jsx)(Fi,{sessionId:ee.sessionId,nonce:ee.nonce,checkoutMode:"full",billingApiUrl:L,locale:A,theme:g,...J?{appearance:J}:{},buttonsTheme:ke,buttonsStyles:m,initialErrorMessage:ee.errorMessage,initialPayPalOrderId:ee.payPalOrderId,cardTitleContent:null,onComplete:_t,onError:qt,onDecline:Ce})})})]})}var Oi=require("@flopay/js/card-setup"),Xr=require("@flopay/shared"),Gt=require("react");var Ns=require("@flopay/shared"),Nu=require("@flopay/shared");function Di(e){let t=(0,Ns.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Zn=require("react/jsx-runtime"),za=class extends Xr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function mo(e,t={}){let r=e instanceof Xr.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 za(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 Dc({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:d,buttonsStyles:p,loading:y=null,onReady:b,onComplete:v,onDecline:S,onCancel:E,onValidation:V,onError:x}){let[D,A]=(0,Gt.useState)(null),[g,O]=(0,Gt.useState)(null),[ke,m]=(0,Gt.useState)(null),[me,_]=(0,Gt.useState)(null),[ne,fe]=(0,Gt.useState)(null),ce=(0,Gt.useRef)(!1),Ee=(0,Gt.useRef)(!1),{vaultTheme:vt,surface:ze,overlayTheme:L}=(0,Gt.useMemo)(()=>Di({theme:a,appearance:d,buttonsStyles:p}),[a,d,p]),Ye=(0,Gt.useMemo)(()=>(0,Fa.mergeCardSetupSurface)(ze,s),[ze,s]),at=(0,Gt.useRef)(b),qe=(0,Gt.useRef)(x),ye=(0,Gt.useRef)(v),N=(0,Gt.useRef)(S),le=(0,Gt.useRef)(E),de=(0,Gt.useRef)(V),rt=(0,Gt.useRef)(!1),je=(0,Gt.useRef)(!1),Q=(0,Gt.useRef)(0);return at.current=b,qe.current=x,ye.current=v,N.current=S,le.current=E,de.current=V,(0,Gt.useEffect)(()=>{let W=Q.current+1;return Q.current=W,()=>{queueMicrotask(()=>{Q.current===W&&(rt.current||je.current||(je.current=!0,(0,Ge.invokeMerchantCallback)(()=>{le.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Gt.useEffect)(()=>{let W=!0,ee=(0,Xr.resolveBillingApiUrl)(r),te=new Oi.PaymentAPI(ee,{telemetry:n});return A(null),O(null),m(null),rt.current=!1,je.current=!1,(async()=>{try{if(!e.trim())throw new Xr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Xr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ve=await te.getUnifiedCheckoutSession(e,t);if(!W)return;let ue=ve.data.session;if(!ue||!(0,Xr.isCardSetupCheckoutSession)(ue))throw new Xr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let pe=ue.vault;(0,Xr.isMountableVaultBlock)(pe)||(pe=await te.getVaultCapture(e,t));let Fe=(0,Xr.resolveVaultMountOptions)(pe,{billingApiUrl:ee,sessionId:e,nonce:t});if(!Fe)throw new Xr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!W)return;O(Fe),A(new Oi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(ve){if(!W)return;let ue=mo(ve);rt.current=!0,m(ue),(0,Ge.invokeMerchantCallback)(()=>qe.current?.(ue))}})(),()=>{W=!1,te.destroy()}},[r,t,e,n]),(0,Gt.useEffect)(()=>{if(!D)return;let W=!1;Ee.current=!1,ce.current=!1;let ee=D.on("submitting",()=>{ce.current=!0,fe(null),_("processing")}),te=D.on("complete",pe=>{rt.current=!0,ce.current=!1,_("success"),(async()=>(await new Promise(Fe=>setTimeout(Fe,600)),!Ee.current&&(Ee.current=!0,(0,Ge.invokeMerchantCallback)(()=>{ye.current?.({status:"succeeded",sessionId:e,...pe.paymentMethod?{paymentMethod:pe.paymentMethod}:{}})}),W||_(null))))()}),ve=D.on("decline",pe=>{rt.current=!0,ce.current=!1,fe(pe.message??null),_("error"),(0,Ge.invokeMerchantCallback)(()=>{N.current?.({status:"declined",sessionId:e,...pe.declineReason?{reason:pe.declineReason}:{},...pe.message?{message:pe.message}:{}})}),(async()=>(await new Promise(Fe=>setTimeout(Fe,400)),W||_(null)))()}),ue=D.on("challenge_dismissed",()=>{_(null)});return()=>{W=!0,ee(),te(),ve(),ue()}},[D,e]),ke?(0,Zn.jsx)("div",{role:"alert",children:ke.message}):!D||!g?.html?(0,Zn.jsx)(Zn.Fragment,{children:y}):(0,Zn.jsxs)(Zn.Fragment,{children:[me&&(0,Zn.jsx)(on,{status:me,errorMessage:ne,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...L?{theme:L}:{}}),(0,Zn.jsx)(wo,{capture:D,html:g.html,messageToken:g.messageToken,expectedOrigin:g.expectedOrigin,verificationRequired:g.verificationRequired,theme:vt,containerStyle:Ye,onReady:()=>{(0,Ge.invokeMerchantCallback)(()=>at.current?.())},onValidation:W=>{(0,Ge.invokeMerchantCallback)(()=>de.current?.(W))},onError:W=>{if(!W)return;ce.current&&(ce.current=!1,fe(W),_("error"),setTimeout(()=>_(null),400));let ee=mo(new Error(W),{code:"card_setup_widget_failed",retryable:!0});(0,Ge.invokeMerchantCallback)(()=>qe.current?.(ee))}})]})}var Oc=require("@flopay/js/card-setup"),In=require("@flopay/shared"),Lc=require("@paypal/paypal-js"),Bo=require("react");var Uc=require("react/jsx-runtime");function Nc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:d,customer:{userId:p,email:y},onSubmitting:b,onConfirmed:v,onFailed:S,onAbandoned:E}){let V=(0,Bo.useRef)(null),x=(0,Bo.useRef)({onSubmitting:b,onConfirmed:v,onFailed:S,onAbandoned:E});x.current={onSubmitting:b,onConfirmed:v,onFailed:S,onAbandoned:E};let[D]=(0,Bo.useState)(()=>(0,Gn.detectPayPalEnvironment)().inAppBrowser);return(0,Bo.useEffect)(()=>{let A=!0,g,O=new Oc.PaymentAPI(s,{telemetry:d}),ke={userId:p,email:y};return(async()=>{try{let m=await(0,Lc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),me=V.current;if(!A||!me)return;if(!m?.Buttons)throw new In.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let _=m.Buttons({createVaultSetupToken:async()=>{x.current.onSubmitting();let ne=await O.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:In.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,In.isSettledSessionIntent)(ne))throw(0,In.settledSessionIntentError)(n);if(ne.provider!=="paypal"||ne.providerObjectType!=="setup_token")throw new In.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return ne.providerObjectId},onApprove:async ne=>{let fe=ne.vaultSetupToken;if(!fe)throw new In.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let ce=await O.processPayment(ke.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:fe,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:In.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:ke});if(!ce.ok)throw new In.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:ce.status});A&&x.current.onConfirmed()},onCancel:()=>{A&&x.current.onAbandoned()},onError:ne=>{if(!A)return;let{popupBlocked:fe}=(0,Re.classifyExternalMethodFailure)(ne,{inAppBrowser:D,handoffObserved:!1});x.current.onFailed(fe?new Error((0,Re.buildExternalMethodRecoveryMessage)("PayPal",!0,D)):ne,{code:fe?"popup_blocked":"paypal_setup_failed",retryable:!0})}});g=()=>_.close(),await _.render(me)}catch(m){if(!A)return;x.current.onFailed(m,{code:"paypal_unavailable",retryable:!0})}})(),()=>{A=!1,g?.().catch(()=>{}),O.destroy()}},[s,e,r,y,t,D,a,n,d,p]),(0,Uc.jsx)("div",{ref:V,"data-flopay-paypal-setup":""})}var qc=require("@flopay/js/card-setup"),Tn=require("@flopay/shared"),Qn=require("@stripe/react-stripe-js"),jc=require("@stripe/stripe-js"),Jr=require("react");var qr=require("react/jsx-runtime"),Vc={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"}},Us=new Map;function Uu(e){let t=Us.get(e);if(t)return t;let r=(0,jc.loadStripe)(e).catch(n=>{throw Us.delete(e),n});return Us.set(e,r),r}function zu(e){return e?(0,Tn.toStripeAppearance)(e):void 0}function qu(e){return(0,Re.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function zc(e){return e==="paypal"?"PayPal":(0,Tn.getStripeMethodDisplayName)(e)}function ju(){return typeof window>"u"?"":window.location.href}var Vu={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function Wc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:d}=e,[p]=(0,Jr.useState)(()=>Uu(t)),y=(0,Jr.useMemo)(()=>{let b=zu(d),v=(0,Tn.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:Vc[r]?.types??[r],...v?{setupFutureUsage:v}:{},...b?{appearance:b}:{}}},[d,n,a,s,r]);return(0,qr.jsx)(Qn.Elements,{stripe:p,options:y,children:(0,qr.jsx)(Wu,{...e})})}function Wu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:d,themeId:p,buttonsLayout:y,onSubmitting:b,onConfirmed:v,onDeclined:S,onFailed:E,onValidation:V,onUnavailable:x}){let D=(0,Qn.useStripe)(),A=(0,Qn.useElements)(),[g,O]=(0,Jr.useState)(!1),[ke,m]=(0,Jr.useState)("loading"),[me,_]=(0,Jr.useState)(!1),[ne,fe]=(0,Jr.useState)(!1),ce=(0,Jr.useRef)(!1),[Ee]=(0,Jr.useState)(()=>(0,Gn.detectPayPalEnvironment)()),[vt,ze]=(0,Jr.useState)(!1),L=(0,Jr.useCallback)((le,de)=>{if((0,Re.classifyExternalMethodFailure)(le,{inAppBrowser:Ee.inAppBrowser,handoffObserved:!1}).popupBlocked){ze(!0),E(new Error((0,Re.buildExternalMethodRecoveryMessage)(zc(e),!0,Ee.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}E(de.message===void 0?le:new Error(de.message),{code:de.code,retryable:!0})},[Ee.inAppBrowser,e,E]),Ye=(0,Jr.useCallback)(async le=>{let de=!1,rt=!1,je=()=>{!le||de||rt||(rt=!0,le.paymentFailed({reason:"fail"}))};if(!D||!A||ce.current){je();return}ce.current=!0,O(!0);try{let Q=await A.submit();if(Q.error){je(),V(Q.error.message??null);return}b();let W=await new qc.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,Tn.isSettledSessionIntent)(W))throw(0,Tn.settledSessionIntentError)(r);if(W.provider!=="stripe"||W.intentKind!=="setup")throw new Tn.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});de=!0;let ee=await D.confirmSetup({elements:A,clientSecret:W.clientSecret,confirmParams:{return_url:ju()},redirect:"if_required"});if(ee.error){qu(ee.error)?S({...ee.error.decline_code||ee.error.code?{reason:ee.error.decline_code??ee.error.code}:{},...ee.error.message?{message:ee.error.message}:{}}):L(ee.error,{code:"payment_method_setup_provider_failed",message:ee.error.message??"The payment method could not be saved."});return}v()}catch(Q){je(),L(Q,{code:"payment_method_setup_failed"})}finally{ce.current=!1,O(!1)}},[a,t,A,e,n,v,S,b,V,L,r,D,s]),at=Vc[e]?.wallet,qe=at==="paypal"&&(0,Yn.resolveStripePayPalPresentation)(Ee,"auto",vt?"blocked":Ee.popupCapability)==="redirect",ye=d?.variables?.borderRadius??y?.cardButton?.borderRadius??8;if(t==="wallet"&&at&&!qe)return(0,qr.jsxs)(qr.Fragment,{children:[(0,qr.jsx)(sa,{}),(0,qr.jsx)(xa,{state:ke,borderRadius:ye,children:(0,qr.jsx)(Qn.ExpressCheckoutElement,{options:{...vi,paymentMethods:Pi([e])},onReady:le=>{let de=Aa(le,[at]);m(de),de==="unavailable"&&x()},onLoadError:()=>{m("load_error"),x()},onConfirm:le=>{Ye(le)}})})]});let N=zc(e);return(0,qr.jsxs)(qr.Fragment,{children:[me?(0,qr.jsx)(hi,{method:e,themeId:p,hasNextStep:!0,highlighted:ne,disabled:g,onClick:()=>fe(le=>!le),backgroundColor:y?.cardButton?.backgroundColor,borderColor:y?.cardInputBorder,textColor:y?.cardButton?.color,borderRadius:ye}):null,(0,qr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ne,style:ne?{display:"flex",flexDirection:"column"}:Vu,children:[(0,qr.jsx)(Qn.PaymentElement,{options:{layout:Ci},onReady:()=>_(!0),onLoadError:()=>x(),onChange:le=>{le.complete&&V(null)}}),(0,qr.jsx)(bi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!D||!A||g||!ne,onClick:()=>{Ye()},color:d?.variables?.colorPrimary??"#4A49FF",borderRadius:d?.variables?.borderRadius??"8px",style:y?.submitButton,children:g?"Saving\u2026":`Save ${N}`})]})]})}var qa=require("@flopay/js/card-setup"),_r=require("@flopay/shared"),Je=as(require("react"),1);var la=require("@flopay/js/card-setup"),xr=require("@flopay/shared");var ur=require("react/jsx-runtime"),$u=15,Hu=2e3;function Ku(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function zs(e){return new Promise(t=>setTimeout(t,e))}async function Gu(e,t,r){if(!t.trim())throw new _r.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new _r.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,_r.isCardSetupCheckoutSession)(a))throw new _r.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,xr.readSetupAdvertisement)(n);if(!(0,xr.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 _r.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function Yu(e,t,r,n,a){let s=t.vault??null;(0,_r.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let d=(0,_r.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!d)throw new _r.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return d}var Li=class extends Je.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 $c({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:d="modern-light",containerStyle:p,appearance:y,buttonsStyles:b,loading:v=null,onReady:S,onComplete:E,onDecline:V,onCancel:x,onValidation:D,onError:A}){let[g]=(0,Je.useState)(la.readSetupRedirectReturn),[O,ke]=(0,Je.useState)(null),[m,me]=(0,Je.useState)(!1),[_,ne]=(0,Je.useState)(null),[fe,ce]=(0,Je.useState)(null),[Ee,vt]=(0,Je.useState)(null),[ze,L]=(0,Je.useState)(null),[Ye,at]=(0,Je.useState)(()=>new Set),qe=(0,Je.useRef)(Ye),ye=(0,Je.useRef)(null);ye.current=O;let N=(0,Je.useRef)(!1),le=(0,Je.useRef)(!1),de=(0,Je.useRef)(!1),rt=(0,Je.useRef)(!1),je=(0,Je.useRef)(0),Q=(0,Je.useRef)(0),W=(0,Je.useRef)(!1),{vaultTheme:ee,surface:te,overlayTheme:ve,appearance:ue,buttonsLayout:pe}=(0,Je.useMemo)(()=>Di({theme:d,appearance:y,buttonsStyles:b}),[d,y,b]),Fe=(0,Je.useMemo)(()=>(0,Fa.mergeCardSetupSurface)(te,p),[te,p]),ge=(0,Je.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:S,onComplete:E,onDecline:V,onCancel:x,onValidation:D,onError:A});ge.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:S,onComplete:E,onDecline:V,onCancel:x,onValidation:D,onError:A},(0,Je.useEffect)(()=>{W.current=!0;let u=je.current+1;return je.current=u,()=>{W.current=!1,Q.current+=1,queueMicrotask(()=>{je.current===u&&(de.current||rt.current||(rt.current=!0,(0,Ge.invokeMerchantCallback)(()=>{ge.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let H=(0,Je.useCallback)((u,B)=>{de.current=!0,N.current=!1,L({status:"success",wording:u,message:null}),(async()=>(await zs(600),!le.current&&(le.current=!0,(0,Ge.invokeMerchantCallback)(()=>{ge.current.onComplete?.({status:"succeeded",sessionId:ge.current.sessionId,...B?{paymentMethod:B}:{}})}),W.current&&L(null))))()},[]),Be=(0,Je.useCallback)((u,B)=>{de.current=!0,N.current=!1,L({status:"error",wording:u,message:B.message??null}),(0,Ge.invokeMerchantCallback)(()=>{ge.current.onDecline?.({status:"declined",sessionId:ge.current.sessionId,...B.reason?{reason:B.reason}:{},...B.message?{message:B.message}:{}})}),(async()=>(await zs(400),W.current&&L(null)))()},[]),ut=(0,Je.useCallback)((u,B)=>{N.current?(N.current=!1,L({status:"error",wording:u,message:B.message}),setTimeout(()=>{W.current&&L(null)},400)):L(null),(0,Ge.invokeMerchantCallback)(()=>ge.current.onError?.(B))},[]),Xe=(0,Je.useCallback)(async u=>{let B=Q.current+1;Q.current=B;let I=()=>!W.current||B!==Q.current;N.current=!0,L({status:"processing",wording:"payment_method",message:null});let xe=new qa.PaymentAPI((0,_r.resolveBillingApiUrl)(ge.current.billingApiUrl),{telemetry:ge.current.telemetry});try{for(let z=0;z<$u;z+=1){if((z>0||u.waitFirst)&&await zs(Hu),I())return;let F=await xe.getUnifiedCheckoutSession(ge.current.sessionId,ge.current.nonce);if(I())return;let $e=F.data.session?.status;if($e==="complete"){me(!0),H("payment_method");return}if($e==="expired")throw new _r.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new _r.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(z){if(I())return;let F=z instanceof _r.FloPayError&&z.code==="payment_method_setup_unverified";ut("payment_method",mo(z,F?{retryable:!0}:{}))}finally{xe.destroy()}},[ut,H]);(0,Je.useEffect)(()=>{let u=!0,B=(0,_r.resolveBillingApiUrl)(a),I=new qa.PaymentAPI(B,{telemetry:s});ke(null),me(!1),ne(null),ce(null),vt(null);let xe=new Set;return qe.current=xe,at(xe),de.current=!1,rt.current=!1,le.current=!1,(async()=>{try{let{session:z,advertisement:F}=await Gu(I,r,n);if(!u)return;let $e={advertisement:F,customer:Ku(z),...z.futureUse?{futureUse:z.futureUse}:{},...z.futureUseUnsupported?{futureUseUnsupported:z.futureUseUnsupported}:{}};if(g){if((0,la.clearSetupRedirectParams)(),z.status==="complete"){me(!0),ke($e),H("payment_method");return}g.failed?Be("payment_method",{reason:"redirect_failed"}):Xe({waitFirst:!0})}let ar=F.card?await Yu(I,z,r,n,B):null;if(!u)return;ke($e),ar&&(ce(ar),ne(new qa.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(z){if(!u)return;let F=mo(z);de.current=!0,vt(F),(0,Ge.invokeMerchantCallback)(()=>ge.current.onError?.(F))}})(),()=>{u=!1,I.destroy()}},[a,n,g,Be,H,r,s,Xe]),(0,Je.useEffect)(()=>{if(!_)return;N.current=!1;let u=_.on("submitting",()=>{N.current=!0,L({status:"processing",wording:"card",message:null})}),B=_.on("complete",z=>{H("card",z.paymentMethod)}),I=_.on("decline",z=>{Be("card",{...z.declineReason?{reason:z.declineReason}:{},...z.message?{message:z.message}:{}})}),xe=_.on("challenge_dismissed",()=>{L(null)});return()=>{u(),B(),I(),xe()}},[_,Be,H]);let nt=(0,Je.useCallback)((u,B,I)=>{if(I.retryable){ut("payment_method",mo(B,I));return}if(qe.current.has(u))return;let xe=new Set(qe.current);xe.add(u),qe.current=xe,at(xe);let z=ye.current?.advertisement,F=z?(0,xr.advertisedMethodKeys)(z).some($e=>!xe.has($e)):!1;ut("payment_method",mo(B,{code:I.code,retryable:F}))},[ut]),it=(0,Je.useMemo)(()=>({onSubmitting:()=>{N.current=!0,L({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Xe({waitFirst:!1})},onDeclined:u=>Be("payment_method",u),onValidation:u=>{(0,Ge.invokeMerchantCallback)(()=>ge.current.onValidation?.(u))},onAbandoned:()=>{N.current=!1,L(null)}}),[Be,Xe]),or=(0,Je.useRef)(nt);or.current=nt;let _t=(0,Je.useRef)(new Map),qt=u=>{let B=_t.current.get(u);if(B)return B;let I=(xe,z)=>or.current(u,xe,z);return _t.current.set(u,I),I},Ce=(0,Je.useCallback)(u=>{if(qe.current.has(u))return;let B=new Set(qe.current);B.add(u),qe.current=B,at(B);let I=ye.current?.advertisement;I&&(0,xr.advertisedMethodKeys)(I).some(z=>!B.has(z))||ut("payment_method",mo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ut]),oe=(0,Je.useRef)(Ce);oe.current=Ce;let Ze=(0,Je.useRef)(new Map),J=u=>{let B=Ze.current.get(u);if(B)return B;let I=()=>oe.current(u);return Ze.current.set(u,I),I},Ct=ze?(0,ur.jsx)(on,{status:ze.status,errorMessage:ze.message,...(0,xr.setupOverlayLabels)(ze.wording),successNote:null,...ve?{theme:ve}:{}}):null;if(Ee)return(0,ur.jsx)("div",{role:"alert",children:Ee.message});if(!O||m)return(0,ur.jsxs)(ur.Fragment,{children:[Ct,O?null:v]});let{advertisement:Rt,customer:se,futureUse:De,futureUseUnsupported:It}=O,h=(0,_r.resolveBillingApiUrl)(a),U=s===void 0?{}:{telemetry:s},he=Rt.stripe.filter(({method:u})=>!Ye.has(u)),ae=Ye.has("paypal")?null:Rt.paypal,Wt=!!(Rt.card&&_&&fe?.html),Bt=({method:u,publishableKey:B,currency:I})=>(0,ur.jsx)("div",{"data-flopay-payment-method":u,style:{display:"contents"},children:(0,ur.jsx)(Li,{onFailed:qt(u),children:(0,ur.jsx)(Je.Suspense,{fallback:null,children:(0,ur.jsx)(e,{method:u,category:(0,xr.stripeMethodCategory)(u),publishableKey:B,currency:I,...De?{futureUse:De}:{},...It?{futureUseUnsupported:It}:{},sessionId:r,nonce:n,billingApiUrl:h,...U,...ue?{appearance:ue}:{},...pe?{buttonsLayout:pe}:{},...typeof d=="string"?{themeId:d}:{},...it,onFailed:qt(u),onUnavailable:J(u)})})})},u),Ae=he.filter(({method:u})=>(0,xr.stripeMethodCategory)(u)==="wallet"),be=he.filter(({method:u})=>(0,xr.stripeMethodCategory)(u)!=="wallet"),bt=he.length>0||ae!==null;return(0,ur.jsxs)(ur.Fragment,{children:[Ct,bt?(0,ur.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ae.map(Bt),ae?(0,ur.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,ur.jsx)(Li,{onFailed:qt("paypal"),children:(0,ur.jsx)(Je.Suspense,{fallback:null,children:(0,ur.jsx)(t,{clientId:ae.clientId,...ae.environment?{environment:ae.environment}:{},...Rt.currency?{currency:Rt.currency}:{},sessionId:r,nonce:n,billingApiUrl:h,customer:se,...U,...it,onFailed:qt("paypal"),onUnavailable:J("paypal")})})})}):null,be.map(Bt)]}):null,Wt&&bt?(0,ur.jsx)(Ba,{label:"or add a card"}):null,Wt&&_&&fe?.html?(0,ur.jsx)("div",{"data-flopay-payment-method":"card",children:(0,ur.jsx)(wo,{capture:_,html:fe.html,messageToken:fe.messageToken,expectedOrigin:fe.expectedOrigin,verificationRequired:fe.verificationRequired,theme:ee,containerStyle:Fe,onReady:()=>{(0,Ge.invokeMerchantCallback)(()=>ge.current.onReady?.())},onValidation:u=>{(0,Ge.invokeMerchantCallback)(()=>ge.current.onValidation?.(u))},onError:u=>{u&&ut("card",mo(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Kc=require("react/jsx-runtime"),Xu={StripeSetupMethod:Wc,PayPalSetupMethod:Nc};function Hc(e){return(0,Kc.jsx)($c,{...e,branches:Xu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|