@flopay/react 1.11.0 → 1.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +8 -8
- package/dist/index.mjs +7 -7
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as Tl}from"./chunk-LIYRDFMO.mjs";import{c as xt,d as Sr,e as ea,f as xi,g as gl,h as ta,i as hl,j as Pl,k as id,m as sd}from"./chunk-AZRGKPW7.mjs";import{a as _l}from"./chunk-YSFYLEHB.mjs";import{a as oa,b as La,c as Fi,d as Di,e as Ni,f as Sl,g as wl,h as Il,i as kl,j as Rl,k as El}from"./chunk-UFFPBTKU.mjs";import{a as Da,b as vl,c as Lr,d as na,e as Na,f as bl,g as Bi,h as Ur,i as ra,j as Cl,k as Oa}from"./chunk-M7R46EDF.mjs";import{dropThirdPartyOnlyError as Gy}from"@flopay/shared";import{PaymentAPI as Bs}from"@flopay/js";import{FloPayError as wa,resolveBillingApiUrl as fp,resolveButtonsLayoutTheme as gp,resolveTheme as hp}from"@flopay/shared";import{useCallback as Nr,useEffect as Lo,useMemo as Sa,useRef as Uo,useState as zo}from"react";import{Fragment as Co,jsx as Jn,jsxs as Al}from"react/jsx-runtime";function ld(){return Al(Co,{children:[Al("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:[Jn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Jn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Jn("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:Jn("path",{d:"M9 18l6-6-6-6"})})]})}function cd(){return Jn(Co,{children:"Go back"})}function dd(){return Jn(Co,{children:"Secure card checkout"})}function Po(e){return e!==void 0&&(e===""||e===null||e===!1)}function vo({content:e}){return Jn(Co,{children:e===void 0?Jn(ld,{}):e})}function bo({content:e}){return Jn(Co,{children:e===void 0?Jn(cd,{}):e})}function aa({content:e}){return Jn(Co,{children:e===void 0?Jn(dd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as ud,classifyTelemetryFailure as pd,FloPayError as kn,isCardHolderNamePlaceholder as Ml,isMoneySettledOutcome as md,isSetupIntentClientSecret as yd,isValidEmail as fd,resolveSetupFutureUsage as gd}from"@flopay/shared";var hd="Checkout is temporarily unavailable. Please try again later.";function Oi(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 Pd(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function xl(){return new kn(hd,"api_error",{code:"CheckoutInitializationFailed"})}function Li(e){return!!e?.gateways?.worldpayCorporateGateway}function zr(e){return e?.status==="open"&&Li(e)}function Bl(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card")||zr(r))||t&&e?.data.paypal?.publishableKey)}function Fl(e,t){if(t&&(!(e instanceof kn)||e.type==="authentication_error"))return Oi(e);if(!(e instanceof kn&&Pd(e))){if(!t&&!(e instanceof kn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...pd(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 So(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},l=Ml(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[u,S]of Object.entries(s)){if(l&&u.endsWith("Name")||typeof S!="string")continue;let v=S.trim();v&&(f[u]=v)}return o=e.claimCheckoutSession(t,n,{accountData:f}),o.catch(()=>{}),o}}function Dl(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 Ui(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 Nl(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 no(e){if(Ml(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function zi(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 qr(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var vd=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function jr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of vd)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 $r(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 Ol(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Ua(e){let t=Ol(e);return new kn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function za(e){return e instanceof kn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function wo(e){return Ol(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(ud,"api_error",{code:"checkout_processing_timeout"})}function ia(e,t){return e==="processing"||md(e,t)}function Ll(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Ul(e,t){let n=e;if(yd(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:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new kn(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}var bd=["apple_pay","google_pay"];function zl(e,t="automatic",n){let r=gd(n,bd,"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}:{}}}function qi(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function sa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Qu,PaymentAPI as ci,SESSION_CREATE_TELEMETRY as ep}from"@flopay/js";import{buildCheckoutDisplayData as tp,classifyTelemetryFailure as Lc,FloPayError as vn,isDetachedSessionEligible as np,resolveBillingApiUrl as rp,resolveButtonsLayoutTheme as op,resolveIdempotencyKey as Mc,resolveTheme as Uc,SDK_VERSION as zc,telemetryStatusClass as ap}from"@flopay/shared";import Is,{useCallback as Pn,useEffect as mr,useMemo as Xn,useRef as Bt,useState as Vt}from"react";import{createContext as ql}from"react";var Zn=ql({flopay:null,paypalFlopay:null,billingApiUrl:""}),dr=ql({session:null,loading:!1,error:null});import{PaymentAPI as Ki}from"@flopay/js";import{classifyTelemetryFailure as Dd,FloPayError as Hi,generateIdempotencyKey as Nd,isValidEmail as ua,normalizeGatewayEnvironment as Od,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Vi,SDK_VERSION as Ld}from"@flopay/shared";import{loadScript as Ud}from"@paypal/paypal-js";import{useCallback as wr,useContext as zd,useEffect as Lt,useMemo as pa,useRef as rt,useState as Vr}from"react";import{isValidEmail as Cd}from"@flopay/shared";import{useCallback as jl,useEffect as Sd,useRef as $l,useState as Hl}from"react";import{jsx as Kl,jsxs as la}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 Io(){let[e,t]=Hl(null),n=$l(null),r=$l(0),o=jl((s,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:l}),new Promise(f=>{n.current=f})),[]),i=jl(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return Sd(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function ko({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=Hl(e.email?.trim()??""),f=Cd(s.trim());return la("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:[la("div",{style:{fontWeight:700},children:["Continue with ",t]}),la("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Kl("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:u=>l(u.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),la("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Kl("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),la("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 wd}from"@flopay/shared";import{useContext as qa}from"react";function Kr(){return qa(Zn).flopay}function ji(){return qa(Zn).paypalFlopay??null}function Id(){return qa(dr)}function Vl(){return qa(Zn).billingApiUrl||wd()}import{FLO_INSTRUMENT_SCHEMA_VERSION as kd}from"@flopay/shared";import{useCallback as Rd,useRef as ja}from"react";var _d={"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 Ed(e){return e==="stripe"||e==="paypal"?e:void 0}function Td(e){let t=Ed(e.provider),n={schemaVersion:kd,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=_d[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 $i=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Ro(e,t){let n=ja(e);n.current=e;let r=ja(new Set),o=ja(t),i=ja(t);return ea(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Rd(s=>{if(i.current!==t)return;let l=Td(s);if(l){if($i.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}xt(()=>n.current?.(l))}},[t])}import{createContext as Ad}from"react";var ca=Ad(null);function $a(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Md=Symbol.for("@flopay/js.telemetry.bridge.v1"),xd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Bd(){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 Fd(e){let t=Bd(),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 Ka(e){let t=globalThis[xd];return Fd(t?.(e)??{})}function pn(e){if(e)return e[Md]}import{useCallback as Hr,useEffect as Wl,useRef as ro}from"react";function da(e,t){let n=ro(0),r=ro(null),o=ro(null),i=ro(e),s=ro(t?.onHandoffObserved),l=ro(t?.defersMissingTerminal),f=ro(t?.onMissingTerminalDeferred);Wl(()=>{i.current=e,s.current=t?.onHandoffObserved,l.current=t?.defersMissingTerminal,f.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let u=Hr((h=o.current)=>{h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),S=Hr(h=>{u();let b=n.current+1;return n.current=b,r.current=null,o.current={generation:b,method:h,timer:null,yieldedControl:!1},b},[u]),v=Hr(h=>{let b=o.current;return h!==void 0&&b?.generation!==h?!1:(u(b),o.current=null,(h===void 0||r.current===h)&&(r.current=null),!0)},[u]),H=Hr(h=>{let b=o.current,se=h??b?.generation??n.current;(h===void 0||b?.generation===h)&&(u(b),o.current=null),r.current=se},[u]),$=Hr(h=>r.current===(h??n.current),[]),k=Hr(h=>o.current?.generation===h&&r.current!==h,[]),q=Hr(()=>{let h=o.current;h&&(u(h),!h.yieldedControl&&(h.yieldedControl=!0,s.current?.(h.method)))},[u]),K=Hr(()=>{let h=o.current;!h?.yieldedControl||document.visibilityState!=="visible"||(u(h),h.timer=setTimeout(()=>{if(h.timer=null,o.current?.generation===h.generation){if(l.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 Wl(()=>{let h=()=>{document.visibilityState==="visible"?K():q()};return document.addEventListener("visibilitychange",h),window.addEventListener("blur",q),window.addEventListener("focus",K),()=>{document.removeEventListener("visibilitychange",h),window.removeEventListener("blur",q),window.removeEventListener("focus",K),u()}},[u,q,K]),{startAttempt:S,finishAttempt:v,invalidateAttempt:H,isAttemptInvalidated:$,isAttemptCurrent:k,generationRef:n}}import{jsx as oo,jsxs as Wi}from"react/jsx-runtime";var Ha=45,qd=1e3,jd=11e3,$d={width:"100%",minHeight:Ha,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"},Kd={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 Hd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Kd[e.kind]??null}}function Gl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":bl(t)?"paypal_init_timeout":"paypal_init_failure"}function Vd(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 Wd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Yl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:l,currency:f,isSubscription:u,providerObjectType:S,approvalPresentation:v,onTokenizedBody:H,onComplete:$,onErrorChange:k,onDecline:q,onTechnicalFailure:K,isProcessing:h=!1,onLoadStateChange:b,onInitializationStateChange:se,allowAutomaticRetry:U=!0,onButtonClick:ve,runBeforeButtonClick:J,session:ke,existingOrderId:qe,telemetry:Re,telemetryContext:it,onInstrument:Ut,debug:me=!1}){let Me=Kr(),gt=Ro(Ut,e),Te=pa(()=>{if(Me)return null;let m=Ka({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ld,enabled:Re!==!1});return m.setCheckoutContext(it??{}),m.beginCheckout(it??{}),m},[n,Me,Re,it?.checkoutMode,it?.layout]),Ve=pa(()=>pn(Me),[Me]);Lt(()=>()=>{Te&&Te.flush().catch(()=>{}).finally(()=>Te.destroy())},[Te]);let _e=pa(()=>({error:m=>{Ve?Ve.error(m):Te?.error(m),gt({class:"technical_error",errorCode:m.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":m.errorCode,requestCategory:m.requestCategory,provider:m.provider})},log:m=>{Ve?Ve.log(m):Te?.log(m),gt({class:"lifecycle",name:m.name,provider:m.provider})},performance:m=>{Ve?Ve.performance(m):Te?.performance(m)},terminal:m=>{Ve?Ve.terminal(m):Te?.terminal(m)},startTiming:()=>Ve?.now()??Te?.now()??0,elapsed:m=>Ve?.elapsed(m)??Math.max(0,(Te?.now()??m)-m)}),[gt,Ve,Te]),ne=rt(null),je=rt(0),$e=rt(null),pt=rt(null),Ce=rt(null),ye=zd(ca),le=rt(null);le.current||(le.current=$a());let F=ye??le.current,Se=rt(null),Ue=rt(!1),[xe,W]=Vr(!1),[ht,ze]=Vr(!1),[Ae,Ze]=Vr(0),Be=rt(0),[Qe,De]=Vr(!1),Pt=rt(!1),Wt=rt(!1),[mt,Et]=Vr(!1),[_,re]=Vr(!1),{request:Ne,collect:L,finish:we}=Io(),yt=rt({sessionId:e,required:!ua(r?.trim()||ke?.customer?.email?.trim())});yt.current.sessionId!==e&&(yt.current={sessionId:e,required:!ua(r?.trim()||ke?.customer?.email?.trim())});let Oe=yt.current.required,It=pa(()=>n.replace(/\/+$/,""),[n]),p=ke?.gateways?.paypal?.providerObjectType??S,g=p??(u?"subscription":"order"),[D]=Vr(ra),x=ke?.gateways?.paypal?.approvalPresentation??v,ee=Oa(D,x==="app_switch"?"app_switch":void 0,g),vt=p==="order"||p==="setup_token",fe=pa(()=>JSON.stringify([It,s,f,l??"",g,vt,ee,e,qe??""]),[It,s,f,l,qe,g,vt,ee,e]),Ke=rt(fe),Z=Ke.current!==fe,zt=rt(me),bt=rt(null),[Tt,st]=Vr([]),ce=wr(m=>{zt.current&&st(Ge=>[...Ge,`${new Date().toISOString().slice(11,23)} ${m}`])},[]);Lt(()=>{zt.current=me,me&&ce("debug:enabled"),bt.current?.setEnabled(me)},[ce,me]);let Rn=rt(H),On=rt($),mn=rt(k),qt=rt(q),Ln=rt(K),Un=rt(ve),gn=rt(b),At=rt(se),We=rt(i),Le=rt(J),_n=rt(ke),kt=rt(r),zn=rt(o),yn=rt(t),jt=rt(null),Xt=rt(new Map),Qn=rt(new Map),Hn=rt(!1);Lt(()=>(Hn.current=!0,()=>{Hn.current=!1}),[]),Lt(()=>{Rn.current=H},[H]),Lt(()=>{We.current=i},[i]),Lt(()=>{On.current=$},[$]),Lt(()=>{mn.current=k},[k]),Lt(()=>{qt.current=q},[q]),Lt(()=>{Ln.current=K},[K]),Lt(()=>{Un.current=ve},[ve]),Lt(()=>{gn.current=b},[b]),Lt(()=>{At.current=se},[se]),Lt(()=>{Le.current=J},[J]),Lt(()=>{_n.current=ke},[ke]),Lt(()=>{kt.current=r},[r]),Lt(()=>{zn.current=o},[o]),Lt(()=>{yn.current=t},[t]),Lt(()=>{Be.current=Ae},[Ae]),Lt(()=>{Qe&&Se.current?.focus()},[Qe,Ae]);let Qt=wr(()=>{window.setTimeout(()=>{Se.current?.focus()},0)},[]),Rt=wr(()=>{W(!1),Ze(m=>m+1)},[]),en=wr(()=>{De(!1),(ne.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ne.current)?.focus?.()},[]);Lt(()=>{!xe||!Ue.current||(Ue.current=!1,en())},[en,xe,Ae]);let nn=wr((m,Ge)=>{let V=Ge?.popupBlocked??Ur(m);V&&F.markBlocked();let hn=Da("PayPal",V,D.inAppBrowser),qn=Ln.current;if(qn){let Gt=V&&D.inAppBrowser?new Hi(hn,"api_error",{code:Ge?.code??"paypal_popup_blocked"}):m;qn("paypal",Gt,Ge);return}mn.current?.(hn)},[F,D.inAppBrowser]),Ft=wr(m=>{let Ge=$e.current,V=pt.current;Ge===null||!V||(_e.log({...V,popupCapability:F.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:m}),_e.performance({...V,popupCapability:F.current(),stage:"overlay_return",durationMs:_e.elapsed(Ge),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:m}),$e.current=null)},[F,_e]),an=wr((m,Ge,V)=>{let hn=pt.current;Ft("overlay_timeout"),hn&&_e.error({...hn,popupCapability:F.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),nn(Ge,{...V,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ee,terminalReason:"overlay_timeout"}),De(!0),Rt(),Qt()},[Ft,Qt,nn,F,ee,Rt,_e]),Nt=wr(()=>{F.markAvailable();let m=pt.current;m&&(Ce.current=m.attempt,_e.log({...m,popupCapability:F.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[F,_e]),{finishAttempt:rn,generationRef:Dt,invalidateAttempt:G,isAttemptCurrent:er,isAttemptInvalidated:tr,startAttempt:nr}=da(an,{onHandoffObserved:Nt}),tn=wr(()=>(De(!1),nr("paypal")),[nr]),En=wr(m=>{G(m?.generation),m?.showRetry&&De(!0),m?.remount&&Rt(),m?.focus!==!1&&Qt()},[Qt,G,Rt]),bn=m=>{let Ge=jt.current;return Ge&&Qn.current.set(m,Ge),m};Lt(()=>{Ke.current!==fe&&(Ke.current=fe,Pt.current=!1,Wt.current=!1,W(!1),ze(!1),Et(!1),At.current?.("loading"))},[fe]),Lt(()=>{xt(()=>gn.current?.(xe&&!mt))},[xe,mt]);let he=Od(l);Lt(()=>{let m={attempt:Dt.current+1,inAppBrowser:D.inAppBrowser,appFamily:D.appFamily,popupCapability:F.current(),presentationMode:ee},Ge=()=>({...pt.current??m,popupCapability:F.current()}),V={error:d=>_e.error({...d,...Ge()}),log:d=>_e.log({...d,...Ge()}),performance:d=>_e.performance({...d,...Ge()}),terminal:d=>_e.terminal({...d,...Ge()}),startTiming:_e.startTiming,elapsed:_e.elapsed},hn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",qn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(ce(`mount clientId=${hn} env=${l??"(unset)"}\u2192${he??"live"} ccy=${f} sub=${u}`),ce(`ua=${qn.slice(0,80)}${qn.length>80?"\u2026":""}`),!s){ce("FAIL: clientId empty \u2014 gateway misconfigured"),Et(!0),V.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(!ne.current){ce("FAIL: containerRef not attached");return}je.current=V.startTiming(),V.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,Tn=!1,tt=()=>Gt||Tn,rr,Zr=!1,_t=()=>{rr=Nd(),rr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Zr=!0},An=null,yr=!1,Vn=null,Yt=!1,or=()=>{!Vn||Yt||(Yt=!0,Vn.close().catch(()=>{}))},Mn=!1,_r=!1,xn=ne.current,fr=null,gr=null,Er=[],jn=null,Wn=!1,Tr=!1,Mt=null,Cn=d=>{if(!d||typeof d.getBoundingClientRect!="function")return"(no rect)";let c=d.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},Gn=d=>{if(!d)return"(empty)";try{let c=new URL(d,typeof window>"u"?"https://localhost":window.location.href),I=c.pathname.toLowerCase();return I.includes("checkcaptcha")||I.includes("captcha")?`CAPTCHA(${c.host}${I})`:I.includes("risk")||I.includes("challenge")?`RISK(${c.host}${I})`:I.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${I}`.slice(0,100)}catch{return d.slice(0,80)}},Ar=d=>{let c=d.getAttribute("src"),I=d.getAttribute("srcdoc"),T=d.getAttribute("name"),Q=d.getAttribute("sandbox"),ae=[];return c&&ae.push(`src=${Gn(c)}`),I&&ae.push(`srcdoc[${I.length}ch]`),!c&&!I&&ae.push("src=(empty) srcdoc=(empty)"),T&&ae.push(`name=${T.slice(0,40)}`),Q!==null&&ae.push(`sandbox="${Q.slice(0,40)}"`),ae.join(" ")},Mr=d=>{if(!(d instanceof HTMLIFrameElement))return"";try{let c=d.contentDocument;if(!c)return"cd=null";let I=c.body?.children.length??0,T=c.body?.innerHTML.length??0,Q=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${I}children,${T}ch] head[${Q}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},He=[],sn=d=>{if(tt())return;let c=d.message??String(d.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(ce(`window:error ${c.slice(0,140)}`),He.push(c))},ln=d=>{if(tt())return;let c=d.reason instanceof Error?d.reason.message:String(d.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(ce(`window:rejection ${c.slice(0,140)}`),He.push(c))},Sn={value:0},Xr=()=>{fr?.disconnect(),fr=null,gr?.disconnect(),gr=null;for(let d of Er.splice(0))clearTimeout(d);Tr=!1,Wn&&typeof window<"u"&&(window.removeEventListener("error",sn),window.removeEventListener("unhandledrejection",ln)),Wn=!1},hr=()=>{if(!(Wn||tt()||Mn)){if(Wn=!0,He.length=0,Sn.value=0,typeof window<"u"&&(window.addEventListener("error",sn),window.addEventListener("unhandledrejection",ln)),typeof PerformanceObserver<"u")try{gr=new PerformanceObserver(d=>{if(!tt())for(let c of d.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Sn.value+=1;let I=Math.round(c.duration);ce(`net ${I}ms ${c.name.slice(0,90)}`)}}),gr.observe({type:"resource",buffered:!0})}catch{}Mt?.()}},Or=()=>{jn&&(clearTimeout(jn),jn=null)},wn=()=>{Xr(),Or()},cn={setEnabled:d=>{d?hr():Xr()}};bt.current=cn,zt.current&&hr();let xr=d=>{if(!d)return!1;let c=d.toLowerCase();return c.includes("zoid destroyed")||c.includes("destroyed all components")||c.includes("window closed")||c.includes("detected container element removed")},Bn=d=>{if(tt()||xr(d))return;let c=jr(d)??d;xt(()=>mn.current?.(c))},w=(d,c)=>{if(Gt||yr)return;yr=!0,Tn=!0,wn(),or();let I=Hd({kind:d,generationActive:!0,automaticRetryAllowed:U,automaticRetryUsed:Pt.current});if(I.action==="retry"){Pt.current=!0,W(!1),re(!1),ze(!0),At.current?.("retrying"),An=setTimeout(()=>{Gt||Ze(T=>T+1)},qd);return}if(W(!1),re(!1),ze(!1),Et(!0),I.action!=="ignore"){if(At.current?.("exhausted"),I.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",c);return}if(I.report){let T=Bi({code:Gl(d,c),message:c},{inAppBrowser:D.inAppBrowser,handoffObserved:!1});T.popupBlocked&&F.markBlocked(),V.error({errorCode:T.popupBlocked?T.errorCode:I.report.errorCode,stage:I.report.stage,operationOutcome:I.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:T.terminalReason})}Wt.current||(Wt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Gl(d,c)))}};Et(!1);let R=async(d,c=jt.current)=>{if(tt())return;let I=c?.sessionId??e;if(Rn.current){await Rn.current(d,{sessionId:I,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let T=V.startTiming();V.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Q=()=>{V.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"processing",durationMs:V.elapsed(T),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ae=_n.current,Fe=c?.accountPatch?.email??kt.current,at=c?.accountPatch?.userId??ae?.customer?.id??ae?.accountData?.userId??"",pe=c?.accountPatch?.firstName??ae?.customer?.firstName??ae?.accountData?.firstName,C=c?.accountPatch?.lastName??ae?.customer?.lastName??ae?.accountData?.lastName,ie=await new Ki(It,{telemetry:!1}).processPayment(at,{sessionId:I,nonce:c?.nonce??yn.current,paymentMethodCategory:"paypal",tokenizedData:d,accountData:{userId:at,email:Fe??ae?.customer?.email??"",...pe?{firstName:pe}:{},...C?{lastName:C}:{},country:c?.accountPatch?.country??ae?.customer?.country??ae?.accountData?.country??void 0,zip:c?.accountPatch?.zip??ae?.customer?.zip??ae?.accountData?.zip??void 0}});if(ie.ok){if(Tn||Gt&&Hn.current)return;Q(),V.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),xt(()=>On.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(tt())return;let te=await ie.json().catch(()=>null),A=te?.message??"PayPal payment failed.",Y=jr(A)??A;Q(),ie.status===400&&(typeof te?.declineCode=="string"||!Array.isArray(te?.fields))?V.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ie.status===400||ie.status===422?V.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):V.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Wd(ie.status),failureCategory:ie.status>=500?"server_error":void 0}),Bn(Y),xt(()=>qt.current?.(un("paypal",Y,{code:te?.code,declineCode:te?.declineCode})));return}catch(ae){if(tt())return;Q(),V.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Fe=ae instanceof Error?ae.message:"PayPal payment failed.",at=jr(Fe)??Fe;Bn(at),xt(()=>qt.current?.(un("paypal",at)));return}},O=()=>new Hi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),E=d=>tt()?Promise.reject(O()):Promise.resolve(d),nt=async d=>{if(tt())throw O();Zr||_t();let c=jt.current,I=c?.sessionId??e,T=c?.nonce??yn.current;V.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Q;try{Q=await new Ki(It,{telemetry:!1}).createSessionIntent(I,T??"",vt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Vi,paymentMethodId:null,intentKind:g==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:rr})}catch(ae){throw V.error({...Dd(ae,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ae}if(tt())throw O();if(Q.provider!=="paypal"||Q.providerObjectType!==g)throw new Error(d);return V.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Q.providerObjectId},ut=(d,c)=>{let I=c?.nonce??yn.current;if(!I)return;let T=c?.sessionId??e,Q=na(d)??Lr(d)??"provider_declined";new Ki(It,{telemetry:!1}).reportSessionIntentDecline(T,I,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Q}).catch(()=>{})},j=Ae;ce("loadScript:scheduled (deferred 1 tick)");let Ee=null,B=setTimeout(()=>{if(Gt){ce("loadScript:skipped (cancelled before defer ran)");return}ce("loadScript:start");let d=he==="live"?"production":he,c={};g==="subscription"?c={intent:"subscription",vault:!0}:g==="order"&&(c={intent:"capture"}),Ee=Ud({clientId:s,currency:f,...c,...d?{environment:d}:{},...d==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let I=!1;Ee.then(T=>{if(I=!0,ce(`loadScript:resolved inactive=${tt()} ns=${!!T} buttons=${!!T?.Buttons}`),tt())return;if(!T?.Buttons){ce("FAIL: namespace missing Buttons factory"),w("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}V.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"provider_ready",durationMs:V.elapsed(je.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),V.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Q=async(ie,te)=>{if(tt()||Be.current!==j)return;let A=ie.vaultSetupToken??ie.subscriptionID??ie.orderID??"",Y=A?Qn.current.get(A):Xt.current.get(j);if(!(!Y||!er(Y.generation))&&rn(Y.generation)){Qn.current.delete(A),Xt.current.delete(Y.surfaceKey),Ft("approved");try{if(re(!0),xt(()=>mn.current?.(null)),!A)throw new Hi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let N=_n.current,ct=no(zn.current??[N?.customer?.firstName,N?.customer?.lastName].filter(Boolean).join(" ")),Ie=Nn({email:Y.accountPatch?.email?.trim()||kt.current?.trim()||N?.customer?.email?.trim(),firstName:Y.accountPatch?.firstName?.trim()||ct.firstName,lastName:Y.accountPatch?.lastName?.trim()||ct.lastName});if(!ua(Ie.email)||!(Ie.firstName||Ie.lastName))try{let In=Vd(await te?.order?.get?.());Ie=Nn({email:In.email||Ie.email,firstName:In.firstName||Ie.firstName,lastName:In.lastName||Ie.lastName})}catch{}if((We.current||Oe)&&!ua(Ie.email)){let In=await L("PayPal",Ie);if(!In)return;Ie=In}ua(Ie.email)&&(Y.accountPatch=Nn({...Y.accountPatch,...Ie}),await We.current?.(Ie));let ar;g==="setup_token"?ar={id:A,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Vi}:vt?ar={id:A,isPaypal:!0,gateway:"paypal",paymentMethodType:Vi}:ar={id:A,isPaypal:!0},await R(ar,Y)}catch(N){Bn(N instanceof Error?N.message:"PayPal capture failed.")}finally{tt()||re(!1)}}},ae=ie=>{let te=qe?()=>E(qe):()=>nt(ie);return async()=>bn(await te())},Fe=T.Buttons({style:{layout:"horizontal",height:Ha,tagline:!1},...ee==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ie,te)=>{if(tt()){await te.reject();return}_t();let A=Le.current,Y={};if(A)try{let Ie=await A("paypal");if(tt()){await te.reject();return}if(!Ie.proceed){jt.current=null,Xt.current.delete(j),await te.reject();return}Y={sessionId:Ie.sessionId,accountPatch:Ie.accountPatch,nonce:Ie.nonce}}catch(Ie){ce(`onClick:runBeforeButtonClick rejected msg=${(Ie instanceof Error?Ie.message:String(Ie)).slice(0,120)}`),jt.current=null,Xt.current.delete(j),await te.reject();return}xt(()=>Un.current?.("paypal"));let N=tn(),ct={generation:N,surfaceKey:j,...Y};jt.current=ct,Xt.current.set(j,ct),pt.current={...m,attempt:N},await te.resolve(),V.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),V.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),$e.current=V.startTiming()},createOrder:g==="order"?ae("Failed to create PayPal order."):void 0,createSubscription:g==="subscription"?ae("Failed to create PayPal subscription."):void 0,createVaultSetupToken:g==="setup_token"?async()=>bn(await nt("Failed to create PayPal setup token.")):void 0,onApprove:Q,onCancel:()=>{if(tt())return;let ie=Xt.current.get(j)??jt.current;ie&&Xt.current.delete(ie.surfaceKey),jt.current=null,Ft("cancelled"),V.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ue.current=!0,En({generation:ie?.generation,remount:!0,focus:!1})},onError:ie=>{if(tt()||Be.current!==j)return;let te=ie instanceof Error?ie.message:"PayPal failed to render.";if(ce(`onError rendered=${Mn} msg=${te.slice(0,120)}`),Mn){let A=Xt.current.get(j)??jt.current;if(A&&!er(A.generation)||!A&&tr())return;if(xr(te)){rn(A?.generation);return}let{errorCode:Y,popupBlocked:N,providerDeclined:ct,terminalReason:Ie}=Bi(ie,{inAppBrowser:D.inAppBrowser,handoffObserved:A!=null&&Ce.current===A.generation});if(N&&F.markBlocked(),Ft(Ie),ct){V.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ie}),ut(ie,A),xt(()=>qt.current?.(un("paypal",te))),A&&Xt.current.delete(A.surfaceKey),jt.current=null,rn(A?.generation);return}V.error({errorCode:Y,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ie}),A&&Xt.current.delete(A.surfaceKey),jt.current=null,En({generation:A?.generation,remount:!0,showRetry:!0,focus:!0}),nn(ie,{code:"paypal_runtime_failed",popupBlocked:N,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ee,terminalReason:Ie});return}w(xr(te)?"teardown":"pre_ready_callback",te)}}),at=Fe.isEligible();if(ce(`isEligible=${at}`),V.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!at){W(!1),w("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}_r=!0,Vn=Fe,Mt=()=>{if(!Wn||Tr||tt()||Mn)return;Tr=!0,ce(`container:dims ${Cn(xn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(fr=new MutationObserver(te=>{if(!tt()){for(let A of te)if(A.type==="childList")A.addedNodes.forEach(Y=>{if(!(Y instanceof Element))return;let N=Y.tagName.toLowerCase(),ct=(Y.getAttribute("title")??"").slice(0,40),Ie=N==="iframe"?` ${Ar(Y)}`:"";ce(`child+ ${N}${ct?` title="${ct}"`:""}${Ie} dims=${Cn(Y)}`)});else if(A.type==="attributes"&&A.target instanceof Element){let Y=A.target;if(Y.tagName.toLowerCase()!=="iframe")continue;let N=A.attributeName;(N==="src"||N==="srcdoc")&&ce(`attr~ iframe ${N}=${N==="srcdoc"?`[${(Y.getAttribute("srcdoc")??"").length}ch]`:Gn(Y.getAttribute("src"))} dims=${Cn(Y)}`)}}}),fr.observe(xn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ie=te=>{if(tt()||Mn)return;let A=xn.querySelectorAll("iframe"),Y=typeof document<"u"&&"hasStorageAccess"in document;ce(`watchdog:${te} container=${Cn(xn)} children=${xn.childElementCount} iframes=${A.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Y} paypalNetRequests=${Sn.value}`),A.forEach((N,ct)=>{let Ie=(N.getAttribute("title")??"").slice(0,40);ce(` iframe[${ct}] ${Cn(N)}${Ie?` title="${Ie}"`:""} ${Ar(N)}`);let ar=Mr(N);ar&&ce(` ${ar}`)}),He.length===0&&ce(" (no PayPal/zoid window errors captured)")};Er.push(setTimeout(()=>ie("3s"),3e3)),Er.push(setTimeout(()=>ie("8s"),8e3)),Er.push(setTimeout(()=>ie("15s"),15e3))},Mt(),ce("render:start");let C=V.startTiming();jn=setTimeout(()=>{tt()||Mn||(ce("watchdog:11s retryable render timeout"),w("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},jd);let lt=Fe.render(xn);(async()=>{try{if(await lt,ce(`render:resolved inactive=${tt()}`),wn(),tt()){or();return}Mn=!0,W(!0),ze(!1),At.current?.("ready"),V.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),V.performance({stage:"checkout_render",durationMs:V.elapsed(C),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ie){let te=ie instanceof Error?ie.message:"PayPal failed to render.";ce(`render:rejected msg=${te.slice(0,120)}`),wn(),w(xr(te)?"teardown":"render_rejected",te)}})()}).catch(T=>{let Q=T instanceof Error?T.message:"PayPal operation failed.";ce(`provider:failed msg=${Q.slice(0,120)}`);let ae="script_rejected";I&&xr(Q)?ae="teardown":I&&_r&&(ae="render_rejected"),w(ae,Q)})},0);return()=>{Gt=!0,clearTimeout(B),An&&clearTimeout(An),wn(),bt.current===cn&&(bt.current=null),or(),$e.current=null,pt.current=null}},[U,It,s,f,l,g,ee,vt,e,qe,Ae,_e,L,Oe,ce,Ft]);let et=me?Wi("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=${xe} failed=${mt})`,Tt.length===0?`
|
|
1
|
+
import{a as Al}from"./chunk-LIYRDFMO.mjs";import{c as Bt,d as br,e as ta,f as Bi,g as hl,h as na,i as Pl,j as vl,k as sd,m as ld}from"./chunk-AZRGKPW7.mjs";import{a as El}from"./chunk-YSFYLEHB.mjs";import{a as aa,b as Ua,c as Di,d as Ni,e as Oi,f as wl,g as Il,h as kl,i as Rl,j as _l,k as Tl}from"./chunk-UFFPBTKU.mjs";import{a as Na,b as Cl,c as Ur,d as ra,e as Oa,f as bl,g as Fi,h as zr,i as oa,j as Sl,k as La}from"./chunk-M7R46EDF.mjs";import{dropThirdPartyOnlyError as Qy}from"@flopay/shared";import{PaymentAPI as Fs}from"@flopay/js";import{FloPayError as Ia,resolveBillingApiUrl as Cp,resolveButtonsLayoutTheme as bp,resolveTheme as Sp}from"@flopay/shared";import{useCallback as Or,useEffect as Uo,useMemo as wa,useRef as zo,useState as qo}from"react";import{Fragment as So,jsx as Jn,jsxs as Ml}from"react/jsx-runtime";function cd(){return Ml(So,{children:[Ml("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:[Jn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Jn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Jn("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:Jn("path",{d:"M9 18l6-6-6-6"})})]})}function dd(){return Jn(So,{children:"Go back"})}function ud(){return Jn(So,{children:"Secure card checkout"})}function vo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Co({content:e}){return Jn(So,{children:e===void 0?Jn(cd,{}):e})}function bo({content:e}){return Jn(So,{children:e===void 0?Jn(dd,{}):e})}function ia({content:e}){return Jn(So,{children:e===void 0?Jn(ud,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as pd,classifyTelemetryFailure as md,FloPayError as In,isCardHolderNamePlaceholder as xl,isMoneySettledOutcome as yd,isSetupIntentClientSecret as fd,isValidEmail as gd,resolveSetupFutureUsage as hd}from"@flopay/shared";var Pd="Checkout is temporarily unavailable. Please try again later.";function Li(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof In&&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 Bl(){return new In(Pd,"api_error",{code:"CheckoutInitializationFailed"})}function Ui(e){return!!e?.gateways?.worldpayCorporateGateway}function qr(e){return e?.status==="open"&&Ui(e)}function Fl(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card")||qr(r))||t&&e?.data.paypal?.publishableKey)}function Dl(e,t){if(t&&(!(e instanceof In)||e.type==="authentication_error"))return Li(e);if(!(e instanceof In&&vd(e))){if(!t&&!(e instanceof In)&&(e instanceof TypeError||e instanceof SyntaxError))return{...md(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof In)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof In))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function wo(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},l=xl(s.firstName,s.lastName);if(!gd(s.email))return Promise.reject(new In("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let f={};for(let[u,S]of Object.entries(s)){if(l&&u.endsWith("Name")||typeof S!="string")continue;let v=S.trim();v&&(f[u]=v)}return o=e.claimCheckoutSession(t,n,{accountData:f}),o.catch(()=>{}),o}}function Nl(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 zi(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Ol(e,t){let 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 ro(e){if(xl(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function qi(e,t){return t?{...e,...t}:e}function dn(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 Cd=[{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 Cd)if(n.test(t))return r;return e}function Fr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Dr(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 Ll(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function za(e){let t=Ll(e);return new In(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function qa(e){return e instanceof In||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Io(e){return Ll(e)?new In("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new In("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new In(pd,"api_error",{code:"checkout_processing_timeout"})}function sa(e,t){return e==="processing"||yd(e,t)}function Ul(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function zl(e,t){let n=e;if(fd(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new In(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 In(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}var bd=["apple_pay","google_pay"];function ql(e,t="automatic",n){let r=hd(n,bd,"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 Sd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function ji(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:Sd.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function la(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as op,PaymentAPI as di,SESSION_CREATE_TELEMETRY as ap}from"@flopay/js";import{buildCheckoutDisplayData as ip,classifyTelemetryFailure as Uc,FloPayError as Pn,isDetachedSessionEligible as sp,resolveBillingApiUrl as lp,resolveButtonsLayoutTheme as cp,resolveIdempotencyKey as xc,resolveTheme as zc,SDK_VERSION as qc,telemetryStatusClass as dp}from"@flopay/shared";import ks,{useCallback as hn,useEffect as pr,useMemo as Zn,useRef as Ft,useState as Wt}from"react";import{createContext as jl}from"react";var Xn=jl({flopay:null,paypalFlopay:null,billingApiUrl:""}),cr=jl({session:null,loading:!1,error:null});import{PaymentAPI as Hi}from"@flopay/js";import{classifyTelemetryFailure as Od,FloPayError as Wi,generateIdempotencyKey as Ld,isValidEmail as pa,normalizeGatewayEnvironment as Ud,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Vi,SDK_VERSION as zd}from"@flopay/shared";import{loadScript as qd}from"@paypal/paypal-js";import{useCallback as Sr,useContext as jd,useEffect as Ut,useMemo as ma,useRef as rt,useState as Vr}from"react";import{isValidEmail as wd}from"@flopay/shared";import{useCallback as $l,useEffect as Id,useRef as Kl,useState as Wl}from"react";import{jsx as Hl,jsxs as ca}from"react/jsx-runtime";function Dn(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 ko(){let[e,t]=Wl(null),n=Kl(null),r=Kl(0),o=$l((s,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:l}),new Promise(f=>{n.current=f})),[]),i=$l(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return Id(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function Ro({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=Wl(e.email?.trim()??""),f=wd(s.trim());return ca("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:[ca("div",{style:{fontWeight:700},children:["Continue with ",t]}),ca("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Hl("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:u=>l(u.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),ca("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Hl("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),ca("button",{type:"button",disabled:!f||o,onClick:()=>{n(Dn({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as kd}from"@flopay/shared";import{useContext as ja}from"react";function Hr(){return ja(Xn).flopay}function $i(){return ja(Xn).paypalFlopay??null}function Rd(){return ja(cr)}function Vl(){return ja(Xn).billingApiUrl||kd()}import{FLO_INSTRUMENT_SCHEMA_VERSION as _d}from"@flopay/shared";import{useCallback as Ed,useRef as $a}from"react";var Td={"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 Ad(e){return e==="stripe"||e==="paypal"?e:void 0}function Md(e){let t=Ad(e.provider),n={schemaVersion:_d,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Td[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 Ki=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function _o(e,t){let n=$a(e);n.current=e;let r=$a(new Set),o=$a(t),i=$a(t);return ta(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Ed(s=>{if(i.current!==t)return;let l=Md(s);if(l){if(Ki.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}Bt(()=>n.current?.(l))}},[t])}import{createContext as xd}from"react";var da=xd(null);function Ka(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Bd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Fd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Dd(){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 Nd(e){let t=Dd(),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 Ha(e){let t=globalThis[Fd];return Nd(t?.(e)??{})}function un(e){if(e)return e[Bd]}import{useCallback as Wr,useEffect as Gl,useRef as oo}from"react";function ua(e,t){let n=oo(0),r=oo(null),o=oo(null),i=oo(e),s=oo(t?.onHandoffObserved),l=oo(t?.defersMissingTerminal),f=oo(t?.onMissingTerminalDeferred);Gl(()=>{i.current=e,s.current=t?.onHandoffObserved,l.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)},[]),S=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]),v=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]),H=Wr(h=>{let C=o.current,se=h??C?.generation??n.current;(h===void 0||C?.generation===h)&&(u(C),o.current=null),r.current=se},[u]),$=Wr(h=>r.current===(h??n.current),[]),k=Wr(h=>o.current?.generation===h&&r.current!==h,[]),q=Wr(()=>{let h=o.current;h&&(u(h),!h.yieldedControl&&(h.yieldedControl=!0,s.current?.(h.method)))},[u]),K=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(l.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 Gl(()=>{let h=()=>{document.visibilityState==="visible"?K():q()};return document.addEventListener("visibilitychange",h),window.addEventListener("blur",q),window.addEventListener("focus",K),()=>{document.removeEventListener("visibilitychange",h),window.removeEventListener("blur",q),window.removeEventListener("focus",K),u()}},[u,q,K]),{startAttempt:S,finishAttempt:v,invalidateAttempt:H,isAttemptInvalidated:$,isAttemptCurrent:k,generationRef:n}}import{jsx as ao,jsxs as Gi}from"react/jsx-runtime";var Wa=45,$d=1e3,Kd=11e3,Hd={width:"100%",minHeight:Wa,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"},Wd={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 Vd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Wd[e.kind]??null}}function Yl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":bl(t)?"paypal_init_timeout":"paypal_init_failure"}function Gd(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 Yd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Jl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:l,currency:f,isSubscription:u,providerObjectType:S,approvalPresentation:v,onTokenizedBody:H,onComplete:$,onErrorChange:k,onDecline:q,onTechnicalFailure:K,isProcessing:h=!1,onLoadStateChange:C,onInitializationStateChange:se,allowAutomaticRetry:z=!0,onButtonClick:Ce,runBeforeButtonClick:J,session:ke,existingOrderId:qe,telemetry:Re,telemetryContext:it,onInstrument:zt,debug:me=!1}){let Me=Hr(),Pt=_o(zt,e),Te=ma(()=>{if(Me)return null;let m=Ha({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:zd,enabled:Re!==!1});return m.setCheckoutContext(it??{}),m.beginCheckout(it??{}),m},[n,Me,Re,it?.checkoutMode,it?.layout]),We=ma(()=>un(Me),[Me]);Ut(()=>()=>{Te&&Te.flush().catch(()=>{}).finally(()=>Te.destroy())},[Te]);let _e=ma(()=>({error:m=>{We?We.error(m):Te?.error(m),Pt({class:"technical_error",errorCode:m.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":m.errorCode,requestCategory:m.requestCategory,provider:m.provider})},log:m=>{We?We.log(m):Te?.log(m),Pt({class:"lifecycle",name:m.name,provider:m.provider})},performance:m=>{We?We.performance(m):Te?.performance(m)},terminal:m=>{We?We.terminal(m):Te?.terminal(m)},startTiming:()=>We?.now()??Te?.now()??0,elapsed:m=>We?.elapsed(m)??Math.max(0,(Te?.now()??m)-m)}),[Pt,We,Te]),ne=rt(null),je=rt(0),$e=rt(null),yt=rt(null),be=rt(null),ye=jd(da),le=rt(null);le.current||(le.current=Ka());let F=ye??le.current,Se=rt(null),Ue=rt(!1),[xe,V]=Vr(!1),[vt,ze]=Vr(!1),[Ae,Xe]=Vr(0),Be=rt(0),[Qe,De]=Vr(!1),Ct=rt(!1),Vt=rt(!1),[ft,Tt]=Vr(!1),[T,re]=Vr(!1),{request:Ne,collect:L,finish:we}=ko(),gt=rt({sessionId:e,required:!pa(r?.trim()||ke?.customer?.email?.trim())});gt.current.sessionId!==e&&(gt.current={sessionId:e,required:!pa(r?.trim()||ke?.customer?.email?.trim())});let Oe=gt.current.required,It=ma(()=>n.replace(/\/+$/,""),[n]),p=ke?.gateways?.paypal?.providerObjectType??S,g=p??(u?"subscription":"order"),[D]=Vr(oa),x=ke?.gateways?.paypal?.approvalPresentation??v,ee=La(D,x==="app_switch"?"app_switch":void 0,g),ut=p==="order"||p==="setup_token",fe=ma(()=>JSON.stringify([It,s,f,l??"",g,ut,ee,e,qe??""]),[It,s,f,l,qe,g,ut,ee,e]),Ke=rt(fe),X=Ke.current!==fe,qt=rt(me),bt=rt(null),[At,st]=Vr([]),ce=Sr(m=>{qt.current&&st(Ge=>[...Ge,`${new Date().toISOString().slice(11,23)} ${m}`])},[]);Ut(()=>{qt.current=me,me&&ce("debug:enabled"),bt.current?.setEnabled(me)},[ce,me]);let kn=rt(H),Nn=rt($),pn=rt(k),jt=rt(q),On=rt(K),Ln=rt(Ce),fn=rt(C),Mt=rt(se),Ve=rt(i),Le=rt(J),Rn=rt(ke),kt=rt(r),Un=rt(o),mn=rt(t),$t=rt(null),Zt=rt(new Map),Qn=rt(new Map),Hn=rt(!1);Ut(()=>(Hn.current=!0,()=>{Hn.current=!1}),[]),Ut(()=>{kn.current=H},[H]),Ut(()=>{Ve.current=i},[i]),Ut(()=>{Nn.current=$},[$]),Ut(()=>{pn.current=k},[k]),Ut(()=>{jt.current=q},[q]),Ut(()=>{On.current=K},[K]),Ut(()=>{Ln.current=Ce},[Ce]),Ut(()=>{fn.current=C},[C]),Ut(()=>{Mt.current=se},[se]),Ut(()=>{Le.current=J},[J]),Ut(()=>{Rn.current=ke},[ke]),Ut(()=>{kt.current=r},[r]),Ut(()=>{Un.current=o},[o]),Ut(()=>{mn.current=t},[t]),Ut(()=>{Be.current=Ae},[Ae]),Ut(()=>{Qe&&Se.current?.focus()},[Qe,Ae]);let Qt=Sr(()=>{window.setTimeout(()=>{Se.current?.focus()},0)},[]),Rt=Sr(()=>{V(!1),Xe(m=>m+1)},[]),en=Sr(()=>{De(!1),(ne.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ne.current)?.focus?.()},[]);Ut(()=>{!xe||!Ue.current||(Ue.current=!1,en())},[en,xe,Ae]);let nn=Sr((m,Ge)=>{let W=Ge?.popupBlocked??zr(m);W&&F.markBlocked();let gn=Na("PayPal",W,D.inAppBrowser),zn=On.current;if(zn){let Gt=W&&D.inAppBrowser?new Wi(gn,"api_error",{code:Ge?.code??"paypal_popup_blocked"}):m;zn("paypal",Gt,Ge);return}pn.current?.(gn)},[F,D.inAppBrowser]),Dt=Sr(m=>{let Ge=$e.current,W=yt.current;Ge===null||!W||(_e.log({...W,popupCapability:F.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:m}),_e.performance({...W,popupCapability:F.current(),stage:"overlay_return",durationMs:_e.elapsed(Ge),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:m}),$e.current=null)},[F,_e]),an=Sr((m,Ge,W)=>{let gn=yt.current;Dt("overlay_timeout"),gn&&_e.error({...gn,popupCapability:F.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),nn(Ge,{...W,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ee,terminalReason:"overlay_timeout"}),De(!0),Rt(),Qt()},[Dt,Qt,nn,F,ee,Rt,_e]),Ot=Sr(()=>{F.markAvailable();let m=yt.current;m&&(be.current=m.attempt,_e.log({...m,popupCapability:F.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[F,_e]),{finishAttempt:rn,generationRef:Nt,invalidateAttempt:G,isAttemptCurrent:er,isAttemptInvalidated:tr,startAttempt:nr}=ua(an,{onHandoffObserved:Ot}),tn=Sr(()=>(De(!1),nr("paypal")),[nr]),_n=Sr(m=>{G(m?.generation),m?.showRetry&&De(!0),m?.remount&&Rt(),m?.focus!==!1&&Qt()},[Qt,G,Rt]),vn=m=>{let Ge=$t.current;return Ge&&Qn.current.set(m,Ge),m};Ut(()=>{Ke.current!==fe&&(Ke.current=fe,Ct.current=!1,Vt.current=!1,V(!1),ze(!1),Tt(!1),Mt.current?.("loading"))},[fe]),Ut(()=>{Bt(()=>fn.current?.(xe&&!ft))},[xe,ft]);let he=Ud(l);Ut(()=>{let m={attempt:Nt.current+1,inAppBrowser:D.inAppBrowser,appFamily:D.appFamily,popupCapability:F.current(),presentationMode:ee},Ge=()=>({...yt.current??m,popupCapability:F.current()}),W={error:d=>_e.error({...d,...Ge()}),log:d=>_e.log({...d,...Ge()}),performance:d=>_e.performance({...d,...Ge()}),terminal:d=>_e.terminal({...d,...Ge()}),startTiming:_e.startTiming,elapsed:_e.elapsed},gn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",zn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(ce(`mount clientId=${gn} env=${l??"(unset)"}\u2192${he??"live"} ccy=${f} sub=${u}`),ce(`ua=${zn.slice(0,80)}${zn.length>80?"\u2026":""}`),!s){ce("FAIL: clientId empty \u2014 gateway misconfigured"),Tt(!0),W.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(!ne.current){ce("FAIL: containerRef not attached");return}je.current=W.startTiming(),W.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,En=!1,tt=()=>Gt||En,rr,Zr=!1,_t=()=>{rr=Ld(),rr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Zr=!0},Tn=null,mr=!1,Wn=null,Yt=!1,or=()=>{!Wn||Yt||(Yt=!0,Wn.close().catch(()=>{}))},An=!1,Rr=!1,Mn=ne.current,yr=null,fr=null,_r=[],qn=null,Vn=!1,Er=!1,xt=null,Cn=d=>{if(!d||typeof d.getBoundingClientRect!="function")return"(no rect)";let c=d.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},Gn=d=>{if(!d)return"(empty)";try{let c=new URL(d,typeof window>"u"?"https://localhost":window.location.href),I=c.pathname.toLowerCase();return I.includes("checkcaptcha")||I.includes("captcha")?`CAPTCHA(${c.host}${I})`:I.includes("risk")||I.includes("challenge")?`RISK(${c.host}${I})`:I.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${I}`.slice(0,100)}catch{return d.slice(0,80)}},Tr=d=>{let c=d.getAttribute("src"),I=d.getAttribute("srcdoc"),E=d.getAttribute("name"),Q=d.getAttribute("sandbox"),ae=[];return c&&ae.push(`src=${Gn(c)}`),I&&ae.push(`srcdoc[${I.length}ch]`),!c&&!I&&ae.push("src=(empty) srcdoc=(empty)"),E&&ae.push(`name=${E.slice(0,40)}`),Q!==null&&ae.push(`sandbox="${Q.slice(0,40)}"`),ae.join(" ")},Ar=d=>{if(!(d instanceof HTMLIFrameElement))return"";try{let c=d.contentDocument;if(!c)return"cd=null";let I=c.body?.children.length??0,E=c.body?.innerHTML.length??0,Q=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${I}children,${E}ch] head[${Q}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},He=[],sn=d=>{if(tt())return;let c=d.message??String(d.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(ce(`window:error ${c.slice(0,140)}`),He.push(c))},ln=d=>{if(tt())return;let c=d.reason instanceof Error?d.reason.message:String(d.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(ce(`window:rejection ${c.slice(0,140)}`),He.push(c))},bn={value:0},Qr=()=>{yr?.disconnect(),yr=null,fr?.disconnect(),fr=null;for(let d of _r.splice(0))clearTimeout(d);Er=!1,Vn&&typeof window<"u"&&(window.removeEventListener("error",sn),window.removeEventListener("unhandledrejection",ln)),Vn=!1},gr=()=>{if(!(Vn||tt()||An)){if(Vn=!0,He.length=0,bn.value=0,typeof window<"u"&&(window.addEventListener("error",sn),window.addEventListener("unhandledrejection",ln)),typeof PerformanceObserver<"u")try{fr=new PerformanceObserver(d=>{if(!tt())for(let c of d.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;bn.value+=1;let I=Math.round(c.duration);ce(`net ${I}ms ${c.name.slice(0,90)}`)}}),fr.observe({type:"resource",buffered:!0})}catch{}xt?.()}},Lr=()=>{qn&&(clearTimeout(qn),qn=null)},Sn=()=>{Qr(),Lr()},cn={setEnabled:d=>{d?gr():Qr()}};bt.current=cn,qt.current&&gr();let Mr=d=>{if(!d)return!1;let c=d.toLowerCase();return c.includes("zoid destroyed")||c.includes("destroyed all components")||c.includes("window closed")||c.includes("detected container element removed")},xn=d=>{if(tt()||Mr(d))return;let c=$r(d)??d;Bt(()=>pn.current?.(c))},w=(d,c)=>{if(Gt||mr)return;mr=!0,En=!0,Sn(),or();let I=Vd({kind:d,generationActive:!0,automaticRetryAllowed:z,automaticRetryUsed:Ct.current});if(I.action==="retry"){Ct.current=!0,V(!1),re(!1),ze(!0),Mt.current?.("retrying"),Tn=setTimeout(()=>{Gt||Xe(E=>E+1)},$d);return}if(V(!1),re(!1),ze(!1),Tt(!0),I.action!=="ignore"){if(Mt.current?.("exhausted"),I.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",c);return}if(I.report){let E=Fi({code:Yl(d,c),message:c},{inAppBrowser:D.inAppBrowser,handoffObserved:!1});E.popupBlocked&&F.markBlocked(),W.error({errorCode:E.popupBlocked?E.errorCode:I.report.errorCode,stage:I.report.stage,operationOutcome:I.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:E.terminalReason})}Vt.current||(Vt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Yl(d,c)))}};Tt(!1);let R=async(d,c=$t.current)=>{if(tt())return;let I=c?.sessionId??e;if(kn.current){await kn.current(d,{sessionId:I,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let E=W.startTiming();W.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Q=()=>{W.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"processing",durationMs:W.elapsed(E),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ae=Rn.current,Fe=c?.accountPatch?.email??kt.current,at=c?.accountPatch?.userId??ae?.customer?.id??ae?.accountData?.userId??"",pe=c?.accountPatch?.firstName??ae?.customer?.firstName??ae?.accountData?.firstName,b=c?.accountPatch?.lastName??ae?.customer?.lastName??ae?.accountData?.lastName,ie=await new Hi(It,{telemetry:!1}).processPayment(at,{sessionId:I,nonce:c?.nonce??mn.current,paymentMethodCategory:"paypal",tokenizedData:d,accountData:{userId:at,email:Fe??ae?.customer?.email??"",...pe?{firstName:pe}:{},...b?{lastName:b}:{},country:c?.accountPatch?.country??ae?.customer?.country??ae?.accountData?.country??void 0,zip:c?.accountPatch?.zip??ae?.customer?.zip??ae?.accountData?.zip??void 0}});if(ie.ok){if(En||Gt&&Hn.current)return;Q(),W.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Bt(()=>Nn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(tt())return;let te=await ie.json().catch(()=>null),A=te?.message??"PayPal payment failed.",Y=$r(A)??A;Q(),ie.status===400&&(typeof te?.declineCode=="string"||!Array.isArray(te?.fields))?W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ie.status===400||ie.status===422?W.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):W.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Yd(ie.status),failureCategory:ie.status>=500?"server_error":void 0}),xn(Y),Bt(()=>jt.current?.(dn("paypal",Y,{code:te?.code,declineCode:te?.declineCode})));return}catch(ae){if(tt())return;Q(),W.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Fe=ae instanceof Error?ae.message:"PayPal payment failed.",at=$r(Fe)??Fe;xn(at),Bt(()=>jt.current?.(dn("paypal",at)));return}},O=()=>new Wi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),_=d=>tt()?Promise.reject(O()):Promise.resolve(d),nt=async d=>{if(tt())throw O();Zr||_t();let c=$t.current,I=c?.sessionId??e,E=c?.nonce??mn.current;W.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Q;try{Q=await new Hi(It,{telemetry:!1}).createSessionIntent(I,E??"",ut?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Vi,paymentMethodId:null,intentKind:g==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:rr})}catch(ae){throw W.error({...Od(ae,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ae}if(tt())throw O();if(Q.provider!=="paypal"||Q.providerObjectType!==g)throw new Error(d);return W.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Q.providerObjectId},pt=(d,c)=>{let I=c?.nonce??mn.current;if(!I)return;let E=c?.sessionId??e,Q=ra(d)??Ur(d)??"provider_declined";new Hi(It,{telemetry:!1}).reportSessionIntentDecline(E,I,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Q}).catch(()=>{})},j=Ae;ce("loadScript:scheduled (deferred 1 tick)");let Ee=null,B=setTimeout(()=>{if(Gt){ce("loadScript:skipped (cancelled before defer ran)");return}ce("loadScript:start");let d=he==="live"?"production":he,c={};g==="subscription"?c={intent:"subscription",vault:!0}:g==="order"&&(c={intent:"capture"}),Ee=qd({clientId:s,currency:f,...c,...d?{environment:d}:{},...d==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let I=!1;Ee.then(E=>{if(I=!0,ce(`loadScript:resolved inactive=${tt()} ns=${!!E} buttons=${!!E?.Buttons}`),tt())return;if(!E?.Buttons){ce("FAIL: namespace missing Buttons factory"),w("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}W.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"provider_ready",durationMs:W.elapsed(je.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),W.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Q=async(ie,te)=>{if(tt()||Be.current!==j)return;let A=ie.vaultSetupToken??ie.subscriptionID??ie.orderID??"",Y=A?Qn.current.get(A):Zt.current.get(j);if(!(!Y||!er(Y.generation))&&rn(Y.generation)){Qn.current.delete(A),Zt.current.delete(Y.surfaceKey),Dt("approved");try{if(re(!0),Bt(()=>pn.current?.(null)),!A)throw new Wi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let N=Rn.current,ct=ro(Un.current??[N?.customer?.firstName,N?.customer?.lastName].filter(Boolean).join(" ")),Ie=Dn({email:Y.accountPatch?.email?.trim()||kt.current?.trim()||N?.customer?.email?.trim(),firstName:Y.accountPatch?.firstName?.trim()||ct.firstName,lastName:Y.accountPatch?.lastName?.trim()||ct.lastName});if(!pa(Ie.email)||!(Ie.firstName||Ie.lastName))try{let wn=Gd(await te?.order?.get?.());Ie=Dn({email:wn.email||Ie.email,firstName:wn.firstName||Ie.firstName,lastName:wn.lastName||Ie.lastName})}catch{}if((Ve.current||Oe)&&!pa(Ie.email)){let wn=await L("PayPal",Ie);if(!wn)return;Ie=wn}pa(Ie.email)&&(Y.accountPatch=Dn({...Y.accountPatch,...Ie}),await Ve.current?.(Ie));let ar;g==="setup_token"?ar={id:A,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Vi}:ut?ar={id:A,isPaypal:!0,gateway:"paypal",paymentMethodType:Vi}:ar={id:A,isPaypal:!0},await R(ar,Y)}catch(N){xn(N instanceof Error?N.message:"PayPal capture failed.")}finally{tt()||re(!1)}}},ae=ie=>{let te=qe?()=>_(qe):()=>nt(ie);return async()=>vn(await te())},Fe=E.Buttons({style:{layout:"horizontal",height:Wa,tagline:!1},...ee==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ie,te)=>{if(tt()){await te.reject();return}_t();let A=Le.current,Y={};if(A)try{let Ie=await A("paypal");if(tt()){await te.reject();return}if(!Ie.proceed){$t.current=null,Zt.current.delete(j),await te.reject();return}Y={sessionId:Ie.sessionId,accountPatch:Ie.accountPatch,nonce:Ie.nonce}}catch(Ie){ce(`onClick:runBeforeButtonClick rejected msg=${(Ie instanceof Error?Ie.message:String(Ie)).slice(0,120)}`),$t.current=null,Zt.current.delete(j),await te.reject();return}Bt(()=>Ln.current?.("paypal"));let N=tn(),ct={generation:N,surfaceKey:j,...Y};$t.current=ct,Zt.current.set(j,ct),yt.current={...m,attempt:N},await te.resolve(),W.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),$e.current=W.startTiming()},createOrder:g==="order"?ae("Failed to create PayPal order."):void 0,createSubscription:g==="subscription"?ae("Failed to create PayPal subscription."):void 0,createVaultSetupToken:g==="setup_token"?async()=>vn(await nt("Failed to create PayPal setup token.")):void 0,onApprove:Q,onCancel:()=>{if(tt())return;let ie=Zt.current.get(j)??$t.current;ie&&Zt.current.delete(ie.surfaceKey),$t.current=null,Dt("cancelled"),W.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ue.current=!0,_n({generation:ie?.generation,remount:!0,focus:!1})},onError:ie=>{if(tt()||Be.current!==j)return;let te=ie instanceof Error?ie.message:"PayPal failed to render.";if(ce(`onError rendered=${An} msg=${te.slice(0,120)}`),An){let A=Zt.current.get(j)??$t.current;if(A&&!er(A.generation)||!A&&tr())return;if(Mr(te)){rn(A?.generation);return}let{errorCode:Y,popupBlocked:N,providerDeclined:ct,terminalReason:Ie}=Fi(ie,{inAppBrowser:D.inAppBrowser,handoffObserved:A!=null&&be.current===A.generation});if(N&&F.markBlocked(),Dt(Ie),ct){W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ie}),pt(ie,A),Bt(()=>jt.current?.(dn("paypal",te))),A&&Zt.current.delete(A.surfaceKey),$t.current=null,rn(A?.generation);return}W.error({errorCode:Y,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ie}),A&&Zt.current.delete(A.surfaceKey),$t.current=null,_n({generation:A?.generation,remount:!0,showRetry:!0,focus:!0}),nn(ie,{code:"paypal_runtime_failed",popupBlocked:N,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ee,terminalReason:Ie});return}w(Mr(te)?"teardown":"pre_ready_callback",te)}}),at=Fe.isEligible();if(ce(`isEligible=${at}`),W.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!at){V(!1),w("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Rr=!0,Wn=Fe,xt=()=>{if(!Vn||Er||tt()||An)return;Er=!0,ce(`container:dims ${Cn(Mn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(yr=new MutationObserver(te=>{if(!tt()){for(let A of te)if(A.type==="childList")A.addedNodes.forEach(Y=>{if(!(Y instanceof Element))return;let N=Y.tagName.toLowerCase(),ct=(Y.getAttribute("title")??"").slice(0,40),Ie=N==="iframe"?` ${Tr(Y)}`:"";ce(`child+ ${N}${ct?` title="${ct}"`:""}${Ie} dims=${Cn(Y)}`)});else if(A.type==="attributes"&&A.target instanceof Element){let Y=A.target;if(Y.tagName.toLowerCase()!=="iframe")continue;let N=A.attributeName;(N==="src"||N==="srcdoc")&&ce(`attr~ iframe ${N}=${N==="srcdoc"?`[${(Y.getAttribute("srcdoc")??"").length}ch]`:Gn(Y.getAttribute("src"))} dims=${Cn(Y)}`)}}}),yr.observe(Mn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ie=te=>{if(tt()||An)return;let A=Mn.querySelectorAll("iframe"),Y=typeof document<"u"&&"hasStorageAccess"in document;ce(`watchdog:${te} container=${Cn(Mn)} children=${Mn.childElementCount} iframes=${A.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Y} paypalNetRequests=${bn.value}`),A.forEach((N,ct)=>{let Ie=(N.getAttribute("title")??"").slice(0,40);ce(` iframe[${ct}] ${Cn(N)}${Ie?` title="${Ie}"`:""} ${Tr(N)}`);let ar=Ar(N);ar&&ce(` ${ar}`)}),He.length===0&&ce(" (no PayPal/zoid window errors captured)")};_r.push(setTimeout(()=>ie("3s"),3e3)),_r.push(setTimeout(()=>ie("8s"),8e3)),_r.push(setTimeout(()=>ie("15s"),15e3))},xt(),ce("render:start");let b=W.startTiming();qn=setTimeout(()=>{tt()||An||(ce("watchdog:11s retryable render timeout"),w("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Kd);let lt=Fe.render(Mn);(async()=>{try{if(await lt,ce(`render:resolved inactive=${tt()}`),Sn(),tt()){or();return}An=!0,V(!0),ze(!1),Mt.current?.("ready"),W.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"checkout_render",durationMs:W.elapsed(b),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ie){let te=ie instanceof Error?ie.message:"PayPal failed to render.";ce(`render:rejected msg=${te.slice(0,120)}`),Sn(),w(Mr(te)?"teardown":"render_rejected",te)}})()}).catch(E=>{let Q=E instanceof Error?E.message:"PayPal operation failed.";ce(`provider:failed msg=${Q.slice(0,120)}`);let ae="script_rejected";I&&Mr(Q)?ae="teardown":I&&Rr&&(ae="render_rejected"),w(ae,Q)})},0);return()=>{Gt=!0,clearTimeout(B),Tn&&clearTimeout(Tn),Sn(),bt.current===cn&&(bt.current=null),or(),$e.current=null,yt.current=null}},[z,It,s,f,l,g,ee,ut,e,qe,Ae,_e,L,Oe,ce,Dt]);let et=me?Gi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ft?"#fef2f2":"#f3f4f6",border:`1px solid ${ft?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${xe} failed=${ft})`,At.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return mt&&!Z?me?oo("div",{children:et}):null:Wi("div",{children:[et,Ne&&oo(ko,{identity:Ne.identity,methodLabel:Ne.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:we,onCancel:()=>we(null)}),Wi("div",{"aria-hidden":ht||Ne?!0:void 0,style:ht||Ne?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ha},children:[!xe&&!ht&&oo("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"}}),oo("div",{ref:ne,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ha,display:"flex",opacity:xe?1:0},"aria-busy":_||h},Ae)]},Ae),Qe&&oo("button",{ref:Se,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:en,style:$d,children:"Try PayPal again"})]})}function Va(e){return oo(Yl,{...e})}function Jl(e){return oo(Yl,{...e})}import{jsx as Zl,jsxs as Gd}from"react/jsx-runtime";function _o({children:e,margin:t,icon:n=!0,styleOverride:r}){return Gd("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&&Zl("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Zl("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 Yd,resolveSessionCurrency as Jd}from"@flopay/shared";function Eo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Yi=":idempotency-key";function Ji(e,t){if(!Eo())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 Zi(e,t){if(!Eo())return null;try{let n=window.sessionStorage.getItem(e+Yi);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 Wa(e,t){if(Eo())try{Ji(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Ga(e,t){if(Wa(e,t),!!Eo())try{Zi(e,t)&&window.sessionStorage.removeItem(e+Yi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ya(e,t,n,r){if(Eo())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 Ja(e,t,n){if(Eo())try{window.sessionStorage.setItem(e+Yi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Gi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Zd(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([s],[l])=>s<l?-1:s>l?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let s=0;s<t.length;s++){let l=t.charCodeAt(s);n=r^Math.imul(n^l,597399067),r=o^Math.imul(r^l,2869860233),o=i^Math.imul(o^l,951274213),i=n^Math.imul(i^l,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 To(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=>Gi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Gi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Gi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Zd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Xl(e,t=!1){let n=To(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 Ql(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=Jd(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??Yd(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,S)=>`${u.code}:${u.type??""}`.localeCompare(`${S.code}:${S.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,S)=>`${u.code}:${u.type??""}`.localeCompare(`${S.code}:${S.type??""}`));if(i.length!==s.length)return!1;for(let[u,S]of i.entries()){let v=s[u];if(v===void 0||S.code!==v.code||S.type!==void 0&&S.type!==v.type||S.quantity!==v.quantity||S.totalAmount!==v.totalAmount||S.overrideAmount!==v.overrideAmount||S.currency!==v.currency)return!1}let l=[...t.couponCodes??[]].sort(),f=[...e.coupons??[]].sort();return l.length===f.length&&l.every((u,S)=>u===f[S])}import{resolveBillingApiUrl as Xd}from"@flopay/shared";import{useEffect as Wr,useMemo as Qd,useRef as ec,useState as tc}from"react";import{jsx as eu}from"react/jsx-runtime";function Za({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,s]=tc(e instanceof Promise?null:e),[l,f]=tc(t instanceof Promise||!t?null:t),u=ec(null),S=ec(null),v=Ro(r);Wr(()=>{v({class:"lifecycle",name:"checkout.mount"})},[v]),Wr(()=>{i&&v({class:"lifecycle",name:"sdk.initialize.ready"})},[v,i]),Wr(()=>{if(i)return pn(i)?.subscribe?.(v)},[v,i]),Wr(()=>{if(!(!l||l===i))return pn(l)?.subscribe?.(v)},[v,i,l]),Wr(()=>{if(!i)return;let k=pn(i);return u.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Wr(()=>{let k=!1;return e instanceof Promise?e.then(q=>{k||s(q)},()=>{k||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{k=!0}},[v,e]),Wr(()=>{let k=!1;if(!t){f(null);return}return t instanceof Promise?t.then(q=>{k||f(q)},()=>{k||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):f(t),()=>{k=!0}},[v,t]),Wr(()=>{if(!i||S.current===i)return;S.current=i;let k=pn(i);k?.log({name:"checkout.rendered",stage:"checkout_render"}),v({class:"lifecycle",name:"checkout.rendered"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(u.current??0),durationMode:"machine"})},[v,i]);let H=Xd(n?.billingApiUrl),$=Qd(()=>({flopay:i,paypalFlopay:l,billingApiUrl:H,emitInstrument:v}),[i,l,H,v]);return eu(Zn.Provider,{value:$,children:o})}var Xa="flopay_recent_completion_";function Ao(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Xa+e,JSON.stringify(t))}catch{}}function Xi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Xa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Xa+e),!1):!0}catch{return!1}}async function Qa(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 nc,PaymentAPI as ti}from"@flopay/js";import{classifyPaymentRejection as tu,FloPayError as wt,isAuthorizationOnlySession as nu,isSetupIntentClientSecret as ru,normalizeCheckoutFailureOutcome as rc,THREE_DS_CHALLENGE_WINDOW_MS as ac}from"@flopay/shared";var ya="card",ou=1e3;async function au(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 iu(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:l}=await e.confirmCardSetup(t,n);return{error:l,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 Gr(e){return new wt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Qi(){return new wt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function ts(e,t){return Object.assign(e,{checkoutMethod:t})}function Dr(e,t){let n=e instanceof wt?e:new wt(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 ma(e,t){try{return await e()}catch(n){throw Dr(n,t)}}function ic(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 su(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function ns(e){if(typeof document>"u"||typeof window>"u")throw new wt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw Gr();let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let v=new AbortController,H=()=>v.abort();e.signal?.aborted?v.abort():e.signal?.addEventListener("abort",H);let $=window.setTimeout(()=>v.abort(),n);try{let k=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:v.signal});if(!k.ok)return{status:"unknown"};let q=await k.json().catch(()=>null);return lu(q)}catch{return{status:"unknown"}}finally{window.clearTimeout($),e.signal?.removeEventListener("abort",H)}},i,s=()=>e.pollCompletionEndpoint!==!1?o():(i??(i=o()),i),l=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 S=null;try{S=new URL(e.billingApiUrl,window.location.href).origin}catch{S=null}try{let v=await new Promise((H,$)=>{let k=!1,q=0,K=0,h=0,b=!1,se=()=>{window.clearTimeout(q),window.clearInterval(K),window.clearTimeout(h),window.removeEventListener("message",ke),u.removeEventListener("load",ve),e.signal?.removeEventListener("abort",J)},U=async()=>{if(!(k||b)){b=!0;try{let qe=await s();if(k||!su(qe))return;k=!0,se(),H(qe)}finally{b=!1}}},ve=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(h),h=window.setTimeout(()=>{U()},250))},J=()=>{k||(k=!0,se(),$(Gr()))},ke=qe=>{if(qe.source!==u.contentWindow||S&&qe.origin!==S)return;let Re=qe.data;!Re||typeof Re!="object"||Re.source!=="flopay-vault-3ds-return"||k||(k=!0,se(),H(null))};q=window.setTimeout(()=>{k||(k=!0,se(),$(Qi()))},ac),e.pollCompletionEndpoint!==!1&&(K=window.setInterval(()=>{U()},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 v||await s()}finally{f.parentNode?.removeChild(f),l?.isConnected&&l.focus()}}async function Mo(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,i=t.nonce??t.session.clientSecret,s=new ti(n,{telemetry:!1}),l=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,f=new AbortController,u=new AbortController,S=()=>{f.abort(o.reason),u.abort(o.reason)};o.aborted?S():o.addEventListener("abort",S,{once:!0});let v=ns({billingApiUrl:n,sessionId:r,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:f.signal,pollCompletionEndpoint:!1}),H=s.waitForCheckoutSessionCompletion(r,{initialDelayMs:ou,nonce:i,statusUrl:l,continueAfterActionRequired:!0,timeoutMs:ac+15e3,signal:u.signal}),$;try{let q=await Promise.race([v,H]);if("data"in q)$=q;else{if(q.status==="declined")throw Ir({type:q.declineReason??"authorization_declined",gatewayErrorCode:q.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(q.status==="timeout")throw Qi();$=await H}}catch(q){if(o.aborted||q instanceof Error&&q.name==="AbortError")throw Gr(q);if(!(q instanceof wt)||q.code!=="three_ds_timeout"&&q.code!=="checkout_processing_timeout")throw q;try{$=await s.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:i,statusUrl:l,timeoutMs:5e3,signal:o})}catch(h){if(o.aborted)throw Gr(h);if(!(h instanceof wt)||h.code!=="checkout_processing_timeout")throw h}let K=$&&$r($,t.session);if(!Fr(K)&&K?.status!=="expired"){if(t.telemetry){let h=new ti(n);try{h.reportThreeDsAbandoned(r)}finally{h.destroy()}}throw Qi()}}finally{o.removeEventListener("abort",S),f.abort(),u.abort()}let k=$&&$r($,t.session);if(!Fr(k))throw wo(k);return{...Br(k,r),checkoutMethod:"card"}}function lu(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 Ir(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=jr(o)??o,s=ts(new wt(i,"api_error",{code:e?.code??rc(e?.outcome)??rc(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function es(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ei(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function sc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ei(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 l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||ei(l)))return l;let s=o.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let f=l,u=[f.stripeClientSecret,f.clientSecret];for(let S of u)if(typeof S=="string"&&S.length>0&&(!t?.requirePaymentIntentClientSecret||ei(S)))return S}}}}async function cu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=sc(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let l=(await new ti(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ei(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function xo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),f=t??n.id,u=r??n.clientSecret,S=n.customer?.id??n.accountData?.userId??"",v=n.customer?.email??n.accountData?.email??"",H=n.customer?.firstName??n.accountData?.firstName??"",$=n.customer?.lastName??n.accountData?.lastName??"",k=n.customer?.country??n.accountData?.country??void 0,q=n.customer?.zip??n.accountData?.zip??void 0,h=await new ti(l,s===!1?{telemetry:!1}:void 0).processPayment(S,{sessionId:f,nonce:u,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:S,email:v,firstName:H,lastName:$,country:k,zip:q},returnUrl:i??es(n)});if(h.ok){let U=typeof h.json=="function"?await h.json().catch(()=>null):null;if(nu(n)||U?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof U?.paymentId=="string"?U.paymentId:n.paymentId,sessionId:typeof U?.sessionId=="string"?U.sessionId:f,authorizationExpiresAt:typeof U?.authorizationExpiresAt=="string"?U.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:sa(o),checkoutMethod:oc(o,n)}};let ve=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ve?{paymentIntentId:ve}:{},paymentMethodId:sa(o),checkoutMethod:oc(o,n)}}}let b;try{b=await h.json()}catch(U){throw new wt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:h.status,cause:U})}if(b?.type==="3ds_required"&&typeof b.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:b.nextActionRedirectUrl};if(b?.type==="paypal_redirect_required"||b?.type==="3ds_required"){let U=sc(b);if(!U)throw new wt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:h.status});return{type:b.type,threeDSecureToken:U,paymentMethodId:b.paymentMethodId}}if(b?.gatewayErrorCode==="authentication_required"){let U=await cu({billingApiUrl:l,sessionId:f,nonce:u,responseJson:b});if(U)return U;throw ts(new wt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let se=new wt(b?.message??"Payment failed. Please try again.","api_error",{code:b?.code??b?.gatewayErrorCode,declineCode:b?.declineCode??b?.gatewayDeclineReason,statusCode:h.status});throw Object.assign(se,{telemetryOutcome:tu(h.status,b)})}async function ni(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:f,signal:u}){let S=t?.getRawProvider();if(!S)throw Dr(new wt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw ts(new wt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let v=ru(e.threeDSecureToken),H=null,$=e.paymentMethodId,k=await ma(()=>au(S,e.threeDSecureToken,v),"card");if(k){if(k.error)throw Dr(new wt(k.error.message??`Failed to retrieve 3DS ${v?"setup":"payment"} status.`,"api_error",{code:k.error.code}),"card");let K=k.intent;!$&&K?.payment_method&&(typeof K.payment_method=="string"?$=K.payment_method:"id"in K.payment_method&&($=K.payment_method.id??void 0))}let q=$?await ma(()=>iu(S,e.threeDSecureToken,{payment_method:$,return_url:l??es(s)??window.location.href},v),"card"):null;if(q){if(q.error)throw Dr(new wt(q.error.message??"3DS authentication failed.","api_error",{code:q.error.code}),"card");H=q.intent}else{let K=await ma(()=>S.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(K.error)throw Dr(new wt(K.error.message??"3DS authentication failed.","api_error",{code:K.error.code}),"card");H=(v?K.setupIntent:K.paymentIntent)??null}if(H&&(H.status==="requires_capture"||H.status==="succeeded"||H.status==="processing")){let K=await xo({billingApiUrl:o,sessionId:i,session:s,telemetry:f,tokenizedData:{id:H.id,type:"card",threeDSecureActionResultTokenId:H.id},returnUrl:l});return K.type==="success"?{...K.result,paymentIntentId:K.result.paymentIntentId??H.id,paymentMethodId:K.result.paymentMethodId??$}:K.type==="next_action_required"?Mo(K,{billingApiUrl:o,sessionId:i??s.id,session:s,signal:u}):ni(K,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:f,signal:u})}throw Dr(new wt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let v=(n??t)?.getRawProvider();if(!v)throw Dr(new wt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:$}=await ma(()=>v.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if($)throw Dr(new wt($.message??"PayPal authorization failed.","api_error",{code:$.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:H}=await ma(()=>v.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??es(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(H)throw Dr(new wt(H.message??"PayPal authorization failed.","api_error",{code:H.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new wt("Unsupported payment redirect state.","api_error")}function fa(e){if(e instanceof wt){let r=jr(e.message);return r&&r!==e.message?Object.assign(new wt(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=jr(t)??t;return new wt(n,"api_error")}function rs(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||zr(e.data.session);if(!t&&!n&&!r)throw new wt("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 oc(e,t){return e?e.isPaypal?"paypal":"card":t&&zr(t)?"card":void 0}async function os({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,l]=await Promise.all([nc(e,{billingApiUrl:n,locale:r,telemetry:o}),i?nc(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 wt("The payment provider did not initialize.","authentication_error");let f=null;return i?f=l:t&&(f=s),{flopay:s,paypalFlopay:f}}import{PaymentAPI as Fo,PciVaultCardCapture as du,toStripeAppearance as uu}from"@flopay/js";import{COUNTRY_OPTIONS as pu,classifyPaymentRejection as mu,FloPayError as pr,filterStripeMethodsByCountry as yu,getPostalCodeExample as fu,getPostalCodeLabel as ps,getStateFromPostalCode as lc,getStateLabel as as,getStateOptions as gu,getStripeMethodDisplayName as Pa,isAuthorizationOnlySession as is,isAVSFieldVisible as ot,isPostalCodeSupported as hu,isSetupIntentClientSecret as ss,isValidEmail as fn,isValidPostalCode as Pu,needsStripeMethodExplicitConfirm as cc,normalizeCheckoutFailureOutcome as vu,partitionStripeMethods as bu,randomUuidV4 as Cu,resolveAVSConfig as Su,resolveButtonsLayoutTheme as wu,resolveSetupFutureUsage as Sc,resolveTheme as Iu,stripeExpressMethodToOptionKey as ku}from"@flopay/shared";import{ExpressCheckoutElement as wc,PaymentElement as Ru,Elements as ao,useElements as gs,useStripe as hs}from"@stripe/react-stripe-js";import _u,{useCallback as Je,useContext as No,useEffect as St,useMemo as ft,useRef as oe,useState as ue}from"react";function Bo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ri(e,t){if(e)return{error:n=>e.error(Bo(t,n)),log:n=>e.log(Bo(t,n)),performance:n=>e.performance(Bo(t,n)),terminal:n=>e.terminal(Bo(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 Do,jsx as y,jsxs as Xe}from"react/jsx-runtime";var kr="flopay_stripe_resume",dc="flopay_wallet_resume",Ic="fw1",Eu="fw2",kc=300*1e3,Tu=900,Au=25e3,Mu=25e3,xu=1e4,Rc=["payment_intent","payment_intent_client_secret","redirect_status"],ur={provider:"paypal",paymentMethodCategory:"paypal"},oi={},ls={};function Ht(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 Ps(e){return`${Eu}:${e}`}function ai(e){return Ht(Ps(e))}function ii(e,t){if(typeof window>"u")return null;let n=Ps(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>kc||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(ai(e),null):o}catch{return ai(e),null}}function Bu(e){return Ht(Ps(e.sessionId),e)}function uc(e,t,n){let r=ii(e,t);return!r||r.clientSecret!==n?!1:ai(e)}function cs(e,t,n){if(typeof window>"u")return;ii(e,t)?.clientSecret===n&&ai(e)}function Fu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ds(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":ia(e.status),o=Fu(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([Ul(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},xu),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Du(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function _c(e){return e instanceof pr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function si(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Fo(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw _c(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ha="flopay_paypal_resume",ga=new Map;function Ec(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(ha);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function Nu(){if(typeof window>"u")return!1;let[e,t]=vs();return e?Ec(t)!==null:!1}function vs(){let e=new URLSearchParams(window.location.search);return Rc.map(t=>e.get(t))}function bs(){let e=new URL(window.location.href);for(let t of Rc)e.searchParams.delete(t);return e.toString()}function Ou(){Ht(ha),window.history.replaceState({},"",bs())}var Lu=250,mc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Uu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Cs(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 li({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Fo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function zu(e){return e instanceof pr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function us(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Tc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=no(n),s=i.firstName?i:no(r?.name);return Nn({email:fn(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function qu({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let s=Tc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return fn(s.email)?s:i(o,s)}var va=180,yc=`flopay-card-enter ${va}ms cubic-bezier(0, 0, 0.2, 1) both`,fc=`flopay-card-exit ${va}ms cubic-bezier(0.4, 0, 0.2, 1) both`,ju=`flopay-buttons-enter ${va}ms cubic-bezier(0, 0, 0.2, 1) both`,$u=`flopay-buttons-exit ${va}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Ku(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ss(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 Hu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Vu(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 ms={width:"100%",minHeight:oa,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 Wu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function gc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ys(e){return e==="paypal"?"PayPal":Pa(e)}function Gu(e){let t=fu(e);return`Enter a valid ${ps(e)}${t?` (e.g. ${t})`:""}`}function Yu(e,t,n){let r=hu(e),o=t.trim(),i=n&&r,s=i&&!o,l=i&&!!o&&!Pu(e,o);return{visible:n,supported:r,required:i,empty:s,malformed:l}}function Ju(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!fn(n);return{required:t,empty:r,malformed:o,value:n}}function hc(e,t){return t instanceof pr?t:new pr(t instanceof Error?t.message:`${Wu(e)} before-click hook failed.`,"validation_error")}function Zu(e){return typeof e=="number"?`${e}px`:e}function ws(e){return y(Xu,{...e})}function Pc({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:f,onTechnicalFailure:u,runBeforeButtonClick:S,billingName:v,onBuyerIdentityReady:H,onLoadStateChange:$,placeholderBorderRadius:k,popupCapabilityOwner:q,externalTelemetryContext:K,presentationMode:h}){let b=Kr(),{emitInstrument:se}=No(Zn),U=hs(),ve=gs(),J=ft(()=>ri(pn(b),K),[K,b]),[ke,qe]=ue("loading");St(()=>{$?.(ke)},[ke,$]);let[Re,it]=ue(!1),Ut=oe(!1),me=!fn(n?.trim())||!v?.trim(),{request:Me,collect:gt,finish:Te}=Io(),Ve=oe(!1),_e=oe(null),ne=oe(null),[je,$e]=ue(0),[pt,Ce]=ue(!1),ye=oe(!1),le=oe(new Map),{startAttempt:F,finishAttempt:Se,invalidateAttempt:Ue,isAttemptInvalidated:xe,isAttemptCurrent:W,generationRef:ht}=da((_,re,Ne)=>{u?.(_,re,{...Ne,popupBlocked:Ne?.popupBlocked??Ur(re),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h,terminalReason:"overlay_timeout"}),Ce(!0),$e(L=>L+1)},{onHandoffObserved:()=>{q.markAvailable(),J?.log({name:"provider.popup.opened",stage:"overlay_open",...ur,attempt:ht.current})}});St(()=>{pt&&ne.current?.focus()},[pt,je]);let ze=Je(()=>{$e(_=>_+1)},[]),Ae=Je((_,re,Ne)=>{Ue(Ne),u?.("paypal",_,{code:re,popupBlocked:Ur(_),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h}),Ce(!0),ze()},[Ue,u,h,ze]),Ze=Je(()=>{window.setTimeout(()=>{(_e.current?.querySelector("iframe")??_e.current)?.focus()},0)},[]);St(()=>{ye.current&&(ye.current=!1,Ze())},[Ze,je]);let Be=Je(()=>{Ce(!1),i?.(null),Ze()},[Ze,i]);St(()=>{if(!U||Ve.current)return;let[_,re,Ne]=vs();if(!_||!re)return;let L=Ec(re);if(!L)return;Ve.current=!0;let we=!0,yt=ga.get(re);yt||(yt=Ne==="failed"?Promise.resolve(null):Promise.resolve().then(()=>U.retrievePaymentIntent(re)),ga.set(re,yt));let Oe={accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce},It=()=>{J?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...ur,requestCategory:"provider_sdk"})};return J?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...ur}),(async()=>{try{it(!0);let p=await yt;if(!we)return;if(p?.error){ga.delete(re),It(),i?.(p.error.message??"Failed to retrieve PayPal payment status.");return}if(Ou(),ga.delete(re),Ne==="failed"){let D="PayPal payment was declined. Please try again.";J?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}),i?.(D),f?.(un("paypal",D));return}let g=p?.paymentIntent;if(g&&g.id!==_){It(),i?.("Failed to match the returned PayPal payment.");return}if(g&&(g.status==="requires_capture"||g.status==="succeeded")){let D=typeof g.payment_method=="string"?g.payment_method:g.payment_method?.id;o({id:D??g.id,type:"card",threeDSecureActionResultTokenId:g.id,isPaypal:!0},{...Oe,presentationMode:"redirect"})}else{let D="PayPal payment was not completed. Please try again.";J?.terminal({outcome:g?.status==="canceled"?"payment_cancelled":"payment_declined",...ur,terminalReason:g?.status==="canceled"?"cancelled":"provider_declined"}),i?.(D),f?.(un("paypal",D))}}catch(p){if(!we)return;ga.delete(re),It(),i?.(p instanceof Error?p.message:"Failed to complete PayPal payment.")}finally{we&&it(!1)}})(),()=>{we=!1,Ve.current=!1}},[U,o,i,f,J]);let Qe=Je(async(_=!1)=>{let re=S?await S("paypal"):{proceed:!0};if(!re.proceed)return le.current.delete(je),!1;let Ne=F("paypal");return le.current.set(je,{generation:Ne,accountPatch:re.accountPatch,sessionId:re.sessionId,nonce:re.nonce}),Ce(!1),J?.log({name:`provider.${_?"redirect.started":"handoff.requested"}`,stage:_?"redirect":"overlay_open",...ur,attempt:Ne}),l?.("paypal"),!0},[l,J,S,F,je]),De=Je(async _=>{if(s||Re||!await Qe()){_.reject();return}_.resolve()},[s,Qe,Re]),Pt=Je(async _=>{if(!U||!ve)return;let re=le.current.get(je);if(re&&!W(re.generation)){le.current.delete(je);return}if(!re&&xe()||re&&!Se(re.generation))return;re||Se();let Ne=re??null;if(le.current.delete(je),!Ne&&S){let M=await S("paypal");if(!M.proceed){_.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Ne={accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}}let L=Ne?.sessionId??e,we=Ne?.nonce??t,yt=await qu({event:_,prepared:Ne,email:n,billingName:v,methodLabel:"PayPal",collect:gt});if(!yt){_.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Oe=yt.email,It={...Ne?.accountPatch,...Nn(yt,!0)};try{if(it(!0),i?.(null),!L||!fn(Oe))throw new Error("Missing sessionId or email for PayPal payment");await H?.(yt);let M=U.createPaymentMethod,{error:p,paymentMethod:g}=await M({type:"paypal"});if(p){Ae(p,"stripe_paypal_create_payment_method_failed",re?.generation),_.paymentFailed({reason:"fail"});return}let D=await si(r,se,L,we??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:g?.id??null,intentKind:"payment"});if(D.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let x=D.clientSecret,ee={return_url:bs()};if(g?.id&&(ee.payment_method=g.id),!Ht(ha,{clientSecret:x,sessionId:L,nonce:we,accountPatch:It})&&h==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:fe,paymentIntent:Ke}=await U.confirmPayment({clientSecret:x,confirmParams:ee,redirect:"if_required"});if(fe){if(Ht(ha),Na(fe)){let zt=fe.message??"Your payment was declined.";J?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}),i?.(zt),f?.(un("paypal",zt,{code:Lr(fe),declineCode:na(fe)})),await li({billingApiUrl:r,sessionId:L,nonce:we,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Lr(fe)??"provider_declined"}})}else Ae(fe,"stripe_paypal_confirm_failed",re?.generation);return}Ht(ha);let Z=typeof Ke?.payment_method=="string"?Ke.payment_method:Ke?.payment_method?.id;o({id:Z??Ke?.id,type:"card",threeDSecureActionResultTokenId:Ke?.id,isPaypal:!0},{accountPatch:It,paymentMethodCategory:"paypal",presentationMode:h,sessionId:L,nonce:we});return}catch(M){Ae(M,"stripe_paypal_failed",re?.generation)}finally{it(!1)}},[U,ve,e,t,n,v,gt,H,r,se,o,i,f,S,Ae,Se,W,xe,J,h,je]),Wt=Je(async()=>{if(!(Ut.current||s||Re||!U||!ve)){Ut.current=!0,it(!0);try{if(!await Qe(!0))return;await Pt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Ut.current=!1,it(!1)}}},[ve,Pt,s,Qe,U,Re]),mt=h==="redirect"?y("button",{type:"button",disabled:s||Re,onClick:()=>{Wt()},style:{width:"100%",minHeight:oa,border:"1px solid #d1d5db",borderRadius:k??8,background:"#ffc439",color:"#111827",cursor:s||Re?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):y(wc,{onReady:_=>qe(Fi(_,["paypal"])),onLoadError:()=>{qe("load_error"),Cs(J,"paypal","paypal","provider_error")},onClick:De,onConfirm:Pt,onCancel:()=>{let _=le.current.get(je);le.current.delete(je),J?.terminal({outcome:"payment_cancelled",...ur,terminalReason:"cancelled",..._?{attempt:_.generation}:{}}),Ue(_?.generation),Ce(!1),ye.current=!0,ze()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:me,emailRequired:me,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},je),Et=Xe(Do,{children:[Xe("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:ne,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Be,style:ms,children:"Try PayPal again"}),Me&&y(ko,{identity:Me.identity,methodLabel:Me.methodLabel,onComplete:Te,onCancel:()=>Te(null)},Me.id),y("div",{style:{display:Me?"none":void 0},children:mt})]}),Re&&!Me&&y(Sr,{status:"processing"})]});return h==="redirect"?Et:y(Di,{state:ke,placeholderTestId:"flopay-paypal-placeholder",borderRadius:k,children:Et})}function vc(e){return e==="apple_pay"||e==="google_pay"}function bc({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:f,onDecline:u,onTechnicalFailure:S,runBeforeButtonClick:v,billingName:H,onBuyerIdentityReady:$,onLoadStateChange:k,placeholderBorderRadius:q,popupCapabilityOwner:K,externalTelemetryContext:h}){let b=Kr(),{emitInstrument:se}=No(Zn),U=hs(),ve=gs(),J=ft(()=>ri(pn(b),h),[h,b]),[ke,qe]=ue("loading");St(()=>{k?.(ke)},[ke,k]);let[Re,it]=ue(!1),Ut=oe(!fn(n?.trim())||!H?.trim()).current,{request:me,collect:Me,finish:gt}=Io(),Te=oe(null),Ve=oe(null),[_e,ne]=ue(0),[je,$e]=ue(!1),[pt,Ce]=ue(()=>ii(e,t)?"blocked":"idle"),[ye,le]=ue("google_pay"),F=oe(null),Se=oe(!0),Ue=oe(!1),xe=oe("google_pay"),W=oe("google_pay"),ht=oe(null),ze=oe(null),Ae=oe(new Set),Ze=oe(null);St(()=>(Se.current=!0,()=>{Se.current=!1;for(let M of Ae.current)window.clearTimeout(M);Ae.current.clear()}),[]);let Be=oe(new Map),{startAttempt:Qe,finishAttempt:De,invalidateAttempt:Pt,isAttemptInvalidated:Wt,isAttemptCurrent:mt,generationRef:Et}=da((M,p,g)=>{S?.(M,p,{...g,popupBlocked:g?.popupBlocked??Ur(p),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),le(M),$e(!0),ne(D=>D+1)},{onHandoffObserved:M=>{K.markAvailable(),J?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Et.current,...M==="apple_pay"||M==="google_pay"?{walletType:M}:{}})},defersMissingTerminal:vc,onMissingTerminalDeferred:(M,p)=>{let g=J?.now()??globalThis.performance?.now()??Date.now(),D=Ze.current,x=D?.generation===p?D.startedAt:g;J?.performance({stage:"overlay_return",durationMs:Math.max(0,g-x),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:p,...vc(M)?{walletType:M}:{}}),J?.flush?.().catch(()=>{})}});St(()=>{je&&Ve.current?.focus()},[je,_e]);let _=Je(()=>{ne(M=>M+1)},[]),re=Je((M,p,g,D,x=!1)=>{Pt(D),S?.(M,p,{code:g,popupBlocked:Ur(p),telemetryReported:x,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),le(M),$e(!0),_()},[Pt,S,_]),Ne=Je(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);St(()=>{Ue.current&&(Ue.current=!1,Ne())},[Ne,_e]);let L=Je(()=>{$e(!1),l?.(null),Ne()},[Ne,l]),we=Je(()=>{F.current?.()},[]);St(()=>{let M=ii(e,t);if(!M)return;let p=!1,g=!1,D=async()=>{if(!g){g=!0,p||Ce("checking");try{let x=await pc(U,M.clientSecret,Ae.current);if(p)return;let ee=ds(x,M.providerObjectId,ss(M.clientSecret));if(ee.kind==="confirmed"){if(!uc(e,t,M.clientSecret))return;F.current=null,Ce("idle"),s({id:ee.paymentMethodId,type:"card",threeDSecureActionResultTokenId:ee.intentId},{...M.accountPatch?{accountPatch:M.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(ee.kind==="terminal"){cs(e,t,M.clientSecret),F.current=null,Ce("idle"),le(M.paymentMethodType),$e(!0),_();return}Ce("blocked")}catch{p||Ce("blocked")}finally{g=!1}}};return F.current=D,Ce("blocked"),()=>{p=!0,F.current===D&&(F.current=null)}},[t,s,_,e,U]);let yt=Je(async M=>{let p=!1,g=We=>{p||(p=!0,M.paymentFailed({reason:"fail",...We?{message:We}:{}}))};if(!U||!ve){g();return}let D=Be.current.get(_e);if(D&&!mt(D.generation)){Be.current.delete(_e),g();return}if(!D&&Wt()){g();return}if(D&&!De(D.generation)){g();return}D||De();let x=M.expressPaymentType??D?.method??xe.current,ee=D??null,vt=gc(x),fe;x==="apple_pay"?fe="apple_pay":x==="google_pay"&&(fe="google_pay");let Ke=D?.generation??Et.current,Z=J,zt=Z?.now()??globalThis.performance?.now()??Date.now(),bt=new AbortController,Tt=!1,st=!1,ce=null,Rn=e,On="processing",mn="other",qt="provider_runtime",Ln,Un=new Promise((We,Le)=>{Ln=Le}),gn=window.setTimeout(()=>{Tt=!0,bt.abort(),Ln(oi)},Au),At=async(We,Le,_n)=>{On=We,mn=Le,qt=Le==="intent_create"||Le==="session_claim"?"transport_error":"provider_runtime";let kt=Z?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([_n,Un])}finally{let zn=Z?.now()??globalThis.performance?.now()??Date.now();Z?.performance({stage:We,durationMs:Math.max(0,zn-kt),durationMode:"machine",requestCategory:Le,paymentMethodCategory:"wallet",provider:"stripe",...Tt?{statusClass:"timeout"}:{}})}};try{if(it(!0),l?.(null),!ee&&v){let he=await At("processing","other",v(vt));if(!he.proceed){g();return}ee={accountPatch:he.accountPatch,sessionId:he.sessionId,nonce:he.nonce}}let We=ee?.sessionId??e;Rn=We;let Le=ee?.nonce??t,_n=ht.current??ee?.accountPatch,kt=Tc({event:M,fallbackEmail:_n?.email??n,fallbackName:[_n?.firstName,_n?.lastName].join(" ").trim()||H});if(!fn(kt.email)){g("Buyer details are required."),Me(ys(x),kt).then(he=>{he&&(ht.current=he)});return}ht.current=null;let zn={...ee?.accountPatch,...Nn(kt,!0)};await At("processing","session_claim",Promise.resolve($?.(kt)));let{error:yn}=await At("tokenization","provider_sdk",ve.submit());if(yn){g(),re(x,yn,"stripe_wallet_submit_failed",D?.generation);return}if(!We)throw new Error("Missing sessionId or email for payment.");let jt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:x,paymentMethodId:null,intentKind:o},Xt=JSON.stringify({sessionId:We,nonce:Le??"",request:jt}),Qn=ze.current,Hn=Qn?.retryIdentity===Xt?Qn.authorizationAttemptId:Cu();ze.current={authorizationAttemptId:Hn,retryIdentity:Xt};let Qt=await At("processing","intent_create",si(r,se,We,Le??"",{...jt,authorizationAttemptId:Hn},{signal:bt.signal}));if(Qt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Rt=Qt.clientSecret,en=Bu({createdAt:Date.now(),sessionId:We,...Le?{nonce:Le}:{},clientSecret:Rt,providerObjectId:Qt.providerObjectId,paymentMethodType:x,accountPatch:zn});window.clearTimeout(gn),st=!0,Z?.performance({stage:"callback",durationMs:Math.max(0,(Z?.now()??globalThis.performance?.now()??Date.now())-zt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let nn=Z?.now()??globalThis.performance?.now()??Date.now(),Ft={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...fe?{walletType:fe}:{},attempt:Ke},an=!1,Nt=null;Z?.log({name:"payment.provider_confirmation.started",...Ft}),ce=window.setTimeout(()=>{ce!==null&&Ae.current.delete(ce),an=!0;let he=Z?.now()??globalThis.performance?.now()??Date.now();Z?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Ft,operationOutcome:"watchdog_expired",durationMs:Math.max(0,he-nn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Z?.flush?.().catch(()=>{}),Nt?.()},Mu),Ae.current.add(ce);let rn=(he,et)=>{ce!==null&&(window.clearTimeout(ce),Ae.current.delete(ce),ce=null);let m=Z?.now()??globalThis.performance?.now()??Date.now(),Ge=Math.max(0,m-nn),V=he;an&&(he==="resolved"?V="resolved_late":he==="returned_error"?V="returned_error_late":V="rejected_late");let hn=et??(he==="resolved"?"approved":"provider_error");return Z?.log({name:"payment.provider_confirmation.returned",...Ft,operationOutcome:V,terminalReason:hn}),Z?.performance({...Ft,durationMs:Ge,durationMode:"buyer",operationOutcome:V,terminalReason:hn}),{durationMs:Ge,operationOutcome:V,terminalReason:hn}},Dt=!1,G=!1,er=he=>{if(!he||typeof he!="object")return null;let et=he;if(et.error)return null;let m=et.setupIntent??et.paymentIntent,Ge=ds(m??null,void 0,!!et.setupIntent);return Ge.kind==="confirmed"?Ge:null},tr=he=>{if(Dt||D&&Et.current!==D.generation)return;let et=er(he);if(!et)return;if(en&&!uc(We,Le,Rt)){Dt=!0;return}let{intentId:m,paymentMethodId:Ge}=et;Dt=!0,G=!0,ze.current=null,F.current=null,Se.current&&(Ce("idle"),it(!1));let V=`${Ic}:${We}`;Ht(V,{createdAt:Date.now(),sessionId:We,nonce:Le,accountPatch:zn,paymentMethodId:Ge,providerIntentId:m,paymentMethodType:x});try{s({id:Ge,type:"card",threeDSecureActionResultTokenId:m},{accountPatch:zn,paymentMethodCategory:"wallet",sessionId:We,nonce:Le})}finally{Ht(V)}},nr=!1;Nt=async()=>{if(!(nr||Dt||G)){nr=!0,Se.current&&Ce("checking");try{let he=await pc(U,Rt,Ae.current);if(Dt||G)return;let et=ss(Rt),m=ds(he,Qt.providerObjectId,et);if(m.kind==="confirmed"){tr(et?{setupIntent:he}:{paymentIntent:he});return}if(m.kind==="terminal"){if(G=!0,cs(We,Le,Rt),ze.current=null,F.current=null,!Se.current)return;Ce("idle"),g(),re(x,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",D?.generation,!0);return}Se.current&&!G&&(Ce("blocked"),it(!1))}catch{Se.current&&!G&&(Ce("blocked"),it(!1))}finally{nr=!1}}},F.current=Nt;let tn,En;try{let he=await(ss(Rt)?U.confirmSetup({elements:ve,clientSecret:Rt,redirect:"if_required"}):U.confirmPayment({elements:ve,clientSecret:Rt,redirect:"if_required"}));if(!he||typeof he!="object"||(tn=he,!tn.error&&!er(tn)))throw ls;En=rn(tn.error?"returned_error":"resolved",tn.error&&Na(tn.error)?"provider_declined":void 0)}catch(he){let et=he===ls,m=rn(et?"returned_error":"rejected");if(Z?.error({...et?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:qi(he),...Ft,operationOutcome:m.operationOutcome,durationMs:m.durationMs,statusClass:"unknown",terminalReason:m.terminalReason}),!Se.current||Dt)return;await Nt?.();return}let bn=tn.error;if(bn){if(!Se.current||Dt)return;if(Na(bn)){G=!0,cs(We,Le,Rt),ze.current=null,F.current=null,Ce("idle");let he=bn.message??"Your payment was declined.";g(he),l?.(he),u?.(un(vt,he,{code:Lr(bn),declineCode:na(bn)})),li({billingApiUrl:r,sessionId:We,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:x,providerDeclineReason:Lr(bn)??"provider_declined",...Qt.intentKind==="payment"&&Qt.providerObjectId.startsWith("pi_")?{providerIntentId:Qt.providerObjectId}:{}}})}else Z?.error({...qi(bn),...Ft,operationOutcome:En.operationOutcome,durationMs:En.durationMs,statusClass:"unknown",terminalReason:En.terminalReason}),await Nt?.();return}if(tr(tn),!Dt)throw new Error("Invalid provider returned for APM intent")}catch(We){if(We===oi){let Le=Z?.now()??globalThis.performance?.now()??Date.now();Z?.error({errorCode:Du(mn),stage:On,requestCategory:mn,paymentMethodCategory:"wallet",provider:"stripe",...fe?{walletType:fe}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Rn,durationMs:Math.max(0,Le-zt),statusClass:"timeout",failureCategory:qt,attempt:Ke,terminalReason:"provider_error"}),Z?.flush?.().catch(()=>{})}g(),re(x,We,We===oi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",D?.generation,We===oi)}finally{if(window.clearTimeout(gn),ce!==null&&(window.clearTimeout(ce),Ae.current.delete(ce)),!st){let We=Z?.now()??globalThis.performance?.now()??Date.now();Z?.performance({stage:"callback",durationMs:Math.max(0,We-zt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Tt?{statusClass:"timeout"}:{}})}Se.current&&it(!1)}},[U,ve,e,t,n,H,Me,$,r,se,o,s,l,u,v,re,De,mt,Wt,Et,J,_e]),Oe=ft(()=>wl(i),[i]),It=ft(()=>i.map(ku),[i]);return Xe(Do,{children:[y(Di,{state:ke,placeholderTestId:"flopay-wallet-placeholder",borderRadius:q,children:Xe("div",{ref:Te,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:Ve,type:"button","data-testid":"flopay-wallet-retry-button",onClick:L,style:ms,children:["Try ",ys(ye)," again"]}),pt!=="idle"&&Xe("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:ms,children:pt==="checking"?"Checking payment status\u2026":"Check payment status"})]}),me&&y(ko,{identity:me.identity,methodLabel:me.methodLabel,onComplete:gt,onCancel:()=>gt(null)},me.id),pt==="idle"&&y("div",{style:{display:me?"none":void 0},children:y(wc,{onReady:M=>{qe(Fi(M,It))},onLoadError:M=>{qe("load_error"),Cs(J,"stripe","wallet","provider_error")},onClick:async M=>{let p=J?.now()??globalThis.performance?.now()??Date.now();xe.current=M.expressPaymentType,W.current=gc(M.expressPaymentType);let g=!0,D=window.setTimeout(()=>{g=!1,M.reject()},Tu),x=v?await v(W.current):{proceed:!0};if(window.clearTimeout(D),!g)return;if(!x.proceed){Be.current.delete(_e),M.reject();return}let ee=Qe(M.expressPaymentType);Ze.current={generation:ee,startedAt:p},Be.current.set(_e,{generation:ee,method:M.expressPaymentType,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),$e(!1),J?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ee,...M.expressPaymentType==="apple_pay"||M.expressPaymentType==="google_pay"?{walletType:M.expressPaymentType}:{}}),f?.(W.current),M.resolve()},onConfirm:yt,onCancel:()=>{let M=Be.current.get(_e);Be.current.delete(_e),J?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...M?{attempt:M.generation}:{}}),Pt(M?.generation),ze.current=null,$e(!1),Ue.current=!0,_()},options:{...Il,paymentMethods:Oe,emailRequired:Ut,billingAddressRequired:Ut}},_e)})]})}),Re&&y(Sr,{status:"processing"})]})}function Ac(e,t,n){let r=Sc(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...r?{setupFutureUsage:r}:null}}function fs({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:f,onDecline:u,onCancel:S,runBeforeButtonClick:v,onButtonClick:H,isProcessing:$,submitButtonColor:k,submitButtonBorderRadius:q,submitButtonStyle:K,errorText:h}){let b=Kr(),{emitInstrument:se}=No(Zn),U=hs(),ve=gs(),[J,ke]=ue(!1),qe=oe(!1),[Re,it]=ue(!1),[Ut,me]=ue("loading"),[Me,gt]=ue(""),Te=!fn(r?.trim()),Ve=!Te||fn(Me.trim()),_e=Je(async()=>{if(!U||!ve||$||qe.current||!Re)return;qe.current=!0,ke(!0);let ne=v?await v("card"):{proceed:!0};if(!ne.proceed){qe.current=!1,ke(!1);return}H?.("card");let je=ne.sessionId??t,$e=ne.nonce??n,pt=no(o?.trim()),Ce=Nn({email:ne.accountPatch?.email?.trim()||r?.trim()||Me.trim(),firstName:ne.accountPatch?.firstName?.trim()||pt.firstName,lastName:ne.accountPatch?.lastName?.trim()||pt.lastName}),ye=Ce.email,le=Nn({...ne.accountPatch,...Ce});try{if(f?.(null),!fn(ye))throw new Error("A valid email address is required for payment.");await i?.(Ce);let F=await ve.submit();if(F.error){f?.(F.error.message??"Payment failed.");return}let Se=[Ce.firstName,Ce.lastName].filter(Boolean).join(" "),Ue=await U.createPaymentMethod({elements:ve,params:{billing_details:{email:ye,...Se?{name:Se}:{}}}});if(Ue.error||!Ue.paymentMethod){f?.(Ue.error?.message??"Failed to create payment method.");return}let xe=Ue.paymentMethod;if(!je||!ye)throw new Error("Missing sessionId or email for payment.");let W=xe.type||e,ht=await si(s,se,je,$e??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:W,paymentMethodId:null,intentKind:"payment"});if(ht.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ze=ht.clientSecret;Ht(kr,{clientSecret:ze,sessionId:je,nonce:$e,accountPatch:le,paymentMethodId:xe.id,paymentMethodType:xe.type??e,gateway:"stripe"});let{error:Ae,paymentIntent:Ze}=await U.confirmPayment({clientSecret:ze,confirmParams:{return_url:window.location.href,payment_method:xe.id},redirect:"if_required"});if(Ae){Ht(kr);let De=Ae.message??"Payment failed.";f?.(De),u?.(un("card",De,{code:Ae.code})),await li({billingApiUrl:s,sessionId:je,nonce:$e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ae.code??"provider_declined"}});return}let Be=Ze?.status;if(!ia(Be)){Ht(kr);let De=Be==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(De),u?.(un("card",De,{code:Be??"missing_payment_intent"}));return}Ht(kr);let Qe=typeof Ze?.payment_method=="string"?Ze.payment_method:Ze?.payment_method?.id;l({id:Qe??xe.id,type:"card",threeDSecureActionResultTokenId:Ze?.id,gateway:"stripe",paymentMethodType:xe.type??e},{accountPatch:le,paymentMethodCategory:"apm",sessionId:je,nonce:$e})}catch(F){f?.(F instanceof Error?F.message:"Payment failed. Please try again.")}finally{qe.current=!1,ke(!1)}},[U,ve,$,Re,v,H,t,n,r,o,Me,i,s,se,e,l,f,u]);return Xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Te&&y("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Te&&Xe("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",y("input",{type:"email",autoComplete:"email",required:!0,value:Me,onChange:ne=>gt(ne.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),y(Ru,{onReady:()=>me("ready"),onLoadError:()=>{me("load_error"),Cs(pn(b),"stripe","apm")},onChange:ne=>{it(!!ne.complete)},options:{layout:kl,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...fn(r?.trim())?{email:r?.trim()}:{}}}}}),y(Rl,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{_e()},disabled:!Re||!Ve||J||$||Ut!=="ready",color:k,borderRadius:q,style:K,children:J?"Processing\u2026":`Pay with ${Pa(e)}`}),h&&y(_o,{margin:"0.75rem 0 0",children:h})]})}function Cc({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:f,futureUseSession:u,onTokenizedBody:S,onErrorChange:v,onButtonClick:H,onDecline:$,runBeforeButtonClick:k,onLoadStateChange:q,isProcessing:K=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:b=8,submitButtonStyle:se,buttonAppearance:U,themeId:ve,onExpandApm:J,expandedApmMethod:ke}){let{emitInstrument:qe}=No(Zn),[Re,it]=ue(null),[Ut,me]=ue(null),Me=oe(!1),{request:gt,collect:Te,finish:Ve}=Io();St(()=>{s.length>0&&l?q?.("ready"):l||q?.("loading")},[s.length,l,q]);let _e=Je(async ye=>{if(!l||Me.current||K)return;Me.current=!0,me(ye);let le=k?await k("card"):{proceed:!0};if(!le.proceed){Me.current=!1,me(null);return}H?.("card");let F=le.sessionId??e,Se=le.nonce??t,Ue=no([le.accountPatch?.firstName,le.accountPatch?.lastName].filter(Boolean).join(" ")||r),xe=Nn({email:le.accountPatch?.email?.trim()||n?.trim(),firstName:le.accountPatch?.firstName?.trim()||Ue.firstName,lastName:le.accountPatch?.lastName?.trim()||Ue.lastName});if(!fn(xe.email)){me(null);let ze=await Te(Pa(ye),xe);if(!ze){Me.current=!1;return}xe=ze,me(ye)}let W=xe.email,ht=Nn({...le.accountPatch,...xe});try{if(v?.(null),!F||!fn(W))throw new Error("Missing sessionId or email for payment.");await o?.(xe);let ze=await si(i,qe,F,Se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ye,paymentMethodId:null,intentKind:"payment"});if(ze.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ae=ze.clientSecret;Ht(kr,{clientSecret:Ae,sessionId:F,nonce:Se,accountPatch:ht,paymentMethodType:ye,gateway:"stripe"});let{error:Ze,paymentIntent:Be}=await l.confirmPayment({clientSecret:Ae,confirmParams:{return_url:window.location.href,payment_method_data:{type:ye,billing_details:{name:[xe.firstName,xe.lastName].filter(Boolean).join(" "),...W?{email:W}:{}}}},redirect:"if_required"});if(Ze){Ht(kr);let Pt=Ze.message??"Payment failed.";v?.(Pt),$?.(un("card",Pt,{code:Ze.code})),await li({billingApiUrl:i,sessionId:F,nonce:Se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ye,providerDeclineReason:Ze.code??"provider_declined"}});return}let Qe=Be?.status;if(!ia(Qe)){Ht(kr);let Pt=Qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";v?.(Pt),$?.(un("card",Pt,{code:Qe??"missing_payment_intent"}));return}Ht(kr);let De=typeof Be?.payment_method=="string"?Be.payment_method:Be?.payment_method?.id;S({id:De??Be?.id,type:"card",threeDSecureActionResultTokenId:Be?.id,gateway:"stripe",paymentMethodType:ye},{accountPatch:ht,paymentMethodCategory:"apm",sessionId:F,nonce:Se})}catch(ze){v?.(ze instanceof Error?ze.message:"Payment failed. Please try again.")}finally{Me.current=!1,me(null)}},[l,K,k,H,e,t,n,Te,i,qe,r,o,S,v,$]),[ne,je]=ue(null),$e=J?ke??null:ne,pt=Je(ye=>{Me.current||K||$e&&$e!==ye||(cc(ye)?J?J(ye):je(ye):_e(ye))},[$e,K,_e,J]),Ce=ft(()=>ne?Ac(f,ne,u):null,[ne,f,u]);return y("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:gt?y(ko,{identity:gt.identity,methodLabel:gt.methodLabel,onComplete:Ve,onCancel:()=>Ve(null)},gt.id):s.map(ye=>{let le=ke===ye,F=Ut===ye,Se=Ut!==null&&Ut!==ye||ke!=null&&ke!==ye;return Xe(_u.Fragment,{children:[y(Sl,{method:ye,themeId:ve,submitting:F,disabled:Se,highlighted:le,hasNextStep:cc(ye),onClick:()=>pt(ye),backgroundColor:U?.backgroundColor,borderColor:U?.borderColor,textColor:U?.textColor,borderRadius:U?.borderRadius,fontFamily:U?.fontFamily}),!J&&ne===ye&&Ce&&l&&y(ao,{stripe:l,options:Ce,children:y(fs,{method:ye,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:S,onErrorChange:v,onDecline:$,onCancel:()=>je(null),runBeforeButtonClick:k,onButtonClick:H,isProcessing:K,submitButtonColor:h,submitButtonBorderRadius:b,submitButtonStyle:se})},ye)]},ye)})})}function Xu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:i,onComplete:s,onError:l,onDecline:f,onTokenizedBody:u,firstName:S,lastName:v,chv:H,className:$,submitLabel:k,isProcessing:q,error:K,onErrorChange:h,showPayPal:b=!0,showStripe:se=!0,walletPresentation:U="auto",enabledPaymentMethods:ve,enabledPaymentMethodCountries:J,showApplePay:ke=!0,showGooglePay:qe=!0,layout:Re="default",theme:it,buttonsTheme:Ut,buttonsStyles:me,appearance:Me,cardButtonContent:gt,cardBackButtonContent:Te,cardTitleContent:Ve,showSecurityFooter:_e,onButtonClick:ne,onBeforeButtonClick:je,onBuyerIdentityReady:$e,enableAVS:pt,cardFieldOrder:Ce,cardPreFormSlot:ye,avsLayout:le="row",country:F,zip:Se,addressLine1:Ue,addressLine2:xe,city:W,state:ht,onCountryChange:ze,onZipChange:Ae,avsCheck:Ze,checkoutType:Be,checkoutLayout:Qe,totalAmount:De=0,currency:Pt="usd",initialCardOpen:Wt=!1,directPaypal:mt,isSubscription:Et=!1,session:_,dataAttachmentPending:re=!1,dataAttachmentRequiresIdentity:Ne=!1,debug:L=!1}){let we=Kr(),yt=ji(),Oe=No(dr),{emitInstrument:It}=No(Zn),M=oe(null);M.current||(M.current=$a());let p=M.current,[,g]=ue(0),D=oe(null);D.current||(D.current=ra());let x=D.current,ee=ft(()=>({browser:x,capability:p,presentationMode:"popup"}),[x,p]),vt=_??Oe.session,fe=ft(()=>({futureUse:vt?.futureUse,futureUseUnsupported:vt?.futureUseUnsupported}),[vt?.futureUse,vt?.futureUseUnsupported]),Ke=vt?.gateways?.paypal?.providerObjectType??mt?.providerObjectType,Z=re||Oe.claimPending===!0,zt=Ne||Oe.claimRequiresIdentity===!0,bt=Z&&!zt,Tt=Vl(),st=n||Tt,[ce,Rn]=ue(!1),[On,mn]=ue(null),[qt,Ln]=ue(F??""),[Un,gn]=ue(Se??""),[At,We]=ue(Ue??""),[Le,_n]=ue(xe??""),[kt,zn]=ue(W??""),[yn,jt]=ue(ht??""),[Xt,Qn]=ue(""),[Hn,Qt]=ue({}),Rt=oe(Se??""),en=oe(F??""),nn=oe(Ue??""),Ft=oe(xe??""),an=oe(W??""),Nt=oe(ht??""),rn=oe(""),Dt=oe({});St(()=>{let a=(P,z,be,X,ge)=>{if(Dt.current[P])return;let Zt=z?.trim();!Zt||Zt===be.current||(be.current=Zt,X(Zt),ge?.(Zt))};a("country",F,en,Ln,ze),a("zip",Se,Rt,gn,Ae),a("addressLine1",Ue,nn,We),a("addressLine2",xe,Ft,_n),a("city",W,an,zn),a("state",ht,Nt,jt)},[F,Se,Ue,xe,W,ht,ze,Ae]);let G=ft(()=>Su(pt),[pt]),er=G!==null,tr=ft(()=>is(_),[_]),nr=!!_?.vault?.html,tn=!!_?.gateways?.pcivault,En=Li(_),he=!!(_?.gateways?.stripe?.enabledPaymentMethods??ve)?.includes("card")||zr(_),et=nr||he||tn,m=!!(se&&et&&e),[Ge,V]=ue(()=>Re!=="buttons"||Wt?e??null:null),[hn,qn]=ue(0),Gt=Re!=="buttons"||Wt||!!e&&Ge===e,Tn=_?.captureMethod,tt=oe(we);St(()=>{tt.current=we},[we]);let[rr,Zr]=ue(null);St(()=>{if(!m||!e||!Gt){Zr(null);return}let a=tt.current?tt.current.cardCapture({sessionId:e,captureMethod:Tn}):new du({sessionId:e,captureMethod:Tn,billingApiUrl:st,telemetry:r});return Zr({sessionId:e,captureMethod:Tn,billingApiUrl:st,telemetry:r,capture:a}),()=>{a.unmount()}},[m,e,Gt,Tn,st,r]);let _t=m&&e&&Gt&&rr?.sessionId===e&&rr.captureMethod===Tn&&rr.billingApiUrl===st&&rr.telemetry===r?rr.capture:null,An=ft(()=>{let a=qt,P=G?ot(G.postal_code,a):!1;return Yu(a,Un,P)},[G,qt,Un]),{avsInvalid:yr,invalidAvsFields:Vn}=ft(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!m||!G)return{avsInvalid:!1,invalidAvsFields:a};let P=qt,z=(ge,Zt)=>ot(ge,P)&&!Zt.trim(),be={line1:z(G.address_line_1,At),city:z(G.city,kt),state:z(G.state,yn),zip:An.empty||An.malformed};return{avsInvalid:be.line1||be.city||be.state||be.zip,invalidAvsFields:be}},[m,G,qt,At,kt,yn,An]),[Yt,or]=ue(!1),[Mn,_r]=ue(!1),[xn,fr]=ue(!1),[gr,Er]=ue({line1:!1,city:!1,state:!1}),jn=oe(!1),Wn=oe({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Tr=oe(!1),Mt=Je(a=>{Wn.current[a]=!0,Tr.current=!0},[]),Cn=Je(a=>!jn.current&&Wn.current[a],[]),Gn=Je(a=>{Cn(a)&&Er(P=>P[a]?P:{...P,[a]:!0})},[Cn]),[Ar,Mr]=ue(()=>us(_?.vault)),[He,sn]=ue(Wt&&et?"card":"buttons"),[ln,Sn]=ue(null),Xr=He==="expanding"||He==="card",hr=_?.gateways?.stripe&&!En?"stripe":void 0,Or=Je(()=>{It?.({class:"card_surface",provider:hr})},[hr,It]),wn=oe(null),cn=Je(a=>{wn.current&&clearTimeout(wn.current),wn.current=setTimeout(()=>{wn.current=null,a()},va)},[]);St(()=>()=>{wn.current&&clearTimeout(wn.current)},[]);let xr=Je(()=>{Or(),V(e??null),qn(a=>a+1),sn("expanding"),cn(()=>sn("card"))},[cn,Or,e]),Bn=Je(()=>{sn("collapsing"),cn(()=>sn("buttons"))},[cn]),w=Je(a=>{Sn(a),sn("apm-expanding"),cn(()=>sn("apm-form"))},[cn]),R=Je(()=>{sn("apm-collapsing"),cn(()=>{sn("buttons"),Sn(null)})},[cn]);St(()=>{Re==="buttons"&&Wt&&et&&(V(e??null),sn("card"))},[Re,Wt,et,e]);let[O,E]=ue(null),nt=oe(!1),ut=oe(null),j=oe("idle"),[Ee,B]=ue(!1),d=oe(Ee);d.current=Ee;let[c,I]=ue(()=>mt?.existingOrderId?{orderId:mt.existingOrderId,attempts:1}:null),T=oe(c);St(()=>{T.current=c},[c]);let Q=oe(null),ae=ft(()=>{if($e||Oe.claimBuyerIdentity||_?.buyerIdentified!==!1||!e||!t)return;let a=`${st}|${e}|${t}`;Q.current?.key!==a&&(Q.current={key:a,claim:So(new Fo(st,{telemetry:!1}),e,t,{...i?{userId:i}:{},...S?{firstName:S}:{},...v?{lastName:v}:{}})});let P=Q.current.claim;return async z=>{await P(z)}},[$e,Oe.claimBuyerIdentity,_?.buyerIdentified,e,t,st,i,S,v]),Fe=$e??Oe.claimBuyerIdentity??ae,at=K??On,pe=ft(()=>Iu(it),[it]),C=ft(()=>{let a=pe?.buttonsLayout??wu(Ut);return me?{...a,...me,cardButton:{...a.cardButton,...me.cardButton},cardFormContainer:{...a.cardFormContainer,...me.cardFormContainer},backButton:{...a.backButton,...me.backButton},backButtonIcon:{...a.backButtonIcon,...me.backButtonIcon},submitButton:{...a.submitButton,...me.submitButton},title:{...a.title,...me.title}}:a},[pe,Ut,me]),lt=Me??pe?.appearance,ie=ft(()=>Pl({appearance:lt,buttonsStyles:C,layout:Re}),[lt,C,Re]),te=Oe.inlineSessionPatchProcessing??!1,A=(q??ce)||te,Y=st.replace(/\/+$/,""),N=ft(()=>zi({userId:i,email:o,firstName:S,lastName:v,country:F,zip:Se},Hn),[i,o,S,v,F,Se,Hn]),ct=[N.firstName,N.lastName].filter(a=>!!a?.trim()).join(" "),Ie=!fn(N.email?.trim()),ar=oe(null);m&&ar.current===null&&(ar.current=Ie);let In=m&&(ar.current??Ie),mi=ft(()=>Ju(Xt,In),[Xt,In]),so=mi.empty||mi.malformed,$n=ft(()=>we?we.getRawProvider():null,[we]),Fs=ft(()=>yt?yt.getRawProvider():null,[yt]),qo=De||100,lo=Pt.toLowerCase(),yi=ft(()=>lt?uu(lt):null,[lt]),co=yi,Ds=ft(()=>{let a=yi??{},P=a.rules??{};return{...a,rules:{...P,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...P[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...P[".AccordionItemContents"]??{}}}}},[yi]),Ns=ft(()=>({...zl(De,_?.captureMethod,fe),currency:lo,...co?{appearance:co}:null}),[De,lo,_?.captureMethod,fe,co]),fi=Sc(fe,"paypal","paypal"),Os=ft(()=>({mode:"payment",amount:qo,currency:lo,captureMethod:"manual",...fi?{setupFutureUsage:fi}:null,...co?{appearance:co}:null}),[qo,lo,fi,co]),Pe=Je(a=>{mn(a),h?.(a)},[h]),gi=oe(""),[Ls,$c]=ue(!1),hi=Je(()=>{$c(!0)},[]);St(()=>{if(!m||!In||!Fe||!Ls||so||gi.current)return;let a=Nn({email:fn(N.email?.trim())?N.email?.trim():rn.current.trim(),firstName:N.firstName?.trim(),lastName:N.lastName?.trim()});gi.current=JSON.stringify(a),Qt(P=>({...P,...a})),Promise.resolve(Fe(a)).catch(P=>{gi.current="",Pe(P instanceof Error?P.message:"Failed to attach buyer details.")})},[m,In,Fe,Ls,so,N.email,N.firstName,N.lastName,Pe]),St(()=>{!m||!_t||_t.setCardFieldOrder?.(Ce??null,G==null&&!In)},[m,_t,Ce,G,In]),St(()=>{(He==="expanding"||He==="collapsing"||He==="apm-expanding"||He==="apm-collapsing")&&Pe(null)},[He,Pe]);let Pr=Je((a,P,z)=>{f?.(un(a,P,z))},[f]),uo=Je((a,P,z)=>{let be=z?.popupBlocked??Ur(P);be&&p.markBlocked()&&g(Ye=>Ye+1);let X=Da(ys(a),be,x.inAppBrowser),ge=Lr(P),Zt=(ge?.toLowerCase()==="error"?void 0:ge)??vl(z?.code)??"external_payment_method_failed",lr=new pr(X,"api_error",{code:"external_payment_method_failed",param:a,details:{providerCode:Zt,popupBlocked:be,inAppBrowser:x.inAppBrowser,appFamily:x.appFamily,popupCapability:p.current(),presentationMode:z?.presentationMode??"popup"}});z?.telemetryReported||pn(we)?.error(Bo({...ee,presentationMode:z?.presentationMode??"popup"},{errorCode:be?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:z?.provider??(a==="paypal"?"paypal":"stripe"),paymentMethodCategory:z?.paymentMethodCategory??(a==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:z?.terminalReason??(be?"popup_blocked":"provider_error")})),E(null),Re==="buttons"&&(sn("buttons"),Sn(null)),Pe(X),l?.(lr),console.error("[FloPay] External payment method failed:",{method:a,code:Zt,popupBlocked:be})},[x,ee,we,Re,l,p,Pe]);St(()=>{if(!m||!e){Mr(null);return}let a=us(_?.vault);if(a){Mr(a);return}if(!Gt){Mr(null);return}Mr(null);let P=!0;return new Fo(Y).getVaultCapture(e,t).then(z=>{if(!P)return;let be=us(z);be?Mr(be):Pe("Failed to load the secure card form.")}).catch(z=>{P&&Pe(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{P=!1}},[m,Gt,hn,e,_?.vault,Y,t,Pe]);let ir=oe({onComplete:s,onError:l,updateError:Pe,emitDecline:Pr,resolvedAccount:N,avsConfig:G,avsCheckProp:Ze,sessionId:e,nonce:t,baseUrl:Y,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt,serverSideCardGateway:En});ir.current={onComplete:s,onError:l,updateError:Pe,emitDecline:Pr,resolvedAccount:N,avsConfig:G,avsCheckProp:Ze,sessionId:e,nonce:t,baseUrl:Y,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt,serverSideCardGateway:En};let Pi=oe(!1),Us=Je(()=>{let a=ir.current,P=a.resolvedAccount.email?.trim(),z=fn(P)?P:rn.current.trim();if(!fn(z))return null;let be=a.resolvedAccount.firstName?.trim(),X=a.resolvedAccount.lastName?.trim(),ge=en.current.trim()||a.resolvedAccount.country?.trim()||"",Zt=a.avsConfig?ot(a.avsConfig.state,ge):!1,lr=a.avsConfig?ot(a.avsConfig.address_line_1,ge):!1,Ye=a.avsConfig?ot(a.avsConfig.postal_code,ge):!1,dt=a.avsConfig?ot(a.avsConfig.city,ge):!1,Ct=a.avsConfig?ot(a.avsConfig.address_line_2,ge):!1,Kt=lr&&!Zt&&Ye?lc(ge,(Rt.current??"").trim()):null,dn=Zt?Nt.current:Kt;return{accountData:{userId:a.resolvedAccount.userId??"",email:z,...be?{firstName:be}:{},...X?{lastName:X}:{},...Ye&&Rt.current?{zip:Rt.current}:{},...dt&&an.current?{city:an.current}:{},...dn?{state:dn}:{},...lr&&nn.current?{addressLine1:nn.current}:{},...Ct&&Ft.current?{addressLine2:Ft.current}:{},...ge?{country:ge}:{}},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:ot(a.avsConfig.country,ge),postal_code:Ye,address_line_1:lr,address_line_2:Ct,city:dt,state:Zt}}:{}}},[]),zs=oe(Z);zs.current=Z,St(()=>{Z||at!==mc||ir.current.updateError(null)},[Z,at]),St(()=>{!m||!_t||_t.setSubmitGate?.(yr||Z||so||Ee)},[m,_t,yr,Z,so,Ee]),St(()=>{if(!m||!_t)return;Pi.current=!1;let a=null,P=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,j.current="idle",E(null)},400)},z=_t.on("submitting",()=>{or(!0),ut.current&&clearTimeout(ut.current),j.current="validation-window",ut.current=setTimeout(()=>{ut.current=null,j.current==="validation-window"&&(j.current="processing")},Lu),E("processing");let Ye=ir.current;if(!Ye.sessionId||!Ye.nonce)return;let dt=Us();if(!dt){Ye.updateError("Enter a valid email address."),j.current="idle",E(null);return}new Fo(Ye.baseUrl).patchAccountSnapshot(Ye.sessionId,Ye.nonce,dt,{telemetryMode:"best_effort"}).catch(Ct=>{if(!zu(Ct))return;let Kt=Ct instanceof Error?Ct.message:"Please check your billing address and try again.";Ye.updateError(Kt),j.current="idle",E(null),Ye.onError?.(Ct instanceof pr?Ct:new pr(Kt,"api_error"))})}),be=_t.on("complete",async Ye=>{if(Ao(Ye.sessionId??ir.current.sessionId),j.current="terminal",B(!1),E("success"),await new Promise(dn=>setTimeout(dn,600)),Pi.current)return;Pi.current=!0;let dt=ir.current,Ct=is(dt)||Ye.outcome==="authorized",Kt=dt.serverSideCardGateway?{}:{paymentIntentId:Ye.intentId};ir.current.onComplete?.(Ct?{status:"authorized",...Kt,paymentId:Ye.paymentId??dt.paymentId,sessionId:Ye.sessionId??dt.sessionId,authorizationExpiresAt:Ye.authorizationExpiresAt??dt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Kt,checkoutMethod:"card"})}),X=_t.on("decline",Ye=>{let dt=ir.current,Ct=Ye.message??"Your payment was declined. Please try another card or contact your bank.";j.current="terminal",B(!1),dt.updateError(Ct),E("error");let Kt=Ye.failureOutcome??vu(Ye.declineReason)??"authorization_declined";dt.emitDecline("card",Ct,{code:Kt,declineCode:Kt}),P()}),ge=_t.on("error",Ye=>{let dt=ir.current,Ct=Ye.message??"There was a problem processing your payment. Please try again.";j.current="terminal",B(!1),dt.updateError(Ct),E("error"),dt.onError?.(new pr(Ct,"api_error",{code:Ye.failureOutcome??"capture_failed"})),P()}),Zt=_t.on("challenge_dismissed",()=>{ut.current&&(clearTimeout(ut.current),ut.current=null),j.current="processing",B(!0),E(null)}),lr=_t.on("blocked",()=>{if(d.current){ir.current.updateError(Uu);return}if(!zs.current){or(!0);return}hi(),ir.current.updateError(mc)});return()=>{a&&(clearTimeout(a),a=null),ut.current&&(clearTimeout(ut.current),ut.current=null),j.current="idle",B(!1),E(null),z(),be(),X(),ge(),Zt(),lr()}},[m,_t,hi,Us]);let vr=!!mt?.clientId,jo=Array.isArray(ve),Ia=jo&&ve.length>0,qs=jo&&ve.includes("paypal"),ka=oe(null);ka.current===null&&(ka.current=Nu());let po=ka.current?"redirect":Cl(x,U,p.current()),{expressMethods:Ra,paymentElementMethods:$o}=ft(()=>bu(ve,{excludePaypal:vr}),[ve,vr]),js=vr||!!yt||qs&&po==="redirect",Kc=ft(()=>js?Ra.filter(a=>a!=="paypal"):Ra,[Ra,js]),Hc=ft(()=>{let a=[];return ke&&a.push("apple_pay"),qe&&a.push("google_pay"),a},[ke,qe]),mo=jo?Kc:Hc,Vc=se&&mo.length>0,vi=er?qt:F,_a=ft(()=>{let a=vi?.trim().toUpperCase();return a?J?$o.filter(P=>{let z=J[P];return!z||z.length===0||z.includes(a)}):yu($o,vi):$o},[$o,vi,J]),bi=ft(()=>({mode:"payment",amount:qo,currency:lo,paymentMethodCreation:"manual",appearance:Ds}),[qo,lo,Ds]),[$s,Ks]=ue("loading"),[Hs,Vs]=ue("loading"),[Ws,Gs]=ue("loading"),[Wc,Ci]=ue(!1),[Ys,Si]=ue("loading"),[wi,Gc]=ue();St(()=>{Gc(ra())},[]);let Ea=wi?.inAppBrowser,Ta=wi?Oa(wi,mt?.approvalPresentation,Ke??(Et?"subscription":"order")):"popup",Js=b&&(vr||(jo?qs:Ea===!1)),Zs=se&&Vc,Ko=(!bt||!!Oe.waitForDataAttachment)&&Js&&vr,Xs=Ys==="retrying"||Ys==="exhausted",Ho=null;se&&(yt?Ho=Fs:po==="redirect"&&(Ho=$n));let Qs=ft(()=>({...ee,presentationMode:po}),[ee,po]),Vo=!bt&&Js&&!!Ho&&(!vr||Xs),yo=!bt&&Zs&&!!$n,Wo=!bt&&se&&Ia&&_a.length>0&&!!$n,Yc=Ko&&!Xs?Wc:Vo&&Ni($s),Jc=yo&&Ni(Hs),Zc=Wo&&Ws!=="load_error",el=a=>a==="loading"||a==="ready",tl=Ko||Vo&&el($s)||yo&&el(Hs)||Wo&&Ws!=="load_error",Aa=oe(!1);St(()=>{if(!Aa.current){if(!se&&!b){Aa.current=!0;let a=new pr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(a),Pe(a.message)}else if(!se&&b&&!vr){Aa.current=!0;let a=new pr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(a),Pe(a.message)}else if(Ea!==void 0&&!bt&&!et&&!tl){Aa.current=!0;let a=new pr("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"});l?.(a),Pe(a.message)}}},[se,b,vr,Ea,bt,et,tl,l,Pe]);let nl=oe(!1);St(()=>{if(nl.current||!Ia)return;let a=[];ke!==!0&&a.push("showApplePay"),qe!==!0&&a.push("showGooglePay"),a.length!==0&&(nl.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.`))},[Ia,ke,qe]);let rl=Je((a,P)=>Oe.applyInlineSessionPatch?Oe.applyInlineSessionPatch(a).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let be=hc(P,z);return Pe(be.message),l?.(be),{error:be,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Oe.applyInlineSessionPatch,t,l,e,Pe]),sr=Je(async a=>{if(a!=="card"&&bt&&await Oe.waitForDataAttachment?.(),!je)return{proceed:!0};try{let P=await je({method:a,sessionId:e||void 0,createSession:Oe.inlineSessionDraft});if(P===!1)return{proceed:!1};if(P&&typeof P=="object"){P.account&&Qt(be=>({...be??{},...P.account}));let z=await rl(P,a);return z.error?{proceed:!1,accountPatch:P.account}:{proceed:!0,accountPatch:P.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(P){let z=hc(a,P);return Pe(z.message),l?.(z),{proceed:!1}}},[rl,Oe.inlineSessionDraft,Oe.waitForDataAttachment,bt,je,l,e,Pe]),ol=Je(async(a,P)=>{if(nt.current)return;nt.current=!0,Rn(!0),E("processing"),Pe(null);let z=P?.sessionId??e,be=P?.nonce??t,X=zi(N,P?.accountPatch),ge=P?.completionPaymentMethodId??sa(a),Zt=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,lr=Ku(a),Ye=P?.presentationMode?ri(pn(we),{...ee,presentationMode:P.presentationMode}):void 0,dt=()=>{It?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:lr}),Ye?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...ur,requestCategory:"process_payment"})};try{let Kt=await new Fo(Y).processPayment(X.userId??"",{sessionId:z,nonce:be,paymentMethodCategory:P?.paymentMethodCategory??Vu(a),tokenizedData:Zt,accountData:{...P?.accountPatch,userId:X.userId??"",email:X.email??"",firstName:X.firstName||void 0,lastName:X.lastName||void 0,...G?(()=>{let Ot=en.current,br=ot(G.state,Ot),Kn=ot(G.address_line_1,Ot),Cr=ot(G.postal_code,Ot),to=Kn&&!br&&Cr?lc(Ot,(Rt.current??"").trim()):null,Qo=br?Nt.current:to;return{country:Ot,...Cr&&Rt.current?{zip:Rt.current}:{},...ot(G.city,Ot)&&an.current?{city:an.current}:{},...Qo?{state:Qo}:{},...Kn&&nn.current?{addressLine1:nn.current}:{},...ot(G.address_line_2,Ot)&&Ft.current?{addressLine2:Ft.current}:{}}})():{}},chv:H,avsCheck:Ze??!1,checkoutType:Be,checkoutLayout:Qe,avsConfig:G?{country:ot(G.country,en.current),postal_code:ot(G.postal_code,en.current),address_line_1:ot(G.address_line_1,en.current),address_line_2:ot(G.address_line_2,en.current),city:ot(G.city,en.current),state:ot(G.state,en.current)}:void 0});if(Kt.ok){let Ot=Kt.status===204?null:await Kt.json().catch(()=>null),br=is(_)||Ot?.status==="authorized";Ao(z),Ye?.terminal({outcome:"payment_succeeded",...ur}),E("success"),I(null),await new Promise(to=>setTimeout(to,600));let Kn;typeof Ot?.paymentId=="string"?Kn=Ot.paymentId:_?.paymentId&&(Kn=_.paymentId);let Cr;typeof Ot?.authorizationExpiresAt=="string"?Cr=Ot.authorizationExpiresAt:_?.authorizationExpiresAt&&(Cr=_.authorizationExpiresAt),s?.(br?{status:"authorized",...Kn===void 0?{}:{paymentId:Kn},sessionId:typeof Ot?.sessionId=="string"?Ot.sessionId:z,...Cr===void 0?{}:{authorizationExpiresAt:Cr},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ge,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ge,checkoutMethod:a.isPaypal?"paypal":"card"});return}let dn=await Kt.json().catch(()=>null);if(dn?.type==="paypal_redirect_required"){let Ot=dn.threeDSecureToken,br=dn.paymentMethodId||a.id||"";if(!we||!Ot){E("error"),Pe("PayPal authorization required but no token provided.");return}try{let Kn=yt?.getRawProvider();if(!Kn){Pe("PayPal is not available.");return}let Cr={return_url:window.location.href};br&&(Cr.payment_method=br);let{error:to}=await Kn.confirmPayment({clientSecret:Ot,confirmParams:Cr,redirect:"if_required"});if(to){E("error");let Qo=to.message??"PayPal payment failed.";Pe(Qo),Pr("paypal",Qo,{code:to.code})}}catch(Kn){E("error"),Pe(Kn instanceof Error?Kn.message:"PayPal authorization failed.")}return}if(dn?.type==="paypal_direct_required"){let Ot=dn.orderId;if(!Ot){E("error"),Pe("PayPal retry required but no order id provided.");return}let br=T.current?.attempts??0;if(br>=2){E("error"),Pe("PayPal payment could not be completed after multiple attempts."),Pr("paypal","paypal_direct_required retry limit exceeded");return}Ci(!1),Si("loading"),I({orderId:Ot,attempts:br+1}),E(null);return}mu(Kt.status,dn)?Ye?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}):dt(),E("error");let cr=dn?.message??"Payment failed. Please try again.";Pe(cr),Pr(a.isPaypal?"paypal":"card",cr,{code:dn?.code??dn?.gatewayErrorCode,declineCode:dn?.declineCode??dn?.gatewayDeclineReason}),await new Promise(Ot=>setTimeout(Ot,400))}catch(Ct){_c(Ct)||dt(),E("error"),Pe(Ct instanceof Error?Ct.message:"An unexpected error occurred"),await new Promise(Kt=>setTimeout(Kt,400))}finally{Rn(!1),E(null),nt.current=!1}},[Y,e,t,N,G,Ze,Be,Qe,H,we,yt,_,s,Pe,Pr,It,ee]),Fn=Je((a,P)=>{u?u(a):ol(a,P)},[u,ol]),Go=`${Ic}:${e}`;St(()=>{if(typeof window>"u")return;let a=localStorage.getItem(Go);if(!a)return;let P;try{P=JSON.parse(a)}catch{Ht(Go);return}if(!P||typeof P.createdAt!="number"||Date.now()-P.createdAt<0||Date.now()-P.createdAt>kc||typeof P.paymentMethodId!="string"||typeof P.providerIntentId!="string"||typeof P.paymentMethodType!="string"||P.sessionId!==e||!t||P.nonce!==t||!mo.includes(P.paymentMethodType)){Ht(Go);return}Ht(Go),Fn({id:P.paymentMethodId,type:"card",threeDSecureActionResultTokenId:P.providerIntentId,gateway:"stripe",paymentMethodType:P.paymentMethodType},{...P.accountPatch?{accountPatch:P.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Fn,t,e,Go,mo]);let al=oe(!1);St(()=>{if(typeof window>"u"||al.current)return;let[a,P,z]=vs();if(!a||!P||ka.current||!we)return;let be=we.getRawProvider();if(!be)return;let X=dt=>{let Ct=localStorage.getItem(dt);if(!Ct)return null;try{return JSON.parse(Ct)}catch{return Ht(dt),null}},ge=X(kr)??X(dc),Zt;if(ge?.clientSecret){if(ge.clientSecret!==P)return;Zt={...ge.accountPatch?{accountPatch:ge.accountPatch}:{},...ge.sessionId?{sessionId:ge.sessionId}:{},...ge.nonce?{nonce:ge.nonce}:{}}}else if(ge?.sessionId&&ge.sessionId!==e)return;al.current=!0,Ht(kr),Ht(dc),window.history.replaceState({},"",bs());let lr=ge?.paymentMethodType??ge?.tokenType??"card",Ye="card";(async()=>{if(z==="failed"){let cr="Payment was declined. Please try again.";Pe(cr),Pr(Ye,cr);return}let{paymentIntent:dt,error:Ct}=await be.retrievePaymentIntent(P);if(Ct){let cr=Ct.message??"Failed to retrieve payment status.";Pe(cr),Pr(Ye,cr,{code:Ct.code});return}let Kt=dt?.status,dn=ia(Kt);if(!dt||!dn){let cr=Kt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Pe(cr),Pr(Ye,cr,{code:Kt??"missing_payment_intent"});return}let fl=typeof dt.payment_method=="string"?dt.payment_method:dt.payment_method?.id;Fn({id:fl??ge?.paymentMethodId??ge?.tokenId??dt.id,type:"card",threeDSecureActionResultTokenId:dt.id,gateway:ge?.gateway??"stripe",paymentMethodType:lr},Zt)})()},[e,Fn,we,Pe,Pr]);let Ii=Je(a=>{a.preventDefault()},[]);if(!(m||we!==null))return y("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Yo=Re==="buttons",Dn=lt?.variables,Xc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ki=Dn?.colorBackground,Qc=ki&&!Xc.has(ki)?ki:void 0,Jo=C.cardInputBorder??(Yo?"#e5e7eb":"#A4A4FF"),il=Dn?.colorDanger??"#dc2626",$t=a=>Vn[a]&&(gr[a]||Yt),Ma=so&&(xn||Yt),Yn=a=>a?il:Jo,xa=(An.malformed||An.empty)&&(Mn||Yt),ed=Yn(xa),Ri=C.cardFormContainer?.backgroundColor??Qc??(Yo?"white":"#EDEDFF"),fo=C.cardInputBackground??Dn?.colorBackground??"white",_i=Po(Te),sl=Po(Ve),go=C.nameInput,ll=C.cardInputFontSize??Zu(go?.fontSize)??Dn?.fontSizeBase??"16px",cl=typeof go?.fontFamily=="string"?go.fontFamily:Dn?.fontFamily??"Poppins, sans-serif",dl=hl(go?.fontWeight)??400,td=C.cardInputColor??(typeof go?.color=="string"?go.color:void 0)??Dn?.colorText??"#262833",nd=C.cardInputPlaceholderColor??"#9ca3af",Jt=Dn?.borderRadius??"8px",Qr=Dn?.borderRadius??C.cardButton?.borderRadius??Jt,eo=Dn?.colorPrimary??"#4A49FF",rd=Dn?.colorPrimaryHover??ta(eo,.12),Ei=Dn?.colorText??"#262833",Ti={fontSize:ll,fontFamily:cl,fontWeight:dl,color:td,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Zo={marginTop:"0.375rem",...Ti,fontSize:"0.75rem",lineHeight:1.4,color:il},od={"--flopay-input-placeholder-color":nd,"--flopay-input-font-size":ll,"--flopay-input-font-family":cl,"--flopay-input-font-weight":String(dl)},Xo=C.cardFormContainer??{},Ai=Xo.padding??(Yo?"0":"1rem"),Mi=Xo.borderRadius??Jt,ad=_t&&Ar?y(xi,{capture:_t,html:Ar.html,messageToken:Ar.messageToken,expectedOrigin:Ar.expectedOrigin,theme:ie,submitLabel:k,onReady:()=>{if(!In&&!G||typeof document>"u")return;let a=()=>{let z=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(z){jn.current=!0;try{z.focus()}finally{jn.current=!1}}};Tr.current||a()},onError:a=>Pe(a),onValidation:a=>{let P=j.current;(P==="idle"||P==="validation-window")&&(Pe(a),a&&j.current==="validation-window"&&(ut.current&&(clearTimeout(ut.current),ut.current=null),j.current="idle",E(null)))}}):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"}),ul=Xe("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&Or()},style:{backgroundColor:Ri,borderRadius:Mi,...Xo,padding:Ai,...od,display:"flex",flexDirection:"column"},children:[y("style",{children:`
|
|
3
|
+
${At.join(`
|
|
4
|
+
`)}`]}):null;return ft&&!X?me?ao("div",{children:et}):null:Gi("div",{children:[et,Ne&&ao(Ro,{identity:Ne.identity,methodLabel:Ne.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:we,onCancel:()=>we(null)}),Gi("div",{"aria-hidden":vt||Ne?!0:void 0,style:vt||Ne?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Wa},children:[!xe&&!vt&&ao("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"}}),ao("div",{ref:ne,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Wa,display:"flex",opacity:xe?1:0},"aria-busy":T||h},Ae)]},Ae),Qe&&ao("button",{ref:Se,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:en,style:Hd,children:"Try PayPal again"})]})}function Va(e){return ao(Jl,{...e})}function Xl(e){return ao(Jl,{...e})}import{jsx as Zl,jsxs as Jd}from"react/jsx-runtime";function Eo({children:e,margin:t,icon:n=!0,styleOverride:r}){return Jd("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&&Zl("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Zl("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 Xd,resolveSessionCurrency as Zd}from"@flopay/shared";function To(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Ji=":idempotency-key";function Xi(e,t){if(!To())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 Zi(e,t){if(!To())return null;try{let n=window.sessionStorage.getItem(e+Ji);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 Ga(e,t){if(To())try{Xi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Ya(e,t){if(Ga(e,t),!!To())try{Zi(e,t)&&window.sessionStorage.removeItem(e+Ji)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ja(e,t,n,r){if(To())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 Xa(e,t,n){if(To())try{window.sessionStorage.setItem(e+Ji,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Yi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Qd(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([s],[l])=>s<l?-1:s>l?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let s=0;s<t.length;s++){let l=t.charCodeAt(s);n=r^Math.imul(n^l,597399067),r=o^Math.imul(r^l,2869860233),o=i^Math.imul(o^l,951274213),i=n^Math.imul(i^l,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 Ao(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=>Yi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Yi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Yi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Qd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Ql(e,t=!1){let n=Ao(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 ec(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=Zd(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??Xd(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,S)=>`${u.code}:${u.type??""}`.localeCompare(`${S.code}:${S.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,S)=>`${u.code}:${u.type??""}`.localeCompare(`${S.code}:${S.type??""}`));if(i.length!==s.length)return!1;for(let[u,S]of i.entries()){let v=s[u];if(v===void 0||S.code!==v.code||S.type!==void 0&&S.type!==v.type||S.quantity!==v.quantity||S.totalAmount!==v.totalAmount||S.overrideAmount!==v.overrideAmount||S.currency!==v.currency)return!1}let l=[...t.couponCodes??[]].sort(),f=[...e.coupons??[]].sort();return l.length===f.length&&l.every((u,S)=>u===f[S])}import{resolveBillingApiUrl as eu}from"@flopay/shared";import{useEffect as Gr,useMemo as tu,useRef as tc,useState as nc}from"react";import{jsx as nu}from"react/jsx-runtime";function Za({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,s]=nc(e instanceof Promise?null:e),[l,f]=nc(t instanceof Promise||!t?null:t),u=tc(null),S=tc(null),v=_o(r);Gr(()=>{v({class:"lifecycle",name:"checkout.mount"})},[v]),Gr(()=>{i&&v({class:"lifecycle",name:"sdk.initialize.ready"})},[v,i]),Gr(()=>{if(i)return un(i)?.subscribe?.(v)},[v,i]),Gr(()=>{if(!(!l||l===i))return un(l)?.subscribe?.(v)},[v,i,l]),Gr(()=>{if(!i)return;let k=un(i);return u.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Gr(()=>{let k=!1;return e instanceof Promise?e.then(q=>{k||s(q)},()=>{k||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{k=!0}},[v,e]),Gr(()=>{let k=!1;if(!t){f(null);return}return t instanceof Promise?t.then(q=>{k||f(q)},()=>{k||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):f(t),()=>{k=!0}},[v,t]),Gr(()=>{if(!i||S.current===i)return;S.current=i;let k=un(i);k?.log({name:"checkout.rendered",stage:"checkout_render"}),v({class:"lifecycle",name:"checkout.rendered"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(u.current??0),durationMode:"machine"})},[v,i]);let H=eu(n?.billingApiUrl),$=tu(()=>({flopay:i,paypalFlopay:l,billingApiUrl:H,emitInstrument:v}),[i,l,H,v]);return nu(Xn.Provider,{value:$,children:o})}var Qa="flopay_recent_completion_";function Mo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Qa+e,JSON.stringify(t))}catch{}}function Qi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Qa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Qa+e),!1):!0}catch{return!1}}async function ei(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 rc,PaymentAPI as ni}from"@flopay/js";import{classifyPaymentRejection as ru,FloPayError as wt,isAuthorizationOnlySession as ou,isSetupIntentClientSecret as au,normalizeCheckoutFailureOutcome as oc,THREE_DS_CHALLENGE_WINDOW_MS as ic}from"@flopay/shared";var fa="card",iu=1e3;async function su(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 lu(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:l}=await e.confirmCardSetup(t,n);return{error:l,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 wt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function es(){return new wt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function ns(e,t){return Object.assign(e,{checkoutMethod:t})}function Nr(e,t){let n=e instanceof wt?e:new wt(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 ya(e,t){try{return await e()}catch(n){throw Nr(n,t)}}function sc(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 cu(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function rs(e){if(typeof document>"u"||typeof window>"u")throw new wt("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 v=new AbortController,H=()=>v.abort();e.signal?.aborted?v.abort():e.signal?.addEventListener("abort",H);let $=window.setTimeout(()=>v.abort(),n);try{let k=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:v.signal});if(!k.ok)return{status:"unknown"};let q=await k.json().catch(()=>null);return du(q)}catch{return{status:"unknown"}}finally{window.clearTimeout($),e.signal?.removeEventListener("abort",H)}},i,s=()=>e.pollCompletionEndpoint!==!1?o():(i??(i=o()),i),l=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 S=null;try{S=new URL(e.billingApiUrl,window.location.href).origin}catch{S=null}try{let v=await new Promise((H,$)=>{let k=!1,q=0,K=0,h=0,C=!1,se=()=>{window.clearTimeout(q),window.clearInterval(K),window.clearTimeout(h),window.removeEventListener("message",ke),u.removeEventListener("load",Ce),e.signal?.removeEventListener("abort",J)},z=async()=>{if(!(k||C)){C=!0;try{let qe=await s();if(k||!cu(qe))return;k=!0,se(),H(qe)}finally{C=!1}}},Ce=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(h),h=window.setTimeout(()=>{z()},250))},J=()=>{k||(k=!0,se(),$(Yr()))},ke=qe=>{if(qe.source!==u.contentWindow||S&&qe.origin!==S)return;let Re=qe.data;!Re||typeof Re!="object"||Re.source!=="flopay-vault-3ds-return"||k||(k=!0,se(),H(null))};q=window.setTimeout(()=>{k||(k=!0,se(),$(es()))},ic),e.pollCompletionEndpoint!==!1&&(K=window.setInterval(()=>{z()},t)),u.addEventListener("load",Ce),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 v||await s()}finally{f.parentNode?.removeChild(f),l?.isConnected&&l.focus()}}async function xo(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,i=t.nonce??t.session.clientSecret,s=new ni(n,{telemetry:!1}),l=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,f=new AbortController,u=new AbortController,S=()=>{f.abort(o.reason),u.abort(o.reason)};o.aborted?S():o.addEventListener("abort",S,{once:!0});let v=rs({billingApiUrl:n,sessionId:r,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:f.signal,pollCompletionEndpoint:!1}),H=s.waitForCheckoutSessionCompletion(r,{initialDelayMs:iu,nonce:i,statusUrl:l,continueAfterActionRequired:!0,timeoutMs:ic+15e3,signal:u.signal}),$;try{let q=await Promise.race([v,H]);if("data"in q)$=q;else{if(q.status==="declined")throw wr({type:q.declineReason??"authorization_declined",gatewayErrorCode:q.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(q.status==="timeout")throw es();$=await H}}catch(q){if(o.aborted||q instanceof Error&&q.name==="AbortError")throw Yr(q);if(!(q instanceof wt)||q.code!=="three_ds_timeout"&&q.code!=="checkout_processing_timeout")throw q;try{$=await s.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:i,statusUrl:l,timeoutMs:5e3,signal:o})}catch(h){if(o.aborted)throw Yr(h);if(!(h instanceof wt)||h.code!=="checkout_processing_timeout")throw h}let K=$&&Kr($,t.session);if(!Dr(K)&&K?.status!=="expired"){if(t.telemetry){let h=new ni(n);try{h.reportThreeDsAbandoned(r)}finally{h.destroy()}}throw es()}}finally{o.removeEventListener("abort",S),f.abort(),u.abort()}let k=$&&Kr($,t.session);if(!Dr(k))throw Io(k);return{...Fr(k,r),checkoutMethod:"card"}}function du(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 wr(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=ns(new wt(i,"api_error",{code:e?.code??oc(e?.outcome)??oc(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function ts(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ti(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function lc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ti(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 l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||ti(l)))return l;let s=o.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let f=l,u=[f.stripeClientSecret,f.clientSecret];for(let S of u)if(typeof S=="string"&&S.length>0&&(!t?.requirePaymentIntentClientSecret||ti(S)))return S}}}}async function uu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=lc(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let l=(await new ni(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ti(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Bo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),f=t??n.id,u=r??n.clientSecret,S=n.customer?.id??n.accountData?.userId??"",v=n.customer?.email??n.accountData?.email??"",H=n.customer?.firstName??n.accountData?.firstName??"",$=n.customer?.lastName??n.accountData?.lastName??"",k=n.customer?.country??n.accountData?.country??void 0,q=n.customer?.zip??n.accountData?.zip??void 0,h=await new ni(l,s===!1?{telemetry:!1}:void 0).processPayment(S,{sessionId:f,nonce:u,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:S,email:v,firstName:H,lastName:$,country:k,zip:q},returnUrl:i??ts(n)});if(h.ok){let z=typeof h.json=="function"?await h.json().catch(()=>null):null;if(ou(n)||z?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof z?.paymentId=="string"?z.paymentId:n.paymentId,sessionId:typeof z?.sessionId=="string"?z.sessionId:f,authorizationExpiresAt:typeof z?.authorizationExpiresAt=="string"?z.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:la(o),checkoutMethod:ac(o,n)}};let Ce=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Ce?{paymentIntentId:Ce}:{},paymentMethodId:la(o),checkoutMethod:ac(o,n)}}}let C;try{C=await h.json()}catch(z){throw new wt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:h.status,cause:z})}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 z=lc(C);if(!z)throw new wt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:h.status});return{type:C.type,threeDSecureToken:z,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let z=await uu({billingApiUrl:l,sessionId:f,nonce:u,responseJson:C});if(z)return z;throw ns(new wt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let se=new wt(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(se,{telemetryOutcome:ru(h.status,C)})}async function ri(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:f,signal:u}){let S=t?.getRawProvider();if(!S)throw Nr(new wt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw ns(new wt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let v=au(e.threeDSecureToken),H=null,$=e.paymentMethodId,k=await ya(()=>su(S,e.threeDSecureToken,v),"card");if(k){if(k.error)throw Nr(new wt(k.error.message??`Failed to retrieve 3DS ${v?"setup":"payment"} status.`,"api_error",{code:k.error.code}),"card");let K=k.intent;!$&&K?.payment_method&&(typeof K.payment_method=="string"?$=K.payment_method:"id"in K.payment_method&&($=K.payment_method.id??void 0))}let q=$?await ya(()=>lu(S,e.threeDSecureToken,{payment_method:$,return_url:l??ts(s)??window.location.href},v),"card"):null;if(q){if(q.error)throw Nr(new wt(q.error.message??"3DS authentication failed.","api_error",{code:q.error.code}),"card");H=q.intent}else{let K=await ya(()=>S.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(K.error)throw Nr(new wt(K.error.message??"3DS authentication failed.","api_error",{code:K.error.code}),"card");H=(v?K.setupIntent:K.paymentIntent)??null}if(H&&(H.status==="requires_capture"||H.status==="succeeded"||H.status==="processing")){let K=await Bo({billingApiUrl:o,sessionId:i,session:s,telemetry:f,tokenizedData:{id:H.id,type:"card",threeDSecureActionResultTokenId:H.id},returnUrl:l});return K.type==="success"?{...K.result,paymentIntentId:K.result.paymentIntentId??H.id,paymentMethodId:K.result.paymentMethodId??$}:K.type==="next_action_required"?xo(K,{billingApiUrl:o,sessionId:i??s.id,session:s,signal:u}):ri(K,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:f,signal:u})}throw Nr(new wt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let v=(n??t)?.getRawProvider();if(!v)throw Nr(new wt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:$}=await ya(()=>v.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if($)throw Nr(new wt($.message??"PayPal authorization failed.","api_error",{code:$.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:H}=await ya(()=>v.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??ts(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(H)throw Nr(new wt(H.message??"PayPal authorization failed.","api_error",{code:H.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new wt("Unsupported payment redirect state.","api_error")}function ga(e){if(e instanceof wt){let r=$r(e.message);return r&&r!==e.message?Object.assign(new wt(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 wt(n,"api_error")}function os(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||qr(e.data.session);if(!t&&!n&&!r)throw new wt("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 ac(e,t){return e?e.isPaypal?"paypal":"card":t&&qr(t)?"card":void 0}async function as({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,l]=await Promise.all([rc(e,{billingApiUrl:n,locale:r,telemetry:o}),i?rc(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 wt("The payment provider did not initialize.","authentication_error");let f=null;return i?f=l:t&&(f=s),{flopay:s,paypalFlopay:f}}import{PaymentAPI as Do,PciVaultCardCapture as pu,toStripeAppearance as mu}from"@flopay/js";import{COUNTRY_OPTIONS as yu,classifyPaymentRejection as fu,FloPayError as ur,filterStripeMethodsByCountry as gu,getPostalCodeExample as hu,getPostalCodeLabel as ms,getStateFromPostalCode as cc,getStateLabel as is,getStateOptions as Pu,getStripeMethodDisplayName as va,isAuthorizationOnlySession as ss,isAVSFieldVisible as ot,isPostalCodeSupported as vu,isSetupIntentClientSecret as ls,isValidEmail as yn,isValidPostalCode as Cu,needsStripeMethodExplicitConfirm as dc,normalizeCheckoutFailureOutcome as bu,partitionStripeMethods as Su,randomUuidV4 as wu,resolveAVSConfig as Iu,resolveButtonsLayoutTheme as ku,resolveSetupFutureUsage as wc,resolveTheme as Ru,stripeExpressMethodToOptionKey as _u}from"@flopay/shared";import{ExpressCheckoutElement as Ic,PaymentElement as Eu,Elements as io,useElements as hs,useStripe as Ps}from"@stripe/react-stripe-js";import Tu,{useCallback as Je,useContext as Oo,useEffect as St,useMemo as ht,useRef as oe,useState as ue}from"react";function Fo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function oi(e,t){if(e)return{error:n=>e.error(Fo(t,n)),log:n=>e.log(Fo(t,n)),performance:n=>e.performance(Fo(t,n)),terminal:n=>e.terminal(Fo(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 No,jsx as y,jsxs as Ze}from"react/jsx-runtime";var Ir="flopay_stripe_resume",uc="flopay_wallet_resume",kc="fw1",Au="fw2",Rc=300*1e3,Mu=900,xu=25e3,Bu=25e3,Fu=1e4,_c=["payment_intent","payment_intent_client_secret","redirect_status"],dr={provider:"paypal",paymentMethodCategory:"paypal"},Du="x-flopay-process-result-source",Nu="status";async function Ou(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 ai={},cs={};function Ht(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function vs(e){return`${Au}:${e}`}function ii(e){return Ht(vs(e))}function si(e,t){if(typeof window>"u")return null;let n=vs(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>Rc||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(ii(e),null):o}catch{return ii(e),null}}function Lu(e){return Ht(vs(e.sessionId),e)}function pc(e,t,n){let r=si(e,t);return!r||r.clientSecret!==n?!1:ii(e)}function ds(e,t,n){if(typeof window>"u")return;si(e,t)?.clientSecret===n&&ii(e)}function Uu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function us(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":sa(e.status),o=Uu(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function mc(e,t,n){let r=null;try{return await Promise.race([zl(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},Fu),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function zu(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Ec(e){return e instanceof ur&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function li(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Do(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Ec(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Pa="flopay_paypal_resume",ha=new Map;function Tc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(Pa);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function qu(){if(typeof window>"u")return!1;let[e,t]=Cs();return e?Tc(t)!==null:!1}function Cs(){let e=new URLSearchParams(window.location.search);return _c.map(t=>e.get(t))}function bs(){let e=new URL(window.location.href);for(let t of _c)e.searchParams.delete(t);return e.toString()}function ju(){Ht(Pa),window.history.replaceState({},"",bs())}var $u=250,yc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Ku="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Ss(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 ci({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Do(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Hu(e){return e instanceof ur&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ps(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Ac({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=ro(n),s=i.firstName?i:ro(r?.name);return Dn({email:yn(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Wu({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let s=Ac({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return yn(s.email)?s:i(o,s)}var Ca=180,fc=`flopay-card-enter ${Ca}ms cubic-bezier(0, 0, 0.2, 1) both`,gc=`flopay-card-exit ${Ca}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Vu=`flopay-buttons-enter ${Ca}ms cubic-bezier(0, 0, 0.2, 1) both`,Gu=`flopay-buttons-exit ${Ca}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Yu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ws(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 Ju={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Xu(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 ys={width:"100%",minHeight:aa,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 Zu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function hc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function fs(e){return e==="paypal"?"PayPal":va(e)}function Qu(e){let t=hu(e);return`Enter a valid ${ms(e)}${t?` (e.g. ${t})`:""}`}function ep(e,t,n){let r=vu(e),o=t.trim(),i=n&&r,s=i&&!o,l=i&&!!o&&!Cu(e,o);return{visible:n,supported:r,required:i,empty:s,malformed:l}}function tp(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!yn(n);return{required:t,empty:r,malformed:o,value:n}}function Pc(e,t){return t instanceof ur?t:new ur(t instanceof Error?t.message:`${Zu(e)} before-click hook failed.`,"validation_error")}function np(e){return typeof e=="number"?`${e}px`:e}function Is(e){return y(rp,{...e})}function vc({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:f,onTechnicalFailure:u,runBeforeButtonClick:S,billingName:v,onBuyerIdentityReady:H,onLoadStateChange:$,placeholderBorderRadius:k,popupCapabilityOwner:q,externalTelemetryContext:K,presentationMode:h}){let C=Hr(),{emitInstrument:se}=Oo(Xn),z=Ps(),Ce=hs(),J=ht(()=>oi(un(C),K),[K,C]),[ke,qe]=ue("loading");St(()=>{$?.(ke)},[ke,$]);let[Re,it]=ue(!1),zt=oe(!1),me=!yn(n?.trim())||!v?.trim(),{request:Me,collect:Pt,finish:Te}=ko(),We=oe(!1),_e=oe(null),ne=oe(null),[je,$e]=ue(0),[yt,be]=ue(!1),ye=oe(!1),le=oe(new Map),{startAttempt:F,finishAttempt:Se,invalidateAttempt:Ue,isAttemptInvalidated:xe,isAttemptCurrent:V,generationRef:vt}=ua((T,re,Ne)=>{u?.(T,re,{...Ne,popupBlocked:Ne?.popupBlocked??zr(re),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h,terminalReason:"overlay_timeout"}),be(!0),$e(L=>L+1)},{onHandoffObserved:()=>{q.markAvailable(),J?.log({name:"provider.popup.opened",stage:"overlay_open",...dr,attempt:vt.current})}});St(()=>{yt&&ne.current?.focus()},[yt,je]);let ze=Je(()=>{$e(T=>T+1)},[]),Ae=Je((T,re,Ne)=>{Ue(Ne),u?.("paypal",T,{code:re,popupBlocked:zr(T),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h}),be(!0),ze()},[Ue,u,h,ze]),Xe=Je(()=>{window.setTimeout(()=>{(_e.current?.querySelector("iframe")??_e.current)?.focus()},0)},[]);St(()=>{ye.current&&(ye.current=!1,Xe())},[Xe,je]);let Be=Je(()=>{be(!1),i?.(null),Xe()},[Xe,i]);St(()=>{if(!z||We.current)return;let[T,re,Ne]=Cs();if(!T||!re)return;let L=Tc(re);if(!L)return;We.current=!0;let we=!0,gt=ha.get(re);gt||(gt=Ne==="failed"?Promise.resolve(null):Promise.resolve().then(()=>z.retrievePaymentIntent(re)),ha.set(re,gt));let Oe={accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce},It=()=>{J?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...dr,requestCategory:"provider_sdk"})};return J?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...dr}),(async()=>{try{it(!0);let p=await gt;if(!we)return;if(p?.error){ha.delete(re),It(),i?.(p.error.message??"Failed to retrieve PayPal payment status.");return}if(ju(),ha.delete(re),Ne==="failed"){let D="PayPal payment was declined. Please try again.";J?.terminal({outcome:"payment_declined",...dr,terminalReason:"provider_declined"}),i?.(D),f?.(dn("paypal",D));return}let g=p?.paymentIntent;if(g&&g.id!==T){It(),i?.("Failed to match the returned PayPal payment.");return}if(g&&(g.status==="requires_capture"||g.status==="succeeded")){let D=typeof g.payment_method=="string"?g.payment_method:g.payment_method?.id;o({id:D??g.id,type:"card",threeDSecureActionResultTokenId:g.id,isPaypal:!0},{...Oe,presentationMode:"redirect"})}else{let D="PayPal payment was not completed. Please try again.";J?.terminal({outcome:g?.status==="canceled"?"payment_cancelled":"payment_declined",...dr,terminalReason:g?.status==="canceled"?"cancelled":"provider_declined"}),i?.(D),f?.(dn("paypal",D))}}catch(p){if(!we)return;ha.delete(re),It(),i?.(p instanceof Error?p.message:"Failed to complete PayPal payment.")}finally{we&&it(!1)}})(),()=>{we=!1,We.current=!1}},[z,o,i,f,J]);let Qe=Je(async(T=!1)=>{let re=S?await S("paypal"):{proceed:!0};if(!re.proceed)return le.current.delete(je),!1;let Ne=F("paypal");return le.current.set(je,{generation:Ne,accountPatch:re.accountPatch,sessionId:re.sessionId,nonce:re.nonce}),be(!1),J?.log({name:`provider.${T?"redirect.started":"handoff.requested"}`,stage:T?"redirect":"overlay_open",...dr,attempt:Ne}),l?.("paypal"),!0},[l,J,S,F,je]),De=Je(async T=>{if(s||Re||!await Qe()){T.reject();return}T.resolve()},[s,Qe,Re]),Ct=Je(async T=>{if(!z||!Ce)return;let re=le.current.get(je);if(re&&!V(re.generation)){le.current.delete(je);return}if(!re&&xe()||re&&!Se(re.generation))return;re||Se();let Ne=re??null;if(le.current.delete(je),!Ne&&S){let M=await S("paypal");if(!M.proceed){T.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Ne={accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}}let L=Ne?.sessionId??e,we=Ne?.nonce??t,gt=await Wu({event:T,prepared:Ne,email:n,billingName:v,methodLabel:"PayPal",collect:Pt});if(!gt){T.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Oe=gt.email,It={...Ne?.accountPatch,...Dn(gt,!0)};try{if(it(!0),i?.(null),!L||!yn(Oe))throw new Error("Missing sessionId or email for PayPal payment");await H?.(gt);let M=z.createPaymentMethod,{error:p,paymentMethod:g}=await M({type:"paypal"});if(p){Ae(p,"stripe_paypal_create_payment_method_failed",re?.generation),T.paymentFailed({reason:"fail"});return}let D=await li(r,se,L,we??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:g?.id??null,intentKind:"payment"});if(D.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let x=D.clientSecret,ee={return_url:bs()};if(g?.id&&(ee.payment_method=g.id),!Ht(Pa,{clientSecret:x,sessionId:L,nonce:we,accountPatch:It})&&h==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:fe,paymentIntent:Ke}=await z.confirmPayment({clientSecret:x,confirmParams:ee,redirect:"if_required"});if(fe){if(Ht(Pa),Oa(fe)){let qt=fe.message??"Your payment was declined.";J?.terminal({outcome:"payment_declined",...dr,terminalReason:"provider_declined"}),i?.(qt),f?.(dn("paypal",qt,{code:Ur(fe),declineCode:ra(fe)})),await ci({billingApiUrl:r,sessionId:L,nonce:we,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ur(fe)??"provider_declined"}})}else Ae(fe,"stripe_paypal_confirm_failed",re?.generation);return}Ht(Pa);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:It,paymentMethodCategory:"paypal",presentationMode:h,sessionId:L,nonce:we});return}catch(M){Ae(M,"stripe_paypal_failed",re?.generation)}finally{it(!1)}},[z,Ce,e,t,n,v,Pt,H,r,se,o,i,f,S,Ae,Se,V,xe,J,h,je]),Vt=Je(async()=>{if(!(zt.current||s||Re||!z||!Ce)){zt.current=!0,it(!0);try{if(!await Qe(!0))return;await Ct({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{zt.current=!1,it(!1)}}},[Ce,Ct,s,Qe,z,Re]),ft=h==="redirect"?y("button",{type:"button",disabled:s||Re,onClick:()=>{Vt()},style:{width:"100%",minHeight:aa,border:"1px solid #d1d5db",borderRadius:k??8,background:"#ffc439",color:"#111827",cursor:s||Re?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):y(Ic,{onReady:T=>qe(Di(T,["paypal"])),onLoadError:()=>{qe("load_error"),Ss(J,"paypal","paypal","provider_error")},onClick:De,onConfirm:Ct,onCancel:()=>{let T=le.current.get(je);le.current.delete(je),J?.terminal({outcome:"payment_cancelled",...dr,terminalReason:"cancelled",...T?{attempt:T.generation}:{}}),Ue(T?.generation),be(!1),ye.current=!0,ze()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:me,emailRequired:me,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},je),Tt=Ze(No,{children:[Ze("div",{ref:_e,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[yt&&y("button",{ref:ne,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Be,style:ys,children:"Try PayPal again"}),Me&&y(Ro,{identity:Me.identity,methodLabel:Me.methodLabel,onComplete:Te,onCancel:()=>Te(null)},Me.id),y("div",{style:{display:Me?"none":void 0},children:ft})]}),Re&&!Me&&y(br,{status:"processing"})]});return h==="redirect"?Tt:y(Ni,{state:ke,placeholderTestId:"flopay-paypal-placeholder",borderRadius:k,children:Tt})}function Cc(e){return e==="apple_pay"||e==="google_pay"}function bc({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:f,onDecline:u,onTechnicalFailure:S,runBeforeButtonClick:v,billingName:H,onBuyerIdentityReady:$,onLoadStateChange:k,placeholderBorderRadius:q,popupCapabilityOwner:K,externalTelemetryContext:h}){let C=Hr(),{emitInstrument:se}=Oo(Xn),z=Ps(),Ce=hs(),J=ht(()=>oi(un(C),h),[h,C]),[ke,qe]=ue("loading");St(()=>{k?.(ke)},[ke,k]);let[Re,it]=ue(!1),zt=oe(!yn(n?.trim())||!H?.trim()).current,{request:me,collect:Me,finish:Pt}=ko(),Te=oe(null),We=oe(null),[_e,ne]=ue(0),[je,$e]=ue(!1),[yt,be]=ue(()=>si(e,t)?"blocked":"idle"),[ye,le]=ue("google_pay"),F=oe(null),Se=oe(!0),Ue=oe(!1),xe=oe("google_pay"),V=oe("google_pay"),vt=oe(null),ze=oe(null),Ae=oe(new Set),Xe=oe(null);St(()=>(Se.current=!0,()=>{Se.current=!1;for(let M of Ae.current)window.clearTimeout(M);Ae.current.clear()}),[]);let Be=oe(new Map),{startAttempt:Qe,finishAttempt:De,invalidateAttempt:Ct,isAttemptInvalidated:Vt,isAttemptCurrent:ft,generationRef:Tt}=ua((M,p,g)=>{S?.(M,p,{...g,popupBlocked:g?.popupBlocked??zr(p),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),le(M),$e(!0),ne(D=>D+1)},{onHandoffObserved:M=>{K.markAvailable(),J?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Tt.current,...M==="apple_pay"||M==="google_pay"?{walletType:M}:{}})},defersMissingTerminal:Cc,onMissingTerminalDeferred:(M,p)=>{let g=J?.now()??globalThis.performance?.now()??Date.now(),D=Xe.current,x=D?.generation===p?D.startedAt:g;J?.performance({stage:"overlay_return",durationMs:Math.max(0,g-x),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:p,...Cc(M)?{walletType:M}:{}}),J?.flush?.().catch(()=>{})}});St(()=>{je&&We.current?.focus()},[je,_e]);let T=Je(()=>{ne(M=>M+1)},[]),re=Je((M,p,g,D,x=!1)=>{Ct(D),S?.(M,p,{code:g,popupBlocked:zr(p),telemetryReported:x,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),le(M),$e(!0),T()},[Ct,S,T]),Ne=Je(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);St(()=>{Ue.current&&(Ue.current=!1,Ne())},[Ne,_e]);let L=Je(()=>{$e(!1),l?.(null),Ne()},[Ne,l]),we=Je(()=>{F.current?.()},[]);St(()=>{let M=si(e,t);if(!M)return;let p=!1,g=!1,D=async()=>{if(!g){g=!0,p||be("checking");try{let x=await mc(z,M.clientSecret,Ae.current);if(p)return;let ee=us(x,M.providerObjectId,ls(M.clientSecret));if(ee.kind==="confirmed"){if(!pc(e,t,M.clientSecret))return;F.current=null,be("idle"),s({id:ee.paymentMethodId,type:"card",threeDSecureActionResultTokenId:ee.intentId},{...M.accountPatch?{accountPatch:M.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(ee.kind==="terminal"){ds(e,t,M.clientSecret),F.current=null,be("idle"),le(M.paymentMethodType),$e(!0),T();return}be("blocked")}catch{p||be("blocked")}finally{g=!1}}};return F.current=D,be("blocked"),()=>{p=!0,F.current===D&&(F.current=null)}},[t,s,T,e,z]);let gt=Je(async M=>{let p=!1,g=Ve=>{p||(p=!0,M.paymentFailed({reason:"fail",...Ve?{message:Ve}:{}}))};if(!z||!Ce){g();return}let D=Be.current.get(_e);if(D&&!ft(D.generation)){Be.current.delete(_e),g();return}if(!D&&Vt()){g();return}if(D&&!De(D.generation)){g();return}D||De();let x=M.expressPaymentType??D?.method??xe.current,ee=D??null,ut=hc(x),fe;x==="apple_pay"?fe="apple_pay":x==="google_pay"&&(fe="google_pay");let Ke=D?.generation??Tt.current,X=J,qt=X?.now()??globalThis.performance?.now()??Date.now(),bt=new AbortController,At=!1,st=!1,ce=null,kn=e,Nn="processing",pn="other",jt="provider_runtime",On,Ln=new Promise((Ve,Le)=>{On=Le}),fn=window.setTimeout(()=>{At=!0,bt.abort(),On(ai)},xu),Mt=async(Ve,Le,Rn)=>{Nn=Ve,pn=Le,jt=Le==="intent_create"||Le==="session_claim"?"transport_error":"provider_runtime";let kt=X?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Rn,Ln])}finally{let Un=X?.now()??globalThis.performance?.now()??Date.now();X?.performance({stage:Ve,durationMs:Math.max(0,Un-kt),durationMode:"machine",requestCategory:Le,paymentMethodCategory:"wallet",provider:"stripe",...At?{statusClass:"timeout"}:{}})}};try{if(it(!0),l?.(null),!ee&&v){let he=await Mt("processing","other",v(ut));if(!he.proceed){g();return}ee={accountPatch:he.accountPatch,sessionId:he.sessionId,nonce:he.nonce}}let Ve=ee?.sessionId??e;kn=Ve;let Le=ee?.nonce??t,Rn=vt.current??ee?.accountPatch,kt=Ac({event:M,fallbackEmail:Rn?.email??n,fallbackName:[Rn?.firstName,Rn?.lastName].join(" ").trim()||H});if(!yn(kt.email)){g("Buyer details are required."),Me(fs(x),kt).then(he=>{he&&(vt.current=he)});return}vt.current=null;let Un={...ee?.accountPatch,...Dn(kt,!0)};await Mt("processing","session_claim",Promise.resolve($?.(kt)));let{error:mn}=await Mt("tokenization","provider_sdk",Ce.submit());if(mn){g(),re(x,mn,"stripe_wallet_submit_failed",D?.generation);return}if(!Ve)throw new Error("Missing sessionId or email for payment.");let $t={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:x,paymentMethodId:null,intentKind:o},Zt=JSON.stringify({sessionId:Ve,nonce:Le??"",request:$t}),Qn=ze.current,Hn=Qn?.retryIdentity===Zt?Qn.authorizationAttemptId:wu();ze.current={authorizationAttemptId:Hn,retryIdentity:Zt};let Qt=await Mt("processing","intent_create",li(r,se,Ve,Le??"",{...$t,authorizationAttemptId:Hn},{signal:bt.signal}));if(Qt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Rt=Qt.clientSecret,en=Lu({createdAt:Date.now(),sessionId:Ve,...Le?{nonce:Le}:{},clientSecret:Rt,providerObjectId:Qt.providerObjectId,paymentMethodType:x,accountPatch:Un});window.clearTimeout(fn),st=!0,X?.performance({stage:"callback",durationMs:Math.max(0,(X?.now()??globalThis.performance?.now()??Date.now())-qt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let nn=X?.now()??globalThis.performance?.now()??Date.now(),Dt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...fe?{walletType:fe}:{},attempt:Ke},an=!1,Ot=null;X?.log({name:"payment.provider_confirmation.started",...Dt}),ce=window.setTimeout(()=>{ce!==null&&Ae.current.delete(ce),an=!0;let he=X?.now()??globalThis.performance?.now()??Date.now();X?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Dt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,he-nn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),X?.flush?.().catch(()=>{}),Ot?.()},Bu),Ae.current.add(ce);let rn=(he,et)=>{ce!==null&&(window.clearTimeout(ce),Ae.current.delete(ce),ce=null);let m=X?.now()??globalThis.performance?.now()??Date.now(),Ge=Math.max(0,m-nn),W=he;an&&(he==="resolved"?W="resolved_late":he==="returned_error"?W="returned_error_late":W="rejected_late");let gn=et??(he==="resolved"?"approved":"provider_error");return X?.log({name:"payment.provider_confirmation.returned",...Dt,operationOutcome:W,terminalReason:gn}),X?.performance({...Dt,durationMs:Ge,durationMode:"buyer",operationOutcome:W,terminalReason:gn}),{durationMs:Ge,operationOutcome:W,terminalReason:gn}},Nt=!1,G=!1,er=he=>{if(!he||typeof he!="object")return null;let et=he;if(et.error)return null;let m=et.setupIntent??et.paymentIntent,Ge=us(m??null,void 0,!!et.setupIntent);return Ge.kind==="confirmed"?Ge:null},tr=he=>{if(Nt||D&&Tt.current!==D.generation)return;let et=er(he);if(!et)return;if(en&&!pc(Ve,Le,Rt)){Nt=!0;return}let{intentId:m,paymentMethodId:Ge}=et;Nt=!0,G=!0,ze.current=null,F.current=null,Se.current&&(be("idle"),it(!1));let W=`${kc}:${Ve}`;Ht(W,{createdAt:Date.now(),sessionId:Ve,nonce:Le,accountPatch:Un,paymentMethodId:Ge,providerIntentId:m,paymentMethodType:x});try{s({id:Ge,type:"card",threeDSecureActionResultTokenId:m},{accountPatch:Un,paymentMethodCategory:"wallet",sessionId:Ve,nonce:Le})}finally{Ht(W)}},nr=!1;Ot=async()=>{if(!(nr||Nt||G)){nr=!0,Se.current&&be("checking");try{let he=await mc(z,Rt,Ae.current);if(Nt||G)return;let et=ls(Rt),m=us(he,Qt.providerObjectId,et);if(m.kind==="confirmed"){tr(et?{setupIntent:he}:{paymentIntent:he});return}if(m.kind==="terminal"){if(G=!0,ds(Ve,Le,Rt),ze.current=null,F.current=null,!Se.current)return;be("idle"),g(),re(x,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",D?.generation,!0);return}Se.current&&!G&&(be("blocked"),it(!1))}catch{Se.current&&!G&&(be("blocked"),it(!1))}finally{nr=!1}}},F.current=Ot;let tn,_n;try{let he=await(ls(Rt)?z.confirmSetup({elements:Ce,clientSecret:Rt,redirect:"if_required"}):z.confirmPayment({elements:Ce,clientSecret:Rt,redirect:"if_required"}));if(!he||typeof he!="object"||(tn=he,!tn.error&&!er(tn)))throw cs;_n=rn(tn.error?"returned_error":"resolved",tn.error&&Oa(tn.error)?"provider_declined":void 0)}catch(he){let et=he===cs,m=rn(et?"returned_error":"rejected");if(X?.error({...et?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:ji(he),...Dt,operationOutcome:m.operationOutcome,durationMs:m.durationMs,statusClass:"unknown",terminalReason:m.terminalReason}),!Se.current||Nt)return;await Ot?.();return}let vn=tn.error;if(vn){if(!Se.current||Nt)return;if(Oa(vn)){G=!0,ds(Ve,Le,Rt),ze.current=null,F.current=null,be("idle");let he=vn.message??"Your payment was declined.";g(he),l?.(he),u?.(dn(ut,he,{code:Ur(vn),declineCode:ra(vn)})),ci({billingApiUrl:r,sessionId:Ve,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:x,providerDeclineReason:Ur(vn)??"provider_declined",...Qt.intentKind==="payment"&&Qt.providerObjectId.startsWith("pi_")?{providerIntentId:Qt.providerObjectId}:{}}})}else X?.error({...ji(vn),...Dt,operationOutcome:_n.operationOutcome,durationMs:_n.durationMs,statusClass:"unknown",terminalReason:_n.terminalReason}),await Ot?.();return}if(tr(tn),!Nt)throw new Error("Invalid provider returned for APM intent")}catch(Ve){if(Ve===ai){let Le=X?.now()??globalThis.performance?.now()??Date.now();X?.error({errorCode:zu(pn),stage:Nn,requestCategory:pn,paymentMethodCategory:"wallet",provider:"stripe",...fe?{walletType:fe}:{},operationOutcome:"watchdog_expired",checkoutSessionId:kn,durationMs:Math.max(0,Le-qt),statusClass:"timeout",failureCategory:jt,attempt:Ke,terminalReason:"provider_error"}),X?.flush?.().catch(()=>{})}g(),re(x,Ve,Ve===ai?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",D?.generation,Ve===ai)}finally{if(window.clearTimeout(fn),ce!==null&&(window.clearTimeout(ce),Ae.current.delete(ce)),!st){let Ve=X?.now()??globalThis.performance?.now()??Date.now();X?.performance({stage:"callback",durationMs:Math.max(0,Ve-qt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...At?{statusClass:"timeout"}:{}})}Se.current&&it(!1)}},[z,Ce,e,t,n,H,Me,$,r,se,o,s,l,u,v,re,De,ft,Vt,Tt,J,_e]),Oe=ht(()=>Il(i),[i]),It=ht(()=>i.map(_u),[i]);return Ze(No,{children:[y(Ni,{state:ke,placeholderTestId:"flopay-wallet-placeholder",borderRadius:q,children:Ze("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[je&&Ze("button",{ref:We,type:"button","data-testid":"flopay-wallet-retry-button",onClick:L,style:ys,children:["Try ",fs(ye)," again"]}),yt!=="idle"&&Ze("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:yt==="checking",style:ys,children:yt==="checking"?"Checking payment status\u2026":"Check payment status"})]}),me&&y(Ro,{identity:me.identity,methodLabel:me.methodLabel,onComplete:Pt,onCancel:()=>Pt(null)},me.id),yt==="idle"&&y("div",{style:{display:me?"none":void 0},children:y(Ic,{onReady:M=>{qe(Di(M,It))},onLoadError:M=>{qe("load_error"),Ss(J,"stripe","wallet","provider_error")},onClick:async M=>{let p=J?.now()??globalThis.performance?.now()??Date.now();xe.current=M.expressPaymentType,V.current=hc(M.expressPaymentType);let g=!0,D=window.setTimeout(()=>{g=!1,M.reject()},Mu),x=v?await v(V.current):{proceed:!0};if(window.clearTimeout(D),!g)return;if(!x.proceed){Be.current.delete(_e),M.reject();return}let ee=Qe(M.expressPaymentType);Xe.current={generation:ee,startedAt:p},Be.current.set(_e,{generation:ee,method:M.expressPaymentType,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),$e(!1),J?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ee,...M.expressPaymentType==="apple_pay"||M.expressPaymentType==="google_pay"?{walletType:M.expressPaymentType}:{}}),f?.(V.current),M.resolve()},onConfirm:gt,onCancel:()=>{let M=Be.current.get(_e);Be.current.delete(_e),J?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...M?{attempt:M.generation}:{}}),Ct(M?.generation),ze.current=null,$e(!1),Ue.current=!0,T()},options:{...kl,paymentMethods:Oe,emailRequired:zt,billingAddressRequired:zt}},_e)})]})}),Re&&y(br,{status:"processing"})]})}function Mc(e,t,n){let r=wc(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...r?{setupFutureUsage:r}:null}}function gs({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:f,onDecline:u,onCancel:S,runBeforeButtonClick:v,onButtonClick:H,isProcessing:$,submitButtonColor:k,submitButtonBorderRadius:q,submitButtonStyle:K,errorText:h}){let C=Hr(),{emitInstrument:se}=Oo(Xn),z=Ps(),Ce=hs(),[J,ke]=ue(!1),qe=oe(!1),[Re,it]=ue(!1),[zt,me]=ue("loading"),[Me,Pt]=ue(""),Te=!yn(r?.trim()),We=!Te||yn(Me.trim()),_e=Je(async()=>{if(!z||!Ce||$||qe.current||!Re)return;qe.current=!0,ke(!0);let ne=v?await v("card"):{proceed:!0};if(!ne.proceed){qe.current=!1,ke(!1);return}H?.("card");let je=ne.sessionId??t,$e=ne.nonce??n,yt=ro(o?.trim()),be=Dn({email:ne.accountPatch?.email?.trim()||r?.trim()||Me.trim(),firstName:ne.accountPatch?.firstName?.trim()||yt.firstName,lastName:ne.accountPatch?.lastName?.trim()||yt.lastName}),ye=be.email,le=Dn({...ne.accountPatch,...be});try{if(f?.(null),!yn(ye))throw new Error("A valid email address is required for payment.");await i?.(be);let F=await Ce.submit();if(F.error){f?.(F.error.message??"Payment failed.");return}let Se=[be.firstName,be.lastName].filter(Boolean).join(" "),Ue=await z.createPaymentMethod({elements:Ce,params:{billing_details:{email:ye,...Se?{name:Se}:{}}}});if(Ue.error||!Ue.paymentMethod){f?.(Ue.error?.message??"Failed to create payment method.");return}let xe=Ue.paymentMethod;if(!je||!ye)throw new Error("Missing sessionId or email for payment.");let V=xe.type||e,vt=await li(s,se,je,$e??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:V,paymentMethodId:null,intentKind:"payment"});if(vt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ze=vt.clientSecret;Ht(Ir,{clientSecret:ze,sessionId:je,nonce:$e,accountPatch:le,paymentMethodId:xe.id,paymentMethodType:xe.type??e,gateway:"stripe"});let{error:Ae,paymentIntent:Xe}=await z.confirmPayment({clientSecret:ze,confirmParams:{return_url:window.location.href,payment_method:xe.id},redirect:"if_required"});if(Ae){Ht(Ir);let De=Ae.message??"Payment failed.";f?.(De),u?.(dn("card",De,{code:Ae.code})),await ci({billingApiUrl:s,sessionId:je,nonce:$e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ae.code??"provider_declined"}});return}let Be=Xe?.status;if(!sa(Be)){Ht(Ir);let De=Be==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(De),u?.(dn("card",De,{code:Be??"missing_payment_intent"}));return}Ht(Ir);let Qe=typeof Xe?.payment_method=="string"?Xe.payment_method:Xe?.payment_method?.id;l({id:Qe??xe.id,type:"card",threeDSecureActionResultTokenId:Xe?.id,gateway:"stripe",paymentMethodType:xe.type??e},{accountPatch:le,paymentMethodCategory:"apm",sessionId:je,nonce:$e})}catch(F){f?.(F instanceof Error?F.message:"Payment failed. Please try again.")}finally{qe.current=!1,ke(!1)}},[z,Ce,$,Re,v,H,t,n,r,o,Me,i,s,se,e,l,f,u]);return Ze("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Te&&y("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Te&&Ze("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",y("input",{type:"email",autoComplete:"email",required:!0,value:Me,onChange:ne=>Pt(ne.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),y(Eu,{onReady:()=>me("ready"),onLoadError:()=>{me("load_error"),Ss(un(C),"stripe","apm")},onChange:ne=>{it(!!ne.complete)},options:{layout:Rl,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...yn(r?.trim())?{email:r?.trim()}:{}}}}}),y(_l,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{_e()},disabled:!Re||!We||J||$||zt!=="ready",color:k,borderRadius:q,style:K,children:J?"Processing\u2026":`Pay with ${va(e)}`}),h&&y(Eo,{margin:"0.75rem 0 0",children:h})]})}function Sc({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:f,futureUseSession:u,onTokenizedBody:S,onErrorChange:v,onButtonClick:H,onDecline:$,runBeforeButtonClick:k,onLoadStateChange:q,isProcessing:K=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:C=8,submitButtonStyle:se,buttonAppearance:z,themeId:Ce,onExpandApm:J,expandedApmMethod:ke}){let{emitInstrument:qe}=Oo(Xn),[Re,it]=ue(null),[zt,me]=ue(null),Me=oe(!1),{request:Pt,collect:Te,finish:We}=ko();St(()=>{s.length>0&&l?q?.("ready"):l||q?.("loading")},[s.length,l,q]);let _e=Je(async ye=>{if(!l||Me.current||K)return;Me.current=!0,me(ye);let le=k?await k("card"):{proceed:!0};if(!le.proceed){Me.current=!1,me(null);return}H?.("card");let F=le.sessionId??e,Se=le.nonce??t,Ue=ro([le.accountPatch?.firstName,le.accountPatch?.lastName].filter(Boolean).join(" ")||r),xe=Dn({email:le.accountPatch?.email?.trim()||n?.trim(),firstName:le.accountPatch?.firstName?.trim()||Ue.firstName,lastName:le.accountPatch?.lastName?.trim()||Ue.lastName});if(!yn(xe.email)){me(null);let ze=await Te(va(ye),xe);if(!ze){Me.current=!1;return}xe=ze,me(ye)}let V=xe.email,vt=Dn({...le.accountPatch,...xe});try{if(v?.(null),!F||!yn(V))throw new Error("Missing sessionId or email for payment.");await o?.(xe);let ze=await li(i,qe,F,Se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ye,paymentMethodId:null,intentKind:"payment"});if(ze.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ae=ze.clientSecret;Ht(Ir,{clientSecret:Ae,sessionId:F,nonce:Se,accountPatch:vt,paymentMethodType:ye,gateway:"stripe"});let{error:Xe,paymentIntent:Be}=await l.confirmPayment({clientSecret:Ae,confirmParams:{return_url:window.location.href,payment_method_data:{type:ye,billing_details:{name:[xe.firstName,xe.lastName].filter(Boolean).join(" "),...V?{email:V}:{}}}},redirect:"if_required"});if(Xe){Ht(Ir);let Ct=Xe.message??"Payment failed.";v?.(Ct),$?.(dn("card",Ct,{code:Xe.code})),await ci({billingApiUrl:i,sessionId:F,nonce:Se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ye,providerDeclineReason:Xe.code??"provider_declined"}});return}let Qe=Be?.status;if(!sa(Qe)){Ht(Ir);let Ct=Qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";v?.(Ct),$?.(dn("card",Ct,{code:Qe??"missing_payment_intent"}));return}Ht(Ir);let De=typeof Be?.payment_method=="string"?Be.payment_method:Be?.payment_method?.id;S({id:De??Be?.id,type:"card",threeDSecureActionResultTokenId:Be?.id,gateway:"stripe",paymentMethodType:ye},{accountPatch:vt,paymentMethodCategory:"apm",sessionId:F,nonce:Se})}catch(ze){v?.(ze instanceof Error?ze.message:"Payment failed. Please try again.")}finally{Me.current=!1,me(null)}},[l,K,k,H,e,t,n,Te,i,qe,r,o,S,v,$]),[ne,je]=ue(null),$e=J?ke??null:ne,yt=Je(ye=>{Me.current||K||$e&&$e!==ye||(dc(ye)?J?J(ye):je(ye):_e(ye))},[$e,K,_e,J]),be=ht(()=>ne?Mc(f,ne,u):null,[ne,f,u]);return y("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Pt?y(Ro,{identity:Pt.identity,methodLabel:Pt.methodLabel,onComplete:We,onCancel:()=>We(null)},Pt.id):s.map(ye=>{let le=ke===ye,F=zt===ye,Se=zt!==null&&zt!==ye||ke!=null&&ke!==ye;return Ze(Tu.Fragment,{children:[y(wl,{method:ye,themeId:Ce,submitting:F,disabled:Se,highlighted:le,hasNextStep:dc(ye),onClick:()=>yt(ye),backgroundColor:z?.backgroundColor,borderColor:z?.borderColor,textColor:z?.textColor,borderRadius:z?.borderRadius,fontFamily:z?.fontFamily}),!J&&ne===ye&&be&&l&&y(io,{stripe:l,options:be,children:y(gs,{method:ye,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:S,onErrorChange:v,onDecline:$,onCancel:()=>je(null),runBeforeButtonClick:k,onButtonClick:H,isProcessing:K,submitButtonColor:h,submitButtonBorderRadius:C,submitButtonStyle:se})},ye)]},ye)})})}function rp({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:i,onComplete:s,onError:l,onDecline:f,onTokenizedBody:u,firstName:S,lastName:v,chv:H,className:$,submitLabel:k,isProcessing:q,error:K,onErrorChange:h,showPayPal:C=!0,showStripe:se=!0,walletPresentation:z="auto",enabledPaymentMethods:Ce,enabledPaymentMethodCountries:J,showApplePay:ke=!0,showGooglePay:qe=!0,layout:Re="default",theme:it,buttonsTheme:zt,buttonsStyles:me,appearance:Me,cardButtonContent:Pt,cardBackButtonContent:Te,cardTitleContent:We,showSecurityFooter:_e,onButtonClick:ne,onBeforeButtonClick:je,onBuyerIdentityReady:$e,enableAVS:yt,cardFieldOrder:be,cardPreFormSlot:ye,avsLayout:le="row",country:F,zip:Se,addressLine1:Ue,addressLine2:xe,city:V,state:vt,onCountryChange:ze,onZipChange:Ae,avsCheck:Xe,checkoutType:Be,checkoutLayout:Qe,totalAmount:De=0,currency:Ct="usd",initialCardOpen:Vt=!1,directPaypal:ft,isSubscription:Tt=!1,session:T,dataAttachmentPending:re=!1,dataAttachmentRequiresIdentity:Ne=!1,debug:L=!1}){let we=Hr(),gt=$i(),Oe=Oo(cr),{emitInstrument:It}=Oo(Xn),M=oe(null);M.current||(M.current=Ka());let p=M.current,[,g]=ue(0),D=oe(null);D.current||(D.current=oa());let x=D.current,ee=ht(()=>({browser:x,capability:p,presentationMode:"popup"}),[x,p]),ut=T??Oe.session,fe=ht(()=>({futureUse:ut?.futureUse,futureUseUnsupported:ut?.futureUseUnsupported}),[ut?.futureUse,ut?.futureUseUnsupported]),Ke=ut?.gateways?.paypal?.providerObjectType??ft?.providerObjectType,X=re||Oe.claimPending===!0,qt=Ne||Oe.claimRequiresIdentity===!0,bt=X&&!qt,At=Vl(),st=n||At,[ce,kn]=ue(!1),[Nn,pn]=ue(null),[jt,On]=ue(F??""),[Ln,fn]=ue(Se??""),[Mt,Ve]=ue(Ue??""),[Le,Rn]=ue(xe??""),[kt,Un]=ue(V??""),[mn,$t]=ue(vt??""),[Zt,Qn]=ue(""),[Hn,Qt]=ue({}),Rt=oe(Se??""),en=oe(F??""),nn=oe(Ue??""),Dt=oe(xe??""),an=oe(V??""),Ot=oe(vt??""),rn=oe(""),Nt=oe({});St(()=>{let a=(P,U,ve,Z,ge)=>{if(Nt.current[P])return;let Xt=U?.trim();!Xt||Xt===ve.current||(ve.current=Xt,Z(Xt),ge?.(Xt))};a("country",F,en,On,ze),a("zip",Se,Rt,fn,Ae),a("addressLine1",Ue,nn,Ve),a("addressLine2",xe,Dt,Rn),a("city",V,an,Un),a("state",vt,Ot,$t)},[F,Se,Ue,xe,V,vt,ze,Ae]);let G=ht(()=>Iu(yt),[yt]),er=G!==null,tr=ht(()=>ss(T),[T]),nr=!!T?.vault?.html,tn=!!T?.gateways?.pcivault,_n=Ui(T),he=!!(T?.gateways?.stripe?.enabledPaymentMethods??Ce)?.includes("card")||qr(T),et=nr||he||tn,m=!!(se&&et&&e),[Ge,W]=ue(()=>Re!=="buttons"||Vt?e??null:null),[gn,zn]=ue(0),Gt=Re!=="buttons"||Vt||!!e&&Ge===e,En=T?.captureMethod,tt=oe(we);St(()=>{tt.current=we},[we]);let[rr,Zr]=ue(null);St(()=>{if(!m||!e||!Gt){Zr(null);return}let a=tt.current?tt.current.cardCapture({sessionId:e,captureMethod:En}):new pu({sessionId:e,captureMethod:En,billingApiUrl:st,telemetry:r});return Zr({sessionId:e,captureMethod:En,billingApiUrl:st,telemetry:r,capture:a}),()=>{a.unmount()}},[m,e,Gt,En,st,r]);let _t=m&&e&&Gt&&rr?.sessionId===e&&rr.captureMethod===En&&rr.billingApiUrl===st&&rr.telemetry===r?rr.capture:null,Tn=ht(()=>{let a=jt,P=G?ot(G.postal_code,a):!1;return ep(a,Ln,P)},[G,jt,Ln]),{avsInvalid:mr,invalidAvsFields:Wn}=ht(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!m||!G)return{avsInvalid:!1,invalidAvsFields:a};let P=jt,U=(ge,Xt)=>ot(ge,P)&&!Xt.trim(),ve={line1:U(G.address_line_1,Mt),city:U(G.city,kt),state:U(G.state,mn),zip:Tn.empty||Tn.malformed};return{avsInvalid:ve.line1||ve.city||ve.state||ve.zip,invalidAvsFields:ve}},[m,G,jt,Mt,kt,mn,Tn]),[Yt,or]=ue(!1),[An,Rr]=ue(!1),[Mn,yr]=ue(!1),[fr,_r]=ue({line1:!1,city:!1,state:!1}),qn=oe(!1),Vn=oe({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Er=oe(!1),xt=Je(a=>{Vn.current[a]=!0,Er.current=!0},[]),Cn=Je(a=>!qn.current&&Vn.current[a],[]),Gn=Je(a=>{Cn(a)&&_r(P=>P[a]?P:{...P,[a]:!0})},[Cn]),[Tr,Ar]=ue(()=>ps(T?.vault)),[He,sn]=ue(Vt&&et?"card":"buttons"),[ln,bn]=ue(null),Qr=He==="expanding"||He==="card",gr=T?.gateways?.stripe&&!_n?"stripe":void 0,Lr=Je(()=>{It?.({class:"card_surface",provider:gr})},[gr,It]),Sn=oe(null),cn=Je(a=>{Sn.current&&clearTimeout(Sn.current),Sn.current=setTimeout(()=>{Sn.current=null,a()},Ca)},[]);St(()=>()=>{Sn.current&&clearTimeout(Sn.current)},[]);let Mr=Je(()=>{Lr(),W(e??null),zn(a=>a+1),sn("expanding"),cn(()=>sn("card"))},[cn,Lr,e]),xn=Je(()=>{sn("collapsing"),cn(()=>sn("buttons"))},[cn]),w=Je(a=>{bn(a),sn("apm-expanding"),cn(()=>sn("apm-form"))},[cn]),R=Je(()=>{sn("apm-collapsing"),cn(()=>{sn("buttons"),bn(null)})},[cn]);St(()=>{Re==="buttons"&&Vt&&et&&(W(e??null),sn("card"))},[Re,Vt,et,e]);let[O,_]=ue(null),nt=oe(!1),pt=oe(null),j=oe("idle"),[Ee,B]=ue(!1),d=oe(Ee);d.current=Ee;let[c,I]=ue(()=>ft?.existingOrderId?{orderId:ft.existingOrderId,attempts:1}:null),E=oe(c);St(()=>{E.current=c},[c]);let Q=oe(null),ae=ht(()=>{if($e||Oe.claimBuyerIdentity||T?.buyerIdentified!==!1||!e||!t)return;let a=`${st}|${e}|${t}`;Q.current?.key!==a&&(Q.current={key:a,claim:wo(new Do(st,{telemetry:!1}),e,t,{...i?{userId:i}:{},...S?{firstName:S}:{},...v?{lastName:v}:{}})});let P=Q.current.claim;return async U=>{await P(U)}},[$e,Oe.claimBuyerIdentity,T?.buyerIdentified,e,t,st,i,S,v]),Fe=$e??Oe.claimBuyerIdentity??ae,at=K??Nn,pe=ht(()=>Ru(it),[it]),b=ht(()=>{let a=pe?.buttonsLayout??ku(zt);return me?{...a,...me,cardButton:{...a.cardButton,...me.cardButton},cardFormContainer:{...a.cardFormContainer,...me.cardFormContainer},backButton:{...a.backButton,...me.backButton},backButtonIcon:{...a.backButtonIcon,...me.backButtonIcon},submitButton:{...a.submitButton,...me.submitButton},title:{...a.title,...me.title}}:a},[pe,zt,me]),lt=Me??pe?.appearance,ie=ht(()=>vl({appearance:lt,buttonsStyles:b,layout:Re}),[lt,b,Re]),te=Oe.inlineSessionPatchProcessing??!1,A=(q??ce)||te,Y=st.replace(/\/+$/,""),N=ht(()=>qi({userId:i,email:o,firstName:S,lastName:v,country:F,zip:Se},Hn),[i,o,S,v,F,Se,Hn]),ct=[N.firstName,N.lastName].filter(a=>!!a?.trim()).join(" "),Ie=!yn(N.email?.trim()),ar=oe(null);m&&ar.current===null&&(ar.current=Ie);let wn=m&&(ar.current??Ie),yi=ht(()=>tp(Zt,wn),[Zt,wn]),lo=yi.empty||yi.malformed,jn=ht(()=>we?we.getRawProvider():null,[we]),Ds=ht(()=>gt?gt.getRawProvider():null,[gt]),jo=De||100,co=Ct.toLowerCase(),fi=ht(()=>lt?mu(lt):null,[lt]),uo=fi,Ns=ht(()=>{let a=fi??{},P=a.rules??{};return{...a,rules:{...P,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...P[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...P[".AccordionItemContents"]??{}}}}},[fi]),Os=ht(()=>({...ql(De,ut?.captureMethod,fe),currency:co,...uo?{appearance:uo}:null}),[De,co,ut?.captureMethod,fe,uo]),gi=wc(fe,"paypal","paypal"),Ls=ht(()=>({mode:"payment",amount:jo,currency:co,captureMethod:"manual",...gi?{setupFutureUsage:gi}:null,...uo?{appearance:uo}:null}),[jo,co,gi,uo]),Pe=Je(a=>{pn(a),h?.(a)},[h]),hi=oe(""),[Us,Kc]=ue(!1),Pi=Je(()=>{Kc(!0)},[]);St(()=>{if(!m||!wn||!Fe||!Us||lo||hi.current)return;let a=Dn({email:yn(N.email?.trim())?N.email?.trim():rn.current.trim(),firstName:N.firstName?.trim(),lastName:N.lastName?.trim()});hi.current=JSON.stringify(a),Qt(P=>({...P,...a})),Promise.resolve(Fe(a)).catch(P=>{hi.current="",Pe(P instanceof Error?P.message:"Failed to attach buyer details.")})},[m,wn,Fe,Us,lo,N.email,N.firstName,N.lastName,Pe]),St(()=>{!m||!_t||_t.setCardFieldOrder?.(be??null,G==null&&!wn)},[m,_t,be,G,wn]),St(()=>{(He==="expanding"||He==="collapsing"||He==="apm-expanding"||He==="apm-collapsing")&&Pe(null)},[He,Pe]);let hr=Je((a,P,U)=>{f?.(dn(a,P,U))},[f]),po=Je((a,P,U)=>{let ve=U?.popupBlocked??zr(P);ve&&p.markBlocked()&&g(Ye=>Ye+1);let Z=Na(fs(a),ve,x.inAppBrowser),ge=Ur(P),Xt=(ge?.toLowerCase()==="error"?void 0:ge)??Cl(U?.code)??"external_payment_method_failed",lr=new ur(Z,"api_error",{code:"external_payment_method_failed",param:a,details:{providerCode:Xt,popupBlocked:ve,inAppBrowser:x.inAppBrowser,appFamily:x.appFamily,popupCapability:p.current(),presentationMode:U?.presentationMode??"popup"}});U?.telemetryReported||un(we)?.error(Fo({...ee,presentationMode:U?.presentationMode??"popup"},{errorCode:ve?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:U?.provider??(a==="paypal"?"paypal":"stripe"),paymentMethodCategory:U?.paymentMethodCategory??(a==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:U?.terminalReason??(ve?"popup_blocked":"provider_error")})),_(null),Re==="buttons"&&(sn("buttons"),bn(null)),Pe(Z),l?.(lr),console.error("[FloPay] External payment method failed:",{method:a,code:Xt,popupBlocked:ve})},[x,ee,we,Re,l,p,Pe]);St(()=>{if(!m||!e){Ar(null);return}let a=ps(T?.vault);if(a){Ar(a);return}if(!Gt){Ar(null);return}Ar(null);let P=!0;return new Do(Y).getVaultCapture(e,t).then(U=>{if(!P)return;let ve=ps(U);ve?Ar(ve):Pe("Failed to load the secure card form.")}).catch(U=>{P&&Pe(U instanceof Error?U.message:"Failed to load the secure card form.")}),()=>{P=!1}},[m,Gt,gn,e,T?.vault,Y,t,Pe]);let ir=oe({onComplete:s,onError:l,updateError:Pe,emitDecline:hr,resolvedAccount:N,avsConfig:G,avsCheckProp:Xe,sessionId:e,nonce:t,baseUrl:Y,captureMethod:T?.captureMethod,paymentId:T?.paymentId,authorizationExpiresAt:T?.authorizationExpiresAt,serverSideCardGateway:_n});ir.current={onComplete:s,onError:l,updateError:Pe,emitDecline:hr,resolvedAccount:N,avsConfig:G,avsCheckProp:Xe,sessionId:e,nonce:t,baseUrl:Y,captureMethod:T?.captureMethod,paymentId:T?.paymentId,authorizationExpiresAt:T?.authorizationExpiresAt,serverSideCardGateway:_n};let vi=oe(!1),zs=Je(()=>{let a=ir.current,P=a.resolvedAccount.email?.trim(),U=yn(P)?P:rn.current.trim();if(!yn(U))return null;let ve=a.resolvedAccount.firstName?.trim(),Z=a.resolvedAccount.lastName?.trim(),ge=en.current.trim()||a.resolvedAccount.country?.trim()||"",Xt=a.avsConfig?ot(a.avsConfig.state,ge):!1,lr=a.avsConfig?ot(a.avsConfig.address_line_1,ge):!1,Ye=a.avsConfig?ot(a.avsConfig.postal_code,ge):!1,dt=a.avsConfig?ot(a.avsConfig.city,ge):!1,mt=a.avsConfig?ot(a.avsConfig.address_line_2,ge):!1,Lt=lr&&!Xt&&Ye?cc(ge,(Rt.current??"").trim()):null,xr=Xt?Ot.current:Lt;return{accountData:{userId:a.resolvedAccount.userId??"",email:U,...ve?{firstName:ve}:{},...Z?{lastName:Z}:{},...Ye&&Rt.current?{zip:Rt.current}:{},...dt&&an.current?{city:an.current}:{},...xr?{state:xr}:{},...lr&&nn.current?{addressLine1:nn.current}:{},...mt&&Dt.current?{addressLine2:Dt.current}:{},...ge?{country:ge}:{}},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:ot(a.avsConfig.country,ge),postal_code:Ye,address_line_1:lr,address_line_2:mt,city:dt,state:Xt}}:{}}},[]),qs=oe(X);qs.current=X,St(()=>{X||at!==yc||ir.current.updateError(null)},[X,at]),St(()=>{!m||!_t||_t.setSubmitGate?.(mr||X||lo||Ee)},[m,_t,mr,X,lo,Ee]),St(()=>{if(!m||!_t)return;vi.current=!1;let a=null,P=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,j.current="idle",_(null)},400)},U=_t.on("submitting",()=>{or(!0),pt.current&&clearTimeout(pt.current),j.current="validation-window",pt.current=setTimeout(()=>{pt.current=null,j.current==="validation-window"&&(j.current="processing")},$u),_("processing");let Ye=ir.current;if(!Ye.sessionId||!Ye.nonce)return;let dt=zs();if(!dt){Ye.updateError("Enter a valid email address."),j.current="idle",_(null);return}new Do(Ye.baseUrl).patchAccountSnapshot(Ye.sessionId,Ye.nonce,dt,{telemetryMode:"best_effort"}).catch(mt=>{if(!Hu(mt))return;let Lt=mt instanceof Error?mt.message:"Please check your billing address and try again.";Ye.updateError(Lt),j.current="idle",_(null),Ye.onError?.(mt instanceof ur?mt:new ur(Lt,"api_error"))})}),ve=_t.on("complete",async Ye=>{if(Mo(Ye.sessionId??ir.current.sessionId),j.current="terminal",B(!1),_("success"),await new Promise(xr=>setTimeout(xr,600)),vi.current)return;vi.current=!0;let dt=ir.current,mt=ss(dt)||Ye.outcome==="authorized",Lt=dt.serverSideCardGateway?{}:{paymentIntentId:Ye.intentId};ir.current.onComplete?.(mt?{status:"authorized",...Lt,paymentId:Ye.paymentId??dt.paymentId,sessionId:Ye.sessionId??dt.sessionId,authorizationExpiresAt:Ye.authorizationExpiresAt??dt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Lt,checkoutMethod:"card"})}),Z=_t.on("decline",Ye=>{let dt=ir.current,mt=Ye.message??"Your payment was declined. Please try another card or contact your bank.";j.current="terminal",B(!1),dt.updateError(mt),_("error");let Lt=Ye.failureOutcome??bu(Ye.declineReason)??"authorization_declined";dt.emitDecline("card",mt,{code:Lt,declineCode:Lt}),P()}),ge=_t.on("error",Ye=>{let dt=ir.current,mt=Ye.message??"There was a problem processing your payment. Please try again.";j.current="terminal",B(!1),dt.updateError(mt),_("error"),dt.onError?.(new ur(mt,"api_error",{code:Ye.failureOutcome??"capture_failed"})),P()}),Xt=_t.on("challenge_dismissed",()=>{pt.current&&(clearTimeout(pt.current),pt.current=null),j.current="processing",B(!0),_(null)}),lr=_t.on("blocked",()=>{if(d.current){ir.current.updateError(Ku);return}if(!qs.current){or(!0);return}Pi(),ir.current.updateError(yc)});return()=>{a&&(clearTimeout(a),a=null),pt.current&&(clearTimeout(pt.current),pt.current=null),j.current="idle",B(!1),_(null),U(),ve(),Z(),ge(),Xt(),lr()}},[m,_t,Pi,zs]);let Pr=!!ft?.clientId,$o=Array.isArray(Ce),ka=$o&&Ce.length>0,js=$o&&Ce.includes("paypal"),Ra=oe(null);Ra.current===null&&(Ra.current=qu());let mo=Ra.current?"redirect":Sl(x,z,p.current()),{expressMethods:_a,paymentElementMethods:Ko}=ht(()=>Su(Ce,{excludePaypal:Pr}),[Ce,Pr]),$s=Pr||!!gt||js&&mo==="redirect",Hc=ht(()=>$s?_a.filter(a=>a!=="paypal"):_a,[_a,$s]),Wc=ht(()=>{let a=[];return ke&&a.push("apple_pay"),qe&&a.push("google_pay"),a},[ke,qe]),yo=$o?Hc:Wc,Vc=se&&yo.length>0,Ci=er?jt:F,Ea=ht(()=>{let a=Ci?.trim().toUpperCase();return a?J?Ko.filter(P=>{let U=J[P];return!U||U.length===0||U.includes(a)}):gu(Ko,Ci):Ko},[Ko,Ci,J]),bi=ht(()=>({mode:"payment",amount:jo,currency:co,paymentMethodCreation:"manual",appearance:Ns}),[jo,co,Ns]),[Ks,Hs]=ue("loading"),[Ws,Vs]=ue("loading"),[Gs,Ys]=ue("loading"),[Gc,Si]=ue(!1),[Js,wi]=ue("loading"),[Ii,Yc]=ue();St(()=>{Yc(oa())},[]);let Ta=Ii?.inAppBrowser,Aa=Ii?La(Ii,ft?.approvalPresentation,Ke??(Tt?"subscription":"order")):"popup",Xs=C&&(Pr||($o?js:Ta===!1)),Zs=se&&Vc,Ho=(!bt||!!Oe.waitForDataAttachment)&&Xs&&Pr,Qs=Js==="retrying"||Js==="exhausted",Wo=null;se&&(gt?Wo=Ds:mo==="redirect"&&(Wo=jn));let el=ht(()=>({...ee,presentationMode:mo}),[ee,mo]),Vo=!bt&&Xs&&!!Wo&&(!Pr||Qs),fo=!bt&&Zs&&!!jn,Go=!bt&&se&&ka&&Ea.length>0&&!!jn,Jc=Ho&&!Qs?Gc:Vo&&Oi(Ks),Xc=fo&&Oi(Ws),Zc=Go&&Gs!=="load_error",tl=a=>a==="loading"||a==="ready",nl=Ho||Vo&&tl(Ks)||fo&&tl(Ws)||Go&&Gs!=="load_error",Ma=oe(!1);St(()=>{if(!Ma.current){if(!se&&!C){Ma.current=!0;let a=new ur("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(a),Pe(a.message)}else if(!se&&C&&!Pr){Ma.current=!0;let a=new ur("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(a),Pe(a.message)}else if(Ta!==void 0&&!bt&&!et&&!nl){Ma.current=!0;let a=new ur("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"});l?.(a),Pe(a.message)}}},[se,C,Pr,Ta,bt,et,nl,l,Pe]);let rl=oe(!1);St(()=>{if(rl.current||!ka)return;let a=[];ke!==!0&&a.push("showApplePay"),qe!==!0&&a.push("showGooglePay"),a.length!==0&&(rl.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.`))},[ka,ke,qe]);let ol=Je((a,P)=>Oe.applyInlineSessionPatch?Oe.applyInlineSessionPatch(a).then(U=>({error:null,sessionId:U.sessionId||e,nonce:U.session?.clientSecret||t})).catch(U=>{let ve=Pc(P,U);return Pe(ve.message),l?.(ve),{error:ve,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Oe.applyInlineSessionPatch,t,l,e,Pe]),sr=Je(async a=>{if(a!=="card"&&bt&&await Oe.waitForDataAttachment?.(),!je)return{proceed:!0};try{let P=await je({method:a,sessionId:e||void 0,createSession:Oe.inlineSessionDraft});if(P===!1)return{proceed:!1};if(P&&typeof P=="object"){P.account&&Qt(ve=>({...ve??{},...P.account}));let U=await ol(P,a);return U.error?{proceed:!1,accountPatch:P.account}:{proceed:!0,accountPatch:P.account,sessionId:U.sessionId,nonce:U.nonce}}return{proceed:!0}}catch(P){let U=Pc(a,P);return Pe(U.message),l?.(U),{proceed:!1}}},[ol,Oe.inlineSessionDraft,Oe.waitForDataAttachment,bt,je,l,e,Pe]),al=Je(async(a,P)=>{if(nt.current)return;nt.current=!0,kn(!0),_("processing"),Pe(null);let U=P?.sessionId??e,ve=P?.nonce??t,Z=qi(N,P?.accountPatch),ge=P?.completionPaymentMethodId??la(a),Xt=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,lr=Yu(a),Ye=P?.presentationMode?oi(un(we),{...ee,presentationMode:P.presentationMode}):void 0,dt=()=>{It?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:lr}),Ye?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...dr,requestCategory:"process_payment"})};try{let mt=new Do(Y),Lt=await mt.processPayment(Z.userId??"",{sessionId:U,nonce:ve,paymentMethodCategory:P?.paymentMethodCategory??Xu(a),tokenizedData:Xt,accountData:{...P?.accountPatch,userId:Z.userId??"",email:Z.email??"",firstName:Z.firstName||void 0,lastName:Z.lastName||void 0,...G?(()=>{let Et=en.current,vr=ot(G.state,Et),Kn=ot(G.address_line_1,Et),Cr=ot(G.postal_code,Et),no=Kn&&!vr&&Cr?cc(Et,(Rt.current??"").trim()):null,ea=vr?Ot.current:no;return{country:Et,...Cr&&Rt.current?{zip:Rt.current}:{},...ot(G.city,Et)&&an.current?{city:an.current}:{},...ea?{state:ea}:{},...Kn&&nn.current?{addressLine1:nn.current}:{},...ot(G.address_line_2,Et)&&Dt.current?{addressLine2:Dt.current}:{}}})():{}},chv:H,avsCheck:Xe??!1,checkoutType:Be,checkoutLayout:Qe,avsConfig:G?{country:ot(G.country,en.current),postal_code:ot(G.postal_code,en.current),address_line_1:ot(G.address_line_1,en.current),address_line_2:ot(G.address_line_2,en.current),city:ot(G.city,en.current),state:ot(G.state,en.current)}:void 0}),xr=async Et=>{let vr=ss(T)||Et?.status==="authorized";Mo(U),Ye?.terminal({outcome:"payment_succeeded",...dr}),_("success"),I(null),await new Promise(no=>setTimeout(no,600));let Kn;typeof Et?.paymentId=="string"?Kn=Et.paymentId:T?.paymentId&&(Kn=T.paymentId);let Cr;typeof Et?.authorizationExpiresAt=="string"?Cr=Et.authorizationExpiresAt:T?.authorizationExpiresAt&&(Cr=T.authorizationExpiresAt),s?.(vr?{status:"authorized",...Kn===void 0?{}:{paymentId:Kn},sessionId:typeof Et?.sessionId=="string"?Et.sessionId:U,...Cr===void 0?{}:{authorizationExpiresAt:Cr},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ge,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:ge,checkoutMethod:a.isPaypal?"paypal":"card"})};if(Lt.ok){await xr(Lt.status===204?null:await Lt.json().catch(()=>null));return}let $n=await Lt.json().catch(()=>null);if($n?.type==="paypal_redirect_required"){let Et=$n.threeDSecureToken,vr=$n.paymentMethodId||a.id||"";if(!we||!Et){_("error"),Pe("PayPal authorization required but no token provided.");return}try{let Kn=gt?.getRawProvider();if(!Kn){Pe("PayPal is not available.");return}let Cr={return_url:window.location.href};vr&&(Cr.payment_method=vr);let{error:no}=await Kn.confirmPayment({clientSecret:Et,confirmParams:Cr,redirect:"if_required"});if(no){_("error");let ea=no.message??"PayPal payment failed.";Pe(ea),hr("paypal",ea,{code:no.code})}}catch(Kn){_("error"),Pe(Kn instanceof Error?Kn.message:"PayPal authorization failed.")}return}if($n?.type==="paypal_direct_required"){let Et=$n.orderId;if(!Et){_("error"),Pe("PayPal retry required but no order id provided.");return}let vr=E.current?.attempts??0;if(vr>=2){_("error"),Pe("PayPal payment could not be completed after multiple attempts."),hr("paypal","paypal_direct_required retry limit exceeded");return}Si(!1),wi("loading"),I({orderId:Et,attempts:vr+1}),_(null);return}if(Lt.headers.get(Du)===Nu){let Et=await Ou(mt,U,ve);if(Et!==void 0){await xr(Et);return}}fu(Lt.status,$n)?Ye?.terminal({outcome:"payment_declined",...dr,terminalReason:"provider_declined"}):dt(),_("error");let gl=$n?.message??"Payment failed. Please try again.";Pe(gl),hr(a.isPaypal?"paypal":"card",gl,{code:$n?.code??$n?.gatewayErrorCode,declineCode:$n?.declineCode??$n?.gatewayDeclineReason}),await new Promise(Et=>setTimeout(Et,400))}catch(mt){Ec(mt)||dt(),_("error"),Pe(mt instanceof Error?mt.message:"An unexpected error occurred"),await new Promise(Lt=>setTimeout(Lt,400))}finally{kn(!1),_(null),nt.current=!1}},[Y,e,t,N,G,Xe,Be,Qe,H,we,gt,T,s,Pe,hr,It,ee]),Bn=Je((a,P)=>{u?u(a):al(a,P)},[u,al]),Yo=`${kc}:${e}`;St(()=>{if(typeof window>"u")return;let a=localStorage.getItem(Yo);if(!a)return;let P;try{P=JSON.parse(a)}catch{Ht(Yo);return}if(!P||typeof P.createdAt!="number"||Date.now()-P.createdAt<0||Date.now()-P.createdAt>Rc||typeof P.paymentMethodId!="string"||typeof P.providerIntentId!="string"||typeof P.paymentMethodType!="string"||P.sessionId!==e||!t||P.nonce!==t||!yo.includes(P.paymentMethodType)){Ht(Yo);return}Ht(Yo),Bn({id:P.paymentMethodId,type:"card",threeDSecureActionResultTokenId:P.providerIntentId,gateway:"stripe",paymentMethodType:P.paymentMethodType},{...P.accountPatch?{accountPatch:P.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Bn,t,e,Yo,yo]);let il=oe(!1);St(()=>{if(typeof window>"u"||il.current)return;let[a,P,U]=Cs();if(!a||!P||Ra.current||!we)return;let ve=we.getRawProvider();if(!ve)return;let Z=dt=>{let mt=localStorage.getItem(dt);if(!mt)return null;try{return JSON.parse(mt)}catch{return Ht(dt),null}},ge=Z(Ir)??Z(uc),Xt;if(ge?.clientSecret){if(ge.clientSecret!==P)return;Xt={...ge.accountPatch?{accountPatch:ge.accountPatch}:{},...ge.sessionId?{sessionId:ge.sessionId}:{},...ge.nonce?{nonce:ge.nonce}:{}}}else if(ge?.sessionId&&ge.sessionId!==e)return;il.current=!0,Ht(Ir),Ht(uc),window.history.replaceState({},"",bs());let lr=ge?.paymentMethodType??ge?.tokenType??"card",Ye="card";(async()=>{if(U==="failed"){let Br="Payment was declined. Please try again.";Pe(Br),hr(Ye,Br);return}let{paymentIntent:dt,error:mt}=await ve.retrievePaymentIntent(P);if(mt){let Br=mt.message??"Failed to retrieve payment status.";Pe(Br),hr(Ye,Br,{code:mt.code});return}let Lt=dt?.status,xr=sa(Lt);if(!dt||!xr){let Br=Lt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Pe(Br),hr(Ye,Br,{code:Lt??"missing_payment_intent"});return}let $n=typeof dt.payment_method=="string"?dt.payment_method:dt.payment_method?.id;Bn({id:$n??ge?.paymentMethodId??ge?.tokenId??dt.id,type:"card",threeDSecureActionResultTokenId:dt.id,gateway:ge?.gateway??"stripe",paymentMethodType:lr},Xt)})()},[e,Bn,we,Pe,hr]);let ki=Je(a=>{a.preventDefault()},[]);if(!(m||we!==null))return y("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Jo=Re==="buttons",Fn=lt?.variables,Qc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ri=Fn?.colorBackground,ed=Ri&&!Qc.has(Ri)?Ri:void 0,Xo=b.cardInputBorder??(Jo?"#e5e7eb":"#A4A4FF"),sl=Fn?.colorDanger??"#dc2626",Kt=a=>Wn[a]&&(fr[a]||Yt),xa=lo&&(Mn||Yt),Yn=a=>a?sl:Xo,Ba=(Tn.malformed||Tn.empty)&&(An||Yt),td=Yn(Ba),_i=b.cardFormContainer?.backgroundColor??ed??(Jo?"white":"#EDEDFF"),go=b.cardInputBackground??Fn?.colorBackground??"white",Ei=vo(Te),ll=vo(We),ho=b.nameInput,cl=b.cardInputFontSize??np(ho?.fontSize)??Fn?.fontSizeBase??"16px",dl=typeof ho?.fontFamily=="string"?ho.fontFamily:Fn?.fontFamily??"Poppins, sans-serif",ul=Pl(ho?.fontWeight)??400,nd=b.cardInputColor??(typeof ho?.color=="string"?ho.color:void 0)??Fn?.colorText??"#262833",rd=b.cardInputPlaceholderColor??"#9ca3af",Jt=Fn?.borderRadius??"8px",eo=Fn?.borderRadius??b.cardButton?.borderRadius??Jt,to=Fn?.colorPrimary??"#4A49FF",od=Fn?.colorPrimaryHover??na(to,.12),Ti=Fn?.colorText??"#262833",Ai={fontSize:cl,fontFamily:dl,fontWeight:ul,color:nd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Zo={marginTop:"0.375rem",...Ai,fontSize:"0.75rem",lineHeight:1.4,color:sl},ad={"--flopay-input-placeholder-color":rd,"--flopay-input-font-size":cl,"--flopay-input-font-family":dl,"--flopay-input-font-weight":String(ul)},Qo=b.cardFormContainer??{},Mi=Qo.padding??(Jo?"0":"1rem"),xi=Qo.borderRadius??Jt,id=_t&&Tr?y(Bi,{capture:_t,html:Tr.html,messageToken:Tr.messageToken,expectedOrigin:Tr.expectedOrigin,theme:ie,submitLabel:k,onReady:()=>{if(!wn&&!G||typeof document>"u")return;let a=()=>{let U=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(U){qn.current=!0;try{U.focus()}finally{qn.current=!1}}};Er.current||a()},onError:a=>Pe(a),onValidation:a=>{let P=j.current;(P==="idle"||P==="validation-window")&&(Pe(a),a&&j.current==="validation-window"&&(pt.current&&(clearTimeout(pt.current),pt.current=null),j.current="idle",_(null)))}}):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"}),pl=Ze("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&Lr()},style:{backgroundColor:_i,borderRadius:xi,...Qo,padding:Mi,...ad,display:"flex",flexDirection:"column"},children:[y("style",{children:`
|
|
5
5
|
.flopay-shared-input::placeholder {
|
|
6
6
|
color: var(--flopay-input-placeholder-color);
|
|
7
7
|
opacity: 1;
|
|
@@ -9,13 +9,13 @@ ${Tt.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,yl=He==="apm-expanding"||He==="apm-form"||He==="apm-collapsing",ho;He==="apm-expanding"?ho=yc:He==="apm-collapsing"&&(ho=fc);let Fa=ln?Ac(bi,ln,fe):null;if(Re==="buttons"){let a=He==="buttons"||He==="expanding"||He==="apm-expanding",P=He==="expanding"||He==="card"||He==="collapsing",z=gt===void 0?{boxSizing:"border-box",height:oa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},be;He==="expanding"||He==="apm-expanding"?be=$u:(He==="collapsing"||He==="apm-collapsing")&&(be=ju);let X;return He==="expanding"?X=yc:He==="collapsing"&&(X=fc),Xe("form",{onSubmit:Ii,className:$,noValidate:!0,style:{position:"relative"},children:[y(La,{}),O&&y(Sr,{status:O,errorMessage:at,authorized:tr}),Xe("div",{style:{display:"grid"},children:[Xe("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!be?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!be?Hu:{},...be?{animation:be,pointerEvents:"none"}:{}},children:[pl("flopay-direct-paypal-gate-debug"),ml("flopay-stripe-gate-debug"),Ko&&mt&&Xe(Do,{children:[c&&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(ca.Provider,{value:p,children:y(Va,{sessionId:e,nonce:t,billingApiUrl:st,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:Fe,clientId:mt.clientId,environment:mt.environment,currency:Pt.toUpperCase(),isSubscription:Et,providerObjectType:Ke,approvalPresentation:Ta==="popup"?void 0:Ta,onTokenizedBody:Fn,onComplete:s,onErrorChange:Pe,onDecline:f,onTechnicalFailure:uo,onButtonClick:ne,runBeforeButtonClick:sr,isProcessing:A,onLoadStateChange:Ci,onInitializationStateChange:Si,session:vt,existingOrderId:c?.orderId,debug:L},c?.orderId??"fresh")})]}),Vo&&y(ao,{stripe:Ho,options:Os,children:y(Pc,{sessionId:e,nonce:t,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,onTokenizedBody:Fn,onErrorChange:Pe,isProcessing:A,onButtonClick:ne,onDecline:f,onTechnicalFailure:uo,runBeforeButtonClick:sr,onLoadStateChange:Ks,placeholderBorderRadius:Qr,popupCapabilityOwner:p,externalTelemetryContext:Qs,presentationMode:po})}),yo?y(ao,{stripe:$n,options:Ns,children:y(bc,{sessionId:e,nonce:t,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,intentKind:De>0?"payment":"setup",expressMethods:mo,onTokenizedBody:Fn,onErrorChange:Pe,onButtonClick:ne,onDecline:f,onTechnicalFailure:uo,runBeforeButtonClick:sr,onLoadStateChange:Vs,placeholderBorderRadius:Qr,popupCapabilityOwner:p,externalTelemetryContext:ee})}):null,!yo&&Zs?y("div",{style:{height:oa,borderRadius:Qr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Wo&&y(Cc,{sessionId:e,nonce:t,email:N.email,billingName:[N.firstName,N.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,paymentElementMethods:_a,stripeInstance:$n,paymentElementBaseOptions:bi,futureUseSession:fe,onTokenizedBody:Fn,onErrorChange:Pe,onButtonClick:ne,onDecline:f,runBeforeButtonClick:sr,onLoadStateChange:Gs,isProcessing:A,submitButtonColor:eo,submitButtonBorderRadius:Jt,submitButtonStyle:C.submitButton,onExpandApm:w,expandedApmMethod:ln,themeId:it,buttonAppearance:{backgroundColor:C.cardButton?.backgroundColor,borderColor:C.cardInputBorder,textColor:C.cardButton?.color,borderRadius:Qr}}),m&&y("button",{type:"button",onClick:async()=>{A||!(await sr("card")).proceed||(ne?.("card"),xr())},disabled:A,style:{width:"100%",...z,...C.cardButton,...Ss({themeBundle:pe,resolvedPrimaryColor:eo,resolvedBorderRadius:Jt,submitButtonStyle:C.submitButton,explicitPrimaryColor:Dn?.colorPrimary}),fontSize:C.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:A?"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:A?.6:1},onMouseEnter:ge=>{!A&&(pe||Dn?.colorPrimary)&&(ge.currentTarget.style.backgroundColor=rd)},onMouseLeave:ge=>{(pe||Dn?.colorPrimary)&&(ge.currentTarget.style.backgroundColor=eo)},onMouseDown:ge=>{ge.currentTarget.style.transform="scale(0.985)"},onMouseUp:ge=>{ge.currentTarget.style.transform="scale(1)"},children:y(vo,{content:gt})}),at&&He==="buttons"&&y(_o,{margin:"0.25rem 0",styleOverride:C.errorBanner,children:at})]}),m&&P&&y("div",{style:{gridArea:"1 / 1",...X?{animation:X}:{},...He==="collapsing"?{pointerEvents:"none"}:{}},children:ul}),se&&yl&&ln&&Fa&&$n&&y("div",{style:{gridArea:"1 / 1",...ho?{animation:ho}:{},...He==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Xe("div",{style:{backgroundColor:Ri,borderRadius:Mi,...Xo,padding:Ai},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:R,style:{display:"inline-flex",alignItems:"center",gap:_i?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:C.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...C.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",...C.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(bo,{content:Te})]}),y("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:C.titleFontSize??"1.05rem",color:Ei,paddingRight:80,...C.title},children:`Pay with ${Pa(ln)}`})]}),y(ao,{stripe:$n,options:Fa,children:y(fs,{method:ln,sessionId:e,nonce:t,email:N.email,billingName:[N.firstName,N.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,onTokenizedBody:Fn,onErrorChange:Pe,onDecline:f,onCancel:R,runBeforeButtonClick:sr,onButtonClick:ne,isProcessing:A,submitButtonColor:eo,submitButtonBorderRadius:Jt,submitButtonStyle:C.submitButton,errorText:at})},ln)]})})]})]})}return yl&&ln&&Fa&&$n&&se?Xe("form",{onSubmit:Ii,className:$,noValidate:!0,style:{position:"relative"},children:[y(La,{}),O&&y(Sr,{status:O,errorMessage:at,authorized:tr}),y("div",{style:{...ho?{animation:ho}:{},...He==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Xe("div",{style:{backgroundColor:Ri,borderRadius:Mi,...Xo,padding:Ai},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:R,style:{display:"inline-flex",alignItems:"center",gap:_i?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:C.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...C.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",...C.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(bo,{content:Te})]}),y("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:C.titleFontSize??"1.05rem",color:Ei,paddingRight:80,...C.title},children:`Pay with ${Pa(ln)}`})]}),y(ao,{stripe:$n,options:Fa,children:y(fs,{method:ln,sessionId:e,nonce:t,email:N.email,billingName:[N.firstName,N.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,onTokenizedBody:Fn,onErrorChange:Pe,onDecline:f,onCancel:R,runBeforeButtonClick:sr,onButtonClick:ne,isProcessing:A,submitButtonColor:eo,submitButtonBorderRadius:Jt,submitButtonStyle:C.submitButton,errorText:at})},ln)]})})]}):Xe("form",{onSubmit:Ii,className:$,noValidate:!0,style:{position:"relative"},children:[y(La,{}),O&&y(Sr,{status:O,errorMessage:at,authorized:tr}),Xe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[pl("flopay-direct-paypal-gate-debug-default"),ml("flopay-stripe-gate-debug-default"),Ko&&mt&&Xe(Do,{children:[c&&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(ca.Provider,{value:p,children:y(Va,{sessionId:e,nonce:t,billingApiUrl:st,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:Fe,clientId:mt.clientId,environment:mt.environment,currency:Pt.toUpperCase(),isSubscription:Et,providerObjectType:Ke,approvalPresentation:Ta==="popup"?void 0:Ta,onTokenizedBody:Fn,onComplete:s,onErrorChange:Pe,onDecline:f,onTechnicalFailure:uo,onButtonClick:ne,runBeforeButtonClick:sr,isProcessing:A,onLoadStateChange:Ci,onInitializationStateChange:Si,session:vt,existingOrderId:c?.orderId,debug:L},c?.orderId??"fresh")})]}),Vo&&y(ao,{stripe:Ho,options:Os,children:y(Pc,{sessionId:e,nonce:t,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,onTokenizedBody:Fn,onErrorChange:Pe,isProcessing:A,onButtonClick:ne,onDecline:f,onTechnicalFailure:uo,runBeforeButtonClick:sr,onLoadStateChange:Ks,placeholderBorderRadius:Qr,popupCapabilityOwner:p,externalTelemetryContext:Qs,presentationMode:po})}),yo&&y(ao,{stripe:$n,options:Ns,children:y(bc,{sessionId:e,nonce:t,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,intentKind:De>0?"payment":"setup",expressMethods:mo,onTokenizedBody:Fn,onErrorChange:Pe,onButtonClick:ne,onDecline:f,onTechnicalFailure:uo,runBeforeButtonClick:sr,onLoadStateChange:Vs,placeholderBorderRadius:Qr,popupCapabilityOwner:p,externalTelemetryContext:ee})}),Wo&&y(Cc,{sessionId:e,nonce:t,email:N.email,billingName:[N.firstName,N.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:st,paymentElementMethods:_a,stripeInstance:$n,paymentElementBaseOptions:bi,futureUseSession:fe,onTokenizedBody:Fn,onErrorChange:Pe,onButtonClick:ne,onDecline:f,runBeforeButtonClick:sr,onLoadStateChange:Gs,isProcessing:A,submitButtonColor:eo,submitButtonBorderRadius:Jt,submitButtonStyle:C.submitButton,themeId:it,onExpandApm:w,expandedApmMethod:ln,buttonAppearance:{backgroundColor:C.cardButton?.backgroundColor,borderColor:C.cardInputBorder,textColor:C.cardButton?.color,borderRadius:Qr}})]}),m&&(Jc||Yc||Zc)&&y(gl,{label:"or pay with card"}),m&&ul]})}import{Fragment as Rr,jsx as de,jsxs as on}from"react/jsx-runtime";var Oo=44,As="flopay_checkout_saved_payment_resume",pi=new Map,di=new Map;function xc(e,t){t.settled&&t.consumers===0&&pi.get(e)===t&&pi.delete(e)}function ip(e,t,n){let r=di.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};di.set(e,i);let s=()=>{di.get(e)===i&&di.delete(e)};return o.then(s,s),o}function ba(e){return new Promise(t=>setTimeout(t,e))}function ui(e,t,n){let r=Ka({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:zc,enabled:t!==!1});return r.beginCheckout(n),r}function Ca(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ks(e,t,n,r,o,i){let s=ui(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),Ca(s)}function Bc(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 Fc(e,t,n,r,o){let i=Lc(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 vn&&t.code==="session_auto_completed"?!1:t instanceof vn&&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 qc(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 Rs(e){return!e||e.data.stripe?.publishableKey?!1:!!qc(e)?.clientId}var sp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function lp(e){return new Qu(sp,{publishableKey:"provider_unavailable",...e})}async function _s(e,t){let{publishableKey:n,paypalPublishableKey:r}=rs(e);return{...await os({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Ms(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function cp(){if(!Ms())return null;try{let e=window.sessionStorage.getItem(As);return e?JSON.parse(e):null}catch{return null}}function Dc(e){if(Ms())try{window.sessionStorage.setItem(As,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Es(){if(Ms())try{window.sessionStorage.removeItem(As)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function dp(){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 Nc(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 Ts(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function up(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Oc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function pp(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 xs({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:s,loading:l,error:f,onComplete:u,onError:S,onInstrument:v,onDecline:H,onCountryChange:$,onZipChange:k,showPayPal:q=!0,showStripe:K=!0,walletPresentation:h="auto",enabledPaymentMethods:b,showApplePay:se=!0,showGooglePay:U=!0,debug:ve=!1,layout:J,theme:ke,buttonsTheme:qe,buttonsStyles:Re,cardButtonContent:it,cardBackButtonContent:Ut,cardTitleContent:me,showSecurityFooter:Me,onButtonClick:gt,onBeforeButtonClick:Te,enableAVS:Ve,cardFieldOrder:_e,cardPreFormSlot:ne,avsLayout:je,submitLabel:$e,className:pt,initialErrorMessage:Ce=null,initialPayPalOrderId:ye,children:le,checkoutMode:F,confirmLabel:Se,renderConfirmButton:Ue,onSessionCompleted:xe}){let W=rp(r),ht=Xn(()=>Uc(ke),[ke]),ze=i??ht?.appearance,Ae=n?"embedded_checkout":"standard_checkout",Ze=Ts(le,J),[Be,Qe]=Vt(null),[De,Pt]=Vt(null),Wt=Bt(null),mt=Bt(null),Et=Bt(0),[_,re]=Vt(null),Ne=Bt(null),[L,we]=Vt(null),yt=Xn(()=>n?To(n):"",[n]),Oe=n?`create:${yt}`:`session:${e??""}`,It=Oc(L),M=Bt(new Set),p=Bt(Oe),g=Bt(Oe);ea(()=>{g.current=Oe,p.current!==Oe&&(p.current=Oe,M.current.clear())},[Oe]);let D=Pn(w=>{if(g.current===Oe){if($i.has(w.name)){if(M.current.has(w.name))return;M.current.add(w.name)}xt(()=>v?.(w))}},[Oe,v]),x=Ro(D,Oe),ee=Bt(!1),vt=Pn(w=>{if(ee.current)return;let R=w.gateway||!It?w:{...w,gateway:It};D(R)},[D,It]);mr(()=>{x({class:"lifecycle",name:"checkout.mount"})},[x]);let[fe,Ke]=Vt(e??""),Z=e??fe,zt=n?"":Z,[bt,Tt]=Vt(!0),[st,ce]=Vt(null),[Rn,On]=Vt(0),[mn,qt]=Vt("full"),[Ln,Un]=Vt(!1),[gn,At]=Vt(Ce),[We,Le]=Vt(null),[_n,kt]=Vt(null),[zn,yn]=Vt(!1),[jt,Xt]=Vt(void 0),[Qn,Hn]=Vt(""),[Qt,Rt]=Vt(!1),[en,nn]=Vt(!1),[Ft,an]=Vt(!1),Nt=Bt(null),rn=Bt(0),Dt=Bt(void 0),[G,er]=Vt("loading"),[tr,nr]=Vt(0),tn=Bt(!1),En=Bt(!1),bn=Bt(!1),he=Bt(null),et=Bt(null),m=Xn(()=>({checkoutMode:F??mn,layout:up(le,J)}),[F,le,mn,J]),Ge=Bt(u);Ge.current=u;let V=Bt(S);V.current=S;let hn=Bt(H);hn.current=H;let qn=Pn(w=>Qa(he,async R=>{try{return await w(R)}catch(O){throw R.aborted?Gr(O):O}}),[]);mr(()=>()=>{he.current?.abort(),he.current=null},[]);let Gt=Pn((w,R)=>{Wt.current=w,Pt(w),Ne.current=R,re(R)},[]),Tn=Pn(()=>{let w=mt.current;w&&(mt.current=null,w.destroy())},[]);mr(()=>{pn(De)?.setCheckoutContext(m),_&&_!==De&&pn(_)?.setCheckoutContext(m)},[De,_,m]);let tt=Bt(xe);tt.current=xe;let rr=Pn(w=>{er(w),!(w!=="exhausted"||bn.current)&&(bn.current=!0,V.current?.(new vn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Zr=Pn(()=>{er("retrying"),nr(w=>w+1)},[]);mr(()=>{er("loading"),nr(0),bn.current=!1},[Z]),mr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:zc,checkout_type:Ae,checkout_layout:Ze,billing_api_url:W})},[Ze,Ae,W]);let _t=Xn(()=>n?To(n,!0):"",[n]),An=Xn(()=>Qn===_t?jt:void 0,[jt,Qn,_t]),yr=Xn(()=>n?Ui(n,An):void 0,[n,An]),Vn=F??yr?.checkoutMode??"full",Yt=Xn(()=>yr?{...yr,checkoutMode:Vn}:void 0,[yr,Vn]);mr(()=>{Xt(void 0),Hn(_t),Dt.current=void 0,Nt.current=null,an(!1)},[_t]),mr(()=>{At(Ce)},[Ce]);let or=Pn((w,R,O)=>{xt(()=>{hn.current?.(un(w,R,O))})},[]),Mn=Pn(async(w,R)=>{At(null),kt(null),yn(!1),Le("processing");let O=R?.sessionId??w.id,E=w.clientSecret||t,nt=Oc(w),ut=Wt.current??Ne.current,j=pn(ut),Ee=ut?null:ui(W,o,m),B={log:pe=>{j?j.log(pe):Ee?.log(pe)},error:pe=>{j?j.error(pe):Ee?.error(pe)},terminal:pe=>{j?j.terminal(pe):Ee?.terminal(pe)},performance:pe=>{j?j.performance(pe):Ee?.performance(pe)},now:()=>j?.now()??Ee?.now()??0,elapsed:pe=>j?.elapsed(pe)??Math.max(0,(Ee?.now()??pe)-pe)},d=B.now(),c=!!(R?.initialAutoProcessingError||R?.initialAutoProcessingPending),I=!1,T,Q=()=>{I||(I=!0,c=!0,T=B.now(),B.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ae=!1,Fe=()=>{ae||(ae=!0,B.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),B.performance({stage:"processing",durationMs:B.elapsed(d),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),T!==void 0&&B.performance({stage:"recovery",durationMs:B.elapsed(T),durationMode:"machine",paymentMethodCategory:"saved"}))};B.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ee.current=!0;try{B.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ee.current=!1}x({class:"lifecycle",name:"payment.processing.started",provider:nt}),c&&Q();let at;try{let pe=ic(R?.initialAutoProcessingError),C=R?.initialAutoProcessingError?.type==="3ds_required"&&!R.initialAutoProcessingError.threeDSecureToken&&R.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:R.initialAutoProcessingError.nextActionRedirectUrl}:null,lt,ie=te=>(Q(),qn(A=>Mo(te,{billingApiUrl:W,sessionId:O,nonce:E,session:w,signal:A})));if(C)lt=await ie(C);else if(pe)Q(),pe.type==="paypal_redirect_required"&&et.current?.publishableKey&&Dc({sessionId:O,publishableKey:et.current.publishableKey,paypalPublishableKey:et.current.paypalPublishableKey}),lt=await qn(te=>ni(pe,{flopay:Wt.current,paypalFlopay:Ne.current,attempt3DS:R?.attempt3DS,billingApiUrl:W,sessionId:O,session:w,telemetry:!1,signal:te})),pe.type==="paypal_redirect_required"&&Es();else if(R?.initialAutoProcessingPending){let te=R.initialAutoProcessingPending,A=new ci(W,{telemetry:!1}),Y=await qn(Ie=>A.waitForCheckoutSessionCompletion(te.sessionId,{initialDelayMs:te.retryAfterMs,nonce:E,statusUrl:te.statusUrl,signal:Ie})),N=$r(Y,w),ct=Y.autoProcessingError?.type==="3ds_required"&&Y.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Y.autoProcessingError.nextActionRedirectUrl}:null;if(ct)lt=await ie(ct);else{if(!Fr(N))throw wo(N);lt=Br(N,O)}}else{if(R?.initialAutoProcessingError)throw Ir(R.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:R.initialAutoProcessingError.checkoutMethod});if(R?.fromCreateSession)return R?.fallbackToFull&&(qt("full"),Nc("full")),!1;{let te=await xo({billingApiUrl:W,sessionId:O,session:w,nonce:E,telemetry:!1});te.type==="success"?lt=te.result:te.type==="next_action_required"?lt=await ie(te):(Q(),te.type==="paypal_redirect_required"&&et.current?.publishableKey&&Dc({sessionId:O,publishableKey:et.current.publishableKey,paypalPublishableKey:et.current.paypalPublishableKey}),lt=await qn(A=>ni(te,{flopay:Wt.current,paypalFlopay:Ne.current,attempt3DS:R?.attempt3DS,billingApiUrl:W,sessionId:O,session:w,telemetry:!1,signal:A})),te.type==="paypal_redirect_required"&&Es())}}O&&Ao(O),Fe(),c&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),B.terminal({outcome:lt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),yn(lt.status==="authorized"),Le("success"),await ba(600),at=()=>Ge.current?.(lt)}catch(pe){let C=qr(fa(pe),O);if(C.code==="three_ds_aborted")return!1;let lt=C.checkoutMethod??ya;At(C.message),kt(C.message),yn(!1),R?.fallbackToFull&&(B.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),qt("full"),Nc("full")),Fe();let ie=C.statusCode===void 0?void 0:ap(C.statusCode,"unknown"),te=ie==="4xx"?{requestCategory:"process_payment",statusClass:ie}:{},A=ie===void 0||ie==="4xx";if(A&&(C.telemetryOutcome==="payment_declined"||!!(C.declineCode||C.code?.toLowerCase().includes("declin"))))B.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...te});else if(A&&(C.telemetryOutcome==="validation_rejected"||C.type==="validation_error"))B.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...te});else{let ct=Lc(pe,c?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ie=C.telemetryRequestCategory??"process_payment";ee.current=!0;try{B.error({...ct,...C.telemetryFailureCategory?{failureCategory:C.telemetryFailureCategory}:{},stage:c?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ie})}finally{ee.current=!1}x({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ie,provider:nt})}return xt(()=>V.current?.(C)),or(lt,C,{code:C.code,declineCode:C.declineCode}),Le("error"),await Promise.allSettled([ba(400),R?.ensureProvidersReady?R.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{Fe(),Ee&&Ca(Ee),Le(null),kt(null)}return xt(at),!0},[or,x,t,W,qn,o,m]);mr(()=>{if(typeof window>"u"||En.current)return;let w=new URLSearchParams(window.location.search),R=w.get("payment_intent_client_secret");if(!R)return;let O=cp();O&&(En.current=!0,(async()=>{let E,nt=0;At(null),kt(null),Le("processing"),Un(!0);try{if(w.get("redirect_status")==="failed")throw Object.assign(new vn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ut,paypalFlopay:j}=await os({publishableKey:O.publishableKey,paypalPublishableKey:O.paypalPublishableKey,billingApiUrl:W,locale:s,telemetry:o});E=pn(j??ut),E?.setCheckoutContext(m),nt=E?.now()??0,E?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),E?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Ee=(j??ut)?.getRawProvider();if(!Ee)throw Object.assign(new vn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:d}=await Ee.retrievePaymentIntent(R);if(d)throw Object.assign(new vn(d.message??"Failed to retrieve PayPal payment status.","api_error",{code:d.code}),{checkoutMethod:"paypal"});let c=Ll(B?.status);if(!B||c==="failed")throw Object.assign(new vn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let I=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,T=c;if(O.sessionId){let Fe=(await new ci(W,{telemetry:!1}).getUnifiedCheckoutSession(O.sessionId)).data.session;if(Fe&&Fe.status!=="complete"){let at=await xo({billingApiUrl:W,sessionId:O.sessionId,session:Fe,telemetry:!1,tokenizedData:{id:I??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(at.type!=="success")throw Object.assign(new vn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});T=at.result.status}}O.sessionId&&Ao(O.sessionId),E?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),E?.performance({stage:"redirect_resume",durationMs:E.elapsed(nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),E?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Le("success"),await ba(600),xt(()=>Ge.current?.({status:T,paymentIntentId:B.id,paymentMethodId:I,checkoutMethod:"paypal"}))}catch(ut){let j=qr(fa(ut),O.sessionId),Ee=j.checkoutMethod??"paypal",B=!!(j.declineCode||j.code?.toLowerCase().includes("declin"));if(E)E.performance({stage:"redirect_resume",durationMs:E.elapsed(nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?E.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):E.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let d=ui(W,o,m);d.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ca(d)}else ks(W,o,m,"REDIRECT_RESUME_FAILED","redirect_resume");At(j.message),kt(j.message),xt(()=>V.current?.(j)),or(Ee,j,{code:j.code,declineCode:j.declineCode}),Le("error"),await ba(400)}finally{Es(),dp(),Le(null),kt(null),Un(!1)}})())},[or,s,W,o,m]);let _r=Bt(null),xn=Xn(()=>Yt?To(Yt):"",[Yt]),fr=Bt(Yt);fr.current=Yt,mr(()=>{Ke(e??"")},[e]),mr(()=>{tn.current=!1,At(Ce),kt(null),yn(!1),Le(null)},[xn,Ce,e]);async function gr(w,R,O){let E=ui(W,o,m),nt=new ci(W,{telemetry:!1}),ut=!1;try{let j=w.idempotencyKey===void 0?void 0:Mc(w.idempotencyKey),Ee=Ji(R,O),B=Zi(R,O);Ee?.canonicalIdentity===O&&B&&B.canonicalIdentity===void 0&&(Ja(R,O,B.idempotencyKey),B={...B,canonicalIdentity:O});let d=j??(B?.canonicalIdentity===O?B.idempotencyKey:void 0),c,I=!1;E.log({name:Ee?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let T=Ee?.sid??null,Q=null,ae,Fe,at=!1;if(T)try{Q=await nt.getUnifiedCheckoutSession(T,Ee?.nonce),Ee&&Ee.canonicalIdentity===void 0&&(Ql(Q.data.session,w)?(Ya(R,O,T,Ee.nonce??Q.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(Ja(R,O,B.idempotencyKey),d??(d=B.idempotencyKey))):(Ga(R,O),B=null,d=j,T=null,Q=null));let C=Q?.data.session?.status,lt=Q?.data.session,ie=lt?.clientSecret||Ee?.nonce;if(T&<?.buyerIdentified===!1&&ie&&(Fe=So(nt,T,ie,w.account)),T&&Q&&C==="complete"){if(Xi(T))return{sid:T,result:Q};Ga(R,O),T=null,Q=null,I=!0}}catch{E.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ee?.canonicalIdentity===void 0?(Ga(R,O),d=j):Wa(R,O),T=null}if(!T){!j&&(I||!d)&&(d=Mc(),c=d),d&&Ja(R,O,d);let C=E.now(),lt=0;E.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ie={...w,idempotencyKey:d,avsCheck:!!Ve,avsConfig:typeof Ve=="object"?Ve:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ts(le,J)};Object.defineProperty(ie,ep,{configurable:!1,enumerable:!1,value:{onAttempt:Y=>{lt=Math.max(lt,Y)}}});let te=()=>{Bc(E,"session_create",C,lt)},A=Y=>{Fc(E,Y,"session_create",C,lt)&&x({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(np(ie)){let Y=await nt.createDetachedSession(ie);Y.claimed.catch(()=>{}),Q=Y.shell,T=Y.sessionId,Fe=Y.claim;let N=E.now();E.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ae=Y.claimed.then(ct=>{let Ie=ct.data.session?.id??Y.sessionId;return Ie&&Ya(R,O,Ie,ct.data.session?.clientSecret??Y.nonce),Bc(E,"session_claim",N),te(),ct},ct=>{throw Wa(R,O),Fc(E,ct,"session_claim",N,0)&&x({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),ct}).finally(()=>Ca(E)),ae.catch(()=>{}),ut=!0,E.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),E.performance({stage:"session_shell",durationMs:E.now()-C,durationMode:"machine",requestCategory:"session_create",attempt:lt,statusClass:"2xx",paymentMethodCategory:"card"})}else Q=await nt.createAndFetchSession(ie),te()}catch(Y){throw A(Y),Y}T=Q.data.session?.id??T??"",T&&!ae&&Ya(R,O,T,Q.data.session?.clientSecret)}let pe=Q?.data.session;return!Fe&&T&&pe?.buyerIdentified===!1&&pe.clientSecret&&(Fe=So(nt,T,pe.clientSecret,w.account)),{sid:T??"",result:Q,sdkGeneratedIdempotencyKey:c,...ae?{claimed:ae}:{},...Fe?{claim:Fe}:{},...at?{claimRequiresIdentity:!0}:{}}}finally{ut||Ca(E)}}let Er=Bt(gr);ea(()=>{Er.current=gr},[gr]);let jn=Pn(async(w,R)=>{let O=fr.current;if(!O)throw new vn("createSession is required to bootstrap checkout.","validation_error");let E=Ui(O,w),nt=To(E),ut=Xl(E),j=pi.get(nt);if(!j){let d={canonicalIdentity:nt,promise:Er.current(E,ut,nt),consumers:0,settled:!1};j=d,pi.set(nt,d);let c=()=>{d.settled=!0,xc(nt,d)};d.promise.then(c,c)}j.consumers+=1;let Ee=!1,B=()=>{Ee||(Ee=!0,j.consumers-=1,xc(nt,j))};R?.(B);try{let d=await j.promise;_r.current=nt,w&&(Hn(_t),Xt(pe=>Dl(pe,w)));let{sid:c,result:I,claimed:T,claim:Q,claimRequiresIdentity:ae}=d;if(Dt.current=Q,an(ae===!0),Qe(I),I.data.session&&we(I.data.session),c&&Ke(c),T){rn.current+=1;let pe=rn.current;Nt.current=T,nn(!0),T.then(C=>{rn.current===pe&&(Nt.current===T&&(Nt.current=null),Qe(C),C.data.session&&we(C.data.session),nn(!1),an(!1))},C=>{rn.current===pe&&(Nt.current===T&&(Nt.current=null),nn(!1),an(!1),ce(C instanceof vn?C:new vn(C instanceof Error?C.message:"Failed to create session","api_error")))})}else rn.current+=1,Nt.current=null,nn(!1),an(!1);let{flopay:Fe,paypalFlopay:at}=await _s(I,{billingApiUrl:W,locale:s,telemetry:o});return Gt(Fe,at),Tt(!1),d}catch(d){throw _r.current===nt&&(_r.current=null),d}finally{R||B()}},[_t,Gt,s,W,o]),Wn=Bt(Mn);Wn.current=Mn;let Tr=Bt(jn);Tr.current=jn;let Mt=Pn(async w=>{if(!pp(w)||Qt)return{sessionId:fe,session:L};Rt(!0);try{let R=await jn(w);return{sessionId:R.sid,session:R.result.data.session??null}}finally{Rt(!1)}},[jn,Qt,fe,L]),Cn=Pn(async w=>{let R=Dt.current;if(!R)return;let O=rn.current,E=await R(w);rn.current===O&&(Qe(E),E.data.session&&we(E.data.session))},[]),Gn=Pn(async()=>{await Nt.current},[]),Ar=Pn(async()=>(await Gn(),{proceed:!0}),[Gn]);mr(()=>{let w=!1,R,O=++Et.current;Tn(),ce(null),On(0);let E=()=>{w=!0,Et.current===O&&(Et.current+=1,Tn())},nt=fr.current;if(xn&&nt)return qt(Vn),Tt(!1),_r.current===xn?E:(we(Nl(nt,F)),(async()=>{let Ee=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),B=Vn==="auto"&&!tn.current&&!Ee;B&&(At(null),kt(null),Le("processing"));try{let d=await Tr.current(void 0,Q=>{R=Q}),c=d.result.data.session??null;et.current=rs(d.result);let I=Rs(d.result),T=Xi(d.sid||c?.id);if(!w&&B&&c&&!I&&!T){tn.current=!0,await ip(xn,d.sdkGeneratedIdempotencyKey,()=>Wn.current(c,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:d.result.autoProcessingError,initialAutoProcessingPending:d.result.autoProcessingPending,autoProcessingAttempted:d.result.autoProcessingAttempted,sessionId:d.sid||c.id}));return}!w&&B&&((I||T)&&(tn.current=!0),Le(null),kt(null))}catch(d){if(w)return;let c=za(d);if(B&&c==="session_auto_completed"){tn.current=!0,Le("success"),await ba(600),w||(xt(()=>{Ge.current?.({status:"succeeded"})}),Le(null),kt(null));return}B&&(Le(null),kt(null));let I=d instanceof vn?d:new vn(d instanceof Error?d.message:"Failed to create session","api_error");ce(I)}finally{R?.(),R=void 0}})(),()=>{E(),R?.()});Tt(!0);async function ut(){let Ee=!1,B=null;try{let d=new ci(W,{telemetry:!1}),c=await d.getUnifiedCheckoutSession(Z,t);if(B=c,w)return;Qe(c);let I=c.data.session??null;if(we(I),!I)throw new vn("No session data returned","api_error");let T=I.checkoutMode;if(T==="setup")throw new vn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(I.status==="authorized"){Tt(!1),xt(()=>{Ge.current?.(Br(I,Z)),tt.current?.(I.successUrl??"")});return}if(I.status==="complete"){Tt(!1),xt(()=>{tt.current?.(I.successUrl??"")});return}if(I.status==="expired")throw Ua(I);Ee=!0;let Q=F??T??"full";qt(Q),rn.current+=1;let ae=I.clientSecret||t;Dt.current=I.buyerIdentified===!1&&ae?So(d,Z,ae,{...I.customer?.id?{userId:I.customer.id}:{}}):void 0,nn(!1),an(!1);let Fe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),at=Rs(c);if(Q==="auto"&&!tn.current&&!Fe&&!at){tn.current=!0;let pe=j(c);try{if(await Wn.current(I,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>pe,sessionId:Z||I.id}),w)return;await pe,w||Tt(!1);return}catch{if(w)return;await pe,w||Tt(!1);return}}await j(c),w||Tt(!1)}catch(d){if(w)return;let c=Fl(d,Ee);if(Ee&&x({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),c){let{errorCode:T,stage:Q,...ae}=c;ks(W,o,m,T,Q,ae)}if(c?.stage==="provider_load"&&(F??B?.data.session?.checkoutMode??"full")==="full"&&Bl(B,q,K)){let T=lp({billingApiUrl:W,locale:s,telemetry:o});mt.current=T,Gt(T,null),On(1),Tt(!1);return}let I=d instanceof vn&&c?.stage!=="provider_load"?d:xl();I!==d&&xt(()=>V.current?.(I)),ce(I),Tt(!1)}}async function j(Ee){let{flopay:B,paypalFlopay:d,...c}=await _s(Ee,{billingApiUrl:W,locale:s,telemetry:o});et.current={publishableKey:c.publishableKey,paypalPublishableKey:c.paypalPublishableKey},Gt(B,d),On(0)}return ut(),E},[F,xn,Vn,zt,t,q,K]);let Mr=Pn(async()=>{if(!Be||Rn!==1)return;let w=Et.current;On(2);try{let{flopay:R,paypalFlopay:O}=await _s(Be,{billingApiUrl:W,locale:s,telemetry:o});if(Et.current!==w)return;Tn(),Gt(R,O),On(0)}catch(R){if(Et.current!==w)return;let{errorCode:O,stage:E,...nt}=Oi(R);ks(W,o,m,O,E,nt)}},[Tn,Gt,s,Rn,W,o,m,Be]),He=!!(Z&&(L?.clientSecret||t)),sn=Ln||!He,ln=Pn(async()=>{if(!(Ln||!He||!L)){Un(!0),At(null);try{await Mn(L,{attempt3DS:!0,fallbackToFull:!0,sessionId:Z||L.id})}finally{Un(!1)}}},[Z,Ln,He,Mn,L]),Sn=qc(Be,ye),Xr=Rs(Be),hr=Xn(()=>{if(!(!Be||!L||!Be.data.stripe?.publishableKey))return{billingApiUrl:W}},[Be,L,W]),Or=!!(n&&!le&&J==="buttons"&&Te&&Vn==="full"),wn=!!(Z&&(L?.vault?.html||zr(L))),cn=Xn(()=>({session:L,loading:bt,error:st,checkoutMode:mn,inlineSessionDraft:Yt,applyInlineSessionPatch:Or?Mt:void 0,inlineSessionPatchProcessing:Qt,claimPending:en,claimRequiresIdentity:Ft,claimBuyerIdentity:Cn,waitForDataAttachment:Gn}),[L,bt,st,mn,Yt,Or,Mt,Qt,en,Ft,Cn,Gn]),xr=!!n&&J==="buttons"&&!Xr&&!wn&&(!De||!hr),Bn=We?de(Sr,{status:We,errorMessage:_n,authorized:zn}):null;if(bt&&!wn){if(l)return on(Rr,{children:[l,Bn]});if(J==="buttons"){let w=ht?.buttonsLayout?.cardButton?.borderRadius??ht?.appearance.variables?.borderRadius??8,R=O=>de("div",{style:{height:O,borderRadius:w,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return on(Rr,{children:[on("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[q&&R(Oo),K&&(se||U)&&R(Oo),K&&R(Oo),de("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Bn]})}return on(Rr,{children:[on("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[de("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),de("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Bn]})}return st?f?de(dr.Provider,{value:cn,children:f(st)}):de(dr.Provider,{value:cn,children:de("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:st.message})}):xr?on(Rr,{children:[de(dr.Provider,{value:cn,children:de(yp,{onButtonClick:gt,showPayPal:q,showStripe:K,showApplePay:se,showGooglePay:U,theme:ke,buttonsTheme:qe,buttonsStyles:Re,cardButtonContent:it,cardBackButtonContent:Ut,cardTitleContent:me})}),Bn]}):Xr&&L&&Sn?on(Rr,{children:[de(dr.Provider,{value:cn,children:on("div",{className:pt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[gn&&de(_o,{icon:!1,children:gn}),G==="retrying"&&de("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),G==="exhausted"&&on("div",{role:"alert",children:[de("div",{children:"PayPal is temporarily unavailable. Please try again."}),de("button",{type:"button",onClick:Zr,children:"Retry PayPal"})]}),G!=="exhausted"&&de("div",{"aria-hidden":G==="retrying"?!0:void 0,style:G==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:de(Jl,{sessionId:Z,nonce:L.clientSecret||void 0,billingApiUrl:W,email:L.customer?.email||Yt?.account?.email,billingName:[L.customer?.firstName,L.customer?.lastName].filter(Boolean).join(" ")||[Yt?.account?.firstName,Yt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Cn,clientId:Sn.clientId,environment:Sn.environment,currency:(L.currency??"usd").toUpperCase(),isSubscription:L.mode==="subscription",providerObjectType:Sn.providerObjectType,approvalPresentation:Sn.approvalPresentation,existingOrderId:Sn.existingOrderId,onComplete:u,onErrorChange:At,onDecline:H,onButtonClick:gt,runBeforeButtonClick:Ar,onInitializationStateChange:rr,allowAutomaticRetry:tr===0,session:L,telemetry:o,telemetryContext:m,onInstrument:vt,debug:ve},`${Oe}:paypal-init-${tr}`)})]})}),Bn]}):mn==="confirm"?on(Rr,{children:[de(dr.Provider,{value:cn,children:de(Za,{flopay:De,paypalFlopay:_,options:hr??{billingApiUrl:W},onInstrument:vt,children:on("div",{className:pt,children:[gn&&de("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:gn}),Ue?Ue({onConfirm:ln,isProcessing:sn}):de("button",{type:"button",onClick:ln,disabled:sn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:sn?"not-allowed":"pointer",opacity:sn?.6:1},children:Ln?"Processing...":Se??"Confirm Purchase"})]})},Oe)}),Bn]}):(!De||!hr)&&!(wn&&mn==="full")?de(Rr,{children:Bn}):on(Rr,{children:[de(dr.Provider,{value:cn,children:on(Za,{flopay:De,paypalFlopay:_,options:hr??{billingApiUrl:W},onInstrument:vt,children:[Rn===1&&de("button",{type:"button",onClick:Mr,children:"Retry payment methods"}),le?on(Rr,{children:[gn&&de("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:gn}),de(mp,{sessionId:Z,nonce:L?.clientSecret||void 0,billingApiUrl:W,session:L,submitLabel:$e,walletPresentation:h,children:le})]}):de(ws,{sessionId:Z,nonce:L?.clientSecret||void 0,telemetry:o,email:L?.customer?.email||Yt?.account?.email,userId:L?.customer?.id||Yt?.account?.userId,firstName:L?.customer?.firstName||Yt?.account?.firstName,lastName:L?.customer?.lastName||Yt?.account?.lastName,totalAmount:L?Math.round(tp(L).total*100):0,currency:L?.currency?.toLowerCase()??"usd",onComplete:u,onError:S,onDecline:H,error:gn,onErrorChange:At,showPayPal:q,showStripe:K,walletPresentation:h,enabledPaymentMethods:Rn?[]:b??Be?.data.stripe?.enabledPaymentMethods??L?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Be?.data.stripe?.enabledPaymentMethodCountries,showApplePay:se,showGooglePay:U,layout:J,theme:ke,buttonsTheme:qe,buttonsStyles:Re,appearance:ze,cardButtonContent:it,cardBackButtonContent:Ut,cardTitleContent:me,onButtonClick:gt,onBeforeButtonClick:Te,onBuyerIdentityReady:Cn,enableAVS:Ve,..._e?{cardFieldOrder:_e}:{},...ne?{cardPreFormSlot:ne}:{},avsLayout:je,country:L?.customer?.country,city:L?.customer?.city,state:L?.customer?.state,onCountryChange:$,onZipChange:k,avsCheck:!!Ve,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Ts(le,J),className:pt,submitLabel:$e,directPaypal:Sn,isSubscription:L?.mode==="subscription",session:L,dataAttachmentPending:en,dataAttachmentRequiresIdentity:Ft,debug:ve})]},Oe)}),Bn]})}function mp({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:i,children:s}){return de(Rr,{children:Is.Children.map(s,l=>{if(!Is.isValidElement(l))return l;let f=l.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?l:Is.cloneElement(l,u)})})}function yp({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:f,cardBackButtonContent:u,cardTitleContent:S}){let[v,H]=Vt(!1),$=Xn(()=>Uc(i),[i]),k=Xn(()=>{let b=$?.buttonsLayout??op(s);return l?{...b,...l,cardButton:{...b.cardButton,...l.cardButton},cardFormContainer:{...b.cardFormContainer,...l.cardFormContainer},backButton:{...b.backButton,...l.backButton},backButtonIcon:{...b.backButtonIcon,...l.backButtonIcon},submitButton:{...b.submitButton,...l.submitButton},title:{...b.title,...l.title}}:b},[$,s,l]),q=$?.buttonsLayout?.cardButton?.borderRadius??$?.appearance.variables?.borderRadius??8,K=b=>de("div",{style:{height:b,borderRadius:q,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),h=f===void 0?{boxSizing:"border-box",height:Oo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(v){let b=k.cardInputBorder??"#e5e7eb",se=k.cardInputBackground??"white",U=Po(u),ve=Po(S);return on("div",{style:{backgroundColor:k.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...k.cardFormContainer},children:[on("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[on("button",{type:"button",onClick:()=>H(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:U?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...k.backButton},children:[de("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...k.backButtonIcon},children:de("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:de("path",{d:"M15 18l-6-6 6-6"})})}),de(bo,{content:u})]}),ve?de("div",{style:{flex:1}}):de("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...k.title},children:de(aa,{content:S})})]}),de("div",{style:{backgroundColor:se,border:`1px solid ${b}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:de("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),on("div",{style:{display:"flex"},children:[de("div",{style:{flex:1,backgroundColor:se,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomLeftRadius:8,padding:12,height:45},children:de("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),de("div",{style:{flex:1,backgroundColor:se,borderTop:"none",borderRight:`1px solid ${b}`,borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomRightRadius:8,padding:12,height:45},children:de("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),de("div",{style:{backgroundColor:se,border:`1px solid ${b}`,borderRadius:8,marginTop:8,padding:12,height:45},children:de("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),de("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...k.submitButton,opacity:.5}}),de("style",{children:`
|
|
12
|
+
`}),Jo&&Qr&&Ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:m?-2:0},children:[Ze("button",{type:"button",onClick:xn,style:{display:"inline-flex",alignItems:"center",gap:Ei?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.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",...b.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(bo,{content:Te})]}),ll?y("div",{style:{flex:1}}):y("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...b.title},children:y(ia,{content:We})})]}),!Jo&&!ll&&y("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ti,order:m?-3:0,...b.title},children:y(ia,{content:We})}),m&&ye&&y("div",{style:{order:-2,width:"100%"},children:ye}),m&&wn&&Ze("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[y("div",{style:{backgroundColor:go,border:`1px solid ${Yn(xa)}`,borderRadius:Jt,padding:"10px"},children:y("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Zt,onChange:a=>{xt("email"),rn.current=a.target.value,Qn(a.target.value)},onPointerDown:()=>xt("email"),onKeyDown:()=>xt("email"),onBlur:()=>{Cn("email")&&yr(!0),lo||Pi()},disabled:A,required:!0,"aria-invalid":xa||void 0,"aria-describedby":xa?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ai}})}),xa&&y("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Zo,children:yi.empty?"Email address is required":"Enter a valid email address"})]}),G&&y("div",{style:{order:m?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=jt,P=(Z=!1)=>({backgroundColor:go,border:`1px solid ${Yn(Z)}`,borderRadius:Jt,marginTop:"0.5rem",padding:"10px"}),U=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ai}),ve=Pu(a);return Ze(No,{children:[ot(G.address_line_1,a)&&Ze(No,{children:[y("div",{style:P(Kt("line1")),children:y("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:Mt,onChange:Z=>{xt("line1"),Nt.current.addressLine1=!0,nn.current=Z.target.value,Ve(Z.target.value)},onPointerDown:()=>xt("line1"),onKeyDown:()=>xt("line1"),onBlur:()=>Gn("line1"),disabled:A,required:!0,"aria-invalid":Kt("line1")||void 0,"aria-describedby":Kt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:U()})}),Kt("line1")&&y("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Zo,children:"Street address is required"})]}),ot(G.address_line_2,a)&&y("div",{style:P(),children:y("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:Z=>{Nt.current.addressLine2=!0,Dt.current=Z.target.value,Rn(Z.target.value)},disabled:A,"data-testid":"flopay-address-line2",style:U()})}),(ot(G.city,a)||ot(G.state,a))&&Ze("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[ot(G.city,a)&&y("div",{style:{flex:1,backgroundColor:go,borderTop:`1px solid ${Yn(Kt("city"))}`,borderRight:`1px solid ${Yn(Kt("city"))}`,borderBottom:`1px solid ${Yn(Kt("city"))}`,borderLeft:`1px solid ${Yn(Kt("city"))}`,padding:"10px",borderTopLeftRadius:Jt,borderBottomLeftRadius:Jt,...ot(G.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Jt}},children:y("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:kt,onChange:Z=>{xt("city"),Nt.current.city=!0,an.current=Z.target.value,Un(Z.target.value)},onPointerDown:()=>xt("city"),onKeyDown:()=>xt("city"),onBlur:()=>Gn("city"),disabled:A,required:!0,"aria-invalid":Kt("city")||void 0,"aria-describedby":Kt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:U()})}),ot(G.state,a)&&y("div",{style:{flex:1,backgroundColor:go,borderTop:`1px solid ${Yn(Kt("state"))}`,borderRight:`1px solid ${Yn(Kt("state"))}`,borderBottom:`1px solid ${Yn(Kt("state"))}`,borderLeft:`1px solid ${Yn(Kt("state"))}`,padding:"10px",borderTopRightRadius:Jt,borderBottomRightRadius:Jt,...ot(G.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Yn(Kt("state")||Kt("city"))}`}:{borderRadius:Jt}},children:ve?Ze("select",{id:"flopay-billing-state",name:"billing-state",value:mn,onChange:Z=>{xt("state"),Nt.current.state=!0,Ot.current=Z.target.value,$t(Z.target.value)},onPointerDown:()=>xt("state"),onKeyDown:()=>xt("state"),onBlur:()=>Gn("state"),disabled:A,autoComplete:"billing address-level1",required:!0,"aria-invalid":Kt("state")||void 0,"aria-describedby":Kt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...U(),cursor:"pointer"},children:[y("option",{value:"",children:is(a)}),ve.map(Z=>y("option",{value:Z.code,children:Z.name},Z.code))]}):y("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:is(a),autoComplete:"billing address-level1",value:mn,onChange:Z=>{xt("state"),Nt.current.state=!0,Ot.current=Z.target.value,$t(Z.target.value)},onPointerDown:()=>xt("state"),onKeyDown:()=>xt("state"),onBlur:()=>Gn("state"),disabled:A,required:!0,"aria-invalid":Kt("state")||void 0,"aria-describedby":Kt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:U()})})]}),Kt("city")&&y("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Zo,children:"City is required"}),Kt("state")&&Ze("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Zo,children:[is(a)," is required"]}),(ot(G.country,a)||ot(G.postal_code,a))&&Ze("div",{style:{display:"flex",flexDirection:le==="column"?"column":"row",gap:le==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[ot(G.country,a)&&y("div",{style:{flex:le==="row"?1:void 0,backgroundColor:go,borderTop:`1px solid ${Xo}`,borderRight:`1px solid ${Xo}`,borderBottom:`1px solid ${Xo}`,borderLeft:`1px solid ${Xo}`,padding:"10px",...le==="row"&&ot(G.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:Jt,borderBottomLeftRadius:Jt,borderRight:"none"}:{borderRadius:Jt}},children:Ze("select",{id:"flopay-billing-country",name:"billing-country",value:jt,onChange:Z=>{Nt.current.country=!0,en.current=Z.target.value,On(Z.target.value),ze?.(Z.target.value),Ot.current="",$t("")},disabled:A,autoComplete:"billing country","data-testid":"flopay-country",style:{...U(),cursor:"pointer"},children:[jt===""?y("option",{value:"",children:"Select country"}):null,yu.map(Z=>Ze("option",{value:Z.code,children:[Z.flag," ",Z.name]},Z.code))]})}),ot(G.postal_code,a)&&y("div",{style:{flex:le==="row"?1:void 0,backgroundColor:go,border:`1px solid ${td}`,padding:"10px",...le==="row"&&ot(G.country,a)?{borderRadius:"0",borderTopRightRadius:Jt,borderBottomRightRadius:Jt}:{borderRadius:Jt}},children:y("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:ms(jt),autoComplete:"billing postal-code",value:Ln,onChange:Z=>{xt("zip"),Nt.current.zip=!0,Rt.current=Z.target.value,fn(Z.target.value),Ae?.(Z.target.value)},onPointerDown:()=>xt("zip"),onKeyDown:()=>xt("zip"),onBlur:()=>{Cn("zip")&&Rr(!0)},disabled:A,required:Tn.required,"aria-invalid":Ba||void 0,"aria-describedby":Ba?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:U()})})]}),Ba&&y("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Zo,children:Tn.empty?`${ms(a)} is required`:Qu(a)})]})})()}),m&&id,at&&y(Eo,{margin:"0.75rem 0",styleOverride:b.errorBanner,children:at})]}),Fa={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"},ml=a=>L?!C||!Pr?y("pre",{"data-testid":a,style:Fa,children:"FloPay/DirectPayPal-debug - not enabled"}):y("pre",{"data-testid":a,style:Fa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${C}`,` directPaypalConfigured=${Pr}`,` inAppBrowserDetected=${String(Ta)}`,` shouldRenderDirectPayPal=${Ho}`,` shouldRenderStripePayPal=${Vo}`,` hasPaypalStripeInstance=${!!Ds}`].join(`
|
|
13
|
+
`)}):null,yl=a=>L?!se||!jn?y("pre",{"data-testid":a,style:Fa,children:"FloPay/Stripe-debug - not enabled"}):y("pre",{"data-testid":a,style:Fa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${se}`,` currency=${Ct}`,` amountInCents=${jo}`,` enabledPaymentMethods: ${JSON.stringify(Ce??[])}`,` enabledPaymentMethodsProvided=${$o}`,` hasEnabledMethods=${ka}`,` expressMethods: ${JSON.stringify(_a)}`,` walletExpressMethods: ${JSON.stringify(yo)}`,` paymentElementMethods: ${JSON.stringify(Ko)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ea)}`,` hasStripeInstance=${!!jn}`,` shouldRenderWallets=${fo}`,` shouldRenderPaymentElement=${Go}`].join(`
|
|
14
|
+
`)}):null,fl=He==="apm-expanding"||He==="apm-form"||He==="apm-collapsing",Po;He==="apm-expanding"?Po=fc:He==="apm-collapsing"&&(Po=gc);let Da=ln?Mc(bi,ln,fe):null;if(Re==="buttons"){let a=He==="buttons"||He==="expanding"||He==="apm-expanding",P=He==="expanding"||He==="card"||He==="collapsing",U=Pt===void 0?{boxSizing:"border-box",height:aa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ve;He==="expanding"||He==="apm-expanding"?ve=Gu:(He==="collapsing"||He==="apm-collapsing")&&(ve=Vu);let Z;return He==="expanding"?Z=fc:He==="collapsing"&&(Z=gc),Ze("form",{onSubmit:ki,className:$,noValidate:!0,style:{position:"relative"},children:[y(Ua,{}),O&&y(br,{status:O,errorMessage:at,authorized:tr}),Ze("div",{style:{display:"grid"},children:[Ze("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!ve?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!ve?Ju:{},...ve?{animation:ve,pointerEvents:"none"}:{}},children:[ml("flopay-direct-paypal-gate-debug"),yl("flopay-stripe-gate-debug"),Ho&&ft&&Ze(No,{children:[c&&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(da.Provider,{value:p,children:y(Va,{sessionId:e,nonce:t,billingApiUrl:st,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:Fe,clientId:ft.clientId,environment:ft.environment,currency:Ct.toUpperCase(),isSubscription:Tt,providerObjectType:Ke,approvalPresentation:Aa==="popup"?void 0:Aa,onTokenizedBody:Bn,onComplete:s,onErrorChange:Pe,onDecline:f,onTechnicalFailure:po,onButtonClick:ne,runBeforeButtonClick:sr,isProcessing:A,onLoadStateChange:Si,onInitializationStateChange:wi,session:ut,existingOrderId:c?.orderId,debug:L},c?.orderId??"fresh")})]}),Vo&&y(io,{stripe:Wo,options:Ls,children:y(vc,{sessionId:e,nonce:t,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,onTokenizedBody:Bn,onErrorChange:Pe,isProcessing:A,onButtonClick:ne,onDecline:f,onTechnicalFailure:po,runBeforeButtonClick:sr,onLoadStateChange:Hs,placeholderBorderRadius:eo,popupCapabilityOwner:p,externalTelemetryContext:el,presentationMode:mo})}),fo?y(io,{stripe:jn,options:Os,children:y(bc,{sessionId:e,nonce:t,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,intentKind:De>0?"payment":"setup",expressMethods:yo,onTokenizedBody:Bn,onErrorChange:Pe,onButtonClick:ne,onDecline:f,onTechnicalFailure:po,runBeforeButtonClick:sr,onLoadStateChange:Vs,placeholderBorderRadius:eo,popupCapabilityOwner:p,externalTelemetryContext:ee})}):null,!fo&&Zs?y("div",{style:{height:aa,borderRadius:eo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Go&&y(Sc,{sessionId:e,nonce:t,email:N.email,billingName:[N.firstName,N.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,paymentElementMethods:Ea,stripeInstance:jn,paymentElementBaseOptions:bi,futureUseSession:fe,onTokenizedBody:Bn,onErrorChange:Pe,onButtonClick:ne,onDecline:f,runBeforeButtonClick:sr,onLoadStateChange:Ys,isProcessing:A,submitButtonColor:to,submitButtonBorderRadius:Jt,submitButtonStyle:b.submitButton,onExpandApm:w,expandedApmMethod:ln,themeId:it,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:eo}}),m&&y("button",{type:"button",onClick:async()=>{A||!(await sr("card")).proceed||(ne?.("card"),Mr())},disabled:A,style:{width:"100%",...U,...b.cardButton,...ws({themeBundle:pe,resolvedPrimaryColor:to,resolvedBorderRadius:Jt,submitButtonStyle:b.submitButton,explicitPrimaryColor:Fn?.colorPrimary}),fontSize:b.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:A?"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:A?.6:1},onMouseEnter:ge=>{!A&&(pe||Fn?.colorPrimary)&&(ge.currentTarget.style.backgroundColor=od)},onMouseLeave:ge=>{(pe||Fn?.colorPrimary)&&(ge.currentTarget.style.backgroundColor=to)},onMouseDown:ge=>{ge.currentTarget.style.transform="scale(0.985)"},onMouseUp:ge=>{ge.currentTarget.style.transform="scale(1)"},children:y(Co,{content:Pt})}),at&&He==="buttons"&&y(Eo,{margin:"0.25rem 0",styleOverride:b.errorBanner,children:at})]}),m&&P&&y("div",{style:{gridArea:"1 / 1",...Z?{animation:Z}:{},...He==="collapsing"?{pointerEvents:"none"}:{}},children:pl}),se&&fl&&ln&&Da&&jn&&y("div",{style:{gridArea:"1 / 1",...Po?{animation:Po}:{},...He==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ze("div",{style:{backgroundColor:_i,borderRadius:xi,...Qo,padding:Mi},children:[Ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ze("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:R,style:{display:"inline-flex",alignItems:"center",gap:Ei?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.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",...b.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(bo,{content:Te})]}),y("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:Ti,paddingRight:80,...b.title},children:`Pay with ${va(ln)}`})]}),y(io,{stripe:jn,options:Da,children:y(gs,{method:ln,sessionId:e,nonce:t,email:N.email,billingName:[N.firstName,N.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,onTokenizedBody:Bn,onErrorChange:Pe,onDecline:f,onCancel:R,runBeforeButtonClick:sr,onButtonClick:ne,isProcessing:A,submitButtonColor:to,submitButtonBorderRadius:Jt,submitButtonStyle:b.submitButton,errorText:at})},ln)]})})]})]})}return fl&&ln&&Da&&jn&&se?Ze("form",{onSubmit:ki,className:$,noValidate:!0,style:{position:"relative"},children:[y(Ua,{}),O&&y(br,{status:O,errorMessage:at,authorized:tr}),y("div",{style:{...Po?{animation:Po}:{},...He==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ze("div",{style:{backgroundColor:_i,borderRadius:xi,...Qo,padding:Mi},children:[Ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ze("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:R,style:{display:"inline-flex",alignItems:"center",gap:Ei?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.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",...b.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(bo,{content:Te})]}),y("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:Ti,paddingRight:80,...b.title},children:`Pay with ${va(ln)}`})]}),y(io,{stripe:jn,options:Da,children:y(gs,{method:ln,sessionId:e,nonce:t,email:N.email,billingName:[N.firstName,N.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,onTokenizedBody:Bn,onErrorChange:Pe,onDecline:f,onCancel:R,runBeforeButtonClick:sr,onButtonClick:ne,isProcessing:A,submitButtonColor:to,submitButtonBorderRadius:Jt,submitButtonStyle:b.submitButton,errorText:at})},ln)]})})]}):Ze("form",{onSubmit:ki,className:$,noValidate:!0,style:{position:"relative"},children:[y(Ua,{}),O&&y(br,{status:O,errorMessage:at,authorized:tr}),Ze("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ml("flopay-direct-paypal-gate-debug-default"),yl("flopay-stripe-gate-debug-default"),Ho&&ft&&Ze(No,{children:[c&&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(da.Provider,{value:p,children:y(Va,{sessionId:e,nonce:t,billingApiUrl:st,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:Fe,clientId:ft.clientId,environment:ft.environment,currency:Ct.toUpperCase(),isSubscription:Tt,providerObjectType:Ke,approvalPresentation:Aa==="popup"?void 0:Aa,onTokenizedBody:Bn,onComplete:s,onErrorChange:Pe,onDecline:f,onTechnicalFailure:po,onButtonClick:ne,runBeforeButtonClick:sr,isProcessing:A,onLoadStateChange:Si,onInitializationStateChange:wi,session:ut,existingOrderId:c?.orderId,debug:L},c?.orderId??"fresh")})]}),Vo&&y(io,{stripe:Wo,options:Ls,children:y(vc,{sessionId:e,nonce:t,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,onTokenizedBody:Bn,onErrorChange:Pe,isProcessing:A,onButtonClick:ne,onDecline:f,onTechnicalFailure:po,runBeforeButtonClick:sr,onLoadStateChange:Hs,placeholderBorderRadius:eo,popupCapabilityOwner:p,externalTelemetryContext:el,presentationMode:mo})}),fo&&y(io,{stripe:jn,options:Os,children:y(bc,{sessionId:e,nonce:t,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:Fe,billingApiUrl:st,intentKind:De>0?"payment":"setup",expressMethods:yo,onTokenizedBody:Bn,onErrorChange:Pe,onButtonClick:ne,onDecline:f,onTechnicalFailure:po,runBeforeButtonClick:sr,onLoadStateChange:Vs,placeholderBorderRadius:eo,popupCapabilityOwner:p,externalTelemetryContext:ee})}),Go&&y(Sc,{sessionId:e,nonce:t,email:N.email,billingName:[N.firstName,N.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:st,paymentElementMethods:Ea,stripeInstance:jn,paymentElementBaseOptions:bi,futureUseSession:fe,onTokenizedBody:Bn,onErrorChange:Pe,onButtonClick:ne,onDecline:f,runBeforeButtonClick:sr,onLoadStateChange:Ys,isProcessing:A,submitButtonColor:to,submitButtonBorderRadius:Jt,submitButtonStyle:b.submitButton,themeId:it,onExpandApm:w,expandedApmMethod:ln,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:eo}})]}),m&&(Xc||Jc||Zc)&&y(hl,{label:"or pay with card"}),m&&pl]})}import{Fragment as kr,jsx as de,jsxs as on}from"react/jsx-runtime";var Lo=44,Ms="flopay_checkout_saved_payment_resume",mi=new Map,ui=new Map;function Bc(e,t){t.settled&&t.consumers===0&&mi.get(e)===t&&mi.delete(e)}function up(e,t,n){let r=ui.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};ui.set(e,i);let s=()=>{ui.get(e)===i&&ui.delete(e)};return o.then(s,s),o}function ba(e){return new Promise(t=>setTimeout(t,e))}function pi(e,t,n){let r=Ha({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:qc,enabled:t!==!1});return r.beginCheckout(n),r}function Sa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Rs(e,t,n,r,o,i){let s=pi(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),Sa(s)}function Fc(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 Dc(e,t,n,r,o){let i=Uc(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 Pn&&t.code==="session_auto_completed"?!1:t instanceof Pn&&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 jc(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 _s(e){return!e||e.data.stripe?.publishableKey?!1:!!jc(e)?.clientId}var pp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function mp(e){return new op(pp,{publishableKey:"provider_unavailable",...e})}async function Es(e,t){let{publishableKey:n,paypalPublishableKey:r}=os(e);return{...await as({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function xs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function yp(){if(!xs())return null;try{let e=window.sessionStorage.getItem(Ms);return e?JSON.parse(e):null}catch{return null}}function Nc(e){if(xs())try{window.sessionStorage.setItem(Ms,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ts(){if(xs())try{window.sessionStorage.removeItem(Ms)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function fp(){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 Oc(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 As(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function gp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Lc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function hp(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:r,telemetry:o,appearance:i,locale:s,loading:l,error:f,onComplete:u,onError:S,onInstrument:v,onDecline:H,onCountryChange:$,onZipChange:k,showPayPal:q=!0,showStripe:K=!0,walletPresentation:h="auto",enabledPaymentMethods:C,showApplePay:se=!0,showGooglePay:z=!0,debug:Ce=!1,layout:J,theme:ke,buttonsTheme:qe,buttonsStyles:Re,cardButtonContent:it,cardBackButtonContent:zt,cardTitleContent:me,showSecurityFooter:Me,onButtonClick:Pt,onBeforeButtonClick:Te,enableAVS:We,cardFieldOrder:_e,cardPreFormSlot:ne,avsLayout:je,submitLabel:$e,className:yt,initialErrorMessage:be=null,initialPayPalOrderId:ye,children:le,checkoutMode:F,confirmLabel:Se,renderConfirmButton:Ue,onSessionCompleted:xe}){let V=lp(r),vt=Zn(()=>zc(ke),[ke]),ze=i??vt?.appearance,Ae=n?"embedded_checkout":"standard_checkout",Xe=As(le,J),[Be,Qe]=Wt(null),[De,Ct]=Wt(null),Vt=Ft(null),ft=Ft(null),Tt=Ft(0),[T,re]=Wt(null),Ne=Ft(null),[L,we]=Wt(null),gt=Zn(()=>n?Ao(n):"",[n]),Oe=n?`create:${gt}`:`session:${e??""}`,It=Lc(L),M=Ft(new Set),p=Ft(Oe),g=Ft(Oe);ta(()=>{g.current=Oe,p.current!==Oe&&(p.current=Oe,M.current.clear())},[Oe]);let D=hn(w=>{if(g.current===Oe){if(Ki.has(w.name)){if(M.current.has(w.name))return;M.current.add(w.name)}Bt(()=>v?.(w))}},[Oe,v]),x=_o(D,Oe),ee=Ft(!1),ut=hn(w=>{if(ee.current)return;let R=w.gateway||!It?w:{...w,gateway:It};D(R)},[D,It]);pr(()=>{x({class:"lifecycle",name:"checkout.mount"})},[x]);let[fe,Ke]=Wt(e??""),X=e??fe,qt=n?"":X,[bt,At]=Wt(!0),[st,ce]=Wt(null),[kn,Nn]=Wt(0),[pn,jt]=Wt("full"),[On,Ln]=Wt(!1),[fn,Mt]=Wt(be),[Ve,Le]=Wt(null),[Rn,kt]=Wt(null),[Un,mn]=Wt(!1),[$t,Zt]=Wt(void 0),[Qn,Hn]=Wt(""),[Qt,Rt]=Wt(!1),[en,nn]=Wt(!1),[Dt,an]=Wt(!1),Ot=Ft(null),rn=Ft(0),Nt=Ft(void 0),[G,er]=Wt("loading"),[tr,nr]=Wt(0),tn=Ft(!1),_n=Ft(!1),vn=Ft(!1),he=Ft(null),et=Ft(null),m=Zn(()=>({checkoutMode:F??pn,layout:gp(le,J)}),[F,le,pn,J]),Ge=Ft(u);Ge.current=u;let W=Ft(S);W.current=S;let gn=Ft(H);gn.current=H;let zn=hn(w=>ei(he,async R=>{try{return await w(R)}catch(O){throw R.aborted?Yr(O):O}}),[]);pr(()=>()=>{he.current?.abort(),he.current=null},[]);let Gt=hn((w,R)=>{Vt.current=w,Ct(w),Ne.current=R,re(R)},[]),En=hn(()=>{let w=ft.current;w&&(ft.current=null,w.destroy())},[]);pr(()=>{un(De)?.setCheckoutContext(m),T&&T!==De&&un(T)?.setCheckoutContext(m)},[De,T,m]);let tt=Ft(xe);tt.current=xe;let rr=hn(w=>{er(w),!(w!=="exhausted"||vn.current)&&(vn.current=!0,W.current?.(new Pn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Zr=hn(()=>{er("retrying"),nr(w=>w+1)},[]);pr(()=>{er("loading"),nr(0),vn.current=!1},[X]),pr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:qc,checkout_type:Ae,checkout_layout:Xe,billing_api_url:V})},[Xe,Ae,V]);let _t=Zn(()=>n?Ao(n,!0):"",[n]),Tn=Zn(()=>Qn===_t?$t:void 0,[$t,Qn,_t]),mr=Zn(()=>n?zi(n,Tn):void 0,[n,Tn]),Wn=F??mr?.checkoutMode??"full",Yt=Zn(()=>mr?{...mr,checkoutMode:Wn}:void 0,[mr,Wn]);pr(()=>{Zt(void 0),Hn(_t),Nt.current=void 0,Ot.current=null,an(!1)},[_t]),pr(()=>{Mt(be)},[be]);let or=hn((w,R,O)=>{Bt(()=>{gn.current?.(dn(w,R,O))})},[]),An=hn(async(w,R)=>{Mt(null),kt(null),mn(!1),Le("processing");let O=R?.sessionId??w.id,_=w.clientSecret||t,nt=Lc(w),pt=Vt.current??Ne.current,j=un(pt),Ee=pt?null:pi(V,o,m),B={log:pe=>{j?j.log(pe):Ee?.log(pe)},error:pe=>{j?j.error(pe):Ee?.error(pe)},terminal:pe=>{j?j.terminal(pe):Ee?.terminal(pe)},performance:pe=>{j?j.performance(pe):Ee?.performance(pe)},now:()=>j?.now()??Ee?.now()??0,elapsed:pe=>j?.elapsed(pe)??Math.max(0,(Ee?.now()??pe)-pe)},d=B.now(),c=!!(R?.initialAutoProcessingError||R?.initialAutoProcessingPending),I=!1,E,Q=()=>{I||(I=!0,c=!0,E=B.now(),B.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ae=!1,Fe=()=>{ae||(ae=!0,B.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),B.performance({stage:"processing",durationMs:B.elapsed(d),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),E!==void 0&&B.performance({stage:"recovery",durationMs:B.elapsed(E),durationMode:"machine",paymentMethodCategory:"saved"}))};B.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ee.current=!0;try{B.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ee.current=!1}x({class:"lifecycle",name:"payment.processing.started",provider:nt}),c&&Q();let at;try{let pe=sc(R?.initialAutoProcessingError),b=R?.initialAutoProcessingError?.type==="3ds_required"&&!R.initialAutoProcessingError.threeDSecureToken&&R.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:R.initialAutoProcessingError.nextActionRedirectUrl}:null,lt,ie=te=>(Q(),zn(A=>xo(te,{billingApiUrl:V,sessionId:O,nonce:_,session:w,signal:A})));if(b)lt=await ie(b);else if(pe)Q(),pe.type==="paypal_redirect_required"&&et.current?.publishableKey&&Nc({sessionId:O,publishableKey:et.current.publishableKey,paypalPublishableKey:et.current.paypalPublishableKey}),lt=await zn(te=>ri(pe,{flopay:Vt.current,paypalFlopay:Ne.current,attempt3DS:R?.attempt3DS,billingApiUrl:V,sessionId:O,session:w,telemetry:!1,signal:te})),pe.type==="paypal_redirect_required"&&Ts();else if(R?.initialAutoProcessingPending){let te=R.initialAutoProcessingPending,A=new di(V,{telemetry:!1}),Y=await zn(Ie=>A.waitForCheckoutSessionCompletion(te.sessionId,{initialDelayMs:te.retryAfterMs,nonce:_,statusUrl:te.statusUrl,signal:Ie})),N=Kr(Y,w),ct=Y.autoProcessingError?.type==="3ds_required"&&Y.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Y.autoProcessingError.nextActionRedirectUrl}:null;if(ct)lt=await ie(ct);else{if(!Dr(N))throw Io(N);lt=Fr(N,O)}}else{if(R?.initialAutoProcessingError)throw wr(R.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:R.initialAutoProcessingError.checkoutMethod});if(R?.fromCreateSession)return R?.fallbackToFull&&(jt("full"),Oc("full")),!1;{let te=await Bo({billingApiUrl:V,sessionId:O,session:w,nonce:_,telemetry:!1});te.type==="success"?lt=te.result:te.type==="next_action_required"?lt=await ie(te):(Q(),te.type==="paypal_redirect_required"&&et.current?.publishableKey&&Nc({sessionId:O,publishableKey:et.current.publishableKey,paypalPublishableKey:et.current.paypalPublishableKey}),lt=await zn(A=>ri(te,{flopay:Vt.current,paypalFlopay:Ne.current,attempt3DS:R?.attempt3DS,billingApiUrl:V,sessionId:O,session:w,telemetry:!1,signal:A})),te.type==="paypal_redirect_required"&&Ts())}}O&&Mo(O),Fe(),c&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),B.terminal({outcome:lt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),mn(lt.status==="authorized"),Le("success"),await ba(600),at=()=>Ge.current?.(lt)}catch(pe){let b=jr(ga(pe),O);if(b.code==="three_ds_aborted")return!1;let lt=b.checkoutMethod??fa;Mt(b.message),kt(b.message),mn(!1),R?.fallbackToFull&&(B.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),jt("full"),Oc("full")),Fe();let ie=b.statusCode===void 0?void 0:dp(b.statusCode,"unknown"),te=ie==="4xx"?{requestCategory:"process_payment",statusClass:ie}:{},A=ie===void 0||ie==="4xx";if(A&&(b.telemetryOutcome==="payment_declined"||!!(b.declineCode||b.code?.toLowerCase().includes("declin"))))B.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...te});else if(A&&(b.telemetryOutcome==="validation_rejected"||b.type==="validation_error"))B.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...te});else{let ct=Uc(pe,c?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ie=b.telemetryRequestCategory??"process_payment";ee.current=!0;try{B.error({...ct,...b.telemetryFailureCategory?{failureCategory:b.telemetryFailureCategory}:{},stage:c?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ie})}finally{ee.current=!1}x({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ie,provider:nt})}return Bt(()=>W.current?.(b)),or(lt,b,{code:b.code,declineCode:b.declineCode}),Le("error"),await Promise.allSettled([ba(400),R?.ensureProvidersReady?R.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{Fe(),Ee&&Sa(Ee),Le(null),kt(null)}return Bt(at),!0},[or,x,t,V,zn,o,m]);pr(()=>{if(typeof window>"u"||_n.current)return;let w=new URLSearchParams(window.location.search),R=w.get("payment_intent_client_secret");if(!R)return;let O=yp();O&&(_n.current=!0,(async()=>{let _,nt=0;Mt(null),kt(null),Le("processing"),Ln(!0);try{if(w.get("redirect_status")==="failed")throw Object.assign(new Pn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:pt,paypalFlopay:j}=await as({publishableKey:O.publishableKey,paypalPublishableKey:O.paypalPublishableKey,billingApiUrl:V,locale:s,telemetry:o});_=un(j??pt),_?.setCheckoutContext(m),nt=_?.now()??0,_?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),_?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Ee=(j??pt)?.getRawProvider();if(!Ee)throw Object.assign(new Pn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:d}=await Ee.retrievePaymentIntent(R);if(d)throw Object.assign(new Pn(d.message??"Failed to retrieve PayPal payment status.","api_error",{code:d.code}),{checkoutMethod:"paypal"});let c=Ul(B?.status);if(!B||c==="failed")throw Object.assign(new Pn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let I=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,E=c;if(O.sessionId){let Fe=(await new di(V,{telemetry:!1}).getUnifiedCheckoutSession(O.sessionId)).data.session;if(Fe&&Fe.status!=="complete"){let at=await Bo({billingApiUrl:V,sessionId:O.sessionId,session:Fe,telemetry:!1,tokenizedData:{id:I??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(at.type!=="success")throw Object.assign(new Pn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});E=at.result.status}}O.sessionId&&Mo(O.sessionId),_?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),_?.performance({stage:"redirect_resume",durationMs:_.elapsed(nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),_?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Le("success"),await ba(600),Bt(()=>Ge.current?.({status:E,paymentIntentId:B.id,paymentMethodId:I,checkoutMethod:"paypal"}))}catch(pt){let j=jr(ga(pt),O.sessionId),Ee=j.checkoutMethod??"paypal",B=!!(j.declineCode||j.code?.toLowerCase().includes("declin"));if(_)_.performance({stage:"redirect_resume",durationMs:_.elapsed(nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?_.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):_.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let d=pi(V,o,m);d.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Sa(d)}else Rs(V,o,m,"REDIRECT_RESUME_FAILED","redirect_resume");Mt(j.message),kt(j.message),Bt(()=>W.current?.(j)),or(Ee,j,{code:j.code,declineCode:j.declineCode}),Le("error"),await ba(400)}finally{Ts(),fp(),Le(null),kt(null),Ln(!1)}})())},[or,s,V,o,m]);let Rr=Ft(null),Mn=Zn(()=>Yt?Ao(Yt):"",[Yt]),yr=Ft(Yt);yr.current=Yt,pr(()=>{Ke(e??"")},[e]),pr(()=>{tn.current=!1,Mt(be),kt(null),mn(!1),Le(null)},[Mn,be,e]);async function fr(w,R,O){let _=pi(V,o,m),nt=new di(V,{telemetry:!1}),pt=!1;try{let j=w.idempotencyKey===void 0?void 0:xc(w.idempotencyKey),Ee=Xi(R,O),B=Zi(R,O);Ee?.canonicalIdentity===O&&B&&B.canonicalIdentity===void 0&&(Xa(R,O,B.idempotencyKey),B={...B,canonicalIdentity:O});let d=j??(B?.canonicalIdentity===O?B.idempotencyKey:void 0),c,I=!1;_.log({name:Ee?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let E=Ee?.sid??null,Q=null,ae,Fe,at=!1;if(E)try{Q=await nt.getUnifiedCheckoutSession(E,Ee?.nonce),Ee&&Ee.canonicalIdentity===void 0&&(ec(Q.data.session,w)?(Ja(R,O,E,Ee.nonce??Q.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(Xa(R,O,B.idempotencyKey),d??(d=B.idempotencyKey))):(Ya(R,O),B=null,d=j,E=null,Q=null));let b=Q?.data.session?.status,lt=Q?.data.session,ie=lt?.clientSecret||Ee?.nonce;if(E&<?.buyerIdentified===!1&&ie&&(Fe=wo(nt,E,ie,w.account)),E&&Q&&b==="complete"){if(Qi(E))return{sid:E,result:Q};Ya(R,O),E=null,Q=null,I=!0}}catch{_.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ee?.canonicalIdentity===void 0?(Ya(R,O),d=j):Ga(R,O),E=null}if(!E){!j&&(I||!d)&&(d=xc(),c=d),d&&Xa(R,O,d);let b=_.now(),lt=0;_.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ie={...w,idempotencyKey:d,avsCheck:!!We,avsConfig:typeof We=="object"?We:void 0,checkoutType:"embedded_checkout",checkoutLayout:As(le,J)};Object.defineProperty(ie,ap,{configurable:!1,enumerable:!1,value:{onAttempt:Y=>{lt=Math.max(lt,Y)}}});let te=()=>{Fc(_,"session_create",b,lt)},A=Y=>{Dc(_,Y,"session_create",b,lt)&&x({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(sp(ie)){let Y=await nt.createDetachedSession(ie);Y.claimed.catch(()=>{}),Q=Y.shell,E=Y.sessionId,Fe=Y.claim;let N=_.now();_.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ae=Y.claimed.then(ct=>{let Ie=ct.data.session?.id??Y.sessionId;return Ie&&Ja(R,O,Ie,ct.data.session?.clientSecret??Y.nonce),Fc(_,"session_claim",N),te(),ct},ct=>{throw Ga(R,O),Dc(_,ct,"session_claim",N,0)&&x({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),ct}).finally(()=>Sa(_)),ae.catch(()=>{}),pt=!0,_.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),_.performance({stage:"session_shell",durationMs:_.now()-b,durationMode:"machine",requestCategory:"session_create",attempt:lt,statusClass:"2xx",paymentMethodCategory:"card"})}else Q=await nt.createAndFetchSession(ie),te()}catch(Y){throw A(Y),Y}E=Q.data.session?.id??E??"",E&&!ae&&Ja(R,O,E,Q.data.session?.clientSecret)}let pe=Q?.data.session;return!Fe&&E&&pe?.buyerIdentified===!1&&pe.clientSecret&&(Fe=wo(nt,E,pe.clientSecret,w.account)),{sid:E??"",result:Q,sdkGeneratedIdempotencyKey:c,...ae?{claimed:ae}:{},...Fe?{claim:Fe}:{},...at?{claimRequiresIdentity:!0}:{}}}finally{pt||Sa(_)}}let _r=Ft(fr);ta(()=>{_r.current=fr},[fr]);let qn=hn(async(w,R)=>{let O=yr.current;if(!O)throw new Pn("createSession is required to bootstrap checkout.","validation_error");let _=zi(O,w),nt=Ao(_),pt=Ql(_),j=mi.get(nt);if(!j){let d={canonicalIdentity:nt,promise:_r.current(_,pt,nt),consumers:0,settled:!1};j=d,mi.set(nt,d);let c=()=>{d.settled=!0,Bc(nt,d)};d.promise.then(c,c)}j.consumers+=1;let Ee=!1,B=()=>{Ee||(Ee=!0,j.consumers-=1,Bc(nt,j))};R?.(B);try{let d=await j.promise;Rr.current=nt,w&&(Hn(_t),Zt(pe=>Nl(pe,w)));let{sid:c,result:I,claimed:E,claim:Q,claimRequiresIdentity:ae}=d;if(Nt.current=Q,an(ae===!0),Qe(I),I.data.session&&we(I.data.session),c&&Ke(c),E){rn.current+=1;let pe=rn.current;Ot.current=E,nn(!0),E.then(b=>{rn.current===pe&&(Ot.current===E&&(Ot.current=null),Qe(b),b.data.session&&we(b.data.session),nn(!1),an(!1))},b=>{rn.current===pe&&(Ot.current===E&&(Ot.current=null),nn(!1),an(!1),ce(b instanceof Pn?b:new Pn(b instanceof Error?b.message:"Failed to create session","api_error")))})}else rn.current+=1,Ot.current=null,nn(!1),an(!1);let{flopay:Fe,paypalFlopay:at}=await Es(I,{billingApiUrl:V,locale:s,telemetry:o});return Gt(Fe,at),At(!1),d}catch(d){throw Rr.current===nt&&(Rr.current=null),d}finally{R||B()}},[_t,Gt,s,V,o]),Vn=Ft(An);Vn.current=An;let Er=Ft(qn);Er.current=qn;let xt=hn(async w=>{if(!hp(w)||Qt)return{sessionId:fe,session:L};Rt(!0);try{let R=await qn(w);return{sessionId:R.sid,session:R.result.data.session??null}}finally{Rt(!1)}},[qn,Qt,fe,L]),Cn=hn(async w=>{let R=Nt.current;if(!R)return;let O=rn.current,_=await R(w);rn.current===O&&(Qe(_),_.data.session&&we(_.data.session))},[]),Gn=hn(async()=>{await Ot.current},[]),Tr=hn(async()=>(await Gn(),{proceed:!0}),[Gn]);pr(()=>{let w=!1,R,O=++Tt.current;En(),ce(null),Nn(0);let _=()=>{w=!0,Tt.current===O&&(Tt.current+=1,En())},nt=yr.current;if(Mn&&nt)return jt(Wn),At(!1),Rr.current===Mn?_:(we(Ol(nt,F)),(async()=>{let Ee=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),B=Wn==="auto"&&!tn.current&&!Ee;B&&(Mt(null),kt(null),Le("processing"));try{let d=await Er.current(void 0,Q=>{R=Q}),c=d.result.data.session??null;et.current=os(d.result);let I=_s(d.result),E=Qi(d.sid||c?.id);if(!w&&B&&c&&!I&&!E){tn.current=!0,await up(Mn,d.sdkGeneratedIdempotencyKey,()=>Vn.current(c,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:d.result.autoProcessingError,initialAutoProcessingPending:d.result.autoProcessingPending,autoProcessingAttempted:d.result.autoProcessingAttempted,sessionId:d.sid||c.id}));return}!w&&B&&((I||E)&&(tn.current=!0),Le(null),kt(null))}catch(d){if(w)return;let c=qa(d);if(B&&c==="session_auto_completed"){tn.current=!0,Le("success"),await ba(600),w||(Bt(()=>{Ge.current?.({status:"succeeded"})}),Le(null),kt(null));return}B&&(Le(null),kt(null));let I=d instanceof Pn?d:new Pn(d instanceof Error?d.message:"Failed to create session","api_error");ce(I)}finally{R?.(),R=void 0}})(),()=>{_(),R?.()});At(!0);async function pt(){let Ee=!1,B=null;try{let d=new di(V,{telemetry:!1}),c=await d.getUnifiedCheckoutSession(X,t);if(B=c,w)return;Qe(c);let I=c.data.session??null;if(we(I),!I)throw new Pn("No session data returned","api_error");let E=I.checkoutMode;if(E==="setup")throw new Pn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(I.status==="authorized"){At(!1),Bt(()=>{Ge.current?.(Fr(I,X)),tt.current?.(I.successUrl??"")});return}if(I.status==="complete"){At(!1),Bt(()=>{tt.current?.(I.successUrl??"")});return}if(I.status==="expired")throw za(I);Ee=!0;let Q=F??E??"full";jt(Q),rn.current+=1;let ae=I.clientSecret||t;Nt.current=I.buyerIdentified===!1&&ae?wo(d,X,ae,{...I.customer?.id?{userId:I.customer.id}:{}}):void 0,nn(!1),an(!1);let Fe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),at=_s(c);if(Q==="auto"&&!tn.current&&!Fe&&!at){tn.current=!0;let pe=j(c);try{if(await Vn.current(I,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>pe,sessionId:X||I.id}),w)return;await pe,w||At(!1);return}catch{if(w)return;await pe,w||At(!1);return}}await j(c),w||At(!1)}catch(d){if(w)return;let c=Dl(d,Ee);if(Ee&&x({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),c){let{errorCode:E,stage:Q,...ae}=c;Rs(V,o,m,E,Q,ae)}if(c?.stage==="provider_load"&&(F??B?.data.session?.checkoutMode??"full")==="full"&&Fl(B,q,K)){let E=mp({billingApiUrl:V,locale:s,telemetry:o});ft.current=E,Gt(E,null),Nn(1),At(!1);return}let I=d instanceof Pn&&c?.stage!=="provider_load"?d:Bl();I!==d&&Bt(()=>W.current?.(I)),ce(I),At(!1)}}async function j(Ee){let{flopay:B,paypalFlopay:d,...c}=await Es(Ee,{billingApiUrl:V,locale:s,telemetry:o});et.current={publishableKey:c.publishableKey,paypalPublishableKey:c.paypalPublishableKey},Gt(B,d),Nn(0)}return pt(),_},[F,Mn,Wn,qt,t,q,K]);let Ar=hn(async()=>{if(!Be||kn!==1)return;let w=Tt.current;Nn(2);try{let{flopay:R,paypalFlopay:O}=await Es(Be,{billingApiUrl:V,locale:s,telemetry:o});if(Tt.current!==w)return;En(),Gt(R,O),Nn(0)}catch(R){if(Tt.current!==w)return;let{errorCode:O,stage:_,...nt}=Li(R);Rs(V,o,m,O,_,nt)}},[En,Gt,s,kn,V,o,m,Be]),He=!!(X&&(L?.clientSecret||t)),sn=On||!He,ln=hn(async()=>{if(!(On||!He||!L)){Ln(!0),Mt(null);try{await An(L,{attempt3DS:!0,fallbackToFull:!0,sessionId:X||L.id})}finally{Ln(!1)}}},[X,On,He,An,L]),bn=jc(Be,ye),Qr=_s(Be),gr=Zn(()=>{if(!(!Be||!L||!Be.data.stripe?.publishableKey))return{billingApiUrl:V}},[Be,L,V]),Lr=!!(n&&!le&&J==="buttons"&&Te&&Wn==="full"),Sn=!!(X&&(L?.vault?.html||qr(L))),cn=Zn(()=>({session:L,loading:bt,error:st,checkoutMode:pn,inlineSessionDraft:Yt,applyInlineSessionPatch:Lr?xt:void 0,inlineSessionPatchProcessing:Qt,claimPending:en,claimRequiresIdentity:Dt,claimBuyerIdentity:Cn,waitForDataAttachment:Gn}),[L,bt,st,pn,Yt,Lr,xt,Qt,en,Dt,Cn,Gn]),Mr=!!n&&J==="buttons"&&!Qr&&!Sn&&(!De||!gr),xn=Ve?de(br,{status:Ve,errorMessage:Rn,authorized:Un}):null;if(bt&&!Sn){if(l)return on(kr,{children:[l,xn]});if(J==="buttons"){let w=vt?.buttonsLayout?.cardButton?.borderRadius??vt?.appearance.variables?.borderRadius??8,R=O=>de("div",{style:{height:O,borderRadius:w,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return on(kr,{children:[on("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[q&&R(Lo),K&&(se||z)&&R(Lo),K&&R(Lo),de("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),xn]})}return on(kr,{children:[on("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[de("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),de("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),xn]})}return st?f?de(cr.Provider,{value:cn,children:f(st)}):de(cr.Provider,{value:cn,children:de("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:st.message})}):Mr?on(kr,{children:[de(cr.Provider,{value:cn,children:de(vp,{onButtonClick:Pt,showPayPal:q,showStripe:K,showApplePay:se,showGooglePay:z,theme:ke,buttonsTheme:qe,buttonsStyles:Re,cardButtonContent:it,cardBackButtonContent:zt,cardTitleContent:me})}),xn]}):Qr&&L&&bn?on(kr,{children:[de(cr.Provider,{value:cn,children:on("div",{className:yt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[fn&&de(Eo,{icon:!1,children:fn}),G==="retrying"&&de("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),G==="exhausted"&&on("div",{role:"alert",children:[de("div",{children:"PayPal is temporarily unavailable. Please try again."}),de("button",{type:"button",onClick:Zr,children:"Retry PayPal"})]}),G!=="exhausted"&&de("div",{"aria-hidden":G==="retrying"?!0:void 0,style:G==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:de(Xl,{sessionId:X,nonce:L.clientSecret||void 0,billingApiUrl:V,email:L.customer?.email||Yt?.account?.email,billingName:[L.customer?.firstName,L.customer?.lastName].filter(Boolean).join(" ")||[Yt?.account?.firstName,Yt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Cn,clientId:bn.clientId,environment:bn.environment,currency:(L.currency??"usd").toUpperCase(),isSubscription:L.mode==="subscription",providerObjectType:bn.providerObjectType,approvalPresentation:bn.approvalPresentation,existingOrderId:bn.existingOrderId,onComplete:u,onErrorChange:Mt,onDecline:H,onButtonClick:Pt,runBeforeButtonClick:Tr,onInitializationStateChange:rr,allowAutomaticRetry:tr===0,session:L,telemetry:o,telemetryContext:m,onInstrument:ut,debug:Ce},`${Oe}:paypal-init-${tr}`)})]})}),xn]}):pn==="confirm"?on(kr,{children:[de(cr.Provider,{value:cn,children:de(Za,{flopay:De,paypalFlopay:T,options:gr??{billingApiUrl:V},onInstrument:ut,children:on("div",{className:yt,children:[fn&&de("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:fn}),Ue?Ue({onConfirm:ln,isProcessing:sn}):de("button",{type:"button",onClick:ln,disabled:sn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:sn?"not-allowed":"pointer",opacity:sn?.6:1},children:On?"Processing...":Se??"Confirm Purchase"})]})},Oe)}),xn]}):(!De||!gr)&&!(Sn&&pn==="full")?de(kr,{children:xn}):on(kr,{children:[de(cr.Provider,{value:cn,children:on(Za,{flopay:De,paypalFlopay:T,options:gr??{billingApiUrl:V},onInstrument:ut,children:[kn===1&&de("button",{type:"button",onClick:Ar,children:"Retry payment methods"}),le?on(kr,{children:[fn&&de("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:fn}),de(Pp,{sessionId:X,nonce:L?.clientSecret||void 0,billingApiUrl:V,session:L,submitLabel:$e,walletPresentation:h,children:le})]}):de(Is,{sessionId:X,nonce:L?.clientSecret||void 0,telemetry:o,email:L?.customer?.email||Yt?.account?.email,userId:L?.customer?.id||Yt?.account?.userId,firstName:L?.customer?.firstName||Yt?.account?.firstName,lastName:L?.customer?.lastName||Yt?.account?.lastName,totalAmount:L?Math.round(ip(L).total*100):0,currency:L?.currency?.toLowerCase()??"usd",onComplete:u,onError:S,onDecline:H,error:fn,onErrorChange:Mt,showPayPal:q,showStripe:K,walletPresentation:h,enabledPaymentMethods:kn?[]:C??Be?.data.stripe?.enabledPaymentMethods??L?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Be?.data.stripe?.enabledPaymentMethodCountries,showApplePay:se,showGooglePay:z,layout:J,theme:ke,buttonsTheme:qe,buttonsStyles:Re,appearance:ze,cardButtonContent:it,cardBackButtonContent:zt,cardTitleContent:me,onButtonClick:Pt,onBeforeButtonClick:Te,onBuyerIdentityReady:Cn,enableAVS:We,..._e?{cardFieldOrder:_e}:{},...ne?{cardPreFormSlot:ne}:{},avsLayout:je,country:L?.customer?.country,city:L?.customer?.city,state:L?.customer?.state,onCountryChange:$,onZipChange:k,avsCheck:!!We,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:As(le,J),className:yt,submitLabel:$e,directPaypal:bn,isSubscription:L?.mode==="subscription",session:L,dataAttachmentPending:en,dataAttachmentRequiresIdentity:Dt,debug:Ce})]},Oe)}),xn]})}function Pp({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:i,children:s}){return de(kr,{children:ks.Children.map(s,l=>{if(!ks.isValidElement(l))return l;let f=l.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?l:ks.cloneElement(l,u)})})}function vp({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:f,cardBackButtonContent:u,cardTitleContent:S}){let[v,H]=Wt(!1),$=Zn(()=>zc(i),[i]),k=Zn(()=>{let C=$?.buttonsLayout??cp(s);return l?{...C,...l,cardButton:{...C.cardButton,...l.cardButton},cardFormContainer:{...C.cardFormContainer,...l.cardFormContainer},backButton:{...C.backButton,...l.backButton},backButtonIcon:{...C.backButtonIcon,...l.backButtonIcon},submitButton:{...C.submitButton,...l.submitButton},title:{...C.title,...l.title}}:C},[$,s,l]),q=$?.buttonsLayout?.cardButton?.borderRadius??$?.appearance.variables?.borderRadius??8,K=C=>de("div",{style:{height:C,borderRadius:q,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),h=f===void 0?{boxSizing:"border-box",height:Lo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(v){let C=k.cardInputBorder??"#e5e7eb",se=k.cardInputBackground??"white",z=vo(u),Ce=vo(S);return on("div",{style:{backgroundColor:k.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...k.cardFormContainer},children:[on("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[on("button",{type:"button",onClick:()=>H(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:z?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...k.backButton},children:[de("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...k.backButtonIcon},children:de("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:de("path",{d:"M15 18l-6-6 6-6"})})}),de(bo,{content:u})]}),Ce?de("div",{style:{flex:1}}):de("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...k.title},children:de(ia,{content:S})})]}),de("div",{style:{backgroundColor:se,border:`1px solid ${C}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:de("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),on("div",{style:{display:"flex"},children:[de("div",{style:{flex:1,backgroundColor:se,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomLeftRadius:8,padding:12,height:45},children:de("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),de("div",{style:{flex:1,backgroundColor:se,borderTop:"none",borderRight:`1px solid ${C}`,borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomRightRadius:8,padding:12,height:45},children:de("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),de("div",{style:{backgroundColor:se,border:`1px solid ${C}`,borderRadius:8,marginTop:8,padding:12,height:45},children:de("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),de("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...k.submitButton,opacity:.5}}),de("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 on("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&K(Oo),n&&(r||o)&&K(Oo),n&&de("button",{type:"button",onClick:()=>{e?.("card"),H(!0)},style:{width:"100%",...h,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:k.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...k.cardButton},onMouseDown:b=>{b.currentTarget.style.transform="scale(0.985)"},onMouseUp:b=>{b.currentTarget.style.transform="scale(1)"},children:de(vo,{content:f})}),de("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as wp,jsx as io,jsxs as Ip}from"react/jsx-runtime";var Pp=44;function jc(e){return new Promise(t=>setTimeout(t,e))}function vp(e,t){return e instanceof wa?e:new wa(e instanceof Error?e.message:t,"api_error")}function bp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Cp(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 Sp({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:s,items:l,subscriptions:f,account:u,successUrl:S,cancelUrl:v,couponCodes:H,tagsData:$,utmMetadata:k,billingApiUrl:q,locale:K,theme:h,appearance:b,buttonsTheme:se,buttonsStyles:U,onSuccess:ve,onError:J,onDecline:ke,children:qe,disabled:Re=!1,type:it="button",style:Ut,...me}){let Me=Sa(()=>fp(q),[q]),gt=Sa(()=>Cp({createSession:n,clientId:i,products:s,items:l,subscriptions:f,account:u,successUrl:S,cancelUrl:v,couponCodes:H,tagsData:$,utmMetadata:k}),[u,v,i,H,n,s,l,f,S,$,k]),[Te,Ve]=zo(!1),[_e,ne]=zo(null),[je,$e]=zo(null),[pt,Ce]=zo(!1),[ye,le]=zo(null),[F,Se]=zo(null),Ue=Uo(!0),xe=Uo(null),W=Uo(F),ht=Uo(ve),ze=Uo(J),Ae=Uo(ke),Ze=Nr(p=>Qa(xe,async g=>{try{return await p(g)}catch(D){throw g.aborted?Gr(D):D}}),[]);Lo(()=>{W.current=F},[F]),Lo(()=>{ht.current=ve},[ve]),Lo(()=>{ze.current=J},[J]),Lo(()=>{Ae.current=ke},[ke]),Lo(()=>(Ue.current=!0,()=>{Ue.current=!1,xe.current?.abort()}),[]),Lo(()=>{if(typeof window>"u")return;let p=g=>{g.key==="Escape"&&Se(null)};return window.addEventListener("keydown",p),()=>{window.removeEventListener("keydown",p)}},[]);let Be=Nr((p,g=ya)=>{Ae.current?.(un(g,p,{code:p.code,declineCode:p.declineCode}))},[]),Qe=Nr(async p=>{Ue.current&&($e(null),Ce(p.result.status==="authorized"),ne("success"),await jc(600),Ue.current&&xt(()=>ht.current?.(p)))},[]),De=Nr(async(p,g)=>{Ue.current&&(ze.current?.(p),g?.emitDecline&&Be(p,g.method),$e(p.message),Ce(!1),ne("error"),await jc(400))},[Be]),Pt=Nr(async(p,g,D)=>{let x=p.data.session??null;if(!x)throw qr(new wa("No session data returned","api_error"),g);let ee=x.clientSecret||t;if(Fr(x)){await Qe({result:Br(x,g),session:x,sessionId:x.id||g,autoCompleted:!1});return}if(x.status==="expired")throw qr(Ua(x),x.id||g);try{if(p.autoProcessingPending){let fe=p.autoProcessingPending,Ke=new Bs(Me),Z=await Ze(Tt=>Ke.waitForCheckoutSessionCompletion(fe.sessionId,{initialDelayMs:fe.retryAfterMs,nonce:ee,statusUrl:fe.statusUrl,signal:Tt})),zt=$r(Z,x),bt=Z.autoProcessingError?.type==="3ds_required"&&Z.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Z.autoProcessingError.nextActionRedirectUrl}:null;if(bt&&g&&ee){let Tt=await Ze(st=>Mo(bt,{billingApiUrl:Me,sessionId:g,nonce:ee,session:x,signal:st,telemetry:!0}));await Qe({result:Tt,session:x,sessionId:x.id||g,autoCompleted:!1});return}if(Z.autoProcessingError)throw Ir(Z.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Z.autoProcessingError.checkoutMethod});if(!Fr(zt))throw wo(zt);await Qe({result:Br(zt,g),session:zt,sessionId:zt.id||g,autoCompleted:!1});return}if(p.autoProcessingError){let fe=p.autoProcessingError.nextActionRedirectUrl;if(p.autoProcessingError.type==="3ds_required"&&fe&&g&&ee){let Ke=await Ze(Tt=>ns({billingApiUrl:Me,sessionId:g,nonce:ee,nextActionRedirectUrl:fe,signal:Tt}));if(Ke.status==="declined")throw Ir({type:Ke.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ke.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:p.autoProcessingError.checkoutMethod});let zt=await new Bs(Me).waitForCheckoutSessionCompletion(g,{initialDelayMs:0,nonce:ee}),bt=$r(zt,x);if(!Fr(bt))throw Ir({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:p.autoProcessingError.checkoutMethod});await Qe({result:Br(bt,g),session:bt,sessionId:bt.id||g,autoCompleted:!1});return}throw Ir(p.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:p.autoProcessingError.checkoutMethod})}if(D?.fromCreateSession&&p.autoProcessingAttempted===!0)throw Ir({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let vt=await xo({billingApiUrl:Me,sessionId:g??x.id,session:x,nonce:ee});if(vt.type==="next_action_required"&&ee){let fe=g??x.id,Ke=await Ze(Z=>Mo(vt,{billingApiUrl:Me,sessionId:fe,nonce:ee,session:x,signal:Z,telemetry:!0}));await Qe({result:Ke,session:x,sessionId:x.id||fe,autoCompleted:!1});return}if(vt.type!=="success")throw Ir({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Qe({result:vt.result,session:x,sessionId:x.id||g,autoCompleted:!1})}catch(vt){let fe=x.id||g,Ke=qr(fa(vt),fe);if(Ke.code==="three_ds_aborted")return;if(Ke.code==="checkout_processing_timeout"){if(!Ue.current)return;le(Ke.message),xt(()=>ze.current?.(Ke));return}await De(Ke,{emitDecline:!0,method:Ke.checkoutMethod??ya}),bp(Ke,fe)&&fe&&Ue.current&&Se({sessionId:fe,errorMessage:Ke.message,nonce:ee||void 0,payPalOrderId:Ke.orderId})}},[t,Me,Ze,De,Qe]),Wt=Nr(async p=>{if(me.onClick?.(p),!(p.defaultPrevented||Re||Te)){if(Se(null),le(null),e&>){let g=new wa("Provide either sessionId or create-session props, not both.","validation_error");await De(g),Ue.current&&(ne(null),$e(null));return}if(!e&&!gt){let g=new wa("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await De(g),Ue.current&&(ne(null),$e(null));return}Ve(!0),$e(null),Ce(!1),ne("processing");try{let g=new Bs(Me);if(e){let D=await g.getUnifiedCheckoutSession(e,t);await Pt(D,e);return}try{let D=await g.createAndFetchSession({...gt});await Pt(D,D.data.session?.id??null,{fromCreateSession:!0})}catch(D){if(za(D)==="session_auto_completed"){await Qe({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw D}}catch(g){await De(qr(vp(g,"Automatic payment failed. Please try again."),e))}finally{Ue.current&&(ne(null),$e(null),Ve(!1))}}},[me.onClick,gt,Re,Te,t,Pt,Me,e,De,Qe]),mt=Nr(p=>{let g=W.current;Se(null),ht.current?.({result:p,session:null,sessionId:g?.sessionId??null,autoCompleted:!1})},[]),Et=Nr(p=>{ze.current?.(p)},[]),_=Nr(p=>{Ae.current?.(p)},[]),re=Sa(()=>hp(h),[h]),Ne=Sa(()=>{let p=re?.buttonsLayout??gp(se);return U?{...p,...U,cardButton:{...p.cardButton,...U.cardButton}}:p},[re,se,U]),L=Sa(()=>{let p=re?.appearance;return b?p?{...p,...b,variables:{...p.variables,...b.variables}}:b:p},[b,re]),we=L?.variables,yt=we?.colorPrimary??"#4A49FF",Oe=we?.colorPrimaryHover??ta(yt,.12),It=we?.borderRadius??"8px";return Ip(wp,{children:[io("button",{...me,type:it,onClick:Wt,disabled:Re||Te,"aria-busy":Te,style:{width:"100%",...qe===void 0?{boxSizing:"border-box",height:Pp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Ne.cardButton,...Ss({themeBundle:re,resolvedPrimaryColor:yt,resolvedBorderRadius:It,submitButtonStyle:Ne.submitButton,explicitPrimaryColor:we?.colorPrimary}),fontSize:Ne.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Re||Te?"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||Te?.6:1,...Ut},onMouseEnter:p=>{me.onMouseEnter?.(p),!p.defaultPrevented&&!Re&&!Te&&(re||we?.colorPrimary)&&(p.currentTarget.style.backgroundColor=Oe)},onMouseLeave:p=>{me.onMouseLeave?.(p),!p.defaultPrevented&&(re||we?.colorPrimary)&&(p.currentTarget.style.backgroundColor=yt)},onMouseDown:p=>{me.onMouseDown?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(0.985)")},onMouseUp:p=>{me.onMouseUp?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(1)")},children:io(vo,{content:qe})}),ye&&io("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ye}),_e&&io(Sr,{status:_e,errorMessage:je,authorized:pt}),F&&io("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:io("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:io(xs,{sessionId:F.sessionId,nonce:F.nonce,checkoutMode:"full",billingApiUrl:Me,locale:K,theme:h,...L?{appearance:L}:{},buttonsTheme:se,buttonsStyles:U,initialErrorMessage:F.errorMessage,initialPayPalOrderId:F.payPalOrderId,cardTitleContent:null,onComplete:mt,onError:Et,onDecline:_})})})]})}import{jsx as _p}from"react/jsx-runtime";var kp={StripeSetupMethod:El,PayPalSetupMethod:_l};function Rp(e){return _p(Tl,{...e,branches:kp})}export{Va as DirectPayPalButton,Sp as FloPayAutomaticPaymentButton,sd as FloPayCardSetup,id as FloPayCardSetupError,xs as FloPayCheckout,Rp as FloPayPaymentMethodSetup,Za as FloPayProvider,ws as SplitCardForm,xi as VaultCardFields,Gy as dropThirdPartyOnlyError,Id as useCheckout,Kr as useFloPay,ji as usePayPalFloPay};
|
|
21
|
+
`})]})}return on("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&K(Lo),n&&(r||o)&&K(Lo),n&&de("button",{type:"button",onClick:()=>{e?.("card"),H(!0)},style:{width:"100%",...h,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:k.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...k.cardButton},onMouseDown:C=>{C.currentTarget.style.transform="scale(0.985)"},onMouseUp:C=>{C.currentTarget.style.transform="scale(1)"},children:de(Co,{content:f})}),de("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Ep,jsx as so,jsxs as Tp}from"react/jsx-runtime";var wp=44;function $c(e){return new Promise(t=>setTimeout(t,e))}function Ip(e,t){return e instanceof Ia?e:new Ia(e instanceof Error?e.message:t,"api_error")}function kp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Rp(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:r,checkoutMethod:o,clientId:i,products:s,items:l,subscriptions:f,account:u,successUrl:S,cancelUrl:v,couponCodes:H,tagsData:$,utmMetadata:k,billingApiUrl:q,locale:K,theme:h,appearance:C,buttonsTheme:se,buttonsStyles:z,onSuccess:Ce,onError:J,onDecline:ke,children:qe,disabled:Re=!1,type:it="button",style:zt,...me}){let Me=wa(()=>Cp(q),[q]),Pt=wa(()=>Rp({createSession:n,clientId:i,products:s,items:l,subscriptions:f,account:u,successUrl:S,cancelUrl:v,couponCodes:H,tagsData:$,utmMetadata:k}),[u,v,i,H,n,s,l,f,S,$,k]),[Te,We]=qo(!1),[_e,ne]=qo(null),[je,$e]=qo(null),[yt,be]=qo(!1),[ye,le]=qo(null),[F,Se]=qo(null),Ue=zo(!0),xe=zo(null),V=zo(F),vt=zo(Ce),ze=zo(J),Ae=zo(ke),Xe=Or(p=>ei(xe,async g=>{try{return await p(g)}catch(D){throw g.aborted?Yr(D):D}}),[]);Uo(()=>{V.current=F},[F]),Uo(()=>{vt.current=Ce},[Ce]),Uo(()=>{ze.current=J},[J]),Uo(()=>{Ae.current=ke},[ke]),Uo(()=>(Ue.current=!0,()=>{Ue.current=!1,xe.current?.abort()}),[]),Uo(()=>{if(typeof window>"u")return;let p=g=>{g.key==="Escape"&&Se(null)};return window.addEventListener("keydown",p),()=>{window.removeEventListener("keydown",p)}},[]);let Be=Or((p,g=fa)=>{Ae.current?.(dn(g,p,{code:p.code,declineCode:p.declineCode}))},[]),Qe=Or(async p=>{Ue.current&&($e(null),be(p.result.status==="authorized"),ne("success"),await $c(600),Ue.current&&Bt(()=>vt.current?.(p)))},[]),De=Or(async(p,g)=>{Ue.current&&(ze.current?.(p),g?.emitDecline&&Be(p,g.method),$e(p.message),be(!1),ne("error"),await $c(400))},[Be]),Ct=Or(async(p,g,D)=>{let x=p.data.session??null;if(!x)throw jr(new Ia("No session data returned","api_error"),g);let ee=x.clientSecret||t;if(Dr(x)){await Qe({result:Fr(x,g),session:x,sessionId:x.id||g,autoCompleted:!1});return}if(x.status==="expired")throw jr(za(x),x.id||g);try{if(p.autoProcessingPending){let fe=p.autoProcessingPending,Ke=new Fs(Me),X=await Xe(At=>Ke.waitForCheckoutSessionCompletion(fe.sessionId,{initialDelayMs:fe.retryAfterMs,nonce:ee,statusUrl:fe.statusUrl,signal:At})),qt=Kr(X,x),bt=X.autoProcessingError?.type==="3ds_required"&&X.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:X.autoProcessingError.nextActionRedirectUrl}:null;if(bt&&g&&ee){let At=await Xe(st=>xo(bt,{billingApiUrl:Me,sessionId:g,nonce:ee,session:x,signal:st,telemetry:!0}));await Qe({result:At,session:x,sessionId:x.id||g,autoCompleted:!1});return}if(X.autoProcessingError)throw wr(X.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:X.autoProcessingError.checkoutMethod});if(!Dr(qt))throw Io(qt);await Qe({result:Fr(qt,g),session:qt,sessionId:qt.id||g,autoCompleted:!1});return}if(p.autoProcessingError){let fe=p.autoProcessingError.nextActionRedirectUrl;if(p.autoProcessingError.type==="3ds_required"&&fe&&g&&ee){let Ke=await Xe(At=>rs({billingApiUrl:Me,sessionId:g,nonce:ee,nextActionRedirectUrl:fe,signal:At}));if(Ke.status==="declined")throw wr({type:Ke.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ke.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:p.autoProcessingError.checkoutMethod});let qt=await new Fs(Me).waitForCheckoutSessionCompletion(g,{initialDelayMs:0,nonce:ee}),bt=Kr(qt,x);if(!Dr(bt))throw wr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:p.autoProcessingError.checkoutMethod});await Qe({result:Fr(bt,g),session:bt,sessionId:bt.id||g,autoCompleted:!1});return}throw wr(p.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:p.autoProcessingError.checkoutMethod})}if(D?.fromCreateSession&&p.autoProcessingAttempted===!0)throw wr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ut=await Bo({billingApiUrl:Me,sessionId:g??x.id,session:x,nonce:ee});if(ut.type==="next_action_required"&&ee){let fe=g??x.id,Ke=await Xe(X=>xo(ut,{billingApiUrl:Me,sessionId:fe,nonce:ee,session:x,signal:X,telemetry:!0}));await Qe({result:Ke,session:x,sessionId:x.id||fe,autoCompleted:!1});return}if(ut.type!=="success")throw wr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Qe({result:ut.result,session:x,sessionId:x.id||g,autoCompleted:!1})}catch(ut){let fe=x.id||g,Ke=jr(ga(ut),fe);if(Ke.code==="three_ds_aborted")return;if(Ke.code==="checkout_processing_timeout"){if(!Ue.current)return;le(Ke.message),Bt(()=>ze.current?.(Ke));return}await De(Ke,{emitDecline:!0,method:Ke.checkoutMethod??fa}),kp(Ke,fe)&&fe&&Ue.current&&Se({sessionId:fe,errorMessage:Ke.message,nonce:ee||void 0,payPalOrderId:Ke.orderId})}},[t,Me,Xe,De,Qe]),Vt=Or(async p=>{if(me.onClick?.(p),!(p.defaultPrevented||Re||Te)){if(Se(null),le(null),e&&Pt){let g=new Ia("Provide either sessionId or create-session props, not both.","validation_error");await De(g),Ue.current&&(ne(null),$e(null));return}if(!e&&!Pt){let g=new Ia("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await De(g),Ue.current&&(ne(null),$e(null));return}We(!0),$e(null),be(!1),ne("processing");try{let g=new Fs(Me);if(e){let D=await g.getUnifiedCheckoutSession(e,t);await Ct(D,e);return}try{let D=await g.createAndFetchSession({...Pt});await Ct(D,D.data.session?.id??null,{fromCreateSession:!0})}catch(D){if(qa(D)==="session_auto_completed"){await Qe({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw D}}catch(g){await De(jr(Ip(g,"Automatic payment failed. Please try again."),e))}finally{Ue.current&&(ne(null),$e(null),We(!1))}}},[me.onClick,Pt,Re,Te,t,Ct,Me,e,De,Qe]),ft=Or(p=>{let g=V.current;Se(null),vt.current?.({result:p,session:null,sessionId:g?.sessionId??null,autoCompleted:!1})},[]),Tt=Or(p=>{ze.current?.(p)},[]),T=Or(p=>{Ae.current?.(p)},[]),re=wa(()=>Sp(h),[h]),Ne=wa(()=>{let p=re?.buttonsLayout??bp(se);return z?{...p,...z,cardButton:{...p.cardButton,...z.cardButton}}:p},[re,se,z]),L=wa(()=>{let p=re?.appearance;return C?p?{...p,...C,variables:{...p.variables,...C.variables}}:C:p},[C,re]),we=L?.variables,gt=we?.colorPrimary??"#4A49FF",Oe=we?.colorPrimaryHover??na(gt,.12),It=we?.borderRadius??"8px";return Tp(Ep,{children:[so("button",{...me,type:it,onClick:Vt,disabled:Re||Te,"aria-busy":Te,style:{width:"100%",...qe===void 0?{boxSizing:"border-box",height:wp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Ne.cardButton,...ws({themeBundle:re,resolvedPrimaryColor:gt,resolvedBorderRadius:It,submitButtonStyle:Ne.submitButton,explicitPrimaryColor:we?.colorPrimary}),fontSize:Ne.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Re||Te?"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||Te?.6:1,...zt},onMouseEnter:p=>{me.onMouseEnter?.(p),!p.defaultPrevented&&!Re&&!Te&&(re||we?.colorPrimary)&&(p.currentTarget.style.backgroundColor=Oe)},onMouseLeave:p=>{me.onMouseLeave?.(p),!p.defaultPrevented&&(re||we?.colorPrimary)&&(p.currentTarget.style.backgroundColor=gt)},onMouseDown:p=>{me.onMouseDown?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(0.985)")},onMouseUp:p=>{me.onMouseUp?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(1)")},children:so(Co,{content:qe})}),ye&&so("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ye}),_e&&so(br,{status:_e,errorMessage:je,authorized:yt}),F&&so("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:so("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:so(Bs,{sessionId:F.sessionId,nonce:F.nonce,checkoutMode:"full",billingApiUrl:Me,locale:K,theme:h,...L?{appearance:L}:{},buttonsTheme:se,buttonsStyles:z,initialErrorMessage:F.errorMessage,initialPayPalOrderId:F.payPalOrderId,cardTitleContent:null,onComplete:ft,onError:Tt,onDecline:T})})})]})}import{jsx as xp}from"react/jsx-runtime";var Ap={StripeSetupMethod:Tl,PayPalSetupMethod:El};function Mp(e){return xp(Al,{...e,branches:Ap})}export{Va as DirectPayPalButton,_p as FloPayAutomaticPaymentButton,ld as FloPayCardSetup,sd as FloPayCardSetupError,Bs as FloPayCheckout,Mp as FloPayPaymentMethodSetup,Za as FloPayProvider,Is as SplitCardForm,Bi as VaultCardFields,Qy as dropThirdPartyOnlyError,Rd as useCheckout,Hr as useFloPay,$i as usePayPalFloPay};
|