@flopay/react 1.11.4 → 1.11.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/card-setup-entry.cjs +2 -2
- package/dist/card-setup-entry.mjs +1 -1
- package/dist/chunk-H4MQCBX4.mjs +22 -0
- package/dist/{chunk-YSFYLEHB.mjs → chunk-HSYSKQPT.mjs} +1 -1
- package/dist/chunk-KKA5TF5P.mjs +6 -0
- package/dist/chunk-Q5RE4G4O.mjs +1 -0
- package/dist/chunk-VK67324N.mjs +1 -0
- package/dist/index.cjs +9 -9
- package/dist/index.d.cts +8 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.mjs +7 -7
- package/dist/payment-method-setup-entry.cjs +3 -3
- package/dist/payment-method-setup-entry.mjs +1 -1
- package/dist/payment-method-setup-paypal-AGIJIZDK.mjs +1 -0
- package/dist/payment-method-setup-stripe-6O2YE4RY.mjs +1 -0
- package/package.json +3 -3
- package/dist/chunk-AZRGKPW7.mjs +0 -6
- package/dist/chunk-LIYRDFMO.mjs +0 -1
- package/dist/chunk-M7R46EDF.mjs +0 -1
- package/dist/chunk-UFFPBTKU.mjs +0 -22
- package/dist/payment-method-setup-paypal-FRRQW56L.mjs +0 -1
- package/dist/payment-method-setup-stripe-TI2A5JPE.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as Al}from"./chunk-LIYRDFMO.mjs";import{c as Bt,d as br,e as ta,f as Fi,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 za,c as Ni,d as Oi,e as Li,f as wl,g as Il,h as kl,i as _l,j as Rl,k as Tl}from"./chunk-UFFPBTKU.mjs";import{a as Oa,b as Cl,c as Lr,d as ra,e as La,f as bl,g as Di,h as Ur,i as oa,j as Sl,k as Ua}from"./chunk-M7R46EDF.mjs";import{dropThirdPartyOnlyError as ef}from"@flopay/shared";import{PaymentAPI as Fs}from"@flopay/js";import{FloPayError as ka,resolveBillingApiUrl as bp,resolveButtonsLayoutTheme as Sp,resolveTheme as wp}from"@flopay/shared";import{useCallback as Nr,useEffect as Uo,useMemo as Ia,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 Ui(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 zi(e){return!!e?.gateways?.worldpayCorporateGateway}function zr(e){return e?.status==="open"&&zi(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")||zr(r))||t&&e?.data.paypal?.publishableKey)}function Dl(e,t){if(t&&(!(e instanceof In)||e.type==="authentication_error"))return Ui(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!==void 0)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 qi(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 ji(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 qr(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 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 Cd)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 Ll(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function qa(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 ja(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 $i(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 ap,PaymentAPI as ui,SESSION_CREATE_TELEMETRY as ip}from"@flopay/js";import{buildCheckoutDisplayData as sp,classifyTelemetryFailure as Uc,FloPayError as Pn,isDetachedSessionEligible as lp,resolveBillingApiUrl as cp,resolveButtonsLayoutTheme as dp,resolveIdempotencyKey as xc,resolveTheme as zc,SDK_VERSION as qc,telemetryStatusClass as up}from"@flopay/shared";import ks,{useCallback as hn,useEffect as pr,useMemo as Zn,useRef as Ft,useState as Ht}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 Vi,generateIdempotencyKey as Ld,isValidEmail as pa,normalizeGatewayEnvironment as Ud,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Gi,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 Hr}from"react";import{isValidEmail as wd}from"@flopay/shared";import{useCallback as $l,useEffect as Id,useRef as Kl,useState as Hl}from"react";import{jsx as Wl,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]=Hl(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 _o({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=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",Wl("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&&Wl("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 $a}from"react";function Kr(){return $a(Xn).flopay}function Ki(){return $a(Xn).paypalFlopay??null}function _d(){return $a(cr)}function Vl(){return $a(Xn).billingApiUrl||kd()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Rd}from"@flopay/shared";import{useCallback as Ed,useRef as Ka}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:Rd,...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 Wi=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Ro(e,t){let n=Ka(e);n.current=e;let r=Ka(new Set),o=Ka(t),i=Ka(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(Wi.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 Wa(){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]),W=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:W,isAttemptInvalidated:$,isAttemptCurrent:k,generationRef:n}}import{jsx as ao,jsxs as Yi}from"react/jsx-runtime";var Va=45,$d=1e3,Kd=11e3,Wd={width:"100%",minHeight:Va,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"},Hd={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:Hd[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:W,onComplete:$,onErrorChange:k,onDecline:q,onTechnicalFailure:K,isProcessing:h=!1,onLoadStateChange:C,onInitializationStateChange:se,allowAutomaticRetry:z=!0,onButtonClick:Ce,runBeforeButtonClick:J,session:ke,existingOrderId:je,telemetry:_e,telemetryContext:it,onInstrument:zt,debug:ye=!1}){let Me=Kr(),Pt=Ro(zt,e),Te=ma(()=>{if(Me)return null;let m=Ha({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:zd,enabled:_e!==!1});return m.setCheckoutContext(it??{}),m.beginCheckout(it??{}),m},[n,Me,_e,it?.checkoutMode,it?.layout]),Ve=ma(()=>un(Me),[Me]);Ut(()=>()=>{Te&&Te.flush().catch(()=>{}).finally(()=>Te.destroy())},[Te]);let Re=ma(()=>({error:m=>{Ve?Ve.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=>{Ve?Ve.log(m):Te?.log(m),Pt({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)}),[Pt,Ve,Te]),ne=rt(null),$e=rt(0),Ke=rt(null),yt=rt(null),be=rt(null),fe=jd(da),le=rt(null);le.current||(le.current=Wa());let F=fe??le.current,Se=rt(null),ze=rt(!1),[xe,V]=Hr(!1),[vt,qe]=Hr(!1),[Ae,Xe]=Hr(0),Be=rt(0),[Qe,Ne]=Hr(!1),Ct=rt(!1),Vt=rt(!1),[ft,Tt]=Hr(!1),[T,re]=Hr(!1),{request:Oe,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 Le=gt.current.required,It=ma(()=>n.replace(/\/+$/,""),[n]),p=ke?.gateways?.paypal?.providerObjectType??S,g=p??(u?"subscription":"order"),[D]=Hr(oa),x=ke?.gateways?.paypal?.approvalPresentation??v,ee=Ua(D,x==="app_switch"?"app_switch":void 0,g),ut=p==="order"||p==="setup_token",ge=ma(()=>JSON.stringify([It,s,f,l??"",g,ut,ee,e,je??""]),[It,s,f,l,je,g,ut,ee,e]),We=rt(ge),X=We.current!==ge,qt=rt(ye),bt=rt(null),[At,st]=Hr([]),ce=Sr(m=>{qt.current&&st(Fe=>[...Fe,`${new Date().toISOString().slice(11,23)} ${m}`])},[]);Ut(()=>{qt.current=ye,ye&&ce("debug:enabled"),bt.current?.setEnabled(ye)},[ce,ye]);let kn=rt(W),Nn=rt($),pn=rt(k),jt=rt(q),On=rt(K),Ln=rt(Ce),fn=rt(C),Mt=rt(se),Ge=rt(i),Ue=rt(J),_n=rt(ke),kt=rt(r),Un=rt(o),mn=rt(t),$t=rt(null),Zt=rt(new Map),Qn=rt(new Map),Wn=rt(!1);Ut(()=>(Wn.current=!0,()=>{Wn.current=!1}),[]),Ut(()=>{kn.current=W},[W]),Ut(()=>{Ge.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(()=>{Ue.current=J},[J]),Ut(()=>{_n.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)},[]),_t=Sr(()=>{V(!1),Xe(m=>m+1)},[]),en=Sr(()=>{Ne(!1),(ne.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ne.current)?.focus?.()},[]);Ut(()=>{!xe||!ze.current||(ze.current=!1,en())},[en,xe,Ae]);let nn=Sr((m,Fe)=>{let H=Fe?.popupBlocked??Ur(m);H&&F.markBlocked();let gn=Oa("PayPal",H,D.inAppBrowser),zn=On.current;if(zn){let Gt=H&&D.inAppBrowser?new Vi(gn,"api_error",{code:Fe?.code??"paypal_popup_blocked"}):m;zn("paypal",Gt,Fe);return}pn.current?.(gn)},[F,D.inAppBrowser]),Dt=Sr(m=>{let Fe=Ke.current,H=yt.current;Fe===null||!H||(Re.log({...H,popupCapability:F.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:m}),Re.performance({...H,popupCapability:F.current(),stage:"overlay_return",durationMs:Re.elapsed(Fe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:m}),Ke.current=null)},[F,Re]),an=Sr((m,Fe,H)=>{let gn=yt.current;Dt("overlay_timeout"),gn&&Re.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(Fe,{...H,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ee,terminalReason:"overlay_timeout"}),Ne(!0),_t(),Qt()},[Dt,Qt,nn,F,ee,_t,Re]),Ot=Sr(()=>{F.markAvailable();let m=yt.current;m&&(be.current=m.attempt,Re.log({...m,popupCapability:F.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[F,Re]),{finishAttempt:rn,generationRef:Nt,invalidateAttempt:G,isAttemptCurrent:er,isAttemptInvalidated:tr,startAttempt:nr}=ua(an,{onHandoffObserved:Ot}),tn=Sr(()=>(Ne(!1),nr("paypal")),[nr]),Rn=Sr(m=>{G(m?.generation),m?.showRetry&&Ne(!0),m?.remount&&_t(),m?.focus!==!1&&Qt()},[Qt,G,_t]),vn=m=>{let Fe=$t.current;return Fe&&Qn.current.set(m,Fe),m};Ut(()=>{We.current!==ge&&(We.current=ge,Ct.current=!1,Vt.current=!1,V(!1),qe(!1),Tt(!1),Mt.current?.("loading"))},[ge]),Ut(()=>{Bt(()=>fn.current?.(xe&&!ft))},[xe,ft]);let pe=Ud(l);Ut(()=>{let m={attempt:Nt.current+1,inAppBrowser:D.inAppBrowser,appFamily:D.appFamily,popupCapability:F.current(),presentationMode:ee},Fe=()=>({...yt.current??m,popupCapability:F.current()}),H={error:d=>Re.error({...d,...Fe()}),log:d=>Re.log({...d,...Fe()}),performance:d=>Re.performance({...d,...Fe()}),terminal:d=>Re.terminal({...d,...Fe()}),startTiming:Re.startTiming,elapsed:Re.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${pe??"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),H.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}$e.current=H.startTiming(),H.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,En=!1,tt=()=>Gt||En,rr,Xr=!1,Rt=()=>{rr=Ld(),rr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Xr=!0},Tn=null,mr=!1,Hn=null,Yt=!1,or=()=>{!Hn||Yt||(Yt=!0,Hn.close().catch(()=>{}))},An=!1,_r=!1,Mn=ne.current,yr=null,fr=null,Rr=[],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},Zr=()=>{yr?.disconnect(),yr=null,fr?.disconnect(),fr=null;for(let d of Rr.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?.()}},Or=()=>{qn&&(clearTimeout(qn),qn=null)},Sn=()=>{Zr(),Or()},cn={setEnabled:d=>{d?gr():Zr()}};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=jr(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),qe(!0),Mt.current?.("retrying"),Tn=setTimeout(()=>{Gt||Xe(E=>E+1)},$d);return}if(V(!1),re(!1),qe(!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=Di({code:Yl(d,c),message:c},{inAppBrowser:D.inAppBrowser,handoffObserved:!1});E.popupBlocked&&F.markBlocked(),H.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 _=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=H.startTiming();H.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Q=()=>{H.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),H.performance({stage:"processing",durationMs:H.elapsed(E),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ae=_n.current,De=c?.accountPatch?.email??kt.current,at=c?.accountPatch?.userId??ae?.customer?.id??ae?.accountData?.userId??"",me=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:De??ae?.customer?.email??"",...me?{firstName:me}:{},...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&&Wn.current)return;Q(),H.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=jr(A)??A;Q(),ie.status===400&&(typeof te?.declineCode=="string"||!Array.isArray(te?.fields))?H.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ie.status===400||ie.status===422?H.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):H.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(),H.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let De=ae instanceof Error?ae.message:"PayPal payment failed.",at=jr(De)??De;xn(at),Bt(()=>jt.current?.(dn("paypal",at)));return}},O=()=>new Vi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),R=d=>tt()?Promise.reject(O()):Promise.resolve(d),nt=async d=>{if(tt())throw O();Xr||Rt();let c=$t.current,I=c?.sessionId??e,E=c?.nonce??mn.current;H.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:Gi,paymentMethodId:null,intentKind:g==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:rr})}catch(ae){throw H.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 H.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)??Lr(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=pe==="live"?"production":pe,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}H.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),H.performance({stage:"provider_ready",durationMs:H.elapsed($e.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),H.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 Vi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let N=_n.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((Ge.current||Le)&&!pa(Ie.email)){let wn=await L("PayPal",Ie);if(!wn)return;Ie=wn}pa(Ie.email)&&(Y.accountPatch=Dn({...Y.accountPatch,...Ie}),await Ge.current?.(Ie));let ar;g==="setup_token"?ar={id:A,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Gi}:ut?ar={id:A,isPaypal:!0,gateway:"paypal",paymentMethodType:Gi}:ar={id:A,isPaypal:!0},await _(ar,Y)}catch(N){xn(N instanceof Error?N.message:"PayPal capture failed.")}finally{tt()||re(!1)}}},ae=ie=>{let te=je?()=>R(je):()=>nt(ie);return async()=>vn(await te())},De=E.Buttons({style:{layout:"horizontal",height:Va,tagline:!1},...ee==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ie,te)=>{if(tt()){await te.reject();return}Rt();let A=Ue.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(),H.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),H.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Ke.current=H.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"),H.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ze.current=!0,Rn({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}=Di(ie,{inAppBrowser:D.inAppBrowser,handoffObserved:A!=null&&be.current===A.generation});if(N&&F.markBlocked(),Dt(Ie),ct){H.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}H.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,Rn({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=De.isEligible();if(ce(`isEligible=${at}`),H.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}_r=!0,Hn=De,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)")};Rr.push(setTimeout(()=>ie("3s"),3e3)),Rr.push(setTimeout(()=>ie("8s"),8e3)),Rr.push(setTimeout(()=>ie("15s"),15e3))},xt(),ce("render:start");let b=H.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=De.render(Mn);(async()=>{try{if(await lt,ce(`render:resolved inactive=${tt()}`),Sn(),tt()){or();return}An=!0,V(!0),qe(!1),Mt.current?.("ready"),H.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),H.performance({stage:"checkout_render",durationMs:H.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&&_r&&(ae="render_rejected"),w(ae,Q)})},0);return()=>{Gt=!0,clearTimeout(B),Tn&&clearTimeout(Tn),Sn(),bt.current===cn&&(bt.current=null),or(),Ke.current=null,yt.current=null}},[z,It,s,f,l,g,ee,ut,e,je,Ae,Re,L,Le,ce,Dt]);let et=ye?Yi("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?`
|
|
1
|
+
import{a as Sl}from"./chunk-Q5RE4G4O.mjs";import{c as Nt,d as Sr,e as Xo,f as Ti,g as ll,h as cl,i as Qo,j as dl,k as rd,m as od}from"./chunk-KKA5TF5P.mjs";import{a as bl}from"./chunk-HSYSKQPT.mjs";import{a as ta,b as Oa,c as xi,d as Bi,e as Fi,f as fl,g as gl,h as hl,i as Pl,j as vl,k as Cl}from"./chunk-H4MQCBX4.mjs";import{a as Ba,b as Mi,c as ul,d as Ai,e as go,f as pl,g as zr,h as Fa,i as yl,j as ea,k as Da,l as ml}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as Cf}from"@flopay/shared";import{PaymentAPI as Cs}from"@flopay/js";import{FloPayError as Ca,resolveBillingApiUrl as Op,resolveButtonsLayoutTheme as Np,resolveTheme as Lp}from"@flopay/shared";import{useCallback as Fr,useEffect as No,useMemo as ba,useRef as Lo,useState as zo}from"react";import{Fragment as bo,jsx as Kn,jsxs as wl}from"react/jsx-runtime";function ad(){return wl(bo,{children:[wl("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[Kn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Kn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Kn("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:Kn("path",{d:"M9 18l6-6-6-6"})})]})}function id(){return Kn(bo,{children:"Go back"})}function sd(){return Kn(bo,{children:"Secure card checkout"})}function ho(e){return e!==void 0&&(e===""||e===null||e===!1)}function Po({content:e}){return Kn(bo,{children:e===void 0?Kn(ad,{}):e})}function vo({content:e}){return Kn(bo,{children:e===void 0?Kn(id,{}):e})}function na({content:e}){return Kn(bo,{children:e===void 0?Kn(sd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as ld,canRecoverHostedCardForm as cd,classifyTelemetryFailure as dd,FloPayError as kn,isCardHolderNamePlaceholder as ud,isMoneySettledOutcome as pd,isMountableVaultBlock as yd,isSetupIntentClientSecret as md,isValidEmail as fd,resolveSetupFutureUsage as gd,resolveWalletModeOptions as hd}from"@flopay/shared";import{canRecoverHostedCardForm as Qr,hasServerSideCardGateway as Bl}from"@flopay/shared";import{splitFullName as aa}from"@flopay/shared";import{applyFriendlyMessageOverride as wo}from"@flopay/shared";var Pd="Checkout is temporarily unavailable. Please try again later.";function Di(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof kn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function vd(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function kl(){return new kn(Pd,"api_error",{code:"CheckoutInitializationFailed"})}function Il(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(yd(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||cd(o))||t&&e?.data.paypal?.publishableKey)}function Rl(e,t){if(t&&(!(e instanceof kn)||e.type==="authentication_error"))return Di(e);if(!(e instanceof kn&&vd(e))){if(!t&&!(e instanceof kn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...dd(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof kn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof kn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Co(e,t,n,o={}){let a;return(i={})=>{if(a!==void 0)return a;let s={...o,...i,email:i.email?.trim()||o.email?.trim()},c=ud(s.firstName,s.lastName);if(!fd(s.email))return Promise.reject(new kn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let f={};for(let[C,E]of Object.entries(s)){if(c&&C.endsWith("Name")||typeof E!="string")continue;let k=E.trim();k&&(f[C]=k)}return a=e.claimCheckoutSession(t,n,{accountData:f}),a.catch(()=>{}),a}}function El(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Oi(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function _l(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],o=n.reduce((i,s)=>i+(s.overrideAmount??s.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(o*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Ni(e,t){return t?{...e,...t}:e}function un(e,t,n){let o=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:o,...a?{code:a}:{},...i?{declineCode:i}:{},...s?{sessionId:s}:{}}}function Ur(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Mr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Ar(e){return e?.status==="authorized"||e?.status==="complete"}function qr(e,t){if(e.data.session)return e.data.session;let n=e.raw,o=n?.latestTransactionAttempt?.result,a=n?.status==="authorized"||o==="AUTHORIZED";return a||n?.status==="completed"||o==="SUCCESS"?{...t,status:a?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function Tl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Na(e){let t=Tl(e);return new kn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function La(e){return e instanceof kn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function So(e){return Tl(e)?new kn("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new kn("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new kn(ld,"api_error",{code:"checkout_processing_timeout"})}function ra(e,t){return e==="processing"||pd(e,t)}function Ml(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Al(e,t){let n=e;if(md(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new kn(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:o,error:a}=await n.retrievePaymentIntent(t);if(a)throw new kn(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var bd=["apple_pay","google_pay"];function xl(e,t="automatic",n){let o=gd(n,bd,"wallet");return{...hd(e,t),paymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var Cd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Li(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Cd.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function oa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Pp,PaymentAPI as ai,SESSION_CREATE_TELEMETRY as vp}from"@flopay/js";import{buildCheckoutDisplayData as bp,classifyTelemetryFailure as Dc,FloPayError as bn,isDetachedSessionEligible as Cp,isMountableVaultBlock as Sp,resolveBillingApiUrl as wp,resolveButtonsLayoutTheme as kp,resolveDirectPaypalConfig as Oc,resolveIdempotencyKey as _c,resolveCheckoutLogLayout as Ip,resolveTheme as Nc,SDK_VERSION as Lc,telemetryStatusClass as Rp}from"@flopay/shared";import ps,{useCallback as vn,useEffect as pr,useMemo as Yn,useRef as At,useState as Gt}from"react";import{createContext as Fl}from"react";var Gn=Fl({flopay:null,paypalFlopay:null,billingApiUrl:""}),cr=Fl({session:null,loading:!1,error:null});import{PaymentAPI as Ui}from"@flopay/js";import{buildPayPalProcessPaymentRequest as Od,buildPayPalSessionIntentRequest as Nd,buildPayPalTokenizedBody as Ld,classifyTelemetryFailure as zd,describePayPalProcessFailure as Ud,FloPayError as qi,friendlyPayPalFailureMessage as qd,generateIdempotencyKey as jd,isPayPalTeardownMessage as $d,isValidEmail as jl,mergePayPalPayerIdentity as Wd,needsPayPalPayerDetails as Hd,normalizeGatewayEnvironment as Vd,paypalProviderIdentityRequired as $l,resolvePayPalApprovalIdentity as Kd,resolvePayPalDeclineReason as Gd,SDK_VERSION as Yd,usesPayPalVaultedChannel as Jd}from"@flopay/shared";import{loadScript as Zd}from"@paypal/paypal-js";import{useCallback as wr,useContext as Xd,useEffect as Lt,useMemo as ca,useRef as ot,useState as Wr}from"react";import{compactBuyerIdentity as Sd,isValidEmail as wd}from"@flopay/shared";import{useCallback as Dl,useEffect as kd,useRef as Ol,useState as Ll}from"react";import{compactBuyerIdentity as dr}from"@flopay/shared";import{jsx as Nl,jsxs as ia}from"react/jsx-runtime";function ko(){let[e,t]=Ll(null),n=Ol(null),o=Ol(0),a=Dl((s,c)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:c}),new Promise(f=>{n.current=f})),[]),i=Dl(s=>{let c=n.current;n.current=null,t(null),c?.(s)},[]);return kd(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function Io({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[s,c]=Ll(e.email?.trim()??""),f=wd(s.trim());return ia("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[ia("div",{style:{fontWeight:700},children:["Continue with ",t]}),ia("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Nl("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:C=>c(C.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),ia("div",{style:{display:"flex",gap:"0.5rem"},children:[o&&Nl("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),ia("button",{type:"button",disabled:!f||a,onClick:()=>{n(Sd({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as Id}from"@flopay/shared";import{useContext as za}from"react";function jr(){return za(Gn).flopay}function zi(){return za(Gn).paypalFlopay??null}function Rd(){return za(cr)}function zl(){return za(Gn).billingApiUrl||Id()}import{FLO_INSTRUMENT_ONCE_NAMES as Ed,invokeMerchantCallback as _d,projectFloInstrument as Td}from"@flopay/shared";import{useCallback as Md,useRef as Ua}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Ul}from"@flopay/shared";function Ro(e,t){let n=Ua(e);n.current=e;let o=Ua(new Set),a=Ua(t),i=Ua(t);return Xo(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),Md(s=>{if(i.current!==t)return;let c=Td(s);if(c){if(Ed.has(c.name)){if(o.current.has(c.name))return;o.current.add(c.name)}_d(()=>n.current?.(c))}},[t])}import{createContext as Ad}from"react";var sa=Ad(null);function qa(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var xd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Bd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Fd(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function Dd(e){let t=Fd(),n=(a,i)=>a?a.bind(e):i,o=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:o,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,o()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function ja(e){let t=globalThis[Bd];return Dd(t?.(e)??{})}function pn(e){if(e)return e[xd]}import{useCallback as $r,useEffect as ql,useRef as eo}from"react";function la(e,t){let n=eo(0),o=eo(null),a=eo(null),i=eo(e),s=eo(t?.onHandoffObserved),c=eo(t?.defersMissingTerminal),f=eo(t?.onMissingTerminalDeferred);ql(()=>{i.current=e,s.current=t?.onHandoffObserved,c.current=t?.defersMissingTerminal,f.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let C=$r((v=a.current)=>{v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),E=$r(v=>{C();let P=n.current+1;return n.current=P,o.current=null,a.current={generation:P,method:v,timer:null,yieldedControl:!1},P},[C]),k=$r(v=>{let P=a.current;return v!==void 0&&P?.generation!==v?!1:(C(P),a.current=null,(v===void 0||o.current===v)&&(o.current=null),!0)},[C]),z=$r(v=>{let P=a.current,he=v??P?.generation??n.current;(v===void 0||P?.generation===v)&&(C(P),a.current=null),o.current=he},[C]),ne=$r(v=>o.current===(v??n.current),[]),O=$r(v=>a.current?.generation===v&&o.current!==v,[]),ve=$r(()=>{let v=a.current;v&&(C(v),!v.yieldedControl&&(v.yieldedControl=!0,s.current?.(v.method)))},[C]),V=$r(()=>{let v=a.current;!v?.yieldedControl||document.visibilityState!=="visible"||(C(v),v.timer=setTimeout(()=>{if(v.timer=null,a.current?.generation===v.generation){if(c.current?.(v.method)){f.current?.(v.method,v.generation);return}a.current=null,o.current=v.generation,i.current(v.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},ul))},[C]);return ql(()=>{let v=()=>{document.visibilityState==="visible"?V():ve()};return document.addEventListener("visibilitychange",v),window.addEventListener("blur",ve),window.addEventListener("focus",V),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("blur",ve),window.removeEventListener("focus",V),C()}},[C,ve,V]),{startAttempt:E,finishAttempt:k,invalidateAttempt:z,isAttemptInvalidated:ne,isAttemptCurrent:O,generationRef:n}}import{jsx as to,jsxs as ji}from"react/jsx-runtime";var $a=45,Qd=1e3,eu=11e3,tu={width:"100%",minHeight:$a,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},nu={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function ru(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:nu[e.kind]??null}}function Wl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":pl(t)?"paypal_init_timeout":"paypal_init_failure"}function ou(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Hl({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:s,environment:c,currency:f,isSubscription:C,providerObjectType:E,approvalPresentation:k,onTokenizedBody:z,onComplete:ne,onErrorChange:O,onDecline:ve,onTechnicalFailure:V,isProcessing:v=!1,onLoadStateChange:P,onInitializationStateChange:he,allowAutomaticRetry:N=!0,onButtonClick:Ie,runBeforeButtonClick:Y,session:Fe,existingOrderId:lt,telemetry:ze,telemetryContext:ct,onInstrument:zt,debug:pe=!1}){let Te=jr(),Pt=Ro(zt,e),Re=ca(()=>{if(Te)return null;let u=ja({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Yd,enabled:ze!==!1});return u.setCheckoutContext(ct??{}),u.beginCheckout(ct??{}),u},[n,Te,ze,ct?.checkoutMode,ct?.layout]),He=ca(()=>pn(Te),[Te]);Lt(()=>()=>{Re&&Re.flush().catch(()=>{}).finally(()=>Re.destroy())},[Re]);let ke=ca(()=>({error:u=>{He?He.error(u):Re?.error(u),Pt({class:"technical_error",errorCode:u.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":u.errorCode,requestCategory:u.requestCategory,provider:u.provider})},log:u=>{He?He.log(u):Re?.log(u),Pt({class:"lifecycle",name:u.name,provider:u.provider})},performance:u=>{He?He.performance(u):Re?.performance(u)},terminal:u=>{He?He.terminal(u):Re?.terminal(u)},startTiming:()=>He?.now()??Re?.now()??0,elapsed:u=>He?.elapsed(u)??Math.max(0,(Re?.now()??u)-u)}),[Pt,He,Re]),Q=ot(null),je=ot(0),$e=ot(null),pt=ot(null),be=ot(null),ye=Xd(sa),re=ot(null);re.current||(re.current=qa());let M=ye??re.current,Ce=ot(null),Ue=ot(!1),[Me,U]=Wr(!1),[vt,qe]=Wr(!1),[Ee,Je]=Wr(0),Ae=ot(0),[Qe,De]=Wr(!1),bt=ot(!1),Yt=ot(!1),[yt,Et]=Wr(!1),[I,ee]=Wr(!1),{request:Oe,collect:F,finish:Se}=ko(),mt=ot({sessionId:e,required:$l(o,Fe)});mt.current.sessionId!==e&&(mt.current={sessionId:e,required:$l(o,Fe)});let Ne=mt.current.required,wt=ca(()=>n.replace(/\/+$/,""),[n]),d=Fe?.gateways?.paypal?.providerObjectType??E,m=d??(C?"subscription":"order"),[A]=Wr(ea),T=Fe?.gateways?.paypal?.approvalPresentation??k,J=Da(A,T==="app_switch"?"app_switch":void 0,m),ft=Jd(d),me=ca(()=>JSON.stringify([wt,s,f,c??"",m,ft,J,e,lt??""]),[wt,s,f,c,lt,m,ft,J,e]),We=ot(me),H=We.current!==me,Ut=ot(pe),Ct=ot(null),[_t,at]=Wr([]),oe=wr(u=>{Ut.current&&at(xe=>[...xe,`${new Date().toISOString().slice(11,23)} ${u}`])},[]);Lt(()=>{Ut.current=pe,pe&&oe("debug:enabled"),Ct.current?.setEnabled(pe)},[oe,pe]);let In=ot(z),Bn=ot(ne),yn=ot(O),qt=ot(ve),Fn=ot(V),Dn=ot(Ie),hn=ot(P),Tt=ot(he),Ve=ot(i),Le=ot(Y),Rn=ot(Fe),kt=ot(o),On=ot(a),mn=ot(t),jt=ot(null),Qt=ot(new Map),Jn=ot(new Map),$n=ot(!1);Lt(()=>($n.current=!0,()=>{$n.current=!1}),[]),Lt(()=>{In.current=z},[z]),Lt(()=>{Ve.current=i},[i]),Lt(()=>{Bn.current=ne},[ne]),Lt(()=>{yn.current=O},[O]),Lt(()=>{qt.current=ve},[ve]),Lt(()=>{Fn.current=V},[V]),Lt(()=>{Dn.current=Ie},[Ie]),Lt(()=>{hn.current=P},[P]),Lt(()=>{Tt.current=he},[he]),Lt(()=>{Le.current=Y},[Y]),Lt(()=>{Rn.current=Fe},[Fe]),Lt(()=>{kt.current=o},[o]),Lt(()=>{On.current=a},[a]),Lt(()=>{mn.current=t},[t]),Lt(()=>{Ae.current=Ee},[Ee]),Lt(()=>{Qe&&Ce.current?.focus()},[Qe,Ee]);let en=wr(()=>{window.setTimeout(()=>{Ce.current?.focus()},0)},[]),xt=wr(()=>{U(!1),Je(u=>u+1)},[]),Cn=wr(()=>{De(!1),(Q.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Q.current)?.focus?.()},[]);Lt(()=>{!Me||!Ue.current||(Ue.current=!1,Cn())},[Cn,Me,Ee]);let ln=wr((u,xe)=>{let L=xe?.popupBlocked??zr(u);L&&M.markBlocked();let Pn=Ba("PayPal",L,A.inAppBrowser),Nn=Fn.current;if(Nn){let Jt=L&&A.inAppBrowser?new qi(Pn,"api_error",{code:xe?.code??"paypal_popup_blocked"}):u;Nn("paypal",Jt,xe);return}yn.current?.(Pn)},[M,A.inAppBrowser]),Ft=wr(u=>{let xe=$e.current,L=pt.current;xe===null||!L||(ke.log({...L,popupCapability:M.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:u}),ke.performance({...L,popupCapability:M.current(),stage:"overlay_return",durationMs:ke.elapsed(xe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:u}),$e.current=null)},[M,ke]),fn=wr((u,xe,L)=>{let Pn=pt.current;Ft("overlay_timeout"),Pn&&ke.error({...Pn,popupCapability:M.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),ln(xe,{...L,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:J,terminalReason:"overlay_timeout"}),De(!0),xt(),en()},[Ft,en,ln,M,J,xt,ke]),Dt=wr(()=>{M.markAvailable();let u=pt.current;u&&(be.current=u.attempt,ke.log({...u,popupCapability:M.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[M,ke]),{finishAttempt:on,generationRef:Bt,invalidateAttempt:ae,isAttemptCurrent:Zn,isAttemptInvalidated:Xn,startAttempt:Qn}=la(fn,{onHandoffObserved:Dt}),tn=wr(()=>(De(!1),Qn("paypal")),[Qn]),En=wr(u=>{ae(u?.generation),u?.showRetry&&De(!0),u?.remount&&xt(),u?.focus!==!1&&en()},[en,ae,xt]),Sn=u=>{let xe=jt.current;return xe&&Jn.current.set(u,xe),u};Lt(()=>{We.current!==me&&(We.current=me,bt.current=!1,Yt.current=!1,U(!1),qe(!1),Et(!1),Tt.current?.("loading"))},[me]),Lt(()=>{Nt(()=>hn.current?.(Me&&!yt))},[Me,yt]);let ce=Vd(c);Lt(()=>{let u={attempt:Bt.current+1,inAppBrowser:A.inAppBrowser,appFamily:A.appFamily,popupCapability:M.current(),presentationMode:J},xe=()=>({...pt.current??u,popupCapability:M.current()}),L={error:l=>ke.error({...l,...xe()}),log:l=>ke.log({...l,...xe()}),performance:l=>ke.performance({...l,...xe()}),terminal:l=>ke.terminal({...l,...xe()}),startTiming:ke.startTiming,elapsed:ke.elapsed},Pn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",Nn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(oe(`mount clientId=${Pn} env=${c??"(unset)"}\u2192${ce??"live"} ccy=${f} sub=${C}`),oe(`ua=${Nn.slice(0,80)}${Nn.length>80?"\u2026":""}`),!s){oe("FAIL: clientId empty \u2014 gateway misconfigured"),Et(!0),L.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Q.current){oe("FAIL: containerRef not attached");return}je.current=L.startTiming(),L.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Jt=!1,_n=!1,nt=()=>Jt||_n,yr=ft?m:void 0,Dr,It=!1,Ln=()=>{Dr=jd(),Dr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),It=!0},er=null,tr=!1,$t=null,mr=!1,fr=()=>{!$t||mr||(mr=!0,$t.close().catch(()=>{}))},Tn=!1,gr=!1,Wn=Q.current,hr=null,Er=null,zn=[],nr=null,rr=!1,Mt=!1,Un=null,wn=l=>{if(!l||typeof l.getBoundingClientRect!="function")return"(no rect)";let y=l.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},or=l=>{if(!l)return"(empty)";try{let y=new URL(l,typeof window>"u"?"https://localhost":window.location.href),h=y.pathname.toLowerCase();return h.includes("checkcaptcha")||h.includes("captcha")?`CAPTCHA(${y.host}${h})`:h.includes("risk")||h.includes("challenge")?`RISK(${y.host}${h})`:h.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${h}`.slice(0,100)}catch{return l.slice(0,80)}},ar=l=>{let y=l.getAttribute("src"),h=l.getAttribute("srcdoc"),$=l.getAttribute("name"),le=l.getAttribute("sandbox"),Pe=[];return y&&Pe.push(`src=${or(y)}`),h&&Pe.push(`srcdoc[${h.length}ch]`),!y&&!h&&Pe.push("src=(empty) srcdoc=(empty)"),$&&Pe.push(`name=${$.slice(0,40)}`),le!==null&&Pe.push(`sandbox="${le.slice(0,40)}"`),Pe.join(" ")},tt=l=>{if(!(l instanceof HTMLIFrameElement))return"";try{let y=l.contentDocument;if(!y)return"cd=null";let h=y.body?.children.length??0,$=y.body?.innerHTML.length??0,le=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${h}children,${$}ch] head[${le}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},nn=[],cn=l=>{if(nt())return;let y=l.message??String(l.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(oe(`window:error ${y.slice(0,140)}`),nn.push(y))},Mn=l=>{if(nt())return;let y=l.reason instanceof Error?l.reason.message:String(l.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(oe(`window:rejection ${y.slice(0,140)}`),nn.push(y))},Or={value:0},Pr=()=>{hr?.disconnect(),hr=null,Er?.disconnect(),Er=null;for(let l of zn.splice(0))clearTimeout(l);Mt=!1,rr&&typeof window<"u"&&(window.removeEventListener("error",cn),window.removeEventListener("unhandledrejection",Mn)),rr=!1},_r=()=>{if(!(rr||nt()||Tn)){if(rr=!0,nn.length=0,Or.value=0,typeof window<"u"&&(window.addEventListener("error",cn),window.addEventListener("unhandledrejection",Mn)),typeof PerformanceObserver<"u")try{Er=new PerformanceObserver(l=>{if(!nt())for(let y of l.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;Or.value+=1;let h=Math.round(y.duration);oe(`net ${h}ms ${y.name.slice(0,90)}`)}}),Er.observe({type:"resource",buffered:!0})}catch{}Un?.()}},Hn=()=>{nr&&(clearTimeout(nr),nr=null)},rn=()=>{Pr(),Hn()},Nr={setEnabled:l=>{l?_r():Pr()}};Ct.current=Nr,Ut.current&&_r();let an=$d,w=l=>{if(nt()||an(l))return;let y=wo(l)??l;Nt(()=>yn.current?.(y))},b=(l,y)=>{if(Jt||tr)return;tr=!0,_n=!0,rn(),fr();let h=ru({kind:l,generationActive:!0,automaticRetryAllowed:N,automaticRetryUsed:bt.current});if(h.action==="retry"){bt.current=!0,U(!1),ee(!1),qe(!0),Tt.current?.("retrying"),er=setTimeout(()=>{Jt||Je($=>$+1)},Qd);return}if(U(!1),ee(!1),qe(!1),Et(!0),h.action!=="ignore"){if(Tt.current?.("exhausted"),h.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",y);return}if(h.report){let $=Mi({code:Wl(l,y),message:y},{inAppBrowser:A.inAppBrowser,handoffObserved:!1});$.popupBlocked&&M.markBlocked(),L.error({errorCode:$.popupBlocked?$.errorCode:h.report.errorCode,stage:h.report.stage,operationOutcome:h.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:$.terminalReason})}Yt.current||(Yt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Wl(l,y)))}};Et(!1);let j=async(l,y=jt.current)=>{if(nt())return;let h=y?.sessionId??e;if(In.current){await In.current(l,{sessionId:h,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let $=L.startTiming();L.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let le=()=>{L.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"processing",durationMs:L.elapsed($),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Pe=Od({body:l,sessionId:h,nonce:y?.nonce??mn.current,accountPatch:y?.accountPatch,session:Rn.current,email:kt.current}),te=await new Ui(wt,{telemetry:!1}).processPayment(Pe.userId,Pe.params);if(te.ok){if(_n||Jt&&$n.current)return;le(),L.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Nt(()=>Bn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(nt())return;let we=await te.json().catch(()=>null),Be=Ud(we),rt=Be.message;le(),te.status===400&&(typeof we?.declineCode=="string"||!Array.isArray(we?.fields))?L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):te.status===400||te.status===422?L.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):L.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ou(te.status),failureCategory:te.status>=500?"server_error":void 0}),w(rt),Nt(()=>qt.current?.(un("paypal",rt,{code:Be.code,declineCode:Be.declineCode})));return}catch(Pe){if(nt())return;le(),L.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ht=qd(Pe instanceof Error?Pe.message:void 0);w(Ht),Nt(()=>qt.current?.(un("paypal",Ht)));return}},K=()=>new qi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),it=l=>nt()?Promise.reject(K()):Promise.resolve(l),Wt=async l=>{if(nt())throw K();It||Ln();let y=jt.current,h=y?.sessionId??e,$=y?.nonce??mn.current;L.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let le;try{le=await new Ui(wt,{telemetry:!1}).createSessionIntent(h,$??"",Nd(yr),{idempotencyKey:Dr})}catch(Pe){throw L.error({...zd(Pe,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Pe}if(nt())throw K();if(le.provider!=="paypal"||le.providerObjectType!==m)throw new Error(l);return L.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),le.providerObjectId},de=(l,y)=>{let h=y?.nonce??mn.current;if(!h)return;let $=y?.sessionId??e,le=Gd(l);new Ui(wt,{telemetry:!1}).reportSessionIntentDecline($,h,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:le}).catch(()=>{})},x=Ee;oe("loadScript:scheduled (deferred 1 tick)");let B=null,R=setTimeout(()=>{if(Jt){oe("loadScript:skipped (cancelled before defer ran)");return}oe("loadScript:start");let l=ce==="live"?"production":ce,y={};m==="subscription"?y={intent:"subscription",vault:!0}:m==="order"&&(y={intent:"capture"}),B=Zd({clientId:s,currency:f,...y,...l?{environment:l}:{},...l==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let h=!1;B.then($=>{if(h=!0,oe(`loadScript:resolved inactive=${nt()} ns=${!!$} buttons=${!!$?.Buttons}`),nt())return;if(!$?.Buttons){oe("FAIL: namespace missing Buttons factory"),b("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}L.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"provider_ready",durationMs:L.elapsed(je.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),L.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let le=async(Z,S)=>{if(nt()||Ae.current!==x)return;let q=Z.vaultSetupToken??Z.subscriptionID??Z.orderID??"",Ke=q?Jn.current.get(q):Qt.current.get(x);if(!(!Ke||!Zn(Ke.generation))&&on(Ke.generation)){Jn.current.delete(q),Qt.current.delete(Ke.surfaceKey),Ft("approved");try{if(ee(!0),Nt(()=>yn.current?.(null)),!q)throw new qi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ge=Kd({accountPatch:Ke.accountPatch,email:kt.current,billingName:On.current,session:Rn.current});if(Hd(ge))try{ge=Wd(ge,await S?.order?.get?.())}catch{}if((Ve.current||Ne)&&!jl(ge.email)){let dt=await F("PayPal",ge);if(!dt)return;ge=dt}jl(ge.email)&&(Ke.accountPatch=dr({...Ke.accountPatch,...ge}),await Ve.current?.(ge));let _e=Ld(q,yr);await j(_e,Ke)}catch(ge){w(ge instanceof Error?ge.message:"PayPal capture failed.")}finally{nt()||ee(!1)}}},Pe=Z=>{let S=lt?()=>it(lt):()=>Wt(Z);return async()=>Sn(await S())},Ht=$.Buttons({style:{layout:"horizontal",height:$a,tagline:!1},...J==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Z,S)=>{if(nt()){await S.reject();return}Ln();let q=Le.current,Ke={};if(q)try{let dt=await q("paypal");if(nt()){await S.reject();return}if(!dt.proceed){jt.current=null,Qt.current.delete(x),await S.reject();return}Ke={sessionId:dt.sessionId,accountPatch:dt.accountPatch,nonce:dt.nonce}}catch(dt){oe(`onClick:runBeforeButtonClick rejected msg=${(dt instanceof Error?dt.message:String(dt)).slice(0,120)}`),jt.current=null,Qt.current.delete(x),await S.reject();return}Nt(()=>Dn.current?.("paypal"));let ge=tn(),_e={generation:ge,surfaceKey:x,...Ke};jt.current=_e,Qt.current.set(x,_e),pt.current={...u,attempt:ge},await S.resolve(),L.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),$e.current=L.startTiming()},createOrder:m==="order"?Pe("Failed to create PayPal order."):void 0,createSubscription:m==="subscription"?Pe("Failed to create PayPal subscription."):void 0,createVaultSetupToken:m==="setup_token"?async()=>Sn(await Wt("Failed to create PayPal setup token.")):void 0,onApprove:le,onCancel:()=>{if(nt())return;let Z=Qt.current.get(x)??jt.current;Z&&Qt.current.delete(Z.surfaceKey),jt.current=null,Ft("cancelled"),L.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ue.current=!0,En({generation:Z?.generation,remount:!0,focus:!1})},onError:Z=>{if(nt()||Ae.current!==x)return;let S=Z instanceof Error?Z.message:"PayPal failed to render.";if(oe(`onError rendered=${Tn} msg=${S.slice(0,120)}`),Tn){let q=Qt.current.get(x)??jt.current;if(q&&!Zn(q.generation)||!q&&Xn())return;if(an(S)){on(q?.generation);return}let{errorCode:Ke,popupBlocked:ge,providerDeclined:_e,terminalReason:dt}=Mi(Z,{inAppBrowser:A.inAppBrowser,handoffObserved:q!=null&&be.current===q.generation});if(ge&&M.markBlocked(),Ft(dt),_e){L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:dt}),de(Z,q),Nt(()=>qt.current?.(un("paypal",S))),q&&Qt.current.delete(q.surfaceKey),jt.current=null,on(q?.generation);return}L.error({errorCode:Ke,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:dt}),q&&Qt.current.delete(q.surfaceKey),jt.current=null,En({generation:q?.generation,remount:!0,showRetry:!0,focus:!0}),ln(Z,{code:"paypal_runtime_failed",popupBlocked:ge,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:J,terminalReason:dt});return}b(an(S)?"teardown":"pre_ready_callback",S)}}),te=Ht.isEligible();if(oe(`isEligible=${te}`),L.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!te){U(!1),b("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}gr=!0,$t=Ht,Un=()=>{if(!rr||Mt||nt()||Tn)return;Mt=!0,oe(`container:dims ${wn(Wn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(hr=new MutationObserver(S=>{if(!nt()){for(let q of S)if(q.type==="childList")q.addedNodes.forEach(Ke=>{if(!(Ke instanceof Element))return;let ge=Ke.tagName.toLowerCase(),_e=(Ke.getAttribute("title")??"").slice(0,40),dt=ge==="iframe"?` ${ar(Ke)}`:"";oe(`child+ ${ge}${_e?` title="${_e}"`:""}${dt} dims=${wn(Ke)}`)});else if(q.type==="attributes"&&q.target instanceof Element){let Ke=q.target;if(Ke.tagName.toLowerCase()!=="iframe")continue;let ge=q.attributeName;(ge==="src"||ge==="srcdoc")&&oe(`attr~ iframe ${ge}=${ge==="srcdoc"?`[${(Ke.getAttribute("srcdoc")??"").length}ch]`:or(Ke.getAttribute("src"))} dims=${wn(Ke)}`)}}}),hr.observe(Wn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Z=S=>{if(nt()||Tn)return;let q=Wn.querySelectorAll("iframe"),Ke=typeof document<"u"&&"hasStorageAccess"in document;oe(`watchdog:${S} container=${wn(Wn)} children=${Wn.childElementCount} iframes=${q.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Ke} paypalNetRequests=${Or.value}`),q.forEach((ge,_e)=>{let dt=(ge.getAttribute("title")??"").slice(0,40);oe(` iframe[${_e}] ${wn(ge)}${dt?` title="${dt}"`:""} ${ar(ge)}`);let Ze=tt(ge);Ze&&oe(` ${Ze}`)}),nn.length===0&&oe(" (no PayPal/zoid window errors captured)")};zn.push(setTimeout(()=>Z("3s"),3e3)),zn.push(setTimeout(()=>Z("8s"),8e3)),zn.push(setTimeout(()=>Z("15s"),15e3))},Un(),oe("render:start");let Be=L.startTiming();nr=setTimeout(()=>{nt()||Tn||(oe("watchdog:11s retryable render timeout"),b("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},eu);let rt=Ht.render(Wn);(async()=>{try{if(await rt,oe(`render:resolved inactive=${nt()}`),rn(),nt()){fr();return}Tn=!0,U(!0),qe(!1),Tt.current?.("ready"),L.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"checkout_render",durationMs:L.elapsed(Be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Z){let S=Z instanceof Error?Z.message:"PayPal failed to render.";oe(`render:rejected msg=${S.slice(0,120)}`),rn(),b(an(S)?"teardown":"render_rejected",S)}})()}).catch($=>{let le=$ instanceof Error?$.message:"PayPal operation failed.";oe(`provider:failed msg=${le.slice(0,120)}`);let Pe="script_rejected";h&&an(le)?Pe="teardown":h&&gr&&(Pe="render_rejected"),b(Pe,le)})},0);return()=>{Jt=!0,clearTimeout(R),er&&clearTimeout(er),rn(),Ct.current===Nr&&(Ct.current=null),fr(),$e.current=null,pt.current=null}},[N,wt,s,f,c,m,J,ft,e,lt,Ee,ke,F,Ne,oe,Ft]);let et=pe?ji("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:yt?"#fef2f2":"#f3f4f6",border:`1px solid ${yt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Me} failed=${yt})`,_t.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return ft&&!X?ye?ao("div",{children:et}):null:Yi("div",{children:[et,Oe&&ao(_o,{identity:Oe.identity,methodLabel:Oe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:we,onCancel:()=>we(null)}),Yi("div",{"aria-hidden":vt||Oe?!0:void 0,style:vt||Oe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Va},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:Va,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:Wd,children:"Try PayPal again"})]})}function Ga(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 Xi=":idempotency-key";function Zi(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 Qi(e,t){if(!To())return null;try{let n=window.sessionStorage.getItem(e+Xi);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 Ya(e,t){if(To())try{Zi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Ja(e,t){if(Ya(e,t),!!To())try{Qi(e,t)&&window.sessionStorage.removeItem(e+Xi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Xa(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 Za(e,t,n){if(To())try{window.sessionStorage.setItem(e+Xi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Ji(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=>Ji(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Ji(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Ji(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 Vr,useMemo as tu,useRef as tc,useState as nc}from"react";import{jsx as nu}from"react/jsx-runtime";function Qa({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=Ro(r);Vr(()=>{v({class:"lifecycle",name:"checkout.mount"})},[v]),Vr(()=>{i&&v({class:"lifecycle",name:"sdk.initialize.ready"})},[v,i]),Vr(()=>{if(i)return un(i)?.subscribe?.(v)},[v,i]),Vr(()=>{if(!(!l||l===i))return un(l)?.subscribe?.(v)},[v,i,l]),Vr(()=>{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]),Vr(()=>{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]),Vr(()=>{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]),Vr(()=>{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 W=eu(n?.billingApiUrl),$=tu(()=>({flopay:i,paypalFlopay:l,billingApiUrl:W,emitInstrument:v}),[i,l,W,v]);return nu(Xn.Provider,{value:$,children:o})}var ei="flopay_recent_completion_";function Mo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ei+e,JSON.stringify(t))}catch{}}function es(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ei+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ei+e),!1):!0}catch{return!1}}async function ti(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 ri}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 Gr(e){return new wt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function ts(){return new wt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function rs(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 ya(e,t){try{return await e()}catch(n){throw Dr(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 os(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,W=()=>v.abort();e.signal?.aborted?v.abort():e.signal?.addEventListener("abort",W);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",W)}},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((W,$)=>{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 je=await s();if(k||!cu(je))return;k=!0,se(),W(je)}finally{C=!1}}},Ce=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(h),h=window.setTimeout(()=>{z()},250))},J=()=>{k||(k=!0,se(),$(Gr()))},ke=je=>{if(je.source!==u.contentWindow||S&&je.origin!==S)return;let _e=je.data;!_e||typeof _e!="object"||_e.source!=="flopay-vault-3ds-return"||k||(k=!0,se(),W(null))};q=window.setTimeout(()=>{k||(k=!0,se(),$(ts()))},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 ri(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=os({billingApiUrl:n,sessionId:r,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:f.signal,pollCompletionEndpoint:!1}),W=s.waitForCheckoutSessionCompletion(r,{initialDelayMs:iu,nonce:i,statusUrl:l,continueAfterActionRequired:!0,timeoutMs:ic+15e3,signal:u.signal}),$;try{let q=await Promise.race([v,W]);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 ts();$=await W}}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 ri(n);try{h.reportThreeDsAbandoned(r)}finally{h.destroy()}}throw ts()}}finally{o.removeEventListener("abort",S),f.abort(),u.abort()}let k=$&&$r($,t.session);if(!Fr(k))throw Io(k);return{...Br(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=jr(o)??o,s=rs(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 ns(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ni(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||ni(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||ni(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||ni(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 ri(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ni(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??"",W=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 ri(l,s===!1?{telemetry:!1}:void 0).processPayment(S,{sessionId:f,nonce:u,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:S,email:v,firstName:W,lastName:$,country:k,zip:q},returnUrl:i??ns(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 rs(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 oi(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 rs(new wt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let v=au(e.threeDSecureToken),W=null,$=e.paymentMethodId,k=await ya(()=>su(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 ya(()=>lu(S,e.threeDSecureToken,{payment_method:$,return_url:l??ns(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");W=q.intent}else{let K=await ya(()=>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");W=(v?K.setupIntent:K.paymentIntent)??null}if(W&&(W.status==="requires_capture"||W.status==="succeeded"||W.status==="processing")){let K=await Bo({billingApiUrl:o,sessionId:i,session:s,telemetry:f,tokenizedData:{id:W.id,type:"card",threeDSecureActionResultTokenId:W.id},returnUrl:l});return K.type==="success"?{...K.result,paymentIntentId:K.result.paymentIntentId??W.id,paymentMethodId:K.result.paymentMethodId??$}:K.type==="next_action_required"?xo(K,{billingApiUrl:o,sessionId:i??s.id,session:s,signal:u}):oi(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 ya(()=>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:W}=await ya(()=>v.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??ns(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(W)throw Dr(new wt(W.message??"PayPal authorization failed.","api_error",{code:W.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=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 as(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 ac(e,t){return e?e.isPaypal?"paypal":"card":t&&zr(t)?"card":void 0}async function is({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 ss,getStateOptions as Pu,getStripeMethodDisplayName as Ca,isAuthorizationOnlySession as ls,isAVSFieldVisible as ot,isPostalCodeSupported as vu,isSetupIntentClientSecret as cs,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 _u,stripeExpressMethodToOptionKey as Ru}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 ai(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",_c=300*1e3,Mu=900,xu=25e3,Bu=25e3,Fu=1e4,Rc=["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 ii={},Pa=class{constructor(t){this.reason=t}};function Lu(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function Wt(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function vs(e){return`${Au}:${e}`}function si(e){return Wt(vs(e))}function li(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>_c||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(si(e),null):o}catch{return si(e),null}}function Uu(e){return Wt(vs(e.sessionId),e)}function pc(e,t,n){let r=li(e,t);return!r||r.clientSecret!==n?!1:si(e)}function ds(e,t,n){if(typeof window>"u")return;li(e,t)?.clientSecret===n&&si(e)}function zu(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=zu(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 qu(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 ci(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 va="flopay_paypal_resume",ha=new Map;function Tc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(va);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function ju(){if(typeof window>"u")return!1;let[e,t]=Cs();return e?Tc(t)!==null:!1}function Cs(){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 $u(){Wt(va),window.history.replaceState({},"",bs())}var Ku=250,yc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Wu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function 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 di({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 Vu({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 ba=180,fc=`flopay-card-enter ${ba}ms cubic-bezier(0, 0, 0.2, 1) both`,gc=`flopay-card-exit ${ba}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Gu=`flopay-buttons-enter ${ba}ms cubic-bezier(0, 0, 0.2, 1) both`,Yu=`flopay-buttons-exit ${ba}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Ju(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 Xu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Zu(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 Qu(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":Ca(e)}function ep(e){let t=hu(e);return`Enter a valid ${ms(e)}${t?` (e.g. ${t})`:""}`}function tp(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 np(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:`${Qu(e)} before-click hook failed.`,"validation_error")}function rp(e){return typeof e=="number"?`${e}px`:e}function Is(e){return y(op,{...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:W,onLoadStateChange:$,placeholderBorderRadius:k,popupCapabilityOwner:q,externalTelemetryContext:K,presentationMode:h}){let C=Kr(),{emitInstrument:se}=Oo(Xn),z=Ps(),Ce=hs(),J=ht(()=>ai(un(C),K),[K,C]),[ke,je]=ue("loading");St(()=>{$?.(ke)},[ke,$]);let[_e,it]=ue(!1),zt=oe(!1),ye=!yn(n?.trim())||!v?.trim(),{request:Me,collect:Pt,finish:Te}=ko(),Ve=oe(!1),Re=oe(null),ne=oe(null),[$e,Ke]=ue(0),[yt,be]=ue(!1),fe=oe(!1),le=oe(new Map),{startAttempt:F,finishAttempt:Se,invalidateAttempt:ze,isAttemptInvalidated:xe,isAttemptCurrent:V,generationRef:vt}=ua((T,re,Oe)=>{u?.(T,re,{...Oe,popupBlocked:Oe?.popupBlocked??Ur(re),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h,terminalReason:"overlay_timeout"}),be(!0),Ke(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,$e]);let qe=Je(()=>{Ke(T=>T+1)},[]),Ae=Je((T,re,Oe)=>{ze(Oe),u?.("paypal",T,{code:re,popupBlocked:Ur(T),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h}),be(!0),qe()},[ze,u,h,qe]),Xe=Je(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);St(()=>{fe.current&&(fe.current=!1,Xe())},[Xe,$e]);let Be=Je(()=>{be(!1),i?.(null),Xe()},[Xe,i]);St(()=>{if(!z||Ve.current)return;let[T,re,Oe]=Cs();if(!T||!re)return;let L=Tc(re);if(!L)return;Ve.current=!0;let we=!0,gt=ha.get(re);gt||(gt=Oe==="failed"?Promise.resolve(null):Promise.resolve().then(()=>z.retrievePaymentIntent(re)),ha.set(re,gt));let Le={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($u(),ha.delete(re),Oe==="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},{...Le,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,Ve.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($e),!1;let Oe=F("paypal");return le.current.set($e,{generation:Oe,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:Oe}),l?.("paypal"),!0},[l,J,S,F,$e]),Ne=Je(async T=>{if(s||_e||!await Qe()){T.reject();return}T.resolve()},[s,Qe,_e]),Ct=Je(async T=>{if(!z||!Ce)return;let re=le.current.get($e);if(re&&!V(re.generation)){le.current.delete($e);return}if(!re&&xe()||re&&!Se(re.generation))return;re||Se();let Oe=re??null;if(le.current.delete($e),!Oe&&S){let M=await S("paypal");if(!M.proceed){T.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Oe={accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}}let L=Oe?.sessionId??e,we=Oe?.nonce??t,gt=await Vu({event:T,prepared:Oe,email:n,billingName:v,methodLabel:"PayPal",collect:Pt});if(!gt){T.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Le=gt.email,It={...Oe?.accountPatch,...Dn(gt,!0)};try{if(it(!0),i?.(null),!L||!yn(Le))throw new Error("Missing sessionId or email for PayPal payment");await W?.(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 ci(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),!Wt(va,{clientSecret:x,sessionId:L,nonce:we,accountPatch:It})&&h==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:ge,paymentIntent:We}=await z.confirmPayment({clientSecret:x,confirmParams:ee,redirect:"if_required"});if(ge){if(Wt(va),La(ge)){let qt=ge.message??"Your payment was declined.";J?.terminal({outcome:"payment_declined",...dr,terminalReason:"provider_declined"}),i?.(qt),f?.(dn("paypal",qt,{code:Lr(ge),declineCode:ra(ge)})),await di({billingApiUrl:r,sessionId:L,nonce:we,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Lr(ge)??"provider_declined"}})}else Ae(ge,"stripe_paypal_confirm_failed",re?.generation);return}Wt(va);let X=typeof We?.payment_method=="string"?We.payment_method:We?.payment_method?.id;o({id:X??We?.id,type:"card",threeDSecureActionResultTokenId:We?.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,W,r,se,o,i,f,S,Ae,Se,V,xe,J,h,$e]),Vt=Je(async()=>{if(!(zt.current||s||_e||!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,_e]),ft=h==="redirect"?y("button",{type:"button",disabled:s||_e,onClick:()=>{Vt()},style:{width:"100%",minHeight:aa,border:"1px solid #d1d5db",borderRadius:k??8,background:"#ffc439",color:"#111827",cursor:s||_e?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):y(Ic,{onReady:T=>je(Ni(T,["paypal"])),onLoadError:()=>{je("load_error"),Ss(J,"paypal","paypal","provider_error")},onClick:Ne,onConfirm:Ct,onCancel:()=>{let T=le.current.get($e);le.current.delete($e),J?.terminal({outcome:"payment_cancelled",...dr,terminalReason:"cancelled",...T?{attempt:T.generation}:{}}),ze(T?.generation),be(!1),fe.current=!0,qe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ye,emailRequired:ye,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},$e),Tt=Ze(No,{children:[Ze("div",{ref:Re,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(_o,{identity:Me.identity,methodLabel:Me.methodLabel,onComplete:Te,onCancel:()=>Te(null)},Me.id),y("div",{style:{display:Me?"none":void 0},children:ft})]}),_e&&!Me&&y(br,{status:"processing"})]});return h==="redirect"?Tt:y(Oi,{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:W,onBuyerIdentityReady:$,onLoadStateChange:k,placeholderBorderRadius:q,popupCapabilityOwner:K,externalTelemetryContext:h}){let C=Kr(),{emitInstrument:se}=Oo(Xn),z=Ps(),Ce=hs(),J=ht(()=>ai(un(C),h),[h,C]),[ke,je]=ue("loading");St(()=>{k?.(ke)},[ke,k]);let[_e,it]=ue(!1),zt=oe(!yn(n?.trim())||!W?.trim()).current,{request:ye,collect:Me,finish:Pt}=ko(),Te=oe(null),Ve=oe(null),[Re,ne]=ue(0),[$e,Ke]=ue(!1),[yt,be]=ue(()=>li(e,t)?"blocked":"idle"),[fe,le]=ue("google_pay"),F=oe(null),Se=oe(!0),ze=oe(!1),xe=oe("google_pay"),V=oe("google_pay"),vt=oe(null),qe=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:Ne,invalidateAttempt:Ct,isAttemptInvalidated:Vt,isAttemptCurrent:ft,generationRef:Tt}=ua((M,p,g)=>{S?.(M,p,{...g,popupBlocked:g?.popupBlocked??Ur(p),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),le(M),Ke(!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(()=>{$e&&Ve.current?.focus()},[$e,Re]);let T=Je(()=>{ne(M=>M+1)},[]),re=Je((M,p,g,D,x=!1)=>{Ct(D),S?.(M,p,{code:g,popupBlocked:Ur(p),telemetryReported:x,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),le(M),Ke(!0),T()},[Ct,S,T]),Oe=Je(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);St(()=>{ze.current&&(ze.current=!1,Oe())},[Oe,Re]);let L=Je(()=>{Ke(!1),l?.(null),Oe()},[Oe,l]),we=Je(()=>{F.current?.()},[]);St(()=>{let M=li(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,cs(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),Ke(!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=Ge=>{p||(p=!0,M.paymentFailed({reason:"fail",...Ge?{message:Ge}:{}}))};if(!z||!Ce){g();return}let D=Be.current.get(Re);if(D&&!ft(D.generation)){Be.current.delete(Re),g();return}if(!D&&Vt()){g();return}if(D&&!Ne(D.generation)){g();return}D||Ne();let x=M.expressPaymentType??D?.method??xe.current,ee=D??null,ut=hc(x),ge;x==="apple_pay"?ge="apple_pay":x==="google_pay"&&(ge="google_pay");let We=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((Ge,Ue)=>{On=Ue}),fn=window.setTimeout(()=>{At=!0,bt.abort(),On(ii)},xu),Mt=async(Ge,Ue,_n)=>{Nn=Ge,pn=Ue,jt=Ue==="intent_create"||Ue==="session_claim"?"transport_error":"provider_runtime";let kt=X?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([_n,Ln])}finally{let Un=X?.now()??globalThis.performance?.now()??Date.now();X?.performance({stage:Ge,durationMs:Math.max(0,Un-kt),durationMode:"machine",requestCategory:Ue,paymentMethodCategory:"wallet",provider:"stripe",...At?{statusClass:"timeout"}:{}})}};try{if(it(!0),l?.(null),!ee&&v){let pe=await Mt("processing","other",v(ut));if(!pe.proceed){g();return}ee={accountPatch:pe.accountPatch,sessionId:pe.sessionId,nonce:pe.nonce}}let Ge=ee?.sessionId??e;kn=Ge;let Ue=ee?.nonce??t,_n=vt.current??ee?.accountPatch,kt=Ac({event:M,fallbackEmail:_n?.email??n,fallbackName:[_n?.firstName,_n?.lastName].join(" ").trim()||W});if(!yn(kt.email)){g("Buyer details are required."),Me(fs(x),kt).then(pe=>{pe&&(vt.current=pe)});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(!Ge)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:Ge,nonce:Ue??"",request:$t}),Qn=qe.current,Wn=Qn?.retryIdentity===Zt?Qn.authorizationAttemptId:wu();qe.current={authorizationAttemptId:Wn,retryIdentity:Zt};let Qt=await Mt("processing","intent_create",ci(r,se,Ge,Ue??"",{...$t,authorizationAttemptId:Wn},{signal:bt.signal}));if(Qt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let _t=Qt.clientSecret,en=Uu({createdAt:Date.now(),sessionId:Ge,...Ue?{nonce:Ue}:{},clientSecret:_t,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",...ge?{walletType:ge}:{},attempt:We},an=!1,Ot=null;X?.log({name:"payment.provider_confirmation.started",...Dt}),ce=window.setTimeout(()=>{ce!==null&&Ae.current.delete(ce),an=!0;let pe=X?.now()??globalThis.performance?.now()??Date.now();X?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Dt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,pe-nn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),X?.flush?.().catch(()=>{}),Ot?.()},Bu),Ae.current.add(ce);let rn=(pe,et)=>{ce!==null&&(window.clearTimeout(ce),Ae.current.delete(ce),ce=null);let m=X?.now()??globalThis.performance?.now()??Date.now(),Fe=Math.max(0,m-nn),H=pe;an&&(pe==="resolved"?H="resolved_late":pe==="returned_error"?H="returned_error_late":H="rejected_late");let gn=et??(pe==="resolved"?"approved":"provider_error");return X?.log({name:"payment.provider_confirmation.returned",...Dt,operationOutcome:H,terminalReason:gn}),X?.performance({...Dt,durationMs:Fe,durationMode:"buyer",operationOutcome:H,terminalReason:gn}),{durationMs:Fe,operationOutcome:H,terminalReason:gn}},Nt=!1,G=!1,er=pe=>{if(!pe||typeof pe!="object")return null;let et=pe;if(et.error)return null;let m=et.setupIntent??et.paymentIntent,Fe=us(m??null,void 0,!!et.setupIntent);return Fe.kind==="confirmed"?Fe:null},tr=pe=>{if(Nt||D&&Tt.current!==D.generation)return;let et=er(pe);if(!et)return;if(en&&!pc(Ge,Ue,_t)){Nt=!0;return}let{intentId:m,paymentMethodId:Fe}=et;Nt=!0,G=!0,qe.current=null,F.current=null,Se.current&&(be("idle"),it(!1));let H=`${kc}:${Ge}`;Wt(H,{createdAt:Date.now(),sessionId:Ge,nonce:Ue,accountPatch:Un,paymentMethodId:Fe,providerIntentId:m,paymentMethodType:x});try{s({id:Fe,type:"card",threeDSecureActionResultTokenId:m},{accountPatch:Un,paymentMethodCategory:"wallet",sessionId:Ge,nonce:Ue})}finally{Wt(H)}},nr=!1;Ot=async()=>{if(!(nr||Nt||G)){nr=!0,Se.current&&be("checking");try{let pe=await mc(z,_t,Ae.current);if(Nt||G)return;let et=cs(_t),m=us(pe,Qt.providerObjectId,et);if(m.kind==="confirmed"){tr(et?{setupIntent:pe}:{paymentIntent:pe});return}if(m.kind==="terminal"){if(G=!0,ds(Ge,Ue,_t),qe.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,Rn;try{let pe=await(cs(_t)?z.confirmSetup({elements:Ce,clientSecret:_t,redirect:"if_required"}):z.confirmPayment({elements:Ce,clientSecret:_t,redirect:"if_required"}));if(!pe||typeof pe!="object")throw new Pa(Lu(pe));if(tn=pe,!tn.error&&!er(tn))throw new Pa("confirmation_result_unconfirmed");Rn=rn(tn.error?"returned_error":"resolved",tn.error&&La(tn.error)?"provider_declined":void 0)}catch(pe){let et=pe instanceof Pa?pe.reason:void 0,m=et!==void 0,Fe=rn(m?"returned_error":"rejected");if(X?.error({...m?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:et}:$i(pe),...Dt,operationOutcome:Fe.operationOutcome,durationMs:Fe.durationMs,statusClass:"unknown",terminalReason:Fe.terminalReason}),!Se.current||Nt)return;await Ot?.();return}let vn=tn.error;if(vn){if(!Se.current||Nt)return;if(La(vn)){G=!0,ds(Ge,Ue,_t),qe.current=null,F.current=null,be("idle");let pe=vn.message??"Your payment was declined.";g(pe),l?.(pe),u?.(dn(ut,pe,{code:Lr(vn),declineCode:ra(vn)})),di({billingApiUrl:r,sessionId:Ge,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:x,providerDeclineReason:Lr(vn)??"provider_declined",...Qt.intentKind==="payment"&&Qt.providerObjectId.startsWith("pi_")?{providerIntentId:Qt.providerObjectId}:{}}})}else X?.error({...$i(vn),...Dt,operationOutcome:Rn.operationOutcome,durationMs:Rn.durationMs,statusClass:"unknown",terminalReason:Rn.terminalReason}),await Ot?.();return}if(tr(tn),!Nt)throw new Error("Invalid provider returned for APM intent")}catch(Ge){if(Ge===ii){let Ue=X?.now()??globalThis.performance?.now()??Date.now();X?.error({errorCode:qu(pn),stage:Nn,requestCategory:pn,paymentMethodCategory:"wallet",provider:"stripe",...ge?{walletType:ge}:{},operationOutcome:"watchdog_expired",checkoutSessionId:kn,durationMs:Math.max(0,Ue-qt),statusClass:"timeout",failureCategory:jt,attempt:We,terminalReason:"provider_error"}),X?.flush?.().catch(()=>{})}g(),re(x,Ge,Ge===ii?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",D?.generation,Ge===ii)}finally{if(window.clearTimeout(fn),ce!==null&&(window.clearTimeout(ce),Ae.current.delete(ce)),!st){let Ge=X?.now()??globalThis.performance?.now()??Date.now();X?.performance({stage:"callback",durationMs:Math.max(0,Ge-qt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...At?{statusClass:"timeout"}:{}})}Se.current&&it(!1)}},[z,Ce,e,t,n,W,Me,$,r,se,o,s,l,u,v,re,Ne,ft,Vt,Tt,J,Re]),Le=ht(()=>Il(i),[i]),It=ht(()=>i.map(Ru),[i]);return Ze(No,{children:[y(Oi,{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:[$e&&Ze("button",{ref:Ve,type:"button","data-testid":"flopay-wallet-retry-button",onClick:L,style:ys,children:["Try ",fs(fe)," 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"})]}),ye&&y(_o,{identity:ye.identity,methodLabel:ye.methodLabel,onComplete:Pt,onCancel:()=>Pt(null)},ye.id),yt==="idle"&&y("div",{style:{display:ye?"none":void 0},children:y(Ic,{onReady:M=>{je(Ni(M,It))},onLoadError:M=>{je("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(Re),M.reject();return}let ee=Qe(M.expressPaymentType);Xe.current={generation:ee,startedAt:p},Be.current.set(Re,{generation:ee,method:M.expressPaymentType,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),Ke(!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(Re);Be.current.delete(Re),J?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...M?{attempt:M.generation}:{}}),Ct(M?.generation),qe.current=null,Ke(!1),ze.current=!0,T()},options:{...kl,paymentMethods:Le,emailRequired:zt,billingAddressRequired:zt}},Re)})]})}),_e&&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:W,isProcessing:$,submitButtonColor:k,submitButtonBorderRadius:q,submitButtonStyle:K,errorText:h}){let C=Kr(),{emitInstrument:se}=Oo(Xn),z=Ps(),Ce=hs(),[J,ke]=ue(!1),je=oe(!1),[_e,it]=ue(!1),[zt,ye]=ue("loading"),[Me,Pt]=ue(""),Te=!yn(r?.trim()),Ve=!Te||yn(Me.trim()),Re=Je(async()=>{if(!z||!Ce||$||je.current||!_e)return;je.current=!0,ke(!0);let ne=v?await v("card"):{proceed:!0};if(!ne.proceed){je.current=!1,ke(!1);return}W?.("card");let $e=ne.sessionId??t,Ke=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}),fe=be.email,le=Dn({...ne.accountPatch,...be});try{if(f?.(null),!yn(fe))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(" "),ze=await z.createPaymentMethod({elements:Ce,params:{billing_details:{email:fe,...Se?{name:Se}:{}}}});if(ze.error||!ze.paymentMethod){f?.(ze.error?.message??"Failed to create payment method.");return}let xe=ze.paymentMethod;if(!$e||!fe)throw new Error("Missing sessionId or email for payment.");let V=xe.type||e,vt=await ci(s,se,$e,Ke??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:V,paymentMethodId:null,intentKind:"payment"});if(vt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let qe=vt.clientSecret;Wt(Ir,{clientSecret:qe,sessionId:$e,nonce:Ke,accountPatch:le,paymentMethodId:xe.id,paymentMethodType:xe.type??e,gateway:"stripe"});let{error:Ae,paymentIntent:Xe}=await z.confirmPayment({clientSecret:qe,confirmParams:{return_url:window.location.href,payment_method:xe.id},redirect:"if_required"});if(Ae){Wt(Ir);let Ne=Ae.message??"Payment failed.";f?.(Ne),u?.(dn("card",Ne,{code:Ae.code})),await di({billingApiUrl:s,sessionId:$e,nonce:Ke,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ae.code??"provider_declined"}});return}let Be=Xe?.status;if(!sa(Be)){Wt(Ir);let Ne=Be==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(Ne),u?.(dn("card",Ne,{code:Be??"missing_payment_intent"}));return}Wt(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:$e,nonce:Ke})}catch(F){f?.(F instanceof Error?F.message:"Payment failed. Please try again.")}finally{je.current=!1,ke(!1)}},[z,Ce,$,_e,v,W,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:()=>ye("ready"),onLoadError:()=>{ye("load_error"),Ss(un(C),"stripe","apm")},onChange:ne=>{it(!!ne.complete)},options:{layout:_l,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...yn(r?.trim())?{email:r?.trim()}:{}}}}}),y(Rl,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Re()},disabled:!_e||!Ve||J||$||zt!=="ready",color:k,borderRadius:q,style:K,children:J?"Processing\u2026":`Pay with ${Ca(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:W,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:je}=Oo(Xn),[_e,it]=ue(null),[zt,ye]=ue(null),Me=oe(!1),{request:Pt,collect:Te,finish:Ve}=ko();St(()=>{s.length>0&&l?q?.("ready"):l||q?.("loading")},[s.length,l,q]);let Re=Je(async fe=>{if(!l||Me.current||K)return;Me.current=!0,ye(fe);let le=k?await k("card"):{proceed:!0};if(!le.proceed){Me.current=!1,ye(null);return}W?.("card");let F=le.sessionId??e,Se=le.nonce??t,ze=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()||ze.firstName,lastName:le.accountPatch?.lastName?.trim()||ze.lastName});if(!yn(xe.email)){ye(null);let qe=await Te(Ca(fe),xe);if(!qe){Me.current=!1;return}xe=qe,ye(fe)}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 qe=await ci(i,je,F,Se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:fe,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ae=qe.clientSecret;Wt(Ir,{clientSecret:Ae,sessionId:F,nonce:Se,accountPatch:vt,paymentMethodType:fe,gateway:"stripe"});let{error:Xe,paymentIntent:Be}=await l.confirmPayment({clientSecret:Ae,confirmParams:{return_url:window.location.href,payment_method_data:{type:fe,billing_details:{name:[xe.firstName,xe.lastName].filter(Boolean).join(" "),...V?{email:V}:{}}}},redirect:"if_required"});if(Xe){Wt(Ir);let Ct=Xe.message??"Payment failed.";v?.(Ct),$?.(dn("card",Ct,{code:Xe.code})),await di({billingApiUrl:i,sessionId:F,nonce:Se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:fe,providerDeclineReason:Xe.code??"provider_declined"}});return}let Qe=Be?.status;if(!sa(Qe)){Wt(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}Wt(Ir);let Ne=typeof Be?.payment_method=="string"?Be.payment_method:Be?.payment_method?.id;S({id:Ne??Be?.id,type:"card",threeDSecureActionResultTokenId:Be?.id,gateway:"stripe",paymentMethodType:fe},{accountPatch:vt,paymentMethodCategory:"apm",sessionId:F,nonce:Se})}catch(qe){v?.(qe instanceof Error?qe.message:"Payment failed. Please try again.")}finally{Me.current=!1,ye(null)}},[l,K,k,W,e,t,n,Te,i,je,r,o,S,v,$]),[ne,$e]=ue(null),Ke=J?ke??null:ne,yt=Je(fe=>{Me.current||K||Ke&&Ke!==fe||(dc(fe)?J?J(fe):$e(fe):Re(fe))},[Ke,K,Re,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(_o,{identity:Pt.identity,methodLabel:Pt.methodLabel,onComplete:Ve,onCancel:()=>Ve(null)},Pt.id):s.map(fe=>{let le=ke===fe,F=zt===fe,Se=zt!==null&&zt!==fe||ke!=null&&ke!==fe;return Ze(Tu.Fragment,{children:[y(wl,{method:fe,themeId:Ce,submitting:F,disabled:Se,highlighted:le,hasNextStep:dc(fe),onClick:()=>yt(fe),backgroundColor:z?.backgroundColor,borderColor:z?.borderColor,textColor:z?.textColor,borderRadius:z?.borderRadius,fontFamily:z?.fontFamily}),!J&&ne===fe&&be&&l&&y(io,{stripe:l,options:be,children:y(gs,{method:fe,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:S,onErrorChange:v,onDecline:$,onCancel:()=>$e(null),runBeforeButtonClick:k,onButtonClick:W,isProcessing:K,submitButtonColor:h,submitButtonBorderRadius:C,submitButtonStyle:se})},fe)]},fe)})})}function op({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:W,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:je=!0,layout:_e="default",theme:it,buttonsTheme:zt,buttonsStyles:ye,appearance:Me,cardButtonContent:Pt,cardBackButtonContent:Te,cardTitleContent:Ve,showSecurityFooter:Re,onButtonClick:ne,onBeforeButtonClick:$e,onBuyerIdentityReady:Ke,enableAVS:yt,cardFieldOrder:be,cardPreFormSlot:fe,avsLayout:le="row",country:F,zip:Se,addressLine1:ze,addressLine2:xe,city:V,state:vt,onCountryChange:qe,onZipChange:Ae,avsCheck:Xe,checkoutType:Be,checkoutLayout:Qe,totalAmount:Ne=0,currency:Ct="usd",initialCardOpen:Vt=!1,directPaypal:ft,isSubscription:Tt=!1,session:T,dataAttachmentPending:re=!1,dataAttachmentRequiresIdentity:Oe=!1,debug:L=!1}){let we=Kr(),gt=Ki(),Le=Oo(cr),{emitInstrument:It}=Oo(Xn),M=oe(null);M.current||(M.current=Wa());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??Le.session,ge=ht(()=>({futureUse:ut?.futureUse,futureUseUnsupported:ut?.futureUseUnsupported}),[ut?.futureUse,ut?.futureUseUnsupported]),We=ut?.gateways?.paypal?.providerObjectType??ft?.providerObjectType,X=re||Le.claimPending===!0,qt=Oe||Le.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,Ge]=ue(ze??""),[Ue,_n]=ue(xe??""),[kt,Un]=ue(V??""),[mn,$t]=ue(vt??""),[Zt,Qn]=ue(""),[Wn,Qt]=ue({}),_t=oe(Se??""),en=oe(F??""),nn=oe(ze??""),Dt=oe(xe??""),an=oe(V??""),Ot=oe(vt??""),rn=oe(""),Nt=oe({});St(()=>{let a=(P,U,ve,Z,he)=>{if(Nt.current[P])return;let Xt=U?.trim();!Xt||Xt===ve.current||(ve.current=Xt,Z(Xt),he?.(Xt))};a("country",F,en,On,qe),a("zip",Se,_t,fn,Ae),a("addressLine1",ze,nn,Ge),a("addressLine2",xe,Dt,_n),a("city",V,an,Un),a("state",vt,Ot,$t)},[F,Se,ze,xe,V,vt,qe,Ae]);let G=ht(()=>Iu(yt),[yt]),er=G!==null,tr=ht(()=>ls(T),[T]),nr=!!T?.vault?.html,tn=!!T?.gateways?.pcivault,Rn=zi(T),pe=!!(T?.gateways?.stripe?.enabledPaymentMethods??Ce)?.includes("card")||zr(T),et=nr||pe||tn,m=!!(se&&et&&e),[Fe,H]=ue(()=>_e!=="buttons"||Vt?e??null:null),[gn,zn]=ue(0),Gt=_e!=="buttons"||Vt||!!e&&Fe===e,En=T?.captureMethod,tt=oe(we);St(()=>{tt.current=we},[we]);let[rr,Xr]=ue(null);St(()=>{if(!m||!e||!Gt){Xr(null);return}let a=tt.current?tt.current.cardCapture({sessionId:e,captureMethod:En}):new pu({sessionId:e,captureMethod:En,billingApiUrl:st,telemetry:r});return Xr({sessionId:e,captureMethod:En,billingApiUrl:st,telemetry:r,capture:a}),()=>{a.unmount()}},[m,e,Gt,En,st,r]);let Rt=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 tp(a,Ln,P)},[G,jt,Ln]),{avsInvalid:mr,invalidAvsFields:Hn}=ht(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!m||!G)return{avsInvalid:!1,invalidAvsFields:a};let P=jt,U=(he,Xt)=>ot(he,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,_r]=ue(!1),[Mn,yr]=ue(!1),[fr,Rr]=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)&&Rr(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),Zr=He==="expanding"||He==="card",gr=T?.gateways?.stripe&&!Rn?"stripe":void 0,Or=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()},ba)},[]);St(()=>()=>{Sn.current&&clearTimeout(Sn.current)},[]);let Mr=Je(()=>{Or(),H(e??null),zn(a=>a+1),sn("expanding"),cn(()=>sn("card"))},[cn,Or,e]),xn=Je(()=>{sn("collapsing"),cn(()=>sn("buttons"))},[cn]),w=Je(a=>{bn(a),sn("apm-expanding"),cn(()=>sn("apm-form"))},[cn]),_=Je(()=>{sn("apm-collapsing"),cn(()=>{sn("buttons"),bn(null)})},[cn]);St(()=>{_e==="buttons"&&Vt&&et&&(H(e??null),sn("card"))},[_e,Vt,et,e]);let[O,R]=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(Ke||Le.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)}},[Ke,Le.claimBuyerIdentity,T?.buyerIdentified,e,t,st,i,S,v]),De=Ke??Le.claimBuyerIdentity??ae,at=K??Nn,me=ht(()=>_u(it),[it]),b=ht(()=>{let a=me?.buttonsLayout??ku(zt);return ye?{...a,...ye,cardButton:{...a.cardButton,...ye.cardButton},cardFormContainer:{...a.cardFormContainer,...ye.cardFormContainer},backButton:{...a.backButton,...ye.backButton},backButtonIcon:{...a.backButtonIcon,...ye.backButtonIcon},submitButton:{...a.submitButton,...ye.submitButton},title:{...a.title,...ye.title}}:a},[me,zt,ye]),lt=Me??me?.appearance,ie=ht(()=>vl({appearance:lt,buttonsStyles:b,layout:_e}),[lt,b,_e]),te=Le.inlineSessionPatchProcessing??!1,A=(q??ce)||te,Y=st.replace(/\/+$/,""),N=ht(()=>ji({userId:i,email:o,firstName:S,lastName:v,country:F,zip:Se},Wn),[i,o,S,v,F,Se,Wn]),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),fi=ht(()=>np(Zt,wn),[Zt,wn]),lo=fi.empty||fi.malformed,jn=ht(()=>we?we.getRawProvider():null,[we]),Ds=ht(()=>gt?gt.getRawProvider():null,[gt]),jo=Ne||100,co=Ct.toLowerCase(),gi=ht(()=>lt?mu(lt):null,[lt]),uo=gi,Ns=ht(()=>{let a=gi??{},P=a.rules??{};return{...a,rules:{...P,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...P[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...P[".AccordionItemContents"]??{}}}}},[gi]),Os=ht(()=>({...ql(Ne,ut?.captureMethod,ge),currency:co,...uo?{appearance:uo}:null}),[Ne,co,ut?.captureMethod,ge,uo]),hi=wc(ge,"paypal","paypal"),Ls=ht(()=>({mode:"payment",amount:jo,currency:co,captureMethod:"manual",...hi?{setupFutureUsage:hi}:null,...uo?{appearance:uo}:null}),[jo,co,hi,uo]),Pe=Je(a=>{pn(a),h?.(a)},[h]),Pi=oe(""),[Us,Kc]=ue(!1),vi=Je(()=>{Kc(!0)},[]);St(()=>{if(!m||!wn||!De||!Us||lo||Pi.current)return;let a=Dn({email:yn(N.email?.trim())?N.email?.trim():rn.current.trim(),firstName:N.firstName?.trim(),lastName:N.lastName?.trim()});Pi.current=JSON.stringify(a),Qt(P=>({...P,...a})),Promise.resolve(De(a)).catch(P=>{Pi.current="",Pe(P instanceof Error?P.message:"Failed to attach buyer details.")})},[m,wn,De,Us,lo,N.email,N.firstName,N.lastName,Pe]),St(()=>{!m||!Rt||Rt.setCardFieldOrder?.(be??null,G==null&&!wn)},[m,Rt,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??Ur(P);ve&&p.markBlocked()&&g(Ye=>Ye+1);let Z=Oa(fs(a),ve,x.inAppBrowser),he=Lr(P),Xt=(he?.toLowerCase()==="error"?void 0:he)??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")})),R(null),_e==="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,_e,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:Rn});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:Rn};let Ci=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(),he=en.current.trim()||a.resolvedAccount.country?.trim()||"",Xt=a.avsConfig?ot(a.avsConfig.state,he):!1,lr=a.avsConfig?ot(a.avsConfig.address_line_1,he):!1,Ye=a.avsConfig?ot(a.avsConfig.postal_code,he):!1,dt=a.avsConfig?ot(a.avsConfig.city,he):!1,mt=a.avsConfig?ot(a.avsConfig.address_line_2,he):!1,Lt=lr&&!Xt&&Ye?cc(he,(_t.current??"").trim()):null,to=Xt?Ot.current:Lt;return{accountData:{userId:a.resolvedAccount.userId??"",email:U,...ve?{firstName:ve}:{},...Z?{lastName:Z}:{},...Ye&&_t.current?{zip:_t.current}:{},...dt&&an.current?{city:an.current}:{},...to?{state:to}:{},...lr&&nn.current?{addressLine1:nn.current}:{},...mt&&Dt.current?{addressLine2:Dt.current}:{},...he?{country:he}:{}},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:ot(a.avsConfig.country,he),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||!Rt||Rt.setSubmitGate?.(mr||X||lo||Ee)},[m,Rt,mr,X,lo,Ee]),St(()=>{if(!m||!Rt)return;Ci.current=!1;let a=null,P=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,j.current="idle",R(null)},400)},U=Rt.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")},Ku),R("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",R(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",R(null),Ye.onError?.(mt instanceof ur?mt:new ur(Lt,"api_error"))})}),ve=Rt.on("complete",Ye=>{Mo(Ye.sessionId??ir.current.sessionId),j.current="terminal",B(!1),R("success"),setTimeout(()=>{if(Ci.current)return;Ci.current=!0;let dt=ir.current,mt=ls(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"})},600)}),Z=Rt.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),R("error");let Lt=Ye.failureOutcome??bu(Ye.declineReason)??"authorization_declined";dt.emitDecline("card",mt,{code:Lt,declineCode:Lt}),P()}),he=Rt.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),R("error"),dt.onError?.(new ur(mt,"api_error",{code:Ye.failureOutcome??"capture_failed"})),P()}),Xt=Rt.on("challenge_dismissed",()=>{pt.current&&(clearTimeout(pt.current),pt.current=null),j.current="processing",B(!0),R(null)}),lr=Rt.on("blocked",()=>{if(d.current){ir.current.updateError(Wu);return}if(!qs.current){or(!0);return}vi(),ir.current.updateError(yc)});return()=>{a&&(clearTimeout(a),a=null),pt.current&&(clearTimeout(pt.current),pt.current=null),j.current="idle",B(!1),R(null),U(),ve(),Z(),he(),Xt(),lr()}},[m,Rt,vi,zs]);let Pr=!!ft?.clientId,$o=Array.isArray(Ce),_a=$o&&Ce.length>0,js=$o&&Ce.includes("paypal"),Ra=oe(null);Ra.current===null&&(Ra.current=ju());let mo=Ra.current?"redirect":Sl(x,z,p.current()),{expressMethods:Ea,paymentElementMethods:Ko}=ht(()=>Su(Ce,{excludePaypal:Pr}),[Ce,Pr]),$s=Pr||!!gt||js&&mo==="redirect",Wc=ht(()=>$s?Ea.filter(a=>a!=="paypal"):Ea,[Ea,$s]),Hc=ht(()=>{let a=[];return ke&&a.push("apple_pay"),je&&a.push("google_pay"),a},[ke,je]),yo=$o?Wc:Hc,Vc=se&&yo.length>0,bi=er?jt:F,Ta=ht(()=>{let a=bi?.trim().toUpperCase();return a?J?Ko.filter(P=>{let U=J[P];return!U||U.length===0||U.includes(a)}):gu(Ko,bi):Ko},[Ko,bi,J]),Si=ht(()=>({mode:"payment",amount:jo,currency:co,paymentMethodCreation:"manual",appearance:Ns}),[jo,co,Ns]),[Ks,Ws]=ue("loading"),[Hs,Vs]=ue("loading"),[Gs,Ys]=ue("loading"),[Gc,wi]=ue(!1),[Js,Ii]=ue("loading"),[ki,Yc]=ue();St(()=>{Yc(oa())},[]);let Aa=ki?.inAppBrowser,Ma=ki?Ua(ki,ft?.approvalPresentation,We??(Tt?"subscription":"order")):"popup",Xs=C&&(Pr||($o?js:Aa===!1)),Zs=se&&Vc,Wo=(!bt||!!Le.waitForDataAttachment)&&Xs&&Pr,Qs=Js==="retrying"||Js==="exhausted",Ho=null;se&&(gt?Ho=Ds:mo==="redirect"&&(Ho=jn));let el=ht(()=>({...ee,presentationMode:mo}),[ee,mo]),Vo=!bt&&Xs&&!!Ho&&(!Pr||Qs),fo=!bt&&Zs&&!!jn,Go=!bt&&se&&_a&&Ta.length>0&&!!jn,Jc=Wo&&!Qs?Gc:Vo&&Li(Ks),Xc=fo&&Li(Hs),Zc=Go&&Gs!=="load_error",tl=a=>a==="loading"||a==="ready",nl=Wo||Vo&&tl(Ks)||fo&&tl(Hs)||Go&&Gs!=="load_error",xa=oe(!1);St(()=>{if(!xa.current){if(!se&&!C){xa.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){xa.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(Aa!==void 0&&!bt&&!et&&!nl){xa.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,Aa,bt,et,nl,l,Pe]);let rl=oe(!1);St(()=>{if(rl.current||!_a)return;let a=[];ke!==!0&&a.push("showApplePay"),je!==!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.`))},[_a,ke,je]);let ol=Je((a,P)=>Le.applyInlineSessionPatch?Le.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}),[Le.applyInlineSessionPatch,t,l,e,Pe]),sr=Je(async a=>{if(a!=="card"&&bt&&await Le.waitForDataAttachment?.(),!$e)return{proceed:!0};try{let P=await $e({method:a,sessionId:e||void 0,createSession:Le.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,Le.inlineSessionDraft,Le.waitForDataAttachment,bt,$e,l,e,Pe]),al=Je(async(a,P)=>{if(nt.current)return;nt.current=!0,kn(!0),R("processing"),Pe(null);let U=P?.sessionId??e,ve=P?.nonce??t,Z=ji(N,P?.accountPatch),he=P?.completionPaymentMethodId??la(a),Xt=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,lr=Ju(a),Ye=P?.presentationMode?ai(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??Zu(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,(_t.current??"").trim()):null,ea=vr?Ot.current:no;return{country:Et,...Cr&&_t.current?{zip:_t.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:W,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}),to=async Et=>{let vr=ls(T)||Et?.status==="authorized";Mo(U),Ye?.terminal({outcome:"payment_succeeded",...dr}),R("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:he,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:he,checkoutMethod:a.isPaypal?"paypal":"card"})};if(Lt.ok){await to(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){R("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){R("error");let ea=no.message??"PayPal payment failed.";Pe(ea),hr("paypal",ea,{code:no.code})}}catch(Kn){R("error"),Pe(Kn instanceof Error?Kn.message:"PayPal authorization failed.")}return}if($n?.type==="paypal_direct_required"){let Et=$n.orderId;if(!Et){R("error"),Pe("PayPal retry required but no order id provided.");return}let vr=E.current?.attempts??0;if(vr>=2){R("error"),Pe("PayPal payment could not be completed after multiple attempts."),hr("paypal","paypal_direct_required retry limit exceeded");return}wi(!1),Ii("loading"),I({orderId:Et,attempts:vr+1}),R(null);return}if(Lt.headers.get(Du)===Nu){let Et=await Ou(mt,U,ve);if(Et!==void 0){await to(Et);return}}fu(Lt.status,$n)?Ye?.terminal({outcome:"payment_declined",...dr,terminalReason:"provider_declined"}):dt(),R("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(),R("error"),Pe(mt instanceof Error?mt.message:"An unexpected error occurred"),await new Promise(Lt=>setTimeout(Lt,400))}finally{kn(!1),R(null),nt.current=!1}},[Y,e,t,N,G,Xe,Be,Qe,W,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{Wt(Yo);return}if(!P||typeof P.createdAt!="number"||Date.now()-P.createdAt<0||Date.now()-P.createdAt>_c||typeof P.paymentMethodId!="string"||typeof P.providerIntentId!="string"||typeof P.paymentMethodType!="string"||P.sessionId!==e||!t||P.nonce!==t||!yo.includes(P.paymentMethodType)){Wt(Yo);return}Wt(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 Wt(dt),null}},he=Z(Ir)??Z(uc),Xt;if(he?.clientSecret){if(he.clientSecret!==P)return;Xt={...he.accountPatch?{accountPatch:he.accountPatch}:{},...he.sessionId?{sessionId:he.sessionId}:{},...he.nonce?{nonce:he.nonce}:{}}}else if(he?.sessionId&&he.sessionId!==e)return;il.current=!0,Wt(Ir),Wt(uc),window.history.replaceState({},"",bs());let lr=he?.paymentMethodType??he?.tokenType??"card",Ye="card";(async()=>{if(U==="failed"){let xr="Payment was declined. Please try again.";Pe(xr),hr(Ye,xr);return}let{paymentIntent:dt,error:mt}=await ve.retrievePaymentIntent(P);if(mt){let xr=mt.message??"Failed to retrieve payment status.";Pe(xr),hr(Ye,xr,{code:mt.code});return}let Lt=dt?.status,to=sa(Lt);if(!dt||!to){let xr=Lt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Pe(xr),hr(Ye,xr,{code:Lt??"missing_payment_intent"});return}let $n=typeof dt.payment_method=="string"?dt.payment_method:dt.payment_method?.id;Bn({id:$n??he?.paymentMethodId??he?.tokenId??dt.id,type:"card",threeDSecureActionResultTokenId:dt.id,gateway:he?.gateway??"stripe",paymentMethodType:lr},Xt)})()},[e,Bn,we,Pe,hr]);let _i=Je(a=>{a.preventDefault()},[]);if(!(m||we!==null))return y("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Jo=_e==="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=>Hn[a]&&(fr[a]||Yt),Ba=lo&&(Mn||Yt),Yn=a=>a?sl:Xo,Fa=(Tn.malformed||Tn.empty)&&(An||Yt),td=Yn(Fa),Ei=b.cardFormContainer?.backgroundColor??ed??(Jo?"white":"#EDEDFF"),go=b.cardInputBackground??Fn?.colorBackground??"white",Ti=vo(Te),ll=vo(Ve),ho=b.nameInput,cl=b.cardInputFontSize??rp(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",Qr=Fn?.borderRadius??b.cardButton?.borderRadius??Jt,eo=Fn?.colorPrimary??"#4A49FF",od=Fn?.colorPrimaryHover??na(eo,.12),Ai=Fn?.colorText??"#262833",Mi={fontSize:cl,fontFamily:dl,fontWeight:ul,color:nd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Zo={marginTop:"0.375rem",...Mi,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??{},xi=Qo.padding??(Jo?"0":"1rem"),Bi=Qo.borderRadius??Jt,id=Rt&&Tr?y(Fi,{capture:Rt,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",R(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)&&Or()},style:{backgroundColor:Ei,borderRadius:Bi,...Qo,padding:xi,...ad,display:"flex",flexDirection:"column"},children:[y("style",{children:`
|
|
3
|
+
${_t.join(`
|
|
4
|
+
`)}`]}):null;return yt&&!H?pe?to("div",{children:et}):null:ji("div",{children:[et,Oe&&to(Io,{identity:Oe.identity,methodLabel:Oe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Se,onCancel:()=>Se(null)}),ji("div",{"aria-hidden":vt||Oe?!0:void 0,style:vt||Oe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:$a},children:[!Me&&!vt&&to("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),to("div",{ref:Q,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:$a,display:"flex",opacity:Me?1:0},"aria-busy":I||v},Ee)]},Ee),Qe&&to("button",{ref:Ce,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Cn,style:tu,children:"Try PayPal again"})]})}function Wa(e){return to(Hl,{...e})}function Vl(e){return to(Hl,{...e})}import{jsx as Kl,jsxs as au}from"react/jsx-runtime";function Eo({children:e,margin:t,icon:n=!0,styleOverride:o}){return au("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...o??{}},children:[n&&Kl("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Kl("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{clearCachedInlineCheckout as Ha,clearCachedInlineSession as $i,hashCreateParams as Gl,legacyCachedSessionMatchesDraft as Yl,persistCachedInlineIdempotencyKey as Va,persistCachedInlineSession as Ka,readCachedInlineIdempotencyKey as Jl,readCachedInlineSession as Zl,serializeCreateParams as da}from"@flopay/shared";import{resolveBillingApiUrl as iu}from"@flopay/shared";import{useEffect as Hr,useMemo as su,useRef as Xl,useState as Ql}from"react";import{jsx as lu}from"react/jsx-runtime";function Ga({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=Ql(e instanceof Promise?null:e),[c,f]=Ql(t instanceof Promise||!t?null:t),C=Xl(null),E=Xl(null),k=Ro(o);Hr(()=>{k({class:"lifecycle",name:"checkout.mount"})},[k]),Hr(()=>{i&&k({class:"lifecycle",name:"sdk.initialize.ready"})},[k,i]),Hr(()=>{if(i)return pn(i)?.subscribe?.(k)},[k,i]),Hr(()=>{if(!(!c||c===i))return pn(c)?.subscribe?.(k)},[k,i,c]),Hr(()=>{if(!i)return;let O=pn(i);return C.current=O?.beginCheckout()??O?.now()??0,O?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{O?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Hr(()=>{let O=!1;return e instanceof Promise?e.then(ve=>{O||s(ve)},()=>{O||k({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{O=!0}},[k,e]),Hr(()=>{let O=!1;if(!t){f(null);return}return t instanceof Promise?t.then(ve=>{O||f(ve)},()=>{O||k({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):f(t),()=>{O=!0}},[k,t]),Hr(()=>{if(!i||E.current===i)return;E.current=i;let O=pn(i);O?.log({name:"checkout.rendered",stage:"checkout_render"}),k({class:"lifecycle",name:"checkout.rendered"}),O?.performance({stage:"checkout_render",durationMs:O.elapsed(C.current??0),durationMode:"machine"})},[k,i]);let z=iu(n?.billingApiUrl),ne=su(()=>({flopay:i,paypalFlopay:c,billingApiUrl:z,emitInstrument:k}),[i,c,z,k]);return lu(Gn.Provider,{value:ne,children:a})}import{markSessionRecentlyCompleted as _o,wasSessionRecentlyCompleted as Wi}from"@flopay/shared";async function Ya(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{completeSavedCardNextAction as cu,loadFloPay as ec,PaymentAPI as Za,runSavedCardChallenge as du}from"@flopay/js";import{classifyPaymentRejection as uu,FloPayError as St,isAuthorizationOnlySession as pu,isMountableVaultBlock as yu,isSetupIntentClientSecret as mu,normalizeCheckoutFailureOutcome as tc}from"@flopay/shared";var pa="card";async function fu(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:o,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:o??null}}async function gu(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:s??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function To(e){return new St("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function hu(){return new St("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Vi(e,t){return Object.assign(e,{checkoutMethod:t})}function xr(e,t){let n=e instanceof St?e:new St(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function ua(e,t){try{return await e()}catch(n){throw xr(n,t)}}function rc(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function oc(e){return du(e)}async function Mo(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,s=new Za(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,f;try{f=await cu({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:E=>kr({type:E.declineReason??"authorization_declined",gatewayErrorCode:E.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},s)}catch(E){if(a.aborted||E instanceof Error&&E.name==="AbortError")throw E instanceof St&&E.code==="three_ds_aborted"?E:To(E);if(!(E instanceof St)||E.code!=="three_ds_timeout"&&E.code!=="checkout_processing_timeout")throw E;try{f=await s.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:c,timeoutMs:5e3,signal:a})}catch(z){if(a.aborted)throw To(z);if(!(z instanceof St)||z.code!=="checkout_processing_timeout")throw z}let k=f&&qr(f,t.session);if(!Ar(k)&&k?.status!=="expired"){if(t.telemetry){let z=new Za(n);try{z.reportThreeDsAbandoned(o)}finally{z.destroy()}}throw hu()}}let C=f&&qr(f,t.session);if(!Ar(C))throw So(C);return{...Mr(C,o),checkoutMethod:"card"}}function kr(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=wo(a)??a,s=Vi(new St(i,"api_error",{code:e?.code??tc(e?.outcome)??tc(e?.type)??e?.gatewayErrorCode}),o);return e?.orderId&&(s.orderId=e.orderId),s}function Hi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ja(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ac(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ja(a)))return a;let o=e?.data;if(o&&typeof o=="object"){let a=o,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let c of i)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||Ja(c)))return c;let s=a.gateways;if(s&&typeof s=="object"){let c=s.stripe;if(c&&typeof c=="object"){let f=c,C=[f.stripeClientSecret,f.clientSecret];for(let E of C)if(typeof E=="string"&&E.length>0&&(!t?.requirePaymentIntentClientSecret||Ja(E)))return E}}}}async function Pu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=ac(o,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let c=(await new Za(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ja(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Ao({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:s}){let c=e.replace(/\/+$/,""),f=t??n.id,C=o??n.clientSecret,E=n.customer?.id??n.accountData?.userId??"",k=n.customer?.email??n.accountData?.email??"",z=n.customer?.firstName??n.accountData?.firstName??"",ne=n.customer?.lastName??n.accountData?.lastName??"",O=n.customer?.country??n.accountData?.country??void 0,ve=n.customer?.zip??n.accountData?.zip??void 0,v=await new Za(c,s===!1?{telemetry:!1}:void 0).processPayment(E,{sessionId:f,nonce:C,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:E,email:k,firstName:z,lastName:ne,country:O,zip:ve},returnUrl:i??Hi(n)});if(v.ok){let N=typeof v.json=="function"?await v.json().catch(()=>null):null;if(pu(n)||N?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof N?.paymentId=="string"?N.paymentId:n.paymentId,sessionId:typeof N?.sessionId=="string"?N.sessionId:f,authorizationExpiresAt:typeof N?.authorizationExpiresAt=="string"?N.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:oa(a),checkoutMethod:nc(a,n)}};let Ie=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Ie?{paymentIntentId:Ie}:{},paymentMethodId:oa(a),checkoutMethod:nc(a,n)}}}let P;try{P=await v.json()}catch(N){throw new St("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:v.status,cause:N})}if(P?.type==="3ds_required"&&typeof P.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:P.nextActionRedirectUrl};if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let N=ac(P);if(!N)throw new St("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:v.status});return{type:P.type,threeDSecureToken:N,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let N=await Pu({billingApiUrl:c,sessionId:f,nonce:C,responseJson:P});if(N)return N;throw Vi(new St("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let he=new St(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:v.status});throw Object.assign(he,{telemetryOutcome:uu(v.status,P)})}async function Xa(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:c,telemetry:f,signal:C}){let E=t?.getRawProvider();if(!E)throw xr(new St("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw Vi(new St("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let k=mu(e.threeDSecureToken),z=null,ne=e.paymentMethodId,O=await ua(()=>fu(E,e.threeDSecureToken,k),"card");if(O){if(O.error)throw xr(new St(O.error.message??`Failed to retrieve 3DS ${k?"setup":"payment"} status.`,"api_error",{code:O.error.code}),"card");let V=O.intent;!ne&&V?.payment_method&&(typeof V.payment_method=="string"?ne=V.payment_method:"id"in V.payment_method&&(ne=V.payment_method.id??void 0))}let ve=ne?await ua(()=>gu(E,e.threeDSecureToken,{payment_method:ne,return_url:c??Hi(s)??window.location.href},k),"card"):null;if(ve){if(ve.error)throw xr(new St(ve.error.message??"3DS authentication failed.","api_error",{code:ve.error.code}),"card");z=ve.intent}else{let V=await ua(()=>E.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(V.error)throw xr(new St(V.error.message??"3DS authentication failed.","api_error",{code:V.error.code}),"card");z=(k?V.setupIntent:V.paymentIntent)??null}if(z&&(z.status==="requires_capture"||z.status==="succeeded"||z.status==="processing")){let V=await Ao({billingApiUrl:a,sessionId:i,session:s,telemetry:f,tokenizedData:{id:z.id,type:"card",threeDSecureActionResultTokenId:z.id},returnUrl:c});return V.type==="success"?{...V.result,paymentIntentId:V.result.paymentIntentId??z.id,paymentMethodId:V.result.paymentMethodId??ne}:V.type==="next_action_required"?Mo(V,{billingApiUrl:a,sessionId:i??s.id,session:s,signal:C}):Xa(V,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:c,telemetry:f,signal:C})}throw xr(new St("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let k=(n??t)?.getRawProvider();if(!k)throw xr(new St("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:ne}=await ua(()=>k.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(ne)throw xr(new St(ne.message??"PayPal authorization failed.","api_error",{code:ne.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:z}=await ua(()=>k.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Hi(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(z)throw xr(new St(z.message??"PayPal authorization failed.","api_error",{code:z.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new St("Unsupported payment redirect state.","api_error")}function ya(e){if(e instanceof St){let o=wo(e.message);return o&&o!==e.message?Object.assign(new St(o,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=wo(t)??t;return new St(n,"api_error")}function Ki(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=yu(e.data.session?.vault)||Qr(e.data.session);if(!t&&!n&&!o)throw new St("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function nc(e,t){return e?e.isPaypal?"paypal":"card":t&&Qr(t)?"card":void 0}async function Gi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:o,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[s,c]=await Promise.all([ec(e,{billingApiUrl:n,locale:o,telemetry:a}),i?ec(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(C=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",C),null)):Promise.resolve(null)]);if(!s)throw new St("The payment provider did not initialize.","authentication_error");let f=null;return i?f=c:t&&(f=s),{flopay:s,paypalFlopay:f}}import{PaymentAPI as Bo,PciVaultCardCapture as vu,toStripeAppearance as bu}from"@flopay/js";import{buildCheckoutProcessMetadata as Cu,buildProcessPaymentAvsAccount as Su,COUNTRY_OPTIONS as wu,classifyPaymentRejection as ku,clearStripePayPalReturn as Iu,FloPayError as Br,filterStripeMethodsByCountryGate as Ru,getPostalCodeExample as Eu,getPostalCodeLabel as ns,getStateFromPostalCode as _u,getStateLabel as Yi,getStateOptions as Tu,getStripeMethodDisplayName as ga,hasMatchingStripePayPalReturn as Mu,isAuthorizationOnlySession as Ji,isAVSFieldVisible as Kt,isMountableVaultBlock as Au,isPostalCodeSupported as xu,isSetupIntentClientSecret as Zi,isValidEmail as gn,isValidPostalCode as Bu,needsStripeMethodExplicitConfirm as ic,normalizeBeforeButtonClickError as sc,normalizeCheckoutFailureOutcome as Fu,partitionStripeMethods as Du,randomUuidV4 as Ou,readMatchingStripePayPalContinuation as Nu,readStripeRedirectParams as vc,resolveAVSConfig as Lu,resolveButtonsLayoutTheme as zu,resolveSetupFutureUsage as bc,resolveTheme as Uu,resolveVaultMountOptions as Xi,STRIPE_PAYPAL_RESUME_KEY as qu,derivePrimaryTileStyle as ju,stripeExpressMethodToOptionKey as $u,stripeRedirectReturnUrl as Cc}from"@flopay/shared";import{ExpressCheckoutElement as Sc,PaymentElement as Wu,Elements as no,useElements as is,useStripe as ss}from"@stripe/react-stripe-js";import Hu,{useCallback as Ye,useContext as Do,useEffect as ht,useMemo as gt,useRef as G,useState as ie}from"react";function xo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Qa(e,t){if(e)return{error:n=>e.error(xo(t,n)),log:n=>e.log(xo(t,n)),performance:n=>e.performance(xo(t,n)),terminal:n=>e.terminal(xo(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}import{Fragment as Fo,jsx as p,jsxs as Xe}from"react/jsx-runtime";var Ir="flopay_stripe_resume",lc="flopay_wallet_resume",wc="fw1",Vu="fw2",kc=300*1e3,Ku=900,Gu=25e3,Yu=25e3,Ju=1e4,ur={provider:"paypal",paymentMethodCategory:"paypal"},Zu="x-flopay-process-result-source",Xu="status";async function Qu(e,t,n){try{let o=(await e.getUnifiedCheckoutSession(t,n)).data.session;if(o?.status==="complete")return null;if(o?.status==="authorized")return{status:"authorized",paymentId:o.paymentId,sessionId:o.id||t,authorizationExpiresAt:o.authorizationExpiresAt}}catch{}}var ei={},fa=class{constructor(t){this.reason=t}};function ep(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function Xt(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function ls(e){return`${Vu}:${e}`}function ti(e){return Xt(ls(e))}function ni(e,t){if(typeof window>"u")return null;let n=ls(e);try{let o=localStorage.getItem(n);if(!o)return null;let a=JSON.parse(o);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>kc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(ti(e),null):a}catch{return ti(e),null}}function tp(e){return Xt(ls(e.sessionId),e)}function cc(e,t,n){let o=ni(e,t);return!o||o.clientSecret!==n?!1:ti(e)}function Qi(e,t,n){if(typeof window>"u")return;ni(e,t)?.clientSecret===n&&ti(e)}function np(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function es(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let o=n?e.status==="succeeded":ra(e.status),a=np(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function dc(e,t,n){let o=null;try{return await Promise.race([Al(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},Ju),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function rp(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Ic(e){return e instanceof Br&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ri(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new Bo(e,{telemetry:!1}).createSessionIntent(...n)}catch(a){throw Ic(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var ts=qu,ma=new Map,op=250,uc="Just a moment \u2014 we are finalizing your order. Please press pay again.",ap="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function cs(e,t,n,o){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...o?{terminalReason:o}:{}})}async function oi({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new Bo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function ip(e){return e instanceof Br&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Rc({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=aa(n),s=i.firstName?i:aa(o?.name);return dr({email:gn(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function sp({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=Rc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return gn(s.email)?s:i(a,s)}var ha=180,pc=`flopay-card-enter ${ha}ms cubic-bezier(0, 0, 0.2, 1) both`,yc=`flopay-card-exit ${ha}ms cubic-bezier(0.4, 0, 0.2, 1) both`,lp=`flopay-buttons-enter ${ha}ms cubic-bezier(0, 0, 0.2, 1) both`,cp=`flopay-buttons-exit ${ha}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function dp(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ds(e){return ju(e)}var up={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function pp(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var rs={width:"100%",minHeight:ta,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function mc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function os(e){return e==="paypal"?"PayPal":ga(e)}function yp(e){let t=Eu(e);return`Enter a valid ${ns(e)}${t?` (e.g. ${t})`:""}`}function mp(e,t,n){let o=xu(e),a=t.trim(),i=n&&o,s=i&&!a,c=i&&!!a&&!Bu(e,a);return{visible:n,supported:o,required:i,empty:s,malformed:c}}function fp(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!gn(n);return{required:t,empty:o,malformed:a,value:n}}function gp(e){return typeof e=="number"?`${e}px`:e}function us(e){return p(hp,{...e})}function fc({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:s=!1,onButtonClick:c,onDecline:f,onTechnicalFailure:C,runBeforeButtonClick:E,billingName:k,onBuyerIdentityReady:z,onLoadStateChange:ne,placeholderBorderRadius:O,popupCapabilityOwner:ve,externalTelemetryContext:V,presentationMode:v}){let P=jr(),{emitInstrument:he}=Do(Gn),N=ss(),Ie=is(),Y=gt(()=>Qa(pn(P),V),[V,P]),[Fe,lt]=ie("loading");ht(()=>{ne?.(Fe)},[Fe,ne]);let[ze,ct]=ie(!1),zt=G(!1),pe=!gn(n?.trim())||!k?.trim(),{request:Te,collect:Pt,finish:Re}=ko(),He=G(!1),ke=G(null),Q=G(null),[je,$e]=ie(0),[pt,be]=ie(!1),ye=G(!1),re=G(new Map),{startAttempt:M,finishAttempt:Ce,invalidateAttempt:Ue,isAttemptInvalidated:Me,isAttemptCurrent:U,generationRef:vt}=la((I,ee,Oe)=>{C?.(I,ee,{...Oe,popupBlocked:Oe?.popupBlocked??zr(ee),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:v,terminalReason:"overlay_timeout"}),be(!0),$e(F=>F+1)},{onHandoffObserved:()=>{ve.markAvailable(),Y?.log({name:"provider.popup.opened",stage:"overlay_open",...ur,attempt:vt.current})}});ht(()=>{pt&&Q.current?.focus()},[pt,je]);let qe=Ye(()=>{$e(I=>I+1)},[]),Ee=Ye((I,ee,Oe)=>{Ue(Oe),C?.("paypal",I,{code:ee,popupBlocked:zr(I),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:v}),be(!0),qe()},[Ue,C,v,qe]),Je=Ye(()=>{window.setTimeout(()=>{(ke.current?.querySelector("iframe")??ke.current)?.focus()},0)},[]);ht(()=>{ye.current&&(ye.current=!1,Je())},[Je,je]);let Ae=Ye(()=>{be(!1),i?.(null),Je()},[Je,i]);ht(()=>{if(!N||He.current)return;let[I,ee,Oe]=vc();if(!I||!ee)return;let F=Nu(ee);if(!F)return;He.current=!0;let Se=!0,mt=ma.get(ee);mt||(mt=Oe==="failed"?Promise.resolve(null):Promise.resolve().then(()=>N.retrievePaymentIntent(ee)),ma.set(ee,mt));let Ne={accountPatch:F.accountPatch,sessionId:F.sessionId,nonce:F.nonce},wt=()=>{Y?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...ur,requestCategory:"provider_sdk"})};return Y?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...ur}),(async()=>{try{ct(!0);let d=await mt;if(!Se)return;if(d?.error){ma.delete(ee),wt(),i?.(d.error.message??"Failed to retrieve PayPal payment status.");return}if(Iu(),ma.delete(ee),Oe==="failed"){let A="PayPal payment was declined. Please try again.";Y?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}),i?.(A),f?.(un("paypal",A));return}let m=d?.paymentIntent;if(m&&m.id!==I){wt(),i?.("Failed to match the returned PayPal payment.");return}if(m&&(m.status==="requires_capture"||m.status==="succeeded")){let A=typeof m.payment_method=="string"?m.payment_method:m.payment_method?.id;a({id:A??m.id,type:"card",threeDSecureActionResultTokenId:m.id,isPaypal:!0},{...Ne,presentationMode:"redirect"})}else{let A="PayPal payment was not completed. Please try again.";Y?.terminal({outcome:m?.status==="canceled"?"payment_cancelled":"payment_declined",...ur,terminalReason:m?.status==="canceled"?"cancelled":"provider_declined"}),i?.(A),f?.(un("paypal",A))}}catch(d){if(!Se)return;ma.delete(ee),wt(),i?.(d instanceof Error?d.message:"Failed to complete PayPal payment.")}finally{Se&&ct(!1)}})(),()=>{Se=!1,He.current=!1}},[N,a,i,f,Y]);let Qe=Ye(async(I=!1)=>{let ee=E?await E("paypal"):{proceed:!0};if(!ee.proceed)return re.current.delete(je),!1;let Oe=M("paypal");return re.current.set(je,{generation:Oe,accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce}),be(!1),Y?.log({name:`provider.${I?"redirect.started":"handoff.requested"}`,stage:I?"redirect":"overlay_open",...ur,attempt:Oe}),c?.("paypal"),!0},[c,Y,E,M,je]),De=Ye(async I=>{if(s||ze||!await Qe()){I.reject();return}I.resolve()},[s,Qe,ze]),bt=Ye(async I=>{if(!N||!Ie)return;let ee=re.current.get(je);if(ee&&!U(ee.generation)){re.current.delete(je);return}if(!ee&&Me()||ee&&!Ce(ee.generation))return;ee||Ce();let Oe=ee??null;if(re.current.delete(je),!Oe&&E){let _=await E("paypal");if(!_.proceed){I.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Oe={accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}}let F=Oe?.sessionId??e,Se=Oe?.nonce??t,mt=await sp({event:I,prepared:Oe,email:n,billingName:k,methodLabel:"PayPal",collect:Pt});if(!mt){I.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ne=mt.email,wt={...Oe?.accountPatch,...dr(mt,!0)};try{if(ct(!0),i?.(null),!F||!gn(Ne))throw new Error("Missing sessionId or email for PayPal payment");await z?.(mt);let _=N.createPaymentMethod,{error:d,paymentMethod:m}=await _({type:"paypal"});if(d){Ee(d,"stripe_paypal_create_payment_method_failed",ee?.generation),I.paymentFailed({reason:"fail"});return}let A=await ri(o,he,F,Se??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:m?.id??null,intentKind:"payment"});if(A.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let T=A.clientSecret,J={return_url:Cc()};if(m?.id&&(J.payment_method=m.id),!Xt(ts,{clientSecret:T,sessionId:F,nonce:Se,accountPatch:wt})&&v==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:me,paymentIntent:We}=await N.confirmPayment({clientSecret:T,confirmParams:J,redirect:"if_required"});if(me){if(Xt(ts),Fa(me)){let Ut=me.message??"Your payment was declined.";Y?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}),i?.(Ut),f?.(un("paypal",Ut,{code:go(me),declineCode:Ai(me)})),await oi({billingApiUrl:o,sessionId:F,nonce:Se,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:go(me)??"provider_declined"}})}else Ee(me,"stripe_paypal_confirm_failed",ee?.generation);return}Xt(ts);let H=typeof We?.payment_method=="string"?We.payment_method:We?.payment_method?.id;a({id:H??We?.id,type:"card",threeDSecureActionResultTokenId:We?.id,isPaypal:!0},{accountPatch:wt,paymentMethodCategory:"paypal",presentationMode:v,sessionId:F,nonce:Se});return}catch(_){Ee(_,"stripe_paypal_failed",ee?.generation)}finally{ct(!1)}},[N,Ie,e,t,n,k,Pt,z,o,he,a,i,f,E,Ee,Ce,U,Me,Y,v,je]),Yt=Ye(async()=>{if(!(zt.current||s||ze||!N||!Ie)){zt.current=!0,ct(!0);try{if(!await Qe(!0))return;await bt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{zt.current=!1,ct(!1)}}},[Ie,bt,s,Qe,N,ze]),yt=v==="redirect"?p("button",{type:"button",disabled:s||ze,onClick:()=>{Yt()},style:{width:"100%",minHeight:ta,border:"1px solid #d1d5db",borderRadius:O??8,background:"#ffc439",color:"#111827",cursor:s||ze?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):p(Sc,{onReady:I=>lt(xi(I,["paypal"])),onLoadError:()=>{lt("load_error"),cs(Y,"paypal","paypal","provider_error")},onClick:De,onConfirm:bt,onCancel:()=>{let I=re.current.get(je);re.current.delete(je),Y?.terminal({outcome:"payment_cancelled",...ur,terminalReason:"cancelled",...I?{attempt:I.generation}:{}}),Ue(I?.generation),be(!1),ye.current=!0,qe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:pe,emailRequired:pe,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},je),Et=Xe(Fo,{children:[Xe("div",{ref:ke,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[pt&&p("button",{ref:Q,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ae,style:rs,children:"Try PayPal again"}),Te&&p(Io,{identity:Te.identity,methodLabel:Te.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Te.id),p("div",{style:{display:Te?"none":void 0},children:yt})]}),ze&&!Te&&p(Sr,{status:"processing"})]});return v==="redirect"?Et:p(Bi,{state:Fe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:O,children:Et})}function gc(e){return e==="apple_pay"||e==="google_pay"}function hc({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:s,onErrorChange:c,onButtonClick:f,onDecline:C,onTechnicalFailure:E,runBeforeButtonClick:k,billingName:z,onBuyerIdentityReady:ne,onLoadStateChange:O,placeholderBorderRadius:ve,popupCapabilityOwner:V,externalTelemetryContext:v}){let P=jr(),{emitInstrument:he}=Do(Gn),N=ss(),Ie=is(),Y=gt(()=>Qa(pn(P),v),[v,P]),[Fe,lt]=ie("loading");ht(()=>{O?.(Fe)},[Fe,O]);let[ze,ct]=ie(!1),zt=G(!gn(n?.trim())||!z?.trim()).current,{request:pe,collect:Te,finish:Pt}=ko(),Re=G(null),He=G(null),[ke,Q]=ie(0),[je,$e]=ie(!1),[pt,be]=ie(()=>ni(e,t)?"blocked":"idle"),[ye,re]=ie("google_pay"),M=G(null),Ce=G(!0),Ue=G(!1),Me=G("google_pay"),U=G("google_pay"),vt=G(null),qe=G(null),Ee=G(new Set),Je=G(null);ht(()=>(Ce.current=!0,()=>{Ce.current=!1;for(let _ of Ee.current)window.clearTimeout(_);Ee.current.clear()}),[]);let Ae=G(new Map),{startAttempt:Qe,finishAttempt:De,invalidateAttempt:bt,isAttemptInvalidated:Yt,isAttemptCurrent:yt,generationRef:Et}=la((_,d,m)=>{E?.(_,d,{...m,popupBlocked:m?.popupBlocked??zr(d),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),re(_),$e(!0),Q(A=>A+1)},{onHandoffObserved:_=>{V.markAvailable(),Y?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Et.current,..._==="apple_pay"||_==="google_pay"?{walletType:_}:{}})},defersMissingTerminal:gc,onMissingTerminalDeferred:(_,d)=>{let m=Y?.now()??globalThis.performance?.now()??Date.now(),A=Je.current,T=A?.generation===d?A.startedAt:m;Y?.performance({stage:"overlay_return",durationMs:Math.max(0,m-T),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:d,...gc(_)?{walletType:_}:{}}),Y?.flush?.().catch(()=>{})}});ht(()=>{je&&He.current?.focus()},[je,ke]);let I=Ye(()=>{Q(_=>_+1)},[]),ee=Ye((_,d,m,A,T=!1)=>{bt(A),E?.(_,d,{code:m,popupBlocked:zr(d),telemetryReported:T,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),re(_),$e(!0),I()},[bt,E,I]),Oe=Ye(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);ht(()=>{Ue.current&&(Ue.current=!1,Oe())},[Oe,ke]);let F=Ye(()=>{$e(!1),c?.(null),Oe()},[Oe,c]),Se=Ye(()=>{M.current?.()},[]);ht(()=>{let _=ni(e,t);if(!_)return;let d=!1,m=!1,A=async()=>{if(!m){m=!0,d||be("checking");try{let T=await dc(N,_.clientSecret,Ee.current);if(d)return;let J=es(T,_.providerObjectId,Zi(_.clientSecret));if(J.kind==="confirmed"){if(!cc(e,t,_.clientSecret))return;M.current=null,be("idle"),s({id:J.paymentMethodId,type:"card",threeDSecureActionResultTokenId:J.intentId},{..._.accountPatch?{accountPatch:_.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(J.kind==="terminal"){Qi(e,t,_.clientSecret),M.current=null,be("idle"),re(_.paymentMethodType),$e(!0),I();return}be("blocked")}catch{d||be("blocked")}finally{m=!1}}};return M.current=A,be("blocked"),()=>{d=!0,M.current===A&&(M.current=null)}},[t,s,I,e,N]);let mt=Ye(async _=>{let d=!1,m=Ve=>{d||(d=!0,_.paymentFailed({reason:"fail",...Ve?{message:Ve}:{}}))};if(!N||!Ie){m();return}let A=Ae.current.get(ke);if(A&&!yt(A.generation)){Ae.current.delete(ke),m();return}if(!A&&Yt()){m();return}if(A&&!De(A.generation)){m();return}A||De();let T=_.expressPaymentType??A?.method??Me.current,J=A??null,ft=mc(T),me;T==="apple_pay"?me="apple_pay":T==="google_pay"&&(me="google_pay");let We=A?.generation??Et.current,H=Y,Ut=H?.now()??globalThis.performance?.now()??Date.now(),Ct=new AbortController,_t=!1,at=!1,oe=null,In=e,Bn="processing",yn="other",qt="provider_runtime",Fn,Dn=new Promise((Ve,Le)=>{Fn=Le}),hn=window.setTimeout(()=>{_t=!0,Ct.abort(),Fn(ei)},Gu),Tt=async(Ve,Le,Rn)=>{Bn=Ve,yn=Le,qt=Le==="intent_create"||Le==="session_claim"?"transport_error":"provider_runtime";let kt=H?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Rn,Dn])}finally{let On=H?.now()??globalThis.performance?.now()??Date.now();H?.performance({stage:Ve,durationMs:Math.max(0,On-kt),durationMode:"machine",requestCategory:Le,paymentMethodCategory:"wallet",provider:"stripe",..._t?{statusClass:"timeout"}:{}})}};try{if(ct(!0),c?.(null),!J&&k){let ce=await Tt("processing","other",k(ft));if(!ce.proceed){m();return}J={accountPatch:ce.accountPatch,sessionId:ce.sessionId,nonce:ce.nonce}}let Ve=J?.sessionId??e;In=Ve;let Le=J?.nonce??t,Rn=vt.current??J?.accountPatch,kt=Rc({event:_,fallbackEmail:Rn?.email??n,fallbackName:[Rn?.firstName,Rn?.lastName].join(" ").trim()||z});if(!gn(kt.email)){m("Buyer details are required."),Te(os(T),kt).then(ce=>{ce&&(vt.current=ce)});return}vt.current=null;let On={...J?.accountPatch,...dr(kt,!0)};await Tt("processing","session_claim",Promise.resolve(ne?.(kt)));let{error:mn}=await Tt("tokenization","provider_sdk",Ie.submit());if(mn){m(),ee(T,mn,"stripe_wallet_submit_failed",A?.generation);return}if(!Ve)throw new Error("Missing sessionId or email for payment.");let jt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:T,paymentMethodId:null,intentKind:a},Qt=JSON.stringify({sessionId:Ve,nonce:Le??"",request:jt}),Jn=qe.current,$n=Jn?.retryIdentity===Qt?Jn.authorizationAttemptId:Ou();qe.current={authorizationAttemptId:$n,retryIdentity:Qt};let en=await Tt("processing","intent_create",ri(o,he,Ve,Le??"",{...jt,authorizationAttemptId:$n},{signal:Ct.signal}));if(en.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let xt=en.clientSecret,Cn=tp({createdAt:Date.now(),sessionId:Ve,...Le?{nonce:Le}:{},clientSecret:xt,providerObjectId:en.providerObjectId,paymentMethodType:T,accountPatch:On});window.clearTimeout(hn),at=!0,H?.performance({stage:"callback",durationMs:Math.max(0,(H?.now()??globalThis.performance?.now()??Date.now())-Ut),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let ln=H?.now()??globalThis.performance?.now()??Date.now(),Ft={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...me?{walletType:me}:{},attempt:We},fn=!1,Dt=null;H?.log({name:"payment.provider_confirmation.started",...Ft}),oe=window.setTimeout(()=>{oe!==null&&Ee.current.delete(oe),fn=!0;let ce=H?.now()??globalThis.performance?.now()??Date.now();H?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Ft,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ce-ln),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),H?.flush?.().catch(()=>{}),Dt?.()},Yu),Ee.current.add(oe);let on=(ce,et)=>{oe!==null&&(window.clearTimeout(oe),Ee.current.delete(oe),oe=null);let u=H?.now()??globalThis.performance?.now()??Date.now(),xe=Math.max(0,u-ln),L=ce;fn&&(ce==="resolved"?L="resolved_late":ce==="returned_error"?L="returned_error_late":L="rejected_late");let Pn=et??(ce==="resolved"?"approved":"provider_error");return H?.log({name:"payment.provider_confirmation.returned",...Ft,operationOutcome:L,terminalReason:Pn}),H?.performance({...Ft,durationMs:xe,durationMode:"buyer",operationOutcome:L,terminalReason:Pn}),{durationMs:xe,operationOutcome:L,terminalReason:Pn}},Bt=!1,ae=!1,Zn=ce=>{if(!ce||typeof ce!="object")return null;let et=ce;if(et.error)return null;let u=et.setupIntent??et.paymentIntent,xe=es(u??null,void 0,!!et.setupIntent);return xe.kind==="confirmed"?xe:null},Xn=ce=>{if(Bt||A&&Et.current!==A.generation)return;let et=Zn(ce);if(!et)return;if(Cn&&!cc(Ve,Le,xt)){Bt=!0;return}let{intentId:u,paymentMethodId:xe}=et;Bt=!0,ae=!0,qe.current=null,M.current=null,Ce.current&&(be("idle"),ct(!1));let L=`${wc}:${Ve}`;Xt(L,{createdAt:Date.now(),sessionId:Ve,nonce:Le,accountPatch:On,paymentMethodId:xe,providerIntentId:u,paymentMethodType:T});try{s({id:xe,type:"card",threeDSecureActionResultTokenId:u},{accountPatch:On,paymentMethodCategory:"wallet",sessionId:Ve,nonce:Le})}finally{Xt(L)}},Qn=!1;Dt=async()=>{if(!(Qn||Bt||ae)){Qn=!0,Ce.current&&be("checking");try{let ce=await dc(N,xt,Ee.current);if(Bt||ae)return;let et=Zi(xt),u=es(ce,en.providerObjectId,et);if(u.kind==="confirmed"){Xn(et?{setupIntent:ce}:{paymentIntent:ce});return}if(u.kind==="terminal"){if(ae=!0,Qi(Ve,Le,xt),qe.current=null,M.current=null,!Ce.current)return;be("idle"),m(),ee(T,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",A?.generation,!0);return}Ce.current&&!ae&&(be("blocked"),ct(!1))}catch{Ce.current&&!ae&&(be("blocked"),ct(!1))}finally{Qn=!1}}},M.current=Dt;let tn,En;try{let ce=await(Zi(xt)?N.confirmSetup({elements:Ie,clientSecret:xt,redirect:"if_required"}):N.confirmPayment({elements:Ie,clientSecret:xt,redirect:"if_required"}));if(!ce||typeof ce!="object")throw new fa(ep(ce));if(tn=ce,!tn.error&&!Zn(tn))throw new fa("confirmation_result_unconfirmed");En=on(tn.error?"returned_error":"resolved",tn.error&&Fa(tn.error)?"provider_declined":void 0)}catch(ce){let et=ce instanceof fa?ce.reason:void 0,u=et!==void 0,xe=on(u?"returned_error":"rejected");if(H?.error({...u?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:et}:Li(ce),...Ft,operationOutcome:xe.operationOutcome,durationMs:xe.durationMs,statusClass:"unknown",terminalReason:xe.terminalReason}),!Ce.current||Bt)return;await Dt?.();return}let Sn=tn.error;if(Sn){if(!Ce.current||Bt)return;if(Fa(Sn)){ae=!0,Qi(Ve,Le,xt),qe.current=null,M.current=null,be("idle");let ce=Sn.message??"Your payment was declined.";m(ce),c?.(ce),C?.(un(ft,ce,{code:go(Sn),declineCode:Ai(Sn)})),oi({billingApiUrl:o,sessionId:Ve,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:T,providerDeclineReason:go(Sn)??"provider_declined",...en.intentKind==="payment"&&en.providerObjectId.startsWith("pi_")?{providerIntentId:en.providerObjectId}:{}}})}else H?.error({...Li(Sn),...Ft,operationOutcome:En.operationOutcome,durationMs:En.durationMs,statusClass:"unknown",terminalReason:En.terminalReason}),await Dt?.();return}if(Xn(tn),!Bt)throw new Error("Invalid provider returned for APM intent")}catch(Ve){if(Ve===ei){let Le=H?.now()??globalThis.performance?.now()??Date.now();H?.error({errorCode:rp(yn),stage:Bn,requestCategory:yn,paymentMethodCategory:"wallet",provider:"stripe",...me?{walletType:me}:{},operationOutcome:"watchdog_expired",checkoutSessionId:In,durationMs:Math.max(0,Le-Ut),statusClass:"timeout",failureCategory:qt,attempt:We,terminalReason:"provider_error"}),H?.flush?.().catch(()=>{})}m(),ee(T,Ve,Ve===ei?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",A?.generation,Ve===ei)}finally{if(window.clearTimeout(hn),oe!==null&&(window.clearTimeout(oe),Ee.current.delete(oe)),!at){let Ve=H?.now()??globalThis.performance?.now()??Date.now();H?.performance({stage:"callback",durationMs:Math.max(0,Ve-Ut),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",..._t?{statusClass:"timeout"}:{}})}Ce.current&&ct(!1)}},[N,Ie,e,t,n,z,Te,ne,o,he,a,s,c,C,k,ee,De,yt,Yt,Et,Y,ke]),Ne=gt(()=>gl(i),[i]),wt=gt(()=>i.map($u),[i]);return Xe(Fo,{children:[p(Bi,{state:Fe,placeholderTestId:"flopay-wallet-placeholder",borderRadius:ve,children:Xe("div",{ref:Re,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[je&&Xe("button",{ref:He,type:"button","data-testid":"flopay-wallet-retry-button",onClick:F,style:rs,children:["Try ",os(ye)," again"]}),pt!=="idle"&&Xe("div",{role:"status","aria-live":"polite",children:[p("p",{children:"We are still confirming your payment. Check its status before trying again."}),p("button",{type:"button",onClick:Se,disabled:pt==="checking",style:rs,children:pt==="checking"?"Checking payment status\u2026":"Check payment status"})]}),pe&&p(Io,{identity:pe.identity,methodLabel:pe.methodLabel,onComplete:Pt,onCancel:()=>Pt(null)},pe.id),pt==="idle"&&p("div",{style:{display:pe?"none":void 0},children:p(Sc,{onReady:_=>{lt(xi(_,wt))},onLoadError:_=>{lt("load_error"),cs(Y,"stripe","wallet","provider_error")},onClick:async _=>{let d=Y?.now()??globalThis.performance?.now()??Date.now();Me.current=_.expressPaymentType,U.current=mc(_.expressPaymentType);let m=!0,A=window.setTimeout(()=>{m=!1,_.reject()},Ku),T=k?await k(U.current):{proceed:!0};if(window.clearTimeout(A),!m)return;if(!T.proceed){Ae.current.delete(ke),_.reject();return}let J=Qe(_.expressPaymentType);Je.current={generation:J,startedAt:d},Ae.current.set(ke,{generation:J,method:_.expressPaymentType,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),$e(!1),Y?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:J,..._.expressPaymentType==="apple_pay"||_.expressPaymentType==="google_pay"?{walletType:_.expressPaymentType}:{}}),f?.(U.current),_.resolve()},onConfirm:mt,onCancel:()=>{let _=Ae.current.get(ke);Ae.current.delete(ke),Y?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",..._?{attempt:_.generation}:{}}),bt(_?.generation),qe.current=null,$e(!1),Ue.current=!0,I()},options:{...hl,paymentMethods:Ne,emailRequired:zt,billingAddressRequired:zt}},ke)})]})}),ze&&p(Sr,{status:"processing"})]})}function Ec(e,t,n){let o=bc(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function as({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:c,onErrorChange:f,onDecline:C,onCancel:E,runBeforeButtonClick:k,onButtonClick:z,isProcessing:ne,submitButtonColor:O,submitButtonBorderRadius:ve,submitButtonStyle:V,errorText:v}){let P=jr(),{emitInstrument:he}=Do(Gn),N=ss(),Ie=is(),[Y,Fe]=ie(!1),lt=G(!1),[ze,ct]=ie(!1),[zt,pe]=ie("loading"),[Te,Pt]=ie(""),Re=!gn(o?.trim()),He=!Re||gn(Te.trim()),ke=Ye(async()=>{if(!N||!Ie||ne||lt.current||!ze)return;lt.current=!0,Fe(!0);let Q=k?await k("card"):{proceed:!0};if(!Q.proceed){lt.current=!1,Fe(!1);return}z?.("card");let je=Q.sessionId??t,$e=Q.nonce??n,pt=aa(a?.trim()),be=dr({email:Q.accountPatch?.email?.trim()||o?.trim()||Te.trim(),firstName:Q.accountPatch?.firstName?.trim()||pt.firstName,lastName:Q.accountPatch?.lastName?.trim()||pt.lastName}),ye=be.email,re=dr({...Q.accountPatch,...be});try{if(f?.(null),!gn(ye))throw new Error("A valid email address is required for payment.");await i?.(be);let M=await Ie.submit();if(M.error){f?.(M.error.message??"Payment failed.");return}let Ce=[be.firstName,be.lastName].filter(Boolean).join(" "),Ue=await N.createPaymentMethod({elements:Ie,params:{billing_details:{email:ye,...Ce?{name:Ce}:{}}}});if(Ue.error||!Ue.paymentMethod){f?.(Ue.error?.message??"Failed to create payment method.");return}let Me=Ue.paymentMethod;if(!je||!ye)throw new Error("Missing sessionId or email for payment.");let U=Me.type||e,vt=await ri(s,he,je,$e??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:U,paymentMethodId:null,intentKind:"payment"});if(vt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let qe=vt.clientSecret;Xt(Ir,{clientSecret:qe,sessionId:je,nonce:$e,accountPatch:re,paymentMethodId:Me.id,paymentMethodType:Me.type??e,gateway:"stripe"});let{error:Ee,paymentIntent:Je}=await N.confirmPayment({clientSecret:qe,confirmParams:{return_url:window.location.href,payment_method:Me.id},redirect:"if_required"});if(Ee){Xt(Ir);let De=Ee.message??"Payment failed.";f?.(De),C?.(un("card",De,{code:Ee.code})),await oi({billingApiUrl:s,sessionId:je,nonce:$e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ee.code??"provider_declined"}});return}let Ae=Je?.status;if(!ra(Ae)){Xt(Ir);let De=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(De),C?.(un("card",De,{code:Ae??"missing_payment_intent"}));return}Xt(Ir);let Qe=typeof Je?.payment_method=="string"?Je.payment_method:Je?.payment_method?.id;c({id:Qe??Me.id,type:"card",threeDSecureActionResultTokenId:Je?.id,gateway:"stripe",paymentMethodType:Me.type??e},{accountPatch:re,paymentMethodCategory:"apm",sessionId:je,nonce:$e})}catch(M){f?.(M instanceof Error?M.message:"Payment failed. Please try again.")}finally{lt.current=!1,Fe(!1)}},[N,Ie,ne,ze,k,z,t,n,o,a,Te,i,s,he,e,c,f,C]);return Xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Re&&p("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Re&&Xe("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",p("input",{type:"email",autoComplete:"email",required:!0,value:Te,onChange:Q=>Pt(Q.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),p(Wu,{onReady:()=>pe("ready"),onLoadError:()=>{pe("load_error"),cs(pn(P),"stripe","apm")},onChange:Q=>{ct(!!Q.complete)},options:{layout:Pl,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...gn(o?.trim())?{email:o?.trim()}:{}}}}}),p(vl,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ke()},disabled:!ze||!He||Y||ne||zt!=="ready",color:O,borderRadius:ve,style:V,children:Y?"Processing\u2026":`Pay with ${ga(e)}`}),v&&p(Eo,{margin:"0.75rem 0 0",children:v})]})}function Pc({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:s,stripeInstance:c,paymentElementBaseOptions:f,futureUseSession:C,onTokenizedBody:E,onErrorChange:k,onButtonClick:z,onDecline:ne,runBeforeButtonClick:O,onLoadStateChange:ve,isProcessing:V=!1,submitButtonColor:v="#4A49FF",submitButtonBorderRadius:P=8,submitButtonStyle:he,buttonAppearance:N,themeId:Ie,onExpandApm:Y,expandedApmMethod:Fe}){let{emitInstrument:lt}=Do(Gn),[ze,ct]=ie(null),[zt,pe]=ie(null),Te=G(!1),{request:Pt,collect:Re,finish:He}=ko();ht(()=>{s.length>0&&c?ve?.("ready"):c||ve?.("loading")},[s.length,c,ve]);let ke=Ye(async ye=>{if(!c||Te.current||V)return;Te.current=!0,pe(ye);let re=O?await O("card"):{proceed:!0};if(!re.proceed){Te.current=!1,pe(null);return}z?.("card");let M=re.sessionId??e,Ce=re.nonce??t,Ue=aa([re.accountPatch?.firstName,re.accountPatch?.lastName].filter(Boolean).join(" ")||o),Me=dr({email:re.accountPatch?.email?.trim()||n?.trim(),firstName:re.accountPatch?.firstName?.trim()||Ue.firstName,lastName:re.accountPatch?.lastName?.trim()||Ue.lastName});if(!gn(Me.email)){pe(null);let qe=await Re(ga(ye),Me);if(!qe){Te.current=!1;return}Me=qe,pe(ye)}let U=Me.email,vt=dr({...re.accountPatch,...Me});try{if(k?.(null),!M||!gn(U))throw new Error("Missing sessionId or email for payment.");await a?.(Me);let qe=await ri(i,lt,M,Ce??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ye,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ee=qe.clientSecret;Xt(Ir,{clientSecret:Ee,sessionId:M,nonce:Ce,accountPatch:vt,paymentMethodType:ye,gateway:"stripe"});let{error:Je,paymentIntent:Ae}=await c.confirmPayment({clientSecret:Ee,confirmParams:{return_url:window.location.href,payment_method_data:{type:ye,billing_details:{name:[Me.firstName,Me.lastName].filter(Boolean).join(" "),...U?{email:U}:{}}}},redirect:"if_required"});if(Je){Xt(Ir);let bt=Je.message??"Payment failed.";k?.(bt),ne?.(un("card",bt,{code:Je.code})),await oi({billingApiUrl:i,sessionId:M,nonce:Ce,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ye,providerDeclineReason:Je.code??"provider_declined"}});return}let Qe=Ae?.status;if(!ra(Qe)){Xt(Ir);let bt=Qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";k?.(bt),ne?.(un("card",bt,{code:Qe??"missing_payment_intent"}));return}Xt(Ir);let De=typeof Ae?.payment_method=="string"?Ae.payment_method:Ae?.payment_method?.id;E({id:De??Ae?.id,type:"card",threeDSecureActionResultTokenId:Ae?.id,gateway:"stripe",paymentMethodType:ye},{accountPatch:vt,paymentMethodCategory:"apm",sessionId:M,nonce:Ce})}catch(qe){k?.(qe instanceof Error?qe.message:"Payment failed. Please try again.")}finally{Te.current=!1,pe(null)}},[c,V,O,z,e,t,n,Re,i,lt,o,a,E,k,ne]),[Q,je]=ie(null),$e=Y?Fe??null:Q,pt=Ye(ye=>{Te.current||V||$e&&$e!==ye||(ic(ye)?Y?Y(ye):je(ye):ke(ye))},[$e,V,ke,Y]),be=gt(()=>Q?Ec(f,Q,C):null,[Q,f,C]);return p("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Pt?p(Io,{identity:Pt.identity,methodLabel:Pt.methodLabel,onComplete:He,onCancel:()=>He(null)},Pt.id):s.map(ye=>{let re=Fe===ye,M=zt===ye,Ce=zt!==null&&zt!==ye||Fe!=null&&Fe!==ye;return Xe(Hu.Fragment,{children:[p(fl,{method:ye,themeId:Ie,submitting:M,disabled:Ce,highlighted:re,hasNextStep:ic(ye),onClick:()=>pt(ye),backgroundColor:N?.backgroundColor,borderColor:N?.borderColor,textColor:N?.textColor,borderRadius:N?.borderRadius,fontFamily:N?.fontFamily}),!Y&&Q===ye&&be&&c&&p(no,{stripe:c,options:be,children:p(as,{method:ye,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:E,onErrorChange:k,onDecline:ne,onCancel:()=>je(null),runBeforeButtonClick:O,onButtonClick:z,isProcessing:V,submitButtonColor:v,submitButtonBorderRadius:P,submitButtonStyle:he})},ye)]},ye)})})}function hp({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:s,onError:c,onDecline:f,onTokenizedBody:C,firstName:E,lastName:k,chv:z,className:ne,submitLabel:O,isProcessing:ve,error:V,onErrorChange:v,showPayPal:P=!0,showStripe:he=!0,walletPresentation:N="auto",enabledPaymentMethods:Ie,enabledPaymentMethodCountries:Y,showApplePay:Fe=!0,showGooglePay:lt=!0,layout:ze="default",theme:ct,buttonsTheme:zt,buttonsStyles:pe,appearance:Te,cardButtonContent:Pt,cardBackButtonContent:Re,cardTitleContent:He,showSecurityFooter:ke,onButtonClick:Q,onBeforeButtonClick:je,onBuyerIdentityReady:$e,enableAVS:pt,cardFieldOrder:be,cardPreFormSlot:ye,avsLayout:re="row",country:M,zip:Ce,addressLine1:Ue,addressLine2:Me,city:U,state:vt,onCountryChange:qe,onZipChange:Ee,avsCheck:Je,checkoutType:Ae,checkoutLayout:Qe,totalAmount:De=0,currency:bt="usd",initialCardOpen:Yt=!1,directPaypal:yt,isSubscription:Et=!1,session:I,dataAttachmentPending:ee=!1,dataAttachmentRequiresIdentity:Oe=!1,debug:F=!1}){let Se=jr(),mt=zi(),Ne=Do(cr),{emitInstrument:wt}=Do(Gn),_=G(null);_.current||(_.current=qa());let d=_.current,[,m]=ie(0),A=G(null);A.current||(A.current=ea());let T=A.current,J=gt(()=>({browser:T,capability:d,presentationMode:"popup"}),[T,d]),ft=I??Ne.session,me=gt(()=>({futureUse:ft?.futureUse,futureUseUnsupported:ft?.futureUseUnsupported}),[ft?.futureUse,ft?.futureUseUnsupported]),We=ft?.gateways?.paypal?.providerObjectType??yt?.providerObjectType,H=ee||Ne.claimPending===!0,Ut=Oe||Ne.claimRequiresIdentity===!0,Ct=H&&!Ut,_t=zl(),at=n||_t,[oe,In]=ie(!1),[Bn,yn]=ie(null),[qt,Fn]=ie(M??""),[Dn,hn]=ie(Ce??""),[Tt,Ve]=ie(Ue??""),[Le,Rn]=ie(Me??""),[kt,On]=ie(U??""),[mn,jt]=ie(vt??""),[Qt,Jn]=ie(""),[$n,en]=ie({}),xt=G(Ce??""),Cn=G(M??""),ln=G(Ue??""),Ft=G(Me??""),fn=G(U??""),Dt=G(vt??""),on=G(""),Bt=G({});ht(()=>{let r=(g,W,fe,D,X)=>{if(Bt.current[g])return;let Rt=W?.trim();!Rt||Rt===fe.current||(fe.current=Rt,D(Rt),X?.(Rt))};r("country",M,Cn,Fn,qe),r("zip",Ce,xt,hn,Ee),r("addressLine1",Ue,ln,Ve),r("addressLine2",Me,Ft,Rn),r("city",U,fn,On),r("state",vt,Dt,jt)},[M,Ce,Ue,Me,U,vt,qe,Ee]);let ae=gt(()=>Lu(pt),[pt]),Zn=ae!==null,Xn=gt(()=>Ji(I),[I]),Qn=Au(I?.vault),tn=!!I?.gateways?.pcivault,En=Bl(I),ce=!!(I?.gateways?.stripe?.enabledPaymentMethods??Ie)?.includes("card")||Qr(I),et=Qn||ce||tn,u=!!(he&&et&&e),[xe,L]=ie(()=>ze!=="buttons"||Yt?e??null:null),[Pn,Nn]=ie(0),Jt=ze!=="buttons"||Yt||!!e&&xe===e,_n=I?.captureMethod,nt=G(Se);ht(()=>{nt.current=Se},[Se]);let[yr,Dr]=ie(null);ht(()=>{if(!u||!e||!Jt){Dr(null);return}let r=nt.current?nt.current.cardCapture({sessionId:e,captureMethod:_n}):new vu({sessionId:e,captureMethod:_n,billingApiUrl:at,telemetry:o});return Dr({sessionId:e,captureMethod:_n,billingApiUrl:at,telemetry:o,capture:r}),()=>{r.unmount()}},[u,e,Jt,_n,at,o]);let It=u&&e&&Jt&&yr?.sessionId===e&&yr.captureMethod===_n&&yr.billingApiUrl===at&&yr.telemetry===o?yr.capture:null,Ln=gt(()=>{let r=qt,g=ae?Kt(ae.postal_code,r):!1;return mp(r,Dn,g)},[ae,qt,Dn]),{avsInvalid:er,invalidAvsFields:tr}=gt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!u||!ae)return{avsInvalid:!1,invalidAvsFields:r};let g=qt,W=(X,Rt)=>Kt(X,g)&&!Rt.trim(),fe={line1:W(ae.address_line_1,Tt),city:W(ae.city,kt),state:W(ae.state,mn),zip:Ln.empty||Ln.malformed};return{avsInvalid:fe.line1||fe.city||fe.state||fe.zip,invalidAvsFields:fe}},[u,ae,qt,Tt,kt,mn,Ln]),[$t,mr]=ie(!1),[fr,Tn]=ie(!1),[gr,Wn]=ie(!1),[hr,Er]=ie({line1:!1,city:!1,state:!1}),zn=G(!1),nr=G({email:!1,line1:!1,city:!1,state:!1,zip:!1}),rr=G(!1),Mt=Ye(r=>{nr.current[r]=!0,rr.current=!0},[]),Un=Ye(r=>!zn.current&&nr.current[r],[]),wn=Ye(r=>{Un(r)&&Er(g=>g[r]?g:{...g,[r]:!0})},[Un]),[or,ar]=ie(()=>Xi(I?.vault,{billingApiUrl:at,sessionId:e,nonce:t})),[tt,nn]=ie(Yt&&et?"card":"buttons"),[cn,Mn]=ie(null),Or=tt==="expanding"||tt==="card",Pr=I?.gateways?.stripe&&!En?"stripe":void 0,_r=Ye(()=>{wt?.({class:"card_surface",provider:Pr})},[Pr,wt]),Hn=G(null),rn=Ye(r=>{Hn.current&&clearTimeout(Hn.current),Hn.current=setTimeout(()=>{Hn.current=null,r()},ha)},[]);ht(()=>()=>{Hn.current&&clearTimeout(Hn.current)},[]);let Nr=G(!1),[an,w]=ie(0),b=G(null),j=Ye(()=>{_r(),L(e??null),Nr.current&&(Nr.current=!1,w(r=>r+1)),Nn(r=>r+1),nn("expanding"),rn(()=>nn("card"))},[rn,_r,e]),K=Ye(()=>{nn("collapsing"),rn(()=>nn("buttons"))},[rn]),it=Ye(r=>{Mn(r),nn("apm-expanding"),rn(()=>nn("apm-form"))},[rn]),Wt=Ye(()=>{nn("apm-collapsing"),rn(()=>{nn("buttons"),Mn(null)})},[rn]);ht(()=>{ze==="buttons"&&Yt&&et&&(L(e??null),nn("card"))},[ze,Yt,et,e]);let[de,x]=ie(null),B=G(!1),R=G(null),l=G("idle"),[y,h]=ie(!1),$=G(y);$.current=y;let[le,Pe]=ie(()=>yt?.existingOrderId?{orderId:yt.existingOrderId,attempts:1}:null),Ht=G(le);ht(()=>{Ht.current=le},[le]);let te=G(null),we=gt(()=>{if($e||Ne.claimBuyerIdentity||I?.buyerIdentified!==!1||!e||!t)return;let r=`${at}|${e}|${t}`;te.current?.key!==r&&(te.current={key:r,claim:Co(new Bo(at,{telemetry:!1}),e,t,{...i?{userId:i}:{},...E?{firstName:E}:{},...k?{lastName:k}:{}})});let g=te.current.claim;return async W=>{await g(W)}},[$e,Ne.claimBuyerIdentity,I?.buyerIdentified,e,t,at,i,E,k]),Be=$e??Ne.claimBuyerIdentity??we,rt=V??Bn,Z=gt(()=>Uu(ct),[ct]),S=gt(()=>{let r=Z?.buttonsLayout??zu(zt);return pe?{...r,...pe,cardButton:{...r.cardButton,...pe.cardButton},cardFormContainer:{...r.cardFormContainer,...pe.cardFormContainer},backButton:{...r.backButton,...pe.backButton},backButtonIcon:{...r.backButtonIcon,...pe.backButtonIcon},submitButton:{...r.submitButton,...pe.submitButton},title:{...r.title,...pe.title}}:r},[Z,zt,pe]),q=Te??Z?.appearance,Ke=gt(()=>cl({appearance:q,buttonsStyles:S,layout:ze}),[q,S,ze]),ge=Ne.inlineSessionPatchProcessing??!1,_e=(ve??oe)||ge,dt=at.replace(/\/+$/,""),Ze=gt(()=>Ni({userId:i,email:a,firstName:E,lastName:k,country:M,zip:Ce},$n),[i,a,E,k,M,Ce,$n]),oo=[Ze.firstName,Ze.lastName].filter(r=>!!r?.trim()).join(" "),Ss=!gn(Ze.email?.trim()),ci=G(null);u&&ci.current===null&&(ci.current=Ss);let Lr=u&&(ci.current??Ss),di=gt(()=>fp(Qt,Lr),[Qt,Lr]),ao=di.empty||di.malformed,qn=gt(()=>Se?Se.getRawProvider():null,[Se]),ws=gt(()=>mt?mt.getRawProvider():null,[mt]),Uo=De||100,io=bt.toLowerCase(),ui=gt(()=>q?bu(q):null,[q]),so=ui,ks=gt(()=>{let r=ui??{},g=r.rules??{};return{...r,rules:{...g,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...g[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...g[".AccordionItemContents"]??{}}}}},[ui]),Is=gt(()=>({...xl(De,ft?.captureMethod,me),currency:io,...so?{appearance:so}:null}),[De,io,ft?.captureMethod,me,so]),pi=bc(me,"paypal","paypal"),Rs=gt(()=>({mode:"payment",amount:Uo,currency:io,captureMethod:"manual",...pi?{setupFutureUsage:pi}:null,...so?{appearance:so}:null}),[Uo,io,pi,so]),ue=Ye(r=>{yn(r),v?.(r)},[v]),Es=G(0);ht(()=>{an!==Es.current&&(Es.current=an,ue(null))},[an,ue]);let yi=G(""),[_s,Uc]=ie(!1),mi=Ye(()=>{Uc(!0)},[]);ht(()=>{if(!u||!Lr||!Be||!_s||ao||yi.current)return;let r=dr({email:gn(Ze.email?.trim())?Ze.email?.trim():on.current.trim(),firstName:Ze.firstName?.trim(),lastName:Ze.lastName?.trim()});yi.current=JSON.stringify(r),en(g=>({...g,...r})),Promise.resolve(Be(r)).catch(g=>{yi.current="",ue(g instanceof Error?g.message:"Failed to attach buyer details.")})},[u,Lr,Be,_s,ao,Ze.email,Ze.firstName,Ze.lastName,ue]),ht(()=>{!u||!It||It.setCardFieldOrder?.(be??null,ae==null&&!Lr)},[u,It,be,ae,Lr]),ht(()=>{(tt==="expanding"||tt==="collapsing"||tt==="apm-expanding"||tt==="apm-collapsing")&&ue(null)},[tt,ue]);let vr=Ye((r,g,W)=>{f?.(un(r,g,W))},[f]),lo=Ye((r,g,W)=>{let fe=W?.popupBlocked??zr(g);fe&&d.markBlocked()&&m(Ge=>Ge+1);let D=Ba(os(r),fe,T.inAppBrowser),X=go(g),Rt=(X?.toLowerCase()==="error"?void 0:X)??yl(W?.code)??"external_payment_method_failed",lr=new Br(D,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:Rt,popupBlocked:fe,inAppBrowser:T.inAppBrowser,appFamily:T.appFamily,popupCapability:d.current(),presentationMode:W?.presentationMode??"popup"}});W?.telemetryReported||pn(Se)?.error(xo({...J,presentationMode:W?.presentationMode??"popup"},{errorCode:fe?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:W?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:W?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:W?.terminalReason??(fe?"popup_blocked":"provider_error")})),x(null),ze==="buttons"&&(nn("buttons"),Mn(null)),ue(D),c?.(lr),console.error("[FloPay] External payment method failed:",{method:r,code:Rt,popupBlocked:fe})},[T,J,Se,ze,c,d,ue]);ht(()=>{if(!u||!e){ar(null);return}let r={billingApiUrl:dt,sessionId:e,nonce:t},g=Xi(I?.vault,r);if(g){ar(g);return}if(!Jt){ar(null);return}let W=`${dt}\0${e}\0${t??""}`,fe=b.current;if(fe&&fe.key===W){ar(fe.mount);return}ar(null);let D=!0;return new Bo(dt).getVaultCapture(e,t).then(X=>{if(!D)return;let Rt=Xi(X,r);Rt?.verificationRequired&&!X.html&&(b.current={key:W,mount:Rt}),Rt?ar(Rt):ue("Failed to load the secure card form.")}).catch(X=>{D&&ue(X instanceof Error?X.message:"Failed to load the secure card form.")}),()=>{D=!1}},[u,Jt,Pn,e,I?.vault,dt,t,ue]);let ir=G({onComplete:s,onError:c,updateError:ue,emitDecline:vr,resolvedAccount:Ze,avsConfig:ae,avsCheckProp:Je,sessionId:e,nonce:t,baseUrl:dt,captureMethod:I?.captureMethod,paymentId:I?.paymentId,authorizationExpiresAt:I?.authorizationExpiresAt,serverSideCardGateway:En});ir.current={onComplete:s,onError:c,updateError:ue,emitDecline:vr,resolvedAccount:Ze,avsConfig:ae,avsCheckProp:Je,sessionId:e,nonce:t,baseUrl:dt,captureMethod:I?.captureMethod,paymentId:I?.paymentId,authorizationExpiresAt:I?.authorizationExpiresAt,serverSideCardGateway:En};let fi=G(!1),Ts=Ye(()=>{let r=ir.current,g=r.resolvedAccount.email?.trim(),W=gn(g)?g:on.current.trim();if(!gn(W))return null;let fe=r.resolvedAccount.firstName?.trim(),D=r.resolvedAccount.lastName?.trim(),X=Cn.current.trim()||r.resolvedAccount.country?.trim()||"",Rt=r.avsConfig?Kt(r.avsConfig.state,X):!1,lr=r.avsConfig?Kt(r.avsConfig.address_line_1,X):!1,Ge=r.avsConfig?Kt(r.avsConfig.postal_code,X):!1,st=r.avsConfig?Kt(r.avsConfig.city,X):!1,ut=r.avsConfig?Kt(r.avsConfig.address_line_2,X):!1,Ot=lr&&!Rt&&Ge?_u(X,(xt.current??"").trim()):null,Jr=Rt?Dt.current:Ot;return{accountData:{userId:r.resolvedAccount.userId??"",email:W,...fe?{firstName:fe}:{},...D?{lastName:D}:{},...Ge&&xt.current?{zip:xt.current}:{},...st&&fn.current?{city:fn.current}:{},...Jr?{state:Jr}:{},...lr&&ln.current?{addressLine1:ln.current}:{},...ut&&Ft.current?{addressLine2:Ft.current}:{},...X?{country:X}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:Kt(r.avsConfig.country,X),postal_code:Ge,address_line_1:lr,address_line_2:ut,city:st,state:Rt}}:{}}},[]),Ms=G(H);Ms.current=H,ht(()=>{H||rt!==uc||ir.current.updateError(null)},[H,rt]),ht(()=>{!u||!It||It.setSubmitGate?.(er||H||ao||y)},[u,It,er,H,ao,y]),ht(()=>{if(!u||!It)return;fi.current=!1;let r=null,g=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,l.current="idle",x(null)},400)},W=It.on("submitting",()=>{mr(!0),R.current&&clearTimeout(R.current),l.current="validation-window",R.current=setTimeout(()=>{R.current=null,l.current==="validation-window"&&(l.current="processing")},op),x("processing");let Ge=ir.current;if(!Ge.sessionId||!Ge.nonce)return;let st=Ts();if(!st){Ge.updateError("Enter a valid email address."),l.current="idle",x(null);return}new Bo(Ge.baseUrl).patchAccountSnapshot(Ge.sessionId,Ge.nonce,st,{telemetryMode:"best_effort"}).catch(ut=>{if(!ip(ut))return;let Ot=ut instanceof Error?ut.message:"Please check your billing address and try again.";Ge.updateError(Ot),l.current="idle",x(null),Ge.onError?.(ut instanceof Br?ut:new Br(Ot,"api_error"))})}),fe=It.on("complete",Ge=>{_o(Ge.sessionId??ir.current.sessionId),l.current="terminal",h(!1),x("success"),setTimeout(()=>{if(fi.current)return;fi.current=!0;let st=ir.current,ut=Ji(st)||Ge.outcome==="authorized",Ot=st.serverSideCardGateway?{}:{paymentIntentId:Ge.intentId};ir.current.onComplete?.(ut?{status:"authorized",...Ot,paymentId:Ge.paymentId??st.paymentId,sessionId:Ge.sessionId??st.sessionId,authorizationExpiresAt:Ge.authorizationExpiresAt??st.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Ot,checkoutMethod:"card"})},600)}),D=It.on("decline",Ge=>{let st=ir.current,ut=Ge.message??"Your payment was declined. Please try another card or contact your bank.";l.current="terminal",h(!1),st.updateError(ut),x("error");let Ot=Ge.failureOutcome??Fu(Ge.declineReason)??"authorization_declined";st.emitDecline("card",ut,{code:Ot,declineCode:Ot}),g()}),X=It.on("error",Ge=>{let st=ir.current,ut=Ge.message??"There was a problem processing your payment. Please try again.";l.current="terminal",h(!1),st.updateError(ut),x("error"),st.onError?.(new Br(ut,"api_error",{code:Ge.failureOutcome??"capture_failed"})),g()}),Rt=It.on("challenge_dismissed",()=>{R.current&&(clearTimeout(R.current),R.current=null),l.current="processing",h(!0),x(null)}),lr=It.on("blocked",()=>{if($.current){ir.current.updateError(ap);return}if(!Ms.current){mr(!0);return}mi(),ir.current.updateError(uc)});return()=>{r&&(clearTimeout(r),r=null),R.current&&(clearTimeout(R.current),R.current=null),l.current="idle",h(!1),x(null),W(),fe(),D(),X(),Rt(),lr()}},[u,It,mi,Ts]);let br=!!yt?.clientId,qo=Array.isArray(Ie),Sa=qo&&Ie.length>0,As=qo&&Ie.includes("paypal"),wa=G(null);wa.current===null&&(wa.current=Mu());let co=wa.current?"redirect":ml(T,N,d.current()),{expressMethods:ka,paymentElementMethods:gi}=gt(()=>Du(Ie,{excludePaypal:br}),[Ie,br]),xs=br||!!mt||As&&co==="redirect",qc=gt(()=>xs?ka.filter(r=>r!=="paypal"):ka,[ka,xs]),jc=gt(()=>{let r=[];return Fe&&r.push("apple_pay"),lt&&r.push("google_pay"),r},[Fe,lt]),uo=qo?qc:jc,$c=he&&uo.length>0,Bs=Zn?qt:M,Ia=gt(()=>Ru(gi,Bs,Y),[gi,Bs,Y]),hi=gt(()=>({mode:"payment",amount:Uo,currency:io,paymentMethodCreation:"manual",appearance:ks}),[Uo,io,ks]),[Fs,Ds]=ie("loading"),[Os,Ns]=ie("loading"),[Ls,zs]=ie("loading"),[Wc,Pi]=ie(!1),[Us,vi]=ie("loading"),[bi,Hc]=ie();ht(()=>{Hc(ea())},[]);let Ra=bi?.inAppBrowser,Ea=bi?Da(bi,yt?.approvalPresentation,We??(Et?"subscription":"order")):"popup",qs=P&&(br||(qo?As:Ra===!1)),js=he&&$c,jo=(!Ct||!!Ne.waitForDataAttachment)&&qs&&br,$s=Us==="retrying"||Us==="exhausted",$o=null;he&&(mt?$o=ws:co==="redirect"&&($o=qn));let Ws=gt(()=>({...J,presentationMode:co}),[J,co]),Wo=!Ct&&qs&&!!$o&&(!br||$s),po=!Ct&&js&&!!qn,Ho=!Ct&&he&&Sa&&Ia.length>0&&!!qn,Vc=jo&&!$s?Wc:Wo&&Fi(Fs),Kc=po&&Fi(Os),Gc=Ho&&Ls!=="load_error",Hs=r=>r==="loading"||r==="ready",Vs=jo||Wo&&Hs(Fs)||po&&Hs(Os)||Ho&&Ls!=="load_error",_a=G(!1);ht(()=>{if(!_a.current){if(!he&&!P){_a.current=!0;let r=new Br("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(r),ue(r.message)}else if(!he&&P&&!br){_a.current=!0;let r=new Br("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(r),ue(r.message)}else if(Ra!==void 0&&!Ct&&!et&&!Vs){_a.current=!0;let r=new Br("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});c?.(r),ue(r.message)}}},[he,P,br,Ra,Ct,et,Vs,c,ue]);let Ks=G(!1);ht(()=>{if(Ks.current||!Sa)return;let r=[];Fe!==!0&&r.push("showApplePay"),lt!==!0&&r.push("showGooglePay"),r.length!==0&&(Ks.current=!0,console.warn(`[FloPay] ${r.join(" / ")} ${r.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Sa,Fe,lt]);let Gs=Ye((r,g)=>Ne.applyInlineSessionPatch?Ne.applyInlineSessionPatch(r).then(W=>({error:null,sessionId:W.sessionId||e,nonce:W.session?.clientSecret||t})).catch(W=>{let fe=sc(g,W);return ue(fe.message),c?.(fe),{error:fe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ne.applyInlineSessionPatch,t,c,e,ue]),sr=Ye(async r=>{if(r!=="card"&&Ct&&await Ne.waitForDataAttachment?.(),!je)return{proceed:!0};try{let g=await je({method:r,sessionId:e||void 0,createSession:Ne.inlineSessionDraft});if(g===!1)return{proceed:!1};if(g&&typeof g=="object"){g.account&&en(fe=>({...fe??{},...g.account}));let W=await Gs(g,r);return W.error?{proceed:!1,accountPatch:g.account}:{proceed:!0,accountPatch:g.account,sessionId:W.sessionId,nonce:W.nonce}}return{proceed:!0}}catch(g){let W=sc(r,g);return ue(W.message),c?.(W),{proceed:!1}}},[Gs,Ne.inlineSessionDraft,Ne.waitForDataAttachment,Ct,je,c,e,ue]),Ys=Ye(async(r,g)=>{if(B.current)return;B.current=!0,In(!0),x("processing"),ue(null);let W=g?.sessionId??e,fe=g?.nonce??t,D=Ni(Ze,g?.accountPatch),X=g?.completionPaymentMethodId??oa(r),Rt=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,lr=dp(r),Ge=g?.presentationMode?Qa(pn(Se),{...J,presentationMode:g.presentationMode}):void 0,st=()=>{wt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:lr}),Ge?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...ur,requestCategory:"process_payment"})};try{let ut=new Bo(dt),Ot=await ut.processPayment(D.userId??"",{sessionId:W,nonce:fe,paymentMethodCategory:g?.paymentMethodCategory??pp(r),tokenizedData:Rt,accountData:{...g?.accountPatch,userId:D.userId??"",email:D.email??"",firstName:D.firstName||void 0,lastName:D.lastName||void 0,...Su({avsConfig:ae,country:Cn.current,zip:xt.current,city:fn.current,state:Dt.current,addressLine1:ln.current,addressLine2:Ft.current})},...Cu({chv:z,avsCheck:Je,checkoutType:Ae,checkoutLayout:Qe,avsConfig:ae,country:Cn.current})}),Jr=async dn=>{let Zr=Ji(I)||dn?.status==="authorized";_o(W),Ge?.terminal({outcome:"payment_succeeded",...ur}),x("success"),Pe(null),await new Promise(Zo=>setTimeout(Zo,600));let Cr;typeof dn?.paymentId=="string"?Cr=dn.paymentId:I?.paymentId&&(Cr=I.paymentId);let Xr;typeof dn?.authorizationExpiresAt=="string"?Xr=dn.authorizationExpiresAt:I?.authorizationExpiresAt&&(Xr=I.authorizationExpiresAt),s?.(Zr?{status:"authorized",...Cr===void 0?{}:{paymentId:Cr},sessionId:typeof dn?.sessionId=="string"?dn.sessionId:W,...Xr===void 0?{}:{authorizationExpiresAt:Xr},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:X,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:X,checkoutMethod:r.isPaypal?"paypal":"card"})};if(Ot.ok){await Jr(Ot.status===204?null:await Ot.json().catch(()=>null));return}let jn=await Ot.json().catch(()=>null);if(jn?.type==="paypal_redirect_required"){let dn=jn.threeDSecureToken,Zr=jn.paymentMethodId||r.id||"";if(!Se||!dn){x("error"),ue("PayPal authorization required but no token provided.");return}try{let Cr=mt?.getRawProvider();if(!Cr){ue("PayPal is not available.");return}let Xr={return_url:window.location.href};Zr&&(Xr.payment_method=Zr);let{error:Zo}=await Cr.confirmPayment({clientSecret:dn,confirmParams:Xr,redirect:"if_required"});if(Zo){x("error");let sl=Zo.message??"PayPal payment failed.";ue(sl),vr("paypal",sl,{code:Zo.code})}}catch(Cr){x("error"),ue(Cr instanceof Error?Cr.message:"PayPal authorization failed.")}return}if(jn?.type==="paypal_direct_required"){let dn=jn.orderId;if(!dn){x("error"),ue("PayPal retry required but no order id provided.");return}let Zr=Ht.current?.attempts??0;if(Zr>=2){x("error"),ue("PayPal payment could not be completed after multiple attempts."),vr("paypal","paypal_direct_required retry limit exceeded");return}Pi(!1),vi("loading"),Pe({orderId:dn,attempts:Zr+1}),x(null);return}if(Ot.headers.get(Zu)===Xu){let dn=await Qu(ut,W,fe);if(dn!==void 0){await Jr(dn);return}}ku(Ot.status,jn)?Ge?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}):st(),x("error");let il=jn?.message??"Payment failed. Please try again.";ue(il),vr(r.isPaypal?"paypal":"card",il,{code:jn?.code??jn?.gatewayErrorCode,declineCode:jn?.declineCode??jn?.gatewayDeclineReason}),await new Promise(dn=>setTimeout(dn,400))}catch(ut){Ic(ut)||st(),x("error"),ue(ut instanceof Error?ut.message:"An unexpected error occurred"),await new Promise(Ot=>setTimeout(Ot,400))}finally{In(!1),x(null),B.current=!1}},[dt,e,t,Ze,ae,Je,Ae,Qe,z,Se,mt,I,s,ue,vr,wt,J]),An=Ye((r,g)=>{C?C(r):Ys(r,g)},[C,Ys]),Vo=`${wc}:${e}`;ht(()=>{if(typeof window>"u")return;let r=localStorage.getItem(Vo);if(!r)return;let g;try{g=JSON.parse(r)}catch{Xt(Vo);return}if(!g||typeof g.createdAt!="number"||Date.now()-g.createdAt<0||Date.now()-g.createdAt>kc||typeof g.paymentMethodId!="string"||typeof g.providerIntentId!="string"||typeof g.paymentMethodType!="string"||g.sessionId!==e||!t||g.nonce!==t||!uo.includes(g.paymentMethodType)){Xt(Vo);return}Xt(Vo),An({id:g.paymentMethodId,type:"card",threeDSecureActionResultTokenId:g.providerIntentId,gateway:"stripe",paymentMethodType:g.paymentMethodType},{...g.accountPatch?{accountPatch:g.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[An,t,e,Vo,uo]);let Js=G(!1);ht(()=>{if(typeof window>"u"||Js.current)return;let[r,g,W]=vc();if(!r||!g||wa.current||!Se)return;let fe=Se.getRawProvider();if(!fe)return;let D=st=>{let ut=localStorage.getItem(st);if(!ut)return null;try{return JSON.parse(ut)}catch{return Xt(st),null}},X=D(Ir)??D(lc),Rt;if(X?.clientSecret){if(X.clientSecret!==g)return;Rt={...X.accountPatch?{accountPatch:X.accountPatch}:{},...X.sessionId?{sessionId:X.sessionId}:{},...X.nonce?{nonce:X.nonce}:{}}}else if(X?.sessionId&&X.sessionId!==e)return;Js.current=!0,Xt(Ir),Xt(lc),window.history.replaceState({},"",Cc());let lr=X?.paymentMethodType??X?.tokenType??"card",Ge="card";(async()=>{if(W==="failed"){let Tr="Payment was declined. Please try again.";ue(Tr),vr(Ge,Tr);return}let{paymentIntent:st,error:ut}=await fe.retrievePaymentIntent(g);if(ut){let Tr=ut.message??"Failed to retrieve payment status.";ue(Tr),vr(Ge,Tr,{code:ut.code});return}let Ot=st?.status,Jr=ra(Ot);if(!st||!Jr){let Tr=Ot==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ue(Tr),vr(Ge,Tr,{code:Ot??"missing_payment_intent"});return}let jn=typeof st.payment_method=="string"?st.payment_method:st.payment_method?.id;An({id:jn??X?.paymentMethodId??X?.tokenId??st.id,type:"card",threeDSecureActionResultTokenId:st.id,gateway:X?.gateway??"stripe",paymentMethodType:lr},Rt)})()},[e,An,Se,ue,vr]);let Ci=Ye(r=>{r.preventDefault()},[]);if(!(u||Se!==null))return p("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Ko=ze==="buttons",xn=q?.variables,Yc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Si=xn?.colorBackground,Jc=Si&&!Yc.has(Si)?Si:void 0,Go=S.cardInputBorder??(Ko?"#e5e7eb":"#A4A4FF"),Zs=xn?.colorDanger??"#dc2626",Vt=r=>tr[r]&&(hr[r]||$t),Ta=ao&&(gr||$t),Vn=r=>r?Zs:Go,Ma=(Ln.malformed||Ln.empty)&&(fr||$t),Zc=Vn(Ma),wi=S.cardFormContainer?.backgroundColor??Jc??(Ko?"white":"#EDEDFF"),yo=S.cardInputBackground??xn?.colorBackground??"white",ki=ho(Re),Xs=ho(He),mo=S.nameInput,Qs=S.cardInputFontSize??gp(mo?.fontSize)??xn?.fontSizeBase??"16px",el=typeof mo?.fontFamily=="string"?mo.fontFamily:xn?.fontFamily??"Poppins, sans-serif",tl=dl(mo?.fontWeight)??400,Xc=S.cardInputColor??(typeof mo?.color=="string"?mo.color:void 0)??xn?.colorText??"#262833",Qc=S.cardInputPlaceholderColor??"#9ca3af",Zt=xn?.borderRadius??"8px",Gr=xn?.borderRadius??S.cardButton?.borderRadius??Zt,Yr=xn?.colorPrimary??"#4A49FF",ed=xn?.colorPrimaryHover??Qo(Yr,.12),Ii=xn?.colorText??"#262833",Ri={fontSize:Qs,fontFamily:el,fontWeight:tl,color:Xc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Yo={marginTop:"0.375rem",...Ri,fontSize:"0.75rem",lineHeight:1.4,color:Zs},td={"--flopay-input-placeholder-color":Qc,"--flopay-input-font-size":Qs,"--flopay-input-font-family":el,"--flopay-input-font-weight":String(tl)},Jo=S.cardFormContainer??{},Ei=Jo.padding??(Ko?"0":"1rem"),_i=Jo.borderRadius??Zt,nd=It&&or?p(Ti,{capture:It,html:or.html,messageToken:or.messageToken,expectedOrigin:or.expectedOrigin,verificationRequired:or.verificationRequired,theme:Ke,submitLabel:O,onReady:()=>{if(!Lr&&!ae||typeof document>"u")return;let r=()=>{let W=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(W){zn.current=!0;try{W.focus()}finally{zn.current=!1}}};rr.current||r()},onError:r=>{r&&or.verificationRequired&&l.current==="idle"&&(Nr.current=!0),ue(r)},onValidation:r=>{let g=l.current;(g==="idle"||g==="validation-window")&&(ue(r),r&&l.current==="validation-window"&&(R.current&&(clearTimeout(R.current),R.current=null),l.current="idle",x(null)))}},an):p("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),nl=Xe("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&_r()},style:{backgroundColor:wi,borderRadius:_i,...Jo,padding:Ei,...td,display:"flex",flexDirection:"column"},children:[p("style",{children:`
|
|
5
5
|
.flopay-shared-input::placeholder {
|
|
6
6
|
color: var(--flopay-input-placeholder-color);
|
|
7
7
|
opacity: 1;
|
|
@@ -9,13 +9,13 @@ ${At.join(`
|
|
|
9
9
|
font-family: var(--flopay-input-font-family);
|
|
10
10
|
font-weight: var(--flopay-input-font-weight);
|
|
11
11
|
}
|
|
12
|
-
`}),
|
|
13
|
-
`)}):null,
|
|
14
|
-
`)}):null,fl=He==="apm-expanding"||He==="apm-form"||He==="apm-collapsing",Po;He==="apm-expanding"?Po=fc:He==="apm-collapsing"&&(Po=gc);let Na=ln?Mc(Si,ln,ge):null;if(_e==="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=Yu:(He==="collapsing"||He==="apm-collapsing")&&(ve=Gu);let Z;return He==="expanding"?Z=fc:He==="collapsing"&&(Z=gc),Ze("form",{onSubmit:_i,className:$,noValidate:!0,style:{position:"relative"},children:[y(za,{}),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?Xu:{},...ve?{animation:ve,pointerEvents:"none"}:{}},children:[ml("flopay-direct-paypal-gate-debug"),yl("flopay-stripe-gate-debug"),Wo&&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(Ga,{sessionId:e,nonce:t,billingApiUrl:st,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:De,clientId:ft.clientId,environment:ft.environment,currency:Ct.toUpperCase(),isSubscription:Tt,providerObjectType:We,approvalPresentation:Ma==="popup"?void 0:Ma,onTokenizedBody:Bn,onComplete:s,onErrorChange:Pe,onDecline:f,onTechnicalFailure:po,onButtonClick:ne,runBeforeButtonClick:sr,isProcessing:A,onLoadStateChange:wi,onInitializationStateChange:Ii,session:ut,existingOrderId:c?.orderId,debug:L},c?.orderId??"fresh")})]}),Vo&&y(io,{stripe:Ho,options:Ls,children:y(vc,{sessionId:e,nonce:t,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:De,billingApiUrl:st,onTokenizedBody:Bn,onErrorChange:Pe,isProcessing:A,onButtonClick:ne,onDecline:f,onTechnicalFailure:po,runBeforeButtonClick:sr,onLoadStateChange:Ws,placeholderBorderRadius:Qr,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:De,billingApiUrl:st,intentKind:Ne>0?"payment":"setup",expressMethods:yo,onTokenizedBody:Bn,onErrorChange:Pe,onButtonClick:ne,onDecline:f,onTechnicalFailure:po,runBeforeButtonClick:sr,onLoadStateChange:Vs,placeholderBorderRadius:Qr,popupCapabilityOwner:p,externalTelemetryContext:ee})}):null,!fo&&Zs?y("div",{style:{height:aa,borderRadius:Qr,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:De,billingApiUrl:st,paymentElementMethods:Ta,stripeInstance:jn,paymentElementBaseOptions:Si,futureUseSession:ge,onTokenizedBody:Bn,onErrorChange:Pe,onButtonClick:ne,onDecline:f,runBeforeButtonClick:sr,onLoadStateChange:Ys,isProcessing:A,submitButtonColor:eo,submitButtonBorderRadius:Jt,submitButtonStyle:b.submitButton,onExpandApm:w,expandedApmMethod:ln,themeId:it,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:Qr}}),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:me,resolvedPrimaryColor:eo,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:he=>{!A&&(me||Fn?.colorPrimary)&&(he.currentTarget.style.backgroundColor=od)},onMouseLeave:he=>{(me||Fn?.colorPrimary)&&(he.currentTarget.style.backgroundColor=eo)},onMouseDown:he=>{he.currentTarget.style.transform="scale(0.985)"},onMouseUp:he=>{he.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&&Na&&jn&&y("div",{style:{gridArea:"1 / 1",...Po?{animation:Po}:{},...He==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ze("div",{style:{backgroundColor:Ei,borderRadius:Bi,...Qo,padding:xi},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:_,style:{display:"inline-flex",alignItems:"center",gap:Ti?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:Ai,paddingRight:80,...b.title},children:`Pay with ${Ca(ln)}`})]}),y(io,{stripe:jn,options:Na,children:y(gs,{method:ln,sessionId:e,nonce:t,email:N.email,billingName:[N.firstName,N.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:De,billingApiUrl:st,onTokenizedBody:Bn,onErrorChange:Pe,onDecline:f,onCancel:_,runBeforeButtonClick:sr,onButtonClick:ne,isProcessing:A,submitButtonColor:eo,submitButtonBorderRadius:Jt,submitButtonStyle:b.submitButton,errorText:at})},ln)]})})]})]})}return fl&&ln&&Na&&jn&&se?Ze("form",{onSubmit:_i,className:$,noValidate:!0,style:{position:"relative"},children:[y(za,{}),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:Ei,borderRadius:Bi,...Qo,padding:xi},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:_,style:{display:"inline-flex",alignItems:"center",gap:Ti?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:Ai,paddingRight:80,...b.title},children:`Pay with ${Ca(ln)}`})]}),y(io,{stripe:jn,options:Na,children:y(gs,{method:ln,sessionId:e,nonce:t,email:N.email,billingName:[N.firstName,N.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:De,billingApiUrl:st,onTokenizedBody:Bn,onErrorChange:Pe,onDecline:f,onCancel:_,runBeforeButtonClick:sr,onButtonClick:ne,isProcessing:A,submitButtonColor:eo,submitButtonBorderRadius:Jt,submitButtonStyle:b.submitButton,errorText:at})},ln)]})})]}):Ze("form",{onSubmit:_i,className:$,noValidate:!0,style:{position:"relative"},children:[y(za,{}),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"),Wo&&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(Ga,{sessionId:e,nonce:t,billingApiUrl:st,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:De,clientId:ft.clientId,environment:ft.environment,currency:Ct.toUpperCase(),isSubscription:Tt,providerObjectType:We,approvalPresentation:Ma==="popup"?void 0:Ma,onTokenizedBody:Bn,onComplete:s,onErrorChange:Pe,onDecline:f,onTechnicalFailure:po,onButtonClick:ne,runBeforeButtonClick:sr,isProcessing:A,onLoadStateChange:wi,onInitializationStateChange:Ii,session:ut,existingOrderId:c?.orderId,debug:L},c?.orderId??"fresh")})]}),Vo&&y(io,{stripe:Ho,options:Ls,children:y(vc,{sessionId:e,nonce:t,email:N.email,billingName:ct||void 0,onBuyerIdentityReady:De,billingApiUrl:st,onTokenizedBody:Bn,onErrorChange:Pe,isProcessing:A,onButtonClick:ne,onDecline:f,onTechnicalFailure:po,runBeforeButtonClick:sr,onLoadStateChange:Ws,placeholderBorderRadius:Qr,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:De,billingApiUrl:st,intentKind:Ne>0?"payment":"setup",expressMethods:yo,onTokenizedBody:Bn,onErrorChange:Pe,onButtonClick:ne,onDecline:f,onTechnicalFailure:po,runBeforeButtonClick:sr,onLoadStateChange:Vs,placeholderBorderRadius:Qr,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:Ta,stripeInstance:jn,paymentElementBaseOptions:Si,futureUseSession:ge,onTokenizedBody:Bn,onErrorChange:Pe,onButtonClick:ne,onDecline:f,runBeforeButtonClick:sr,onLoadStateChange:Ys,isProcessing:A,submitButtonColor:eo,submitButtonBorderRadius:Jt,submitButtonStyle:b.submitButton,themeId:it,onExpandApm:w,expandedApmMethod:ln,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:Qr}})]}),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",yi=new Map,pi=new Map;function Bc(e,t){t.settled&&t.consumers===0&&yi.get(e)===t&&yi.delete(e)}function pp(e,t,n){let r=pi.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};pi.set(e,i);let s=()=>{pi.get(e)===i&&pi.delete(e)};return o.then(s,s),o}function Sa(e){return new Promise(t=>setTimeout(t,e))}function mi(e,t,n){let r=Ha({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:qc,enabled:t!==!1});return r.beginCheckout(n),r}function wa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function _s(e,t,n,r,o,i){let s=mi(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),wa(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 Rs(e){return!e||e.data.stripe?.publishableKey?!1:!!jc(e)?.clientId}var mp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function yp(e){return new ap(mp,{publishableKey:"provider_unavailable",...e})}async function Es(e,t){let{publishableKey:n,paypalPublishableKey:r}=as(e);return{...await is({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function xs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function fp(){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 gp(){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 hp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Lc(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 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:W,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:je,buttonsStyles:_e,cardButtonContent:it,cardBackButtonContent:zt,cardTitleContent:ye,showSecurityFooter:Me,onButtonClick:Pt,onBeforeButtonClick:Te,enableAVS:Ve,cardFieldOrder:Re,cardPreFormSlot:ne,avsLayout:$e,submitLabel:Ke,className:yt,initialErrorMessage:be=null,initialPayPalOrderId:fe,children:le,checkoutMode:F,confirmLabel:Se,renderConfirmButton:ze,onSessionCompleted:xe}){let V=cp(r),vt=Zn(()=>zc(ke),[ke]),qe=i??vt?.appearance,Ae=n?"embedded_checkout":"standard_checkout",Xe=As(le,J),[Be,Qe]=Ht(null),[Ne,Ct]=Ht(null),Vt=Ft(null),ft=Ft(null),Tt=Ft(0),[T,re]=Ht(null),Oe=Ft(null),[L,we]=Ht(null),gt=Zn(()=>n?Ao(n):"",[n]),Le=n?`create:${gt}`:`session:${e??""}`,It=Lc(L),M=Ft(new Set),p=Ft(Le),g=Ft(Le);ta(()=>{g.current=Le,p.current!==Le&&(p.current=Le,M.current.clear())},[Le]);let D=hn(w=>{if(g.current===Le){if(Wi.has(w.name)){if(M.current.has(w.name))return;M.current.add(w.name)}Bt(()=>v?.(w))}},[Le,v]),x=Ro(D,Le),ee=Ft(!1),ut=hn(w=>{if(ee.current)return;let _=w.gateway||!It?w:{...w,gateway:It};D(_)},[D,It]);pr(()=>{x({class:"lifecycle",name:"checkout.mount"})},[x]);let[ge,We]=Ht(e??""),X=e??ge,qt=n?"":X,[bt,At]=Ht(!0),[st,ce]=Ht(null),[kn,Nn]=Ht(0),[pn,jt]=Ht("full"),[On,Ln]=Ht(!1),[fn,Mt]=Ht(be),[Ge,Ue]=Ht(null),[_n,kt]=Ht(null),[Un,mn]=Ht(!1),[$t,Zt]=Ht(void 0),[Qn,Wn]=Ht(""),[Qt,_t]=Ht(!1),[en,nn]=Ht(!1),[Dt,an]=Ht(!1),Ot=Ft(null),rn=Ft(0),Nt=Ft(void 0),[G,er]=Ht("loading"),[tr,nr]=Ht(0),tn=Ft(!1),Rn=Ft(!1),vn=Ft(!1),pe=Ft(null),et=Ft(null),m=Zn(()=>({checkoutMode:F??pn,layout:hp(le,J)}),[F,le,pn,J]),Fe=Ft(u);Fe.current=u;let H=Ft(S);H.current=S;let gn=Ft(W);gn.current=W;let zn=hn(w=>ti(pe,async _=>{try{return await w(_)}catch(O){throw _.aborted?Gr(O):O}}),[]);pr(()=>()=>{pe.current?.abort(),pe.current=null},[]);let Gt=hn((w,_)=>{Vt.current=w,Ct(w),Oe.current=_,re(_)},[]),En=hn(()=>{let w=ft.current;w&&(ft.current=null,w.destroy())},[]);pr(()=>{un(Ne)?.setCheckoutContext(m),T&&T!==Ne&&un(T)?.setCheckoutContext(m)},[Ne,T,m]);let tt=Ft(xe);tt.current=xe;let rr=hn(w=>{er(w),!(w!=="exhausted"||vn.current)&&(vn.current=!0,H.current?.(new Pn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Xr=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 Rt=Zn(()=>n?Ao(n,!0):"",[n]),Tn=Zn(()=>Qn===Rt?$t:void 0,[$t,Qn,Rt]),mr=Zn(()=>n?qi(n,Tn):void 0,[n,Tn]),Hn=F??mr?.checkoutMode??"full",Yt=Zn(()=>mr?{...mr,checkoutMode:Hn}:void 0,[mr,Hn]);pr(()=>{Zt(void 0),Wn(Rt),Nt.current=void 0,Ot.current=null,an(!1)},[Rt]),pr(()=>{Mt(be)},[be]);let or=hn((w,_,O)=>{Bt(()=>{gn.current?.(dn(w,_,O))})},[]),An=hn(async(w,_)=>{Mt(null),kt(null),mn(!1),Ue("processing");let O=_?.sessionId??w.id,R=w.clientSecret||t,nt=Lc(w),pt=Vt.current??Oe.current,j=un(pt),Ee=pt?null:mi(V,o,m),B={log:me=>{j?j.log(me):Ee?.log(me)},error:me=>{j?j.error(me):Ee?.error(me)},terminal:me=>{j?j.terminal(me):Ee?.terminal(me)},performance:me=>{j?j.performance(me):Ee?.performance(me)},now:()=>j?.now()??Ee?.now()??0,elapsed:me=>j?.elapsed(me)??Math.max(0,(Ee?.now()??me)-me)},d=B.now(),c=!!(_?.initialAutoProcessingError||_?.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,De=()=>{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 me=sc(_?.initialAutoProcessingError),b=_?.initialAutoProcessingError?.type==="3ds_required"&&!_.initialAutoProcessingError.threeDSecureToken&&_.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:_.initialAutoProcessingError.nextActionRedirectUrl}:null,lt,ie=te=>(Q(),zn(A=>xo(te,{billingApiUrl:V,sessionId:O,nonce:R,session:w,signal:A})));if(b)lt=await ie(b);else if(me)Q(),me.type==="paypal_redirect_required"&&et.current?.publishableKey&&Nc({sessionId:O,publishableKey:et.current.publishableKey,paypalPublishableKey:et.current.paypalPublishableKey}),lt=await zn(te=>oi(me,{flopay:Vt.current,paypalFlopay:Oe.current,attempt3DS:_?.attempt3DS,billingApiUrl:V,sessionId:O,session:w,telemetry:!1,signal:te})),me.type==="paypal_redirect_required"&&Ts();else if(_?.initialAutoProcessingPending){let te=_.initialAutoProcessingPending,A=new ui(V,{telemetry:!1}),Y=await zn(Ie=>A.waitForCheckoutSessionCompletion(te.sessionId,{initialDelayMs:te.retryAfterMs,nonce:R,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 Io(N);lt=Br(N,O)}}else{if(_?.initialAutoProcessingError)throw wr(_.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:_.initialAutoProcessingError.checkoutMethod});if(_?.fromCreateSession)return _?.fallbackToFull&&(jt("full"),Oc("full")),!1;{let te=await Bo({billingApiUrl:V,sessionId:O,session:w,nonce:R,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=>oi(te,{flopay:Vt.current,paypalFlopay:Oe.current,attempt3DS:_?.attempt3DS,billingApiUrl:V,sessionId:O,session:w,telemetry:!1,signal:A})),te.type==="paypal_redirect_required"&&Ts())}}O&&Mo(O),De(),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"),Ue("success"),await Sa(600),at=()=>Fe.current?.(lt)}catch(me){let b=qr(ga(me),O);if(b.code==="three_ds_aborted")return!1;let lt=b.checkoutMethod??fa;Mt(b.message),kt(b.message),mn(!1),_?.fallbackToFull&&(B.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),jt("full"),Oc("full")),De();let ie=b.statusCode===void 0?void 0:up(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(me,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(()=>H.current?.(b)),or(lt,b,{code:b.code,declineCode:b.declineCode}),Ue("error"),await Promise.allSettled([Sa(400),_?.ensureProvidersReady?_.ensureProvidersReady():Promise.resolve()]),c&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{De(),Ee&&wa(Ee),Ue(null),kt(null)}return Bt(at),!0},[or,x,t,V,zn,o,m]);pr(()=>{if(typeof window>"u"||Rn.current)return;let w=new URLSearchParams(window.location.search),_=w.get("payment_intent_client_secret");if(!_)return;let O=fp();O&&(Rn.current=!0,(async()=>{let R,nt=0;Mt(null),kt(null),Ue("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 is({publishableKey:O.publishableKey,paypalPublishableKey:O.paypalPublishableKey,billingApiUrl:V,locale:s,telemetry:o});R=un(j??pt),R?.setCheckoutContext(m),nt=R?.now()??0,R?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),R?.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(_);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 De=(await new ui(V,{telemetry:!1}).getUnifiedCheckoutSession(O.sessionId)).data.session;if(De&&De.status!=="complete"){let at=await Bo({billingApiUrl:V,sessionId:O.sessionId,session:De,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),R?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),R?.performance({stage:"redirect_resume",durationMs:R.elapsed(nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),R?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ue("success"),await Sa(600),Bt(()=>Fe.current?.({status:E,paymentIntentId:B.id,paymentMethodId:I,checkoutMethod:"paypal"}))}catch(pt){let j=qr(ga(pt),O.sessionId),Ee=j.checkoutMethod??"paypal",B=!!(j.declineCode||j.code?.toLowerCase().includes("declin"));if(R)R.performance({stage:"redirect_resume",durationMs:R.elapsed(nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?R.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):R.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let d=mi(V,o,m);d.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),wa(d)}else _s(V,o,m,"REDIRECT_RESUME_FAILED","redirect_resume");Mt(j.message),kt(j.message),Bt(()=>H.current?.(j)),or(Ee,j,{code:j.code,declineCode:j.declineCode}),Ue("error"),await Sa(400)}finally{Ts(),gp(),Ue(null),kt(null),Ln(!1)}})())},[or,s,V,o,m]);let _r=Ft(null),Mn=Zn(()=>Yt?Ao(Yt):"",[Yt]),yr=Ft(Yt);yr.current=Yt,pr(()=>{We(e??"")},[e]),pr(()=>{tn.current=!1,Mt(be),kt(null),mn(!1),Ue(null)},[Mn,be,e]);async function fr(w,_,O){let R=mi(V,o,m),nt=new ui(V,{telemetry:!1}),pt=!1;try{let j=w.idempotencyKey===void 0?void 0:xc(w.idempotencyKey),Ee=Zi(_,O),B=Qi(_,O);Ee?.canonicalIdentity===O&&B&&B.canonicalIdentity===void 0&&(Za(_,O,B.idempotencyKey),B={...B,canonicalIdentity:O});let d=j??(B?.canonicalIdentity===O?B.idempotencyKey:void 0),c,I=!1;R.log({name:Ee?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let E=Ee?.sid??null,Q=null,ae,De,at=!1;if(E)try{Q=await nt.getUnifiedCheckoutSession(E,Ee?.nonce),Ee&&Ee.canonicalIdentity===void 0&&(ec(Q.data.session,w)?(Xa(_,O,E,Ee.nonce??Q.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(Za(_,O,B.idempotencyKey),d??(d=B.idempotencyKey))):(Ja(_,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&&(De=wo(nt,E,ie,w.account)),E&&Q&&b==="complete"){if(es(E))return{sid:E,result:Q};Ja(_,O),E=null,Q=null,I=!0}}catch{R.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ee?.canonicalIdentity===void 0?(Ja(_,O),d=j):Ya(_,O),E=null}if(!E){!j&&(I||!d)&&(d=xc(),c=d),d&&Za(_,O,d);let b=R.now(),lt=0;R.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:As(le,J)};Object.defineProperty(ie,ip,{configurable:!1,enumerable:!1,value:{onAttempt:Y=>{lt=Math.max(lt,Y)}}});let te=()=>{Fc(R,"session_create",b,lt)},A=Y=>{Dc(R,Y,"session_create",b,lt)&&x({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(lp(ie)){let Y=await nt.createDetachedSession(ie);Y.claimed.catch(()=>{}),Q=Y.shell,E=Y.sessionId,De=Y.claim;let N=R.now();R.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&&Xa(_,O,Ie,ct.data.session?.clientSecret??Y.nonce),Fc(R,"session_claim",N),te(),ct},ct=>{throw Ya(_,O),Dc(R,ct,"session_claim",N,0)&&x({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),ct}).finally(()=>wa(R)),ae.catch(()=>{}),pt=!0,R.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),R.performance({stage:"session_shell",durationMs:R.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&&Xa(_,O,E,Q.data.session?.clientSecret)}let me=Q?.data.session;return!De&&E&&me?.buyerIdentified===!1&&me.clientSecret&&(De=wo(nt,E,me.clientSecret,w.account)),{sid:E??"",result:Q,sdkGeneratedIdempotencyKey:c,...ae?{claimed:ae}:{},...De?{claim:De}:{},...at?{claimRequiresIdentity:!0}:{}}}finally{pt||wa(R)}}let Rr=Ft(fr);ta(()=>{Rr.current=fr},[fr]);let qn=hn(async(w,_)=>{let O=yr.current;if(!O)throw new Pn("createSession is required to bootstrap checkout.","validation_error");let R=qi(O,w),nt=Ao(R),pt=Ql(R),j=yi.get(nt);if(!j){let d={canonicalIdentity:nt,promise:Rr.current(R,pt,nt),consumers:0,settled:!1};j=d,yi.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))};_?.(B);try{let d=await j.promise;_r.current=nt,w&&(Wn(Rt),Zt(me=>Nl(me,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&&We(c),E){rn.current+=1;let me=rn.current;Ot.current=E,nn(!0),E.then(b=>{rn.current===me&&(Ot.current===E&&(Ot.current=null),Qe(b),b.data.session&&we(b.data.session),nn(!1),an(!1))},b=>{rn.current===me&&(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:De,paypalFlopay:at}=await Es(I,{billingApiUrl:V,locale:s,telemetry:o});return Gt(De,at),At(!1),d}catch(d){throw _r.current===nt&&(_r.current=null),d}finally{_||B()}},[Rt,Gt,s,V,o]),Vn=Ft(An);Vn.current=An;let Er=Ft(qn);Er.current=qn;let xt=hn(async w=>{if(!Pp(w)||Qt)return{sessionId:ge,session:L};_t(!0);try{let _=await qn(w);return{sessionId:_.sid,session:_.result.data.session??null}}finally{_t(!1)}},[qn,Qt,ge,L]),Cn=hn(async w=>{let _=Nt.current;if(!_)return;let O=rn.current,R=await _(w);rn.current===O&&(Qe(R),R.data.session&&we(R.data.session))},[]),Gn=hn(async()=>{await Ot.current},[]),Tr=hn(async()=>(await Gn(),{proceed:!0}),[Gn]);pr(()=>{let w=!1,_,O=++Tt.current;En(),ce(null),Nn(0);let R=()=>{w=!0,Tt.current===O&&(Tt.current+=1,En())},nt=yr.current;if(Mn&&nt)return jt(Hn),At(!1),_r.current===Mn?R:(we(Ol(nt,F)),(async()=>{let Ee=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),B=Hn==="auto"&&!tn.current&&!Ee;B&&(Mt(null),kt(null),Ue("processing"));try{let d=await Er.current(void 0,Q=>{_=Q}),c=d.result.data.session??null;et.current=as(d.result);let I=Rs(d.result),E=es(d.sid||c?.id);if(!w&&B&&c&&!I&&!E){tn.current=!0,await pp(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),Ue(null),kt(null))}catch(d){if(w)return;let c=ja(d);if(B&&c==="session_auto_completed"){tn.current=!0,Ue("success"),await Sa(600),w||(Bt(()=>{Fe.current?.({status:"succeeded"})}),Ue(null),kt(null));return}B&&(Ue(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{_?.(),_=void 0}})(),()=>{R(),_?.()});At(!0);async function pt(){let Ee=!1,B=null;try{let d=new ui(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(()=>{Fe.current?.(Br(I,X)),tt.current?.(I.successUrl??"")});return}if(I.status==="complete"){At(!1),Bt(()=>{tt.current?.(I.successUrl??"")});return}if(I.status==="expired")throw qa(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 De=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),at=Rs(c);if(Q==="auto"&&!tn.current&&!De&&!at){tn.current=!0;let me=j(c);try{if(await Vn.current(I,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>me,sessionId:X||I.id}),w)return;await me,w||At(!1);return}catch{if(w)return;await me,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;_s(V,o,m,E,Q,ae)}if(c?.stage==="provider_load"&&(F??B?.data.session?.checkoutMode??"full")==="full"&&Fl(B,q,K)){let E=yp({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(()=>H.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(),R},[F,Mn,Hn,qt,t,q,K]);let Ar=hn(async()=>{if(!Be||kn!==1)return;let w=Tt.current;Nn(2);try{let{flopay:_,paypalFlopay:O}=await Es(Be,{billingApiUrl:V,locale:s,telemetry:o});if(Tt.current!==w)return;En(),Gt(_,O),Nn(0)}catch(_){if(Tt.current!==w)return;let{errorCode:O,stage:R,...nt}=Ui(_);_s(V,o,m,O,R,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,fe),Zr=Rs(Be),gr=Zn(()=>{if(!(!Be||!L||!Be.data.stripe?.publishableKey))return{billingApiUrl:V}},[Be,L,V]),Or=!!(n&&!le&&J==="buttons"&&Te&&Hn==="full"),Sn=!!(X&&(L?.vault?.html||zr(L))),cn=Zn(()=>({session:L,loading:bt,error:st,checkoutMode:pn,inlineSessionDraft:Yt,applyInlineSessionPatch:Or?xt:void 0,inlineSessionPatchProcessing:Qt,claimPending:en,claimRequiresIdentity:Dt,claimBuyerIdentity:Cn,waitForDataAttachment:Gn}),[L,bt,st,pn,Yt,Or,xt,Qt,en,Dt,Cn,Gn]),Mr=!!n&&J==="buttons"&&!Zr&&!Sn&&(!Ne||!gr),xn=Ge?de(br,{status:Ge,errorMessage:_n,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,_=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&&_(Lo),K&&(se||z)&&_(Lo),K&&_(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(Cp,{onButtonClick:Pt,showPayPal:q,showStripe:K,showApplePay:se,showGooglePay:z,theme:ke,buttonsTheme:je,buttonsStyles:_e,cardButtonContent:it,cardBackButtonContent:zt,cardTitleContent:ye})}),xn]}):Zr&&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:Xr,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:W,onButtonClick:Pt,runBeforeButtonClick:Tr,onInitializationStateChange:rr,allowAutomaticRetry:tr===0,session:L,telemetry:o,telemetryContext:m,onInstrument:ut,debug:Ce},`${Le}:paypal-init-${tr}`)})]})}),xn]}):pn==="confirm"?on(kr,{children:[de(cr.Provider,{value:cn,children:de(Qa,{flopay:Ne,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}),ze?ze({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"})]})},Le)}),xn]}):(!Ne||!gr)&&!(Sn&&pn==="full")?de(kr,{children:xn}):on(kr,{children:[de(cr.Provider,{value:cn,children:on(Qa,{flopay:Ne,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(vp,{sessionId:X,nonce:L?.clientSecret||void 0,billingApiUrl:V,session:L,submitLabel:Ke,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(sp(L).total*100):0,currency:L?.currency?.toLowerCase()??"usd",onComplete:u,onError:S,onDecline:W,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:je,buttonsStyles:_e,appearance:qe,cardButtonContent:it,cardBackButtonContent:zt,cardTitleContent:ye,onButtonClick:Pt,onBeforeButtonClick:Te,onBuyerIdentityReady:Cn,enableAVS:Ve,...Re?{cardFieldOrder:Re}:{},...ne?{cardPreFormSlot:ne}:{},avsLayout:$e,country:L?.customer?.country,city:L?.customer?.city,state:L?.customer?.state,onCountryChange:$,onZipChange:k,avsCheck:!!Ve,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:As(le,J),className:yt,submitLabel:Ke,directPaypal:bn,isSubscription:L?.mode==="subscription",session:L,dataAttachmentPending:en,dataAttachmentRequiresIdentity:Dt,debug:Ce})]},Le)}),xn]})}function vp({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 Cp({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,W]=Ht(!1),$=Zn(()=>zc(i),[i]),k=Zn(()=>{let C=$?.buttonsLayout??dp(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:()=>W(!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:`
|
|
12
|
+
`}),Ko&&Or&&Xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:u?-2:0},children:[Xe("button",{type:"button",onClick:K,style:{display:"inline-flex",alignItems:"center",gap:ki?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:S.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...S.backButton},"aria-label":"Back to payment methods",children:[p("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...S.backButtonIcon},children:p("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:p("path",{d:"M15 18l-6-6 6-6"})})}),p(vo,{content:Re})]}),Xs?p("div",{style:{flex:1}}):p("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:S.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...S.title},children:p(na,{content:He})})]}),!Ko&&!Xs&&p("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ii,order:u?-3:0,...S.title},children:p(na,{content:He})}),u&&ye&&p("div",{style:{order:-2,width:"100%"},children:ye}),u&&Lr&&Xe("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[p("div",{style:{backgroundColor:yo,border:`1px solid ${Vn(Ta)}`,borderRadius:Zt,padding:"10px"},children:p("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Qt,onChange:r=>{Mt("email"),on.current=r.target.value,Jn(r.target.value)},onPointerDown:()=>Mt("email"),onKeyDown:()=>Mt("email"),onBlur:()=>{Un("email")&&Wn(!0),ao||mi()},disabled:_e,required:!0,"aria-invalid":Ta||void 0,"aria-describedby":Ta?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ri}})}),Ta&&p("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Yo,children:di.empty?"Email address is required":"Enter a valid email address"})]}),ae&&p("div",{style:{order:u?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=qt,g=(D=!1)=>({backgroundColor:yo,border:`1px solid ${Vn(D)}`,borderRadius:Zt,marginTop:"0.5rem",padding:"10px"}),W=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ri}),fe=Tu(r);return Xe(Fo,{children:[Kt(ae.address_line_1,r)&&Xe(Fo,{children:[p("div",{style:g(Vt("line1")),children:p("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Tt,onChange:D=>{Mt("line1"),Bt.current.addressLine1=!0,ln.current=D.target.value,Ve(D.target.value)},onPointerDown:()=>Mt("line1"),onKeyDown:()=>Mt("line1"),onBlur:()=>wn("line1"),disabled:_e,required:!0,"aria-invalid":Vt("line1")||void 0,"aria-describedby":Vt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:W()})}),Vt("line1")&&p("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Yo,children:"Street address is required"})]}),Kt(ae.address_line_2,r)&&p("div",{style:g(),children:p("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Le,onChange:D=>{Bt.current.addressLine2=!0,Ft.current=D.target.value,Rn(D.target.value)},disabled:_e,"data-testid":"flopay-address-line2",style:W()})}),(Kt(ae.city,r)||Kt(ae.state,r))&&Xe("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Kt(ae.city,r)&&p("div",{style:{flex:1,backgroundColor:yo,borderTop:`1px solid ${Vn(Vt("city"))}`,borderRight:`1px solid ${Vn(Vt("city"))}`,borderBottom:`1px solid ${Vn(Vt("city"))}`,borderLeft:`1px solid ${Vn(Vt("city"))}`,padding:"10px",borderTopLeftRadius:Zt,borderBottomLeftRadius:Zt,...Kt(ae.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Zt}},children:p("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:kt,onChange:D=>{Mt("city"),Bt.current.city=!0,fn.current=D.target.value,On(D.target.value)},onPointerDown:()=>Mt("city"),onKeyDown:()=>Mt("city"),onBlur:()=>wn("city"),disabled:_e,required:!0,"aria-invalid":Vt("city")||void 0,"aria-describedby":Vt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:W()})}),Kt(ae.state,r)&&p("div",{style:{flex:1,backgroundColor:yo,borderTop:`1px solid ${Vn(Vt("state"))}`,borderRight:`1px solid ${Vn(Vt("state"))}`,borderBottom:`1px solid ${Vn(Vt("state"))}`,borderLeft:`1px solid ${Vn(Vt("state"))}`,padding:"10px",borderTopRightRadius:Zt,borderBottomRightRadius:Zt,...Kt(ae.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Vn(Vt("state")||Vt("city"))}`}:{borderRadius:Zt}},children:fe?Xe("select",{id:"flopay-billing-state",name:"billing-state",value:mn,onChange:D=>{Mt("state"),Bt.current.state=!0,Dt.current=D.target.value,jt(D.target.value)},onPointerDown:()=>Mt("state"),onKeyDown:()=>Mt("state"),onBlur:()=>wn("state"),disabled:_e,autoComplete:"billing address-level1",required:!0,"aria-invalid":Vt("state")||void 0,"aria-describedby":Vt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...W(),cursor:"pointer"},children:[p("option",{value:"",children:Yi(r)}),fe.map(D=>p("option",{value:D.code,children:D.name},D.code))]}):p("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Yi(r),autoComplete:"billing address-level1",value:mn,onChange:D=>{Mt("state"),Bt.current.state=!0,Dt.current=D.target.value,jt(D.target.value)},onPointerDown:()=>Mt("state"),onKeyDown:()=>Mt("state"),onBlur:()=>wn("state"),disabled:_e,required:!0,"aria-invalid":Vt("state")||void 0,"aria-describedby":Vt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:W()})})]}),Vt("city")&&p("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Yo,children:"City is required"}),Vt("state")&&Xe("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Yo,children:[Yi(r)," is required"]}),(Kt(ae.country,r)||Kt(ae.postal_code,r))&&Xe("div",{style:{display:"flex",flexDirection:re==="column"?"column":"row",gap:re==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Kt(ae.country,r)&&p("div",{style:{flex:re==="row"?1:void 0,backgroundColor:yo,borderTop:`1px solid ${Go}`,borderRight:`1px solid ${Go}`,borderBottom:`1px solid ${Go}`,borderLeft:`1px solid ${Go}`,padding:"10px",...re==="row"&&Kt(ae.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:Zt,borderBottomLeftRadius:Zt,borderRight:"none"}:{borderRadius:Zt}},children:Xe("select",{id:"flopay-billing-country",name:"billing-country",value:qt,onChange:D=>{Bt.current.country=!0,Cn.current=D.target.value,Fn(D.target.value),qe?.(D.target.value),Dt.current="",jt("")},disabled:_e,autoComplete:"billing country","data-testid":"flopay-country",style:{...W(),cursor:"pointer"},children:[qt===""?p("option",{value:"",children:"Select country"}):null,wu.map(D=>Xe("option",{value:D.code,children:[D.flag," ",D.name]},D.code))]})}),Kt(ae.postal_code,r)&&p("div",{style:{flex:re==="row"?1:void 0,backgroundColor:yo,border:`1px solid ${Zc}`,padding:"10px",...re==="row"&&Kt(ae.country,r)?{borderRadius:"0",borderTopRightRadius:Zt,borderBottomRightRadius:Zt}:{borderRadius:Zt}},children:p("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:ns(qt),autoComplete:"billing postal-code",value:Dn,onChange:D=>{Mt("zip"),Bt.current.zip=!0,xt.current=D.target.value,hn(D.target.value),Ee?.(D.target.value)},onPointerDown:()=>Mt("zip"),onKeyDown:()=>Mt("zip"),onBlur:()=>{Un("zip")&&Tn(!0)},disabled:_e,required:Ln.required,"aria-invalid":Ma||void 0,"aria-describedby":Ma?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:W()})})]}),Ma&&p("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Yo,children:Ln.empty?`${ns(r)} is required`:yp(r)})]})})()}),u&&nd,rt&&p(Eo,{margin:"0.75rem 0",styleOverride:S.errorBanner,children:rt})]}),Aa={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},rl=r=>F?!P||!br?p("pre",{"data-testid":r,style:Aa,children:"FloPay/DirectPayPal-debug - not enabled"}):p("pre",{"data-testid":r,style:Aa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${P}`,` directPaypalConfigured=${br}`,` inAppBrowserDetected=${String(Ra)}`,` shouldRenderDirectPayPal=${jo}`,` shouldRenderStripePayPal=${Wo}`,` hasPaypalStripeInstance=${!!ws}`].join(`
|
|
13
|
+
`)}):null,ol=r=>F?!he||!qn?p("pre",{"data-testid":r,style:Aa,children:"FloPay/Stripe-debug - not enabled"}):p("pre",{"data-testid":r,style:Aa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${he}`,` currency=${bt}`,` amountInCents=${Uo}`,` enabledPaymentMethods: ${JSON.stringify(Ie??[])}`,` enabledPaymentMethodsProvided=${qo}`,` hasEnabledMethods=${Sa}`,` expressMethods: ${JSON.stringify(ka)}`,` walletExpressMethods: ${JSON.stringify(uo)}`,` paymentElementMethods: ${JSON.stringify(gi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ia)}`,` hasStripeInstance=${!!qn}`,` shouldRenderWallets=${po}`,` shouldRenderPaymentElement=${Ho}`].join(`
|
|
14
|
+
`)}):null,al=tt==="apm-expanding"||tt==="apm-form"||tt==="apm-collapsing",fo;tt==="apm-expanding"?fo=pc:tt==="apm-collapsing"&&(fo=yc);let xa=cn?Ec(hi,cn,me):null;if(ze==="buttons"){let r=tt==="buttons"||tt==="expanding"||tt==="apm-expanding",g=tt==="expanding"||tt==="card"||tt==="collapsing",W=Pt===void 0?{boxSizing:"border-box",height:ta,padding:"0 1rem"}:{padding:"0.9rem 1rem"},fe;tt==="expanding"||tt==="apm-expanding"?fe=cp:(tt==="collapsing"||tt==="apm-collapsing")&&(fe=lp);let D;return tt==="expanding"?D=pc:tt==="collapsing"&&(D=yc),Xe("form",{onSubmit:Ci,className:ne,noValidate:!0,style:{position:"relative"},children:[p(Oa,{}),de&&p(Sr,{status:de,errorMessage:rt,authorized:Xn}),Xe("div",{style:{display:"grid"},children:[Xe("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!fe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!fe?up:{},...fe?{animation:fe,pointerEvents:"none"}:{}},children:[rl("flopay-direct-paypal-gate-debug"),ol("flopay-stripe-gate-debug"),jo&&yt&&Xe(Fo,{children:[le&&p("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),p(sa.Provider,{value:d,children:p(Wa,{sessionId:e,nonce:t,billingApiUrl:at,email:Ze.email,billingName:oo||void 0,onBuyerIdentityReady:Be,clientId:yt.clientId,environment:yt.environment,currency:bt.toUpperCase(),isSubscription:Et,providerObjectType:We,approvalPresentation:Ea==="popup"?void 0:Ea,onTokenizedBody:An,onComplete:s,onErrorChange:ue,onDecline:f,onTechnicalFailure:lo,onButtonClick:Q,runBeforeButtonClick:sr,isProcessing:_e,onLoadStateChange:Pi,onInitializationStateChange:vi,session:ft,existingOrderId:le?.orderId,debug:F},le?.orderId??"fresh")})]}),Wo&&p(no,{stripe:$o,options:Rs,children:p(fc,{sessionId:e,nonce:t,email:Ze.email,billingName:oo||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,onTokenizedBody:An,onErrorChange:ue,isProcessing:_e,onButtonClick:Q,onDecline:f,onTechnicalFailure:lo,runBeforeButtonClick:sr,onLoadStateChange:Ds,placeholderBorderRadius:Gr,popupCapabilityOwner:d,externalTelemetryContext:Ws,presentationMode:co})}),po?p(no,{stripe:qn,options:Is,children:p(hc,{sessionId:e,nonce:t,email:Ze.email,billingName:oo||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,intentKind:De>0?"payment":"setup",expressMethods:uo,onTokenizedBody:An,onErrorChange:ue,onButtonClick:Q,onDecline:f,onTechnicalFailure:lo,runBeforeButtonClick:sr,onLoadStateChange:Ns,placeholderBorderRadius:Gr,popupCapabilityOwner:d,externalTelemetryContext:J})}):null,!po&&js?p("div",{style:{height:ta,borderRadius:Gr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Ho&&p(Pc,{sessionId:e,nonce:t,email:Ze.email,billingName:[Ze.firstName,Ze.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,paymentElementMethods:Ia,stripeInstance:qn,paymentElementBaseOptions:hi,futureUseSession:me,onTokenizedBody:An,onErrorChange:ue,onButtonClick:Q,onDecline:f,runBeforeButtonClick:sr,onLoadStateChange:zs,isProcessing:_e,submitButtonColor:Yr,submitButtonBorderRadius:Zt,submitButtonStyle:S.submitButton,onExpandApm:it,expandedApmMethod:cn,themeId:ct,buttonAppearance:{backgroundColor:S.cardButton?.backgroundColor,borderColor:S.cardInputBorder,textColor:S.cardButton?.color,borderRadius:Gr}}),u&&p("button",{type:"button",onClick:async()=>{_e||!(await sr("card")).proceed||(Q?.("card"),j())},disabled:_e,style:{width:"100%",...W,...S.cardButton,...ds({themeBundle:Z,resolvedPrimaryColor:Yr,resolvedBorderRadius:Zt,submitButtonStyle:S.submitButton,explicitPrimaryColor:xn?.colorPrimary}),fontSize:S.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:_e?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:_e?.6:1},onMouseEnter:X=>{!_e&&(Z||xn?.colorPrimary)&&(X.currentTarget.style.backgroundColor=ed)},onMouseLeave:X=>{(Z||xn?.colorPrimary)&&(X.currentTarget.style.backgroundColor=Yr)},onMouseDown:X=>{X.currentTarget.style.transform="scale(0.985)"},onMouseUp:X=>{X.currentTarget.style.transform="scale(1)"},children:p(Po,{content:Pt})}),rt&&tt==="buttons"&&p(Eo,{margin:"0.25rem 0",styleOverride:S.errorBanner,children:rt})]}),u&&g&&p("div",{style:{gridArea:"1 / 1",...D?{animation:D}:{},...tt==="collapsing"?{pointerEvents:"none"}:{}},children:nl}),he&&al&&cn&&xa&&qn&&p("div",{style:{gridArea:"1 / 1",...fo?{animation:fo}:{},...tt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Xe("div",{style:{backgroundColor:wi,borderRadius:_i,...Jo,padding:Ei},children:[Xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Xe("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:ki?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:S.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...S.backButton},"aria-label":"Back to payment methods",children:[p("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...S.backButtonIcon},children:p("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:p("path",{d:"M15 18l-6-6 6-6"})})}),p(vo,{content:Re})]}),p("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:S.titleFontSize??"1.05rem",color:Ii,paddingRight:80,...S.title},children:`Pay with ${ga(cn)}`})]}),p(no,{stripe:qn,options:xa,children:p(as,{method:cn,sessionId:e,nonce:t,email:Ze.email,billingName:[Ze.firstName,Ze.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,onTokenizedBody:An,onErrorChange:ue,onDecline:f,onCancel:Wt,runBeforeButtonClick:sr,onButtonClick:Q,isProcessing:_e,submitButtonColor:Yr,submitButtonBorderRadius:Zt,submitButtonStyle:S.submitButton,errorText:rt})},cn)]})})]})]})}return al&&cn&&xa&&qn&&he?Xe("form",{onSubmit:Ci,className:ne,noValidate:!0,style:{position:"relative"},children:[p(Oa,{}),de&&p(Sr,{status:de,errorMessage:rt,authorized:Xn}),p("div",{style:{...fo?{animation:fo}:{},...tt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Xe("div",{style:{backgroundColor:wi,borderRadius:_i,...Jo,padding:Ei},children:[Xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Xe("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:ki?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:S.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...S.backButton},"aria-label":"Back to payment methods",children:[p("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...S.backButtonIcon},children:p("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:p("path",{d:"M15 18l-6-6 6-6"})})}),p(vo,{content:Re})]}),p("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:S.titleFontSize??"1.05rem",color:Ii,paddingRight:80,...S.title},children:`Pay with ${ga(cn)}`})]}),p(no,{stripe:qn,options:xa,children:p(as,{method:cn,sessionId:e,nonce:t,email:Ze.email,billingName:[Ze.firstName,Ze.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,onTokenizedBody:An,onErrorChange:ue,onDecline:f,onCancel:Wt,runBeforeButtonClick:sr,onButtonClick:Q,isProcessing:_e,submitButtonColor:Yr,submitButtonBorderRadius:Zt,submitButtonStyle:S.submitButton,errorText:rt})},cn)]})})]}):Xe("form",{onSubmit:Ci,className:ne,noValidate:!0,style:{position:"relative"},children:[p(Oa,{}),de&&p(Sr,{status:de,errorMessage:rt,authorized:Xn}),Xe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[rl("flopay-direct-paypal-gate-debug-default"),ol("flopay-stripe-gate-debug-default"),jo&&yt&&Xe(Fo,{children:[le&&p("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),p(sa.Provider,{value:d,children:p(Wa,{sessionId:e,nonce:t,billingApiUrl:at,email:Ze.email,billingName:oo||void 0,onBuyerIdentityReady:Be,clientId:yt.clientId,environment:yt.environment,currency:bt.toUpperCase(),isSubscription:Et,providerObjectType:We,approvalPresentation:Ea==="popup"?void 0:Ea,onTokenizedBody:An,onComplete:s,onErrorChange:ue,onDecline:f,onTechnicalFailure:lo,onButtonClick:Q,runBeforeButtonClick:sr,isProcessing:_e,onLoadStateChange:Pi,onInitializationStateChange:vi,session:ft,existingOrderId:le?.orderId,debug:F},le?.orderId??"fresh")})]}),Wo&&p(no,{stripe:$o,options:Rs,children:p(fc,{sessionId:e,nonce:t,email:Ze.email,billingName:oo||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,onTokenizedBody:An,onErrorChange:ue,isProcessing:_e,onButtonClick:Q,onDecline:f,onTechnicalFailure:lo,runBeforeButtonClick:sr,onLoadStateChange:Ds,placeholderBorderRadius:Gr,popupCapabilityOwner:d,externalTelemetryContext:Ws,presentationMode:co})}),po&&p(no,{stripe:qn,options:Is,children:p(hc,{sessionId:e,nonce:t,email:Ze.email,billingName:oo||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,intentKind:De>0?"payment":"setup",expressMethods:uo,onTokenizedBody:An,onErrorChange:ue,onButtonClick:Q,onDecline:f,onTechnicalFailure:lo,runBeforeButtonClick:sr,onLoadStateChange:Ns,placeholderBorderRadius:Gr,popupCapabilityOwner:d,externalTelemetryContext:J})}),Ho&&p(Pc,{sessionId:e,nonce:t,email:Ze.email,billingName:[Ze.firstName,Ze.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:at,paymentElementMethods:Ia,stripeInstance:qn,paymentElementBaseOptions:hi,futureUseSession:me,onTokenizedBody:An,onErrorChange:ue,onButtonClick:Q,onDecline:f,runBeforeButtonClick:sr,onLoadStateChange:zs,isProcessing:_e,submitButtonColor:Yr,submitButtonBorderRadius:Zt,submitButtonStyle:S.submitButton,themeId:ct,onExpandApm:it,expandedApmMethod:cn,buttonAppearance:{backgroundColor:S.cardButton?.backgroundColor,borderColor:S.cardInputBorder,textColor:S.cardButton?.color,borderRadius:Gr}})]}),u&&(Kc||Vc||Gc)&&p(ll,{label:"or pay with card"}),u&&nl]})}import{Fragment as Rr,jsx as se,jsxs as sn}from"react/jsx-runtime";var Oo=44,Ps="flopay_checkout_saved_payment_resume",li=new Map,ii=new Map;function Tc(e,t){t.settled&&t.consumers===0&&li.get(e)===t&&li.delete(e)}function Ep(e,t,n){let o=ii.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};ii.set(e,i);let s=()=>{ii.get(e)===i&&ii.delete(e)};return a.then(s,s),a}function Pa(e){return new Promise(t=>setTimeout(t,e))}function si(e,t,n){let o=ja({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Lc,enabled:t!==!1});return o.beginCheckout(n),o}function va(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ys(e,t,n,o,a,i){let s=si(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),va(s)}function Mc(e,t,n,o){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...o===void 0?{}:{attempt:o},statusClass:"2xx"})}function Ac(e,t,n,o,a){let i=Dc(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-o),durationMode:"machine",requestCategory:n,attempt:a,statusClass:i.statusClass}),t instanceof bn&&t.code==="session_auto_completed"?!1:t instanceof bn&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...i,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function ms(e){return!e||e.data.stripe?.publishableKey?!1:!!Oc(e.data.paypal)?.clientId}var _p={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Tp(e){return new Pp(_p,{publishableKey:"provider_unavailable",...e})}async function fs(e,t){let{publishableKey:n,paypalPublishableKey:o}=Ki(e);return{...await Gi({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function vs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Mp(){if(!vs())return null;try{let e=window.sessionStorage.getItem(Ps);return e?JSON.parse(e):null}catch{return null}}function xc(e){if(vs())try{window.sessionStorage.setItem(Ps,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function gs(){if(vs())try{window.sessionStorage.removeItem(Ps)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Ap(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let o of t)e.searchParams.has(o)&&(e.searchParams.delete(o),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Bc(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function hs(e,t){return Ip(!!e,t)}function xp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Fc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Bp(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function bs({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:s,loading:c,error:f,onComplete:C,onError:E,onInstrument:k,onDecline:z,onCountryChange:ne,onZipChange:O,showPayPal:ve=!0,showStripe:V=!0,walletPresentation:v="auto",enabledPaymentMethods:P,showApplePay:he=!0,showGooglePay:N=!0,debug:Ie=!1,layout:Y,theme:Fe,buttonsTheme:lt,buttonsStyles:ze,cardButtonContent:ct,cardBackButtonContent:zt,cardTitleContent:pe,showSecurityFooter:Te,onButtonClick:Pt,onBeforeButtonClick:Re,enableAVS:He,cardFieldOrder:ke,cardPreFormSlot:Q,avsLayout:je,submitLabel:$e,className:pt,initialErrorMessage:be=null,initialPayPalOrderId:ye,children:re,checkoutMode:M,confirmLabel:Ce,renderConfirmButton:Ue,onSessionCompleted:Me}){let U=wp(o),vt=Yn(()=>Nc(Fe),[Fe]),qe=i??vt?.appearance,Ee=n?"embedded_checkout":"standard_checkout",Je=hs(re,Y),[Ae,Qe]=Gt(null),[De,bt]=Gt(null),Yt=At(null),yt=At(null),Et=At(0),[I,ee]=Gt(null),Oe=At(null),[F,Se]=Gt(null),mt=Yn(()=>n?da(n):"",[n]),Ne=n?`create:${mt}`:`session:${e??""}`,wt=Fc(F),_=At(new Set),d=At(Ne),m=At(Ne);Xo(()=>{m.current=Ne,d.current!==Ne&&(d.current=Ne,_.current.clear())},[Ne]);let A=vn(w=>{if(m.current===Ne){if(Ul.has(w.name)){if(_.current.has(w.name))return;_.current.add(w.name)}Nt(()=>k?.(w))}},[Ne,k]),T=Ro(A,Ne),J=At(!1),ft=vn(w=>{if(J.current)return;let b=w.gateway||!wt?w:{...w,gateway:wt};A(b)},[A,wt]);pr(()=>{T({class:"lifecycle",name:"checkout.mount"})},[T]);let[me,We]=Gt(e??""),H=e??me,Ut=n?"":H,[Ct,_t]=Gt(!0),[at,oe]=Gt(null),[In,Bn]=Gt(0),[yn,qt]=Gt("full"),[Fn,Dn]=Gt(!1),[hn,Tt]=Gt(be),[Ve,Le]=Gt(null),[Rn,kt]=Gt(null),[On,mn]=Gt(!1),[jt,Qt]=Gt(void 0),[Jn,$n]=Gt(""),[en,xt]=Gt(!1),[Cn,ln]=Gt(!1),[Ft,fn]=Gt(!1),Dt=At(null),on=At(0),Bt=At(void 0),[ae,Zn]=Gt("loading"),[Xn,Qn]=Gt(0),tn=At(!1),En=At(!1),Sn=At(!1),ce=At(null),et=At(null),u=Yn(()=>({checkoutMode:M??yn,layout:xp(re,Y)}),[M,re,yn,Y]),xe=At(C);xe.current=C;let L=At(E);L.current=E;let Pn=At(z);Pn.current=z;let Nn=vn(w=>Ya(ce,async b=>{try{return await w(b)}catch(j){throw b.aborted?To(j):j}}),[]);pr(()=>()=>{ce.current?.abort(),ce.current=null},[]);let Jt=vn((w,b)=>{Yt.current=w,bt(w),Oe.current=b,ee(b)},[]),_n=vn(()=>{let w=yt.current;w&&(yt.current=null,w.destroy())},[]);pr(()=>{pn(De)?.setCheckoutContext(u),I&&I!==De&&pn(I)?.setCheckoutContext(u)},[De,I,u]);let nt=At(Me);nt.current=Me;let yr=vn(w=>{Zn(w),!(w!=="exhausted"||Sn.current)&&(Sn.current=!0,L.current?.(new bn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Dr=vn(()=>{Zn("retrying"),Qn(w=>w+1)},[]);pr(()=>{Zn("loading"),Qn(0),Sn.current=!1},[H]),pr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Lc,checkout_type:Ee,checkout_layout:Je,billing_api_url:U})},[Je,Ee,U]);let It=Yn(()=>n?da(n,!0):"",[n]),Ln=Yn(()=>Jn===It?jt:void 0,[jt,Jn,It]),er=Yn(()=>n?Oi(n,Ln):void 0,[n,Ln]),tr=M??er?.checkoutMode??"full",$t=Yn(()=>er?{...er,checkoutMode:tr}:void 0,[er,tr]);pr(()=>{Qt(void 0),$n(It),Bt.current=void 0,Dt.current=null,fn(!1)},[It]),pr(()=>{Tt(be)},[be]);let mr=vn((w,b,j)=>{Nt(()=>{Pn.current?.(un(w,b,j))})},[]),fr=vn(async(w,b)=>{Tt(null),kt(null),mn(!1),Le("processing");let j=b?.sessionId??w.id,K=w.clientSecret||t,it=Fc(w),Wt=Yt.current??Oe.current,de=pn(Wt),x=Wt?null:si(U,a,u),B={log:te=>{de?de.log(te):x?.log(te)},error:te=>{de?de.error(te):x?.error(te)},terminal:te=>{de?de.terminal(te):x?.terminal(te)},performance:te=>{de?de.performance(te):x?.performance(te)},now:()=>de?.now()??x?.now()??0,elapsed:te=>de?.elapsed(te)??Math.max(0,(x?.now()??te)-te)},R=B.now(),l=!!(b?.initialAutoProcessingError||b?.initialAutoProcessingPending),y=!1,h,$=()=>{y||(y=!0,l=!0,h=B.now(),B.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},le=!1,Pe=()=>{le||(le=!0,B.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),B.performance({stage:"processing",durationMs:B.elapsed(R),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),h!==void 0&&B.performance({stage:"recovery",durationMs:B.elapsed(h),durationMode:"machine",paymentMethodCategory:"saved"}))};B.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),J.current=!0;try{B.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{J.current=!1}T({class:"lifecycle",name:"payment.processing.started",provider:it}),l&&$();let Ht;try{let te=rc(b?.initialAutoProcessingError),we=b?.initialAutoProcessingError?.type==="3ds_required"&&!b.initialAutoProcessingError.threeDSecureToken&&b.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:b.initialAutoProcessingError.nextActionRedirectUrl}:null,Be,rt=Z=>($(),Nn(S=>Mo(Z,{billingApiUrl:U,sessionId:j,nonce:K,session:w,signal:S})));if(we)Be=await rt(we);else if(te)$(),te.type==="paypal_redirect_required"&&et.current?.publishableKey&&xc({sessionId:j,publishableKey:et.current.publishableKey,paypalPublishableKey:et.current.paypalPublishableKey}),Be=await Nn(Z=>Xa(te,{flopay:Yt.current,paypalFlopay:Oe.current,attempt3DS:b?.attempt3DS,billingApiUrl:U,sessionId:j,session:w,telemetry:!1,signal:Z})),te.type==="paypal_redirect_required"&&gs();else if(b?.initialAutoProcessingPending){let Z=b.initialAutoProcessingPending,S=new ai(U,{telemetry:!1}),q=await Nn(_e=>S.waitForCheckoutSessionCompletion(Z.sessionId,{initialDelayMs:Z.retryAfterMs,nonce:K,statusUrl:Z.statusUrl,signal:_e})),Ke=qr(q,w),ge=q.autoProcessingError?.type==="3ds_required"&&q.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:q.autoProcessingError.nextActionRedirectUrl}:null;if(ge)Be=await rt(ge);else{if(!Ar(Ke))throw So(Ke);Be=Mr(Ke,j)}}else{if(b?.initialAutoProcessingError)throw kr(b.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.initialAutoProcessingError.checkoutMethod});if(b?.fromCreateSession)return b?.fallbackToFull&&(qt("full"),Bc("full")),!1;{let Z=await Ao({billingApiUrl:U,sessionId:j,session:w,nonce:K,telemetry:!1});Z.type==="success"?Be=Z.result:Z.type==="next_action_required"?Be=await rt(Z):($(),Z.type==="paypal_redirect_required"&&et.current?.publishableKey&&xc({sessionId:j,publishableKey:et.current.publishableKey,paypalPublishableKey:et.current.paypalPublishableKey}),Be=await Nn(S=>Xa(Z,{flopay:Yt.current,paypalFlopay:Oe.current,attempt3DS:b?.attempt3DS,billingApiUrl:U,sessionId:j,session:w,telemetry:!1,signal:S})),Z.type==="paypal_redirect_required"&&gs())}}j&&_o(j),Pe(),l&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),B.terminal({outcome:Be.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),mn(Be.status==="authorized"),Le("success"),await Pa(600),Ht=()=>xe.current?.(Be)}catch(te){let we=Ur(ya(te),j);if(we.code==="three_ds_aborted")return!1;let Be=we.checkoutMethod??pa;Tt(we.message),kt(we.message),mn(!1),b?.fallbackToFull&&(B.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),qt("full"),Bc("full")),Pe();let rt=we.statusCode===void 0?void 0:Rp(we.statusCode,"unknown"),Z=rt==="4xx"?{requestCategory:"process_payment",statusClass:rt}:{},S=rt===void 0||rt==="4xx";if(S&&(we.telemetryOutcome==="payment_declined"||!!(we.declineCode||we.code?.toLowerCase().includes("declin"))))B.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Z});else if(S&&(we.telemetryOutcome==="validation_rejected"||we.type==="validation_error"))B.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Z});else{let ge=Dc(te,l?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),_e=we.telemetryRequestCategory??"process_payment";J.current=!0;try{B.error({...ge,...we.telemetryFailureCategory?{failureCategory:we.telemetryFailureCategory}:{},stage:l?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:_e})}finally{J.current=!1}T({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:_e,provider:it})}return Nt(()=>L.current?.(we)),mr(Be,we,{code:we.code,declineCode:we.declineCode}),Le("error"),await Promise.allSettled([Pa(400),b?.ensureProvidersReady?b.ensureProvidersReady():Promise.resolve()]),l&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Pe(),x&&va(x),Le(null),kt(null)}return Nt(Ht),!0},[mr,T,t,U,Nn,a,u]);pr(()=>{if(typeof window>"u"||En.current)return;let w=new URLSearchParams(window.location.search),b=w.get("payment_intent_client_secret");if(!b)return;let j=Mp();j&&(En.current=!0,(async()=>{let K,it=0;Tt(null),kt(null),Le("processing"),Dn(!0);try{if(w.get("redirect_status")==="failed")throw Object.assign(new bn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Wt,paypalFlopay:de}=await Gi({publishableKey:j.publishableKey,paypalPublishableKey:j.paypalPublishableKey,billingApiUrl:U,locale:s,telemetry:a});K=pn(de??Wt),K?.setCheckoutContext(u),it=K?.now()??0,K?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),K?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let x=(de??Wt)?.getRawProvider();if(!x)throw Object.assign(new bn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:R}=await x.retrievePaymentIntent(b);if(R)throw Object.assign(new bn(R.message??"Failed to retrieve PayPal payment status.","api_error",{code:R.code}),{checkoutMethod:"paypal"});let l=Ml(B?.status);if(!B||l==="failed")throw Object.assign(new bn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let y=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,h=l;if(j.sessionId){let Pe=(await new ai(U,{telemetry:!1}).getUnifiedCheckoutSession(j.sessionId)).data.session;if(Pe&&Pe.status!=="complete"){let Ht=await Ao({billingApiUrl:U,sessionId:j.sessionId,session:Pe,telemetry:!1,tokenizedData:{id:y??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(Ht.type!=="success")throw Object.assign(new bn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});h=Ht.result.status}}j.sessionId&&_o(j.sessionId),K?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),K?.performance({stage:"redirect_resume",durationMs:K.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),K?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Le("success"),await Pa(600),Nt(()=>xe.current?.({status:h,paymentIntentId:B.id,paymentMethodId:y,checkoutMethod:"paypal"}))}catch(Wt){let de=Ur(ya(Wt),j.sessionId),x=de.checkoutMethod??"paypal",B=!!(de.declineCode||de.code?.toLowerCase().includes("declin"));if(K)K.performance({stage:"redirect_resume",durationMs:K.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?K.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):K.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let R=si(U,a,u);R.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),va(R)}else ys(U,a,u,"REDIRECT_RESUME_FAILED","redirect_resume");Tt(de.message),kt(de.message),Nt(()=>L.current?.(de)),mr(x,de,{code:de.code,declineCode:de.declineCode}),Le("error"),await Pa(400)}finally{gs(),Ap(),Le(null),kt(null),Dn(!1)}})())},[mr,s,U,a,u]);let Tn=At(null),gr=Yn(()=>$t?da($t):"",[$t]),Wn=At($t);Wn.current=$t,pr(()=>{We(e??"")},[e]),pr(()=>{tn.current=!1,Tt(be),kt(null),mn(!1),Le(null)},[gr,be,e]);async function hr(w,b,j){let K=si(U,a,u),it=new ai(U,{telemetry:!1}),Wt=!1;try{let de=w.idempotencyKey===void 0?void 0:_c(w.idempotencyKey),x=Zl(b,j),B=Jl(b,j);x?.canonicalIdentity===j&&B&&B.canonicalIdentity===void 0&&(Va(b,j,B.idempotencyKey),B={...B,canonicalIdentity:j});let R=de??(B?.canonicalIdentity===j?B.idempotencyKey:void 0),l,y=!1;K.log({name:x?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let h=x?.sid??null,$=null,le,Pe,Ht=!1;if(h)try{$=await it.getUnifiedCheckoutSession(h,x?.nonce),x&&x.canonicalIdentity===void 0&&(Yl($.data.session,w)?(Ka(b,j,h,x.nonce??$.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(Va(b,j,B.idempotencyKey),R??(R=B.idempotencyKey))):(Ha(b,j),B=null,R=de,h=null,$=null));let we=$?.data.session?.status,Be=$?.data.session,rt=Be?.clientSecret||x?.nonce;if(h&&Be?.buyerIdentified===!1&&rt&&(Pe=Co(it,h,rt,w.account)),h&&$&&we==="complete"){if(Wi(h))return{sid:h,result:$};Ha(b,j),h=null,$=null,y=!0}}catch{K.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),x?.canonicalIdentity===void 0?(Ha(b,j),R=de):$i(b,j),h=null}if(!h){!de&&(y||!R)&&(R=_c(),l=R),R&&Va(b,j,R);let we=K.now(),Be=0;K.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let rt={...w,idempotencyKey:R,avsCheck:!!He,avsConfig:typeof He=="object"?He:void 0,checkoutType:"embedded_checkout",checkoutLayout:hs(re,Y)};Object.defineProperty(rt,vp,{configurable:!1,enumerable:!1,value:{onAttempt:q=>{Be=Math.max(Be,q)}}});let Z=()=>{Mc(K,"session_create",we,Be)},S=q=>{Ac(K,q,"session_create",we,Be)&&T({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(Cp(rt)){let q=await it.createDetachedSession(rt);q.claimed.catch(()=>{}),$=q.shell,h=q.sessionId,Pe=q.claim;let Ke=K.now();K.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),le=q.claimed.then(ge=>{let _e=ge.data.session?.id??q.sessionId;return _e&&Ka(b,j,_e,ge.data.session?.clientSecret??q.nonce),Mc(K,"session_claim",Ke),Z(),ge},ge=>{throw $i(b,j),Ac(K,ge,"session_claim",Ke,0)&&T({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),ge}).finally(()=>va(K)),le.catch(()=>{}),Wt=!0,K.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),K.performance({stage:"session_shell",durationMs:K.now()-we,durationMode:"machine",requestCategory:"session_create",attempt:Be,statusClass:"2xx",paymentMethodCategory:"card"})}else $=await it.createAndFetchSession(rt),Z()}catch(q){throw S(q),q}h=$.data.session?.id??h??"",h&&!le&&Ka(b,j,h,$.data.session?.clientSecret)}let te=$?.data.session;return!Pe&&h&&te?.buyerIdentified===!1&&te.clientSecret&&(Pe=Co(it,h,te.clientSecret,w.account)),{sid:h??"",result:$,sdkGeneratedIdempotencyKey:l,...le?{claimed:le}:{},...Pe?{claim:Pe}:{},...Ht?{claimRequiresIdentity:!0}:{}}}finally{Wt||va(K)}}let Er=At(hr);Xo(()=>{Er.current=hr},[hr]);let zn=vn(async(w,b)=>{let j=Wn.current;if(!j)throw new bn("createSession is required to bootstrap checkout.","validation_error");let K=Oi(j,w),it=da(K),Wt=Gl(K),de=li.get(it);if(!de){let R={canonicalIdentity:it,promise:Er.current(K,Wt,it),consumers:0,settled:!1};de=R,li.set(it,R);let l=()=>{R.settled=!0,Tc(it,R)};R.promise.then(l,l)}de.consumers+=1;let x=!1,B=()=>{x||(x=!0,de.consumers-=1,Tc(it,de))};b?.(B);try{let R=await de.promise;Tn.current=it,w&&($n(It),Qt(te=>El(te,w)));let{sid:l,result:y,claimed:h,claim:$,claimRequiresIdentity:le}=R;if(Bt.current=$,fn(le===!0),Qe(y),y.data.session&&Se(y.data.session),l&&We(l),h){on.current+=1;let te=on.current;Dt.current=h,ln(!0),h.then(we=>{on.current===te&&(Dt.current===h&&(Dt.current=null),Qe(we),we.data.session&&Se(we.data.session),ln(!1),fn(!1))},we=>{on.current===te&&(Dt.current===h&&(Dt.current=null),ln(!1),fn(!1),oe(we instanceof bn?we:new bn(we instanceof Error?we.message:"Failed to create session","api_error")))})}else on.current+=1,Dt.current=null,ln(!1),fn(!1);let{flopay:Pe,paypalFlopay:Ht}=await fs(y,{billingApiUrl:U,locale:s,telemetry:a});return Jt(Pe,Ht),_t(!1),R}catch(R){throw Tn.current===it&&(Tn.current=null),R}finally{b||B()}},[It,Jt,s,U,a]),nr=At(fr);nr.current=fr;let rr=At(zn);rr.current=zn;let Mt=vn(async w=>{if(!Bp(w)||en)return{sessionId:me,session:F};xt(!0);try{let b=await zn(w);return{sessionId:b.sid,session:b.result.data.session??null}}finally{xt(!1)}},[zn,en,me,F]),Un=vn(async w=>{let b=Bt.current;if(!b)return;let j=on.current,K=await b(w);on.current===j&&(Qe(K),K.data.session&&Se(K.data.session))},[]),wn=vn(async()=>{await Dt.current},[]),or=vn(async()=>(await wn(),{proceed:!0}),[wn]);pr(()=>{let w=!1,b,j=++Et.current;_n(),oe(null),Bn(0);let K=()=>{w=!0,Et.current===j&&(Et.current+=1,_n())},it=Wn.current;if(gr&&it)return qt(tr),_t(!1),Tn.current===gr?K:(Se(_l(it,M)),(async()=>{let x=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),B=tr==="auto"&&!tn.current&&!x;B&&(Tt(null),kt(null),Le("processing"));try{let R=await rr.current(void 0,$=>{b=$}),l=R.result.data.session??null;et.current=Ki(R.result);let y=ms(R.result),h=Wi(R.sid||l?.id);if(!w&&B&&l&&!y&&!h){tn.current=!0,await Ep(gr,R.sdkGeneratedIdempotencyKey,()=>nr.current(l,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:R.result.autoProcessingError,initialAutoProcessingPending:R.result.autoProcessingPending,autoProcessingAttempted:R.result.autoProcessingAttempted,sessionId:R.sid||l.id}));return}!w&&B&&((y||h)&&(tn.current=!0),Le(null),kt(null))}catch(R){if(w)return;let l=La(R);if(B&&l==="session_auto_completed"){tn.current=!0,Le("success"),await Pa(600),w||(Nt(()=>{xe.current?.({status:"succeeded"})}),Le(null),kt(null));return}B&&(Le(null),kt(null));let y=R instanceof bn?R:new bn(R instanceof Error?R.message:"Failed to create session","api_error");oe(y)}finally{b?.(),b=void 0}})(),()=>{K(),b?.()});_t(!0);async function Wt(){let x=!1,B=null;try{let R=new ai(U,{telemetry:!1}),l=await R.getUnifiedCheckoutSession(H,t);if(B=l,w)return;Qe(l);let y=l.data.session??null;if(Se(y),!y)throw new bn("No session data returned","api_error");let h=y.checkoutMode;if(h==="setup")throw new bn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(y.status==="authorized"){_t(!1),Nt(()=>{xe.current?.(Mr(y,H)),nt.current?.(y.successUrl??"")});return}if(y.status==="complete"){_t(!1),Nt(()=>{nt.current?.(y.successUrl??"")});return}if(y.status==="expired")throw Na(y);x=!0;let $=M??h??"full";qt($),on.current+=1;let le=y.clientSecret||t;Bt.current=y.buyerIdentified===!1&&le?Co(R,H,le,{...y.customer?.id?{userId:y.customer.id}:{}}):void 0,ln(!1),fn(!1);let Pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ht=ms(l);if($==="auto"&&!tn.current&&!Pe&&!Ht){tn.current=!0;let te=de(l);try{if(await nr.current(y,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>te,sessionId:H||y.id}),w)return;await te,w||_t(!1);return}catch{if(w)return;await te,w||_t(!1);return}}await de(l),w||_t(!1)}catch(R){if(w)return;let l=Rl(R,x);if(x&&T({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),l){let{errorCode:h,stage:$,...le}=l;ys(U,a,u,h,$,le)}if(l?.stage==="provider_load"&&(M??B?.data.session?.checkoutMode??"full")==="full"&&Il(B,ve,V)){let h=Tp({billingApiUrl:U,locale:s,telemetry:a});yt.current=h,Jt(h,null),Bn(1),_t(!1);return}let y=R instanceof bn&&l?.stage!=="provider_load"?R:kl();y!==R&&Nt(()=>L.current?.(y)),oe(y),_t(!1)}}async function de(x){let{flopay:B,paypalFlopay:R,...l}=await fs(x,{billingApiUrl:U,locale:s,telemetry:a});et.current={publishableKey:l.publishableKey,paypalPublishableKey:l.paypalPublishableKey},Jt(B,R),Bn(0)}return Wt(),K},[M,gr,tr,Ut,t,ve,V]);let ar=vn(async()=>{if(!Ae||In!==1)return;let w=Et.current;Bn(2);try{let{flopay:b,paypalFlopay:j}=await fs(Ae,{billingApiUrl:U,locale:s,telemetry:a});if(Et.current!==w)return;_n(),Jt(b,j),Bn(0)}catch(b){if(Et.current!==w)return;let{errorCode:j,stage:K,...it}=Di(b);ys(U,a,u,j,K,it)}},[_n,Jt,s,In,U,a,u,Ae]),tt=!!(H&&(F?.clientSecret||t)),nn=Fn||!tt,cn=vn(async()=>{if(!(Fn||!tt||!F)){Dn(!0),Tt(null);try{await fr(F,{attempt3DS:!0,fallbackToFull:!0,sessionId:H||F.id})}finally{Dn(!1)}}},[H,Fn,tt,fr,F]),Mn=Oc(Ae?.data.paypal,ye),Or=ms(Ae),Pr=Yn(()=>{if(!(!Ae||!F||!Ae.data.stripe?.publishableKey))return{billingApiUrl:U}},[Ae,F,U]),_r=!!(n&&!re&&Y==="buttons"&&Re&&tr==="full"),Hn=!!(H&&(Sp(F?.vault)||Qr(F))),rn=Yn(()=>({session:F,loading:Ct,error:at,checkoutMode:yn,inlineSessionDraft:$t,applyInlineSessionPatch:_r?Mt:void 0,inlineSessionPatchProcessing:en,claimPending:Cn,claimRequiresIdentity:Ft,claimBuyerIdentity:Un,waitForDataAttachment:wn}),[F,Ct,at,yn,$t,_r,Mt,en,Cn,Ft,Un,wn]),Nr=!!n&&Y==="buttons"&&!Or&&!Hn&&(!De||!Pr),an=Ve?se(Sr,{status:Ve,errorMessage:Rn,authorized:On}):null;if(Ct&&!Hn){if(c)return sn(Rr,{children:[c,an]});if(Y==="buttons"){let w=vt?.buttonsLayout?.cardButton?.borderRadius??vt?.appearance.variables?.borderRadius??8,b=j=>se("div",{style:{height:j,borderRadius:w,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return sn(Rr,{children:[sn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ve&&b(Oo),V&&(he||N)&&b(Oo),V&&b(Oo),se("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),an]})}return sn(Rr,{children:[sn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[se("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),se("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),an]})}return at?f?se(cr.Provider,{value:rn,children:f(at)}):se(cr.Provider,{value:rn,children:se("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:at.message})}):Nr?sn(Rr,{children:[se(cr.Provider,{value:rn,children:se(Dp,{onButtonClick:Pt,showPayPal:ve,showStripe:V,showApplePay:he,showGooglePay:N,theme:Fe,buttonsTheme:lt,buttonsStyles:ze,cardButtonContent:ct,cardBackButtonContent:zt,cardTitleContent:pe})}),an]}):Or&&F&&Mn?sn(Rr,{children:[se(cr.Provider,{value:rn,children:sn("div",{className:pt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[hn&&se(Eo,{icon:!1,children:hn}),ae==="retrying"&&se("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),ae==="exhausted"&&sn("div",{role:"alert",children:[se("div",{children:"PayPal is temporarily unavailable. Please try again."}),se("button",{type:"button",onClick:Dr,children:"Retry PayPal"})]}),ae!=="exhausted"&&se("div",{"aria-hidden":ae==="retrying"?!0:void 0,style:ae==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:se(Vl,{sessionId:H,nonce:F.clientSecret||void 0,billingApiUrl:U,email:F.customer?.email||$t?.account?.email,billingName:[F.customer?.firstName,F.customer?.lastName].filter(Boolean).join(" ")||[$t?.account?.firstName,$t?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Un,clientId:Mn.clientId,environment:Mn.environment,currency:(F.currency??"usd").toUpperCase(),isSubscription:F.mode==="subscription",providerObjectType:Mn.providerObjectType,approvalPresentation:Mn.approvalPresentation,existingOrderId:Mn.existingOrderId,onComplete:C,onErrorChange:Tt,onDecline:z,onButtonClick:Pt,runBeforeButtonClick:or,onInitializationStateChange:yr,allowAutomaticRetry:Xn===0,session:F,telemetry:a,telemetryContext:u,onInstrument:ft,debug:Ie},`${Ne}:paypal-init-${Xn}`)})]})}),an]}):yn==="confirm"?sn(Rr,{children:[se(cr.Provider,{value:rn,children:se(Ga,{flopay:De,paypalFlopay:I,options:Pr??{billingApiUrl:U},onInstrument:ft,children:sn("div",{className:pt,children:[hn&&se("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:hn}),Ue?Ue({onConfirm:cn,isProcessing:nn}):se("button",{type:"button",onClick:cn,disabled:nn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:nn?"not-allowed":"pointer",opacity:nn?.6:1},children:Fn?"Processing...":Ce??"Confirm Purchase"})]})},Ne)}),an]}):(!De||!Pr)&&!(Hn&&yn==="full")?se(Rr,{children:an}):sn(Rr,{children:[se(cr.Provider,{value:rn,children:sn(Ga,{flopay:De,paypalFlopay:I,options:Pr??{billingApiUrl:U},onInstrument:ft,children:[In===1&&se("button",{type:"button",onClick:ar,children:"Retry payment methods"}),re?sn(Rr,{children:[hn&&se("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:hn}),se(Fp,{sessionId:H,nonce:F?.clientSecret||void 0,billingApiUrl:U,session:F,submitLabel:$e,walletPresentation:v,children:re})]}):se(us,{sessionId:H,nonce:F?.clientSecret||void 0,telemetry:a,email:F?.customer?.email||$t?.account?.email,userId:F?.customer?.id||$t?.account?.userId,firstName:F?.customer?.firstName||$t?.account?.firstName,lastName:F?.customer?.lastName||$t?.account?.lastName,totalAmount:F?Math.round(bp(F).total*100):0,currency:F?.currency?.toLowerCase()??"usd",onComplete:C,onError:E,onDecline:z,error:hn,onErrorChange:Tt,showPayPal:ve,showStripe:V,walletPresentation:v,enabledPaymentMethods:In?[]:P??Ae?.data.stripe?.enabledPaymentMethods??F?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ae?.data.stripe?.enabledPaymentMethodCountries,showApplePay:he,showGooglePay:N,layout:Y,theme:Fe,buttonsTheme:lt,buttonsStyles:ze,appearance:qe,cardButtonContent:ct,cardBackButtonContent:zt,cardTitleContent:pe,onButtonClick:Pt,onBeforeButtonClick:Re,onBuyerIdentityReady:Un,enableAVS:He,...ke?{cardFieldOrder:ke}:{},...Q?{cardPreFormSlot:Q}:{},avsLayout:je,country:F?.customer?.country,city:F?.customer?.city,state:F?.customer?.state,onCountryChange:ne,onZipChange:O,avsCheck:!!He,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:hs(re,Y),className:pt,submitLabel:$e,directPaypal:Mn,isSubscription:F?.mode==="subscription",session:F,dataAttachmentPending:Cn,dataAttachmentRequiresIdentity:Ft,debug:Ie})]},Ne)}),an]})}function Fp({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,children:s}){return se(Rr,{children:ps.Children.map(s,c=>{if(!ps.isValidElement(c))return c;let f=c.props,C={};return f.sessionId||(C.sessionId=e),!f.nonce&&t&&(C.nonce=t),f.billingApiUrl||(C.billingApiUrl=n),f.submitLabel===void 0&&a!==void 0&&(C.submitLabel=a),f.walletPresentation===void 0&&(C.walletPresentation=i),o?.customer&&(f.email||(C.email=o.customer.email),f.userId||(C.userId=o.customer.id),f.firstName||(C.firstName=o.customer.firstName),f.lastName||(C.lastName=o.customer.lastName)),Object.keys(C).length===0?c:ps.cloneElement(c,C)})})}function Dp({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:o,showGooglePay:a,theme:i,buttonsTheme:s,buttonsStyles:c,cardButtonContent:f,cardBackButtonContent:C,cardTitleContent:E}){let[k,z]=Gt(!1),ne=Yn(()=>Nc(i),[i]),O=Yn(()=>{let P=ne?.buttonsLayout??kp(s);return c?{...P,...c,cardButton:{...P.cardButton,...c.cardButton},cardFormContainer:{...P.cardFormContainer,...c.cardFormContainer},backButton:{...P.backButton,...c.backButton},backButtonIcon:{...P.backButtonIcon,...c.backButtonIcon},submitButton:{...P.submitButton,...c.submitButton},title:{...P.title,...c.title}}:P},[ne,s,c]),ve=ne?.buttonsLayout?.cardButton?.borderRadius??ne?.appearance.variables?.borderRadius??8,V=P=>se("div",{style:{height:P,borderRadius:ve,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),v=f===void 0?{boxSizing:"border-box",height:Oo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(k){let P=O.cardInputBorder??"#e5e7eb",he=O.cardInputBackground??"white",N=ho(C),Ie=ho(E);return sn("div",{style:{backgroundColor:O.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...O.cardFormContainer},children:[sn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[sn("button",{type:"button",onClick:()=>z(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:N?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...O.backButton},children:[se("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...O.backButtonIcon},children:se("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:se("path",{d:"M15 18l-6-6 6-6"})})}),se(vo,{content:C})]}),Ie?se("div",{style:{flex:1}}):se("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...O.title},children:se(na,{content:E})})]}),se("div",{style:{backgroundColor:he,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:se("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),sn("div",{style:{display:"flex"},children:[se("div",{style:{flex:1,backgroundColor:he,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:se("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),se("div",{style:{flex:1,backgroundColor:he,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:se("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),se("div",{style:{backgroundColor:he,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:se("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),se("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...O.submitButton,opacity:.5}}),se("style",{children:`
|
|
15
15
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
16
16
|
@keyframes flopay-interim-expand {
|
|
17
17
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
18
18
|
40% { opacity: 1; }
|
|
19
19
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
20
20
|
}
|
|
21
|
-
`})]})}return 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"),W(!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 Tp,jsx as so,jsxs as Ap}from"react/jsx-runtime";var Ip=44;function $c(e){return new Promise(t=>setTimeout(t,e))}function kp(e,t){return e instanceof ka?e:new ka(e instanceof Error?e.message:t,"api_error")}function _p(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 Ep({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:W,tagsData:$,utmMetadata:k,billingApiUrl:q,locale:K,theme:h,appearance:C,buttonsTheme:se,buttonsStyles:z,onSuccess:Ce,onError:J,onDecline:ke,children:je,disabled:_e=!1,type:it="button",style:zt,...ye}){let Me=Ia(()=>bp(q),[q]),Pt=Ia(()=>Rp({createSession:n,clientId:i,products:s,items:l,subscriptions:f,account:u,successUrl:S,cancelUrl:v,couponCodes:W,tagsData:$,utmMetadata:k}),[u,v,i,W,n,s,l,f,S,$,k]),[Te,Ve]=qo(!1),[Re,ne]=qo(null),[$e,Ke]=qo(null),[yt,be]=qo(!1),[fe,le]=qo(null),[F,Se]=qo(null),ze=zo(!0),xe=zo(null),V=zo(F),vt=zo(Ce),qe=zo(J),Ae=zo(ke),Xe=Nr(p=>ti(xe,async g=>{try{return await p(g)}catch(D){throw g.aborted?Gr(D):D}}),[]);Uo(()=>{V.current=F},[F]),Uo(()=>{vt.current=Ce},[Ce]),Uo(()=>{qe.current=J},[J]),Uo(()=>{Ae.current=ke},[ke]),Uo(()=>(ze.current=!0,()=>{ze.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=Nr((p,g=fa)=>{Ae.current?.(dn(g,p,{code:p.code,declineCode:p.declineCode}))},[]),Qe=Nr(async p=>{ze.current&&(Ke(null),be(p.result.status==="authorized"),ne("success"),await $c(600),ze.current&&Bt(()=>vt.current?.(p)))},[]),Ne=Nr(async(p,g)=>{ze.current&&(qe.current?.(p),g?.emitDecline&&Be(p,g.method),Ke(p.message),be(!1),ne("error"),await $c(400))},[Be]),Ct=Nr(async(p,g,D)=>{let x=p.data.session??null;if(!x)throw qr(new ka("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(qa(x),x.id||g);try{if(p.autoProcessingPending){let ge=p.autoProcessingPending,We=new Fs(Me),X=await Xe(At=>We.waitForCheckoutSessionCompletion(ge.sessionId,{initialDelayMs:ge.retryAfterMs,nonce:ee,statusUrl:ge.statusUrl,signal:At})),qt=$r(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(!Fr(qt))throw Io(qt);await Qe({result:Br(qt,g),session:qt,sessionId:qt.id||g,autoCompleted:!1});return}if(p.autoProcessingError){let ge=p.autoProcessingError.nextActionRedirectUrl;if(p.autoProcessingError.type==="3ds_required"&&ge&&g&&ee){let We=await Xe(At=>os({billingApiUrl:Me,sessionId:g,nonce:ee,nextActionRedirectUrl:ge,signal:At}));if(We.status==="declined")throw wr({type:We.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:We.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:p.autoProcessingError.checkoutMethod});let qt=await new Fs(Me).waitForCheckoutSessionCompletion(g,{initialDelayMs:0,nonce:ee}),bt=$r(qt,x);if(!Fr(bt))throw wr({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 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 ge=g??x.id,We=await Xe(X=>xo(ut,{billingApiUrl:Me,sessionId:ge,nonce:ee,session:x,signal:X,telemetry:!0}));await Qe({result:We,session:x,sessionId:x.id||ge,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 ge=x.id||g,We=qr(ga(ut),ge);if(We.code==="three_ds_aborted")return;if(We.code==="checkout_processing_timeout"){if(!ze.current)return;le(We.message),Bt(()=>qe.current?.(We));return}await Ne(We,{emitDecline:!0,method:We.checkoutMethod??fa}),_p(We,ge)&&ge&&ze.current&&Se({sessionId:ge,errorMessage:We.message,nonce:ee||void 0,payPalOrderId:We.orderId})}},[t,Me,Xe,Ne,Qe]),Vt=Nr(async p=>{if(ye.onClick?.(p),!(p.defaultPrevented||_e||Te)){if(Se(null),le(null),e&&Pt){let g=new ka("Provide either sessionId or create-session props, not both.","validation_error");await Ne(g),ze.current&&(ne(null),Ke(null));return}if(!e&&!Pt){let g=new ka("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Ne(g),ze.current&&(ne(null),Ke(null));return}Ve(!0),Ke(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(ja(D)==="session_auto_completed"){await Qe({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw D}}catch(g){await Ne(qr(kp(g,"Automatic payment failed. Please try again."),e))}finally{ze.current&&(ne(null),Ke(null),Ve(!1))}}},[ye.onClick,Pt,_e,Te,t,Ct,Me,e,Ne,Qe]),ft=Nr(p=>{let g=V.current;Se(null),vt.current?.({result:p,session:null,sessionId:g?.sessionId??null,autoCompleted:!1})},[]),Tt=Nr(p=>{qe.current?.(p)},[]),T=Nr(p=>{Ae.current?.(p)},[]),re=Ia(()=>wp(h),[h]),Oe=Ia(()=>{let p=re?.buttonsLayout??Sp(se);return z?{...p,...z,cardButton:{...p.cardButton,...z.cardButton}}:p},[re,se,z]),L=Ia(()=>{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",Le=we?.colorPrimaryHover??na(gt,.12),It=we?.borderRadius??"8px";return Ap(Tp,{children:[so("button",{...ye,type:it,onClick:Vt,disabled:_e||Te,"aria-busy":Te,style:{width:"100%",...je===void 0?{boxSizing:"border-box",height:Ip,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Oe.cardButton,...ws({themeBundle:re,resolvedPrimaryColor:gt,resolvedBorderRadius:It,submitButtonStyle:Oe.submitButton,explicitPrimaryColor:we?.colorPrimary}),fontSize:Oe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:_e||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:_e||Te?.6:1,...zt},onMouseEnter:p=>{ye.onMouseEnter?.(p),!p.defaultPrevented&&!_e&&!Te&&(re||we?.colorPrimary)&&(p.currentTarget.style.backgroundColor=Le)},onMouseLeave:p=>{ye.onMouseLeave?.(p),!p.defaultPrevented&&(re||we?.colorPrimary)&&(p.currentTarget.style.backgroundColor=gt)},onMouseDown:p=>{ye.onMouseDown?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(0.985)")},onMouseUp:p=>{ye.onMouseUp?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(1)")},children:so(Co,{content:je})}),fe&&so("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:fe}),Re&&so(br,{status:Re,errorMessage:$e,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 Bp}from"react/jsx-runtime";var Mp={StripeSetupMethod:Tl,PayPalSetupMethod:El};function xp(e){return Bp(Al,{...e,branches:Mp})}export{Ga as DirectPayPalButton,Ep as FloPayAutomaticPaymentButton,ld as FloPayCardSetup,sd as FloPayCardSetupError,Bs as FloPayCheckout,xp as FloPayPaymentMethodSetup,Qa as FloPayProvider,Is as SplitCardForm,Fi as VaultCardFields,ef as dropThirdPartyOnlyError,_d as useCheckout,Kr as useFloPay,Ki as usePayPalFloPay};
|
|
21
|
+
`})]})}return sn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&V(Oo),n&&(o||a)&&V(Oo),n&&se("button",{type:"button",onClick:()=>{e?.("card"),z(!0)},style:{width:"100%",...v,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:O.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...O.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:se(Po,{content:f})}),se("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Wp,jsx as ro,jsxs as Hp}from"react/jsx-runtime";var zp=44;function zc(e){return new Promise(t=>setTimeout(t,e))}function Up(e,t){return e instanceof Ca?e:new Ca(e instanceof Error?e.message:t,"api_error")}function qp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function jp(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function $p({sessionId:e,nonce:t,createSession:n,paymentMethodId:o,checkoutMethod:a,clientId:i,products:s,items:c,subscriptions:f,account:C,successUrl:E,cancelUrl:k,couponCodes:z,tagsData:ne,utmMetadata:O,billingApiUrl:ve,locale:V,theme:v,appearance:P,buttonsTheme:he,buttonsStyles:N,onSuccess:Ie,onError:Y,onDecline:Fe,children:lt,disabled:ze=!1,type:ct="button",style:zt,...pe}){let Te=ba(()=>Op(ve),[ve]),Pt=ba(()=>jp({createSession:n,clientId:i,products:s,items:c,subscriptions:f,account:C,successUrl:E,cancelUrl:k,couponCodes:z,tagsData:ne,utmMetadata:O}),[C,k,i,z,n,s,c,f,E,ne,O]),[Re,He]=zo(!1),[ke,Q]=zo(null),[je,$e]=zo(null),[pt,be]=zo(!1),[ye,re]=zo(null),[M,Ce]=zo(null),Ue=Lo(!0),Me=Lo(null),U=Lo(M),vt=Lo(Ie),qe=Lo(Y),Ee=Lo(Fe),Je=Fr(d=>Ya(Me,async m=>{try{return await d(m)}catch(A){throw m.aborted?To(A):A}}),[]);No(()=>{U.current=M},[M]),No(()=>{vt.current=Ie},[Ie]),No(()=>{qe.current=Y},[Y]),No(()=>{Ee.current=Fe},[Fe]),No(()=>(Ue.current=!0,()=>{Ue.current=!1,Me.current?.abort()}),[]),No(()=>{if(typeof window>"u")return;let d=m=>{m.key==="Escape"&&Ce(null)};return window.addEventListener("keydown",d),()=>{window.removeEventListener("keydown",d)}},[]);let Ae=Fr((d,m=pa)=>{Ee.current?.(un(m,d,{code:d.code,declineCode:d.declineCode}))},[]),Qe=Fr(async d=>{Ue.current&&($e(null),be(d.result.status==="authorized"),Q("success"),await zc(600),Ue.current&&Nt(()=>vt.current?.(d)))},[]),De=Fr(async(d,m)=>{Ue.current&&(qe.current?.(d),m?.emitDecline&&Ae(d,m.method),$e(d.message),be(!1),Q("error"),await zc(400))},[Ae]),bt=Fr(async(d,m,A)=>{let T=d.data.session??null;if(!T)throw Ur(new Ca("No session data returned","api_error"),m);let J=T.clientSecret||t;if(Ar(T)){await Qe({result:Mr(T,m),session:T,sessionId:T.id||m,autoCompleted:!1});return}if(T.status==="expired")throw Ur(Na(T),T.id||m);try{if(d.autoProcessingPending){let me=d.autoProcessingPending,We=new Cs(Te),H=await Je(_t=>We.waitForCheckoutSessionCompletion(me.sessionId,{initialDelayMs:me.retryAfterMs,nonce:J,statusUrl:me.statusUrl,signal:_t})),Ut=qr(H,T),Ct=H.autoProcessingError?.type==="3ds_required"&&H.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:H.autoProcessingError.nextActionRedirectUrl}:null;if(Ct&&m&&J){let _t=await Je(at=>Mo(Ct,{billingApiUrl:Te,sessionId:m,nonce:J,session:T,signal:at,telemetry:!0}));await Qe({result:_t,session:T,sessionId:T.id||m,autoCompleted:!1});return}if(H.autoProcessingError)throw kr(H.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:H.autoProcessingError.checkoutMethod});if(!Ar(Ut))throw So(Ut);await Qe({result:Mr(Ut,m),session:Ut,sessionId:Ut.id||m,autoCompleted:!1});return}if(d.autoProcessingError){let me=d.autoProcessingError.nextActionRedirectUrl;if(d.autoProcessingError.type==="3ds_required"&&me&&m&&J){let We=await Je(_t=>oc({billingApiUrl:Te,sessionId:m,nonce:J,nextActionRedirectUrl:me,signal:_t}));if(We.status==="declined")throw kr({type:We.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:We.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:d.autoProcessingError.checkoutMethod});let Ut=await new Cs(Te).waitForCheckoutSessionCompletion(m,{initialDelayMs:0,nonce:J}),Ct=qr(Ut,T);if(!Ar(Ct))throw kr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:d.autoProcessingError.checkoutMethod});await Qe({result:Mr(Ct,m),session:Ct,sessionId:Ct.id||m,autoCompleted:!1});return}throw kr(d.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:d.autoProcessingError.checkoutMethod})}if(A?.fromCreateSession&&d.autoProcessingAttempted===!0)throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ft=await Ao({billingApiUrl:Te,sessionId:m??T.id,session:T,nonce:J});if(ft.type==="next_action_required"&&J){let me=m??T.id,We=await Je(H=>Mo(ft,{billingApiUrl:Te,sessionId:me,nonce:J,session:T,signal:H,telemetry:!0}));await Qe({result:We,session:T,sessionId:T.id||me,autoCompleted:!1});return}if(ft.type!=="success")throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Qe({result:ft.result,session:T,sessionId:T.id||m,autoCompleted:!1})}catch(ft){let me=T.id||m,We=Ur(ya(ft),me);if(We.code==="three_ds_aborted")return;if(We.code==="checkout_processing_timeout"){if(!Ue.current)return;re(We.message),Nt(()=>qe.current?.(We));return}await De(We,{emitDecline:!0,method:We.checkoutMethod??pa}),qp(We,me)&&me&&Ue.current&&Ce({sessionId:me,errorMessage:We.message,nonce:J||void 0,payPalOrderId:We.orderId})}},[t,Te,Je,De,Qe]),Yt=Fr(async d=>{if(pe.onClick?.(d),!(d.defaultPrevented||ze||Re)){if(Ce(null),re(null),e&&Pt){let m=new Ca("Provide either sessionId or create-session props, not both.","validation_error");await De(m),Ue.current&&(Q(null),$e(null));return}if(!e&&!Pt){let m=new Ca("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await De(m),Ue.current&&(Q(null),$e(null));return}He(!0),$e(null),be(!1),Q("processing");try{let m=new Cs(Te);if(e){let A=await m.getUnifiedCheckoutSession(e,t);await bt(A,e);return}try{let A=await m.createAndFetchSession({...Pt});await bt(A,A.data.session?.id??null,{fromCreateSession:!0})}catch(A){if(La(A)==="session_auto_completed"){await Qe({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw A}}catch(m){await De(Ur(Up(m,"Automatic payment failed. Please try again."),e))}finally{Ue.current&&(Q(null),$e(null),He(!1))}}},[pe.onClick,Pt,ze,Re,t,bt,Te,e,De,Qe]),yt=Fr(d=>{let m=U.current;Ce(null),vt.current?.({result:d,session:null,sessionId:m?.sessionId??null,autoCompleted:!1})},[]),Et=Fr(d=>{qe.current?.(d)},[]),I=Fr(d=>{Ee.current?.(d)},[]),ee=ba(()=>Lp(v),[v]),Oe=ba(()=>{let d=ee?.buttonsLayout??Np(he);return N?{...d,...N,cardButton:{...d.cardButton,...N.cardButton}}:d},[ee,he,N]),F=ba(()=>{let d=ee?.appearance;return P?d?{...d,...P,variables:{...d.variables,...P.variables}}:P:d},[P,ee]),Se=F?.variables,mt=Se?.colorPrimary??"#4A49FF",Ne=Se?.colorPrimaryHover??Qo(mt,.12),wt=Se?.borderRadius??"8px";return Hp(Wp,{children:[ro("button",{...pe,type:ct,onClick:Yt,disabled:ze||Re,"aria-busy":Re,style:{width:"100%",...lt===void 0?{boxSizing:"border-box",height:zp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Oe.cardButton,...ds({themeBundle:ee,resolvedPrimaryColor:mt,resolvedBorderRadius:wt,submitButtonStyle:Oe.submitButton,explicitPrimaryColor:Se?.colorPrimary}),fontSize:Oe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ze||Re?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ze||Re?.6:1,...zt},onMouseEnter:d=>{pe.onMouseEnter?.(d),!d.defaultPrevented&&!ze&&!Re&&(ee||Se?.colorPrimary)&&(d.currentTarget.style.backgroundColor=Ne)},onMouseLeave:d=>{pe.onMouseLeave?.(d),!d.defaultPrevented&&(ee||Se?.colorPrimary)&&(d.currentTarget.style.backgroundColor=mt)},onMouseDown:d=>{pe.onMouseDown?.(d),d.defaultPrevented||(d.currentTarget.style.transform="scale(0.985)")},onMouseUp:d=>{pe.onMouseUp?.(d),d.defaultPrevented||(d.currentTarget.style.transform="scale(1)")},children:ro(Po,{content:lt})}),ye&&ro("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ye}),ke&&ro(Sr,{status:ke,errorMessage:je,authorized:pt}),M&&ro("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:d=>{d.target===d.currentTarget&&Ce(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:ro("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:ro(bs,{sessionId:M.sessionId,nonce:M.nonce,checkoutMode:"full",billingApiUrl:Te,locale:V,theme:v,...F?{appearance:F}:{},buttonsTheme:he,buttonsStyles:N,initialErrorMessage:M.errorMessage,initialPayPalOrderId:M.payPalOrderId,cardTitleContent:null,onComplete:yt,onError:Et,onDecline:I})})})]})}import{jsx as Gp}from"react/jsx-runtime";var Vp={StripeSetupMethod:Cl,PayPalSetupMethod:bl};function Kp(e){return Gp(Sl,{...e,branches:Vp})}export{Wa as DirectPayPalButton,$p as FloPayAutomaticPaymentButton,od as FloPayCardSetup,rd as FloPayCardSetupError,bs as FloPayCheckout,Kp as FloPayPaymentMethodSetup,Ga as FloPayProvider,us as SplitCardForm,Ti as VaultCardFields,Cf as dropThirdPartyOnlyError,Rd as useCheckout,jr as useFloPay,zi as usePayPalFloPay};
|