@flopay/react 1.16.5 → 1.16.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +8 -8
- package/dist/index.mjs +6 -6
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Ud=Object.create;var yi=Object.defineProperty;var zd=Object.getOwnPropertyDescriptor;var qd=Object.getOwnPropertyNames;var Vd=Object.getPrototypeOf,jd=Object.prototype.hasOwnProperty;var Wd=(e,t)=>{for(var r in t)yi(e,r,{get:t[r],enumerable:!0})},Yl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of qd(t))!jd.call(e,a)&&a!==r&&yi(e,a,{get:()=>t[a],enumerable:!(n=zd(t,a))||n.enumerable});return e};var ws=(e,t,r)=>(r=e!=null?Ud(Vd(e)):{},Yl(t||!e||!e.__esModule?yi(r,"default",{value:e,enumerable:!0}):r,e)),$d=e=>Yl(yi({},"__esModule",{value:!0}),e);var Tp={};Wd(Tp,{DirectPayPalButton:()=>Oa,FloPayAutomaticPaymentButton:()=>nd,FloPayCardSetup:()=>od,FloPayCardSetupError:()=>Qa,FloPayCheckout:()=>Ki,FloPayPaymentMethodSetup:()=>fd,FloPayProvider:()=>La,SplitCardForm:()=>ji,VaultCardFields:()=>_o,dropThirdPartyOnlyError:()=>hd.dropThirdPartyOnlyError,useCheckout:()=>lc,useFloPay:()=>fo,usePayPalFloPay:()=>Pi});module.exports=$d(Tp);var hd=require("@flopay/shared");var Gi=require("@flopay/js"),wr=require("@flopay/shared"),lt=require("react");var er=require("react/jsx-runtime");function Hd(){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 Kd(){return(0,er.jsx)(er.Fragment,{children:"Go back"})}function Gd(){return(0,er.jsx)(er.Fragment,{children:"Secure card checkout"})}function na(e){return e!==void 0&&(e===""||e===null||e===!1)}function oa({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(Hd,{}):e})}function aa({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(Kd,{}):e})}function Ta({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(Gd,{}):e})}var St=require("@flopay/shared"),Un=require("@flopay/shared"),la=require("@flopay/shared"),Bo=require("@flopay/shared");function Rs(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof St.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Yd(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 Xl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,St.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,St.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function Jl(e,t){if(t&&(!(e instanceof St.FloPayError)||e.type==="authentication_error"))return Rs(e);if(!(e instanceof St.FloPayError&&Yd(e))){if(!t&&!(e instanceof St.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,St.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof St.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof St.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function ia(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let d={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,St.isCardHolderNamePlaceholder)(d.firstName,d.lastName);if(!(0,St.isValidEmail)(d.email))return Promise.reject(new St.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[b,P]of Object.entries(d)){if(p&&b.endsWith("Name")||typeof P!="string")continue;let f=P.trim();f&&(m[b]=f)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function Zl(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 ks(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 Ql(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 Es(e,t){return t?{...e,...t}:e}function Cr(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 ec=new WeakMap;function tc(e,t){return typeof e=="object"&&e!==null&&ec.set(e,t?{sessionId:t}:{}),e}function rc(e){return typeof e=="object"&&e!==null?ec.get(e):void 0}function Ro(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function po(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function mo(e){return e?.status==="authorized"||e?.status==="complete"}function ko(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,a=r?.status==="authorized"||n==="AUTHORIZED";return a||r?.status==="completed"||n==="SUCCESS"?{...t,status:a?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function nc(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function fi(e){let t=nc(e);return new St.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function gi(e){return e instanceof St.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function sa(e){return nc(e)?new St.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new St.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new St.FloPayError(St.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function Ma(e,t){return e==="processing"||(0,St.isMoneySettledOutcome)(e,t)}function oc(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function ac(e,t){let r=e;if((0,St.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:d}=await r.retrieveSetupIntent(t);if(d)throw new St.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 St.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var Xd=["apple_pay","google_pay"];function ic(e,t="automatic",r){let n=(0,St.resolveSetupFutureUsage)(r,Xd,"wallet");return{...(0,St.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var Jd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function _s(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:Jd.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Aa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var Po=require("@flopay/js"),me=require("@flopay/shared"),R=ws(require("react"),1);var Is=require("react"),kn=(0,Is.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),zn=(0,Is.createContext)({session:null,loading:!1,error:null});var Ri=require("@flopay/js"),Ue=require("@flopay/shared"),mc=require("@paypal/paypal-js"),E=require("react");var hi=require("@flopay/shared"),qn=require("react"),En=require("@flopay/shared"),yo=require("react/jsx-runtime");function ca(){let[e,t]=(0,qn.useState)(null),r=(0,qn.useRef)(null),n=(0,qn.useRef)(0),a=(0,qn.useCallback)((d,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:d,identity:p}),new Promise(m=>{r.current=m})),[]),s=(0,qn.useCallback)(d=>{let p=r.current;r.current=null,t(null),p?.(d)},[]);return(0,qn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function da({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[d,p]=(0,qn.useState)(e.email?.trim()??""),m=(0,hi.isValidEmail)(d.trim());return(0,yo.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,yo.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,yo.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,yo.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,yo.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,yo.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,yo.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,hi.compactBuyerIdentity)({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var _e=require("@flopay/shared");var sc=require("@flopay/shared"),xa=require("react");function fo(){return(0,xa.useContext)(kn).flopay}function Pi(){return(0,xa.useContext)(kn).paypalFlopay??null}function lc(){return(0,xa.useContext)(zn)}function cc(){return(0,xa.useContext)(kn).billingApiUrl||(0,sc.resolveBillingApiUrl)()}var Zd=require("@flopay/shared"),eo=require("@flopay/shared"),to=require("@flopay/shared");var ua=require("@flopay/shared"),Do=require("react");var vi=require("react"),Oo=typeof window>"u"?vi.useEffect:vi.useLayoutEffect;var Ts=require("@flopay/shared");function pa(e,t){let r=(0,Do.useRef)(e);r.current=e;let n=(0,Do.useRef)(new Set),a=(0,Do.useRef)(t),s=(0,Do.useRef)(t);return Oo(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,Do.useCallback)(d=>{if(s.current!==t)return;let p=(0,ua.projectFloInstrument)(d);if(p){if(ua.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,ua.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Ge=require("@flopay/shared");var dc=require("react"),Fa=(0,dc.createContext)(null);function Ci(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var bi="provider.callback.ignored";function Si(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var Qd=Symbol.for("@flopay/js.telemetry.bridge.v1"),eu=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function tu(){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 ru(e){let t=tu(),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 wi(e){let t=globalThis[eu];return ru(t?.(e)??{})}function br(e){if(e)return e[Qd]}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),d=(0,gr.useRef)(t?.onHandoffObserved),p=(0,gr.useRef)(t?.defersMissingTerminal),m=(0,gr.useRef)(t?.onMissingTerminalDeferred);(0,gr.useEffect)(()=>{s.current=e,d.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let b=(0,gr.useCallback)((y=a.current)=>{y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),P=(0,gr.useCallback)(y=>{b();let K=r.current+1;return r.current=K,n.current=null,a.current={generation:K,method:y,timer:null,yieldedControl:!1},K},[b]),f=(0,gr.useCallback)(y=>{let K=a.current;return y!==void 0&&K?.generation!==y?!1:(b(K),a.current=null,(y===void 0||n.current===y)&&(n.current=null),!0)},[b]),_=(0,gr.useCallback)(y=>{let K=a.current,Z=y??K?.generation??r.current;(y===void 0||K?.generation===y)&&(b(K),a.current=null),n.current=Z},[b]),j=(0,gr.useCallback)(y=>n.current===(y??r.current),[]),W=(0,gr.useCallback)(y=>a.current?.generation===y&&n.current!==y,[]),k=(0,gr.useCallback)(()=>{let y=a.current;y&&(b(y),!y.yieldedControl&&(y.yieldedControl=!0,d.current?.(y.method)))},[b]),T=(0,gr.useCallback)(()=>{let y=a.current;!y?.yieldedControl||document.visibilityState!=="visible"||(b(y),y.timer=setTimeout(()=>{if(y.timer=null,a.current?.generation===y.generation){if(p.current?.(y.method)){m.current?.(y.method,y.generation);return}a.current=null,n.current=y.generation,s.current(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},_e.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[b]);return(0,gr.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?T():k()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",k),window.addEventListener("focus",T),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",k),window.removeEventListener("focus",T),b()}},[b,k,T]),{startAttempt:P,finishAttempt:f,invalidateAttempt:_,isAttemptInvalidated:j,isAttemptCurrent:W,generationRef:r}}var _n=require("react/jsx-runtime"),ki=45,nu=1e3,ou=11e3,uc="paypal_intent_settled",au={width:"100%",minHeight:ki,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"},iu={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 su(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:iu[e.kind]??null}}function pc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,_e.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function lu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function yc({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:d,environment:p,currency:m,isSubscription:b,providerObjectType:P,approvalPresentation:f,onTokenizedBody:_,onComplete:j,onErrorChange:W,onDecline:k,onCancel:T,onTechnicalFailure:y,isProcessing:K=!1,onLoadStateChange:Z,onInitializationStateChange:v,allowAutomaticRetry:ke=!0,onButtonClick:M,runBeforeButtonClick:se,session:be,existingOrderId:Ie,telemetry:ye,telemetryContext:vt,onInstrument:ut,debug:q=!1}){let We=fo(),$e=pa(ut,e),Be=(0,E.useMemo)(()=>{if(We)return null;let O=wi({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:Ue.SDK_VERSION,enabled:ye!==!1});return O.setCheckoutContext(vt??{}),O.beginCheckout(vt??{}),O},[r,We,ye,vt?.checkoutMode,vt?.layout]),we=(0,E.useMemo)(()=>br(We),[We]);(0,E.useEffect)(()=>()=>{Be&&Be.flush().catch(()=>{}).finally(()=>Be.destroy())},[Be]);let X=(0,E.useMemo)(()=>({error:O=>{we?we.error(O):Be?.error(O),$e({class:"technical_error",errorCode:O.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":O.errorCode,requestCategory:O.requestCategory,provider:O.provider})},log:O=>{we?we.log(O):Be?.log(O),$e({class:"lifecycle",name:O.name,provider:O.provider})},performance:O=>{we?we.performance(O):Be?.performance(O)},terminal:O=>{we?we.terminal(O):Be?.terminal(O)},startTiming:()=>we?.now()??Be?.now()??0,elapsed:O=>we?.elapsed(O)??Math.max(0,(Be?.now()??O)-O)}),[$e,we,Be]),G=(0,E.useRef)(null),tt=(0,E.useRef)(0),Ee=(0,E.useRef)(null),qe=(0,E.useRef)(null),te=(0,E.useRef)(null),V=(0,E.useContext)(Fa),Se=(0,E.useRef)(null);Se.current||(Se.current=Ci());let Q=V??Se.current,pt=(0,E.useRef)(null),fe=(0,E.useRef)(!1),[Pe,Oe]=(0,E.useState)(!1),[ce,Ve]=(0,E.useState)(!1),[De,nt]=(0,E.useState)(0),ct=(0,E.useRef)(0),[Y,Rt]=(0,E.useState)(!1),Ht=(0,E.useRef)(!1),Mt=(0,E.useRef)(!1),[Lt,he]=(0,E.useState)(!1),[Me,Ye]=(0,E.useState)(!1),{request:Pt,collect:ft,finish:ze}=ca(),Nt=(0,E.useRef)({sessionId:e,required:(0,Ue.paypalProviderIdentityRequired)(n,be)});Nt.current.sessionId!==e&&(Nt.current={sessionId:e,required:(0,Ue.paypalProviderIdentityRequired)(n,be)});let de=Nt.current.required,kt=(0,E.useMemo)(()=>r.replace(/\/+$/,""),[r]),$=be?.gateways?.paypal?.providerObjectType??P,ge=$??(b?"subscription":"order"),[Ut]=(0,E.useState)(eo.detectPayPalEnvironment),g=be?.gateways?.paypal?.approvalPresentation??f,J=(0,to.resolvePayPalPresentationMode)(Ut,g==="app_switch"?"app_switch":void 0,ge),He=(0,Ue.usesPayPalVaultedChannel)($),L=(0,E.useMemo)(()=>JSON.stringify([kt,d,m,p??"",ge,He,J,e,Ie??""]),[kt,d,m,p,Ie,ge,He,J,e]),mt=(0,E.useRef)(L),u=mt.current!==L,S=(0,E.useRef)(q),I=(0,E.useRef)(null),[H,F]=(0,E.useState)([]),B=(0,E.useCallback)(O=>{S.current&&F(Qe=>[...Qe,`${new Date().toISOString().slice(11,23)} ${O}`])},[]);(0,E.useEffect)(()=>{S.current=q,q&&B("debug:enabled"),I.current?.setEnabled(q)},[B,q]);let Ae=(0,E.useRef)(_),Vr=(0,E.useRef)(j),$t=(0,E.useRef)(W),nr=(0,E.useRef)(k),Te=(0,E.useRef)(T),kr=(0,E.useRef)(y),Ur=(0,E.useRef)(M),Xr=(0,E.useRef)(Z),Or=(0,E.useRef)(v),Kt=(0,E.useRef)(s),jr=(0,E.useRef)(se),an=(0,E.useRef)(be),Er=(0,E.useRef)(n),_r=(0,E.useRef)(a),vn=(0,E.useRef)(t),at=(0,E.useRef)(null),Pr=(0,E.useRef)(new Map),Xt=(0,E.useRef)(new Map),gt=(0,E.useRef)(!1),Et=(0,E.useRef)(e);Et.current=e;let[sn]=(0,E.useState)(Si);(0,E.useEffect)(()=>(gt.current=!0,()=>{gt.current=!1}),[]),(0,E.useEffect)(()=>{Ae.current=_},[_]),(0,E.useEffect)(()=>{Kt.current=s},[s]),(0,E.useEffect)(()=>{Vr.current=j},[j]),(0,E.useEffect)(()=>{$t.current=W},[W]),(0,E.useEffect)(()=>{nr.current=k},[k]),(0,E.useEffect)(()=>{Te.current=T},[T]),(0,E.useEffect)(()=>{kr.current=y},[y]),(0,E.useEffect)(()=>{Ur.current=M},[M]),(0,E.useEffect)(()=>{Xr.current=Z},[Z]),(0,E.useEffect)(()=>{Or.current=v},[v]),(0,E.useEffect)(()=>{jr.current=se},[se]),(0,E.useEffect)(()=>{an.current=be},[be]),(0,E.useEffect)(()=>{Er.current=n},[n]),(0,E.useEffect)(()=>{_r.current=a},[a]),(0,E.useEffect)(()=>{vn.current=t},[t]),(0,E.useEffect)(()=>{ct.current=De},[De]),(0,E.useEffect)(()=>{Y&&pt.current?.focus()},[Y,De]);let zr=(0,E.useCallback)(()=>{window.setTimeout(()=>{pt.current?.focus()},0)},[]),Dr=(0,E.useCallback)(()=>{Oe(!1),nt(O=>O+1)},[]),ln=(0,E.useCallback)(()=>{Rt(!1),(G.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??G.current)?.focus?.()},[]);(0,E.useEffect)(()=>{!Pe||!fe.current||(fe.current=!1,ln())},[ln,Pe,De]);let Jr=(0,E.useCallback)((O,Qe)=>{let ue=Qe?.popupBlocked??(0,_e.isPopupBlockedError)(O);ue&&Q.markBlocked();let ve=(0,_e.buildExternalMethodRecoveryMessage)("PayPal",ue,Ut.inAppBrowser),Gt=kr.current;if(Gt){let zt=ue&&Ut.inAppBrowser?new Ue.FloPayError(ve,"api_error",{code:Qe?.code??"paypal_popup_blocked"}):O;Gt("paypal",zt,Qe);return}if(O instanceof Ue.FloPayError&&O.code==="checkout_processing_timeout"){$t.current?.(O.message);return}$t.current?.(ve)},[Q,Ut.inAppBrowser]),Ir=(0,E.useCallback)(O=>{let Qe=Ee.current,ue=qe.current;Qe===null||!ue||(X.log({...ue,popupCapability:Q.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:O}),X.performance({...ue,popupCapability:Q.current(),stage:"overlay_return",durationMs:X.elapsed(Qe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:O}),Ee.current=null)},[Q,X]),cn=(0,E.useCallback)((O,Qe,ue)=>{let ve=qe.current;Ir("overlay_timeout"),ve&&X.error({...ve,popupCapability:Q.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Jr(Qe,{...ue,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:J,terminalReason:"overlay_timeout"}),Rt(!0),Dr(),zr()},[Ir,zr,Jr,Q,J,Dr,X]),Zr=(0,E.useCallback)(()=>{Q.markAvailable();let O=qe.current;O&&(te.current=O.attempt,X.log({...O,popupCapability:Q.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[Q,X]),Lr=(0,E.useCallback)(()=>!0,[]),or=(0,E.useCallback)(()=>{let O=qe.current;if(!O)return;let Qe=Ee.current;X.performance({...O,popupCapability:Q.current(),stage:"overlay_return",durationMs:Qe===null?0:X.elapsed(Qe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[Q,X]),{finishAttempt:vr,generationRef:ur,invalidateAttempt:pr,isAttemptCurrent:Tr,isAttemptInvalidated:Mr,startAttempt:Qr}=Ba(cn,{onHandoffObserved:Zr,defersMissingTerminal:Lr,onMissingTerminalDeferred:or}),mr=(0,E.useCallback)(()=>(Rt(!1),Qr("paypal")),[Qr]),tr=(0,E.useCallback)(O=>{pr(O?.generation),O?.showRetry&&Rt(!0),O?.remount&&Dr(),O?.focus!==!1&&zr()},[zr,pr,Dr]),Nr=O=>{let Qe=at.current;return Qe&&Xt.current.set(O,Qe),O};(0,E.useEffect)(()=>{mt.current!==L&&(mt.current=L,Ht.current=!1,Mt.current=!1,Oe(!1),Ve(!1),he(!1),Or.current?.("loading"))},[L]),(0,E.useEffect)(()=>{(0,Ge.invokeMerchantCallback)(()=>Xr.current?.(Pe&&!Lt))},[Pe,Lt]);let Ze=(0,Ue.normalizeGatewayEnvironment)(p);(0,E.useEffect)(()=>{let O={attempt:ur.current+1,inAppBrowser:Ut.inAppBrowser,appFamily:Ut.appFamily,popupCapability:Q.current(),presentationMode:J},Qe=()=>({...qe.current??O,popupCapability:Q.current()}),ue={error:h=>X.error({...h,...Qe()}),log:h=>X.log({...h,...Qe()}),performance:h=>X.performance({...h,...Qe()}),terminal:h=>X.terminal({...h,...Qe()}),startTiming:X.startTiming,elapsed:X.elapsed},ve=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",Gt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(B(`mount clientId=${ve} env=${p??"(unset)"}\u2192${Ze??"live"} ccy=${m} sub=${b}`),B(`ua=${Gt.slice(0,80)}${Gt.length>80?"\u2026":""}`),!d){B("FAIL: clientId empty \u2014 gateway misconfigured"),he(!0),ue.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(!G.current){B("FAIL: containerRef not attached");return}tt.current=ue.startTiming(),ue.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let zt=!1,xt=!1,z=()=>zt||xt,bn=h=>{let w=gt.current,N=w?h:"torn_down";w&&B(`onError ignored reason=${N}`),sn.take(Et.current)&&ue.log({name:bi,stage:"provider_ready",reason:N,provider:"paypal",paymentMethodCategory:"paypal"})},jo=()=>Et.current===e?"stale_attempt":"session_changed",Io=He?ge:void 0,Sn,xn=!1,dn=()=>{Sn=(0,Ue.generateIdempotencyKey)(),Sn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),xn=!0},en=null,ar=!1,Fn=null,un=!1,Bn=()=>{!Fn||un||(un=!0,Fn.close().catch(()=>{}))},Ft=!1,tn=!1,pn=G.current,io=null,mn=null,On=[],so=null,$n=!1,Hn=!1,Kn=null,lo=h=>{if(!h||typeof h.getBoundingClientRect!="function")return"(no rect)";let w=h.getBoundingClientRect();return`${Math.round(w.width)}\xD7${Math.round(w.height)}`},Wo=h=>{if(!h)return"(empty)";try{let w=new URL(h,typeof window>"u"?"https://localhost":window.location.href),N=w.pathname.toLowerCase();return N.includes("checkcaptcha")||N.includes("captcha")?`CAPTCHA(${w.host}${N})`:N.includes("risk")||N.includes("challenge")?`RISK(${w.host}${N})`:N.includes("smart/buttons")?`smart-buttons(${w.host})`:`${w.host}${N}`.slice(0,100)}catch{return h.slice(0,80)}},Gn=h=>{let w=h.getAttribute("src"),N=h.getAttribute("srcdoc"),ie=h.getAttribute("name"),oe=h.getAttribute("sandbox"),ae=[];return w&&ae.push(`src=${Wo(w)}`),N&&ae.push(`srcdoc[${N.length}ch]`),!w&&!N&&ae.push("src=(empty) srcdoc=(empty)"),ie&&ae.push(`name=${ie.slice(0,40)}`),oe!==null&&ae.push(`sandbox="${oe.slice(0,40)}"`),ae.join(" ")},co=h=>{if(!(h instanceof HTMLIFrameElement))return"";try{let w=h.contentDocument;if(!w)return"cd=null";let N=w.body?.children.length??0,ie=w.body?.innerHTML.length??0,oe=w.head?.innerHTML.length??0;return`cd=same-origin readyState=${w.readyState} body[${N}children,${ie}ch] head[${oe}ch]`}catch(w){return`cd=cross-origin(${w.message.slice(0,30)})`}},Yn=[],qt=h=>{if(z())return;let w=h.message??String(h.error??"(no message)");w&&(w.toLowerCase().includes("paypal")||w.toLowerCase().includes("zoid")||w.toLowerCase().includes("postrobot")||w.toLowerCase().includes("storage"))&&(B(`window:error ${w.slice(0,140)}`),Yn.push(w))},Xn=h=>{if(z())return;let w=h.reason instanceof Error?h.reason.message:String(h.reason??"(no reason)");w&&(w.toLowerCase().includes("paypal")||w.toLowerCase().includes("zoid")||w.toLowerCase().includes("postrobot")||w.toLowerCase().includes("storage"))&&(B(`window:rejection ${w.slice(0,140)}`),Yn.push(w))},yn={value:0},wn=()=>{io?.disconnect(),io=null,mn?.disconnect(),mn=null;for(let h of On.splice(0))clearTimeout(h);Hn=!1,$n&&typeof window<"u"&&(window.removeEventListener("error",qt),window.removeEventListener("unhandledrejection",Xn)),$n=!1},fn=()=>{if(!($n||z()||Ft)){if($n=!0,Yn.length=0,yn.value=0,typeof window<"u"&&(window.addEventListener("error",qt),window.addEventListener("unhandledrejection",Xn)),typeof PerformanceObserver<"u")try{mn=new PerformanceObserver(h=>{if(!z())for(let w of h.getEntries()){if(!w.name.toLowerCase().includes("paypal"))continue;yn.value+=1;let N=Math.round(w.duration);B(`net ${N}ms ${w.name.slice(0,90)}`)}}),mn.observe({type:"resource",buffered:!0})}catch{}Kn?.()}},dt=()=>{so&&(clearTimeout(so),so=null)},Ar=()=>{wn(),dt()},Jt={setEnabled:h=>{h?fn():wn()}};I.current=Jt,S.current&&fn();let A=Ue.isPayPalTeardownMessage,D=h=>{if(z()||A(h))return;let w=(0,Bo.applyFriendlyMessageOverride)(h)??h;(0,Ge.invokeMerchantCallback)(()=>$t.current?.(w))},ne=(h,w)=>{if(zt||ar)return;ar=!0,xt=!0,Ar(),Bn();let N=su({kind:h,generationActive:!0,automaticRetryAllowed:ke,automaticRetryUsed:Ht.current});if(N.action==="retry"){Ht.current=!0,Oe(!1),Ye(!1),Ve(!0),Or.current?.("retrying"),en=setTimeout(()=>{zt||nt(ie=>ie+1)},nu);return}if(Oe(!1),Ye(!1),Ve(!1),he(!0),N.action!=="ignore"){if(Or.current?.("exhausted"),N.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",w);return}if(N.report){let ie=(0,_e.classifyExternalMethodFailure)({code:pc(h,w),message:w},{inAppBrowser:Ut.inAppBrowser,handoffObserved:!1});ie.popupBlocked&&Q.markBlocked(),ue.error({errorCode:ie.popupBlocked?ie.errorCode:N.report.errorCode,stage:N.report.stage,operationOutcome:N.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:ie.terminalReason})}Mt.current||(Mt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",pc(h,w)))}};he(!1);let Re=async(h,w=at.current)=>{if(z())return;let N=w?.sessionId??e;if(Ae.current){await Ae.current(h,{sessionId:N,accountPatch:w?.accountPatch,nonce:w?.nonce});return}let ie=ue.startTiming();ue.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let oe=()=>{ue.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ue.performance({stage:"processing",durationMs:ue.elapsed(ie),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ae=(0,Ue.buildPayPalProcessPaymentRequest)({body:h,sessionId:N,nonce:w?.nonce??vn.current,accountPatch:w?.accountPatch,session:an.current,email:Er.current}),Ot=await new Ri.PaymentAPI(kt,{telemetry:!1}).processPayment(ae.userId,ae.params);if(Ot.ok){if(xt||zt&>.current)return;oe(),ue.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ge.invokeMerchantCallback)(()=>Vr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(z())return;let st=await Ot.json().catch(()=>null),Ct=(0,Ue.describePayPalProcessFailure)(st),It=Ct.message;oe(),Ot.status===400&&(typeof st?.declineCode=="string"||!Array.isArray(st?.fields))?ue.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Ot.status===400||Ot.status===422?ue.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):ue.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:lu(Ot.status),failureCategory:Ot.status>=500?"server_error":void 0}),D(It),(0,Ge.invokeMerchantCallback)(()=>nr.current?.(Cr("paypal",It,{code:Ct.code,declineCode:Ct.declineCode})));return}catch(ae){if(z())return;oe(),ue.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Bt=(0,Ue.friendlyPayPalFailureMessage)(ae instanceof Error?ae.message:void 0);D(Bt),(0,Ge.invokeMerchantCallback)(()=>nr.current?.(Cr("paypal",Bt)));return}},_t=()=>new Ue.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Zt=h=>z()?Promise.reject(_t()):Promise.resolve(h),xe=async h=>{if(h.ok){ue.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ge.invokeMerchantCallback)(()=>Vr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let w=await h.json().catch(()=>null),N=(0,Ue.describePayPalProcessFailure)(w);ue.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ge.invokeMerchantCallback)(()=>nr.current?.(Cr("paypal",N.message,{code:N.code,declineCode:N.declineCode})))},it=()=>{let h=at.current;Ir("approved"),h&&(Pr.current.delete(h.surfaceKey),vr(h.generation)),at.current=null},re=async h=>{if(z())throw _t();xn||dn();let w=at.current,N=w?.sessionId??e,ie=w?.nonce??vn.current;ue.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let oe;try{oe=await new Ri.PaymentAPI(kt,{telemetry:!1}).createSessionIntent(N,ie??"",(0,Ue.buildPayPalSessionIntentRequest)(Io),{idempotencyKey:Sn})}catch(ae){throw ue.error({...(0,Ue.classifyTelemetryFailure)(ae,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ae}if(z())throw _t();if((0,Ue.isSettledSessionIntent)(oe))throw await xe(oe.response),it(),new Ue.FloPayError("PayPal checkout already settled.","api_error",{code:uc});if(oe.provider!=="paypal"||oe.providerObjectType!==ge)throw new Error(h);return ue.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),oe.providerObjectId},et=(h,w)=>{let N=w?.nonce??vn.current;if(!N)return;let ie=w?.sessionId??e,oe=(0,Ue.resolvePayPalDeclineReason)(h);new Ri.PaymentAPI(kt,{telemetry:!1}).reportSessionIntentDecline(ie,N,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:oe}).catch(()=>{})},pe=De;B("loadScript:scheduled (deferred 1 tick)");let yt=null,le=setTimeout(()=>{if(zt){B("loadScript:skipped (cancelled before defer ran)");return}B("loadScript:start");let h=Ze==="live"?"production":Ze,w={};ge==="subscription"?w={intent:"subscription",vault:!0}:ge==="order"&&(w={intent:"capture"}),yt=(0,mc.loadScript)({clientId:d,currency:m,...w,...h?{environment:h}:{},...h==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let N=!1;yt.then(ie=>{if(N=!0,B(`loadScript:resolved inactive=${z()} ns=${!!ie} buttons=${!!ie?.Buttons}`),z())return;if(!ie?.Buttons){B("FAIL: namespace missing Buttons factory"),ne("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}ue.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),ue.performance({stage:"provider_ready",durationMs:ue.elapsed(tt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ue.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let oe=async(Xe,Ke)=>{if(z()||ct.current!==pe)return;let Le=Xe.vaultSetupToken??Xe.subscriptionID??Xe.orderID??"",Vt=Le?Xt.current.get(Le):Pr.current.get(pe);if(!(!Vt||!Tr(Vt.generation))&&vr(Vt.generation)){Xt.current.delete(Le),Pr.current.delete(Vt.surfaceKey),Ir("approved");try{if(Ye(!0),(0,Ge.invokeMerchantCallback)(()=>$t.current?.(null)),!Le)throw new Ue.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let wt=(0,Ue.resolvePayPalApprovalIdentity)({accountPatch:Vt.accountPatch,email:Er.current,billingName:_r.current,session:an.current});if((0,Ue.needsPayPalPayerDetails)(wt))try{wt=(0,Ue.mergePayPalPayerIdentity)(wt,await Ke?.order?.get?.())}catch{}if((Kt.current||de)&&!(0,Ue.isValidEmail)(wt.email)){let Qt=await ft("PayPal",wt);if(!Qt)return;wt=Qt}(0,Ue.isValidEmail)(wt.email)&&(Vt.accountPatch=(0,En.compactBuyerIdentity)({...Vt.accountPatch,...wt}),await Kt.current?.(wt));let Wr=(0,Ue.buildPayPalTokenizedBody)(Le,Io);await Re(Wr,Vt)}catch(wt){D(wt instanceof Error?wt.message:"PayPal capture failed.")}finally{z()||Ye(!1)}}},ae=Xe=>{let Ke=Ie?()=>Zt(Ie):()=>re(Xe);return async()=>Nr(await Ke())},Bt=ie.Buttons({style:{layout:"horizontal",height:ki,tagline:!1},...J==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Xe,Ke)=>{if(z()){await Ke.reject();return}dn();let Le=jr.current,Vt={};if(Le)try{let Qt=await Le("paypal");if(z()){await Ke.reject();return}if(!Qt.proceed){at.current=null,Pr.current.delete(pe),await Ke.reject();return}Vt={sessionId:Qt.sessionId,accountPatch:Qt.accountPatch,nonce:Qt.nonce}}catch(Qt){B(`onClick:runBeforeButtonClick rejected msg=${(Qt instanceof Error?Qt.message:String(Qt)).slice(0,120)}`),at.current=null,Pr.current.delete(pe),await Ke.reject();return}(0,Ge.invokeMerchantCallback)(()=>Ur.current?.("paypal"));let wt=mr(),Wr={generation:wt,surfaceKey:pe,...Vt};at.current=Wr,Pr.current.set(pe,Wr),qe.current={...O,attempt:wt},await Ke.resolve(),ue.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ue.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Ee.current=ue.startTiming()},createOrder:ge==="order"?ae("Failed to create PayPal order."):void 0,createSubscription:ge==="subscription"?ae("Failed to create PayPal subscription."):void 0,createVaultSetupToken:ge==="setup_token"?async()=>Nr(await re("Failed to create PayPal setup token.")):void 0,onApprove:oe,onCancel:()=>{if(z())return;let Xe=Pr.current.get(pe)??at.current,Ke=Xe&&Tr(Xe.generation)?(0,Ue.buildPayPalCancelEvent)(Xe.sessionId??e,Io):null;Xe&&Pr.current.delete(Xe.surfaceKey),at.current=null,Ir("cancelled"),ue.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),fe.current=!0,tr({generation:Xe?.generation,remount:!0,focus:!1}),Ke&&(0,Ge.invokeMerchantCallback)(()=>Te.current?.(Ke))},onError:Xe=>{if(Xe instanceof Ue.FloPayError&&Xe.code===uc)return;let Ke=Xe instanceof Error?Xe.message:"PayPal failed to render.";if(z()||ct.current!==pe){A(Ke)||bn(jo());return}if(Ft){let Le=Pr.current.get(pe)??at.current;if(!Le||!Tr(Le.generation)){if(A(Ke)){!Le&&!Mr()&&vr();return}bn(Le||Mr()?"stale_attempt":"no_current_attempt");return}if(B(`onError rendered=${Ft} msg=${Ke.slice(0,120)}`),A(Ke)){vr(Le.generation);return}let{errorCode:Vt,popupBlocked:wt,providerDeclined:Wr,terminalReason:Qt}=(0,_e.classifyExternalMethodFailure)(Xe,{inAppBrowser:Ut.inAppBrowser,handoffObserved:te.current===Le.generation});if(wt&&Q.markBlocked(),Ir(Qt),Wr){ue.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Qt}),et(Xe,Le),(0,Ge.invokeMerchantCallback)(()=>nr.current?.(Cr("paypal",Ke))),Pr.current.delete(Le.surfaceKey),at.current=null,vr(Le.generation);return}ue.error({errorCode:Vt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Qt}),Pr.current.delete(Le.surfaceKey),at.current=null,tr({generation:Le.generation,remount:!0,showRetry:!0,focus:!0}),Jr(Xe,{code:"paypal_runtime_failed",popupBlocked:wt,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:J,terminalReason:Qt});return}B(`onError rendered=${Ft} msg=${Ke.slice(0,120)}`),ne(A(Ke)?"teardown":"pre_ready_callback",Ke)}}),Ot=Bt.isEligible();if(B(`isEligible=${Ot}`),ue.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Ot){Oe(!1),ne("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}tn=!0,Fn=Bt,Kn=()=>{if(!$n||Hn||z()||Ft)return;Hn=!0,B(`container:dims ${lo(pn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(io=new MutationObserver(Ke=>{if(!z()){for(let Le of Ke)if(Le.type==="childList")Le.addedNodes.forEach(Vt=>{if(!(Vt instanceof Element))return;let wt=Vt.tagName.toLowerCase(),Wr=(Vt.getAttribute("title")??"").slice(0,40),Qt=wt==="iframe"?` ${Gn(Vt)}`:"";B(`child+ ${wt}${Wr?` title="${Wr}"`:""}${Qt} dims=${lo(Vt)}`)});else if(Le.type==="attributes"&&Le.target instanceof Element){let Vt=Le.target;if(Vt.tagName.toLowerCase()!=="iframe")continue;let wt=Le.attributeName;(wt==="src"||wt==="srcdoc")&&B(`attr~ iframe ${wt}=${wt==="srcdoc"?`[${(Vt.getAttribute("srcdoc")??"").length}ch]`:Wo(Vt.getAttribute("src"))} dims=${lo(Vt)}`)}}}),io.observe(pn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Xe=Ke=>{if(z()||Ft)return;let Le=pn.querySelectorAll("iframe"),Vt=typeof document<"u"&&"hasStorageAccess"in document;B(`watchdog:${Ke} container=${lo(pn)} children=${pn.childElementCount} iframes=${Le.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Vt} paypalNetRequests=${yn.value}`),Le.forEach((wt,Wr)=>{let Qt=(wt.getAttribute("title")??"").slice(0,40);B(` iframe[${Wr}] ${lo(wt)}${Qt?` title="${Qt}"`:""} ${Gn(wt)}`);let $r=co(wt);$r&&B(` ${$r}`)}),Yn.length===0&&B(" (no PayPal/zoid window errors captured)")};On.push(setTimeout(()=>Xe("3s"),3e3)),On.push(setTimeout(()=>Xe("8s"),8e3)),On.push(setTimeout(()=>Xe("15s"),15e3))},Kn(),B("render:start");let Ct=ue.startTiming();so=setTimeout(()=>{z()||Ft||(B("watchdog:11s retryable render timeout"),ne("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},ou);let It=Bt.render(pn);(async()=>{try{if(await It,B(`render:resolved inactive=${z()}`),Ar(),z()){Bn();return}Ft=!0,Oe(!0),Ve(!1),Or.current?.("ready"),ue.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),ue.performance({stage:"checkout_render",durationMs:ue.elapsed(Ct),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Xe){let Ke=Xe instanceof Error?Xe.message:"PayPal failed to render.";B(`render:rejected msg=${Ke.slice(0,120)}`),Ar(),ne(A(Ke)?"teardown":"render_rejected",Ke)}})()}).catch(ie=>{let oe=ie instanceof Error?ie.message:"PayPal operation failed.";B(`provider:failed msg=${oe.slice(0,120)}`);let ae="script_rejected";N&&A(oe)?ae="teardown":N&&tn&&(ae="render_rejected"),ne(ae,oe)})},0);return()=>{zt=!0,clearTimeout(le),en&&clearTimeout(en),Ar(),I.current===Jt&&(I.current=null),Bn(),Ee.current=null,qe.current=null}},[ke,kt,d,m,p,ge,J,He,e,Ie,De,X,ft,de,B,Ir]);let Cn=q?(0,_n.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Lt?"#fef2f2":"#f3f4f6",border:`1px solid ${Lt?"#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=${Lt})`,H.length===0?`
|
|
1
|
+
"use strict";var Ud=Object.create;var yi=Object.defineProperty;var zd=Object.getOwnPropertyDescriptor;var qd=Object.getOwnPropertyNames;var jd=Object.getPrototypeOf,Vd=Object.prototype.hasOwnProperty;var Wd=(e,t)=>{for(var r in t)yi(e,r,{get:t[r],enumerable:!0})},Yl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of qd(t))!Vd.call(e,a)&&a!==r&&yi(e,a,{get:()=>t[a],enumerable:!(n=zd(t,a))||n.enumerable});return e};var ws=(e,t,r)=>(r=e!=null?Ud(jd(e)):{},Yl(t||!e||!e.__esModule?yi(r,"default",{value:e,enumerable:!0}):r,e)),$d=e=>Yl(yi({},"__esModule",{value:!0}),e);var Mp={};Wd(Mp,{DirectPayPalButton:()=>Oa,FloPayAutomaticPaymentButton:()=>nd,FloPayCardSetup:()=>od,FloPayCardSetupError:()=>Qa,FloPayCheckout:()=>Ki,FloPayPaymentMethodSetup:()=>fd,FloPayProvider:()=>La,SplitCardForm:()=>Vi,VaultCardFields:()=>_o,dropThirdPartyOnlyError:()=>hd.dropThirdPartyOnlyError,useCheckout:()=>lc,useFloPay:()=>fo,usePayPalFloPay:()=>Pi});module.exports=$d(Mp);var hd=require("@flopay/shared");var Gi=require("@flopay/js"),wr=require("@flopay/shared"),lt=require("react");var er=require("react/jsx-runtime");function Hd(){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 Kd(){return(0,er.jsx)(er.Fragment,{children:"Go back"})}function Gd(){return(0,er.jsx)(er.Fragment,{children:"Secure card checkout"})}function na(e){return e!==void 0&&(e===""||e===null||e===!1)}function oa({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(Hd,{}):e})}function aa({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(Kd,{}):e})}function Ta({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(Gd,{}):e})}var St=require("@flopay/shared"),Un=require("@flopay/shared"),la=require("@flopay/shared"),Bo=require("@flopay/shared");function Rs(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof St.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Yd(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 Xl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,St.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,St.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function Jl(e,t){if(t&&(!(e instanceof St.FloPayError)||e.type==="authentication_error"))return Rs(e);if(!(e instanceof St.FloPayError&&Yd(e))){if(!t&&!(e instanceof St.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,St.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof St.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof St.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function ia(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let d={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,St.isCardHolderNamePlaceholder)(d.firstName,d.lastName);if(!(0,St.isValidEmail)(d.email))return Promise.reject(new St.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[b,P]of Object.entries(d)){if(p&&b.endsWith("Name")||typeof P!="string")continue;let g=P.trim();g&&(m[b]=g)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function Zl(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 ks(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 Ql(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 Es(e,t){return t?{...e,...t}:e}function Cr(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 ec=new WeakMap;function tc(e,t){return typeof e=="object"&&e!==null&&ec.set(e,t?{sessionId:t}:{}),e}function rc(e){return typeof e=="object"&&e!==null?ec.get(e):void 0}function Ro(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function po(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function mo(e){return e?.status==="authorized"||e?.status==="complete"}function ko(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,a=r?.status==="authorized"||n==="AUTHORIZED";return a||r?.status==="completed"||n==="SUCCESS"?{...t,status:a?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function nc(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function fi(e){let t=nc(e);return new St.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function gi(e){return e instanceof St.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function sa(e){return nc(e)?new St.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new St.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new St.FloPayError(St.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function Ma(e,t){return e==="processing"||(0,St.isMoneySettledOutcome)(e,t)}function oc(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function ac(e,t){let r=e;if((0,St.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:d}=await r.retrieveSetupIntent(t);if(d)throw new St.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 St.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var Xd=["apple_pay","google_pay"];function ic(e,t="automatic",r){let n=(0,St.resolveSetupFutureUsage)(r,Xd,"wallet");return{...(0,St.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var Jd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function _s(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:Jd.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Aa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var Po=require("@flopay/js"),me=require("@flopay/shared"),R=ws(require("react"),1);var Is=require("react"),kn=(0,Is.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),zn=(0,Is.createContext)({session:null,loading:!1,error:null});var Ri=require("@flopay/js"),Ue=require("@flopay/shared"),mc=require("@paypal/paypal-js"),E=require("react");var hi=require("@flopay/shared"),qn=require("react"),En=require("@flopay/shared"),yo=require("react/jsx-runtime");function ca(){let[e,t]=(0,qn.useState)(null),r=(0,qn.useRef)(null),n=(0,qn.useRef)(0),a=(0,qn.useCallback)((d,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:d,identity:p}),new Promise(m=>{r.current=m})),[]),s=(0,qn.useCallback)(d=>{let p=r.current;r.current=null,t(null),p?.(d)},[]);return(0,qn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function da({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[d,p]=(0,qn.useState)(e.email?.trim()??""),m=(0,hi.isValidEmail)(d.trim());return(0,yo.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,yo.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,yo.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,yo.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,yo.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,yo.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,yo.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,hi.compactBuyerIdentity)({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var _e=require("@flopay/shared");var sc=require("@flopay/shared"),xa=require("react");function fo(){return(0,xa.useContext)(kn).flopay}function Pi(){return(0,xa.useContext)(kn).paypalFlopay??null}function lc(){return(0,xa.useContext)(zn)}function cc(){return(0,xa.useContext)(kn).billingApiUrl||(0,sc.resolveBillingApiUrl)()}var Zd=require("@flopay/shared"),eo=require("@flopay/shared"),to=require("@flopay/shared");var ua=require("@flopay/shared"),Do=require("react");var vi=require("react"),Oo=typeof window>"u"?vi.useEffect:vi.useLayoutEffect;var Ts=require("@flopay/shared");function pa(e,t){let r=(0,Do.useRef)(e);r.current=e;let n=(0,Do.useRef)(new Set),a=(0,Do.useRef)(t),s=(0,Do.useRef)(t);return Oo(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,Do.useCallback)(d=>{if(s.current!==t)return;let p=(0,ua.projectFloInstrument)(d);if(p){if(ua.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,ua.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Ge=require("@flopay/shared");var dc=require("react"),Fa=(0,dc.createContext)(null);function Ci(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var bi="provider.callback.ignored";function Si(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var Qd=Symbol.for("@flopay/js.telemetry.bridge.v1"),eu=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function tu(){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 ru(e){let t=tu(),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 wi(e){let t=globalThis[eu];return ru(t?.(e)??{})}function br(e){if(e)return e[Qd]}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),d=(0,gr.useRef)(t?.onHandoffObserved),p=(0,gr.useRef)(t?.defersMissingTerminal),m=(0,gr.useRef)(t?.onMissingTerminalDeferred);(0,gr.useEffect)(()=>{s.current=e,d.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let b=(0,gr.useCallback)((y=a.current)=>{y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),P=(0,gr.useCallback)(y=>{b();let K=r.current+1;return r.current=K,n.current=null,a.current={generation:K,method:y,timer:null,yieldedControl:!1},K},[b]),g=(0,gr.useCallback)(y=>{let K=a.current;return y!==void 0&&K?.generation!==y?!1:(b(K),a.current=null,(y===void 0||n.current===y)&&(n.current=null),!0)},[b]),_=(0,gr.useCallback)(y=>{let K=a.current,Z=y??K?.generation??r.current;(y===void 0||K?.generation===y)&&(b(K),a.current=null),n.current=Z},[b]),V=(0,gr.useCallback)(y=>n.current===(y??r.current),[]),W=(0,gr.useCallback)(y=>a.current?.generation===y&&n.current!==y,[]),k=(0,gr.useCallback)(()=>{let y=a.current;y&&(b(y),!y.yieldedControl&&(y.yieldedControl=!0,d.current?.(y.method)))},[b]),T=(0,gr.useCallback)(()=>{let y=a.current;!y?.yieldedControl||document.visibilityState!=="visible"||(b(y),y.timer=setTimeout(()=>{if(y.timer=null,a.current?.generation===y.generation){if(p.current?.(y.method)){m.current?.(y.method,y.generation);return}a.current=null,n.current=y.generation,s.current(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},_e.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[b]);return(0,gr.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?T():k()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",k),window.addEventListener("focus",T),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",k),window.removeEventListener("focus",T),b()}},[b,k,T]),{startAttempt:P,finishAttempt:g,invalidateAttempt:_,isAttemptInvalidated:V,isAttemptCurrent:W,generationRef:r}}var _n=require("react/jsx-runtime"),ki=45,nu=1e3,ou=11e3,uc="paypal_intent_settled",au={width:"100%",minHeight:ki,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"},iu={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 su(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:iu[e.kind]??null}}function pc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,_e.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function lu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function yc({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:d,environment:p,currency:m,isSubscription:b,providerObjectType:P,approvalPresentation:g,onTokenizedBody:_,onComplete:V,onErrorChange:W,onDecline:k,onCancel:T,onTechnicalFailure:y,isProcessing:K=!1,onLoadStateChange:Z,onInitializationStateChange:v,allowAutomaticRetry:ke=!0,onButtonClick:M,runBeforeButtonClick:se,session:Se,existingOrderId:Ie,telemetry:ye,telemetryContext:vt,onInstrument:ut,debug:z=!1}){let We=fo(),$e=pa(ut,e),Be=(0,E.useMemo)(()=>{if(We)return null;let O=wi({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:Ue.SDK_VERSION,enabled:ye!==!1});return O.setCheckoutContext(vt??{}),O.beginCheckout(vt??{}),O},[r,We,ye,vt?.checkoutMode,vt?.layout]),Re=(0,E.useMemo)(()=>br(We),[We]);(0,E.useEffect)(()=>()=>{Be&&Be.flush().catch(()=>{}).finally(()=>Be.destroy())},[Be]);let X=(0,E.useMemo)(()=>({error:O=>{Re?Re.error(O):Be?.error(O),$e({class:"technical_error",errorCode:O.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":O.errorCode,requestCategory:O.requestCategory,provider:O.provider})},log:O=>{Re?Re.log(O):Be?.log(O),$e({class:"lifecycle",name:O.name,provider:O.provider})},performance:O=>{Re?Re.performance(O):Be?.performance(O)},terminal:O=>{Re?Re.terminal(O):Be?.terminal(O)},startTiming:()=>Re?.now()??Be?.now()??0,elapsed:O=>Re?.elapsed(O)??Math.max(0,(Be?.now()??O)-O)}),[$e,Re,Be]),G=(0,E.useRef)(null),tt=(0,E.useRef)(0),Ee=(0,E.useRef)(null),qe=(0,E.useRef)(null),re=(0,E.useRef)(null),q=(0,E.useContext)(Fa),we=(0,E.useRef)(null);we.current||(we.current=Ci());let Q=q??we.current,pt=(0,E.useRef)(null),fe=(0,E.useRef)(!1),[Pe,Oe]=(0,E.useState)(!1),[ce,je]=(0,E.useState)(!1),[De,nt]=(0,E.useState)(0),ct=(0,E.useRef)(0),[Y,Rt]=(0,E.useState)(!1),Ht=(0,E.useRef)(!1),Mt=(0,E.useRef)(!1),[Lt,he]=(0,E.useState)(!1),[Me,Ye]=(0,E.useState)(!1),{request:Pt,collect:ft,finish:ze}=ca(),Nt=(0,E.useRef)({sessionId:e,required:(0,Ue.paypalProviderIdentityRequired)(n,Se)});Nt.current.sessionId!==e&&(Nt.current={sessionId:e,required:(0,Ue.paypalProviderIdentityRequired)(n,Se)});let de=Nt.current.required,kt=(0,E.useMemo)(()=>r.replace(/\/+$/,""),[r]),$=Se?.gateways?.paypal?.providerObjectType??P,ge=$??(b?"subscription":"order"),[Ut]=(0,E.useState)(eo.detectPayPalEnvironment),h=Se?.gateways?.paypal?.approvalPresentation??g,J=(0,to.resolvePayPalPresentationMode)(Ut,h==="app_switch"?"app_switch":void 0,ge),He=(0,Ue.usesPayPalVaultedChannel)($),L=(0,E.useMemo)(()=>JSON.stringify([kt,d,m,p??"",ge,He,J,e,Ie??""]),[kt,d,m,p,Ie,ge,He,J,e]),mt=(0,E.useRef)(L),u=mt.current!==L,S=(0,E.useRef)(z),I=(0,E.useRef)(null),[H,F]=(0,E.useState)([]),B=(0,E.useCallback)(O=>{S.current&&F(Qe=>[...Qe,`${new Date().toISOString().slice(11,23)} ${O}`])},[]);(0,E.useEffect)(()=>{S.current=z,z&&B("debug:enabled"),I.current?.setEnabled(z)},[B,z]);let Ae=(0,E.useRef)(_),jr=(0,E.useRef)(V),$t=(0,E.useRef)(W),nr=(0,E.useRef)(k),Te=(0,E.useRef)(T),kr=(0,E.useRef)(y),Ur=(0,E.useRef)(M),Xr=(0,E.useRef)(Z),Or=(0,E.useRef)(v),Kt=(0,E.useRef)(s),Vr=(0,E.useRef)(se),an=(0,E.useRef)(Se),Er=(0,E.useRef)(n),_r=(0,E.useRef)(a),vn=(0,E.useRef)(t),at=(0,E.useRef)(null),Pr=(0,E.useRef)(new Map),Xt=(0,E.useRef)(new Map),gt=(0,E.useRef)(!1),Et=(0,E.useRef)(e);Et.current=e;let[sn]=(0,E.useState)(Si);(0,E.useEffect)(()=>(gt.current=!0,()=>{gt.current=!1}),[]),(0,E.useEffect)(()=>{Ae.current=_},[_]),(0,E.useEffect)(()=>{Kt.current=s},[s]),(0,E.useEffect)(()=>{jr.current=V},[V]),(0,E.useEffect)(()=>{$t.current=W},[W]),(0,E.useEffect)(()=>{nr.current=k},[k]),(0,E.useEffect)(()=>{Te.current=T},[T]),(0,E.useEffect)(()=>{kr.current=y},[y]),(0,E.useEffect)(()=>{Ur.current=M},[M]),(0,E.useEffect)(()=>{Xr.current=Z},[Z]),(0,E.useEffect)(()=>{Or.current=v},[v]),(0,E.useEffect)(()=>{Vr.current=se},[se]),(0,E.useEffect)(()=>{an.current=Se},[Se]),(0,E.useEffect)(()=>{Er.current=n},[n]),(0,E.useEffect)(()=>{_r.current=a},[a]),(0,E.useEffect)(()=>{vn.current=t},[t]),(0,E.useEffect)(()=>{ct.current=De},[De]),(0,E.useEffect)(()=>{Y&&pt.current?.focus()},[Y,De]);let zr=(0,E.useCallback)(()=>{window.setTimeout(()=>{pt.current?.focus()},0)},[]),Dr=(0,E.useCallback)(()=>{Oe(!1),nt(O=>O+1)},[]),ln=(0,E.useCallback)(()=>{Rt(!1),(G.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??G.current)?.focus?.()},[]);(0,E.useEffect)(()=>{!Pe||!fe.current||(fe.current=!1,ln())},[ln,Pe,De]);let Jr=(0,E.useCallback)((O,Qe)=>{let ue=Qe?.popupBlocked??(0,_e.isPopupBlockedError)(O);ue&&Q.markBlocked();let ve=(0,_e.buildExternalMethodRecoveryMessage)("PayPal",ue,Ut.inAppBrowser),Gt=kr.current;if(Gt){let zt=ue&&Ut.inAppBrowser?new Ue.FloPayError(ve,"api_error",{code:Qe?.code??"paypal_popup_blocked"}):O;Gt("paypal",zt,Qe);return}if(O instanceof Ue.FloPayError&&O.code==="checkout_processing_timeout"){$t.current?.(O.message);return}$t.current?.(ve)},[Q,Ut.inAppBrowser]),Ir=(0,E.useCallback)(O=>{let Qe=Ee.current,ue=qe.current;Qe===null||!ue||(X.log({...ue,popupCapability:Q.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:O}),X.performance({...ue,popupCapability:Q.current(),stage:"overlay_return",durationMs:X.elapsed(Qe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:O}),Ee.current=null)},[Q,X]),cn=(0,E.useCallback)((O,Qe,ue)=>{let ve=qe.current;Ir("overlay_timeout"),ve&&X.error({...ve,popupCapability:Q.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Jr(Qe,{...ue,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:J,terminalReason:"overlay_timeout"}),Rt(!0),Dr(),zr()},[Ir,zr,Jr,Q,J,Dr,X]),Zr=(0,E.useCallback)(()=>{Q.markAvailable();let O=qe.current;O&&(re.current=O.attempt,X.log({...O,popupCapability:Q.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[Q,X]),Lr=(0,E.useCallback)(()=>!0,[]),or=(0,E.useCallback)(()=>{let O=qe.current;if(!O)return;let Qe=Ee.current;X.performance({...O,popupCapability:Q.current(),stage:"overlay_return",durationMs:Qe===null?0:X.elapsed(Qe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[Q,X]),{finishAttempt:vr,generationRef:ur,invalidateAttempt:pr,isAttemptCurrent:Tr,isAttemptInvalidated:Mr,startAttempt:Qr}=Ba(cn,{onHandoffObserved:Zr,defersMissingTerminal:Lr,onMissingTerminalDeferred:or}),mr=(0,E.useCallback)(()=>(Rt(!1),Qr("paypal")),[Qr]),tr=(0,E.useCallback)(O=>{pr(O?.generation),O?.showRetry&&Rt(!0),O?.remount&&Dr(),O?.focus!==!1&&zr()},[zr,pr,Dr]),Nr=O=>{let Qe=at.current;return Qe&&Xt.current.set(O,Qe),O};(0,E.useEffect)(()=>{mt.current!==L&&(mt.current=L,Ht.current=!1,Mt.current=!1,Oe(!1),je(!1),he(!1),Or.current?.("loading"))},[L]),(0,E.useEffect)(()=>{(0,Ge.invokeMerchantCallback)(()=>Xr.current?.(Pe&&!Lt))},[Pe,Lt]);let Ze=(0,Ue.normalizeGatewayEnvironment)(p);(0,E.useEffect)(()=>{let O={attempt:ur.current+1,inAppBrowser:Ut.inAppBrowser,appFamily:Ut.appFamily,popupCapability:Q.current(),presentationMode:J},Qe=()=>({...qe.current??O,popupCapability:Q.current()}),ue={error:f=>X.error({...f,...Qe()}),log:f=>X.log({...f,...Qe()}),performance:f=>X.performance({...f,...Qe()}),terminal:f=>X.terminal({...f,...Qe()}),startTiming:X.startTiming,elapsed:X.elapsed},ve=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",Gt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(B(`mount clientId=${ve} env=${p??"(unset)"}\u2192${Ze??"live"} ccy=${m} sub=${b}`),B(`ua=${Gt.slice(0,80)}${Gt.length>80?"\u2026":""}`),!d){B("FAIL: clientId empty \u2014 gateway misconfigured"),he(!0),ue.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(!G.current){B("FAIL: containerRef not attached");return}tt.current=ue.startTiming(),ue.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let zt=!1,xt=!1,U=()=>zt||xt,bn=f=>{let w=gt.current,j=w?f:"torn_down";w&&B(`onError ignored reason=${j}`),sn.take(Et.current)&&ue.log({name:bi,stage:"provider_ready",reason:j,provider:"paypal",paymentMethodCategory:"paypal"})},Vo=()=>Et.current===e?"stale_attempt":"session_changed",Io=He?ge:void 0,Sn,xn=!1,dn=()=>{Sn=(0,Ue.generateIdempotencyKey)(),Sn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),xn=!0},en=null,ar=!1,Fn=null,un=!1,Bn=()=>{!Fn||un||(un=!0,Fn.close().catch(()=>{}))},Ft=!1,tn=!1,pn=G.current,io=null,mn=null,On=[],so=null,$n=!1,Hn=!1,Kn=null,lo=f=>{if(!f||typeof f.getBoundingClientRect!="function")return"(no rect)";let w=f.getBoundingClientRect();return`${Math.round(w.width)}\xD7${Math.round(w.height)}`},Wo=f=>{if(!f)return"(empty)";try{let w=new URL(f,typeof window>"u"?"https://localhost":window.location.href),j=w.pathname.toLowerCase();return j.includes("checkcaptcha")||j.includes("captcha")?`CAPTCHA(${w.host}${j})`:j.includes("risk")||j.includes("challenge")?`RISK(${w.host}${j})`:j.includes("smart/buttons")?`smart-buttons(${w.host})`:`${w.host}${j}`.slice(0,100)}catch{return f.slice(0,80)}},Gn=f=>{let w=f.getAttribute("src"),j=f.getAttribute("srcdoc"),ae=f.getAttribute("name"),ee=f.getAttribute("sandbox"),ie=[];return w&&ie.push(`src=${Wo(w)}`),j&&ie.push(`srcdoc[${j.length}ch]`),!w&&!j&&ie.push("src=(empty) srcdoc=(empty)"),ae&&ie.push(`name=${ae.slice(0,40)}`),ee!==null&&ie.push(`sandbox="${ee.slice(0,40)}"`),ie.join(" ")},co=f=>{if(!(f instanceof HTMLIFrameElement))return"";try{let w=f.contentDocument;if(!w)return"cd=null";let j=w.body?.children.length??0,ae=w.body?.innerHTML.length??0,ee=w.head?.innerHTML.length??0;return`cd=same-origin readyState=${w.readyState} body[${j}children,${ae}ch] head[${ee}ch]`}catch(w){return`cd=cross-origin(${w.message.slice(0,30)})`}},Yn=[],qt=f=>{if(U())return;let w=f.message??String(f.error??"(no message)");w&&(w.toLowerCase().includes("paypal")||w.toLowerCase().includes("zoid")||w.toLowerCase().includes("postrobot")||w.toLowerCase().includes("storage"))&&(B(`window:error ${w.slice(0,140)}`),Yn.push(w))},Xn=f=>{if(U())return;let w=f.reason instanceof Error?f.reason.message:String(f.reason??"(no reason)");w&&(w.toLowerCase().includes("paypal")||w.toLowerCase().includes("zoid")||w.toLowerCase().includes("postrobot")||w.toLowerCase().includes("storage"))&&(B(`window:rejection ${w.slice(0,140)}`),Yn.push(w))},yn={value:0},wn=()=>{io?.disconnect(),io=null,mn?.disconnect(),mn=null;for(let f of On.splice(0))clearTimeout(f);Hn=!1,$n&&typeof window<"u"&&(window.removeEventListener("error",qt),window.removeEventListener("unhandledrejection",Xn)),$n=!1},fn=()=>{if(!($n||U()||Ft)){if($n=!0,Yn.length=0,yn.value=0,typeof window<"u"&&(window.addEventListener("error",qt),window.addEventListener("unhandledrejection",Xn)),typeof PerformanceObserver<"u")try{mn=new PerformanceObserver(f=>{if(!U())for(let w of f.getEntries()){if(!w.name.toLowerCase().includes("paypal"))continue;yn.value+=1;let j=Math.round(w.duration);B(`net ${j}ms ${w.name.slice(0,90)}`)}}),mn.observe({type:"resource",buffered:!0})}catch{}Kn?.()}},dt=()=>{so&&(clearTimeout(so),so=null)},Ar=()=>{wn(),dt()},Jt={setEnabled:f=>{f?fn():wn()}};I.current=Jt,S.current&&fn();let A=Ue.isPayPalTeardownMessage,D=f=>{if(U()||A(f))return;let w=(0,Bo.applyFriendlyMessageOverride)(f)??f;(0,Ge.invokeMerchantCallback)(()=>$t.current?.(w))},ne=(f,w)=>{if(zt||ar)return;ar=!0,xt=!0,Ar(),Bn();let j=su({kind:f,generationActive:!0,automaticRetryAllowed:ke,automaticRetryUsed:Ht.current});if(j.action==="retry"){Ht.current=!0,Oe(!1),Ye(!1),je(!0),Or.current?.("retrying"),en=setTimeout(()=>{zt||nt(ae=>ae+1)},nu);return}if(Oe(!1),Ye(!1),je(!1),he(!0),j.action!=="ignore"){if(Or.current?.("exhausted"),j.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",w);return}if(j.report){let ae=(0,_e.classifyExternalMethodFailure)({code:pc(f,w),message:w},{inAppBrowser:Ut.inAppBrowser,handoffObserved:!1});ae.popupBlocked&&Q.markBlocked(),ue.error({errorCode:ae.popupBlocked?ae.errorCode:j.report.errorCode,stage:j.report.stage,operationOutcome:j.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:ae.terminalReason})}Mt.current||(Mt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",pc(f,w)))}};he(!1);let Ce=async(f,w=at.current)=>{if(U())return;let j=w?.sessionId??e;if(Ae.current){await Ae.current(f,{sessionId:j,accountPatch:w?.accountPatch,nonce:w?.nonce});return}let ae=ue.startTiming();ue.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ee=()=>{ue.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ue.performance({stage:"processing",durationMs:ue.elapsed(ae),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ie=(0,Ue.buildPayPalProcessPaymentRequest)({body:f,sessionId:j,nonce:w?.nonce??vn.current,accountPatch:w?.accountPatch,session:an.current,email:Er.current}),Ot=await new Ri.PaymentAPI(kt,{telemetry:!1}).processPayment(ie.userId,ie.params);if(Ot.ok){if(xt||zt&>.current)return;ee(),ue.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ge.invokeMerchantCallback)(()=>jr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(U())return;let st=await Ot.json().catch(()=>null),Ct=(0,Ue.describePayPalProcessFailure)(st),It=Ct.message;ee(),Ot.status===400&&(typeof st?.declineCode=="string"||!Array.isArray(st?.fields))?ue.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Ot.status===400||Ot.status===422?ue.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):ue.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:lu(Ot.status),failureCategory:Ot.status>=500?"server_error":void 0}),D(It),(0,Ge.invokeMerchantCallback)(()=>nr.current?.(Cr("paypal",It,{code:Ct.code,declineCode:Ct.declineCode})));return}catch(ie){if(U())return;ee(),ue.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Bt=(0,Ue.friendlyPayPalFailureMessage)(ie instanceof Error?ie.message:void 0);D(Bt),(0,Ge.invokeMerchantCallback)(()=>nr.current?.(Cr("paypal",Bt)));return}},_t=()=>new Ue.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Zt=f=>U()?Promise.reject(_t()):Promise.resolve(f),xe=async f=>{if(f.ok){ue.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ge.invokeMerchantCallback)(()=>jr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let w=await f.json().catch(()=>null),j=(0,Ue.describePayPalProcessFailure)(w);ue.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ge.invokeMerchantCallback)(()=>nr.current?.(Cr("paypal",j.message,{code:j.code,declineCode:j.declineCode})))},it=()=>{let f=at.current;Ir("approved"),f&&(Pr.current.delete(f.surfaceKey),vr(f.generation)),at.current=null},oe=async f=>{if(U())throw _t();xn||dn();let w=at.current,j=w?.sessionId??e,ae=w?.nonce??vn.current;ue.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ee;try{ee=await new Ri.PaymentAPI(kt,{telemetry:!1}).createSessionIntent(j,ae??"",(0,Ue.buildPayPalSessionIntentRequest)(Io),{idempotencyKey:Sn})}catch(ie){throw ue.error({...(0,Ue.classifyTelemetryFailure)(ie,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ie}if(U())throw _t();if((0,Ue.isSettledSessionIntent)(ee))throw await xe(ee.response),it(),new Ue.FloPayError("PayPal checkout already settled.","api_error",{code:uc});if(ee.provider!=="paypal"||ee.providerObjectType!==ge)throw new Error(f);return ue.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ee.providerObjectId},et=(f,w)=>{let j=w?.nonce??vn.current;if(!j)return;let ae=w?.sessionId??e,ee=(0,Ue.resolvePayPalDeclineReason)(f);new Ri.PaymentAPI(kt,{telemetry:!1}).reportSessionIntentDecline(ae,j,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ee}).catch(()=>{})},pe=De;B("loadScript:scheduled (deferred 1 tick)");let yt=null,le=setTimeout(()=>{if(zt){B("loadScript:skipped (cancelled before defer ran)");return}B("loadScript:start");let f=Ze==="live"?"production":Ze,w={};ge==="subscription"?w={intent:"subscription",vault:!0}:ge==="order"&&(w={intent:"capture"}),yt=(0,mc.loadScript)({clientId:d,currency:m,...w,...f?{environment:f}:{},...f==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let j=!1;yt.then(ae=>{if(j=!0,B(`loadScript:resolved inactive=${U()} ns=${!!ae} buttons=${!!ae?.Buttons}`),U())return;if(!ae?.Buttons){B("FAIL: namespace missing Buttons factory"),ne("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}ue.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),ue.performance({stage:"provider_ready",durationMs:ue.elapsed(tt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ue.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let ee=async(Xe,Ke)=>{if(U()||ct.current!==pe)return;let Le=Xe.vaultSetupToken??Xe.subscriptionID??Xe.orderID??"",jt=Le?Xt.current.get(Le):Pr.current.get(pe);if(!(!jt||!Tr(jt.generation))&&vr(jt.generation)){Xt.current.delete(Le),Pr.current.delete(jt.surfaceKey),Ir("approved");try{if(Ye(!0),(0,Ge.invokeMerchantCallback)(()=>$t.current?.(null)),!Le)throw new Ue.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let wt=(0,Ue.resolvePayPalApprovalIdentity)({accountPatch:jt.accountPatch,email:Er.current,billingName:_r.current,session:an.current});if((0,Ue.needsPayPalPayerDetails)(wt))try{wt=(0,Ue.mergePayPalPayerIdentity)(wt,await Ke?.order?.get?.())}catch{}if((Kt.current||de)&&!(0,Ue.isValidEmail)(wt.email)){let Qt=await ft("PayPal",wt);if(!Qt)return;wt=Qt}(0,Ue.isValidEmail)(wt.email)&&(jt.accountPatch=(0,En.compactBuyerIdentity)({...jt.accountPatch,...wt}),await Kt.current?.(wt));let Wr=(0,Ue.buildPayPalTokenizedBody)(Le,Io);await Ce(Wr,jt)}catch(wt){D(wt instanceof Error?wt.message:"PayPal capture failed.")}finally{U()||Ye(!1)}}},ie=Xe=>{let Ke=Ie?()=>Zt(Ie):()=>oe(Xe);return async()=>Nr(await Ke())},Bt=ae.Buttons({style:{layout:"horizontal",height:ki,tagline:!1},...J==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Xe,Ke)=>{if(U()){await Ke.reject();return}dn();let Le=Vr.current,jt={};if(Le)try{let Qt=await Le("paypal");if(U()){await Ke.reject();return}if(!Qt.proceed){at.current=null,Pr.current.delete(pe),await Ke.reject();return}jt={sessionId:Qt.sessionId,accountPatch:Qt.accountPatch,nonce:Qt.nonce}}catch(Qt){B(`onClick:runBeforeButtonClick rejected msg=${(Qt instanceof Error?Qt.message:String(Qt)).slice(0,120)}`),at.current=null,Pr.current.delete(pe),await Ke.reject();return}(0,Ge.invokeMerchantCallback)(()=>Ur.current?.("paypal"));let wt=mr(),Wr={generation:wt,surfaceKey:pe,...jt};at.current=Wr,Pr.current.set(pe,Wr),qe.current={...O,attempt:wt},await Ke.resolve(),ue.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ue.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Ee.current=ue.startTiming()},createOrder:ge==="order"?ie("Failed to create PayPal order."):void 0,createSubscription:ge==="subscription"?ie("Failed to create PayPal subscription."):void 0,createVaultSetupToken:ge==="setup_token"?async()=>Nr(await oe("Failed to create PayPal setup token.")):void 0,onApprove:ee,onCancel:()=>{if(U())return;let Xe=Pr.current.get(pe)??at.current,Ke=Xe&&Tr(Xe.generation)?(0,Ue.buildPayPalCancelEvent)(Xe.sessionId??e,Io):null;Xe&&Pr.current.delete(Xe.surfaceKey),at.current=null,Ir("cancelled"),ue.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),fe.current=!0,tr({generation:Xe?.generation,remount:!0,focus:!1}),Ke&&(0,Ge.invokeMerchantCallback)(()=>Te.current?.(Ke))},onError:Xe=>{if(Xe instanceof Ue.FloPayError&&Xe.code===uc)return;let Ke=Xe instanceof Error?Xe.message:"PayPal failed to render.";if(U()||ct.current!==pe){A(Ke)||bn(Vo());return}if(Ft){let Le=Pr.current.get(pe)??at.current;if(!Le||!Tr(Le.generation)){if(A(Ke)){!Le&&!Mr()&&vr();return}bn(Le||Mr()?"stale_attempt":"no_current_attempt");return}if(B(`onError rendered=${Ft} msg=${Ke.slice(0,120)}`),A(Ke)){vr(Le.generation);return}let{errorCode:jt,popupBlocked:wt,providerDeclined:Wr,terminalReason:Qt}=(0,_e.classifyExternalMethodFailure)(Xe,{inAppBrowser:Ut.inAppBrowser,handoffObserved:re.current===Le.generation});if(wt&&Q.markBlocked(),Ir(Qt),Wr){ue.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Qt}),et(Xe,Le),(0,Ge.invokeMerchantCallback)(()=>nr.current?.(Cr("paypal",Ke))),Pr.current.delete(Le.surfaceKey),at.current=null,vr(Le.generation);return}ue.error({errorCode:jt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Qt}),Pr.current.delete(Le.surfaceKey),at.current=null,tr({generation:Le.generation,remount:!0,showRetry:!0,focus:!0}),Jr(Xe,{code:"paypal_runtime_failed",popupBlocked:wt,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:J,terminalReason:Qt});return}B(`onError rendered=${Ft} msg=${Ke.slice(0,120)}`),ne(A(Ke)?"teardown":"pre_ready_callback",Ke)}}),Ot=Bt.isEligible();if(B(`isEligible=${Ot}`),ue.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Ot){Oe(!1),ne("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}tn=!0,Fn=Bt,Kn=()=>{if(!$n||Hn||U()||Ft)return;Hn=!0,B(`container:dims ${lo(pn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(io=new MutationObserver(Ke=>{if(!U()){for(let Le of Ke)if(Le.type==="childList")Le.addedNodes.forEach(jt=>{if(!(jt instanceof Element))return;let wt=jt.tagName.toLowerCase(),Wr=(jt.getAttribute("title")??"").slice(0,40),Qt=wt==="iframe"?` ${Gn(jt)}`:"";B(`child+ ${wt}${Wr?` title="${Wr}"`:""}${Qt} dims=${lo(jt)}`)});else if(Le.type==="attributes"&&Le.target instanceof Element){let jt=Le.target;if(jt.tagName.toLowerCase()!=="iframe")continue;let wt=Le.attributeName;(wt==="src"||wt==="srcdoc")&&B(`attr~ iframe ${wt}=${wt==="srcdoc"?`[${(jt.getAttribute("srcdoc")??"").length}ch]`:Wo(jt.getAttribute("src"))} dims=${lo(jt)}`)}}}),io.observe(pn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Xe=Ke=>{if(U()||Ft)return;let Le=pn.querySelectorAll("iframe"),jt=typeof document<"u"&&"hasStorageAccess"in document;B(`watchdog:${Ke} container=${lo(pn)} children=${pn.childElementCount} iframes=${Le.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${jt} paypalNetRequests=${yn.value}`),Le.forEach((wt,Wr)=>{let Qt=(wt.getAttribute("title")??"").slice(0,40);B(` iframe[${Wr}] ${lo(wt)}${Qt?` title="${Qt}"`:""} ${Gn(wt)}`);let $r=co(wt);$r&&B(` ${$r}`)}),Yn.length===0&&B(" (no PayPal/zoid window errors captured)")};On.push(setTimeout(()=>Xe("3s"),3e3)),On.push(setTimeout(()=>Xe("8s"),8e3)),On.push(setTimeout(()=>Xe("15s"),15e3))},Kn(),B("render:start");let Ct=ue.startTiming();so=setTimeout(()=>{U()||Ft||(B("watchdog:11s retryable render timeout"),ne("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},ou);let It=Bt.render(pn);(async()=>{try{if(await It,B(`render:resolved inactive=${U()}`),Ar(),U()){Bn();return}Ft=!0,Oe(!0),je(!1),Or.current?.("ready"),ue.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),ue.performance({stage:"checkout_render",durationMs:ue.elapsed(Ct),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Xe){let Ke=Xe instanceof Error?Xe.message:"PayPal failed to render.";B(`render:rejected msg=${Ke.slice(0,120)}`),Ar(),ne(A(Ke)?"teardown":"render_rejected",Ke)}})()}).catch(ae=>{let ee=ae instanceof Error?ae.message:"PayPal operation failed.";B(`provider:failed msg=${ee.slice(0,120)}`);let ie="script_rejected";j&&A(ee)?ie="teardown":j&&tn&&(ie="render_rejected"),ne(ie,ee)})},0);return()=>{zt=!0,clearTimeout(le),en&&clearTimeout(en),Ar(),I.current===Jt&&(I.current=null),Bn(),Ee.current=null,qe.current=null}},[ke,kt,d,m,p,ge,J,He,e,Ie,De,X,ft,de,B,Ir]);let Cn=z?(0,_n.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Lt?"#fef2f2":"#f3f4f6",border:`1px solid ${Lt?"#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=${Lt})`,H.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
3
|
${H.join(`
|
|
4
|
-
`)}`]}):null;return Lt&&!u?
|
|
4
|
+
`)}`]}):null;return Lt&&!u?z?(0,_n.jsx)("div",{children:Cn}):null:(0,_n.jsxs)("div",{children:[Cn,Pt&&(0,_n.jsx)(da,{identity:Pt.identity,methodLabel:Pt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:ze,onCancel:()=>ze(null)}),(0,_n.jsxs)("div",{"aria-hidden":ce||Pt?!0:void 0,style:ce||Pt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ki},children:[!Pe&&!ce&&(0,_n.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,_n.jsx)("div",{ref:G,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ki,display:"flex",opacity:Pe?1:0},"aria-busy":Me||K},De)]},De),Y&&(0,_n.jsx)("button",{ref:pt,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:ln,style:au,children:"Try PayPal again"})]})}function Oa(e){return(0,_n.jsx)(yc,{...e})}function fc(e){return(0,_n.jsx)(yc,{...e})}var Da=require("react/jsx-runtime");function ma({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,Da.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,Da.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Da.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 ht=require("@flopay/shared");var gc=new Set;function cu(){return globalThis.process?.env?.NODE_ENV==="production"}function hc(e,t){gc.has(e)||cu()||(gc.add(e),console.warn(t))}function Pc(){hc("automatic-payment-button-inline-create","[FloPay] FloPayAutomaticPaymentButton: creating the session from inline props is deprecated and may be downgraded to a Full checkout. Mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and pass `getSession` instead.")}function vc(){hc("checkout-keyless-create","[FloPay] FloPayCheckout: `createSession` with checkoutMode confirm/auto is deprecated and may be downgraded to a Full checkout. For one-click, mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and use FloPayAutomaticPaymentButton `getSession`.")}var hr=require("react/jsx-runtime");var du={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function nn({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=du}){let m={fontSize:13,color:p.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,hr.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,hr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...p.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,hr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,hr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,hr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:p.spinnerTrackColor,strokeWidth:"3"}),(0,hr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:p.spinnerAccentColor})]}),e==="success"&&(0,hr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,hr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,hr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,hr.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,hr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,hr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,hr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,hr.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,hr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:p.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(a??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&s]}),e==="success"&&d!==null&&(0,hr.jsx)("p",{style:m,children:d}),e==="error"&&t&&(0,hr.jsx)("p",{style:m,children:t}),(0,hr.jsx)("style",{children:`
|
|
5
5
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
6
6
|
@keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
|
|
7
7
|
@keyframes flopay-draw { to { stroke-dashoffset: 0; } }
|
|
8
8
|
@keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
|
|
9
|
-
`})]})})}var Ei=require("@flopay/shared"),Sr=require("react");var Cc=require("react/jsx-runtime");function La({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,d]=(0,Sr.useState)(e instanceof Promise?null:e),[p,m]=(0,Sr.useState)(t instanceof Promise||!t?null:t),b=(0,Sr.useRef)(null),P=(0,Sr.useRef)(null),f=pa(n),_=(0,Sr.useCallback)(k=>{(0,Ei.isCardFieldsInstrumentSource)(k)||f(k)},[f]);(0,Sr.useEffect)(()=>{f({class:"lifecycle",name:"checkout.mount"})},[f]),(0,Sr.useEffect)(()=>{s&&f({class:"lifecycle",name:"sdk.initialize.ready"})},[f,s]),(0,Sr.useEffect)(()=>{if(s)return br(s)?.subscribe?.(_)},[_,s]),(0,Sr.useEffect)(()=>{if(!(!p||p===s))return br(p)?.subscribe?.(_)},[_,s,p]),(0,Sr.useEffect)(()=>{if(!s)return;let k=br(s);return b.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Sr.useEffect)(()=>{let k=!1;return e instanceof Promise?e.then(T=>{k||d(T)},()=>{k||f({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{k=!0}},[f,e]),(0,Sr.useEffect)(()=>{let k=!1;if(!t){m(null);return}return t instanceof Promise?t.then(T=>{k||m(T)},()=>{k||f({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{k=!0}},[f,t]),(0,Sr.useEffect)(()=>{if(!s||P.current===s)return;P.current=s;let k=br(s);k?.log({name:"checkout.rendered",stage:"checkout_render"}),f({class:"lifecycle",name:"checkout.rendered"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(b.current??0),durationMode:"machine"})},[f,s]);let j=(0,Ei.resolveBillingApiUrl)(r?.billingApiUrl),W=(0,Sr.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:j,emitInstrument:f}),[s,p,j,f]);return(0,Cc.jsx)(kn.Provider,{value:W,children:a})}var Vn=require("@flopay/shared");async function _i(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 Kr=require("@flopay/js"),je=require("@flopay/shared");var za="card";async function uu(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 pu(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 ya(e){return new je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function mu(){return new je.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Ua(e,t){return Object.assign(e,{checkoutMethod:t})}function go(e,t){let r=e instanceof je.FloPayError?e:new je.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Na(e,t){try{return await e()}catch(r){throw go(r,t)}}function Sc(e){return!e?.type||!e.threeDSecureToken||(0,je.isMerchantAuthRequired)(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function wc(e){return(0,Kr.runSavedCardChallenge)(e)}function qa(e,t,r,n=!0){let a={release:()=>{}};if(!n)return a;try{let s=new Kr.PaymentAPI(e),d=(0,Kr.beginSavedCardChallengeTelemetry)(s,t,r);return d?{telemetry:d,release:()=>{setTimeout(()=>{try{s.destroy()}catch{}},0)}}:a}catch{return a}}async function fa(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,d=new Kr.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,Kr.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:P=>ro({type:P.declineReason??"authorization_declined",gatewayErrorCode:P.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},d)}catch(P){if(a.aborted||P instanceof Error&&P.name==="AbortError")throw P instanceof je.FloPayError&&P.code==="three_ds_aborted"?P:ya(P);if(!(P instanceof je.FloPayError)||P.code!=="three_ds_timeout"&&P.code!=="checkout_processing_timeout")throw P;try{m=await d.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(_){if(a.aborted)throw ya(_);if(!(_ instanceof je.FloPayError)||_.code!=="checkout_processing_timeout")throw _}let f=m&&ko(m,t.session);if(!mo(f)&&f?.status!=="expired"){if(t.telemetry){let _=new Kr.PaymentAPI(r);try{_.reportThreeDsAbandoned(n)}finally{_.destroy()}}throw mu()}}let b=m&&ko(m,t.session);if(!mo(b))throw sa(b);return{...po(b,n),checkoutMethod:"card"}}function Rc(e){return new je.FloPayError("This payment needs your card details. Please complete your payment below.","authentication_error",{code:je.MERCHANT_AUTH_REQUIRED_CODE,...e===void 0?{}:{statusCode:e}})}function ro(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card");if((0,je.isMerchantAuthRequired)(e))return Ua(Rc(),n);let a=e?.message??t,s=(0,Bo.applyFriendlyMessageOverride)(a)??a,d=Ua(new je.FloPayError(s,"api_error",{code:e?.code??(0,je.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,je.normalizeCheckoutFailureOutcome)(e?.type)??(e?.type==="paypal_direct_required"?"paypal_direct_required":void 0)??e?.gatewayErrorCode}),n);return e?.orderId&&(d.orderId=e.orderId),d}function Ms(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ii(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function kc(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ii(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||Ii(p)))return p;let d=a.gateways;if(d&&typeof d=="object"){let p=d.stripe;if(p&&typeof p=="object"){let m=p,b=[m.stripeClientSecret,m.clientSecret];for(let P of b)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||Ii(P)))return P}}}}async function yu({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=kc(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 Kr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(Ii(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function ga({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:d}){let p=e.replace(/\/+$/,""),m=t??r.id,b=n??r.clientSecret,P=r.customer?.id??r.accountData?.userId??"",f=r.customer?.email??r.accountData?.email??"",_=r.customer?.firstName??r.accountData?.firstName??"",j=r.customer?.lastName??r.accountData?.lastName??"",W=r.customer?.country??r.accountData?.country??void 0,k=r.customer?.zip??r.accountData?.zip??void 0,y=await new Kr.PaymentAPI(p,d===!1?{telemetry:!1}:void 0).processPayment(P,{sessionId:m,nonce:b,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:P,email:f,firstName:_,lastName:j,country:W,zip:k},returnUrl:s??Ms(r)});if(y.ok){let Z=typeof y.json=="function"?await y.json().catch(()=>null):null;if((0,je.isAuthorizationOnlySession)(r)||Z?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof Z?.paymentId=="string"?Z.paymentId:r.paymentId,sessionId:typeof Z?.sessionId=="string"?Z.sessionId:m,authorizationExpiresAt:typeof Z?.authorizationExpiresAt=="string"?Z.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:Aa(a),checkoutMethod:bc(a,r)}};let v=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...v?{paymentIntentId:v}:{},paymentMethodId:Aa(a),checkoutMethod:bc(a,r)}}}let K;try{K=await y.json()}catch(Z){throw new je.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status,cause:Z})}if((0,je.isMerchantAuthRequired)(K))throw Ua(Rc(y.status),"card");if(K?.type==="3ds_required"&&typeof K.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:K.nextActionRedirectUrl};if(K?.type==="paypal_redirect_required"||K?.type==="3ds_required"){let Z=kc(K);if(!Z)throw new je.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status});return{type:K.type,threeDSecureToken:Z,paymentMethodId:K.paymentMethodId}}if(K?.gatewayErrorCode==="authentication_required"){let Z=await yu({billingApiUrl:p,sessionId:m,nonce:b,responseJson:K});if(Z)return Z;throw Ua(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw fu(K,y.status)}function fu(e,t){let r=new je.FloPayError(e?.message??"Payment failed. Please try again.","api_error",{code:e?.code??e?.gatewayErrorCode,declineCode:e?.declineCode??e?.gatewayDeclineReason,statusCode:t});return Object.assign(r,{telemetryOutcome:(0,je.classifyPaymentRejection)(t,e)})}async function Ti(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:m,signal:b}){let P=t?.getRawProvider();if(!P)throw go(new je.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw Ua(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let f=(0,je.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,j=e.paymentMethodId,W=await Na(()=>uu(P,e.threeDSecureToken,f),"card");if(W){if(W.error)throw go(new je.FloPayError(W.error.message??`Failed to retrieve 3DS ${f?"setup":"payment"} status.`,"api_error",{code:W.error.code}),"card");let T=W.intent;!j&&T?.payment_method&&(typeof T.payment_method=="string"?j=T.payment_method:"id"in T.payment_method&&(j=T.payment_method.id??void 0))}let k=j?await Na(()=>pu(P,e.threeDSecureToken,{payment_method:j,return_url:p??Ms(d)??window.location.href},f),"card"):null;if(k){if(k.error)throw go(new je.FloPayError(k.error.message??"3DS authentication failed.","api_error",{code:k.error.code}),"card");_=k.intent}else{let T=await Na(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(T.error)throw go(new je.FloPayError(T.error.message??"3DS authentication failed.","api_error",{code:T.error.code}),"card");_=(f?T.setupIntent:T.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let T=await ga({billingApiUrl:a,sessionId:s,session:d,telemetry:m,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:p});return T.type==="success"?{...T.result,paymentIntentId:T.result.paymentIntentId??_.id,paymentMethodId:T.result.paymentMethodId??j}:T.type==="next_action_required"?fa(T,{billingApiUrl:a,sessionId:s??d.id,session:d,signal:b}):Ti(T,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:m,signal:b})}throw go(new je.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let f=(r??t)?.getRawProvider();if(!f)throw go(new je.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:j}=await Na(()=>f.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(j)throw go(new je.FloPayError(j.message??"PayPal authorization failed.","api_error",{code:j.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await Na(()=>f.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??Ms(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(_)throw go(new je.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new je.FloPayError("Unsupported payment redirect state.","api_error")}function Va(e){if(e instanceof je.FloPayError){let n=(0,Bo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new je.FloPayError(n,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",r=(0,Bo.applyFriendlyMessageOverride)(t)??t;return new je.FloPayError(r,"api_error")}function As(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,je.isMountableVaultBlock)(e.data.session?.vault)||(0,Un.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new je.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function bc(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,Un.canRecoverHostedCardForm)(t)?"card":void 0}async function xs({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,Kr.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,Kr.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 je.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return s?m=p:t&&(m=d),{flopay:d,paypalFlopay:m}}var Wn=require("@flopay/js"),c=require("@flopay/shared"),lr=require("@stripe/react-stripe-js"),o=ws(require("react"),1);function Lo(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(Lo(t,r)),log:r=>e.log(Lo(t,r)),performance:r=>e.performance(Lo(t,r)),terminal:r=>e.terminal(Lo(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 No=require("react"),Uo=require("react/jsx-runtime"),Ec="More payment options",gu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},hu={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function Fs({label:e,open:t,showLink:r,onOpen:n,color:a,fontFamily:s,children:d}){let p=(0,No.useId)(),m=(0,No.useRef)(null),b=(0,No.useRef)(!1);return(0,No.useEffect)(()=>{t&&b.current&&m.current?.focus()},[t]),(0,Uo.jsxs)(Uo.Fragment,{children:[!t&&r&&(0,Uo.jsx)("button",{type:"button","data-testid":"flopay-more-payment-options","aria-expanded":!1,"aria-controls":p,onClick:()=>{b.current=!0,n()},style:{alignSelf:"center",margin:0,padding:"0.25rem 0",border:0,background:"none",cursor:"pointer",color:a,fontFamily:s,fontSize:"0.9rem",fontWeight:500,textDecoration:"underline",textUnderlineOffset:"0.2em"},children:e}),(0,Uo.jsx)("div",{id:p,ref:m,role:"group","aria-label":e,tabIndex:t?-1:void 0,"data-testid":"flopay-more-payment-options-section",style:t?hu:gu,children:d})]})}var ho=require("@flopay/shared"),Ic=require("react");var _c={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 Fr=require("react/jsx-runtime"),Pu=`
|
|
9
|
+
`})]})})}var Ei=require("@flopay/shared"),Sr=require("react");var Cc=require("react/jsx-runtime");function La({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,d]=(0,Sr.useState)(e instanceof Promise?null:e),[p,m]=(0,Sr.useState)(t instanceof Promise||!t?null:t),b=(0,Sr.useRef)(null),P=(0,Sr.useRef)(null),g=pa(n),_=(0,Sr.useCallback)(k=>{(0,Ei.isCardFieldsInstrumentSource)(k)||g(k)},[g]);(0,Sr.useEffect)(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),(0,Sr.useEffect)(()=>{s&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,s]),(0,Sr.useEffect)(()=>{if(s)return br(s)?.subscribe?.(_)},[_,s]),(0,Sr.useEffect)(()=>{if(!(!p||p===s))return br(p)?.subscribe?.(_)},[_,s,p]),(0,Sr.useEffect)(()=>{if(!s)return;let k=br(s);return b.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Sr.useEffect)(()=>{let k=!1;return e instanceof Promise?e.then(T=>{k||d(T)},()=>{k||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{k=!0}},[g,e]),(0,Sr.useEffect)(()=>{let k=!1;if(!t){m(null);return}return t instanceof Promise?t.then(T=>{k||m(T)},()=>{k||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{k=!0}},[g,t]),(0,Sr.useEffect)(()=>{if(!s||P.current===s)return;P.current=s;let k=br(s);k?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(b.current??0),durationMode:"machine"})},[g,s]);let V=(0,Ei.resolveBillingApiUrl)(r?.billingApiUrl),W=(0,Sr.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:V,emitInstrument:g}),[s,p,V,g]);return(0,Cc.jsx)(kn.Provider,{value:W,children:a})}var jn=require("@flopay/shared");async function _i(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 Kr=require("@flopay/js"),Ve=require("@flopay/shared");var za="card";async function uu(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 pu(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 ya(e){return new Ve.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function mu(){return new Ve.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Ua(e,t){return Object.assign(e,{checkoutMethod:t})}function go(e,t){let r=e instanceof Ve.FloPayError?e:new Ve.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 Na(e,t){try{return await e()}catch(r){throw go(r,t)}}function Sc(e){return!e?.type||!e.threeDSecureToken||(0,Ve.isMerchantAuthRequired)(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function wc(e){return(0,Kr.runSavedCardChallenge)(e)}function qa(e,t,r,n=!0){let a={release:()=>{}};if(!n)return a;try{let s=new Kr.PaymentAPI(e),d=(0,Kr.beginSavedCardChallengeTelemetry)(s,t,r);return d?{telemetry:d,release:()=>{setTimeout(()=>{try{s.destroy()}catch{}},0)}}:a}catch{return a}}async function fa(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,d=new Kr.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,Kr.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:P=>ro({type:P.declineReason??"authorization_declined",gatewayErrorCode:P.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},d)}catch(P){if(a.aborted||P instanceof Error&&P.name==="AbortError")throw P instanceof Ve.FloPayError&&P.code==="three_ds_aborted"?P:ya(P);if(!(P instanceof Ve.FloPayError)||P.code!=="three_ds_timeout"&&P.code!=="checkout_processing_timeout")throw P;try{m=await d.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(_){if(a.aborted)throw ya(_);if(!(_ instanceof Ve.FloPayError)||_.code!=="checkout_processing_timeout")throw _}let g=m&&ko(m,t.session);if(!mo(g)&&g?.status!=="expired"){if(t.telemetry){let _=new Kr.PaymentAPI(r);try{_.reportThreeDsAbandoned(n)}finally{_.destroy()}}throw mu()}}let b=m&&ko(m,t.session);if(!mo(b))throw sa(b);return{...po(b,n),checkoutMethod:"card"}}function Rc(e){return new Ve.FloPayError("This payment needs your card details. Please complete your payment below.","authentication_error",{code:Ve.MERCHANT_AUTH_REQUIRED_CODE,...e===void 0?{}:{statusCode:e}})}function ro(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card");if((0,Ve.isMerchantAuthRequired)(e))return Ua(Rc(),n);let a=e?.message??t,s=(0,Bo.applyFriendlyMessageOverride)(a)??a,d=Ua(new Ve.FloPayError(s,"api_error",{code:e?.code??(0,Ve.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ve.normalizeCheckoutFailureOutcome)(e?.type)??(e?.type==="paypal_direct_required"?"paypal_direct_required":void 0)??e?.gatewayErrorCode}),n);return e?.orderId&&(d.orderId=e.orderId),d}function Ms(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ii(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function kc(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ii(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||Ii(p)))return p;let d=a.gateways;if(d&&typeof d=="object"){let p=d.stripe;if(p&&typeof p=="object"){let m=p,b=[m.stripeClientSecret,m.clientSecret];for(let P of b)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||Ii(P)))return P}}}}async function yu({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=kc(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 Kr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(Ii(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function ga({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:d}){let p=e.replace(/\/+$/,""),m=t??r.id,b=n??r.clientSecret,P=r.customer?.id??r.accountData?.userId??"",g=r.customer?.email??r.accountData?.email??"",_=r.customer?.firstName??r.accountData?.firstName??"",V=r.customer?.lastName??r.accountData?.lastName??"",W=r.customer?.country??r.accountData?.country??void 0,k=r.customer?.zip??r.accountData?.zip??void 0,y=await new Kr.PaymentAPI(p,d===!1?{telemetry:!1}:void 0).processPayment(P,{sessionId:m,nonce:b,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:P,email:g,firstName:_,lastName:V,country:W,zip:k},returnUrl:s??Ms(r)});if(y.ok){let Z=typeof y.json=="function"?await y.json().catch(()=>null):null;if((0,Ve.isAuthorizationOnlySession)(r)||Z?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof Z?.paymentId=="string"?Z.paymentId:r.paymentId,sessionId:typeof Z?.sessionId=="string"?Z.sessionId:m,authorizationExpiresAt:typeof Z?.authorizationExpiresAt=="string"?Z.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:Aa(a),checkoutMethod:bc(a,r)}};let v=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...v?{paymentIntentId:v}:{},paymentMethodId:Aa(a),checkoutMethod:bc(a,r)}}}let K;try{K=await y.json()}catch(Z){throw new Ve.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status,cause:Z})}if((0,Ve.isMerchantAuthRequired)(K))throw Ua(Rc(y.status),"card");if(K?.type==="3ds_required"&&typeof K.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:K.nextActionRedirectUrl};if(K?.type==="paypal_redirect_required"||K?.type==="3ds_required"){let Z=kc(K);if(!Z)throw new Ve.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status});return{type:K.type,threeDSecureToken:Z,paymentMethodId:K.paymentMethodId}}if(K?.gatewayErrorCode==="authentication_required"){let Z=await yu({billingApiUrl:p,sessionId:m,nonce:b,responseJson:K});if(Z)return Z;throw Ua(new Ve.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw fu(K,y.status)}function fu(e,t){let r=new Ve.FloPayError(e?.message??"Payment failed. Please try again.","api_error",{code:e?.code??e?.gatewayErrorCode,declineCode:e?.declineCode??e?.gatewayDeclineReason,statusCode:t});return Object.assign(r,{telemetryOutcome:(0,Ve.classifyPaymentRejection)(t,e)})}async function Ti(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:m,signal:b}){let P=t?.getRawProvider();if(!P)throw go(new Ve.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw Ua(new Ve.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=(0,Ve.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,V=e.paymentMethodId,W=await Na(()=>uu(P,e.threeDSecureToken,g),"card");if(W){if(W.error)throw go(new Ve.FloPayError(W.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:W.error.code}),"card");let T=W.intent;!V&&T?.payment_method&&(typeof T.payment_method=="string"?V=T.payment_method:"id"in T.payment_method&&(V=T.payment_method.id??void 0))}let k=V?await Na(()=>pu(P,e.threeDSecureToken,{payment_method:V,return_url:p??Ms(d)??window.location.href},g),"card"):null;if(k){if(k.error)throw go(new Ve.FloPayError(k.error.message??"3DS authentication failed.","api_error",{code:k.error.code}),"card");_=k.intent}else{let T=await Na(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(T.error)throw go(new Ve.FloPayError(T.error.message??"3DS authentication failed.","api_error",{code:T.error.code}),"card");_=(g?T.setupIntent:T.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let T=await ga({billingApiUrl:a,sessionId:s,session:d,telemetry:m,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:p});return T.type==="success"?{...T.result,paymentIntentId:T.result.paymentIntentId??_.id,paymentMethodId:T.result.paymentMethodId??V}:T.type==="next_action_required"?fa(T,{billingApiUrl:a,sessionId:s??d.id,session:d,signal:b}):Ti(T,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:m,signal:b})}throw go(new Ve.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(r??t)?.getRawProvider();if(!g)throw go(new Ve.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:V}=await Na(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(V)throw go(new Ve.FloPayError(V.message??"PayPal authorization failed.","api_error",{code:V.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await Na(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??Ms(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(_)throw go(new Ve.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ve.FloPayError("Unsupported payment redirect state.","api_error")}function ja(e){if(e instanceof Ve.FloPayError){let n=(0,Bo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new Ve.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,Bo.applyFriendlyMessageOverride)(t)??t;return new Ve.FloPayError(r,"api_error")}function As(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,Ve.isMountableVaultBlock)(e.data.session?.vault)||(0,Un.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new Ve.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 bc(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,Un.canRecoverHostedCardForm)(t)?"card":void 0}async function xs({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,Kr.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,Kr.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 Ve.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return s?m=p:t&&(m=d),{flopay:d,paypalFlopay:m}}var Wn=require("@flopay/js"),c=require("@flopay/shared"),lr=require("@stripe/react-stripe-js"),o=ws(require("react"),1);function Lo(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(Lo(t,r)),log:r=>e.log(Lo(t,r)),performance:r=>e.performance(Lo(t,r)),terminal:r=>e.terminal(Lo(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 No=require("react"),Uo=require("react/jsx-runtime"),Ec="More payment options",gu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},hu={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function Fs({label:e,open:t,showLink:r,onOpen:n,color:a,fontFamily:s,children:d}){let p=(0,No.useId)(),m=(0,No.useRef)(null),b=(0,No.useRef)(!1);return(0,No.useEffect)(()=>{t&&b.current&&m.current?.focus()},[t]),(0,Uo.jsxs)(Uo.Fragment,{children:[!t&&r&&(0,Uo.jsx)("button",{type:"button","data-testid":"flopay-more-payment-options","aria-expanded":!1,"aria-controls":p,onClick:()=>{b.current=!0,n()},style:{alignSelf:"center",margin:0,padding:"0.25rem 0",border:0,background:"none",cursor:"pointer",color:a,fontFamily:s,fontSize:"0.9rem",fontWeight:500,textDecoration:"underline",textUnderlineOffset:"0.2em"},children:e}),(0,Uo.jsx)("div",{id:p,ref:m,role:"group","aria-label":e,tabIndex:t?-1:void 0,"data-testid":"flopay-more-payment-options-section",style:t?hu:gu,children:d})]})}var ho=require("@flopay/shared"),Ic=require("react");var _c={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 Fr=require("react/jsx-runtime"),Pu=`
|
|
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 @@ ${H.join(`
|
|
|
27
27
|
0% { opacity: 1; transform: translateX(0) scale(1); }
|
|
28
28
|
100% { opacity: 0; transform: translateX(16px) scale(0.97); }
|
|
29
29
|
}
|
|
30
|
-
`,Eo=44;function ha(){return(0,Fr.jsx)("style",{children:Pu})}function ja(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function Wa({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Fr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Fr.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,Fr.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 $a(e){return e!=="unavailable"&&e!=="load_error"}function Ai({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:d,backgroundColor:p,borderColor:m,textColor:b,borderRadius:P,fontFamily:f}){let _=(0,ho.resolveStripeMethodBrandVariant)(e,t),j=_c[e],[W,k]=(0,Ic.useState)(!1),T=!!j&&!W,y=_?.backgroundColor??p??"#ffffff",K=_?.borderColor??m??"#d1d5db",Z=_?.textColor??b??"#262833";return(0,Fr.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&d()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Eo,padding:"0 1rem",backgroundColor:y,color:Z,border:`1px solid ${K}`,borderRadius:P??8,fontSize:"0.95rem",fontWeight:600,fontFamily:f,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,Fr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,ho.getStripeMethodDisplayName)(e)}\u2026`}):(0,Fr.jsxs)(Fr.Fragment,{children:[(0,Fr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,ho.hasVendoredStripeMethodLogo)(e)?8:0},children:[T?(0,Fr.jsx)("img",{src:j,alt:"","aria-hidden":"true",onError:()=>k(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!T&&_?.logoSvg?(0,Fr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:_.logoSvg}}):null,(0,Fr.jsx)("span",{children:(0,ho.getStripeMethodDisplayName)(e)})]}),s&&(0,Fr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:Z,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,Fr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function xi(e){let t=new Set(e.map(ho.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var Fi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},Bi={type:"accordion",defaultCollapsed:!1,radios:"never"};function Oi({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:d,children:p}){return(0,Fr.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 Bs=require("react/jsx-runtime"),vu=["first","second","third","fourth"];function Os({rows:e,borderRadius:t}){return(0,Bs.jsx)("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:vu.slice(0,Math.max(1,e)).map(r=>(0,Bs.jsx)("div",{style:{height:Eo,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},r))})}var Mc=require("@flopay/js"),Di=require("@flopay/shared"),Li=require("react"),Cu=1500,Tc=new Set;function Ac(e){for(let t of e)Tc.has(t)||(Tc.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function bu(e){if(e!=null)try{return JSON.stringify(e)}catch{return Ac(["the rules could not be sent (they are not plain data), so the default layout applies."]),"{}"}}var Su={order:[...Di.DEFAULT_PAYMENT_METHOD_ORDER],moreOptions:[]};function xc({rules:e,sessionId:t,nonce:r,billingApiUrl:n,waitForSession:a}){let s=bu(e),[d,p]=(0,Li.useState)(null);return(0,Li.useEffect)(()=>{if(s===void 0||a)return;let m=JSON.parse(s),b=!1,P=W=>{b||(b=!0,p(W))},f=()=>P((0,Di.resolveDefaultPaymentMethodLayout)(m));if(!t||!r||!n){f();return}let _=new AbortController,j=setTimeout(()=>{f(),_.abort()},Cu);return new Mc.PaymentAPI(n,{telemetry:!1}).resolvePaymentMethodLayout(t,r,m,{signal:_.signal}).then(W=>{if(!W){f();return}b||Ac(W.warnings),P({order:W.order,moreOptions:W.moreOptions})}).catch(f).finally(()=>clearTimeout(j)),()=>{b=!0,clearTimeout(j),_.abort()}},[s,t,r,n,a]),s===void 0?Su:d}var Pn=require("react");var Ha=require("@flopay/shared"),wu=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 Ru(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return wu.has(t.charAt(0).toLowerCase()+t.slice(1))}function ku(e,t){return typeof t=="number"&&t!==0&&!Ru(e)?`${t}px`:String(t).trim()}function Fc(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]=ku(r,n)}}}var zo=require("react/jsx-runtime"),Ds=new WeakSet;function _o({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:d,containerStyle:p,onReady:m,onError:b,onValidation:P}){let f=(0,Pn.useRef)(null),_=(0,Pn.useRef)(m),j=(0,Pn.useRef)(b),W=(0,Pn.useRef)(P);_.current=m,j.current=b,W.current=P;let k=(0,Pn.useRef)(s);k.current=s;let T=(0,Pn.useRef)(null),y=d??void 0,K=(0,Pn.useRef)(y);K.current=y;let Z=(0,Pn.useRef)(void 0);return(0,Pn.useEffect)(()=>{let v=f.current;if(!v)return;let ke=!0,M=!1,se=()=>{!ke||M||(M=!0,_.current?.())},be=e.on("ready",()=>{se()}),Ie=e.on("error",q=>{j.current?.(q.message??"There was a problem loading the secure card form.")}),ye=e.on("validation",q=>{W.current?.(q.message??null)}),vt=K.current??(Ds.has(e)?null:void 0),ut={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...k.current?{theme:k.current}:{},...vt===void 0?{}:{submitLabel:vt}};return T.current=k.current??null,Z.current=K.current,K.current!==void 0&&Ds.add(e),e.mount(v,ut).then(()=>{se()}).catch(q=>{ke&&j.current?.(q instanceof Error?q.message:"Failed to load the secure card form.")}),()=>{ke=!1,be(),Ie(),ye(),e.unmount()}},[e,t,r,n,a]),Oo(()=>{let v=f.current;v&&Fc(v,p)},[p]),(0,Pn.useEffect)(()=>{s!==void 0&&(s===null&&T.current===null||(T.current=s,e.applyTheme?.(s)))},[e,s]),(0,Pn.useEffect)(()=>{y!==Z.current&&(Z.current=y,y!==void 0&&Ds.add(e),e.setSubmitLabel?.(y??null))},[e,y]),(0,zo.jsx)("div",{ref:f,"data-testid":"flopay-vault-card-fields"})}function Ka({label:e}){return(0,zo.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,zo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,zo.jsx)("span",{children:e}),(0,zo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var Ks=require("@flopay/shared"),l=require("react/jsx-runtime"),no="flopay_stripe_resume",Bc="flopay_wallet_resume",Wc="fw1",Eu="fw2",$c=300*1e3,_u=900,Iu="express_checkout_click_timeout",Tu=25e3,Mu=25e3,Au=1e4,jn={provider:"paypal",paymentMethodCategory:"paypal"},xu="x-flopay-process-result-source",Fu="status";async function Bu(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 Ni={},Ya=class{constructor(t){this.reason=t}};function Ou(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function cr(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function Ws(e){return`${Eu}:${e}`}function Ui(e){return cr(Ws(e))}function zi(e,t){if(typeof window>"u")return null;let r=Ws(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>$c||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(Ui(e),null):a}catch{return Ui(e),null}}function Du(e){return cr(Ws(e.sessionId),e)}function Oc(e,t,r){let n=zi(e,t);return!n||n.clientSecret!==r?!1:Ui(e)}function Ls(e,t,r){if(typeof window>"u")return;zi(e,t)?.clientSecret===r&&Ui(e)}function Lu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Ns(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":Ma(e.status),a=Lu(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Dc(e,t,r){let n=null;try{return await Promise.race([ac(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Au),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Nu(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Hc(e){return e instanceof c.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function qi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Wn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw Hc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var Us=c.STRIPE_PAYPAL_RESUME_KEY,Ga=new Map,Uu=250,Lc="Just a moment \u2014 we are finalizing your order. Please press pay again.",zu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function $s(e,t,r,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:r,requestCategory:"provider_sdk",...n?{terminalReason:n}:{}})}async function Vi({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new Wn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function qu(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,la.splitFullName)(r),d=s.firstName?s:(0,la.splitFullName)(n?.name);return(0,En.compactBuyerIdentity)({email:(0,c.isValidEmail)(a)?a:n?.email?.trim(),firstName:d.firstName,lastName:d.lastName})}async function Vu({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 Xa=180,Nc=`flopay-card-enter ${Xa}ms cubic-bezier(0, 0, 0.2, 1) both`,Uc=`flopay-card-exit ${Xa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,ju=`flopay-buttons-enter ${Xa}ms cubic-bezier(0, 0, 0.2, 1) both`,Wu=`flopay-buttons-exit ${Xa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function $u(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Hs(e){return(0,c.derivePrimaryTileStyle)(e)}var Hu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Ku(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 qs={width:"100%",minHeight:Eo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function zc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Vs(e){return e==="paypal"?"PayPal":(0,c.getStripeMethodDisplayName)(e)}function Gu(e){let t=(0,c.getPostalCodeExample)(e);return`Enter a valid ${(0,c.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Yu(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 Xu(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 Ju(e){return typeof e=="number"?`${e}px`:e}function ji(e){return(0,l.jsx)(ep,{...e})}function qc({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:d=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:b,runBeforeButtonClick:P,billingName:f,onBuyerIdentityReady:_,onLoadStateChange:j,placeholderBorderRadius:W,popupCapabilityOwner:k,externalTelemetryContext:T,presentationMode:y}){let K=fo(),{emitInstrument:Z}=(0,o.useContext)(kn),v=(0,lr.useStripe)(),ke=(0,lr.useElements)(),M=(0,o.useMemo)(()=>Mi(br(K),T),[T,K]),[se,be]=(0,o.useState)("loading");(0,o.useEffect)(()=>{j?.(se)},[se,j]);let[Ie,ye]=(0,o.useState)(!1),vt=(0,o.useRef)(!1),ut=!(0,c.isValidEmail)(r?.trim())||!f?.trim(),{request:q,collect:We,finish:$e}=ca(),Be=(0,o.useRef)(!1),we=(0,o.useRef)(null),X=(0,o.useRef)(null),[G,tt]=(0,o.useState)(0),[Ee,qe]=(0,o.useState)(!1),te=(0,o.useRef)(!1),V=(0,o.useRef)(new Map),{startAttempt:Se,finishAttempt:Q,invalidateAttempt:pt,isAttemptInvalidated:fe,isAttemptCurrent:Pe,generationRef:Oe}=Ba((he,Me,Ye)=>{b?.(he,Me,{...Ye,popupBlocked:Ye?.popupBlocked??(0,_e.isPopupBlockedError)(Me),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y,terminalReason:"overlay_timeout"}),qe(!0),tt(Pt=>Pt+1)},{onHandoffObserved:()=>{k.markAvailable(),M?.log({name:"provider.popup.opened",stage:"overlay_open",...jn,attempt:Oe.current})}});(0,o.useEffect)(()=>{Ee&&X.current?.focus()},[Ee,G]);let ce=(0,o.useCallback)(()=>{tt(he=>he+1)},[]),Ve=(0,o.useCallback)((he,Me,Ye)=>{pt(Ye),b?.("paypal",he,{code:Me,popupBlocked:(0,_e.isPopupBlockedError)(he),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y}),qe(!0),ce()},[pt,b,y,ce]),De=(0,o.useCallback)(()=>{window.setTimeout(()=>{(we.current?.querySelector("iframe")??we.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{te.current&&(te.current=!1,De())},[De,G]);let nt=(0,o.useCallback)(()=>{qe(!1),s?.(null),De()},[De,s]);(0,o.useEffect)(()=>{if(!v||Be.current)return;let[he,Me,Ye]=(0,c.readStripeRedirectParams)();if(!he||!Me)return;let Pt=(0,c.readMatchingStripePayPalContinuation)(Me);if(!Pt)return;Be.current=!0;let ft=!0,ze=Ga.get(Me);ze||(ze=Ye==="failed"?Promise.resolve(null):Promise.resolve().then(()=>v.retrievePaymentIntent(Me)),Ga.set(Me,ze));let Nt={accountPatch:Pt.accountPatch,sessionId:Pt.sessionId,nonce:Pt.nonce},de=()=>{M?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...jn,requestCategory:"provider_sdk"})};return M?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...jn}),(async()=>{try{ye(!0);let At=await ze;if(!ft)return;if(At?.error){Ga.delete(Me),de(),s?.(At.error.message??"Failed to retrieve PayPal payment status.");return}if((0,c.clearStripePayPalReturn)(),Ga.delete(Me),Ye==="failed"){let ge="PayPal payment was declined. Please try again.";M?.terminal({outcome:"payment_declined",...jn,terminalReason:"provider_declined"}),s?.(ge),m?.(Cr("paypal",ge));return}let $=At?.paymentIntent;if($&&$.id!==he){de(),s?.("Failed to match the returned PayPal payment.");return}if($&&($.status==="requires_capture"||$.status==="succeeded")){let ge=typeof $.payment_method=="string"?$.payment_method:$.payment_method?.id;a({id:ge??$.id,type:"card",threeDSecureActionResultTokenId:$.id,isPaypal:!0},{...Nt,presentationMode:"redirect"})}else{let ge="PayPal payment was not completed. Please try again.";M?.terminal({outcome:$?.status==="canceled"?"payment_cancelled":"payment_declined",...jn,terminalReason:$?.status==="canceled"?"cancelled":"provider_declined"}),s?.(ge),m?.(Cr("paypal",ge))}}catch(At){if(!ft)return;Ga.delete(Me),de(),s?.(At instanceof Error?At.message:"Failed to complete PayPal payment.")}finally{ft&&ye(!1)}})(),()=>{ft=!1,Be.current=!1}},[v,a,s,m,M]);let ct=(0,o.useCallback)(async(he=!1)=>{let Me=P?await P("paypal"):{proceed:!0};if(!Me.proceed)return V.current.delete(G),!1;let Ye=Se("paypal");return V.current.set(G,{generation:Ye,accountPatch:Me.accountPatch,sessionId:Me.sessionId,nonce:Me.nonce}),qe(!1),M?.log({name:`provider.${he?"redirect.started":"handoff.requested"}`,stage:he?"redirect":"overlay_open",...jn,attempt:Ye}),p?.("paypal"),!0},[p,M,P,Se,G]),Y=(0,o.useCallback)(async he=>{if(d||Ie||!await ct()){he.reject();return}he.resolve()},[d,ct,Ie]),Rt=(0,o.useCallback)(async he=>{if(!v||!ke)return;let Me=V.current.get(G);if(Me&&!Pe(Me.generation)){V.current.delete(G);return}if(!Me&&fe()||Me&&!Q(Me.generation))return;Me||Q();let Ye=Me??null;if(V.current.delete(G),!Ye&&P){let kt=await P("paypal");if(!kt.proceed){he.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Ye={accountPatch:kt.accountPatch,sessionId:kt.sessionId,nonce:kt.nonce}}let Pt=Ye?.sessionId??e,ft=Ye?.nonce??t,ze=await Vu({event:he,prepared:Ye,email:r,billingName:f,methodLabel:"PayPal",collect:We});if(!ze){he.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Nt=ze.email,de={...Ye?.accountPatch,...(0,En.compactBuyerIdentity)(ze,!0)};try{if(ye(!0),s?.(null),!Pt||!(0,c.isValidEmail)(Nt))throw new Error("Missing sessionId or email for PayPal payment");await _?.(ze);let kt=v.createPaymentMethod,{error:At,paymentMethod:$}=await kt({type:"paypal"});if(At){Ve(At,"stripe_paypal_create_payment_method_failed",Me?.generation),he.paymentFailed({reason:"fail"});return}let ge=await qi(n,Z,Pt,ft??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:$?.id??null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(ge)){he.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:de,paymentMethodCategory:"paypal",presentationMode:y,sessionId:Pt,nonce:ft,settledProcessResponse:ge.response});return}if(ge.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ut=ge.clientSecret,g={return_url:(0,c.stripeRedirectReturnUrl)()};if($?.id&&(g.payment_method=$.id),!cr(Us,{clientSecret:Ut,sessionId:Pt,nonce:ft,accountPatch:de})&&y==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:He,paymentIntent:L}=await v.confirmPayment({clientSecret:Ut,confirmParams:g,redirect:"if_required"});if(He){if(cr(Us),(0,_e.isProviderDecline)(He)){let u=He.message??"Your payment was declined.";M?.terminal({outcome:"payment_declined",...jn,terminalReason:"provider_declined"}),s?.(u),m?.(Cr("paypal",u,{code:(0,_e.getProviderErrorCode)(He),declineCode:(0,_e.getProviderDeclineCode)(He)})),await Vi({billingApiUrl:n,sessionId:Pt,nonce:ft,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,_e.getProviderErrorCode)(He)??"provider_declined"}})}else Ve(He,"stripe_paypal_confirm_failed",Me?.generation);return}cr(Us);let mt=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;a({id:mt??L?.id,type:"card",threeDSecureActionResultTokenId:L?.id,isPaypal:!0},{accountPatch:de,paymentMethodCategory:"paypal",presentationMode:y,sessionId:Pt,nonce:ft});return}catch(kt){Ve(kt,"stripe_paypal_failed",Me?.generation)}finally{ye(!1)}},[v,ke,e,t,r,f,We,_,n,Z,a,s,m,P,Ve,Q,Pe,fe,M,y,G]),Ht=(0,o.useCallback)(async()=>{if(!(vt.current||d||Ie||!v||!ke)){vt.current=!0,ye(!0);try{if(!await ct(!0))return;await Rt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{vt.current=!1,ye(!1)}}},[ke,Rt,d,ct,v,Ie]),Mt=y==="redirect"?(0,l.jsx)("button",{type:"button",disabled:d||Ie,onClick:()=>{Ht()},style:{width:"100%",minHeight:Eo,border:"1px solid #d1d5db",borderRadius:W??8,background:"#ffc439",color:"#111827",cursor:d||Ie?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,l.jsx)(lr.ExpressCheckoutElement,{onReady:he=>be(ja(he,["paypal"])),onLoadError:()=>{be("load_error"),$s(M,"paypal","paypal","provider_error")},onClick:Y,onConfirm:Rt,onCancel:()=>{let he=V.current.get(G);V.current.delete(G),M?.terminal({outcome:"payment_cancelled",...jn,terminalReason:"cancelled",...he?{attempt:he.generation}:{}}),pt(he?.generation),qe(!1),te.current=!0,ce()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ut,emailRequired:ut,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},G),Lt=(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{ref:we,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ee&&(0,l.jsx)("button",{ref:X,type:"button","data-testid":"flopay-paypal-retry-button",onClick:nt,style:qs,children:"Try PayPal again"}),q&&(0,l.jsx)(da,{identity:q.identity,methodLabel:q.methodLabel,onComplete:$e,onCancel:()=>$e(null)},q.id),(0,l.jsx)("div",{style:{display:q?"none":void 0},children:Mt})]}),Ie&&!q&&(0,l.jsx)(nn,{status:"processing"})]});return y==="redirect"?Lt:(0,l.jsx)(Wa,{state:se,placeholderTestId:"flopay-paypal-placeholder",borderRadius:W,children:Lt})}function zs(e){return e==="apple_pay"||e==="google_pay"}var Zu=200;function Qu({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,c.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function Vc({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:d,onErrorChange:p,onButtonClick:m,onDecline:b,onTechnicalFailure:P,runBeforeButtonClick:f,billingName:_,onBuyerIdentityReady:j,onLoadStateChange:W,placeholderBorderRadius:k,popupCapabilityOwner:T,externalTelemetryContext:y}){let K=fo(),{emitInstrument:Z}=(0,o.useContext)(kn),v=(0,lr.useStripe)(),ke=(0,lr.useElements)(),M=(0,o.useMemo)(()=>Mi(br(K),y),[y,K]),[se,be]=(0,o.useState)("loading");(0,o.useEffect)(()=>{W?.(se)},[se,W]);let[Ie,ye]=(0,o.useState)(!1);(0,o.useEffect)(()=>{qe.current=Ie},[Ie]);let vt=(0,o.useRef)(!(0,c.isValidEmail)(r?.trim())||!_?.trim()).current,{request:ut,collect:q,finish:We}=ca(),$e=(0,o.useRef)(null),Be=(0,o.useRef)(null),[we,X]=(0,o.useState)(0),[G,tt]=(0,o.useState)(()=>(0,c.shouldPreferWalletPopup)()),Ee=(0,o.useRef)(G),qe=(0,o.useRef)(!1),[te,V]=(0,o.useState)(!1),[Se,Q]=(0,o.useState)(()=>zi(e,t)?"blocked":"idle"),[pt,fe]=(0,o.useState)("google_pay"),Pe=(0,o.useRef)(null),Oe=(0,o.useRef)(!0),ce=(0,o.useRef)(!1),Ve=(0,o.useRef)("google_pay"),De=(0,o.useRef)("google_pay"),nt=(0,o.useRef)(null),ct=(0,o.useRef)(null),Y=(0,o.useRef)(new Set),Rt=(0,o.useRef)(null),Ht=(0,o.useRef)(null);(0,o.useEffect)(()=>(Oe.current=!0,()=>{Oe.current=!1;for(let u of Y.current)window.clearTimeout(u);Y.current.clear()}),[]);let Mt=(0,o.useRef)(new Map),{startAttempt:Lt,finishAttempt:he,invalidateAttempt:Me,isAttemptInvalidated:Ye,isAttemptCurrent:Pt,generationRef:ft}=Ba((u,S,I)=>{P?.(u,S,{...I,popupBlocked:I?.popupBlocked??(0,_e.isPopupBlockedError)(S),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),fe(u),V(!0),X(H=>H+1)},{onHandoffObserved:u=>{Ht.current=ft.current,T.markAvailable(),M?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ft.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})},defersMissingTerminal:zs,onMissingTerminalDeferred:(u,S)=>{let I=M?.now()??globalThis.performance?.now()??Date.now(),H=Rt.current,F=H?.generation===S?H.startedAt:I;M?.performance({stage:"overlay_return",durationMs:Math.max(0,I-F),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:S,...zs(u)?{walletType:u}:{}}),M?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{te&&Be.current?.focus()},[te,we]);let ze=(0,o.useRef)(0),Nt=(0,o.useRef)(!1),de=(0,o.useCallback)(()=>{if(ze.current>0){Nt.current=!0;return}X(u=>u+1)},[]),kt=(0,o.useCallback)(()=>{ze.current-=1,!(ze.current>0||!Nt.current)&&(Nt.current=!1,Oe.current&&X(u=>u+1))},[]),At=(0,o.useCallback)((u,S,I,H,F=!1)=>{Me(H),P?.(u,S,{code:I,popupBlocked:(0,_e.isPopupBlockedError)(S),telemetryReported:F,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),fe(u),V(!0),de()},[Me,P,de]),$=(0,o.useCallback)(u=>{M?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...zs(u)?{walletType:u}:{}}),P?.(u,new Error("The wallet click was not ready within the time the wallet allows."),{code:Iu,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),fe(u),V(!0)},[P,M]),ge=(0,o.useCallback)(()=>{window.setTimeout(()=>{($e.current?.querySelector("iframe")??$e.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{ce.current&&(ce.current=!1,ge())},[ge,we]);let Ut=(0,o.useCallback)(()=>{V(!1),p?.(null),ge()},[ge,p]),g=(0,o.useCallback)(()=>{Pe.current?.()},[]);(0,o.useEffect)(()=>{let u=null,S=()=>{u=null;let H=(0,c.shouldPreferWalletPopup)();H!==Ee.current&&(Ee.current=H,tt(H),!qe.current&&!Pt(ft.current)&&de())},I=()=>{u!==null&&window.clearTimeout(u),u=window.setTimeout(S,Zu)};return window.addEventListener("resize",I),()=>{window.removeEventListener("resize",I),u!==null&&window.clearTimeout(u)}},[ft,Pt,de]),(0,o.useEffect)(()=>{let u=zi(e,t);if(!u)return;let S=!1,I=!1,H=async()=>{if(!I){I=!0,S||Q("checking");try{let F=await Dc(v,u.clientSecret,Y.current);if(S)return;let B=Ns(F,u.providerObjectId,(0,c.isSetupIntentClientSecret)(u.clientSecret));if(B.kind==="confirmed"){if(!Oc(e,t,u.clientSecret))return;Pe.current=null,Q("idle"),d({id:B.paymentMethodId,type:"card",threeDSecureActionResultTokenId:B.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(B.kind==="terminal"){Ls(e,t,u.clientSecret),Pe.current=null,Q("idle"),fe(u.paymentMethodType),V(!0),de();return}Q("blocked")}catch{S||Q("blocked")}finally{I=!1}}};return Pe.current=H,Q("blocked"),()=>{S=!0,Pe.current===H&&(Pe.current=null)}},[t,d,de,e,v]);let J=(0,o.useCallback)(async u=>{let S=!1,I=!1,H=gt=>{S||I||(S=!0,u.paymentFailed({reason:"fail",...gt?{message:gt}:{}}))};if(!v||!ke){H();return}let F=Mt.current.get(we);if(F&&!Pt(F.generation)){Mt.current.delete(we),H();return}if(!F&&Ye()){H();return}if(F&&!he(F.generation)){H();return}F||(he(),Nt.current=!1);let B=u.expressPaymentType??F?.method??Ve.current,Ae=F??null,Vr=zc(B),$t;B==="apple_pay"?$t="apple_pay":B==="google_pay"&&($t="google_pay");let nr=F?.generation??ft.current,Te=M,kr=Te?.now()??globalThis.performance?.now()??Date.now(),Ur=new AbortController,Xr=!1,Or=!1,Kt=null,jr=e,an="processing",Er="other",_r="provider_runtime",vn,at=new Promise((gt,Et)=>{vn=Et}),Pr=window.setTimeout(()=>{Xr=!0,Ur.abort(),vn(Ni)},Tu),Xt=async(gt,Et,sn)=>{an=gt,Er=Et,_r=Et==="intent_create"||Et==="session_claim"?"transport_error":"provider_runtime";let zr=Te?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([sn,at])}finally{let Dr=Te?.now()??globalThis.performance?.now()??Date.now();Te?.performance({stage:gt,durationMs:Math.max(0,Dr-zr),durationMode:"machine",requestCategory:Et,paymentMethodCategory:"wallet",provider:"stripe",...Xr?{statusClass:"timeout"}:{}})}};try{if(ye(!0),p?.(null),!Ae&&f){let ve=await Xt("processing","other",f(Vr));if(!ve.proceed){H();return}Ae={accountPatch:ve.accountPatch,sessionId:ve.sessionId,nonce:ve.nonce}}let gt=Ae?.sessionId??e;jr=gt;let Et=Ae?.nonce??t,sn=nt.current??Ae?.accountPatch,zr=Kc({event:u,fallbackEmail:sn?.email??r,fallbackName:[sn?.firstName,sn?.lastName].join(" ").trim()||_});if(!(0,c.isValidEmail)(zr.email)){H("Buyer details are required."),q(Vs(B),zr).then(ve=>{ve&&(nt.current=ve)});return}nt.current=null;let Dr={...Ae?.accountPatch,...(0,En.compactBuyerIdentity)(zr,!0)};await Xt("processing","session_claim",Promise.resolve(j?.(zr)));let{error:ln}=await Xt("tokenization","provider_sdk",ke.submit());if(ln){H(),At(B,ln,"stripe_wallet_submit_failed",F?.generation);return}if(!gt)throw new Error("Missing sessionId or email for payment.");let Jr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:B,paymentMethodId:null,intentKind:a},Ir=JSON.stringify({sessionId:gt,nonce:Et??"",request:Jr}),cn=ct.current,Zr=cn?.retryIdentity===Ir?cn.authorizationAttemptId:(0,c.randomUuidV4)();ct.current={authorizationAttemptId:Zr,retryIdentity:Ir};let Lr=await Xt("processing","intent_create",qi(n,Z,gt,Et??"",{...Jr,authorizationAttemptId:Zr},{signal:Ur.signal}));if((0,c.isSettledSessionIntent)(Lr)){H(),d({type:"card",paymentMethodType:B},{accountPatch:Dr,paymentMethodCategory:"wallet",sessionId:gt,nonce:Et,settledProcessResponse:Lr.response});return}if(Lr.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let or=Lr.clientSecret,vr=Du({createdAt:Date.now(),sessionId:gt,...Et?{nonce:Et}:{},clientSecret:or,providerObjectId:Lr.providerObjectId,paymentMethodType:B,accountPatch:Dr});window.clearTimeout(Pr),Or=!0,Te?.performance({stage:"callback",durationMs:Math.max(0,(Te?.now()??globalThis.performance?.now()??Date.now())-kr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let ur=Te?.now()??globalThis.performance?.now()??Date.now(),pr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...$t?{walletType:$t}:{},attempt:nr},Tr=!1,Mr=null;Te?.log({name:"payment.provider_confirmation.started",...pr}),Kt=window.setTimeout(()=>{Kt!==null&&Y.current.delete(Kt),Tr=!0;let ve=Te?.now()??globalThis.performance?.now()??Date.now();Te?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...pr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ve-ur),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Te?.flush?.().catch(()=>{}),Mr?.()},Mu),Y.current.add(Kt);let Qr=(ve,Gt)=>{Kt!==null&&(window.clearTimeout(Kt),Y.current.delete(Kt),Kt=null);let zt=Te?.now()??globalThis.performance?.now()??Date.now(),xt=Math.max(0,zt-ur),z=ve;Tr&&(ve==="resolved"?z="resolved_late":ve==="returned_error"?z="returned_error_late":z="rejected_late");let bn=Gt??(ve==="resolved"?"approved":"provider_error");return Te?.log({name:"payment.provider_confirmation.returned",...pr,operationOutcome:z,terminalReason:bn}),Te?.performance({...pr,durationMs:xt,durationMode:"buyer",operationOutcome:z,terminalReason:bn}),{durationMs:xt,operationOutcome:z,terminalReason:bn}},mr=!1,tr=!1,Nr=ve=>{if(!ve||typeof ve!="object")return null;let Gt=ve;if(Gt.error)return null;let zt=Gt.setupIntent??Gt.paymentIntent,xt=Ns(zt??null,void 0,!!Gt.setupIntent);return xt.kind==="confirmed"?xt:null},Ze=ve=>{if(mr||F&&ft.current!==F.generation)return;let Gt=Nr(ve);if(!Gt)return;if(vr&&!Oc(gt,Et,or)){mr=!0;return}let{intentId:zt,paymentMethodId:xt}=Gt;mr=!0,tr=!0,ct.current=null,Pe.current=null,Oe.current&&(Q("idle"),ye(!1));let z=`${Wc}:${gt}`;cr(z,{createdAt:Date.now(),sessionId:gt,nonce:Et,accountPatch:Dr,paymentMethodId:xt,providerIntentId:zt,paymentMethodType:B});try{d({id:xt,type:"card",threeDSecureActionResultTokenId:zt},{accountPatch:Dr,paymentMethodCategory:"wallet",sessionId:gt,nonce:Et})}finally{cr(z)}},Cn=!1;Mr=async()=>{if(!(Cn||mr||tr)){Cn=!0,Oe.current&&Q("checking");try{let ve=await Dc(v,or,Y.current);if(mr||tr)return;let Gt=(0,c.isSetupIntentClientSecret)(or),zt=Ns(ve,Lr.providerObjectId,Gt);if(zt.kind==="confirmed"){Ze(Gt?{setupIntent:ve}:{paymentIntent:ve});return}if(zt.kind==="terminal"){if(tr=!0,Ls(gt,Et,or),ct.current=null,Pe.current=null,!Oe.current)return;Q("idle"),H(),At(B,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",F?.generation,!0);return}Oe.current&&!tr&&(Q("blocked"),ye(!1))}catch{Oe.current&&!tr&&(Q("blocked"),ye(!1))}finally{Cn=!1}}},Pe.current=Mr;let O,Qe;try{I=!0,ze.current+=1;let ve;try{ve=await((0,c.isSetupIntentClientSecret)(or)?v.confirmSetup({elements:ke,clientSecret:or,redirect:"if_required"}):v.confirmPayment({elements:ke,clientSecret:or,redirect:"if_required"}))}finally{kt()}if(!ve||typeof ve!="object")throw new Ya(Ou(ve));if(O=ve,!O.error&&!Nr(O))throw new Ya("confirmation_result_unconfirmed");Qe=Qr(O.error?"returned_error":"resolved",O.error&&(0,_e.isProviderDecline)(O.error)?"provider_declined":void 0)}catch(ve){let Gt=ve instanceof Ya?ve.reason:void 0,zt=Gt!==void 0,xt=Qr(zt?"returned_error":"rejected");if(Te?.error({...zt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Gt}:_s(ve),...pr,operationOutcome:xt.operationOutcome,durationMs:xt.durationMs,statusClass:"unknown",terminalReason:xt.terminalReason}),!Oe.current||mr)return;await Mr?.();return}let ue=O.error;if(ue){if(!Oe.current||mr)return;if((0,_e.isProviderDecline)(ue)){tr=!0,Ls(gt,Et,or),ct.current=null,Pe.current=null,Q("idle"),Mt.current.get(we)===F&&Mt.current.delete(we);let ve=ue.message??"Your payment was declined.";p?.(ve),b?.(Cr(Vr,ve,{code:(0,_e.getProviderErrorCode)(ue),declineCode:(0,_e.getProviderDeclineCode)(ue)})),Vi({billingApiUrl:n,sessionId:gt,nonce:Et,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:B,providerDeclineReason:(0,_e.getProviderErrorCode)(ue)??"provider_declined",...Lr.intentKind==="payment"&&Lr.providerObjectId.startsWith("pi_")?{providerIntentId:Lr.providerObjectId}:{}}})}else Te?.error({..._s(ue),...pr,operationOutcome:Qe.operationOutcome,durationMs:Qe.durationMs,statusClass:"unknown",terminalReason:Qe.terminalReason}),await Mr?.();return}if(Ze(O),!mr)throw new Error("Invalid provider returned for APM intent")}catch(gt){if(gt===Ni){let Et=Te?.now()??globalThis.performance?.now()??Date.now();Te?.error({errorCode:Nu(Er),stage:an,requestCategory:Er,paymentMethodCategory:"wallet",provider:"stripe",...$t?{walletType:$t}:{},operationOutcome:"watchdog_expired",checkoutSessionId:jr,durationMs:Math.max(0,Et-kr),statusClass:"timeout",failureCategory:_r,attempt:nr,terminalReason:"provider_error"}),Te?.flush?.().catch(()=>{})}H(),At(B,gt,gt===Ni?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",F?.generation,gt===Ni)}finally{if(window.clearTimeout(Pr),Kt!==null&&(window.clearTimeout(Kt),Y.current.delete(Kt)),!Or){let gt=Te?.now()??globalThis.performance?.now()??Date.now();Te?.performance({stage:"callback",durationMs:Math.max(0,gt-kr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Xr?{statusClass:"timeout"}:{}})}Oe.current&&ye(!1)}},[v,ke,e,t,r,_,q,j,n,Z,a,d,p,b,f,At,kt,he,Pt,Ye,ft,M,we]),He=(0,o.useMemo)(()=>xi(s),[s]),L=(0,o.useMemo)(()=>s.map(c.stripeExpressMethodToOptionKey),[s]),mt=(0,o.useMemo)(()=>(0,l.jsx)(lr.ExpressCheckoutElement,{onReady:u=>{be(ja(u,L))},onLoadError:u=>{be("load_error"),$s(M,"stripe","wallet","provider_error")},onClick:async u=>{let S=M?.now()??globalThis.performance?.now()??Date.now();Ve.current=u.expressPaymentType,De.current=zc(u.expressPaymentType);let I=!0,H=window.setTimeout(()=>{I=!1,u.reject(),$(u.expressPaymentType)},_u),F=f?await f(De.current,{abandoned:()=>!I}):{proceed:!0};if(window.clearTimeout(H),!I)return;if(!F.proceed){Mt.current.delete(we),u.reject();return}let B=Lt(u.expressPaymentType);Nt.current=!1,Rt.current={generation:B,startedAt:S},Mt.current.set(we,{generation:B,method:u.expressPaymentType,accountPatch:F.accountPatch,sessionId:F.sessionId,nonce:F.nonce}),V(!1),M?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:B,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),m?.(De.current),u.resolve()},onConfirm:J,onCancel:()=>{let u=Mt.current.get(we);Mt.current.delete(we);let S=Rt.current,I=M?.now()??globalThis.performance?.now()??Date.now();if(u&&S?.generation===u.generation&&(0,c.isWalletSheetRefusedForWindowSize)({method:u.method,elapsedMs:I-S.startedAt,handoffObserved:Ht.current===u.generation})){M?.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"}),ct.current=null,At(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}M?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),Me(u?.generation),ct.current=null,V(!1),ce.current=!0,de()},options:{...Fi,paymentMethods:He,emailRequired:vt,billingAddressRequired:vt}},we),[L,He,J,Me,m,vt,At,$,de,f,Lt,we,M]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Wa,{state:se,placeholderTestId:"flopay-wallet-placeholder",borderRadius:k,children:(0,l.jsxs)("div",{ref:$e,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[te&&(0,l.jsxs)("button",{ref:Be,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ut,style:qs,children:["Try ",Vs(pt)," again"]}),Se!=="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:g,disabled:Se==="checking",style:qs,children:Se==="checking"?"Checking payment status\u2026":"Check payment status"})]}),ut&&(0,l.jsx)(da,{identity:ut.identity,methodLabel:ut.methodLabel,onComplete:We,onCancel:()=>We(null)},ut.id),(0,l.jsxs)("div",{style:{display:ut||Se!=="idle"?"none":void 0},children:[(0,l.jsx)(Qu,{active:G}),mt]})]})}),Ie&&(0,l.jsx)(nn,{status:"processing"})]})}function Gc(e,t,r){let n=(0,c.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function js({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:d,onTokenizedBody:p,onErrorChange:m,onDecline:b,onCancel:P,runBeforeButtonClick:f,onButtonClick:_,isProcessing:j,submitButtonColor:W,submitButtonBorderRadius:k,submitButtonStyle:T,errorText:y}){let K=fo(),{emitInstrument:Z}=(0,o.useContext)(kn),v=(0,lr.useStripe)(),ke=(0,lr.useElements)(),[M,se]=(0,o.useState)(!1),be=(0,o.useRef)(!1),[Ie,ye]=(0,o.useState)(!1),[vt,ut]=(0,o.useState)("loading"),[q,We]=(0,o.useState)(""),$e=!(0,c.isValidEmail)(n?.trim()),Be=!$e||(0,c.isValidEmail)(q.trim()),we=(0,o.useCallback)(async()=>{if(!v||!ke||j||be.current||!Ie)return;be.current=!0,se(!0);let X=f?await f("card"):{proceed:!0};if(!X.proceed){be.current=!1,se(!1);return}_?.("card");let G=X.sessionId??t,tt=X.nonce??r,Ee=(0,la.splitFullName)(a?.trim()),qe=(0,En.compactBuyerIdentity)({email:X.accountPatch?.email?.trim()||n?.trim()||q.trim(),firstName:X.accountPatch?.firstName?.trim()||Ee.firstName,lastName:X.accountPatch?.lastName?.trim()||Ee.lastName}),te=qe.email,V=(0,En.compactBuyerIdentity)({...X.accountPatch,...qe});try{if(m?.(null),!(0,c.isValidEmail)(te))throw new Error("A valid email address is required for payment.");await s?.(qe);let Se=await ke.submit();if(Se.error){m?.(Se.error.message??"Payment failed.");return}let Q=[qe.firstName,qe.lastName].filter(Boolean).join(" "),pt=await v.createPaymentMethod({elements:ke,params:{billing_details:{email:te,...Q?{name:Q}:{}}}});if(pt.error||!pt.paymentMethod){m?.(pt.error?.message??"Failed to create payment method.");return}let fe=pt.paymentMethod;if(!G||!te)throw new Error("Missing sessionId or email for payment.");let Pe=fe.type||e,Oe=await qi(d,Z,G,tt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Pe,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(Oe)){p({type:"card",gateway:"stripe",paymentMethodType:Pe},{accountPatch:V,paymentMethodCategory:"apm",sessionId:G,nonce:tt,settledProcessResponse:Oe.response});return}if(Oe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ce=Oe.clientSecret;cr(no,{clientSecret:ce,sessionId:G,nonce:tt,accountPatch:V,paymentMethodId:fe.id,paymentMethodType:fe.type??e,gateway:"stripe"});let{error:Ve,paymentIntent:De}=await v.confirmPayment({clientSecret:ce,confirmParams:{return_url:window.location.href,payment_method:fe.id},redirect:"if_required"});if(Ve){cr(no);let Y=Ve.message??"Payment failed.";m?.(Y),b?.(Cr("card",Y,{code:Ve.code})),await Vi({billingApiUrl:d,sessionId:G,nonce:tt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ve.code??"provider_declined"}});return}let nt=De?.status;if(!Ma(nt)){cr(no);let Y=nt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(Y),b?.(Cr("card",Y,{code:nt??"missing_payment_intent"}));return}cr(no);let ct=typeof De?.payment_method=="string"?De.payment_method:De?.payment_method?.id;p({id:ct??fe.id,type:"card",threeDSecureActionResultTokenId:De?.id,gateway:"stripe",paymentMethodType:fe.type??e},{accountPatch:V,paymentMethodCategory:"apm",sessionId:G,nonce:tt})}catch(Se){m?.(Se instanceof Error?Se.message:"Payment failed. Please try again.")}finally{be.current=!1,se(!1)}},[v,ke,j,Ie,f,_,t,r,n,a,q,s,d,Z,e,p,m,b]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[$e&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:$e&&(0,l.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,l.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:q,onChange:X=>We(X.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(lr.PaymentElement,{onReady:()=>ut("ready"),onLoadError:()=>{ut("load_error"),$s(br(K),"stripe","apm")},onChange:X=>{ye(!!X.complete)},options:{layout:Bi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,c.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,l.jsx)(Oi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{we()},disabled:!Ie||!Be||M||j||vt!=="ready",color:W,borderRadius:k,style:T,children:M?"Processing\u2026":`Pay with ${(0,c.getStripeMethodDisplayName)(e)}`}),y&&(0,l.jsx)(ma,{margin:"0.75rem 0 0",children:y})]})}function jc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:d,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:b,onTokenizedBody:P,onErrorChange:f,onButtonClick:_,onDecline:j,runBeforeButtonClick:W,onLoadStateChange:k,isProcessing:T=!1,submitButtonColor:y="#4A49FF",submitButtonBorderRadius:K=8,submitButtonStyle:Z,buttonAppearance:v,themeId:ke,onExpandApm:M,expandedApmMethod:se}){let{emitInstrument:be}=(0,o.useContext)(kn),[Ie,ye]=(0,o.useState)(null),[vt,ut]=(0,o.useState)(null),q=(0,o.useRef)(!1),{request:We,collect:$e,finish:Be}=ca();(0,o.useEffect)(()=>{d.length>0&&p?k?.("ready"):p||k?.("loading")},[d.length,p,k]);let we=(0,o.useCallback)(async te=>{if(!p||q.current||T)return;q.current=!0,ut(te);let V=W?await W("card"):{proceed:!0};if(!V.proceed){q.current=!1,ut(null);return}_?.("card");let Se=V.sessionId??e,Q=V.nonce??t,pt=(0,la.splitFullName)([V.accountPatch?.firstName,V.accountPatch?.lastName].filter(Boolean).join(" ")||n),fe=(0,En.compactBuyerIdentity)({email:V.accountPatch?.email?.trim()||r?.trim(),firstName:V.accountPatch?.firstName?.trim()||pt.firstName,lastName:V.accountPatch?.lastName?.trim()||pt.lastName});if(!(0,c.isValidEmail)(fe.email)){ut(null);let ce=await $e((0,c.getStripeMethodDisplayName)(te),fe);if(!ce){q.current=!1;return}fe=ce,ut(te)}let Pe=fe.email,Oe=(0,En.compactBuyerIdentity)({...V.accountPatch,...fe});try{if(f?.(null),!Se||!(0,c.isValidEmail)(Pe))throw new Error("Missing sessionId or email for payment.");await a?.(fe);let ce=await qi(s,be,Se,Q??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(ce)){P({type:"card",gateway:"stripe",paymentMethodType:te},{accountPatch:Oe,paymentMethodCategory:"apm",sessionId:Se,nonce:Q,settledProcessResponse:ce.response});return}if(ce.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ve=ce.clientSecret;cr(no,{clientSecret:Ve,sessionId:Se,nonce:Q,accountPatch:Oe,paymentMethodType:te,gateway:"stripe"});let{error:De,paymentIntent:nt}=await p.confirmPayment({clientSecret:Ve,confirmParams:{return_url:window.location.href,payment_method_data:{type:te,billing_details:{name:[fe.firstName,fe.lastName].filter(Boolean).join(" "),...Pe?{email:Pe}:{}}}},redirect:"if_required"});if(De){cr(no);let Rt=De.message??"Payment failed.";f?.(Rt),j?.(Cr("card",Rt,{code:De.code})),await Vi({billingApiUrl:s,sessionId:Se,nonce:Q,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,providerDeclineReason:De.code??"provider_declined"}});return}let ct=nt?.status;if(!Ma(ct)){cr(no);let Rt=ct==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(Rt),j?.(Cr("card",Rt,{code:ct??"missing_payment_intent"}));return}cr(no);let Y=typeof nt?.payment_method=="string"?nt.payment_method:nt?.payment_method?.id;P({id:Y??nt?.id,type:"card",threeDSecureActionResultTokenId:nt?.id,gateway:"stripe",paymentMethodType:te},{accountPatch:Oe,paymentMethodCategory:"apm",sessionId:Se,nonce:Q})}catch(ce){f?.(ce instanceof Error?ce.message:"Payment failed. Please try again.")}finally{q.current=!1,ut(null)}},[p,T,W,_,e,t,r,$e,s,be,n,a,P,f,j]),[X,G]=(0,o.useState)(null),tt=M?se??null:X,Ee=(0,o.useCallback)(te=>{q.current||T||tt&&tt!==te||((0,c.needsStripeMethodExplicitConfirm)(te)?M?M(te):G(te):we(te))},[tt,T,we,M]),qe=(0,o.useMemo)(()=>X?Gc(m,X,b):null,[X,m,b]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:We?(0,l.jsx)(da,{identity:We.identity,methodLabel:We.methodLabel,onComplete:Be,onCancel:()=>Be(null)},We.id):d.map(te=>{let V=se===te,Se=vt===te,Q=vt!==null&&vt!==te||se!=null&&se!==te;return(0,l.jsxs)(o.default.Fragment,{children:[(0,l.jsx)(Ai,{method:te,themeId:ke,submitting:Se,disabled:Q,highlighted:V,hasNextStep:(0,c.needsStripeMethodExplicitConfirm)(te),onClick:()=>Ee(te),backgroundColor:v?.backgroundColor,borderColor:v?.borderColor,textColor:v?.textColor,borderRadius:v?.borderRadius,fontFamily:v?.fontFamily}),!M&&X===te&&qe&&p&&(0,l.jsx)(lr.Elements,{stripe:p,options:qe,children:(0,l.jsx)(js,{method:te,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:P,onErrorChange:f,onDecline:j,onCancel:()=>G(null),runBeforeButtonClick:W,onButtonClick:_,isProcessing:T,submitButtonColor:y,submitButtonBorderRadius:K,submitButtonStyle:Z})},te)]},te)})})}function ep({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:d,onError:p,onDecline:m,onCancel:b,onTokenizedBody:P,firstName:f,lastName:_,chv:j,className:W,submitLabel:k,isProcessing:T,error:y,onErrorChange:K,showPayPal:Z=!0,showStripe:v=!0,walletPresentation:ke="auto",enabledPaymentMethods:M,enabledPaymentMethodCountries:se,showApplePay:be=!0,showGooglePay:Ie=!0,layout:ye="default",paymentMethodLayout:vt,moreOptionsLabel:ut,theme:q,buttonsTheme:We,buttonsStyles:$e,appearance:Be,cardButtonContent:we,cardBackButtonContent:X,cardTitleContent:G,showSecurityFooter:tt,onButtonClick:Ee,onBeforeButtonClick:qe,onBuyerIdentityReady:te,enableAVS:V,cardFieldOrder:Se,cardAutoFocus:Q,onCardFieldsReady:pt,onCardFieldsFailed:fe,cardFieldsTimeoutMs:Pe,cardPreFormSlot:Oe,avsLayout:ce="row",country:Ve,zip:De,addressLine1:nt,addressLine2:ct,city:Y,state:Rt,onCountryChange:Ht,onZipChange:Mt,avsCheck:Lt,checkoutType:he,checkoutLayout:Me,totalAmount:Ye=0,currency:Pt="usd",initialCardOpen:ft=!1,directPaypal:ze,isSubscription:Nt=!1,session:de,dataAttachmentPending:kt=!1,dataAttachmentRequiresIdentity:At=!1,debug:$=!1}){let ge=fo(),Ut=Pi(),g=(0,o.useContext)(zn),{emitInstrument:J}=(0,o.useContext)(kn),He=(0,o.useRef)(null);He.current||(He.current=Ci());let L=He.current,[,mt]=(0,o.useState)(0),u=(0,o.useRef)(null);u.current||(u.current=(0,eo.detectPayPalEnvironment)());let S=u.current,I=(0,o.useMemo)(()=>({browser:S,capability:L,presentationMode:"popup"}),[S,L]),H=de??g.session,F=(0,o.useMemo)(()=>({futureUse:H?.futureUse,futureUseUnsupported:H?.futureUseUnsupported}),[H?.futureUse,H?.futureUseUnsupported]),B=H?.gateways?.paypal?.providerObjectType??ze?.providerObjectType,Ae=kt||g.claimPending===!0,Vr=At||g.claimRequiresIdentity===!0,$t=Ae&&!Vr,nr=cc(),Te=r||nr,kr=xc({rules:vt,sessionId:e,nonce:t,billingApiUrl:Te,waitForSession:$t}),Ur=kr?.order??null,[Xr,Or]=(0,o.useState)(!1),Kt=(0,o.useMemo)(()=>Ur?(0,c.keyPaymentMethodOrder)(Ur):null,[Ur]),jr=Ur!==null&&(0,c.isCardFormFirst)(Ur),[an,Er]=(0,o.useState)(!1),[_r,vn]=(0,o.useState)(null),[at,Pr]=(0,o.useState)(Ve??""),[Xt,gt]=(0,o.useState)(De??""),[Et,sn]=(0,o.useState)(nt??""),[zr,Dr]=(0,o.useState)(ct??""),[ln,Jr]=(0,o.useState)(Y??""),[Ir,cn]=(0,o.useState)(Rt??""),[Zr,Lr]=(0,o.useState)(""),[or,vr]=(0,o.useState)({}),ur=(0,o.useRef)(De??""),pr=(0,o.useRef)(Ve??""),Tr=(0,o.useRef)(nt??""),Mr=(0,o.useRef)(ct??""),Qr=(0,o.useRef)(Y??""),mr=(0,o.useRef)(Rt??""),tr=(0,o.useRef)(""),Nr=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(C,U,Ce,ee,Fe)=>{if(Nr.current[C])return;let jt=U?.trim();!jt||jt===Ce.current||(Ce.current=jt,ee(jt),Fe?.(jt))};i("country",Ve,pr,Pr,Ht),i("zip",De,ur,gt,Mt),i("addressLine1",nt,Tr,sn),i("addressLine2",ct,Mr,Dr),i("city",Y,Qr,Jr),i("state",Rt,mr,cn)},[Ve,De,nt,ct,Y,Rt,Ht,Mt]);let Ze=(0,o.useMemo)(()=>(0,c.resolveAVSConfig)(V),[V]),Cn=Ze!==null,O=(0,o.useMemo)(()=>(0,c.isAuthorizationOnlySession)(de),[de]),Qe=(0,c.isMountableVaultBlock)(de?.vault),ue=!!de?.gateways?.pcivault,ve=(0,Un.hasServerSideCardGateway)(de),zt=!!(de?.gateways?.stripe?.enabledPaymentMethods??M)?.includes("card")||(0,Un.canRecoverHostedCardForm)(de),xt=Qe||zt||ue,z=!!(v&&xt&&e),[bn,jo]=(0,o.useState)(()=>ye!=="buttons"||ft?e??null:null),[Io,Sn]=(0,o.useState)(0),xn=ye!=="buttons"||ft||!!e&&bn===e,dn=de?.captureMethod,en=(0,o.useRef)(ge);(0,o.useEffect)(()=>{en.current=ge},[ge]);let ar=(0,o.useRef)(Pe);ar.current=Pe;let Fn=(0,o.useRef)({onCardFieldsReady:pt,onCardFieldsFailed:fe,emitInstrument:J});Fn.current={onCardFieldsReady:pt,onCardFieldsFailed:fe,emitInstrument:J};let[un,Bn]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!z||!e||!xn){Bn(null);return}let i=en.current?en.current.cardCapture({sessionId:e,captureMethod:dn,cardFieldsTimeoutMs:ar.current}):new Wn.PciVaultCardCapture({sessionId:e,captureMethod:dn,billingApiUrl:Te,telemetry:n,cardFieldsTimeoutMs:ar.current}),C=i.onCardFields?.(U=>{let Ce=Fn.current;Ce.emitInstrument?.((0,c.cardFieldsInstrumentSource)(U)),U.type==="card_fields_ready"?(0,c.invokeMerchantCallback)(()=>Ce.onCardFieldsReady?.(U)):(0,c.invokeMerchantCallback)(()=>Ce.onCardFieldsFailed?.(U))});return Bn({sessionId:e,captureMethod:dn,billingApiUrl:Te,telemetry:n,capture:i}),()=>{C?.(),i.unmount()}},[z,e,xn,dn,Te,n]);let Ft=z&&e&&xn&&un?.sessionId===e&&un.captureMethod===dn&&un.billingApiUrl===Te&&un.telemetry===n?un.capture:null,tn=(0,o.useMemo)(()=>{let i=at,C=Ze?(0,c.isAVSFieldVisible)(Ze.postal_code,i):!1;return Yu(i,Xt,C)},[Ze,at,Xt]),{avsInvalid:pn,invalidAvsFields:io}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!z||!Ze)return{avsInvalid:!1,invalidAvsFields:i};let C=at,U=(Fe,jt)=>(0,c.isAVSFieldVisible)(Fe,C)&&!jt.trim(),Ce={line1:U(Ze.address_line_1,Et),city:U(Ze.city,ln),state:U(Ze.state,Ir),zip:tn.empty||tn.malformed};return{avsInvalid:Ce.line1||Ce.city||Ce.state||Ce.zip,invalidAvsFields:Ce}},[z,Ze,at,Et,ln,Ir,tn]),[mn,On]=(0,o.useState)(!1),[so,$n]=(0,o.useState)(!1),[Hn,Kn]=(0,o.useState)(!1),[lo,Wo]=(0,o.useState)({line1:!1,city:!1,state:!1}),Gn=(0,o.useRef)(!1),co=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Yn=(0,o.useRef)(!1),qt=(0,o.useCallback)(i=>{co.current[i]=!0,Yn.current=!0},[]),Xn=(0,o.useCallback)(i=>!Gn.current&&co.current[i],[]),yn=(0,o.useCallback)(i=>{Xn(i)&&Wo(C=>C[i]?C:{...C,[i]:!0})},[Xn]),[wn,fn]=(0,o.useState)(()=>(0,c.resolveVaultMountOptions)(de?.vault,{billingApiUrl:Te,sessionId:e,nonce:t})),[dt,Ar]=(0,o.useState)(ft&&xt?"card":"buttons"),[Jt,A]=(0,o.useState)(null),D=dt==="expanding"||dt==="card",ne=de?.gateways?.stripe&&!ve?"stripe":void 0,Re=(0,o.useCallback)(()=>{J?.({class:"card_surface",provider:ne})},[ne,J]),_t=(0,o.useCallback)(()=>{Or(!0),J?.({class:"more_options"})},[J]),Zt=(0,o.useRef)(null),xe=(0,o.useCallback)(i=>{Zt.current&&clearTimeout(Zt.current),Zt.current=setTimeout(()=>{Zt.current=null,i()},Xa)},[]);(0,o.useEffect)(()=>()=>{Zt.current&&clearTimeout(Zt.current)},[]);let it=(0,o.useRef)(!1),[re,et]=(0,o.useState)(0),pe=(0,o.useRef)(null),yt=(0,o.useCallback)(()=>{Re(),jo(e??null),it.current&&(it.current=!1,et(i=>i+1)),Sn(i=>i+1),Ar("expanding"),xe(()=>Ar("card"))},[xe,Re,e]),le=(0,o.useCallback)(()=>{Ar("collapsing"),xe(()=>Ar("buttons"))},[xe]),h=(0,o.useCallback)(i=>{A(i),Ar("apm-expanding"),xe(()=>Ar("apm-form"))},[xe]),w=(0,o.useCallback)(()=>{Ar("apm-collapsing"),xe(()=>{Ar("buttons"),A(null)})},[xe]);(0,o.useEffect)(()=>{ye==="buttons"&&ft&&xt&&(jo(e??null),Ar("card"))},[ye,ft,xt,e]);let[N,ie]=(0,o.useState)(null),oe=(0,o.useRef)(null),[ae,Bt]=(0,o.useState)(0);(0,o.useEffect)(()=>{ae!==0&&oe.current?.focus()},[ae]);let Ot=(0,o.useRef)(!1),st=(0,o.useRef)(null),Ct=(0,o.useRef)("idle"),[It,Xe]=(0,o.useState)(!1),Ke=(0,o.useRef)(It);Ke.current=It;let[Le,Vt]=(0,o.useState)(()=>ze?.existingOrderId?{orderId:ze.existingOrderId,attempts:1}:null),wt=(0,o.useRef)(Le);(0,o.useEffect)(()=>{wt.current=Le},[Le]);let Wr=(0,o.useRef)(null),Qt=(0,o.useMemo)(()=>{if(te||g.claimBuyerIdentity||de?.buyerIdentified!==!1||!e||!t)return;let i=`${Te}|${e}|${t}`;Wr.current?.key!==i&&(Wr.current={key:i,claim:ia(new Wn.PaymentAPI(Te,{telemetry:!1}),e,t,{...s?{userId:s}:{},...f?{firstName:f}:{},..._?{lastName:_}:{}})});let C=Wr.current.claim;return async U=>{await C(U)}},[te,g.claimBuyerIdentity,de?.buyerIdentified,e,t,Te,s,f,_]),$r=te??g.claimBuyerIdentity??Qt,Dn=y??_r,$o=(0,o.useMemo)(()=>(0,c.resolveTheme)(q),[q]),rt=(0,o.useMemo)(()=>{let i=$o?.buttonsLayout??(0,c.resolveButtonsLayoutTheme)(We);return $e?{...i,...$e,cardButton:{...i.cardButton,...$e.cardButton},cardFormContainer:{...i.cardFormContainer,...$e.cardFormContainer},backButton:{...i.backButton,...$e.backButton},backButtonIcon:{...i.backButtonIcon,...$e.backButtonIcon},submitButton:{...i.submitButton,...$e.submitButton},title:{...i.title,...$e.title}}:i},[$o,We,$e]),Ho=Be??$o?.appearance,Pd=(0,o.useMemo)(()=>(0,c.computeVaultCardThemeColors)({appearance:Ho,buttonsStyles:rt,layout:ye}),[Ho,rt,ye]),vd=g.inlineSessionPatchProcessing??!1,ir=(T??an)||vd,Co=Te.replace(/\/+$/,""),Tt=(0,o.useMemo)(()=>Es({userId:s,email:a,firstName:f,lastName:_,country:Ve,zip:De},or),[s,a,f,_,Ve,De,or]),Ko=[Tt.firstName,Tt.lastName].filter(i=>!!i?.trim()).join(" "),al=!(0,c.isValidEmail)(Tt.email?.trim()),Zi=(0,o.useRef)(null);z&&Zi.current===null&&(Zi.current=al);let bo=z&&(Zi.current??al),Qi=(0,o.useMemo)(()=>Xu(Zr,bo),[Zr,bo]),Go=Qi.empty||Qi.malformed,gn=(0,o.useMemo)(()=>ge?ge.getRawProvider():null,[ge]),il=(0,o.useMemo)(()=>Ut?Ut.getRawProvider():null,[Ut]),va=Ye||100,Yo=Pt.toLowerCase(),es=(0,o.useMemo)(()=>Ho?(0,Wn.toStripeAppearance)(Ho):null,[Ho]),Xo=es,sl=(0,o.useMemo)(()=>{let i=es??{},C=i.rules??{};return{...i,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[es]),ll=(0,o.useMemo)(()=>({...ic(Ye,H?.captureMethod,F),currency:Yo,...Xo?{appearance:Xo}:null}),[Ye,Yo,H?.captureMethod,F,Xo]),ts=(0,c.resolveSetupFutureUsage)(F,"paypal","paypal"),cl=(0,o.useMemo)(()=>({mode:"payment",amount:va,currency:Yo,captureMethod:"manual",...ts?{setupFutureUsage:ts}:null,...Xo?{appearance:Xo}:null}),[va,Yo,ts,Xo]),Ne=(0,o.useCallback)(i=>{vn(i),K?.(i)},[K]),dl=(0,o.useRef)(0);(0,o.useEffect)(()=>{re!==dl.current&&(dl.current=re,Ne(null))},[re,Ne]);let rs=(0,o.useRef)(""),[ul,Cd]=(0,o.useState)(!1),ns=(0,o.useCallback)(()=>{Cd(!0)},[]);(0,o.useEffect)(()=>{if(!z||!bo||!$r||!ul||Go||rs.current)return;let i=(0,En.compactBuyerIdentity)({email:(0,c.isValidEmail)(Tt.email?.trim())?Tt.email?.trim():tr.current.trim(),firstName:Tt.firstName?.trim(),lastName:Tt.lastName?.trim()});rs.current=JSON.stringify(i),vr(C=>({...C,...i})),Promise.resolve($r(i)).catch(C=>{rs.current="",Ne(C instanceof Error?C.message:"Failed to attach buyer details.")})},[z,bo,$r,ul,Go,Tt.email,Tt.firstName,Tt.lastName,Ne]),(0,o.useEffect)(()=>{if(!z||!Ft)return;let i=Q!==!1&&Ze==null&&!bo;Ft.setCardFieldOrder?.(Se??null,i)},[z,Ft,Se,Q,Ze,bo]),(0,o.useEffect)(()=>{(dt==="expanding"||dt==="collapsing"||dt==="apm-expanding"||dt==="apm-collapsing")&&Ne(null)},[dt,Ne]);let Jn=(0,o.useCallback)((i,C,U)=>{m?.(Cr(i,C,U))},[m]),pl=(0,o.useRef)(dt);pl.current=dt;let[ml]=(0,o.useState)(Si),yl=(0,o.useCallback)(()=>{let i=pl.current;if(ye==="buttons"&&(i==="card"||i==="expanding"))return!0;let C=Ct.current;return C==="validation-window"||C==="processing"||Ke.current},[ye]),fl=(0,o.useCallback)((i,C,U)=>{ml.take(e)&&br(ge)?.log(Lo({...I,presentationMode:U?.presentationMode??"popup"},{name:bi,stage:"recovery",reason:"other_method_active",provider:U?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:U?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[I,ge,ml,e]),ti=(0,o.useCallback)((i,C,U)=>{U?.telemetryReported||br(ge)?.error(Lo({...I,presentationMode:U?.presentationMode??"popup"},{errorCode:C?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:U?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:U?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:U?.terminalReason??(C?"popup_blocked":"provider_error")}))},[I,ge]),Jo=(0,o.useCallback)((i,C,U)=>{let Ce=U?.popupBlocked??(0,_e.isPopupBlockedError)(C);if(yl()){ti(i,Ce,U),fl(i,C,U);return}if(C instanceof c.FloPayError&&C.code==="checkout_processing_timeout"){ti(i,!1,U),ie(null),ye==="buttons"&&(Ar("buttons"),A(null)),Ne(C.message),p?.(C);return}Ce&&L.markBlocked()&&mt(bt=>bt+1);let ee=Vs(i),Fe=U?.code===c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,c.buildWalletSheetWindowMessage)(ee):(0,_e.buildExternalMethodRecoveryMessage)(ee,Ce,S.inAppBrowser),jt=(0,_e.getProviderErrorCode)(C),Wt=(jt?.toLowerCase()==="error"?void 0:jt)??(0,_e.sanitizeExternalFailureCode)(U?.code)??"external_payment_method_failed",ot=new c.FloPayError(Fe,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:Wt,popupBlocked:Ce,inAppBrowser:S.inAppBrowser,appFamily:S.appFamily,popupCapability:L.current(),presentationMode:U?.presentationMode??"popup"}});ti(i,Ce,U),ie(null),ye==="buttons"&&(Ar("buttons"),A(null)),Ne(Fe),p?.(ot),console.error("[FloPay] External payment method failed:",{method:i,code:Wt,popupBlocked:Ce})},[S,yl,ye,p,L,fl,ti,Ne]);(0,o.useEffect)(()=>{if(!z||!e){fn(null);return}let i={billingApiUrl:Co,sessionId:e,nonce:t},C=(0,c.resolveVaultMountOptions)(de?.vault,i);if(C){fn(C);return}if(!xn){fn(null);return}let U=`${Co}\0${e}\0${t??""}`,Ce=pe.current;if(Ce&&Ce.key===U){fn(Ce.mount);return}fn(null);let ee=!0;return new Wn.PaymentAPI(Co).getVaultCapture(e,t).then(Fe=>{if(!ee)return;let jt=(0,c.resolveVaultMountOptions)(Fe,i);jt?.verificationRequired&&!Fe.html&&(pe.current={key:U,mount:jt}),jt?fn(jt):Ne("Failed to load the secure card form.")}).catch(Fe=>{ee&&Ne(Fe instanceof Error?Fe.message:"Failed to load the secure card form.")}),()=>{ee=!1}},[z,xn,Io,e,de?.vault,Co,t,Ne]);let Ln=(0,o.useRef)({onComplete:d,onError:p,updateError:Ne,emitDecline:Jn,resolvedAccount:Tt,avsConfig:Ze,avsCheckProp:Lt,sessionId:e,nonce:t,baseUrl:Co,captureMethod:de?.captureMethod,paymentId:de?.paymentId,authorizationExpiresAt:de?.authorizationExpiresAt,serverSideCardGateway:ve});Ln.current={onComplete:d,onError:p,updateError:Ne,emitDecline:Jn,resolvedAccount:Tt,avsConfig:Ze,avsCheckProp:Lt,sessionId:e,nonce:t,baseUrl:Co,captureMethod:de?.captureMethod,paymentId:de?.paymentId,authorizationExpiresAt:de?.authorizationExpiresAt,serverSideCardGateway:ve};let os=(0,o.useRef)(!1),gl=(0,o.useCallback)(()=>{let i=Ln.current,C=i.resolvedAccount.email?.trim(),U=(0,c.isValidEmail)(C)?C:tr.current.trim();if(!(0,c.isValidEmail)(U))return null;let Ce=i.resolvedAccount.firstName?.trim(),ee=i.resolvedAccount.lastName?.trim(),Fe=pr.current.trim()||i.resolvedAccount.country?.trim()||"",jt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.state,Fe):!1,Wt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_1,Fe):!1,ot=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.postal_code,Fe):!1,bt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.city,Fe):!1,Dt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_2,Fe):!1,yr=Wt&&!jt&&ot?(0,c.getStateFromPostalCode)(Fe,(ur.current??"").trim()):null,hn=jt?mr.current:yr;return{accountData:{userId:i.resolvedAccount.userId??"",email:U,...Ce?{firstName:Ce}:{},...ee?{lastName:ee}:{},...ot&&ur.current?{zip:ur.current}:{},...bt&&Qr.current?{city:Qr.current}:{},...hn?{state:hn}:{},...Wt&&Tr.current?{addressLine1:Tr.current}:{},...Dt&&Mr.current?{addressLine2:Mr.current}:{},...Fe?{country:Fe}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,c.isAVSFieldVisible)(i.avsConfig.country,Fe),postal_code:ot,address_line_1:Wt,address_line_2:Dt,city:bt,state:jt}}:{}}},[]),hl=(0,o.useRef)(Ae);hl.current=Ae,(0,o.useEffect)(()=>{Ae||Dn!==Lc||Ln.current.updateError(null)},[Ae,Dn]),(0,o.useEffect)(()=>{!z||!Ft||Ft.setSubmitGate?.(pn||Ae||Go||It)},[z,Ft,pn,Ae,Go,It]),(0,o.useEffect)(()=>{if(!z||!Ft)return;os.current=!1;let i=null,C=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,Ct.current="idle",ie(null)},400)},U=Ft.on("submitting",()=>{On(!0),st.current&&clearTimeout(st.current),Ct.current="validation-window",st.current=setTimeout(()=>{st.current=null,Ct.current==="validation-window"&&(Ct.current="processing")},Uu),ie("processing");let ot=Ln.current;if(!ot.sessionId||!ot.nonce)return;let bt=gl();if(!bt){ot.updateError("Enter a valid email address."),Ct.current="idle",ie(null);return}new Wn.PaymentAPI(ot.baseUrl).patchAccountSnapshot(ot.sessionId,ot.nonce,bt,{telemetryMode:"best_effort"}).catch(Dt=>{if(!qu(Dt))return;let yr=Dt instanceof Error?Dt.message:"Please check your billing address and try again.";ot.updateError(yr),Ct.current="idle",ie(null),ot.onError?.(Dt instanceof c.FloPayError?Dt:new c.FloPayError(yr,"api_error"))})}),Ce=Ft.on("complete",ot=>{(0,Vn.markSessionRecentlyCompleted)(ot.sessionId??Ln.current.sessionId),Ct.current="terminal",Xe(!1),ie("success"),setTimeout(()=>{if(os.current)return;os.current=!0;let bt=Ln.current,Dt=(0,c.isAuthorizationOnlySession)(bt)||ot.outcome==="authorized",yr=bt.serverSideCardGateway?{}:{paymentIntentId:ot.intentId};Ln.current.onComplete?.(Dt?{status:"authorized",...yr,paymentId:ot.paymentId??bt.paymentId,sessionId:ot.sessionId??bt.sessionId,authorizationExpiresAt:ot.authorizationExpiresAt??bt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...yr,checkoutMethod:"card"})},600)}),ee=Ft.on("decline",ot=>{let bt=Ln.current,Dt=ot.message??"Your payment was declined. Please try another card or contact your bank.";Ct.current="terminal",Xe(!1),bt.updateError(Dt),ie("error");let yr=ot.failureOutcome??(0,c.normalizeCheckoutFailureOutcome)(ot.declineReason)??"authorization_declined";bt.emitDecline("card",Dt,{code:yr,declineCode:yr}),C()}),Fe=Ft.on("error",ot=>{let bt=Ln.current,Dt=(0,c.buyerEmailRequiredPrompt)(ot.vaultOutcome);if(Dt!==null){i&&(clearTimeout(i),i=null),Ct.current="idle",Xe(!1),bt.updateError(Dt),ie(null),Bt(hn=>hn+1),bt.onError?.(new c.FloPayError(Dt,"api_error",{code:c.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let yr=ot.message??"There was a problem processing your payment. Please try again.";Ct.current="terminal",Xe(!1),bt.updateError(yr),ie("error"),bt.onError?.(new c.FloPayError(yr,"api_error",{code:ot.failureOutcome??"capture_failed"})),C()}),jt=Ft.on("challenge_dismissed",()=>{st.current&&(clearTimeout(st.current),st.current=null),Ct.current="processing",Xe(!0),ie(null)}),Wt=Ft.on("blocked",()=>{if(Ke.current){Ln.current.updateError(zu);return}if(!hl.current){On(!0);return}ns(),Ln.current.updateError(Lc)});return()=>{i&&(clearTimeout(i),i=null),st.current&&(clearTimeout(st.current),st.current=null),Ct.current="idle",Xe(!1),ie(null),U(),Ce(),ee(),Fe(),jt(),Wt()}},[z,Ft,ns,gl]);let Zn=!!ze?.clientId,Ca=Array.isArray(M),ri=Ca&&M.length>0,Pl=Ca&&M.includes("paypal"),ni=(0,o.useRef)(null);ni.current===null&&(ni.current=(0,c.hasMatchingStripePayPalReturn)());let Zo=ni.current?"redirect":(0,to.resolveStripePayPalPresentation)(S,ke,L.current()),{expressMethods:oi,paymentElementMethods:as}=(0,o.useMemo)(()=>(0,c.partitionStripeMethods)(M,{excludePaypal:Zn}),[M,Zn]),vl=Zn||!!Ut||Pl&&Zo==="redirect",bd=(0,o.useMemo)(()=>vl?oi.filter(i=>i!=="paypal"):oi,[oi,vl]),Sd=(0,o.useMemo)(()=>{let i=[];return be&&i.push("apple_pay"),Ie&&i.push("google_pay"),i},[be,Ie]),Qo=Ca?bd:Sd,wd=v&&Qo.length>0,Cl=Cn?at:Ve,ai=(0,o.useMemo)(()=>(0,c.filterStripeMethodsByCountryGate)(as,Cl,se),[as,Cl,se]),is=(0,o.useMemo)(()=>({mode:"payment",amount:va,currency:Yo,paymentMethodCreation:"manual",appearance:sl}),[va,Yo,sl]),[ss,bl]=(0,o.useState)("loading"),[ls,Sl]=(0,o.useState)("loading"),[cs,wl]=(0,o.useState)("loading"),[Rd,ds]=(0,o.useState)(!1),[Rl,us]=(0,o.useState)("loading"),[ps,kd]=(0,o.useState)();(0,o.useEffect)(()=>{kd((0,eo.detectPayPalEnvironment)())},[]);let ii=ps?.inAppBrowser,si=ps?(0,to.resolvePayPalPresentationMode)(ps,ze?.approvalPresentation,B??(Nt?"subscription":"order")):"popup",kl=Z&&(Zn||(Ca?Pl:ii===!1)),Ed=S.inAppBrowser&&L.current()==="blocked",El=v&&wd&&!Ed,To=(!$t||!!g.waitForDataAttachment)&&kl&&Zn,ms=Rl==="retrying"||Rl==="exhausted",ba=null;v&&(Ut?ba=il:Zo==="redirect"&&(ba=gn));let _l=(0,o.useMemo)(()=>({...I,presentationMode:Zo}),[I,Zo]),Mo=!$t&&kl&&!!ba&&(!Zn||ms),So=!$t&&El&&!!gn,Ao=!$t&&v&&ri&&ai.length>0&&!!gn,_d=To&&!ms?Rd:Mo&&$a(ss),Id=So&&$a(ls),Td=Ao&&cs!=="load_error",Il=[To||Mo,So,Ao,z].filter(Boolean).length,Md={card:z,paypal:To&&!ms||Mo&&$a(ss),wallets:So&&$a(ls),apms:Ao&&cs!=="load_error"},Tl=i=>Md[i],Ml=i=>i==="loading"||i==="ready",Al=To||Mo&&Ml(ss)||So&&Ml(ls)||Ao&&cs!=="load_error",li=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!li.current){if(!v&&!Z){li.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(!v&&Z&&!Zn){li.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(ii!==void 0&&!$t&&!xt&&!Al){li.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)}}},[v,Z,Zn,ii,$t,xt,Al,p,Ne]);let xl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(xl.current||!ri)return;let i=[];be!==!0&&i.push("showApplePay"),Ie!==!0&&i.push("showGooglePay"),i.length!==0&&(xl.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.`))},[ri,be,Ie]);let Fl=(0,o.useCallback)((i,C,U)=>g.applyInlineSessionPatch?g.applyInlineSessionPatch(i).then(Ce=>({error:null,sessionId:Ce.sessionId||e,nonce:Ce.session?.clientSecret||t})).catch(Ce=>{let ee=(0,c.normalizeBeforeButtonClickError)(C,Ce);return U?.abandoned?.()||(Ne(ee.message),p?.(ee)),{error:ee,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[g.applyInlineSessionPatch,t,p,e,Ne]),Nn=(0,o.useCallback)(async(i,C)=>{if(i!=="card"&&$t&&await g.waitForDataAttachment?.(),!qe)return{proceed:!0};try{let U=await qe({method:i,sessionId:e||void 0,createSession:g.inlineSessionDraft});if(U===!1)return{proceed:!1};if(U&&typeof U=="object"){U.account&&vr(ee=>({...ee??{},...U.account}));let Ce=await Fl(U,i,C);return Ce.error?{proceed:!1,accountPatch:U.account}:{proceed:!0,accountPatch:U.account,sessionId:Ce.sessionId,nonce:Ce.nonce}}return{proceed:!0}}catch(U){if(!C?.abandoned?.()){let Ce=(0,c.normalizeBeforeButtonClickError)(i,U);Ne(Ce.message),p?.(Ce)}return{proceed:!1}}},[Fl,g.inlineSessionDraft,g.waitForDataAttachment,$t,qe,p,e,Ne]),Bl=(0,o.useCallback)(async(i,C)=>{if(Ot.current)return;Ot.current=!0,Er(!0),ie("processing"),Ne(null);let U=C?.sessionId??e,Ce=C?.nonce??t,ee=Es(Tt,C?.accountPatch),Fe=C?.completionPaymentMethodId??Aa(i),jt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,Wt=$u(i),ot=C?.presentationMode?Mi(br(ge),{...I,presentationMode:C.presentationMode}):void 0,bt=()=>{J?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Wt}),ot?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...jn,requestCategory:"process_payment"})};try{let Dt=new Wn.PaymentAPI(Co),hn=C?.settledProcessResponse??await Dt.processPayment(ee.userId??"",{sessionId:U,nonce:Ce,paymentMethodCategory:C?.paymentMethodCategory??Ku(i),tokenizedData:jt,accountData:{...C?.accountPatch,userId:ee.userId??"",email:ee.email??"",firstName:ee.firstName||void 0,lastName:ee.lastName||void 0,...(0,c.buildProcessPaymentAvsAccount)({avsConfig:Ze,country:pr.current,zip:ur.current,city:Qr.current,state:mr.current,addressLine1:Tr.current,addressLine2:Mr.current})},...(0,c.buildCheckoutProcessMetadata)({chv:j,avsCheck:Lt,checkoutType:he,checkoutLayout:Me,avsConfig:Ze,country:pr.current})}),mi=async xr=>{let xo=(0,c.isAuthorizationOnlySession)(de)||xr?.status==="authorized";(0,Vn.markSessionRecentlyCompleted)(U),ot?.terminal({outcome:"payment_succeeded",...jn}),ie("success"),Vt(null),await new Promise(Ia=>setTimeout(Ia,600));let Qn;typeof xr?.paymentId=="string"?Qn=xr.paymentId:de?.paymentId&&(Qn=de.paymentId);let Fo;typeof xr?.authorizationExpiresAt=="string"?Fo=xr.authorizationExpiresAt:de?.authorizationExpiresAt&&(Fo=de.authorizationExpiresAt),d?.(xo?{status:"authorized",...Qn===void 0?{}:{paymentId:Qn},sessionId:typeof xr?.sessionId=="string"?xr.sessionId:U,...Fo===void 0?{}:{authorizationExpiresAt:Fo},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Fe,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Fe,checkoutMethod:i.isPaypal?"paypal":"card"})};if(hn.ok){await mi(hn.status===204?null:await hn.json().catch(()=>null));return}let fr=await hn.json().catch(()=>null);if(fr?.type==="paypal_redirect_required"){let xr=fr.threeDSecureToken,xo=fr.paymentMethodId||i.id||"";if(!ge||!xr){ie("error"),Ne("PayPal authorization required but no token provided.");return}try{let Qn=Ut?.getRawProvider();if(!Qn){Ne("PayPal is not available.");return}let Fo={return_url:window.location.href};xo&&(Fo.payment_method=xo);let{error:Ia}=await Qn.confirmPayment({clientSecret:xr,confirmParams:Fo,redirect:"if_required"});if(Ia){ie("error");let Gl=Ia.message??"PayPal payment failed.";Ne(Gl),Jn("paypal",Gl,{code:Ia.code})}}catch(Qn){ie("error"),Ne(Qn instanceof Error?Qn.message:"PayPal authorization failed.")}return}if(fr?.type==="paypal_direct_required"){let xr=fr.orderId;if(!xr){ie("error"),Ne("PayPal retry required but no order id provided.");return}let xo=wt.current?.attempts??0;if(xo>=2){ie("error"),Ne("PayPal payment could not be completed after multiple attempts."),Jn("paypal","paypal_direct_required retry limit exceeded");return}ds(!1),us("loading"),Vt({orderId:xr,attempts:xo+1}),ie(null);return}if(hn.headers.get(xu)===Fu){let xr=await Bu(Dt,U,Ce);if(xr!==void 0){await mi(xr);return}}(0,c.classifyPaymentRejection)(hn.status,fr)?ot?.terminal({outcome:"payment_declined",...jn,terminalReason:"provider_declined"}):bt(),ie("error");let Kl=fr?.message??"Payment failed. Please try again.";Ne(Kl),Jn(i.isPaypal?"paypal":"card",Kl,{code:fr?.code??fr?.gatewayErrorCode,declineCode:fr?.declineCode??fr?.gatewayDeclineReason}),await new Promise(xr=>setTimeout(xr,400))}catch(Dt){Hc(Dt)||bt(),ie("error"),Ne(Dt instanceof Error?Dt.message:"An unexpected error occurred"),await new Promise(yr=>setTimeout(yr,400))}finally{Er(!1),ie(null),Ot.current=!1}},[Co,e,t,Tt,Ze,Lt,he,Me,j,ge,Ut,de,d,Ne,Jn,J,I]),rn=(0,o.useCallback)((i,C)=>{P&&!C?.settledProcessResponse?P(i):Bl(i,C)},[P,Bl]),Sa=`${Wc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(Sa);if(!i)return;let C;try{C=JSON.parse(i)}catch{cr(Sa);return}if(!C||typeof C.createdAt!="number"||Date.now()-C.createdAt<0||Date.now()-C.createdAt>$c||typeof C.paymentMethodId!="string"||typeof C.providerIntentId!="string"||typeof C.paymentMethodType!="string"||C.sessionId!==e||!t||C.nonce!==t||!Qo.includes(C.paymentMethodType)){cr(Sa);return}cr(Sa),rn({id:C.paymentMethodId,type:"card",threeDSecureActionResultTokenId:C.providerIntentId,gateway:"stripe",paymentMethodType:C.paymentMethodType},{...C.accountPatch?{accountPatch:C.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[rn,t,e,Sa,Qo]);let Ol=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Ol.current)return;let[i,C,U]=(0,c.readStripeRedirectParams)();if(!i||!C||ni.current||!ge)return;let Ce=ge.getRawProvider();if(!Ce)return;let ee=bt=>{let Dt=localStorage.getItem(bt);if(!Dt)return null;try{return JSON.parse(Dt)}catch{return cr(bt),null}},Fe=ee(no)??ee(Bc),jt;if(Fe?.clientSecret){if(Fe.clientSecret!==C)return;jt={...Fe.accountPatch?{accountPatch:Fe.accountPatch}:{},...Fe.sessionId?{sessionId:Fe.sessionId}:{},...Fe.nonce?{nonce:Fe.nonce}:{}}}else if(Fe?.sessionId&&Fe.sessionId!==e)return;Ol.current=!0,cr(no),cr(Bc),window.history.replaceState({},"",(0,c.stripeRedirectReturnUrl)());let Wt=Fe?.paymentMethodType??Fe?.tokenType??"card",ot="card";(async()=>{if(U==="failed"){let fr="Payment was declined. Please try again.";Ne(fr),Jn(ot,fr);return}let{paymentIntent:bt,error:Dt}=await Ce.retrievePaymentIntent(C);if(Dt){let fr=Dt.message??"Failed to retrieve payment status.";Ne(fr),Jn(ot,fr,{code:Dt.code});return}let yr=bt?.status,hn=Ma(yr);if(!bt||!hn){let fr=yr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ne(fr),Jn(ot,fr,{code:yr??"missing_payment_intent"});return}let mi=typeof bt.payment_method=="string"?bt.payment_method:bt.payment_method?.id;rn({id:mi??Fe?.paymentMethodId??Fe?.tokenId??bt.id,type:"card",threeDSecureActionResultTokenId:bt.id,gateway:Fe?.gateway??"stripe",paymentMethodType:Wt},jt)})()},[e,rn,ge,Ne,Jn]);let ys=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(z||ge!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let wa=ye==="buttons",Hr=Ho?.variables,Ad=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),fs=Hr?.colorBackground,xd=fs&&!Ad.has(fs)?fs:void 0,Ra=rt.cardInputBorder??(wa?"#e5e7eb":"#A4A4FF"),Dl=Hr?.colorDanger??"#dc2626",rr=i=>io[i]&&(lo[i]||mn),ci=Go&&(Hn||mn),Rn=i=>i?Dl:Ra,di=(tn.malformed||tn.empty)&&(so||mn),Fd=Rn(di),gs=rt.cardFormContainer?.backgroundColor??xd??(wa?"white":"#EDEDFF"),ea=rt.cardInputBackground??Hr?.colorBackground??"white",hs=na(X),Ll=na(G),ta=rt.nameInput,Nl=rt.cardInputFontSize??Ju(ta?.fontSize)??Hr?.fontSizeBase??"16px",Ul=typeof ta?.fontFamily=="string"?ta.fontFamily:Hr?.fontFamily??"Poppins, sans-serif",zl=(0,c.toCssWeight)(ta?.fontWeight)??400,Bd=rt.cardInputColor??(typeof ta?.color=="string"?ta.color:void 0)??Hr?.colorText??"#262833",Od=rt.cardInputPlaceholderColor??"#9ca3af",sr=Hr?.borderRadius??"8px",uo=Hr?.borderRadius??rt.cardButton?.borderRadius??sr,wo=Hr?.colorPrimary??"#4A49FF",Dd=Hr?.colorPrimaryHover??(0,c.darkenHex)(wo,.12),Ps=Hr?.colorText??"#262833",vs={fontSize:Nl,fontFamily:Ul,fontWeight:zl,color:Bd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ka={marginTop:"0.375rem",...vs,fontSize:"0.75rem",lineHeight:1.4,color:Dl},Ld={"--flopay-input-placeholder-color":Od,"--flopay-input-font-size":Nl,"--flopay-input-font-family":Ul,"--flopay-input-font-weight":String(zl)},Ea=rt.cardFormContainer??{},Cs=Ea.padding??(wa?"0":"1rem"),bs=Ea.borderRadius??sr,Nd=Ft&&wn?(0,l.jsx)(_o,{capture:Ft,html:wn.html,messageToken:wn.messageToken,expectedOrigin:wn.expectedOrigin,verificationRequired:wn.verificationRequired,theme:Pd,submitLabel:k,onReady:()=>{if(!bo&&!Ze||typeof document>"u"||Q===!1)return;let i=()=>{let U=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(U){Gn.current=!0;try{U.focus()}finally{Gn.current=!1}}};Yn.current||i()},onError:i=>{i&&wn.verificationRequired&&Ct.current==="idle"&&(it.current=!0),Ne(i)},onValidation:i=>{let C=Ct.current;(C==="idle"||C==="validation-window")&&(Ne(i),i&&Ct.current==="validation-window"&&(st.current&&(clearTimeout(st.current),st.current=null),Ct.current="idle",ie(null)))}},re):(0,l.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Ss=(0,l.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&Re()},style:{backgroundColor:gs,borderRadius:bs,...Ea,padding:Cs,...Ld,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
|
|
30
|
+
`,Eo=44;function ha(){return(0,Fr.jsx)("style",{children:Pu})}function Va(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function Wa({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Fr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Fr.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,Fr.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 $a(e){return e!=="unavailable"&&e!=="load_error"}function Ai({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:d,backgroundColor:p,borderColor:m,textColor:b,borderRadius:P,fontFamily:g}){let _=(0,ho.resolveStripeMethodBrandVariant)(e,t),V=_c[e],[W,k]=(0,Ic.useState)(!1),T=!!V&&!W,y=_?.backgroundColor??p??"#ffffff",K=_?.borderColor??m??"#d1d5db",Z=_?.textColor??b??"#262833";return(0,Fr.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&d()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Eo,padding:"0 1rem",backgroundColor:y,color:Z,border:`1px solid ${K}`,borderRadius:P??8,fontSize:"0.95rem",fontWeight:600,fontFamily:g,cursor:r||n?"not-allowed":"pointer",opacity:n&&!r?.55:1,animation:r?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,Fr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,ho.getStripeMethodDisplayName)(e)}\u2026`}):(0,Fr.jsxs)(Fr.Fragment,{children:[(0,Fr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,ho.hasVendoredStripeMethodLogo)(e)?8:0},children:[T?(0,Fr.jsx)("img",{src:V,alt:"","aria-hidden":"true",onError:()=>k(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!T&&_?.logoSvg?(0,Fr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:_.logoSvg}}):null,(0,Fr.jsx)("span",{children:(0,ho.getStripeMethodDisplayName)(e)})]}),s&&(0,Fr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:Z,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,Fr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function xi(e){let t=new Set(e.map(ho.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var Fi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},Bi={type:"accordion",defaultCollapsed:!1,radios:"never"};function Oi({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:d,children:p}){return(0,Fr.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 Bs=require("react/jsx-runtime"),vu=["first","second","third","fourth"];function Os({rows:e,borderRadius:t}){return(0,Bs.jsx)("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:vu.slice(0,Math.max(1,e)).map(r=>(0,Bs.jsx)("div",{style:{height:Eo,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},r))})}var Mc=require("@flopay/js"),Di=require("@flopay/shared"),Li=require("react"),Cu=1500,Tc=new Set;function Ac(e){for(let t of e)Tc.has(t)||(Tc.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function bu(e){if(e!=null)try{return JSON.stringify(e)}catch{return Ac(["the rules could not be sent (they are not plain data), so the default layout applies."]),"{}"}}var Su={order:[...Di.DEFAULT_PAYMENT_METHOD_ORDER],moreOptions:[]};function xc({rules:e,sessionId:t,nonce:r,billingApiUrl:n,waitForSession:a}){let s=bu(e),[d,p]=(0,Li.useState)(null);return(0,Li.useEffect)(()=>{if(s===void 0||a)return;let m=JSON.parse(s),b=!1,P=W=>{b||(b=!0,p(W))},g=()=>P((0,Di.resolveDefaultPaymentMethodLayout)(m));if(!t||!r||!n){g();return}let _=new AbortController,V=setTimeout(()=>{g(),_.abort()},Cu);return new Mc.PaymentAPI(n,{telemetry:!1}).resolvePaymentMethodLayout(t,r,m,{signal:_.signal}).then(W=>{if(!W){g();return}b||Ac(W.warnings),P({order:W.order,moreOptions:W.moreOptions})}).catch(g).finally(()=>clearTimeout(V)),()=>{b=!0,clearTimeout(V),_.abort()}},[s,t,r,n,a]),s===void 0?Su:d}var Pn=require("react");var Ha=require("@flopay/shared"),wu=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 Ru(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return wu.has(t.charAt(0).toLowerCase()+t.slice(1))}function ku(e,t){return typeof t=="number"&&t!==0&&!Ru(e)?`${t}px`:String(t).trim()}function Fc(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]=ku(r,n)}}}var zo=require("react/jsx-runtime"),Ds=new WeakSet;function _o({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:d,containerStyle:p,onReady:m,onError:b,onValidation:P}){let g=(0,Pn.useRef)(null),_=(0,Pn.useRef)(m),V=(0,Pn.useRef)(b),W=(0,Pn.useRef)(P);_.current=m,V.current=b,W.current=P;let k=(0,Pn.useRef)(s);k.current=s;let T=(0,Pn.useRef)(null),y=d??void 0,K=(0,Pn.useRef)(y);K.current=y;let Z=(0,Pn.useRef)(void 0);return(0,Pn.useEffect)(()=>{let v=g.current;if(!v)return;let ke=!0,M=!1,se=()=>{!ke||M||(M=!0,_.current?.())},Se=e.on("ready",()=>{se()}),Ie=e.on("error",z=>{V.current?.(z.message??"There was a problem loading the secure card form.")}),ye=e.on("validation",z=>{W.current?.(z.message??null)}),vt=K.current??(Ds.has(e)?null:void 0),ut={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...k.current?{theme:k.current}:{},...vt===void 0?{}:{submitLabel:vt}};return T.current=k.current??null,Z.current=K.current,K.current!==void 0&&Ds.add(e),e.mount(v,ut).then(()=>{se()}).catch(z=>{ke&&V.current?.(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{ke=!1,Se(),Ie(),ye(),e.unmount()}},[e,t,r,n,a]),Oo(()=>{let v=g.current;v&&Fc(v,p)},[p]),(0,Pn.useEffect)(()=>{s!==void 0&&(s===null&&T.current===null||(T.current=s,e.applyTheme?.(s)))},[e,s]),(0,Pn.useEffect)(()=>{y!==Z.current&&(Z.current=y,y!==void 0&&Ds.add(e),e.setSubmitLabel?.(y??null))},[e,y]),(0,zo.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields"})}function Ka({label:e}){return(0,zo.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,zo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,zo.jsx)("span",{children:e}),(0,zo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var Ks=require("@flopay/shared"),l=require("react/jsx-runtime"),no="flopay_stripe_resume",Bc="flopay_wallet_resume",Wc="fw1",Eu="fw2",$c=300*1e3,_u=900,Iu="express_checkout_click_timeout",Tu=25e3,Mu=25e3,Au=1e4,Vn={provider:"paypal",paymentMethodCategory:"paypal"},xu="x-flopay-process-result-source",Fu="status";async function Bu(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 Ni={},Ya=class{constructor(t){this.reason=t}};function Ou(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function cr(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function Ws(e){return`${Eu}:${e}`}function Ui(e){return cr(Ws(e))}function zi(e,t){if(typeof window>"u")return null;let r=Ws(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>$c||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(Ui(e),null):a}catch{return Ui(e),null}}function Du(e){return cr(Ws(e.sessionId),e)}function Oc(e,t,r){let n=zi(e,t);return!n||n.clientSecret!==r?!1:Ui(e)}function Ls(e,t,r){if(typeof window>"u")return;zi(e,t)?.clientSecret===r&&Ui(e)}function Lu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Ns(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":Ma(e.status),a=Lu(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Dc(e,t,r){let n=null;try{return await Promise.race([ac(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Au),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Nu(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Hc(e){return e instanceof c.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function qi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Wn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw Hc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var Us=c.STRIPE_PAYPAL_RESUME_KEY,Ga=new Map,Uu=250,Lc="Just a moment \u2014 we are finalizing your order. Please press pay again.",zu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function $s(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 ji({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new Wn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function qu(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,la.splitFullName)(r),d=s.firstName?s:(0,la.splitFullName)(n?.name);return(0,En.compactBuyerIdentity)({email:(0,c.isValidEmail)(a)?a:n?.email?.trim(),firstName:d.firstName,lastName:d.lastName})}async function ju({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let d=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 Xa=180,Nc=`flopay-card-enter ${Xa}ms cubic-bezier(0, 0, 0.2, 1) both`,Uc=`flopay-card-exit ${Xa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Vu=`flopay-buttons-enter ${Xa}ms cubic-bezier(0, 0, 0.2, 1) both`,Wu=`flopay-buttons-exit ${Xa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function $u(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Hs(e){return(0,c.derivePrimaryTileStyle)(e)}var Hu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Ku(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 qs={width:"100%",minHeight:Eo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function zc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function js(e){return e==="paypal"?"PayPal":(0,c.getStripeMethodDisplayName)(e)}function Gu(e){let t=(0,c.getPostalCodeExample)(e);return`Enter a valid ${(0,c.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Yu(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 Xu(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 Ju(e){return typeof e=="number"?`${e}px`:e}function Vi(e){return(0,l.jsx)(ep,{...e})}function qc({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:d=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:b,runBeforeButtonClick:P,billingName:g,onBuyerIdentityReady:_,onLoadStateChange:V,placeholderBorderRadius:W,popupCapabilityOwner:k,externalTelemetryContext:T,presentationMode:y}){let K=fo(),{emitInstrument:Z}=(0,o.useContext)(kn),v=(0,lr.useStripe)(),ke=(0,lr.useElements)(),M=(0,o.useMemo)(()=>Mi(br(K),T),[T,K]),[se,Se]=(0,o.useState)("loading");(0,o.useEffect)(()=>{V?.(se)},[se,V]);let[Ie,ye]=(0,o.useState)(!1),vt=(0,o.useRef)(!1),ut=!(0,c.isValidEmail)(r?.trim())||!g?.trim(),{request:z,collect:We,finish:$e}=ca(),Be=(0,o.useRef)(!1),Re=(0,o.useRef)(null),X=(0,o.useRef)(null),[G,tt]=(0,o.useState)(0),[Ee,qe]=(0,o.useState)(!1),re=(0,o.useRef)(!1),q=(0,o.useRef)(new Map),{startAttempt:we,finishAttempt:Q,invalidateAttempt:pt,isAttemptInvalidated:fe,isAttemptCurrent:Pe,generationRef:Oe}=Ba((he,Me,Ye)=>{b?.(he,Me,{...Ye,popupBlocked:Ye?.popupBlocked??(0,_e.isPopupBlockedError)(Me),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y,terminalReason:"overlay_timeout"}),qe(!0),tt(Pt=>Pt+1)},{onHandoffObserved:()=>{k.markAvailable(),M?.log({name:"provider.popup.opened",stage:"overlay_open",...Vn,attempt:Oe.current})}});(0,o.useEffect)(()=>{Ee&&X.current?.focus()},[Ee,G]);let ce=(0,o.useCallback)(()=>{tt(he=>he+1)},[]),je=(0,o.useCallback)((he,Me,Ye)=>{pt(Ye),b?.("paypal",he,{code:Me,popupBlocked:(0,_e.isPopupBlockedError)(he),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y}),qe(!0),ce()},[pt,b,y,ce]),De=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{re.current&&(re.current=!1,De())},[De,G]);let nt=(0,o.useCallback)(()=>{qe(!1),s?.(null),De()},[De,s]);(0,o.useEffect)(()=>{if(!v||Be.current)return;let[he,Me,Ye]=(0,c.readStripeRedirectParams)();if(!he||!Me)return;let Pt=(0,c.readMatchingStripePayPalContinuation)(Me);if(!Pt)return;Be.current=!0;let ft=!0,ze=Ga.get(Me);ze||(ze=Ye==="failed"?Promise.resolve(null):Promise.resolve().then(()=>v.retrievePaymentIntent(Me)),Ga.set(Me,ze));let Nt={accountPatch:Pt.accountPatch,sessionId:Pt.sessionId,nonce:Pt.nonce},de=()=>{M?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Vn,requestCategory:"provider_sdk"})};return M?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Vn}),(async()=>{try{ye(!0);let At=await ze;if(!ft)return;if(At?.error){Ga.delete(Me),de(),s?.(At.error.message??"Failed to retrieve PayPal payment status.");return}if((0,c.clearStripePayPalReturn)(),Ga.delete(Me),Ye==="failed"){let ge="PayPal payment was declined. Please try again.";M?.terminal({outcome:"payment_declined",...Vn,terminalReason:"provider_declined"}),s?.(ge),m?.(Cr("paypal",ge));return}let $=At?.paymentIntent;if($&&$.id!==he){de(),s?.("Failed to match the returned PayPal payment.");return}if($&&($.status==="requires_capture"||$.status==="succeeded")){let ge=typeof $.payment_method=="string"?$.payment_method:$.payment_method?.id;a({id:ge??$.id,type:"card",threeDSecureActionResultTokenId:$.id,isPaypal:!0},{...Nt,presentationMode:"redirect"})}else{let ge="PayPal payment was not completed. Please try again.";M?.terminal({outcome:$?.status==="canceled"?"payment_cancelled":"payment_declined",...Vn,terminalReason:$?.status==="canceled"?"cancelled":"provider_declined"}),s?.(ge),m?.(Cr("paypal",ge))}}catch(At){if(!ft)return;Ga.delete(Me),de(),s?.(At instanceof Error?At.message:"Failed to complete PayPal payment.")}finally{ft&&ye(!1)}})(),()=>{ft=!1,Be.current=!1}},[v,a,s,m,M]);let ct=(0,o.useCallback)(async(he=!1)=>{let Me=P?await P("paypal"):{proceed:!0};if(!Me.proceed)return q.current.delete(G),!1;let Ye=we("paypal");return q.current.set(G,{generation:Ye,accountPatch:Me.accountPatch,sessionId:Me.sessionId,nonce:Me.nonce}),qe(!1),M?.log({name:`provider.${he?"redirect.started":"handoff.requested"}`,stage:he?"redirect":"overlay_open",...Vn,attempt:Ye}),p?.("paypal"),!0},[p,M,P,we,G]),Y=(0,o.useCallback)(async he=>{if(d||Ie||!await ct()){he.reject();return}he.resolve()},[d,ct,Ie]),Rt=(0,o.useCallback)(async he=>{if(!v||!ke)return;let Me=q.current.get(G);if(Me&&!Pe(Me.generation)){q.current.delete(G);return}if(!Me&&fe()||Me&&!Q(Me.generation))return;Me||Q();let Ye=Me??null;if(q.current.delete(G),!Ye&&P){let kt=await P("paypal");if(!kt.proceed){he.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Ye={accountPatch:kt.accountPatch,sessionId:kt.sessionId,nonce:kt.nonce}}let Pt=Ye?.sessionId??e,ft=Ye?.nonce??t,ze=await ju({event:he,prepared:Ye,email:r,billingName:g,methodLabel:"PayPal",collect:We});if(!ze){he.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Nt=ze.email,de={...Ye?.accountPatch,...(0,En.compactBuyerIdentity)(ze,!0)};try{if(ye(!0),s?.(null),!Pt||!(0,c.isValidEmail)(Nt))throw new Error("Missing sessionId or email for PayPal payment");await _?.(ze);let kt=v.createPaymentMethod,{error:At,paymentMethod:$}=await kt({type:"paypal"});if(At){je(At,"stripe_paypal_create_payment_method_failed",Me?.generation),he.paymentFailed({reason:"fail"});return}let ge=await qi(n,Z,Pt,ft??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:$?.id??null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(ge)){he.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:de,paymentMethodCategory:"paypal",presentationMode:y,sessionId:Pt,nonce:ft,settledProcessResponse:ge.response});return}if(ge.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ut=ge.clientSecret,h={return_url:(0,c.stripeRedirectReturnUrl)()};if($?.id&&(h.payment_method=$.id),!cr(Us,{clientSecret:Ut,sessionId:Pt,nonce:ft,accountPatch:de})&&y==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:He,paymentIntent:L}=await v.confirmPayment({clientSecret:Ut,confirmParams:h,redirect:"if_required"});if(He){if(cr(Us),(0,_e.isProviderDecline)(He)){let u=He.message??"Your payment was declined.";M?.terminal({outcome:"payment_declined",...Vn,terminalReason:"provider_declined"}),s?.(u),m?.(Cr("paypal",u,{code:(0,_e.getProviderErrorCode)(He),declineCode:(0,_e.getProviderDeclineCode)(He)})),await ji({billingApiUrl:n,sessionId:Pt,nonce:ft,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,_e.getProviderErrorCode)(He)??"provider_declined"}})}else je(He,"stripe_paypal_confirm_failed",Me?.generation);return}cr(Us);let mt=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;a({id:mt??L?.id,type:"card",threeDSecureActionResultTokenId:L?.id,isPaypal:!0},{accountPatch:de,paymentMethodCategory:"paypal",presentationMode:y,sessionId:Pt,nonce:ft});return}catch(kt){je(kt,"stripe_paypal_failed",Me?.generation)}finally{ye(!1)}},[v,ke,e,t,r,g,We,_,n,Z,a,s,m,P,je,Q,Pe,fe,M,y,G]),Ht=(0,o.useCallback)(async()=>{if(!(vt.current||d||Ie||!v||!ke)){vt.current=!0,ye(!0);try{if(!await ct(!0))return;await Rt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{vt.current=!1,ye(!1)}}},[ke,Rt,d,ct,v,Ie]),Mt=y==="redirect"?(0,l.jsx)("button",{type:"button",disabled:d||Ie,onClick:()=>{Ht()},style:{width:"100%",minHeight:Eo,border:"1px solid #d1d5db",borderRadius:W??8,background:"#ffc439",color:"#111827",cursor:d||Ie?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,l.jsx)(lr.ExpressCheckoutElement,{onReady:he=>Se(Va(he,["paypal"])),onLoadError:()=>{Se("load_error"),$s(M,"paypal","paypal","provider_error")},onClick:Y,onConfirm:Rt,onCancel:()=>{let he=q.current.get(G);q.current.delete(G),M?.terminal({outcome:"payment_cancelled",...Vn,terminalReason:"cancelled",...he?{attempt:he.generation}:{}}),pt(he?.generation),qe(!1),re.current=!0,ce()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ut,emailRequired:ut,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},G),Lt=(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{ref:Re,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ee&&(0,l.jsx)("button",{ref:X,type:"button","data-testid":"flopay-paypal-retry-button",onClick:nt,style:qs,children:"Try PayPal again"}),z&&(0,l.jsx)(da,{identity:z.identity,methodLabel:z.methodLabel,onComplete:$e,onCancel:()=>$e(null)},z.id),(0,l.jsx)("div",{style:{display:z?"none":void 0},children:Mt})]}),Ie&&!z&&(0,l.jsx)(nn,{status:"processing"})]});return y==="redirect"?Lt:(0,l.jsx)(Wa,{state:se,placeholderTestId:"flopay-paypal-placeholder",borderRadius:W,children:Lt})}function zs(e){return e==="apple_pay"||e==="google_pay"}var Zu=200;function Qu({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,c.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function jc({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:d,onErrorChange:p,onButtonClick:m,onDecline:b,onTechnicalFailure:P,runBeforeButtonClick:g,billingName:_,onBuyerIdentityReady:V,onLoadStateChange:W,placeholderBorderRadius:k,popupCapabilityOwner:T,externalTelemetryContext:y}){let K=fo(),{emitInstrument:Z}=(0,o.useContext)(kn),v=(0,lr.useStripe)(),ke=(0,lr.useElements)(),M=(0,o.useMemo)(()=>Mi(br(K),y),[y,K]),[se,Se]=(0,o.useState)("loading");(0,o.useEffect)(()=>{W?.(se)},[se,W]);let[Ie,ye]=(0,o.useState)(!1);(0,o.useEffect)(()=>{qe.current=Ie},[Ie]);let vt=(0,o.useRef)(!(0,c.isValidEmail)(r?.trim())||!_?.trim()).current,{request:ut,collect:z,finish:We}=ca(),$e=(0,o.useRef)(null),Be=(0,o.useRef)(null),[Re,X]=(0,o.useState)(0),[G,tt]=(0,o.useState)(()=>(0,c.shouldPreferWalletPopup)()),Ee=(0,o.useRef)(G),qe=(0,o.useRef)(!1),[re,q]=(0,o.useState)(!1),[we,Q]=(0,o.useState)(()=>zi(e,t)?"blocked":"idle"),[pt,fe]=(0,o.useState)("google_pay"),Pe=(0,o.useRef)(null),Oe=(0,o.useRef)(!0),ce=(0,o.useRef)(!1),je=(0,o.useRef)("google_pay"),De=(0,o.useRef)("google_pay"),nt=(0,o.useRef)(null),ct=(0,o.useRef)(null),Y=(0,o.useRef)(new Set),Rt=(0,o.useRef)(null),Ht=(0,o.useRef)(null);(0,o.useEffect)(()=>(Oe.current=!0,()=>{Oe.current=!1;for(let u of Y.current)window.clearTimeout(u);Y.current.clear()}),[]);let Mt=(0,o.useRef)(new Map),{startAttempt:Lt,finishAttempt:he,invalidateAttempt:Me,isAttemptInvalidated:Ye,isAttemptCurrent:Pt,generationRef:ft}=Ba((u,S,I)=>{P?.(u,S,{...I,popupBlocked:I?.popupBlocked??(0,_e.isPopupBlockedError)(S),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),fe(u),q(!0),X(H=>H+1)},{onHandoffObserved:u=>{Ht.current=ft.current,T.markAvailable(),M?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ft.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})},defersMissingTerminal:zs,onMissingTerminalDeferred:(u,S)=>{let I=M?.now()??globalThis.performance?.now()??Date.now(),H=Rt.current,F=H?.generation===S?H.startedAt:I;M?.performance({stage:"overlay_return",durationMs:Math.max(0,I-F),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:S,...zs(u)?{walletType:u}:{}}),M?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{re&&Be.current?.focus()},[re,Re]);let ze=(0,o.useRef)(0),Nt=(0,o.useRef)(!1),de=(0,o.useCallback)(()=>{if(ze.current>0){Nt.current=!0;return}X(u=>u+1)},[]),kt=(0,o.useCallback)(()=>{ze.current-=1,!(ze.current>0||!Nt.current)&&(Nt.current=!1,Oe.current&&X(u=>u+1))},[]),At=(0,o.useCallback)((u,S,I,H,F=!1)=>{Me(H),P?.(u,S,{code:I,popupBlocked:(0,_e.isPopupBlockedError)(S),telemetryReported:F,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),fe(u),q(!0),de()},[Me,P,de]),$=(0,o.useCallback)(u=>{M?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...zs(u)?{walletType:u}:{}}),P?.(u,new Error("The wallet click was not ready within the time the wallet allows."),{code:Iu,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),fe(u),q(!0)},[P,M]),ge=(0,o.useCallback)(()=>{window.setTimeout(()=>{($e.current?.querySelector("iframe")??$e.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{ce.current&&(ce.current=!1,ge())},[ge,Re]);let Ut=(0,o.useCallback)(()=>{q(!1),p?.(null),ge()},[ge,p]),h=(0,o.useCallback)(()=>{Pe.current?.()},[]);(0,o.useEffect)(()=>{let u=null,S=()=>{u=null;let H=(0,c.shouldPreferWalletPopup)();H!==Ee.current&&(Ee.current=H,tt(H),!qe.current&&!Pt(ft.current)&&de())},I=()=>{u!==null&&window.clearTimeout(u),u=window.setTimeout(S,Zu)};return window.addEventListener("resize",I),()=>{window.removeEventListener("resize",I),u!==null&&window.clearTimeout(u)}},[ft,Pt,de]),(0,o.useEffect)(()=>{let u=zi(e,t);if(!u)return;let S=!1,I=!1,H=async()=>{if(!I){I=!0,S||Q("checking");try{let F=await Dc(v,u.clientSecret,Y.current);if(S)return;let B=Ns(F,u.providerObjectId,(0,c.isSetupIntentClientSecret)(u.clientSecret));if(B.kind==="confirmed"){if(!Oc(e,t,u.clientSecret))return;Pe.current=null,Q("idle"),d({id:B.paymentMethodId,type:"card",threeDSecureActionResultTokenId:B.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(B.kind==="terminal"){Ls(e,t,u.clientSecret),Pe.current=null,Q("idle"),fe(u.paymentMethodType),q(!0),de();return}Q("blocked")}catch{S||Q("blocked")}finally{I=!1}}};return Pe.current=H,Q("blocked"),()=>{S=!0,Pe.current===H&&(Pe.current=null)}},[t,d,de,e,v]);let J=(0,o.useCallback)(async u=>{let S=!1,I=!1,H=gt=>{S||I||(S=!0,u.paymentFailed({reason:"fail",...gt?{message:gt}:{}}))};if(!v||!ke){H();return}let F=Mt.current.get(Re);if(F&&!Pt(F.generation)){Mt.current.delete(Re),H();return}if(!F&&Ye()){H();return}if(F&&!he(F.generation)){H();return}F||(he(),Nt.current=!1);let B=u.expressPaymentType??F?.method??je.current,Ae=F??null,jr=zc(B),$t;B==="apple_pay"?$t="apple_pay":B==="google_pay"&&($t="google_pay");let nr=F?.generation??ft.current,Te=M,kr=Te?.now()??globalThis.performance?.now()??Date.now(),Ur=new AbortController,Xr=!1,Or=!1,Kt=null,Vr=e,an="processing",Er="other",_r="provider_runtime",vn,at=new Promise((gt,Et)=>{vn=Et}),Pr=window.setTimeout(()=>{Xr=!0,Ur.abort(),vn(Ni)},Tu),Xt=async(gt,Et,sn)=>{an=gt,Er=Et,_r=Et==="intent_create"||Et==="session_claim"?"transport_error":"provider_runtime";let zr=Te?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([sn,at])}finally{let Dr=Te?.now()??globalThis.performance?.now()??Date.now();Te?.performance({stage:gt,durationMs:Math.max(0,Dr-zr),durationMode:"machine",requestCategory:Et,paymentMethodCategory:"wallet",provider:"stripe",...Xr?{statusClass:"timeout"}:{}})}};try{if(ye(!0),p?.(null),!Ae&&g){let ve=await Xt("processing","other",g(jr));if(!ve.proceed){H();return}Ae={accountPatch:ve.accountPatch,sessionId:ve.sessionId,nonce:ve.nonce}}let gt=Ae?.sessionId??e;Vr=gt;let Et=Ae?.nonce??t,sn=nt.current??Ae?.accountPatch,zr=Kc({event:u,fallbackEmail:sn?.email??r,fallbackName:[sn?.firstName,sn?.lastName].join(" ").trim()||_});if(!(0,c.isValidEmail)(zr.email)){H("Buyer details are required."),z(js(B),zr).then(ve=>{ve&&(nt.current=ve)});return}nt.current=null;let Dr={...Ae?.accountPatch,...(0,En.compactBuyerIdentity)(zr,!0)};await Xt("processing","session_claim",Promise.resolve(V?.(zr)));let{error:ln}=await Xt("tokenization","provider_sdk",ke.submit());if(ln){H(),At(B,ln,"stripe_wallet_submit_failed",F?.generation);return}if(!gt)throw new Error("Missing sessionId or email for payment.");let Jr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:B,paymentMethodId:null,intentKind:a},Ir=JSON.stringify({sessionId:gt,nonce:Et??"",request:Jr}),cn=ct.current,Zr=cn?.retryIdentity===Ir?cn.authorizationAttemptId:(0,c.randomUuidV4)();ct.current={authorizationAttemptId:Zr,retryIdentity:Ir};let Lr=await Xt("processing","intent_create",qi(n,Z,gt,Et??"",{...Jr,authorizationAttemptId:Zr},{signal:Ur.signal}));if((0,c.isSettledSessionIntent)(Lr)){H(),d({type:"card",paymentMethodType:B},{accountPatch:Dr,paymentMethodCategory:"wallet",sessionId:gt,nonce:Et,settledProcessResponse:Lr.response});return}if(Lr.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let or=Lr.clientSecret,vr=Du({createdAt:Date.now(),sessionId:gt,...Et?{nonce:Et}:{},clientSecret:or,providerObjectId:Lr.providerObjectId,paymentMethodType:B,accountPatch:Dr});window.clearTimeout(Pr),Or=!0,Te?.performance({stage:"callback",durationMs:Math.max(0,(Te?.now()??globalThis.performance?.now()??Date.now())-kr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let ur=Te?.now()??globalThis.performance?.now()??Date.now(),pr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...$t?{walletType:$t}:{},attempt:nr},Tr=!1,Mr=null;Te?.log({name:"payment.provider_confirmation.started",...pr}),Kt=window.setTimeout(()=>{Kt!==null&&Y.current.delete(Kt),Tr=!0;let ve=Te?.now()??globalThis.performance?.now()??Date.now();Te?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...pr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ve-ur),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Te?.flush?.().catch(()=>{}),Mr?.()},Mu),Y.current.add(Kt);let Qr=(ve,Gt)=>{Kt!==null&&(window.clearTimeout(Kt),Y.current.delete(Kt),Kt=null);let zt=Te?.now()??globalThis.performance?.now()??Date.now(),xt=Math.max(0,zt-ur),U=ve;Tr&&(ve==="resolved"?U="resolved_late":ve==="returned_error"?U="returned_error_late":U="rejected_late");let bn=Gt??(ve==="resolved"?"approved":"provider_error");return Te?.log({name:"payment.provider_confirmation.returned",...pr,operationOutcome:U,terminalReason:bn}),Te?.performance({...pr,durationMs:xt,durationMode:"buyer",operationOutcome:U,terminalReason:bn}),{durationMs:xt,operationOutcome:U,terminalReason:bn}},mr=!1,tr=!1,Nr=ve=>{if(!ve||typeof ve!="object")return null;let Gt=ve;if(Gt.error)return null;let zt=Gt.setupIntent??Gt.paymentIntent,xt=Ns(zt??null,void 0,!!Gt.setupIntent);return xt.kind==="confirmed"?xt:null},Ze=ve=>{if(mr||F&&ft.current!==F.generation)return;let Gt=Nr(ve);if(!Gt)return;if(vr&&!Oc(gt,Et,or)){mr=!0;return}let{intentId:zt,paymentMethodId:xt}=Gt;mr=!0,tr=!0,ct.current=null,Pe.current=null,Oe.current&&(Q("idle"),ye(!1));let U=`${Wc}:${gt}`;cr(U,{createdAt:Date.now(),sessionId:gt,nonce:Et,accountPatch:Dr,paymentMethodId:xt,providerIntentId:zt,paymentMethodType:B});try{d({id:xt,type:"card",threeDSecureActionResultTokenId:zt},{accountPatch:Dr,paymentMethodCategory:"wallet",sessionId:gt,nonce:Et})}finally{cr(U)}},Cn=!1;Mr=async()=>{if(!(Cn||mr||tr)){Cn=!0,Oe.current&&Q("checking");try{let ve=await Dc(v,or,Y.current);if(mr||tr)return;let Gt=(0,c.isSetupIntentClientSecret)(or),zt=Ns(ve,Lr.providerObjectId,Gt);if(zt.kind==="confirmed"){Ze(Gt?{setupIntent:ve}:{paymentIntent:ve});return}if(zt.kind==="terminal"){if(tr=!0,Ls(gt,Et,or),ct.current=null,Pe.current=null,!Oe.current)return;Q("idle"),H(),At(B,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",F?.generation,!0);return}Oe.current&&!tr&&(Q("blocked"),ye(!1))}catch{Oe.current&&!tr&&(Q("blocked"),ye(!1))}finally{Cn=!1}}},Pe.current=Mr;let O,Qe;try{I=!0,ze.current+=1;let ve;try{ve=await((0,c.isSetupIntentClientSecret)(or)?v.confirmSetup({elements:ke,clientSecret:or,redirect:"if_required"}):v.confirmPayment({elements:ke,clientSecret:or,redirect:"if_required"}))}finally{kt()}if(!ve||typeof ve!="object")throw new Ya(Ou(ve));if(O=ve,!O.error&&!Nr(O))throw new Ya("confirmation_result_unconfirmed");Qe=Qr(O.error?"returned_error":"resolved",O.error&&(0,_e.isProviderDecline)(O.error)?"provider_declined":void 0)}catch(ve){let Gt=ve instanceof Ya?ve.reason:void 0,zt=Gt!==void 0,xt=Qr(zt?"returned_error":"rejected");if(Te?.error({...zt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Gt}:_s(ve),...pr,operationOutcome:xt.operationOutcome,durationMs:xt.durationMs,statusClass:"unknown",terminalReason:xt.terminalReason}),!Oe.current||mr)return;await Mr?.();return}let ue=O.error;if(ue){if(!Oe.current||mr)return;if((0,_e.isProviderDecline)(ue)){tr=!0,Ls(gt,Et,or),ct.current=null,Pe.current=null,Q("idle"),Mt.current.get(Re)===F&&Mt.current.delete(Re);let ve=ue.message??"Your payment was declined.";p?.(ve),b?.(Cr(jr,ve,{code:(0,_e.getProviderErrorCode)(ue),declineCode:(0,_e.getProviderDeclineCode)(ue)})),ji({billingApiUrl:n,sessionId:gt,nonce:Et,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:B,providerDeclineReason:(0,_e.getProviderErrorCode)(ue)??"provider_declined",...Lr.intentKind==="payment"&&Lr.providerObjectId.startsWith("pi_")?{providerIntentId:Lr.providerObjectId}:{}}})}else Te?.error({..._s(ue),...pr,operationOutcome:Qe.operationOutcome,durationMs:Qe.durationMs,statusClass:"unknown",terminalReason:Qe.terminalReason}),await Mr?.();return}if(Ze(O),!mr)throw new Error("Invalid provider returned for APM intent")}catch(gt){if(gt===Ni){let Et=Te?.now()??globalThis.performance?.now()??Date.now();Te?.error({errorCode:Nu(Er),stage:an,requestCategory:Er,paymentMethodCategory:"wallet",provider:"stripe",...$t?{walletType:$t}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Vr,durationMs:Math.max(0,Et-kr),statusClass:"timeout",failureCategory:_r,attempt:nr,terminalReason:"provider_error"}),Te?.flush?.().catch(()=>{})}H(),At(B,gt,gt===Ni?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",F?.generation,gt===Ni)}finally{if(window.clearTimeout(Pr),Kt!==null&&(window.clearTimeout(Kt),Y.current.delete(Kt)),!Or){let gt=Te?.now()??globalThis.performance?.now()??Date.now();Te?.performance({stage:"callback",durationMs:Math.max(0,gt-kr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Xr?{statusClass:"timeout"}:{}})}Oe.current&&ye(!1)}},[v,ke,e,t,r,_,z,V,n,Z,a,d,p,b,g,At,kt,he,Pt,Ye,ft,M,Re]),He=(0,o.useMemo)(()=>xi(s),[s]),L=(0,o.useMemo)(()=>s.map(c.stripeExpressMethodToOptionKey),[s]),mt=(0,o.useMemo)(()=>(0,l.jsx)(lr.ExpressCheckoutElement,{onReady:u=>{Se(Va(u,L))},onLoadError:u=>{Se("load_error"),$s(M,"stripe","wallet","provider_error")},onClick:async u=>{let S=M?.now()??globalThis.performance?.now()??Date.now();je.current=u.expressPaymentType,De.current=zc(u.expressPaymentType);let I=!0,H=window.setTimeout(()=>{I=!1,u.reject(),$(u.expressPaymentType)},_u),F=g?await g(De.current,{abandoned:()=>!I}):{proceed:!0};if(window.clearTimeout(H),!I)return;if(!F.proceed){Mt.current.delete(Re),u.reject();return}let B=Lt(u.expressPaymentType);Nt.current=!1,Rt.current={generation:B,startedAt:S},Mt.current.set(Re,{generation:B,method:u.expressPaymentType,accountPatch:F.accountPatch,sessionId:F.sessionId,nonce:F.nonce}),q(!1),M?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:B,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),m?.(De.current),u.resolve()},onConfirm:J,onCancel:()=>{let u=Mt.current.get(Re);Mt.current.delete(Re);let S=Rt.current,I=M?.now()??globalThis.performance?.now()??Date.now();if(u&&S?.generation===u.generation&&(0,c.isWalletSheetRefusedForWindowSize)({method:u.method,elapsedMs:I-S.startedAt,handoffObserved:Ht.current===u.generation})){M?.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"}),ct.current=null,At(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}M?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),Me(u?.generation),ct.current=null,q(!1),ce.current=!0,de()},options:{...Fi,paymentMethods:He,emailRequired:vt,billingAddressRequired:vt}},Re),[L,He,J,Me,m,vt,At,$,de,g,Lt,Re,M]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Wa,{state:se,placeholderTestId:"flopay-wallet-placeholder",borderRadius:k,children:(0,l.jsxs)("div",{ref:$e,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[re&&(0,l.jsxs)("button",{ref:Be,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ut,style:qs,children:["Try ",js(pt)," again"]}),we!=="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:h,disabled:we==="checking",style:qs,children:we==="checking"?"Checking payment status\u2026":"Check payment status"})]}),ut&&(0,l.jsx)(da,{identity:ut.identity,methodLabel:ut.methodLabel,onComplete:We,onCancel:()=>We(null)},ut.id),(0,l.jsxs)("div",{style:{display:ut||we!=="idle"?"none":void 0},children:[(0,l.jsx)(Qu,{active:G}),mt]})]})}),Ie&&(0,l.jsx)(nn,{status:"processing"})]})}function Gc(e,t,r){let n=(0,c.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function Vs({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:d,onTokenizedBody:p,onErrorChange:m,onDecline:b,onCancel:P,runBeforeButtonClick:g,onButtonClick:_,isProcessing:V,submitButtonColor:W,submitButtonBorderRadius:k,submitButtonStyle:T,errorText:y}){let K=fo(),{emitInstrument:Z}=(0,o.useContext)(kn),v=(0,lr.useStripe)(),ke=(0,lr.useElements)(),[M,se]=(0,o.useState)(!1),Se=(0,o.useRef)(!1),[Ie,ye]=(0,o.useState)(!1),[vt,ut]=(0,o.useState)("loading"),[z,We]=(0,o.useState)(""),$e=!(0,c.isValidEmail)(n?.trim()),Be=!$e||(0,c.isValidEmail)(z.trim()),Re=(0,o.useCallback)(async()=>{if(!v||!ke||V||Se.current||!Ie)return;Se.current=!0,se(!0);let X=g?await g("card"):{proceed:!0};if(!X.proceed){Se.current=!1,se(!1);return}_?.("card");let G=X.sessionId??t,tt=X.nonce??r,Ee=(0,la.splitFullName)(a?.trim()),qe=(0,En.compactBuyerIdentity)({email:X.accountPatch?.email?.trim()||n?.trim()||z.trim(),firstName:X.accountPatch?.firstName?.trim()||Ee.firstName,lastName:X.accountPatch?.lastName?.trim()||Ee.lastName}),re=qe.email,q=(0,En.compactBuyerIdentity)({...X.accountPatch,...qe});try{if(m?.(null),!(0,c.isValidEmail)(re))throw new Error("A valid email address is required for payment.");await s?.(qe);let we=await ke.submit();if(we.error){m?.(we.error.message??"Payment failed.");return}let Q=[qe.firstName,qe.lastName].filter(Boolean).join(" "),pt=await v.createPaymentMethod({elements:ke,params:{billing_details:{email:re,...Q?{name:Q}:{}}}});if(pt.error||!pt.paymentMethod){m?.(pt.error?.message??"Failed to create payment method.");return}let fe=pt.paymentMethod;if(!G||!re)throw new Error("Missing sessionId or email for payment.");let Pe=fe.type||e,Oe=await qi(d,Z,G,tt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Pe,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(Oe)){p({type:"card",gateway:"stripe",paymentMethodType:Pe},{accountPatch:q,paymentMethodCategory:"apm",sessionId:G,nonce:tt,settledProcessResponse:Oe.response});return}if(Oe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ce=Oe.clientSecret;cr(no,{clientSecret:ce,sessionId:G,nonce:tt,accountPatch:q,paymentMethodId:fe.id,paymentMethodType:fe.type??e,gateway:"stripe"});let{error:je,paymentIntent:De}=await v.confirmPayment({clientSecret:ce,confirmParams:{return_url:window.location.href,payment_method:fe.id},redirect:"if_required"});if(je){cr(no);let Y=je.message??"Payment failed.";m?.(Y),b?.(Cr("card",Y,{code:je.code})),await ji({billingApiUrl:d,sessionId:G,nonce:tt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:je.code??"provider_declined"}});return}let nt=De?.status;if(!Ma(nt)){cr(no);let Y=nt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(Y),b?.(Cr("card",Y,{code:nt??"missing_payment_intent"}));return}cr(no);let ct=typeof De?.payment_method=="string"?De.payment_method:De?.payment_method?.id;p({id:ct??fe.id,type:"card",threeDSecureActionResultTokenId:De?.id,gateway:"stripe",paymentMethodType:fe.type??e},{accountPatch:q,paymentMethodCategory:"apm",sessionId:G,nonce:tt})}catch(we){m?.(we instanceof Error?we.message:"Payment failed. Please try again.")}finally{Se.current=!1,se(!1)}},[v,ke,V,Ie,g,_,t,r,n,a,z,s,d,Z,e,p,m,b]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[$e&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:$e&&(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:z,onChange:X=>We(X.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(lr.PaymentElement,{onReady:()=>ut("ready"),onLoadError:()=>{ut("load_error"),$s(br(K),"stripe","apm")},onChange:X=>{ye(!!X.complete)},options:{layout:Bi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,c.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,l.jsx)(Oi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Re()},disabled:!Ie||!Be||M||V||vt!=="ready",color:W,borderRadius:k,style:T,children:M?"Processing\u2026":`Pay with ${(0,c.getStripeMethodDisplayName)(e)}`}),y&&(0,l.jsx)(ma,{margin:"0.75rem 0 0",children:y})]})}function Vc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:d,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:b,onTokenizedBody:P,onErrorChange:g,onButtonClick:_,onDecline:V,runBeforeButtonClick:W,onLoadStateChange:k,isProcessing:T=!1,submitButtonColor:y="#4A49FF",submitButtonBorderRadius:K=8,submitButtonStyle:Z,buttonAppearance:v,themeId:ke,onExpandApm:M,expandedApmMethod:se}){let{emitInstrument:Se}=(0,o.useContext)(kn),[Ie,ye]=(0,o.useState)(null),[vt,ut]=(0,o.useState)(null),z=(0,o.useRef)(!1),{request:We,collect:$e,finish:Be}=ca();(0,o.useEffect)(()=>{d.length>0&&p?k?.("ready"):p||k?.("loading")},[d.length,p,k]);let Re=(0,o.useCallback)(async re=>{if(!p||z.current||T)return;z.current=!0,ut(re);let q=W?await W("card"):{proceed:!0};if(!q.proceed){z.current=!1,ut(null);return}_?.("card");let we=q.sessionId??e,Q=q.nonce??t,pt=(0,la.splitFullName)([q.accountPatch?.firstName,q.accountPatch?.lastName].filter(Boolean).join(" ")||n),fe=(0,En.compactBuyerIdentity)({email:q.accountPatch?.email?.trim()||r?.trim(),firstName:q.accountPatch?.firstName?.trim()||pt.firstName,lastName:q.accountPatch?.lastName?.trim()||pt.lastName});if(!(0,c.isValidEmail)(fe.email)){ut(null);let ce=await $e((0,c.getStripeMethodDisplayName)(re),fe);if(!ce){z.current=!1;return}fe=ce,ut(re)}let Pe=fe.email,Oe=(0,En.compactBuyerIdentity)({...q.accountPatch,...fe});try{if(g?.(null),!we||!(0,c.isValidEmail)(Pe))throw new Error("Missing sessionId or email for payment.");await a?.(fe);let ce=await qi(s,Se,we,Q??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(ce)){P({type:"card",gateway:"stripe",paymentMethodType:re},{accountPatch:Oe,paymentMethodCategory:"apm",sessionId:we,nonce:Q,settledProcessResponse:ce.response});return}if(ce.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let je=ce.clientSecret;cr(no,{clientSecret:je,sessionId:we,nonce:Q,accountPatch:Oe,paymentMethodType:re,gateway:"stripe"});let{error:De,paymentIntent:nt}=await p.confirmPayment({clientSecret:je,confirmParams:{return_url:window.location.href,payment_method_data:{type:re,billing_details:{name:[fe.firstName,fe.lastName].filter(Boolean).join(" "),...Pe?{email:Pe}:{}}}},redirect:"if_required"});if(De){cr(no);let Rt=De.message??"Payment failed.";g?.(Rt),V?.(Cr("card",Rt,{code:De.code})),await ji({billingApiUrl:s,sessionId:we,nonce:Q,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,providerDeclineReason:De.code??"provider_declined"}});return}let ct=nt?.status;if(!Ma(ct)){cr(no);let Rt=ct==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(Rt),V?.(Cr("card",Rt,{code:ct??"missing_payment_intent"}));return}cr(no);let Y=typeof nt?.payment_method=="string"?nt.payment_method:nt?.payment_method?.id;P({id:Y??nt?.id,type:"card",threeDSecureActionResultTokenId:nt?.id,gateway:"stripe",paymentMethodType:re},{accountPatch:Oe,paymentMethodCategory:"apm",sessionId:we,nonce:Q})}catch(ce){g?.(ce instanceof Error?ce.message:"Payment failed. Please try again.")}finally{z.current=!1,ut(null)}},[p,T,W,_,e,t,r,$e,s,Se,n,a,P,g,V]),[X,G]=(0,o.useState)(null),tt=M?se??null:X,Ee=(0,o.useCallback)(re=>{z.current||T||tt&&tt!==re||((0,c.needsStripeMethodExplicitConfirm)(re)?M?M(re):G(re):Re(re))},[tt,T,Re,M]),qe=(0,o.useMemo)(()=>X?Gc(m,X,b):null,[X,m,b]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:We?(0,l.jsx)(da,{identity:We.identity,methodLabel:We.methodLabel,onComplete:Be,onCancel:()=>Be(null)},We.id):d.map(re=>{let q=se===re,we=vt===re,Q=vt!==null&&vt!==re||se!=null&&se!==re;return(0,l.jsxs)(o.default.Fragment,{children:[(0,l.jsx)(Ai,{method:re,themeId:ke,submitting:we,disabled:Q,highlighted:q,hasNextStep:(0,c.needsStripeMethodExplicitConfirm)(re),onClick:()=>Ee(re),backgroundColor:v?.backgroundColor,borderColor:v?.borderColor,textColor:v?.textColor,borderRadius:v?.borderRadius,fontFamily:v?.fontFamily}),!M&&X===re&&qe&&p&&(0,l.jsx)(lr.Elements,{stripe:p,options:qe,children:(0,l.jsx)(Vs,{method:re,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:P,onErrorChange:g,onDecline:V,onCancel:()=>G(null),runBeforeButtonClick:W,onButtonClick:_,isProcessing:T,submitButtonColor:y,submitButtonBorderRadius:K,submitButtonStyle:Z})},re)]},re)})})}function ep({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:d,onError:p,onDecline:m,onCancel:b,onTokenizedBody:P,firstName:g,lastName:_,chv:V,className:W,submitLabel:k,isProcessing:T,error:y,onErrorChange:K,showPayPal:Z=!0,showStripe:v=!0,walletPresentation:ke="auto",enabledPaymentMethods:M,enabledPaymentMethodCountries:se,showApplePay:Se=!0,showGooglePay:Ie=!0,layout:ye="default",paymentMethodLayout:vt,moreOptionsLabel:ut,theme:z,buttonsTheme:We,buttonsStyles:$e,appearance:Be,cardButtonContent:Re,cardBackButtonContent:X,cardTitleContent:G,showSecurityFooter:tt,onButtonClick:Ee,onBeforeButtonClick:qe,onBuyerIdentityReady:re,enableAVS:q,cardFieldOrder:we,cardAutoFocus:Q,onCardFieldsReady:pt,onCardFieldsFailed:fe,cardFieldsTimeoutMs:Pe,cardPreFormSlot:Oe,avsLayout:ce="row",country:je,zip:De,addressLine1:nt,addressLine2:ct,city:Y,state:Rt,onCountryChange:Ht,onZipChange:Mt,avsCheck:Lt,checkoutType:he,checkoutLayout:Me,totalAmount:Ye=0,currency:Pt="usd",initialCardOpen:ft=!1,directPaypal:ze,isSubscription:Nt=!1,session:de,dataAttachmentPending:kt=!1,dataAttachmentRequiresIdentity:At=!1,debug:$=!1}){let ge=fo(),Ut=Pi(),h=(0,o.useContext)(zn),{emitInstrument:J}=(0,o.useContext)(kn),He=(0,o.useRef)(null);He.current||(He.current=Ci());let L=He.current,[,mt]=(0,o.useState)(0),u=(0,o.useRef)(null);u.current||(u.current=(0,eo.detectPayPalEnvironment)());let S=u.current,I=(0,o.useMemo)(()=>({browser:S,capability:L,presentationMode:"popup"}),[S,L]),H=de??h.session,F=(0,o.useMemo)(()=>({futureUse:H?.futureUse,futureUseUnsupported:H?.futureUseUnsupported}),[H?.futureUse,H?.futureUseUnsupported]),B=H?.gateways?.paypal?.providerObjectType??ze?.providerObjectType,Ae=kt||h.claimPending===!0,jr=At||h.claimRequiresIdentity===!0,$t=Ae&&!jr,nr=cc(),Te=r||nr,kr=xc({rules:vt,sessionId:e,nonce:t,billingApiUrl:Te,waitForSession:$t}),Ur=kr?.order??null,[Xr,Or]=(0,o.useState)(!1),Kt=(0,o.useMemo)(()=>Ur?(0,c.keyPaymentMethodOrder)(Ur):null,[Ur]),Vr=Ur!==null&&(0,c.isCardFormFirst)(Ur),[an,Er]=(0,o.useState)(!1),[_r,vn]=(0,o.useState)(null),[at,Pr]=(0,o.useState)(je??""),[Xt,gt]=(0,o.useState)(De??""),[Et,sn]=(0,o.useState)(nt??""),[zr,Dr]=(0,o.useState)(ct??""),[ln,Jr]=(0,o.useState)(Y??""),[Ir,cn]=(0,o.useState)(Rt??""),[Zr,Lr]=(0,o.useState)(""),[or,vr]=(0,o.useState)({}),ur=(0,o.useRef)(De??""),pr=(0,o.useRef)(je??""),Tr=(0,o.useRef)(nt??""),Mr=(0,o.useRef)(ct??""),Qr=(0,o.useRef)(Y??""),mr=(0,o.useRef)(Rt??""),tr=(0,o.useRef)(""),Nr=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(C,N,be,te,Fe)=>{if(Nr.current[C])return;let Vt=N?.trim();!Vt||Vt===be.current||(be.current=Vt,te(Vt),Fe?.(Vt))};i("country",je,pr,Pr,Ht),i("zip",De,ur,gt,Mt),i("addressLine1",nt,Tr,sn),i("addressLine2",ct,Mr,Dr),i("city",Y,Qr,Jr),i("state",Rt,mr,cn)},[je,De,nt,ct,Y,Rt,Ht,Mt]);let Ze=(0,o.useMemo)(()=>(0,c.resolveAVSConfig)(q),[q]),Cn=Ze!==null,O=(0,o.useMemo)(()=>(0,c.isAuthorizationOnlySession)(de),[de]),Qe=(0,c.isMountableVaultBlock)(de?.vault),ue=!!de?.gateways?.pcivault,ve=(0,Un.hasServerSideCardGateway)(de),zt=!!(de?.gateways?.stripe?.enabledPaymentMethods??M)?.includes("card")||(0,Un.canRecoverHostedCardForm)(de),xt=Qe||zt||ue,U=!!(v&&xt&&e),[bn,Vo]=(0,o.useState)(()=>ye!=="buttons"||ft?e??null:null),[Io,Sn]=(0,o.useState)(0),xn=ye!=="buttons"||ft||!!e&&bn===e,dn=de?.captureMethod,en=(0,o.useRef)(ge);(0,o.useEffect)(()=>{en.current=ge},[ge]);let ar=(0,o.useRef)(Pe);ar.current=Pe;let Fn=(0,o.useRef)({onCardFieldsReady:pt,onCardFieldsFailed:fe,emitInstrument:J});Fn.current={onCardFieldsReady:pt,onCardFieldsFailed:fe,emitInstrument:J};let[un,Bn]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!U||!e||!xn){Bn(null);return}let i=en.current?en.current.cardCapture({sessionId:e,captureMethod:dn,cardFieldsTimeoutMs:ar.current}):new Wn.PciVaultCardCapture({sessionId:e,captureMethod:dn,billingApiUrl:Te,telemetry:n,cardFieldsTimeoutMs:ar.current}),C=i.onCardFields?.(N=>{let be=Fn.current;be.emitInstrument?.((0,c.cardFieldsInstrumentSource)(N)),N.type==="card_fields_ready"?(0,c.invokeMerchantCallback)(()=>be.onCardFieldsReady?.(N)):(0,c.invokeMerchantCallback)(()=>be.onCardFieldsFailed?.(N))});return Bn({sessionId:e,captureMethod:dn,billingApiUrl:Te,telemetry:n,capture:i}),()=>{C?.(),i.unmount()}},[U,e,xn,dn,Te,n]);let Ft=U&&e&&xn&&un?.sessionId===e&&un.captureMethod===dn&&un.billingApiUrl===Te&&un.telemetry===n?un.capture:null,tn=(0,o.useMemo)(()=>{let i=at,C=Ze?(0,c.isAVSFieldVisible)(Ze.postal_code,i):!1;return Yu(i,Xt,C)},[Ze,at,Xt]),{avsInvalid:pn,invalidAvsFields:io}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!U||!Ze)return{avsInvalid:!1,invalidAvsFields:i};let C=at,N=(Fe,Vt)=>(0,c.isAVSFieldVisible)(Fe,C)&&!Vt.trim(),be={line1:N(Ze.address_line_1,Et),city:N(Ze.city,ln),state:N(Ze.state,Ir),zip:tn.empty||tn.malformed};return{avsInvalid:be.line1||be.city||be.state||be.zip,invalidAvsFields:be}},[U,Ze,at,Et,ln,Ir,tn]),[mn,On]=(0,o.useState)(!1),[so,$n]=(0,o.useState)(!1),[Hn,Kn]=(0,o.useState)(!1),[lo,Wo]=(0,o.useState)({line1:!1,city:!1,state:!1}),Gn=(0,o.useRef)(!1),co=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Yn=(0,o.useRef)(!1),qt=(0,o.useCallback)(i=>{co.current[i]=!0,Yn.current=!0},[]),Xn=(0,o.useCallback)(i=>!Gn.current&&co.current[i],[]),yn=(0,o.useCallback)(i=>{Xn(i)&&Wo(C=>C[i]?C:{...C,[i]:!0})},[Xn]),[wn,fn]=(0,o.useState)(()=>(0,c.resolveVaultMountOptions)(de?.vault,{billingApiUrl:Te,sessionId:e,nonce:t})),[dt,Ar]=(0,o.useState)(ft&&xt?"card":"buttons"),[Jt,A]=(0,o.useState)(null),D=dt==="expanding"||dt==="card",ne=de?.gateways?.stripe&&!ve?"stripe":void 0,Ce=(0,o.useCallback)(()=>{J?.({class:"card_surface",provider:ne})},[ne,J]),_t=(0,o.useCallback)(()=>{Or(!0),J?.({class:"more_options"})},[J]),Zt=(0,o.useRef)(null),xe=(0,o.useCallback)(i=>{Zt.current&&clearTimeout(Zt.current),Zt.current=setTimeout(()=>{Zt.current=null,i()},Xa)},[]);(0,o.useEffect)(()=>()=>{Zt.current&&clearTimeout(Zt.current)},[]);let it=(0,o.useRef)(!1),[oe,et]=(0,o.useState)(0),pe=(0,o.useRef)(null),yt=(0,o.useCallback)(()=>{Ce(),Vo(e??null),it.current&&(it.current=!1,et(i=>i+1)),Sn(i=>i+1),Ar("expanding"),xe(()=>Ar("card"))},[xe,Ce,e]),le=(0,o.useCallback)(()=>{Ar("collapsing"),xe(()=>Ar("buttons"))},[xe]),f=(0,o.useCallback)(i=>{A(i),Ar("apm-expanding"),xe(()=>Ar("apm-form"))},[xe]),w=(0,o.useCallback)(()=>{Ar("apm-collapsing"),xe(()=>{Ar("buttons"),A(null)})},[xe]);(0,o.useEffect)(()=>{ye==="buttons"&&ft&&xt&&(Vo(e??null),Ar("card"))},[ye,ft,xt,e]);let[j,ae]=(0,o.useState)(null),ee=(0,o.useRef)(null),[ie,Bt]=(0,o.useState)(0);(0,o.useEffect)(()=>{ie!==0&&ee.current?.focus()},[ie]);let Ot=(0,o.useRef)(!1),st=(0,o.useRef)(null),Ct=(0,o.useRef)("idle"),[It,Xe]=(0,o.useState)(!1),Ke=(0,o.useRef)(It);Ke.current=It;let[Le,jt]=(0,o.useState)(()=>ze?.existingOrderId?{orderId:ze.existingOrderId,attempts:1}:null),wt=(0,o.useRef)(Le);(0,o.useEffect)(()=>{wt.current=Le},[Le]);let Wr=(0,o.useRef)(null),Qt=(0,o.useMemo)(()=>{if(re||h.claimBuyerIdentity||de?.buyerIdentified!==!1||!e||!t)return;let i=`${Te}|${e}|${t}`;Wr.current?.key!==i&&(Wr.current={key:i,claim:ia(new Wn.PaymentAPI(Te,{telemetry:!1}),e,t,{...s?{userId:s}:{},...g?{firstName:g}:{},..._?{lastName:_}:{}})});let C=Wr.current.claim;return async N=>{await C(N)}},[re,h.claimBuyerIdentity,de?.buyerIdentified,e,t,Te,s,g,_]),$r=re??h.claimBuyerIdentity??Qt,Dn=y??_r,$o=(0,o.useMemo)(()=>(0,c.resolveTheme)(z),[z]),rt=(0,o.useMemo)(()=>{let i=$o?.buttonsLayout??(0,c.resolveButtonsLayoutTheme)(We);return $e?{...i,...$e,cardButton:{...i.cardButton,...$e.cardButton},cardFormContainer:{...i.cardFormContainer,...$e.cardFormContainer},backButton:{...i.backButton,...$e.backButton},backButtonIcon:{...i.backButtonIcon,...$e.backButtonIcon},submitButton:{...i.submitButton,...$e.submitButton},title:{...i.title,...$e.title}}:i},[$o,We,$e]),Ho=Be??$o?.appearance,Pd=(0,o.useMemo)(()=>(0,c.computeVaultCardThemeColors)({appearance:Ho,buttonsStyles:rt,layout:ye}),[Ho,rt,ye]),vd=h.inlineSessionPatchProcessing??!1,ir=(T??an)||vd,Co=Te.replace(/\/+$/,""),Tt=(0,o.useMemo)(()=>Es({userId:s,email:a,firstName:g,lastName:_,country:je,zip:De},or),[s,a,g,_,je,De,or]),Ko=[Tt.firstName,Tt.lastName].filter(i=>!!i?.trim()).join(" "),al=!(0,c.isValidEmail)(Tt.email?.trim()),Zi=(0,o.useRef)(null);U&&Zi.current===null&&(Zi.current=al);let bo=U&&(Zi.current??al),Qi=(0,o.useMemo)(()=>Xu(Zr,bo),[Zr,bo]),Go=Qi.empty||Qi.malformed,gn=(0,o.useMemo)(()=>ge?ge.getRawProvider():null,[ge]),il=(0,o.useMemo)(()=>Ut?Ut.getRawProvider():null,[Ut]),va=Ye||100,Yo=Pt.toLowerCase(),es=(0,o.useMemo)(()=>Ho?(0,Wn.toStripeAppearance)(Ho):null,[Ho]),Xo=es,sl=(0,o.useMemo)(()=>{let i=es??{},C=i.rules??{};return{...i,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[es]),ll=(0,o.useMemo)(()=>({...ic(Ye,H?.captureMethod,F),currency:Yo,...Xo?{appearance:Xo}:null}),[Ye,Yo,H?.captureMethod,F,Xo]),ts=(0,c.resolveSetupFutureUsage)(F,"paypal","paypal"),cl=(0,o.useMemo)(()=>({mode:"payment",amount:va,currency:Yo,captureMethod:"manual",...ts?{setupFutureUsage:ts}:null,...Xo?{appearance:Xo}:null}),[va,Yo,ts,Xo]),Ne=(0,o.useCallback)(i=>{vn(i),K?.(i)},[K]),dl=(0,o.useRef)(0);(0,o.useEffect)(()=>{oe!==dl.current&&(dl.current=oe,Ne(null))},[oe,Ne]);let rs=(0,o.useRef)(""),[ul,Cd]=(0,o.useState)(!1),ns=(0,o.useCallback)(()=>{Cd(!0)},[]);(0,o.useEffect)(()=>{if(!U||!bo||!$r||!ul||Go||rs.current)return;let i=(0,En.compactBuyerIdentity)({email:(0,c.isValidEmail)(Tt.email?.trim())?Tt.email?.trim():tr.current.trim(),firstName:Tt.firstName?.trim(),lastName:Tt.lastName?.trim()});rs.current=JSON.stringify(i),vr(C=>({...C,...i})),Promise.resolve($r(i)).catch(C=>{rs.current="",Ne(C instanceof Error?C.message:"Failed to attach buyer details.")})},[U,bo,$r,ul,Go,Tt.email,Tt.firstName,Tt.lastName,Ne]),(0,o.useEffect)(()=>{if(!U||!Ft)return;let i=Q!==!1&&Ze==null&&!bo;Ft.setCardFieldOrder?.(we??null,i)},[U,Ft,we,Q,Ze,bo]),(0,o.useEffect)(()=>{(dt==="expanding"||dt==="collapsing"||dt==="apm-expanding"||dt==="apm-collapsing")&&Ne(null)},[dt,Ne]);let Jn=(0,o.useCallback)((i,C,N)=>{m?.(Cr(i,C,N))},[m]),pl=(0,o.useRef)(dt);pl.current=dt;let[ml]=(0,o.useState)(Si),yl=(0,o.useCallback)(()=>{let i=pl.current;if(ye==="buttons"&&(i==="card"||i==="expanding"))return!0;let C=Ct.current;return C==="validation-window"||C==="processing"||Ke.current},[ye]),fl=(0,o.useCallback)((i,C,N)=>{ml.take(e)&&br(ge)?.log(Lo({...I,presentationMode:N?.presentationMode??"popup"},{name:bi,stage:"recovery",reason:"other_method_active",provider:N?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:N?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[I,ge,ml,e]),ti=(0,o.useCallback)((i,C,N)=>{N?.telemetryReported||br(ge)?.error(Lo({...I,presentationMode:N?.presentationMode??"popup"},{errorCode:C?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:N?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:N?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:N?.terminalReason??(C?"popup_blocked":"provider_error")}))},[I,ge]),Jo=(0,o.useCallback)((i,C,N)=>{let be=N?.popupBlocked??(0,_e.isPopupBlockedError)(C);if(yl()){ti(i,be,N),fl(i,C,N);return}if(C instanceof c.FloPayError&&C.code==="checkout_processing_timeout"){ti(i,!1,N),ae(null),ye==="buttons"&&(Ar("buttons"),A(null)),Ne(C.message),p?.(C);return}be&&L.markBlocked()&&mt(bt=>bt+1);let te=js(i),Fe=N?.code===c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,c.buildWalletSheetWindowMessage)(te):(0,_e.buildExternalMethodRecoveryMessage)(te,be,S.inAppBrowser),Vt=(0,_e.getProviderErrorCode)(C),Wt=(Vt?.toLowerCase()==="error"?void 0:Vt)??(0,_e.sanitizeExternalFailureCode)(N?.code)??"external_payment_method_failed",ot=new c.FloPayError(Fe,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:Wt,popupBlocked:be,inAppBrowser:S.inAppBrowser,appFamily:S.appFamily,popupCapability:L.current(),presentationMode:N?.presentationMode??"popup"}});ti(i,be,N),ae(null),ye==="buttons"&&(Ar("buttons"),A(null)),Ne(Fe),p?.(ot),console.error("[FloPay] External payment method failed:",{method:i,code:Wt,popupBlocked:be})},[S,yl,ye,p,L,fl,ti,Ne]);(0,o.useEffect)(()=>{if(!U||!e){fn(null);return}let i={billingApiUrl:Co,sessionId:e,nonce:t},C=(0,c.resolveVaultMountOptions)(de?.vault,i);if(C){fn(C);return}if(!xn){fn(null);return}let N=`${Co}\0${e}\0${t??""}`,be=pe.current;if(be&&be.key===N){fn(be.mount);return}fn(null);let te=!0;return new Wn.PaymentAPI(Co).getVaultCapture(e,t).then(Fe=>{if(!te)return;let Vt=(0,c.resolveVaultMountOptions)(Fe,i);Vt?.verificationRequired&&!Fe.html&&(pe.current={key:N,mount:Vt}),Vt?fn(Vt):Ne("Failed to load the secure card form.")}).catch(Fe=>{te&&Ne(Fe instanceof Error?Fe.message:"Failed to load the secure card form.")}),()=>{te=!1}},[U,xn,Io,e,de?.vault,Co,t,Ne]);let Ln=(0,o.useRef)({onComplete:d,onError:p,updateError:Ne,emitDecline:Jn,resolvedAccount:Tt,avsConfig:Ze,avsCheckProp:Lt,sessionId:e,nonce:t,baseUrl:Co,captureMethod:de?.captureMethod,paymentId:de?.paymentId,authorizationExpiresAt:de?.authorizationExpiresAt,serverSideCardGateway:ve});Ln.current={onComplete:d,onError:p,updateError:Ne,emitDecline:Jn,resolvedAccount:Tt,avsConfig:Ze,avsCheckProp:Lt,sessionId:e,nonce:t,baseUrl:Co,captureMethod:de?.captureMethod,paymentId:de?.paymentId,authorizationExpiresAt:de?.authorizationExpiresAt,serverSideCardGateway:ve};let os=(0,o.useRef)(!1),gl=(0,o.useCallback)(()=>{let i=Ln.current,C=i.resolvedAccount.email?.trim(),N=(0,c.isValidEmail)(C)?C:tr.current.trim();if(!(0,c.isValidEmail)(N))return null;let be=i.resolvedAccount.firstName?.trim(),te=i.resolvedAccount.lastName?.trim(),Fe=pr.current.trim()||i.resolvedAccount.country?.trim()||"",Vt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.state,Fe):!1,Wt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_1,Fe):!1,ot=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.postal_code,Fe):!1,bt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.city,Fe):!1,Dt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_2,Fe):!1,yr=Wt&&!Vt&&ot?(0,c.getStateFromPostalCode)(Fe,(ur.current??"").trim()):null,hn=Vt?mr.current:yr;return{accountData:{userId:i.resolvedAccount.userId??"",email:N,...be?{firstName:be}:{},...te?{lastName:te}:{},...ot&&ur.current?{zip:ur.current}:{},...bt&&Qr.current?{city:Qr.current}:{},...hn?{state:hn}:{},...Wt&&Tr.current?{addressLine1:Tr.current}:{},...Dt&&Mr.current?{addressLine2:Mr.current}:{},...Fe?{country:Fe}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,c.isAVSFieldVisible)(i.avsConfig.country,Fe),postal_code:ot,address_line_1:Wt,address_line_2:Dt,city:bt,state:Vt}}:{}}},[]),hl=(0,o.useRef)(Ae);hl.current=Ae,(0,o.useEffect)(()=>{Ae||Dn!==Lc||Ln.current.updateError(null)},[Ae,Dn]),(0,o.useEffect)(()=>{!U||!Ft||Ft.setSubmitGate?.(pn||Ae||Go||It)},[U,Ft,pn,Ae,Go,It]),(0,o.useEffect)(()=>{if(!U||!Ft)return;os.current=!1;let i=null,C=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,Ct.current="idle",ae(null)},400)},N=Ft.on("submitting",()=>{On(!0),st.current&&clearTimeout(st.current),Ct.current="validation-window",st.current=setTimeout(()=>{st.current=null,Ct.current==="validation-window"&&(Ct.current="processing")},Uu),ae("processing");let ot=Ln.current;if(!ot.sessionId||!ot.nonce)return;let bt=gl();if(!bt){ot.updateError("Enter a valid email address."),Ct.current="idle",ae(null);return}new Wn.PaymentAPI(ot.baseUrl).patchAccountSnapshot(ot.sessionId,ot.nonce,bt,{telemetryMode:"best_effort"}).catch(Dt=>{if(!qu(Dt))return;let yr=Dt instanceof Error?Dt.message:"Please check your billing address and try again.";ot.updateError(yr),Ct.current="idle",ae(null),ot.onError?.(Dt instanceof c.FloPayError?Dt:new c.FloPayError(yr,"api_error"))})}),be=Ft.on("complete",ot=>{(0,jn.markSessionRecentlyCompleted)(ot.sessionId??Ln.current.sessionId),Ct.current="terminal",Xe(!1),ae("success"),setTimeout(()=>{if(os.current)return;os.current=!0;let bt=Ln.current,Dt=(0,c.isAuthorizationOnlySession)(bt)||ot.outcome==="authorized",yr=bt.serverSideCardGateway?{}:{paymentIntentId:ot.intentId};Ln.current.onComplete?.(Dt?{status:"authorized",...yr,paymentId:ot.paymentId??bt.paymentId,sessionId:ot.sessionId??bt.sessionId,authorizationExpiresAt:ot.authorizationExpiresAt??bt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...yr,checkoutMethod:"card"})},600)}),te=Ft.on("decline",ot=>{let bt=Ln.current,Dt=ot.message??"Your payment was declined. Please try another card or contact your bank.";Ct.current="terminal",Xe(!1),bt.updateError(Dt),ae("error");let yr=ot.failureOutcome??(0,c.normalizeCheckoutFailureOutcome)(ot.declineReason)??"authorization_declined";bt.emitDecline("card",Dt,{code:yr,declineCode:yr}),C()}),Fe=Ft.on("error",ot=>{let bt=Ln.current,Dt=(0,c.buyerEmailRequiredPrompt)(ot.vaultOutcome);if(Dt!==null){i&&(clearTimeout(i),i=null),Ct.current="idle",Xe(!1),bt.updateError(Dt),ae(null),Bt(hn=>hn+1),bt.onError?.(new c.FloPayError(Dt,"api_error",{code:c.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let yr=ot.message??"There was a problem processing your payment. Please try again.";Ct.current="terminal",Xe(!1),bt.updateError(yr),ae("error"),bt.onError?.(new c.FloPayError(yr,"api_error",{code:ot.failureOutcome??"capture_failed"})),C()}),Vt=Ft.on("challenge_dismissed",()=>{st.current&&(clearTimeout(st.current),st.current=null),Ct.current="processing",Xe(!0),ae(null)}),Wt=Ft.on("blocked",()=>{if(Ke.current){Ln.current.updateError(zu);return}if(!hl.current){On(!0);return}ns(),Ln.current.updateError(Lc)});return()=>{i&&(clearTimeout(i),i=null),st.current&&(clearTimeout(st.current),st.current=null),Ct.current="idle",Xe(!1),ae(null),N(),be(),te(),Fe(),Vt(),Wt()}},[U,Ft,ns,gl]);let Zn=!!ze?.clientId,Ca=Array.isArray(M),ri=Ca&&M.length>0,Pl=Ca&&M.includes("paypal"),ni=(0,o.useRef)(null);ni.current===null&&(ni.current=(0,c.hasMatchingStripePayPalReturn)());let Zo=ni.current?"redirect":(0,to.resolveStripePayPalPresentation)(S,ke,L.current()),{expressMethods:oi,paymentElementMethods:as}=(0,o.useMemo)(()=>(0,c.partitionStripeMethods)(M,{excludePaypal:Zn}),[M,Zn]),vl=Zn||!!Ut||Pl&&Zo==="redirect",bd=(0,o.useMemo)(()=>vl?oi.filter(i=>i!=="paypal"):oi,[oi,vl]),Sd=(0,o.useMemo)(()=>{let i=[];return Se&&i.push("apple_pay"),Ie&&i.push("google_pay"),i},[Se,Ie]),Qo=Ca?bd:Sd,wd=v&&Qo.length>0,Cl=Cn?at:je,ai=(0,o.useMemo)(()=>(0,c.filterStripeMethodsByCountryGate)(as,Cl,se),[as,Cl,se]),is=(0,o.useMemo)(()=>({mode:"payment",amount:va,currency:Yo,paymentMethodCreation:"manual",appearance:sl}),[va,Yo,sl]),[ss,bl]=(0,o.useState)("loading"),[ls,Sl]=(0,o.useState)("loading"),[cs,wl]=(0,o.useState)("loading"),[Rd,ds]=(0,o.useState)(!1),[Rl,us]=(0,o.useState)("loading"),[ps,kd]=(0,o.useState)();(0,o.useEffect)(()=>{kd((0,eo.detectPayPalEnvironment)())},[]);let ii=ps?.inAppBrowser,si=ps?(0,to.resolvePayPalPresentationMode)(ps,ze?.approvalPresentation,B??(Nt?"subscription":"order")):"popup",kl=Z&&(Zn||(Ca?Pl:ii===!1)),Ed=S.inAppBrowser&&L.current()==="blocked",El=v&&wd&&!Ed,To=(!$t||!!h.waitForDataAttachment)&&kl&&Zn,ms=Rl==="retrying"||Rl==="exhausted",ba=null;v&&(Ut?ba=il:Zo==="redirect"&&(ba=gn));let _l=(0,o.useMemo)(()=>({...I,presentationMode:Zo}),[I,Zo]),Mo=!$t&&kl&&!!ba&&(!Zn||ms),So=!$t&&El&&!!gn,Ao=!$t&&v&&ri&&ai.length>0&&!!gn,_d=To&&!ms?Rd:Mo&&$a(ss),Id=So&&$a(ls),Td=Ao&&cs!=="load_error",Il=[To||Mo,So,Ao,U].filter(Boolean).length,Md={card:U,paypal:To&&!ms||Mo&&$a(ss),wallets:So&&$a(ls),apms:Ao&&cs!=="load_error"},Tl=i=>Md[i],Ml=i=>i==="loading"||i==="ready",Al=To||Mo&&Ml(ss)||So&&Ml(ls)||Ao&&cs!=="load_error",li=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!li.current){if(!v&&!Z){li.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(!v&&Z&&!Zn){li.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(ii!==void 0&&!$t&&!xt&&!Al){li.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)}}},[v,Z,Zn,ii,$t,xt,Al,p,Ne]);let xl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(xl.current||!ri)return;let i=[];Se!==!0&&i.push("showApplePay"),Ie!==!0&&i.push("showGooglePay"),i.length!==0&&(xl.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.`))},[ri,Se,Ie]);let Fl=(0,o.useCallback)((i,C,N)=>h.applyInlineSessionPatch?h.applyInlineSessionPatch(i).then(be=>({error:null,sessionId:be.sessionId||e,nonce:be.session?.clientSecret||t})).catch(be=>{let te=(0,c.normalizeBeforeButtonClickError)(C,be);return N?.abandoned?.()||(Ne(te.message),p?.(te)),{error:te,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[h.applyInlineSessionPatch,t,p,e,Ne]),Nn=(0,o.useCallback)(async(i,C)=>{if(i!=="card"&&$t&&await h.waitForDataAttachment?.(),!qe)return{proceed:!0};try{let N=await qe({method:i,sessionId:e||void 0,createSession:h.inlineSessionDraft});if(N===!1)return{proceed:!1};if(N&&typeof N=="object"){N.account&&vr(te=>({...te??{},...N.account}));let be=await Fl(N,i,C);return be.error?{proceed:!1,accountPatch:N.account}:{proceed:!0,accountPatch:N.account,sessionId:be.sessionId,nonce:be.nonce}}return{proceed:!0}}catch(N){if(!C?.abandoned?.()){let be=(0,c.normalizeBeforeButtonClickError)(i,N);Ne(be.message),p?.(be)}return{proceed:!1}}},[Fl,h.inlineSessionDraft,h.waitForDataAttachment,$t,qe,p,e,Ne]),Bl=(0,o.useCallback)(async(i,C)=>{if(Ot.current)return;Ot.current=!0,Er(!0),ae("processing"),Ne(null);let N=C?.sessionId??e,be=C?.nonce??t,te=Es(Tt,C?.accountPatch),Fe=C?.completionPaymentMethodId??Aa(i),Vt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,Wt=$u(i),ot=C?.presentationMode?Mi(br(ge),{...I,presentationMode:C.presentationMode}):void 0,bt=()=>{J?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Wt}),ot?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Vn,requestCategory:"process_payment"})};try{let Dt=new Wn.PaymentAPI(Co),hn=C?.settledProcessResponse??await Dt.processPayment(te.userId??"",{sessionId:N,nonce:be,paymentMethodCategory:C?.paymentMethodCategory??Ku(i),tokenizedData:Vt,accountData:{...C?.accountPatch,userId:te.userId??"",email:te.email??"",firstName:te.firstName||void 0,lastName:te.lastName||void 0,...(0,c.buildProcessPaymentAvsAccount)({avsConfig:Ze,country:pr.current,zip:ur.current,city:Qr.current,state:mr.current,addressLine1:Tr.current,addressLine2:Mr.current})},...(0,c.buildCheckoutProcessMetadata)({chv:V,avsCheck:Lt,checkoutType:he,checkoutLayout:Me,avsConfig:Ze,country:pr.current})}),mi=async xr=>{let xo=(0,c.isAuthorizationOnlySession)(de)||xr?.status==="authorized";(0,jn.markSessionRecentlyCompleted)(N),ot?.terminal({outcome:"payment_succeeded",...Vn}),ae("success"),jt(null),await new Promise(Ia=>setTimeout(Ia,600));let Qn;typeof xr?.paymentId=="string"?Qn=xr.paymentId:de?.paymentId&&(Qn=de.paymentId);let Fo;typeof xr?.authorizationExpiresAt=="string"?Fo=xr.authorizationExpiresAt:de?.authorizationExpiresAt&&(Fo=de.authorizationExpiresAt),d?.(xo?{status:"authorized",...Qn===void 0?{}:{paymentId:Qn},sessionId:typeof xr?.sessionId=="string"?xr.sessionId:N,...Fo===void 0?{}:{authorizationExpiresAt:Fo},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Fe,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Fe,checkoutMethod:i.isPaypal?"paypal":"card"})};if(hn.ok){await mi(hn.status===204?null:await hn.json().catch(()=>null));return}let fr=await hn.json().catch(()=>null);if(fr?.type==="paypal_redirect_required"){let xr=fr.threeDSecureToken,xo=fr.paymentMethodId||i.id||"";if(!ge||!xr){ae("error"),Ne("PayPal authorization required but no token provided.");return}try{let Qn=Ut?.getRawProvider();if(!Qn){Ne("PayPal is not available.");return}let Fo={return_url:window.location.href};xo&&(Fo.payment_method=xo);let{error:Ia}=await Qn.confirmPayment({clientSecret:xr,confirmParams:Fo,redirect:"if_required"});if(Ia){ae("error");let Gl=Ia.message??"PayPal payment failed.";Ne(Gl),Jn("paypal",Gl,{code:Ia.code})}}catch(Qn){ae("error"),Ne(Qn instanceof Error?Qn.message:"PayPal authorization failed.")}return}if(fr?.type==="paypal_direct_required"){let xr=fr.orderId;if(!xr){ae("error"),Ne("PayPal retry required but no order id provided.");return}let xo=wt.current?.attempts??0;if(xo>=2){ae("error"),Ne("PayPal payment could not be completed after multiple attempts."),Jn("paypal","paypal_direct_required retry limit exceeded");return}ds(!1),us("loading"),jt({orderId:xr,attempts:xo+1}),ae(null);return}if(hn.headers.get(xu)===Fu){let xr=await Bu(Dt,N,be);if(xr!==void 0){await mi(xr);return}}(0,c.classifyPaymentRejection)(hn.status,fr)?ot?.terminal({outcome:"payment_declined",...Vn,terminalReason:"provider_declined"}):bt(),ae("error");let Kl=fr?.message??"Payment failed. Please try again.";Ne(Kl),Jn(i.isPaypal?"paypal":"card",Kl,{code:fr?.code??fr?.gatewayErrorCode,declineCode:fr?.declineCode??fr?.gatewayDeclineReason}),await new Promise(xr=>setTimeout(xr,400))}catch(Dt){Hc(Dt)||bt(),ae("error"),Ne(Dt instanceof Error?Dt.message:"An unexpected error occurred"),await new Promise(yr=>setTimeout(yr,400))}finally{Er(!1),ae(null),Ot.current=!1}},[Co,e,t,Tt,Ze,Lt,he,Me,V,ge,Ut,de,d,Ne,Jn,J,I]),rn=(0,o.useCallback)((i,C)=>{P&&!C?.settledProcessResponse?P(i):Bl(i,C)},[P,Bl]),Sa=`${Wc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(Sa);if(!i)return;let C;try{C=JSON.parse(i)}catch{cr(Sa);return}if(!C||typeof C.createdAt!="number"||Date.now()-C.createdAt<0||Date.now()-C.createdAt>$c||typeof C.paymentMethodId!="string"||typeof C.providerIntentId!="string"||typeof C.paymentMethodType!="string"||C.sessionId!==e||!t||C.nonce!==t||!Qo.includes(C.paymentMethodType)){cr(Sa);return}cr(Sa),rn({id:C.paymentMethodId,type:"card",threeDSecureActionResultTokenId:C.providerIntentId,gateway:"stripe",paymentMethodType:C.paymentMethodType},{...C.accountPatch?{accountPatch:C.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[rn,t,e,Sa,Qo]);let Ol=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Ol.current)return;let[i,C,N]=(0,c.readStripeRedirectParams)();if(!i||!C||ni.current||!ge)return;let be=ge.getRawProvider();if(!be)return;let te=bt=>{let Dt=localStorage.getItem(bt);if(!Dt)return null;try{return JSON.parse(Dt)}catch{return cr(bt),null}},Fe=te(no)??te(Bc),Vt;if(Fe?.clientSecret){if(Fe.clientSecret!==C)return;Vt={...Fe.accountPatch?{accountPatch:Fe.accountPatch}:{},...Fe.sessionId?{sessionId:Fe.sessionId}:{},...Fe.nonce?{nonce:Fe.nonce}:{}}}else if(Fe?.sessionId&&Fe.sessionId!==e)return;Ol.current=!0,cr(no),cr(Bc),window.history.replaceState({},"",(0,c.stripeRedirectReturnUrl)());let Wt=Fe?.paymentMethodType??Fe?.tokenType??"card",ot="card";(async()=>{if(N==="failed"){let fr="Payment was declined. Please try again.";Ne(fr),Jn(ot,fr);return}let{paymentIntent:bt,error:Dt}=await be.retrievePaymentIntent(C);if(Dt){let fr=Dt.message??"Failed to retrieve payment status.";Ne(fr),Jn(ot,fr,{code:Dt.code});return}let yr=bt?.status,hn=Ma(yr);if(!bt||!hn){let fr=yr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ne(fr),Jn(ot,fr,{code:yr??"missing_payment_intent"});return}let mi=typeof bt.payment_method=="string"?bt.payment_method:bt.payment_method?.id;rn({id:mi??Fe?.paymentMethodId??Fe?.tokenId??bt.id,type:"card",threeDSecureActionResultTokenId:bt.id,gateway:Fe?.gateway??"stripe",paymentMethodType:Wt},Vt)})()},[e,rn,ge,Ne,Jn]);let ys=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(U||ge!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let wa=ye==="buttons",Hr=Ho?.variables,Ad=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),fs=Hr?.colorBackground,xd=fs&&!Ad.has(fs)?fs:void 0,Ra=rt.cardInputBorder??(wa?"#e5e7eb":"#A4A4FF"),Dl=Hr?.colorDanger??"#dc2626",rr=i=>io[i]&&(lo[i]||mn),ci=Go&&(Hn||mn),Rn=i=>i?Dl:Ra,di=(tn.malformed||tn.empty)&&(so||mn),Fd=Rn(di),gs=rt.cardFormContainer?.backgroundColor??xd??(wa?"white":"#EDEDFF"),ea=rt.cardInputBackground??Hr?.colorBackground??"white",hs=na(X),Ll=na(G),ta=rt.nameInput,Nl=rt.cardInputFontSize??Ju(ta?.fontSize)??Hr?.fontSizeBase??"16px",Ul=typeof ta?.fontFamily=="string"?ta.fontFamily:Hr?.fontFamily??"Poppins, sans-serif",zl=(0,c.toCssWeight)(ta?.fontWeight)??400,Bd=rt.cardInputColor??(typeof ta?.color=="string"?ta.color:void 0)??Hr?.colorText??"#262833",Od=rt.cardInputPlaceholderColor??"#9ca3af",sr=Hr?.borderRadius??"8px",uo=Hr?.borderRadius??rt.cardButton?.borderRadius??sr,wo=Hr?.colorPrimary??"#4A49FF",Dd=Hr?.colorPrimaryHover??(0,c.darkenHex)(wo,.12),Ps=Hr?.colorText??"#262833",vs={fontSize:Nl,fontFamily:Ul,fontWeight:zl,color:Bd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ka={marginTop:"0.375rem",...vs,fontSize:"0.75rem",lineHeight:1.4,color:Dl},Ld={"--flopay-input-placeholder-color":Od,"--flopay-input-font-size":Nl,"--flopay-input-font-family":Ul,"--flopay-input-font-weight":String(zl)},Ea=rt.cardFormContainer??{},Cs=Ea.padding??(wa?"0":"1rem"),bs=Ea.borderRadius??sr,Nd=Ft&&wn?(0,l.jsx)(_o,{capture:Ft,html:wn.html,messageToken:wn.messageToken,expectedOrigin:wn.expectedOrigin,verificationRequired:wn.verificationRequired,theme:Pd,submitLabel:k,onReady:()=>{if(!bo&&!Ze||typeof document>"u"||Q===!1)return;let i=()=>{let N=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(N){Gn.current=!0;try{N.focus()}finally{Gn.current=!1}}};Yn.current||i()},onError:i=>{i&&wn.verificationRequired&&Ct.current==="idle"&&(it.current=!0),Ne(i)},onValidation:i=>{let C=Ct.current;(C==="idle"||C==="validation-window")&&(Ne(i),i&&Ct.current==="validation-window"&&(st.current&&(clearTimeout(st.current),st.current=null),Ct.current="idle",ae(null)))}},oe):(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"}),Ss=(0,l.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&Ce()},style:{backgroundColor:gs,borderRadius:bs,...Ea,padding:Cs,...Ld,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 @@ ${H.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),wa&&D&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:z?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:le,style:{display:"inline-flex",alignItems:"center",gap:hs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:rt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...rt.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...rt.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(aa,{content:X})]}),Ll?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:rt.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...rt.title},children:(0,l.jsx)(Ta,{content:G})})]}),!wa&&!Ll&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ps,order:z?-3:0,...rt.title},children:(0,l.jsx)(Ta,{content:G})}),z&&Oe&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:Oe}),z&&bo&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:ea,border:`1px solid ${Rn(ci)}`,borderRadius:sr,padding:"10px"},children:(0,l.jsx)("input",{ref:oe,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Zr,onChange:i=>{qt("email"),tr.current=i.target.value,Lr(i.target.value)},onPointerDown:()=>qt("email"),onKeyDown:()=>qt("email"),onBlur:()=>{Xn("email")&&Kn(!0),Go||ns()},disabled:ir,required:!0,"aria-invalid":ci||void 0,"aria-describedby":ci?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...vs}})}),ci&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ka,children:Qi.empty?"Email address is required":"Enter a valid email address"})]}),Ze&&(0,l.jsx)("div",{style:{order:z?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=at,C=(ee=!1)=>({backgroundColor:ea,border:`1px solid ${Rn(ee)}`,borderRadius:sr,marginTop:"0.5rem",padding:"10px"}),U=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...vs}),Ce=(0,c.getStateOptions)(i);return(0,l.jsxs)(l.Fragment,{children:[(0,c.isAVSFieldVisible)(Ze.address_line_1,i)&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{style:C(rr("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:Et,onChange:ee=>{qt("line1"),Nr.current.addressLine1=!0,Tr.current=ee.target.value,sn(ee.target.value)},onPointerDown:()=>qt("line1"),onKeyDown:()=>qt("line1"),onBlur:()=>yn("line1"),disabled:ir,required:!0,"aria-invalid":rr("line1")||void 0,"aria-describedby":rr("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:U()})}),rr("line1")&&(0,l.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ka,children:"Street address is required"})]}),(0,c.isAVSFieldVisible)(Ze.address_line_2,i)&&(0,l.jsx)("div",{style:C(),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:zr,onChange:ee=>{Nr.current.addressLine2=!0,Mr.current=ee.target.value,Dr(ee.target.value)},disabled:ir,"data-testid":"flopay-address-line2",style:U()})}),((0,c.isAVSFieldVisible)(Ze.city,i)||(0,c.isAVSFieldVisible)(Ze.state,i))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(Ze.city,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:ea,borderTop:`1px solid ${Rn(rr("city"))}`,borderRight:`1px solid ${Rn(rr("city"))}`,borderBottom:`1px solid ${Rn(rr("city"))}`,borderLeft:`1px solid ${Rn(rr("city"))}`,padding:"10px",borderTopLeftRadius:sr,borderBottomLeftRadius:sr,...(0,c.isAVSFieldVisible)(Ze.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:sr}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:ln,onChange:ee=>{qt("city"),Nr.current.city=!0,Qr.current=ee.target.value,Jr(ee.target.value)},onPointerDown:()=>qt("city"),onKeyDown:()=>qt("city"),onBlur:()=>yn("city"),disabled:ir,required:!0,"aria-invalid":rr("city")||void 0,"aria-describedby":rr("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:U()})}),(0,c.isAVSFieldVisible)(Ze.state,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:ea,borderTop:`1px solid ${Rn(rr("state"))}`,borderRight:`1px solid ${Rn(rr("state"))}`,borderBottom:`1px solid ${Rn(rr("state"))}`,borderLeft:`1px solid ${Rn(rr("state"))}`,padding:"10px",borderTopRightRadius:sr,borderBottomRightRadius:sr,...(0,c.isAVSFieldVisible)(Ze.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Rn(rr("state")||rr("city"))}`}:{borderRadius:sr}},children:Ce?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Ir,onChange:ee=>{qt("state"),Nr.current.state=!0,mr.current=ee.target.value,cn(ee.target.value)},onPointerDown:()=>qt("state"),onKeyDown:()=>qt("state"),onBlur:()=>yn("state"),disabled:ir,autoComplete:"billing address-level1",required:!0,"aria-invalid":rr("state")||void 0,"aria-describedby":rr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...U(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,c.getStateLabel)(i)}),Ce.map(ee=>(0,l.jsx)("option",{value:ee.code,children:ee.name},ee.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:Ir,onChange:ee=>{qt("state"),Nr.current.state=!0,mr.current=ee.target.value,cn(ee.target.value)},onPointerDown:()=>qt("state"),onKeyDown:()=>qt("state"),onBlur:()=>yn("state"),disabled:ir,required:!0,"aria-invalid":rr("state")||void 0,"aria-describedby":rr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:U()})})]}),rr("city")&&(0,l.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ka,children:"City is required"}),rr("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ka,children:[(0,c.getStateLabel)(i)," is required"]}),((0,c.isAVSFieldVisible)(Ze.country,i)||(0,c.isAVSFieldVisible)(Ze.postal_code,i))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:ce==="column"?"column":"row",gap:ce==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(Ze.country,i)&&(0,l.jsx)("div",{style:{flex:ce==="row"?1:void 0,backgroundColor:ea,borderTop:`1px solid ${Ra}`,borderRight:`1px solid ${Ra}`,borderBottom:`1px solid ${Ra}`,borderLeft:`1px solid ${Ra}`,padding:"10px",...ce==="row"&&(0,c.isAVSFieldVisible)(Ze.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:sr,borderBottomLeftRadius:sr,borderRight:"none"}:{borderRadius:sr}},children:(0,l.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:at,onChange:ee=>{Nr.current.country=!0,pr.current=ee.target.value,Pr(ee.target.value),Ht?.(ee.target.value),mr.current="",cn("")},disabled:ir,autoComplete:"billing country","data-testid":"flopay-country",style:{...U(),cursor:"pointer"},children:[at===""?(0,l.jsx)("option",{value:"",children:"Select country"}):null,c.COUNTRY_OPTIONS.map(ee=>(0,l.jsxs)("option",{value:ee.code,children:[ee.flag," ",ee.name]},ee.code))]})}),(0,c.isAVSFieldVisible)(Ze.postal_code,i)&&(0,l.jsx)("div",{style:{flex:ce==="row"?1:void 0,backgroundColor:ea,border:`1px solid ${Fd}`,padding:"10px",...ce==="row"&&(0,c.isAVSFieldVisible)(Ze.country,i)?{borderRadius:"0",borderTopRightRadius:sr,borderBottomRightRadius:sr}:{borderRadius:sr}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,c.getPostalCodeLabel)(at),autoComplete:"billing postal-code",value:Xt,onChange:ee=>{qt("zip"),Nr.current.zip=!0,ur.current=ee.target.value,gt(ee.target.value),Mt?.(ee.target.value)},onPointerDown:()=>qt("zip"),onKeyDown:()=>qt("zip"),onBlur:()=>{Xn("zip")&&$n(!0)},disabled:ir,required:tn.required,"aria-invalid":di||void 0,"aria-describedby":di?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:U()})})]}),di&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ka,children:tn.empty?`${(0,c.getPostalCodeLabel)(i)} is required`:Gu(i)})]})})()}),z&&Nd,Dn&&(0,l.jsx)(ma,{margin:"0.75rem 0",styleOverride:rt.errorBanner,children:Dn})]}),ui={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"},ql=i=>$?!Z||!Zn?(0,l.jsx)("pre",{"data-testid":i,style:ui,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:ui,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${Z}`,` directPaypalConfigured=${Zn}`,` inAppBrowserDetected=${String(ii)}`,` shouldRenderDirectPayPal=${To}`,` shouldRenderStripePayPal=${Mo}`,` hasPaypalStripeInstance=${!!il}`].join(`
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,jl=dt==="apm-expanding"||dt==="apm-form"||dt==="apm-collapsing",ra;dt==="apm-expanding"?ra=Nc:dt==="apm-collapsing"&&(ra=Uc);let pi=Jt?Gc(is,Jt,F):null,Wl={label:ut||Ec,open:Xr,onOpen:_t,color:wo,fontFamily:Hr?.fontFamily};if(ye==="buttons"){let i=dt==="buttons"||dt==="expanding"||dt==="apm-expanding",C=dt==="expanding"||dt==="card"||dt==="collapsing",U=we===void 0?{boxSizing:"border-box",height:Eo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ce;dt==="expanding"||dt==="apm-expanding"?Ce=Wu:(dt==="collapsing"||dt==="apm-collapsing")&&(Ce=ju);let ee;dt==="expanding"?ee=Nc:dt==="collapsing"&&(ee=Uc);let Fe=kr&&(0,c.placePaymentMethodGroups)(kr,{canHide:()=>!0,available:Tl}),jt={paypal:(0,l.jsxs)(l.Fragment,{children:[To&&ze&&(0,l.jsxs)(l.Fragment,{children:[Le&&(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)(Fa.Provider,{value:L,children:(0,l.jsx)(Oa,{sessionId:e,nonce:t,billingApiUrl:Te,email:Tt.email,billingName:Ko||void 0,onBuyerIdentityReady:$r,clientId:ze.clientId,environment:ze.environment,currency:Pt.toUpperCase(),isSubscription:Nt,providerObjectType:B,approvalPresentation:si==="popup"?void 0:si,onTokenizedBody:rn,onComplete:d,onErrorChange:Ne,onDecline:m,onCancel:b,onTechnicalFailure:Jo,onButtonClick:Ee,runBeforeButtonClick:Nn,isProcessing:ir,onLoadStateChange:ds,onInitializationStateChange:us,session:H,existingOrderId:Le?.orderId,debug:$},Le?.orderId??"fresh")})]}),Mo&&(0,l.jsx)(lr.Elements,{stripe:ba,options:cl,children:(0,l.jsx)(qc,{sessionId:e,nonce:t,email:Tt.email,billingName:Ko||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,onTokenizedBody:rn,onErrorChange:Ne,isProcessing:ir,onButtonClick:Ee,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:bl,placeholderBorderRadius:uo,popupCapabilityOwner:L,externalTelemetryContext:_l,presentationMode:Zo})})]}),wallets:(0,l.jsxs)(l.Fragment,{children:[So?(0,l.jsx)(lr.Elements,{stripe:gn,options:ll,children:(0,l.jsx)(Vc,{sessionId:e,nonce:t,email:Tt.email,billingName:Ko||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,intentKind:Ye>0?"payment":"setup",expressMethods:Qo,onTokenizedBody:rn,onErrorChange:Ne,onButtonClick:Ee,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:Sl,placeholderBorderRadius:uo,popupCapabilityOwner:L,externalTelemetryContext:I})}):null,!So&&El?(0,l.jsx)("div",{style:{height:Eo,borderRadius:uo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:(0,l.jsx)(l.Fragment,{children:Ao&&(0,l.jsx)(jc,{sessionId:e,nonce:t,email:Tt.email,billingName:[Tt.firstName,Tt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,paymentElementMethods:ai,stripeInstance:gn,paymentElementBaseOptions:is,futureUseSession:F,onTokenizedBody:rn,onErrorChange:Ne,onButtonClick:Ee,onDecline:m,runBeforeButtonClick:Nn,onLoadStateChange:wl,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,onExpandApm:h,expandedApmMethod:Jt,themeId:q,buttonAppearance:{backgroundColor:rt.cardButton?.backgroundColor,borderColor:rt.cardInputBorder,textColor:rt.cardButton?.color,borderRadius:uo}})}),card:(0,l.jsx)(l.Fragment,{children:z&&(0,l.jsx)("button",{type:"button",onClick:async()=>{ir||!(await Nn("card")).proceed||(Ee?.("card"),yt())},disabled:ir,style:{width:"100%",...U,...rt.cardButton,...Hs({themeBundle:$o,resolvedPrimaryColor:wo,resolvedBorderRadius:sr,submitButtonStyle:rt.submitButton,explicitPrimaryColor:Hr?.colorPrimary}),fontSize:rt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ir?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ir?.6:1},onMouseEnter:Wt=>{!ir&&($o||Hr?.colorPrimary)&&(Wt.currentTarget.style.backgroundColor=Dd)},onMouseLeave:Wt=>{($o||Hr?.colorPrimary)&&(Wt.currentTarget.style.backgroundColor=wo)},onMouseDown:Wt=>{Wt.currentTarget.style.transform="scale(0.985)"},onMouseUp:Wt=>{Wt.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(oa,{content:we})})})};return(0,l.jsxs)("form",{onSubmit:ys,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),N&&(0,l.jsx)(nn,{status:N,errorMessage:Dn,authorized:O}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Ce?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Ce?Hu:{},...Ce?{animation:Ce,pointerEvents:"none"}:{}},children:[ql("flopay-direct-paypal-gate-debug"),Vl("flopay-stripe-gate-debug"),Kt&&Fe?(0,l.jsxs)(l.Fragment,{children:[Kt.filter(({group:Wt})=>Fe.inView.includes(Wt)).map(({group:Wt,key:ot})=>(0,l.jsx)(o.default.Fragment,{children:jt[Wt]},ot)),Fe.behindLink.length>0&&(0,l.jsx)(Fs,{...Wl,showLink:Fe.showLink,children:Kt.filter(({group:Wt})=>Fe.behindLink.includes(Wt)).map(({group:Wt,key:ot})=>(0,l.jsx)(o.default.Fragment,{children:jt[Wt]},ot))})]}):(0,l.jsx)(Os,{rows:Il,borderRadius:uo}),Dn&&dt==="buttons"&&(0,l.jsx)(ma,{margin:"0.25rem 0",styleOverride:rt.errorBanner,children:Dn})]}),z&&C&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...ee?{animation:ee}:{},...dt==="collapsing"?{pointerEvents:"none"}:{}},children:Ss}),v&&jl&&Jt&&pi&&gn&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...ra?{animation:ra}:{},...dt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:gs,borderRadius:bs,...Ea,padding:Cs},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:w,style:{display:"inline-flex",alignItems:"center",gap:hs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:rt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...rt.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...rt.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(aa,{content:X})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:rt.titleFontSize??"1.05rem",color:Ps,paddingRight:80,...rt.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(Jt)}`})]}),(0,l.jsx)(lr.Elements,{stripe:gn,options:pi,children:(0,l.jsx)(js,{method:Jt,sessionId:e,nonce:t,email:Tt.email,billingName:[Tt.firstName,Tt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,onTokenizedBody:rn,onErrorChange:Ne,onDecline:m,onCancel:w,runBeforeButtonClick:Nn,onButtonClick:Ee,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,errorText:Dn})},Jt)]})})]})]})}if(jl&&Jt&&pi&&gn&&v)return(0,l.jsxs)("form",{onSubmit:ys,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),N&&(0,l.jsx)(nn,{status:N,errorMessage:Dn,authorized:O}),(0,l.jsx)("div",{style:{...ra?{animation:ra}:{},...dt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:gs,borderRadius:bs,...Ea,padding:Cs},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:w,style:{display:"inline-flex",alignItems:"center",gap:hs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:rt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...rt.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...rt.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(aa,{content:X})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:rt.titleFontSize??"1.05rem",color:Ps,paddingRight:80,...rt.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(Jt)}`})]}),(0,l.jsx)(lr.Elements,{stripe:gn,options:pi,children:(0,l.jsx)(js,{method:Jt,sessionId:e,nonce:t,email:Tt.email,billingName:[Tt.firstName,Tt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,onTokenizedBody:rn,onErrorChange:Ne,onDecline:m,onCancel:w,runBeforeButtonClick:Nn,onButtonClick:Ee,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,errorText:Dn})},Jt)]})})]});let $l=Id||_d||Td,_a=kr&&(0,c.placePaymentMethodGroups)(kr,{canHide:i=>i!=="card",available:Tl}),Hl={paypal:(0,l.jsxs)(l.Fragment,{children:[To&&ze&&(0,l.jsxs)(l.Fragment,{children:[Le&&(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)(Fa.Provider,{value:L,children:(0,l.jsx)(Oa,{sessionId:e,nonce:t,billingApiUrl:Te,email:Tt.email,billingName:Ko||void 0,onBuyerIdentityReady:$r,clientId:ze.clientId,environment:ze.environment,currency:Pt.toUpperCase(),isSubscription:Nt,providerObjectType:B,approvalPresentation:si==="popup"?void 0:si,onTokenizedBody:rn,onComplete:d,onErrorChange:Ne,onDecline:m,onCancel:b,onTechnicalFailure:Jo,onButtonClick:Ee,runBeforeButtonClick:Nn,isProcessing:ir,onLoadStateChange:ds,onInitializationStateChange:us,session:H,existingOrderId:Le?.orderId,debug:$},Le?.orderId??"fresh")})]}),Mo&&(0,l.jsx)(lr.Elements,{stripe:ba,options:cl,children:(0,l.jsx)(qc,{sessionId:e,nonce:t,email:Tt.email,billingName:Ko||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,onTokenizedBody:rn,onErrorChange:Ne,isProcessing:ir,onButtonClick:Ee,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:bl,placeholderBorderRadius:uo,popupCapabilityOwner:L,externalTelemetryContext:_l,presentationMode:Zo})})]}),wallets:(0,l.jsx)(l.Fragment,{children:So&&(0,l.jsx)(lr.Elements,{stripe:gn,options:ll,children:(0,l.jsx)(Vc,{sessionId:e,nonce:t,email:Tt.email,billingName:Ko||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,intentKind:Ye>0?"payment":"setup",expressMethods:Qo,onTokenizedBody:rn,onErrorChange:Ne,onButtonClick:Ee,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:Sl,placeholderBorderRadius:uo,popupCapabilityOwner:L,externalTelemetryContext:I})})}),apms:(0,l.jsx)(l.Fragment,{children:Ao&&(0,l.jsx)(jc,{sessionId:e,nonce:t,email:Tt.email,billingName:[Tt.firstName,Tt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Te,paymentElementMethods:ai,stripeInstance:gn,paymentElementBaseOptions:is,futureUseSession:F,onTokenizedBody:rn,onErrorChange:Ne,onButtonClick:Ee,onDecline:m,runBeforeButtonClick:Nn,onLoadStateChange:wl,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,themeId:q,onExpandApm:h,expandedApmMethod:Jt,buttonAppearance:{backgroundColor:rt.cardButton?.backgroundColor,borderColor:rt.cardInputBorder,textColor:rt.cardButton?.color,borderRadius:uo}})})};return(0,l.jsxs)("form",{onSubmit:ys,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),N&&(0,l.jsx)(nn,{status:N,errorMessage:Dn,authorized:O}),Kt===null?(0,l.jsx)(Os,{rows:Il,borderRadius:uo}):(0,l.jsxs)(l.Fragment,{children:[jr&&z&&Ss,jr&&z&&$l&&(0,l.jsx)(Ka,{label:"or pay another way"}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ql("flopay-direct-paypal-gate-debug-default"),Vl("flopay-stripe-gate-debug-default"),Kt.map(({group:i,key:C})=>i==="card"||!_a?.inView.includes(i)?null:(0,l.jsx)(o.default.Fragment,{children:Hl[i]},C)),_a&&_a.behindLink.length>0&&(0,l.jsx)(Fs,{...Wl,showLink:_a.showLink,children:Kt.map(({group:i,key:C})=>_a.behindLink.includes(i)&&i!=="card"?(0,l.jsx)(o.default.Fragment,{children:Hl[i]},C):null)})]}),!jr&&z&&$l&&(0,l.jsx)(Ka,{label:"or pay with card"}),!jr&&z&&Ss]})]})}var x=require("react/jsx-runtime"),qo=44,Qs="flopay_checkout_saved_payment_resume",Hi=new Map,Wi=new Map;function Yc(e,t){t.settled&&t.consumers===0&&Hi.get(e)===t&&Hi.delete(e)}function tp(e,t,r){let n=Wi.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};Wi.set(e,s);let d=()=>{Wi.get(e)===s&&Wi.delete(e)};return a.then(d,d),a}function Ja(e){return new Promise(t=>setTimeout(t,e))}function $i(e,t,r){let n=wi({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:me.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Za(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Gs(e,t,r,n,a,s){let d=$i(e,t,r);d.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Za(d)}function Xc(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 Jc(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 Ys(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,me.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var rp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function np(e){return new Po.FloPay(rp,{publishableKey:"provider_unavailable",...e})}async function Xs(e,t){let{publishableKey:r,paypalPublishableKey:n}=As(e);return{...await xs({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function el(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function op(){if(!el())return null;try{let e=window.sessionStorage.getItem(Qs);return e?JSON.parse(e):null}catch{return null}}function Zc(e){if(el())try{window.sessionStorage.setItem(Qs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Js(){if(el())try{window.sessionStorage.removeItem(Qs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ap(){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 Qc(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 Zs(e,t){return(0,me.resolveCheckoutLogLayout)(!!e,t)}function ip(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function ed(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function sp(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 Ki({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:d,loading:p,error:m,onComplete:b,onError:P,onInstrument:f,onDecline:_,onCancel:j,onCountryChange:W,onZipChange:k,showPayPal:T=!0,showStripe:y=!0,walletPresentation:K="auto",enabledPaymentMethods:Z,showApplePay:v=!0,showGooglePay:ke=!0,debug:M=!1,layout:se,paymentMethodLayout:be,moreOptionsLabel:Ie,theme:ye,buttonsTheme:vt,buttonsStyles:ut,cardButtonContent:q,cardBackButtonContent:We,cardTitleContent:$e,showSecurityFooter:Be,onButtonClick:we,onBeforeButtonClick:X,enableAVS:G,cardFieldOrder:tt,cardAutoFocus:Ee,onCardFieldsReady:qe,onCardFieldsFailed:te,cardFieldsTimeoutMs:V,cardPreFormSlot:Se,avsLayout:Q,submitLabel:pt,className:fe,initialErrorMessage:Pe=null,initialPayPalOrderId:Oe,children:ce,checkoutMode:Ve,confirmLabel:De,renderConfirmButton:nt,onSessionCompleted:ct}){let Y=(0,me.resolveBillingApiUrl)(n),Rt=(0,R.useMemo)(()=>(0,me.resolveTheme)(ye),[ye]),Ht=s??Rt?.appearance,Mt=r?"embedded_checkout":"standard_checkout",Lt=Zs(ce,se),[he,Me]=(0,R.useState)(null),[Ye,Pt]=(0,R.useState)(null),ft=(0,R.useRef)(null),ze=(0,R.useRef)(null),Nt=(0,R.useRef)(0),[de,kt]=(0,R.useState)(null),At=(0,R.useRef)(null),[$,ge]=(0,R.useState)(null),Ut=(0,R.useMemo)(()=>r?(0,ht.serializeCreateParams)(r):"",[r]),g=r?`create:${Ut}`:`session:${e??""}`,J=ed($),He=(0,R.useRef)(new Set),L=(0,R.useRef)(g),mt=(0,R.useRef)(g);Oo(()=>{mt.current=g,L.current!==g&&(L.current=g,He.current.clear())},[g]);let u=(0,R.useCallback)(A=>{if(mt.current===g){if(Ts.FLO_INSTRUMENT_ONCE_NAMES.has(A.name)){if(He.current.has(A.name))return;He.current.add(A.name)}(0,Ge.invokeMerchantCallback)(()=>f?.(A))}},[g,f]),S=pa(u,g),I=(0,R.useRef)(!1),H=(0,R.useCallback)(A=>{if(I.current)return;let D=A.gateway||!J?A:{...A,gateway:J};u(D)},[u,J]);(0,R.useEffect)(()=>{S({class:"lifecycle",name:"checkout.mount"})},[S]);let[F,B]=(0,R.useState)(e??""),Ae=e??F,Vr=r?"":Ae,[$t,nr]=(0,R.useState)(!0),[Te,kr]=(0,R.useState)(null),[Ur,Xr]=(0,R.useState)(0),[Or,Kt]=(0,R.useState)("full"),[jr,an]=(0,R.useState)(!1),[Er,_r]=(0,R.useState)(Pe),[vn,at]=(0,R.useState)(null),[Pr,Xt]=(0,R.useState)(null),[gt,Et]=(0,R.useState)(!1),[sn,zr]=(0,R.useState)(void 0),[Dr,ln]=(0,R.useState)(""),[Jr,Ir]=(0,R.useState)(!1),[cn,Zr]=(0,R.useState)(!1),[Lr,or]=(0,R.useState)(!1),vr=(0,R.useRef)(null),ur=(0,R.useRef)(0),pr=(0,R.useRef)(void 0),[Tr,Mr]=(0,R.useState)("loading"),[Qr,mr]=(0,R.useState)(0),tr=(0,R.useRef)(!1),Nr=(0,R.useRef)(!1),Ze=(0,R.useRef)(!1),Cn=(0,R.useRef)(null),O=(0,R.useRef)(null),Qe=(0,R.useMemo)(()=>({checkoutMode:Ve??Or,layout:ip(ce,se)}),[Ve,ce,Or,se]),ue=(0,R.useRef)(b);ue.current=b;let ve=(0,R.useRef)(P);ve.current=P;let Gt=(0,R.useRef)(_);Gt.current=_;let zt=(0,R.useCallback)(A=>_i(Cn,async D=>{try{return await A(D)}catch(ne){throw D.aborted?ya(ne):ne}}),[]);(0,R.useEffect)(()=>()=>{Cn.current?.abort(),Cn.current=null},[]);let xt=(0,R.useCallback)((A,D)=>{ft.current=A,Pt(A),At.current=D,kt(D)},[]),z=(0,R.useCallback)(()=>{let A=ze.current;A&&(ze.current=null,A.destroy())},[]);(0,R.useEffect)(()=>{br(Ye)?.setCheckoutContext(Qe),de&&de!==Ye&&br(de)?.setCheckoutContext(Qe)},[Ye,de,Qe]);let bn=(0,R.useRef)(ct);bn.current=ct;let jo=(0,R.useCallback)(A=>{Mr(A),!(A!=="exhausted"||Ze.current)&&(Ze.current=!0,ve.current?.(new me.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Io=(0,R.useCallback)(()=>{Mr("retrying"),mr(A=>A+1)},[]);(0,R.useEffect)(()=>{Mr("loading"),mr(0),Ze.current=!1},[Ae]),(0,R.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:me.SDK_VERSION,checkout_type:Mt,checkout_layout:Lt,billing_api_url:Y})},[Lt,Mt,Y]);let Sn=(0,R.useMemo)(()=>r?(0,ht.serializeCreateParams)(r,!0):"",[r]),xn=(0,R.useMemo)(()=>Dr===Sn?sn:void 0,[sn,Dr,Sn]),dn=(0,R.useMemo)(()=>r?ks(r,xn):void 0,[r,xn]),en=Ve??dn?.checkoutMode??"full",ar=(0,R.useMemo)(()=>dn?{...dn,checkoutMode:en}:void 0,[dn,en]);(0,R.useEffect)(()=>{zr(void 0),ln(Sn),pr.current=void 0,vr.current=null,or(!1)},[Sn]),(0,R.useEffect)(()=>{_r(Pe)},[Pe]);let Fn=(0,R.useCallback)((A,D,ne)=>{(0,Ge.invokeMerchantCallback)(()=>{Gt.current?.(Cr(A,D,ne))})},[]),un=(0,R.useCallback)(async(A,D)=>{_r(null),Xt(null),Et(!1),at("processing");let ne=D?.sessionId??A.id,Re=A.clientSecret||t,_t=ed(A),Zt=ft.current??At.current,xe=br(Zt),it=Zt?null:$i(Y,a,Qe),re={log:oe=>{xe?xe.log(oe):it?.log(oe)},error:oe=>{xe?xe.error(oe):it?.error(oe)},terminal:oe=>{xe?xe.terminal(oe):it?.terminal(oe)},performance:oe=>{xe?xe.performance(oe):it?.performance(oe)},now:()=>xe?.now()??it?.now()??0,elapsed:oe=>xe?.elapsed(oe)??Math.max(0,(it?.now()??oe)-oe)},et=re.now(),pe=!!(D?.initialAutoProcessingError||D?.initialAutoProcessingPending),yt=!1,le,h=()=>{yt||(yt=!0,pe=!0,le=re.now(),re.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},w=!1,N=()=>{w||(w=!0,re.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),re.performance({stage:"processing",durationMs:re.elapsed(et),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),le!==void 0&&re.performance({stage:"recovery",durationMs:re.elapsed(le),durationMode:"machine",paymentMethodCategory:"saved"}))};re.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),I.current=!0;try{re.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{I.current=!1}S({class:"lifecycle",name:"payment.processing.started",provider:_t}),pe&&h();let ie;try{let oe=Sc(D?.initialAutoProcessingError),ae=D?.initialAutoProcessingError?.type==="3ds_required"&&!(0,me.isMerchantAuthRequired)(D.initialAutoProcessingError)&&!D.initialAutoProcessingError.threeDSecureToken&&D.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:D.initialAutoProcessingError.nextActionRedirectUrl}:null,Bt,Ot=st=>{h();let Ct=qa(Y,ne,A,a!==!1);return zt(It=>fa(st,{billingApiUrl:Y,sessionId:ne,nonce:Re,session:A,signal:It,...Ct.telemetry?{challengeTelemetry:Ct.telemetry}:{}})).finally(Ct.release)};if(ae)Bt=await Ot(ae);else if(oe)h(),oe.type==="paypal_redirect_required"&&O.current?.publishableKey&&Zc({sessionId:ne,publishableKey:O.current.publishableKey,paypalPublishableKey:O.current.paypalPublishableKey}),Bt=await zt(st=>Ti(oe,{flopay:ft.current,paypalFlopay:At.current,attempt3DS:D?.attempt3DS,billingApiUrl:Y,sessionId:ne,session:A,telemetry:!1,signal:st})),oe.type==="paypal_redirect_required"&&Js();else if(D?.initialAutoProcessingPending){let st=D.initialAutoProcessingPending,Ct=new Po.PaymentAPI(Y,{telemetry:!1}),It=await zt(Le=>Ct.waitForCheckoutSessionCompletion(st.sessionId,{initialDelayMs:st.retryAfterMs,nonce:Re,statusUrl:st.statusUrl,signal:Le})),Xe=ko(It,A),Ke=It.autoProcessingError?.type==="3ds_required"&&It.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:It.autoProcessingError.nextActionRedirectUrl}:null;if(Ke)Bt=await Ot(Ke);else{if(!mo(Xe))throw sa(Xe);Bt=po(Xe,ne)}}else{if(D?.initialAutoProcessingError)throw ro(D.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.initialAutoProcessingError.checkoutMethod});if(D?.fromCreateSession)return D?.fallbackToFull&&(Kt("full"),Qc("full")),!1;{let st=await ga({billingApiUrl:Y,sessionId:ne,session:A,nonce:Re,telemetry:!1});st.type==="success"?Bt=st.result:st.type==="next_action_required"?Bt=await Ot(st):(h(),st.type==="paypal_redirect_required"&&O.current?.publishableKey&&Zc({sessionId:ne,publishableKey:O.current.publishableKey,paypalPublishableKey:O.current.paypalPublishableKey}),Bt=await zt(Ct=>Ti(st,{flopay:ft.current,paypalFlopay:At.current,attempt3DS:D?.attempt3DS,billingApiUrl:Y,sessionId:ne,session:A,telemetry:!1,signal:Ct})),st.type==="paypal_redirect_required"&&Js())}}ne&&(0,Vn.markSessionRecentlyCompleted)(ne),N(),pe&&(re.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),re.terminal({outcome:Bt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Et(Bt.status==="authorized"),at("success"),await Ja(600),ie=()=>ue.current?.(Bt)}catch(oe){let ae=Ro(Va(oe),ne);if(ae.code==="three_ds_aborted")return!1;let Bt=ae.checkoutMethod??za;_r(ae.message),Xt(ae.message),Et(!1),D?.fallbackToFull&&(re.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Kt("full"),Qc("full")),N();let Ot=ae.statusCode===void 0?void 0:(0,me.telemetryStatusClass)(ae.statusCode,"unknown"),st=Ot==="4xx"?{requestCategory:"process_payment",statusClass:Ot}:{},Ct=Ot===void 0||Ot==="4xx";if((0,me.isExpectedPaymentDecline)(ae))re.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...st});else if(Ct&&(ae.telemetryOutcome==="validation_rejected"||ae.type==="validation_error"))re.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...st});else{let Ke=(0,me.classifyTelemetryFailure)(oe,pe?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Le=ae.telemetryRequestCategory??"process_payment";I.current=!0;try{re.error({...Ke,...ae.telemetryFailureCategory?{failureCategory:ae.telemetryFailureCategory}:{},stage:pe?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Le})}finally{I.current=!1}S({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Le,provider:_t})}return(0,me.isDeclineCallbackFailure)(ae)?Fn(Bt,ae,{code:ae.code,declineCode:ae.declineCode}):(0,Ge.invokeMerchantCallback)(()=>ve.current?.(ae)),at("error"),await Promise.allSettled([Ja(400),D?.ensureProvidersReady?D.ensureProvidersReady():Promise.resolve()]),pe&&(re.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{N(),it&&Za(it),at(null),Xt(null)}return(0,Ge.invokeMerchantCallback)(ie),!0},[Fn,S,t,Y,zt,a,Qe]);(0,R.useEffect)(()=>{if(typeof window>"u"||Nr.current)return;let A=new URLSearchParams(window.location.search),D=A.get("payment_intent_client_secret");if(!D)return;let ne=op();ne&&(Nr.current=!0,(async()=>{await Promise.resolve();let Re,_t=0;_r(null),Xt(null),at("processing"),an(!0);try{if(A.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:Zt,paypalFlopay:xe}=await xs({publishableKey:ne.publishableKey,paypalPublishableKey:ne.paypalPublishableKey,billingApiUrl:Y,locale:d,telemetry:a});Re=br(xe??Zt),Re?.setCheckoutContext(Qe),_t=Re?.now()??0,Re?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Re?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let it=(xe??Zt)?.getRawProvider();if(!it)throw Object.assign(new me.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:re,error:et}=await it.retrievePaymentIntent(D);if(et)throw Object.assign(new me.FloPayError(et.message??"Failed to retrieve PayPal payment status.","api_error",{code:et.code}),{checkoutMethod:"paypal"});let pe=oc(re?.status);if(!re||pe==="failed")throw Object.assign(new me.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let yt=typeof re.payment_method=="string"?re.payment_method:re.payment_method?.id,le=pe;if(ne.sessionId){let N=(await new Po.PaymentAPI(Y,{telemetry:!1}).getUnifiedCheckoutSession(ne.sessionId)).data.session;if(N&&N.status!=="complete"){let ie=await ga({billingApiUrl:Y,sessionId:ne.sessionId,session:N,telemetry:!1,tokenizedData:{id:yt??re.id,type:"card",threeDSecureActionResultTokenId:re.id,isPaypal:!0}});if(ie.type!=="success")throw Object.assign(new me.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});le=ie.result.status}}ne.sessionId&&(0,Vn.markSessionRecentlyCompleted)(ne.sessionId),Re?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Re?.performance({stage:"redirect_resume",durationMs:Re.elapsed(_t),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Re?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),at("success"),await Ja(600),(0,Ge.invokeMerchantCallback)(()=>ue.current?.({status:le,paymentIntentId:re.id,paymentMethodId:yt,checkoutMethod:"paypal"}))}catch(Zt){let xe=Ro(Va(Zt),ne.sessionId),it=xe.checkoutMethod??"paypal",re=(0,me.isExpectedPaymentDecline)(xe);if(Re)Re.performance({stage:"redirect_resume",durationMs:Re.elapsed(_t),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),re?Re.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Re.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(re){let et=$i(Y,a,Qe);et.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Za(et)}else Gs(Y,a,Qe,"REDIRECT_RESUME_FAILED","redirect_resume");_r(xe.message),Xt(xe.message),(0,me.isDeclineCallbackFailure)(xe)?Fn(it,xe,{code:xe.code,declineCode:xe.declineCode}):(0,Ge.invokeMerchantCallback)(()=>ve.current?.(xe)),at("error"),await Ja(400)}finally{Js(),ap(),at(null),Xt(null),an(!1)}})())},[Fn,d,Y,a,Qe]);let Bn=(0,R.useRef)(null),Ft=(0,R.useMemo)(()=>ar?(0,ht.serializeCreateParams)(ar):"",[ar]),tn=(0,R.useRef)(ar);tn.current=ar,(0,R.useEffect)(()=>{B(e??"")},[e]),(0,R.useEffect)(()=>{tr.current=!1,_r(Pe),Xt(null),Et(!1),at(null)},[Ft,Pe,e]);async function pn(A,D,ne){let Re=$i(Y,a,Qe),_t=new Po.PaymentAPI(Y,{telemetry:!1}),Zt=!1;try{let xe=A.idempotencyKey===void 0?void 0:(0,me.resolveIdempotencyKey)(A.idempotencyKey),it=(0,ht.readCachedInlineSession)(D,ne),re=(0,ht.readCachedInlineIdempotencyKey)(D,ne);it?.canonicalIdentity===ne&&re&&re.canonicalIdentity===void 0&&((0,ht.persistCachedInlineIdempotencyKey)(D,ne,re.idempotencyKey),re={...re,canonicalIdentity:ne});let et=xe??(re?.canonicalIdentity===ne?re.idempotencyKey:void 0),pe,yt=!1;Re.log({name:it?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let le=it?.sid??null,h=null,w,N,ie=!1;if(le)try{h=await _t.getUnifiedCheckoutSession(le,it?.nonce),it&&it.canonicalIdentity===void 0&&((0,ht.legacyCachedSessionMatchesDraft)(h.data.session,A)?((0,ht.persistCachedInlineSession)(D,ne,le,it.nonce??h.data.session?.clientSecret),re&&re.canonicalIdentity===void 0&&((0,ht.persistCachedInlineIdempotencyKey)(D,ne,re.idempotencyKey),et??(et=re.idempotencyKey))):((0,ht.clearCachedInlineCheckout)(D,ne),re=null,et=xe,le=null,h=null));let ae=h?.data.session?.status,Bt=h?.data.session,Ot=Bt?.clientSecret||it?.nonce;if(le&&Bt?.buyerIdentified===!1&&Ot&&(N=ia(_t,le,Ot,A.account)),le&&h&&ae==="complete"){if((0,Vn.wasSessionRecentlyCompleted)(le))return{sid:le,result:h};(0,ht.clearCachedInlineCheckout)(D,ne),le=null,h=null,yt=!0}}catch{Re.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),it?.canonicalIdentity===void 0?((0,ht.clearCachedInlineCheckout)(D,ne),et=xe):(0,ht.clearCachedInlineSession)(D,ne),le=null}if(!le){!xe&&(yt||!et)&&(et=(0,me.resolveIdempotencyKey)(),pe=et),et&&(0,ht.persistCachedInlineIdempotencyKey)(D,ne,et);let ae=Re.now(),Bt=0;Re.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ot={...A,idempotencyKey:et,avsCheck:!!G,avsConfig:typeof G=="object"?G:void 0,checkoutType:"embedded_checkout",checkoutLayout:Zs(ce,se)};Object.defineProperty(Ot,Po.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:It=>{Bt=Math.max(Bt,It)}}});let st=()=>{Xc(Re,"session_create",ae,Bt)},Ct=It=>{Jc(Re,It,"session_create",ae,Bt)&&S({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(A.checkoutMode==="confirm"||A.checkoutMode==="auto")&&vc();try{if((0,me.isDetachedSessionEligible)(Ot)){let It=await _t.createDetachedSession(Ot);It.claimed.catch(()=>{}),h=It.shell,le=It.sessionId,N=It.claim;let Xe=Re.now();Re.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),w=It.claimed.then(Ke=>{let Le=Ke.data.session?.id??It.sessionId;return Le&&(0,ht.persistCachedInlineSession)(D,ne,Le,Ke.data.session?.clientSecret??It.nonce),Xc(Re,"session_claim",Xe),st(),Ke},Ke=>{throw(0,ht.clearCachedInlineSession)(D,ne),Jc(Re,Ke,"session_claim",Xe,0)&&S({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Ke}).finally(()=>Za(Re)),w.catch(()=>{}),Zt=!0,Re.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Re.performance({stage:"session_shell",durationMs:Re.now()-ae,durationMode:"machine",requestCategory:"session_create",attempt:Bt,statusClass:"2xx",paymentMethodCategory:"card"})}else h=await _t.createAndFetchSession(Ot),st()}catch(It){throw Ct(It),It}le=h.data.session?.id??le??"",le&&!w&&(0,ht.persistCachedInlineSession)(D,ne,le,h.data.session?.clientSecret)}let oe=h?.data.session;return!N&&le&&oe?.buyerIdentified===!1&&oe.clientSecret&&(N=ia(_t,le,oe.clientSecret,A.account)),{sid:le??"",result:h,sdkGeneratedIdempotencyKey:pe,...w?{claimed:w}:{},...N?{claim:N}:{},...ie?{claimRequiresIdentity:!0}:{}}}finally{Zt||Za(Re)}}let io=(0,R.useRef)(pn);Oo(()=>{io.current=pn},[pn]);let mn=(0,R.useCallback)(async(A,D)=>{let ne=tn.current;if(!ne)throw new me.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Re=ks(ne,A),_t=(0,ht.serializeCreateParams)(Re),Zt=(0,ht.hashCreateParams)(Re),xe=Hi.get(_t);if(!xe){let et={canonicalIdentity:_t,promise:io.current(Re,Zt,_t),consumers:0,settled:!1};xe=et,Hi.set(_t,et);let pe=()=>{et.settled=!0,Yc(_t,et)};et.promise.then(pe,pe)}xe.consumers+=1;let it=!1,re=()=>{it||(it=!0,xe.consumers-=1,Yc(_t,xe))};D?.(re);try{let et=await xe.promise;Bn.current=_t,A&&(ln(Sn),zr(oe=>Zl(oe,A)));let{sid:pe,result:yt,claimed:le,claim:h,claimRequiresIdentity:w}=et;if(pr.current=h,or(w===!0),Me(yt),yt.data.session&&ge(yt.data.session),pe&&B(pe),le){ur.current+=1;let oe=ur.current;vr.current=le,Zr(!0),le.then(ae=>{ur.current===oe&&(vr.current===le&&(vr.current=null),Me(ae),ae.data.session&&ge(ae.data.session),Zr(!1),or(!1))},ae=>{ur.current===oe&&(vr.current===le&&(vr.current=null),Zr(!1),or(!1),kr(ae instanceof me.FloPayError?ae:new me.FloPayError(ae instanceof Error?ae.message:"Failed to create session","api_error")))})}else ur.current+=1,vr.current=null,Zr(!1),or(!1);let{flopay:N,paypalFlopay:ie}=await Xs(yt,{billingApiUrl:Y,locale:d,telemetry:a}).catch(oe=>{throw tc(oe,pe||yt.data.session?.id)});return xt(N,ie),nr(!1),et}catch(et){throw Bn.current===_t&&(Bn.current=null),et}finally{D||re()}},[Sn,xt,d,Y,a]),On=(0,R.useRef)(un);On.current=un;let so=(0,R.useRef)(mn);so.current=mn;let $n=(0,R.useCallback)(async A=>{if(!sp(A)||Jr)return{sessionId:F,session:$};Ir(!0);try{let D=await mn(A);return{sessionId:D.sid,session:D.result.data.session??null}}finally{Ir(!1)}},[mn,Jr,F,$]),Hn=(0,R.useCallback)(async A=>{let D=pr.current;if(!D)return;let ne=ur.current,Re=await D(A);ur.current===ne&&(Me(Re),Re.data.session&&ge(Re.data.session))},[]),Kn=(0,R.useCallback)(async()=>{await vr.current},[]),lo=(0,R.useCallback)(async()=>(await Kn(),{proceed:!0}),[Kn]);(0,R.useEffect)(()=>{let A=!1,D,ne=++Nt.current;z(),kr(null),Xr(0);let Re=()=>{A=!0,Nt.current===ne&&(Nt.current+=1,z())},_t=tn.current;if(Ft&&_t)return Kt(en),nr(!1),Bn.current===Ft?Re:(ge(Ql(_t,Ve)),(async()=>{let it=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),re=en==="auto"&&!tr.current&&!it;re&&(_r(null),Xt(null),at("processing"));let et=!1;try{let pe=await so.current(void 0,w=>{D=w});et=!0;let yt=pe.result.data.session??null;O.current=As(pe.result);let le=Ys(pe.result),h=(0,Vn.wasSessionRecentlyCompleted)(pe.sid||yt?.id);if(!A&&re&&yt&&!le&&!h){tr.current=!0,await tp(Ft,pe.sdkGeneratedIdempotencyKey,()=>On.current(yt,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:pe.result.autoProcessingError,initialAutoProcessingPending:pe.result.autoProcessingPending,autoProcessingAttempted:pe.result.autoProcessingAttempted,sessionId:pe.sid||yt.id}));return}!A&&re&&((le||h)&&(tr.current=!0),at(null),Xt(null))}catch(pe){if(A)return;let yt=gi(pe);if(re&&yt==="session_auto_completed"){tr.current=!0,at("success"),await Ja(600),A||((0,Ge.invokeMerchantCallback)(()=>{ue.current?.({status:"succeeded"})}),at(null),Xt(null));return}if(re&&(at(null),Xt(null)),!et){let h=rc(pe),w=(0,me.toPublicCheckoutInitError)(pe,h?{stage:"provider_load",provider:"stripe",...h}:{stage:"session_request"});(h||!(pe instanceof me.FloPayError))&&(0,Ge.invokeMerchantCallback)(()=>ve.current?.(w)),kr(w);return}let le=pe instanceof me.FloPayError?pe:new me.FloPayError(pe instanceof Error?pe.message:"Failed to create session","api_error");kr(le)}finally{D?.(),D=void 0}})(),()=>{Re(),D?.()});nr(!0);async function Zt(){let it=!1,re=!1,et=null;try{let pe=new Po.PaymentAPI(Y,{telemetry:!1}),yt=await pe.getUnifiedCheckoutSession(Ae,t);if(re=!0,et=yt,A)return;Me(yt);let le=yt.data.session??null;if(ge(le),!le)throw new me.FloPayError("No session data returned","api_error");let h=le.checkoutMode;if(h==="setup")throw new me.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(le.status==="authorized"){nr(!1),(0,Ge.invokeMerchantCallback)(()=>{ue.current?.(po(le,Ae)),bn.current?.(le.successUrl??"")});return}if(le.status==="complete"){nr(!1),(0,Ge.invokeMerchantCallback)(()=>{bn.current?.(le.successUrl??"")});return}if(le.status==="expired")throw fi(le);it=!0;let w=Ve??h??"full";Kt(w),ur.current+=1;let N=le.clientSecret||t;pr.current=le.buyerIdentified===!1&&N?ia(pe,Ae,N,{...le.customer?.id?{userId:le.customer.id}:{}}):void 0,Zr(!1),or(!1);let ie=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),oe=Ys(yt);if(w==="auto"&&!tr.current&&!ie&&!oe){tr.current=!0;let ae=xe(yt);try{if(await On.current(le,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ae,sessionId:Ae||le.id}),A)return;await ae,A||nr(!1);return}catch{if(A)return;await ae,A||nr(!1);return}}await xe(yt),A||nr(!1)}catch(pe){if(A)return;let yt=Jl(pe,it);if(it&&S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),yt){let{errorCode:N,stage:ie,...oe}=yt;Gs(Y,a,Qe,N,ie,oe)}if(yt?.stage==="provider_load"&&(Ve??et?.data.session?.checkoutMode??"full")==="full"&&Xl(et,T,y)){let N=np({billingApiUrl:Y,locale:d,telemetry:a});ze.current=N,xt(N,null),Xr(1),nr(!1);return}let le=yt?.stage==="provider_load",h="session_request";le?h="provider_load":re&&(h="post_session");let w=(0,me.toPublicCheckoutInitError)(pe,{stage:h,provider:"stripe",sessionId:Ae||void 0});(le||!(pe instanceof me.FloPayError))&&(0,Ge.invokeMerchantCallback)(()=>ve.current?.(w)),kr(w),nr(!1)}}async function xe(it){let{flopay:re,paypalFlopay:et,...pe}=await Xs(it,{billingApiUrl:Y,locale:d,telemetry:a});O.current={publishableKey:pe.publishableKey,paypalPublishableKey:pe.paypalPublishableKey},xt(re,et),Xr(0)}return Zt(),Re},[Ve,Ft,en,Vr,t,T,y]);let Wo=(0,R.useCallback)(async()=>{if(!he||Ur!==1)return;let A=Nt.current;Xr(2);try{let{flopay:D,paypalFlopay:ne}=await Xs(he,{billingApiUrl:Y,locale:d,telemetry:a});if(Nt.current!==A)return;z(),xt(D,ne),Xr(0)}catch(D){if(Nt.current!==A)return;let{errorCode:ne,stage:Re,..._t}=Rs(D);Gs(Y,a,Qe,ne,Re,_t)}},[z,xt,d,Ur,Y,a,Qe,he]),Gn=!!(Ae&&($?.clientSecret||t)),co=jr||!Gn,Yn=(0,R.useCallback)(async()=>{if(!(jr||!Gn||!$)){an(!0),_r(null);try{await un($,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ae||$.id})}finally{an(!1)}}},[Ae,jr,Gn,un,$]),qt=(0,me.resolveDirectPaypalConfig)(he?.data.paypal,Oe),Xn=Ys(he),yn=(0,R.useMemo)(()=>{if(!(!he||!$||!he.data.stripe?.publishableKey))return{billingApiUrl:Y}},[he,$,Y]),wn=!!(r&&!ce&&se==="buttons"&&X&&en==="full"),fn=!!(Ae&&((0,me.isMountableVaultBlock)($?.vault)||(0,Un.canRecoverHostedCardForm)($))),dt=(0,R.useMemo)(()=>({session:$,loading:$t,error:Te,checkoutMode:Or,inlineSessionDraft:ar,applyInlineSessionPatch:wn?$n:void 0,inlineSessionPatchProcessing:Jr,claimPending:cn,claimRequiresIdentity:Lr,claimBuyerIdentity:Hn,waitForDataAttachment:Kn}),[$,$t,Te,Or,ar,wn,$n,Jr,cn,Lr,Hn,Kn]),Ar=!!r&&se==="buttons"&&!Xn&&!fn&&(!Ye||!yn),Jt=vn?(0,x.jsx)(nn,{status:vn,errorMessage:Pr,authorized:gt}):null;if($t&&!fn){if(p)return(0,x.jsxs)(x.Fragment,{children:[p,Jt]});if(se==="buttons"){let A=Rt?.buttonsLayout?.cardButton?.borderRadius??Rt?.appearance.variables?.borderRadius??8,D=ne=>(0,x.jsx)("div",{style:{height:ne,borderRadius:A,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[T&&D(qo),y&&(v||ke)&&D(qo),y&&D(qo),(0,x.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Jt]})}return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,x.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,x.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Jt]})}return Te?m?(0,x.jsx)(zn.Provider,{value:dt,children:m(Te)}):(0,x.jsx)(zn.Provider,{value:dt,children:(0,x.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Te.message})}):Ar?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(zn.Provider,{value:dt,children:(0,x.jsx)(cp,{onButtonClick:we,paymentMethodLayout:be,showPayPal:T,showStripe:y,showApplePay:v,showGooglePay:ke,theme:ye,buttonsTheme:vt,buttonsStyles:ut,cardButtonContent:q,cardBackButtonContent:We,cardTitleContent:$e})}),Jt]}):Xn&&$&&qt?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(zn.Provider,{value:dt,children:(0,x.jsxs)("div",{className:fe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Er&&(0,x.jsx)(ma,{icon:!1,children:Er}),Tr==="retrying"&&(0,x.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Tr==="exhausted"&&(0,x.jsxs)("div",{role:"alert",children:[(0,x.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,x.jsx)("button",{type:"button",onClick:Io,children:"Retry PayPal"})]}),Tr!=="exhausted"&&(0,x.jsx)("div",{"aria-hidden":Tr==="retrying"?!0:void 0,style:Tr==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,x.jsx)(fc,{sessionId:Ae,nonce:$.clientSecret||void 0,billingApiUrl:Y,email:$.customer?.email||ar?.account?.email,billingName:[$.customer?.firstName,$.customer?.lastName].filter(Boolean).join(" ")||[ar?.account?.firstName,ar?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Hn,clientId:qt.clientId,environment:qt.environment,currency:($.currency??"usd").toUpperCase(),isSubscription:$.mode==="subscription",providerObjectType:qt.providerObjectType,approvalPresentation:qt.approvalPresentation,existingOrderId:qt.existingOrderId,onComplete:b,onErrorChange:_r,onDecline:_,onCancel:j,onButtonClick:we,runBeforeButtonClick:lo,onInitializationStateChange:jo,allowAutomaticRetry:Qr===0,session:$,telemetry:a,telemetryContext:Qe,onInstrument:H,debug:M},`${g}:paypal-init-${Qr}`)})]})}),Jt]}):Or==="confirm"?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(zn.Provider,{value:dt,children:(0,x.jsx)(La,{flopay:Ye,paypalFlopay:de,options:yn??{billingApiUrl:Y},onInstrument:H,children:(0,x.jsxs)("div",{className:fe,children:[Er&&(0,x.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Er}),nt?nt({onConfirm:Yn,isProcessing:co}):(0,x.jsx)("button",{type:"button",onClick:Yn,disabled:co,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:co?"not-allowed":"pointer",opacity:co?.6:1},children:jr?"Processing...":De??"Confirm Purchase"})]})},g)}),Jt]}):(!Ye||!yn)&&!(fn&&Or==="full")?(0,x.jsx)(x.Fragment,{children:Jt}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(zn.Provider,{value:dt,children:(0,x.jsxs)(La,{flopay:Ye,paypalFlopay:de,options:yn??{billingApiUrl:Y},onInstrument:H,children:[Ur===1&&(0,x.jsx)("button",{type:"button",onClick:Wo,children:"Retry payment methods"}),ce?(0,x.jsxs)(x.Fragment,{children:[Er&&(0,x.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Er}),(0,x.jsx)(lp,{sessionId:Ae,nonce:$?.clientSecret||void 0,billingApiUrl:Y,session:$,submitLabel:pt,walletPresentation:K,paymentMethodLayout:be,moreOptionsLabel:Ie,children:ce})]}):(0,x.jsx)(ji,{sessionId:Ae,nonce:$?.clientSecret||void 0,telemetry:a,email:$?.customer?.email||ar?.account?.email,userId:$?.customer?.id||ar?.account?.userId,firstName:$?.customer?.firstName||ar?.account?.firstName,lastName:$?.customer?.lastName||ar?.account?.lastName,totalAmount:$?Math.round((0,me.buildCheckoutDisplayData)($).total*100):0,currency:$?.currency?.toLowerCase()??"usd",onComplete:b,onError:P,onDecline:_,onCancel:j,error:Er,onErrorChange:_r,showPayPal:T,showStripe:y,walletPresentation:K,enabledPaymentMethods:Ur?[]:Z??he?.data.stripe?.enabledPaymentMethods??$?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:he?.data.stripe?.enabledPaymentMethodCountries,showApplePay:v,showGooglePay:ke,layout:se,paymentMethodLayout:be,moreOptionsLabel:Ie,theme:ye,buttonsTheme:vt,buttonsStyles:ut,appearance:Ht,cardButtonContent:q,cardBackButtonContent:We,cardTitleContent:$e,onButtonClick:we,onBeforeButtonClick:X,onBuyerIdentityReady:Hn,enableAVS:G,...tt?{cardFieldOrder:tt}:{},...Ee===void 0?{}:{cardAutoFocus:Ee},...qe?{onCardFieldsReady:qe}:{},...te?{onCardFieldsFailed:te}:{},...V===void 0?{}:{cardFieldsTimeoutMs:V},...Se?{cardPreFormSlot:Se}:{},avsLayout:Q,country:$?.customer?.country,city:$?.customer?.city,state:$?.customer?.state,onCountryChange:W,onZipChange:k,avsCheck:!!G,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Zs(ce,se),className:fe,submitLabel:pt,directPaypal:qt,isSubscription:$?.mode==="subscription",session:$,dataAttachmentPending:cn,dataAttachmentRequiresIdentity:Lr,debug:M})]},g)}),Jt]})}function lp({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,paymentMethodLayout:d,moreOptionsLabel:p,children:m}){return(0,x.jsx)(x.Fragment,{children:R.default.Children.map(m,b=>{if(!R.default.isValidElement(b))return b;let P=b.props,f={};return P.sessionId||(f.sessionId=e),!P.nonce&&t&&(f.nonce=t),P.billingApiUrl||(f.billingApiUrl=r),P.submitLabel===void 0&&a!==void 0&&(f.submitLabel=a),P.walletPresentation===void 0&&(f.walletPresentation=s),P.paymentMethodLayout===void 0&&d!==void 0&&(f.paymentMethodLayout=d),P.moreOptionsLabel===void 0&&p!==void 0&&(f.moreOptionsLabel=p),n?.customer&&(P.email||(f.email=n.customer.email),P.userId||(f.userId=n.customer.id),P.firstName||(f.firstName=n.customer.firstName),P.lastName||(f.lastName=n.customer.lastName)),Object.keys(f).length===0?b:R.default.cloneElement(b,f)})})}function cp({onButtonClick:e,paymentMethodLayout:t,showPayPal:r,showStripe:n=!0,showApplePay:a,showGooglePay:s,theme:d,buttonsTheme:p,buttonsStyles:m,cardButtonContent:b,cardBackButtonContent:P,cardTitleContent:f}){let[_,j]=(0,R.useState)(!1),W=(0,R.useMemo)(()=>(0,me.resolveTheme)(d),[d]),k=(0,R.useMemo)(()=>{let v=W?.buttonsLayout??(0,me.resolveButtonsLayoutTheme)(p);return m?{...v,...m,cardButton:{...v.cardButton,...m.cardButton},cardFormContainer:{...v.cardFormContainer,...m.cardFormContainer},backButton:{...v.backButton,...m.backButton},backButtonIcon:{...v.backButtonIcon,...m.backButtonIcon},submitButton:{...v.submitButton,...m.submitButton},title:{...v.title,...m.title}}:v},[W,p,m]),T=W?.buttonsLayout?.cardButton?.borderRadius??W?.appearance.variables?.borderRadius??8,y=v=>(0,x.jsx)("div",{style:{height:v,borderRadius:T,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),K=b===void 0?{boxSizing:"border-box",height:qo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let v=k.cardInputBorder??"#e5e7eb",ke=k.cardInputBackground??"white",M=na(P),se=na(f);return(0,x.jsxs)("div",{style:{backgroundColor:k.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...k.cardFormContainer},children:[(0,x.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,x.jsxs)("button",{type:"button",onClick:()=>j(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:M?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...k.backButton},children:[(0,x.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...k.backButtonIcon},children:(0,x.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,x.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,x.jsx)(aa,{content:P})]}),se?(0,x.jsx)("div",{style:{flex:1}}):(0,x.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...k.title},children:(0,x.jsx)(Ta,{content:f})})]}),(0,x.jsx)("div",{style:{backgroundColor:ke,border:`1px solid ${v}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,x.jsxs)("div",{style:{display:"flex"},children:[(0,x.jsx)("div",{style:{flex:1,backgroundColor:ke,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,x.jsx)("div",{style:{flex:1,backgroundColor:ke,borderTop:"none",borderRight:`1px solid ${v}`,borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,x.jsx)("div",{style:{backgroundColor:ke,border:`1px solid ${v}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,x.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...k.submitButton,opacity:.5}}),(0,x.jsx)("style",{children:`
|
|
38
|
+
`}),wa&&D&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:U?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:le,style:{display:"inline-flex",alignItems:"center",gap:hs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:rt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...rt.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...rt.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(aa,{content:X})]}),Ll?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:rt.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...rt.title},children:(0,l.jsx)(Ta,{content:G})})]}),!wa&&!Ll&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ps,order:U?-3:0,...rt.title},children:(0,l.jsx)(Ta,{content:G})}),U&&Oe&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:Oe}),U&&bo&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:ea,border:`1px solid ${Rn(ci)}`,borderRadius:sr,padding:"10px"},children:(0,l.jsx)("input",{ref:ee,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Zr,onChange:i=>{qt("email"),tr.current=i.target.value,Lr(i.target.value)},onPointerDown:()=>qt("email"),onKeyDown:()=>qt("email"),onBlur:()=>{Xn("email")&&Kn(!0),Go||ns()},disabled:ir,required:!0,"aria-invalid":ci||void 0,"aria-describedby":ci?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...vs}})}),ci&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ka,children:Qi.empty?"Email address is required":"Enter a valid email address"})]}),Ze&&(0,l.jsx)("div",{style:{order:U?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=at,C=(te=!1)=>({backgroundColor:ea,border:`1px solid ${Rn(te)}`,borderRadius:sr,marginTop:"0.5rem",padding:"10px"}),N=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...vs}),be=(0,c.getStateOptions)(i);return(0,l.jsxs)(l.Fragment,{children:[(0,c.isAVSFieldVisible)(Ze.address_line_1,i)&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{style:C(rr("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:Et,onChange:te=>{qt("line1"),Nr.current.addressLine1=!0,Tr.current=te.target.value,sn(te.target.value)},onPointerDown:()=>qt("line1"),onKeyDown:()=>qt("line1"),onBlur:()=>yn("line1"),disabled:ir,required:!0,"aria-invalid":rr("line1")||void 0,"aria-describedby":rr("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:N()})}),rr("line1")&&(0,l.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ka,children:"Street address is required"})]}),(0,c.isAVSFieldVisible)(Ze.address_line_2,i)&&(0,l.jsx)("div",{style:C(),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:zr,onChange:te=>{Nr.current.addressLine2=!0,Mr.current=te.target.value,Dr(te.target.value)},disabled:ir,"data-testid":"flopay-address-line2",style:N()})}),((0,c.isAVSFieldVisible)(Ze.city,i)||(0,c.isAVSFieldVisible)(Ze.state,i))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(Ze.city,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:ea,borderTop:`1px solid ${Rn(rr("city"))}`,borderRight:`1px solid ${Rn(rr("city"))}`,borderBottom:`1px solid ${Rn(rr("city"))}`,borderLeft:`1px solid ${Rn(rr("city"))}`,padding:"10px",borderTopLeftRadius:sr,borderBottomLeftRadius:sr,...(0,c.isAVSFieldVisible)(Ze.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:sr}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:ln,onChange:te=>{qt("city"),Nr.current.city=!0,Qr.current=te.target.value,Jr(te.target.value)},onPointerDown:()=>qt("city"),onKeyDown:()=>qt("city"),onBlur:()=>yn("city"),disabled:ir,required:!0,"aria-invalid":rr("city")||void 0,"aria-describedby":rr("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:N()})}),(0,c.isAVSFieldVisible)(Ze.state,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:ea,borderTop:`1px solid ${Rn(rr("state"))}`,borderRight:`1px solid ${Rn(rr("state"))}`,borderBottom:`1px solid ${Rn(rr("state"))}`,borderLeft:`1px solid ${Rn(rr("state"))}`,padding:"10px",borderTopRightRadius:sr,borderBottomRightRadius:sr,...(0,c.isAVSFieldVisible)(Ze.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Rn(rr("state")||rr("city"))}`}:{borderRadius:sr}},children:be?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Ir,onChange:te=>{qt("state"),Nr.current.state=!0,mr.current=te.target.value,cn(te.target.value)},onPointerDown:()=>qt("state"),onKeyDown:()=>qt("state"),onBlur:()=>yn("state"),disabled:ir,autoComplete:"billing address-level1",required:!0,"aria-invalid":rr("state")||void 0,"aria-describedby":rr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...N(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,c.getStateLabel)(i)}),be.map(te=>(0,l.jsx)("option",{value:te.code,children:te.name},te.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:Ir,onChange:te=>{qt("state"),Nr.current.state=!0,mr.current=te.target.value,cn(te.target.value)},onPointerDown:()=>qt("state"),onKeyDown:()=>qt("state"),onBlur:()=>yn("state"),disabled:ir,required:!0,"aria-invalid":rr("state")||void 0,"aria-describedby":rr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:N()})})]}),rr("city")&&(0,l.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ka,children:"City is required"}),rr("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ka,children:[(0,c.getStateLabel)(i)," is required"]}),((0,c.isAVSFieldVisible)(Ze.country,i)||(0,c.isAVSFieldVisible)(Ze.postal_code,i))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:ce==="column"?"column":"row",gap:ce==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(Ze.country,i)&&(0,l.jsx)("div",{style:{flex:ce==="row"?1:void 0,backgroundColor:ea,borderTop:`1px solid ${Ra}`,borderRight:`1px solid ${Ra}`,borderBottom:`1px solid ${Ra}`,borderLeft:`1px solid ${Ra}`,padding:"10px",...ce==="row"&&(0,c.isAVSFieldVisible)(Ze.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:sr,borderBottomLeftRadius:sr,borderRight:"none"}:{borderRadius:sr}},children:(0,l.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:at,onChange:te=>{Nr.current.country=!0,pr.current=te.target.value,Pr(te.target.value),Ht?.(te.target.value),mr.current="",cn("")},disabled:ir,autoComplete:"billing country","data-testid":"flopay-country",style:{...N(),cursor:"pointer"},children:[at===""?(0,l.jsx)("option",{value:"",children:"Select country"}):null,c.COUNTRY_OPTIONS.map(te=>(0,l.jsxs)("option",{value:te.code,children:[te.flag," ",te.name]},te.code))]})}),(0,c.isAVSFieldVisible)(Ze.postal_code,i)&&(0,l.jsx)("div",{style:{flex:ce==="row"?1:void 0,backgroundColor:ea,border:`1px solid ${Fd}`,padding:"10px",...ce==="row"&&(0,c.isAVSFieldVisible)(Ze.country,i)?{borderRadius:"0",borderTopRightRadius:sr,borderBottomRightRadius:sr}:{borderRadius:sr}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,c.getPostalCodeLabel)(at),autoComplete:"billing postal-code",value:Xt,onChange:te=>{qt("zip"),Nr.current.zip=!0,ur.current=te.target.value,gt(te.target.value),Mt?.(te.target.value)},onPointerDown:()=>qt("zip"),onKeyDown:()=>qt("zip"),onBlur:()=>{Xn("zip")&&$n(!0)},disabled:ir,required:tn.required,"aria-invalid":di||void 0,"aria-describedby":di?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:N()})})]}),di&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ka,children:tn.empty?`${(0,c.getPostalCodeLabel)(i)} is required`:Gu(i)})]})})()}),U&&Nd,Dn&&(0,l.jsx)(ma,{margin:"0.75rem 0",styleOverride:rt.errorBanner,children:Dn})]}),ui={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"},ql=i=>$?!Z||!Zn?(0,l.jsx)("pre",{"data-testid":i,style:ui,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:ui,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${Z}`,` directPaypalConfigured=${Zn}`,` inAppBrowserDetected=${String(ii)}`,` shouldRenderDirectPayPal=${To}`,` shouldRenderStripePayPal=${Mo}`,` hasPaypalStripeInstance=${!!il}`].join(`
|
|
39
|
+
`)}):null,jl=i=>$?!v||!gn?(0,l.jsx)("pre",{"data-testid":i,style:ui,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:ui,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${v}`,` currency=${Pt}`,` amountInCents=${va}`,` enabledPaymentMethods: ${JSON.stringify(M??[])}`,` enabledPaymentMethodsProvided=${Ca}`,` hasEnabledMethods=${ri}`,` expressMethods: ${JSON.stringify(oi)}`,` walletExpressMethods: ${JSON.stringify(Qo)}`,` paymentElementMethods: ${JSON.stringify(as)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ai)}`,` hasStripeInstance=${!!gn}`,` shouldRenderWallets=${So}`,` shouldRenderPaymentElement=${Ao}`].join(`
|
|
40
|
+
`)}):null,Vl=dt==="apm-expanding"||dt==="apm-form"||dt==="apm-collapsing",ra;dt==="apm-expanding"?ra=Nc:dt==="apm-collapsing"&&(ra=Uc);let pi=Jt?Gc(is,Jt,F):null,Wl={label:ut||Ec,open:Xr,onOpen:_t,color:wo,fontFamily:Hr?.fontFamily};if(ye==="buttons"){let i=dt==="buttons"||dt==="expanding"||dt==="apm-expanding",C=dt==="expanding"||dt==="card"||dt==="collapsing",N=Re===void 0?{boxSizing:"border-box",height:Eo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},be;dt==="expanding"||dt==="apm-expanding"?be=Wu:(dt==="collapsing"||dt==="apm-collapsing")&&(be=Vu);let te;dt==="expanding"?te=Nc:dt==="collapsing"&&(te=Uc);let Fe=kr&&(0,c.placePaymentMethodGroups)(kr,{canHide:()=>!0,available:Tl}),Vt={paypal:(0,l.jsxs)(l.Fragment,{children:[To&&ze&&(0,l.jsxs)(l.Fragment,{children:[Le&&(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)(Fa.Provider,{value:L,children:(0,l.jsx)(Oa,{sessionId:e,nonce:t,billingApiUrl:Te,email:Tt.email,billingName:Ko||void 0,onBuyerIdentityReady:$r,clientId:ze.clientId,environment:ze.environment,currency:Pt.toUpperCase(),isSubscription:Nt,providerObjectType:B,approvalPresentation:si==="popup"?void 0:si,onTokenizedBody:rn,onComplete:d,onErrorChange:Ne,onDecline:m,onCancel:b,onTechnicalFailure:Jo,onButtonClick:Ee,runBeforeButtonClick:Nn,isProcessing:ir,onLoadStateChange:ds,onInitializationStateChange:us,session:H,existingOrderId:Le?.orderId,debug:$},Le?.orderId??"fresh")})]}),Mo&&(0,l.jsx)(lr.Elements,{stripe:ba,options:cl,children:(0,l.jsx)(qc,{sessionId:e,nonce:t,email:Tt.email,billingName:Ko||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,onTokenizedBody:rn,onErrorChange:Ne,isProcessing:ir,onButtonClick:Ee,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:bl,placeholderBorderRadius:uo,popupCapabilityOwner:L,externalTelemetryContext:_l,presentationMode:Zo})})]}),wallets:(0,l.jsxs)(l.Fragment,{children:[So?(0,l.jsx)(lr.Elements,{stripe:gn,options:ll,children:(0,l.jsx)(jc,{sessionId:e,nonce:t,email:Tt.email,billingName:Ko||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,intentKind:Ye>0?"payment":"setup",expressMethods:Qo,onTokenizedBody:rn,onErrorChange:Ne,onButtonClick:Ee,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:Sl,placeholderBorderRadius:uo,popupCapabilityOwner:L,externalTelemetryContext:I})}):null,!So&&El?(0,l.jsx)("div",{style:{height:Eo,borderRadius:uo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:(0,l.jsx)(l.Fragment,{children:Ao&&(0,l.jsx)(Vc,{sessionId:e,nonce:t,email:Tt.email,billingName:[Tt.firstName,Tt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,paymentElementMethods:ai,stripeInstance:gn,paymentElementBaseOptions:is,futureUseSession:F,onTokenizedBody:rn,onErrorChange:Ne,onButtonClick:Ee,onDecline:m,runBeforeButtonClick:Nn,onLoadStateChange:wl,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,onExpandApm:f,expandedApmMethod:Jt,themeId:z,buttonAppearance:{backgroundColor:rt.cardButton?.backgroundColor,borderColor:rt.cardInputBorder,textColor:rt.cardButton?.color,borderRadius:uo}})}),card:(0,l.jsx)(l.Fragment,{children:U&&(0,l.jsx)("button",{type:"button",onClick:async()=>{ir||!(await Nn("card")).proceed||(Ee?.("card"),yt())},disabled:ir,style:{width:"100%",...N,...rt.cardButton,...Hs({themeBundle:$o,resolvedPrimaryColor:wo,resolvedBorderRadius:sr,submitButtonStyle:rt.submitButton,explicitPrimaryColor:Hr?.colorPrimary}),fontSize:rt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ir?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ir?.6:1},onMouseEnter:Wt=>{!ir&&($o||Hr?.colorPrimary)&&(Wt.currentTarget.style.backgroundColor=Dd)},onMouseLeave:Wt=>{($o||Hr?.colorPrimary)&&(Wt.currentTarget.style.backgroundColor=wo)},onMouseDown:Wt=>{Wt.currentTarget.style.transform="scale(0.985)"},onMouseUp:Wt=>{Wt.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(oa,{content:Re})})})};return(0,l.jsxs)("form",{onSubmit:ys,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),j&&(0,l.jsx)(nn,{status:j,errorMessage:Dn,authorized:O}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!be?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!be?Hu:{},...be?{animation:be,pointerEvents:"none"}:{}},children:[ql("flopay-direct-paypal-gate-debug"),jl("flopay-stripe-gate-debug"),Kt&&Fe?(0,l.jsxs)(l.Fragment,{children:[Kt.filter(({group:Wt})=>Fe.inView.includes(Wt)).map(({group:Wt,key:ot})=>(0,l.jsx)(o.default.Fragment,{children:Vt[Wt]},ot)),Fe.behindLink.length>0&&(0,l.jsx)(Fs,{...Wl,showLink:Fe.showLink,children:Kt.filter(({group:Wt})=>Fe.behindLink.includes(Wt)).map(({group:Wt,key:ot})=>(0,l.jsx)(o.default.Fragment,{children:Vt[Wt]},ot))})]}):(0,l.jsx)(Os,{rows:Il,borderRadius:uo}),Dn&&dt==="buttons"&&(0,l.jsx)(ma,{margin:"0.25rem 0",styleOverride:rt.errorBanner,children:Dn})]}),U&&C&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...te?{animation:te}:{},...dt==="collapsing"?{pointerEvents:"none"}:{}},children:Ss}),v&&Vl&&Jt&&pi&&gn&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...ra?{animation:ra}:{},...dt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:gs,borderRadius:bs,...Ea,padding:Cs},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:w,style:{display:"inline-flex",alignItems:"center",gap:hs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:rt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...rt.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...rt.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(aa,{content:X})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:rt.titleFontSize??"1.05rem",color:Ps,paddingRight:80,...rt.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(Jt)}`})]}),(0,l.jsx)(lr.Elements,{stripe:gn,options:pi,children:(0,l.jsx)(Vs,{method:Jt,sessionId:e,nonce:t,email:Tt.email,billingName:[Tt.firstName,Tt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,onTokenizedBody:rn,onErrorChange:Ne,onDecline:m,onCancel:w,runBeforeButtonClick:Nn,onButtonClick:Ee,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,errorText:Dn})},Jt)]})})]})]})}if(Vl&&Jt&&pi&&gn&&v)return(0,l.jsxs)("form",{onSubmit:ys,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),j&&(0,l.jsx)(nn,{status:j,errorMessage:Dn,authorized:O}),(0,l.jsx)("div",{style:{...ra?{animation:ra}:{},...dt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:gs,borderRadius:bs,...Ea,padding:Cs},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:w,style:{display:"inline-flex",alignItems:"center",gap:hs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:rt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...rt.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...rt.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(aa,{content:X})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:rt.titleFontSize??"1.05rem",color:Ps,paddingRight:80,...rt.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(Jt)}`})]}),(0,l.jsx)(lr.Elements,{stripe:gn,options:pi,children:(0,l.jsx)(Vs,{method:Jt,sessionId:e,nonce:t,email:Tt.email,billingName:[Tt.firstName,Tt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,onTokenizedBody:rn,onErrorChange:Ne,onDecline:m,onCancel:w,runBeforeButtonClick:Nn,onButtonClick:Ee,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,errorText:Dn})},Jt)]})})]});let $l=Id||_d||Td,_a=kr&&(0,c.placePaymentMethodGroups)(kr,{canHide:i=>i!=="card",available:Tl}),Hl={paypal:(0,l.jsxs)(l.Fragment,{children:[To&&ze&&(0,l.jsxs)(l.Fragment,{children:[Le&&(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)(Fa.Provider,{value:L,children:(0,l.jsx)(Oa,{sessionId:e,nonce:t,billingApiUrl:Te,email:Tt.email,billingName:Ko||void 0,onBuyerIdentityReady:$r,clientId:ze.clientId,environment:ze.environment,currency:Pt.toUpperCase(),isSubscription:Nt,providerObjectType:B,approvalPresentation:si==="popup"?void 0:si,onTokenizedBody:rn,onComplete:d,onErrorChange:Ne,onDecline:m,onCancel:b,onTechnicalFailure:Jo,onButtonClick:Ee,runBeforeButtonClick:Nn,isProcessing:ir,onLoadStateChange:ds,onInitializationStateChange:us,session:H,existingOrderId:Le?.orderId,debug:$},Le?.orderId??"fresh")})]}),Mo&&(0,l.jsx)(lr.Elements,{stripe:ba,options:cl,children:(0,l.jsx)(qc,{sessionId:e,nonce:t,email:Tt.email,billingName:Ko||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,onTokenizedBody:rn,onErrorChange:Ne,isProcessing:ir,onButtonClick:Ee,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:bl,placeholderBorderRadius:uo,popupCapabilityOwner:L,externalTelemetryContext:_l,presentationMode:Zo})})]}),wallets:(0,l.jsx)(l.Fragment,{children:So&&(0,l.jsx)(lr.Elements,{stripe:gn,options:ll,children:(0,l.jsx)(jc,{sessionId:e,nonce:t,email:Tt.email,billingName:Ko||void 0,onBuyerIdentityReady:$r,billingApiUrl:Te,intentKind:Ye>0?"payment":"setup",expressMethods:Qo,onTokenizedBody:rn,onErrorChange:Ne,onButtonClick:Ee,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:Sl,placeholderBorderRadius:uo,popupCapabilityOwner:L,externalTelemetryContext:I})})}),apms:(0,l.jsx)(l.Fragment,{children:Ao&&(0,l.jsx)(Vc,{sessionId:e,nonce:t,email:Tt.email,billingName:[Tt.firstName,Tt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Te,paymentElementMethods:ai,stripeInstance:gn,paymentElementBaseOptions:is,futureUseSession:F,onTokenizedBody:rn,onErrorChange:Ne,onButtonClick:Ee,onDecline:m,runBeforeButtonClick:Nn,onLoadStateChange:wl,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,themeId:z,onExpandApm:f,expandedApmMethod:Jt,buttonAppearance:{backgroundColor:rt.cardButton?.backgroundColor,borderColor:rt.cardInputBorder,textColor:rt.cardButton?.color,borderRadius:uo}})})};return(0,l.jsxs)("form",{onSubmit:ys,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),j&&(0,l.jsx)(nn,{status:j,errorMessage:Dn,authorized:O}),Kt===null?(0,l.jsx)(Os,{rows:Il,borderRadius:uo}):(0,l.jsxs)(l.Fragment,{children:[Vr&&U&&Ss,Vr&&U&&$l&&(0,l.jsx)(Ka,{label:"or pay another way"}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ql("flopay-direct-paypal-gate-debug-default"),jl("flopay-stripe-gate-debug-default"),Kt.map(({group:i,key:C})=>i==="card"||!_a?.inView.includes(i)?null:(0,l.jsx)(o.default.Fragment,{children:Hl[i]},C)),_a&&_a.behindLink.length>0&&(0,l.jsx)(Fs,{...Wl,showLink:_a.showLink,children:Kt.map(({group:i,key:C})=>_a.behindLink.includes(i)&&i!=="card"?(0,l.jsx)(o.default.Fragment,{children:Hl[i]},C):null)})]}),!Vr&&U&&$l&&(0,l.jsx)(Ka,{label:"or pay with card"}),!Vr&&U&&Ss]})]})}var x=require("react/jsx-runtime"),qo=44,Qs="flopay_checkout_saved_payment_resume",tp="paypal_resume_nonce_missing",Hi=new Map,Wi=new Map;function Yc(e,t){t.settled&&t.consumers===0&&Hi.get(e)===t&&Hi.delete(e)}function rp(e,t,r){let n=Wi.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};Wi.set(e,s);let d=()=>{Wi.get(e)===s&&Wi.delete(e)};return a.then(d,d),a}function Ja(e){return new Promise(t=>setTimeout(t,e))}function $i(e,t,r){let n=wi({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:me.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Za(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Gs(e,t,r,n,a,s){let d=$i(e,t,r);d.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Za(d)}function Xc(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 Jc(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 Ys(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,me.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var np={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function op(e){return new Po.FloPay(np,{publishableKey:"provider_unavailable",...e})}async function Xs(e,t){let{publishableKey:r,paypalPublishableKey:n}=As(e);return{...await xs({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function el(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ap(){if(!el())return null;try{let e=window.sessionStorage.getItem(Qs);return e?JSON.parse(e):null}catch{return null}}function Zc(e){if(el())try{window.sessionStorage.setItem(Qs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Js(){if(el())try{window.sessionStorage.removeItem(Qs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ip(){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 Qc(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 Zs(e,t){return(0,me.resolveCheckoutLogLayout)(!!e,t)}function sp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function ed(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function lp(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 Ki({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:d,loading:p,error:m,onComplete:b,onError:P,onInstrument:g,onDecline:_,onCancel:V,onCountryChange:W,onZipChange:k,showPayPal:T=!0,showStripe:y=!0,walletPresentation:K="auto",enabledPaymentMethods:Z,showApplePay:v=!0,showGooglePay:ke=!0,debug:M=!1,layout:se,paymentMethodLayout:Se,moreOptionsLabel:Ie,theme:ye,buttonsTheme:vt,buttonsStyles:ut,cardButtonContent:z,cardBackButtonContent:We,cardTitleContent:$e,showSecurityFooter:Be,onButtonClick:Re,onBeforeButtonClick:X,enableAVS:G,cardFieldOrder:tt,cardAutoFocus:Ee,onCardFieldsReady:qe,onCardFieldsFailed:re,cardFieldsTimeoutMs:q,cardPreFormSlot:we,avsLayout:Q,submitLabel:pt,className:fe,initialErrorMessage:Pe=null,initialPayPalOrderId:Oe,children:ce,checkoutMode:je,confirmLabel:De,renderConfirmButton:nt,onSessionCompleted:ct}){let Y=(0,me.resolveBillingApiUrl)(n),Rt=(0,R.useMemo)(()=>(0,me.resolveTheme)(ye),[ye]),Ht=s??Rt?.appearance,Mt=r?"embedded_checkout":"standard_checkout",Lt=Zs(ce,se),[he,Me]=(0,R.useState)(null),[Ye,Pt]=(0,R.useState)(null),ft=(0,R.useRef)(null),ze=(0,R.useRef)(null),Nt=(0,R.useRef)(0),[de,kt]=(0,R.useState)(null),At=(0,R.useRef)(null),[$,ge]=(0,R.useState)(null),Ut=(0,R.useMemo)(()=>r?(0,ht.serializeCreateParams)(r):"",[r]),h=r?`create:${Ut}`:`session:${e??""}`,J=ed($),He=(0,R.useRef)(new Set),L=(0,R.useRef)(h),mt=(0,R.useRef)(h);Oo(()=>{mt.current=h,L.current!==h&&(L.current=h,He.current.clear())},[h]);let u=(0,R.useCallback)(A=>{if(mt.current===h){if(Ts.FLO_INSTRUMENT_ONCE_NAMES.has(A.name)){if(He.current.has(A.name))return;He.current.add(A.name)}(0,Ge.invokeMerchantCallback)(()=>g?.(A))}},[h,g]),S=pa(u,h),I=(0,R.useRef)(!1),H=(0,R.useCallback)(A=>{if(I.current)return;let D=A.gateway||!J?A:{...A,gateway:J};u(D)},[u,J]);(0,R.useEffect)(()=>{S({class:"lifecycle",name:"checkout.mount"})},[S]);let[F,B]=(0,R.useState)(e??""),Ae=e??F,jr=r?"":Ae,[$t,nr]=(0,R.useState)(!0),[Te,kr]=(0,R.useState)(null),[Ur,Xr]=(0,R.useState)(0),[Or,Kt]=(0,R.useState)("full"),[Vr,an]=(0,R.useState)(!1),[Er,_r]=(0,R.useState)(Pe),[vn,at]=(0,R.useState)(null),[Pr,Xt]=(0,R.useState)(null),[gt,Et]=(0,R.useState)(!1),[sn,zr]=(0,R.useState)(void 0),[Dr,ln]=(0,R.useState)(""),[Jr,Ir]=(0,R.useState)(!1),[cn,Zr]=(0,R.useState)(!1),[Lr,or]=(0,R.useState)(!1),vr=(0,R.useRef)(null),ur=(0,R.useRef)(0),pr=(0,R.useRef)(void 0),[Tr,Mr]=(0,R.useState)("loading"),[Qr,mr]=(0,R.useState)(0),tr=(0,R.useRef)(!1),Nr=(0,R.useRef)(!1),Ze=(0,R.useRef)(!1),Cn=(0,R.useRef)(null),O=(0,R.useRef)(null),Qe=(0,R.useMemo)(()=>({checkoutMode:je??Or,layout:sp(ce,se)}),[je,ce,Or,se]),ue=(0,R.useRef)(b);ue.current=b;let ve=(0,R.useRef)(P);ve.current=P;let Gt=(0,R.useRef)(_);Gt.current=_;let zt=(0,R.useCallback)(A=>_i(Cn,async D=>{try{return await A(D)}catch(ne){throw D.aborted?ya(ne):ne}}),[]);(0,R.useEffect)(()=>()=>{Cn.current?.abort(),Cn.current=null},[]);let xt=(0,R.useCallback)((A,D)=>{ft.current=A,Pt(A),At.current=D,kt(D)},[]),U=(0,R.useCallback)(()=>{let A=ze.current;A&&(ze.current=null,A.destroy())},[]);(0,R.useEffect)(()=>{br(Ye)?.setCheckoutContext(Qe),de&&de!==Ye&&br(de)?.setCheckoutContext(Qe)},[Ye,de,Qe]);let bn=(0,R.useRef)(ct);bn.current=ct;let Vo=(0,R.useCallback)(A=>{Mr(A),!(A!=="exhausted"||Ze.current)&&(Ze.current=!0,ve.current?.(new me.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Io=(0,R.useCallback)(()=>{Mr("retrying"),mr(A=>A+1)},[]);(0,R.useEffect)(()=>{Mr("loading"),mr(0),Ze.current=!1},[Ae]),(0,R.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:me.SDK_VERSION,checkout_type:Mt,checkout_layout:Lt,billing_api_url:Y})},[Lt,Mt,Y]);let Sn=(0,R.useMemo)(()=>r?(0,ht.serializeCreateParams)(r,!0):"",[r]),xn=(0,R.useMemo)(()=>Dr===Sn?sn:void 0,[sn,Dr,Sn]),dn=(0,R.useMemo)(()=>r?ks(r,xn):void 0,[r,xn]),en=je??dn?.checkoutMode??"full",ar=(0,R.useMemo)(()=>dn?{...dn,checkoutMode:en}:void 0,[dn,en]);(0,R.useEffect)(()=>{zr(void 0),ln(Sn),pr.current=void 0,vr.current=null,or(!1)},[Sn]),(0,R.useEffect)(()=>{_r(Pe)},[Pe]);let Fn=(0,R.useCallback)((A,D,ne)=>{(0,Ge.invokeMerchantCallback)(()=>{Gt.current?.(Cr(A,D,ne))})},[]),un=(0,R.useCallback)(async(A,D)=>{_r(null),Xt(null),Et(!1),at("processing");let ne=D?.sessionId??A.id,Ce=A.clientSecret||t,_t=ed(A),Zt=ft.current??At.current,xe=br(Zt),it=Zt?null:$i(Y,a,Qe),oe={log:ee=>{xe?xe.log(ee):it?.log(ee)},error:ee=>{xe?xe.error(ee):it?.error(ee)},terminal:ee=>{xe?xe.terminal(ee):it?.terminal(ee)},performance:ee=>{xe?xe.performance(ee):it?.performance(ee)},now:()=>xe?.now()??it?.now()??0,elapsed:ee=>xe?.elapsed(ee)??Math.max(0,(it?.now()??ee)-ee)},et=oe.now(),pe=!!(D?.initialAutoProcessingError||D?.initialAutoProcessingPending),yt=!1,le,f=()=>{yt||(yt=!0,pe=!0,le=oe.now(),oe.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),oe.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},w=!1,j=()=>{w||(w=!0,oe.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),oe.performance({stage:"processing",durationMs:oe.elapsed(et),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),le!==void 0&&oe.performance({stage:"recovery",durationMs:oe.elapsed(le),durationMode:"machine",paymentMethodCategory:"saved"}))};oe.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),I.current=!0;try{oe.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{I.current=!1}S({class:"lifecycle",name:"payment.processing.started",provider:_t}),pe&&f();let ae;try{let ee=Sc(D?.initialAutoProcessingError),ie=D?.initialAutoProcessingError?.type==="3ds_required"&&!(0,me.isMerchantAuthRequired)(D.initialAutoProcessingError)&&!D.initialAutoProcessingError.threeDSecureToken&&D.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:D.initialAutoProcessingError.nextActionRedirectUrl}:null,Bt,Ot=st=>{f();let Ct=qa(Y,ne,A,a!==!1);return zt(It=>fa(st,{billingApiUrl:Y,sessionId:ne,nonce:Ce,session:A,signal:It,...Ct.telemetry?{challengeTelemetry:Ct.telemetry}:{}})).finally(Ct.release)};if(ie)Bt=await Ot(ie);else if(ee)f(),ee.type==="paypal_redirect_required"&&O.current?.publishableKey&&Zc({sessionId:ne,publishableKey:O.current.publishableKey,paypalPublishableKey:O.current.paypalPublishableKey,nonce:Ce}),Bt=await zt(st=>Ti(ee,{flopay:ft.current,paypalFlopay:At.current,attempt3DS:D?.attempt3DS,billingApiUrl:Y,sessionId:ne,session:A,telemetry:!1,signal:st})),ee.type==="paypal_redirect_required"&&Js();else if(D?.initialAutoProcessingPending){let st=D.initialAutoProcessingPending,Ct=new Po.PaymentAPI(Y,{telemetry:!1}),It=await zt(Le=>Ct.waitForCheckoutSessionCompletion(st.sessionId,{initialDelayMs:st.retryAfterMs,nonce:Ce,statusUrl:st.statusUrl,signal:Le})),Xe=ko(It,A),Ke=It.autoProcessingError?.type==="3ds_required"&&It.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:It.autoProcessingError.nextActionRedirectUrl}:null;if(Ke)Bt=await Ot(Ke);else{if(!mo(Xe))throw sa(Xe);Bt=po(Xe,ne)}}else{if(D?.initialAutoProcessingError)throw ro(D.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.initialAutoProcessingError.checkoutMethod});if(D?.fromCreateSession)return D?.fallbackToFull&&(Kt("full"),Qc("full")),!1;{let st=await ga({billingApiUrl:Y,sessionId:ne,session:A,nonce:Ce,telemetry:!1});st.type==="success"?Bt=st.result:st.type==="next_action_required"?Bt=await Ot(st):(f(),st.type==="paypal_redirect_required"&&O.current?.publishableKey&&Zc({sessionId:ne,publishableKey:O.current.publishableKey,paypalPublishableKey:O.current.paypalPublishableKey,nonce:Ce}),Bt=await zt(Ct=>Ti(st,{flopay:ft.current,paypalFlopay:At.current,attempt3DS:D?.attempt3DS,billingApiUrl:Y,sessionId:ne,session:A,telemetry:!1,signal:Ct})),st.type==="paypal_redirect_required"&&Js())}}ne&&(0,jn.markSessionRecentlyCompleted)(ne),j(),pe&&(oe.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),oe.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),oe.terminal({outcome:Bt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Et(Bt.status==="authorized"),at("success"),await Ja(600),ae=()=>ue.current?.(Bt)}catch(ee){let ie=Ro(ja(ee),ne);if(ie.code==="three_ds_aborted")return!1;let Bt=ie.checkoutMethod??za;_r(ie.message),Xt(ie.message),Et(!1),D?.fallbackToFull&&(oe.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Kt("full"),Qc("full")),j();let Ot=ie.statusCode===void 0?void 0:(0,me.telemetryStatusClass)(ie.statusCode,"unknown"),st=Ot==="4xx"?{requestCategory:"process_payment",statusClass:Ot}:{},Ct=Ot===void 0||Ot==="4xx";if((0,me.isExpectedPaymentDecline)(ie))oe.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...st});else if(Ct&&(ie.telemetryOutcome==="validation_rejected"||ie.type==="validation_error"))oe.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...st});else{let Ke=(0,me.classifyTelemetryFailure)(ee,pe?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Le=ie.telemetryRequestCategory??"process_payment";I.current=!0;try{oe.error({...Ke,...ie.telemetryFailureCategory?{failureCategory:ie.telemetryFailureCategory}:{},stage:pe?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Le})}finally{I.current=!1}S({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Le,provider:_t})}return(0,me.isDeclineCallbackFailure)(ie)?Fn(Bt,ie,{code:ie.code,declineCode:ie.declineCode}):(0,Ge.invokeMerchantCallback)(()=>ve.current?.(ie)),at("error"),await Promise.allSettled([Ja(400),D?.ensureProvidersReady?D.ensureProvidersReady():Promise.resolve()]),pe&&(oe.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),oe.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{j(),it&&Za(it),at(null),Xt(null)}return(0,Ge.invokeMerchantCallback)(ae),!0},[Fn,S,t,Y,zt,a,Qe]);(0,R.useEffect)(()=>{if(typeof window>"u"||Nr.current)return;let A=new URLSearchParams(window.location.search),D=A.get("payment_intent_client_secret");if(!D)return;let ne=ap();ne&&(Nr.current=!0,(async()=>{await Promise.resolve();let Ce,_t=0;_r(null),Xt(null),at("processing"),an(!0);try{if(A.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:Zt,paypalFlopay:xe}=await xs({publishableKey:ne.publishableKey,paypalPublishableKey:ne.paypalPublishableKey,billingApiUrl:Y,locale:d,telemetry:a});Ce=br(xe??Zt),Ce?.setCheckoutContext(Qe),_t=Ce?.now()??0,Ce?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Ce?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let it=(xe??Zt)?.getRawProvider();if(!it)throw Object.assign(new me.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:oe,error:et}=await it.retrievePaymentIntent(D);if(et)throw Object.assign(new me.FloPayError(et.message??"Failed to retrieve PayPal payment status.","api_error",{code:et.code}),{checkoutMethod:"paypal"});let pe=oc(oe?.status);if(!oe||pe==="failed")throw Object.assign(new me.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let yt=typeof oe.payment_method=="string"?oe.payment_method:oe.payment_method?.id,le=pe;if(ne.sessionId){let f=ne.nonce||t;if(!f)throw Object.assign(new me.FloPayError("Unable to resume the PayPal payment: the checkout session nonce is missing.","validation_error",{code:tp}),{checkoutMethod:"paypal"});let ae=(await new Po.PaymentAPI(Y,{telemetry:!1}).getUnifiedCheckoutSession(ne.sessionId,f)).data.session;if(ae&&ae.status!=="complete"){let ee=await ga({billingApiUrl:Y,sessionId:ne.sessionId,session:ae,nonce:f,telemetry:!1,tokenizedData:{id:yt??oe.id,type:"card",threeDSecureActionResultTokenId:oe.id,isPaypal:!0}});if(ee.type!=="success")throw Object.assign(new me.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});le=ee.result.status}}ne.sessionId&&(0,jn.markSessionRecentlyCompleted)(ne.sessionId),Ce?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Ce?.performance({stage:"redirect_resume",durationMs:Ce.elapsed(_t),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Ce?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),at("success"),await Ja(600),(0,Ge.invokeMerchantCallback)(()=>ue.current?.({status:le,paymentIntentId:oe.id,paymentMethodId:yt,checkoutMethod:"paypal"}))}catch(Zt){let xe=Ro(ja(Zt),ne.sessionId),it=xe.checkoutMethod??"paypal",oe=(0,me.isExpectedPaymentDecline)(xe);if(Ce)Ce.performance({stage:"redirect_resume",durationMs:Ce.elapsed(_t),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),oe?Ce.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Ce.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(oe){let et=$i(Y,a,Qe);et.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Za(et)}else Gs(Y,a,Qe,"REDIRECT_RESUME_FAILED","redirect_resume");_r(xe.message),Xt(xe.message),(0,me.isDeclineCallbackFailure)(xe)?Fn(it,xe,{code:xe.code,declineCode:xe.declineCode}):(0,Ge.invokeMerchantCallback)(()=>ve.current?.(xe)),at("error"),await Ja(400)}finally{Js(),ip(),at(null),Xt(null),an(!1)}})())},[Fn,d,t,Y,a,Qe]);let Bn=(0,R.useRef)(null),Ft=(0,R.useMemo)(()=>ar?(0,ht.serializeCreateParams)(ar):"",[ar]),tn=(0,R.useRef)(ar);tn.current=ar,(0,R.useEffect)(()=>{B(e??"")},[e]),(0,R.useEffect)(()=>{tr.current=!1,_r(Pe),Xt(null),Et(!1),at(null)},[Ft,Pe,e]);async function pn(A,D,ne){let Ce=$i(Y,a,Qe),_t=new Po.PaymentAPI(Y,{telemetry:!1}),Zt=!1;try{let xe=A.idempotencyKey===void 0?void 0:(0,me.resolveIdempotencyKey)(A.idempotencyKey),it=(0,ht.readCachedInlineSession)(D,ne),oe=(0,ht.readCachedInlineIdempotencyKey)(D,ne);it?.canonicalIdentity===ne&&oe&&oe.canonicalIdentity===void 0&&((0,ht.persistCachedInlineIdempotencyKey)(D,ne,oe.idempotencyKey),oe={...oe,canonicalIdentity:ne});let et=xe??(oe?.canonicalIdentity===ne?oe.idempotencyKey:void 0),pe,yt=!1;Ce.log({name:it?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let le=it?.sid??null,f=null,w,j,ae=!1;if(le)try{f=await _t.getUnifiedCheckoutSession(le,it?.nonce),it&&it.canonicalIdentity===void 0&&((0,ht.legacyCachedSessionMatchesDraft)(f.data.session,A)?((0,ht.persistCachedInlineSession)(D,ne,le,it.nonce??f.data.session?.clientSecret),oe&&oe.canonicalIdentity===void 0&&((0,ht.persistCachedInlineIdempotencyKey)(D,ne,oe.idempotencyKey),et??(et=oe.idempotencyKey))):((0,ht.clearCachedInlineCheckout)(D,ne),oe=null,et=xe,le=null,f=null));let ie=f?.data.session?.status,Bt=f?.data.session,Ot=Bt?.clientSecret||it?.nonce;if(le&&Bt?.buyerIdentified===!1&&Ot&&(j=ia(_t,le,Ot,A.account)),le&&f&&ie==="complete"){if((0,jn.wasSessionRecentlyCompleted)(le))return{sid:le,result:f};(0,ht.clearCachedInlineCheckout)(D,ne),le=null,f=null,yt=!0}}catch{Ce.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),it?.canonicalIdentity===void 0?((0,ht.clearCachedInlineCheckout)(D,ne),et=xe):(0,ht.clearCachedInlineSession)(D,ne),le=null}if(!le){!xe&&(yt||!et)&&(et=(0,me.resolveIdempotencyKey)(),pe=et),et&&(0,ht.persistCachedInlineIdempotencyKey)(D,ne,et);let ie=Ce.now(),Bt=0;Ce.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ot={...A,idempotencyKey:et,avsCheck:!!G,avsConfig:typeof G=="object"?G:void 0,checkoutType:"embedded_checkout",checkoutLayout:Zs(ce,se)};Object.defineProperty(Ot,Po.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:It=>{Bt=Math.max(Bt,It)}}});let st=()=>{Xc(Ce,"session_create",ie,Bt)},Ct=It=>{Jc(Ce,It,"session_create",ie,Bt)&&S({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(A.checkoutMode==="confirm"||A.checkoutMode==="auto")&&vc();try{if((0,me.isDetachedSessionEligible)(Ot)){let It=await _t.createDetachedSession(Ot);It.claimed.catch(()=>{}),f=It.shell,le=It.sessionId,j=It.claim;let Xe=Ce.now();Ce.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),w=It.claimed.then(Ke=>{let Le=Ke.data.session?.id??It.sessionId;return Le&&(0,ht.persistCachedInlineSession)(D,ne,Le,Ke.data.session?.clientSecret??It.nonce),Xc(Ce,"session_claim",Xe),st(),Ke},Ke=>{throw(0,ht.clearCachedInlineSession)(D,ne),Jc(Ce,Ke,"session_claim",Xe,0)&&S({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Ke}).finally(()=>Za(Ce)),w.catch(()=>{}),Zt=!0,Ce.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Ce.performance({stage:"session_shell",durationMs:Ce.now()-ie,durationMode:"machine",requestCategory:"session_create",attempt:Bt,statusClass:"2xx",paymentMethodCategory:"card"})}else f=await _t.createAndFetchSession(Ot),st()}catch(It){throw Ct(It),It}le=f.data.session?.id??le??"",le&&!w&&(0,ht.persistCachedInlineSession)(D,ne,le,f.data.session?.clientSecret)}let ee=f?.data.session;return!j&&le&&ee?.buyerIdentified===!1&&ee.clientSecret&&(j=ia(_t,le,ee.clientSecret,A.account)),{sid:le??"",result:f,sdkGeneratedIdempotencyKey:pe,...w?{claimed:w}:{},...j?{claim:j}:{},...ae?{claimRequiresIdentity:!0}:{}}}finally{Zt||Za(Ce)}}let io=(0,R.useRef)(pn);Oo(()=>{io.current=pn},[pn]);let mn=(0,R.useCallback)(async(A,D)=>{let ne=tn.current;if(!ne)throw new me.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Ce=ks(ne,A),_t=(0,ht.serializeCreateParams)(Ce),Zt=(0,ht.hashCreateParams)(Ce),xe=Hi.get(_t);if(!xe){let et={canonicalIdentity:_t,promise:io.current(Ce,Zt,_t),consumers:0,settled:!1};xe=et,Hi.set(_t,et);let pe=()=>{et.settled=!0,Yc(_t,et)};et.promise.then(pe,pe)}xe.consumers+=1;let it=!1,oe=()=>{it||(it=!0,xe.consumers-=1,Yc(_t,xe))};D?.(oe);try{let et=await xe.promise;Bn.current=_t,A&&(ln(Sn),zr(ee=>Zl(ee,A)));let{sid:pe,result:yt,claimed:le,claim:f,claimRequiresIdentity:w}=et;if(pr.current=f,or(w===!0),Me(yt),yt.data.session&&ge(yt.data.session),pe&&B(pe),le){ur.current+=1;let ee=ur.current;vr.current=le,Zr(!0),le.then(ie=>{ur.current===ee&&(vr.current===le&&(vr.current=null),Me(ie),ie.data.session&&ge(ie.data.session),Zr(!1),or(!1))},ie=>{ur.current===ee&&(vr.current===le&&(vr.current=null),Zr(!1),or(!1),kr(ie instanceof me.FloPayError?ie:new me.FloPayError(ie instanceof Error?ie.message:"Failed to create session","api_error")))})}else ur.current+=1,vr.current=null,Zr(!1),or(!1);let{flopay:j,paypalFlopay:ae}=await Xs(yt,{billingApiUrl:Y,locale:d,telemetry:a}).catch(ee=>{throw tc(ee,pe||yt.data.session?.id)});return xt(j,ae),nr(!1),et}catch(et){throw Bn.current===_t&&(Bn.current=null),et}finally{D||oe()}},[Sn,xt,d,Y,a]),On=(0,R.useRef)(un);On.current=un;let so=(0,R.useRef)(mn);so.current=mn;let $n=(0,R.useCallback)(async A=>{if(!lp(A)||Jr)return{sessionId:F,session:$};Ir(!0);try{let D=await mn(A);return{sessionId:D.sid,session:D.result.data.session??null}}finally{Ir(!1)}},[mn,Jr,F,$]),Hn=(0,R.useCallback)(async A=>{let D=pr.current;if(!D)return;let ne=ur.current,Ce=await D(A);ur.current===ne&&(Me(Ce),Ce.data.session&&ge(Ce.data.session))},[]),Kn=(0,R.useCallback)(async()=>{await vr.current},[]),lo=(0,R.useCallback)(async()=>(await Kn(),{proceed:!0}),[Kn]);(0,R.useEffect)(()=>{let A=!1,D,ne=++Nt.current;U(),kr(null),Xr(0);let Ce=()=>{A=!0,Nt.current===ne&&(Nt.current+=1,U())},_t=tn.current;if(Ft&&_t)return Kt(en),nr(!1),Bn.current===Ft?Ce:(ge(Ql(_t,je)),(async()=>{let it=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),oe=en==="auto"&&!tr.current&&!it;oe&&(_r(null),Xt(null),at("processing"));let et=!1;try{let pe=await so.current(void 0,w=>{D=w});et=!0;let yt=pe.result.data.session??null;O.current=As(pe.result);let le=Ys(pe.result),f=(0,jn.wasSessionRecentlyCompleted)(pe.sid||yt?.id);if(!A&&oe&&yt&&!le&&!f){tr.current=!0,await rp(Ft,pe.sdkGeneratedIdempotencyKey,()=>On.current(yt,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:pe.result.autoProcessingError,initialAutoProcessingPending:pe.result.autoProcessingPending,autoProcessingAttempted:pe.result.autoProcessingAttempted,sessionId:pe.sid||yt.id}));return}!A&&oe&&((le||f)&&(tr.current=!0),at(null),Xt(null))}catch(pe){if(A)return;let yt=gi(pe);if(oe&&yt==="session_auto_completed"){tr.current=!0,at("success"),await Ja(600),A||((0,Ge.invokeMerchantCallback)(()=>{ue.current?.({status:"succeeded"})}),at(null),Xt(null));return}if(oe&&(at(null),Xt(null)),!et){let f=rc(pe),w=(0,me.toPublicCheckoutInitError)(pe,f?{stage:"provider_load",provider:"stripe",...f}:{stage:"session_request"});(f||!(pe instanceof me.FloPayError))&&(0,Ge.invokeMerchantCallback)(()=>ve.current?.(w)),kr(w);return}let le=pe instanceof me.FloPayError?pe:new me.FloPayError(pe instanceof Error?pe.message:"Failed to create session","api_error");kr(le)}finally{D?.(),D=void 0}})(),()=>{Ce(),D?.()});nr(!0);async function Zt(){let it=!1,oe=!1,et=null;try{let pe=new Po.PaymentAPI(Y,{telemetry:!1}),yt=await pe.getUnifiedCheckoutSession(Ae,t);if(oe=!0,et=yt,A)return;Me(yt);let le=yt.data.session??null;if(ge(le),!le)throw new me.FloPayError("No session data returned","api_error");let f=le.checkoutMode;if(f==="setup")throw new me.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(le.status==="authorized"){nr(!1),(0,Ge.invokeMerchantCallback)(()=>{ue.current?.(po(le,Ae)),bn.current?.(le.successUrl??"")});return}if(le.status==="complete"){nr(!1),(0,Ge.invokeMerchantCallback)(()=>{bn.current?.(le.successUrl??"")});return}if(le.status==="expired")throw fi(le);it=!0;let w=je??f??"full";Kt(w),ur.current+=1;let j=le.clientSecret||t;pr.current=le.buyerIdentified===!1&&j?ia(pe,Ae,j,{...le.customer?.id?{userId:le.customer.id}:{}}):void 0,Zr(!1),or(!1);let ae=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ee=Ys(yt);if(w==="auto"&&!tr.current&&!ae&&!ee){tr.current=!0;let ie=xe(yt);try{if(await On.current(le,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ie,sessionId:Ae||le.id}),A)return;await ie,A||nr(!1);return}catch{if(A)return;await ie,A||nr(!1);return}}await xe(yt),A||nr(!1)}catch(pe){if(A)return;let yt=Jl(pe,it);if(it&&S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),yt){let{errorCode:j,stage:ae,...ee}=yt;Gs(Y,a,Qe,j,ae,ee)}if(yt?.stage==="provider_load"&&(je??et?.data.session?.checkoutMode??"full")==="full"&&Xl(et,T,y)){let j=op({billingApiUrl:Y,locale:d,telemetry:a});ze.current=j,xt(j,null),Xr(1),nr(!1);return}let le=yt?.stage==="provider_load",f="session_request";le?f="provider_load":oe&&(f="post_session");let w=(0,me.toPublicCheckoutInitError)(pe,{stage:f,provider:"stripe",sessionId:Ae||void 0});(le||!(pe instanceof me.FloPayError))&&(0,Ge.invokeMerchantCallback)(()=>ve.current?.(w)),kr(w),nr(!1)}}async function xe(it){let{flopay:oe,paypalFlopay:et,...pe}=await Xs(it,{billingApiUrl:Y,locale:d,telemetry:a});O.current={publishableKey:pe.publishableKey,paypalPublishableKey:pe.paypalPublishableKey},xt(oe,et),Xr(0)}return Zt(),Ce},[je,Ft,en,jr,t,T,y]);let Wo=(0,R.useCallback)(async()=>{if(!he||Ur!==1)return;let A=Nt.current;Xr(2);try{let{flopay:D,paypalFlopay:ne}=await Xs(he,{billingApiUrl:Y,locale:d,telemetry:a});if(Nt.current!==A)return;U(),xt(D,ne),Xr(0)}catch(D){if(Nt.current!==A)return;let{errorCode:ne,stage:Ce,..._t}=Rs(D);Gs(Y,a,Qe,ne,Ce,_t)}},[U,xt,d,Ur,Y,a,Qe,he]),Gn=!!(Ae&&($?.clientSecret||t)),co=Vr||!Gn,Yn=(0,R.useCallback)(async()=>{if(!(Vr||!Gn||!$)){an(!0),_r(null);try{await un($,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ae||$.id})}finally{an(!1)}}},[Ae,Vr,Gn,un,$]),qt=(0,me.resolveDirectPaypalConfig)(he?.data.paypal,Oe),Xn=Ys(he),yn=(0,R.useMemo)(()=>{if(!(!he||!$||!he.data.stripe?.publishableKey))return{billingApiUrl:Y}},[he,$,Y]),wn=!!(r&&!ce&&se==="buttons"&&X&&en==="full"),fn=!!(Ae&&((0,me.isMountableVaultBlock)($?.vault)||(0,Un.canRecoverHostedCardForm)($))),dt=(0,R.useMemo)(()=>({session:$,loading:$t,error:Te,checkoutMode:Or,inlineSessionDraft:ar,applyInlineSessionPatch:wn?$n:void 0,inlineSessionPatchProcessing:Jr,claimPending:cn,claimRequiresIdentity:Lr,claimBuyerIdentity:Hn,waitForDataAttachment:Kn}),[$,$t,Te,Or,ar,wn,$n,Jr,cn,Lr,Hn,Kn]),Ar=!!r&&se==="buttons"&&!Xn&&!fn&&(!Ye||!yn),Jt=vn?(0,x.jsx)(nn,{status:vn,errorMessage:Pr,authorized:gt}):null;if($t&&!fn){if(p)return(0,x.jsxs)(x.Fragment,{children:[p,Jt]});if(se==="buttons"){let A=Rt?.buttonsLayout?.cardButton?.borderRadius??Rt?.appearance.variables?.borderRadius??8,D=ne=>(0,x.jsx)("div",{style:{height:ne,borderRadius:A,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[T&&D(qo),y&&(v||ke)&&D(qo),y&&D(qo),(0,x.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Jt]})}return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,x.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,x.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Jt]})}return Te?m?(0,x.jsx)(zn.Provider,{value:dt,children:m(Te)}):(0,x.jsx)(zn.Provider,{value:dt,children:(0,x.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Te.message})}):Ar?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(zn.Provider,{value:dt,children:(0,x.jsx)(dp,{onButtonClick:Re,paymentMethodLayout:Se,showPayPal:T,showStripe:y,showApplePay:v,showGooglePay:ke,theme:ye,buttonsTheme:vt,buttonsStyles:ut,cardButtonContent:z,cardBackButtonContent:We,cardTitleContent:$e})}),Jt]}):Xn&&$&&qt?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(zn.Provider,{value:dt,children:(0,x.jsxs)("div",{className:fe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Er&&(0,x.jsx)(ma,{icon:!1,children:Er}),Tr==="retrying"&&(0,x.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Tr==="exhausted"&&(0,x.jsxs)("div",{role:"alert",children:[(0,x.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,x.jsx)("button",{type:"button",onClick:Io,children:"Retry PayPal"})]}),Tr!=="exhausted"&&(0,x.jsx)("div",{"aria-hidden":Tr==="retrying"?!0:void 0,style:Tr==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,x.jsx)(fc,{sessionId:Ae,nonce:$.clientSecret||void 0,billingApiUrl:Y,email:$.customer?.email||ar?.account?.email,billingName:[$.customer?.firstName,$.customer?.lastName].filter(Boolean).join(" ")||[ar?.account?.firstName,ar?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Hn,clientId:qt.clientId,environment:qt.environment,currency:($.currency??"usd").toUpperCase(),isSubscription:$.mode==="subscription",providerObjectType:qt.providerObjectType,approvalPresentation:qt.approvalPresentation,existingOrderId:qt.existingOrderId,onComplete:b,onErrorChange:_r,onDecline:_,onCancel:V,onButtonClick:Re,runBeforeButtonClick:lo,onInitializationStateChange:Vo,allowAutomaticRetry:Qr===0,session:$,telemetry:a,telemetryContext:Qe,onInstrument:H,debug:M},`${h}:paypal-init-${Qr}`)})]})}),Jt]}):Or==="confirm"?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(zn.Provider,{value:dt,children:(0,x.jsx)(La,{flopay:Ye,paypalFlopay:de,options:yn??{billingApiUrl:Y},onInstrument:H,children:(0,x.jsxs)("div",{className:fe,children:[Er&&(0,x.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Er}),nt?nt({onConfirm:Yn,isProcessing:co}):(0,x.jsx)("button",{type:"button",onClick:Yn,disabled:co,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:co?"not-allowed":"pointer",opacity:co?.6:1},children:Vr?"Processing...":De??"Confirm Purchase"})]})},h)}),Jt]}):(!Ye||!yn)&&!(fn&&Or==="full")?(0,x.jsx)(x.Fragment,{children:Jt}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(zn.Provider,{value:dt,children:(0,x.jsxs)(La,{flopay:Ye,paypalFlopay:de,options:yn??{billingApiUrl:Y},onInstrument:H,children:[Ur===1&&(0,x.jsx)("button",{type:"button",onClick:Wo,children:"Retry payment methods"}),ce?(0,x.jsxs)(x.Fragment,{children:[Er&&(0,x.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Er}),(0,x.jsx)(cp,{sessionId:Ae,nonce:$?.clientSecret||void 0,billingApiUrl:Y,session:$,submitLabel:pt,walletPresentation:K,paymentMethodLayout:Se,moreOptionsLabel:Ie,children:ce})]}):(0,x.jsx)(Vi,{sessionId:Ae,nonce:$?.clientSecret||void 0,telemetry:a,email:$?.customer?.email||ar?.account?.email,userId:$?.customer?.id||ar?.account?.userId,firstName:$?.customer?.firstName||ar?.account?.firstName,lastName:$?.customer?.lastName||ar?.account?.lastName,totalAmount:$?Math.round((0,me.buildCheckoutDisplayData)($).total*100):0,currency:$?.currency?.toLowerCase()??"usd",onComplete:b,onError:P,onDecline:_,onCancel:V,error:Er,onErrorChange:_r,showPayPal:T,showStripe:y,walletPresentation:K,enabledPaymentMethods:Ur?[]:Z??he?.data.stripe?.enabledPaymentMethods??$?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:he?.data.stripe?.enabledPaymentMethodCountries,showApplePay:v,showGooglePay:ke,layout:se,paymentMethodLayout:Se,moreOptionsLabel:Ie,theme:ye,buttonsTheme:vt,buttonsStyles:ut,appearance:Ht,cardButtonContent:z,cardBackButtonContent:We,cardTitleContent:$e,onButtonClick:Re,onBeforeButtonClick:X,onBuyerIdentityReady:Hn,enableAVS:G,...tt?{cardFieldOrder:tt}:{},...Ee===void 0?{}:{cardAutoFocus:Ee},...qe?{onCardFieldsReady:qe}:{},...re?{onCardFieldsFailed:re}:{},...q===void 0?{}:{cardFieldsTimeoutMs:q},...we?{cardPreFormSlot:we}:{},avsLayout:Q,country:$?.customer?.country,city:$?.customer?.city,state:$?.customer?.state,onCountryChange:W,onZipChange:k,avsCheck:!!G,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Zs(ce,se),className:fe,submitLabel:pt,directPaypal:qt,isSubscription:$?.mode==="subscription",session:$,dataAttachmentPending:cn,dataAttachmentRequiresIdentity:Lr,debug:M})]},h)}),Jt]})}function cp({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,paymentMethodLayout:d,moreOptionsLabel:p,children:m}){return(0,x.jsx)(x.Fragment,{children:R.default.Children.map(m,b=>{if(!R.default.isValidElement(b))return b;let P=b.props,g={};return P.sessionId||(g.sessionId=e),!P.nonce&&t&&(g.nonce=t),P.billingApiUrl||(g.billingApiUrl=r),P.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),P.walletPresentation===void 0&&(g.walletPresentation=s),P.paymentMethodLayout===void 0&&d!==void 0&&(g.paymentMethodLayout=d),P.moreOptionsLabel===void 0&&p!==void 0&&(g.moreOptionsLabel=p),n?.customer&&(P.email||(g.email=n.customer.email),P.userId||(g.userId=n.customer.id),P.firstName||(g.firstName=n.customer.firstName),P.lastName||(g.lastName=n.customer.lastName)),Object.keys(g).length===0?b:R.default.cloneElement(b,g)})})}function dp({onButtonClick:e,paymentMethodLayout:t,showPayPal:r,showStripe:n=!0,showApplePay:a,showGooglePay:s,theme:d,buttonsTheme:p,buttonsStyles:m,cardButtonContent:b,cardBackButtonContent:P,cardTitleContent:g}){let[_,V]=(0,R.useState)(!1),W=(0,R.useMemo)(()=>(0,me.resolveTheme)(d),[d]),k=(0,R.useMemo)(()=>{let v=W?.buttonsLayout??(0,me.resolveButtonsLayoutTheme)(p);return m?{...v,...m,cardButton:{...v.cardButton,...m.cardButton},cardFormContainer:{...v.cardFormContainer,...m.cardFormContainer},backButton:{...v.backButton,...m.backButton},backButtonIcon:{...v.backButtonIcon,...m.backButtonIcon},submitButton:{...v.submitButton,...m.submitButton},title:{...v.title,...m.title}}:v},[W,p,m]),T=W?.buttonsLayout?.cardButton?.borderRadius??W?.appearance.variables?.borderRadius??8,y=v=>(0,x.jsx)("div",{style:{height:v,borderRadius:T,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),K=b===void 0?{boxSizing:"border-box",height:qo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let v=k.cardInputBorder??"#e5e7eb",ke=k.cardInputBackground??"white",M=na(P),se=na(g);return(0,x.jsxs)("div",{style:{backgroundColor:k.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...k.cardFormContainer},children:[(0,x.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,x.jsxs)("button",{type:"button",onClick:()=>V(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:M?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...k.backButton},children:[(0,x.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...k.backButtonIcon},children:(0,x.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,x.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,x.jsx)(aa,{content:P})]}),se?(0,x.jsx)("div",{style:{flex:1}}):(0,x.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...k.title},children:(0,x.jsx)(Ta,{content:g})})]}),(0,x.jsx)("div",{style:{backgroundColor:ke,border:`1px solid ${v}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,x.jsxs)("div",{style:{display:"flex"},children:[(0,x.jsx)("div",{style:{flex:1,backgroundColor:ke,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,x.jsx)("div",{style:{flex:1,backgroundColor:ke,borderTop:"none",borderRight:`1px solid ${v}`,borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,x.jsx)("div",{style:{backgroundColor:ke,border:`1px solid ${v}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,x.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...k.submitButton,opacity:.5}}),(0,x.jsx)("style",{children:`
|
|
41
41
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
42
42
|
@keyframes flopay-interim-expand {
|
|
43
43
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
44
44
|
40% { opacity: 1; }
|
|
45
45
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
46
46
|
}
|
|
47
|
-
`})]})}let Z={paypal:r&&y(qo),wallets:n&&(a||s)&&y(qo),card:n&&(t?y(qo):(0,x.jsx)("button",{type:"button",onClick:()=>{e?.("card"),j(!0)},style:{width:"100%",...K,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:k.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...k.cardButton},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.985)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:(0,x.jsx)(oa,{content:b})}))};return(0,x.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[me.DEFAULT_PAYMENT_METHOD_ORDER.map(v=>(0,x.jsx)(R.default.Fragment,{children:Z[v]},v)),(0,x.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Tn=require("react/jsx-runtime"),dp=44;function td(e){return new Promise(t=>setTimeout(t,e))}var rd=15e3;function tl(e,t){return new wr.FloPayError(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function up(e,t){return new Promise((r,n)=>{let a=()=>n(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(s=>{t.removeEventListener("abort",a),r(s)},s=>{t.removeEventListener("abort",a),n(s)})})}function pp(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function mp(e,t){return e instanceof wr.FloPayError?e:new wr.FloPayError(e instanceof Error?e.message:t,"api_error")}function yp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function fp(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 nd({sessionId:e,nonce:t,createSession:r,getSession:n,paymentMethodId:a,checkoutMethod:s,clientId:d,products:p,items:m,subscriptions:b,account:P,successUrl:f,cancelUrl:_,couponCodes:j,tagsData:W,utmMetadata:k,billingApiUrl:T,locale:y,theme:K,appearance:Z,buttonsTheme:v,buttonsStyles:ke,onSuccess:M,onError:se,onDecline:be,children:Ie,disabled:ye=!1,type:vt="button",style:ut,...q}){let We=(0,lt.useMemo)(()=>(0,wr.resolveBillingApiUrl)(T),[T]),$e=(0,lt.useMemo)(()=>fp({createSession:r,clientId:d,products:p,items:m,subscriptions:b,account:P,successUrl:f,cancelUrl:_,couponCodes:j,tagsData:W,utmMetadata:k}),[P,_,d,j,r,p,m,b,f,W,k]),[Be,we]=(0,lt.useState)(!1),[X,G]=(0,lt.useState)(null),[tt,Ee]=(0,lt.useState)(null),[qe,te]=(0,lt.useState)(!1),[V,Se]=(0,lt.useState)(null),[Q,pt]=(0,lt.useState)(null),fe=(0,lt.useRef)(!0),Pe=(0,lt.useRef)(null),Oe=(0,lt.useRef)(null),ce=(0,lt.useRef)(!1),Ve=(0,lt.useRef)(Q),De=(0,lt.useRef)(M),nt=(0,lt.useRef)(se),ct=(0,lt.useRef)(be),Y=(0,lt.useCallback)(g=>_i(Pe,async J=>{try{return await g(J)}catch(He){throw J.aborted?ya(He):He}}),[]);(0,lt.useEffect)(()=>{Ve.current=Q},[Q]),(0,lt.useEffect)(()=>{De.current=M},[M]),(0,lt.useEffect)(()=>{nt.current=se},[se]),(0,lt.useEffect)(()=>{ct.current=be},[be]),(0,lt.useEffect)(()=>(fe.current=!0,()=>{fe.current=!1,Pe.current?.abort(),Oe.current?.abort()}),[]),(0,lt.useEffect)(()=>{if(typeof window>"u")return;let g=J=>{J.key==="Escape"&&pt(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let Rt=(0,lt.useCallback)((g,J=za)=>{ct.current?.(Cr(J,g,{code:g.code,declineCode:g.declineCode}))},[]),Ht=(0,lt.useCallback)(async g=>{fe.current&&(Ee(null),te(g.result.status==="authorized"),G("success"),await td(600),fe.current&&(0,Ge.invokeMerchantCallback)(()=>De.current?.(g)))},[]),Mt=(0,lt.useCallback)(async(g,J)=>{if(!fe.current)return;!!J?.emitDecline&&(0,wr.isDeclineCallbackFailure)(g)?Rt(g,J?.method):nt.current?.(g),Ee(g.message),te(!1),G("error"),await td(400)},[Rt]),Lt=(0,lt.useCallback)(async(g,J,He)=>{let L=g.data.session??null;if(!L)throw Ro(new wr.FloPayError("No session data returned","api_error"),J);let mt=He?.nonce||L.clientSecret||t;if(mo(L)){await Ht({result:po(L,J),session:L,sessionId:L.id||J,autoCompleted:!1});return}if(L.status==="expired")throw Ro(fi(L),L.id||J);try{if(g.autoProcessingPending){let S=g.autoProcessingPending,I=new Gi.PaymentAPI(We),H=await Y(Ae=>I.waitForCheckoutSessionCompletion(S.sessionId,{initialDelayMs:S.retryAfterMs,nonce:mt,statusUrl:S.statusUrl,signal:Ae})),F=ko(H,L),B=H.autoProcessingError?.type==="3ds_required"&&!(0,wr.isMerchantAuthRequired)(H.autoProcessingError)&&H.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:H.autoProcessingError.nextActionRedirectUrl}:null;if(B&&J&&mt){let Ae=qa(We,J,L),Vr=await Y($t=>fa(B,{billingApiUrl:We,sessionId:J,nonce:mt,session:L,signal:$t,telemetry:!0,...Ae.telemetry?{challengeTelemetry:Ae.telemetry}:{}})).finally(Ae.release);await Ht({result:Vr,session:L,sessionId:L.id||J,autoCompleted:!1});return}if(H.autoProcessingError)throw ro(H.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:H.autoProcessingError.checkoutMethod});if(!mo(F))throw sa(F);await Ht({result:po(F,J),session:F,sessionId:F.id||J,autoCompleted:!1});return}if(g.autoProcessingError){let S=g.autoProcessingError.nextActionRedirectUrl;if(g.autoProcessingError.type==="3ds_required"&&!(0,wr.isMerchantAuthRequired)(g.autoProcessingError)&&S&&J&&mt){let I=await Y(Ae=>wc({billingApiUrl:We,sessionId:J,nonce:mt,nextActionRedirectUrl:S,signal:Ae}));if(I.status==="declined")throw ro({type:I.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:I.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let F=await new Gi.PaymentAPI(We).waitForCheckoutSessionCompletion(J,{initialDelayMs:0,nonce:mt}),B=ko(F,L);if(!mo(B))throw ro({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await Ht({result:po(B,J),session:B,sessionId:B.id||J,autoCompleted:!1});return}throw ro(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(He?.fromCreateSession&&g.autoProcessingAttempted===!0)throw ro({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let u=await ga({billingApiUrl:We,sessionId:J??L.id,session:L,nonce:mt});if(u.type==="next_action_required"&&mt){let S=J??L.id,I=qa(We,S,L),H=await Y(F=>fa(u,{billingApiUrl:We,sessionId:S,nonce:mt,session:L,signal:F,telemetry:!0,...I.telemetry?{challengeTelemetry:I.telemetry}:{}})).finally(I.release);await Ht({result:H,session:L,sessionId:L.id||S,autoCompleted:!1});return}if(u.type!=="success")throw ro({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ht({result:u.result,session:L,sessionId:L.id||J,autoCompleted:!1})}catch(u){let S=L.id||J,I=Ro(Va(u),S);if(I.code==="three_ds_aborted")return;if(I.code==="checkout_processing_timeout"){if(!fe.current)return;Se(I.message),(0,Ge.invokeMerchantCallback)(()=>nt.current?.(I));return}await Mt(I,{emitDecline:!0,method:I.checkoutMethod??za}),yp(I,S)&&S&&fe.current&&pt({sessionId:S,errorMessage:I.message,nonce:mt||void 0,payPalOrderId:I.orderId})}},[t,We,Y,Mt,Ht]),he=(0,lt.useCallback)(async g=>{let J=new AbortController;Oe.current=J;let He=!1,L=setTimeout(()=>{He=!0,J.abort()},rd);try{let mt=await up((async()=>g({signal:J.signal}))(),J.signal);if(!fe.current)return null;if(!pp(mt))throw tl("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:mt.sessionId,nonce:mt.nonce}}catch(mt){if(!fe.current)return null;throw mt instanceof wr.FloPayError&&mt.code==="session_fetch_failed"?mt:He?tl(`getSession did not resolve within ${rd/1e3} seconds.`):tl("Could not fetch the one-click session.",mt)}finally{clearTimeout(L),Oe.current===J&&(Oe.current=null)}},[]),Me=(0,lt.useCallback)(async g=>{if(q.onClick?.(g),g.defaultPrevented||ye||Be||(pt(null),Se(null),ce.current))return;let J=[e,n,$e].filter(Boolean).length;if(J>1){let He=new wr.FloPayError("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await Mt(He),fe.current&&(G(null),Ee(null));return}if(J===0){let He=new wr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Mt(He),fe.current&&(G(null),Ee(null));return}ce.current=!0,we(!0),Ee(null),te(!1),G("processing");try{let He=new Gi.PaymentAPI(We);if(e){let L=await He.getUnifiedCheckoutSession(e,t);await Lt(L,e);return}if(n){let L=await he(n);if(!L)return;let mt=await He.getUnifiedCheckoutSession(L.sessionId,L.nonce);await Lt(mt,L.sessionId,{nonce:L.nonce});return}Pc();try{let L=await He.createAndFetchSession({...$e});await Lt(L,L.data.session?.id??null,{fromCreateSession:!0})}catch(L){if(gi(L)==="session_auto_completed"){await Ht({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw L}}catch(He){await Mt(Ro(mp(He,"Automatic payment failed. Please try again."),e))}finally{ce.current=!1,fe.current&&(G(null),Ee(null),we(!1))}},[q.onClick,$e,ye,he,n,Be,t,Lt,We,e,Mt,Ht]),Ye=(0,lt.useCallback)(g=>{let J=Ve.current;pt(null),De.current?.({result:g,session:null,sessionId:J?.sessionId??null,autoCompleted:!1})},[]),Pt=(0,lt.useCallback)(g=>{nt.current?.(g)},[]),ft=(0,lt.useCallback)(g=>{ct.current?.(g)},[]),ze=(0,lt.useMemo)(()=>(0,wr.resolveTheme)(K),[K]),Nt=(0,lt.useMemo)(()=>{let g=ze?.buttonsLayout??(0,wr.resolveButtonsLayoutTheme)(v);return ke?{...g,...ke,cardButton:{...g.cardButton,...ke.cardButton}}:g},[ze,v,ke]),de=(0,lt.useMemo)(()=>{let g=ze?.appearance;return Z?g?{...g,...Z,variables:{...g.variables,...Z.variables}}:Z:g},[Z,ze]),kt=de?.variables,At=kt?.colorPrimary??"#4A49FF",$=kt?.colorPrimaryHover??(0,Ks.darkenHex)(At,.12),ge=kt?.borderRadius??"8px";return(0,Tn.jsxs)(Tn.Fragment,{children:[(0,Tn.jsx)("button",{...q,type:vt,onClick:Me,disabled:ye||Be,"aria-busy":Be,style:{width:"100%",...Ie===void 0?{boxSizing:"border-box",height:dp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Nt.cardButton,...Hs({themeBundle:ze,resolvedPrimaryColor:At,resolvedBorderRadius:ge,submitButtonStyle:Nt.submitButton,explicitPrimaryColor:kt?.colorPrimary}),fontSize:Nt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ye||Be?"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:ye||Be?.6:1,...ut},onMouseEnter:g=>{q.onMouseEnter?.(g),!g.defaultPrevented&&!ye&&!Be&&(ze||kt?.colorPrimary)&&(g.currentTarget.style.backgroundColor=$)},onMouseLeave:g=>{q.onMouseLeave?.(g),!g.defaultPrevented&&(ze||kt?.colorPrimary)&&(g.currentTarget.style.backgroundColor=At)},onMouseDown:g=>{q.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{q.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:(0,Tn.jsx)(oa,{content:Ie})}),V&&(0,Tn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:V}),X&&(0,Tn.jsx)(nn,{status:X,errorMessage:tt,authorized:qe}),Q&&(0,Tn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&pt(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,Tn.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,Tn.jsx)(Ki,{sessionId:Q.sessionId,nonce:Q.nonce,checkoutMode:"full",billingApiUrl:We,locale:y,theme:K,...de?{appearance:de}:{},buttonsTheme:v,buttonsStyles:ke,initialErrorMessage:Q.errorMessage,initialPayPalOrderId:Q.payPalOrderId,cardTitleContent:null,onComplete:Ye,onError:Pt,onDecline:ft})})})]})}var Xi=require("@flopay/js/card-setup"),Gr=require("@flopay/shared"),Yt=require("react");var rl=require("@flopay/shared"),gp=require("@flopay/shared");function Yi(e){let t=(0,rl.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var oo=require("react/jsx-runtime"),Qa=class extends Gr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function vo(e,t={}){let r=e instanceof Gr.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 Qa(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 od({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:d,buttonsStyles:p,loading:m=null,onReady:b,onComplete:P,onDecline:f,onCancel:_,onValidation:j,onError:W}){let[k,T]=(0,Yt.useState)(null),[y,K]=(0,Yt.useState)(null),[Z,v]=(0,Yt.useState)(null),[ke,M]=(0,Yt.useState)(null),[se,be]=(0,Yt.useState)(null),Ie=(0,Yt.useRef)(!1),ye=(0,Yt.useRef)(!1),{vaultTheme:vt,surface:ut,overlayTheme:q}=(0,Yt.useMemo)(()=>Yi({theme:a,appearance:d,buttonsStyles:p}),[a,d,p]),We=(0,Yt.useMemo)(()=>(0,Ha.mergeCardSetupSurface)(ut,s),[ut,s]),$e=(0,Yt.useRef)(b),Be=(0,Yt.useRef)(W),we=(0,Yt.useRef)(P),X=(0,Yt.useRef)(f),G=(0,Yt.useRef)(_),tt=(0,Yt.useRef)(j),Ee=(0,Yt.useRef)(!1),qe=(0,Yt.useRef)(!1),te=(0,Yt.useRef)(0);return $e.current=b,Be.current=W,we.current=P,X.current=f,G.current=_,tt.current=j,(0,Yt.useEffect)(()=>{let V=te.current+1;return te.current=V,()=>{queueMicrotask(()=>{te.current===V&&(Ee.current||qe.current||(qe.current=!0,(0,Ge.invokeMerchantCallback)(()=>{G.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Yt.useEffect)(()=>{let V=!0,Se=(0,Gr.resolveBillingApiUrl)(r),Q=new Xi.PaymentAPI(Se,{telemetry:n});return T(null),K(null),v(null),Ee.current=!1,qe.current=!1,(async()=>{try{if(!e.trim())throw new Gr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Gr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let pt=await Q.getUnifiedCheckoutSession(e,t);if(!V)return;let fe=pt.data.session;if(!fe||!(0,Gr.isCardSetupCheckoutSession)(fe))throw new Gr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Pe=fe.vault;(0,Gr.isMountableVaultBlock)(Pe)||(Pe=await Q.getVaultCapture(e,t));let Oe=(0,Gr.resolveVaultMountOptions)(Pe,{billingApiUrl:Se,sessionId:e,nonce:t});if(!Oe)throw new Gr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!V)return;K(Oe),T(new Xi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(pt){if(!V)return;let fe=vo(pt);Ee.current=!0,v(fe),(0,Ge.invokeMerchantCallback)(()=>Be.current?.(fe))}})(),()=>{V=!1,Q.destroy()}},[r,t,e,n]),(0,Yt.useEffect)(()=>{if(!k)return;let V=!1;ye.current=!1,Ie.current=!1;let Se=k.on("submitting",()=>{Ie.current=!0,be(null),M("processing")}),Q=k.on("complete",Pe=>{Ee.current=!0,Ie.current=!1,M("success"),(async()=>(await new Promise(Oe=>setTimeout(Oe,600)),!ye.current&&(ye.current=!0,(0,Ge.invokeMerchantCallback)(()=>{we.current?.({status:"succeeded",sessionId:e,...Pe.paymentMethod?{paymentMethod:Pe.paymentMethod}:{}})}),V||M(null))))()}),pt=k.on("decline",Pe=>{Ee.current=!0,Ie.current=!1,be(Pe.message??null),M("error"),(0,Ge.invokeMerchantCallback)(()=>{X.current?.({status:"declined",sessionId:e,...Pe.declineReason?{reason:Pe.declineReason}:{},...Pe.message?{message:Pe.message}:{}})}),(async()=>(await new Promise(Oe=>setTimeout(Oe,400)),V||M(null)))()}),fe=k.on("challenge_dismissed",()=>{M(null)});return()=>{V=!0,Se(),Q(),pt(),fe()}},[k,e]),Z?(0,oo.jsx)("div",{role:"alert",children:Z.message}):!k||!y?.html?(0,oo.jsx)(oo.Fragment,{children:m}):(0,oo.jsxs)(oo.Fragment,{children:[ke&&(0,oo.jsx)(nn,{status:ke,errorMessage:se,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...q?{theme:q}:{}}),(0,oo.jsx)(_o,{capture:k,html:y.html,messageToken:y.messageToken,expectedOrigin:y.expectedOrigin,verificationRequired:y.verificationRequired,theme:vt,containerStyle:We,onReady:()=>{(0,Ge.invokeMerchantCallback)(()=>$e.current?.())},onValidation:V=>{(0,Ge.invokeMerchantCallback)(()=>tt.current?.(V))},onError:V=>{if(!V)return;Ie.current&&(Ie.current=!1,be(V),M("error"),setTimeout(()=>M(null),400));let Se=vo(new Error(V),{code:"card_setup_widget_failed",retryable:!0});(0,Ge.invokeMerchantCallback)(()=>Be.current?.(Se))}})]})}var ad=require("@flopay/js/card-setup"),Mn=require("@flopay/shared"),id=require("@paypal/paypal-js"),Vo=require("react");var ld=require("react/jsx-runtime");function sd({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:d,customer:{userId:p,email:m},onSubmitting:b,onConfirmed:P,onFailed:f,onAbandoned:_}){let j=(0,Vo.useRef)(null),W=(0,Vo.useRef)({onSubmitting:b,onConfirmed:P,onFailed:f,onAbandoned:_});W.current={onSubmitting:b,onConfirmed:P,onFailed:f,onAbandoned:_};let[k]=(0,Vo.useState)(()=>(0,eo.detectPayPalEnvironment)().inAppBrowser);return(0,Vo.useEffect)(()=>{let T=!0,y,K=new ad.PaymentAPI(s,{telemetry:d}),Z={userId:p,email:m};return(async()=>{try{let v=await(0,id.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),ke=j.current;if(!T||!ke)return;if(!v?.Buttons)throw new Mn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let M=v.Buttons({createVaultSetupToken:async()=>{W.current.onSubmitting();let se=await K.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Mn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,Mn.isSettledSessionIntent)(se))throw(0,Mn.settledSessionIntentError)(n);if(se.provider!=="paypal"||se.providerObjectType!=="setup_token")throw new Mn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return se.providerObjectId},onApprove:async se=>{let be=se.vaultSetupToken;if(!be)throw new Mn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let Ie=await K.processPayment(Z.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:be,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Mn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:Z});if(!Ie.ok)throw new Mn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:Ie.status});T&&W.current.onConfirmed()},onCancel:()=>{T&&W.current.onAbandoned()},onError:se=>{if(!T)return;let{popupBlocked:be}=(0,_e.classifyExternalMethodFailure)(se,{inAppBrowser:k,handoffObserved:!1});W.current.onFailed(be?new Error((0,_e.buildExternalMethodRecoveryMessage)("PayPal",!0,k)):se,{code:be?"popup_blocked":"paypal_setup_failed",retryable:!0})}});y=()=>M.close(),await M.render(ke)}catch(v){if(!T)return;W.current.onFailed(v,{code:"paypal_unavailable",retryable:!0})}})(),()=>{T=!1,y?.().catch(()=>{}),K.destroy()}},[s,e,r,m,t,k,a,n,d,p]),(0,ld.jsx)("div",{ref:j,"data-flopay-paypal-setup":""})}var dd=require("@flopay/js/card-setup"),An=require("@flopay/shared"),ao=require("@stripe/react-stripe-js"),ud=require("@stripe/stripe-js"),Yr=require("react");var qr=require("react/jsx-runtime"),pd={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"}},nl=new Map;function hp(e){let t=nl.get(e);if(t)return t;let r=(0,ud.loadStripe)(e).catch(n=>{throw nl.delete(e),n});return nl.set(e,r),r}function Pp(e){return e?(0,An.toStripeAppearance)(e):void 0}function vp(e){return(0,_e.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function cd(e){return e==="paypal"?"PayPal":(0,An.getStripeMethodDisplayName)(e)}function Cp(){return typeof window>"u"?"":window.location.href}var bp={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function md(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:d}=e,[p]=(0,Yr.useState)(()=>hp(t)),m=(0,Yr.useMemo)(()=>{let b=Pp(d),P=(0,An.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:pd[r]?.types??[r],...P?{setupFutureUsage:P}:{},...b?{appearance:b}:{}}},[d,n,a,s,r]);return(0,qr.jsx)(ao.Elements,{stripe:p,options:m,children:(0,qr.jsx)(Sp,{...e})})}function Sp({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:d,themeId:p,buttonsLayout:m,onSubmitting:b,onConfirmed:P,onDeclined:f,onFailed:_,onValidation:j,onUnavailable:W}){let k=(0,ao.useStripe)(),T=(0,ao.useElements)(),[y,K]=(0,Yr.useState)(!1),[Z,v]=(0,Yr.useState)("loading"),[ke,M]=(0,Yr.useState)(!1),[se,be]=(0,Yr.useState)(!1),Ie=(0,Yr.useRef)(!1),[ye]=(0,Yr.useState)(()=>(0,eo.detectPayPalEnvironment)()),[vt,ut]=(0,Yr.useState)(!1),q=(0,Yr.useCallback)((G,tt)=>{if((0,_e.classifyExternalMethodFailure)(G,{inAppBrowser:ye.inAppBrowser,handoffObserved:!1}).popupBlocked){ut(!0),_(new Error((0,_e.buildExternalMethodRecoveryMessage)(cd(e),!0,ye.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}_(tt.message===void 0?G:new Error(tt.message),{code:tt.code,retryable:!0})},[ye.inAppBrowser,e,_]),We=(0,Yr.useCallback)(async G=>{let tt=!1,Ee=!1,qe=()=>{!G||tt||Ee||(Ee=!0,G.paymentFailed({reason:"fail"}))};if(!k||!T||Ie.current){qe();return}Ie.current=!0,K(!0);try{let te=await T.submit();if(te.error){qe(),j(te.error.message??null);return}b();let V=await new dd.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,An.isSettledSessionIntent)(V))throw(0,An.settledSessionIntentError)(r);if(V.provider!=="stripe"||V.intentKind!=="setup")throw new An.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});tt=!0;let Se=await k.confirmSetup({elements:T,clientSecret:V.clientSecret,confirmParams:{return_url:Cp()},redirect:"if_required"});if(Se.error){vp(Se.error)?f({...Se.error.decline_code||Se.error.code?{reason:Se.error.decline_code??Se.error.code}:{},...Se.error.message?{message:Se.error.message}:{}}):q(Se.error,{code:"payment_method_setup_provider_failed",message:Se.error.message??"The payment method could not be saved."});return}P()}catch(te){qe(),q(te,{code:"payment_method_setup_failed"})}finally{Ie.current=!1,K(!1)}},[a,t,T,e,n,P,f,b,j,q,r,k,s]),$e=pd[e]?.wallet,Be=$e==="paypal"&&(0,to.resolveStripePayPalPresentation)(ye,"auto",vt?"blocked":ye.popupCapability)==="redirect",we=d?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&$e&&!Be)return(0,qr.jsxs)(qr.Fragment,{children:[(0,qr.jsx)(ha,{}),(0,qr.jsx)(Wa,{state:Z,borderRadius:we,children:(0,qr.jsx)(ao.ExpressCheckoutElement,{options:{...Fi,paymentMethods:xi([e])},onReady:G=>{let tt=ja(G,[$e]);v(tt),tt==="unavailable"&&W()},onLoadError:()=>{v("load_error"),W()},onConfirm:G=>{We(G)}})})]});let X=cd(e);return(0,qr.jsxs)(qr.Fragment,{children:[ke?(0,qr.jsx)(Ai,{method:e,themeId:p,hasNextStep:!0,highlighted:se,disabled:y,onClick:()=>be(G=>!G),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:we}):null,(0,qr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!se,style:se?{display:"flex",flexDirection:"column"}:bp,children:[(0,qr.jsx)(ao.PaymentElement,{options:{layout:Bi},onReady:()=>M(!0),onLoadError:()=>W(),onChange:G=>{G.complete&&j(null)}}),(0,qr.jsx)(Oi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!k||!T||y||!se,onClick:()=>{We()},color:d?.variables?.colorPrimary??"#4A49FF",borderRadius:d?.variables?.borderRadius??"8px",style:m?.submitButton,children:y?"Saving\u2026":`Save ${X}`})]})]})}var ei=require("@flopay/js/card-setup"),Rr=require("@flopay/shared"),Je=ws(require("react"),1);var Pa=require("@flopay/js/card-setup"),Br=require("@flopay/shared");var dr=require("react/jsx-runtime"),wp=15,Rp=2e3;function kp(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function ol(e){return new Promise(t=>setTimeout(t,e))}async function Ep(e,t,r){if(!t.trim())throw new Rr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new Rr.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,Rr.isCardSetupCheckoutSession)(a))throw new Rr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Br.readSetupAdvertisement)(n);if(!(0,Br.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 Rr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function _p(e,t,r,n,a){let s=t.vault??null;(0,Rr.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let d=(0,Rr.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!d)throw new Rr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return d}var Ji=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 yd({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:d="modern-light",containerStyle:p,appearance:m,buttonsStyles:b,loading:P=null,onReady:f,onComplete:_,onDecline:j,onCancel:W,onValidation:k,onError:T}){let[y]=(0,Je.useState)(Pa.readSetupRedirectReturn),[K,Z]=(0,Je.useState)(null),[v,ke]=(0,Je.useState)(!1),[M,se]=(0,Je.useState)(null),[be,Ie]=(0,Je.useState)(null),[ye,vt]=(0,Je.useState)(null),[ut,q]=(0,Je.useState)(null),[We,$e]=(0,Je.useState)(()=>new Set),Be=(0,Je.useRef)(We),we=(0,Je.useRef)(null);we.current=K;let X=(0,Je.useRef)(!1),G=(0,Je.useRef)(!1),tt=(0,Je.useRef)(!1),Ee=(0,Je.useRef)(!1),qe=(0,Je.useRef)(0),te=(0,Je.useRef)(0),V=(0,Je.useRef)(!1),{vaultTheme:Se,surface:Q,overlayTheme:pt,appearance:fe,buttonsLayout:Pe}=(0,Je.useMemo)(()=>Yi({theme:d,appearance:m,buttonsStyles:b}),[d,m,b]),Oe=(0,Je.useMemo)(()=>(0,Ha.mergeCardSetupSurface)(Q,p),[Q,p]),ce=(0,Je.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:f,onComplete:_,onDecline:j,onCancel:W,onValidation:k,onError:T});ce.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:f,onComplete:_,onDecline:j,onCancel:W,onValidation:k,onError:T},(0,Je.useEffect)(()=>{V.current=!0;let u=qe.current+1;return qe.current=u,()=>{V.current=!1,te.current+=1,queueMicrotask(()=>{qe.current===u&&(tt.current||Ee.current||(Ee.current=!0,(0,Ge.invokeMerchantCallback)(()=>{ce.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let Ve=(0,Je.useCallback)((u,S)=>{tt.current=!0,X.current=!1,q({status:"success",wording:u,message:null}),(async()=>(await ol(600),!G.current&&(G.current=!0,(0,Ge.invokeMerchantCallback)(()=>{ce.current.onComplete?.({status:"succeeded",sessionId:ce.current.sessionId,...S?{paymentMethod:S}:{}})}),V.current&&q(null))))()},[]),De=(0,Je.useCallback)((u,S)=>{tt.current=!0,X.current=!1,q({status:"error",wording:u,message:S.message??null}),(0,Ge.invokeMerchantCallback)(()=>{ce.current.onDecline?.({status:"declined",sessionId:ce.current.sessionId,...S.reason?{reason:S.reason}:{},...S.message?{message:S.message}:{}})}),(async()=>(await ol(400),V.current&&q(null)))()},[]),nt=(0,Je.useCallback)((u,S)=>{X.current?(X.current=!1,q({status:"error",wording:u,message:S.message}),setTimeout(()=>{V.current&&q(null)},400)):q(null),(0,Ge.invokeMerchantCallback)(()=>ce.current.onError?.(S))},[]),ct=(0,Je.useCallback)(async u=>{let S=te.current+1;te.current=S;let I=()=>!V.current||S!==te.current;X.current=!0,q({status:"processing",wording:"payment_method",message:null});let H=new ei.PaymentAPI((0,Rr.resolveBillingApiUrl)(ce.current.billingApiUrl),{telemetry:ce.current.telemetry});try{for(let F=0;F<wp;F+=1){if((F>0||u.waitFirst)&&await ol(Rp),I())return;let B=await H.getUnifiedCheckoutSession(ce.current.sessionId,ce.current.nonce);if(I())return;let Ae=B.data.session?.status;if(Ae==="complete"){ke(!0),Ve("payment_method");return}if(Ae==="expired")throw new Rr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Rr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(F){if(I())return;let B=F instanceof Rr.FloPayError&&F.code==="payment_method_setup_unverified";nt("payment_method",vo(F,B?{retryable:!0}:{}))}finally{H.destroy()}},[nt,Ve]);(0,Je.useEffect)(()=>{let u=!0,S=(0,Rr.resolveBillingApiUrl)(a),I=new ei.PaymentAPI(S,{telemetry:s});Z(null),ke(!1),se(null),Ie(null),vt(null);let H=new Set;return Be.current=H,$e(H),tt.current=!1,Ee.current=!1,G.current=!1,(async()=>{try{let{session:F,advertisement:B}=await Ep(I,r,n);if(!u)return;let Ae={advertisement:B,customer:kp(F),...F.futureUse?{futureUse:F.futureUse}:{},...F.futureUseUnsupported?{futureUseUnsupported:F.futureUseUnsupported}:{}};if(y){if((0,Pa.clearSetupRedirectParams)(),F.status==="complete"){ke(!0),Z(Ae),Ve("payment_method");return}y.failed?De("payment_method",{reason:"redirect_failed"}):ct({waitFirst:!0})}let Vr=B.card?await _p(I,F,r,n,S):null;if(!u)return;Z(Ae),Vr&&(Ie(Vr),se(new ei.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(F){if(!u)return;let B=vo(F);tt.current=!0,vt(B),(0,Ge.invokeMerchantCallback)(()=>ce.current.onError?.(B))}})(),()=>{u=!1,I.destroy()}},[a,n,y,De,Ve,r,s,ct]),(0,Je.useEffect)(()=>{if(!M)return;X.current=!1;let u=M.on("submitting",()=>{X.current=!0,q({status:"processing",wording:"card",message:null})}),S=M.on("complete",F=>{Ve("card",F.paymentMethod)}),I=M.on("decline",F=>{De("card",{...F.declineReason?{reason:F.declineReason}:{},...F.message?{message:F.message}:{}})}),H=M.on("challenge_dismissed",()=>{q(null)});return()=>{u(),S(),I(),H()}},[M,De,Ve]);let Y=(0,Je.useCallback)((u,S,I)=>{if(I.retryable){nt("payment_method",vo(S,I));return}if(Be.current.has(u))return;let H=new Set(Be.current);H.add(u),Be.current=H,$e(H);let F=we.current?.advertisement,B=F?(0,Br.advertisedMethodKeys)(F).some(Ae=>!H.has(Ae)):!1;nt("payment_method",vo(S,{code:I.code,retryable:B}))},[nt]),Rt=(0,Je.useMemo)(()=>({onSubmitting:()=>{X.current=!0,q({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{ct({waitFirst:!1})},onDeclined:u=>De("payment_method",u),onValidation:u=>{(0,Ge.invokeMerchantCallback)(()=>ce.current.onValidation?.(u))},onAbandoned:()=>{X.current=!1,q(null)}}),[De,ct]),Ht=(0,Je.useRef)(Y);Ht.current=Y;let Mt=(0,Je.useRef)(new Map),Lt=u=>{let S=Mt.current.get(u);if(S)return S;let I=(H,F)=>Ht.current(u,H,F);return Mt.current.set(u,I),I},he=(0,Je.useCallback)(u=>{if(Be.current.has(u))return;let S=new Set(Be.current);S.add(u),Be.current=S,$e(S);let I=we.current?.advertisement;I&&(0,Br.advertisedMethodKeys)(I).some(F=>!S.has(F))||nt("payment_method",vo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[nt]),Me=(0,Je.useRef)(he);Me.current=he;let Ye=(0,Je.useRef)(new Map),Pt=u=>{let S=Ye.current.get(u);if(S)return S;let I=()=>Me.current(u);return Ye.current.set(u,I),I},ft=ut?(0,dr.jsx)(nn,{status:ut.status,errorMessage:ut.message,...(0,Br.setupOverlayLabels)(ut.wording),successNote:null,...pt?{theme:pt}:{}}):null;if(ye)return(0,dr.jsx)("div",{role:"alert",children:ye.message});if(!K||v)return(0,dr.jsxs)(dr.Fragment,{children:[ft,K?null:P]});let{advertisement:ze,customer:Nt,futureUse:de,futureUseUnsupported:kt}=K,At=(0,Rr.resolveBillingApiUrl)(a),$=s===void 0?{}:{telemetry:s},ge=ze.stripe.filter(({method:u})=>!We.has(u)),Ut=We.has("paypal")?null:ze.paypal,g=!!(ze.card&&M&&be?.html),J=({method:u,publishableKey:S,currency:I})=>(0,dr.jsx)("div",{"data-flopay-payment-method":u,style:{display:"contents"},children:(0,dr.jsx)(Ji,{onFailed:Lt(u),children:(0,dr.jsx)(Je.Suspense,{fallback:null,children:(0,dr.jsx)(e,{method:u,category:(0,Br.stripeMethodCategory)(u),publishableKey:S,currency:I,...de?{futureUse:de}:{},...kt?{futureUseUnsupported:kt}:{},sessionId:r,nonce:n,billingApiUrl:At,...$,...fe?{appearance:fe}:{},...Pe?{buttonsLayout:Pe}:{},...typeof d=="string"?{themeId:d}:{},...Rt,onFailed:Lt(u),onUnavailable:Pt(u)})})})},u),He=ge.filter(({method:u})=>(0,Br.stripeMethodCategory)(u)==="wallet"),L=ge.filter(({method:u})=>(0,Br.stripeMethodCategory)(u)!=="wallet"),mt=ge.length>0||Ut!==null;return(0,dr.jsxs)(dr.Fragment,{children:[ft,mt?(0,dr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[He.map(J),Ut?(0,dr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,dr.jsx)(Ji,{onFailed:Lt("paypal"),children:(0,dr.jsx)(Je.Suspense,{fallback:null,children:(0,dr.jsx)(t,{clientId:Ut.clientId,...Ut.environment?{environment:Ut.environment}:{},...ze.currency?{currency:ze.currency}:{},sessionId:r,nonce:n,billingApiUrl:At,customer:Nt,...$,...Rt,onFailed:Lt("paypal"),onUnavailable:Pt("paypal")})})})}):null,L.map(J)]}):null,g&&mt?(0,dr.jsx)(Ka,{label:"or add a card"}):null,g&&M&&be?.html?(0,dr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,dr.jsx)(_o,{capture:M,html:be.html,messageToken:be.messageToken,expectedOrigin:be.expectedOrigin,verificationRequired:be.verificationRequired,theme:Se,containerStyle:Oe,onReady:()=>{(0,Ge.invokeMerchantCallback)(()=>ce.current.onReady?.())},onValidation:u=>{(0,Ge.invokeMerchantCallback)(()=>ce.current.onValidation?.(u))},onError:u=>{u&&nt("card",vo(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var gd=require("react/jsx-runtime"),Ip={StripeSetupMethod:md,PayPalSetupMethod:sd};function fd(e){return(0,gd.jsx)(yd,{...e,branches:Ip})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}let Z={paypal:r&&y(qo),wallets:n&&(a||s)&&y(qo),card:n&&(t?y(qo):(0,x.jsx)("button",{type:"button",onClick:()=>{e?.("card"),V(!0)},style:{width:"100%",...K,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:k.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...k.cardButton},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.985)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:(0,x.jsx)(oa,{content:b})}))};return(0,x.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[me.DEFAULT_PAYMENT_METHOD_ORDER.map(v=>(0,x.jsx)(R.default.Fragment,{children:Z[v]},v)),(0,x.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Tn=require("react/jsx-runtime"),up=44;function td(e){return new Promise(t=>setTimeout(t,e))}var rd=15e3;function tl(e,t){return new wr.FloPayError(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function pp(e,t){return new Promise((r,n)=>{let a=()=>n(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(s=>{t.removeEventListener("abort",a),r(s)},s=>{t.removeEventListener("abort",a),n(s)})})}function mp(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function yp(e,t){return e instanceof wr.FloPayError?e:new wr.FloPayError(e instanceof Error?e.message:t,"api_error")}function fp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function gp(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 nd({sessionId:e,nonce:t,createSession:r,getSession:n,paymentMethodId:a,checkoutMethod:s,clientId:d,products:p,items:m,subscriptions:b,account:P,successUrl:g,cancelUrl:_,couponCodes:V,tagsData:W,utmMetadata:k,billingApiUrl:T,locale:y,theme:K,appearance:Z,buttonsTheme:v,buttonsStyles:ke,onSuccess:M,onError:se,onDecline:Se,children:Ie,disabled:ye=!1,type:vt="button",style:ut,...z}){let We=(0,lt.useMemo)(()=>(0,wr.resolveBillingApiUrl)(T),[T]),$e=(0,lt.useMemo)(()=>gp({createSession:r,clientId:d,products:p,items:m,subscriptions:b,account:P,successUrl:g,cancelUrl:_,couponCodes:V,tagsData:W,utmMetadata:k}),[P,_,d,V,r,p,m,b,g,W,k]),[Be,Re]=(0,lt.useState)(!1),[X,G]=(0,lt.useState)(null),[tt,Ee]=(0,lt.useState)(null),[qe,re]=(0,lt.useState)(!1),[q,we]=(0,lt.useState)(null),[Q,pt]=(0,lt.useState)(null),fe=(0,lt.useRef)(!0),Pe=(0,lt.useRef)(null),Oe=(0,lt.useRef)(null),ce=(0,lt.useRef)(!1),je=(0,lt.useRef)(Q),De=(0,lt.useRef)(M),nt=(0,lt.useRef)(se),ct=(0,lt.useRef)(Se),Y=(0,lt.useCallback)(h=>_i(Pe,async J=>{try{return await h(J)}catch(He){throw J.aborted?ya(He):He}}),[]);(0,lt.useEffect)(()=>{je.current=Q},[Q]),(0,lt.useEffect)(()=>{De.current=M},[M]),(0,lt.useEffect)(()=>{nt.current=se},[se]),(0,lt.useEffect)(()=>{ct.current=Se},[Se]),(0,lt.useEffect)(()=>(fe.current=!0,()=>{fe.current=!1,Pe.current?.abort(),Oe.current?.abort()}),[]),(0,lt.useEffect)(()=>{if(typeof window>"u")return;let h=J=>{J.key==="Escape"&&pt(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let Rt=(0,lt.useCallback)((h,J=za)=>{ct.current?.(Cr(J,h,{code:h.code,declineCode:h.declineCode}))},[]),Ht=(0,lt.useCallback)(async h=>{fe.current&&(Ee(null),re(h.result.status==="authorized"),G("success"),await td(600),fe.current&&(0,Ge.invokeMerchantCallback)(()=>De.current?.(h)))},[]),Mt=(0,lt.useCallback)(async(h,J)=>{if(!fe.current)return;!!J?.emitDecline&&(0,wr.isDeclineCallbackFailure)(h)?Rt(h,J?.method):nt.current?.(h),Ee(h.message),re(!1),G("error"),await td(400)},[Rt]),Lt=(0,lt.useCallback)(async(h,J,He)=>{let L=h.data.session??null;if(!L)throw Ro(new wr.FloPayError("No session data returned","api_error"),J);let mt=He?.nonce||L.clientSecret||t;if(mo(L)){await Ht({result:po(L,J),session:L,sessionId:L.id||J,autoCompleted:!1});return}if(L.status==="expired")throw Ro(fi(L),L.id||J);try{if(h.autoProcessingPending){let S=h.autoProcessingPending,I=new Gi.PaymentAPI(We),H=await Y(Ae=>I.waitForCheckoutSessionCompletion(S.sessionId,{initialDelayMs:S.retryAfterMs,nonce:mt,statusUrl:S.statusUrl,signal:Ae})),F=ko(H,L),B=H.autoProcessingError?.type==="3ds_required"&&!(0,wr.isMerchantAuthRequired)(H.autoProcessingError)&&H.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:H.autoProcessingError.nextActionRedirectUrl}:null;if(B&&J&&mt){let Ae=qa(We,J,L),jr=await Y($t=>fa(B,{billingApiUrl:We,sessionId:J,nonce:mt,session:L,signal:$t,telemetry:!0,...Ae.telemetry?{challengeTelemetry:Ae.telemetry}:{}})).finally(Ae.release);await Ht({result:jr,session:L,sessionId:L.id||J,autoCompleted:!1});return}if(H.autoProcessingError)throw ro(H.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:H.autoProcessingError.checkoutMethod});if(!mo(F))throw sa(F);await Ht({result:po(F,J),session:F,sessionId:F.id||J,autoCompleted:!1});return}if(h.autoProcessingError){let S=h.autoProcessingError.nextActionRedirectUrl;if(h.autoProcessingError.type==="3ds_required"&&!(0,wr.isMerchantAuthRequired)(h.autoProcessingError)&&S&&J&&mt){let I=await Y(Ae=>wc({billingApiUrl:We,sessionId:J,nonce:mt,nextActionRedirectUrl:S,signal:Ae}));if(I.status==="declined")throw ro({type:I.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:I.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let F=await new Gi.PaymentAPI(We).waitForCheckoutSessionCompletion(J,{initialDelayMs:0,nonce:mt}),B=ko(F,L);if(!mo(B))throw ro({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await Ht({result:po(B,J),session:B,sessionId:B.id||J,autoCompleted:!1});return}throw ro(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(He?.fromCreateSession&&h.autoProcessingAttempted===!0)throw ro({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let u=await ga({billingApiUrl:We,sessionId:J??L.id,session:L,nonce:mt});if(u.type==="next_action_required"&&mt){let S=J??L.id,I=qa(We,S,L),H=await Y(F=>fa(u,{billingApiUrl:We,sessionId:S,nonce:mt,session:L,signal:F,telemetry:!0,...I.telemetry?{challengeTelemetry:I.telemetry}:{}})).finally(I.release);await Ht({result:H,session:L,sessionId:L.id||S,autoCompleted:!1});return}if(u.type!=="success")throw ro({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ht({result:u.result,session:L,sessionId:L.id||J,autoCompleted:!1})}catch(u){let S=L.id||J,I=Ro(ja(u),S);if(I.code==="three_ds_aborted")return;if(I.code==="checkout_processing_timeout"){if(!fe.current)return;we(I.message),(0,Ge.invokeMerchantCallback)(()=>nt.current?.(I));return}await Mt(I,{emitDecline:!0,method:I.checkoutMethod??za}),fp(I,S)&&S&&fe.current&&pt({sessionId:S,errorMessage:I.message,nonce:mt||void 0,payPalOrderId:I.orderId})}},[t,We,Y,Mt,Ht]),he=(0,lt.useCallback)(async h=>{let J=new AbortController;Oe.current=J;let He=!1,L=setTimeout(()=>{He=!0,J.abort()},rd);try{let mt=await pp((async()=>h({signal:J.signal}))(),J.signal);if(!fe.current)return null;if(!mp(mt))throw tl("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:mt.sessionId,nonce:mt.nonce}}catch(mt){if(!fe.current)return null;throw mt instanceof wr.FloPayError&&mt.code==="session_fetch_failed"?mt:He?tl(`getSession did not resolve within ${rd/1e3} seconds.`):tl("Could not fetch the one-click session.",mt)}finally{clearTimeout(L),Oe.current===J&&(Oe.current=null)}},[]),Me=(0,lt.useCallback)(async h=>{if(z.onClick?.(h),h.defaultPrevented||ye||Be||(pt(null),we(null),ce.current))return;let J=[e,n,$e].filter(Boolean).length;if(J>1){let He=new wr.FloPayError("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await Mt(He),fe.current&&(G(null),Ee(null));return}if(J===0){let He=new wr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Mt(He),fe.current&&(G(null),Ee(null));return}ce.current=!0,Re(!0),Ee(null),re(!1),G("processing");try{let He=new Gi.PaymentAPI(We);if(e){let L=await He.getUnifiedCheckoutSession(e,t);await Lt(L,e);return}if(n){let L=await he(n);if(!L)return;let mt=await He.getUnifiedCheckoutSession(L.sessionId,L.nonce);await Lt(mt,L.sessionId,{nonce:L.nonce});return}Pc();try{let L=await He.createAndFetchSession({...$e});await Lt(L,L.data.session?.id??null,{fromCreateSession:!0})}catch(L){if(gi(L)==="session_auto_completed"){await Ht({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw L}}catch(He){await Mt(Ro(yp(He,"Automatic payment failed. Please try again."),e))}finally{ce.current=!1,fe.current&&(G(null),Ee(null),Re(!1))}},[z.onClick,$e,ye,he,n,Be,t,Lt,We,e,Mt,Ht]),Ye=(0,lt.useCallback)(h=>{let J=je.current;pt(null),De.current?.({result:h,session:null,sessionId:J?.sessionId??null,autoCompleted:!1})},[]),Pt=(0,lt.useCallback)(h=>{nt.current?.(h)},[]),ft=(0,lt.useCallback)(h=>{ct.current?.(h)},[]),ze=(0,lt.useMemo)(()=>(0,wr.resolveTheme)(K),[K]),Nt=(0,lt.useMemo)(()=>{let h=ze?.buttonsLayout??(0,wr.resolveButtonsLayoutTheme)(v);return ke?{...h,...ke,cardButton:{...h.cardButton,...ke.cardButton}}:h},[ze,v,ke]),de=(0,lt.useMemo)(()=>{let h=ze?.appearance;return Z?h?{...h,...Z,variables:{...h.variables,...Z.variables}}:Z:h},[Z,ze]),kt=de?.variables,At=kt?.colorPrimary??"#4A49FF",$=kt?.colorPrimaryHover??(0,Ks.darkenHex)(At,.12),ge=kt?.borderRadius??"8px";return(0,Tn.jsxs)(Tn.Fragment,{children:[(0,Tn.jsx)("button",{...z,type:vt,onClick:Me,disabled:ye||Be,"aria-busy":Be,style:{width:"100%",...Ie===void 0?{boxSizing:"border-box",height:up,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Nt.cardButton,...Hs({themeBundle:ze,resolvedPrimaryColor:At,resolvedBorderRadius:ge,submitButtonStyle:Nt.submitButton,explicitPrimaryColor:kt?.colorPrimary}),fontSize:Nt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ye||Be?"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:ye||Be?.6:1,...ut},onMouseEnter:h=>{z.onMouseEnter?.(h),!h.defaultPrevented&&!ye&&!Be&&(ze||kt?.colorPrimary)&&(h.currentTarget.style.backgroundColor=$)},onMouseLeave:h=>{z.onMouseLeave?.(h),!h.defaultPrevented&&(ze||kt?.colorPrimary)&&(h.currentTarget.style.backgroundColor=At)},onMouseDown:h=>{z.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{z.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,Tn.jsx)(oa,{content:Ie})}),q&&(0,Tn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:q}),X&&(0,Tn.jsx)(nn,{status:X,errorMessage:tt,authorized:qe}),Q&&(0,Tn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&pt(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,Tn.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,Tn.jsx)(Ki,{sessionId:Q.sessionId,nonce:Q.nonce,checkoutMode:"full",billingApiUrl:We,locale:y,theme:K,...de?{appearance:de}:{},buttonsTheme:v,buttonsStyles:ke,initialErrorMessage:Q.errorMessage,initialPayPalOrderId:Q.payPalOrderId,cardTitleContent:null,onComplete:Ye,onError:Pt,onDecline:ft})})})]})}var Xi=require("@flopay/js/card-setup"),Gr=require("@flopay/shared"),Yt=require("react");var rl=require("@flopay/shared"),hp=require("@flopay/shared");function Yi(e){let t=(0,rl.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var oo=require("react/jsx-runtime"),Qa=class extends Gr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function vo(e,t={}){let r=e instanceof Gr.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 Qa(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 od({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:d,buttonsStyles:p,loading:m=null,onReady:b,onComplete:P,onDecline:g,onCancel:_,onValidation:V,onError:W}){let[k,T]=(0,Yt.useState)(null),[y,K]=(0,Yt.useState)(null),[Z,v]=(0,Yt.useState)(null),[ke,M]=(0,Yt.useState)(null),[se,Se]=(0,Yt.useState)(null),Ie=(0,Yt.useRef)(!1),ye=(0,Yt.useRef)(!1),{vaultTheme:vt,surface:ut,overlayTheme:z}=(0,Yt.useMemo)(()=>Yi({theme:a,appearance:d,buttonsStyles:p}),[a,d,p]),We=(0,Yt.useMemo)(()=>(0,Ha.mergeCardSetupSurface)(ut,s),[ut,s]),$e=(0,Yt.useRef)(b),Be=(0,Yt.useRef)(W),Re=(0,Yt.useRef)(P),X=(0,Yt.useRef)(g),G=(0,Yt.useRef)(_),tt=(0,Yt.useRef)(V),Ee=(0,Yt.useRef)(!1),qe=(0,Yt.useRef)(!1),re=(0,Yt.useRef)(0);return $e.current=b,Be.current=W,Re.current=P,X.current=g,G.current=_,tt.current=V,(0,Yt.useEffect)(()=>{let q=re.current+1;return re.current=q,()=>{queueMicrotask(()=>{re.current===q&&(Ee.current||qe.current||(qe.current=!0,(0,Ge.invokeMerchantCallback)(()=>{G.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Yt.useEffect)(()=>{let q=!0,we=(0,Gr.resolveBillingApiUrl)(r),Q=new Xi.PaymentAPI(we,{telemetry:n});return T(null),K(null),v(null),Ee.current=!1,qe.current=!1,(async()=>{try{if(!e.trim())throw new Gr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Gr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let pt=await Q.getUnifiedCheckoutSession(e,t);if(!q)return;let fe=pt.data.session;if(!fe||!(0,Gr.isCardSetupCheckoutSession)(fe))throw new Gr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Pe=fe.vault;(0,Gr.isMountableVaultBlock)(Pe)||(Pe=await Q.getVaultCapture(e,t));let Oe=(0,Gr.resolveVaultMountOptions)(Pe,{billingApiUrl:we,sessionId:e,nonce:t});if(!Oe)throw new Gr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!q)return;K(Oe),T(new Xi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(pt){if(!q)return;let fe=vo(pt);Ee.current=!0,v(fe),(0,Ge.invokeMerchantCallback)(()=>Be.current?.(fe))}})(),()=>{q=!1,Q.destroy()}},[r,t,e,n]),(0,Yt.useEffect)(()=>{if(!k)return;let q=!1;ye.current=!1,Ie.current=!1;let we=k.on("submitting",()=>{Ie.current=!0,Se(null),M("processing")}),Q=k.on("complete",Pe=>{Ee.current=!0,Ie.current=!1,M("success"),(async()=>(await new Promise(Oe=>setTimeout(Oe,600)),!ye.current&&(ye.current=!0,(0,Ge.invokeMerchantCallback)(()=>{Re.current?.({status:"succeeded",sessionId:e,...Pe.paymentMethod?{paymentMethod:Pe.paymentMethod}:{}})}),q||M(null))))()}),pt=k.on("decline",Pe=>{Ee.current=!0,Ie.current=!1,Se(Pe.message??null),M("error"),(0,Ge.invokeMerchantCallback)(()=>{X.current?.({status:"declined",sessionId:e,...Pe.declineReason?{reason:Pe.declineReason}:{},...Pe.message?{message:Pe.message}:{}})}),(async()=>(await new Promise(Oe=>setTimeout(Oe,400)),q||M(null)))()}),fe=k.on("challenge_dismissed",()=>{M(null)});return()=>{q=!0,we(),Q(),pt(),fe()}},[k,e]),Z?(0,oo.jsx)("div",{role:"alert",children:Z.message}):!k||!y?.html?(0,oo.jsx)(oo.Fragment,{children:m}):(0,oo.jsxs)(oo.Fragment,{children:[ke&&(0,oo.jsx)(nn,{status:ke,errorMessage:se,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...z?{theme:z}:{}}),(0,oo.jsx)(_o,{capture:k,html:y.html,messageToken:y.messageToken,expectedOrigin:y.expectedOrigin,verificationRequired:y.verificationRequired,theme:vt,containerStyle:We,onReady:()=>{(0,Ge.invokeMerchantCallback)(()=>$e.current?.())},onValidation:q=>{(0,Ge.invokeMerchantCallback)(()=>tt.current?.(q))},onError:q=>{if(!q)return;Ie.current&&(Ie.current=!1,Se(q),M("error"),setTimeout(()=>M(null),400));let we=vo(new Error(q),{code:"card_setup_widget_failed",retryable:!0});(0,Ge.invokeMerchantCallback)(()=>Be.current?.(we))}})]})}var ad=require("@flopay/js/card-setup"),Mn=require("@flopay/shared"),id=require("@paypal/paypal-js"),jo=require("react");var ld=require("react/jsx-runtime");function sd({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:d,customer:{userId:p,email:m},onSubmitting:b,onConfirmed:P,onFailed:g,onAbandoned:_}){let V=(0,jo.useRef)(null),W=(0,jo.useRef)({onSubmitting:b,onConfirmed:P,onFailed:g,onAbandoned:_});W.current={onSubmitting:b,onConfirmed:P,onFailed:g,onAbandoned:_};let[k]=(0,jo.useState)(()=>(0,eo.detectPayPalEnvironment)().inAppBrowser);return(0,jo.useEffect)(()=>{let T=!0,y,K=new ad.PaymentAPI(s,{telemetry:d}),Z={userId:p,email:m};return(async()=>{try{let v=await(0,id.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),ke=V.current;if(!T||!ke)return;if(!v?.Buttons)throw new Mn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let M=v.Buttons({createVaultSetupToken:async()=>{W.current.onSubmitting();let se=await K.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Mn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,Mn.isSettledSessionIntent)(se))throw(0,Mn.settledSessionIntentError)(n);if(se.provider!=="paypal"||se.providerObjectType!=="setup_token")throw new Mn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return se.providerObjectId},onApprove:async se=>{let Se=se.vaultSetupToken;if(!Se)throw new Mn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let Ie=await K.processPayment(Z.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:Se,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Mn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:Z});if(!Ie.ok)throw new Mn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:Ie.status});T&&W.current.onConfirmed()},onCancel:()=>{T&&W.current.onAbandoned()},onError:se=>{if(!T)return;let{popupBlocked:Se}=(0,_e.classifyExternalMethodFailure)(se,{inAppBrowser:k,handoffObserved:!1});W.current.onFailed(Se?new Error((0,_e.buildExternalMethodRecoveryMessage)("PayPal",!0,k)):se,{code:Se?"popup_blocked":"paypal_setup_failed",retryable:!0})}});y=()=>M.close(),await M.render(ke)}catch(v){if(!T)return;W.current.onFailed(v,{code:"paypal_unavailable",retryable:!0})}})(),()=>{T=!1,y?.().catch(()=>{}),K.destroy()}},[s,e,r,m,t,k,a,n,d,p]),(0,ld.jsx)("div",{ref:V,"data-flopay-paypal-setup":""})}var dd=require("@flopay/js/card-setup"),An=require("@flopay/shared"),ao=require("@stripe/react-stripe-js"),ud=require("@stripe/stripe-js"),Yr=require("react");var qr=require("react/jsx-runtime"),pd={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"}},nl=new Map;function Pp(e){let t=nl.get(e);if(t)return t;let r=(0,ud.loadStripe)(e).catch(n=>{throw nl.delete(e),n});return nl.set(e,r),r}function vp(e){return e?(0,An.toStripeAppearance)(e):void 0}function Cp(e){return(0,_e.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function cd(e){return e==="paypal"?"PayPal":(0,An.getStripeMethodDisplayName)(e)}function bp(){return typeof window>"u"?"":window.location.href}var Sp={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function md(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:d}=e,[p]=(0,Yr.useState)(()=>Pp(t)),m=(0,Yr.useMemo)(()=>{let b=vp(d),P=(0,An.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:pd[r]?.types??[r],...P?{setupFutureUsage:P}:{},...b?{appearance:b}:{}}},[d,n,a,s,r]);return(0,qr.jsx)(ao.Elements,{stripe:p,options:m,children:(0,qr.jsx)(wp,{...e})})}function wp({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:d,themeId:p,buttonsLayout:m,onSubmitting:b,onConfirmed:P,onDeclined:g,onFailed:_,onValidation:V,onUnavailable:W}){let k=(0,ao.useStripe)(),T=(0,ao.useElements)(),[y,K]=(0,Yr.useState)(!1),[Z,v]=(0,Yr.useState)("loading"),[ke,M]=(0,Yr.useState)(!1),[se,Se]=(0,Yr.useState)(!1),Ie=(0,Yr.useRef)(!1),[ye]=(0,Yr.useState)(()=>(0,eo.detectPayPalEnvironment)()),[vt,ut]=(0,Yr.useState)(!1),z=(0,Yr.useCallback)((G,tt)=>{if((0,_e.classifyExternalMethodFailure)(G,{inAppBrowser:ye.inAppBrowser,handoffObserved:!1}).popupBlocked){ut(!0),_(new Error((0,_e.buildExternalMethodRecoveryMessage)(cd(e),!0,ye.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}_(tt.message===void 0?G:new Error(tt.message),{code:tt.code,retryable:!0})},[ye.inAppBrowser,e,_]),We=(0,Yr.useCallback)(async G=>{let tt=!1,Ee=!1,qe=()=>{!G||tt||Ee||(Ee=!0,G.paymentFailed({reason:"fail"}))};if(!k||!T||Ie.current){qe();return}Ie.current=!0,K(!0);try{let re=await T.submit();if(re.error){qe(),V(re.error.message??null);return}b();let q=await new dd.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,An.isSettledSessionIntent)(q))throw(0,An.settledSessionIntentError)(r);if(q.provider!=="stripe"||q.intentKind!=="setup")throw new An.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});tt=!0;let we=await k.confirmSetup({elements:T,clientSecret:q.clientSecret,confirmParams:{return_url:bp()},redirect:"if_required"});if(we.error){Cp(we.error)?g({...we.error.decline_code||we.error.code?{reason:we.error.decline_code??we.error.code}:{},...we.error.message?{message:we.error.message}:{}}):z(we.error,{code:"payment_method_setup_provider_failed",message:we.error.message??"The payment method could not be saved."});return}P()}catch(re){qe(),z(re,{code:"payment_method_setup_failed"})}finally{Ie.current=!1,K(!1)}},[a,t,T,e,n,P,g,b,V,z,r,k,s]),$e=pd[e]?.wallet,Be=$e==="paypal"&&(0,to.resolveStripePayPalPresentation)(ye,"auto",vt?"blocked":ye.popupCapability)==="redirect",Re=d?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&$e&&!Be)return(0,qr.jsxs)(qr.Fragment,{children:[(0,qr.jsx)(ha,{}),(0,qr.jsx)(Wa,{state:Z,borderRadius:Re,children:(0,qr.jsx)(ao.ExpressCheckoutElement,{options:{...Fi,paymentMethods:xi([e])},onReady:G=>{let tt=Va(G,[$e]);v(tt),tt==="unavailable"&&W()},onLoadError:()=>{v("load_error"),W()},onConfirm:G=>{We(G)}})})]});let X=cd(e);return(0,qr.jsxs)(qr.Fragment,{children:[ke?(0,qr.jsx)(Ai,{method:e,themeId:p,hasNextStep:!0,highlighted:se,disabled:y,onClick:()=>Se(G=>!G),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:Re}):null,(0,qr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!se,style:se?{display:"flex",flexDirection:"column"}:Sp,children:[(0,qr.jsx)(ao.PaymentElement,{options:{layout:Bi},onReady:()=>M(!0),onLoadError:()=>W(),onChange:G=>{G.complete&&V(null)}}),(0,qr.jsx)(Oi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!k||!T||y||!se,onClick:()=>{We()},color:d?.variables?.colorPrimary??"#4A49FF",borderRadius:d?.variables?.borderRadius??"8px",style:m?.submitButton,children:y?"Saving\u2026":`Save ${X}`})]})]})}var ei=require("@flopay/js/card-setup"),Rr=require("@flopay/shared"),Je=ws(require("react"),1);var Pa=require("@flopay/js/card-setup"),Br=require("@flopay/shared");var dr=require("react/jsx-runtime"),Rp=15,kp=2e3;function Ep(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function ol(e){return new Promise(t=>setTimeout(t,e))}async function _p(e,t,r){if(!t.trim())throw new Rr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new Rr.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,Rr.isCardSetupCheckoutSession)(a))throw new Rr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Br.readSetupAdvertisement)(n);if(!(0,Br.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 Rr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function Ip(e,t,r,n,a){let s=t.vault??null;(0,Rr.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let d=(0,Rr.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!d)throw new Rr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return d}var Ji=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 yd({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:d="modern-light",containerStyle:p,appearance:m,buttonsStyles:b,loading:P=null,onReady:g,onComplete:_,onDecline:V,onCancel:W,onValidation:k,onError:T}){let[y]=(0,Je.useState)(Pa.readSetupRedirectReturn),[K,Z]=(0,Je.useState)(null),[v,ke]=(0,Je.useState)(!1),[M,se]=(0,Je.useState)(null),[Se,Ie]=(0,Je.useState)(null),[ye,vt]=(0,Je.useState)(null),[ut,z]=(0,Je.useState)(null),[We,$e]=(0,Je.useState)(()=>new Set),Be=(0,Je.useRef)(We),Re=(0,Je.useRef)(null);Re.current=K;let X=(0,Je.useRef)(!1),G=(0,Je.useRef)(!1),tt=(0,Je.useRef)(!1),Ee=(0,Je.useRef)(!1),qe=(0,Je.useRef)(0),re=(0,Je.useRef)(0),q=(0,Je.useRef)(!1),{vaultTheme:we,surface:Q,overlayTheme:pt,appearance:fe,buttonsLayout:Pe}=(0,Je.useMemo)(()=>Yi({theme:d,appearance:m,buttonsStyles:b}),[d,m,b]),Oe=(0,Je.useMemo)(()=>(0,Ha.mergeCardSetupSurface)(Q,p),[Q,p]),ce=(0,Je.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:g,onComplete:_,onDecline:V,onCancel:W,onValidation:k,onError:T});ce.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:g,onComplete:_,onDecline:V,onCancel:W,onValidation:k,onError:T},(0,Je.useEffect)(()=>{q.current=!0;let u=qe.current+1;return qe.current=u,()=>{q.current=!1,re.current+=1,queueMicrotask(()=>{qe.current===u&&(tt.current||Ee.current||(Ee.current=!0,(0,Ge.invokeMerchantCallback)(()=>{ce.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let je=(0,Je.useCallback)((u,S)=>{tt.current=!0,X.current=!1,z({status:"success",wording:u,message:null}),(async()=>(await ol(600),!G.current&&(G.current=!0,(0,Ge.invokeMerchantCallback)(()=>{ce.current.onComplete?.({status:"succeeded",sessionId:ce.current.sessionId,...S?{paymentMethod:S}:{}})}),q.current&&z(null))))()},[]),De=(0,Je.useCallback)((u,S)=>{tt.current=!0,X.current=!1,z({status:"error",wording:u,message:S.message??null}),(0,Ge.invokeMerchantCallback)(()=>{ce.current.onDecline?.({status:"declined",sessionId:ce.current.sessionId,...S.reason?{reason:S.reason}:{},...S.message?{message:S.message}:{}})}),(async()=>(await ol(400),q.current&&z(null)))()},[]),nt=(0,Je.useCallback)((u,S)=>{X.current?(X.current=!1,z({status:"error",wording:u,message:S.message}),setTimeout(()=>{q.current&&z(null)},400)):z(null),(0,Ge.invokeMerchantCallback)(()=>ce.current.onError?.(S))},[]),ct=(0,Je.useCallback)(async u=>{let S=re.current+1;re.current=S;let I=()=>!q.current||S!==re.current;X.current=!0,z({status:"processing",wording:"payment_method",message:null});let H=new ei.PaymentAPI((0,Rr.resolveBillingApiUrl)(ce.current.billingApiUrl),{telemetry:ce.current.telemetry});try{for(let F=0;F<Rp;F+=1){if((F>0||u.waitFirst)&&await ol(kp),I())return;let B=await H.getUnifiedCheckoutSession(ce.current.sessionId,ce.current.nonce);if(I())return;let Ae=B.data.session?.status;if(Ae==="complete"){ke(!0),je("payment_method");return}if(Ae==="expired")throw new Rr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Rr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(F){if(I())return;let B=F instanceof Rr.FloPayError&&F.code==="payment_method_setup_unverified";nt("payment_method",vo(F,B?{retryable:!0}:{}))}finally{H.destroy()}},[nt,je]);(0,Je.useEffect)(()=>{let u=!0,S=(0,Rr.resolveBillingApiUrl)(a),I=new ei.PaymentAPI(S,{telemetry:s});Z(null),ke(!1),se(null),Ie(null),vt(null);let H=new Set;return Be.current=H,$e(H),tt.current=!1,Ee.current=!1,G.current=!1,(async()=>{try{let{session:F,advertisement:B}=await _p(I,r,n);if(!u)return;let Ae={advertisement:B,customer:Ep(F),...F.futureUse?{futureUse:F.futureUse}:{},...F.futureUseUnsupported?{futureUseUnsupported:F.futureUseUnsupported}:{}};if(y){if((0,Pa.clearSetupRedirectParams)(),F.status==="complete"){ke(!0),Z(Ae),je("payment_method");return}y.failed?De("payment_method",{reason:"redirect_failed"}):ct({waitFirst:!0})}let jr=B.card?await Ip(I,F,r,n,S):null;if(!u)return;Z(Ae),jr&&(Ie(jr),se(new ei.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(F){if(!u)return;let B=vo(F);tt.current=!0,vt(B),(0,Ge.invokeMerchantCallback)(()=>ce.current.onError?.(B))}})(),()=>{u=!1,I.destroy()}},[a,n,y,De,je,r,s,ct]),(0,Je.useEffect)(()=>{if(!M)return;X.current=!1;let u=M.on("submitting",()=>{X.current=!0,z({status:"processing",wording:"card",message:null})}),S=M.on("complete",F=>{je("card",F.paymentMethod)}),I=M.on("decline",F=>{De("card",{...F.declineReason?{reason:F.declineReason}:{},...F.message?{message:F.message}:{}})}),H=M.on("challenge_dismissed",()=>{z(null)});return()=>{u(),S(),I(),H()}},[M,De,je]);let Y=(0,Je.useCallback)((u,S,I)=>{if(I.retryable){nt("payment_method",vo(S,I));return}if(Be.current.has(u))return;let H=new Set(Be.current);H.add(u),Be.current=H,$e(H);let F=Re.current?.advertisement,B=F?(0,Br.advertisedMethodKeys)(F).some(Ae=>!H.has(Ae)):!1;nt("payment_method",vo(S,{code:I.code,retryable:B}))},[nt]),Rt=(0,Je.useMemo)(()=>({onSubmitting:()=>{X.current=!0,z({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{ct({waitFirst:!1})},onDeclined:u=>De("payment_method",u),onValidation:u=>{(0,Ge.invokeMerchantCallback)(()=>ce.current.onValidation?.(u))},onAbandoned:()=>{X.current=!1,z(null)}}),[De,ct]),Ht=(0,Je.useRef)(Y);Ht.current=Y;let Mt=(0,Je.useRef)(new Map),Lt=u=>{let S=Mt.current.get(u);if(S)return S;let I=(H,F)=>Ht.current(u,H,F);return Mt.current.set(u,I),I},he=(0,Je.useCallback)(u=>{if(Be.current.has(u))return;let S=new Set(Be.current);S.add(u),Be.current=S,$e(S);let I=Re.current?.advertisement;I&&(0,Br.advertisedMethodKeys)(I).some(F=>!S.has(F))||nt("payment_method",vo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[nt]),Me=(0,Je.useRef)(he);Me.current=he;let Ye=(0,Je.useRef)(new Map),Pt=u=>{let S=Ye.current.get(u);if(S)return S;let I=()=>Me.current(u);return Ye.current.set(u,I),I},ft=ut?(0,dr.jsx)(nn,{status:ut.status,errorMessage:ut.message,...(0,Br.setupOverlayLabels)(ut.wording),successNote:null,...pt?{theme:pt}:{}}):null;if(ye)return(0,dr.jsx)("div",{role:"alert",children:ye.message});if(!K||v)return(0,dr.jsxs)(dr.Fragment,{children:[ft,K?null:P]});let{advertisement:ze,customer:Nt,futureUse:de,futureUseUnsupported:kt}=K,At=(0,Rr.resolveBillingApiUrl)(a),$=s===void 0?{}:{telemetry:s},ge=ze.stripe.filter(({method:u})=>!We.has(u)),Ut=We.has("paypal")?null:ze.paypal,h=!!(ze.card&&M&&Se?.html),J=({method:u,publishableKey:S,currency:I})=>(0,dr.jsx)("div",{"data-flopay-payment-method":u,style:{display:"contents"},children:(0,dr.jsx)(Ji,{onFailed:Lt(u),children:(0,dr.jsx)(Je.Suspense,{fallback:null,children:(0,dr.jsx)(e,{method:u,category:(0,Br.stripeMethodCategory)(u),publishableKey:S,currency:I,...de?{futureUse:de}:{},...kt?{futureUseUnsupported:kt}:{},sessionId:r,nonce:n,billingApiUrl:At,...$,...fe?{appearance:fe}:{},...Pe?{buttonsLayout:Pe}:{},...typeof d=="string"?{themeId:d}:{},...Rt,onFailed:Lt(u),onUnavailable:Pt(u)})})})},u),He=ge.filter(({method:u})=>(0,Br.stripeMethodCategory)(u)==="wallet"),L=ge.filter(({method:u})=>(0,Br.stripeMethodCategory)(u)!=="wallet"),mt=ge.length>0||Ut!==null;return(0,dr.jsxs)(dr.Fragment,{children:[ft,mt?(0,dr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[He.map(J),Ut?(0,dr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,dr.jsx)(Ji,{onFailed:Lt("paypal"),children:(0,dr.jsx)(Je.Suspense,{fallback:null,children:(0,dr.jsx)(t,{clientId:Ut.clientId,...Ut.environment?{environment:Ut.environment}:{},...ze.currency?{currency:ze.currency}:{},sessionId:r,nonce:n,billingApiUrl:At,customer:Nt,...$,...Rt,onFailed:Lt("paypal"),onUnavailable:Pt("paypal")})})})}):null,L.map(J)]}):null,h&&mt?(0,dr.jsx)(Ka,{label:"or add a card"}):null,h&&M&&Se?.html?(0,dr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,dr.jsx)(_o,{capture:M,html:Se.html,messageToken:Se.messageToken,expectedOrigin:Se.expectedOrigin,verificationRequired:Se.verificationRequired,theme:we,containerStyle:Oe,onReady:()=>{(0,Ge.invokeMerchantCallback)(()=>ce.current.onReady?.())},onValidation:u=>{(0,Ge.invokeMerchantCallback)(()=>ce.current.onValidation?.(u))},onError:u=>{u&&nt("card",vo(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var gd=require("react/jsx-runtime"),Tp={StripeSetupMethod:md,PayPalSetupMethod:sd};function fd(e){return(0,gd.jsx)(yd,{...e,branches:Tp})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|