@flopay/react 1.11.5 → 1.11.6
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/card-setup-entry.cjs +2 -2
- package/dist/card-setup-entry.mjs +1 -1
- package/dist/chunk-H4MQCBX4.mjs +22 -0
- package/dist/{chunk-YSFYLEHB.mjs → chunk-HSYSKQPT.mjs} +1 -1
- package/dist/chunk-KKA5TF5P.mjs +6 -0
- package/dist/chunk-Q5RE4G4O.mjs +1 -0
- package/dist/chunk-VK67324N.mjs +1 -0
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +7 -7
- package/dist/payment-method-setup-entry.cjs +3 -3
- package/dist/payment-method-setup-entry.mjs +1 -1
- package/dist/payment-method-setup-paypal-AGIJIZDK.mjs +1 -0
- package/dist/payment-method-setup-stripe-6O2YE4RY.mjs +1 -0
- package/package.json +3 -3
- package/dist/chunk-52RFSQJ7.mjs +0 -1
- package/dist/chunk-AW5LOT2K.mjs +0 -6
- package/dist/chunk-M7R46EDF.mjs +0 -1
- package/dist/chunk-UFFPBTKU.mjs +0 -22
- package/dist/payment-method-setup-paypal-FRRQW56L.mjs +0 -1
- package/dist/payment-method-setup-stripe-TI2A5JPE.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as Dl}from"./chunk-52RFSQJ7.mjs";import{c as Bt,d as Ir,e as ra,f as Oi,g as Sl,h as oa,i as wl,j as Il,k as pd,m as md}from"./chunk-AW5LOT2K.mjs";import{a as Bl}from"./chunk-YSFYLEHB.mjs";import{a as sa,b as ja,c as Ui,d as zi,e as qi,f as El,g as Tl,h as Al,i as Ml,j as xl,k as Fl}from"./chunk-UFFPBTKU.mjs";import{a as Ua,b as kl,c as Ur,d as aa,e as za,f as Rl,g as Li,h as zr,i as ia,j as _l,k as qa}from"./chunk-M7R46EDF.mjs";import{dropThirdPartyOnlyError as df}from"@flopay/shared";import{PaymentAPI as Os}from"@flopay/js";import{FloPayError as _a,resolveBillingApiUrl as Ap,resolveButtonsLayoutTheme as Mp,resolveTheme as xp}from"@flopay/shared";import{useCallback as Nr,useEffect as qo,useMemo as Ra,useRef as jo,useState as $o}from"react";import{Fragment as Io,jsx as Xn,jsxs as Nl}from"react/jsx-runtime";function yd(){return Nl(Io,{children:[Nl("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:[Xn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Xn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Xn("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:Xn("path",{d:"M9 18l6-6-6-6"})})]})}function fd(){return Xn(Io,{children:"Go back"})}function gd(){return Xn(Io,{children:"Secure card checkout"})}function Co(e){return e!==void 0&&(e===""||e===null||e===!1)}function So({content:e}){return Xn(Io,{children:e===void 0?Xn(yd,{}):e})}function wo({content:e}){return Xn(Io,{children:e===void 0?Xn(fd,{}):e})}function la({content:e}){return Xn(Io,{children:e===void 0?Xn(gd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as hd,classifyTelemetryFailure as Pd,FloPayError as Rn,isCardHolderNamePlaceholder as Ol,isMoneySettledOutcome as vd,isMountableVaultBlock as bd,isSetupIntentClientSecret as Cd,isValidEmail as Sd,resolveSetupFutureUsage as wd}from"@flopay/shared";var Id="Checkout is temporarily unavailable. Please try again later.";function ji(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Rn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function kd(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 Ll(){return new Rn(Id,"api_error",{code:"CheckoutInitializationFailed"})}function $i(e){return!!e?.gateways?.worldpayCorporateGateway}function qr(e){return e?.status==="open"&&$i(e)}function Ul(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(bd(r?.vault)||r?.gateways?.pcivault||o?.includes("card")||qr(r))||t&&e?.data.paypal?.publishableKey)}function zl(e,t){if(t&&(!(e instanceof Rn)||e.type==="authentication_error"))return ji(e);if(!(e instanceof Rn&&kd(e))){if(!t&&!(e instanceof Rn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Pd(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Rn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Rn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function ko(e,t,n,r={}){let o;return(i={})=>{if(o!==void 0)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},d=Ol(s.firstName,s.lastName);if(!Sd(s.email))return Promise.reject(new Rn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let f={};for(let[u,w]of Object.entries(s)){if(d&&u.endsWith("Name")||typeof w!="string")continue;let b=w.trim();b&&(f[u]=b)}return o=e.claimCheckoutSession(t,n,{accountData:f}),o.catch(()=>{}),o}}function ql(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Ki(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 jl(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],r=n.reduce((i,s)=>i+(s.overrideAmount??s.totalAmount??0),0),o=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,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:n.map((i,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??o,metadata:i.metadata??null}))}}function oo(e){if(Ol(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Vi(e,t){return t?{...e,...t}:e}function un(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{},...s?{sessionId:s}:{}}}function jr(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var Rd=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function $r(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Rd)if(n.test(t))return r;return e}function Br(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Fr(e){return e?.status==="authorized"||e?.status==="complete"}function Kr(e,t){if(e.data.session)return e.data.session;let n=e.raw,r=n?.latestTransactionAttempt?.result,o=n?.status==="authorized"||r==="AUTHORIZED";return o||n?.status==="completed"||r==="SUCCESS"?{...t,status:o?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function $l(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function $a(e){let t=$l(e);return new Rn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Ka(e){return e instanceof Rn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Ro(e){return $l(e)?new Rn("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Rn("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Rn(hd,"api_error",{code:"checkout_processing_timeout"})}function ca(e,t){return e==="processing"||vd(e,t)}function Kl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Vl(e,t){let n=e;if(Cd(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new Rn(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new Rn(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}var _d=["apple_pay","google_pay"];function Wl(e,t="automatic",n){let r=wd(n,_d,"wallet");return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],...r?{setupFutureUsage:r}:{}}}var Ed=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Wi(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Ed.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function da(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as mp,PaymentAPI as mi,SESSION_CREATE_TELEMETRY as yp}from"@flopay/js";import{buildCheckoutDisplayData as fp,classifyTelemetryFailure as Kc,FloPayError as Cn,isDetachedSessionEligible as gp,isMountableVaultBlock as hp,resolveBillingApiUrl as Pp,resolveButtonsLayoutTheme as vp,resolveIdempotencyKey as Oc,resolveTheme as Vc,SDK_VERSION as Wc,telemetryStatusClass as bp}from"@flopay/shared";import Es,{useCallback as bn,useEffect as yr,useMemo as Qn,useRef as Ft,useState as Ht}from"react";import{createContext as Hl}from"react";var Zn=Hl({flopay:null,paypalFlopay:null,billingApiUrl:""}),ur=Hl({session:null,loading:!1,error:null});import{PaymentAPI as Yi}from"@flopay/js";import{classifyTelemetryFailure as $d,FloPayError as Ji,generateIdempotencyKey as Kd,isValidEmail as ya,normalizeGatewayEnvironment as Vd,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Xi,SDK_VERSION as Wd}from"@flopay/shared";import{loadScript as Hd}from"@paypal/paypal-js";import{useCallback as kr,useContext as Gd,useEffect as zt,useMemo as fa,useRef as rt,useState as Hr}from"react";import{isValidEmail as Td}from"@flopay/shared";import{useCallback as Gl,useEffect as Ad,useRef as Yl,useState as Xl}from"react";import{jsx as Jl,jsxs as ua}from"react/jsx-runtime";function Nn(e,t=!1){let{firstName:n,lastName:r,...o}=e,i=n?.trim(),s=r?.trim();return{...o,...i||t?{firstName:i??""}:{},...s||t?{lastName:s??""}:{}}}function _o(){let[e,t]=Xl(null),n=Yl(null),r=Yl(0),o=Gl((s,d)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:d}),new Promise(f=>{n.current=f})),[]),i=Gl(s=>{let d=n.current;n.current=null,t(null),d?.(s)},[]);return Ad(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function Eo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,d]=Xl(e.email?.trim()??""),f=Td(s.trim());return ua("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[ua("div",{style:{fontWeight:700},children:["Continue with ",t]}),ua("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Jl("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:u=>d(u.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),ua("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Jl("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),ua("button",{type:"button",disabled:!f||o,onClick:()=>{n(Nn({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as Md}from"@flopay/shared";import{useContext as Va}from"react";function Vr(){return Va(Zn).flopay}function Hi(){return Va(Zn).paypalFlopay??null}function xd(){return Va(ur)}function Zl(){return Va(Zn).billingApiUrl||Md()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Bd}from"@flopay/shared";import{useCallback as Fd,useRef as Wa}from"react";var Dd={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function Nd(e){return e==="stripe"||e==="paypal"?e:void 0}function Od(e){let t=Nd(e.provider),n={schemaVersion:Bd,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Dd[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var Gi=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function To(e,t){let n=Wa(e);n.current=e;let r=Wa(new Set),o=Wa(t),i=Wa(t);return ra(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Fd(s=>{if(i.current!==t)return;let d=Od(s);if(d){if(Gi.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}Bt(()=>n.current?.(d))}},[t])}import{createContext as Ld}from"react";var pa=Ld(null);function Ha(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Ud=Symbol.for("@flopay/js.telemetry.bridge.v1"),zd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function qd(){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 jd(e){let t=qd(),n=(o,i)=>o?o.bind(e):i,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Ga(e){let t=globalThis[zd];return jd(t?.(e)??{})}function pn(e){if(e)return e[Ud]}import{useCallback as Wr,useEffect as Ql,useRef as ao}from"react";function ma(e,t){let n=ao(0),r=ao(null),o=ao(null),i=ao(e),s=ao(t?.onHandoffObserved),d=ao(t?.defersMissingTerminal),f=ao(t?.onMissingTerminalDeferred);Ql(()=>{i.current=e,s.current=t?.onHandoffObserved,d.current=t?.defersMissingTerminal,f.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let u=Wr((h=o.current)=>{h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),w=Wr(h=>{u();let C=n.current+1;return n.current=C,r.current=null,o.current={generation:C,method:h,timer:null,yieldedControl:!1},C},[u]),b=Wr(h=>{let C=o.current;return h!==void 0&&C?.generation!==h?!1:(u(C),o.current=null,(h===void 0||r.current===h)&&(r.current=null),!0)},[u]),j=Wr(h=>{let C=o.current,le=h??C?.generation??n.current;(h===void 0||C?.generation===h)&&(u(C),o.current=null),r.current=le},[u]),L=Wr(h=>r.current===(h??n.current),[]),I=Wr(h=>o.current?.generation===h&&r.current!==h,[]),N=Wr(()=>{let h=o.current;h&&(u(h),!h.yieldedControl&&(h.yieldedControl=!0,s.current?.(h.method)))},[u]),U=Wr(()=>{let h=o.current;!h?.yieldedControl||document.visibilityState!=="visible"||(u(h),h.timer=setTimeout(()=>{if(h.timer=null,o.current?.generation===h.generation){if(d.current?.(h.method)){f.current?.(h.method,h.generation);return}o.current=null,r.current=h.generation,i.current(h.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},600))},[u]);return Ql(()=>{let h=()=>{document.visibilityState==="visible"?U():N()};return document.addEventListener("visibilitychange",h),window.addEventListener("blur",N),window.addEventListener("focus",U),()=>{document.removeEventListener("visibilitychange",h),window.removeEventListener("blur",N),window.removeEventListener("focus",U),u()}},[u,N,U]),{startAttempt:w,finishAttempt:b,invalidateAttempt:j,isAttemptInvalidated:L,isAttemptCurrent:I,generationRef:n}}import{jsx as io,jsxs as Zi}from"react/jsx-runtime";var Ya=45,Yd=1e3,Jd=11e3,Xd={width:"100%",minHeight:Ya,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"},Zd={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 Qd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Zd[e.kind]??null}}function ec(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Rl(t)?"paypal_init_timeout":"paypal_init_failure"}function eu(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function tu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function tc({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:d,currency:f,isSubscription:u,providerObjectType:w,approvalPresentation:b,onTokenizedBody:j,onComplete:L,onErrorChange:I,onDecline:N,onTechnicalFailure:U,isProcessing:h=!1,onLoadStateChange:C,onInitializationStateChange:le,allowAutomaticRetry:D=!0,onButtonClick:ve,runBeforeButtonClick:J,session:ke,existingOrderId:qe,telemetry:Re,telemetryContext:st,onInstrument:qt,debug:fe=!1}){let Ae=Vr(),ht=To(qt,e),Ee=fa(()=>{if(Ae)return null;let m=Ga({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Wd,enabled:Re!==!1});return m.setCheckoutContext(st??{}),m.beginCheckout(st??{}),m},[n,Ae,Re,st?.checkoutMode,st?.layout]),He=fa(()=>pn(Ae),[Ae]);zt(()=>()=>{Ee&&Ee.flush().catch(()=>{}).finally(()=>Ee.destroy())},[Ee]);let _e=fa(()=>({error:m=>{He?He.error(m):Ee?.error(m),ht({class:"technical_error",errorCode:m.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":m.errorCode,requestCategory:m.requestCategory,provider:m.provider})},log:m=>{He?He.log(m):Ee?.log(m),ht({class:"lifecycle",name:m.name,provider:m.provider})},performance:m=>{He?He.performance(m):Ee?.performance(m)},terminal:m=>{He?He.terminal(m):Ee?.terminal(m)},startTiming:()=>He?.now()??Ee?.now()??0,elapsed:m=>He?.elapsed(m)??Math.max(0,(Ee?.now()??m)-m)}),[ht,He,Ee]),ie=rt(null),je=rt(0),$e=rt(null),pt=rt(null),Ce=rt(null),ge=Gd(pa),ce=rt(null);ce.current||(ce.current=Ha());let M=ge??ce.current,Se=rt(null),Ue=rt(!1),[Me,V]=Hr(!1),[Pt,ze]=Hr(!1),[Te,Ze]=Hr(0),xe=rt(0),[et,Fe]=Hr(!1),vt=rt(!1),Gt=rt(!1),[mt,Tt]=Hr(!1),[E,se]=Hr(!1),{request:De,collect:F,finish:we}=_o(),yt=rt({sessionId:e,required:!ya(r?.trim()||ke?.customer?.email?.trim())});yt.current.sessionId!==e&&(yt.current={sessionId:e,required:!ya(r?.trim()||ke?.customer?.email?.trim())});let Ne=yt.current.required,St=fa(()=>n.replace(/\/+$/,""),[n]),p=ke?.gateways?.paypal?.providerObjectType??w,g=p??(u?"subscription":"order"),[x]=Hr(ia),A=ke?.gateways?.paypal?.approvalPresentation??b,re=qa(x,A==="app_switch"?"app_switch":void 0,g),ct=p==="order"||p==="setup_token",he=fa(()=>JSON.stringify([St,s,f,d??"",g,ct,re,e,qe??""]),[St,s,f,d,qe,g,ct,re,e]),Ke=rt(he),X=Ke.current!==he,jt=rt(fe),bt=rt(null),[At,at]=Hr([]),de=kr(m=>{jt.current&&at(Be=>[...Be,`${new Date().toISOString().slice(11,23)} ${m}`])},[]);zt(()=>{jt.current=fe,fe&&de("debug:enabled"),bt.current?.setEnabled(fe)},[de,fe]);let _n=rt(j),On=rt(L),mn=rt(I),$t=rt(N),Ln=rt(U),Un=rt(ve),hn=rt(C),Mt=rt(le),Ge=rt(i),Oe=rt(J),En=rt(ke),wt=rt(r),zn=rt(o),yn=rt(t),Kt=rt(null),Qt=rt(new Map),er=rt(new Map),Wn=rt(!1);zt(()=>(Wn.current=!0,()=>{Wn.current=!1}),[]),zt(()=>{_n.current=j},[j]),zt(()=>{Ge.current=i},[i]),zt(()=>{On.current=L},[L]),zt(()=>{mn.current=I},[I]),zt(()=>{$t.current=N},[N]),zt(()=>{Ln.current=U},[U]),zt(()=>{Un.current=ve},[ve]),zt(()=>{hn.current=C},[C]),zt(()=>{Mt.current=le},[le]),zt(()=>{Oe.current=J},[J]),zt(()=>{En.current=ke},[ke]),zt(()=>{wt.current=r},[r]),zt(()=>{zn.current=o},[o]),zt(()=>{yn.current=t},[t]),zt(()=>{xe.current=Te},[Te]),zt(()=>{et&&Se.current?.focus()},[et,Te]);let en=kr(()=>{window.setTimeout(()=>{Se.current?.focus()},0)},[]),It=kr(()=>{V(!1),Ze(m=>m+1)},[]),tn=kr(()=>{Fe(!1),(ie.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ie.current)?.focus?.()},[]);zt(()=>{!Me||!Ue.current||(Ue.current=!1,tn())},[tn,Me,Te]);let rn=kr((m,Be)=>{let $=Be?.popupBlocked??zr(m);$&&M.markBlocked();let Pn=Ua("PayPal",$,x.inAppBrowser),qn=Ln.current;if(qn){let Yt=$&&x.inAppBrowser?new Ji(Pn,"api_error",{code:Be?.code??"paypal_popup_blocked"}):m;qn("paypal",Yt,Be);return}mn.current?.(Pn)},[M,x.inAppBrowser]),Dt=kr(m=>{let Be=$e.current,$=pt.current;Be===null||!$||(_e.log({...$,popupCapability:M.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:m}),_e.performance({...$,popupCapability:M.current(),stage:"overlay_return",durationMs:_e.elapsed(Be),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:m}),$e.current=null)},[M,_e]),sn=kr((m,Be,$)=>{let Pn=pt.current;Dt("overlay_timeout"),Pn&&_e.error({...Pn,popupCapability:M.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),rn(Be,{...$,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:re,terminalReason:"overlay_timeout"}),Fe(!0),It(),en()},[Dt,en,rn,M,re,It,_e]),Ot=kr(()=>{M.markAvailable();let m=pt.current;m&&(Ce.current=m.attempt,_e.log({...m,popupCapability:M.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[M,_e]),{finishAttempt:on,generationRef:Nt,invalidateAttempt:W,isAttemptCurrent:tr,isAttemptInvalidated:nr,startAttempt:rr}=ma(sn,{onHandoffObserved:Ot}),nn=kr(()=>(Fe(!1),rr("paypal")),[rr]),Tn=kr(m=>{W(m?.generation),m?.showRetry&&Fe(!0),m?.remount&&It(),m?.focus!==!1&&en()},[en,W,It]),Sn=m=>{let Be=Kt.current;return Be&&er.current.set(m,Be),m};zt(()=>{Ke.current!==he&&(Ke.current=he,vt.current=!1,Gt.current=!1,V(!1),ze(!1),Tt(!1),Mt.current?.("loading"))},[he]),zt(()=>{Bt(()=>hn.current?.(Me&&!mt))},[Me,mt]);let me=Vd(d);zt(()=>{let m={attempt:Nt.current+1,inAppBrowser:x.inAppBrowser,appFamily:x.appFamily,popupCapability:M.current(),presentationMode:re},Be=()=>({...pt.current??m,popupCapability:M.current()}),$={error:l=>_e.error({...l,...Be()}),log:l=>_e.log({...l,...Be()}),performance:l=>_e.performance({...l,...Be()}),terminal:l=>_e.terminal({...l,...Be()}),startTiming:_e.startTiming,elapsed:_e.elapsed},Pn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",qn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(de(`mount clientId=${Pn} env=${d??"(unset)"}\u2192${me??"live"} ccy=${f} sub=${u}`),de(`ua=${qn.slice(0,80)}${qn.length>80?"\u2026":""}`),!s){de("FAIL: clientId empty \u2014 gateway misconfigured"),Tt(!0),$.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(!ie.current){de("FAIL: containerRef not attached");return}je.current=$.startTiming(),$.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Yt=!1,An=!1,nt=()=>Yt||An,or,Zr=!1,kt=()=>{or=Kd(),or||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Zr=!0},Mn=null,fr=!1,Hn=null,Jt=!1,ar=()=>{!Hn||Jt||(Jt=!0,Hn.close().catch(()=>{}))},xn=!1,Tr=!1,Bn=ie.current,gr=null,hr=null,Ar=[],jn=null,Gn=!1,Mr=!1,xt=null,wn=l=>{if(!l||typeof l.getBoundingClientRect!="function")return"(no rect)";let c=l.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},Yn=l=>{if(!l)return"(empty)";try{let c=new URL(l,typeof window>"u"?"https://localhost":window.location.href),S=c.pathname.toLowerCase();return S.includes("checkcaptcha")||S.includes("captcha")?`CAPTCHA(${c.host}${S})`:S.includes("risk")||S.includes("challenge")?`RISK(${c.host}${S})`:S.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${S}`.slice(0,100)}catch{return l.slice(0,80)}},ir=l=>{let c=l.getAttribute("src"),S=l.getAttribute("srcdoc"),R=l.getAttribute("name"),te=l.getAttribute("sandbox"),Z=[];return c&&Z.push(`src=${Yn(c)}`),S&&Z.push(`srcdoc[${S.length}ch]`),!c&&!S&&Z.push("src=(empty) srcdoc=(empty)"),R&&Z.push(`name=${R.slice(0,40)}`),te!==null&&Z.push(`sandbox="${te.slice(0,40)}"`),Z.join(" ")},Pr=l=>{if(!(l instanceof HTMLIFrameElement))return"";try{let c=l.contentDocument;if(!c)return"cd=null";let S=c.body?.children.length??0,R=c.body?.innerHTML.length??0,te=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${S}children,${R}ch] head[${te}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},Ve=[],ln=l=>{if(nt())return;let c=l.message??String(l.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(de(`window:error ${c.slice(0,140)}`),Ve.push(c))},cn=l=>{if(nt())return;let c=l.reason instanceof Error?l.reason.message:String(l.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(de(`window:rejection ${c.slice(0,140)}`),Ve.push(c))},In={value:0},Qr=()=>{gr?.disconnect(),gr=null,hr?.disconnect(),hr=null;for(let l of Ar.splice(0))clearTimeout(l);Mr=!1,Gn&&typeof window<"u"&&(window.removeEventListener("error",ln),window.removeEventListener("unhandledrejection",cn)),Gn=!1},vr=()=>{if(!(Gn||nt()||xn)){if(Gn=!0,Ve.length=0,In.value=0,typeof window<"u"&&(window.addEventListener("error",ln),window.addEventListener("unhandledrejection",cn)),typeof PerformanceObserver<"u")try{hr=new PerformanceObserver(l=>{if(!nt())for(let c of l.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;In.value+=1;let S=Math.round(c.duration);de(`net ${S}ms ${c.name.slice(0,90)}`)}}),hr.observe({type:"resource",buffered:!0})}catch{}xt?.()}},Or=()=>{jn&&(clearTimeout(jn),jn=null)},kn=()=>{Qr(),Or()},dn={setEnabled:l=>{l?vr():Qr()}};bt.current=dn,jt.current&&vr();let sr=l=>{if(!l)return!1;let c=l.toLowerCase();return c.includes("zoid destroyed")||c.includes("destroyed all components")||c.includes("window closed")||c.includes("detected container element removed")},fn=l=>{if(nt()||sr(l))return;let c=$r(l)??l;Bt(()=>mn.current?.(c))},k=(l,c)=>{if(Yt||fr)return;fr=!0,An=!0,kn(),ar();let S=Qd({kind:l,generationActive:!0,automaticRetryAllowed:D,automaticRetryUsed:vt.current});if(S.action==="retry"){vt.current=!0,V(!1),se(!1),ze(!0),Mt.current?.("retrying"),Mn=setTimeout(()=>{Yt||Ze(R=>R+1)},Yd);return}if(V(!1),se(!1),ze(!1),Tt(!0),S.action!=="ignore"){if(Mt.current?.("exhausted"),S.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",c);return}if(S.report){let R=Li({code:ec(l,c),message:c},{inAppBrowser:x.inAppBrowser,handoffObserved:!1});R.popupBlocked&&M.markBlocked(),$.error({errorCode:R.popupBlocked?R.errorCode:S.report.errorCode,stage:S.report.stage,operationOutcome:S.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:R.terminalReason})}Gt.current||(Gt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",ec(l,c)))}};Tt(!1);let _=async(l,c=Kt.current)=>{if(nt())return;let S=c?.sessionId??e;if(_n.current){await _n.current(l,{sessionId:S,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let R=$.startTiming();$.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let te=()=>{$.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"processing",durationMs:$.elapsed(R),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Z=En.current,dt=c?.accountPatch?.email??wt.current,Lt=c?.accountPatch?.userId??Z?.customer?.id??Z?.accountData?.userId??"",be=c?.accountPatch?.firstName??Z?.customer?.firstName??Z?.accountData?.firstName,Ie=c?.accountPatch?.lastName??Z?.customer?.lastName??Z?.accountData?.lastName,G=await new Yi(St,{telemetry:!1}).processPayment(Lt,{sessionId:S,nonce:c?.nonce??yn.current,paymentMethodCategory:"paypal",tokenizedData:l,accountData:{userId:Lt,email:dt??Z?.customer?.email??"",...be?{firstName:be}:{},...Ie?{lastName:Ie}:{},country:c?.accountPatch?.country??Z?.customer?.country??Z?.accountData?.country??void 0,zip:c?.accountPatch?.zip??Z?.customer?.zip??Z?.accountData?.zip??void 0}});if(G.ok){if(An||Yt&&Wn.current)return;te(),$.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Bt(()=>On.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(nt())return;let Q=await G.json().catch(()=>null),P=Q?.message??"PayPal payment failed.",Y=$r(P)??P;te(),G.status===400&&(typeof Q?.declineCode=="string"||!Array.isArray(Q?.fields))?$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):G.status===400||G.status===422?$.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):$.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:tu(G.status),failureCategory:G.status>=500?"server_error":void 0}),fn(Y),Bt(()=>$t.current?.(un("paypal",Y,{code:Q?.code,declineCode:Q?.declineCode})));return}catch(Z){if(nt())return;te(),$.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let dt=Z instanceof Error?Z.message:"PayPal payment failed.",Lt=$r(dt)??dt;fn(Lt),Bt(()=>$t.current?.(un("paypal",Lt)));return}},K=()=>new Ji("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),oe=l=>nt()?Promise.reject(K()):Promise.resolve(l),it=async l=>{if(nt())throw K();Zr||kt();let c=Kt.current,S=c?.sessionId??e,R=c?.nonce??yn.current;$.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let te;try{te=await new Yi(St,{telemetry:!1}).createSessionIntent(S,R??"",ct?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Xi,paymentMethodId:null,intentKind:g==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:or})}catch(Z){throw $.error({...$d(Z,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Z}if(nt())throw K();if(te.provider!=="paypal"||te.providerObjectType!==g)throw new Error(l);return $.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),te.providerObjectId},Xt=(l,c)=>{let S=c?.nonce??yn.current;if(!S)return;let R=c?.sessionId??e,te=aa(l)??Ur(l)??"provider_declined";new Yi(St,{telemetry:!1}).reportSessionIntentDecline(R,S,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:te}).catch(()=>{})},ee=Te;de("loadScript:scheduled (deferred 1 tick)");let H=null,B=setTimeout(()=>{if(Yt){de("loadScript:skipped (cancelled before defer ran)");return}de("loadScript:start");let l=me==="live"?"production":me,c={};g==="subscription"?c={intent:"subscription",vault:!0}:g==="order"&&(c={intent:"capture"}),H=Hd({clientId:s,currency:f,...c,...l?{environment:l}:{},...l==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let S=!1;H.then(R=>{if(S=!0,de(`loadScript:resolved inactive=${nt()} ns=${!!R} buttons=${!!R?.Buttons}`),nt())return;if(!R?.Buttons){de("FAIL: namespace missing Buttons factory"),k("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}$.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"provider_ready",durationMs:$.elapsed(je.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),$.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let te=async(G,Q)=>{if(nt()||xe.current!==ee)return;let P=G.vaultSetupToken??G.subscriptionID??G.orderID??"",Y=P?er.current.get(P):Qt.current.get(ee);if(!(!Y||!tr(Y.generation))&&on(Y.generation)){er.current.delete(P),Qt.current.delete(Y.surfaceKey),Dt("approved");try{if(se(!0),Bt(()=>mn.current?.(null)),!P)throw new Ji("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ye=En.current,Rt=oo(zn.current??[Ye?.customer?.firstName,Ye?.customer?.lastName].filter(Boolean).join(" ")),z=Nn({email:Y.accountPatch?.email?.trim()||wt.current?.trim()||Ye?.customer?.email?.trim(),firstName:Y.accountPatch?.firstName?.trim()||Rt.firstName,lastName:Y.accountPatch?.lastName?.trim()||Rt.lastName});if(!ya(z.email)||!(z.firstName||z.lastName))try{let Le=eu(await Q?.order?.get?.());z=Nn({email:Le.email||z.email,firstName:Le.firstName||z.firstName,lastName:Le.lastName||z.lastName})}catch{}if((Ge.current||Ne)&&!ya(z.email)){let Le=await F("PayPal",z);if(!Le)return;z=Le}ya(z.email)&&(Y.accountPatch=Nn({...Y.accountPatch,...z}),await Ge.current?.(z));let vn;g==="setup_token"?vn={id:P,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Xi}:ct?vn={id:P,isPaypal:!0,gateway:"paypal",paymentMethodType:Xi}:vn={id:P,isPaypal:!0},await _(vn,Y)}catch(Ye){fn(Ye instanceof Error?Ye.message:"PayPal capture failed.")}finally{nt()||se(!1)}}},Z=G=>{let Q=qe?()=>oe(qe):()=>it(G);return async()=>Sn(await Q())},dt=R.Buttons({style:{layout:"horizontal",height:Ya,tagline:!1},...re==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(G,Q)=>{if(nt()){await Q.reject();return}kt();let P=Oe.current,Y={};if(P)try{let z=await P("paypal");if(nt()){await Q.reject();return}if(!z.proceed){Kt.current=null,Qt.current.delete(ee),await Q.reject();return}Y={sessionId:z.sessionId,accountPatch:z.accountPatch,nonce:z.nonce}}catch(z){de(`onClick:runBeforeButtonClick rejected msg=${(z instanceof Error?z.message:String(z)).slice(0,120)}`),Kt.current=null,Qt.current.delete(ee),await Q.reject();return}Bt(()=>Un.current?.("paypal"));let Ye=nn(),Rt={generation:Ye,surfaceKey:ee,...Y};Kt.current=Rt,Qt.current.set(ee,Rt),pt.current={...m,attempt:Ye},await Q.resolve(),$.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),$.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),$e.current=$.startTiming()},createOrder:g==="order"?Z("Failed to create PayPal order."):void 0,createSubscription:g==="subscription"?Z("Failed to create PayPal subscription."):void 0,createVaultSetupToken:g==="setup_token"?async()=>Sn(await it("Failed to create PayPal setup token.")):void 0,onApprove:te,onCancel:()=>{if(nt())return;let G=Qt.current.get(ee)??Kt.current;G&&Qt.current.delete(G.surfaceKey),Kt.current=null,Dt("cancelled"),$.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ue.current=!0,Tn({generation:G?.generation,remount:!0,focus:!1})},onError:G=>{if(nt()||xe.current!==ee)return;let Q=G instanceof Error?G.message:"PayPal failed to render.";if(de(`onError rendered=${xn} msg=${Q.slice(0,120)}`),xn){let P=Qt.current.get(ee)??Kt.current;if(P&&!tr(P.generation)||!P&&nr())return;if(sr(Q)){on(P?.generation);return}let{errorCode:Y,popupBlocked:Ye,providerDeclined:Rt,terminalReason:z}=Li(G,{inAppBrowser:x.inAppBrowser,handoffObserved:P!=null&&Ce.current===P.generation});if(Ye&&M.markBlocked(),Dt(z),Rt){$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:z}),Xt(G,P),Bt(()=>$t.current?.(un("paypal",Q))),P&&Qt.current.delete(P.surfaceKey),Kt.current=null,on(P?.generation);return}$.error({errorCode:Y,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:z}),P&&Qt.current.delete(P.surfaceKey),Kt.current=null,Tn({generation:P?.generation,remount:!0,showRetry:!0,focus:!0}),rn(G,{code:"paypal_runtime_failed",popupBlocked:Ye,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:re,terminalReason:z});return}k(sr(Q)?"teardown":"pre_ready_callback",Q)}}),Lt=dt.isEligible();if(de(`isEligible=${Lt}`),$.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Lt){V(!1),k("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Tr=!0,Hn=dt,xt=()=>{if(!Gn||Mr||nt()||xn)return;Mr=!0,de(`container:dims ${wn(Bn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(gr=new MutationObserver(Q=>{if(!nt()){for(let P of Q)if(P.type==="childList")P.addedNodes.forEach(Y=>{if(!(Y instanceof Element))return;let Ye=Y.tagName.toLowerCase(),Rt=(Y.getAttribute("title")??"").slice(0,40),z=Ye==="iframe"?` ${ir(Y)}`:"";de(`child+ ${Ye}${Rt?` title="${Rt}"`:""}${z} dims=${wn(Y)}`)});else if(P.type==="attributes"&&P.target instanceof Element){let Y=P.target;if(Y.tagName.toLowerCase()!=="iframe")continue;let Ye=P.attributeName;(Ye==="src"||Ye==="srcdoc")&&de(`attr~ iframe ${Ye}=${Ye==="srcdoc"?`[${(Y.getAttribute("srcdoc")??"").length}ch]`:Yn(Y.getAttribute("src"))} dims=${wn(Y)}`)}}}),gr.observe(Bn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let G=Q=>{if(nt()||xn)return;let P=Bn.querySelectorAll("iframe"),Y=typeof document<"u"&&"hasStorageAccess"in document;de(`watchdog:${Q} container=${wn(Bn)} children=${Bn.childElementCount} iframes=${P.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Y} paypalNetRequests=${In.value}`),P.forEach((Ye,Rt)=>{let z=(Ye.getAttribute("title")??"").slice(0,40);de(` iframe[${Rt}] ${wn(Ye)}${z?` title="${z}"`:""} ${ir(Ye)}`);let vn=Pr(Ye);vn&&de(` ${vn}`)}),Ve.length===0&&de(" (no PayPal/zoid window errors captured)")};Ar.push(setTimeout(()=>G("3s"),3e3)),Ar.push(setTimeout(()=>G("8s"),8e3)),Ar.push(setTimeout(()=>G("15s"),15e3))},xt(),de("render:start");let Ie=$.startTiming();jn=setTimeout(()=>{nt()||xn||(de("watchdog:11s retryable render timeout"),k("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Jd);let We=dt.render(Bn);(async()=>{try{if(await We,de(`render:resolved inactive=${nt()}`),kn(),nt()){ar();return}xn=!0,V(!0),ze(!1),Mt.current?.("ready"),$.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),$.performance({stage:"checkout_render",durationMs:$.elapsed(Ie),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(G){let Q=G instanceof Error?G.message:"PayPal failed to render.";de(`render:rejected msg=${Q.slice(0,120)}`),kn(),k(sr(Q)?"teardown":"render_rejected",Q)}})()}).catch(R=>{let te=R instanceof Error?R.message:"PayPal operation failed.";de(`provider:failed msg=${te.slice(0,120)}`);let Z="script_rejected";S&&sr(te)?Z="teardown":S&&Tr&&(Z="render_rejected"),k(Z,te)})},0);return()=>{Yt=!0,clearTimeout(B),Mn&&clearTimeout(Mn),kn(),bt.current===dn&&(bt.current=null),ar(),$e.current=null,pt.current=null}},[D,St,s,f,d,g,re,ct,e,qe,Te,_e,F,Ne,de,Dt]);let tt=fe?Zi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:mt?"#fef2f2":"#f3f4f6",border:`1px solid ${mt?"#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=${Me} failed=${mt})`,At.length===0?`
|
|
1
|
+
import{a as Sl}from"./chunk-Q5RE4G4O.mjs";import{c as Nt,d as Sr,e as Xo,f as Ti,g as ll,h as cl,i as Qo,j as dl,k as rd,m as od}from"./chunk-KKA5TF5P.mjs";import{a as bl}from"./chunk-HSYSKQPT.mjs";import{a as ta,b as Oa,c as xi,d as Bi,e as Fi,f as fl,g as gl,h as hl,i as Pl,j as vl,k as Cl}from"./chunk-H4MQCBX4.mjs";import{a as Ba,b as Mi,c as ul,d as Ai,e as go,f as pl,g as zr,h as Fa,i as yl,j as ea,k as Da,l as ml}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as Cf}from"@flopay/shared";import{PaymentAPI as Cs}from"@flopay/js";import{FloPayError as Ca,resolveBillingApiUrl as Op,resolveButtonsLayoutTheme as Np,resolveTheme as Lp}from"@flopay/shared";import{useCallback as Fr,useEffect as No,useMemo as ba,useRef as Lo,useState as zo}from"react";import{Fragment as bo,jsx as Kn,jsxs as wl}from"react/jsx-runtime";function ad(){return wl(bo,{children:[wl("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:[Kn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Kn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Kn("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:Kn("path",{d:"M9 18l6-6-6-6"})})]})}function id(){return Kn(bo,{children:"Go back"})}function sd(){return Kn(bo,{children:"Secure card checkout"})}function ho(e){return e!==void 0&&(e===""||e===null||e===!1)}function Po({content:e}){return Kn(bo,{children:e===void 0?Kn(ad,{}):e})}function vo({content:e}){return Kn(bo,{children:e===void 0?Kn(id,{}):e})}function na({content:e}){return Kn(bo,{children:e===void 0?Kn(sd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as ld,canRecoverHostedCardForm as cd,classifyTelemetryFailure as dd,FloPayError as kn,isCardHolderNamePlaceholder as ud,isMoneySettledOutcome as pd,isMountableVaultBlock as yd,isSetupIntentClientSecret as md,isValidEmail as fd,resolveSetupFutureUsage as gd,resolveWalletModeOptions as hd}from"@flopay/shared";import{canRecoverHostedCardForm as Qr,hasServerSideCardGateway as Bl}from"@flopay/shared";import{splitFullName as aa}from"@flopay/shared";import{applyFriendlyMessageOverride as wo}from"@flopay/shared";var Pd="Checkout is temporarily unavailable. Please try again later.";function Di(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof kn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function vd(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 kl(){return new kn(Pd,"api_error",{code:"CheckoutInitializationFailed"})}function Il(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(yd(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||cd(o))||t&&e?.data.paypal?.publishableKey)}function Rl(e,t){if(t&&(!(e instanceof kn)||e.type==="authentication_error"))return Di(e);if(!(e instanceof kn&&vd(e))){if(!t&&!(e instanceof kn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...dd(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof kn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof kn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Co(e,t,n,o={}){let a;return(i={})=>{if(a!==void 0)return a;let s={...o,...i,email:i.email?.trim()||o.email?.trim()},c=ud(s.firstName,s.lastName);if(!fd(s.email))return Promise.reject(new kn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let f={};for(let[C,E]of Object.entries(s)){if(c&&C.endsWith("Name")||typeof E!="string")continue;let k=E.trim();k&&(f[C]=k)}return a=e.claimCheckoutSession(t,n,{accountData:f}),a.catch(()=>{}),a}}function El(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Oi(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 _l(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],o=n.reduce((i,s)=>i+(s.overrideAmount??s.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(o*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:n.map((i,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Ni(e,t){return t?{...e,...t}:e}function un(e,t,n){let o=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:o,...a?{code:a}:{},...i?{declineCode:i}:{},...s?{sessionId:s}:{}}}function Ur(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Mr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Ar(e){return e?.status==="authorized"||e?.status==="complete"}function qr(e,t){if(e.data.session)return e.data.session;let n=e.raw,o=n?.latestTransactionAttempt?.result,a=n?.status==="authorized"||o==="AUTHORIZED";return a||n?.status==="completed"||o==="SUCCESS"?{...t,status:a?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function Tl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Na(e){let t=Tl(e);return new kn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function La(e){return e instanceof kn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function So(e){return Tl(e)?new kn("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new kn("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new kn(ld,"api_error",{code:"checkout_processing_timeout"})}function ra(e,t){return e==="processing"||pd(e,t)}function Ml(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Al(e,t){let n=e;if(md(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new kn(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:o,error:a}=await n.retrievePaymentIntent(t);if(a)throw new kn(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var bd=["apple_pay","google_pay"];function xl(e,t="automatic",n){let o=gd(n,bd,"wallet");return{...hd(e,t),paymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var Cd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Li(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:Cd.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function oa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Pp,PaymentAPI as ai,SESSION_CREATE_TELEMETRY as vp}from"@flopay/js";import{buildCheckoutDisplayData as bp,classifyTelemetryFailure as Dc,FloPayError as bn,isDetachedSessionEligible as Cp,isMountableVaultBlock as Sp,resolveBillingApiUrl as wp,resolveButtonsLayoutTheme as kp,resolveDirectPaypalConfig as Oc,resolveIdempotencyKey as _c,resolveCheckoutLogLayout as Ip,resolveTheme as Nc,SDK_VERSION as Lc,telemetryStatusClass as Rp}from"@flopay/shared";import ps,{useCallback as vn,useEffect as pr,useMemo as Yn,useRef as At,useState as Gt}from"react";import{createContext as Fl}from"react";var Gn=Fl({flopay:null,paypalFlopay:null,billingApiUrl:""}),cr=Fl({session:null,loading:!1,error:null});import{PaymentAPI as Ui}from"@flopay/js";import{buildPayPalProcessPaymentRequest as Od,buildPayPalSessionIntentRequest as Nd,buildPayPalTokenizedBody as Ld,classifyTelemetryFailure as zd,describePayPalProcessFailure as Ud,FloPayError as qi,friendlyPayPalFailureMessage as qd,generateIdempotencyKey as jd,isPayPalTeardownMessage as $d,isValidEmail as jl,mergePayPalPayerIdentity as Wd,needsPayPalPayerDetails as Hd,normalizeGatewayEnvironment as Vd,paypalProviderIdentityRequired as $l,resolvePayPalApprovalIdentity as Kd,resolvePayPalDeclineReason as Gd,SDK_VERSION as Yd,usesPayPalVaultedChannel as Jd}from"@flopay/shared";import{loadScript as Zd}from"@paypal/paypal-js";import{useCallback as wr,useContext as Xd,useEffect as Lt,useMemo as ca,useRef as ot,useState as Wr}from"react";import{compactBuyerIdentity as Sd,isValidEmail as wd}from"@flopay/shared";import{useCallback as Dl,useEffect as kd,useRef as Ol,useState as Ll}from"react";import{compactBuyerIdentity as dr}from"@flopay/shared";import{jsx as Nl,jsxs as ia}from"react/jsx-runtime";function ko(){let[e,t]=Ll(null),n=Ol(null),o=Ol(0),a=Dl((s,c)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:c}),new Promise(f=>{n.current=f})),[]),i=Dl(s=>{let c=n.current;n.current=null,t(null),c?.(s)},[]);return kd(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function Io({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[s,c]=Ll(e.email?.trim()??""),f=wd(s.trim());return ia("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[ia("div",{style:{fontWeight:700},children:["Continue with ",t]}),ia("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Nl("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:C=>c(C.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),ia("div",{style:{display:"flex",gap:"0.5rem"},children:[o&&Nl("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),ia("button",{type:"button",disabled:!f||a,onClick:()=>{n(Sd({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as Id}from"@flopay/shared";import{useContext as za}from"react";function jr(){return za(Gn).flopay}function zi(){return za(Gn).paypalFlopay??null}function Rd(){return za(cr)}function zl(){return za(Gn).billingApiUrl||Id()}import{FLO_INSTRUMENT_ONCE_NAMES as Ed,invokeMerchantCallback as _d,projectFloInstrument as Td}from"@flopay/shared";import{useCallback as Md,useRef as Ua}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Ul}from"@flopay/shared";function Ro(e,t){let n=Ua(e);n.current=e;let o=Ua(new Set),a=Ua(t),i=Ua(t);return Xo(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),Md(s=>{if(i.current!==t)return;let c=Td(s);if(c){if(Ed.has(c.name)){if(o.current.has(c.name))return;o.current.add(c.name)}_d(()=>n.current?.(c))}},[t])}import{createContext as Ad}from"react";var sa=Ad(null);function qa(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var xd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Bd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Fd(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function Dd(e){let t=Fd(),n=(a,i)=>a?a.bind(e):i,o=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:o,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,o()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function ja(e){let t=globalThis[Bd];return Dd(t?.(e)??{})}function pn(e){if(e)return e[xd]}import{useCallback as $r,useEffect as ql,useRef as eo}from"react";function la(e,t){let n=eo(0),o=eo(null),a=eo(null),i=eo(e),s=eo(t?.onHandoffObserved),c=eo(t?.defersMissingTerminal),f=eo(t?.onMissingTerminalDeferred);ql(()=>{i.current=e,s.current=t?.onHandoffObserved,c.current=t?.defersMissingTerminal,f.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let C=$r((v=a.current)=>{v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),E=$r(v=>{C();let P=n.current+1;return n.current=P,o.current=null,a.current={generation:P,method:v,timer:null,yieldedControl:!1},P},[C]),k=$r(v=>{let P=a.current;return v!==void 0&&P?.generation!==v?!1:(C(P),a.current=null,(v===void 0||o.current===v)&&(o.current=null),!0)},[C]),z=$r(v=>{let P=a.current,he=v??P?.generation??n.current;(v===void 0||P?.generation===v)&&(C(P),a.current=null),o.current=he},[C]),ne=$r(v=>o.current===(v??n.current),[]),O=$r(v=>a.current?.generation===v&&o.current!==v,[]),ve=$r(()=>{let v=a.current;v&&(C(v),!v.yieldedControl&&(v.yieldedControl=!0,s.current?.(v.method)))},[C]),V=$r(()=>{let v=a.current;!v?.yieldedControl||document.visibilityState!=="visible"||(C(v),v.timer=setTimeout(()=>{if(v.timer=null,a.current?.generation===v.generation){if(c.current?.(v.method)){f.current?.(v.method,v.generation);return}a.current=null,o.current=v.generation,i.current(v.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},ul))},[C]);return ql(()=>{let v=()=>{document.visibilityState==="visible"?V():ve()};return document.addEventListener("visibilitychange",v),window.addEventListener("blur",ve),window.addEventListener("focus",V),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("blur",ve),window.removeEventListener("focus",V),C()}},[C,ve,V]),{startAttempt:E,finishAttempt:k,invalidateAttempt:z,isAttemptInvalidated:ne,isAttemptCurrent:O,generationRef:n}}import{jsx as to,jsxs as ji}from"react/jsx-runtime";var $a=45,Qd=1e3,eu=11e3,tu={width:"100%",minHeight:$a,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"},nu={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 ru(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:nu[e.kind]??null}}function Wl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":pl(t)?"paypal_init_timeout":"paypal_init_failure"}function ou(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Hl({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:s,environment:c,currency:f,isSubscription:C,providerObjectType:E,approvalPresentation:k,onTokenizedBody:z,onComplete:ne,onErrorChange:O,onDecline:ve,onTechnicalFailure:V,isProcessing:v=!1,onLoadStateChange:P,onInitializationStateChange:he,allowAutomaticRetry:N=!0,onButtonClick:Ie,runBeforeButtonClick:Y,session:Fe,existingOrderId:lt,telemetry:ze,telemetryContext:ct,onInstrument:zt,debug:pe=!1}){let Te=jr(),Pt=Ro(zt,e),Re=ca(()=>{if(Te)return null;let u=ja({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Yd,enabled:ze!==!1});return u.setCheckoutContext(ct??{}),u.beginCheckout(ct??{}),u},[n,Te,ze,ct?.checkoutMode,ct?.layout]),He=ca(()=>pn(Te),[Te]);Lt(()=>()=>{Re&&Re.flush().catch(()=>{}).finally(()=>Re.destroy())},[Re]);let ke=ca(()=>({error:u=>{He?He.error(u):Re?.error(u),Pt({class:"technical_error",errorCode:u.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":u.errorCode,requestCategory:u.requestCategory,provider:u.provider})},log:u=>{He?He.log(u):Re?.log(u),Pt({class:"lifecycle",name:u.name,provider:u.provider})},performance:u=>{He?He.performance(u):Re?.performance(u)},terminal:u=>{He?He.terminal(u):Re?.terminal(u)},startTiming:()=>He?.now()??Re?.now()??0,elapsed:u=>He?.elapsed(u)??Math.max(0,(Re?.now()??u)-u)}),[Pt,He,Re]),Q=ot(null),je=ot(0),$e=ot(null),pt=ot(null),be=ot(null),ye=Xd(sa),re=ot(null);re.current||(re.current=qa());let M=ye??re.current,Ce=ot(null),Ue=ot(!1),[Me,U]=Wr(!1),[vt,qe]=Wr(!1),[Ee,Je]=Wr(0),Ae=ot(0),[Qe,De]=Wr(!1),bt=ot(!1),Yt=ot(!1),[yt,Et]=Wr(!1),[I,ee]=Wr(!1),{request:Oe,collect:F,finish:Se}=ko(),mt=ot({sessionId:e,required:$l(o,Fe)});mt.current.sessionId!==e&&(mt.current={sessionId:e,required:$l(o,Fe)});let Ne=mt.current.required,wt=ca(()=>n.replace(/\/+$/,""),[n]),d=Fe?.gateways?.paypal?.providerObjectType??E,m=d??(C?"subscription":"order"),[A]=Wr(ea),T=Fe?.gateways?.paypal?.approvalPresentation??k,J=Da(A,T==="app_switch"?"app_switch":void 0,m),ft=Jd(d),me=ca(()=>JSON.stringify([wt,s,f,c??"",m,ft,J,e,lt??""]),[wt,s,f,c,lt,m,ft,J,e]),We=ot(me),H=We.current!==me,Ut=ot(pe),Ct=ot(null),[_t,at]=Wr([]),oe=wr(u=>{Ut.current&&at(xe=>[...xe,`${new Date().toISOString().slice(11,23)} ${u}`])},[]);Lt(()=>{Ut.current=pe,pe&&oe("debug:enabled"),Ct.current?.setEnabled(pe)},[oe,pe]);let In=ot(z),Bn=ot(ne),yn=ot(O),qt=ot(ve),Fn=ot(V),Dn=ot(Ie),hn=ot(P),Tt=ot(he),Ve=ot(i),Le=ot(Y),Rn=ot(Fe),kt=ot(o),On=ot(a),mn=ot(t),jt=ot(null),Qt=ot(new Map),Jn=ot(new Map),$n=ot(!1);Lt(()=>($n.current=!0,()=>{$n.current=!1}),[]),Lt(()=>{In.current=z},[z]),Lt(()=>{Ve.current=i},[i]),Lt(()=>{Bn.current=ne},[ne]),Lt(()=>{yn.current=O},[O]),Lt(()=>{qt.current=ve},[ve]),Lt(()=>{Fn.current=V},[V]),Lt(()=>{Dn.current=Ie},[Ie]),Lt(()=>{hn.current=P},[P]),Lt(()=>{Tt.current=he},[he]),Lt(()=>{Le.current=Y},[Y]),Lt(()=>{Rn.current=Fe},[Fe]),Lt(()=>{kt.current=o},[o]),Lt(()=>{On.current=a},[a]),Lt(()=>{mn.current=t},[t]),Lt(()=>{Ae.current=Ee},[Ee]),Lt(()=>{Qe&&Ce.current?.focus()},[Qe,Ee]);let en=wr(()=>{window.setTimeout(()=>{Ce.current?.focus()},0)},[]),xt=wr(()=>{U(!1),Je(u=>u+1)},[]),Cn=wr(()=>{De(!1),(Q.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Q.current)?.focus?.()},[]);Lt(()=>{!Me||!Ue.current||(Ue.current=!1,Cn())},[Cn,Me,Ee]);let ln=wr((u,xe)=>{let L=xe?.popupBlocked??zr(u);L&&M.markBlocked();let Pn=Ba("PayPal",L,A.inAppBrowser),Nn=Fn.current;if(Nn){let Jt=L&&A.inAppBrowser?new qi(Pn,"api_error",{code:xe?.code??"paypal_popup_blocked"}):u;Nn("paypal",Jt,xe);return}yn.current?.(Pn)},[M,A.inAppBrowser]),Ft=wr(u=>{let xe=$e.current,L=pt.current;xe===null||!L||(ke.log({...L,popupCapability:M.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:u}),ke.performance({...L,popupCapability:M.current(),stage:"overlay_return",durationMs:ke.elapsed(xe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:u}),$e.current=null)},[M,ke]),fn=wr((u,xe,L)=>{let Pn=pt.current;Ft("overlay_timeout"),Pn&&ke.error({...Pn,popupCapability:M.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),ln(xe,{...L,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:J,terminalReason:"overlay_timeout"}),De(!0),xt(),en()},[Ft,en,ln,M,J,xt,ke]),Dt=wr(()=>{M.markAvailable();let u=pt.current;u&&(be.current=u.attempt,ke.log({...u,popupCapability:M.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[M,ke]),{finishAttempt:on,generationRef:Bt,invalidateAttempt:ae,isAttemptCurrent:Zn,isAttemptInvalidated:Xn,startAttempt:Qn}=la(fn,{onHandoffObserved:Dt}),tn=wr(()=>(De(!1),Qn("paypal")),[Qn]),En=wr(u=>{ae(u?.generation),u?.showRetry&&De(!0),u?.remount&&xt(),u?.focus!==!1&&en()},[en,ae,xt]),Sn=u=>{let xe=jt.current;return xe&&Jn.current.set(u,xe),u};Lt(()=>{We.current!==me&&(We.current=me,bt.current=!1,Yt.current=!1,U(!1),qe(!1),Et(!1),Tt.current?.("loading"))},[me]),Lt(()=>{Nt(()=>hn.current?.(Me&&!yt))},[Me,yt]);let ce=Vd(c);Lt(()=>{let u={attempt:Bt.current+1,inAppBrowser:A.inAppBrowser,appFamily:A.appFamily,popupCapability:M.current(),presentationMode:J},xe=()=>({...pt.current??u,popupCapability:M.current()}),L={error:l=>ke.error({...l,...xe()}),log:l=>ke.log({...l,...xe()}),performance:l=>ke.performance({...l,...xe()}),terminal:l=>ke.terminal({...l,...xe()}),startTiming:ke.startTiming,elapsed:ke.elapsed},Pn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",Nn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(oe(`mount clientId=${Pn} env=${c??"(unset)"}\u2192${ce??"live"} ccy=${f} sub=${C}`),oe(`ua=${Nn.slice(0,80)}${Nn.length>80?"\u2026":""}`),!s){oe("FAIL: clientId empty \u2014 gateway misconfigured"),Et(!0),L.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(!Q.current){oe("FAIL: containerRef not attached");return}je.current=L.startTiming(),L.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Jt=!1,_n=!1,nt=()=>Jt||_n,yr=ft?m:void 0,Dr,It=!1,Ln=()=>{Dr=jd(),Dr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),It=!0},er=null,tr=!1,$t=null,mr=!1,fr=()=>{!$t||mr||(mr=!0,$t.close().catch(()=>{}))},Tn=!1,gr=!1,Wn=Q.current,hr=null,Er=null,zn=[],nr=null,rr=!1,Mt=!1,Un=null,wn=l=>{if(!l||typeof l.getBoundingClientRect!="function")return"(no rect)";let y=l.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},or=l=>{if(!l)return"(empty)";try{let y=new URL(l,typeof window>"u"?"https://localhost":window.location.href),h=y.pathname.toLowerCase();return h.includes("checkcaptcha")||h.includes("captcha")?`CAPTCHA(${y.host}${h})`:h.includes("risk")||h.includes("challenge")?`RISK(${y.host}${h})`:h.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${h}`.slice(0,100)}catch{return l.slice(0,80)}},ar=l=>{let y=l.getAttribute("src"),h=l.getAttribute("srcdoc"),$=l.getAttribute("name"),le=l.getAttribute("sandbox"),Pe=[];return y&&Pe.push(`src=${or(y)}`),h&&Pe.push(`srcdoc[${h.length}ch]`),!y&&!h&&Pe.push("src=(empty) srcdoc=(empty)"),$&&Pe.push(`name=${$.slice(0,40)}`),le!==null&&Pe.push(`sandbox="${le.slice(0,40)}"`),Pe.join(" ")},tt=l=>{if(!(l instanceof HTMLIFrameElement))return"";try{let y=l.contentDocument;if(!y)return"cd=null";let h=y.body?.children.length??0,$=y.body?.innerHTML.length??0,le=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${h}children,${$}ch] head[${le}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},nn=[],cn=l=>{if(nt())return;let y=l.message??String(l.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(oe(`window:error ${y.slice(0,140)}`),nn.push(y))},Mn=l=>{if(nt())return;let y=l.reason instanceof Error?l.reason.message:String(l.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(oe(`window:rejection ${y.slice(0,140)}`),nn.push(y))},Or={value:0},Pr=()=>{hr?.disconnect(),hr=null,Er?.disconnect(),Er=null;for(let l of zn.splice(0))clearTimeout(l);Mt=!1,rr&&typeof window<"u"&&(window.removeEventListener("error",cn),window.removeEventListener("unhandledrejection",Mn)),rr=!1},_r=()=>{if(!(rr||nt()||Tn)){if(rr=!0,nn.length=0,Or.value=0,typeof window<"u"&&(window.addEventListener("error",cn),window.addEventListener("unhandledrejection",Mn)),typeof PerformanceObserver<"u")try{Er=new PerformanceObserver(l=>{if(!nt())for(let y of l.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;Or.value+=1;let h=Math.round(y.duration);oe(`net ${h}ms ${y.name.slice(0,90)}`)}}),Er.observe({type:"resource",buffered:!0})}catch{}Un?.()}},Hn=()=>{nr&&(clearTimeout(nr),nr=null)},rn=()=>{Pr(),Hn()},Nr={setEnabled:l=>{l?_r():Pr()}};Ct.current=Nr,Ut.current&&_r();let an=$d,w=l=>{if(nt()||an(l))return;let y=wo(l)??l;Nt(()=>yn.current?.(y))},b=(l,y)=>{if(Jt||tr)return;tr=!0,_n=!0,rn(),fr();let h=ru({kind:l,generationActive:!0,automaticRetryAllowed:N,automaticRetryUsed:bt.current});if(h.action==="retry"){bt.current=!0,U(!1),ee(!1),qe(!0),Tt.current?.("retrying"),er=setTimeout(()=>{Jt||Je($=>$+1)},Qd);return}if(U(!1),ee(!1),qe(!1),Et(!0),h.action!=="ignore"){if(Tt.current?.("exhausted"),h.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",y);return}if(h.report){let $=Mi({code:Wl(l,y),message:y},{inAppBrowser:A.inAppBrowser,handoffObserved:!1});$.popupBlocked&&M.markBlocked(),L.error({errorCode:$.popupBlocked?$.errorCode:h.report.errorCode,stage:h.report.stage,operationOutcome:h.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:$.terminalReason})}Yt.current||(Yt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Wl(l,y)))}};Et(!1);let j=async(l,y=jt.current)=>{if(nt())return;let h=y?.sessionId??e;if(In.current){await In.current(l,{sessionId:h,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let $=L.startTiming();L.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let le=()=>{L.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"processing",durationMs:L.elapsed($),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Pe=Od({body:l,sessionId:h,nonce:y?.nonce??mn.current,accountPatch:y?.accountPatch,session:Rn.current,email:kt.current}),te=await new Ui(wt,{telemetry:!1}).processPayment(Pe.userId,Pe.params);if(te.ok){if(_n||Jt&&$n.current)return;le(),L.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Nt(()=>Bn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(nt())return;let we=await te.json().catch(()=>null),Be=Ud(we),rt=Be.message;le(),te.status===400&&(typeof we?.declineCode=="string"||!Array.isArray(we?.fields))?L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):te.status===400||te.status===422?L.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):L.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ou(te.status),failureCategory:te.status>=500?"server_error":void 0}),w(rt),Nt(()=>qt.current?.(un("paypal",rt,{code:Be.code,declineCode:Be.declineCode})));return}catch(Pe){if(nt())return;le(),L.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ht=qd(Pe instanceof Error?Pe.message:void 0);w(Ht),Nt(()=>qt.current?.(un("paypal",Ht)));return}},K=()=>new qi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),it=l=>nt()?Promise.reject(K()):Promise.resolve(l),Wt=async l=>{if(nt())throw K();It||Ln();let y=jt.current,h=y?.sessionId??e,$=y?.nonce??mn.current;L.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let le;try{le=await new Ui(wt,{telemetry:!1}).createSessionIntent(h,$??"",Nd(yr),{idempotencyKey:Dr})}catch(Pe){throw L.error({...zd(Pe,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Pe}if(nt())throw K();if(le.provider!=="paypal"||le.providerObjectType!==m)throw new Error(l);return L.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),le.providerObjectId},de=(l,y)=>{let h=y?.nonce??mn.current;if(!h)return;let $=y?.sessionId??e,le=Gd(l);new Ui(wt,{telemetry:!1}).reportSessionIntentDecline($,h,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:le}).catch(()=>{})},x=Ee;oe("loadScript:scheduled (deferred 1 tick)");let B=null,R=setTimeout(()=>{if(Jt){oe("loadScript:skipped (cancelled before defer ran)");return}oe("loadScript:start");let l=ce==="live"?"production":ce,y={};m==="subscription"?y={intent:"subscription",vault:!0}:m==="order"&&(y={intent:"capture"}),B=Zd({clientId:s,currency:f,...y,...l?{environment:l}:{},...l==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let h=!1;B.then($=>{if(h=!0,oe(`loadScript:resolved inactive=${nt()} ns=${!!$} buttons=${!!$?.Buttons}`),nt())return;if(!$?.Buttons){oe("FAIL: namespace missing Buttons factory"),b("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}L.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"provider_ready",durationMs:L.elapsed(je.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),L.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let le=async(Z,S)=>{if(nt()||Ae.current!==x)return;let q=Z.vaultSetupToken??Z.subscriptionID??Z.orderID??"",Ke=q?Jn.current.get(q):Qt.current.get(x);if(!(!Ke||!Zn(Ke.generation))&&on(Ke.generation)){Jn.current.delete(q),Qt.current.delete(Ke.surfaceKey),Ft("approved");try{if(ee(!0),Nt(()=>yn.current?.(null)),!q)throw new qi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ge=Kd({accountPatch:Ke.accountPatch,email:kt.current,billingName:On.current,session:Rn.current});if(Hd(ge))try{ge=Wd(ge,await S?.order?.get?.())}catch{}if((Ve.current||Ne)&&!jl(ge.email)){let dt=await F("PayPal",ge);if(!dt)return;ge=dt}jl(ge.email)&&(Ke.accountPatch=dr({...Ke.accountPatch,...ge}),await Ve.current?.(ge));let _e=Ld(q,yr);await j(_e,Ke)}catch(ge){w(ge instanceof Error?ge.message:"PayPal capture failed.")}finally{nt()||ee(!1)}}},Pe=Z=>{let S=lt?()=>it(lt):()=>Wt(Z);return async()=>Sn(await S())},Ht=$.Buttons({style:{layout:"horizontal",height:$a,tagline:!1},...J==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Z,S)=>{if(nt()){await S.reject();return}Ln();let q=Le.current,Ke={};if(q)try{let dt=await q("paypal");if(nt()){await S.reject();return}if(!dt.proceed){jt.current=null,Qt.current.delete(x),await S.reject();return}Ke={sessionId:dt.sessionId,accountPatch:dt.accountPatch,nonce:dt.nonce}}catch(dt){oe(`onClick:runBeforeButtonClick rejected msg=${(dt instanceof Error?dt.message:String(dt)).slice(0,120)}`),jt.current=null,Qt.current.delete(x),await S.reject();return}Nt(()=>Dn.current?.("paypal"));let ge=tn(),_e={generation:ge,surfaceKey:x,...Ke};jt.current=_e,Qt.current.set(x,_e),pt.current={...u,attempt:ge},await S.resolve(),L.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),$e.current=L.startTiming()},createOrder:m==="order"?Pe("Failed to create PayPal order."):void 0,createSubscription:m==="subscription"?Pe("Failed to create PayPal subscription."):void 0,createVaultSetupToken:m==="setup_token"?async()=>Sn(await Wt("Failed to create PayPal setup token.")):void 0,onApprove:le,onCancel:()=>{if(nt())return;let Z=Qt.current.get(x)??jt.current;Z&&Qt.current.delete(Z.surfaceKey),jt.current=null,Ft("cancelled"),L.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ue.current=!0,En({generation:Z?.generation,remount:!0,focus:!1})},onError:Z=>{if(nt()||Ae.current!==x)return;let S=Z instanceof Error?Z.message:"PayPal failed to render.";if(oe(`onError rendered=${Tn} msg=${S.slice(0,120)}`),Tn){let q=Qt.current.get(x)??jt.current;if(q&&!Zn(q.generation)||!q&&Xn())return;if(an(S)){on(q?.generation);return}let{errorCode:Ke,popupBlocked:ge,providerDeclined:_e,terminalReason:dt}=Mi(Z,{inAppBrowser:A.inAppBrowser,handoffObserved:q!=null&&be.current===q.generation});if(ge&&M.markBlocked(),Ft(dt),_e){L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:dt}),de(Z,q),Nt(()=>qt.current?.(un("paypal",S))),q&&Qt.current.delete(q.surfaceKey),jt.current=null,on(q?.generation);return}L.error({errorCode:Ke,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:dt}),q&&Qt.current.delete(q.surfaceKey),jt.current=null,En({generation:q?.generation,remount:!0,showRetry:!0,focus:!0}),ln(Z,{code:"paypal_runtime_failed",popupBlocked:ge,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:J,terminalReason:dt});return}b(an(S)?"teardown":"pre_ready_callback",S)}}),te=Ht.isEligible();if(oe(`isEligible=${te}`),L.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!te){U(!1),b("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}gr=!0,$t=Ht,Un=()=>{if(!rr||Mt||nt()||Tn)return;Mt=!0,oe(`container:dims ${wn(Wn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(hr=new MutationObserver(S=>{if(!nt()){for(let q of S)if(q.type==="childList")q.addedNodes.forEach(Ke=>{if(!(Ke instanceof Element))return;let ge=Ke.tagName.toLowerCase(),_e=(Ke.getAttribute("title")??"").slice(0,40),dt=ge==="iframe"?` ${ar(Ke)}`:"";oe(`child+ ${ge}${_e?` title="${_e}"`:""}${dt} dims=${wn(Ke)}`)});else if(q.type==="attributes"&&q.target instanceof Element){let Ke=q.target;if(Ke.tagName.toLowerCase()!=="iframe")continue;let ge=q.attributeName;(ge==="src"||ge==="srcdoc")&&oe(`attr~ iframe ${ge}=${ge==="srcdoc"?`[${(Ke.getAttribute("srcdoc")??"").length}ch]`:or(Ke.getAttribute("src"))} dims=${wn(Ke)}`)}}}),hr.observe(Wn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Z=S=>{if(nt()||Tn)return;let q=Wn.querySelectorAll("iframe"),Ke=typeof document<"u"&&"hasStorageAccess"in document;oe(`watchdog:${S} container=${wn(Wn)} children=${Wn.childElementCount} iframes=${q.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Ke} paypalNetRequests=${Or.value}`),q.forEach((ge,_e)=>{let dt=(ge.getAttribute("title")??"").slice(0,40);oe(` iframe[${_e}] ${wn(ge)}${dt?` title="${dt}"`:""} ${ar(ge)}`);let Ze=tt(ge);Ze&&oe(` ${Ze}`)}),nn.length===0&&oe(" (no PayPal/zoid window errors captured)")};zn.push(setTimeout(()=>Z("3s"),3e3)),zn.push(setTimeout(()=>Z("8s"),8e3)),zn.push(setTimeout(()=>Z("15s"),15e3))},Un(),oe("render:start");let Be=L.startTiming();nr=setTimeout(()=>{nt()||Tn||(oe("watchdog:11s retryable render timeout"),b("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},eu);let rt=Ht.render(Wn);(async()=>{try{if(await rt,oe(`render:resolved inactive=${nt()}`),rn(),nt()){fr();return}Tn=!0,U(!0),qe(!1),Tt.current?.("ready"),L.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"checkout_render",durationMs:L.elapsed(Be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Z){let S=Z instanceof Error?Z.message:"PayPal failed to render.";oe(`render:rejected msg=${S.slice(0,120)}`),rn(),b(an(S)?"teardown":"render_rejected",S)}})()}).catch($=>{let le=$ instanceof Error?$.message:"PayPal operation failed.";oe(`provider:failed msg=${le.slice(0,120)}`);let Pe="script_rejected";h&&an(le)?Pe="teardown":h&&gr&&(Pe="render_rejected"),b(Pe,le)})},0);return()=>{Jt=!0,clearTimeout(R),er&&clearTimeout(er),rn(),Ct.current===Nr&&(Ct.current=null),fr(),$e.current=null,pt.current=null}},[N,wt,s,f,c,m,J,ft,e,lt,Ee,ke,F,Ne,oe,Ft]);let et=pe?ji("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:yt?"#fef2f2":"#f3f4f6",border:`1px solid ${yt?"#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=${Me} failed=${yt})`,_t.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return mt&&!X?fe?io("div",{children:tt}):null:Zi("div",{children:[tt,De&&io(Eo,{identity:De.identity,methodLabel:De.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:we,onCancel:()=>we(null)}),Zi("div",{"aria-hidden":Pt||De?!0:void 0,style:Pt||De?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ya},children:[!Me&&!Pt&&io("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"}}),io("div",{ref:ie,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ya,display:"flex",opacity:Me?1:0},"aria-busy":E||h},Te)]},Te),et&&io("button",{ref:Se,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:tn,style:Xd,children:"Try PayPal again"})]})}function Ja(e){return io(tc,{...e})}function nc(e){return io(tc,{...e})}import{jsx as rc,jsxs as nu}from"react/jsx-runtime";function Ao({children:e,margin:t,icon:n=!0,styleOverride:r}){return nu("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,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&rc("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:rc("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]})}import{foldIntoProducts as ru,resolveSessionCurrency as ou}from"@flopay/shared";function Mo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var es=":idempotency-key";function ts(e,t){if(!Mo())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function ns(e,t){if(!Mo())return null;try{let n=window.sessionStorage.getItem(e+es);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function Xa(e,t){if(Mo())try{ts(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Za(e,t){if(Xa(e,t),!!Mo())try{ns(e,t)&&window.sessionStorage.removeItem(e+es)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Qa(e,t,n,r){if(Mo())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function ei(e,t,n){if(Mo())try{window.sessionStorage.setItem(e+es,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Qi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function au(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([s],[d])=>s<d?-1:s>d?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let s=0;s<t.length;s++){let d=t.charCodeAt(s);n=r^Math.imul(n^d,597399067),r=o^Math.imul(r^d,2869860233),o=i^Math.imul(o^d,951274213),i=n^Math.imul(i^d,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(i^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),i=Math.imul(r^i>>>19,2716044179),n^=r^o^i,r^=n,o^=n,i^=n,[n,r,o,i].map(s=>(s>>>0).toString(16).padStart(8,"0")).join("")}function xo(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>Qi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Qi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Qi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:au(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function oc(e,t=!1){let n=xo(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function ac(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=ou(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??ru(t.items,t.subscriptions)).map(u=>({type:u.type,code:u.code??u.providerItemId??u.providerPlanId??"",quantity:u.quantity??1,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount??null,currency:(u.currency??o).toUpperCase()})).sort((u,w)=>`${u.code}:${u.type??""}`.localeCompare(`${w.code}:${w.type??""}`)),s=e.products.map(u=>({type:u.type,code:u.code??"",quantity:u.quantity??1,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount??null,currency:(u.currency??e.currency).toUpperCase()})).sort((u,w)=>`${u.code}:${u.type??""}`.localeCompare(`${w.code}:${w.type??""}`));if(i.length!==s.length)return!1;for(let[u,w]of i.entries()){let b=s[u];if(b===void 0||w.code!==b.code||w.type!==void 0&&w.type!==b.type||w.quantity!==b.quantity||w.totalAmount!==b.totalAmount||w.overrideAmount!==b.overrideAmount||w.currency!==b.currency)return!1}let d=[...t.couponCodes??[]].sort(),f=[...e.coupons??[]].sort();return d.length===f.length&&d.every((u,w)=>u===f[w])}import{resolveBillingApiUrl as iu}from"@flopay/shared";import{useEffect as Gr,useMemo as su,useRef as ic,useState as sc}from"react";import{jsx as lu}from"react/jsx-runtime";function ti({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,s]=sc(e instanceof Promise?null:e),[d,f]=sc(t instanceof Promise||!t?null:t),u=ic(null),w=ic(null),b=To(r);Gr(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),Gr(()=>{i&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,i]),Gr(()=>{if(i)return pn(i)?.subscribe?.(b)},[b,i]),Gr(()=>{if(!(!d||d===i))return pn(d)?.subscribe?.(b)},[b,i,d]),Gr(()=>{if(!i)return;let I=pn(i);return u.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Gr(()=>{let I=!1;return e instanceof Promise?e.then(N=>{I||s(N)},()=>{I||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{I=!0}},[b,e]),Gr(()=>{let I=!1;if(!t){f(null);return}return t instanceof Promise?t.then(N=>{I||f(N)},()=>{I||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):f(t),()=>{I=!0}},[b,t]),Gr(()=>{if(!i||w.current===i)return;w.current=i;let I=pn(i);I?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(u.current??0),durationMode:"machine"})},[b,i]);let j=iu(n?.billingApiUrl),L=su(()=>({flopay:i,paypalFlopay:d,billingApiUrl:j,emitInstrument:b}),[i,d,j,b]);return lu(Zn.Provider,{value:L,children:o})}var ni="flopay_recent_completion_";function Bo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ni+e,JSON.stringify(t))}catch{}}function rs(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ni+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ni+e),!1):!0}catch{return!1}}async function ri(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{loadFloPay as lc,PaymentAPI as ai}from"@flopay/js";import{classifyPaymentRejection as cu,FloPayError as Ct,isAuthorizationOnlySession as du,isMountableVaultBlock as uu,isSetupIntentClientSecret as pu,normalizeCheckoutFailureOutcome as cc,THREE_DS_CHALLENGE_WINDOW_MS as uc}from"@flopay/shared";var ha="card",mu=1e3;async function yu(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function fu(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:s??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:o??null}}function Yr(e){return new Ct("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function os(){return new Ct("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function is(e,t){return Object.assign(e,{checkoutMethod:t})}function Dr(e,t){let n=e instanceof Ct?e:new Ct(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function ga(e,t){try{return await e()}catch(n){throw Dr(n,t)}}function pc(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function gu(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function ss(e){if(typeof document>"u"||typeof window>"u")throw new Ct("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw Yr();let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let b=new AbortController,j=()=>b.abort();e.signal?.aborted?b.abort():e.signal?.addEventListener("abort",j);let L=window.setTimeout(()=>b.abort(),n);try{let I=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:b.signal});if(!I.ok)return{status:"unknown"};let N=await I.json().catch(()=>null);return hu(N)}catch{return{status:"unknown"}}finally{window.clearTimeout(L),e.signal?.removeEventListener("abort",j)}},i,s=()=>e.pollCompletionEndpoint!==!1?o():(i??(i=o()),i),d=document.activeElement instanceof HTMLElement?document.activeElement:null,f=document.createElement("div");f.setAttribute("data-flopay-auto-3ds-overlay","1"),f.setAttribute("role","dialog"),f.setAttribute("aria-modal","true"),f.setAttribute("aria-label","Card authentication"),f.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let u=document.createElement("iframe");u.setAttribute("title","Card authentication"),u.setAttribute("allow","payment"),u.tabIndex=0,u.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let w=null;try{w=new URL(e.billingApiUrl,window.location.href).origin}catch{w=null}try{let b=await new Promise((j,L)=>{let I=!1,N=0,U=0,h=0,C=!1,le=()=>{window.clearTimeout(N),window.clearInterval(U),window.clearTimeout(h),window.removeEventListener("message",ke),u.removeEventListener("load",ve),e.signal?.removeEventListener("abort",J)},D=async()=>{if(!(I||C)){C=!0;try{let qe=await s();if(I||!gu(qe))return;I=!0,le(),j(qe)}finally{C=!1}}},ve=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(h),h=window.setTimeout(()=>{D()},250))},J=()=>{I||(I=!0,le(),L(Yr()))},ke=qe=>{if(qe.source!==u.contentWindow||w&&qe.origin!==w)return;let Re=qe.data;!Re||typeof Re!="object"||Re.source!=="flopay-vault-3ds-return"||I||(I=!0,le(),j(null))};N=window.setTimeout(()=>{I||(I=!0,le(),L(os()))},uc),e.pollCompletionEndpoint!==!1&&(U=window.setInterval(()=>{D()},t)),u.addEventListener("load",ve),window.addEventListener("message",ke),e.signal?.addEventListener("abort",J),u.src=e.nextActionRedirectUrl,f.appendChild(u),document.body.appendChild(f),u.focus(),e.signal?.aborted&&J()});return b||await s()}finally{f.parentNode?.removeChild(f),d?.isConnected&&d.focus()}}async function Fo(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,i=t.nonce??t.session.clientSecret,s=new ai(n,{telemetry:!1}),d=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,f=new AbortController,u=new AbortController,w=()=>{f.abort(o.reason),u.abort(o.reason)};o.aborted?w():o.addEventListener("abort",w,{once:!0});let b=ss({billingApiUrl:n,sessionId:r,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:f.signal,pollCompletionEndpoint:!1}),j=s.waitForCheckoutSessionCompletion(r,{initialDelayMs:mu,nonce:i,statusUrl:d,continueAfterActionRequired:!0,timeoutMs:uc+15e3,signal:u.signal}),L;try{let N=await Promise.race([b,j]);if("data"in N)L=N;else{if(N.status==="declined")throw Rr({type:N.declineReason??"authorization_declined",gatewayErrorCode:N.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(N.status==="timeout")throw os();L=await j}}catch(N){if(o.aborted||N instanceof Error&&N.name==="AbortError")throw Yr(N);if(!(N instanceof Ct)||N.code!=="three_ds_timeout"&&N.code!=="checkout_processing_timeout")throw N;try{L=await s.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:i,statusUrl:d,timeoutMs:5e3,signal:o})}catch(h){if(o.aborted)throw Yr(h);if(!(h instanceof Ct)||h.code!=="checkout_processing_timeout")throw h}let U=L&&Kr(L,t.session);if(!Fr(U)&&U?.status!=="expired"){if(t.telemetry){let h=new ai(n);try{h.reportThreeDsAbandoned(r)}finally{h.destroy()}}throw os()}}finally{o.removeEventListener("abort",w),f.abort(),u.abort()}let I=L&&Kr(L,t.session);if(!Fr(I))throw Ro(I);return{...Br(I,r),checkoutMethod:"card"}}function hu(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Rr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,i=$r(o)??o,s=is(new Ct(i,"api_error",{code:e?.code??cc(e?.outcome)??cc(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function as(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function oi(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function mc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||oi(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,i=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of i)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||oi(d)))return d;let s=o.gateways;if(s&&typeof s=="object"){let d=s.stripe;if(d&&typeof d=="object"){let f=d,u=[f.stripeClientSecret,f.clientSecret];for(let w of u)if(typeof w=="string"&&w.length>0&&(!t?.requirePaymentIntentClientSecret||oi(w)))return w}}}}async function Pu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=mc(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new ai(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(oi(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function Do({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:s}){let d=e.replace(/\/+$/,""),f=t??n.id,u=r??n.clientSecret,w=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",j=n.customer?.firstName??n.accountData?.firstName??"",L=n.customer?.lastName??n.accountData?.lastName??"",I=n.customer?.country??n.accountData?.country??void 0,N=n.customer?.zip??n.accountData?.zip??void 0,h=await new ai(d,s===!1?{telemetry:!1}:void 0).processPayment(w,{sessionId:f,nonce:u,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:w,email:b,firstName:j,lastName:L,country:I,zip:N},returnUrl:i??as(n)});if(h.ok){let D=typeof h.json=="function"?await h.json().catch(()=>null):null;if(du(n)||D?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof D?.paymentId=="string"?D.paymentId:n.paymentId,sessionId:typeof D?.sessionId=="string"?D.sessionId:f,authorizationExpiresAt:typeof D?.authorizationExpiresAt=="string"?D.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:da(o),checkoutMethod:dc(o,n)}};let ve=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ve?{paymentIntentId:ve}:{},paymentMethodId:da(o),checkoutMethod:dc(o,n)}}}let C;try{C=await h.json()}catch(D){throw new Ct("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:h.status,cause:D})}if(C?.type==="3ds_required"&&typeof C.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:C.nextActionRedirectUrl};if(C?.type==="paypal_redirect_required"||C?.type==="3ds_required"){let D=mc(C);if(!D)throw new Ct("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:h.status});return{type:C.type,threeDSecureToken:D,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let D=await Pu({billingApiUrl:d,sessionId:f,nonce:u,responseJson:C});if(D)return D;throw is(new Ct("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let le=new Ct(C?.message??"Payment failed. Please try again.","api_error",{code:C?.code??C?.gatewayErrorCode,declineCode:C?.declineCode??C?.gatewayDeclineReason,statusCode:h.status});throw Object.assign(le,{telemetryOutcome:cu(h.status,C)})}async function ii(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:d,telemetry:f,signal:u}){let w=t?.getRawProvider();if(!w)throw Dr(new Ct("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw is(new Ct("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let b=pu(e.threeDSecureToken),j=null,L=e.paymentMethodId,I=await ga(()=>yu(w,e.threeDSecureToken,b),"card");if(I){if(I.error)throw Dr(new Ct(I.error.message??`Failed to retrieve 3DS ${b?"setup":"payment"} status.`,"api_error",{code:I.error.code}),"card");let U=I.intent;!L&&U?.payment_method&&(typeof U.payment_method=="string"?L=U.payment_method:"id"in U.payment_method&&(L=U.payment_method.id??void 0))}let N=L?await ga(()=>fu(w,e.threeDSecureToken,{payment_method:L,return_url:d??as(s)??window.location.href},b),"card"):null;if(N){if(N.error)throw Dr(new Ct(N.error.message??"3DS authentication failed.","api_error",{code:N.error.code}),"card");j=N.intent}else{let U=await ga(()=>w.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(U.error)throw Dr(new Ct(U.error.message??"3DS authentication failed.","api_error",{code:U.error.code}),"card");j=(b?U.setupIntent:U.paymentIntent)??null}if(j&&(j.status==="requires_capture"||j.status==="succeeded"||j.status==="processing")){let U=await Do({billingApiUrl:o,sessionId:i,session:s,telemetry:f,tokenizedData:{id:j.id,type:"card",threeDSecureActionResultTokenId:j.id},returnUrl:d});return U.type==="success"?{...U.result,paymentIntentId:U.result.paymentIntentId??j.id,paymentMethodId:U.result.paymentMethodId??L}:U.type==="next_action_required"?Fo(U,{billingApiUrl:o,sessionId:i??s.id,session:s,signal:u}):ii(U,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:d,telemetry:f,signal:u})}throw Dr(new Ct("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let b=(n??t)?.getRawProvider();if(!b)throw Dr(new Ct("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:L}=await ga(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(L)throw Dr(new Ct(L.message??"PayPal authorization failed.","api_error",{code:L.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:j}=await ga(()=>b.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??as(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(j)throw Dr(new Ct(j.message??"PayPal authorization failed.","api_error",{code:j.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ct("Unsupported payment redirect state.","api_error")}function Pa(e){if(e instanceof Ct){let r=$r(e.message);return r&&r!==e.message?Object.assign(new Ct(r,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.",n=$r(t)??t;return new Ct(n,"api_error")}function ls(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=uu(e.data.session?.vault)||qr(e.data.session);if(!t&&!n&&!r)throw new Ct("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 dc(e,t){return e?e.isPaypal?"paypal":"card":t&&qr(t)?"card":void 0}async function cs({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[s,d]=await Promise.all([lc(e,{billingApiUrl:n,locale:r,telemetry:o}),i?lc(i,{billingApiUrl:n,locale:r,telemetry:o}).catch(u=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",u),null)):Promise.resolve(null)]);if(!s)throw new Ct("The payment provider did not initialize.","authentication_error");let f=null;return i?f=d:t&&(f=s),{flopay:s,paypalFlopay:f}}import{PaymentAPI as Oo,PciVaultCardCapture as vu,toStripeAppearance as bu}from"@flopay/js";import{COUNTRY_OPTIONS as Cu,classifyPaymentRejection as Su,FloPayError as mr,filterStripeMethodsByCountry as wu,getPostalCodeExample as Iu,getPostalCodeLabel as gs,getStateFromPostalCode as yc,getStateLabel as ds,getStateOptions as ku,getStripeMethodDisplayName as Sa,isAuthorizationOnlySession as us,isAVSFieldVisible as ot,isMountableVaultBlock as Ru,isPostalCodeSupported as _u,isSetupIntentClientSecret as ps,isValidEmail as gn,isValidPostalCode as Eu,needsStripeMethodExplicitConfirm as fc,normalizeCheckoutFailureOutcome as Tu,partitionStripeMethods as Au,randomUuidV4 as Mu,resolveAVSConfig as xu,resolveButtonsLayoutTheme as Bu,resolveSetupFutureUsage as Ec,resolveTheme as Fu,resolveVaultMountOptions as ms,stripeExpressMethodToOptionKey as Du}from"@flopay/shared";import{ExpressCheckoutElement as Tc,PaymentElement as Nu,Elements as so,useElements as bs,useStripe as Cs}from"@stripe/react-stripe-js";import Ou,{useCallback as Xe,useContext as Uo,useEffect as gt,useMemo as ft,useRef as ne,useState as ue}from"react";function No(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function si(e,t){if(e)return{error:n=>e.error(No(t,n)),log:n=>e.log(No(t,n)),performance:n=>e.performance(No(t,n)),terminal:n=>e.terminal(No(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}import{Fragment as Lo,jsx as y,jsxs as Qe}from"react/jsx-runtime";var _r="flopay_stripe_resume",gc="flopay_wallet_resume",Ac="fw1",Lu="fw2",Mc=300*1e3,Uu=900,zu=25e3,qu=25e3,ju=1e4,xc=["payment_intent","payment_intent_client_secret","redirect_status"],pr={provider:"paypal",paymentMethodCategory:"paypal"},$u="x-flopay-process-result-source",Ku="status";async function Vu(e,t,n){try{let r=(await e.getUnifiedCheckoutSession(t,n)).data.session;if(r?.status==="complete")return null;if(r?.status==="authorized")return{status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}}catch{}}var li={},ba=class{constructor(t){this.reason=t}};function Wu(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function Wt(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 Ss(e){return`${Lu}:${e}`}function ci(e){return Wt(Ss(e))}function di(e,t){if(typeof window>"u")return null;let n=Ss(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>Mc||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(ci(e),null):o}catch{return ci(e),null}}function Hu(e){return Wt(Ss(e.sessionId),e)}function hc(e,t,n){let r=di(e,t);return!r||r.clientSecret!==n?!1:ci(e)}function ys(e,t,n){if(typeof window>"u")return;di(e,t)?.clientSecret===n&&ci(e)}function Gu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function fs(e,t,n){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 r=n?e.status==="succeeded":ca(e.status),o=Gu(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function Pc(e,t,n){let r=null;try{return await Promise.race([Vl(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},ju),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Yu(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Bc(e){return e instanceof mr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ui(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Oo(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Bc(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Ca="flopay_paypal_resume",va=new Map;function Fc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(Ca);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function Ju(){if(typeof window>"u")return!1;let[e,t]=ws();return e?Fc(t)!==null:!1}function ws(){let e=new URLSearchParams(window.location.search);return xc.map(t=>e.get(t))}function Is(){let e=new URL(window.location.href);for(let t of xc)e.searchParams.delete(t);return e.toString()}function Xu(){Wt(Ca),window.history.replaceState({},"",Is())}var Zu=250,vc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Qu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function ks(e,t,n,r){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...r?{terminalReason:r}:{}})}async function pi({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Oo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function ep(e){return e instanceof mr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Dc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=oo(n),s=i.firstName?i:oo(r?.name);return Nn({email:gn(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function tp({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let s=Dc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return gn(s.email)?s:i(o,s)}var wa=180,bc=`flopay-card-enter ${wa}ms cubic-bezier(0, 0, 0.2, 1) both`,Cc=`flopay-card-exit ${wa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,np=`flopay-buttons-enter ${wa}ms cubic-bezier(0, 0, 0.2, 1) both`,rp=`flopay-buttons-exit ${wa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function op(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Rs(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var ap={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function ip(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 hs={width:"100%",minHeight:sa,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 sp(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Sc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ps(e){return e==="paypal"?"PayPal":Sa(e)}function lp(e){let t=Iu(e);return`Enter a valid ${gs(e)}${t?` (e.g. ${t})`:""}`}function cp(e,t,n){let r=_u(e),o=t.trim(),i=n&&r,s=i&&!o,d=i&&!!o&&!Eu(e,o);return{visible:n,supported:r,required:i,empty:s,malformed:d}}function dp(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!gn(n);return{required:t,empty:r,malformed:o,value:n}}function wc(e,t){return t instanceof mr?t:new mr(t instanceof Error?t.message:`${sp(e)} before-click hook failed.`,"validation_error")}function up(e){return typeof e=="number"?`${e}px`:e}function _s(e){return y(pp,{...e})}function Ic({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:s=!1,onButtonClick:d,onDecline:f,onTechnicalFailure:u,runBeforeButtonClick:w,billingName:b,onBuyerIdentityReady:j,onLoadStateChange:L,placeholderBorderRadius:I,popupCapabilityOwner:N,externalTelemetryContext:U,presentationMode:h}){let C=Vr(),{emitInstrument:le}=Uo(Zn),D=Cs(),ve=bs(),J=ft(()=>si(pn(C),U),[U,C]),[ke,qe]=ue("loading");gt(()=>{L?.(ke)},[ke,L]);let[Re,st]=ue(!1),qt=ne(!1),fe=!gn(n?.trim())||!b?.trim(),{request:Ae,collect:ht,finish:Ee}=_o(),He=ne(!1),_e=ne(null),ie=ne(null),[je,$e]=ue(0),[pt,Ce]=ue(!1),ge=ne(!1),ce=ne(new Map),{startAttempt:M,finishAttempt:Se,invalidateAttempt:Ue,isAttemptInvalidated:Me,isAttemptCurrent:V,generationRef:Pt}=ma((E,se,De)=>{u?.(E,se,{...De,popupBlocked:De?.popupBlocked??zr(se),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h,terminalReason:"overlay_timeout"}),Ce(!0),$e(F=>F+1)},{onHandoffObserved:()=>{N.markAvailable(),J?.log({name:"provider.popup.opened",stage:"overlay_open",...pr,attempt:Pt.current})}});gt(()=>{pt&&ie.current?.focus()},[pt,je]);let ze=Xe(()=>{$e(E=>E+1)},[]),Te=Xe((E,se,De)=>{Ue(De),u?.("paypal",E,{code:se,popupBlocked:zr(E),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h}),Ce(!0),ze()},[Ue,u,h,ze]),Ze=Xe(()=>{window.setTimeout(()=>{(_e.current?.querySelector("iframe")??_e.current)?.focus()},0)},[]);gt(()=>{ge.current&&(ge.current=!1,Ze())},[Ze,je]);let xe=Xe(()=>{Ce(!1),i?.(null),Ze()},[Ze,i]);gt(()=>{if(!D||He.current)return;let[E,se,De]=ws();if(!E||!se)return;let F=Fc(se);if(!F)return;He.current=!0;let we=!0,yt=va.get(se);yt||(yt=De==="failed"?Promise.resolve(null):Promise.resolve().then(()=>D.retrievePaymentIntent(se)),va.set(se,yt));let Ne={accountPatch:F.accountPatch,sessionId:F.sessionId,nonce:F.nonce},St=()=>{J?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...pr,requestCategory:"provider_sdk"})};return J?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...pr}),(async()=>{try{st(!0);let p=await yt;if(!we)return;if(p?.error){va.delete(se),St(),i?.(p.error.message??"Failed to retrieve PayPal payment status.");return}if(Xu(),va.delete(se),De==="failed"){let x="PayPal payment was declined. Please try again.";J?.terminal({outcome:"payment_declined",...pr,terminalReason:"provider_declined"}),i?.(x),f?.(un("paypal",x));return}let g=p?.paymentIntent;if(g&&g.id!==E){St(),i?.("Failed to match the returned PayPal payment.");return}if(g&&(g.status==="requires_capture"||g.status==="succeeded")){let x=typeof g.payment_method=="string"?g.payment_method:g.payment_method?.id;o({id:x??g.id,type:"card",threeDSecureActionResultTokenId:g.id,isPaypal:!0},{...Ne,presentationMode:"redirect"})}else{let x="PayPal payment was not completed. Please try again.";J?.terminal({outcome:g?.status==="canceled"?"payment_cancelled":"payment_declined",...pr,terminalReason:g?.status==="canceled"?"cancelled":"provider_declined"}),i?.(x),f?.(un("paypal",x))}}catch(p){if(!we)return;va.delete(se),St(),i?.(p instanceof Error?p.message:"Failed to complete PayPal payment.")}finally{we&&st(!1)}})(),()=>{we=!1,He.current=!1}},[D,o,i,f,J]);let et=Xe(async(E=!1)=>{let se=w?await w("paypal"):{proceed:!0};if(!se.proceed)return ce.current.delete(je),!1;let De=M("paypal");return ce.current.set(je,{generation:De,accountPatch:se.accountPatch,sessionId:se.sessionId,nonce:se.nonce}),Ce(!1),J?.log({name:`provider.${E?"redirect.started":"handoff.requested"}`,stage:E?"redirect":"overlay_open",...pr,attempt:De}),d?.("paypal"),!0},[d,J,w,M,je]),Fe=Xe(async E=>{if(s||Re||!await et()){E.reject();return}E.resolve()},[s,et,Re]),vt=Xe(async E=>{if(!D||!ve)return;let se=ce.current.get(je);if(se&&!V(se.generation)){ce.current.delete(je);return}if(!se&&Me()||se&&!Se(se.generation))return;se||Se();let De=se??null;if(ce.current.delete(je),!De&&w){let T=await w("paypal");if(!T.proceed){E.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}De={accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}}let F=De?.sessionId??e,we=De?.nonce??t,yt=await tp({event:E,prepared:De,email:n,billingName:b,methodLabel:"PayPal",collect:ht});if(!yt){E.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ne=yt.email,St={...De?.accountPatch,...Nn(yt,!0)};try{if(st(!0),i?.(null),!F||!gn(Ne))throw new Error("Missing sessionId or email for PayPal payment");await j?.(yt);let T=D.createPaymentMethod,{error:p,paymentMethod:g}=await T({type:"paypal"});if(p){Te(p,"stripe_paypal_create_payment_method_failed",se?.generation),E.paymentFailed({reason:"fail"});return}let x=await ui(r,le,F,we??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:g?.id??null,intentKind:"payment"});if(x.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let A=x.clientSecret,re={return_url:Is()};if(g?.id&&(re.payment_method=g.id),!Wt(Ca,{clientSecret:A,sessionId:F,nonce:we,accountPatch:St})&&h==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:he,paymentIntent:Ke}=await D.confirmPayment({clientSecret:A,confirmParams:re,redirect:"if_required"});if(he){if(Wt(Ca),za(he)){let jt=he.message??"Your payment was declined.";J?.terminal({outcome:"payment_declined",...pr,terminalReason:"provider_declined"}),i?.(jt),f?.(un("paypal",jt,{code:Ur(he),declineCode:aa(he)})),await pi({billingApiUrl:r,sessionId:F,nonce:we,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ur(he)??"provider_declined"}})}else Te(he,"stripe_paypal_confirm_failed",se?.generation);return}Wt(Ca);let X=typeof Ke?.payment_method=="string"?Ke.payment_method:Ke?.payment_method?.id;o({id:X??Ke?.id,type:"card",threeDSecureActionResultTokenId:Ke?.id,isPaypal:!0},{accountPatch:St,paymentMethodCategory:"paypal",presentationMode:h,sessionId:F,nonce:we});return}catch(T){Te(T,"stripe_paypal_failed",se?.generation)}finally{st(!1)}},[D,ve,e,t,n,b,ht,j,r,le,o,i,f,w,Te,Se,V,Me,J,h,je]),Gt=Xe(async()=>{if(!(qt.current||s||Re||!D||!ve)){qt.current=!0,st(!0);try{if(!await et(!0))return;await vt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{qt.current=!1,st(!1)}}},[ve,vt,s,et,D,Re]),mt=h==="redirect"?y("button",{type:"button",disabled:s||Re,onClick:()=>{Gt()},style:{width:"100%",minHeight:sa,border:"1px solid #d1d5db",borderRadius:I??8,background:"#ffc439",color:"#111827",cursor:s||Re?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):y(Tc,{onReady:E=>qe(Ui(E,["paypal"])),onLoadError:()=>{qe("load_error"),ks(J,"paypal","paypal","provider_error")},onClick:Fe,onConfirm:vt,onCancel:()=>{let E=ce.current.get(je);ce.current.delete(je),J?.terminal({outcome:"payment_cancelled",...pr,terminalReason:"cancelled",...E?{attempt:E.generation}:{}}),Ue(E?.generation),Ce(!1),ge.current=!0,ze()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:fe,emailRequired:fe,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},je),Tt=Qe(Lo,{children:[Qe("div",{ref:_e,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[pt&&y("button",{ref:ie,type:"button","data-testid":"flopay-paypal-retry-button",onClick:xe,style:hs,children:"Try PayPal again"}),Ae&&y(Eo,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:Ee,onCancel:()=>Ee(null)},Ae.id),y("div",{style:{display:Ae?"none":void 0},children:mt})]}),Re&&!Ae&&y(Ir,{status:"processing"})]});return h==="redirect"?Tt:y(zi,{state:ke,placeholderTestId:"flopay-paypal-placeholder",borderRadius:I,children:Tt})}function kc(e){return e==="apple_pay"||e==="google_pay"}function Rc({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:s,onErrorChange:d,onButtonClick:f,onDecline:u,onTechnicalFailure:w,runBeforeButtonClick:b,billingName:j,onBuyerIdentityReady:L,onLoadStateChange:I,placeholderBorderRadius:N,popupCapabilityOwner:U,externalTelemetryContext:h}){let C=Vr(),{emitInstrument:le}=Uo(Zn),D=Cs(),ve=bs(),J=ft(()=>si(pn(C),h),[h,C]),[ke,qe]=ue("loading");gt(()=>{I?.(ke)},[ke,I]);let[Re,st]=ue(!1),qt=ne(!gn(n?.trim())||!j?.trim()).current,{request:fe,collect:Ae,finish:ht}=_o(),Ee=ne(null),He=ne(null),[_e,ie]=ue(0),[je,$e]=ue(!1),[pt,Ce]=ue(()=>di(e,t)?"blocked":"idle"),[ge,ce]=ue("google_pay"),M=ne(null),Se=ne(!0),Ue=ne(!1),Me=ne("google_pay"),V=ne("google_pay"),Pt=ne(null),ze=ne(null),Te=ne(new Set),Ze=ne(null);gt(()=>(Se.current=!0,()=>{Se.current=!1;for(let T of Te.current)window.clearTimeout(T);Te.current.clear()}),[]);let xe=ne(new Map),{startAttempt:et,finishAttempt:Fe,invalidateAttempt:vt,isAttemptInvalidated:Gt,isAttemptCurrent:mt,generationRef:Tt}=ma((T,p,g)=>{w?.(T,p,{...g,popupBlocked:g?.popupBlocked??zr(p),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ce(T),$e(!0),ie(x=>x+1)},{onHandoffObserved:T=>{U.markAvailable(),J?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Tt.current,...T==="apple_pay"||T==="google_pay"?{walletType:T}:{}})},defersMissingTerminal:kc,onMissingTerminalDeferred:(T,p)=>{let g=J?.now()??globalThis.performance?.now()??Date.now(),x=Ze.current,A=x?.generation===p?x.startedAt:g;J?.performance({stage:"overlay_return",durationMs:Math.max(0,g-A),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:p,...kc(T)?{walletType:T}:{}}),J?.flush?.().catch(()=>{})}});gt(()=>{je&&He.current?.focus()},[je,_e]);let E=Xe(()=>{ie(T=>T+1)},[]),se=Xe((T,p,g,x,A=!1)=>{vt(x),w?.(T,p,{code:g,popupBlocked:zr(p),telemetryReported:A,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ce(T),$e(!0),E()},[vt,w,E]),De=Xe(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);gt(()=>{Ue.current&&(Ue.current=!1,De())},[De,_e]);let F=Xe(()=>{$e(!1),d?.(null),De()},[De,d]),we=Xe(()=>{M.current?.()},[]);gt(()=>{let T=di(e,t);if(!T)return;let p=!1,g=!1,x=async()=>{if(!g){g=!0,p||Ce("checking");try{let A=await Pc(D,T.clientSecret,Te.current);if(p)return;let re=fs(A,T.providerObjectId,ps(T.clientSecret));if(re.kind==="confirmed"){if(!hc(e,t,T.clientSecret))return;M.current=null,Ce("idle"),s({id:re.paymentMethodId,type:"card",threeDSecureActionResultTokenId:re.intentId},{...T.accountPatch?{accountPatch:T.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(re.kind==="terminal"){ys(e,t,T.clientSecret),M.current=null,Ce("idle"),ce(T.paymentMethodType),$e(!0),E();return}Ce("blocked")}catch{p||Ce("blocked")}finally{g=!1}}};return M.current=x,Ce("blocked"),()=>{p=!0,M.current===x&&(M.current=null)}},[t,s,E,e,D]);let yt=Xe(async T=>{let p=!1,g=Ge=>{p||(p=!0,T.paymentFailed({reason:"fail",...Ge?{message:Ge}:{}}))};if(!D||!ve){g();return}let x=xe.current.get(_e);if(x&&!mt(x.generation)){xe.current.delete(_e),g();return}if(!x&&Gt()){g();return}if(x&&!Fe(x.generation)){g();return}x||Fe();let A=T.expressPaymentType??x?.method??Me.current,re=x??null,ct=Sc(A),he;A==="apple_pay"?he="apple_pay":A==="google_pay"&&(he="google_pay");let Ke=x?.generation??Tt.current,X=J,jt=X?.now()??globalThis.performance?.now()??Date.now(),bt=new AbortController,At=!1,at=!1,de=null,_n=e,On="processing",mn="other",$t="provider_runtime",Ln,Un=new Promise((Ge,Oe)=>{Ln=Oe}),hn=window.setTimeout(()=>{At=!0,bt.abort(),Ln(li)},zu),Mt=async(Ge,Oe,En)=>{On=Ge,mn=Oe,$t=Oe==="intent_create"||Oe==="session_claim"?"transport_error":"provider_runtime";let wt=X?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([En,Un])}finally{let zn=X?.now()??globalThis.performance?.now()??Date.now();X?.performance({stage:Ge,durationMs:Math.max(0,zn-wt),durationMode:"machine",requestCategory:Oe,paymentMethodCategory:"wallet",provider:"stripe",...At?{statusClass:"timeout"}:{}})}};try{if(st(!0),d?.(null),!re&&b){let me=await Mt("processing","other",b(ct));if(!me.proceed){g();return}re={accountPatch:me.accountPatch,sessionId:me.sessionId,nonce:me.nonce}}let Ge=re?.sessionId??e;_n=Ge;let Oe=re?.nonce??t,En=Pt.current??re?.accountPatch,wt=Dc({event:T,fallbackEmail:En?.email??n,fallbackName:[En?.firstName,En?.lastName].join(" ").trim()||j});if(!gn(wt.email)){g("Buyer details are required."),Ae(Ps(A),wt).then(me=>{me&&(Pt.current=me)});return}Pt.current=null;let zn={...re?.accountPatch,...Nn(wt,!0)};await Mt("processing","session_claim",Promise.resolve(L?.(wt)));let{error:yn}=await Mt("tokenization","provider_sdk",ve.submit());if(yn){g(),se(A,yn,"stripe_wallet_submit_failed",x?.generation);return}if(!Ge)throw new Error("Missing sessionId or email for payment.");let Kt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:A,paymentMethodId:null,intentKind:o},Qt=JSON.stringify({sessionId:Ge,nonce:Oe??"",request:Kt}),er=ze.current,Wn=er?.retryIdentity===Qt?er.authorizationAttemptId:Mu();ze.current={authorizationAttemptId:Wn,retryIdentity:Qt};let en=await Mt("processing","intent_create",ui(r,le,Ge,Oe??"",{...Kt,authorizationAttemptId:Wn},{signal:bt.signal}));if(en.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let It=en.clientSecret,tn=Hu({createdAt:Date.now(),sessionId:Ge,...Oe?{nonce:Oe}:{},clientSecret:It,providerObjectId:en.providerObjectId,paymentMethodType:A,accountPatch:zn});window.clearTimeout(hn),at=!0,X?.performance({stage:"callback",durationMs:Math.max(0,(X?.now()??globalThis.performance?.now()??Date.now())-jt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let rn=X?.now()??globalThis.performance?.now()??Date.now(),Dt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...he?{walletType:he}:{},attempt:Ke},sn=!1,Ot=null;X?.log({name:"payment.provider_confirmation.started",...Dt}),de=window.setTimeout(()=>{de!==null&&Te.current.delete(de),sn=!0;let me=X?.now()??globalThis.performance?.now()??Date.now();X?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Dt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,me-rn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),X?.flush?.().catch(()=>{}),Ot?.()},qu),Te.current.add(de);let on=(me,tt)=>{de!==null&&(window.clearTimeout(de),Te.current.delete(de),de=null);let m=X?.now()??globalThis.performance?.now()??Date.now(),Be=Math.max(0,m-rn),$=me;sn&&(me==="resolved"?$="resolved_late":me==="returned_error"?$="returned_error_late":$="rejected_late");let Pn=tt??(me==="resolved"?"approved":"provider_error");return X?.log({name:"payment.provider_confirmation.returned",...Dt,operationOutcome:$,terminalReason:Pn}),X?.performance({...Dt,durationMs:Be,durationMode:"buyer",operationOutcome:$,terminalReason:Pn}),{durationMs:Be,operationOutcome:$,terminalReason:Pn}},Nt=!1,W=!1,tr=me=>{if(!me||typeof me!="object")return null;let tt=me;if(tt.error)return null;let m=tt.setupIntent??tt.paymentIntent,Be=fs(m??null,void 0,!!tt.setupIntent);return Be.kind==="confirmed"?Be:null},nr=me=>{if(Nt||x&&Tt.current!==x.generation)return;let tt=tr(me);if(!tt)return;if(tn&&!hc(Ge,Oe,It)){Nt=!0;return}let{intentId:m,paymentMethodId:Be}=tt;Nt=!0,W=!0,ze.current=null,M.current=null,Se.current&&(Ce("idle"),st(!1));let $=`${Ac}:${Ge}`;Wt($,{createdAt:Date.now(),sessionId:Ge,nonce:Oe,accountPatch:zn,paymentMethodId:Be,providerIntentId:m,paymentMethodType:A});try{s({id:Be,type:"card",threeDSecureActionResultTokenId:m},{accountPatch:zn,paymentMethodCategory:"wallet",sessionId:Ge,nonce:Oe})}finally{Wt($)}},rr=!1;Ot=async()=>{if(!(rr||Nt||W)){rr=!0,Se.current&&Ce("checking");try{let me=await Pc(D,It,Te.current);if(Nt||W)return;let tt=ps(It),m=fs(me,en.providerObjectId,tt);if(m.kind==="confirmed"){nr(tt?{setupIntent:me}:{paymentIntent:me});return}if(m.kind==="terminal"){if(W=!0,ys(Ge,Oe,It),ze.current=null,M.current=null,!Se.current)return;Ce("idle"),g(),se(A,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",x?.generation,!0);return}Se.current&&!W&&(Ce("blocked"),st(!1))}catch{Se.current&&!W&&(Ce("blocked"),st(!1))}finally{rr=!1}}},M.current=Ot;let nn,Tn;try{let me=await(ps(It)?D.confirmSetup({elements:ve,clientSecret:It,redirect:"if_required"}):D.confirmPayment({elements:ve,clientSecret:It,redirect:"if_required"}));if(!me||typeof me!="object")throw new ba(Wu(me));if(nn=me,!nn.error&&!tr(nn))throw new ba("confirmation_result_unconfirmed");Tn=on(nn.error?"returned_error":"resolved",nn.error&&za(nn.error)?"provider_declined":void 0)}catch(me){let tt=me instanceof ba?me.reason:void 0,m=tt!==void 0,Be=on(m?"returned_error":"rejected");if(X?.error({...m?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:tt}:Wi(me),...Dt,operationOutcome:Be.operationOutcome,durationMs:Be.durationMs,statusClass:"unknown",terminalReason:Be.terminalReason}),!Se.current||Nt)return;await Ot?.();return}let Sn=nn.error;if(Sn){if(!Se.current||Nt)return;if(za(Sn)){W=!0,ys(Ge,Oe,It),ze.current=null,M.current=null,Ce("idle");let me=Sn.message??"Your payment was declined.";g(me),d?.(me),u?.(un(ct,me,{code:Ur(Sn),declineCode:aa(Sn)})),pi({billingApiUrl:r,sessionId:Ge,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:A,providerDeclineReason:Ur(Sn)??"provider_declined",...en.intentKind==="payment"&&en.providerObjectId.startsWith("pi_")?{providerIntentId:en.providerObjectId}:{}}})}else X?.error({...Wi(Sn),...Dt,operationOutcome:Tn.operationOutcome,durationMs:Tn.durationMs,statusClass:"unknown",terminalReason:Tn.terminalReason}),await Ot?.();return}if(nr(nn),!Nt)throw new Error("Invalid provider returned for APM intent")}catch(Ge){if(Ge===li){let Oe=X?.now()??globalThis.performance?.now()??Date.now();X?.error({errorCode:Yu(mn),stage:On,requestCategory:mn,paymentMethodCategory:"wallet",provider:"stripe",...he?{walletType:he}:{},operationOutcome:"watchdog_expired",checkoutSessionId:_n,durationMs:Math.max(0,Oe-jt),statusClass:"timeout",failureCategory:$t,attempt:Ke,terminalReason:"provider_error"}),X?.flush?.().catch(()=>{})}g(),se(A,Ge,Ge===li?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",x?.generation,Ge===li)}finally{if(window.clearTimeout(hn),de!==null&&(window.clearTimeout(de),Te.current.delete(de)),!at){let Ge=X?.now()??globalThis.performance?.now()??Date.now();X?.performance({stage:"callback",durationMs:Math.max(0,Ge-jt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...At?{statusClass:"timeout"}:{}})}Se.current&&st(!1)}},[D,ve,e,t,n,j,Ae,L,r,le,o,s,d,u,b,se,Fe,mt,Gt,Tt,J,_e]),Ne=ft(()=>Tl(i),[i]),St=ft(()=>i.map(Du),[i]);return Qe(Lo,{children:[y(zi,{state:ke,placeholderTestId:"flopay-wallet-placeholder",borderRadius:N,children:Qe("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[je&&Qe("button",{ref:He,type:"button","data-testid":"flopay-wallet-retry-button",onClick:F,style:hs,children:["Try ",Ps(ge)," again"]}),pt!=="idle"&&Qe("div",{role:"status","aria-live":"polite",children:[y("p",{children:"We are still confirming your payment. Check its status before trying again."}),y("button",{type:"button",onClick:we,disabled:pt==="checking",style:hs,children:pt==="checking"?"Checking payment status\u2026":"Check payment status"})]}),fe&&y(Eo,{identity:fe.identity,methodLabel:fe.methodLabel,onComplete:ht,onCancel:()=>ht(null)},fe.id),pt==="idle"&&y("div",{style:{display:fe?"none":void 0},children:y(Tc,{onReady:T=>{qe(Ui(T,St))},onLoadError:T=>{qe("load_error"),ks(J,"stripe","wallet","provider_error")},onClick:async T=>{let p=J?.now()??globalThis.performance?.now()??Date.now();Me.current=T.expressPaymentType,V.current=Sc(T.expressPaymentType);let g=!0,x=window.setTimeout(()=>{g=!1,T.reject()},Uu),A=b?await b(V.current):{proceed:!0};if(window.clearTimeout(x),!g)return;if(!A.proceed){xe.current.delete(_e),T.reject();return}let re=et(T.expressPaymentType);Ze.current={generation:re,startedAt:p},xe.current.set(_e,{generation:re,method:T.expressPaymentType,accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}),$e(!1),J?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:re,...T.expressPaymentType==="apple_pay"||T.expressPaymentType==="google_pay"?{walletType:T.expressPaymentType}:{}}),f?.(V.current),T.resolve()},onConfirm:yt,onCancel:()=>{let T=xe.current.get(_e);xe.current.delete(_e),J?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...T?{attempt:T.generation}:{}}),vt(T?.generation),ze.current=null,$e(!1),Ue.current=!0,E()},options:{...Al,paymentMethods:Ne,emailRequired:qt,billingAddressRequired:qt}},_e)})]})}),Re&&y(Ir,{status:"processing"})]})}function Nc(e,t,n){let r=Ec(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...r?{setupFutureUsage:r}:null}}function vs({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:d,onErrorChange:f,onDecline:u,onCancel:w,runBeforeButtonClick:b,onButtonClick:j,isProcessing:L,submitButtonColor:I,submitButtonBorderRadius:N,submitButtonStyle:U,errorText:h}){let C=Vr(),{emitInstrument:le}=Uo(Zn),D=Cs(),ve=bs(),[J,ke]=ue(!1),qe=ne(!1),[Re,st]=ue(!1),[qt,fe]=ue("loading"),[Ae,ht]=ue(""),Ee=!gn(r?.trim()),He=!Ee||gn(Ae.trim()),_e=Xe(async()=>{if(!D||!ve||L||qe.current||!Re)return;qe.current=!0,ke(!0);let ie=b?await b("card"):{proceed:!0};if(!ie.proceed){qe.current=!1,ke(!1);return}j?.("card");let je=ie.sessionId??t,$e=ie.nonce??n,pt=oo(o?.trim()),Ce=Nn({email:ie.accountPatch?.email?.trim()||r?.trim()||Ae.trim(),firstName:ie.accountPatch?.firstName?.trim()||pt.firstName,lastName:ie.accountPatch?.lastName?.trim()||pt.lastName}),ge=Ce.email,ce=Nn({...ie.accountPatch,...Ce});try{if(f?.(null),!gn(ge))throw new Error("A valid email address is required for payment.");await i?.(Ce);let M=await ve.submit();if(M.error){f?.(M.error.message??"Payment failed.");return}let Se=[Ce.firstName,Ce.lastName].filter(Boolean).join(" "),Ue=await D.createPaymentMethod({elements:ve,params:{billing_details:{email:ge,...Se?{name:Se}:{}}}});if(Ue.error||!Ue.paymentMethod){f?.(Ue.error?.message??"Failed to create payment method.");return}let Me=Ue.paymentMethod;if(!je||!ge)throw new Error("Missing sessionId or email for payment.");let V=Me.type||e,Pt=await ui(s,le,je,$e??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:V,paymentMethodId:null,intentKind:"payment"});if(Pt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ze=Pt.clientSecret;Wt(_r,{clientSecret:ze,sessionId:je,nonce:$e,accountPatch:ce,paymentMethodId:Me.id,paymentMethodType:Me.type??e,gateway:"stripe"});let{error:Te,paymentIntent:Ze}=await D.confirmPayment({clientSecret:ze,confirmParams:{return_url:window.location.href,payment_method:Me.id},redirect:"if_required"});if(Te){Wt(_r);let Fe=Te.message??"Payment failed.";f?.(Fe),u?.(un("card",Fe,{code:Te.code})),await pi({billingApiUrl:s,sessionId:je,nonce:$e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Te.code??"provider_declined"}});return}let xe=Ze?.status;if(!ca(xe)){Wt(_r);let Fe=xe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(Fe),u?.(un("card",Fe,{code:xe??"missing_payment_intent"}));return}Wt(_r);let et=typeof Ze?.payment_method=="string"?Ze.payment_method:Ze?.payment_method?.id;d({id:et??Me.id,type:"card",threeDSecureActionResultTokenId:Ze?.id,gateway:"stripe",paymentMethodType:Me.type??e},{accountPatch:ce,paymentMethodCategory:"apm",sessionId:je,nonce:$e})}catch(M){f?.(M instanceof Error?M.message:"Payment failed. Please try again.")}finally{qe.current=!1,ke(!1)}},[D,ve,L,Re,b,j,t,n,r,o,Ae,i,s,le,e,d,f,u]);return Qe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Ee&&y("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Ee&&Qe("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",y("input",{type:"email",autoComplete:"email",required:!0,value:Ae,onChange:ie=>ht(ie.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),y(Nu,{onReady:()=>fe("ready"),onLoadError:()=>{fe("load_error"),ks(pn(C),"stripe","apm")},onChange:ie=>{st(!!ie.complete)},options:{layout:Ml,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...gn(r?.trim())?{email:r?.trim()}:{}}}}}),y(xl,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{_e()},disabled:!Re||!He||J||L||qt!=="ready",color:I,borderRadius:N,style:U,children:J?"Processing\u2026":`Pay with ${Sa(e)}`}),h&&y(Ao,{margin:"0.75rem 0 0",children:h})]})}function _c({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:s,stripeInstance:d,paymentElementBaseOptions:f,futureUseSession:u,onTokenizedBody:w,onErrorChange:b,onButtonClick:j,onDecline:L,runBeforeButtonClick:I,onLoadStateChange:N,isProcessing:U=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:C=8,submitButtonStyle:le,buttonAppearance:D,themeId:ve,onExpandApm:J,expandedApmMethod:ke}){let{emitInstrument:qe}=Uo(Zn),[Re,st]=ue(null),[qt,fe]=ue(null),Ae=ne(!1),{request:ht,collect:Ee,finish:He}=_o();gt(()=>{s.length>0&&d?N?.("ready"):d||N?.("loading")},[s.length,d,N]);let _e=Xe(async ge=>{if(!d||Ae.current||U)return;Ae.current=!0,fe(ge);let ce=I?await I("card"):{proceed:!0};if(!ce.proceed){Ae.current=!1,fe(null);return}j?.("card");let M=ce.sessionId??e,Se=ce.nonce??t,Ue=oo([ce.accountPatch?.firstName,ce.accountPatch?.lastName].filter(Boolean).join(" ")||r),Me=Nn({email:ce.accountPatch?.email?.trim()||n?.trim(),firstName:ce.accountPatch?.firstName?.trim()||Ue.firstName,lastName:ce.accountPatch?.lastName?.trim()||Ue.lastName});if(!gn(Me.email)){fe(null);let ze=await Ee(Sa(ge),Me);if(!ze){Ae.current=!1;return}Me=ze,fe(ge)}let V=Me.email,Pt=Nn({...ce.accountPatch,...Me});try{if(b?.(null),!M||!gn(V))throw new Error("Missing sessionId or email for payment.");await o?.(Me);let ze=await ui(i,qe,M,Se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ge,paymentMethodId:null,intentKind:"payment"});if(ze.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Te=ze.clientSecret;Wt(_r,{clientSecret:Te,sessionId:M,nonce:Se,accountPatch:Pt,paymentMethodType:ge,gateway:"stripe"});let{error:Ze,paymentIntent:xe}=await d.confirmPayment({clientSecret:Te,confirmParams:{return_url:window.location.href,payment_method_data:{type:ge,billing_details:{name:[Me.firstName,Me.lastName].filter(Boolean).join(" "),...V?{email:V}:{}}}},redirect:"if_required"});if(Ze){Wt(_r);let vt=Ze.message??"Payment failed.";b?.(vt),L?.(un("card",vt,{code:Ze.code})),await pi({billingApiUrl:i,sessionId:M,nonce:Se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ge,providerDeclineReason:Ze.code??"provider_declined"}});return}let et=xe?.status;if(!ca(et)){Wt(_r);let vt=et==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";b?.(vt),L?.(un("card",vt,{code:et??"missing_payment_intent"}));return}Wt(_r);let Fe=typeof xe?.payment_method=="string"?xe.payment_method:xe?.payment_method?.id;w({id:Fe??xe?.id,type:"card",threeDSecureActionResultTokenId:xe?.id,gateway:"stripe",paymentMethodType:ge},{accountPatch:Pt,paymentMethodCategory:"apm",sessionId:M,nonce:Se})}catch(ze){b?.(ze instanceof Error?ze.message:"Payment failed. Please try again.")}finally{Ae.current=!1,fe(null)}},[d,U,I,j,e,t,n,Ee,i,qe,r,o,w,b,L]),[ie,je]=ue(null),$e=J?ke??null:ie,pt=Xe(ge=>{Ae.current||U||$e&&$e!==ge||(fc(ge)?J?J(ge):je(ge):_e(ge))},[$e,U,_e,J]),Ce=ft(()=>ie?Nc(f,ie,u):null,[ie,f,u]);return y("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:ht?y(Eo,{identity:ht.identity,methodLabel:ht.methodLabel,onComplete:He,onCancel:()=>He(null)},ht.id):s.map(ge=>{let ce=ke===ge,M=qt===ge,Se=qt!==null&&qt!==ge||ke!=null&&ke!==ge;return Qe(Ou.Fragment,{children:[y(El,{method:ge,themeId:ve,submitting:M,disabled:Se,highlighted:ce,hasNextStep:fc(ge),onClick:()=>pt(ge),backgroundColor:D?.backgroundColor,borderColor:D?.borderColor,textColor:D?.textColor,borderRadius:D?.borderRadius,fontFamily:D?.fontFamily}),!J&&ie===ge&&Ce&&d&&y(so,{stripe:d,options:Ce,children:y(vs,{method:ge,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:w,onErrorChange:b,onDecline:L,onCancel:()=>je(null),runBeforeButtonClick:I,onButtonClick:j,isProcessing:U,submitButtonColor:h,submitButtonBorderRadius:C,submitButtonStyle:le})},ge)]},ge)})})}function pp({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:i,onComplete:s,onError:d,onDecline:f,onTokenizedBody:u,firstName:w,lastName:b,chv:j,className:L,submitLabel:I,isProcessing:N,error:U,onErrorChange:h,showPayPal:C=!0,showStripe:le=!0,walletPresentation:D="auto",enabledPaymentMethods:ve,enabledPaymentMethodCountries:J,showApplePay:ke=!0,showGooglePay:qe=!0,layout:Re="default",theme:st,buttonsTheme:qt,buttonsStyles:fe,appearance:Ae,cardButtonContent:ht,cardBackButtonContent:Ee,cardTitleContent:He,showSecurityFooter:_e,onButtonClick:ie,onBeforeButtonClick:je,onBuyerIdentityReady:$e,enableAVS:pt,cardFieldOrder:Ce,cardPreFormSlot:ge,avsLayout:ce="row",country:M,zip:Se,addressLine1:Ue,addressLine2:Me,city:V,state:Pt,onCountryChange:ze,onZipChange:Te,avsCheck:Ze,checkoutType:xe,checkoutLayout:et,totalAmount:Fe=0,currency:vt="usd",initialCardOpen:Gt=!1,directPaypal:mt,isSubscription:Tt=!1,session:E,dataAttachmentPending:se=!1,dataAttachmentRequiresIdentity:De=!1,debug:F=!1}){let we=Vr(),yt=Hi(),Ne=Uo(ur),{emitInstrument:St}=Uo(Zn),T=ne(null);T.current||(T.current=Ha());let p=T.current,[,g]=ue(0),x=ne(null);x.current||(x.current=ia());let A=x.current,re=ft(()=>({browser:A,capability:p,presentationMode:"popup"}),[A,p]),ct=E??Ne.session,he=ft(()=>({futureUse:ct?.futureUse,futureUseUnsupported:ct?.futureUseUnsupported}),[ct?.futureUse,ct?.futureUseUnsupported]),Ke=ct?.gateways?.paypal?.providerObjectType??mt?.providerObjectType,X=se||Ne.claimPending===!0,jt=De||Ne.claimRequiresIdentity===!0,bt=X&&!jt,At=Zl(),at=n||At,[de,_n]=ue(!1),[On,mn]=ue(null),[$t,Ln]=ue(M??""),[Un,hn]=ue(Se??""),[Mt,Ge]=ue(Ue??""),[Oe,En]=ue(Me??""),[wt,zn]=ue(V??""),[yn,Kt]=ue(Pt??""),[Qt,er]=ue(""),[Wn,en]=ue({}),It=ne(Se??""),tn=ne(M??""),rn=ne(Ue??""),Dt=ne(Me??""),sn=ne(V??""),Ot=ne(Pt??""),on=ne(""),Nt=ne({});gt(()=>{let a=(v,O,Pe,q,ae)=>{if(Nt.current[v])return;let _t=O?.trim();!_t||_t===Pe.current||(Pe.current=_t,q(_t),ae?.(_t))};a("country",M,tn,Ln,ze),a("zip",Se,It,hn,Te),a("addressLine1",Ue,rn,Ge),a("addressLine2",Me,Dt,En),a("city",V,sn,zn),a("state",Pt,Ot,Kt)},[M,Se,Ue,Me,V,Pt,ze,Te]);let W=ft(()=>xu(pt),[pt]),tr=W!==null,nr=ft(()=>us(E),[E]),rr=Ru(E?.vault),nn=!!E?.gateways?.pcivault,Tn=$i(E),me=!!(E?.gateways?.stripe?.enabledPaymentMethods??ve)?.includes("card")||qr(E),tt=rr||me||nn,m=!!(le&&tt&&e),[Be,$]=ue(()=>Re!=="buttons"||Gt?e??null:null),[Pn,qn]=ue(0),Yt=Re!=="buttons"||Gt||!!e&&Be===e,An=E?.captureMethod,nt=ne(we);gt(()=>{nt.current=we},[we]);let[or,Zr]=ue(null);gt(()=>{if(!m||!e||!Yt){Zr(null);return}let a=nt.current?nt.current.cardCapture({sessionId:e,captureMethod:An}):new vu({sessionId:e,captureMethod:An,billingApiUrl:at,telemetry:r});return Zr({sessionId:e,captureMethod:An,billingApiUrl:at,telemetry:r,capture:a}),()=>{a.unmount()}},[m,e,Yt,An,at,r]);let kt=m&&e&&Yt&&or?.sessionId===e&&or.captureMethod===An&&or.billingApiUrl===at&&or.telemetry===r?or.capture:null,Mn=ft(()=>{let a=$t,v=W?ot(W.postal_code,a):!1;return cp(a,Un,v)},[W,$t,Un]),{avsInvalid:fr,invalidAvsFields:Hn}=ft(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!m||!W)return{avsInvalid:!1,invalidAvsFields:a};let v=$t,O=(ae,_t)=>ot(ae,v)&&!_t.trim(),Pe={line1:O(W.address_line_1,Mt),city:O(W.city,wt),state:O(W.state,yn),zip:Mn.empty||Mn.malformed};return{avsInvalid:Pe.line1||Pe.city||Pe.state||Pe.zip,invalidAvsFields:Pe}},[m,W,$t,Mt,wt,yn,Mn]),[Jt,ar]=ue(!1),[xn,Tr]=ue(!1),[Bn,gr]=ue(!1),[hr,Ar]=ue({line1:!1,city:!1,state:!1}),jn=ne(!1),Gn=ne({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Mr=ne(!1),xt=Xe(a=>{Gn.current[a]=!0,Mr.current=!0},[]),wn=Xe(a=>!jn.current&&Gn.current[a],[]),Yn=Xe(a=>{wn(a)&&Ar(v=>v[a]?v:{...v,[a]:!0})},[wn]),[ir,Pr]=ue(()=>ms(E?.vault,{billingApiUrl:at,sessionId:e,nonce:t})),[Ve,ln]=ue(Gt&&tt?"card":"buttons"),[cn,In]=ue(null),Qr=Ve==="expanding"||Ve==="card",vr=E?.gateways?.stripe&&!Tn?"stripe":void 0,Or=Xe(()=>{St?.({class:"card_surface",provider:vr})},[vr,St]),kn=ne(null),dn=Xe(a=>{kn.current&&clearTimeout(kn.current),kn.current=setTimeout(()=>{kn.current=null,a()},wa)},[]);gt(()=>()=>{kn.current&&clearTimeout(kn.current)},[]);let sr=ne(!1),[fn,k]=ue(0),_=ne(null),K=Xe(()=>{Or(),$(e??null),sr.current&&(sr.current=!1,k(a=>a+1)),qn(a=>a+1),ln("expanding"),dn(()=>ln("card"))},[dn,Or,e]),oe=Xe(()=>{ln("collapsing"),dn(()=>ln("buttons"))},[dn]),it=Xe(a=>{In(a),ln("apm-expanding"),dn(()=>ln("apm-form"))},[dn]),Xt=Xe(()=>{ln("apm-collapsing"),dn(()=>{ln("buttons"),In(null)})},[dn]);gt(()=>{Re==="buttons"&&Gt&&tt&&($(e??null),ln("card"))},[Re,Gt,tt,e]);let[ee,H]=ue(null),B=ne(!1),l=ne(null),c=ne("idle"),[S,R]=ue(!1),te=ne(S);te.current=S;let[Z,dt]=ue(()=>mt?.existingOrderId?{orderId:mt.existingOrderId,attempts:1}:null),Lt=ne(Z);gt(()=>{Lt.current=Z},[Z]);let be=ne(null),Ie=ft(()=>{if($e||Ne.claimBuyerIdentity||E?.buyerIdentified!==!1||!e||!t)return;let a=`${at}|${e}|${t}`;be.current?.key!==a&&(be.current={key:a,claim:ko(new Oo(at,{telemetry:!1}),e,t,{...i?{userId:i}:{},...w?{firstName:w}:{},...b?{lastName:b}:{}})});let v=be.current.claim;return async O=>{await v(O)}},[$e,Ne.claimBuyerIdentity,E?.buyerIdentified,e,t,at,i,w,b]),We=$e??Ne.claimBuyerIdentity??Ie,G=U??On,Q=ft(()=>Fu(st),[st]),P=ft(()=>{let a=Q?.buttonsLayout??Bu(qt);return fe?{...a,...fe,cardButton:{...a.cardButton,...fe.cardButton},cardFormContainer:{...a.cardFormContainer,...fe.cardFormContainer},backButton:{...a.backButton,...fe.backButton},backButtonIcon:{...a.backButtonIcon,...fe.backButtonIcon},submitButton:{...a.submitButton,...fe.submitButton},title:{...a.title,...fe.title}}:a},[Q,qt,fe]),Y=Ae??Q?.appearance,Ye=ft(()=>Il({appearance:Y,buttonsStyles:P,layout:Re}),[Y,P,Re]),Rt=Ne.inlineSessionPatchProcessing??!1,z=(N??de)||Rt,vn=at.replace(/\/+$/,""),Le=ft(()=>Vi({userId:i,email:o,firstName:w,lastName:b,country:M,zip:Se},Wn),[i,o,w,b,M,Se,Wn]),co=[Le.firstName,Le.lastName].filter(a=>!!a?.trim()).join(" "),Ls=!gn(Le.email?.trim()),hi=ne(null);m&&hi.current===null&&(hi.current=Ls);let Lr=m&&(hi.current??Ls),Pi=ft(()=>dp(Qt,Lr),[Qt,Lr]),uo=Pi.empty||Pi.malformed,$n=ft(()=>we?we.getRawProvider():null,[we]),Us=ft(()=>yt?yt.getRawProvider():null,[yt]),Ko=Fe||100,po=vt.toLowerCase(),vi=ft(()=>Y?bu(Y):null,[Y]),mo=vi,zs=ft(()=>{let a=vi??{},v=a.rules??{};return{...a,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[vi]),qs=ft(()=>({...Wl(Fe,ct?.captureMethod,he),currency:po,...mo?{appearance:mo}:null}),[Fe,po,ct?.captureMethod,he,mo]),bi=Ec(he,"paypal","paypal"),js=ft(()=>({mode:"payment",amount:Ko,currency:po,captureMethod:"manual",...bi?{setupFutureUsage:bi}:null,...mo?{appearance:mo}:null}),[Ko,po,bi,mo]),ye=Xe(a=>{mn(a),h?.(a)},[h]),$s=ne(0);gt(()=>{fn!==$s.current&&($s.current=fn,ye(null))},[fn,ye]);let Ci=ne(""),[Ks,Yc]=ue(!1),Si=Xe(()=>{Yc(!0)},[]);gt(()=>{if(!m||!Lr||!We||!Ks||uo||Ci.current)return;let a=Nn({email:gn(Le.email?.trim())?Le.email?.trim():on.current.trim(),firstName:Le.firstName?.trim(),lastName:Le.lastName?.trim()});Ci.current=JSON.stringify(a),en(v=>({...v,...a})),Promise.resolve(We(a)).catch(v=>{Ci.current="",ye(v instanceof Error?v.message:"Failed to attach buyer details.")})},[m,Lr,We,Ks,uo,Le.email,Le.firstName,Le.lastName,ye]),gt(()=>{!m||!kt||kt.setCardFieldOrder?.(Ce??null,W==null&&!Lr)},[m,kt,Ce,W,Lr]),gt(()=>{(Ve==="expanding"||Ve==="collapsing"||Ve==="apm-expanding"||Ve==="apm-collapsing")&&ye(null)},[Ve,ye]);let br=Xe((a,v,O)=>{f?.(un(a,v,O))},[f]),yo=Xe((a,v,O)=>{let Pe=O?.popupBlocked??zr(v);Pe&&p.markBlocked()&&g(Je=>Je+1);let q=Ua(Ps(a),Pe,A.inAppBrowser),ae=Ur(v),_t=(ae?.toLowerCase()==="error"?void 0:ae)??kl(O?.code)??"external_payment_method_failed",dr=new mr(q,"api_error",{code:"external_payment_method_failed",param:a,details:{providerCode:_t,popupBlocked:Pe,inAppBrowser:A.inAppBrowser,appFamily:A.appFamily,popupCapability:p.current(),presentationMode:O?.presentationMode??"popup"}});O?.telemetryReported||pn(we)?.error(No({...re,presentationMode:O?.presentationMode??"popup"},{errorCode:Pe?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:O?.provider??(a==="paypal"?"paypal":"stripe"),paymentMethodCategory:O?.paymentMethodCategory??(a==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:O?.terminalReason??(Pe?"popup_blocked":"provider_error")})),H(null),Re==="buttons"&&(ln("buttons"),In(null)),ye(q),d?.(dr),console.error("[FloPay] External payment method failed:",{method:a,code:_t,popupBlocked:Pe})},[A,re,we,Re,d,p,ye]);gt(()=>{if(!m||!e){Pr(null);return}let a={billingApiUrl:vn,sessionId:e,nonce:t},v=ms(E?.vault,a);if(v){Pr(v);return}if(!Yt){Pr(null);return}let O=`${vn}\0${e}\0${t??""}`,Pe=_.current;if(Pe&&Pe.key===O){Pr(Pe.mount);return}Pr(null);let q=!0;return new Oo(vn).getVaultCapture(e,t).then(ae=>{if(!q)return;let _t=ms(ae,a);_t?.verificationRequired&&!ae.html&&(_.current={key:O,mount:_t}),_t?Pr(_t):ye("Failed to load the secure card form.")}).catch(ae=>{q&&ye(ae instanceof Error?ae.message:"Failed to load the secure card form.")}),()=>{q=!1}},[m,Yt,Pn,e,E?.vault,vn,t,ye]);let lr=ne({onComplete:s,onError:d,updateError:ye,emitDecline:br,resolvedAccount:Le,avsConfig:W,avsCheckProp:Ze,sessionId:e,nonce:t,baseUrl:vn,captureMethod:E?.captureMethod,paymentId:E?.paymentId,authorizationExpiresAt:E?.authorizationExpiresAt,serverSideCardGateway:Tn});lr.current={onComplete:s,onError:d,updateError:ye,emitDecline:br,resolvedAccount:Le,avsConfig:W,avsCheckProp:Ze,sessionId:e,nonce:t,baseUrl:vn,captureMethod:E?.captureMethod,paymentId:E?.paymentId,authorizationExpiresAt:E?.authorizationExpiresAt,serverSideCardGateway:Tn};let wi=ne(!1),Vs=Xe(()=>{let a=lr.current,v=a.resolvedAccount.email?.trim(),O=gn(v)?v:on.current.trim();if(!gn(O))return null;let Pe=a.resolvedAccount.firstName?.trim(),q=a.resolvedAccount.lastName?.trim(),ae=tn.current.trim()||a.resolvedAccount.country?.trim()||"",_t=a.avsConfig?ot(a.avsConfig.state,ae):!1,dr=a.avsConfig?ot(a.avsConfig.address_line_1,ae):!1,Je=a.avsConfig?ot(a.avsConfig.postal_code,ae):!1,lt=a.avsConfig?ot(a.avsConfig.city,ae):!1,ut=a.avsConfig?ot(a.avsConfig.address_line_2,ae):!1,Ut=dr&&!_t&&Je?yc(ae,(It.current??"").trim()):null,no=_t?Ot.current:Ut;return{accountData:{userId:a.resolvedAccount.userId??"",email:O,...Pe?{firstName:Pe}:{},...q?{lastName:q}:{},...Je&&It.current?{zip:It.current}:{},...lt&&sn.current?{city:sn.current}:{},...no?{state:no}:{},...dr&&rn.current?{addressLine1:rn.current}:{},...ut&&Dt.current?{addressLine2:Dt.current}:{},...ae?{country:ae}:{}},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:ot(a.avsConfig.country,ae),postal_code:Je,address_line_1:dr,address_line_2:ut,city:lt,state:_t}}:{}}},[]),Ws=ne(X);Ws.current=X,gt(()=>{X||G!==vc||lr.current.updateError(null)},[X,G]),gt(()=>{!m||!kt||kt.setSubmitGate?.(fr||X||uo||S)},[m,kt,fr,X,uo,S]),gt(()=>{if(!m||!kt)return;wi.current=!1;let a=null,v=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,c.current="idle",H(null)},400)},O=kt.on("submitting",()=>{ar(!0),l.current&&clearTimeout(l.current),c.current="validation-window",l.current=setTimeout(()=>{l.current=null,c.current==="validation-window"&&(c.current="processing")},Zu),H("processing");let Je=lr.current;if(!Je.sessionId||!Je.nonce)return;let lt=Vs();if(!lt){Je.updateError("Enter a valid email address."),c.current="idle",H(null);return}new Oo(Je.baseUrl).patchAccountSnapshot(Je.sessionId,Je.nonce,lt,{telemetryMode:"best_effort"}).catch(ut=>{if(!ep(ut))return;let Ut=ut instanceof Error?ut.message:"Please check your billing address and try again.";Je.updateError(Ut),c.current="idle",H(null),Je.onError?.(ut instanceof mr?ut:new mr(Ut,"api_error"))})}),Pe=kt.on("complete",Je=>{Bo(Je.sessionId??lr.current.sessionId),c.current="terminal",R(!1),H("success"),setTimeout(()=>{if(wi.current)return;wi.current=!0;let lt=lr.current,ut=us(lt)||Je.outcome==="authorized",Ut=lt.serverSideCardGateway?{}:{paymentIntentId:Je.intentId};lr.current.onComplete?.(ut?{status:"authorized",...Ut,paymentId:Je.paymentId??lt.paymentId,sessionId:Je.sessionId??lt.sessionId,authorizationExpiresAt:Je.authorizationExpiresAt??lt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Ut,checkoutMethod:"card"})},600)}),q=kt.on("decline",Je=>{let lt=lr.current,ut=Je.message??"Your payment was declined. Please try another card or contact your bank.";c.current="terminal",R(!1),lt.updateError(ut),H("error");let Ut=Je.failureOutcome??Tu(Je.declineReason)??"authorization_declined";lt.emitDecline("card",ut,{code:Ut,declineCode:Ut}),v()}),ae=kt.on("error",Je=>{let lt=lr.current,ut=Je.message??"There was a problem processing your payment. Please try again.";c.current="terminal",R(!1),lt.updateError(ut),H("error"),lt.onError?.(new mr(ut,"api_error",{code:Je.failureOutcome??"capture_failed"})),v()}),_t=kt.on("challenge_dismissed",()=>{l.current&&(clearTimeout(l.current),l.current=null),c.current="processing",R(!0),H(null)}),dr=kt.on("blocked",()=>{if(te.current){lr.current.updateError(Qu);return}if(!Ws.current){ar(!0);return}Si(),lr.current.updateError(vc)});return()=>{a&&(clearTimeout(a),a=null),l.current&&(clearTimeout(l.current),l.current=null),c.current="idle",R(!1),H(null),O(),Pe(),q(),ae(),_t(),dr()}},[m,kt,Si,Vs]);let Cr=!!mt?.clientId,Vo=Array.isArray(ve),Ea=Vo&&ve.length>0,Hs=Vo&&ve.includes("paypal"),Ta=ne(null);Ta.current===null&&(Ta.current=Ju());let fo=Ta.current?"redirect":_l(A,D,p.current()),{expressMethods:Aa,paymentElementMethods:Wo}=ft(()=>Au(ve,{excludePaypal:Cr}),[ve,Cr]),Gs=Cr||!!yt||Hs&&fo==="redirect",Jc=ft(()=>Gs?Aa.filter(a=>a!=="paypal"):Aa,[Aa,Gs]),Xc=ft(()=>{let a=[];return ke&&a.push("apple_pay"),qe&&a.push("google_pay"),a},[ke,qe]),go=Vo?Jc:Xc,Zc=le&&go.length>0,Ii=tr?$t:M,Ma=ft(()=>{let a=Ii?.trim().toUpperCase();return a?J?Wo.filter(v=>{let O=J[v];return!O||O.length===0||O.includes(a)}):wu(Wo,Ii):Wo},[Wo,Ii,J]),ki=ft(()=>({mode:"payment",amount:Ko,currency:po,paymentMethodCreation:"manual",appearance:zs}),[Ko,po,zs]),[Ys,Js]=ue("loading"),[Xs,Zs]=ue("loading"),[Qs,el]=ue("loading"),[Qc,Ri]=ue(!1),[tl,_i]=ue("loading"),[Ei,ed]=ue();gt(()=>{ed(ia())},[]);let xa=Ei?.inAppBrowser,Ba=Ei?qa(Ei,mt?.approvalPresentation,Ke??(Tt?"subscription":"order")):"popup",nl=C&&(Cr||(Vo?Hs:xa===!1)),rl=le&&Zc,Ho=(!bt||!!Ne.waitForDataAttachment)&&nl&&Cr,ol=tl==="retrying"||tl==="exhausted",Go=null;le&&(yt?Go=Us:fo==="redirect"&&(Go=$n));let al=ft(()=>({...re,presentationMode:fo}),[re,fo]),Yo=!bt&&nl&&!!Go&&(!Cr||ol),ho=!bt&&rl&&!!$n,Jo=!bt&&le&&Ea&&Ma.length>0&&!!$n,td=Ho&&!ol?Qc:Yo&&qi(Ys),nd=ho&&qi(Xs),rd=Jo&&Qs!=="load_error",il=a=>a==="loading"||a==="ready",sl=Ho||Yo&&il(Ys)||ho&&il(Xs)||Jo&&Qs!=="load_error",Fa=ne(!1);gt(()=>{if(!Fa.current){if(!le&&!C){Fa.current=!0;let a=new mr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(a),ye(a.message)}else if(!le&&C&&!Cr){Fa.current=!0;let a=new mr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(a),ye(a.message)}else if(xa!==void 0&&!bt&&!tt&&!sl){Fa.current=!0;let a=new mr("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"});d?.(a),ye(a.message)}}},[le,C,Cr,xa,bt,tt,sl,d,ye]);let ll=ne(!1);gt(()=>{if(ll.current||!Ea)return;let a=[];ke!==!0&&a.push("showApplePay"),qe!==!0&&a.push("showGooglePay"),a.length!==0&&(ll.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.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.`))},[Ea,ke,qe]);let cl=Xe((a,v)=>Ne.applyInlineSessionPatch?Ne.applyInlineSessionPatch(a).then(O=>({error:null,sessionId:O.sessionId||e,nonce:O.session?.clientSecret||t})).catch(O=>{let Pe=wc(v,O);return ye(Pe.message),d?.(Pe),{error:Pe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ne.applyInlineSessionPatch,t,d,e,ye]),cr=Xe(async a=>{if(a!=="card"&&bt&&await Ne.waitForDataAttachment?.(),!je)return{proceed:!0};try{let v=await je({method:a,sessionId:e||void 0,createSession:Ne.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&en(Pe=>({...Pe??{},...v.account}));let O=await cl(v,a);return O.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:O.sessionId,nonce:O.nonce}}return{proceed:!0}}catch(v){let O=wc(a,v);return ye(O.message),d?.(O),{proceed:!1}}},[cl,Ne.inlineSessionDraft,Ne.waitForDataAttachment,bt,je,d,e,ye]),dl=Xe(async(a,v)=>{if(B.current)return;B.current=!0,_n(!0),H("processing"),ye(null);let O=v?.sessionId??e,Pe=v?.nonce??t,q=Vi(Le,v?.accountPatch),ae=v?.completionPaymentMethodId??da(a),_t=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,dr=op(a),Je=v?.presentationMode?si(pn(we),{...re,presentationMode:v.presentationMode}):void 0,lt=()=>{St?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:dr}),Je?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...pr,requestCategory:"process_payment"})};try{let ut=new Oo(vn),Ut=await ut.processPayment(q.userId??"",{sessionId:O,nonce:Pe,paymentMethodCategory:v?.paymentMethodCategory??ip(a),tokenizedData:_t,accountData:{...v?.accountPatch,userId:q.userId??"",email:q.email??"",firstName:q.firstName||void 0,lastName:q.lastName||void 0,...W?(()=>{let Et=tn.current,Sr=ot(W.state,Et),Vn=ot(W.address_line_1,Et),wr=ot(W.postal_code,Et),ro=Vn&&!Sr&&wr?yc(Et,(It.current??"").trim()):null,na=Sr?Ot.current:ro;return{country:Et,...wr&&It.current?{zip:It.current}:{},...ot(W.city,Et)&&sn.current?{city:sn.current}:{},...na?{state:na}:{},...Vn&&rn.current?{addressLine1:rn.current}:{},...ot(W.address_line_2,Et)&&Dt.current?{addressLine2:Dt.current}:{}}})():{}},chv:j,avsCheck:Ze??!1,checkoutType:xe,checkoutLayout:et,avsConfig:W?{country:ot(W.country,tn.current),postal_code:ot(W.postal_code,tn.current),address_line_1:ot(W.address_line_1,tn.current),address_line_2:ot(W.address_line_2,tn.current),city:ot(W.city,tn.current),state:ot(W.state,tn.current)}:void 0}),no=async Et=>{let Sr=us(E)||Et?.status==="authorized";Bo(O),Je?.terminal({outcome:"payment_succeeded",...pr}),H("success"),dt(null),await new Promise(ro=>setTimeout(ro,600));let Vn;typeof Et?.paymentId=="string"?Vn=Et.paymentId:E?.paymentId&&(Vn=E.paymentId);let wr;typeof Et?.authorizationExpiresAt=="string"?wr=Et.authorizationExpiresAt:E?.authorizationExpiresAt&&(wr=E.authorizationExpiresAt),s?.(Sr?{status:"authorized",...Vn===void 0?{}:{paymentId:Vn},sessionId:typeof Et?.sessionId=="string"?Et.sessionId:O,...wr===void 0?{}:{authorizationExpiresAt:wr},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ae,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ae,checkoutMethod:a.isPaypal?"paypal":"card"})};if(Ut.ok){await no(Ut.status===204?null:await Ut.json().catch(()=>null));return}let Kn=await Ut.json().catch(()=>null);if(Kn?.type==="paypal_redirect_required"){let Et=Kn.threeDSecureToken,Sr=Kn.paymentMethodId||a.id||"";if(!we||!Et){H("error"),ye("PayPal authorization required but no token provided.");return}try{let Vn=yt?.getRawProvider();if(!Vn){ye("PayPal is not available.");return}let wr={return_url:window.location.href};Sr&&(wr.payment_method=Sr);let{error:ro}=await Vn.confirmPayment({clientSecret:Et,confirmParams:wr,redirect:"if_required"});if(ro){H("error");let na=ro.message??"PayPal payment failed.";ye(na),br("paypal",na,{code:ro.code})}}catch(Vn){H("error"),ye(Vn instanceof Error?Vn.message:"PayPal authorization failed.")}return}if(Kn?.type==="paypal_direct_required"){let Et=Kn.orderId;if(!Et){H("error"),ye("PayPal retry required but no order id provided.");return}let Sr=Lt.current?.attempts??0;if(Sr>=2){H("error"),ye("PayPal payment could not be completed after multiple attempts."),br("paypal","paypal_direct_required retry limit exceeded");return}Ri(!1),_i("loading"),dt({orderId:Et,attempts:Sr+1}),H(null);return}if(Ut.headers.get($u)===Ku){let Et=await Vu(ut,O,Pe);if(Et!==void 0){await no(Et);return}}Su(Ut.status,Kn)?Je?.terminal({outcome:"payment_declined",...pr,terminalReason:"provider_declined"}):lt(),H("error");let Cl=Kn?.message??"Payment failed. Please try again.";ye(Cl),br(a.isPaypal?"paypal":"card",Cl,{code:Kn?.code??Kn?.gatewayErrorCode,declineCode:Kn?.declineCode??Kn?.gatewayDeclineReason}),await new Promise(Et=>setTimeout(Et,400))}catch(ut){Bc(ut)||lt(),H("error"),ye(ut instanceof Error?ut.message:"An unexpected error occurred"),await new Promise(Ut=>setTimeout(Ut,400))}finally{_n(!1),H(null),B.current=!1}},[vn,e,t,Le,W,Ze,xe,et,j,we,yt,E,s,ye,br,St,re]),Fn=Xe((a,v)=>{u?u(a):dl(a,v)},[u,dl]),Xo=`${Ac}:${e}`;gt(()=>{if(typeof window>"u")return;let a=localStorage.getItem(Xo);if(!a)return;let v;try{v=JSON.parse(a)}catch{Wt(Xo);return}if(!v||typeof v.createdAt!="number"||Date.now()-v.createdAt<0||Date.now()-v.createdAt>Mc||typeof v.paymentMethodId!="string"||typeof v.providerIntentId!="string"||typeof v.paymentMethodType!="string"||v.sessionId!==e||!t||v.nonce!==t||!go.includes(v.paymentMethodType)){Wt(Xo);return}Wt(Xo),Fn({id:v.paymentMethodId,type:"card",threeDSecureActionResultTokenId:v.providerIntentId,gateway:"stripe",paymentMethodType:v.paymentMethodType},{...v.accountPatch?{accountPatch:v.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Fn,t,e,Xo,go]);let ul=ne(!1);gt(()=>{if(typeof window>"u"||ul.current)return;let[a,v,O]=ws();if(!a||!v||Ta.current||!we)return;let Pe=we.getRawProvider();if(!Pe)return;let q=lt=>{let ut=localStorage.getItem(lt);if(!ut)return null;try{return JSON.parse(ut)}catch{return Wt(lt),null}},ae=q(_r)??q(gc),_t;if(ae?.clientSecret){if(ae.clientSecret!==v)return;_t={...ae.accountPatch?{accountPatch:ae.accountPatch}:{},...ae.sessionId?{sessionId:ae.sessionId}:{},...ae.nonce?{nonce:ae.nonce}:{}}}else if(ae?.sessionId&&ae.sessionId!==e)return;ul.current=!0,Wt(_r),Wt(gc),window.history.replaceState({},"",Is());let dr=ae?.paymentMethodType??ae?.tokenType??"card",Je="card";(async()=>{if(O==="failed"){let xr="Payment was declined. Please try again.";ye(xr),br(Je,xr);return}let{paymentIntent:lt,error:ut}=await Pe.retrievePaymentIntent(v);if(ut){let xr=ut.message??"Failed to retrieve payment status.";ye(xr),br(Je,xr,{code:ut.code});return}let Ut=lt?.status,no=ca(Ut);if(!lt||!no){let xr=Ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ye(xr),br(Je,xr,{code:Ut??"missing_payment_intent"});return}let Kn=typeof lt.payment_method=="string"?lt.payment_method:lt.payment_method?.id;Fn({id:Kn??ae?.paymentMethodId??ae?.tokenId??lt.id,type:"card",threeDSecureActionResultTokenId:lt.id,gateway:ae?.gateway??"stripe",paymentMethodType:dr},_t)})()},[e,Fn,we,ye,br]);let Ti=Xe(a=>{a.preventDefault()},[]);if(!(m||we!==null))return y("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Zo=Re==="buttons",Dn=Y?.variables,od=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ai=Dn?.colorBackground,ad=Ai&&!od.has(Ai)?Ai:void 0,Qo=P.cardInputBorder??(Zo?"#e5e7eb":"#A4A4FF"),pl=Dn?.colorDanger??"#dc2626",Vt=a=>Hn[a]&&(hr[a]||Jt),Da=uo&&(Bn||Jt),Jn=a=>a?pl:Qo,Na=(Mn.malformed||Mn.empty)&&(xn||Jt),id=Jn(Na),Mi=P.cardFormContainer?.backgroundColor??ad??(Zo?"white":"#EDEDFF"),Po=P.cardInputBackground??Dn?.colorBackground??"white",xi=Co(Ee),ml=Co(He),vo=P.nameInput,yl=P.cardInputFontSize??up(vo?.fontSize)??Dn?.fontSizeBase??"16px",fl=typeof vo?.fontFamily=="string"?vo.fontFamily:Dn?.fontFamily??"Poppins, sans-serif",gl=wl(vo?.fontWeight)??400,sd=P.cardInputColor??(typeof vo?.color=="string"?vo.color:void 0)??Dn?.colorText??"#262833",ld=P.cardInputPlaceholderColor??"#9ca3af",Zt=Dn?.borderRadius??"8px",eo=Dn?.borderRadius??P.cardButton?.borderRadius??Zt,to=Dn?.colorPrimary??"#4A49FF",cd=Dn?.colorPrimaryHover??oa(to,.12),Bi=Dn?.colorText??"#262833",Fi={fontSize:yl,fontFamily:fl,fontWeight:gl,color:sd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ea={marginTop:"0.375rem",...Fi,fontSize:"0.75rem",lineHeight:1.4,color:pl},dd={"--flopay-input-placeholder-color":ld,"--flopay-input-font-size":yl,"--flopay-input-font-family":fl,"--flopay-input-font-weight":String(gl)},ta=P.cardFormContainer??{},Di=ta.padding??(Zo?"0":"1rem"),Ni=ta.borderRadius??Zt,ud=kt&&ir?y(Oi,{capture:kt,html:ir.html,messageToken:ir.messageToken,expectedOrigin:ir.expectedOrigin,verificationRequired:ir.verificationRequired,theme:Ye,submitLabel:I,onReady:()=>{if(!Lr&&!W||typeof document>"u")return;let a=()=>{let O=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(O){jn.current=!0;try{O.focus()}finally{jn.current=!1}}};Mr.current||a()},onError:a=>{a&&ir.verificationRequired&&c.current==="idle"&&(sr.current=!0),ye(a)},onValidation:a=>{let v=c.current;(v==="idle"||v==="validation-window")&&(ye(a),a&&c.current==="validation-window"&&(l.current&&(clearTimeout(l.current),l.current=null),c.current="idle",H(null)))}},fn):y("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"}),hl=Qe("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&Or()},style:{backgroundColor:Mi,borderRadius:Ni,...ta,padding:Di,...dd,display:"flex",flexDirection:"column"},children:[y("style",{children:`
|
|
3
|
+
${_t.join(`
|
|
4
|
+
`)}`]}):null;return yt&&!H?pe?to("div",{children:et}):null:ji("div",{children:[et,Oe&&to(Io,{identity:Oe.identity,methodLabel:Oe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Se,onCancel:()=>Se(null)}),ji("div",{"aria-hidden":vt||Oe?!0:void 0,style:vt||Oe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:$a},children:[!Me&&!vt&&to("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"}}),to("div",{ref:Q,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:$a,display:"flex",opacity:Me?1:0},"aria-busy":I||v},Ee)]},Ee),Qe&&to("button",{ref:Ce,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Cn,style:tu,children:"Try PayPal again"})]})}function Wa(e){return to(Hl,{...e})}function Vl(e){return to(Hl,{...e})}import{jsx as Kl,jsxs as au}from"react/jsx-runtime";function Eo({children:e,margin:t,icon:n=!0,styleOverride:o}){return au("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,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...o??{}},children:[n&&Kl("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Kl("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]})}import{clearCachedInlineCheckout as Ha,clearCachedInlineSession as $i,hashCreateParams as Gl,legacyCachedSessionMatchesDraft as Yl,persistCachedInlineIdempotencyKey as Va,persistCachedInlineSession as Ka,readCachedInlineIdempotencyKey as Jl,readCachedInlineSession as Zl,serializeCreateParams as da}from"@flopay/shared";import{resolveBillingApiUrl as iu}from"@flopay/shared";import{useEffect as Hr,useMemo as su,useRef as Xl,useState as Ql}from"react";import{jsx as lu}from"react/jsx-runtime";function Ga({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=Ql(e instanceof Promise?null:e),[c,f]=Ql(t instanceof Promise||!t?null:t),C=Xl(null),E=Xl(null),k=Ro(o);Hr(()=>{k({class:"lifecycle",name:"checkout.mount"})},[k]),Hr(()=>{i&&k({class:"lifecycle",name:"sdk.initialize.ready"})},[k,i]),Hr(()=>{if(i)return pn(i)?.subscribe?.(k)},[k,i]),Hr(()=>{if(!(!c||c===i))return pn(c)?.subscribe?.(k)},[k,i,c]),Hr(()=>{if(!i)return;let O=pn(i);return C.current=O?.beginCheckout()??O?.now()??0,O?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{O?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Hr(()=>{let O=!1;return e instanceof Promise?e.then(ve=>{O||s(ve)},()=>{O||k({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{O=!0}},[k,e]),Hr(()=>{let O=!1;if(!t){f(null);return}return t instanceof Promise?t.then(ve=>{O||f(ve)},()=>{O||k({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):f(t),()=>{O=!0}},[k,t]),Hr(()=>{if(!i||E.current===i)return;E.current=i;let O=pn(i);O?.log({name:"checkout.rendered",stage:"checkout_render"}),k({class:"lifecycle",name:"checkout.rendered"}),O?.performance({stage:"checkout_render",durationMs:O.elapsed(C.current??0),durationMode:"machine"})},[k,i]);let z=iu(n?.billingApiUrl),ne=su(()=>({flopay:i,paypalFlopay:c,billingApiUrl:z,emitInstrument:k}),[i,c,z,k]);return lu(Gn.Provider,{value:ne,children:a})}import{markSessionRecentlyCompleted as _o,wasSessionRecentlyCompleted as Wi}from"@flopay/shared";async function Ya(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{completeSavedCardNextAction as cu,loadFloPay as ec,PaymentAPI as Za,runSavedCardChallenge as du}from"@flopay/js";import{classifyPaymentRejection as uu,FloPayError as St,isAuthorizationOnlySession as pu,isMountableVaultBlock as yu,isSetupIntentClientSecret as mu,normalizeCheckoutFailureOutcome as tc}from"@flopay/shared";var pa="card";async function fu(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:o,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:o??null}}async function gu(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:s??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function To(e){return new St("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function hu(){return new St("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Vi(e,t){return Object.assign(e,{checkoutMethod:t})}function xr(e,t){let n=e instanceof St?e:new St(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function ua(e,t){try{return await e()}catch(n){throw xr(n,t)}}function rc(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function oc(e){return du(e)}async function Mo(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,s=new Za(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,f;try{f=await cu({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:E=>kr({type:E.declineReason??"authorization_declined",gatewayErrorCode:E.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},s)}catch(E){if(a.aborted||E instanceof Error&&E.name==="AbortError")throw E instanceof St&&E.code==="three_ds_aborted"?E:To(E);if(!(E instanceof St)||E.code!=="three_ds_timeout"&&E.code!=="checkout_processing_timeout")throw E;try{f=await s.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:c,timeoutMs:5e3,signal:a})}catch(z){if(a.aborted)throw To(z);if(!(z instanceof St)||z.code!=="checkout_processing_timeout")throw z}let k=f&&qr(f,t.session);if(!Ar(k)&&k?.status!=="expired"){if(t.telemetry){let z=new Za(n);try{z.reportThreeDsAbandoned(o)}finally{z.destroy()}}throw hu()}}let C=f&&qr(f,t.session);if(!Ar(C))throw So(C);return{...Mr(C,o),checkoutMethod:"card"}}function kr(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=wo(a)??a,s=Vi(new St(i,"api_error",{code:e?.code??tc(e?.outcome)??tc(e?.type)??e?.gatewayErrorCode}),o);return e?.orderId&&(s.orderId=e.orderId),s}function Hi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ja(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ac(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ja(a)))return a;let o=e?.data;if(o&&typeof o=="object"){let a=o,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let c of i)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||Ja(c)))return c;let s=a.gateways;if(s&&typeof s=="object"){let c=s.stripe;if(c&&typeof c=="object"){let f=c,C=[f.stripeClientSecret,f.clientSecret];for(let E of C)if(typeof E=="string"&&E.length>0&&(!t?.requirePaymentIntentClientSecret||Ja(E)))return E}}}}async function Pu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=ac(o,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let c=(await new Za(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ja(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Ao({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:s}){let c=e.replace(/\/+$/,""),f=t??n.id,C=o??n.clientSecret,E=n.customer?.id??n.accountData?.userId??"",k=n.customer?.email??n.accountData?.email??"",z=n.customer?.firstName??n.accountData?.firstName??"",ne=n.customer?.lastName??n.accountData?.lastName??"",O=n.customer?.country??n.accountData?.country??void 0,ve=n.customer?.zip??n.accountData?.zip??void 0,v=await new Za(c,s===!1?{telemetry:!1}:void 0).processPayment(E,{sessionId:f,nonce:C,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:E,email:k,firstName:z,lastName:ne,country:O,zip:ve},returnUrl:i??Hi(n)});if(v.ok){let N=typeof v.json=="function"?await v.json().catch(()=>null):null;if(pu(n)||N?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof N?.paymentId=="string"?N.paymentId:n.paymentId,sessionId:typeof N?.sessionId=="string"?N.sessionId:f,authorizationExpiresAt:typeof N?.authorizationExpiresAt=="string"?N.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:oa(a),checkoutMethod:nc(a,n)}};let Ie=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Ie?{paymentIntentId:Ie}:{},paymentMethodId:oa(a),checkoutMethod:nc(a,n)}}}let P;try{P=await v.json()}catch(N){throw new St("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:v.status,cause:N})}if(P?.type==="3ds_required"&&typeof P.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:P.nextActionRedirectUrl};if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let N=ac(P);if(!N)throw new St("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:v.status});return{type:P.type,threeDSecureToken:N,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let N=await Pu({billingApiUrl:c,sessionId:f,nonce:C,responseJson:P});if(N)return N;throw Vi(new St("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let he=new St(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:v.status});throw Object.assign(he,{telemetryOutcome:uu(v.status,P)})}async function Xa(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:c,telemetry:f,signal:C}){let E=t?.getRawProvider();if(!E)throw xr(new St("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw Vi(new St("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let k=mu(e.threeDSecureToken),z=null,ne=e.paymentMethodId,O=await ua(()=>fu(E,e.threeDSecureToken,k),"card");if(O){if(O.error)throw xr(new St(O.error.message??`Failed to retrieve 3DS ${k?"setup":"payment"} status.`,"api_error",{code:O.error.code}),"card");let V=O.intent;!ne&&V?.payment_method&&(typeof V.payment_method=="string"?ne=V.payment_method:"id"in V.payment_method&&(ne=V.payment_method.id??void 0))}let ve=ne?await ua(()=>gu(E,e.threeDSecureToken,{payment_method:ne,return_url:c??Hi(s)??window.location.href},k),"card"):null;if(ve){if(ve.error)throw xr(new St(ve.error.message??"3DS authentication failed.","api_error",{code:ve.error.code}),"card");z=ve.intent}else{let V=await ua(()=>E.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(V.error)throw xr(new St(V.error.message??"3DS authentication failed.","api_error",{code:V.error.code}),"card");z=(k?V.setupIntent:V.paymentIntent)??null}if(z&&(z.status==="requires_capture"||z.status==="succeeded"||z.status==="processing")){let V=await Ao({billingApiUrl:a,sessionId:i,session:s,telemetry:f,tokenizedData:{id:z.id,type:"card",threeDSecureActionResultTokenId:z.id},returnUrl:c});return V.type==="success"?{...V.result,paymentIntentId:V.result.paymentIntentId??z.id,paymentMethodId:V.result.paymentMethodId??ne}:V.type==="next_action_required"?Mo(V,{billingApiUrl:a,sessionId:i??s.id,session:s,signal:C}):Xa(V,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:c,telemetry:f,signal:C})}throw xr(new St("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let k=(n??t)?.getRawProvider();if(!k)throw xr(new St("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:ne}=await ua(()=>k.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(ne)throw xr(new St(ne.message??"PayPal authorization failed.","api_error",{code:ne.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:z}=await ua(()=>k.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Hi(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(z)throw xr(new St(z.message??"PayPal authorization failed.","api_error",{code:z.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new St("Unsupported payment redirect state.","api_error")}function ya(e){if(e instanceof St){let o=wo(e.message);return o&&o!==e.message?Object.assign(new St(o,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.",n=wo(t)??t;return new St(n,"api_error")}function Ki(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=yu(e.data.session?.vault)||Qr(e.data.session);if(!t&&!n&&!o)throw new St("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 nc(e,t){return e?e.isPaypal?"paypal":"card":t&&Qr(t)?"card":void 0}async function Gi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:o,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[s,c]=await Promise.all([ec(e,{billingApiUrl:n,locale:o,telemetry:a}),i?ec(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(C=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",C),null)):Promise.resolve(null)]);if(!s)throw new St("The payment provider did not initialize.","authentication_error");let f=null;return i?f=c:t&&(f=s),{flopay:s,paypalFlopay:f}}import{PaymentAPI as Bo,PciVaultCardCapture as vu,toStripeAppearance as bu}from"@flopay/js";import{buildCheckoutProcessMetadata as Cu,buildProcessPaymentAvsAccount as Su,COUNTRY_OPTIONS as wu,classifyPaymentRejection as ku,clearStripePayPalReturn as Iu,FloPayError as Br,filterStripeMethodsByCountryGate as Ru,getPostalCodeExample as Eu,getPostalCodeLabel as ns,getStateFromPostalCode as _u,getStateLabel as Yi,getStateOptions as Tu,getStripeMethodDisplayName as ga,hasMatchingStripePayPalReturn as Mu,isAuthorizationOnlySession as Ji,isAVSFieldVisible as Kt,isMountableVaultBlock as Au,isPostalCodeSupported as xu,isSetupIntentClientSecret as Zi,isValidEmail as gn,isValidPostalCode as Bu,needsStripeMethodExplicitConfirm as ic,normalizeBeforeButtonClickError as sc,normalizeCheckoutFailureOutcome as Fu,partitionStripeMethods as Du,randomUuidV4 as Ou,readMatchingStripePayPalContinuation as Nu,readStripeRedirectParams as vc,resolveAVSConfig as Lu,resolveButtonsLayoutTheme as zu,resolveSetupFutureUsage as bc,resolveTheme as Uu,resolveVaultMountOptions as Xi,STRIPE_PAYPAL_RESUME_KEY as qu,derivePrimaryTileStyle as ju,stripeExpressMethodToOptionKey as $u,stripeRedirectReturnUrl as Cc}from"@flopay/shared";import{ExpressCheckoutElement as Sc,PaymentElement as Wu,Elements as no,useElements as is,useStripe as ss}from"@stripe/react-stripe-js";import Hu,{useCallback as Ye,useContext as Do,useEffect as ht,useMemo as gt,useRef as G,useState as ie}from"react";function xo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Qa(e,t){if(e)return{error:n=>e.error(xo(t,n)),log:n=>e.log(xo(t,n)),performance:n=>e.performance(xo(t,n)),terminal:n=>e.terminal(xo(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}import{Fragment as Fo,jsx as p,jsxs as Xe}from"react/jsx-runtime";var Ir="flopay_stripe_resume",lc="flopay_wallet_resume",wc="fw1",Vu="fw2",kc=300*1e3,Ku=900,Gu=25e3,Yu=25e3,Ju=1e4,ur={provider:"paypal",paymentMethodCategory:"paypal"},Zu="x-flopay-process-result-source",Xu="status";async function Qu(e,t,n){try{let o=(await e.getUnifiedCheckoutSession(t,n)).data.session;if(o?.status==="complete")return null;if(o?.status==="authorized")return{status:"authorized",paymentId:o.paymentId,sessionId:o.id||t,authorizationExpiresAt:o.authorizationExpiresAt}}catch{}}var ei={},fa=class{constructor(t){this.reason=t}};function ep(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function Xt(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 ls(e){return`${Vu}:${e}`}function ti(e){return Xt(ls(e))}function ni(e,t){if(typeof window>"u")return null;let n=ls(e);try{let o=localStorage.getItem(n);if(!o)return null;let a=JSON.parse(o);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>kc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(ti(e),null):a}catch{return ti(e),null}}function tp(e){return Xt(ls(e.sessionId),e)}function cc(e,t,n){let o=ni(e,t);return!o||o.clientSecret!==n?!1:ti(e)}function Qi(e,t,n){if(typeof window>"u")return;ni(e,t)?.clientSecret===n&&ti(e)}function np(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function es(e,t,n){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 o=n?e.status==="succeeded":ra(e.status),a=np(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function dc(e,t,n){let o=null;try{return await Promise.race([Al(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},Ju),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function rp(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Ic(e){return e instanceof Br&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ri(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new Bo(e,{telemetry:!1}).createSessionIntent(...n)}catch(a){throw Ic(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var ts=qu,ma=new Map,op=250,uc="Just a moment \u2014 we are finalizing your order. Please press pay again.",ap="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function cs(e,t,n,o){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...o?{terminalReason:o}:{}})}async function oi({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new Bo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function ip(e){return e instanceof Br&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Rc({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=aa(n),s=i.firstName?i:aa(o?.name);return dr({email:gn(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function sp({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=Rc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return gn(s.email)?s:i(a,s)}var ha=180,pc=`flopay-card-enter ${ha}ms cubic-bezier(0, 0, 0.2, 1) both`,yc=`flopay-card-exit ${ha}ms cubic-bezier(0.4, 0, 0.2, 1) both`,lp=`flopay-buttons-enter ${ha}ms cubic-bezier(0, 0, 0.2, 1) both`,cp=`flopay-buttons-exit ${ha}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function dp(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ds(e){return ju(e)}var up={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function pp(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var rs={width:"100%",minHeight:ta,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 mc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function os(e){return e==="paypal"?"PayPal":ga(e)}function yp(e){let t=Eu(e);return`Enter a valid ${ns(e)}${t?` (e.g. ${t})`:""}`}function mp(e,t,n){let o=xu(e),a=t.trim(),i=n&&o,s=i&&!a,c=i&&!!a&&!Bu(e,a);return{visible:n,supported:o,required:i,empty:s,malformed:c}}function fp(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!gn(n);return{required:t,empty:o,malformed:a,value:n}}function gp(e){return typeof e=="number"?`${e}px`:e}function us(e){return p(hp,{...e})}function fc({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:s=!1,onButtonClick:c,onDecline:f,onTechnicalFailure:C,runBeforeButtonClick:E,billingName:k,onBuyerIdentityReady:z,onLoadStateChange:ne,placeholderBorderRadius:O,popupCapabilityOwner:ve,externalTelemetryContext:V,presentationMode:v}){let P=jr(),{emitInstrument:he}=Do(Gn),N=ss(),Ie=is(),Y=gt(()=>Qa(pn(P),V),[V,P]),[Fe,lt]=ie("loading");ht(()=>{ne?.(Fe)},[Fe,ne]);let[ze,ct]=ie(!1),zt=G(!1),pe=!gn(n?.trim())||!k?.trim(),{request:Te,collect:Pt,finish:Re}=ko(),He=G(!1),ke=G(null),Q=G(null),[je,$e]=ie(0),[pt,be]=ie(!1),ye=G(!1),re=G(new Map),{startAttempt:M,finishAttempt:Ce,invalidateAttempt:Ue,isAttemptInvalidated:Me,isAttemptCurrent:U,generationRef:vt}=la((I,ee,Oe)=>{C?.(I,ee,{...Oe,popupBlocked:Oe?.popupBlocked??zr(ee),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:v,terminalReason:"overlay_timeout"}),be(!0),$e(F=>F+1)},{onHandoffObserved:()=>{ve.markAvailable(),Y?.log({name:"provider.popup.opened",stage:"overlay_open",...ur,attempt:vt.current})}});ht(()=>{pt&&Q.current?.focus()},[pt,je]);let qe=Ye(()=>{$e(I=>I+1)},[]),Ee=Ye((I,ee,Oe)=>{Ue(Oe),C?.("paypal",I,{code:ee,popupBlocked:zr(I),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:v}),be(!0),qe()},[Ue,C,v,qe]),Je=Ye(()=>{window.setTimeout(()=>{(ke.current?.querySelector("iframe")??ke.current)?.focus()},0)},[]);ht(()=>{ye.current&&(ye.current=!1,Je())},[Je,je]);let Ae=Ye(()=>{be(!1),i?.(null),Je()},[Je,i]);ht(()=>{if(!N||He.current)return;let[I,ee,Oe]=vc();if(!I||!ee)return;let F=Nu(ee);if(!F)return;He.current=!0;let Se=!0,mt=ma.get(ee);mt||(mt=Oe==="failed"?Promise.resolve(null):Promise.resolve().then(()=>N.retrievePaymentIntent(ee)),ma.set(ee,mt));let Ne={accountPatch:F.accountPatch,sessionId:F.sessionId,nonce:F.nonce},wt=()=>{Y?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...ur,requestCategory:"provider_sdk"})};return Y?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...ur}),(async()=>{try{ct(!0);let d=await mt;if(!Se)return;if(d?.error){ma.delete(ee),wt(),i?.(d.error.message??"Failed to retrieve PayPal payment status.");return}if(Iu(),ma.delete(ee),Oe==="failed"){let A="PayPal payment was declined. Please try again.";Y?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}),i?.(A),f?.(un("paypal",A));return}let m=d?.paymentIntent;if(m&&m.id!==I){wt(),i?.("Failed to match the returned PayPal payment.");return}if(m&&(m.status==="requires_capture"||m.status==="succeeded")){let A=typeof m.payment_method=="string"?m.payment_method:m.payment_method?.id;a({id:A??m.id,type:"card",threeDSecureActionResultTokenId:m.id,isPaypal:!0},{...Ne,presentationMode:"redirect"})}else{let A="PayPal payment was not completed. Please try again.";Y?.terminal({outcome:m?.status==="canceled"?"payment_cancelled":"payment_declined",...ur,terminalReason:m?.status==="canceled"?"cancelled":"provider_declined"}),i?.(A),f?.(un("paypal",A))}}catch(d){if(!Se)return;ma.delete(ee),wt(),i?.(d instanceof Error?d.message:"Failed to complete PayPal payment.")}finally{Se&&ct(!1)}})(),()=>{Se=!1,He.current=!1}},[N,a,i,f,Y]);let Qe=Ye(async(I=!1)=>{let ee=E?await E("paypal"):{proceed:!0};if(!ee.proceed)return re.current.delete(je),!1;let Oe=M("paypal");return re.current.set(je,{generation:Oe,accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce}),be(!1),Y?.log({name:`provider.${I?"redirect.started":"handoff.requested"}`,stage:I?"redirect":"overlay_open",...ur,attempt:Oe}),c?.("paypal"),!0},[c,Y,E,M,je]),De=Ye(async I=>{if(s||ze||!await Qe()){I.reject();return}I.resolve()},[s,Qe,ze]),bt=Ye(async I=>{if(!N||!Ie)return;let ee=re.current.get(je);if(ee&&!U(ee.generation)){re.current.delete(je);return}if(!ee&&Me()||ee&&!Ce(ee.generation))return;ee||Ce();let Oe=ee??null;if(re.current.delete(je),!Oe&&E){let _=await E("paypal");if(!_.proceed){I.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Oe={accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}}let F=Oe?.sessionId??e,Se=Oe?.nonce??t,mt=await sp({event:I,prepared:Oe,email:n,billingName:k,methodLabel:"PayPal",collect:Pt});if(!mt){I.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ne=mt.email,wt={...Oe?.accountPatch,...dr(mt,!0)};try{if(ct(!0),i?.(null),!F||!gn(Ne))throw new Error("Missing sessionId or email for PayPal payment");await z?.(mt);let _=N.createPaymentMethod,{error:d,paymentMethod:m}=await _({type:"paypal"});if(d){Ee(d,"stripe_paypal_create_payment_method_failed",ee?.generation),I.paymentFailed({reason:"fail"});return}let A=await ri(o,he,F,Se??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:m?.id??null,intentKind:"payment"});if(A.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let T=A.clientSecret,J={return_url:Cc()};if(m?.id&&(J.payment_method=m.id),!Xt(ts,{clientSecret:T,sessionId:F,nonce:Se,accountPatch:wt})&&v==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:me,paymentIntent:We}=await N.confirmPayment({clientSecret:T,confirmParams:J,redirect:"if_required"});if(me){if(Xt(ts),Fa(me)){let Ut=me.message??"Your payment was declined.";Y?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}),i?.(Ut),f?.(un("paypal",Ut,{code:go(me),declineCode:Ai(me)})),await oi({billingApiUrl:o,sessionId:F,nonce:Se,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:go(me)??"provider_declined"}})}else Ee(me,"stripe_paypal_confirm_failed",ee?.generation);return}Xt(ts);let H=typeof We?.payment_method=="string"?We.payment_method:We?.payment_method?.id;a({id:H??We?.id,type:"card",threeDSecureActionResultTokenId:We?.id,isPaypal:!0},{accountPatch:wt,paymentMethodCategory:"paypal",presentationMode:v,sessionId:F,nonce:Se});return}catch(_){Ee(_,"stripe_paypal_failed",ee?.generation)}finally{ct(!1)}},[N,Ie,e,t,n,k,Pt,z,o,he,a,i,f,E,Ee,Ce,U,Me,Y,v,je]),Yt=Ye(async()=>{if(!(zt.current||s||ze||!N||!Ie)){zt.current=!0,ct(!0);try{if(!await Qe(!0))return;await bt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{zt.current=!1,ct(!1)}}},[Ie,bt,s,Qe,N,ze]),yt=v==="redirect"?p("button",{type:"button",disabled:s||ze,onClick:()=>{Yt()},style:{width:"100%",minHeight:ta,border:"1px solid #d1d5db",borderRadius:O??8,background:"#ffc439",color:"#111827",cursor:s||ze?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):p(Sc,{onReady:I=>lt(xi(I,["paypal"])),onLoadError:()=>{lt("load_error"),cs(Y,"paypal","paypal","provider_error")},onClick:De,onConfirm:bt,onCancel:()=>{let I=re.current.get(je);re.current.delete(je),Y?.terminal({outcome:"payment_cancelled",...ur,terminalReason:"cancelled",...I?{attempt:I.generation}:{}}),Ue(I?.generation),be(!1),ye.current=!0,qe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:pe,emailRequired:pe,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},je),Et=Xe(Fo,{children:[Xe("div",{ref:ke,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[pt&&p("button",{ref:Q,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ae,style:rs,children:"Try PayPal again"}),Te&&p(Io,{identity:Te.identity,methodLabel:Te.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Te.id),p("div",{style:{display:Te?"none":void 0},children:yt})]}),ze&&!Te&&p(Sr,{status:"processing"})]});return v==="redirect"?Et:p(Bi,{state:Fe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:O,children:Et})}function gc(e){return e==="apple_pay"||e==="google_pay"}function hc({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:s,onErrorChange:c,onButtonClick:f,onDecline:C,onTechnicalFailure:E,runBeforeButtonClick:k,billingName:z,onBuyerIdentityReady:ne,onLoadStateChange:O,placeholderBorderRadius:ve,popupCapabilityOwner:V,externalTelemetryContext:v}){let P=jr(),{emitInstrument:he}=Do(Gn),N=ss(),Ie=is(),Y=gt(()=>Qa(pn(P),v),[v,P]),[Fe,lt]=ie("loading");ht(()=>{O?.(Fe)},[Fe,O]);let[ze,ct]=ie(!1),zt=G(!gn(n?.trim())||!z?.trim()).current,{request:pe,collect:Te,finish:Pt}=ko(),Re=G(null),He=G(null),[ke,Q]=ie(0),[je,$e]=ie(!1),[pt,be]=ie(()=>ni(e,t)?"blocked":"idle"),[ye,re]=ie("google_pay"),M=G(null),Ce=G(!0),Ue=G(!1),Me=G("google_pay"),U=G("google_pay"),vt=G(null),qe=G(null),Ee=G(new Set),Je=G(null);ht(()=>(Ce.current=!0,()=>{Ce.current=!1;for(let _ of Ee.current)window.clearTimeout(_);Ee.current.clear()}),[]);let Ae=G(new Map),{startAttempt:Qe,finishAttempt:De,invalidateAttempt:bt,isAttemptInvalidated:Yt,isAttemptCurrent:yt,generationRef:Et}=la((_,d,m)=>{E?.(_,d,{...m,popupBlocked:m?.popupBlocked??zr(d),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),re(_),$e(!0),Q(A=>A+1)},{onHandoffObserved:_=>{V.markAvailable(),Y?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Et.current,..._==="apple_pay"||_==="google_pay"?{walletType:_}:{}})},defersMissingTerminal:gc,onMissingTerminalDeferred:(_,d)=>{let m=Y?.now()??globalThis.performance?.now()??Date.now(),A=Je.current,T=A?.generation===d?A.startedAt:m;Y?.performance({stage:"overlay_return",durationMs:Math.max(0,m-T),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:d,...gc(_)?{walletType:_}:{}}),Y?.flush?.().catch(()=>{})}});ht(()=>{je&&He.current?.focus()},[je,ke]);let I=Ye(()=>{Q(_=>_+1)},[]),ee=Ye((_,d,m,A,T=!1)=>{bt(A),E?.(_,d,{code:m,popupBlocked:zr(d),telemetryReported:T,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),re(_),$e(!0),I()},[bt,E,I]),Oe=Ye(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);ht(()=>{Ue.current&&(Ue.current=!1,Oe())},[Oe,ke]);let F=Ye(()=>{$e(!1),c?.(null),Oe()},[Oe,c]),Se=Ye(()=>{M.current?.()},[]);ht(()=>{let _=ni(e,t);if(!_)return;let d=!1,m=!1,A=async()=>{if(!m){m=!0,d||be("checking");try{let T=await dc(N,_.clientSecret,Ee.current);if(d)return;let J=es(T,_.providerObjectId,Zi(_.clientSecret));if(J.kind==="confirmed"){if(!cc(e,t,_.clientSecret))return;M.current=null,be("idle"),s({id:J.paymentMethodId,type:"card",threeDSecureActionResultTokenId:J.intentId},{..._.accountPatch?{accountPatch:_.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(J.kind==="terminal"){Qi(e,t,_.clientSecret),M.current=null,be("idle"),re(_.paymentMethodType),$e(!0),I();return}be("blocked")}catch{d||be("blocked")}finally{m=!1}}};return M.current=A,be("blocked"),()=>{d=!0,M.current===A&&(M.current=null)}},[t,s,I,e,N]);let mt=Ye(async _=>{let d=!1,m=Ve=>{d||(d=!0,_.paymentFailed({reason:"fail",...Ve?{message:Ve}:{}}))};if(!N||!Ie){m();return}let A=Ae.current.get(ke);if(A&&!yt(A.generation)){Ae.current.delete(ke),m();return}if(!A&&Yt()){m();return}if(A&&!De(A.generation)){m();return}A||De();let T=_.expressPaymentType??A?.method??Me.current,J=A??null,ft=mc(T),me;T==="apple_pay"?me="apple_pay":T==="google_pay"&&(me="google_pay");let We=A?.generation??Et.current,H=Y,Ut=H?.now()??globalThis.performance?.now()??Date.now(),Ct=new AbortController,_t=!1,at=!1,oe=null,In=e,Bn="processing",yn="other",qt="provider_runtime",Fn,Dn=new Promise((Ve,Le)=>{Fn=Le}),hn=window.setTimeout(()=>{_t=!0,Ct.abort(),Fn(ei)},Gu),Tt=async(Ve,Le,Rn)=>{Bn=Ve,yn=Le,qt=Le==="intent_create"||Le==="session_claim"?"transport_error":"provider_runtime";let kt=H?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Rn,Dn])}finally{let On=H?.now()??globalThis.performance?.now()??Date.now();H?.performance({stage:Ve,durationMs:Math.max(0,On-kt),durationMode:"machine",requestCategory:Le,paymentMethodCategory:"wallet",provider:"stripe",..._t?{statusClass:"timeout"}:{}})}};try{if(ct(!0),c?.(null),!J&&k){let ce=await Tt("processing","other",k(ft));if(!ce.proceed){m();return}J={accountPatch:ce.accountPatch,sessionId:ce.sessionId,nonce:ce.nonce}}let Ve=J?.sessionId??e;In=Ve;let Le=J?.nonce??t,Rn=vt.current??J?.accountPatch,kt=Rc({event:_,fallbackEmail:Rn?.email??n,fallbackName:[Rn?.firstName,Rn?.lastName].join(" ").trim()||z});if(!gn(kt.email)){m("Buyer details are required."),Te(os(T),kt).then(ce=>{ce&&(vt.current=ce)});return}vt.current=null;let On={...J?.accountPatch,...dr(kt,!0)};await Tt("processing","session_claim",Promise.resolve(ne?.(kt)));let{error:mn}=await Tt("tokenization","provider_sdk",Ie.submit());if(mn){m(),ee(T,mn,"stripe_wallet_submit_failed",A?.generation);return}if(!Ve)throw new Error("Missing sessionId or email for payment.");let jt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:T,paymentMethodId:null,intentKind:a},Qt=JSON.stringify({sessionId:Ve,nonce:Le??"",request:jt}),Jn=qe.current,$n=Jn?.retryIdentity===Qt?Jn.authorizationAttemptId:Ou();qe.current={authorizationAttemptId:$n,retryIdentity:Qt};let en=await Tt("processing","intent_create",ri(o,he,Ve,Le??"",{...jt,authorizationAttemptId:$n},{signal:Ct.signal}));if(en.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let xt=en.clientSecret,Cn=tp({createdAt:Date.now(),sessionId:Ve,...Le?{nonce:Le}:{},clientSecret:xt,providerObjectId:en.providerObjectId,paymentMethodType:T,accountPatch:On});window.clearTimeout(hn),at=!0,H?.performance({stage:"callback",durationMs:Math.max(0,(H?.now()??globalThis.performance?.now()??Date.now())-Ut),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let ln=H?.now()??globalThis.performance?.now()??Date.now(),Ft={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...me?{walletType:me}:{},attempt:We},fn=!1,Dt=null;H?.log({name:"payment.provider_confirmation.started",...Ft}),oe=window.setTimeout(()=>{oe!==null&&Ee.current.delete(oe),fn=!0;let ce=H?.now()??globalThis.performance?.now()??Date.now();H?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Ft,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ce-ln),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),H?.flush?.().catch(()=>{}),Dt?.()},Yu),Ee.current.add(oe);let on=(ce,et)=>{oe!==null&&(window.clearTimeout(oe),Ee.current.delete(oe),oe=null);let u=H?.now()??globalThis.performance?.now()??Date.now(),xe=Math.max(0,u-ln),L=ce;fn&&(ce==="resolved"?L="resolved_late":ce==="returned_error"?L="returned_error_late":L="rejected_late");let Pn=et??(ce==="resolved"?"approved":"provider_error");return H?.log({name:"payment.provider_confirmation.returned",...Ft,operationOutcome:L,terminalReason:Pn}),H?.performance({...Ft,durationMs:xe,durationMode:"buyer",operationOutcome:L,terminalReason:Pn}),{durationMs:xe,operationOutcome:L,terminalReason:Pn}},Bt=!1,ae=!1,Zn=ce=>{if(!ce||typeof ce!="object")return null;let et=ce;if(et.error)return null;let u=et.setupIntent??et.paymentIntent,xe=es(u??null,void 0,!!et.setupIntent);return xe.kind==="confirmed"?xe:null},Xn=ce=>{if(Bt||A&&Et.current!==A.generation)return;let et=Zn(ce);if(!et)return;if(Cn&&!cc(Ve,Le,xt)){Bt=!0;return}let{intentId:u,paymentMethodId:xe}=et;Bt=!0,ae=!0,qe.current=null,M.current=null,Ce.current&&(be("idle"),ct(!1));let L=`${wc}:${Ve}`;Xt(L,{createdAt:Date.now(),sessionId:Ve,nonce:Le,accountPatch:On,paymentMethodId:xe,providerIntentId:u,paymentMethodType:T});try{s({id:xe,type:"card",threeDSecureActionResultTokenId:u},{accountPatch:On,paymentMethodCategory:"wallet",sessionId:Ve,nonce:Le})}finally{Xt(L)}},Qn=!1;Dt=async()=>{if(!(Qn||Bt||ae)){Qn=!0,Ce.current&&be("checking");try{let ce=await dc(N,xt,Ee.current);if(Bt||ae)return;let et=Zi(xt),u=es(ce,en.providerObjectId,et);if(u.kind==="confirmed"){Xn(et?{setupIntent:ce}:{paymentIntent:ce});return}if(u.kind==="terminal"){if(ae=!0,Qi(Ve,Le,xt),qe.current=null,M.current=null,!Ce.current)return;be("idle"),m(),ee(T,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",A?.generation,!0);return}Ce.current&&!ae&&(be("blocked"),ct(!1))}catch{Ce.current&&!ae&&(be("blocked"),ct(!1))}finally{Qn=!1}}},M.current=Dt;let tn,En;try{let ce=await(Zi(xt)?N.confirmSetup({elements:Ie,clientSecret:xt,redirect:"if_required"}):N.confirmPayment({elements:Ie,clientSecret:xt,redirect:"if_required"}));if(!ce||typeof ce!="object")throw new fa(ep(ce));if(tn=ce,!tn.error&&!Zn(tn))throw new fa("confirmation_result_unconfirmed");En=on(tn.error?"returned_error":"resolved",tn.error&&Fa(tn.error)?"provider_declined":void 0)}catch(ce){let et=ce instanceof fa?ce.reason:void 0,u=et!==void 0,xe=on(u?"returned_error":"rejected");if(H?.error({...u?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:et}:Li(ce),...Ft,operationOutcome:xe.operationOutcome,durationMs:xe.durationMs,statusClass:"unknown",terminalReason:xe.terminalReason}),!Ce.current||Bt)return;await Dt?.();return}let Sn=tn.error;if(Sn){if(!Ce.current||Bt)return;if(Fa(Sn)){ae=!0,Qi(Ve,Le,xt),qe.current=null,M.current=null,be("idle");let ce=Sn.message??"Your payment was declined.";m(ce),c?.(ce),C?.(un(ft,ce,{code:go(Sn),declineCode:Ai(Sn)})),oi({billingApiUrl:o,sessionId:Ve,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:T,providerDeclineReason:go(Sn)??"provider_declined",...en.intentKind==="payment"&&en.providerObjectId.startsWith("pi_")?{providerIntentId:en.providerObjectId}:{}}})}else H?.error({...Li(Sn),...Ft,operationOutcome:En.operationOutcome,durationMs:En.durationMs,statusClass:"unknown",terminalReason:En.terminalReason}),await Dt?.();return}if(Xn(tn),!Bt)throw new Error("Invalid provider returned for APM intent")}catch(Ve){if(Ve===ei){let Le=H?.now()??globalThis.performance?.now()??Date.now();H?.error({errorCode:rp(yn),stage:Bn,requestCategory:yn,paymentMethodCategory:"wallet",provider:"stripe",...me?{walletType:me}:{},operationOutcome:"watchdog_expired",checkoutSessionId:In,durationMs:Math.max(0,Le-Ut),statusClass:"timeout",failureCategory:qt,attempt:We,terminalReason:"provider_error"}),H?.flush?.().catch(()=>{})}m(),ee(T,Ve,Ve===ei?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",A?.generation,Ve===ei)}finally{if(window.clearTimeout(hn),oe!==null&&(window.clearTimeout(oe),Ee.current.delete(oe)),!at){let Ve=H?.now()??globalThis.performance?.now()??Date.now();H?.performance({stage:"callback",durationMs:Math.max(0,Ve-Ut),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",..._t?{statusClass:"timeout"}:{}})}Ce.current&&ct(!1)}},[N,Ie,e,t,n,z,Te,ne,o,he,a,s,c,C,k,ee,De,yt,Yt,Et,Y,ke]),Ne=gt(()=>gl(i),[i]),wt=gt(()=>i.map($u),[i]);return Xe(Fo,{children:[p(Bi,{state:Fe,placeholderTestId:"flopay-wallet-placeholder",borderRadius:ve,children:Xe("div",{ref:Re,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[je&&Xe("button",{ref:He,type:"button","data-testid":"flopay-wallet-retry-button",onClick:F,style:rs,children:["Try ",os(ye)," again"]}),pt!=="idle"&&Xe("div",{role:"status","aria-live":"polite",children:[p("p",{children:"We are still confirming your payment. Check its status before trying again."}),p("button",{type:"button",onClick:Se,disabled:pt==="checking",style:rs,children:pt==="checking"?"Checking payment status\u2026":"Check payment status"})]}),pe&&p(Io,{identity:pe.identity,methodLabel:pe.methodLabel,onComplete:Pt,onCancel:()=>Pt(null)},pe.id),pt==="idle"&&p("div",{style:{display:pe?"none":void 0},children:p(Sc,{onReady:_=>{lt(xi(_,wt))},onLoadError:_=>{lt("load_error"),cs(Y,"stripe","wallet","provider_error")},onClick:async _=>{let d=Y?.now()??globalThis.performance?.now()??Date.now();Me.current=_.expressPaymentType,U.current=mc(_.expressPaymentType);let m=!0,A=window.setTimeout(()=>{m=!1,_.reject()},Ku),T=k?await k(U.current):{proceed:!0};if(window.clearTimeout(A),!m)return;if(!T.proceed){Ae.current.delete(ke),_.reject();return}let J=Qe(_.expressPaymentType);Je.current={generation:J,startedAt:d},Ae.current.set(ke,{generation:J,method:_.expressPaymentType,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),$e(!1),Y?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:J,..._.expressPaymentType==="apple_pay"||_.expressPaymentType==="google_pay"?{walletType:_.expressPaymentType}:{}}),f?.(U.current),_.resolve()},onConfirm:mt,onCancel:()=>{let _=Ae.current.get(ke);Ae.current.delete(ke),Y?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",..._?{attempt:_.generation}:{}}),bt(_?.generation),qe.current=null,$e(!1),Ue.current=!0,I()},options:{...hl,paymentMethods:Ne,emailRequired:zt,billingAddressRequired:zt}},ke)})]})}),ze&&p(Sr,{status:"processing"})]})}function Ec(e,t,n){let o=bc(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function as({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:c,onErrorChange:f,onDecline:C,onCancel:E,runBeforeButtonClick:k,onButtonClick:z,isProcessing:ne,submitButtonColor:O,submitButtonBorderRadius:ve,submitButtonStyle:V,errorText:v}){let P=jr(),{emitInstrument:he}=Do(Gn),N=ss(),Ie=is(),[Y,Fe]=ie(!1),lt=G(!1),[ze,ct]=ie(!1),[zt,pe]=ie("loading"),[Te,Pt]=ie(""),Re=!gn(o?.trim()),He=!Re||gn(Te.trim()),ke=Ye(async()=>{if(!N||!Ie||ne||lt.current||!ze)return;lt.current=!0,Fe(!0);let Q=k?await k("card"):{proceed:!0};if(!Q.proceed){lt.current=!1,Fe(!1);return}z?.("card");let je=Q.sessionId??t,$e=Q.nonce??n,pt=aa(a?.trim()),be=dr({email:Q.accountPatch?.email?.trim()||o?.trim()||Te.trim(),firstName:Q.accountPatch?.firstName?.trim()||pt.firstName,lastName:Q.accountPatch?.lastName?.trim()||pt.lastName}),ye=be.email,re=dr({...Q.accountPatch,...be});try{if(f?.(null),!gn(ye))throw new Error("A valid email address is required for payment.");await i?.(be);let M=await Ie.submit();if(M.error){f?.(M.error.message??"Payment failed.");return}let Ce=[be.firstName,be.lastName].filter(Boolean).join(" "),Ue=await N.createPaymentMethod({elements:Ie,params:{billing_details:{email:ye,...Ce?{name:Ce}:{}}}});if(Ue.error||!Ue.paymentMethod){f?.(Ue.error?.message??"Failed to create payment method.");return}let Me=Ue.paymentMethod;if(!je||!ye)throw new Error("Missing sessionId or email for payment.");let U=Me.type||e,vt=await ri(s,he,je,$e??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:U,paymentMethodId:null,intentKind:"payment"});if(vt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let qe=vt.clientSecret;Xt(Ir,{clientSecret:qe,sessionId:je,nonce:$e,accountPatch:re,paymentMethodId:Me.id,paymentMethodType:Me.type??e,gateway:"stripe"});let{error:Ee,paymentIntent:Je}=await N.confirmPayment({clientSecret:qe,confirmParams:{return_url:window.location.href,payment_method:Me.id},redirect:"if_required"});if(Ee){Xt(Ir);let De=Ee.message??"Payment failed.";f?.(De),C?.(un("card",De,{code:Ee.code})),await oi({billingApiUrl:s,sessionId:je,nonce:$e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ee.code??"provider_declined"}});return}let Ae=Je?.status;if(!ra(Ae)){Xt(Ir);let De=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(De),C?.(un("card",De,{code:Ae??"missing_payment_intent"}));return}Xt(Ir);let Qe=typeof Je?.payment_method=="string"?Je.payment_method:Je?.payment_method?.id;c({id:Qe??Me.id,type:"card",threeDSecureActionResultTokenId:Je?.id,gateway:"stripe",paymentMethodType:Me.type??e},{accountPatch:re,paymentMethodCategory:"apm",sessionId:je,nonce:$e})}catch(M){f?.(M instanceof Error?M.message:"Payment failed. Please try again.")}finally{lt.current=!1,Fe(!1)}},[N,Ie,ne,ze,k,z,t,n,o,a,Te,i,s,he,e,c,f,C]);return Xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Re&&p("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Re&&Xe("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",p("input",{type:"email",autoComplete:"email",required:!0,value:Te,onChange:Q=>Pt(Q.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),p(Wu,{onReady:()=>pe("ready"),onLoadError:()=>{pe("load_error"),cs(pn(P),"stripe","apm")},onChange:Q=>{ct(!!Q.complete)},options:{layout:Pl,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...gn(o?.trim())?{email:o?.trim()}:{}}}}}),p(vl,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ke()},disabled:!ze||!He||Y||ne||zt!=="ready",color:O,borderRadius:ve,style:V,children:Y?"Processing\u2026":`Pay with ${ga(e)}`}),v&&p(Eo,{margin:"0.75rem 0 0",children:v})]})}function Pc({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:s,stripeInstance:c,paymentElementBaseOptions:f,futureUseSession:C,onTokenizedBody:E,onErrorChange:k,onButtonClick:z,onDecline:ne,runBeforeButtonClick:O,onLoadStateChange:ve,isProcessing:V=!1,submitButtonColor:v="#4A49FF",submitButtonBorderRadius:P=8,submitButtonStyle:he,buttonAppearance:N,themeId:Ie,onExpandApm:Y,expandedApmMethod:Fe}){let{emitInstrument:lt}=Do(Gn),[ze,ct]=ie(null),[zt,pe]=ie(null),Te=G(!1),{request:Pt,collect:Re,finish:He}=ko();ht(()=>{s.length>0&&c?ve?.("ready"):c||ve?.("loading")},[s.length,c,ve]);let ke=Ye(async ye=>{if(!c||Te.current||V)return;Te.current=!0,pe(ye);let re=O?await O("card"):{proceed:!0};if(!re.proceed){Te.current=!1,pe(null);return}z?.("card");let M=re.sessionId??e,Ce=re.nonce??t,Ue=aa([re.accountPatch?.firstName,re.accountPatch?.lastName].filter(Boolean).join(" ")||o),Me=dr({email:re.accountPatch?.email?.trim()||n?.trim(),firstName:re.accountPatch?.firstName?.trim()||Ue.firstName,lastName:re.accountPatch?.lastName?.trim()||Ue.lastName});if(!gn(Me.email)){pe(null);let qe=await Re(ga(ye),Me);if(!qe){Te.current=!1;return}Me=qe,pe(ye)}let U=Me.email,vt=dr({...re.accountPatch,...Me});try{if(k?.(null),!M||!gn(U))throw new Error("Missing sessionId or email for payment.");await a?.(Me);let qe=await ri(i,lt,M,Ce??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ye,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ee=qe.clientSecret;Xt(Ir,{clientSecret:Ee,sessionId:M,nonce:Ce,accountPatch:vt,paymentMethodType:ye,gateway:"stripe"});let{error:Je,paymentIntent:Ae}=await c.confirmPayment({clientSecret:Ee,confirmParams:{return_url:window.location.href,payment_method_data:{type:ye,billing_details:{name:[Me.firstName,Me.lastName].filter(Boolean).join(" "),...U?{email:U}:{}}}},redirect:"if_required"});if(Je){Xt(Ir);let bt=Je.message??"Payment failed.";k?.(bt),ne?.(un("card",bt,{code:Je.code})),await oi({billingApiUrl:i,sessionId:M,nonce:Ce,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ye,providerDeclineReason:Je.code??"provider_declined"}});return}let Qe=Ae?.status;if(!ra(Qe)){Xt(Ir);let bt=Qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";k?.(bt),ne?.(un("card",bt,{code:Qe??"missing_payment_intent"}));return}Xt(Ir);let De=typeof Ae?.payment_method=="string"?Ae.payment_method:Ae?.payment_method?.id;E({id:De??Ae?.id,type:"card",threeDSecureActionResultTokenId:Ae?.id,gateway:"stripe",paymentMethodType:ye},{accountPatch:vt,paymentMethodCategory:"apm",sessionId:M,nonce:Ce})}catch(qe){k?.(qe instanceof Error?qe.message:"Payment failed. Please try again.")}finally{Te.current=!1,pe(null)}},[c,V,O,z,e,t,n,Re,i,lt,o,a,E,k,ne]),[Q,je]=ie(null),$e=Y?Fe??null:Q,pt=Ye(ye=>{Te.current||V||$e&&$e!==ye||(ic(ye)?Y?Y(ye):je(ye):ke(ye))},[$e,V,ke,Y]),be=gt(()=>Q?Ec(f,Q,C):null,[Q,f,C]);return p("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Pt?p(Io,{identity:Pt.identity,methodLabel:Pt.methodLabel,onComplete:He,onCancel:()=>He(null)},Pt.id):s.map(ye=>{let re=Fe===ye,M=zt===ye,Ce=zt!==null&&zt!==ye||Fe!=null&&Fe!==ye;return Xe(Hu.Fragment,{children:[p(fl,{method:ye,themeId:Ie,submitting:M,disabled:Ce,highlighted:re,hasNextStep:ic(ye),onClick:()=>pt(ye),backgroundColor:N?.backgroundColor,borderColor:N?.borderColor,textColor:N?.textColor,borderRadius:N?.borderRadius,fontFamily:N?.fontFamily}),!Y&&Q===ye&&be&&c&&p(no,{stripe:c,options:be,children:p(as,{method:ye,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:E,onErrorChange:k,onDecline:ne,onCancel:()=>je(null),runBeforeButtonClick:O,onButtonClick:z,isProcessing:V,submitButtonColor:v,submitButtonBorderRadius:P,submitButtonStyle:he})},ye)]},ye)})})}function hp({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:s,onError:c,onDecline:f,onTokenizedBody:C,firstName:E,lastName:k,chv:z,className:ne,submitLabel:O,isProcessing:ve,error:V,onErrorChange:v,showPayPal:P=!0,showStripe:he=!0,walletPresentation:N="auto",enabledPaymentMethods:Ie,enabledPaymentMethodCountries:Y,showApplePay:Fe=!0,showGooglePay:lt=!0,layout:ze="default",theme:ct,buttonsTheme:zt,buttonsStyles:pe,appearance:Te,cardButtonContent:Pt,cardBackButtonContent:Re,cardTitleContent:He,showSecurityFooter:ke,onButtonClick:Q,onBeforeButtonClick:je,onBuyerIdentityReady:$e,enableAVS:pt,cardFieldOrder:be,cardPreFormSlot:ye,avsLayout:re="row",country:M,zip:Ce,addressLine1:Ue,addressLine2:Me,city:U,state:vt,onCountryChange:qe,onZipChange:Ee,avsCheck:Je,checkoutType:Ae,checkoutLayout:Qe,totalAmount:De=0,currency:bt="usd",initialCardOpen:Yt=!1,directPaypal:yt,isSubscription:Et=!1,session:I,dataAttachmentPending:ee=!1,dataAttachmentRequiresIdentity:Oe=!1,debug:F=!1}){let Se=jr(),mt=zi(),Ne=Do(cr),{emitInstrument:wt}=Do(Gn),_=G(null);_.current||(_.current=qa());let d=_.current,[,m]=ie(0),A=G(null);A.current||(A.current=ea());let T=A.current,J=gt(()=>({browser:T,capability:d,presentationMode:"popup"}),[T,d]),ft=I??Ne.session,me=gt(()=>({futureUse:ft?.futureUse,futureUseUnsupported:ft?.futureUseUnsupported}),[ft?.futureUse,ft?.futureUseUnsupported]),We=ft?.gateways?.paypal?.providerObjectType??yt?.providerObjectType,H=ee||Ne.claimPending===!0,Ut=Oe||Ne.claimRequiresIdentity===!0,Ct=H&&!Ut,_t=zl(),at=n||_t,[oe,In]=ie(!1),[Bn,yn]=ie(null),[qt,Fn]=ie(M??""),[Dn,hn]=ie(Ce??""),[Tt,Ve]=ie(Ue??""),[Le,Rn]=ie(Me??""),[kt,On]=ie(U??""),[mn,jt]=ie(vt??""),[Qt,Jn]=ie(""),[$n,en]=ie({}),xt=G(Ce??""),Cn=G(M??""),ln=G(Ue??""),Ft=G(Me??""),fn=G(U??""),Dt=G(vt??""),on=G(""),Bt=G({});ht(()=>{let r=(g,W,fe,D,X)=>{if(Bt.current[g])return;let Rt=W?.trim();!Rt||Rt===fe.current||(fe.current=Rt,D(Rt),X?.(Rt))};r("country",M,Cn,Fn,qe),r("zip",Ce,xt,hn,Ee),r("addressLine1",Ue,ln,Ve),r("addressLine2",Me,Ft,Rn),r("city",U,fn,On),r("state",vt,Dt,jt)},[M,Ce,Ue,Me,U,vt,qe,Ee]);let ae=gt(()=>Lu(pt),[pt]),Zn=ae!==null,Xn=gt(()=>Ji(I),[I]),Qn=Au(I?.vault),tn=!!I?.gateways?.pcivault,En=Bl(I),ce=!!(I?.gateways?.stripe?.enabledPaymentMethods??Ie)?.includes("card")||Qr(I),et=Qn||ce||tn,u=!!(he&&et&&e),[xe,L]=ie(()=>ze!=="buttons"||Yt?e??null:null),[Pn,Nn]=ie(0),Jt=ze!=="buttons"||Yt||!!e&&xe===e,_n=I?.captureMethod,nt=G(Se);ht(()=>{nt.current=Se},[Se]);let[yr,Dr]=ie(null);ht(()=>{if(!u||!e||!Jt){Dr(null);return}let r=nt.current?nt.current.cardCapture({sessionId:e,captureMethod:_n}):new vu({sessionId:e,captureMethod:_n,billingApiUrl:at,telemetry:o});return Dr({sessionId:e,captureMethod:_n,billingApiUrl:at,telemetry:o,capture:r}),()=>{r.unmount()}},[u,e,Jt,_n,at,o]);let It=u&&e&&Jt&&yr?.sessionId===e&&yr.captureMethod===_n&&yr.billingApiUrl===at&&yr.telemetry===o?yr.capture:null,Ln=gt(()=>{let r=qt,g=ae?Kt(ae.postal_code,r):!1;return mp(r,Dn,g)},[ae,qt,Dn]),{avsInvalid:er,invalidAvsFields:tr}=gt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!u||!ae)return{avsInvalid:!1,invalidAvsFields:r};let g=qt,W=(X,Rt)=>Kt(X,g)&&!Rt.trim(),fe={line1:W(ae.address_line_1,Tt),city:W(ae.city,kt),state:W(ae.state,mn),zip:Ln.empty||Ln.malformed};return{avsInvalid:fe.line1||fe.city||fe.state||fe.zip,invalidAvsFields:fe}},[u,ae,qt,Tt,kt,mn,Ln]),[$t,mr]=ie(!1),[fr,Tn]=ie(!1),[gr,Wn]=ie(!1),[hr,Er]=ie({line1:!1,city:!1,state:!1}),zn=G(!1),nr=G({email:!1,line1:!1,city:!1,state:!1,zip:!1}),rr=G(!1),Mt=Ye(r=>{nr.current[r]=!0,rr.current=!0},[]),Un=Ye(r=>!zn.current&&nr.current[r],[]),wn=Ye(r=>{Un(r)&&Er(g=>g[r]?g:{...g,[r]:!0})},[Un]),[or,ar]=ie(()=>Xi(I?.vault,{billingApiUrl:at,sessionId:e,nonce:t})),[tt,nn]=ie(Yt&&et?"card":"buttons"),[cn,Mn]=ie(null),Or=tt==="expanding"||tt==="card",Pr=I?.gateways?.stripe&&!En?"stripe":void 0,_r=Ye(()=>{wt?.({class:"card_surface",provider:Pr})},[Pr,wt]),Hn=G(null),rn=Ye(r=>{Hn.current&&clearTimeout(Hn.current),Hn.current=setTimeout(()=>{Hn.current=null,r()},ha)},[]);ht(()=>()=>{Hn.current&&clearTimeout(Hn.current)},[]);let Nr=G(!1),[an,w]=ie(0),b=G(null),j=Ye(()=>{_r(),L(e??null),Nr.current&&(Nr.current=!1,w(r=>r+1)),Nn(r=>r+1),nn("expanding"),rn(()=>nn("card"))},[rn,_r,e]),K=Ye(()=>{nn("collapsing"),rn(()=>nn("buttons"))},[rn]),it=Ye(r=>{Mn(r),nn("apm-expanding"),rn(()=>nn("apm-form"))},[rn]),Wt=Ye(()=>{nn("apm-collapsing"),rn(()=>{nn("buttons"),Mn(null)})},[rn]);ht(()=>{ze==="buttons"&&Yt&&et&&(L(e??null),nn("card"))},[ze,Yt,et,e]);let[de,x]=ie(null),B=G(!1),R=G(null),l=G("idle"),[y,h]=ie(!1),$=G(y);$.current=y;let[le,Pe]=ie(()=>yt?.existingOrderId?{orderId:yt.existingOrderId,attempts:1}:null),Ht=G(le);ht(()=>{Ht.current=le},[le]);let te=G(null),we=gt(()=>{if($e||Ne.claimBuyerIdentity||I?.buyerIdentified!==!1||!e||!t)return;let r=`${at}|${e}|${t}`;te.current?.key!==r&&(te.current={key:r,claim:Co(new Bo(at,{telemetry:!1}),e,t,{...i?{userId:i}:{},...E?{firstName:E}:{},...k?{lastName:k}:{}})});let g=te.current.claim;return async W=>{await g(W)}},[$e,Ne.claimBuyerIdentity,I?.buyerIdentified,e,t,at,i,E,k]),Be=$e??Ne.claimBuyerIdentity??we,rt=V??Bn,Z=gt(()=>Uu(ct),[ct]),S=gt(()=>{let r=Z?.buttonsLayout??zu(zt);return pe?{...r,...pe,cardButton:{...r.cardButton,...pe.cardButton},cardFormContainer:{...r.cardFormContainer,...pe.cardFormContainer},backButton:{...r.backButton,...pe.backButton},backButtonIcon:{...r.backButtonIcon,...pe.backButtonIcon},submitButton:{...r.submitButton,...pe.submitButton},title:{...r.title,...pe.title}}:r},[Z,zt,pe]),q=Te??Z?.appearance,Ke=gt(()=>cl({appearance:q,buttonsStyles:S,layout:ze}),[q,S,ze]),ge=Ne.inlineSessionPatchProcessing??!1,_e=(ve??oe)||ge,dt=at.replace(/\/+$/,""),Ze=gt(()=>Ni({userId:i,email:a,firstName:E,lastName:k,country:M,zip:Ce},$n),[i,a,E,k,M,Ce,$n]),oo=[Ze.firstName,Ze.lastName].filter(r=>!!r?.trim()).join(" "),Ss=!gn(Ze.email?.trim()),ci=G(null);u&&ci.current===null&&(ci.current=Ss);let Lr=u&&(ci.current??Ss),di=gt(()=>fp(Qt,Lr),[Qt,Lr]),ao=di.empty||di.malformed,qn=gt(()=>Se?Se.getRawProvider():null,[Se]),ws=gt(()=>mt?mt.getRawProvider():null,[mt]),Uo=De||100,io=bt.toLowerCase(),ui=gt(()=>q?bu(q):null,[q]),so=ui,ks=gt(()=>{let r=ui??{},g=r.rules??{};return{...r,rules:{...g,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...g[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...g[".AccordionItemContents"]??{}}}}},[ui]),Is=gt(()=>({...xl(De,ft?.captureMethod,me),currency:io,...so?{appearance:so}:null}),[De,io,ft?.captureMethod,me,so]),pi=bc(me,"paypal","paypal"),Rs=gt(()=>({mode:"payment",amount:Uo,currency:io,captureMethod:"manual",...pi?{setupFutureUsage:pi}:null,...so?{appearance:so}:null}),[Uo,io,pi,so]),ue=Ye(r=>{yn(r),v?.(r)},[v]),Es=G(0);ht(()=>{an!==Es.current&&(Es.current=an,ue(null))},[an,ue]);let yi=G(""),[_s,Uc]=ie(!1),mi=Ye(()=>{Uc(!0)},[]);ht(()=>{if(!u||!Lr||!Be||!_s||ao||yi.current)return;let r=dr({email:gn(Ze.email?.trim())?Ze.email?.trim():on.current.trim(),firstName:Ze.firstName?.trim(),lastName:Ze.lastName?.trim()});yi.current=JSON.stringify(r),en(g=>({...g,...r})),Promise.resolve(Be(r)).catch(g=>{yi.current="",ue(g instanceof Error?g.message:"Failed to attach buyer details.")})},[u,Lr,Be,_s,ao,Ze.email,Ze.firstName,Ze.lastName,ue]),ht(()=>{!u||!It||It.setCardFieldOrder?.(be??null,ae==null&&!Lr)},[u,It,be,ae,Lr]),ht(()=>{(tt==="expanding"||tt==="collapsing"||tt==="apm-expanding"||tt==="apm-collapsing")&&ue(null)},[tt,ue]);let vr=Ye((r,g,W)=>{f?.(un(r,g,W))},[f]),lo=Ye((r,g,W)=>{let fe=W?.popupBlocked??zr(g);fe&&d.markBlocked()&&m(Ge=>Ge+1);let D=Ba(os(r),fe,T.inAppBrowser),X=go(g),Rt=(X?.toLowerCase()==="error"?void 0:X)??yl(W?.code)??"external_payment_method_failed",lr=new Br(D,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:Rt,popupBlocked:fe,inAppBrowser:T.inAppBrowser,appFamily:T.appFamily,popupCapability:d.current(),presentationMode:W?.presentationMode??"popup"}});W?.telemetryReported||pn(Se)?.error(xo({...J,presentationMode:W?.presentationMode??"popup"},{errorCode:fe?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:W?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:W?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:W?.terminalReason??(fe?"popup_blocked":"provider_error")})),x(null),ze==="buttons"&&(nn("buttons"),Mn(null)),ue(D),c?.(lr),console.error("[FloPay] External payment method failed:",{method:r,code:Rt,popupBlocked:fe})},[T,J,Se,ze,c,d,ue]);ht(()=>{if(!u||!e){ar(null);return}let r={billingApiUrl:dt,sessionId:e,nonce:t},g=Xi(I?.vault,r);if(g){ar(g);return}if(!Jt){ar(null);return}let W=`${dt}\0${e}\0${t??""}`,fe=b.current;if(fe&&fe.key===W){ar(fe.mount);return}ar(null);let D=!0;return new Bo(dt).getVaultCapture(e,t).then(X=>{if(!D)return;let Rt=Xi(X,r);Rt?.verificationRequired&&!X.html&&(b.current={key:W,mount:Rt}),Rt?ar(Rt):ue("Failed to load the secure card form.")}).catch(X=>{D&&ue(X instanceof Error?X.message:"Failed to load the secure card form.")}),()=>{D=!1}},[u,Jt,Pn,e,I?.vault,dt,t,ue]);let ir=G({onComplete:s,onError:c,updateError:ue,emitDecline:vr,resolvedAccount:Ze,avsConfig:ae,avsCheckProp:Je,sessionId:e,nonce:t,baseUrl:dt,captureMethod:I?.captureMethod,paymentId:I?.paymentId,authorizationExpiresAt:I?.authorizationExpiresAt,serverSideCardGateway:En});ir.current={onComplete:s,onError:c,updateError:ue,emitDecline:vr,resolvedAccount:Ze,avsConfig:ae,avsCheckProp:Je,sessionId:e,nonce:t,baseUrl:dt,captureMethod:I?.captureMethod,paymentId:I?.paymentId,authorizationExpiresAt:I?.authorizationExpiresAt,serverSideCardGateway:En};let fi=G(!1),Ts=Ye(()=>{let r=ir.current,g=r.resolvedAccount.email?.trim(),W=gn(g)?g:on.current.trim();if(!gn(W))return null;let fe=r.resolvedAccount.firstName?.trim(),D=r.resolvedAccount.lastName?.trim(),X=Cn.current.trim()||r.resolvedAccount.country?.trim()||"",Rt=r.avsConfig?Kt(r.avsConfig.state,X):!1,lr=r.avsConfig?Kt(r.avsConfig.address_line_1,X):!1,Ge=r.avsConfig?Kt(r.avsConfig.postal_code,X):!1,st=r.avsConfig?Kt(r.avsConfig.city,X):!1,ut=r.avsConfig?Kt(r.avsConfig.address_line_2,X):!1,Ot=lr&&!Rt&&Ge?_u(X,(xt.current??"").trim()):null,Jr=Rt?Dt.current:Ot;return{accountData:{userId:r.resolvedAccount.userId??"",email:W,...fe?{firstName:fe}:{},...D?{lastName:D}:{},...Ge&&xt.current?{zip:xt.current}:{},...st&&fn.current?{city:fn.current}:{},...Jr?{state:Jr}:{},...lr&&ln.current?{addressLine1:ln.current}:{},...ut&&Ft.current?{addressLine2:Ft.current}:{},...X?{country:X}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:Kt(r.avsConfig.country,X),postal_code:Ge,address_line_1:lr,address_line_2:ut,city:st,state:Rt}}:{}}},[]),Ms=G(H);Ms.current=H,ht(()=>{H||rt!==uc||ir.current.updateError(null)},[H,rt]),ht(()=>{!u||!It||It.setSubmitGate?.(er||H||ao||y)},[u,It,er,H,ao,y]),ht(()=>{if(!u||!It)return;fi.current=!1;let r=null,g=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,l.current="idle",x(null)},400)},W=It.on("submitting",()=>{mr(!0),R.current&&clearTimeout(R.current),l.current="validation-window",R.current=setTimeout(()=>{R.current=null,l.current==="validation-window"&&(l.current="processing")},op),x("processing");let Ge=ir.current;if(!Ge.sessionId||!Ge.nonce)return;let st=Ts();if(!st){Ge.updateError("Enter a valid email address."),l.current="idle",x(null);return}new Bo(Ge.baseUrl).patchAccountSnapshot(Ge.sessionId,Ge.nonce,st,{telemetryMode:"best_effort"}).catch(ut=>{if(!ip(ut))return;let Ot=ut instanceof Error?ut.message:"Please check your billing address and try again.";Ge.updateError(Ot),l.current="idle",x(null),Ge.onError?.(ut instanceof Br?ut:new Br(Ot,"api_error"))})}),fe=It.on("complete",Ge=>{_o(Ge.sessionId??ir.current.sessionId),l.current="terminal",h(!1),x("success"),setTimeout(()=>{if(fi.current)return;fi.current=!0;let st=ir.current,ut=Ji(st)||Ge.outcome==="authorized",Ot=st.serverSideCardGateway?{}:{paymentIntentId:Ge.intentId};ir.current.onComplete?.(ut?{status:"authorized",...Ot,paymentId:Ge.paymentId??st.paymentId,sessionId:Ge.sessionId??st.sessionId,authorizationExpiresAt:Ge.authorizationExpiresAt??st.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Ot,checkoutMethod:"card"})},600)}),D=It.on("decline",Ge=>{let st=ir.current,ut=Ge.message??"Your payment was declined. Please try another card or contact your bank.";l.current="terminal",h(!1),st.updateError(ut),x("error");let Ot=Ge.failureOutcome??Fu(Ge.declineReason)??"authorization_declined";st.emitDecline("card",ut,{code:Ot,declineCode:Ot}),g()}),X=It.on("error",Ge=>{let st=ir.current,ut=Ge.message??"There was a problem processing your payment. Please try again.";l.current="terminal",h(!1),st.updateError(ut),x("error"),st.onError?.(new Br(ut,"api_error",{code:Ge.failureOutcome??"capture_failed"})),g()}),Rt=It.on("challenge_dismissed",()=>{R.current&&(clearTimeout(R.current),R.current=null),l.current="processing",h(!0),x(null)}),lr=It.on("blocked",()=>{if($.current){ir.current.updateError(ap);return}if(!Ms.current){mr(!0);return}mi(),ir.current.updateError(uc)});return()=>{r&&(clearTimeout(r),r=null),R.current&&(clearTimeout(R.current),R.current=null),l.current="idle",h(!1),x(null),W(),fe(),D(),X(),Rt(),lr()}},[u,It,mi,Ts]);let br=!!yt?.clientId,qo=Array.isArray(Ie),Sa=qo&&Ie.length>0,As=qo&&Ie.includes("paypal"),wa=G(null);wa.current===null&&(wa.current=Mu());let co=wa.current?"redirect":ml(T,N,d.current()),{expressMethods:ka,paymentElementMethods:gi}=gt(()=>Du(Ie,{excludePaypal:br}),[Ie,br]),xs=br||!!mt||As&&co==="redirect",qc=gt(()=>xs?ka.filter(r=>r!=="paypal"):ka,[ka,xs]),jc=gt(()=>{let r=[];return Fe&&r.push("apple_pay"),lt&&r.push("google_pay"),r},[Fe,lt]),uo=qo?qc:jc,$c=he&&uo.length>0,Bs=Zn?qt:M,Ia=gt(()=>Ru(gi,Bs,Y),[gi,Bs,Y]),hi=gt(()=>({mode:"payment",amount:Uo,currency:io,paymentMethodCreation:"manual",appearance:ks}),[Uo,io,ks]),[Fs,Ds]=ie("loading"),[Os,Ns]=ie("loading"),[Ls,zs]=ie("loading"),[Wc,Pi]=ie(!1),[Us,vi]=ie("loading"),[bi,Hc]=ie();ht(()=>{Hc(ea())},[]);let Ra=bi?.inAppBrowser,Ea=bi?Da(bi,yt?.approvalPresentation,We??(Et?"subscription":"order")):"popup",qs=P&&(br||(qo?As:Ra===!1)),js=he&&$c,jo=(!Ct||!!Ne.waitForDataAttachment)&&qs&&br,$s=Us==="retrying"||Us==="exhausted",$o=null;he&&(mt?$o=ws:co==="redirect"&&($o=qn));let Ws=gt(()=>({...J,presentationMode:co}),[J,co]),Wo=!Ct&&qs&&!!$o&&(!br||$s),po=!Ct&&js&&!!qn,Ho=!Ct&&he&&Sa&&Ia.length>0&&!!qn,Vc=jo&&!$s?Wc:Wo&&Fi(Fs),Kc=po&&Fi(Os),Gc=Ho&&Ls!=="load_error",Hs=r=>r==="loading"||r==="ready",Vs=jo||Wo&&Hs(Fs)||po&&Hs(Os)||Ho&&Ls!=="load_error",_a=G(!1);ht(()=>{if(!_a.current){if(!he&&!P){_a.current=!0;let r=new Br("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(r),ue(r.message)}else if(!he&&P&&!br){_a.current=!0;let r=new Br("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(r),ue(r.message)}else if(Ra!==void 0&&!Ct&&!et&&!Vs){_a.current=!0;let r=new Br("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"});c?.(r),ue(r.message)}}},[he,P,br,Ra,Ct,et,Vs,c,ue]);let Ks=G(!1);ht(()=>{if(Ks.current||!Sa)return;let r=[];Fe!==!0&&r.push("showApplePay"),lt!==!0&&r.push("showGooglePay"),r.length!==0&&(Ks.current=!0,console.warn(`[FloPay] ${r.join(" / ")} ${r.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.`))},[Sa,Fe,lt]);let Gs=Ye((r,g)=>Ne.applyInlineSessionPatch?Ne.applyInlineSessionPatch(r).then(W=>({error:null,sessionId:W.sessionId||e,nonce:W.session?.clientSecret||t})).catch(W=>{let fe=sc(g,W);return ue(fe.message),c?.(fe),{error:fe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ne.applyInlineSessionPatch,t,c,e,ue]),sr=Ye(async r=>{if(r!=="card"&&Ct&&await Ne.waitForDataAttachment?.(),!je)return{proceed:!0};try{let g=await je({method:r,sessionId:e||void 0,createSession:Ne.inlineSessionDraft});if(g===!1)return{proceed:!1};if(g&&typeof g=="object"){g.account&&en(fe=>({...fe??{},...g.account}));let W=await Gs(g,r);return W.error?{proceed:!1,accountPatch:g.account}:{proceed:!0,accountPatch:g.account,sessionId:W.sessionId,nonce:W.nonce}}return{proceed:!0}}catch(g){let W=sc(r,g);return ue(W.message),c?.(W),{proceed:!1}}},[Gs,Ne.inlineSessionDraft,Ne.waitForDataAttachment,Ct,je,c,e,ue]),Ys=Ye(async(r,g)=>{if(B.current)return;B.current=!0,In(!0),x("processing"),ue(null);let W=g?.sessionId??e,fe=g?.nonce??t,D=Ni(Ze,g?.accountPatch),X=g?.completionPaymentMethodId??oa(r),Rt=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,lr=dp(r),Ge=g?.presentationMode?Qa(pn(Se),{...J,presentationMode:g.presentationMode}):void 0,st=()=>{wt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:lr}),Ge?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...ur,requestCategory:"process_payment"})};try{let ut=new Bo(dt),Ot=await ut.processPayment(D.userId??"",{sessionId:W,nonce:fe,paymentMethodCategory:g?.paymentMethodCategory??pp(r),tokenizedData:Rt,accountData:{...g?.accountPatch,userId:D.userId??"",email:D.email??"",firstName:D.firstName||void 0,lastName:D.lastName||void 0,...Su({avsConfig:ae,country:Cn.current,zip:xt.current,city:fn.current,state:Dt.current,addressLine1:ln.current,addressLine2:Ft.current})},...Cu({chv:z,avsCheck:Je,checkoutType:Ae,checkoutLayout:Qe,avsConfig:ae,country:Cn.current})}),Jr=async dn=>{let Zr=Ji(I)||dn?.status==="authorized";_o(W),Ge?.terminal({outcome:"payment_succeeded",...ur}),x("success"),Pe(null),await new Promise(Zo=>setTimeout(Zo,600));let Cr;typeof dn?.paymentId=="string"?Cr=dn.paymentId:I?.paymentId&&(Cr=I.paymentId);let Xr;typeof dn?.authorizationExpiresAt=="string"?Xr=dn.authorizationExpiresAt:I?.authorizationExpiresAt&&(Xr=I.authorizationExpiresAt),s?.(Zr?{status:"authorized",...Cr===void 0?{}:{paymentId:Cr},sessionId:typeof dn?.sessionId=="string"?dn.sessionId:W,...Xr===void 0?{}:{authorizationExpiresAt:Xr},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:X,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:X,checkoutMethod:r.isPaypal?"paypal":"card"})};if(Ot.ok){await Jr(Ot.status===204?null:await Ot.json().catch(()=>null));return}let jn=await Ot.json().catch(()=>null);if(jn?.type==="paypal_redirect_required"){let dn=jn.threeDSecureToken,Zr=jn.paymentMethodId||r.id||"";if(!Se||!dn){x("error"),ue("PayPal authorization required but no token provided.");return}try{let Cr=mt?.getRawProvider();if(!Cr){ue("PayPal is not available.");return}let Xr={return_url:window.location.href};Zr&&(Xr.payment_method=Zr);let{error:Zo}=await Cr.confirmPayment({clientSecret:dn,confirmParams:Xr,redirect:"if_required"});if(Zo){x("error");let sl=Zo.message??"PayPal payment failed.";ue(sl),vr("paypal",sl,{code:Zo.code})}}catch(Cr){x("error"),ue(Cr instanceof Error?Cr.message:"PayPal authorization failed.")}return}if(jn?.type==="paypal_direct_required"){let dn=jn.orderId;if(!dn){x("error"),ue("PayPal retry required but no order id provided.");return}let Zr=Ht.current?.attempts??0;if(Zr>=2){x("error"),ue("PayPal payment could not be completed after multiple attempts."),vr("paypal","paypal_direct_required retry limit exceeded");return}Pi(!1),vi("loading"),Pe({orderId:dn,attempts:Zr+1}),x(null);return}if(Ot.headers.get(Zu)===Xu){let dn=await Qu(ut,W,fe);if(dn!==void 0){await Jr(dn);return}}ku(Ot.status,jn)?Ge?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}):st(),x("error");let il=jn?.message??"Payment failed. Please try again.";ue(il),vr(r.isPaypal?"paypal":"card",il,{code:jn?.code??jn?.gatewayErrorCode,declineCode:jn?.declineCode??jn?.gatewayDeclineReason}),await new Promise(dn=>setTimeout(dn,400))}catch(ut){Ic(ut)||st(),x("error"),ue(ut instanceof Error?ut.message:"An unexpected error occurred"),await new Promise(Ot=>setTimeout(Ot,400))}finally{In(!1),x(null),B.current=!1}},[dt,e,t,Ze,ae,Je,Ae,Qe,z,Se,mt,I,s,ue,vr,wt,J]),An=Ye((r,g)=>{C?C(r):Ys(r,g)},[C,Ys]),Vo=`${wc}:${e}`;ht(()=>{if(typeof window>"u")return;let r=localStorage.getItem(Vo);if(!r)return;let g;try{g=JSON.parse(r)}catch{Xt(Vo);return}if(!g||typeof g.createdAt!="number"||Date.now()-g.createdAt<0||Date.now()-g.createdAt>kc||typeof g.paymentMethodId!="string"||typeof g.providerIntentId!="string"||typeof g.paymentMethodType!="string"||g.sessionId!==e||!t||g.nonce!==t||!uo.includes(g.paymentMethodType)){Xt(Vo);return}Xt(Vo),An({id:g.paymentMethodId,type:"card",threeDSecureActionResultTokenId:g.providerIntentId,gateway:"stripe",paymentMethodType:g.paymentMethodType},{...g.accountPatch?{accountPatch:g.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[An,t,e,Vo,uo]);let Js=G(!1);ht(()=>{if(typeof window>"u"||Js.current)return;let[r,g,W]=vc();if(!r||!g||wa.current||!Se)return;let fe=Se.getRawProvider();if(!fe)return;let D=st=>{let ut=localStorage.getItem(st);if(!ut)return null;try{return JSON.parse(ut)}catch{return Xt(st),null}},X=D(Ir)??D(lc),Rt;if(X?.clientSecret){if(X.clientSecret!==g)return;Rt={...X.accountPatch?{accountPatch:X.accountPatch}:{},...X.sessionId?{sessionId:X.sessionId}:{},...X.nonce?{nonce:X.nonce}:{}}}else if(X?.sessionId&&X.sessionId!==e)return;Js.current=!0,Xt(Ir),Xt(lc),window.history.replaceState({},"",Cc());let lr=X?.paymentMethodType??X?.tokenType??"card",Ge="card";(async()=>{if(W==="failed"){let Tr="Payment was declined. Please try again.";ue(Tr),vr(Ge,Tr);return}let{paymentIntent:st,error:ut}=await fe.retrievePaymentIntent(g);if(ut){let Tr=ut.message??"Failed to retrieve payment status.";ue(Tr),vr(Ge,Tr,{code:ut.code});return}let Ot=st?.status,Jr=ra(Ot);if(!st||!Jr){let Tr=Ot==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ue(Tr),vr(Ge,Tr,{code:Ot??"missing_payment_intent"});return}let jn=typeof st.payment_method=="string"?st.payment_method:st.payment_method?.id;An({id:jn??X?.paymentMethodId??X?.tokenId??st.id,type:"card",threeDSecureActionResultTokenId:st.id,gateway:X?.gateway??"stripe",paymentMethodType:lr},Rt)})()},[e,An,Se,ue,vr]);let Ci=Ye(r=>{r.preventDefault()},[]);if(!(u||Se!==null))return p("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Ko=ze==="buttons",xn=q?.variables,Yc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Si=xn?.colorBackground,Jc=Si&&!Yc.has(Si)?Si:void 0,Go=S.cardInputBorder??(Ko?"#e5e7eb":"#A4A4FF"),Zs=xn?.colorDanger??"#dc2626",Vt=r=>tr[r]&&(hr[r]||$t),Ta=ao&&(gr||$t),Vn=r=>r?Zs:Go,Ma=(Ln.malformed||Ln.empty)&&(fr||$t),Zc=Vn(Ma),wi=S.cardFormContainer?.backgroundColor??Jc??(Ko?"white":"#EDEDFF"),yo=S.cardInputBackground??xn?.colorBackground??"white",ki=ho(Re),Xs=ho(He),mo=S.nameInput,Qs=S.cardInputFontSize??gp(mo?.fontSize)??xn?.fontSizeBase??"16px",el=typeof mo?.fontFamily=="string"?mo.fontFamily:xn?.fontFamily??"Poppins, sans-serif",tl=dl(mo?.fontWeight)??400,Xc=S.cardInputColor??(typeof mo?.color=="string"?mo.color:void 0)??xn?.colorText??"#262833",Qc=S.cardInputPlaceholderColor??"#9ca3af",Zt=xn?.borderRadius??"8px",Gr=xn?.borderRadius??S.cardButton?.borderRadius??Zt,Yr=xn?.colorPrimary??"#4A49FF",ed=xn?.colorPrimaryHover??Qo(Yr,.12),Ii=xn?.colorText??"#262833",Ri={fontSize:Qs,fontFamily:el,fontWeight:tl,color:Xc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Yo={marginTop:"0.375rem",...Ri,fontSize:"0.75rem",lineHeight:1.4,color:Zs},td={"--flopay-input-placeholder-color":Qc,"--flopay-input-font-size":Qs,"--flopay-input-font-family":el,"--flopay-input-font-weight":String(tl)},Jo=S.cardFormContainer??{},Ei=Jo.padding??(Ko?"0":"1rem"),_i=Jo.borderRadius??Zt,nd=It&&or?p(Ti,{capture:It,html:or.html,messageToken:or.messageToken,expectedOrigin:or.expectedOrigin,verificationRequired:or.verificationRequired,theme:Ke,submitLabel:O,onReady:()=>{if(!Lr&&!ae||typeof document>"u")return;let r=()=>{let W=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(W){zn.current=!0;try{W.focus()}finally{zn.current=!1}}};rr.current||r()},onError:r=>{r&&or.verificationRequired&&l.current==="idle"&&(Nr.current=!0),ue(r)},onValidation:r=>{let g=l.current;(g==="idle"||g==="validation-window")&&(ue(r),r&&l.current==="validation-window"&&(R.current&&(clearTimeout(R.current),R.current=null),l.current="idle",x(null)))}},an):p("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"}),nl=Xe("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&_r()},style:{backgroundColor:wi,borderRadius:_i,...Jo,padding:Ei,...td,display:"flex",flexDirection:"column"},children:[p("style",{children:`
|
|
5
5
|
.flopay-shared-input::placeholder {
|
|
6
6
|
color: var(--flopay-input-placeholder-color);
|
|
7
7
|
opacity: 1;
|
|
@@ -9,13 +9,13 @@ ${At.join(`
|
|
|
9
9
|
font-family: var(--flopay-input-font-family);
|
|
10
10
|
font-weight: var(--flopay-input-font-weight);
|
|
11
11
|
}
|
|
12
|
-
`}),
|
|
13
|
-
`)}):null,
|
|
14
|
-
`)}):null,bl=Ve==="apm-expanding"||Ve==="apm-form"||Ve==="apm-collapsing",bo;Ve==="apm-expanding"?bo=bc:Ve==="apm-collapsing"&&(bo=Cc);let La=cn?Nc(ki,cn,he):null;if(Re==="buttons"){let a=Ve==="buttons"||Ve==="expanding"||Ve==="apm-expanding",v=Ve==="expanding"||Ve==="card"||Ve==="collapsing",O=ht===void 0?{boxSizing:"border-box",height:sa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Pe;Ve==="expanding"||Ve==="apm-expanding"?Pe=rp:(Ve==="collapsing"||Ve==="apm-collapsing")&&(Pe=np);let q;return Ve==="expanding"?q=bc:Ve==="collapsing"&&(q=Cc),Qe("form",{onSubmit:Ti,className:L,noValidate:!0,style:{position:"relative"},children:[y(ja,{}),ee&&y(Ir,{status:ee,errorMessage:G,authorized:nr}),Qe("div",{style:{display:"grid"},children:[Qe("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!Pe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!Pe?ap:{},...Pe?{animation:Pe,pointerEvents:"none"}:{}},children:[Pl("flopay-direct-paypal-gate-debug"),vl("flopay-stripe-gate-debug"),Ho&&mt&&Qe(Lo,{children:[Z&&y("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."}),y(pa.Provider,{value:p,children:y(Ja,{sessionId:e,nonce:t,billingApiUrl:at,email:Le.email,billingName:co||void 0,onBuyerIdentityReady:We,clientId:mt.clientId,environment:mt.environment,currency:vt.toUpperCase(),isSubscription:Tt,providerObjectType:Ke,approvalPresentation:Ba==="popup"?void 0:Ba,onTokenizedBody:Fn,onComplete:s,onErrorChange:ye,onDecline:f,onTechnicalFailure:yo,onButtonClick:ie,runBeforeButtonClick:cr,isProcessing:z,onLoadStateChange:Ri,onInitializationStateChange:_i,session:ct,existingOrderId:Z?.orderId,debug:F},Z?.orderId??"fresh")})]}),Yo&&y(so,{stripe:Go,options:js,children:y(Ic,{sessionId:e,nonce:t,email:Le.email,billingName:co||void 0,onBuyerIdentityReady:We,billingApiUrl:at,onTokenizedBody:Fn,onErrorChange:ye,isProcessing:z,onButtonClick:ie,onDecline:f,onTechnicalFailure:yo,runBeforeButtonClick:cr,onLoadStateChange:Js,placeholderBorderRadius:eo,popupCapabilityOwner:p,externalTelemetryContext:al,presentationMode:fo})}),ho?y(so,{stripe:$n,options:qs,children:y(Rc,{sessionId:e,nonce:t,email:Le.email,billingName:co||void 0,onBuyerIdentityReady:We,billingApiUrl:at,intentKind:Fe>0?"payment":"setup",expressMethods:go,onTokenizedBody:Fn,onErrorChange:ye,onButtonClick:ie,onDecline:f,onTechnicalFailure:yo,runBeforeButtonClick:cr,onLoadStateChange:Zs,placeholderBorderRadius:eo,popupCapabilityOwner:p,externalTelemetryContext:re})}):null,!ho&&rl?y("div",{style:{height:sa,borderRadius:eo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Jo&&y(_c,{sessionId:e,nonce:t,email:Le.email,billingName:[Le.firstName,Le.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:We,billingApiUrl:at,paymentElementMethods:Ma,stripeInstance:$n,paymentElementBaseOptions:ki,futureUseSession:he,onTokenizedBody:Fn,onErrorChange:ye,onButtonClick:ie,onDecline:f,runBeforeButtonClick:cr,onLoadStateChange:el,isProcessing:z,submitButtonColor:to,submitButtonBorderRadius:Zt,submitButtonStyle:P.submitButton,onExpandApm:it,expandedApmMethod:cn,themeId:st,buttonAppearance:{backgroundColor:P.cardButton?.backgroundColor,borderColor:P.cardInputBorder,textColor:P.cardButton?.color,borderRadius:eo}}),m&&y("button",{type:"button",onClick:async()=>{z||!(await cr("card")).proceed||(ie?.("card"),K())},disabled:z,style:{width:"100%",...O,...P.cardButton,...Rs({themeBundle:Q,resolvedPrimaryColor:to,resolvedBorderRadius:Zt,submitButtonStyle:P.submitButton,explicitPrimaryColor:Dn?.colorPrimary}),fontSize:P.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:z?"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:z?.6:1},onMouseEnter:ae=>{!z&&(Q||Dn?.colorPrimary)&&(ae.currentTarget.style.backgroundColor=cd)},onMouseLeave:ae=>{(Q||Dn?.colorPrimary)&&(ae.currentTarget.style.backgroundColor=to)},onMouseDown:ae=>{ae.currentTarget.style.transform="scale(0.985)"},onMouseUp:ae=>{ae.currentTarget.style.transform="scale(1)"},children:y(So,{content:ht})}),G&&Ve==="buttons"&&y(Ao,{margin:"0.25rem 0",styleOverride:P.errorBanner,children:G})]}),m&&v&&y("div",{style:{gridArea:"1 / 1",...q?{animation:q}:{},...Ve==="collapsing"?{pointerEvents:"none"}:{}},children:hl}),le&&bl&&cn&&La&&$n&&y("div",{style:{gridArea:"1 / 1",...bo?{animation:bo}:{},...Ve==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Qe("div",{style:{backgroundColor:Mi,borderRadius:Ni,...ta,padding:Di},children:[Qe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Qe("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Xt,style:{display:"inline-flex",alignItems:"center",gap:xi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:P.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...P.backButton},"aria-label":"Back to payment methods",children:[y("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...P.backButtonIcon},children:y("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:y("path",{d:"M15 18l-6-6 6-6"})})}),y(wo,{content:Ee})]}),y("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:Bi,paddingRight:80,...P.title},children:`Pay with ${Sa(cn)}`})]}),y(so,{stripe:$n,options:La,children:y(vs,{method:cn,sessionId:e,nonce:t,email:Le.email,billingName:[Le.firstName,Le.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:We,billingApiUrl:at,onTokenizedBody:Fn,onErrorChange:ye,onDecline:f,onCancel:Xt,runBeforeButtonClick:cr,onButtonClick:ie,isProcessing:z,submitButtonColor:to,submitButtonBorderRadius:Zt,submitButtonStyle:P.submitButton,errorText:G})},cn)]})})]})]})}return bl&&cn&&La&&$n&&le?Qe("form",{onSubmit:Ti,className:L,noValidate:!0,style:{position:"relative"},children:[y(ja,{}),ee&&y(Ir,{status:ee,errorMessage:G,authorized:nr}),y("div",{style:{...bo?{animation:bo}:{},...Ve==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Qe("div",{style:{backgroundColor:Mi,borderRadius:Ni,...ta,padding:Di},children:[Qe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Qe("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Xt,style:{display:"inline-flex",alignItems:"center",gap:xi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:P.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...P.backButton},"aria-label":"Back to payment methods",children:[y("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...P.backButtonIcon},children:y("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:y("path",{d:"M15 18l-6-6 6-6"})})}),y(wo,{content:Ee})]}),y("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:Bi,paddingRight:80,...P.title},children:`Pay with ${Sa(cn)}`})]}),y(so,{stripe:$n,options:La,children:y(vs,{method:cn,sessionId:e,nonce:t,email:Le.email,billingName:[Le.firstName,Le.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:We,billingApiUrl:at,onTokenizedBody:Fn,onErrorChange:ye,onDecline:f,onCancel:Xt,runBeforeButtonClick:cr,onButtonClick:ie,isProcessing:z,submitButtonColor:to,submitButtonBorderRadius:Zt,submitButtonStyle:P.submitButton,errorText:G})},cn)]})})]}):Qe("form",{onSubmit:Ti,className:L,noValidate:!0,style:{position:"relative"},children:[y(ja,{}),ee&&y(Ir,{status:ee,errorMessage:G,authorized:nr}),Qe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Pl("flopay-direct-paypal-gate-debug-default"),vl("flopay-stripe-gate-debug-default"),Ho&&mt&&Qe(Lo,{children:[Z&&y("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."}),y(pa.Provider,{value:p,children:y(Ja,{sessionId:e,nonce:t,billingApiUrl:at,email:Le.email,billingName:co||void 0,onBuyerIdentityReady:We,clientId:mt.clientId,environment:mt.environment,currency:vt.toUpperCase(),isSubscription:Tt,providerObjectType:Ke,approvalPresentation:Ba==="popup"?void 0:Ba,onTokenizedBody:Fn,onComplete:s,onErrorChange:ye,onDecline:f,onTechnicalFailure:yo,onButtonClick:ie,runBeforeButtonClick:cr,isProcessing:z,onLoadStateChange:Ri,onInitializationStateChange:_i,session:ct,existingOrderId:Z?.orderId,debug:F},Z?.orderId??"fresh")})]}),Yo&&y(so,{stripe:Go,options:js,children:y(Ic,{sessionId:e,nonce:t,email:Le.email,billingName:co||void 0,onBuyerIdentityReady:We,billingApiUrl:at,onTokenizedBody:Fn,onErrorChange:ye,isProcessing:z,onButtonClick:ie,onDecline:f,onTechnicalFailure:yo,runBeforeButtonClick:cr,onLoadStateChange:Js,placeholderBorderRadius:eo,popupCapabilityOwner:p,externalTelemetryContext:al,presentationMode:fo})}),ho&&y(so,{stripe:$n,options:qs,children:y(Rc,{sessionId:e,nonce:t,email:Le.email,billingName:co||void 0,onBuyerIdentityReady:We,billingApiUrl:at,intentKind:Fe>0?"payment":"setup",expressMethods:go,onTokenizedBody:Fn,onErrorChange:ye,onButtonClick:ie,onDecline:f,onTechnicalFailure:yo,runBeforeButtonClick:cr,onLoadStateChange:Zs,placeholderBorderRadius:eo,popupCapabilityOwner:p,externalTelemetryContext:re})}),Jo&&y(_c,{sessionId:e,nonce:t,email:Le.email,billingName:[Le.firstName,Le.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:at,paymentElementMethods:Ma,stripeInstance:$n,paymentElementBaseOptions:ki,futureUseSession:he,onTokenizedBody:Fn,onErrorChange:ye,onButtonClick:ie,onDecline:f,runBeforeButtonClick:cr,onLoadStateChange:el,isProcessing:z,submitButtonColor:to,submitButtonBorderRadius:Zt,submitButtonStyle:P.submitButton,themeId:st,onExpandApm:it,expandedApmMethod:cn,buttonAppearance:{backgroundColor:P.cardButton?.backgroundColor,borderColor:P.cardInputBorder,textColor:P.cardButton?.color,borderRadius:eo}})]}),m&&(nd||td||rd)&&y(Sl,{label:"or pay with card"}),m&&hl]})}import{Fragment as Er,jsx as pe,jsxs as an}from"react/jsx-runtime";var zo=44,Fs="flopay_checkout_saved_payment_resume",gi=new Map,yi=new Map;function Lc(e,t){t.settled&&t.consumers===0&&gi.get(e)===t&&gi.delete(e)}function Cp(e,t,n){let r=yi.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};yi.set(e,i);let s=()=>{yi.get(e)===i&&yi.delete(e)};return o.then(s,s),o}function Ia(e){return new Promise(t=>setTimeout(t,e))}function fi(e,t,n){let r=Ga({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Wc,enabled:t!==!1});return r.beginCheckout(n),r}function ka(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ts(e,t,n,r,o,i){let s=fi(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),ka(s)}function Uc(e,t,n,r){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()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function zc(e,t,n,r,o){let i=Kc(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:n,attempt:o,statusClass:i.statusClass}),t instanceof Cn&&t.code==="session_auto_completed"?!1:t instanceof Cn&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...i,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function Hc(e,t){let n=e?.data.paypal?.publishableKey;if(n)return{clientId:n,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation,...t?{existingOrderId:t}:{}}}function As(e){return!e||e.data.stripe?.publishableKey?!1:!!Hc(e)?.clientId}var Sp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function wp(e){return new mp(Sp,{publishableKey:"provider_unavailable",...e})}async function Ms(e,t){let{publishableKey:n,paypalPublishableKey:r}=ls(e);return{...await cs({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Ds(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Ip(){if(!Ds())return null;try{let e=window.sessionStorage.getItem(Fs);return e?JSON.parse(e):null}catch{return null}}function qc(e){if(Ds())try{window.sessionStorage.setItem(Fs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function xs(){if(Ds())try{window.sessionStorage.removeItem(Fs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function kp(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function jc(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 Bs(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Rp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function $c(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function _p(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 Ns({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:s,loading:d,error:f,onComplete:u,onError:w,onInstrument:b,onDecline:j,onCountryChange:L,onZipChange:I,showPayPal:N=!0,showStripe:U=!0,walletPresentation:h="auto",enabledPaymentMethods:C,showApplePay:le=!0,showGooglePay:D=!0,debug:ve=!1,layout:J,theme:ke,buttonsTheme:qe,buttonsStyles:Re,cardButtonContent:st,cardBackButtonContent:qt,cardTitleContent:fe,showSecurityFooter:Ae,onButtonClick:ht,onBeforeButtonClick:Ee,enableAVS:He,cardFieldOrder:_e,cardPreFormSlot:ie,avsLayout:je,submitLabel:$e,className:pt,initialErrorMessage:Ce=null,initialPayPalOrderId:ge,children:ce,checkoutMode:M,confirmLabel:Se,renderConfirmButton:Ue,onSessionCompleted:Me}){let V=Pp(r),Pt=Qn(()=>Vc(ke),[ke]),ze=i??Pt?.appearance,Te=n?"embedded_checkout":"standard_checkout",Ze=Bs(ce,J),[xe,et]=Ht(null),[Fe,vt]=Ht(null),Gt=Ft(null),mt=Ft(null),Tt=Ft(0),[E,se]=Ht(null),De=Ft(null),[F,we]=Ht(null),yt=Qn(()=>n?xo(n):"",[n]),Ne=n?`create:${yt}`:`session:${e??""}`,St=$c(F),T=Ft(new Set),p=Ft(Ne),g=Ft(Ne);ra(()=>{g.current=Ne,p.current!==Ne&&(p.current=Ne,T.current.clear())},[Ne]);let x=bn(k=>{if(g.current===Ne){if(Gi.has(k.name)){if(T.current.has(k.name))return;T.current.add(k.name)}Bt(()=>b?.(k))}},[Ne,b]),A=To(x,Ne),re=Ft(!1),ct=bn(k=>{if(re.current)return;let _=k.gateway||!St?k:{...k,gateway:St};x(_)},[x,St]);yr(()=>{A({class:"lifecycle",name:"checkout.mount"})},[A]);let[he,Ke]=Ht(e??""),X=e??he,jt=n?"":X,[bt,At]=Ht(!0),[at,de]=Ht(null),[_n,On]=Ht(0),[mn,$t]=Ht("full"),[Ln,Un]=Ht(!1),[hn,Mt]=Ht(Ce),[Ge,Oe]=Ht(null),[En,wt]=Ht(null),[zn,yn]=Ht(!1),[Kt,Qt]=Ht(void 0),[er,Wn]=Ht(""),[en,It]=Ht(!1),[tn,rn]=Ht(!1),[Dt,sn]=Ht(!1),Ot=Ft(null),on=Ft(0),Nt=Ft(void 0),[W,tr]=Ht("loading"),[nr,rr]=Ht(0),nn=Ft(!1),Tn=Ft(!1),Sn=Ft(!1),me=Ft(null),tt=Ft(null),m=Qn(()=>({checkoutMode:M??mn,layout:Rp(ce,J)}),[M,ce,mn,J]),Be=Ft(u);Be.current=u;let $=Ft(w);$.current=w;let Pn=Ft(j);Pn.current=j;let qn=bn(k=>ri(me,async _=>{try{return await k(_)}catch(K){throw _.aborted?Yr(K):K}}),[]);yr(()=>()=>{me.current?.abort(),me.current=null},[]);let Yt=bn((k,_)=>{Gt.current=k,vt(k),De.current=_,se(_)},[]),An=bn(()=>{let k=mt.current;k&&(mt.current=null,k.destroy())},[]);yr(()=>{pn(Fe)?.setCheckoutContext(m),E&&E!==Fe&&pn(E)?.setCheckoutContext(m)},[Fe,E,m]);let nt=Ft(Me);nt.current=Me;let or=bn(k=>{tr(k),!(k!=="exhausted"||Sn.current)&&(Sn.current=!0,$.current?.(new Cn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Zr=bn(()=>{tr("retrying"),rr(k=>k+1)},[]);yr(()=>{tr("loading"),rr(0),Sn.current=!1},[X]),yr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Wc,checkout_type:Te,checkout_layout:Ze,billing_api_url:V})},[Ze,Te,V]);let kt=Qn(()=>n?xo(n,!0):"",[n]),Mn=Qn(()=>er===kt?Kt:void 0,[Kt,er,kt]),fr=Qn(()=>n?Ki(n,Mn):void 0,[n,Mn]),Hn=M??fr?.checkoutMode??"full",Jt=Qn(()=>fr?{...fr,checkoutMode:Hn}:void 0,[fr,Hn]);yr(()=>{Qt(void 0),Wn(kt),Nt.current=void 0,Ot.current=null,sn(!1)},[kt]),yr(()=>{Mt(Ce)},[Ce]);let ar=bn((k,_,K)=>{Bt(()=>{Pn.current?.(un(k,_,K))})},[]),xn=bn(async(k,_)=>{Mt(null),wt(null),yn(!1),Oe("processing");let K=_?.sessionId??k.id,oe=k.clientSecret||t,it=$c(k),Xt=Gt.current??De.current,ee=pn(Xt),H=Xt?null:fi(V,o,m),B={log:be=>{ee?ee.log(be):H?.log(be)},error:be=>{ee?ee.error(be):H?.error(be)},terminal:be=>{ee?ee.terminal(be):H?.terminal(be)},performance:be=>{ee?ee.performance(be):H?.performance(be)},now:()=>ee?.now()??H?.now()??0,elapsed:be=>ee?.elapsed(be)??Math.max(0,(H?.now()??be)-be)},l=B.now(),c=!!(_?.initialAutoProcessingError||_?.initialAutoProcessingPending),S=!1,R,te=()=>{S||(S=!0,c=!0,R=B.now(),B.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Z=!1,dt=()=>{Z||(Z=!0,B.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),B.performance({stage:"processing",durationMs:B.elapsed(l),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),R!==void 0&&B.performance({stage:"recovery",durationMs:B.elapsed(R),durationMode:"machine",paymentMethodCategory:"saved"}))};B.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),re.current=!0;try{B.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{re.current=!1}A({class:"lifecycle",name:"payment.processing.started",provider:it}),c&&te();let Lt;try{let be=pc(_?.initialAutoProcessingError),Ie=_?.initialAutoProcessingError?.type==="3ds_required"&&!_.initialAutoProcessingError.threeDSecureToken&&_.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:_.initialAutoProcessingError.nextActionRedirectUrl}:null,We,G=Q=>(te(),qn(P=>Fo(Q,{billingApiUrl:V,sessionId:K,nonce:oe,session:k,signal:P})));if(Ie)We=await G(Ie);else if(be)te(),be.type==="paypal_redirect_required"&&tt.current?.publishableKey&&qc({sessionId:K,publishableKey:tt.current.publishableKey,paypalPublishableKey:tt.current.paypalPublishableKey}),We=await qn(Q=>ii(be,{flopay:Gt.current,paypalFlopay:De.current,attempt3DS:_?.attempt3DS,billingApiUrl:V,sessionId:K,session:k,telemetry:!1,signal:Q})),be.type==="paypal_redirect_required"&&xs();else if(_?.initialAutoProcessingPending){let Q=_.initialAutoProcessingPending,P=new mi(V,{telemetry:!1}),Y=await qn(z=>P.waitForCheckoutSessionCompletion(Q.sessionId,{initialDelayMs:Q.retryAfterMs,nonce:oe,statusUrl:Q.statusUrl,signal:z})),Ye=Kr(Y,k),Rt=Y.autoProcessingError?.type==="3ds_required"&&Y.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Y.autoProcessingError.nextActionRedirectUrl}:null;if(Rt)We=await G(Rt);else{if(!Fr(Ye))throw Ro(Ye);We=Br(Ye,K)}}else{if(_?.initialAutoProcessingError)throw Rr(_.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:_.initialAutoProcessingError.checkoutMethod});if(_?.fromCreateSession)return _?.fallbackToFull&&($t("full"),jc("full")),!1;{let Q=await Do({billingApiUrl:V,sessionId:K,session:k,nonce:oe,telemetry:!1});Q.type==="success"?We=Q.result:Q.type==="next_action_required"?We=await G(Q):(te(),Q.type==="paypal_redirect_required"&&tt.current?.publishableKey&&qc({sessionId:K,publishableKey:tt.current.publishableKey,paypalPublishableKey:tt.current.paypalPublishableKey}),We=await qn(P=>ii(Q,{flopay:Gt.current,paypalFlopay:De.current,attempt3DS:_?.attempt3DS,billingApiUrl:V,sessionId:K,session:k,telemetry:!1,signal:P})),Q.type==="paypal_redirect_required"&&xs())}}K&&Bo(K),dt(),c&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),B.terminal({outcome:We.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),yn(We.status==="authorized"),Oe("success"),await Ia(600),Lt=()=>Be.current?.(We)}catch(be){let Ie=jr(Pa(be),K);if(Ie.code==="three_ds_aborted")return!1;let We=Ie.checkoutMethod??ha;Mt(Ie.message),wt(Ie.message),yn(!1),_?.fallbackToFull&&(B.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),$t("full"),jc("full")),dt();let G=Ie.statusCode===void 0?void 0:bp(Ie.statusCode,"unknown"),Q=G==="4xx"?{requestCategory:"process_payment",statusClass:G}:{},P=G===void 0||G==="4xx";if(P&&(Ie.telemetryOutcome==="payment_declined"||!!(Ie.declineCode||Ie.code?.toLowerCase().includes("declin"))))B.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Q});else if(P&&(Ie.telemetryOutcome==="validation_rejected"||Ie.type==="validation_error"))B.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Q});else{let Rt=Kc(be,c?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),z=Ie.telemetryRequestCategory??"process_payment";re.current=!0;try{B.error({...Rt,...Ie.telemetryFailureCategory?{failureCategory:Ie.telemetryFailureCategory}:{},stage:c?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:z})}finally{re.current=!1}A({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:z,provider:it})}return Bt(()=>$.current?.(Ie)),ar(We,Ie,{code:Ie.code,declineCode:Ie.declineCode}),Oe("error"),await Promise.allSettled([Ia(400),_?.ensureProvidersReady?_.ensureProvidersReady():Promise.resolve()]),c&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{dt(),H&&ka(H),Oe(null),wt(null)}return Bt(Lt),!0},[ar,A,t,V,qn,o,m]);yr(()=>{if(typeof window>"u"||Tn.current)return;let k=new URLSearchParams(window.location.search),_=k.get("payment_intent_client_secret");if(!_)return;let K=Ip();K&&(Tn.current=!0,(async()=>{let oe,it=0;Mt(null),wt(null),Oe("processing"),Un(!0);try{if(k.get("redirect_status")==="failed")throw Object.assign(new Cn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Xt,paypalFlopay:ee}=await cs({publishableKey:K.publishableKey,paypalPublishableKey:K.paypalPublishableKey,billingApiUrl:V,locale:s,telemetry:o});oe=pn(ee??Xt),oe?.setCheckoutContext(m),it=oe?.now()??0,oe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),oe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let H=(ee??Xt)?.getRawProvider();if(!H)throw Object.assign(new Cn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:l}=await H.retrievePaymentIntent(_);if(l)throw Object.assign(new Cn(l.message??"Failed to retrieve PayPal payment status.","api_error",{code:l.code}),{checkoutMethod:"paypal"});let c=Kl(B?.status);if(!B||c==="failed")throw Object.assign(new Cn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let S=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,R=c;if(K.sessionId){let dt=(await new mi(V,{telemetry:!1}).getUnifiedCheckoutSession(K.sessionId)).data.session;if(dt&&dt.status!=="complete"){let Lt=await Do({billingApiUrl:V,sessionId:K.sessionId,session:dt,telemetry:!1,tokenizedData:{id:S??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(Lt.type!=="success")throw Object.assign(new Cn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});R=Lt.result.status}}K.sessionId&&Bo(K.sessionId),oe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),oe?.performance({stage:"redirect_resume",durationMs:oe.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),oe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Oe("success"),await Ia(600),Bt(()=>Be.current?.({status:R,paymentIntentId:B.id,paymentMethodId:S,checkoutMethod:"paypal"}))}catch(Xt){let ee=jr(Pa(Xt),K.sessionId),H=ee.checkoutMethod??"paypal",B=!!(ee.declineCode||ee.code?.toLowerCase().includes("declin"));if(oe)oe.performance({stage:"redirect_resume",durationMs:oe.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?oe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):oe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let l=fi(V,o,m);l.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ka(l)}else Ts(V,o,m,"REDIRECT_RESUME_FAILED","redirect_resume");Mt(ee.message),wt(ee.message),Bt(()=>$.current?.(ee)),ar(H,ee,{code:ee.code,declineCode:ee.declineCode}),Oe("error"),await Ia(400)}finally{xs(),kp(),Oe(null),wt(null),Un(!1)}})())},[ar,s,V,o,m]);let Tr=Ft(null),Bn=Qn(()=>Jt?xo(Jt):"",[Jt]),gr=Ft(Jt);gr.current=Jt,yr(()=>{Ke(e??"")},[e]),yr(()=>{nn.current=!1,Mt(Ce),wt(null),yn(!1),Oe(null)},[Bn,Ce,e]);async function hr(k,_,K){let oe=fi(V,o,m),it=new mi(V,{telemetry:!1}),Xt=!1;try{let ee=k.idempotencyKey===void 0?void 0:Oc(k.idempotencyKey),H=ts(_,K),B=ns(_,K);H?.canonicalIdentity===K&&B&&B.canonicalIdentity===void 0&&(ei(_,K,B.idempotencyKey),B={...B,canonicalIdentity:K});let l=ee??(B?.canonicalIdentity===K?B.idempotencyKey:void 0),c,S=!1;oe.log({name:H?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let R=H?.sid??null,te=null,Z,dt,Lt=!1;if(R)try{te=await it.getUnifiedCheckoutSession(R,H?.nonce),H&&H.canonicalIdentity===void 0&&(ac(te.data.session,k)?(Qa(_,K,R,H.nonce??te.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(ei(_,K,B.idempotencyKey),l??(l=B.idempotencyKey))):(Za(_,K),B=null,l=ee,R=null,te=null));let Ie=te?.data.session?.status,We=te?.data.session,G=We?.clientSecret||H?.nonce;if(R&&We?.buyerIdentified===!1&&G&&(dt=ko(it,R,G,k.account)),R&&te&&Ie==="complete"){if(rs(R))return{sid:R,result:te};Za(_,K),R=null,te=null,S=!0}}catch{oe.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),H?.canonicalIdentity===void 0?(Za(_,K),l=ee):Xa(_,K),R=null}if(!R){!ee&&(S||!l)&&(l=Oc(),c=l),l&&ei(_,K,l);let Ie=oe.now(),We=0;oe.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let G={...k,idempotencyKey:l,avsCheck:!!He,avsConfig:typeof He=="object"?He:void 0,checkoutType:"embedded_checkout",checkoutLayout:Bs(ce,J)};Object.defineProperty(G,yp,{configurable:!1,enumerable:!1,value:{onAttempt:Y=>{We=Math.max(We,Y)}}});let Q=()=>{Uc(oe,"session_create",Ie,We)},P=Y=>{zc(oe,Y,"session_create",Ie,We)&&A({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(gp(G)){let Y=await it.createDetachedSession(G);Y.claimed.catch(()=>{}),te=Y.shell,R=Y.sessionId,dt=Y.claim;let Ye=oe.now();oe.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Z=Y.claimed.then(Rt=>{let z=Rt.data.session?.id??Y.sessionId;return z&&Qa(_,K,z,Rt.data.session?.clientSecret??Y.nonce),Uc(oe,"session_claim",Ye),Q(),Rt},Rt=>{throw Xa(_,K),zc(oe,Rt,"session_claim",Ye,0)&&A({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Rt}).finally(()=>ka(oe)),Z.catch(()=>{}),Xt=!0,oe.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),oe.performance({stage:"session_shell",durationMs:oe.now()-Ie,durationMode:"machine",requestCategory:"session_create",attempt:We,statusClass:"2xx",paymentMethodCategory:"card"})}else te=await it.createAndFetchSession(G),Q()}catch(Y){throw P(Y),Y}R=te.data.session?.id??R??"",R&&!Z&&Qa(_,K,R,te.data.session?.clientSecret)}let be=te?.data.session;return!dt&&R&&be?.buyerIdentified===!1&&be.clientSecret&&(dt=ko(it,R,be.clientSecret,k.account)),{sid:R??"",result:te,sdkGeneratedIdempotencyKey:c,...Z?{claimed:Z}:{},...dt?{claim:dt}:{},...Lt?{claimRequiresIdentity:!0}:{}}}finally{Xt||ka(oe)}}let Ar=Ft(hr);ra(()=>{Ar.current=hr},[hr]);let jn=bn(async(k,_)=>{let K=gr.current;if(!K)throw new Cn("createSession is required to bootstrap checkout.","validation_error");let oe=Ki(K,k),it=xo(oe),Xt=oc(oe),ee=gi.get(it);if(!ee){let l={canonicalIdentity:it,promise:Ar.current(oe,Xt,it),consumers:0,settled:!1};ee=l,gi.set(it,l);let c=()=>{l.settled=!0,Lc(it,l)};l.promise.then(c,c)}ee.consumers+=1;let H=!1,B=()=>{H||(H=!0,ee.consumers-=1,Lc(it,ee))};_?.(B);try{let l=await ee.promise;Tr.current=it,k&&(Wn(kt),Qt(be=>ql(be,k)));let{sid:c,result:S,claimed:R,claim:te,claimRequiresIdentity:Z}=l;if(Nt.current=te,sn(Z===!0),et(S),S.data.session&&we(S.data.session),c&&Ke(c),R){on.current+=1;let be=on.current;Ot.current=R,rn(!0),R.then(Ie=>{on.current===be&&(Ot.current===R&&(Ot.current=null),et(Ie),Ie.data.session&&we(Ie.data.session),rn(!1),sn(!1))},Ie=>{on.current===be&&(Ot.current===R&&(Ot.current=null),rn(!1),sn(!1),de(Ie instanceof Cn?Ie:new Cn(Ie instanceof Error?Ie.message:"Failed to create session","api_error")))})}else on.current+=1,Ot.current=null,rn(!1),sn(!1);let{flopay:dt,paypalFlopay:Lt}=await Ms(S,{billingApiUrl:V,locale:s,telemetry:o});return Yt(dt,Lt),At(!1),l}catch(l){throw Tr.current===it&&(Tr.current=null),l}finally{_||B()}},[kt,Yt,s,V,o]),Gn=Ft(xn);Gn.current=xn;let Mr=Ft(jn);Mr.current=jn;let xt=bn(async k=>{if(!_p(k)||en)return{sessionId:he,session:F};It(!0);try{let _=await jn(k);return{sessionId:_.sid,session:_.result.data.session??null}}finally{It(!1)}},[jn,en,he,F]),wn=bn(async k=>{let _=Nt.current;if(!_)return;let K=on.current,oe=await _(k);on.current===K&&(et(oe),oe.data.session&&we(oe.data.session))},[]),Yn=bn(async()=>{await Ot.current},[]),ir=bn(async()=>(await Yn(),{proceed:!0}),[Yn]);yr(()=>{let k=!1,_,K=++Tt.current;An(),de(null),On(0);let oe=()=>{k=!0,Tt.current===K&&(Tt.current+=1,An())},it=gr.current;if(Bn&&it)return $t(Hn),At(!1),Tr.current===Bn?oe:(we(jl(it,M)),(async()=>{let H=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),B=Hn==="auto"&&!nn.current&&!H;B&&(Mt(null),wt(null),Oe("processing"));try{let l=await Mr.current(void 0,te=>{_=te}),c=l.result.data.session??null;tt.current=ls(l.result);let S=As(l.result),R=rs(l.sid||c?.id);if(!k&&B&&c&&!S&&!R){nn.current=!0,await Cp(Bn,l.sdkGeneratedIdempotencyKey,()=>Gn.current(c,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:l.result.autoProcessingError,initialAutoProcessingPending:l.result.autoProcessingPending,autoProcessingAttempted:l.result.autoProcessingAttempted,sessionId:l.sid||c.id}));return}!k&&B&&((S||R)&&(nn.current=!0),Oe(null),wt(null))}catch(l){if(k)return;let c=Ka(l);if(B&&c==="session_auto_completed"){nn.current=!0,Oe("success"),await Ia(600),k||(Bt(()=>{Be.current?.({status:"succeeded"})}),Oe(null),wt(null));return}B&&(Oe(null),wt(null));let S=l instanceof Cn?l:new Cn(l instanceof Error?l.message:"Failed to create session","api_error");de(S)}finally{_?.(),_=void 0}})(),()=>{oe(),_?.()});At(!0);async function Xt(){let H=!1,B=null;try{let l=new mi(V,{telemetry:!1}),c=await l.getUnifiedCheckoutSession(X,t);if(B=c,k)return;et(c);let S=c.data.session??null;if(we(S),!S)throw new Cn("No session data returned","api_error");let R=S.checkoutMode;if(R==="setup")throw new Cn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(S.status==="authorized"){At(!1),Bt(()=>{Be.current?.(Br(S,X)),nt.current?.(S.successUrl??"")});return}if(S.status==="complete"){At(!1),Bt(()=>{nt.current?.(S.successUrl??"")});return}if(S.status==="expired")throw $a(S);H=!0;let te=M??R??"full";$t(te),on.current+=1;let Z=S.clientSecret||t;Nt.current=S.buyerIdentified===!1&&Z?ko(l,X,Z,{...S.customer?.id?{userId:S.customer.id}:{}}):void 0,rn(!1),sn(!1);let dt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Lt=As(c);if(te==="auto"&&!nn.current&&!dt&&!Lt){nn.current=!0;let be=ee(c);try{if(await Gn.current(S,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>be,sessionId:X||S.id}),k)return;await be,k||At(!1);return}catch{if(k)return;await be,k||At(!1);return}}await ee(c),k||At(!1)}catch(l){if(k)return;let c=zl(l,H);if(H&&A({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),c){let{errorCode:R,stage:te,...Z}=c;Ts(V,o,m,R,te,Z)}if(c?.stage==="provider_load"&&(M??B?.data.session?.checkoutMode??"full")==="full"&&Ul(B,N,U)){let R=wp({billingApiUrl:V,locale:s,telemetry:o});mt.current=R,Yt(R,null),On(1),At(!1);return}let S=l instanceof Cn&&c?.stage!=="provider_load"?l:Ll();S!==l&&Bt(()=>$.current?.(S)),de(S),At(!1)}}async function ee(H){let{flopay:B,paypalFlopay:l,...c}=await Ms(H,{billingApiUrl:V,locale:s,telemetry:o});tt.current={publishableKey:c.publishableKey,paypalPublishableKey:c.paypalPublishableKey},Yt(B,l),On(0)}return Xt(),oe},[M,Bn,Hn,jt,t,N,U]);let Pr=bn(async()=>{if(!xe||_n!==1)return;let k=Tt.current;On(2);try{let{flopay:_,paypalFlopay:K}=await Ms(xe,{billingApiUrl:V,locale:s,telemetry:o});if(Tt.current!==k)return;An(),Yt(_,K),On(0)}catch(_){if(Tt.current!==k)return;let{errorCode:K,stage:oe,...it}=ji(_);Ts(V,o,m,K,oe,it)}},[An,Yt,s,_n,V,o,m,xe]),Ve=!!(X&&(F?.clientSecret||t)),ln=Ln||!Ve,cn=bn(async()=>{if(!(Ln||!Ve||!F)){Un(!0),Mt(null);try{await xn(F,{attempt3DS:!0,fallbackToFull:!0,sessionId:X||F.id})}finally{Un(!1)}}},[X,Ln,Ve,xn,F]),In=Hc(xe,ge),Qr=As(xe),vr=Qn(()=>{if(!(!xe||!F||!xe.data.stripe?.publishableKey))return{billingApiUrl:V}},[xe,F,V]),Or=!!(n&&!ce&&J==="buttons"&&Ee&&Hn==="full"),kn=!!(X&&(hp(F?.vault)||qr(F))),dn=Qn(()=>({session:F,loading:bt,error:at,checkoutMode:mn,inlineSessionDraft:Jt,applyInlineSessionPatch:Or?xt:void 0,inlineSessionPatchProcessing:en,claimPending:tn,claimRequiresIdentity:Dt,claimBuyerIdentity:wn,waitForDataAttachment:Yn}),[F,bt,at,mn,Jt,Or,xt,en,tn,Dt,wn,Yn]),sr=!!n&&J==="buttons"&&!Qr&&!kn&&(!Fe||!vr),fn=Ge?pe(Ir,{status:Ge,errorMessage:En,authorized:zn}):null;if(bt&&!kn){if(d)return an(Er,{children:[d,fn]});if(J==="buttons"){let k=Pt?.buttonsLayout?.cardButton?.borderRadius??Pt?.appearance.variables?.borderRadius??8,_=K=>pe("div",{style:{height:K,borderRadius:k,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return an(Er,{children:[an("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[N&&_(zo),U&&(le||D)&&_(zo),U&&_(zo),pe("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),fn]})}return an(Er,{children:[an("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[pe("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),pe("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),fn]})}return at?f?pe(ur.Provider,{value:dn,children:f(at)}):pe(ur.Provider,{value:dn,children:pe("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:at.message})}):sr?an(Er,{children:[pe(ur.Provider,{value:dn,children:pe(Tp,{onButtonClick:ht,showPayPal:N,showStripe:U,showApplePay:le,showGooglePay:D,theme:ke,buttonsTheme:qe,buttonsStyles:Re,cardButtonContent:st,cardBackButtonContent:qt,cardTitleContent:fe})}),fn]}):Qr&&F&&In?an(Er,{children:[pe(ur.Provider,{value:dn,children:an("div",{className:pt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[hn&&pe(Ao,{icon:!1,children:hn}),W==="retrying"&&pe("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),W==="exhausted"&&an("div",{role:"alert",children:[pe("div",{children:"PayPal is temporarily unavailable. Please try again."}),pe("button",{type:"button",onClick:Zr,children:"Retry PayPal"})]}),W!=="exhausted"&&pe("div",{"aria-hidden":W==="retrying"?!0:void 0,style:W==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:pe(nc,{sessionId:X,nonce:F.clientSecret||void 0,billingApiUrl:V,email:F.customer?.email||Jt?.account?.email,billingName:[F.customer?.firstName,F.customer?.lastName].filter(Boolean).join(" ")||[Jt?.account?.firstName,Jt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:wn,clientId:In.clientId,environment:In.environment,currency:(F.currency??"usd").toUpperCase(),isSubscription:F.mode==="subscription",providerObjectType:In.providerObjectType,approvalPresentation:In.approvalPresentation,existingOrderId:In.existingOrderId,onComplete:u,onErrorChange:Mt,onDecline:j,onButtonClick:ht,runBeforeButtonClick:ir,onInitializationStateChange:or,allowAutomaticRetry:nr===0,session:F,telemetry:o,telemetryContext:m,onInstrument:ct,debug:ve},`${Ne}:paypal-init-${nr}`)})]})}),fn]}):mn==="confirm"?an(Er,{children:[pe(ur.Provider,{value:dn,children:pe(ti,{flopay:Fe,paypalFlopay:E,options:vr??{billingApiUrl:V},onInstrument:ct,children:an("div",{className:pt,children:[hn&&pe("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:hn}),Ue?Ue({onConfirm:cn,isProcessing:ln}):pe("button",{type:"button",onClick:cn,disabled:ln,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:ln?"not-allowed":"pointer",opacity:ln?.6:1},children:Ln?"Processing...":Se??"Confirm Purchase"})]})},Ne)}),fn]}):(!Fe||!vr)&&!(kn&&mn==="full")?pe(Er,{children:fn}):an(Er,{children:[pe(ur.Provider,{value:dn,children:an(ti,{flopay:Fe,paypalFlopay:E,options:vr??{billingApiUrl:V},onInstrument:ct,children:[_n===1&&pe("button",{type:"button",onClick:Pr,children:"Retry payment methods"}),ce?an(Er,{children:[hn&&pe("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:hn}),pe(Ep,{sessionId:X,nonce:F?.clientSecret||void 0,billingApiUrl:V,session:F,submitLabel:$e,walletPresentation:h,children:ce})]}):pe(_s,{sessionId:X,nonce:F?.clientSecret||void 0,telemetry:o,email:F?.customer?.email||Jt?.account?.email,userId:F?.customer?.id||Jt?.account?.userId,firstName:F?.customer?.firstName||Jt?.account?.firstName,lastName:F?.customer?.lastName||Jt?.account?.lastName,totalAmount:F?Math.round(fp(F).total*100):0,currency:F?.currency?.toLowerCase()??"usd",onComplete:u,onError:w,onDecline:j,error:hn,onErrorChange:Mt,showPayPal:N,showStripe:U,walletPresentation:h,enabledPaymentMethods:_n?[]:C??xe?.data.stripe?.enabledPaymentMethods??F?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:xe?.data.stripe?.enabledPaymentMethodCountries,showApplePay:le,showGooglePay:D,layout:J,theme:ke,buttonsTheme:qe,buttonsStyles:Re,appearance:ze,cardButtonContent:st,cardBackButtonContent:qt,cardTitleContent:fe,onButtonClick:ht,onBeforeButtonClick:Ee,onBuyerIdentityReady:wn,enableAVS:He,..._e?{cardFieldOrder:_e}:{},...ie?{cardPreFormSlot:ie}:{},avsLayout:je,country:F?.customer?.country,city:F?.customer?.city,state:F?.customer?.state,onCountryChange:L,onZipChange:I,avsCheck:!!He,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Bs(ce,J),className:pt,submitLabel:$e,directPaypal:In,isSubscription:F?.mode==="subscription",session:F,dataAttachmentPending:tn,dataAttachmentRequiresIdentity:Dt,debug:ve})]},Ne)}),fn]})}function Ep({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:i,children:s}){return pe(Er,{children:Es.Children.map(s,d=>{if(!Es.isValidElement(d))return d;let f=d.props,u={};return f.sessionId||(u.sessionId=e),!f.nonce&&t&&(u.nonce=t),f.billingApiUrl||(u.billingApiUrl=n),f.submitLabel===void 0&&o!==void 0&&(u.submitLabel=o),f.walletPresentation===void 0&&(u.walletPresentation=i),r?.customer&&(f.email||(u.email=r.customer.email),f.userId||(u.userId=r.customer.id),f.firstName||(u.firstName=r.customer.firstName),f.lastName||(u.lastName=r.customer.lastName)),Object.keys(u).length===0?d:Es.cloneElement(d,u)})})}function Tp({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:s,buttonsStyles:d,cardButtonContent:f,cardBackButtonContent:u,cardTitleContent:w}){let[b,j]=Ht(!1),L=Qn(()=>Vc(i),[i]),I=Qn(()=>{let C=L?.buttonsLayout??vp(s);return d?{...C,...d,cardButton:{...C.cardButton,...d.cardButton},cardFormContainer:{...C.cardFormContainer,...d.cardFormContainer},backButton:{...C.backButton,...d.backButton},backButtonIcon:{...C.backButtonIcon,...d.backButtonIcon},submitButton:{...C.submitButton,...d.submitButton},title:{...C.title,...d.title}}:C},[L,s,d]),N=L?.buttonsLayout?.cardButton?.borderRadius??L?.appearance.variables?.borderRadius??8,U=C=>pe("div",{style:{height:C,borderRadius:N,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),h=f===void 0?{boxSizing:"border-box",height:zo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let C=I.cardInputBorder??"#e5e7eb",le=I.cardInputBackground??"white",D=Co(u),ve=Co(w);return an("div",{style:{backgroundColor:I.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...I.cardFormContainer},children:[an("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[an("button",{type:"button",onClick:()=>j(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:D?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...I.backButton},children:[pe("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...I.backButtonIcon},children:pe("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:pe("path",{d:"M15 18l-6-6 6-6"})})}),pe(wo,{content:u})]}),ve?pe("div",{style:{flex:1}}):pe("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...I.title},children:pe(la,{content:w})})]}),pe("div",{style:{backgroundColor:le,border:`1px solid ${C}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:pe("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),an("div",{style:{display:"flex"},children:[pe("div",{style:{flex:1,backgroundColor:le,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomLeftRadius:8,padding:12,height:45},children:pe("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),pe("div",{style:{flex:1,backgroundColor:le,borderTop:"none",borderRight:`1px solid ${C}`,borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomRightRadius:8,padding:12,height:45},children:pe("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),pe("div",{style:{backgroundColor:le,border:`1px solid ${C}`,borderRadius:8,marginTop:8,padding:12,height:45},children:pe("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),pe("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...I.submitButton,opacity:.5}}),pe("style",{children:`
|
|
12
|
+
`}),Ko&&Or&&Xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:u?-2:0},children:[Xe("button",{type:"button",onClick:K,style:{display:"inline-flex",alignItems:"center",gap:ki?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:S.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...S.backButton},"aria-label":"Back to payment methods",children:[p("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...S.backButtonIcon},children:p("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:p("path",{d:"M15 18l-6-6 6-6"})})}),p(vo,{content:Re})]}),Xs?p("div",{style:{flex:1}}):p("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:S.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...S.title},children:p(na,{content:He})})]}),!Ko&&!Xs&&p("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ii,order:u?-3:0,...S.title},children:p(na,{content:He})}),u&&ye&&p("div",{style:{order:-2,width:"100%"},children:ye}),u&&Lr&&Xe("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[p("div",{style:{backgroundColor:yo,border:`1px solid ${Vn(Ta)}`,borderRadius:Zt,padding:"10px"},children:p("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Qt,onChange:r=>{Mt("email"),on.current=r.target.value,Jn(r.target.value)},onPointerDown:()=>Mt("email"),onKeyDown:()=>Mt("email"),onBlur:()=>{Un("email")&&Wn(!0),ao||mi()},disabled:_e,required:!0,"aria-invalid":Ta||void 0,"aria-describedby":Ta?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ri}})}),Ta&&p("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Yo,children:di.empty?"Email address is required":"Enter a valid email address"})]}),ae&&p("div",{style:{order:u?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=qt,g=(D=!1)=>({backgroundColor:yo,border:`1px solid ${Vn(D)}`,borderRadius:Zt,marginTop:"0.5rem",padding:"10px"}),W=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ri}),fe=Tu(r);return Xe(Fo,{children:[Kt(ae.address_line_1,r)&&Xe(Fo,{children:[p("div",{style:g(Vt("line1")),children:p("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:Tt,onChange:D=>{Mt("line1"),Bt.current.addressLine1=!0,ln.current=D.target.value,Ve(D.target.value)},onPointerDown:()=>Mt("line1"),onKeyDown:()=>Mt("line1"),onBlur:()=>wn("line1"),disabled:_e,required:!0,"aria-invalid":Vt("line1")||void 0,"aria-describedby":Vt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:W()})}),Vt("line1")&&p("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Yo,children:"Street address is required"})]}),Kt(ae.address_line_2,r)&&p("div",{style:g(),children:p("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Le,onChange:D=>{Bt.current.addressLine2=!0,Ft.current=D.target.value,Rn(D.target.value)},disabled:_e,"data-testid":"flopay-address-line2",style:W()})}),(Kt(ae.city,r)||Kt(ae.state,r))&&Xe("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Kt(ae.city,r)&&p("div",{style:{flex:1,backgroundColor:yo,borderTop:`1px solid ${Vn(Vt("city"))}`,borderRight:`1px solid ${Vn(Vt("city"))}`,borderBottom:`1px solid ${Vn(Vt("city"))}`,borderLeft:`1px solid ${Vn(Vt("city"))}`,padding:"10px",borderTopLeftRadius:Zt,borderBottomLeftRadius:Zt,...Kt(ae.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Zt}},children:p("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:kt,onChange:D=>{Mt("city"),Bt.current.city=!0,fn.current=D.target.value,On(D.target.value)},onPointerDown:()=>Mt("city"),onKeyDown:()=>Mt("city"),onBlur:()=>wn("city"),disabled:_e,required:!0,"aria-invalid":Vt("city")||void 0,"aria-describedby":Vt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:W()})}),Kt(ae.state,r)&&p("div",{style:{flex:1,backgroundColor:yo,borderTop:`1px solid ${Vn(Vt("state"))}`,borderRight:`1px solid ${Vn(Vt("state"))}`,borderBottom:`1px solid ${Vn(Vt("state"))}`,borderLeft:`1px solid ${Vn(Vt("state"))}`,padding:"10px",borderTopRightRadius:Zt,borderBottomRightRadius:Zt,...Kt(ae.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Vn(Vt("state")||Vt("city"))}`}:{borderRadius:Zt}},children:fe?Xe("select",{id:"flopay-billing-state",name:"billing-state",value:mn,onChange:D=>{Mt("state"),Bt.current.state=!0,Dt.current=D.target.value,jt(D.target.value)},onPointerDown:()=>Mt("state"),onKeyDown:()=>Mt("state"),onBlur:()=>wn("state"),disabled:_e,autoComplete:"billing address-level1",required:!0,"aria-invalid":Vt("state")||void 0,"aria-describedby":Vt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...W(),cursor:"pointer"},children:[p("option",{value:"",children:Yi(r)}),fe.map(D=>p("option",{value:D.code,children:D.name},D.code))]}):p("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Yi(r),autoComplete:"billing address-level1",value:mn,onChange:D=>{Mt("state"),Bt.current.state=!0,Dt.current=D.target.value,jt(D.target.value)},onPointerDown:()=>Mt("state"),onKeyDown:()=>Mt("state"),onBlur:()=>wn("state"),disabled:_e,required:!0,"aria-invalid":Vt("state")||void 0,"aria-describedby":Vt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:W()})})]}),Vt("city")&&p("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Yo,children:"City is required"}),Vt("state")&&Xe("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Yo,children:[Yi(r)," is required"]}),(Kt(ae.country,r)||Kt(ae.postal_code,r))&&Xe("div",{style:{display:"flex",flexDirection:re==="column"?"column":"row",gap:re==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Kt(ae.country,r)&&p("div",{style:{flex:re==="row"?1:void 0,backgroundColor:yo,borderTop:`1px solid ${Go}`,borderRight:`1px solid ${Go}`,borderBottom:`1px solid ${Go}`,borderLeft:`1px solid ${Go}`,padding:"10px",...re==="row"&&Kt(ae.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:Zt,borderBottomLeftRadius:Zt,borderRight:"none"}:{borderRadius:Zt}},children:Xe("select",{id:"flopay-billing-country",name:"billing-country",value:qt,onChange:D=>{Bt.current.country=!0,Cn.current=D.target.value,Fn(D.target.value),qe?.(D.target.value),Dt.current="",jt("")},disabled:_e,autoComplete:"billing country","data-testid":"flopay-country",style:{...W(),cursor:"pointer"},children:[qt===""?p("option",{value:"",children:"Select country"}):null,wu.map(D=>Xe("option",{value:D.code,children:[D.flag," ",D.name]},D.code))]})}),Kt(ae.postal_code,r)&&p("div",{style:{flex:re==="row"?1:void 0,backgroundColor:yo,border:`1px solid ${Zc}`,padding:"10px",...re==="row"&&Kt(ae.country,r)?{borderRadius:"0",borderTopRightRadius:Zt,borderBottomRightRadius:Zt}:{borderRadius:Zt}},children:p("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:ns(qt),autoComplete:"billing postal-code",value:Dn,onChange:D=>{Mt("zip"),Bt.current.zip=!0,xt.current=D.target.value,hn(D.target.value),Ee?.(D.target.value)},onPointerDown:()=>Mt("zip"),onKeyDown:()=>Mt("zip"),onBlur:()=>{Un("zip")&&Tn(!0)},disabled:_e,required:Ln.required,"aria-invalid":Ma||void 0,"aria-describedby":Ma?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:W()})})]}),Ma&&p("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Yo,children:Ln.empty?`${ns(r)} is required`:yp(r)})]})})()}),u&&nd,rt&&p(Eo,{margin:"0.75rem 0",styleOverride:S.errorBanner,children:rt})]}),Aa={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"},rl=r=>F?!P||!br?p("pre",{"data-testid":r,style:Aa,children:"FloPay/DirectPayPal-debug - not enabled"}):p("pre",{"data-testid":r,style:Aa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${P}`,` directPaypalConfigured=${br}`,` inAppBrowserDetected=${String(Ra)}`,` shouldRenderDirectPayPal=${jo}`,` shouldRenderStripePayPal=${Wo}`,` hasPaypalStripeInstance=${!!ws}`].join(`
|
|
13
|
+
`)}):null,ol=r=>F?!he||!qn?p("pre",{"data-testid":r,style:Aa,children:"FloPay/Stripe-debug - not enabled"}):p("pre",{"data-testid":r,style:Aa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${he}`,` currency=${bt}`,` amountInCents=${Uo}`,` enabledPaymentMethods: ${JSON.stringify(Ie??[])}`,` enabledPaymentMethodsProvided=${qo}`,` hasEnabledMethods=${Sa}`,` expressMethods: ${JSON.stringify(ka)}`,` walletExpressMethods: ${JSON.stringify(uo)}`,` paymentElementMethods: ${JSON.stringify(gi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ia)}`,` hasStripeInstance=${!!qn}`,` shouldRenderWallets=${po}`,` shouldRenderPaymentElement=${Ho}`].join(`
|
|
14
|
+
`)}):null,al=tt==="apm-expanding"||tt==="apm-form"||tt==="apm-collapsing",fo;tt==="apm-expanding"?fo=pc:tt==="apm-collapsing"&&(fo=yc);let xa=cn?Ec(hi,cn,me):null;if(ze==="buttons"){let r=tt==="buttons"||tt==="expanding"||tt==="apm-expanding",g=tt==="expanding"||tt==="card"||tt==="collapsing",W=Pt===void 0?{boxSizing:"border-box",height:ta,padding:"0 1rem"}:{padding:"0.9rem 1rem"},fe;tt==="expanding"||tt==="apm-expanding"?fe=cp:(tt==="collapsing"||tt==="apm-collapsing")&&(fe=lp);let D;return tt==="expanding"?D=pc:tt==="collapsing"&&(D=yc),Xe("form",{onSubmit:Ci,className:ne,noValidate:!0,style:{position:"relative"},children:[p(Oa,{}),de&&p(Sr,{status:de,errorMessage:rt,authorized:Xn}),Xe("div",{style:{display:"grid"},children:[Xe("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!fe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!fe?up:{},...fe?{animation:fe,pointerEvents:"none"}:{}},children:[rl("flopay-direct-paypal-gate-debug"),ol("flopay-stripe-gate-debug"),jo&&yt&&Xe(Fo,{children:[le&&p("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."}),p(sa.Provider,{value:d,children:p(Wa,{sessionId:e,nonce:t,billingApiUrl:at,email:Ze.email,billingName:oo||void 0,onBuyerIdentityReady:Be,clientId:yt.clientId,environment:yt.environment,currency:bt.toUpperCase(),isSubscription:Et,providerObjectType:We,approvalPresentation:Ea==="popup"?void 0:Ea,onTokenizedBody:An,onComplete:s,onErrorChange:ue,onDecline:f,onTechnicalFailure:lo,onButtonClick:Q,runBeforeButtonClick:sr,isProcessing:_e,onLoadStateChange:Pi,onInitializationStateChange:vi,session:ft,existingOrderId:le?.orderId,debug:F},le?.orderId??"fresh")})]}),Wo&&p(no,{stripe:$o,options:Rs,children:p(fc,{sessionId:e,nonce:t,email:Ze.email,billingName:oo||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,onTokenizedBody:An,onErrorChange:ue,isProcessing:_e,onButtonClick:Q,onDecline:f,onTechnicalFailure:lo,runBeforeButtonClick:sr,onLoadStateChange:Ds,placeholderBorderRadius:Gr,popupCapabilityOwner:d,externalTelemetryContext:Ws,presentationMode:co})}),po?p(no,{stripe:qn,options:Is,children:p(hc,{sessionId:e,nonce:t,email:Ze.email,billingName:oo||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,intentKind:De>0?"payment":"setup",expressMethods:uo,onTokenizedBody:An,onErrorChange:ue,onButtonClick:Q,onDecline:f,onTechnicalFailure:lo,runBeforeButtonClick:sr,onLoadStateChange:Ns,placeholderBorderRadius:Gr,popupCapabilityOwner:d,externalTelemetryContext:J})}):null,!po&&js?p("div",{style:{height:ta,borderRadius:Gr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Ho&&p(Pc,{sessionId:e,nonce:t,email:Ze.email,billingName:[Ze.firstName,Ze.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,paymentElementMethods:Ia,stripeInstance:qn,paymentElementBaseOptions:hi,futureUseSession:me,onTokenizedBody:An,onErrorChange:ue,onButtonClick:Q,onDecline:f,runBeforeButtonClick:sr,onLoadStateChange:zs,isProcessing:_e,submitButtonColor:Yr,submitButtonBorderRadius:Zt,submitButtonStyle:S.submitButton,onExpandApm:it,expandedApmMethod:cn,themeId:ct,buttonAppearance:{backgroundColor:S.cardButton?.backgroundColor,borderColor:S.cardInputBorder,textColor:S.cardButton?.color,borderRadius:Gr}}),u&&p("button",{type:"button",onClick:async()=>{_e||!(await sr("card")).proceed||(Q?.("card"),j())},disabled:_e,style:{width:"100%",...W,...S.cardButton,...ds({themeBundle:Z,resolvedPrimaryColor:Yr,resolvedBorderRadius:Zt,submitButtonStyle:S.submitButton,explicitPrimaryColor:xn?.colorPrimary}),fontSize:S.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:_e?"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:_e?.6:1},onMouseEnter:X=>{!_e&&(Z||xn?.colorPrimary)&&(X.currentTarget.style.backgroundColor=ed)},onMouseLeave:X=>{(Z||xn?.colorPrimary)&&(X.currentTarget.style.backgroundColor=Yr)},onMouseDown:X=>{X.currentTarget.style.transform="scale(0.985)"},onMouseUp:X=>{X.currentTarget.style.transform="scale(1)"},children:p(Po,{content:Pt})}),rt&&tt==="buttons"&&p(Eo,{margin:"0.25rem 0",styleOverride:S.errorBanner,children:rt})]}),u&&g&&p("div",{style:{gridArea:"1 / 1",...D?{animation:D}:{},...tt==="collapsing"?{pointerEvents:"none"}:{}},children:nl}),he&&al&&cn&&xa&&qn&&p("div",{style:{gridArea:"1 / 1",...fo?{animation:fo}:{},...tt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Xe("div",{style:{backgroundColor:wi,borderRadius:_i,...Jo,padding:Ei},children:[Xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Xe("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:ki?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:S.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...S.backButton},"aria-label":"Back to payment methods",children:[p("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...S.backButtonIcon},children:p("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:p("path",{d:"M15 18l-6-6 6-6"})})}),p(vo,{content:Re})]}),p("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:S.titleFontSize??"1.05rem",color:Ii,paddingRight:80,...S.title},children:`Pay with ${ga(cn)}`})]}),p(no,{stripe:qn,options:xa,children:p(as,{method:cn,sessionId:e,nonce:t,email:Ze.email,billingName:[Ze.firstName,Ze.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,onTokenizedBody:An,onErrorChange:ue,onDecline:f,onCancel:Wt,runBeforeButtonClick:sr,onButtonClick:Q,isProcessing:_e,submitButtonColor:Yr,submitButtonBorderRadius:Zt,submitButtonStyle:S.submitButton,errorText:rt})},cn)]})})]})]})}return al&&cn&&xa&&qn&&he?Xe("form",{onSubmit:Ci,className:ne,noValidate:!0,style:{position:"relative"},children:[p(Oa,{}),de&&p(Sr,{status:de,errorMessage:rt,authorized:Xn}),p("div",{style:{...fo?{animation:fo}:{},...tt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Xe("div",{style:{backgroundColor:wi,borderRadius:_i,...Jo,padding:Ei},children:[Xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Xe("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:ki?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:S.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...S.backButton},"aria-label":"Back to payment methods",children:[p("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...S.backButtonIcon},children:p("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:p("path",{d:"M15 18l-6-6 6-6"})})}),p(vo,{content:Re})]}),p("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:S.titleFontSize??"1.05rem",color:Ii,paddingRight:80,...S.title},children:`Pay with ${ga(cn)}`})]}),p(no,{stripe:qn,options:xa,children:p(as,{method:cn,sessionId:e,nonce:t,email:Ze.email,billingName:[Ze.firstName,Ze.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,onTokenizedBody:An,onErrorChange:ue,onDecline:f,onCancel:Wt,runBeforeButtonClick:sr,onButtonClick:Q,isProcessing:_e,submitButtonColor:Yr,submitButtonBorderRadius:Zt,submitButtonStyle:S.submitButton,errorText:rt})},cn)]})})]}):Xe("form",{onSubmit:Ci,className:ne,noValidate:!0,style:{position:"relative"},children:[p(Oa,{}),de&&p(Sr,{status:de,errorMessage:rt,authorized:Xn}),Xe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[rl("flopay-direct-paypal-gate-debug-default"),ol("flopay-stripe-gate-debug-default"),jo&&yt&&Xe(Fo,{children:[le&&p("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."}),p(sa.Provider,{value:d,children:p(Wa,{sessionId:e,nonce:t,billingApiUrl:at,email:Ze.email,billingName:oo||void 0,onBuyerIdentityReady:Be,clientId:yt.clientId,environment:yt.environment,currency:bt.toUpperCase(),isSubscription:Et,providerObjectType:We,approvalPresentation:Ea==="popup"?void 0:Ea,onTokenizedBody:An,onComplete:s,onErrorChange:ue,onDecline:f,onTechnicalFailure:lo,onButtonClick:Q,runBeforeButtonClick:sr,isProcessing:_e,onLoadStateChange:Pi,onInitializationStateChange:vi,session:ft,existingOrderId:le?.orderId,debug:F},le?.orderId??"fresh")})]}),Wo&&p(no,{stripe:$o,options:Rs,children:p(fc,{sessionId:e,nonce:t,email:Ze.email,billingName:oo||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,onTokenizedBody:An,onErrorChange:ue,isProcessing:_e,onButtonClick:Q,onDecline:f,onTechnicalFailure:lo,runBeforeButtonClick:sr,onLoadStateChange:Ds,placeholderBorderRadius:Gr,popupCapabilityOwner:d,externalTelemetryContext:Ws,presentationMode:co})}),po&&p(no,{stripe:qn,options:Is,children:p(hc,{sessionId:e,nonce:t,email:Ze.email,billingName:oo||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,intentKind:De>0?"payment":"setup",expressMethods:uo,onTokenizedBody:An,onErrorChange:ue,onButtonClick:Q,onDecline:f,onTechnicalFailure:lo,runBeforeButtonClick:sr,onLoadStateChange:Ns,placeholderBorderRadius:Gr,popupCapabilityOwner:d,externalTelemetryContext:J})}),Ho&&p(Pc,{sessionId:e,nonce:t,email:Ze.email,billingName:[Ze.firstName,Ze.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:at,paymentElementMethods:Ia,stripeInstance:qn,paymentElementBaseOptions:hi,futureUseSession:me,onTokenizedBody:An,onErrorChange:ue,onButtonClick:Q,onDecline:f,runBeforeButtonClick:sr,onLoadStateChange:zs,isProcessing:_e,submitButtonColor:Yr,submitButtonBorderRadius:Zt,submitButtonStyle:S.submitButton,themeId:ct,onExpandApm:it,expandedApmMethod:cn,buttonAppearance:{backgroundColor:S.cardButton?.backgroundColor,borderColor:S.cardInputBorder,textColor:S.cardButton?.color,borderRadius:Gr}})]}),u&&(Kc||Vc||Gc)&&p(ll,{label:"or pay with card"}),u&&nl]})}import{Fragment as Rr,jsx as se,jsxs as sn}from"react/jsx-runtime";var Oo=44,Ps="flopay_checkout_saved_payment_resume",li=new Map,ii=new Map;function Tc(e,t){t.settled&&t.consumers===0&&li.get(e)===t&&li.delete(e)}function Ep(e,t,n){let o=ii.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};ii.set(e,i);let s=()=>{ii.get(e)===i&&ii.delete(e)};return a.then(s,s),a}function Pa(e){return new Promise(t=>setTimeout(t,e))}function si(e,t,n){let o=ja({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Lc,enabled:t!==!1});return o.beginCheckout(n),o}function va(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ys(e,t,n,o,a,i){let s=si(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),va(s)}function Mc(e,t,n,o){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()-n),durationMode:"machine",requestCategory:t,...o===void 0?{}:{attempt:o},statusClass:"2xx"})}function Ac(e,t,n,o,a){let i=Dc(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-o),durationMode:"machine",requestCategory:n,attempt:a,statusClass:i.statusClass}),t instanceof bn&&t.code==="session_auto_completed"?!1:t instanceof bn&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...i,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function ms(e){return!e||e.data.stripe?.publishableKey?!1:!!Oc(e.data.paypal)?.clientId}var _p={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Tp(e){return new Pp(_p,{publishableKey:"provider_unavailable",...e})}async function fs(e,t){let{publishableKey:n,paypalPublishableKey:o}=Ki(e);return{...await Gi({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function vs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Mp(){if(!vs())return null;try{let e=window.sessionStorage.getItem(Ps);return e?JSON.parse(e):null}catch{return null}}function xc(e){if(vs())try{window.sessionStorage.setItem(Ps,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function gs(){if(vs())try{window.sessionStorage.removeItem(Ps)}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"],n=!1;for(let o of t)e.searchParams.has(o)&&(e.searchParams.delete(o),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Bc(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 hs(e,t){return Ip(!!e,t)}function xp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Fc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Bp(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 bs({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:s,loading:c,error:f,onComplete:C,onError:E,onInstrument:k,onDecline:z,onCountryChange:ne,onZipChange:O,showPayPal:ve=!0,showStripe:V=!0,walletPresentation:v="auto",enabledPaymentMethods:P,showApplePay:he=!0,showGooglePay:N=!0,debug:Ie=!1,layout:Y,theme:Fe,buttonsTheme:lt,buttonsStyles:ze,cardButtonContent:ct,cardBackButtonContent:zt,cardTitleContent:pe,showSecurityFooter:Te,onButtonClick:Pt,onBeforeButtonClick:Re,enableAVS:He,cardFieldOrder:ke,cardPreFormSlot:Q,avsLayout:je,submitLabel:$e,className:pt,initialErrorMessage:be=null,initialPayPalOrderId:ye,children:re,checkoutMode:M,confirmLabel:Ce,renderConfirmButton:Ue,onSessionCompleted:Me}){let U=wp(o),vt=Yn(()=>Nc(Fe),[Fe]),qe=i??vt?.appearance,Ee=n?"embedded_checkout":"standard_checkout",Je=hs(re,Y),[Ae,Qe]=Gt(null),[De,bt]=Gt(null),Yt=At(null),yt=At(null),Et=At(0),[I,ee]=Gt(null),Oe=At(null),[F,Se]=Gt(null),mt=Yn(()=>n?da(n):"",[n]),Ne=n?`create:${mt}`:`session:${e??""}`,wt=Fc(F),_=At(new Set),d=At(Ne),m=At(Ne);Xo(()=>{m.current=Ne,d.current!==Ne&&(d.current=Ne,_.current.clear())},[Ne]);let A=vn(w=>{if(m.current===Ne){if(Ul.has(w.name)){if(_.current.has(w.name))return;_.current.add(w.name)}Nt(()=>k?.(w))}},[Ne,k]),T=Ro(A,Ne),J=At(!1),ft=vn(w=>{if(J.current)return;let b=w.gateway||!wt?w:{...w,gateway:wt};A(b)},[A,wt]);pr(()=>{T({class:"lifecycle",name:"checkout.mount"})},[T]);let[me,We]=Gt(e??""),H=e??me,Ut=n?"":H,[Ct,_t]=Gt(!0),[at,oe]=Gt(null),[In,Bn]=Gt(0),[yn,qt]=Gt("full"),[Fn,Dn]=Gt(!1),[hn,Tt]=Gt(be),[Ve,Le]=Gt(null),[Rn,kt]=Gt(null),[On,mn]=Gt(!1),[jt,Qt]=Gt(void 0),[Jn,$n]=Gt(""),[en,xt]=Gt(!1),[Cn,ln]=Gt(!1),[Ft,fn]=Gt(!1),Dt=At(null),on=At(0),Bt=At(void 0),[ae,Zn]=Gt("loading"),[Xn,Qn]=Gt(0),tn=At(!1),En=At(!1),Sn=At(!1),ce=At(null),et=At(null),u=Yn(()=>({checkoutMode:M??yn,layout:xp(re,Y)}),[M,re,yn,Y]),xe=At(C);xe.current=C;let L=At(E);L.current=E;let Pn=At(z);Pn.current=z;let Nn=vn(w=>Ya(ce,async b=>{try{return await w(b)}catch(j){throw b.aborted?To(j):j}}),[]);pr(()=>()=>{ce.current?.abort(),ce.current=null},[]);let Jt=vn((w,b)=>{Yt.current=w,bt(w),Oe.current=b,ee(b)},[]),_n=vn(()=>{let w=yt.current;w&&(yt.current=null,w.destroy())},[]);pr(()=>{pn(De)?.setCheckoutContext(u),I&&I!==De&&pn(I)?.setCheckoutContext(u)},[De,I,u]);let nt=At(Me);nt.current=Me;let yr=vn(w=>{Zn(w),!(w!=="exhausted"||Sn.current)&&(Sn.current=!0,L.current?.(new bn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Dr=vn(()=>{Zn("retrying"),Qn(w=>w+1)},[]);pr(()=>{Zn("loading"),Qn(0),Sn.current=!1},[H]),pr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Lc,checkout_type:Ee,checkout_layout:Je,billing_api_url:U})},[Je,Ee,U]);let It=Yn(()=>n?da(n,!0):"",[n]),Ln=Yn(()=>Jn===It?jt:void 0,[jt,Jn,It]),er=Yn(()=>n?Oi(n,Ln):void 0,[n,Ln]),tr=M??er?.checkoutMode??"full",$t=Yn(()=>er?{...er,checkoutMode:tr}:void 0,[er,tr]);pr(()=>{Qt(void 0),$n(It),Bt.current=void 0,Dt.current=null,fn(!1)},[It]),pr(()=>{Tt(be)},[be]);let mr=vn((w,b,j)=>{Nt(()=>{Pn.current?.(un(w,b,j))})},[]),fr=vn(async(w,b)=>{Tt(null),kt(null),mn(!1),Le("processing");let j=b?.sessionId??w.id,K=w.clientSecret||t,it=Fc(w),Wt=Yt.current??Oe.current,de=pn(Wt),x=Wt?null:si(U,a,u),B={log:te=>{de?de.log(te):x?.log(te)},error:te=>{de?de.error(te):x?.error(te)},terminal:te=>{de?de.terminal(te):x?.terminal(te)},performance:te=>{de?de.performance(te):x?.performance(te)},now:()=>de?.now()??x?.now()??0,elapsed:te=>de?.elapsed(te)??Math.max(0,(x?.now()??te)-te)},R=B.now(),l=!!(b?.initialAutoProcessingError||b?.initialAutoProcessingPending),y=!1,h,$=()=>{y||(y=!0,l=!0,h=B.now(),B.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},le=!1,Pe=()=>{le||(le=!0,B.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),B.performance({stage:"processing",durationMs:B.elapsed(R),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),h!==void 0&&B.performance({stage:"recovery",durationMs:B.elapsed(h),durationMode:"machine",paymentMethodCategory:"saved"}))};B.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),J.current=!0;try{B.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{J.current=!1}T({class:"lifecycle",name:"payment.processing.started",provider:it}),l&&$();let Ht;try{let te=rc(b?.initialAutoProcessingError),we=b?.initialAutoProcessingError?.type==="3ds_required"&&!b.initialAutoProcessingError.threeDSecureToken&&b.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:b.initialAutoProcessingError.nextActionRedirectUrl}:null,Be,rt=Z=>($(),Nn(S=>Mo(Z,{billingApiUrl:U,sessionId:j,nonce:K,session:w,signal:S})));if(we)Be=await rt(we);else if(te)$(),te.type==="paypal_redirect_required"&&et.current?.publishableKey&&xc({sessionId:j,publishableKey:et.current.publishableKey,paypalPublishableKey:et.current.paypalPublishableKey}),Be=await Nn(Z=>Xa(te,{flopay:Yt.current,paypalFlopay:Oe.current,attempt3DS:b?.attempt3DS,billingApiUrl:U,sessionId:j,session:w,telemetry:!1,signal:Z})),te.type==="paypal_redirect_required"&&gs();else if(b?.initialAutoProcessingPending){let Z=b.initialAutoProcessingPending,S=new ai(U,{telemetry:!1}),q=await Nn(_e=>S.waitForCheckoutSessionCompletion(Z.sessionId,{initialDelayMs:Z.retryAfterMs,nonce:K,statusUrl:Z.statusUrl,signal:_e})),Ke=qr(q,w),ge=q.autoProcessingError?.type==="3ds_required"&&q.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:q.autoProcessingError.nextActionRedirectUrl}:null;if(ge)Be=await rt(ge);else{if(!Ar(Ke))throw So(Ke);Be=Mr(Ke,j)}}else{if(b?.initialAutoProcessingError)throw kr(b.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.initialAutoProcessingError.checkoutMethod});if(b?.fromCreateSession)return b?.fallbackToFull&&(qt("full"),Bc("full")),!1;{let Z=await Ao({billingApiUrl:U,sessionId:j,session:w,nonce:K,telemetry:!1});Z.type==="success"?Be=Z.result:Z.type==="next_action_required"?Be=await rt(Z):($(),Z.type==="paypal_redirect_required"&&et.current?.publishableKey&&xc({sessionId:j,publishableKey:et.current.publishableKey,paypalPublishableKey:et.current.paypalPublishableKey}),Be=await Nn(S=>Xa(Z,{flopay:Yt.current,paypalFlopay:Oe.current,attempt3DS:b?.attempt3DS,billingApiUrl:U,sessionId:j,session:w,telemetry:!1,signal:S})),Z.type==="paypal_redirect_required"&&gs())}}j&&_o(j),Pe(),l&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),B.terminal({outcome:Be.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),mn(Be.status==="authorized"),Le("success"),await Pa(600),Ht=()=>xe.current?.(Be)}catch(te){let we=Ur(ya(te),j);if(we.code==="three_ds_aborted")return!1;let Be=we.checkoutMethod??pa;Tt(we.message),kt(we.message),mn(!1),b?.fallbackToFull&&(B.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),qt("full"),Bc("full")),Pe();let rt=we.statusCode===void 0?void 0:Rp(we.statusCode,"unknown"),Z=rt==="4xx"?{requestCategory:"process_payment",statusClass:rt}:{},S=rt===void 0||rt==="4xx";if(S&&(we.telemetryOutcome==="payment_declined"||!!(we.declineCode||we.code?.toLowerCase().includes("declin"))))B.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Z});else if(S&&(we.telemetryOutcome==="validation_rejected"||we.type==="validation_error"))B.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Z});else{let ge=Dc(te,l?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),_e=we.telemetryRequestCategory??"process_payment";J.current=!0;try{B.error({...ge,...we.telemetryFailureCategory?{failureCategory:we.telemetryFailureCategory}:{},stage:l?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:_e})}finally{J.current=!1}T({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:_e,provider:it})}return Nt(()=>L.current?.(we)),mr(Be,we,{code:we.code,declineCode:we.declineCode}),Le("error"),await Promise.allSettled([Pa(400),b?.ensureProvidersReady?b.ensureProvidersReady():Promise.resolve()]),l&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Pe(),x&&va(x),Le(null),kt(null)}return Nt(Ht),!0},[mr,T,t,U,Nn,a,u]);pr(()=>{if(typeof window>"u"||En.current)return;let w=new URLSearchParams(window.location.search),b=w.get("payment_intent_client_secret");if(!b)return;let j=Mp();j&&(En.current=!0,(async()=>{let K,it=0;Tt(null),kt(null),Le("processing"),Dn(!0);try{if(w.get("redirect_status")==="failed")throw Object.assign(new bn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Wt,paypalFlopay:de}=await Gi({publishableKey:j.publishableKey,paypalPublishableKey:j.paypalPublishableKey,billingApiUrl:U,locale:s,telemetry:a});K=pn(de??Wt),K?.setCheckoutContext(u),it=K?.now()??0,K?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),K?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let x=(de??Wt)?.getRawProvider();if(!x)throw Object.assign(new bn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:R}=await x.retrievePaymentIntent(b);if(R)throw Object.assign(new bn(R.message??"Failed to retrieve PayPal payment status.","api_error",{code:R.code}),{checkoutMethod:"paypal"});let l=Ml(B?.status);if(!B||l==="failed")throw Object.assign(new bn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let y=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,h=l;if(j.sessionId){let Pe=(await new ai(U,{telemetry:!1}).getUnifiedCheckoutSession(j.sessionId)).data.session;if(Pe&&Pe.status!=="complete"){let Ht=await Ao({billingApiUrl:U,sessionId:j.sessionId,session:Pe,telemetry:!1,tokenizedData:{id:y??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(Ht.type!=="success")throw Object.assign(new bn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});h=Ht.result.status}}j.sessionId&&_o(j.sessionId),K?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),K?.performance({stage:"redirect_resume",durationMs:K.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),K?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Le("success"),await Pa(600),Nt(()=>xe.current?.({status:h,paymentIntentId:B.id,paymentMethodId:y,checkoutMethod:"paypal"}))}catch(Wt){let de=Ur(ya(Wt),j.sessionId),x=de.checkoutMethod??"paypal",B=!!(de.declineCode||de.code?.toLowerCase().includes("declin"));if(K)K.performance({stage:"redirect_resume",durationMs:K.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?K.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):K.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let R=si(U,a,u);R.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),va(R)}else ys(U,a,u,"REDIRECT_RESUME_FAILED","redirect_resume");Tt(de.message),kt(de.message),Nt(()=>L.current?.(de)),mr(x,de,{code:de.code,declineCode:de.declineCode}),Le("error"),await Pa(400)}finally{gs(),Ap(),Le(null),kt(null),Dn(!1)}})())},[mr,s,U,a,u]);let Tn=At(null),gr=Yn(()=>$t?da($t):"",[$t]),Wn=At($t);Wn.current=$t,pr(()=>{We(e??"")},[e]),pr(()=>{tn.current=!1,Tt(be),kt(null),mn(!1),Le(null)},[gr,be,e]);async function hr(w,b,j){let K=si(U,a,u),it=new ai(U,{telemetry:!1}),Wt=!1;try{let de=w.idempotencyKey===void 0?void 0:_c(w.idempotencyKey),x=Zl(b,j),B=Jl(b,j);x?.canonicalIdentity===j&&B&&B.canonicalIdentity===void 0&&(Va(b,j,B.idempotencyKey),B={...B,canonicalIdentity:j});let R=de??(B?.canonicalIdentity===j?B.idempotencyKey:void 0),l,y=!1;K.log({name:x?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let h=x?.sid??null,$=null,le,Pe,Ht=!1;if(h)try{$=await it.getUnifiedCheckoutSession(h,x?.nonce),x&&x.canonicalIdentity===void 0&&(Yl($.data.session,w)?(Ka(b,j,h,x.nonce??$.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(Va(b,j,B.idempotencyKey),R??(R=B.idempotencyKey))):(Ha(b,j),B=null,R=de,h=null,$=null));let we=$?.data.session?.status,Be=$?.data.session,rt=Be?.clientSecret||x?.nonce;if(h&&Be?.buyerIdentified===!1&&rt&&(Pe=Co(it,h,rt,w.account)),h&&$&&we==="complete"){if(Wi(h))return{sid:h,result:$};Ha(b,j),h=null,$=null,y=!0}}catch{K.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),x?.canonicalIdentity===void 0?(Ha(b,j),R=de):$i(b,j),h=null}if(!h){!de&&(y||!R)&&(R=_c(),l=R),R&&Va(b,j,R);let we=K.now(),Be=0;K.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let rt={...w,idempotencyKey:R,avsCheck:!!He,avsConfig:typeof He=="object"?He:void 0,checkoutType:"embedded_checkout",checkoutLayout:hs(re,Y)};Object.defineProperty(rt,vp,{configurable:!1,enumerable:!1,value:{onAttempt:q=>{Be=Math.max(Be,q)}}});let Z=()=>{Mc(K,"session_create",we,Be)},S=q=>{Ac(K,q,"session_create",we,Be)&&T({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(Cp(rt)){let q=await it.createDetachedSession(rt);q.claimed.catch(()=>{}),$=q.shell,h=q.sessionId,Pe=q.claim;let Ke=K.now();K.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),le=q.claimed.then(ge=>{let _e=ge.data.session?.id??q.sessionId;return _e&&Ka(b,j,_e,ge.data.session?.clientSecret??q.nonce),Mc(K,"session_claim",Ke),Z(),ge},ge=>{throw $i(b,j),Ac(K,ge,"session_claim",Ke,0)&&T({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),ge}).finally(()=>va(K)),le.catch(()=>{}),Wt=!0,K.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),K.performance({stage:"session_shell",durationMs:K.now()-we,durationMode:"machine",requestCategory:"session_create",attempt:Be,statusClass:"2xx",paymentMethodCategory:"card"})}else $=await it.createAndFetchSession(rt),Z()}catch(q){throw S(q),q}h=$.data.session?.id??h??"",h&&!le&&Ka(b,j,h,$.data.session?.clientSecret)}let te=$?.data.session;return!Pe&&h&&te?.buyerIdentified===!1&&te.clientSecret&&(Pe=Co(it,h,te.clientSecret,w.account)),{sid:h??"",result:$,sdkGeneratedIdempotencyKey:l,...le?{claimed:le}:{},...Pe?{claim:Pe}:{},...Ht?{claimRequiresIdentity:!0}:{}}}finally{Wt||va(K)}}let Er=At(hr);Xo(()=>{Er.current=hr},[hr]);let zn=vn(async(w,b)=>{let j=Wn.current;if(!j)throw new bn("createSession is required to bootstrap checkout.","validation_error");let K=Oi(j,w),it=da(K),Wt=Gl(K),de=li.get(it);if(!de){let R={canonicalIdentity:it,promise:Er.current(K,Wt,it),consumers:0,settled:!1};de=R,li.set(it,R);let l=()=>{R.settled=!0,Tc(it,R)};R.promise.then(l,l)}de.consumers+=1;let x=!1,B=()=>{x||(x=!0,de.consumers-=1,Tc(it,de))};b?.(B);try{let R=await de.promise;Tn.current=it,w&&($n(It),Qt(te=>El(te,w)));let{sid:l,result:y,claimed:h,claim:$,claimRequiresIdentity:le}=R;if(Bt.current=$,fn(le===!0),Qe(y),y.data.session&&Se(y.data.session),l&&We(l),h){on.current+=1;let te=on.current;Dt.current=h,ln(!0),h.then(we=>{on.current===te&&(Dt.current===h&&(Dt.current=null),Qe(we),we.data.session&&Se(we.data.session),ln(!1),fn(!1))},we=>{on.current===te&&(Dt.current===h&&(Dt.current=null),ln(!1),fn(!1),oe(we instanceof bn?we:new bn(we instanceof Error?we.message:"Failed to create session","api_error")))})}else on.current+=1,Dt.current=null,ln(!1),fn(!1);let{flopay:Pe,paypalFlopay:Ht}=await fs(y,{billingApiUrl:U,locale:s,telemetry:a});return Jt(Pe,Ht),_t(!1),R}catch(R){throw Tn.current===it&&(Tn.current=null),R}finally{b||B()}},[It,Jt,s,U,a]),nr=At(fr);nr.current=fr;let rr=At(zn);rr.current=zn;let Mt=vn(async w=>{if(!Bp(w)||en)return{sessionId:me,session:F};xt(!0);try{let b=await zn(w);return{sessionId:b.sid,session:b.result.data.session??null}}finally{xt(!1)}},[zn,en,me,F]),Un=vn(async w=>{let b=Bt.current;if(!b)return;let j=on.current,K=await b(w);on.current===j&&(Qe(K),K.data.session&&Se(K.data.session))},[]),wn=vn(async()=>{await Dt.current},[]),or=vn(async()=>(await wn(),{proceed:!0}),[wn]);pr(()=>{let w=!1,b,j=++Et.current;_n(),oe(null),Bn(0);let K=()=>{w=!0,Et.current===j&&(Et.current+=1,_n())},it=Wn.current;if(gr&&it)return qt(tr),_t(!1),Tn.current===gr?K:(Se(_l(it,M)),(async()=>{let x=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),B=tr==="auto"&&!tn.current&&!x;B&&(Tt(null),kt(null),Le("processing"));try{let R=await rr.current(void 0,$=>{b=$}),l=R.result.data.session??null;et.current=Ki(R.result);let y=ms(R.result),h=Wi(R.sid||l?.id);if(!w&&B&&l&&!y&&!h){tn.current=!0,await Ep(gr,R.sdkGeneratedIdempotencyKey,()=>nr.current(l,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:R.result.autoProcessingError,initialAutoProcessingPending:R.result.autoProcessingPending,autoProcessingAttempted:R.result.autoProcessingAttempted,sessionId:R.sid||l.id}));return}!w&&B&&((y||h)&&(tn.current=!0),Le(null),kt(null))}catch(R){if(w)return;let l=La(R);if(B&&l==="session_auto_completed"){tn.current=!0,Le("success"),await Pa(600),w||(Nt(()=>{xe.current?.({status:"succeeded"})}),Le(null),kt(null));return}B&&(Le(null),kt(null));let y=R instanceof bn?R:new bn(R instanceof Error?R.message:"Failed to create session","api_error");oe(y)}finally{b?.(),b=void 0}})(),()=>{K(),b?.()});_t(!0);async function Wt(){let x=!1,B=null;try{let R=new ai(U,{telemetry:!1}),l=await R.getUnifiedCheckoutSession(H,t);if(B=l,w)return;Qe(l);let y=l.data.session??null;if(Se(y),!y)throw new bn("No session data returned","api_error");let h=y.checkoutMode;if(h==="setup")throw new bn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(y.status==="authorized"){_t(!1),Nt(()=>{xe.current?.(Mr(y,H)),nt.current?.(y.successUrl??"")});return}if(y.status==="complete"){_t(!1),Nt(()=>{nt.current?.(y.successUrl??"")});return}if(y.status==="expired")throw Na(y);x=!0;let $=M??h??"full";qt($),on.current+=1;let le=y.clientSecret||t;Bt.current=y.buyerIdentified===!1&&le?Co(R,H,le,{...y.customer?.id?{userId:y.customer.id}:{}}):void 0,ln(!1),fn(!1);let Pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ht=ms(l);if($==="auto"&&!tn.current&&!Pe&&!Ht){tn.current=!0;let te=de(l);try{if(await nr.current(y,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>te,sessionId:H||y.id}),w)return;await te,w||_t(!1);return}catch{if(w)return;await te,w||_t(!1);return}}await de(l),w||_t(!1)}catch(R){if(w)return;let l=Rl(R,x);if(x&&T({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),l){let{errorCode:h,stage:$,...le}=l;ys(U,a,u,h,$,le)}if(l?.stage==="provider_load"&&(M??B?.data.session?.checkoutMode??"full")==="full"&&Il(B,ve,V)){let h=Tp({billingApiUrl:U,locale:s,telemetry:a});yt.current=h,Jt(h,null),Bn(1),_t(!1);return}let y=R instanceof bn&&l?.stage!=="provider_load"?R:kl();y!==R&&Nt(()=>L.current?.(y)),oe(y),_t(!1)}}async function de(x){let{flopay:B,paypalFlopay:R,...l}=await fs(x,{billingApiUrl:U,locale:s,telemetry:a});et.current={publishableKey:l.publishableKey,paypalPublishableKey:l.paypalPublishableKey},Jt(B,R),Bn(0)}return Wt(),K},[M,gr,tr,Ut,t,ve,V]);let ar=vn(async()=>{if(!Ae||In!==1)return;let w=Et.current;Bn(2);try{let{flopay:b,paypalFlopay:j}=await fs(Ae,{billingApiUrl:U,locale:s,telemetry:a});if(Et.current!==w)return;_n(),Jt(b,j),Bn(0)}catch(b){if(Et.current!==w)return;let{errorCode:j,stage:K,...it}=Di(b);ys(U,a,u,j,K,it)}},[_n,Jt,s,In,U,a,u,Ae]),tt=!!(H&&(F?.clientSecret||t)),nn=Fn||!tt,cn=vn(async()=>{if(!(Fn||!tt||!F)){Dn(!0),Tt(null);try{await fr(F,{attempt3DS:!0,fallbackToFull:!0,sessionId:H||F.id})}finally{Dn(!1)}}},[H,Fn,tt,fr,F]),Mn=Oc(Ae?.data.paypal,ye),Or=ms(Ae),Pr=Yn(()=>{if(!(!Ae||!F||!Ae.data.stripe?.publishableKey))return{billingApiUrl:U}},[Ae,F,U]),_r=!!(n&&!re&&Y==="buttons"&&Re&&tr==="full"),Hn=!!(H&&(Sp(F?.vault)||Qr(F))),rn=Yn(()=>({session:F,loading:Ct,error:at,checkoutMode:yn,inlineSessionDraft:$t,applyInlineSessionPatch:_r?Mt:void 0,inlineSessionPatchProcessing:en,claimPending:Cn,claimRequiresIdentity:Ft,claimBuyerIdentity:Un,waitForDataAttachment:wn}),[F,Ct,at,yn,$t,_r,Mt,en,Cn,Ft,Un,wn]),Nr=!!n&&Y==="buttons"&&!Or&&!Hn&&(!De||!Pr),an=Ve?se(Sr,{status:Ve,errorMessage:Rn,authorized:On}):null;if(Ct&&!Hn){if(c)return sn(Rr,{children:[c,an]});if(Y==="buttons"){let w=vt?.buttonsLayout?.cardButton?.borderRadius??vt?.appearance.variables?.borderRadius??8,b=j=>se("div",{style:{height:j,borderRadius:w,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return sn(Rr,{children:[sn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ve&&b(Oo),V&&(he||N)&&b(Oo),V&&b(Oo),se("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),an]})}return sn(Rr,{children:[sn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[se("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),se("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),an]})}return at?f?se(cr.Provider,{value:rn,children:f(at)}):se(cr.Provider,{value:rn,children:se("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:at.message})}):Nr?sn(Rr,{children:[se(cr.Provider,{value:rn,children:se(Dp,{onButtonClick:Pt,showPayPal:ve,showStripe:V,showApplePay:he,showGooglePay:N,theme:Fe,buttonsTheme:lt,buttonsStyles:ze,cardButtonContent:ct,cardBackButtonContent:zt,cardTitleContent:pe})}),an]}):Or&&F&&Mn?sn(Rr,{children:[se(cr.Provider,{value:rn,children:sn("div",{className:pt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[hn&&se(Eo,{icon:!1,children:hn}),ae==="retrying"&&se("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),ae==="exhausted"&&sn("div",{role:"alert",children:[se("div",{children:"PayPal is temporarily unavailable. Please try again."}),se("button",{type:"button",onClick:Dr,children:"Retry PayPal"})]}),ae!=="exhausted"&&se("div",{"aria-hidden":ae==="retrying"?!0:void 0,style:ae==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:se(Vl,{sessionId:H,nonce:F.clientSecret||void 0,billingApiUrl:U,email:F.customer?.email||$t?.account?.email,billingName:[F.customer?.firstName,F.customer?.lastName].filter(Boolean).join(" ")||[$t?.account?.firstName,$t?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Un,clientId:Mn.clientId,environment:Mn.environment,currency:(F.currency??"usd").toUpperCase(),isSubscription:F.mode==="subscription",providerObjectType:Mn.providerObjectType,approvalPresentation:Mn.approvalPresentation,existingOrderId:Mn.existingOrderId,onComplete:C,onErrorChange:Tt,onDecline:z,onButtonClick:Pt,runBeforeButtonClick:or,onInitializationStateChange:yr,allowAutomaticRetry:Xn===0,session:F,telemetry:a,telemetryContext:u,onInstrument:ft,debug:Ie},`${Ne}:paypal-init-${Xn}`)})]})}),an]}):yn==="confirm"?sn(Rr,{children:[se(cr.Provider,{value:rn,children:se(Ga,{flopay:De,paypalFlopay:I,options:Pr??{billingApiUrl:U},onInstrument:ft,children:sn("div",{className:pt,children:[hn&&se("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:hn}),Ue?Ue({onConfirm:cn,isProcessing:nn}):se("button",{type:"button",onClick:cn,disabled:nn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:nn?"not-allowed":"pointer",opacity:nn?.6:1},children:Fn?"Processing...":Ce??"Confirm Purchase"})]})},Ne)}),an]}):(!De||!Pr)&&!(Hn&&yn==="full")?se(Rr,{children:an}):sn(Rr,{children:[se(cr.Provider,{value:rn,children:sn(Ga,{flopay:De,paypalFlopay:I,options:Pr??{billingApiUrl:U},onInstrument:ft,children:[In===1&&se("button",{type:"button",onClick:ar,children:"Retry payment methods"}),re?sn(Rr,{children:[hn&&se("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:hn}),se(Fp,{sessionId:H,nonce:F?.clientSecret||void 0,billingApiUrl:U,session:F,submitLabel:$e,walletPresentation:v,children:re})]}):se(us,{sessionId:H,nonce:F?.clientSecret||void 0,telemetry:a,email:F?.customer?.email||$t?.account?.email,userId:F?.customer?.id||$t?.account?.userId,firstName:F?.customer?.firstName||$t?.account?.firstName,lastName:F?.customer?.lastName||$t?.account?.lastName,totalAmount:F?Math.round(bp(F).total*100):0,currency:F?.currency?.toLowerCase()??"usd",onComplete:C,onError:E,onDecline:z,error:hn,onErrorChange:Tt,showPayPal:ve,showStripe:V,walletPresentation:v,enabledPaymentMethods:In?[]:P??Ae?.data.stripe?.enabledPaymentMethods??F?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ae?.data.stripe?.enabledPaymentMethodCountries,showApplePay:he,showGooglePay:N,layout:Y,theme:Fe,buttonsTheme:lt,buttonsStyles:ze,appearance:qe,cardButtonContent:ct,cardBackButtonContent:zt,cardTitleContent:pe,onButtonClick:Pt,onBeforeButtonClick:Re,onBuyerIdentityReady:Un,enableAVS:He,...ke?{cardFieldOrder:ke}:{},...Q?{cardPreFormSlot:Q}:{},avsLayout:je,country:F?.customer?.country,city:F?.customer?.city,state:F?.customer?.state,onCountryChange:ne,onZipChange:O,avsCheck:!!He,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:hs(re,Y),className:pt,submitLabel:$e,directPaypal:Mn,isSubscription:F?.mode==="subscription",session:F,dataAttachmentPending:Cn,dataAttachmentRequiresIdentity:Ft,debug:Ie})]},Ne)}),an]})}function Fp({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,children:s}){return se(Rr,{children:ps.Children.map(s,c=>{if(!ps.isValidElement(c))return c;let f=c.props,C={};return f.sessionId||(C.sessionId=e),!f.nonce&&t&&(C.nonce=t),f.billingApiUrl||(C.billingApiUrl=n),f.submitLabel===void 0&&a!==void 0&&(C.submitLabel=a),f.walletPresentation===void 0&&(C.walletPresentation=i),o?.customer&&(f.email||(C.email=o.customer.email),f.userId||(C.userId=o.customer.id),f.firstName||(C.firstName=o.customer.firstName),f.lastName||(C.lastName=o.customer.lastName)),Object.keys(C).length===0?c:ps.cloneElement(c,C)})})}function Dp({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:o,showGooglePay:a,theme:i,buttonsTheme:s,buttonsStyles:c,cardButtonContent:f,cardBackButtonContent:C,cardTitleContent:E}){let[k,z]=Gt(!1),ne=Yn(()=>Nc(i),[i]),O=Yn(()=>{let P=ne?.buttonsLayout??kp(s);return c?{...P,...c,cardButton:{...P.cardButton,...c.cardButton},cardFormContainer:{...P.cardFormContainer,...c.cardFormContainer},backButton:{...P.backButton,...c.backButton},backButtonIcon:{...P.backButtonIcon,...c.backButtonIcon},submitButton:{...P.submitButton,...c.submitButton},title:{...P.title,...c.title}}:P},[ne,s,c]),ve=ne?.buttonsLayout?.cardButton?.borderRadius??ne?.appearance.variables?.borderRadius??8,V=P=>se("div",{style:{height:P,borderRadius:ve,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),v=f===void 0?{boxSizing:"border-box",height:Oo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(k){let P=O.cardInputBorder??"#e5e7eb",he=O.cardInputBackground??"white",N=ho(C),Ie=ho(E);return sn("div",{style:{backgroundColor:O.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...O.cardFormContainer},children:[sn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[sn("button",{type:"button",onClick:()=>z(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:N?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...O.backButton},children:[se("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...O.backButtonIcon},children:se("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:se("path",{d:"M15 18l-6-6 6-6"})})}),se(vo,{content:C})]}),Ie?se("div",{style:{flex:1}}):se("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...O.title},children:se(na,{content:E})})]}),se("div",{style:{backgroundColor:he,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:se("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),sn("div",{style:{display:"flex"},children:[se("div",{style:{flex:1,backgroundColor:he,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:se("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),se("div",{style:{flex:1,backgroundColor:he,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:se("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),se("div",{style:{backgroundColor:he,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:se("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),se("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...O.submitButton,opacity:.5}}),se("style",{children:`
|
|
15
15
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
16
16
|
@keyframes flopay-interim-expand {
|
|
17
17
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
18
18
|
40% { opacity: 1; }
|
|
19
19
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
20
20
|
}
|
|
21
|
-
`})]})}return an("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&U(zo),n&&(r||o)&&U(zo),n&&pe("button",{type:"button",onClick:()=>{e?.("card"),j(!0)},style:{width:"100%",...h,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:I.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,...I.cardButton},onMouseDown:C=>{C.currentTarget.style.transform="scale(0.985)"},onMouseUp:C=>{C.currentTarget.style.transform="scale(1)"},children:pe(So,{content:f})}),pe("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Lp,jsx as lo,jsxs as Up}from"react/jsx-runtime";var Bp=44;function Gc(e){return new Promise(t=>setTimeout(t,e))}function Fp(e,t){return e instanceof _a?e:new _a(e instanceof Error?e.message:t,"api_error")}function Dp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Np(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 Op({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:s,items:d,subscriptions:f,account:u,successUrl:w,cancelUrl:b,couponCodes:j,tagsData:L,utmMetadata:I,billingApiUrl:N,locale:U,theme:h,appearance:C,buttonsTheme:le,buttonsStyles:D,onSuccess:ve,onError:J,onDecline:ke,children:qe,disabled:Re=!1,type:st="button",style:qt,...fe}){let Ae=Ra(()=>Ap(N),[N]),ht=Ra(()=>Np({createSession:n,clientId:i,products:s,items:d,subscriptions:f,account:u,successUrl:w,cancelUrl:b,couponCodes:j,tagsData:L,utmMetadata:I}),[u,b,i,j,n,s,d,f,w,L,I]),[Ee,He]=$o(!1),[_e,ie]=$o(null),[je,$e]=$o(null),[pt,Ce]=$o(!1),[ge,ce]=$o(null),[M,Se]=$o(null),Ue=jo(!0),Me=jo(null),V=jo(M),Pt=jo(ve),ze=jo(J),Te=jo(ke),Ze=Nr(p=>ri(Me,async g=>{try{return await p(g)}catch(x){throw g.aborted?Yr(x):x}}),[]);qo(()=>{V.current=M},[M]),qo(()=>{Pt.current=ve},[ve]),qo(()=>{ze.current=J},[J]),qo(()=>{Te.current=ke},[ke]),qo(()=>(Ue.current=!0,()=>{Ue.current=!1,Me.current?.abort()}),[]),qo(()=>{if(typeof window>"u")return;let p=g=>{g.key==="Escape"&&Se(null)};return window.addEventListener("keydown",p),()=>{window.removeEventListener("keydown",p)}},[]);let xe=Nr((p,g=ha)=>{Te.current?.(un(g,p,{code:p.code,declineCode:p.declineCode}))},[]),et=Nr(async p=>{Ue.current&&($e(null),Ce(p.result.status==="authorized"),ie("success"),await Gc(600),Ue.current&&Bt(()=>Pt.current?.(p)))},[]),Fe=Nr(async(p,g)=>{Ue.current&&(ze.current?.(p),g?.emitDecline&&xe(p,g.method),$e(p.message),Ce(!1),ie("error"),await Gc(400))},[xe]),vt=Nr(async(p,g,x)=>{let A=p.data.session??null;if(!A)throw jr(new _a("No session data returned","api_error"),g);let re=A.clientSecret||t;if(Fr(A)){await et({result:Br(A,g),session:A,sessionId:A.id||g,autoCompleted:!1});return}if(A.status==="expired")throw jr($a(A),A.id||g);try{if(p.autoProcessingPending){let he=p.autoProcessingPending,Ke=new Os(Ae),X=await Ze(At=>Ke.waitForCheckoutSessionCompletion(he.sessionId,{initialDelayMs:he.retryAfterMs,nonce:re,statusUrl:he.statusUrl,signal:At})),jt=Kr(X,A),bt=X.autoProcessingError?.type==="3ds_required"&&X.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:X.autoProcessingError.nextActionRedirectUrl}:null;if(bt&&g&&re){let At=await Ze(at=>Fo(bt,{billingApiUrl:Ae,sessionId:g,nonce:re,session:A,signal:at,telemetry:!0}));await et({result:At,session:A,sessionId:A.id||g,autoCompleted:!1});return}if(X.autoProcessingError)throw Rr(X.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:X.autoProcessingError.checkoutMethod});if(!Fr(jt))throw Ro(jt);await et({result:Br(jt,g),session:jt,sessionId:jt.id||g,autoCompleted:!1});return}if(p.autoProcessingError){let he=p.autoProcessingError.nextActionRedirectUrl;if(p.autoProcessingError.type==="3ds_required"&&he&&g&&re){let Ke=await Ze(At=>ss({billingApiUrl:Ae,sessionId:g,nonce:re,nextActionRedirectUrl:he,signal:At}));if(Ke.status==="declined")throw Rr({type:Ke.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ke.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:p.autoProcessingError.checkoutMethod});let jt=await new Os(Ae).waitForCheckoutSessionCompletion(g,{initialDelayMs:0,nonce:re}),bt=Kr(jt,A);if(!Fr(bt))throw Rr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:p.autoProcessingError.checkoutMethod});await et({result:Br(bt,g),session:bt,sessionId:bt.id||g,autoCompleted:!1});return}throw Rr(p.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:p.autoProcessingError.checkoutMethod})}if(x?.fromCreateSession&&p.autoProcessingAttempted===!0)throw Rr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ct=await Do({billingApiUrl:Ae,sessionId:g??A.id,session:A,nonce:re});if(ct.type==="next_action_required"&&re){let he=g??A.id,Ke=await Ze(X=>Fo(ct,{billingApiUrl:Ae,sessionId:he,nonce:re,session:A,signal:X,telemetry:!0}));await et({result:Ke,session:A,sessionId:A.id||he,autoCompleted:!1});return}if(ct.type!=="success")throw Rr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await et({result:ct.result,session:A,sessionId:A.id||g,autoCompleted:!1})}catch(ct){let he=A.id||g,Ke=jr(Pa(ct),he);if(Ke.code==="three_ds_aborted")return;if(Ke.code==="checkout_processing_timeout"){if(!Ue.current)return;ce(Ke.message),Bt(()=>ze.current?.(Ke));return}await Fe(Ke,{emitDecline:!0,method:Ke.checkoutMethod??ha}),Dp(Ke,he)&&he&&Ue.current&&Se({sessionId:he,errorMessage:Ke.message,nonce:re||void 0,payPalOrderId:Ke.orderId})}},[t,Ae,Ze,Fe,et]),Gt=Nr(async p=>{if(fe.onClick?.(p),!(p.defaultPrevented||Re||Ee)){if(Se(null),ce(null),e&&ht){let g=new _a("Provide either sessionId or create-session props, not both.","validation_error");await Fe(g),Ue.current&&(ie(null),$e(null));return}if(!e&&!ht){let g=new _a("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Fe(g),Ue.current&&(ie(null),$e(null));return}He(!0),$e(null),Ce(!1),ie("processing");try{let g=new Os(Ae);if(e){let x=await g.getUnifiedCheckoutSession(e,t);await vt(x,e);return}try{let x=await g.createAndFetchSession({...ht});await vt(x,x.data.session?.id??null,{fromCreateSession:!0})}catch(x){if(Ka(x)==="session_auto_completed"){await et({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw x}}catch(g){await Fe(jr(Fp(g,"Automatic payment failed. Please try again."),e))}finally{Ue.current&&(ie(null),$e(null),He(!1))}}},[fe.onClick,ht,Re,Ee,t,vt,Ae,e,Fe,et]),mt=Nr(p=>{let g=V.current;Se(null),Pt.current?.({result:p,session:null,sessionId:g?.sessionId??null,autoCompleted:!1})},[]),Tt=Nr(p=>{ze.current?.(p)},[]),E=Nr(p=>{Te.current?.(p)},[]),se=Ra(()=>xp(h),[h]),De=Ra(()=>{let p=se?.buttonsLayout??Mp(le);return D?{...p,...D,cardButton:{...p.cardButton,...D.cardButton}}:p},[se,le,D]),F=Ra(()=>{let p=se?.appearance;return C?p?{...p,...C,variables:{...p.variables,...C.variables}}:C:p},[C,se]),we=F?.variables,yt=we?.colorPrimary??"#4A49FF",Ne=we?.colorPrimaryHover??oa(yt,.12),St=we?.borderRadius??"8px";return Up(Lp,{children:[lo("button",{...fe,type:st,onClick:Gt,disabled:Re||Ee,"aria-busy":Ee,style:{width:"100%",...qe===void 0?{boxSizing:"border-box",height:Bp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...De.cardButton,...Rs({themeBundle:se,resolvedPrimaryColor:yt,resolvedBorderRadius:St,submitButtonStyle:De.submitButton,explicitPrimaryColor:we?.colorPrimary}),fontSize:De.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Re||Ee?"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:Re||Ee?.6:1,...qt},onMouseEnter:p=>{fe.onMouseEnter?.(p),!p.defaultPrevented&&!Re&&!Ee&&(se||we?.colorPrimary)&&(p.currentTarget.style.backgroundColor=Ne)},onMouseLeave:p=>{fe.onMouseLeave?.(p),!p.defaultPrevented&&(se||we?.colorPrimary)&&(p.currentTarget.style.backgroundColor=yt)},onMouseDown:p=>{fe.onMouseDown?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(0.985)")},onMouseUp:p=>{fe.onMouseUp?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(1)")},children:lo(So,{content:qe})}),ge&&lo("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ge}),_e&&lo(Ir,{status:_e,errorMessage:je,authorized:pt}),M&&lo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:p=>{p.target===p.currentTarget&&Se(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:lo("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:lo(Ns,{sessionId:M.sessionId,nonce:M.nonce,checkoutMode:"full",billingApiUrl:Ae,locale:U,theme:h,...F?{appearance:F}:{},buttonsTheme:le,buttonsStyles:D,initialErrorMessage:M.errorMessage,initialPayPalOrderId:M.payPalOrderId,cardTitleContent:null,onComplete:mt,onError:Tt,onDecline:E})})})]})}import{jsx as jp}from"react/jsx-runtime";var zp={StripeSetupMethod:Fl,PayPalSetupMethod:Bl};function qp(e){return jp(Dl,{...e,branches:zp})}export{Ja as DirectPayPalButton,Op as FloPayAutomaticPaymentButton,md as FloPayCardSetup,pd as FloPayCardSetupError,Ns as FloPayCheckout,qp as FloPayPaymentMethodSetup,ti as FloPayProvider,_s as SplitCardForm,Oi as VaultCardFields,df as dropThirdPartyOnlyError,xd as useCheckout,Vr as useFloPay,Hi as usePayPalFloPay};
|
|
21
|
+
`})]})}return sn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&V(Oo),n&&(o||a)&&V(Oo),n&&se("button",{type:"button",onClick:()=>{e?.("card"),z(!0)},style:{width:"100%",...v,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:O.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,...O.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:se(Po,{content:f})}),se("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Wp,jsx as ro,jsxs as Hp}from"react/jsx-runtime";var zp=44;function zc(e){return new Promise(t=>setTimeout(t,e))}function Up(e,t){return e instanceof Ca?e:new Ca(e instanceof Error?e.message:t,"api_error")}function qp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function jp(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 $p({sessionId:e,nonce:t,createSession:n,paymentMethodId:o,checkoutMethod:a,clientId:i,products:s,items:c,subscriptions:f,account:C,successUrl:E,cancelUrl:k,couponCodes:z,tagsData:ne,utmMetadata:O,billingApiUrl:ve,locale:V,theme:v,appearance:P,buttonsTheme:he,buttonsStyles:N,onSuccess:Ie,onError:Y,onDecline:Fe,children:lt,disabled:ze=!1,type:ct="button",style:zt,...pe}){let Te=ba(()=>Op(ve),[ve]),Pt=ba(()=>jp({createSession:n,clientId:i,products:s,items:c,subscriptions:f,account:C,successUrl:E,cancelUrl:k,couponCodes:z,tagsData:ne,utmMetadata:O}),[C,k,i,z,n,s,c,f,E,ne,O]),[Re,He]=zo(!1),[ke,Q]=zo(null),[je,$e]=zo(null),[pt,be]=zo(!1),[ye,re]=zo(null),[M,Ce]=zo(null),Ue=Lo(!0),Me=Lo(null),U=Lo(M),vt=Lo(Ie),qe=Lo(Y),Ee=Lo(Fe),Je=Fr(d=>Ya(Me,async m=>{try{return await d(m)}catch(A){throw m.aborted?To(A):A}}),[]);No(()=>{U.current=M},[M]),No(()=>{vt.current=Ie},[Ie]),No(()=>{qe.current=Y},[Y]),No(()=>{Ee.current=Fe},[Fe]),No(()=>(Ue.current=!0,()=>{Ue.current=!1,Me.current?.abort()}),[]),No(()=>{if(typeof window>"u")return;let d=m=>{m.key==="Escape"&&Ce(null)};return window.addEventListener("keydown",d),()=>{window.removeEventListener("keydown",d)}},[]);let Ae=Fr((d,m=pa)=>{Ee.current?.(un(m,d,{code:d.code,declineCode:d.declineCode}))},[]),Qe=Fr(async d=>{Ue.current&&($e(null),be(d.result.status==="authorized"),Q("success"),await zc(600),Ue.current&&Nt(()=>vt.current?.(d)))},[]),De=Fr(async(d,m)=>{Ue.current&&(qe.current?.(d),m?.emitDecline&&Ae(d,m.method),$e(d.message),be(!1),Q("error"),await zc(400))},[Ae]),bt=Fr(async(d,m,A)=>{let T=d.data.session??null;if(!T)throw Ur(new Ca("No session data returned","api_error"),m);let J=T.clientSecret||t;if(Ar(T)){await Qe({result:Mr(T,m),session:T,sessionId:T.id||m,autoCompleted:!1});return}if(T.status==="expired")throw Ur(Na(T),T.id||m);try{if(d.autoProcessingPending){let me=d.autoProcessingPending,We=new Cs(Te),H=await Je(_t=>We.waitForCheckoutSessionCompletion(me.sessionId,{initialDelayMs:me.retryAfterMs,nonce:J,statusUrl:me.statusUrl,signal:_t})),Ut=qr(H,T),Ct=H.autoProcessingError?.type==="3ds_required"&&H.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:H.autoProcessingError.nextActionRedirectUrl}:null;if(Ct&&m&&J){let _t=await Je(at=>Mo(Ct,{billingApiUrl:Te,sessionId:m,nonce:J,session:T,signal:at,telemetry:!0}));await Qe({result:_t,session:T,sessionId:T.id||m,autoCompleted:!1});return}if(H.autoProcessingError)throw kr(H.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:H.autoProcessingError.checkoutMethod});if(!Ar(Ut))throw So(Ut);await Qe({result:Mr(Ut,m),session:Ut,sessionId:Ut.id||m,autoCompleted:!1});return}if(d.autoProcessingError){let me=d.autoProcessingError.nextActionRedirectUrl;if(d.autoProcessingError.type==="3ds_required"&&me&&m&&J){let We=await Je(_t=>oc({billingApiUrl:Te,sessionId:m,nonce:J,nextActionRedirectUrl:me,signal:_t}));if(We.status==="declined")throw kr({type:We.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:We.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:d.autoProcessingError.checkoutMethod});let Ut=await new Cs(Te).waitForCheckoutSessionCompletion(m,{initialDelayMs:0,nonce:J}),Ct=qr(Ut,T);if(!Ar(Ct))throw kr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:d.autoProcessingError.checkoutMethod});await Qe({result:Mr(Ct,m),session:Ct,sessionId:Ct.id||m,autoCompleted:!1});return}throw kr(d.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:d.autoProcessingError.checkoutMethod})}if(A?.fromCreateSession&&d.autoProcessingAttempted===!0)throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ft=await Ao({billingApiUrl:Te,sessionId:m??T.id,session:T,nonce:J});if(ft.type==="next_action_required"&&J){let me=m??T.id,We=await Je(H=>Mo(ft,{billingApiUrl:Te,sessionId:me,nonce:J,session:T,signal:H,telemetry:!0}));await Qe({result:We,session:T,sessionId:T.id||me,autoCompleted:!1});return}if(ft.type!=="success")throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Qe({result:ft.result,session:T,sessionId:T.id||m,autoCompleted:!1})}catch(ft){let me=T.id||m,We=Ur(ya(ft),me);if(We.code==="three_ds_aborted")return;if(We.code==="checkout_processing_timeout"){if(!Ue.current)return;re(We.message),Nt(()=>qe.current?.(We));return}await De(We,{emitDecline:!0,method:We.checkoutMethod??pa}),qp(We,me)&&me&&Ue.current&&Ce({sessionId:me,errorMessage:We.message,nonce:J||void 0,payPalOrderId:We.orderId})}},[t,Te,Je,De,Qe]),Yt=Fr(async d=>{if(pe.onClick?.(d),!(d.defaultPrevented||ze||Re)){if(Ce(null),re(null),e&&Pt){let m=new Ca("Provide either sessionId or create-session props, not both.","validation_error");await De(m),Ue.current&&(Q(null),$e(null));return}if(!e&&!Pt){let m=new Ca("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await De(m),Ue.current&&(Q(null),$e(null));return}He(!0),$e(null),be(!1),Q("processing");try{let m=new Cs(Te);if(e){let A=await m.getUnifiedCheckoutSession(e,t);await bt(A,e);return}try{let A=await m.createAndFetchSession({...Pt});await bt(A,A.data.session?.id??null,{fromCreateSession:!0})}catch(A){if(La(A)==="session_auto_completed"){await Qe({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw A}}catch(m){await De(Ur(Up(m,"Automatic payment failed. Please try again."),e))}finally{Ue.current&&(Q(null),$e(null),He(!1))}}},[pe.onClick,Pt,ze,Re,t,bt,Te,e,De,Qe]),yt=Fr(d=>{let m=U.current;Ce(null),vt.current?.({result:d,session:null,sessionId:m?.sessionId??null,autoCompleted:!1})},[]),Et=Fr(d=>{qe.current?.(d)},[]),I=Fr(d=>{Ee.current?.(d)},[]),ee=ba(()=>Lp(v),[v]),Oe=ba(()=>{let d=ee?.buttonsLayout??Np(he);return N?{...d,...N,cardButton:{...d.cardButton,...N.cardButton}}:d},[ee,he,N]),F=ba(()=>{let d=ee?.appearance;return P?d?{...d,...P,variables:{...d.variables,...P.variables}}:P:d},[P,ee]),Se=F?.variables,mt=Se?.colorPrimary??"#4A49FF",Ne=Se?.colorPrimaryHover??Qo(mt,.12),wt=Se?.borderRadius??"8px";return Hp(Wp,{children:[ro("button",{...pe,type:ct,onClick:Yt,disabled:ze||Re,"aria-busy":Re,style:{width:"100%",...lt===void 0?{boxSizing:"border-box",height:zp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Oe.cardButton,...ds({themeBundle:ee,resolvedPrimaryColor:mt,resolvedBorderRadius:wt,submitButtonStyle:Oe.submitButton,explicitPrimaryColor:Se?.colorPrimary}),fontSize:Oe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ze||Re?"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:ze||Re?.6:1,...zt},onMouseEnter:d=>{pe.onMouseEnter?.(d),!d.defaultPrevented&&!ze&&!Re&&(ee||Se?.colorPrimary)&&(d.currentTarget.style.backgroundColor=Ne)},onMouseLeave:d=>{pe.onMouseLeave?.(d),!d.defaultPrevented&&(ee||Se?.colorPrimary)&&(d.currentTarget.style.backgroundColor=mt)},onMouseDown:d=>{pe.onMouseDown?.(d),d.defaultPrevented||(d.currentTarget.style.transform="scale(0.985)")},onMouseUp:d=>{pe.onMouseUp?.(d),d.defaultPrevented||(d.currentTarget.style.transform="scale(1)")},children:ro(Po,{content:lt})}),ye&&ro("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ye}),ke&&ro(Sr,{status:ke,errorMessage:je,authorized:pt}),M&&ro("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:d=>{d.target===d.currentTarget&&Ce(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:ro("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:ro(bs,{sessionId:M.sessionId,nonce:M.nonce,checkoutMode:"full",billingApiUrl:Te,locale:V,theme:v,...F?{appearance:F}:{},buttonsTheme:he,buttonsStyles:N,initialErrorMessage:M.errorMessage,initialPayPalOrderId:M.payPalOrderId,cardTitleContent:null,onComplete:yt,onError:Et,onDecline:I})})})]})}import{jsx as Gp}from"react/jsx-runtime";var Vp={StripeSetupMethod:Cl,PayPalSetupMethod:bl};function Kp(e){return Gp(Sl,{...e,branches:Vp})}export{Wa as DirectPayPalButton,$p as FloPayAutomaticPaymentButton,od as FloPayCardSetup,rd as FloPayCardSetupError,bs as FloPayCheckout,Kp as FloPayPaymentMethodSetup,Ga as FloPayProvider,us as SplitCardForm,Ti as VaultCardFields,Cf as dropThirdPartyOnlyError,Rd as useCheckout,jr as useFloPay,zi as usePayPalFloPay};
|