@flopay/react 1.13.0 → 1.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +7 -7
- package/package.json +6 -6
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as vl}from"./chunk-D4CVZRT4.mjs";import{c as Nt,d as Sr,e as Xo,f as _i,g as sl,h as td,j as nd}from"./chunk-YR36EYW2.mjs";import{a as hl}from"./chunk-HSYSKQPT.mjs";import{a as ea,b as Da,c as Ai,d as xi,e as Bi,f as pl,g as yl,h as ml,i as fl,j as gl,k as Pl}from"./chunk-H4MQCBX4.mjs";import{a as xa,b as Ti,c as ll,d as Mi,e as go,f as cl,g as zr,h as Ba,i as dl,j as Qo,k as Fa,l as ul}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as Cf}from"@flopay/shared";import{PaymentAPI as bs}from"@flopay/js";import{FloPayError as ba,resolveBillingApiUrl as Np,resolveButtonsLayoutTheme as Lp,resolveTheme as zp}from"@flopay/shared";import{useCallback as Fr,useEffect as No,useMemo as va,useRef as Lo,useState as zo}from"react";import{Fragment as bo,jsx as Kn,jsxs as bl}from"react/jsx-runtime";function rd(){return bl(bo,{children:[bl("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 od(){return Kn(bo,{children:"Go back"})}function ad(){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(rd,{}):e})}function vo({content:e}){return Kn(bo,{children:e===void 0?Kn(od,{}):e})}function ta({content:e}){return Kn(bo,{children:e===void 0?Kn(ad,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as id,canRecoverHostedCardForm as sd,classifyTelemetryFailure as ld,FloPayError as kn,isCardHolderNamePlaceholder as cd,isMoneySettledOutcome as dd,isMountableVaultBlock as ud,isSetupIntentClientSecret as pd,isValidEmail as yd,resolveSetupFutureUsage as md,resolveWalletModeOptions as fd}from"@flopay/shared";import{canRecoverHostedCardForm as Qr,hasServerSideCardGateway as Ml}from"@flopay/shared";import{splitFullName as oa}from"@flopay/shared";import{applyFriendlyMessageOverride as wo}from"@flopay/shared";var gd="Checkout is temporarily unavailable. Please try again later.";function Fi(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 hd(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 Cl(){return new kn(gd,"api_error",{code:"CheckoutInitializationFailed"})}function Sl(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(ud(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||sd(o))||t&&e?.data.paypal?.publishableKey)}function wl(e,t){if(t&&(!(e instanceof kn)||e.type==="authentication_error"))return Fi(e);if(!(e instanceof kn&&hd(e))){if(!t&&!(e instanceof kn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...ld(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=cd(s.firstName,s.lastName);if(!yd(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 kl(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 Di(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 Il(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 Oi(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 Rl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Oa(e){let t=Rl(e);return new kn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Na(e){return e instanceof kn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function So(e){return Rl(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(id,"api_error",{code:"checkout_processing_timeout"})}function na(e,t){return e==="processing"||dd(e,t)}function El(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function _l(e,t){let n=e;if(pd(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 Pd=["apple_pay","google_pay"];function Tl(e,t="automatic",n){let o=md(n,Pd,"wallet");return{...fd(e,t),paymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var vd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Ni(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:vd.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function ra(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as vp,PaymentAPI as oi,SESSION_CREATE_TELEMETRY as bp}from"@flopay/js";import{buildCheckoutDisplayData as Cp,classifyTelemetryFailure as Bc,FloPayError as bn,isDetachedSessionEligible as Sp,isMountableVaultBlock as wp,resolveBillingApiUrl as kp,resolveButtonsLayoutTheme as Ip,resolveDirectPaypalConfig as Fc,resolveIdempotencyKey as Rc,resolveCheckoutLogLayout as Rp,resolveTheme as Dc,SDK_VERSION as Oc,telemetryStatusClass as Ep}from"@flopay/shared";import us,{useCallback as vn,useEffect as pr,useMemo as Yn,useRef as At,useState as Gt}from"react";import{createContext as Al}from"react";var Gn=Al({flopay:null,paypalFlopay:null,billingApiUrl:""}),cr=Al({session:null,loading:!1,error:null});import{PaymentAPI as zi}from"@flopay/js";import{buildPayPalProcessPaymentRequest as Fd,buildPayPalSessionIntentRequest as Dd,buildPayPalTokenizedBody as Od,classifyTelemetryFailure as Nd,describePayPalProcessFailure as Ld,FloPayError as Ui,friendlyPayPalFailureMessage as zd,generateIdempotencyKey as Ud,isPayPalTeardownMessage as qd,isValidEmail as zl,mergePayPalPayerIdentity as jd,needsPayPalPayerDetails as $d,normalizeGatewayEnvironment as Wd,paypalProviderIdentityRequired as Ul,resolvePayPalApprovalIdentity as Hd,resolvePayPalDeclineReason as Vd,SDK_VERSION as Kd,usesPayPalVaultedChannel as Gd}from"@flopay/shared";import{loadScript as Yd}from"@paypal/paypal-js";import{useCallback as wr,useContext as Jd,useEffect as Lt,useMemo as la,useRef as ot,useState as Wr}from"react";import{compactBuyerIdentity as bd,isValidEmail as Cd}from"@flopay/shared";import{useCallback as xl,useEffect as Sd,useRef as Bl,useState as Dl}from"react";import{compactBuyerIdentity as dr}from"@flopay/shared";import{jsx as Fl,jsxs as aa}from"react/jsx-runtime";function ko(){let[e,t]=Dl(null),n=Bl(null),o=Bl(0),a=xl((s,c)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:c}),new Promise(f=>{n.current=f})),[]),i=xl(s=>{let c=n.current;n.current=null,t(null),c?.(s)},[]);return Sd(()=>()=>{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]=Dl(e.email?.trim()??""),f=Cd(s.trim());return aa("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:[aa("div",{style:{fontWeight:700},children:["Continue with ",t]}),aa("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Fl("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}})]}),aa("div",{style:{display:"flex",gap:"0.5rem"},children:[o&&Fl("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),aa("button",{type:"button",disabled:!f||a,onClick:()=>{n(bd({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as wd}from"@flopay/shared";import{useContext as La}from"react";function jr(){return La(Gn).flopay}function Li(){return La(Gn).paypalFlopay??null}function kd(){return La(cr)}function Ol(){return La(Gn).billingApiUrl||wd()}import{FLO_INSTRUMENT_ONCE_NAMES as Id,invokeMerchantCallback as Rd,projectFloInstrument as Ed}from"@flopay/shared";import{useCallback as _d,useRef as za}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Nl}from"@flopay/shared";function Ro(e,t){let n=za(e);n.current=e;let o=za(new Set),a=za(t),i=za(t);return Xo(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),_d(s=>{if(i.current!==t)return;let c=Ed(s);if(c){if(Id.has(c.name)){if(o.current.has(c.name))return;o.current.add(c.name)}Rd(()=>n.current?.(c))}},[t])}import{createContext as Td}from"react";var ia=Td(null);function Ua(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Md=Symbol.for("@flopay/js.telemetry.bridge.v1"),Ad=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function xd(){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 Bd(e){let t=xd(),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 qa(e){let t=globalThis[Ad];return Bd(t?.(e)??{})}function pn(e){if(e)return e[Md]}import{useCallback as $r,useEffect as Ll,useRef as eo}from"react";function sa(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);Ll(()=>{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"})}},ll))},[C]);return Ll(()=>{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 qi}from"react/jsx-runtime";var ja=45,Zd=1e3,Xd=11e3,Qd={width:"100%",minHeight:ja,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"},eu={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 tu(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:eu[e.kind]??null}}function ql(e,t){return e==="watchdog_expired"?"paypal_render_timeout":cl(t)?"paypal_init_timeout":"paypal_init_failure"}function nu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function jl({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=la(()=>{if(Te)return null;let u=qa({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Kd,enabled:ze!==!1});return u.setCheckoutContext(ct??{}),u.beginCheckout(ct??{}),u},[n,Te,ze,ct?.checkoutMode,ct?.layout]),He=la(()=>pn(Te),[Te]);Lt(()=>()=>{Re&&Re.flush().catch(()=>{}).finally(()=>Re.destroy())},[Re]);let ke=la(()=>({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=Jd(ia),re=ot(null);re.current||(re.current=Ua());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:Ul(o,Fe)});mt.current.sessionId!==e&&(mt.current={sessionId:e,required:Ul(o,Fe)});let Ne=mt.current.required,wt=la(()=>n.replace(/\/+$/,""),[n]),d=Fe?.gateways?.paypal?.providerObjectType??E,m=d??(C?"subscription":"order"),[A]=Wr(Qo),T=Fe?.gateways?.paypal?.approvalPresentation??k,J=Fa(A,T==="app_switch"?"app_switch":void 0,m),ft=Gd(d),me=la(()=>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=xa("PayPal",L,A.inAppBrowser),Nn=Fn.current;if(Nn){let Jt=L&&A.inAppBrowser?new Ui(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}=sa(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=Wd(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=Ud(),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=qd,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=tu({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)},Zd);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 $=Ti({code:ql(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:",ql(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=Fd({body:l,sessionId:h,nonce:y?.nonce??mn.current,accountPatch:y?.accountPatch,session:Rn.current,email:kt.current}),te=await new zi(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=Ld(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:nu(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=zd(Pe instanceof Error?Pe.message:void 0);w(Ht),Nt(()=>qt.current?.(un("paypal",Ht)));return}},K=()=>new Ui("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 zi(wt,{telemetry:!1}).createSessionIntent(h,$??"",Dd(yr),{idempotencyKey:Dr})}catch(Pe){throw L.error({...Nd(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=Vd(l);new zi(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=Yd({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 Ui("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ge=Hd({accountPatch:Ke.accountPatch,email:kt.current,billingName:On.current,session:Rn.current});if($d(ge))try{ge=jd(ge,await S?.order?.get?.())}catch{}if((Ve.current||Ne)&&!zl(ge.email)){let dt=await F("PayPal",ge);if(!dt)return;ge=dt}zl(ge.email)&&(Ke.accountPatch=dr({...Ke.accountPatch,...ge}),await Ve.current?.(ge));let _e=Od(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:ja,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}=Ti(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."))},Xd);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?qi("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?`
|
|
1
|
+
import{a as vl}from"./chunk-D4CVZRT4.mjs";import{c as Dt,d as Sr,e as Xo,f as _i,g as sl,h as rd,j as od}from"./chunk-YR36EYW2.mjs";import{a as hl}from"./chunk-HSYSKQPT.mjs";import{a as ea,b as Da,c as Ai,d as xi,e as Bi,f as pl,g as yl,h as ml,i as fl,j as gl,k as Pl}from"./chunk-H4MQCBX4.mjs";import{a as xa,b as Ti,c as ll,d as Mi,e as go,f as cl,g as zr,h as Ba,i as dl,j as Qo,k as Fa,l as ul}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as Tf}from"@flopay/shared";import{PaymentAPI as bs}from"@flopay/js";import{FloPayError as ba,resolveBillingApiUrl as Hp,resolveButtonsLayoutTheme as Vp,resolveTheme as Kp}from"@flopay/shared";import{useCallback as Fr,useEffect as No,useMemo as va,useRef as Lo,useState as zo}from"react";import{Fragment as bo,jsx as Yn,jsxs as bl}from"react/jsx-runtime";function ad(){return bl(bo,{children:[bl("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:[Yn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Yn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Yn("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:Yn("path",{d:"M9 18l6-6-6-6"})})]})}function id(){return Yn(bo,{children:"Go back"})}function sd(){return Yn(bo,{children:"Secure card checkout"})}function ho(e){return e!==void 0&&(e===""||e===null||e===!1)}function Po({content:e}){return Yn(bo,{children:e===void 0?Yn(ad,{}):e})}function vo({content:e}){return Yn(bo,{children:e===void 0?Yn(id,{}):e})}function ta({content:e}){return Yn(bo,{children:e===void 0?Yn(sd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as ld,canRecoverHostedCardForm as cd,classifyTelemetryFailure as dd,FloPayError as _n,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 Ml}from"@flopay/shared";import{splitFullName as oa}from"@flopay/shared";import{applyFriendlyMessageOverride as wo}from"@flopay/shared";var Pd="Checkout is temporarily unavailable. Please try again later.";function Fi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof _n&&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 Cl(){return new _n(Pd,"api_error",{code:"CheckoutInitializationFailed"})}function Sl(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 wl(e,t){if(t&&(!(e instanceof _n)||e.type==="authentication_error"))return Fi(e);if(!(e instanceof _n&&vd(e))){if(!t&&!(e instanceof _n)&&(e instanceof TypeError||e instanceof SyntaxError))return{...dd(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof _n)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof _n))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 _n("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let f={};for(let[C,T]of Object.entries(s)){if(c&&C.endsWith("Name")||typeof T!="string")continue;let I=T.trim();I&&(f[C]=I)}return a=e.claimCheckoutSession(t,n,{accountData:f}),a.catch(()=>{}),a}}function kl(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 Di(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 Il(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 Oi(e,t){return t?{...e,...t}:e}function yn(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 Rl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Oa(e){let t=Rl(e);return new _n(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Na(e){return e instanceof _n||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function So(e){return Rl(e)?new _n("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new _n("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new _n(ld,"api_error",{code:"checkout_processing_timeout"})}function na(e,t){return e==="processing"||pd(e,t)}function El(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function _l(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 _n(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 _n(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var bd=["apple_pay","google_pay"];function Tl(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 Ni(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 ra(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Ep,PaymentAPI as oi,SESSION_CREATE_TELEMETRY as _p}from"@flopay/js";import{buildCheckoutDisplayData as Tp,classifyTelemetryFailure as Dc,FloPayError as Sn,isDetachedSessionEligible as Mp,isMountableVaultBlock as Ap,resolveBillingApiUrl as xp,resolveButtonsLayoutTheme as Bp,resolveDirectPaypalConfig as Oc,resolveIdempotencyKey as _c,resolveCheckoutLogLayout as Fp,resolveTheme as Nc,SDK_VERSION as Lc,telemetryStatusClass as Dp}from"@flopay/shared";import us,{useCallback as Cn,useEffect as dr,useMemo as Zn,useRef as At,useState as Jt}from"react";import{createContext as Al}from"react";var Jn=Al({flopay:null,paypalFlopay:null,billingApiUrl:""}),sr=Al({session:null,loading:!1,error:null});import{PaymentAPI as zi}from"@flopay/js";import{buildPayPalProcessPaymentRequest as Od,buildPayPalSessionIntentRequest as Nd,buildPayPalTokenizedBody as Ld,classifyTelemetryFailure as zd,describePayPalProcessFailure as Ud,FloPayError as Ui,friendlyPayPalFailureMessage as qd,generateIdempotencyKey as jd,isPayPalTeardownMessage as $d,isValidEmail as zl,mergePayPalPayerIdentity as Wd,needsPayPalPayerDetails as Hd,normalizeGatewayEnvironment as Vd,paypalProviderIdentityRequired as Ul,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 Ot,useMemo as la,useRef as st,useState as Wr}from"react";import{compactBuyerIdentity as Sd,isValidEmail as wd}from"@flopay/shared";import{useCallback as xl,useEffect as kd,useRef as Bl,useState as Dl}from"react";import{compactBuyerIdentity as lr}from"@flopay/shared";import{jsx as Fl,jsxs as aa}from"react/jsx-runtime";function ko(){let[e,t]=Dl(null),n=Bl(null),o=Bl(0),a=xl((s,c)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:c}),new Promise(f=>{n.current=f})),[]),i=xl(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]=Dl(e.email?.trim()??""),f=wd(s.trim());return aa("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:[aa("div",{style:{fontWeight:700},children:["Continue with ",t]}),aa("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Fl("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}})]}),aa("div",{style:{display:"flex",gap:"0.5rem"},children:[o&&Fl("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),aa("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 La}from"react";function jr(){return La(Jn).flopay}function Li(){return La(Jn).paypalFlopay??null}function Rd(){return La(sr)}function Ol(){return La(Jn).billingApiUrl||Id()}import{FLO_INSTRUMENT_ONCE_NAMES as Ed,invokeMerchantCallback as _d,projectFloInstrument as Td}from"@flopay/shared";import{useCallback as Md,useRef as za}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Nl}from"@flopay/shared";function Ro(e,t){let n=za(e);n.current=e;let o=za(new Set),a=za(t),i=za(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 ia=Ad(null);function Ua(){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 qa(e){let t=globalThis[Bd];return Dd(t?.(e)??{})}function mn(e){if(e)return e[xd]}import{useCallback as $r,useEffect as Ll,useRef as eo}from"react";function sa(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);Ll(()=>{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)},[]),T=$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]),I=$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,ve=v??P?.generation??n.current;(v===void 0||P?.generation===v)&&(C(P),a.current=null),o.current=ve},[C]),ie=$r(v=>o.current===(v??n.current),[]),O=$r(v=>a.current?.generation===v&&o.current!==v,[]),Se=$r(()=>{let v=a.current;v&&(C(v),!v.yieldedControl&&(v.yieldedControl=!0,s.current?.(v.method)))},[C]),G=$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"})}},ll))},[C]);return Ll(()=>{let v=()=>{document.visibilityState==="visible"?G():Se()};return document.addEventListener("visibilitychange",v),window.addEventListener("blur",Se),window.addEventListener("focus",G),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("blur",Se),window.removeEventListener("focus",G),C()}},[C,Se,G]),{startAttempt:T,finishAttempt:I,invalidateAttempt:z,isAttemptInvalidated:ie,isAttemptCurrent:O,generationRef:n}}import{jsx as to,jsxs as qi}from"react/jsx-runtime";var ja=45,Qd=1e3,eu=11e3,tu={width:"100%",minHeight:ja,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 ql(e,t){return e==="watchdog_expired"?"paypal_render_timeout":cl(t)?"paypal_init_timeout":"paypal_init_failure"}function ou(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function jl({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:s,environment:c,currency:f,isSubscription:C,providerObjectType:T,approvalPresentation:I,onTokenizedBody:z,onComplete:ie,onErrorChange:O,onDecline:Se,onTechnicalFailure:G,isProcessing:v=!1,onLoadStateChange:P,onInitializationStateChange:ve,allowAutomaticRetry:N=!0,onButtonClick:_e,runBeforeButtonClick:Y,session:Ne,existingOrderId:yt,telemetry:Be,telemetryContext:mt,onInstrument:Nt,debug:fe=!1}){let Fe=jr(),bt=Ro(Nt,e),Te=la(()=>{if(Fe)return null;let p=qa({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Yd,enabled:Be!==!1});return p.setCheckoutContext(mt??{}),p.beginCheckout(mt??{}),p},[n,Fe,Be,mt?.checkoutMode,mt?.layout]),qe=la(()=>mn(Fe),[Fe]);Ot(()=>()=>{Te&&Te.flush().catch(()=>{}).finally(()=>Te.destroy())},[Te]);let Re=la(()=>({error:p=>{qe?qe.error(p):Te?.error(p),bt({class:"technical_error",errorCode:p.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":p.errorCode,requestCategory:p.requestCategory,provider:p.provider})},log:p=>{qe?qe.log(p):Te?.log(p),bt({class:"lifecycle",name:p.name,provider:p.provider})},performance:p=>{qe?qe.performance(p):Te?.performance(p)},terminal:p=>{qe?qe.terminal(p):Te?.terminal(p)},startTiming:()=>qe?.now()??Te?.now()??0,elapsed:p=>qe?.elapsed(p)??Math.max(0,(Te?.now()??p)-p)}),[bt,qe,Te]),ee=st(null),je=st(0),lt=st(null),It=st(null),rt=st(null),ce=Xd(ia),X=st(null);X.current||(X.current=Ua());let L=ce??X.current,he=st(null),$e=st(!1),[Me,A]=Wr(!1),[Ye,Je]=Wr(!1),[Ze,We]=Wr(0),ze=st(0),[De,be]=Wr(!1),Ct=st(!1),Zt=st(!1),[ot,Lt]=Wr(!1),[E,ne]=Wr(!1),{request:Ue,collect:M,finish:se}=ko(),Xe=st({sessionId:e,required:Ul(o,Ne)});Xe.current.sessionId!==e&&(Xe.current={sessionId:e,required:Ul(o,Ne)});let we=Xe.current.required,ht=la(()=>n.replace(/\/+$/,""),[n]),m=Ne?.gateways?.paypal?.providerObjectType??T,w=m??(C?"subscription":"order"),[Ee]=Wr(Qo),de=Ne?.gateways?.paypal?.approvalPresentation??I,y=Fa(Ee,de==="app_switch"?"app_switch":void 0,w),re=Jd(m),_=la(()=>JSON.stringify([ht,s,f,c??"",w,re,y,e,yt??""]),[ht,s,f,c,yt,w,re,y,e]),F=st(_),j=F.current!==_,et=st(fe),St=st(null),[wt,ct]=Wr([]),$=wr(p=>{et.current&&ct(dt=>[...dt,`${new Date().toISOString().slice(11,23)} ${p}`])},[]);Ot(()=>{et.current=fe,fe&&$("debug:enabled"),St.current?.setEnabled(fe)},[$,fe]);let wn=st(z),On=st(ie),fn=st(O),zt=st(Se),Ut=st(G),Tn=st(_e),vn=st(P),xt=st(ve),jn=st(i),qt=st(Y),ur=st(Ne),jt=st(o),$n=st(a),Ae=st(t),Le=st(null),Bt=st(new Map),kn=st(new Map),In=st(!1);Ot(()=>(In.current=!0,()=>{In.current=!1}),[]),Ot(()=>{wn.current=z},[z]),Ot(()=>{jn.current=i},[i]),Ot(()=>{On.current=ie},[ie]),Ot(()=>{fn.current=O},[O]),Ot(()=>{zt.current=Se},[Se]),Ot(()=>{Ut.current=G},[G]),Ot(()=>{Tn.current=_e},[_e]),Ot(()=>{vn.current=P},[P]),Ot(()=>{xt.current=ve},[ve]),Ot(()=>{qt.current=Y},[Y]),Ot(()=>{ur.current=Ne},[Ne]),Ot(()=>{jt.current=o},[o]),Ot(()=>{$n.current=a},[a]),Ot(()=>{Ae.current=t},[t]),Ot(()=>{ze.current=Ze},[Ze]),Ot(()=>{De&&he.current?.focus()},[De,Ze]);let Rn=wr(()=>{window.setTimeout(()=>{he.current?.focus()},0)},[]),gn=wr(()=>{A(!1),We(p=>p+1)},[]),bn=wr(()=>{be(!1),(ee.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ee.current)?.focus?.()},[]);Ot(()=>{!Me||!$e.current||($e.current=!1,bn())},[bn,Me,Ze]);let ln=wr((p,dt)=>{let W=dt?.popupBlocked??zr(p);W&&L.markBlocked();let oe=xa("PayPal",W,Ee.inAppBrowser),Pt=Ut.current;if(Pt){let tt=W&&Ee.inAppBrowser?new Ui(oe,"api_error",{code:dt?.code??"paypal_popup_blocked"}):p;Pt("paypal",tt,dt);return}fn.current?.(oe)},[L,Ee.inAppBrowser]),on=wr(p=>{let dt=lt.current,W=It.current;dt===null||!W||(Re.log({...W,popupCapability:L.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:p}),Re.performance({...W,popupCapability:L.current(),stage:"overlay_return",durationMs:Re.elapsed(dt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:p}),lt.current=null)},[L,Re]),$t=wr((p,dt,W)=>{let oe=It.current;on("overlay_timeout"),oe&&Re.error({...oe,popupCapability:L.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),ln(dt,{...W,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:y,terminalReason:"overlay_timeout"}),be(!0),gn(),Rn()},[on,Rn,ln,L,y,gn,Re]),Rt=wr(()=>{L.markAvailable();let p=It.current;p&&(rt.current=p.attempt,Re.log({...p,popupCapability:L.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[L,Re]),{finishAttempt:cn,generationRef:dn,invalidateAttempt:ue,isAttemptCurrent:Xn,isAttemptInvalidated:Mn,startAttempt:pr}=sa($t,{onHandoffObserved:Rt}),tn=wr(()=>(be(!1),pr("paypal")),[pr]),hn=wr(p=>{ue(p?.generation),p?.showRetry&&be(!0),p?.remount&&gn(),p?.focus!==!1&&Rn()},[Rn,ue,gn]),yr=p=>{let dt=Le.current;return dt&&kn.current.set(p,dt),p};Ot(()=>{F.current!==_&&(F.current=_,Ct.current=!1,Zt.current=!1,A(!1),Je(!1),Lt(!1),xt.current?.("loading"))},[_]),Ot(()=>{Dt(()=>vn.current?.(Me&&!ot))},[Me,ot]);let Wn=Vd(c);Ot(()=>{let p={attempt:dn.current+1,inAppBrowser:Ee.inAppBrowser,appFamily:Ee.appFamily,popupCapability:L.current(),presentationMode:y},dt=()=>({...It.current??p,popupCapability:L.current()}),W={error:l=>Re.error({...l,...dt()}),log:l=>Re.log({...l,...dt()}),performance:l=>Re.performance({...l,...dt()}),terminal:l=>Re.terminal({...l,...dt()}),startTiming:Re.startTiming,elapsed:Re.elapsed},oe=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",Pt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if($(`mount clientId=${oe} env=${c??"(unset)"}\u2192${Wn??"live"} ccy=${f} sub=${C}`),$(`ua=${Pt.slice(0,80)}${Pt.length>80?"\u2026":""}`),!s){$("FAIL: clientId empty \u2014 gateway misconfigured"),Lt(!0),W.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!ee.current){$("FAIL: containerRef not attached");return}je.current=W.startTiming(),W.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let tt=!1,kt=!1,ke=()=>tt||kt,An=re?w:void 0,Dr,_t=!1,Nn=()=>{Dr=jd(),Dr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),_t=!0},Qn=null,er=!1,Ht=null,mr=!1,fr=()=>{!Ht||mr||(mr=!0,Ht.close().catch(()=>{}))},xn=!1,gr=!1,Hn=ee.current,hr=null,Er=null,Ln=[],tr=null,nr=!1,Mt=!1,zn=null,En=l=>{if(!l||typeof l.getBoundingClientRect!="function")return"(no rect)";let u=l.getBoundingClientRect();return`${Math.round(u.width)}\xD7${Math.round(u.height)}`},rr=l=>{if(!l)return"(empty)";try{let u=new URL(l,typeof window>"u"?"https://localhost":window.location.href),h=u.pathname.toLowerCase();return h.includes("checkcaptcha")||h.includes("captcha")?`CAPTCHA(${u.host}${h})`:h.includes("risk")||h.includes("challenge")?`RISK(${u.host}${h})`:h.includes("smart/buttons")?`smart-buttons(${u.host})`:`${u.host}${h}`.slice(0,100)}catch{return l.slice(0,80)}},or=l=>{let u=l.getAttribute("src"),h=l.getAttribute("srcdoc"),V=l.getAttribute("name"),pe=l.getAttribute("sandbox"),Ce=[];return u&&Ce.push(`src=${rr(u)}`),h&&Ce.push(`srcdoc[${h.length}ch]`),!u&&!h&&Ce.push("src=(empty) srcdoc=(empty)"),V&&Ce.push(`name=${V.slice(0,40)}`),pe!==null&&Ce.push(`sandbox="${pe.slice(0,40)}"`),Ce.join(" ")},nt=l=>{if(!(l instanceof HTMLIFrameElement))return"";try{let u=l.contentDocument;if(!u)return"cd=null";let h=u.body?.children.length??0,V=u.body?.innerHTML.length??0,pe=u.head?.innerHTML.length??0;return`cd=same-origin readyState=${u.readyState} body[${h}children,${V}ch] head[${pe}ch]`}catch(u){return`cd=cross-origin(${u.message.slice(0,30)})`}},nn=[],un=l=>{if(ke())return;let u=l.message??String(l.error??"(no message)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&($(`window:error ${u.slice(0,140)}`),nn.push(u))},Bn=l=>{if(ke())return;let u=l.reason instanceof Error?l.reason.message:String(l.reason??"(no reason)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&($(`window:rejection ${u.slice(0,140)}`),nn.push(u))},Or={value:0},Pr=()=>{hr?.disconnect(),hr=null,Er?.disconnect(),Er=null;for(let l of Ln.splice(0))clearTimeout(l);Mt=!1,nr&&typeof window<"u"&&(window.removeEventListener("error",un),window.removeEventListener("unhandledrejection",Bn)),nr=!1},_r=()=>{if(!(nr||ke()||xn)){if(nr=!0,nn.length=0,Or.value=0,typeof window<"u"&&(window.addEventListener("error",un),window.addEventListener("unhandledrejection",Bn)),typeof PerformanceObserver<"u")try{Er=new PerformanceObserver(l=>{if(!ke())for(let u of l.getEntries()){if(!u.name.toLowerCase().includes("paypal"))continue;Or.value+=1;let h=Math.round(u.duration);$(`net ${h}ms ${u.name.slice(0,90)}`)}}),Er.observe({type:"resource",buffered:!0})}catch{}zn?.()}},Vn=()=>{tr&&(clearTimeout(tr),tr=null)},rn=()=>{Pr(),Vn()},Nr={setEnabled:l=>{l?_r():Pr()}};St.current=Nr,et.current&&_r();let an=$d,k=l=>{if(ke()||an(l))return;let u=wo(l)??l;Dt(()=>fn.current?.(u))},b=(l,u)=>{if(tt||er)return;er=!0,kt=!0,rn(),fr();let h=ru({kind:l,generationActive:!0,automaticRetryAllowed:N,automaticRetryUsed:Ct.current});if(h.action==="retry"){Ct.current=!0,A(!1),ne(!1),Je(!0),xt.current?.("retrying"),Qn=setTimeout(()=>{tt||We(V=>V+1)},Qd);return}if(A(!1),ne(!1),Je(!1),Lt(!0),h.action!=="ignore"){if(xt.current?.("exhausted"),h.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",u);return}if(h.report){let V=Ti({code:ql(l,u),message:u},{inAppBrowser:Ee.inAppBrowser,handoffObserved:!1});V.popupBlocked&&L.markBlocked(),W.error({errorCode:V.popupBlocked?V.errorCode:h.report.errorCode,stage:h.report.stage,operationOutcome:h.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:V.terminalReason})}Zt.current||(Zt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",ql(l,u)))}};Lt(!1);let H=async(l,u=Le.current)=>{if(ke())return;let h=u?.sessionId??e;if(wn.current){await wn.current(l,{sessionId:h,accountPatch:u?.accountPatch,nonce:u?.nonce});return}let V=W.startTiming();W.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let pe=()=>{W.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"processing",durationMs:W.elapsed(V),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Ce=Od({body:l,sessionId:h,nonce:u?.nonce??Ae.current,accountPatch:u?.accountPatch,session:ur.current,email:jt.current}),te=await new zi(ht,{telemetry:!1}).processPayment(Ce.userId,Ce.params);if(te.ok){if(kt||tt&&In.current)return;pe(),W.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Dt(()=>On.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ke())return;let Ie=await te.json().catch(()=>null),Oe=Ud(Ie),at=Oe.message;pe(),te.status===400&&(typeof Ie?.declineCode=="string"||!Array.isArray(Ie?.fields))?W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):te.status===400||te.status===422?W.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):W.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ou(te.status),failureCategory:te.status>=500?"server_error":void 0}),k(at),Dt(()=>zt.current?.(yn("paypal",at,{code:Oe.code,declineCode:Oe.declineCode})));return}catch(Ce){if(ke())return;pe(),W.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Kt=qd(Ce instanceof Error?Ce.message:void 0);k(Kt),Dt(()=>zt.current?.(yn("paypal",Kt)));return}},J=()=>new Ui("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ut=l=>ke()?Promise.reject(J()):Promise.resolve(l),Vt=async l=>{if(ke())throw J();_t||Nn();let u=Le.current,h=u?.sessionId??e,V=u?.nonce??Ae.current;W.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let pe;try{pe=await new zi(ht,{telemetry:!1}).createSessionIntent(h,V??"",Nd(An),{idempotencyKey:Dr})}catch(Ce){throw W.error({...zd(Ce,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Ce}if(ke())throw J();if(pe.provider!=="paypal"||pe.providerObjectType!==w)throw new Error(l);return W.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),pe.providerObjectId},ye=(l,u)=>{let h=u?.nonce??Ae.current;if(!h)return;let V=u?.sessionId??e,pe=Gd(l);new zi(ht,{telemetry:!1}).reportSessionIntentDecline(V,h,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:pe}).catch(()=>{})},x=Ze;$("loadScript:scheduled (deferred 1 tick)");let B=null,R=setTimeout(()=>{if(tt){$("loadScript:skipped (cancelled before defer ran)");return}$("loadScript:start");let l=Wn==="live"?"production":Wn,u={};w==="subscription"?u={intent:"subscription",vault:!0}:w==="order"&&(u={intent:"capture"}),B=Zd({clientId:s,currency:f,...u,...l?{environment:l}:{},...l==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let h=!1;B.then(V=>{if(h=!0,$(`loadScript:resolved inactive=${ke()} ns=${!!V} buttons=${!!V?.Buttons}`),ke())return;if(!V?.Buttons){$("FAIL: namespace missing Buttons factory"),b("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}W.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"provider_ready",durationMs:W.elapsed(je.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),W.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let pe=async(Z,S)=>{if(ke()||ze.current!==x)return;let U=Z.vaultSetupToken??Z.subscriptionID??Z.orderID??"",He=U?kn.current.get(U):Bt.current.get(x);if(!(!He||!Xn(He.generation))&&cn(He.generation)){kn.current.delete(U),Bt.current.delete(He.surfaceKey),on("approved");try{if(ne(!0),Dt(()=>fn.current?.(null)),!U)throw new Ui("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Pe=Kd({accountPatch:He.accountPatch,email:jt.current,billingName:$n.current,session:ur.current});if(Hd(Pe))try{Pe=Wd(Pe,await S?.order?.get?.())}catch{}if((jn.current||we)&&!zl(Pe.email)){let ft=await M("PayPal",Pe);if(!ft)return;Pe=ft}zl(Pe.email)&&(He.accountPatch=lr({...He.accountPatch,...Pe}),await jn.current?.(Pe));let xe=Ld(U,An);await H(xe,He)}catch(Pe){k(Pe instanceof Error?Pe.message:"PayPal capture failed.")}finally{ke()||ne(!1)}}},Ce=Z=>{let S=yt?()=>ut(yt):()=>Vt(Z);return async()=>yr(await S())},Kt=V.Buttons({style:{layout:"horizontal",height:ja,tagline:!1},...y==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Z,S)=>{if(ke()){await S.reject();return}Nn();let U=qt.current,He={};if(U)try{let ft=await U("paypal");if(ke()){await S.reject();return}if(!ft.proceed){Le.current=null,Bt.current.delete(x),await S.reject();return}He={sessionId:ft.sessionId,accountPatch:ft.accountPatch,nonce:ft.nonce}}catch(ft){$(`onClick:runBeforeButtonClick rejected msg=${(ft instanceof Error?ft.message:String(ft)).slice(0,120)}`),Le.current=null,Bt.current.delete(x),await S.reject();return}Dt(()=>Tn.current?.("paypal"));let Pe=tn(),xe={generation:Pe,surfaceKey:x,...He};Le.current=xe,Bt.current.set(x,xe),It.current={...p,attempt:Pe},await S.resolve(),W.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),W.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),lt.current=W.startTiming()},createOrder:w==="order"?Ce("Failed to create PayPal order."):void 0,createSubscription:w==="subscription"?Ce("Failed to create PayPal subscription."):void 0,createVaultSetupToken:w==="setup_token"?async()=>yr(await Vt("Failed to create PayPal setup token.")):void 0,onApprove:pe,onCancel:()=>{if(ke())return;let Z=Bt.current.get(x)??Le.current;Z&&Bt.current.delete(Z.surfaceKey),Le.current=null,on("cancelled"),W.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),$e.current=!0,hn({generation:Z?.generation,remount:!0,focus:!1})},onError:Z=>{if(ke()||ze.current!==x)return;let S=Z instanceof Error?Z.message:"PayPal failed to render.";if($(`onError rendered=${xn} msg=${S.slice(0,120)}`),xn){let U=Bt.current.get(x)??Le.current;if(U&&!Xn(U.generation)||!U&&Mn())return;if(an(S)){cn(U?.generation);return}let{errorCode:He,popupBlocked:Pe,providerDeclined:xe,terminalReason:ft}=Ti(Z,{inAppBrowser:Ee.inAppBrowser,handoffObserved:U!=null&&rt.current===U.generation});if(Pe&&L.markBlocked(),on(ft),xe){W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:ft}),ye(Z,U),Dt(()=>zt.current?.(yn("paypal",S))),U&&Bt.current.delete(U.surfaceKey),Le.current=null,cn(U?.generation);return}W.error({errorCode:He,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:ft}),U&&Bt.current.delete(U.surfaceKey),Le.current=null,hn({generation:U?.generation,remount:!0,showRetry:!0,focus:!0}),ln(Z,{code:"paypal_runtime_failed",popupBlocked:Pe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:y,terminalReason:ft});return}b(an(S)?"teardown":"pre_ready_callback",S)}}),te=Kt.isEligible();if($(`isEligible=${te}`),W.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!te){A(!1),b("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}gr=!0,Ht=Kt,zn=()=>{if(!nr||Mt||ke()||xn)return;Mt=!0,$(`container:dims ${En(Hn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(hr=new MutationObserver(S=>{if(!ke()){for(let U of S)if(U.type==="childList")U.addedNodes.forEach(He=>{if(!(He instanceof Element))return;let Pe=He.tagName.toLowerCase(),xe=(He.getAttribute("title")??"").slice(0,40),ft=Pe==="iframe"?` ${or(He)}`:"";$(`child+ ${Pe}${xe?` title="${xe}"`:""}${ft} dims=${En(He)}`)});else if(U.type==="attributes"&&U.target instanceof Element){let He=U.target;if(He.tagName.toLowerCase()!=="iframe")continue;let Pe=U.attributeName;(Pe==="src"||Pe==="srcdoc")&&$(`attr~ iframe ${Pe}=${Pe==="srcdoc"?`[${(He.getAttribute("srcdoc")??"").length}ch]`:rr(He.getAttribute("src"))} dims=${En(He)}`)}}}),hr.observe(Hn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Z=S=>{if(ke()||xn)return;let U=Hn.querySelectorAll("iframe"),He=typeof document<"u"&&"hasStorageAccess"in document;$(`watchdog:${S} container=${En(Hn)} children=${Hn.childElementCount} iframes=${U.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${He} paypalNetRequests=${Or.value}`),U.forEach((Pe,xe)=>{let ft=(Pe.getAttribute("title")??"").slice(0,40);$(` iframe[${xe}] ${En(Pe)}${ft?` title="${ft}"`:""} ${or(Pe)}`);let Qe=nt(Pe);Qe&&$(` ${Qe}`)}),nn.length===0&&$(" (no PayPal/zoid window errors captured)")};Ln.push(setTimeout(()=>Z("3s"),3e3)),Ln.push(setTimeout(()=>Z("8s"),8e3)),Ln.push(setTimeout(()=>Z("15s"),15e3))},zn(),$("render:start");let Oe=W.startTiming();tr=setTimeout(()=>{ke()||xn||($("watchdog:11s retryable render timeout"),b("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},eu);let at=Kt.render(Hn);(async()=>{try{if(await at,$(`render:resolved inactive=${ke()}`),rn(),ke()){fr();return}xn=!0,A(!0),Je(!1),xt.current?.("ready"),W.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),W.performance({stage:"checkout_render",durationMs:W.elapsed(Oe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Z){let S=Z instanceof Error?Z.message:"PayPal failed to render.";$(`render:rejected msg=${S.slice(0,120)}`),rn(),b(an(S)?"teardown":"render_rejected",S)}})()}).catch(V=>{let pe=V instanceof Error?V.message:"PayPal operation failed.";$(`provider:failed msg=${pe.slice(0,120)}`);let Ce="script_rejected";h&&an(pe)?Ce="teardown":h&&gr&&(Ce="render_rejected"),b(Ce,pe)})},0);return()=>{tt=!0,clearTimeout(R),Qn&&clearTimeout(Qn),rn(),St.current===Nr&&(St.current=null),fr(),lt.current=null,It.current=null}},[N,ht,s,f,c,w,y,re,e,yt,Ze,Re,M,we,$,on]);let Wt=fe?qi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ot?"#fef2f2":"#f3f4f6",border:`1px solid ${ot?"#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=${ot})`,wt.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return yt&&!H?pe?to("div",{children:et}):null:qi("div",{children:[et,Oe&&to(Io,{identity:Oe.identity,methodLabel:Oe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Se,onCancel:()=>Se(null)}),qi("div",{"aria-hidden":vt||Oe?!0:void 0,style:vt||Oe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ja},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:ja,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:Qd,children:"Try PayPal again"})]})}function $a(e){return to(jl,{...e})}function $l(e){return to(jl,{...e})}import{jsx as Wl,jsxs as ru}from"react/jsx-runtime";function Eo({children:e,margin:t,icon:n=!0,styleOverride:o}){return ru("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&&Wl("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Wl("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 Wa,clearCachedInlineSession as ji,hashCreateParams as Hl,legacyCachedSessionMatchesDraft as Vl,persistCachedInlineIdempotencyKey as Ha,persistCachedInlineSession as Va,readCachedInlineIdempotencyKey as Kl,readCachedInlineSession as Gl,serializeCreateParams as ca}from"@flopay/shared";import{resolveBillingApiUrl as ou}from"@flopay/shared";import{useEffect as Hr,useMemo as au,useRef as Yl,useState as Jl}from"react";import{jsx as iu}from"react/jsx-runtime";function Ka({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=Jl(e instanceof Promise?null:e),[c,f]=Jl(t instanceof Promise||!t?null:t),C=Yl(null),E=Yl(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=ou(n?.billingApiUrl),ne=au(()=>({flopay:i,paypalFlopay:c,billingApiUrl:z,emitInstrument:k}),[i,c,z,k]);return iu(Gn.Provider,{value:ne,children:a})}import{markSessionRecentlyCompleted as _o,wasSessionRecentlyCompleted as $i}from"@flopay/shared";async function Ga(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 su,loadFloPay as Zl,PaymentAPI as Ja,runSavedCardChallenge as lu}from"@flopay/js";import{classifyPaymentRejection as cu,FloPayError as St,isAuthorizationOnlySession as du,isMountableVaultBlock as uu,isSetupIntentClientSecret as pu,normalizeCheckoutFailureOutcome as Xl}from"@flopay/shared";var ua="card";async function yu(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:o,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:o??null}}async function mu(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 fu(){return new St("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Hi(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 da(e,t){try{return await e()}catch(n){throw xr(n,t)}}function ec(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 tc(e){return lu(e)}async function Mo(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,s=new Ja(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,f;try{f=await su({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 Ja(n);try{z.reportThreeDsAbandoned(o)}finally{z.destroy()}}throw fu()}}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=Hi(new St(i,"api_error",{code:e?.code??Xl(e?.outcome)??Xl(e?.type)??e?.gatewayErrorCode}),o);return e?.orderId&&(s.orderId=e.orderId),s}function Wi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ya(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function nc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ya(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||Ya(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||Ya(E)))return E}}}}async function gu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=nc(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 Ja(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ya(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 Ja(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??Wi(n)});if(v.ok){let N=typeof v.json=="function"?await v.json().catch(()=>null):null;if(du(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:ra(a),checkoutMethod:Ql(a,n)}};let Ie=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Ie?{paymentIntentId:Ie}:{},paymentMethodId:ra(a),checkoutMethod:Ql(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=nc(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 gu({billingApiUrl:c,sessionId:f,nonce:C,responseJson:P});if(N)return N;throw Hi(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:cu(v.status,P)})}async function Za(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 Hi(new St("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let k=pu(e.threeDSecureToken),z=null,ne=e.paymentMethodId,O=await da(()=>yu(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 da(()=>mu(E,e.threeDSecureToken,{payment_method:ne,return_url:c??Wi(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 da(()=>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}):Za(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 da(()=>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 da(()=>k.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Wi(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 pa(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 Vi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=uu(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 Ql(e,t){return e?e.isPaypal?"paypal":"card":t&&Qr(t)?"card":void 0}async function Ki({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([Zl(e,{billingApiUrl:n,locale:o,telemetry:a}),i?Zl(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 hu,toStripeAppearance as Pu}from"@flopay/js";import{buildCheckoutProcessMetadata as vu,buildProcessPaymentAvsAccount as bu,COUNTRY_OPTIONS as Cu,classifyPaymentRejection as Su,clearStripePayPalReturn as wu,computeVaultCardThemeColors as ku,darkenHex as Iu,FloPayError as Br,filterStripeMethodsByCountryGate as Ru,getPostalCodeExample as Eu,getPostalCodeLabel as ts,getStateFromPostalCode as _u,getStateLabel as Gi,getStateOptions as Tu,getStripeMethodDisplayName as fa,hasMatchingStripePayPalReturn as Mu,isAuthorizationOnlySession as Yi,isAVSFieldVisible as Kt,isMountableVaultBlock as Au,isPostalCodeSupported as xu,isSetupIntentClientSecret as Ji,isValidEmail as gn,isValidPostalCode as Bu,needsStripeMethodExplicitConfirm as rc,normalizeBeforeButtonClickError as oc,normalizeCheckoutFailureOutcome as Fu,partitionStripeMethods as Du,randomUuidV4 as Ou,readMatchingStripePayPalContinuation as Nu,readStripeRedirectParams as gc,resolveAVSConfig as Lu,resolveButtonsLayoutTheme as zu,resolveSetupFutureUsage as hc,resolveTheme as Uu,resolveVaultMountOptions as Zi,STRIPE_PAYPAL_RESUME_KEY as qu,derivePrimaryTileStyle as ju,stripeExpressMethodToOptionKey as $u,stripeRedirectReturnUrl as Pc,toCssWeight as Wu}from"@flopay/shared";import{ExpressCheckoutElement as vc,PaymentElement as Hu,Elements as no,useElements as as,useStripe as is}from"@stripe/react-stripe-js";import Vu,{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 Xa(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{darkenHex as Ic}from"@flopay/shared";import{Fragment as Fo,jsx as p,jsxs as Xe}from"react/jsx-runtime";var Ir="flopay_stripe_resume",ac="flopay_wallet_resume",bc="fw1",Ku="fw2",Cc=300*1e3,Gu=900,Yu=25e3,Ju=25e3,Zu=1e4,ur={provider:"paypal",paymentMethodCategory:"paypal"},Xu="x-flopay-process-result-source",Qu="status";async function ep(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 Qa={},ma=class{constructor(t){this.reason=t}};function tp(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 ss(e){return`${Ku}:${e}`}function ei(e){return Xt(ss(e))}function ti(e,t){if(typeof window>"u")return null;let n=ss(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>Cc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(ei(e),null):a}catch{return ei(e),null}}function np(e){return Xt(ss(e.sessionId),e)}function ic(e,t,n){let o=ti(e,t);return!o||o.clientSecret!==n?!1:ei(e)}function Xi(e,t,n){if(typeof window>"u")return;ti(e,t)?.clientSecret===n&&ei(e)}function rp(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Qi(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":na(e.status),a=rp(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function sc(e,t,n){let o=null;try{return await Promise.race([_l(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},Zu),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function op(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Sc(e){return e instanceof Br&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ni(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 Sc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var es=qu,ya=new Map,ap=250,lc="Just a moment \u2014 we are finalizing your order. Please press pay again.",ip="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function ls(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 ri({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new Bo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function sp(e){return e instanceof Br&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function wc({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=oa(n),s=i.firstName?i:oa(o?.name);return dr({email:gn(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function lp({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=wc({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 ga=180,cc=`flopay-card-enter ${ga}ms cubic-bezier(0, 0, 0.2, 1) both`,dc=`flopay-card-exit ${ga}ms cubic-bezier(0.4, 0, 0.2, 1) both`,cp=`flopay-buttons-enter ${ga}ms cubic-bezier(0, 0, 0.2, 1) both`,dp=`flopay-buttons-exit ${ga}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function up(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function cs(e){return ju(e)}var pp={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function yp(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 ns={width:"100%",minHeight:ea,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function uc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function rs(e){return e==="paypal"?"PayPal":fa(e)}function mp(e){let t=Eu(e);return`Enter a valid ${ts(e)}${t?` (e.g. ${t})`:""}`}function fp(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 gp(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!gn(n);return{required:t,empty:o,malformed:a,value:n}}function hp(e){return typeof e=="number"?`${e}px`:e}function ds(e){return p(Pp,{...e})}function pc({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=is(),Ie=as(),Y=gt(()=>Xa(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}=sa((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]=gc();if(!I||!ee)return;let F=Nu(ee);if(!F)return;He.current=!0;let Se=!0,mt=ya.get(ee);mt||(mt=Oe==="failed"?Promise.resolve(null):Promise.resolve().then(()=>N.retrievePaymentIntent(ee)),ya.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){ya.delete(ee),wt(),i?.(d.error.message??"Failed to retrieve PayPal payment status.");return}if(wu(),ya.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;ya.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 lp({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 ni(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:Pc()};if(m?.id&&(J.payment_method=m.id),!Xt(es,{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(es),Ba(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:Mi(me)})),await ri({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(es);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:ea,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(vc,{onReady:I=>lt(Ai(I,["paypal"])),onLoadError:()=>{lt("load_error"),ls(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:ns,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(xi,{state:Fe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:O,children:Et})}function yc(e){return e==="apple_pay"||e==="google_pay"}function mc({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=is(),Ie=as(),Y=gt(()=>Xa(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(()=>ti(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}=sa((_,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:yc,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,...yc(_)?{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 _=ti(e,t);if(!_)return;let d=!1,m=!1,A=async()=>{if(!m){m=!0,d||be("checking");try{let T=await sc(N,_.clientSecret,Ee.current);if(d)return;let J=Qi(T,_.providerObjectId,Ji(_.clientSecret));if(J.kind==="confirmed"){if(!ic(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"){Xi(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=uc(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(Qa)},Yu),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=wc({event:_,fallbackEmail:Rn?.email??n,fallbackName:[Rn?.firstName,Rn?.lastName].join(" ").trim()||z});if(!gn(kt.email)){m("Buyer details are required."),Te(rs(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",ni(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=np({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?.()},Ju),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=Qi(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&&!ic(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=`${bc}:${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 sc(N,xt,Ee.current);if(Bt||ae)return;let et=Ji(xt),u=Qi(ce,en.providerObjectId,et);if(u.kind==="confirmed"){Xn(et?{setupIntent:ce}:{paymentIntent:ce});return}if(u.kind==="terminal"){if(ae=!0,Xi(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(Ji(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 ma(tp(ce));if(tn=ce,!tn.error&&!Zn(tn))throw new ma("confirmation_result_unconfirmed");En=on(tn.error?"returned_error":"resolved",tn.error&&Ba(tn.error)?"provider_declined":void 0)}catch(ce){let et=ce instanceof ma?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}:Ni(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(Ba(Sn)){ae=!0,Xi(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:Mi(Sn)})),ri({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({...Ni(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===Qa){let Le=H?.now()??globalThis.performance?.now()??Date.now();H?.error({errorCode:op(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===Qa?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",A?.generation,Ve===Qa)}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(()=>yl(i),[i]),wt=gt(()=>i.map($u),[i]);return Xe(Fo,{children:[p(xi,{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:ns,children:["Try ",rs(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:ns,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(vc,{onReady:_=>{lt(Ai(_,wt))},onLoadError:_=>{lt("load_error"),ls(Y,"stripe","wallet","provider_error")},onClick:async _=>{let d=Y?.now()??globalThis.performance?.now()??Date.now();Me.current=_.expressPaymentType,U.current=uc(_.expressPaymentType);let m=!0,A=window.setTimeout(()=>{m=!1,_.reject()},Gu),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:{...ml,paymentMethods:Ne,emailRequired:zt,billingAddressRequired:zt}},ke)})]})}),ze&&p(Sr,{status:"processing"})]})}function kc(e,t,n){let o=hc(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function os({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=is(),Ie=as(),[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=oa(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 ni(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 ri({billingApiUrl:s,sessionId:je,nonce:$e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ee.code??"provider_declined"}});return}let Ae=Je?.status;if(!na(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(Hu,{onReady:()=>pe("ready"),onLoadError:()=>{pe("load_error"),ls(pn(P),"stripe","apm")},onChange:Q=>{ct(!!Q.complete)},options:{layout:fl,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...gn(o?.trim())?{email:o?.trim()}:{}}}}}),p(gl,{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 ${fa(e)}`}),v&&p(Eo,{margin:"0.75rem 0 0",children:v})]})}function fc({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=oa([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(fa(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 ni(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 ri({billingApiUrl:i,sessionId:M,nonce:Ce,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ye,providerDeclineReason:Je.code??"provider_declined"}});return}let Qe=Ae?.status;if(!na(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||(rc(ye)?Y?Y(ye):je(ye):ke(ye))},[$e,V,ke,Y]),be=gt(()=>Q?kc(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(Vu.Fragment,{children:[p(pl,{method:ye,themeId:Ie,submitting:M,disabled:Ce,highlighted:re,hasNextStep:rc(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(os,{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 Pp({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=Li(),Ne=Do(cr),{emitInstrument:wt}=Do(Gn),_=G(null);_.current||(_.current=Ua());let d=_.current,[,m]=ie(0),A=G(null);A.current||(A.current=Qo());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=Ol(),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(()=>Yi(I),[I]),Qn=Au(I?.vault),tn=!!I?.gateways?.pcivault,En=Ml(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 hu({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 fp(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(()=>Zi(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()},ga)},[]);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(()=>ku({appearance:q,buttonsStyles:S,layout:ze}),[q,S,ze]),ge=Ne.inlineSessionPatchProcessing??!1,_e=(ve??oe)||ge,dt=at.replace(/\/+$/,""),Ze=gt(()=>Oi({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(" "),Cs=!gn(Ze.email?.trim()),li=G(null);u&&li.current===null&&(li.current=Cs);let Lr=u&&(li.current??Cs),ci=gt(()=>gp(Qt,Lr),[Qt,Lr]),ao=ci.empty||ci.malformed,qn=gt(()=>Se?Se.getRawProvider():null,[Se]),Ss=gt(()=>mt?mt.getRawProvider():null,[mt]),Uo=De||100,io=bt.toLowerCase(),di=gt(()=>q?Pu(q):null,[q]),so=di,ws=gt(()=>{let r=di??{},g=r.rules??{};return{...r,rules:{...g,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...g[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...g[".AccordionItemContents"]??{}}}}},[di]),ks=gt(()=>({...Tl(De,ft?.captureMethod,me),currency:io,...so?{appearance:so}:null}),[De,io,ft?.captureMethod,me,so]),ui=hc(me,"paypal","paypal"),Is=gt(()=>({mode:"payment",amount:Uo,currency:io,captureMethod:"manual",...ui?{setupFutureUsage:ui}:null,...so?{appearance:so}:null}),[Uo,io,ui,so]),ue=Ye(r=>{yn(r),v?.(r)},[v]),Rs=G(0);ht(()=>{an!==Rs.current&&(Rs.current=an,ue(null))},[an,ue]);let pi=G(""),[Es,Lc]=ie(!1),yi=Ye(()=>{Lc(!0)},[]);ht(()=>{if(!u||!Lr||!Be||!Es||ao||pi.current)return;let r=dr({email:gn(Ze.email?.trim())?Ze.email?.trim():on.current.trim(),firstName:Ze.firstName?.trim(),lastName:Ze.lastName?.trim()});pi.current=JSON.stringify(r),en(g=>({...g,...r})),Promise.resolve(Be(r)).catch(g=>{pi.current="",ue(g instanceof Error?g.message:"Failed to attach buyer details.")})},[u,Lr,Be,Es,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=xa(rs(r),fe,T.inAppBrowser),X=go(g),Rt=(X?.toLowerCase()==="error"?void 0:X)??dl(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=Zi(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=Zi(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 mi=G(!1),_s=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}}:{}}},[]),Ts=G(H);Ts.current=H,ht(()=>{H||rt!==lc||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;mi.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")},ap),x("processing");let Ge=ir.current;if(!Ge.sessionId||!Ge.nonce)return;let st=_s();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(!sp(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(mi.current)return;mi.current=!0;let st=ir.current,ut=Yi(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(ip);return}if(!Ts.current){mr(!0);return}yi(),ir.current.updateError(lc)});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,yi,_s]);let br=!!yt?.clientId,qo=Array.isArray(Ie),Ca=qo&&Ie.length>0,Ms=qo&&Ie.includes("paypal"),Sa=G(null);Sa.current===null&&(Sa.current=Mu());let co=Sa.current?"redirect":ul(T,N,d.current()),{expressMethods:wa,paymentElementMethods:fi}=gt(()=>Du(Ie,{excludePaypal:br}),[Ie,br]),As=br||!!mt||Ms&&co==="redirect",zc=gt(()=>As?wa.filter(r=>r!=="paypal"):wa,[wa,As]),Uc=gt(()=>{let r=[];return Fe&&r.push("apple_pay"),lt&&r.push("google_pay"),r},[Fe,lt]),uo=qo?zc:Uc,qc=he&&uo.length>0,xs=Zn?qt:M,ka=gt(()=>Ru(fi,xs,Y),[fi,xs,Y]),gi=gt(()=>({mode:"payment",amount:Uo,currency:io,paymentMethodCreation:"manual",appearance:ws}),[Uo,io,ws]),[Bs,Fs]=ie("loading"),[Ds,Os]=ie("loading"),[Ns,Ls]=ie("loading"),[jc,hi]=ie(!1),[zs,Pi]=ie("loading"),[vi,$c]=ie();ht(()=>{$c(Qo())},[]);let Ia=vi?.inAppBrowser,Ra=vi?Fa(vi,yt?.approvalPresentation,We??(Et?"subscription":"order")):"popup",Us=P&&(br||(qo?Ms:Ia===!1)),qs=he&&qc,jo=(!Ct||!!Ne.waitForDataAttachment)&&Us&&br,js=zs==="retrying"||zs==="exhausted",$o=null;he&&(mt?$o=Ss:co==="redirect"&&($o=qn));let $s=gt(()=>({...J,presentationMode:co}),[J,co]),Wo=!Ct&&Us&&!!$o&&(!br||js),po=!Ct&&qs&&!!qn,Ho=!Ct&&he&&Ca&&ka.length>0&&!!qn,Wc=jo&&!js?jc:Wo&&Bi(Bs),Hc=po&&Bi(Ds),Vc=Ho&&Ns!=="load_error",Ws=r=>r==="loading"||r==="ready",Hs=jo||Wo&&Ws(Bs)||po&&Ws(Ds)||Ho&&Ns!=="load_error",Ea=G(!1);ht(()=>{if(!Ea.current){if(!he&&!P){Ea.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){Ea.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(Ia!==void 0&&!Ct&&!et&&!Hs){Ea.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,Ia,Ct,et,Hs,c,ue]);let Vs=G(!1);ht(()=>{if(Vs.current||!Ca)return;let r=[];Fe!==!0&&r.push("showApplePay"),lt!==!0&&r.push("showGooglePay"),r.length!==0&&(Vs.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.`))},[Ca,Fe,lt]);let Ks=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=oc(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 Ks(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=oc(r,g);return ue(W.message),c?.(W),{proceed:!1}}},[Ks,Ne.inlineSessionDraft,Ne.waitForDataAttachment,Ct,je,c,e,ue]),Gs=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=Oi(Ze,g?.accountPatch),X=g?.completionPaymentMethodId??ra(r),Rt=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,lr=up(r),Ge=g?.presentationMode?Xa(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??yp(r),tokenizedData:Rt,accountData:{...g?.accountPatch,userId:D.userId??"",email:D.email??"",firstName:D.firstName||void 0,lastName:D.lastName||void 0,...bu({avsConfig:ae,country:Cn.current,zip:xt.current,city:fn.current,state:Dt.current,addressLine1:ln.current,addressLine2:Ft.current})},...vu({chv:z,avsCheck:Je,checkoutType:Ae,checkoutLayout:Qe,avsConfig:ae,country:Cn.current})}),Jr=async dn=>{let Zr=Yi(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 il=Zo.message??"PayPal payment failed.";ue(il),vr("paypal",il,{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}hi(!1),Pi("loading"),Pe({orderId:dn,attempts:Zr+1}),x(null);return}if(Ot.headers.get(Xu)===Qu){let dn=await ep(ut,W,fe);if(dn!==void 0){await Jr(dn);return}}Su(Ot.status,jn)?Ge?.terminal({outcome:"payment_declined",...ur,terminalReason:"provider_declined"}):st(),x("error");let al=jn?.message??"Payment failed. Please try again.";ue(al),vr(r.isPaypal?"paypal":"card",al,{code:jn?.code??jn?.gatewayErrorCode,declineCode:jn?.declineCode??jn?.gatewayDeclineReason}),await new Promise(dn=>setTimeout(dn,400))}catch(ut){Sc(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):Gs(r,g)},[C,Gs]),Vo=`${bc}:${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>Cc||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 Ys=G(!1);ht(()=>{if(typeof window>"u"||Ys.current)return;let[r,g,W]=gc();if(!r||!g||Sa.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(ac),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;Ys.current=!0,Xt(Ir),Xt(ac),window.history.replaceState({},"",Pc());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=na(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 bi=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,Kc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ci=xn?.colorBackground,Gc=Ci&&!Kc.has(Ci)?Ci:void 0,Go=S.cardInputBorder??(Ko?"#e5e7eb":"#A4A4FF"),Js=xn?.colorDanger??"#dc2626",Vt=r=>tr[r]&&(hr[r]||$t),_a=ao&&(gr||$t),Vn=r=>r?Js:Go,Ta=(Ln.malformed||Ln.empty)&&(fr||$t),Yc=Vn(Ta),Si=S.cardFormContainer?.backgroundColor??Gc??(Ko?"white":"#EDEDFF"),yo=S.cardInputBackground??xn?.colorBackground??"white",wi=ho(Re),Zs=ho(He),mo=S.nameInput,Xs=S.cardInputFontSize??hp(mo?.fontSize)??xn?.fontSizeBase??"16px",Qs=typeof mo?.fontFamily=="string"?mo.fontFamily:xn?.fontFamily??"Poppins, sans-serif",el=Wu(mo?.fontWeight)??400,Jc=S.cardInputColor??(typeof mo?.color=="string"?mo.color:void 0)??xn?.colorText??"#262833",Zc=S.cardInputPlaceholderColor??"#9ca3af",Zt=xn?.borderRadius??"8px",Gr=xn?.borderRadius??S.cardButton?.borderRadius??Zt,Yr=xn?.colorPrimary??"#4A49FF",Xc=xn?.colorPrimaryHover??Iu(Yr,.12),ki=xn?.colorText??"#262833",Ii={fontSize:Xs,fontFamily:Qs,fontWeight:el,color:Jc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Yo={marginTop:"0.375rem",...Ii,fontSize:"0.75rem",lineHeight:1.4,color:Js},Qc={"--flopay-input-placeholder-color":Zc,"--flopay-input-font-size":Xs,"--flopay-input-font-family":Qs,"--flopay-input-font-weight":String(el)},Jo=S.cardFormContainer??{},Ri=Jo.padding??(Ko?"0":"1rem"),Ei=Jo.borderRadius??Zt,ed=It&&or?p(_i,{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"}),tl=Xe("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&_r()},style:{backgroundColor:Si,borderRadius:Ei,...Jo,padding:Ri,...Qc,display:"flex",flexDirection:"column"},children:[p("style",{children:`
|
|
3
|
+
${wt.join(`
|
|
4
|
+
`)}`]}):null;return ot&&!j?fe?to("div",{children:Wt}):null:qi("div",{children:[Wt,Ue&&to(Io,{identity:Ue.identity,methodLabel:Ue.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:se,onCancel:()=>se(null)}),qi("div",{"aria-hidden":Ye||Ue?!0:void 0,style:Ye||Ue?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ja},children:[!Me&&!Ye&&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:ee,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ja,display:"flex",opacity:Me?1:0},"aria-busy":E||v},Ze)]},Ze),De&&to("button",{ref:he,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:bn,style:tu,children:"Try PayPal again"})]})}function $a(e){return to(jl,{...e})}function $l(e){return to(jl,{...e})}import{jsx as Wl,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&&Wl("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Wl("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 Wa,clearCachedInlineSession as ji,hashCreateParams as Hl,legacyCachedSessionMatchesDraft as Vl,persistCachedInlineIdempotencyKey as Ha,persistCachedInlineSession as Va,readCachedInlineIdempotencyKey as Kl,readCachedInlineSession as Gl,serializeCreateParams as ca}from"@flopay/shared";import{resolveBillingApiUrl as iu}from"@flopay/shared";import{useEffect as Hr,useMemo as su,useRef as Yl,useState as Jl}from"react";import{jsx as lu}from"react/jsx-runtime";function Ka({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=Jl(e instanceof Promise?null:e),[c,f]=Jl(t instanceof Promise||!t?null:t),C=Yl(null),T=Yl(null),I=Ro(o);Hr(()=>{I({class:"lifecycle",name:"checkout.mount"})},[I]),Hr(()=>{i&&I({class:"lifecycle",name:"sdk.initialize.ready"})},[I,i]),Hr(()=>{if(i)return mn(i)?.subscribe?.(I)},[I,i]),Hr(()=>{if(!(!c||c===i))return mn(c)?.subscribe?.(I)},[I,i,c]),Hr(()=>{if(!i)return;let O=mn(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(Se=>{O||s(Se)},()=>{O||I({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{O=!0}},[I,e]),Hr(()=>{let O=!1;if(!t){f(null);return}return t instanceof Promise?t.then(Se=>{O||f(Se)},()=>{O||I({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):f(t),()=>{O=!0}},[I,t]),Hr(()=>{if(!i||T.current===i)return;T.current=i;let O=mn(i);O?.log({name:"checkout.rendered",stage:"checkout_render"}),I({class:"lifecycle",name:"checkout.rendered"}),O?.performance({stage:"checkout_render",durationMs:O.elapsed(C.current??0),durationMode:"machine"})},[I,i]);let z=iu(n?.billingApiUrl),ie=su(()=>({flopay:i,paypalFlopay:c,billingApiUrl:z,emitInstrument:I}),[i,c,z,I]);return lu(Jn.Provider,{value:ie,children:a})}import{markSessionRecentlyCompleted as _o,wasSessionRecentlyCompleted as $i}from"@flopay/shared";async function Ga(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 Zl,PaymentAPI as Ja,runSavedCardChallenge as du}from"@flopay/js";import{classifyPaymentRejection as uu,FloPayError as Et,isAuthorizationOnlySession as pu,isMountableVaultBlock as yu,isSetupIntentClientSecret as mu,normalizeCheckoutFailureOutcome as Xl}from"@flopay/shared";var ua="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 Et("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function hu(){return new Et("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Hi(e,t){return Object.assign(e,{checkoutMethod:t})}function xr(e,t){let n=e instanceof Et?e:new Et(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 da(e,t){try{return await e()}catch(n){throw xr(n,t)}}function ec(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 tc(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 Ja(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:T=>kr({type:T.declineReason??"authorization_declined",gatewayErrorCode:T.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},s)}catch(T){if(a.aborted||T instanceof Error&&T.name==="AbortError")throw T instanceof Et&&T.code==="three_ds_aborted"?T:To(T);if(!(T instanceof Et)||T.code!=="three_ds_timeout"&&T.code!=="checkout_processing_timeout")throw T;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 Et)||z.code!=="checkout_processing_timeout")throw z}let I=f&&qr(f,t.session);if(!Ar(I)&&I?.status!=="expired"){if(t.telemetry){let z=new Ja(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=Hi(new Et(i,"api_error",{code:e?.code??Xl(e?.outcome)??Xl(e?.type)??e?.gatewayErrorCode}),o);return e?.orderId&&(s.orderId=e.orderId),s}function Wi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ya(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function nc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ya(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||Ya(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 T of C)if(typeof T=="string"&&T.length>0&&(!t?.requirePaymentIntentClientSecret||Ya(T)))return T}}}}async function Pu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=nc(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 Ja(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ya(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,T=n.customer?.id??n.accountData?.userId??"",I=n.customer?.email??n.accountData?.email??"",z=n.customer?.firstName??n.accountData?.firstName??"",ie=n.customer?.lastName??n.accountData?.lastName??"",O=n.customer?.country??n.accountData?.country??void 0,Se=n.customer?.zip??n.accountData?.zip??void 0,v=await new Ja(c,s===!1?{telemetry:!1}:void 0).processPayment(T,{sessionId:f,nonce:C,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:T,email:I,firstName:z,lastName:ie,country:O,zip:Se},returnUrl:i??Wi(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:ra(a),checkoutMethod:Ql(a,n)}};let _e=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",..._e?{paymentIntentId:_e}:{},paymentMethodId:ra(a),checkoutMethod:Ql(a,n)}}}let P;try{P=await v.json()}catch(N){throw new Et("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=nc(P);if(!N)throw new Et("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 Hi(new Et("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ve=new Et(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(ve,{telemetryOutcome:uu(v.status,P)})}async function Za(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:c,telemetry:f,signal:C}){let T=t?.getRawProvider();if(!T)throw xr(new Et("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw Hi(new Et("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let I=mu(e.threeDSecureToken),z=null,ie=e.paymentMethodId,O=await da(()=>fu(T,e.threeDSecureToken,I),"card");if(O){if(O.error)throw xr(new Et(O.error.message??`Failed to retrieve 3DS ${I?"setup":"payment"} status.`,"api_error",{code:O.error.code}),"card");let G=O.intent;!ie&&G?.payment_method&&(typeof G.payment_method=="string"?ie=G.payment_method:"id"in G.payment_method&&(ie=G.payment_method.id??void 0))}let Se=ie?await da(()=>gu(T,e.threeDSecureToken,{payment_method:ie,return_url:c??Wi(s)??window.location.href},I),"card"):null;if(Se){if(Se.error)throw xr(new Et(Se.error.message??"3DS authentication failed.","api_error",{code:Se.error.code}),"card");z=Se.intent}else{let G=await da(()=>T.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(G.error)throw xr(new Et(G.error.message??"3DS authentication failed.","api_error",{code:G.error.code}),"card");z=(I?G.setupIntent:G.paymentIntent)??null}if(z&&(z.status==="requires_capture"||z.status==="succeeded"||z.status==="processing")){let G=await Ao({billingApiUrl:a,sessionId:i,session:s,telemetry:f,tokenizedData:{id:z.id,type:"card",threeDSecureActionResultTokenId:z.id},returnUrl:c});return G.type==="success"?{...G.result,paymentIntentId:G.result.paymentIntentId??z.id,paymentMethodId:G.result.paymentMethodId??ie}:G.type==="next_action_required"?Mo(G,{billingApiUrl:a,sessionId:i??s.id,session:s,signal:C}):Za(G,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:c,telemetry:f,signal:C})}throw xr(new Et("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let I=(n??t)?.getRawProvider();if(!I)throw xr(new Et("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:ie}=await da(()=>I.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(ie)throw xr(new Et(ie.message??"PayPal authorization failed.","api_error",{code:ie.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:z}=await da(()=>I.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Wi(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(z)throw xr(new Et(z.message??"PayPal authorization failed.","api_error",{code:z.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Et("Unsupported payment redirect state.","api_error")}function pa(e){if(e instanceof Et){let o=wo(e.message);return o&&o!==e.message?Object.assign(new Et(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 Et(n,"api_error")}function Vi(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 Et("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 Ql(e,t){return e?e.isPaypal?"paypal":"card":t&&Qr(t)?"card":void 0}async function Ki({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([Zl(e,{billingApiUrl:n,locale:o,telemetry:a}),i?Zl(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 Et("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,buildWalletSheetWindowMessage as wu,COUNTRY_OPTIONS as ku,classifyPaymentRejection as Iu,clearStripePayPalReturn as Ru,computeVaultCardThemeColors as Eu,darkenHex as _u,denyPaymentPermissionToNewFrames as Tu,FloPayError as Br,filterStripeMethodsByCountryGate as Mu,getPostalCodeExample as Au,getPostalCodeLabel as ts,getStateFromPostalCode as xu,getStateLabel as Gi,getStateOptions as Bu,getStripeMethodDisplayName as fa,hasMatchingStripePayPalReturn as Fu,isAuthorizationOnlySession as Yi,isAVSFieldVisible as Yt,isMountableVaultBlock as Du,isPostalCodeSupported as Ou,isSetupIntentClientSecret as Ji,isValidEmail as Pn,isValidPostalCode as Nu,isWalletSheetRefusedForWindowSize as Lu,needsStripeMethodExplicitConfirm as rc,normalizeBeforeButtonClickError as oc,normalizeCheckoutFailureOutcome as zu,partitionStripeMethods as Uu,randomUuidV4 as qu,readMatchingStripePayPalContinuation as ju,readStripeRedirectParams as hc,resolveAVSConfig as $u,resolveButtonsLayoutTheme as Wu,resolveSetupFutureUsage as Pc,resolveTheme as Hu,resolveVaultMountOptions as Zi,STRIPE_PAYPAL_RESUME_KEY as Vu,derivePrimaryTileStyle as Ku,shouldPreferWalletPopup as ac,stripeExpressMethodToOptionKey as Gu,stripeRedirectReturnUrl as vc,toCssWeight as Yu,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as bc}from"@flopay/shared";import{ExpressCheckoutElement as Cc,PaymentElement as Ju,Elements as no,useElements as as,useStripe as is}from"@stripe/react-stripe-js";import Zu,{useCallback as Ge,useContext as Do,useEffect as pt,useLayoutEffect as Xu,useMemo as vt,useRef as K,useState as ae}from"react";function xo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Xa(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{darkenHex as Ec}from"@flopay/shared";import{Fragment as Fo,jsx as d,jsxs as Ke}from"react/jsx-runtime";var Ir="flopay_stripe_resume",ic="flopay_wallet_resume",Sc="fw1",Qu="fw2",wc=300*1e3,ep=900,tp=25e3,np=25e3,rp=1e4,cr={provider:"paypal",paymentMethodCategory:"paypal"},op="x-flopay-process-result-source",ap="status";async function ip(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 Qa={},ma=class{constructor(t){this.reason=t}};function sp(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function en(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function ss(e){return`${Qu}:${e}`}function ei(e){return en(ss(e))}function ti(e,t){if(typeof window>"u")return null;let n=ss(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>wc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(ei(e),null):a}catch{return ei(e),null}}function lp(e){return en(ss(e.sessionId),e)}function sc(e,t,n){let o=ti(e,t);return!o||o.clientSecret!==n?!1:ei(e)}function Xi(e,t,n){if(typeof window>"u")return;ti(e,t)?.clientSecret===n&&ei(e)}function cp(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Qi(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":na(e.status),a=cp(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function lc(e,t,n){let o=null;try{return await Promise.race([_l(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},rp),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function dp(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function kc(e){return e instanceof Br&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ni(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 kc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var es=Vu,ya=new Map,up=250,cc="Just a moment \u2014 we are finalizing your order. Please press pay again.",pp="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function ls(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 ri({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new Bo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function yp(e){return e instanceof Br&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ic({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=oa(n),s=i.firstName?i:oa(o?.name);return lr({email:Pn(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function mp({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=Ic({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return Pn(s.email)?s:i(a,s)}var ga=180,dc=`flopay-card-enter ${ga}ms cubic-bezier(0, 0, 0.2, 1) both`,uc=`flopay-card-exit ${ga}ms cubic-bezier(0.4, 0, 0.2, 1) both`,fp=`flopay-buttons-enter ${ga}ms cubic-bezier(0, 0, 0.2, 1) both`,gp=`flopay-buttons-exit ${ga}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function hp(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function cs(e){return Ku(e)}var Pp={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function vp(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 ns={width:"100%",minHeight:ea,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function pc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function rs(e){return e==="paypal"?"PayPal":fa(e)}function bp(e){let t=Au(e);return`Enter a valid ${ts(e)}${t?` (e.g. ${t})`:""}`}function Cp(e,t,n){let o=Ou(e),a=t.trim(),i=n&&o,s=i&&!a,c=i&&!!a&&!Nu(e,a);return{visible:n,supported:o,required:i,empty:s,malformed:c}}function Sp(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!Pn(n);return{required:t,empty:o,malformed:a,value:n}}function wp(e){return typeof e=="number"?`${e}px`:e}function ds(e){return d(Rp,{...e})}function yc({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:s=!1,onButtonClick:c,onDecline:f,onTechnicalFailure:C,runBeforeButtonClick:T,billingName:I,onBuyerIdentityReady:z,onLoadStateChange:ie,placeholderBorderRadius:O,popupCapabilityOwner:Se,externalTelemetryContext:G,presentationMode:v}){let P=jr(),{emitInstrument:ve}=Do(Jn),N=is(),_e=as(),Y=vt(()=>Xa(mn(P),G),[G,P]),[Ne,yt]=ae("loading");pt(()=>{ie?.(Ne)},[Ne,ie]);let[Be,mt]=ae(!1),Nt=K(!1),fe=!Pn(n?.trim())||!I?.trim(),{request:Fe,collect:bt,finish:Te}=ko(),qe=K(!1),Re=K(null),ee=K(null),[je,lt]=ae(0),[It,rt]=ae(!1),ce=K(!1),X=K(new Map),{startAttempt:L,finishAttempt:he,invalidateAttempt:$e,isAttemptInvalidated:Me,isAttemptCurrent:A,generationRef:Ye}=sa((E,ne,Ue)=>{C?.(E,ne,{...Ue,popupBlocked:Ue?.popupBlocked??zr(ne),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:v,terminalReason:"overlay_timeout"}),rt(!0),lt(M=>M+1)},{onHandoffObserved:()=>{Se.markAvailable(),Y?.log({name:"provider.popup.opened",stage:"overlay_open",...cr,attempt:Ye.current})}});pt(()=>{It&&ee.current?.focus()},[It,je]);let Je=Ge(()=>{lt(E=>E+1)},[]),Ze=Ge((E,ne,Ue)=>{$e(Ue),C?.("paypal",E,{code:ne,popupBlocked:zr(E),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:v}),rt(!0),Je()},[$e,C,v,Je]),We=Ge(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);pt(()=>{ce.current&&(ce.current=!1,We())},[We,je]);let ze=Ge(()=>{rt(!1),i?.(null),We()},[We,i]);pt(()=>{if(!N||qe.current)return;let[E,ne,Ue]=hc();if(!E||!ne)return;let M=ju(ne);if(!M)return;qe.current=!0;let se=!0,Xe=ya.get(ne);Xe||(Xe=Ue==="failed"?Promise.resolve(null):Promise.resolve().then(()=>N.retrievePaymentIntent(ne)),ya.set(ne,Xe));let we={accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce},ht=()=>{Y?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...cr,requestCategory:"provider_sdk"})};return Y?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...cr}),(async()=>{try{mt(!0);let m=await Xe;if(!se)return;if(m?.error){ya.delete(ne),ht(),i?.(m.error.message??"Failed to retrieve PayPal payment status.");return}if(Ru(),ya.delete(ne),Ue==="failed"){let Ee="PayPal payment was declined. Please try again.";Y?.terminal({outcome:"payment_declined",...cr,terminalReason:"provider_declined"}),i?.(Ee),f?.(yn("paypal",Ee));return}let w=m?.paymentIntent;if(w&&w.id!==E){ht(),i?.("Failed to match the returned PayPal payment.");return}if(w&&(w.status==="requires_capture"||w.status==="succeeded")){let Ee=typeof w.payment_method=="string"?w.payment_method:w.payment_method?.id;a({id:Ee??w.id,type:"card",threeDSecureActionResultTokenId:w.id,isPaypal:!0},{...we,presentationMode:"redirect"})}else{let Ee="PayPal payment was not completed. Please try again.";Y?.terminal({outcome:w?.status==="canceled"?"payment_cancelled":"payment_declined",...cr,terminalReason:w?.status==="canceled"?"cancelled":"provider_declined"}),i?.(Ee),f?.(yn("paypal",Ee))}}catch(m){if(!se)return;ya.delete(ne),ht(),i?.(m instanceof Error?m.message:"Failed to complete PayPal payment.")}finally{se&&mt(!1)}})(),()=>{se=!1,qe.current=!1}},[N,a,i,f,Y]);let De=Ge(async(E=!1)=>{let ne=T?await T("paypal"):{proceed:!0};if(!ne.proceed)return X.current.delete(je),!1;let Ue=L("paypal");return X.current.set(je,{generation:Ue,accountPatch:ne.accountPatch,sessionId:ne.sessionId,nonce:ne.nonce}),rt(!1),Y?.log({name:`provider.${E?"redirect.started":"handoff.requested"}`,stage:E?"redirect":"overlay_open",...cr,attempt:Ue}),c?.("paypal"),!0},[c,Y,T,L,je]),be=Ge(async E=>{if(s||Be||!await De()){E.reject();return}E.resolve()},[s,De,Be]),Ct=Ge(async E=>{if(!N||!_e)return;let ne=X.current.get(je);if(ne&&!A(ne.generation)){X.current.delete(je);return}if(!ne&&Me()||ne&&!he(ne.generation))return;ne||he();let Ue=ne??null;if(X.current.delete(je),!Ue&&T){let Xt=await T("paypal");if(!Xt.proceed){E.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Ue={accountPatch:Xt.accountPatch,sessionId:Xt.sessionId,nonce:Xt.nonce}}let M=Ue?.sessionId??e,se=Ue?.nonce??t,Xe=await mp({event:E,prepared:Ue,email:n,billingName:I,methodLabel:"PayPal",collect:bt});if(!Xe){E.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let we=Xe.email,ht={...Ue?.accountPatch,...lr(Xe,!0)};try{if(mt(!0),i?.(null),!M||!Pn(we))throw new Error("Missing sessionId or email for PayPal payment");await z?.(Xe);let Xt=N.createPaymentMethod,{error:m,paymentMethod:w}=await Xt({type:"paypal"});if(m){Ze(m,"stripe_paypal_create_payment_method_failed",ne?.generation),E.paymentFailed({reason:"fail"});return}let Ee=await ni(o,ve,M,se??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:w?.id??null,intentKind:"payment"});if(Ee.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let de=Ee.clientSecret,y={return_url:vc()};if(w?.id&&(y.payment_method=w.id),!en(es,{clientSecret:de,sessionId:M,nonce:se,accountPatch:ht})&&v==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:_,paymentIntent:F}=await N.confirmPayment({clientSecret:de,confirmParams:y,redirect:"if_required"});if(_){if(en(es),Ba(_)){let et=_.message??"Your payment was declined.";Y?.terminal({outcome:"payment_declined",...cr,terminalReason:"provider_declined"}),i?.(et),f?.(yn("paypal",et,{code:go(_),declineCode:Mi(_)})),await ri({billingApiUrl:o,sessionId:M,nonce:se,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:go(_)??"provider_declined"}})}else Ze(_,"stripe_paypal_confirm_failed",ne?.generation);return}en(es);let j=typeof F?.payment_method=="string"?F.payment_method:F?.payment_method?.id;a({id:j??F?.id,type:"card",threeDSecureActionResultTokenId:F?.id,isPaypal:!0},{accountPatch:ht,paymentMethodCategory:"paypal",presentationMode:v,sessionId:M,nonce:se});return}catch(Xt){Ze(Xt,"stripe_paypal_failed",ne?.generation)}finally{mt(!1)}},[N,_e,e,t,n,I,bt,z,o,ve,a,i,f,T,Ze,he,A,Me,Y,v,je]),Zt=Ge(async()=>{if(!(Nt.current||s||Be||!N||!_e)){Nt.current=!0,mt(!0);try{if(!await De(!0))return;await Ct({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Nt.current=!1,mt(!1)}}},[_e,Ct,s,De,N,Be]),ot=v==="redirect"?d("button",{type:"button",disabled:s||Be,onClick:()=>{Zt()},style:{width:"100%",minHeight:ea,border:"1px solid #d1d5db",borderRadius:O??8,background:"#ffc439",color:"#111827",cursor:s||Be?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):d(Cc,{onReady:E=>yt(Ai(E,["paypal"])),onLoadError:()=>{yt("load_error"),ls(Y,"paypal","paypal","provider_error")},onClick:be,onConfirm:Ct,onCancel:()=>{let E=X.current.get(je);X.current.delete(je),Y?.terminal({outcome:"payment_cancelled",...cr,terminalReason:"cancelled",...E?{attempt:E.generation}:{}}),$e(E?.generation),rt(!1),ce.current=!0,Je()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:fe,emailRequired:fe,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},je),Lt=Ke(Fo,{children:[Ke("div",{ref:Re,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[It&&d("button",{ref:ee,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ze,style:ns,children:"Try PayPal again"}),Fe&&d(Io,{identity:Fe.identity,methodLabel:Fe.methodLabel,onComplete:Te,onCancel:()=>Te(null)},Fe.id),d("div",{style:{display:Fe?"none":void 0},children:ot})]}),Be&&!Fe&&d(Sr,{status:"processing"})]});return v==="redirect"?Lt:d(xi,{state:Ne,placeholderTestId:"flopay-paypal-placeholder",borderRadius:O,children:Lt})}function mc(e){return e==="apple_pay"||e==="google_pay"}var kp=200;function Ip({active:e}){return Xu(()=>e?Tu(document):void 0,[e]),null}function fc({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:s,onErrorChange:c,onButtonClick:f,onDecline:C,onTechnicalFailure:T,runBeforeButtonClick:I,billingName:z,onBuyerIdentityReady:ie,onLoadStateChange:O,placeholderBorderRadius:Se,popupCapabilityOwner:G,externalTelemetryContext:v}){let P=jr(),{emitInstrument:ve}=Do(Jn),N=is(),_e=as(),Y=vt(()=>Xa(mn(P),v),[v,P]),[Ne,yt]=ae("loading");pt(()=>{O?.(Ne)},[Ne,O]);let[Be,mt]=ae(!1);pt(()=>{rt.current=Be},[Be]);let Nt=K(!Pn(n?.trim())||!z?.trim()).current,{request:fe,collect:Fe,finish:bt}=ko(),Te=K(null),qe=K(null),[Re,ee]=ae(0),[je,lt]=ae(()=>ac()),It=K(je),rt=K(!1),[ce,X]=ae(!1),[L,he]=ae(()=>ti(e,t)?"blocked":"idle"),[$e,Me]=ae("google_pay"),A=K(null),Ye=K(!0),Je=K(!1),Ze=K("google_pay"),We=K("google_pay"),ze=K(null),De=K(null),be=K(new Set),Ct=K(null),Zt=K(null);pt(()=>(Ye.current=!0,()=>{Ye.current=!1;for(let y of be.current)window.clearTimeout(y);be.current.clear()}),[]);let ot=K(new Map),{startAttempt:Lt,finishAttempt:E,invalidateAttempt:ne,isAttemptInvalidated:Ue,isAttemptCurrent:M,generationRef:se}=sa((y,re,_)=>{T?.(y,re,{..._,popupBlocked:_?.popupBlocked??zr(re),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Me(y),X(!0),ee(F=>F+1)},{onHandoffObserved:y=>{Zt.current=se.current,G.markAvailable(),Y?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:se.current,...y==="apple_pay"||y==="google_pay"?{walletType:y}:{}})},defersMissingTerminal:mc,onMissingTerminalDeferred:(y,re)=>{let _=Y?.now()??globalThis.performance?.now()??Date.now(),F=Ct.current,j=F?.generation===re?F.startedAt:_;Y?.performance({stage:"overlay_return",durationMs:Math.max(0,_-j),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:re,...mc(y)?{walletType:y}:{}}),Y?.flush?.().catch(()=>{})}});pt(()=>{ce&&qe.current?.focus()},[ce,Re]);let Xe=Ge(()=>{ee(y=>y+1)},[]),we=Ge((y,re,_,F,j=!1)=>{ne(F),T?.(y,re,{code:_,popupBlocked:zr(re),telemetryReported:j,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Me(y),X(!0),Xe()},[ne,T,Xe]),ht=Ge(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);pt(()=>{Je.current&&(Je.current=!1,ht())},[ht,Re]);let Xt=Ge(()=>{X(!1),c?.(null),ht()},[ht,c]),m=Ge(()=>{A.current?.()},[]);pt(()=>{let y=null,re=()=>{y=null;let F=ac();F!==It.current&&(It.current=F,lt(F),!rt.current&&!M(se.current)&&Xe())},_=()=>{y!==null&&window.clearTimeout(y),y=window.setTimeout(re,kp)};return window.addEventListener("resize",_),()=>{window.removeEventListener("resize",_),y!==null&&window.clearTimeout(y)}},[se,M,Xe]),pt(()=>{let y=ti(e,t);if(!y)return;let re=!1,_=!1,F=async()=>{if(!_){_=!0,re||he("checking");try{let j=await lc(N,y.clientSecret,be.current);if(re)return;let et=Qi(j,y.providerObjectId,Ji(y.clientSecret));if(et.kind==="confirmed"){if(!sc(e,t,y.clientSecret))return;A.current=null,he("idle"),s({id:et.paymentMethodId,type:"card",threeDSecureActionResultTokenId:et.intentId},{...y.accountPatch?{accountPatch:y.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(et.kind==="terminal"){Xi(e,t,y.clientSecret),A.current=null,he("idle"),Me(y.paymentMethodType),X(!0),Xe();return}he("blocked")}catch{re||he("blocked")}finally{_=!1}}};return A.current=F,he("blocked"),()=>{re=!0,A.current===F&&(A.current=null)}},[t,s,Xe,e,N]);let w=Ge(async y=>{let re=!1,_=Ae=>{re||(re=!0,y.paymentFailed({reason:"fail",...Ae?{message:Ae}:{}}))};if(!N||!_e){_();return}let F=ot.current.get(Re);if(F&&!M(F.generation)){ot.current.delete(Re),_();return}if(!F&&Ue()){_();return}if(F&&!E(F.generation)){_();return}F||E();let j=y.expressPaymentType??F?.method??Ze.current,et=F??null,St=pc(j),wt;j==="apple_pay"?wt="apple_pay":j==="google_pay"&&(wt="google_pay");let ct=F?.generation??se.current,$=Y,wn=$?.now()??globalThis.performance?.now()??Date.now(),On=new AbortController,fn=!1,zt=!1,Ut=null,Tn=e,vn="processing",xt="other",jn="provider_runtime",qt,ur=new Promise((Ae,Le)=>{qt=Le}),jt=window.setTimeout(()=>{fn=!0,On.abort(),qt(Qa)},tp),$n=async(Ae,Le,Bt)=>{vn=Ae,xt=Le,jn=Le==="intent_create"||Le==="session_claim"?"transport_error":"provider_runtime";let kn=$?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Bt,ur])}finally{let In=$?.now()??globalThis.performance?.now()??Date.now();$?.performance({stage:Ae,durationMs:Math.max(0,In-kn),durationMode:"machine",requestCategory:Le,paymentMethodCategory:"wallet",provider:"stripe",...fn?{statusClass:"timeout"}:{}})}};try{if(mt(!0),c?.(null),!et&&I){let oe=await $n("processing","other",I(St));if(!oe.proceed){_();return}et={accountPatch:oe.accountPatch,sessionId:oe.sessionId,nonce:oe.nonce}}let Ae=et?.sessionId??e;Tn=Ae;let Le=et?.nonce??t,Bt=ze.current??et?.accountPatch,kn=Ic({event:y,fallbackEmail:Bt?.email??n,fallbackName:[Bt?.firstName,Bt?.lastName].join(" ").trim()||z});if(!Pn(kn.email)){_("Buyer details are required."),Fe(rs(j),kn).then(oe=>{oe&&(ze.current=oe)});return}ze.current=null;let In={...et?.accountPatch,...lr(kn,!0)};await $n("processing","session_claim",Promise.resolve(ie?.(kn)));let{error:Rn}=await $n("tokenization","provider_sdk",_e.submit());if(Rn){_(),we(j,Rn,"stripe_wallet_submit_failed",F?.generation);return}if(!Ae)throw new Error("Missing sessionId or email for payment.");let gn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:j,paymentMethodId:null,intentKind:a},bn=JSON.stringify({sessionId:Ae,nonce:Le??"",request:gn}),ln=De.current,on=ln?.retryIdentity===bn?ln.authorizationAttemptId:qu();De.current={authorizationAttemptId:on,retryIdentity:bn};let $t=await $n("processing","intent_create",ni(o,ve,Ae,Le??"",{...gn,authorizationAttemptId:on},{signal:On.signal}));if($t.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Rt=$t.clientSecret,cn=lp({createdAt:Date.now(),sessionId:Ae,...Le?{nonce:Le}:{},clientSecret:Rt,providerObjectId:$t.providerObjectId,paymentMethodType:j,accountPatch:In});window.clearTimeout(jt),zt=!0,$?.performance({stage:"callback",durationMs:Math.max(0,($?.now()??globalThis.performance?.now()??Date.now())-wn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let dn=$?.now()??globalThis.performance?.now()??Date.now(),ue={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...wt?{walletType:wt}:{},attempt:ct},Xn=!1,Mn=null;$?.log({name:"payment.provider_confirmation.started",...ue}),Ut=window.setTimeout(()=>{Ut!==null&&be.current.delete(Ut),Xn=!0;let oe=$?.now()??globalThis.performance?.now()??Date.now();$?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...ue,operationOutcome:"watchdog_expired",durationMs:Math.max(0,oe-dn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),$?.flush?.().catch(()=>{}),Mn?.()},np),be.current.add(Ut);let pr=(oe,Pt)=>{Ut!==null&&(window.clearTimeout(Ut),be.current.delete(Ut),Ut=null);let tt=$?.now()??globalThis.performance?.now()??Date.now(),kt=Math.max(0,tt-dn),ke=oe;Xn&&(oe==="resolved"?ke="resolved_late":oe==="returned_error"?ke="returned_error_late":ke="rejected_late");let An=Pt??(oe==="resolved"?"approved":"provider_error");return $?.log({name:"payment.provider_confirmation.returned",...ue,operationOutcome:ke,terminalReason:An}),$?.performance({...ue,durationMs:kt,durationMode:"buyer",operationOutcome:ke,terminalReason:An}),{durationMs:kt,operationOutcome:ke,terminalReason:An}},tn=!1,hn=!1,yr=oe=>{if(!oe||typeof oe!="object")return null;let Pt=oe;if(Pt.error)return null;let tt=Pt.setupIntent??Pt.paymentIntent,kt=Qi(tt??null,void 0,!!Pt.setupIntent);return kt.kind==="confirmed"?kt:null},Wn=oe=>{if(tn||F&&se.current!==F.generation)return;let Pt=yr(oe);if(!Pt)return;if(cn&&!sc(Ae,Le,Rt)){tn=!0;return}let{intentId:tt,paymentMethodId:kt}=Pt;tn=!0,hn=!0,De.current=null,A.current=null,Ye.current&&(he("idle"),mt(!1));let ke=`${Sc}:${Ae}`;en(ke,{createdAt:Date.now(),sessionId:Ae,nonce:Le,accountPatch:In,paymentMethodId:kt,providerIntentId:tt,paymentMethodType:j});try{s({id:kt,type:"card",threeDSecureActionResultTokenId:tt},{accountPatch:In,paymentMethodCategory:"wallet",sessionId:Ae,nonce:Le})}finally{en(ke)}},Wt=!1;Mn=async()=>{if(!(Wt||tn||hn)){Wt=!0,Ye.current&&he("checking");try{let oe=await lc(N,Rt,be.current);if(tn||hn)return;let Pt=Ji(Rt),tt=Qi(oe,$t.providerObjectId,Pt);if(tt.kind==="confirmed"){Wn(Pt?{setupIntent:oe}:{paymentIntent:oe});return}if(tt.kind==="terminal"){if(hn=!0,Xi(Ae,Le,Rt),De.current=null,A.current=null,!Ye.current)return;he("idle"),_(),we(j,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",F?.generation,!0);return}Ye.current&&!hn&&(he("blocked"),mt(!1))}catch{Ye.current&&!hn&&(he("blocked"),mt(!1))}finally{Wt=!1}}},A.current=Mn;let p,dt;try{let oe=await(Ji(Rt)?N.confirmSetup({elements:_e,clientSecret:Rt,redirect:"if_required"}):N.confirmPayment({elements:_e,clientSecret:Rt,redirect:"if_required"}));if(!oe||typeof oe!="object")throw new ma(sp(oe));if(p=oe,!p.error&&!yr(p))throw new ma("confirmation_result_unconfirmed");dt=pr(p.error?"returned_error":"resolved",p.error&&Ba(p.error)?"provider_declined":void 0)}catch(oe){let Pt=oe instanceof ma?oe.reason:void 0,tt=Pt!==void 0,kt=pr(tt?"returned_error":"rejected");if($?.error({...tt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Pt}:Ni(oe),...ue,operationOutcome:kt.operationOutcome,durationMs:kt.durationMs,statusClass:"unknown",terminalReason:kt.terminalReason}),!Ye.current||tn)return;await Mn?.();return}let W=p.error;if(W){if(!Ye.current||tn)return;if(Ba(W)){hn=!0,Xi(Ae,Le,Rt),De.current=null,A.current=null,he("idle");let oe=W.message??"Your payment was declined.";_(oe),c?.(oe),C?.(yn(St,oe,{code:go(W),declineCode:Mi(W)})),ri({billingApiUrl:o,sessionId:Ae,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:j,providerDeclineReason:go(W)??"provider_declined",...$t.intentKind==="payment"&&$t.providerObjectId.startsWith("pi_")?{providerIntentId:$t.providerObjectId}:{}}})}else $?.error({...Ni(W),...ue,operationOutcome:dt.operationOutcome,durationMs:dt.durationMs,statusClass:"unknown",terminalReason:dt.terminalReason}),await Mn?.();return}if(Wn(p),!tn)throw new Error("Invalid provider returned for APM intent")}catch(Ae){if(Ae===Qa){let Le=$?.now()??globalThis.performance?.now()??Date.now();$?.error({errorCode:dp(xt),stage:vn,requestCategory:xt,paymentMethodCategory:"wallet",provider:"stripe",...wt?{walletType:wt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Tn,durationMs:Math.max(0,Le-wn),statusClass:"timeout",failureCategory:jn,attempt:ct,terminalReason:"provider_error"}),$?.flush?.().catch(()=>{})}_(),we(j,Ae,Ae===Qa?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",F?.generation,Ae===Qa)}finally{if(window.clearTimeout(jt),Ut!==null&&(window.clearTimeout(Ut),be.current.delete(Ut)),!zt){let Ae=$?.now()??globalThis.performance?.now()??Date.now();$?.performance({stage:"callback",durationMs:Math.max(0,Ae-wn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...fn?{statusClass:"timeout"}:{}})}Ye.current&&mt(!1)}},[N,_e,e,t,n,z,Fe,ie,o,ve,a,s,c,C,I,we,E,M,Ue,se,Y,Re]),Ee=vt(()=>yl(i),[i]),de=vt(()=>i.map(Gu),[i]);return Ke(Fo,{children:[d(xi,{state:Ne,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Se,children:Ke("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[ce&&Ke("button",{ref:qe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Xt,style:ns,children:["Try ",rs($e)," again"]}),L!=="idle"&&Ke("div",{role:"status","aria-live":"polite",children:[d("p",{children:"We are still confirming your payment. Check its status before trying again."}),d("button",{type:"button",onClick:m,disabled:L==="checking",style:ns,children:L==="checking"?"Checking payment status\u2026":"Check payment status"})]}),fe&&d(Io,{identity:fe.identity,methodLabel:fe.methodLabel,onComplete:bt,onCancel:()=>bt(null)},fe.id),L==="idle"&&Ke("div",{style:{display:fe?"none":void 0},children:[d(Ip,{active:je}),d(Cc,{onReady:y=>{yt(Ai(y,de))},onLoadError:y=>{yt("load_error"),ls(Y,"stripe","wallet","provider_error")},onClick:async y=>{let re=Y?.now()??globalThis.performance?.now()??Date.now();Ze.current=y.expressPaymentType,We.current=pc(y.expressPaymentType);let _=!0,F=window.setTimeout(()=>{_=!1,y.reject()},ep),j=I?await I(We.current):{proceed:!0};if(window.clearTimeout(F),!_)return;if(!j.proceed){ot.current.delete(Re),y.reject();return}let et=Lt(y.expressPaymentType);Ct.current={generation:et,startedAt:re},ot.current.set(Re,{generation:et,method:y.expressPaymentType,accountPatch:j.accountPatch,sessionId:j.sessionId,nonce:j.nonce}),X(!1),Y?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:et,...y.expressPaymentType==="apple_pay"||y.expressPaymentType==="google_pay"?{walletType:y.expressPaymentType}:{}}),f?.(We.current),y.resolve()},onConfirm:w,onCancel:()=>{let y=ot.current.get(Re);ot.current.delete(Re);let re=Ct.current,_=Y?.now()??globalThis.performance?.now()??Date.now();if(y&&re?.generation===y.generation&&Lu({method:y.method,elapsedMs:_-re.startedAt,handoffObserved:Zt.current===y.generation})){Y?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:y.generation,walletType:"google_pay"}),De.current=null,we(y.method,new Error("The browser window is too small for the Google Pay sheet."),bc,y.generation,!0);return}Y?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...y?{attempt:y.generation}:{}}),ne(y?.generation),De.current=null,X(!1),Je.current=!0,Xe()},options:{...ml,paymentMethods:Ee,emailRequired:Nt,billingAddressRequired:Nt}},Re)]})]})}),Be&&d(Sr,{status:"processing"})]})}function Rc(e,t,n){let o=Pc(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function os({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:c,onErrorChange:f,onDecline:C,onCancel:T,runBeforeButtonClick:I,onButtonClick:z,isProcessing:ie,submitButtonColor:O,submitButtonBorderRadius:Se,submitButtonStyle:G,errorText:v}){let P=jr(),{emitInstrument:ve}=Do(Jn),N=is(),_e=as(),[Y,Ne]=ae(!1),yt=K(!1),[Be,mt]=ae(!1),[Nt,fe]=ae("loading"),[Fe,bt]=ae(""),Te=!Pn(o?.trim()),qe=!Te||Pn(Fe.trim()),Re=Ge(async()=>{if(!N||!_e||ie||yt.current||!Be)return;yt.current=!0,Ne(!0);let ee=I?await I("card"):{proceed:!0};if(!ee.proceed){yt.current=!1,Ne(!1);return}z?.("card");let je=ee.sessionId??t,lt=ee.nonce??n,It=oa(a?.trim()),rt=lr({email:ee.accountPatch?.email?.trim()||o?.trim()||Fe.trim(),firstName:ee.accountPatch?.firstName?.trim()||It.firstName,lastName:ee.accountPatch?.lastName?.trim()||It.lastName}),ce=rt.email,X=lr({...ee.accountPatch,...rt});try{if(f?.(null),!Pn(ce))throw new Error("A valid email address is required for payment.");await i?.(rt);let L=await _e.submit();if(L.error){f?.(L.error.message??"Payment failed.");return}let he=[rt.firstName,rt.lastName].filter(Boolean).join(" "),$e=await N.createPaymentMethod({elements:_e,params:{billing_details:{email:ce,...he?{name:he}:{}}}});if($e.error||!$e.paymentMethod){f?.($e.error?.message??"Failed to create payment method.");return}let Me=$e.paymentMethod;if(!je||!ce)throw new Error("Missing sessionId or email for payment.");let A=Me.type||e,Ye=await ni(s,ve,je,lt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:A,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Je=Ye.clientSecret;en(Ir,{clientSecret:Je,sessionId:je,nonce:lt,accountPatch:X,paymentMethodId:Me.id,paymentMethodType:Me.type??e,gateway:"stripe"});let{error:Ze,paymentIntent:We}=await N.confirmPayment({clientSecret:Je,confirmParams:{return_url:window.location.href,payment_method:Me.id},redirect:"if_required"});if(Ze){en(Ir);let be=Ze.message??"Payment failed.";f?.(be),C?.(yn("card",be,{code:Ze.code})),await ri({billingApiUrl:s,sessionId:je,nonce:lt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ze.code??"provider_declined"}});return}let ze=We?.status;if(!na(ze)){en(Ir);let be=ze==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(be),C?.(yn("card",be,{code:ze??"missing_payment_intent"}));return}en(Ir);let De=typeof We?.payment_method=="string"?We.payment_method:We?.payment_method?.id;c({id:De??Me.id,type:"card",threeDSecureActionResultTokenId:We?.id,gateway:"stripe",paymentMethodType:Me.type??e},{accountPatch:X,paymentMethodCategory:"apm",sessionId:je,nonce:lt})}catch(L){f?.(L instanceof Error?L.message:"Payment failed. Please try again.")}finally{yt.current=!1,Ne(!1)}},[N,_e,ie,Be,I,z,t,n,o,a,Fe,i,s,ve,e,c,f,C]);return Ke("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Te&&d("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Te&&Ke("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",d("input",{type:"email",autoComplete:"email",required:!0,value:Fe,onChange:ee=>bt(ee.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),d(Ju,{onReady:()=>fe("ready"),onLoadError:()=>{fe("load_error"),ls(mn(P),"stripe","apm")},onChange:ee=>{mt(!!ee.complete)},options:{layout:fl,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...Pn(o?.trim())?{email:o?.trim()}:{}}}}}),d(gl,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Re()},disabled:!Be||!qe||Y||ie||Nt!=="ready",color:O,borderRadius:Se,style:G,children:Y?"Processing\u2026":`Pay with ${fa(e)}`}),v&&d(Eo,{margin:"0.75rem 0 0",children:v})]})}function gc({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:s,stripeInstance:c,paymentElementBaseOptions:f,futureUseSession:C,onTokenizedBody:T,onErrorChange:I,onButtonClick:z,onDecline:ie,runBeforeButtonClick:O,onLoadStateChange:Se,isProcessing:G=!1,submitButtonColor:v="#4A49FF",submitButtonBorderRadius:P=8,submitButtonStyle:ve,buttonAppearance:N,themeId:_e,onExpandApm:Y,expandedApmMethod:Ne}){let{emitInstrument:yt}=Do(Jn),[Be,mt]=ae(null),[Nt,fe]=ae(null),Fe=K(!1),{request:bt,collect:Te,finish:qe}=ko();pt(()=>{s.length>0&&c?Se?.("ready"):c||Se?.("loading")},[s.length,c,Se]);let Re=Ge(async ce=>{if(!c||Fe.current||G)return;Fe.current=!0,fe(ce);let X=O?await O("card"):{proceed:!0};if(!X.proceed){Fe.current=!1,fe(null);return}z?.("card");let L=X.sessionId??e,he=X.nonce??t,$e=oa([X.accountPatch?.firstName,X.accountPatch?.lastName].filter(Boolean).join(" ")||o),Me=lr({email:X.accountPatch?.email?.trim()||n?.trim(),firstName:X.accountPatch?.firstName?.trim()||$e.firstName,lastName:X.accountPatch?.lastName?.trim()||$e.lastName});if(!Pn(Me.email)){fe(null);let Je=await Te(fa(ce),Me);if(!Je){Fe.current=!1;return}Me=Je,fe(ce)}let A=Me.email,Ye=lr({...X.accountPatch,...Me});try{if(I?.(null),!L||!Pn(A))throw new Error("Missing sessionId or email for payment.");await a?.(Me);let Je=await ni(i,yt,L,he??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ce,paymentMethodId:null,intentKind:"payment"});if(Je.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ze=Je.clientSecret;en(Ir,{clientSecret:Ze,sessionId:L,nonce:he,accountPatch:Ye,paymentMethodType:ce,gateway:"stripe"});let{error:We,paymentIntent:ze}=await c.confirmPayment({clientSecret:Ze,confirmParams:{return_url:window.location.href,payment_method_data:{type:ce,billing_details:{name:[Me.firstName,Me.lastName].filter(Boolean).join(" "),...A?{email:A}:{}}}},redirect:"if_required"});if(We){en(Ir);let Ct=We.message??"Payment failed.";I?.(Ct),ie?.(yn("card",Ct,{code:We.code})),await ri({billingApiUrl:i,sessionId:L,nonce:he,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ce,providerDeclineReason:We.code??"provider_declined"}});return}let De=ze?.status;if(!na(De)){en(Ir);let Ct=De==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";I?.(Ct),ie?.(yn("card",Ct,{code:De??"missing_payment_intent"}));return}en(Ir);let be=typeof ze?.payment_method=="string"?ze.payment_method:ze?.payment_method?.id;T({id:be??ze?.id,type:"card",threeDSecureActionResultTokenId:ze?.id,gateway:"stripe",paymentMethodType:ce},{accountPatch:Ye,paymentMethodCategory:"apm",sessionId:L,nonce:he})}catch(Je){I?.(Je instanceof Error?Je.message:"Payment failed. Please try again.")}finally{Fe.current=!1,fe(null)}},[c,G,O,z,e,t,n,Te,i,yt,o,a,T,I,ie]),[ee,je]=ae(null),lt=Y?Ne??null:ee,It=Ge(ce=>{Fe.current||G||lt&<!==ce||(rc(ce)?Y?Y(ce):je(ce):Re(ce))},[lt,G,Re,Y]),rt=vt(()=>ee?Rc(f,ee,C):null,[ee,f,C]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:bt?d(Io,{identity:bt.identity,methodLabel:bt.methodLabel,onComplete:qe,onCancel:()=>qe(null)},bt.id):s.map(ce=>{let X=Ne===ce,L=Nt===ce,he=Nt!==null&&Nt!==ce||Ne!=null&&Ne!==ce;return Ke(Zu.Fragment,{children:[d(pl,{method:ce,themeId:_e,submitting:L,disabled:he,highlighted:X,hasNextStep:rc(ce),onClick:()=>It(ce),backgroundColor:N?.backgroundColor,borderColor:N?.borderColor,textColor:N?.textColor,borderRadius:N?.borderRadius,fontFamily:N?.fontFamily}),!Y&&ee===ce&&rt&&c&&d(no,{stripe:c,options:rt,children:d(os,{method:ce,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:T,onErrorChange:I,onDecline:ie,onCancel:()=>je(null),runBeforeButtonClick:O,onButtonClick:z,isProcessing:G,submitButtonColor:v,submitButtonBorderRadius:P,submitButtonStyle:ve})},ce)]},ce)})})}function Rp({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:s,onError:c,onDecline:f,onTokenizedBody:C,firstName:T,lastName:I,chv:z,className:ie,submitLabel:O,isProcessing:Se,error:G,onErrorChange:v,showPayPal:P=!0,showStripe:ve=!0,walletPresentation:N="auto",enabledPaymentMethods:_e,enabledPaymentMethodCountries:Y,showApplePay:Ne=!0,showGooglePay:yt=!0,layout:Be="default",theme:mt,buttonsTheme:Nt,buttonsStyles:fe,appearance:Fe,cardButtonContent:bt,cardBackButtonContent:Te,cardTitleContent:qe,showSecurityFooter:Re,onButtonClick:ee,onBeforeButtonClick:je,onBuyerIdentityReady:lt,enableAVS:It,cardFieldOrder:rt,cardPreFormSlot:ce,avsLayout:X="row",country:L,zip:he,addressLine1:$e,addressLine2:Me,city:A,state:Ye,onCountryChange:Je,onZipChange:Ze,avsCheck:We,checkoutType:ze,checkoutLayout:De,totalAmount:be=0,currency:Ct="usd",initialCardOpen:Zt=!1,directPaypal:ot,isSubscription:Lt=!1,session:E,dataAttachmentPending:ne=!1,dataAttachmentRequiresIdentity:Ue=!1,debug:M=!1}){let se=jr(),Xe=Li(),we=Do(sr),{emitInstrument:ht}=Do(Jn),Xt=K(null);Xt.current||(Xt.current=Ua());let m=Xt.current,[,w]=ae(0),Ee=K(null);Ee.current||(Ee.current=Qo());let de=Ee.current,y=vt(()=>({browser:de,capability:m,presentationMode:"popup"}),[de,m]),re=E??we.session,_=vt(()=>({futureUse:re?.futureUse,futureUseUnsupported:re?.futureUseUnsupported}),[re?.futureUse,re?.futureUseUnsupported]),F=re?.gateways?.paypal?.providerObjectType??ot?.providerObjectType,j=ne||we.claimPending===!0,et=Ue||we.claimRequiresIdentity===!0,St=j&&!et,wt=Ol(),ct=n||wt,[$,wn]=ae(!1),[On,fn]=ae(null),[zt,Ut]=ae(L??""),[Tn,vn]=ae(he??""),[xt,jn]=ae($e??""),[qt,ur]=ae(Me??""),[jt,$n]=ae(A??""),[Ae,Le]=ae(Ye??""),[Bt,kn]=ae(""),[In,Rn]=ae({}),gn=K(he??""),bn=K(L??""),ln=K($e??""),on=K(Me??""),$t=K(A??""),Rt=K(Ye??""),cn=K(""),dn=K({});pt(()=>{let r=(g,q,ge,D,Q)=>{if(dn.current[g])return;let Tt=q?.trim();!Tt||Tt===ge.current||(ge.current=Tt,D(Tt),Q?.(Tt))};r("country",L,bn,Ut,Je),r("zip",he,gn,vn,Ze),r("addressLine1",$e,ln,jn),r("addressLine2",Me,on,ur),r("city",A,$t,$n),r("state",Ye,Rt,Le)},[L,he,$e,Me,A,Ye,Je,Ze]);let ue=vt(()=>$u(It),[It]),Xn=ue!==null,Mn=vt(()=>Yi(E),[E]),pr=Du(E?.vault),tn=!!E?.gateways?.pcivault,hn=Ml(E),Wn=!!(E?.gateways?.stripe?.enabledPaymentMethods??_e)?.includes("card")||Qr(E),Wt=pr||Wn||tn,p=!!(ve&&Wt&&e),[dt,W]=ae(()=>Be!=="buttons"||Zt?e??null:null),[oe,Pt]=ae(0),tt=Be!=="buttons"||Zt||!!e&&dt===e,kt=E?.captureMethod,ke=K(se);pt(()=>{ke.current=se},[se]);let[An,Dr]=ae(null);pt(()=>{if(!p||!e||!tt){Dr(null);return}let r=ke.current?ke.current.cardCapture({sessionId:e,captureMethod:kt}):new vu({sessionId:e,captureMethod:kt,billingApiUrl:ct,telemetry:o});return Dr({sessionId:e,captureMethod:kt,billingApiUrl:ct,telemetry:o,capture:r}),()=>{r.unmount()}},[p,e,tt,kt,ct,o]);let _t=p&&e&&tt&&An?.sessionId===e&&An.captureMethod===kt&&An.billingApiUrl===ct&&An.telemetry===o?An.capture:null,Nn=vt(()=>{let r=zt,g=ue?Yt(ue.postal_code,r):!1;return Cp(r,Tn,g)},[ue,zt,Tn]),{avsInvalid:Qn,invalidAvsFields:er}=vt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!p||!ue)return{avsInvalid:!1,invalidAvsFields:r};let g=zt,q=(Q,Tt)=>Yt(Q,g)&&!Tt.trim(),ge={line1:q(ue.address_line_1,xt),city:q(ue.city,jt),state:q(ue.state,Ae),zip:Nn.empty||Nn.malformed};return{avsInvalid:ge.line1||ge.city||ge.state||ge.zip,invalidAvsFields:ge}},[p,ue,zt,xt,jt,Ae,Nn]),[Ht,mr]=ae(!1),[fr,xn]=ae(!1),[gr,Hn]=ae(!1),[hr,Er]=ae({line1:!1,city:!1,state:!1}),Ln=K(!1),tr=K({email:!1,line1:!1,city:!1,state:!1,zip:!1}),nr=K(!1),Mt=Ge(r=>{tr.current[r]=!0,nr.current=!0},[]),zn=Ge(r=>!Ln.current&&tr.current[r],[]),En=Ge(r=>{zn(r)&&Er(g=>g[r]?g:{...g,[r]:!0})},[zn]),[rr,or]=ae(()=>Zi(E?.vault,{billingApiUrl:ct,sessionId:e,nonce:t})),[nt,nn]=ae(Zt&&Wt?"card":"buttons"),[un,Bn]=ae(null),Or=nt==="expanding"||nt==="card",Pr=E?.gateways?.stripe&&!hn?"stripe":void 0,_r=Ge(()=>{ht?.({class:"card_surface",provider:Pr})},[Pr,ht]),Vn=K(null),rn=Ge(r=>{Vn.current&&clearTimeout(Vn.current),Vn.current=setTimeout(()=>{Vn.current=null,r()},ga)},[]);pt(()=>()=>{Vn.current&&clearTimeout(Vn.current)},[]);let Nr=K(!1),[an,k]=ae(0),b=K(null),H=Ge(()=>{_r(),W(e??null),Nr.current&&(Nr.current=!1,k(r=>r+1)),Pt(r=>r+1),nn("expanding"),rn(()=>nn("card"))},[rn,_r,e]),J=Ge(()=>{nn("collapsing"),rn(()=>nn("buttons"))},[rn]),ut=Ge(r=>{Bn(r),nn("apm-expanding"),rn(()=>nn("apm-form"))},[rn]),Vt=Ge(()=>{nn("apm-collapsing"),rn(()=>{nn("buttons"),Bn(null)})},[rn]);pt(()=>{Be==="buttons"&&Zt&&Wt&&(W(e??null),nn("card"))},[Be,Zt,Wt,e]);let[ye,x]=ae(null),B=K(!1),R=K(null),l=K("idle"),[u,h]=ae(!1),V=K(u);V.current=u;let[pe,Ce]=ae(()=>ot?.existingOrderId?{orderId:ot.existingOrderId,attempts:1}:null),Kt=K(pe);pt(()=>{Kt.current=pe},[pe]);let te=K(null),Ie=vt(()=>{if(lt||we.claimBuyerIdentity||E?.buyerIdentified!==!1||!e||!t)return;let r=`${ct}|${e}|${t}`;te.current?.key!==r&&(te.current={key:r,claim:Co(new Bo(ct,{telemetry:!1}),e,t,{...i?{userId:i}:{},...T?{firstName:T}:{},...I?{lastName:I}:{}})});let g=te.current.claim;return async q=>{await g(q)}},[lt,we.claimBuyerIdentity,E?.buyerIdentified,e,t,ct,i,T,I]),Oe=lt??we.claimBuyerIdentity??Ie,at=G??On,Z=vt(()=>Hu(mt),[mt]),S=vt(()=>{let r=Z?.buttonsLayout??Wu(Nt);return fe?{...r,...fe,cardButton:{...r.cardButton,...fe.cardButton},cardFormContainer:{...r.cardFormContainer,...fe.cardFormContainer},backButton:{...r.backButton,...fe.backButton},backButtonIcon:{...r.backButtonIcon,...fe.backButtonIcon},submitButton:{...r.submitButton,...fe.submitButton},title:{...r.title,...fe.title}}:r},[Z,Nt,fe]),U=Fe??Z?.appearance,He=vt(()=>Eu({appearance:U,buttonsStyles:S,layout:Be}),[U,S,Be]),Pe=we.inlineSessionPatchProcessing??!1,xe=(Se??$)||Pe,ft=ct.replace(/\/+$/,""),Qe=vt(()=>Oi({userId:i,email:a,firstName:T,lastName:I,country:L,zip:he},In),[i,a,T,I,L,he,In]),oo=[Qe.firstName,Qe.lastName].filter(r=>!!r?.trim()).join(" "),Cs=!Pn(Qe.email?.trim()),li=K(null);p&&li.current===null&&(li.current=Cs);let Lr=p&&(li.current??Cs),ci=vt(()=>Sp(Bt,Lr),[Bt,Lr]),ao=ci.empty||ci.malformed,Un=vt(()=>se?se.getRawProvider():null,[se]),Ss=vt(()=>Xe?Xe.getRawProvider():null,[Xe]),Uo=be||100,io=Ct.toLowerCase(),di=vt(()=>U?bu(U):null,[U]),so=di,ws=vt(()=>{let r=di??{},g=r.rules??{};return{...r,rules:{...g,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...g[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...g[".AccordionItemContents"]??{}}}}},[di]),ks=vt(()=>({...Tl(be,re?.captureMethod,_),currency:io,...so?{appearance:so}:null}),[be,io,re?.captureMethod,_,so]),ui=Pc(_,"paypal","paypal"),Is=vt(()=>({mode:"payment",amount:Uo,currency:io,captureMethod:"manual",...ui?{setupFutureUsage:ui}:null,...so?{appearance:so}:null}),[Uo,io,ui,so]),me=Ge(r=>{fn(r),v?.(r)},[v]),Rs=K(0);pt(()=>{an!==Rs.current&&(Rs.current=an,me(null))},[an,me]);let pi=K(""),[Es,Uc]=ae(!1),yi=Ge(()=>{Uc(!0)},[]);pt(()=>{if(!p||!Lr||!Oe||!Es||ao||pi.current)return;let r=lr({email:Pn(Qe.email?.trim())?Qe.email?.trim():cn.current.trim(),firstName:Qe.firstName?.trim(),lastName:Qe.lastName?.trim()});pi.current=JSON.stringify(r),Rn(g=>({...g,...r})),Promise.resolve(Oe(r)).catch(g=>{pi.current="",me(g instanceof Error?g.message:"Failed to attach buyer details.")})},[p,Lr,Oe,Es,ao,Qe.email,Qe.firstName,Qe.lastName,me]),pt(()=>{!p||!_t||_t.setCardFieldOrder?.(rt??null,ue==null&&!Lr)},[p,_t,rt,ue,Lr]),pt(()=>{(nt==="expanding"||nt==="collapsing"||nt==="apm-expanding"||nt==="apm-collapsing")&&me(null)},[nt,me]);let vr=Ge((r,g,q)=>{f?.(yn(r,g,q))},[f]),lo=Ge((r,g,q)=>{let ge=q?.popupBlocked??zr(g);ge&&m.markBlocked()&&w(it=>it+1);let D=rs(r),Q=q?.code===bc?wu(D):xa(D,ge,de.inAppBrowser),Tt=go(g),Gn=(Tt?.toLowerCase()==="error"?void 0:Tt)??dl(q?.code)??"external_payment_method_failed",Ve=new Br(Q,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:Gn,popupBlocked:ge,inAppBrowser:de.inAppBrowser,appFamily:de.appFamily,popupCapability:m.current(),presentationMode:q?.presentationMode??"popup"}});q?.telemetryReported||mn(se)?.error(xo({...y,presentationMode:q?.presentationMode??"popup"},{errorCode:ge?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:q?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:q?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:q?.terminalReason??(ge?"popup_blocked":"provider_error")})),x(null),Be==="buttons"&&(nn("buttons"),Bn(null)),me(Q),c?.(Ve),console.error("[FloPay] External payment method failed:",{method:r,code:Gn,popupBlocked:ge})},[de,y,se,Be,c,m,me]);pt(()=>{if(!p||!e){or(null);return}let r={billingApiUrl:ft,sessionId:e,nonce:t},g=Zi(E?.vault,r);if(g){or(g);return}if(!tt){or(null);return}let q=`${ft}\0${e}\0${t??""}`,ge=b.current;if(ge&&ge.key===q){or(ge.mount);return}or(null);let D=!0;return new Bo(ft).getVaultCapture(e,t).then(Q=>{if(!D)return;let Tt=Zi(Q,r);Tt?.verificationRequired&&!Q.html&&(b.current={key:q,mount:Tt}),Tt?or(Tt):me("Failed to load the secure card form.")}).catch(Q=>{D&&me(Q instanceof Error?Q.message:"Failed to load the secure card form.")}),()=>{D=!1}},[p,tt,oe,e,E?.vault,ft,t,me]);let ar=K({onComplete:s,onError:c,updateError:me,emitDecline:vr,resolvedAccount:Qe,avsConfig:ue,avsCheckProp:We,sessionId:e,nonce:t,baseUrl:ft,captureMethod:E?.captureMethod,paymentId:E?.paymentId,authorizationExpiresAt:E?.authorizationExpiresAt,serverSideCardGateway:hn});ar.current={onComplete:s,onError:c,updateError:me,emitDecline:vr,resolvedAccount:Qe,avsConfig:ue,avsCheckProp:We,sessionId:e,nonce:t,baseUrl:ft,captureMethod:E?.captureMethod,paymentId:E?.paymentId,authorizationExpiresAt:E?.authorizationExpiresAt,serverSideCardGateway:hn};let mi=K(!1),_s=Ge(()=>{let r=ar.current,g=r.resolvedAccount.email?.trim(),q=Pn(g)?g:cn.current.trim();if(!Pn(q))return null;let ge=r.resolvedAccount.firstName?.trim(),D=r.resolvedAccount.lastName?.trim(),Q=bn.current.trim()||r.resolvedAccount.country?.trim()||"",Tt=r.avsConfig?Yt(r.avsConfig.state,Q):!1,Gn=r.avsConfig?Yt(r.avsConfig.address_line_1,Q):!1,Ve=r.avsConfig?Yt(r.avsConfig.postal_code,Q):!1,it=r.avsConfig?Yt(r.avsConfig.city,Q):!1,gt=r.avsConfig?Yt(r.avsConfig.address_line_2,Q):!1,Ft=Gn&&!Tt&&Ve?xu(Q,(gn.current??"").trim()):null,Jr=Tt?Rt.current:Ft;return{accountData:{userId:r.resolvedAccount.userId??"",email:q,...ge?{firstName:ge}:{},...D?{lastName:D}:{},...Ve&&gn.current?{zip:gn.current}:{},...it&&$t.current?{city:$t.current}:{},...Jr?{state:Jr}:{},...Gn&&ln.current?{addressLine1:ln.current}:{},...gt&&on.current?{addressLine2:on.current}:{},...Q?{country:Q}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:Yt(r.avsConfig.country,Q),postal_code:Ve,address_line_1:Gn,address_line_2:gt,city:it,state:Tt}}:{}}},[]),Ts=K(j);Ts.current=j,pt(()=>{j||at!==cc||ar.current.updateError(null)},[j,at]),pt(()=>{!p||!_t||_t.setSubmitGate?.(Qn||j||ao||u)},[p,_t,Qn,j,ao,u]),pt(()=>{if(!p||!_t)return;mi.current=!1;let r=null,g=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,l.current="idle",x(null)},400)},q=_t.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")},up),x("processing");let Ve=ar.current;if(!Ve.sessionId||!Ve.nonce)return;let it=_s();if(!it){Ve.updateError("Enter a valid email address."),l.current="idle",x(null);return}new Bo(Ve.baseUrl).patchAccountSnapshot(Ve.sessionId,Ve.nonce,it,{telemetryMode:"best_effort"}).catch(gt=>{if(!yp(gt))return;let Ft=gt instanceof Error?gt.message:"Please check your billing address and try again.";Ve.updateError(Ft),l.current="idle",x(null),Ve.onError?.(gt instanceof Br?gt:new Br(Ft,"api_error"))})}),ge=_t.on("complete",Ve=>{_o(Ve.sessionId??ar.current.sessionId),l.current="terminal",h(!1),x("success"),setTimeout(()=>{if(mi.current)return;mi.current=!0;let it=ar.current,gt=Yi(it)||Ve.outcome==="authorized",Ft=it.serverSideCardGateway?{}:{paymentIntentId:Ve.intentId};ar.current.onComplete?.(gt?{status:"authorized",...Ft,paymentId:Ve.paymentId??it.paymentId,sessionId:Ve.sessionId??it.sessionId,authorizationExpiresAt:Ve.authorizationExpiresAt??it.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Ft,checkoutMethod:"card"})},600)}),D=_t.on("decline",Ve=>{let it=ar.current,gt=Ve.message??"Your payment was declined. Please try another card or contact your bank.";l.current="terminal",h(!1),it.updateError(gt),x("error");let Ft=Ve.failureOutcome??zu(Ve.declineReason)??"authorization_declined";it.emitDecline("card",gt,{code:Ft,declineCode:Ft}),g()}),Q=_t.on("error",Ve=>{let it=ar.current,gt=Ve.message??"There was a problem processing your payment. Please try again.";l.current="terminal",h(!1),it.updateError(gt),x("error"),it.onError?.(new Br(gt,"api_error",{code:Ve.failureOutcome??"capture_failed"})),g()}),Tt=_t.on("challenge_dismissed",()=>{R.current&&(clearTimeout(R.current),R.current=null),l.current="processing",h(!0),x(null)}),Gn=_t.on("blocked",()=>{if(V.current){ar.current.updateError(pp);return}if(!Ts.current){mr(!0);return}yi(),ar.current.updateError(cc)});return()=>{r&&(clearTimeout(r),r=null),R.current&&(clearTimeout(R.current),R.current=null),l.current="idle",h(!1),x(null),q(),ge(),D(),Q(),Tt(),Gn()}},[p,_t,yi,_s]);let br=!!ot?.clientId,qo=Array.isArray(_e),Ca=qo&&_e.length>0,Ms=qo&&_e.includes("paypal"),Sa=K(null);Sa.current===null&&(Sa.current=Fu());let co=Sa.current?"redirect":ul(de,N,m.current()),{expressMethods:wa,paymentElementMethods:fi}=vt(()=>Uu(_e,{excludePaypal:br}),[_e,br]),As=br||!!Xe||Ms&&co==="redirect",qc=vt(()=>As?wa.filter(r=>r!=="paypal"):wa,[wa,As]),jc=vt(()=>{let r=[];return Ne&&r.push("apple_pay"),yt&&r.push("google_pay"),r},[Ne,yt]),uo=qo?qc:jc,$c=ve&&uo.length>0,xs=Xn?zt:L,ka=vt(()=>Mu(fi,xs,Y),[fi,xs,Y]),gi=vt(()=>({mode:"payment",amount:Uo,currency:io,paymentMethodCreation:"manual",appearance:ws}),[Uo,io,ws]),[Bs,Fs]=ae("loading"),[Ds,Os]=ae("loading"),[Ns,Ls]=ae("loading"),[Wc,hi]=ae(!1),[zs,Pi]=ae("loading"),[vi,Hc]=ae();pt(()=>{Hc(Qo())},[]);let Ia=vi?.inAppBrowser,Ra=vi?Fa(vi,ot?.approvalPresentation,F??(Lt?"subscription":"order")):"popup",Us=P&&(br||(qo?Ms:Ia===!1)),qs=ve&&$c,jo=(!St||!!we.waitForDataAttachment)&&Us&&br,js=zs==="retrying"||zs==="exhausted",$o=null;ve&&(Xe?$o=Ss:co==="redirect"&&($o=Un));let $s=vt(()=>({...y,presentationMode:co}),[y,co]),Wo=!St&&Us&&!!$o&&(!br||js),po=!St&&qs&&!!Un,Ho=!St&&ve&&Ca&&ka.length>0&&!!Un,Vc=jo&&!js?Wc:Wo&&Bi(Bs),Kc=po&&Bi(Ds),Gc=Ho&&Ns!=="load_error",Ws=r=>r==="loading"||r==="ready",Hs=jo||Wo&&Ws(Bs)||po&&Ws(Ds)||Ho&&Ns!=="load_error",Ea=K(!1);pt(()=>{if(!Ea.current){if(!ve&&!P){Ea.current=!0;let r=new Br("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(r),me(r.message)}else if(!ve&&P&&!br){Ea.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),me(r.message)}else if(Ia!==void 0&&!St&&!Wt&&!Hs){Ea.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),me(r.message)}}},[ve,P,br,Ia,St,Wt,Hs,c,me]);let Vs=K(!1);pt(()=>{if(Vs.current||!Ca)return;let r=[];Ne!==!0&&r.push("showApplePay"),yt!==!0&&r.push("showGooglePay"),r.length!==0&&(Vs.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.`))},[Ca,Ne,yt]);let Ks=Ge((r,g)=>we.applyInlineSessionPatch?we.applyInlineSessionPatch(r).then(q=>({error:null,sessionId:q.sessionId||e,nonce:q.session?.clientSecret||t})).catch(q=>{let ge=oc(g,q);return me(ge.message),c?.(ge),{error:ge,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[we.applyInlineSessionPatch,t,c,e,me]),ir=Ge(async r=>{if(r!=="card"&&St&&await we.waitForDataAttachment?.(),!je)return{proceed:!0};try{let g=await je({method:r,sessionId:e||void 0,createSession:we.inlineSessionDraft});if(g===!1)return{proceed:!1};if(g&&typeof g=="object"){g.account&&Rn(ge=>({...ge??{},...g.account}));let q=await Ks(g,r);return q.error?{proceed:!1,accountPatch:g.account}:{proceed:!0,accountPatch:g.account,sessionId:q.sessionId,nonce:q.nonce}}return{proceed:!0}}catch(g){let q=oc(r,g);return me(q.message),c?.(q),{proceed:!1}}},[Ks,we.inlineSessionDraft,we.waitForDataAttachment,St,je,c,e,me]),Gs=Ge(async(r,g)=>{if(B.current)return;B.current=!0,wn(!0),x("processing"),me(null);let q=g?.sessionId??e,ge=g?.nonce??t,D=Oi(Qe,g?.accountPatch),Q=g?.completionPaymentMethodId??ra(r),Tt=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,Gn=hp(r),Ve=g?.presentationMode?Xa(mn(se),{...y,presentationMode:g.presentationMode}):void 0,it=()=>{ht?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Gn}),Ve?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...cr,requestCategory:"process_payment"})};try{let gt=new Bo(ft),Ft=await gt.processPayment(D.userId??"",{sessionId:q,nonce:ge,paymentMethodCategory:g?.paymentMethodCategory??vp(r),tokenizedData:Tt,accountData:{...g?.accountPatch,userId:D.userId??"",email:D.email??"",firstName:D.firstName||void 0,lastName:D.lastName||void 0,...Su({avsConfig:ue,country:bn.current,zip:gn.current,city:$t.current,state:Rt.current,addressLine1:ln.current,addressLine2:on.current})},...Cu({chv:z,avsCheck:We,checkoutType:ze,checkoutLayout:De,avsConfig:ue,country:bn.current})}),Jr=async pn=>{let Zr=Yi(E)||pn?.status==="authorized";_o(q),Ve?.terminal({outcome:"payment_succeeded",...cr}),x("success"),Ce(null),await new Promise(Zo=>setTimeout(Zo,600));let Cr;typeof pn?.paymentId=="string"?Cr=pn.paymentId:E?.paymentId&&(Cr=E.paymentId);let Xr;typeof pn?.authorizationExpiresAt=="string"?Xr=pn.authorizationExpiresAt:E?.authorizationExpiresAt&&(Xr=E.authorizationExpiresAt),s?.(Zr?{status:"authorized",...Cr===void 0?{}:{paymentId:Cr},sessionId:typeof pn?.sessionId=="string"?pn.sessionId:q,...Xr===void 0?{}:{authorizationExpiresAt:Xr},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:Q,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:Q,checkoutMethod:r.isPaypal?"paypal":"card"})};if(Ft.ok){await Jr(Ft.status===204?null:await Ft.json().catch(()=>null));return}let qn=await Ft.json().catch(()=>null);if(qn?.type==="paypal_redirect_required"){let pn=qn.threeDSecureToken,Zr=qn.paymentMethodId||r.id||"";if(!se||!pn){x("error"),me("PayPal authorization required but no token provided.");return}try{let Cr=Xe?.getRawProvider();if(!Cr){me("PayPal is not available.");return}let Xr={return_url:window.location.href};Zr&&(Xr.payment_method=Zr);let{error:Zo}=await Cr.confirmPayment({clientSecret:pn,confirmParams:Xr,redirect:"if_required"});if(Zo){x("error");let il=Zo.message??"PayPal payment failed.";me(il),vr("paypal",il,{code:Zo.code})}}catch(Cr){x("error"),me(Cr instanceof Error?Cr.message:"PayPal authorization failed.")}return}if(qn?.type==="paypal_direct_required"){let pn=qn.orderId;if(!pn){x("error"),me("PayPal retry required but no order id provided.");return}let Zr=Kt.current?.attempts??0;if(Zr>=2){x("error"),me("PayPal payment could not be completed after multiple attempts."),vr("paypal","paypal_direct_required retry limit exceeded");return}hi(!1),Pi("loading"),Ce({orderId:pn,attempts:Zr+1}),x(null);return}if(Ft.headers.get(op)===ap){let pn=await ip(gt,q,ge);if(pn!==void 0){await Jr(pn);return}}Iu(Ft.status,qn)?Ve?.terminal({outcome:"payment_declined",...cr,terminalReason:"provider_declined"}):it(),x("error");let al=qn?.message??"Payment failed. Please try again.";me(al),vr(r.isPaypal?"paypal":"card",al,{code:qn?.code??qn?.gatewayErrorCode,declineCode:qn?.declineCode??qn?.gatewayDeclineReason}),await new Promise(pn=>setTimeout(pn,400))}catch(gt){kc(gt)||it(),x("error"),me(gt instanceof Error?gt.message:"An unexpected error occurred"),await new Promise(Ft=>setTimeout(Ft,400))}finally{wn(!1),x(null),B.current=!1}},[ft,e,t,Qe,ue,We,ze,De,z,se,Xe,E,s,me,vr,ht,y]),Fn=Ge((r,g)=>{C?C(r):Gs(r,g)},[C,Gs]),Vo=`${Sc}:${e}`;pt(()=>{if(typeof window>"u")return;let r=localStorage.getItem(Vo);if(!r)return;let g;try{g=JSON.parse(r)}catch{en(Vo);return}if(!g||typeof g.createdAt!="number"||Date.now()-g.createdAt<0||Date.now()-g.createdAt>wc||typeof g.paymentMethodId!="string"||typeof g.providerIntentId!="string"||typeof g.paymentMethodType!="string"||g.sessionId!==e||!t||g.nonce!==t||!uo.includes(g.paymentMethodType)){en(Vo);return}en(Vo),Fn({id:g.paymentMethodId,type:"card",threeDSecureActionResultTokenId:g.providerIntentId,gateway:"stripe",paymentMethodType:g.paymentMethodType},{...g.accountPatch?{accountPatch:g.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Fn,t,e,Vo,uo]);let Ys=K(!1);pt(()=>{if(typeof window>"u"||Ys.current)return;let[r,g,q]=hc();if(!r||!g||Sa.current||!se)return;let ge=se.getRawProvider();if(!ge)return;let D=it=>{let gt=localStorage.getItem(it);if(!gt)return null;try{return JSON.parse(gt)}catch{return en(it),null}},Q=D(Ir)??D(ic),Tt;if(Q?.clientSecret){if(Q.clientSecret!==g)return;Tt={...Q.accountPatch?{accountPatch:Q.accountPatch}:{},...Q.sessionId?{sessionId:Q.sessionId}:{},...Q.nonce?{nonce:Q.nonce}:{}}}else if(Q?.sessionId&&Q.sessionId!==e)return;Ys.current=!0,en(Ir),en(ic),window.history.replaceState({},"",vc());let Gn=Q?.paymentMethodType??Q?.tokenType??"card",Ve="card";(async()=>{if(q==="failed"){let Tr="Payment was declined. Please try again.";me(Tr),vr(Ve,Tr);return}let{paymentIntent:it,error:gt}=await ge.retrievePaymentIntent(g);if(gt){let Tr=gt.message??"Failed to retrieve payment status.";me(Tr),vr(Ve,Tr,{code:gt.code});return}let Ft=it?.status,Jr=na(Ft);if(!it||!Jr){let Tr=Ft==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(Tr),vr(Ve,Tr,{code:Ft??"missing_payment_intent"});return}let qn=typeof it.payment_method=="string"?it.payment_method:it.payment_method?.id;Fn({id:qn??Q?.paymentMethodId??Q?.tokenId??it.id,type:"card",threeDSecureActionResultTokenId:it.id,gateway:Q?.gateway??"stripe",paymentMethodType:Gn},Tt)})()},[e,Fn,se,me,vr]);let bi=Ge(r=>{r.preventDefault()},[]);if(!(p||se!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Ko=Be==="buttons",Dn=U?.variables,Yc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ci=Dn?.colorBackground,Jc=Ci&&!Yc.has(Ci)?Ci:void 0,Go=S.cardInputBorder??(Ko?"#e5e7eb":"#A4A4FF"),Js=Dn?.colorDanger??"#dc2626",Gt=r=>er[r]&&(hr[r]||Ht),_a=ao&&(gr||Ht),Kn=r=>r?Js:Go,Ta=(Nn.malformed||Nn.empty)&&(fr||Ht),Zc=Kn(Ta),Si=S.cardFormContainer?.backgroundColor??Jc??(Ko?"white":"#EDEDFF"),yo=S.cardInputBackground??Dn?.colorBackground??"white",wi=ho(Te),Zs=ho(qe),mo=S.nameInput,Xs=S.cardInputFontSize??wp(mo?.fontSize)??Dn?.fontSizeBase??"16px",Qs=typeof mo?.fontFamily=="string"?mo.fontFamily:Dn?.fontFamily??"Poppins, sans-serif",el=Yu(mo?.fontWeight)??400,Xc=S.cardInputColor??(typeof mo?.color=="string"?mo.color:void 0)??Dn?.colorText??"#262833",Qc=S.cardInputPlaceholderColor??"#9ca3af",Qt=Dn?.borderRadius??"8px",Gr=Dn?.borderRadius??S.cardButton?.borderRadius??Qt,Yr=Dn?.colorPrimary??"#4A49FF",ed=Dn?.colorPrimaryHover??_u(Yr,.12),ki=Dn?.colorText??"#262833",Ii={fontSize:Xs,fontFamily:Qs,fontWeight:el,color:Xc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Yo={marginTop:"0.375rem",...Ii,fontSize:"0.75rem",lineHeight:1.4,color:Js},td={"--flopay-input-placeholder-color":Qc,"--flopay-input-font-size":Xs,"--flopay-input-font-family":Qs,"--flopay-input-font-weight":String(el)},Jo=S.cardFormContainer??{},Ri=Jo.padding??(Ko?"0":"1rem"),Ei=Jo.borderRadius??Qt,nd=_t&&rr?d(_i,{capture:_t,html:rr.html,messageToken:rr.messageToken,expectedOrigin:rr.expectedOrigin,verificationRequired:rr.verificationRequired,theme:He,submitLabel:O,onReady:()=>{if(!Lr&&!ue||typeof document>"u")return;let r=()=>{let q=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(q){Ln.current=!0;try{q.focus()}finally{Ln.current=!1}}};nr.current||r()},onError:r=>{r&&rr.verificationRequired&&l.current==="idle"&&(Nr.current=!0),me(r)},onValidation:r=>{let g=l.current;(g==="idle"||g==="validation-window")&&(me(r),r&&l.current==="validation-window"&&(R.current&&(clearTimeout(R.current),R.current=null),l.current="idle",x(null)))}},an):d("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"}),tl=Ke("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&_r()},style:{backgroundColor:Si,borderRadius:Ei,...Jo,padding:Ri,...td,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
5
5
|
.flopay-shared-input::placeholder {
|
|
6
6
|
color: var(--flopay-input-placeholder-color);
|
|
7
7
|
opacity: 1;
|
|
@@ -9,13 +9,13 @@ ${_t.join(`
|
|
|
9
9
|
font-family: var(--flopay-input-font-family);
|
|
10
10
|
font-weight: var(--flopay-input-font-weight);
|
|
11
11
|
}
|
|
12
|
-
`}),Ko&&Or&&
|
|
13
|
-
`)}):null,rl=r=>
|
|
14
|
-
`)}):null,ol=tt==="apm-expanding"||tt==="apm-form"||tt==="apm-collapsing",fo;tt==="apm-expanding"?fo=cc:tt==="apm-collapsing"&&(fo=dc);let Aa=cn?kc(gi,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:ea,padding:"0 1rem"}:{padding:"0.9rem 1rem"},fe;tt==="expanding"||tt==="apm-expanding"?fe=dp:(tt==="collapsing"||tt==="apm-collapsing")&&(fe=cp);let D;return tt==="expanding"?D=cc:tt==="collapsing"&&(D=dc),Xe("form",{onSubmit:bi,className:ne,noValidate:!0,style:{position:"relative"},children:[p(Da,{}),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?pp:{},...fe?{animation:fe,pointerEvents:"none"}:{}},children:[nl("flopay-direct-paypal-gate-debug"),rl("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(ia.Provider,{value:d,children:p($a,{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:Ra==="popup"?void 0:Ra,onTokenizedBody:An,onComplete:s,onErrorChange:ue,onDecline:f,onTechnicalFailure:lo,onButtonClick:Q,runBeforeButtonClick:sr,isProcessing:_e,onLoadStateChange:hi,onInitializationStateChange:Pi,session:ft,existingOrderId:le?.orderId,debug:F},le?.orderId??"fresh")})]}),Wo&&p(no,{stripe:$o,options:Is,children:p(pc,{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:Fs,placeholderBorderRadius:Gr,popupCapabilityOwner:d,externalTelemetryContext:$s,presentationMode:co})}),po?p(no,{stripe:qn,options:ks,children:p(mc,{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:Os,placeholderBorderRadius:Gr,popupCapabilityOwner:d,externalTelemetryContext:J})}):null,!po&&qs?p("div",{style:{height:ea,borderRadius:Gr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Ho&&p(fc,{sessionId:e,nonce:t,email:Ze.email,billingName:[Ze.firstName,Ze.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Be,billingApiUrl:at,paymentElementMethods:ka,stripeInstance:qn,paymentElementBaseOptions:gi,futureUseSession:me,onTokenizedBody:An,onErrorChange:ue,onButtonClick:Q,onDecline:f,runBeforeButtonClick:sr,onLoadStateChange:Ls,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,...cs({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=Xc)},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:tl}),he&&ol&&cn&&Aa&&qn&&p("div",{style:{gridArea:"1 / 1",...fo?{animation:fo}:{},...tt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Xe("div",{style:{backgroundColor:Si,borderRadius:Ei,...Jo,padding:Ri},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:wi?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:ki,paddingRight:80,...S.title},children:`Pay with ${fa(cn)}`})]}),p(no,{stripe:qn,options:Aa,children:p(os,{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 ol&&cn&&Aa&&qn&&he?Xe("form",{onSubmit:bi,className:ne,noValidate:!0,style:{position:"relative"},children:[p(Da,{}),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:Si,borderRadius:Ei,...Jo,padding:Ri},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:wi?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:ki,paddingRight:80,...S.title},children:`Pay with ${fa(cn)}`})]}),p(no,{stripe:qn,options:Aa,children:p(os,{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:bi,className:ne,noValidate:!0,style:{position:"relative"},children:[p(Da,{}),de&&p(Sr,{status:de,errorMessage:rt,authorized:Xn}),Xe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[nl("flopay-direct-paypal-gate-debug-default"),rl("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(ia.Provider,{value:d,children:p($a,{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:Ra==="popup"?void 0:Ra,onTokenizedBody:An,onComplete:s,onErrorChange:ue,onDecline:f,onTechnicalFailure:lo,onButtonClick:Q,runBeforeButtonClick:sr,isProcessing:_e,onLoadStateChange:hi,onInitializationStateChange:Pi,session:ft,existingOrderId:le?.orderId,debug:F},le?.orderId??"fresh")})]}),Wo&&p(no,{stripe:$o,options:Is,children:p(pc,{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:Fs,placeholderBorderRadius:Gr,popupCapabilityOwner:d,externalTelemetryContext:$s,presentationMode:co})}),po&&p(no,{stripe:qn,options:ks,children:p(mc,{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:Os,placeholderBorderRadius:Gr,popupCapabilityOwner:d,externalTelemetryContext:J})}),Ho&&p(fc,{sessionId:e,nonce:t,email:Ze.email,billingName:[Ze.firstName,Ze.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:at,paymentElementMethods:ka,stripeInstance:qn,paymentElementBaseOptions:gi,futureUseSession:me,onTokenizedBody:An,onErrorChange:ue,onButtonClick:Q,onDecline:f,runBeforeButtonClick:sr,onLoadStateChange:Ls,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&&(Hc||Wc||Vc)&&p(sl,{label:"or pay with card"}),u&&tl]})}import{Fragment as Rr,jsx as se,jsxs as sn}from"react/jsx-runtime";var Oo=44,hs="flopay_checkout_saved_payment_resume",si=new Map,ai=new Map;function Ec(e,t){t.settled&&t.consumers===0&&si.get(e)===t&&si.delete(e)}function _p(e,t,n){let o=ai.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};ai.set(e,i);let s=()=>{ai.get(e)===i&&ai.delete(e)};return a.then(s,s),a}function ha(e){return new Promise(t=>setTimeout(t,e))}function ii(e,t,n){let o=qa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Oc,enabled:t!==!1});return o.beginCheckout(n),o}function Pa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ps(e,t,n,o,a,i){let s=ii(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Pa(s)}function _c(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 Tc(e,t,n,o,a){let i=Bc(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 ys(e){return!e||e.data.stripe?.publishableKey?!1:!!Fc(e.data.paypal)?.clientId}var Tp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Mp(e){return new vp(Tp,{publishableKey:"provider_unavailable",...e})}async function ms(e,t){let{publishableKey:n,paypalPublishableKey:o}=Vi(e);return{...await Ki({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function Ps(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Ap(){if(!Ps())return null;try{let e=window.sessionStorage.getItem(hs);return e?JSON.parse(e):null}catch{return null}}function Mc(e){if(Ps())try{window.sessionStorage.setItem(hs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function fs(){if(Ps())try{window.sessionStorage.removeItem(hs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function xp(){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 Ac(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function gs(e,t){return Rp(!!e,t)}function Bp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function xc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Fp(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 vs({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=kp(o),vt=Yn(()=>Dc(Fe),[Fe]),qe=i??vt?.appearance,Ee=n?"embedded_checkout":"standard_checkout",Je=gs(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?ca(n):"",[n]),Ne=n?`create:${mt}`:`session:${e??""}`,wt=xc(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(Nl.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:Bp(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=>Ga(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:Oc,checkout_type:Ee,checkout_layout:Je,billing_api_url:U})},[Je,Ee,U]);let It=Yn(()=>n?ca(n,!0):"",[n]),Ln=Yn(()=>Jn===It?jt:void 0,[jt,Jn,It]),er=Yn(()=>n?Di(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=xc(w),Wt=Yt.current??Oe.current,de=pn(Wt),x=Wt?null:ii(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=ec(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&&Mc({sessionId:j,publishableKey:et.current.publishableKey,paypalPublishableKey:et.current.paypalPublishableKey}),Be=await Nn(Z=>Za(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"&&fs();else if(b?.initialAutoProcessingPending){let Z=b.initialAutoProcessingPending,S=new oi(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"),Ac("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&&Mc({sessionId:j,publishableKey:et.current.publishableKey,paypalPublishableKey:et.current.paypalPublishableKey}),Be=await Nn(S=>Za(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"&&fs())}}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 ha(600),Ht=()=>xe.current?.(Be)}catch(te){let we=Ur(pa(te),j);if(we.code==="three_ds_aborted")return!1;let Be=we.checkoutMethod??ua;Tt(we.message),kt(we.message),mn(!1),b?.fallbackToFull&&(B.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),qt("full"),Ac("full")),Pe();let rt=we.statusCode===void 0?void 0:Ep(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=Bc(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([ha(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&&Pa(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=Ap();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 Ki({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=El(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 oi(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 ha(600),Nt(()=>xe.current?.({status:h,paymentIntentId:B.id,paymentMethodId:y,checkoutMethod:"paypal"}))}catch(Wt){let de=Ur(pa(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=ii(U,a,u);R.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Pa(R)}else ps(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 ha(400)}finally{fs(),xp(),Le(null),kt(null),Dn(!1)}})())},[mr,s,U,a,u]);let Tn=At(null),gr=Yn(()=>$t?ca($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=ii(U,a,u),it=new oi(U,{telemetry:!1}),Wt=!1;try{let de=w.idempotencyKey===void 0?void 0:Rc(w.idempotencyKey),x=Gl(b,j),B=Kl(b,j);x?.canonicalIdentity===j&&B&&B.canonicalIdentity===void 0&&(Ha(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&&(Vl($.data.session,w)?(Va(b,j,h,x.nonce??$.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(Ha(b,j,B.idempotencyKey),R??(R=B.idempotencyKey))):(Wa(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($i(h))return{sid:h,result:$};Wa(b,j),h=null,$=null,y=!0}}catch{K.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),x?.canonicalIdentity===void 0?(Wa(b,j),R=de):ji(b,j),h=null}if(!h){!de&&(y||!R)&&(R=Rc(),l=R),R&&Ha(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:gs(re,Y)};Object.defineProperty(rt,bp,{configurable:!1,enumerable:!1,value:{onAttempt:q=>{Be=Math.max(Be,q)}}});let Z=()=>{_c(K,"session_create",we,Be)},S=q=>{Tc(K,q,"session_create",we,Be)&&T({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(Sp(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&&Va(b,j,_e,ge.data.session?.clientSecret??q.nonce),_c(K,"session_claim",Ke),Z(),ge},ge=>{throw ji(b,j),Tc(K,ge,"session_claim",Ke,0)&&T({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),ge}).finally(()=>Pa(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&&Va(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||Pa(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=Di(j,w),it=ca(K),Wt=Hl(K),de=si.get(it);if(!de){let R={canonicalIdentity:it,promise:Er.current(K,Wt,it),consumers:0,settled:!1};de=R,si.set(it,R);let l=()=>{R.settled=!0,Ec(it,R)};R.promise.then(l,l)}de.consumers+=1;let x=!1,B=()=>{x||(x=!0,de.consumers-=1,Ec(it,de))};b?.(B);try{let R=await de.promise;Tn.current=it,w&&($n(It),Qt(te=>kl(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 ms(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(!Fp(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(Il(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=Vi(R.result);let y=ys(R.result),h=$i(R.sid||l?.id);if(!w&&B&&l&&!y&&!h){tn.current=!0,await _p(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=Na(R);if(B&&l==="session_auto_completed"){tn.current=!0,Le("success"),await ha(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 oi(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 Oa(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=ys(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=wl(R,x);if(x&&T({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),l){let{errorCode:h,stage:$,...le}=l;ps(U,a,u,h,$,le)}if(l?.stage==="provider_load"&&(M??B?.data.session?.checkoutMode??"full")==="full"&&Sl(B,ve,V)){let h=Mp({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:Cl();y!==R&&Nt(()=>L.current?.(y)),oe(y),_t(!1)}}async function de(x){let{flopay:B,paypalFlopay:R,...l}=await ms(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 ms(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}=Fi(b);ps(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=Fc(Ae?.data.paypal,ye),Or=ys(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&&(wp(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(Op,{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($l,{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(Ka,{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(Ka,{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(Dp,{sessionId:H,nonce:F?.clientSecret||void 0,billingApiUrl:U,session:F,submitLabel:$e,walletPresentation:v,children:re})]}):se(ds,{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(Cp(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:gs(re,Y),className:pt,submitLabel:$e,directPaypal:Mn,isSubscription:F?.mode==="subscription",session:F,dataAttachmentPending:Cn,dataAttachmentRequiresIdentity:Ft,debug:Ie})]},Ne)}),an]})}function Dp({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,children:s}){return se(Rr,{children:us.Children.map(s,c=>{if(!us.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:us.cloneElement(c,C)})})}function Op({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(()=>Dc(i),[i]),O=Yn(()=>{let P=ne?.buttonsLayout??Ip(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(ta,{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:`
|
|
12
|
+
`}),Ko&&Or&&Ke("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:p?-2:0},children:[Ke("button",{type:"button",onClick:J,style:{display:"inline-flex",alignItems:"center",gap:wi?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:[d("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:d("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:d("path",{d:"M15 18l-6-6 6-6"})})}),d(vo,{content:Te})]}),Zs?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:S.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...S.title},children:d(ta,{content:qe})})]}),!Ko&&!Zs&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ki,order:p?-3:0,...S.title},children:d(ta,{content:qe})}),p&&ce&&d("div",{style:{order:-2,width:"100%"},children:ce}),p&&Lr&&Ke("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[d("div",{style:{backgroundColor:yo,border:`1px solid ${Kn(_a)}`,borderRadius:Qt,padding:"10px"},children:d("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Bt,onChange:r=>{Mt("email"),cn.current=r.target.value,kn(r.target.value)},onPointerDown:()=>Mt("email"),onKeyDown:()=>Mt("email"),onBlur:()=>{zn("email")&&Hn(!0),ao||yi()},disabled:xe,required:!0,"aria-invalid":_a||void 0,"aria-describedby":_a?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ii}})}),_a&&d("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Yo,children:ci.empty?"Email address is required":"Enter a valid email address"})]}),ue&&d("div",{style:{order:p?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=zt,g=(D=!1)=>({backgroundColor:yo,border:`1px solid ${Kn(D)}`,borderRadius:Qt,marginTop:"0.5rem",padding:"10px"}),q=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ii}),ge=Bu(r);return Ke(Fo,{children:[Yt(ue.address_line_1,r)&&Ke(Fo,{children:[d("div",{style:g(Gt("line1")),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:xt,onChange:D=>{Mt("line1"),dn.current.addressLine1=!0,ln.current=D.target.value,jn(D.target.value)},onPointerDown:()=>Mt("line1"),onKeyDown:()=>Mt("line1"),onBlur:()=>En("line1"),disabled:xe,required:!0,"aria-invalid":Gt("line1")||void 0,"aria-describedby":Gt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:q()})}),Gt("line1")&&d("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Yo,children:"Street address is required"})]}),Yt(ue.address_line_2,r)&&d("div",{style:g(),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:qt,onChange:D=>{dn.current.addressLine2=!0,on.current=D.target.value,ur(D.target.value)},disabled:xe,"data-testid":"flopay-address-line2",style:q()})}),(Yt(ue.city,r)||Yt(ue.state,r))&&Ke("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Yt(ue.city,r)&&d("div",{style:{flex:1,backgroundColor:yo,borderTop:`1px solid ${Kn(Gt("city"))}`,borderRight:`1px solid ${Kn(Gt("city"))}`,borderBottom:`1px solid ${Kn(Gt("city"))}`,borderLeft:`1px solid ${Kn(Gt("city"))}`,padding:"10px",borderTopLeftRadius:Qt,borderBottomLeftRadius:Qt,...Yt(ue.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Qt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:jt,onChange:D=>{Mt("city"),dn.current.city=!0,$t.current=D.target.value,$n(D.target.value)},onPointerDown:()=>Mt("city"),onKeyDown:()=>Mt("city"),onBlur:()=>En("city"),disabled:xe,required:!0,"aria-invalid":Gt("city")||void 0,"aria-describedby":Gt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:q()})}),Yt(ue.state,r)&&d("div",{style:{flex:1,backgroundColor:yo,borderTop:`1px solid ${Kn(Gt("state"))}`,borderRight:`1px solid ${Kn(Gt("state"))}`,borderBottom:`1px solid ${Kn(Gt("state"))}`,borderLeft:`1px solid ${Kn(Gt("state"))}`,padding:"10px",borderTopRightRadius:Qt,borderBottomRightRadius:Qt,...Yt(ue.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Kn(Gt("state")||Gt("city"))}`}:{borderRadius:Qt}},children:ge?Ke("select",{id:"flopay-billing-state",name:"billing-state",value:Ae,onChange:D=>{Mt("state"),dn.current.state=!0,Rt.current=D.target.value,Le(D.target.value)},onPointerDown:()=>Mt("state"),onKeyDown:()=>Mt("state"),onBlur:()=>En("state"),disabled:xe,autoComplete:"billing address-level1",required:!0,"aria-invalid":Gt("state")||void 0,"aria-describedby":Gt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...q(),cursor:"pointer"},children:[d("option",{value:"",children:Gi(r)}),ge.map(D=>d("option",{value:D.code,children:D.name},D.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Gi(r),autoComplete:"billing address-level1",value:Ae,onChange:D=>{Mt("state"),dn.current.state=!0,Rt.current=D.target.value,Le(D.target.value)},onPointerDown:()=>Mt("state"),onKeyDown:()=>Mt("state"),onBlur:()=>En("state"),disabled:xe,required:!0,"aria-invalid":Gt("state")||void 0,"aria-describedby":Gt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:q()})})]}),Gt("city")&&d("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Yo,children:"City is required"}),Gt("state")&&Ke("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Yo,children:[Gi(r)," is required"]}),(Yt(ue.country,r)||Yt(ue.postal_code,r))&&Ke("div",{style:{display:"flex",flexDirection:X==="column"?"column":"row",gap:X==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Yt(ue.country,r)&&d("div",{style:{flex:X==="row"?1:void 0,backgroundColor:yo,borderTop:`1px solid ${Go}`,borderRight:`1px solid ${Go}`,borderBottom:`1px solid ${Go}`,borderLeft:`1px solid ${Go}`,padding:"10px",...X==="row"&&Yt(ue.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:Qt,borderBottomLeftRadius:Qt,borderRight:"none"}:{borderRadius:Qt}},children:Ke("select",{id:"flopay-billing-country",name:"billing-country",value:zt,onChange:D=>{dn.current.country=!0,bn.current=D.target.value,Ut(D.target.value),Je?.(D.target.value),Rt.current="",Le("")},disabled:xe,autoComplete:"billing country","data-testid":"flopay-country",style:{...q(),cursor:"pointer"},children:[zt===""?d("option",{value:"",children:"Select country"}):null,ku.map(D=>Ke("option",{value:D.code,children:[D.flag," ",D.name]},D.code))]})}),Yt(ue.postal_code,r)&&d("div",{style:{flex:X==="row"?1:void 0,backgroundColor:yo,border:`1px solid ${Zc}`,padding:"10px",...X==="row"&&Yt(ue.country,r)?{borderRadius:"0",borderTopRightRadius:Qt,borderBottomRightRadius:Qt}:{borderRadius:Qt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:ts(zt),autoComplete:"billing postal-code",value:Tn,onChange:D=>{Mt("zip"),dn.current.zip=!0,gn.current=D.target.value,vn(D.target.value),Ze?.(D.target.value)},onPointerDown:()=>Mt("zip"),onKeyDown:()=>Mt("zip"),onBlur:()=>{zn("zip")&&xn(!0)},disabled:xe,required:Nn.required,"aria-invalid":Ta||void 0,"aria-describedby":Ta?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:q()})})]}),Ta&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Yo,children:Nn.empty?`${ts(r)} is required`:bp(r)})]})})()}),p&&nd,at&&d(Eo,{margin:"0.75rem 0",styleOverride:S.errorBanner,children:at})]}),Ma={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"},nl=r=>M?!P||!br?d("pre",{"data-testid":r,style:Ma,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":r,style:Ma,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${P}`,` directPaypalConfigured=${br}`,` inAppBrowserDetected=${String(Ia)}`,` shouldRenderDirectPayPal=${jo}`,` shouldRenderStripePayPal=${Wo}`,` hasPaypalStripeInstance=${!!Ss}`].join(`
|
|
13
|
+
`)}):null,rl=r=>M?!ve||!Un?d("pre",{"data-testid":r,style:Ma,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":r,style:Ma,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${ve}`,` currency=${Ct}`,` amountInCents=${Uo}`,` enabledPaymentMethods: ${JSON.stringify(_e??[])}`,` enabledPaymentMethodsProvided=${qo}`,` hasEnabledMethods=${Ca}`,` expressMethods: ${JSON.stringify(wa)}`,` walletExpressMethods: ${JSON.stringify(uo)}`,` paymentElementMethods: ${JSON.stringify(fi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ka)}`,` hasStripeInstance=${!!Un}`,` shouldRenderWallets=${po}`,` shouldRenderPaymentElement=${Ho}`].join(`
|
|
14
|
+
`)}):null,ol=nt==="apm-expanding"||nt==="apm-form"||nt==="apm-collapsing",fo;nt==="apm-expanding"?fo=dc:nt==="apm-collapsing"&&(fo=uc);let Aa=un?Rc(gi,un,_):null;if(Be==="buttons"){let r=nt==="buttons"||nt==="expanding"||nt==="apm-expanding",g=nt==="expanding"||nt==="card"||nt==="collapsing",q=bt===void 0?{boxSizing:"border-box",height:ea,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ge;nt==="expanding"||nt==="apm-expanding"?ge=gp:(nt==="collapsing"||nt==="apm-collapsing")&&(ge=fp);let D;return nt==="expanding"?D=dc:nt==="collapsing"&&(D=uc),Ke("form",{onSubmit:bi,className:ie,noValidate:!0,style:{position:"relative"},children:[d(Da,{}),ye&&d(Sr,{status:ye,errorMessage:at,authorized:Mn}),Ke("div",{style:{display:"grid"},children:[Ke("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!ge?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!ge?Pp:{},...ge?{animation:ge,pointerEvents:"none"}:{}},children:[nl("flopay-direct-paypal-gate-debug"),rl("flopay-stripe-gate-debug"),jo&&ot&&Ke(Fo,{children:[pe&&d("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."}),d(ia.Provider,{value:m,children:d($a,{sessionId:e,nonce:t,billingApiUrl:ct,email:Qe.email,billingName:oo||void 0,onBuyerIdentityReady:Oe,clientId:ot.clientId,environment:ot.environment,currency:Ct.toUpperCase(),isSubscription:Lt,providerObjectType:F,approvalPresentation:Ra==="popup"?void 0:Ra,onTokenizedBody:Fn,onComplete:s,onErrorChange:me,onDecline:f,onTechnicalFailure:lo,onButtonClick:ee,runBeforeButtonClick:ir,isProcessing:xe,onLoadStateChange:hi,onInitializationStateChange:Pi,session:re,existingOrderId:pe?.orderId,debug:M},pe?.orderId??"fresh")})]}),Wo&&d(no,{stripe:$o,options:Is,children:d(yc,{sessionId:e,nonce:t,email:Qe.email,billingName:oo||void 0,onBuyerIdentityReady:Oe,billingApiUrl:ct,onTokenizedBody:Fn,onErrorChange:me,isProcessing:xe,onButtonClick:ee,onDecline:f,onTechnicalFailure:lo,runBeforeButtonClick:ir,onLoadStateChange:Fs,placeholderBorderRadius:Gr,popupCapabilityOwner:m,externalTelemetryContext:$s,presentationMode:co})}),po?d(no,{stripe:Un,options:ks,children:d(fc,{sessionId:e,nonce:t,email:Qe.email,billingName:oo||void 0,onBuyerIdentityReady:Oe,billingApiUrl:ct,intentKind:be>0?"payment":"setup",expressMethods:uo,onTokenizedBody:Fn,onErrorChange:me,onButtonClick:ee,onDecline:f,onTechnicalFailure:lo,runBeforeButtonClick:ir,onLoadStateChange:Os,placeholderBorderRadius:Gr,popupCapabilityOwner:m,externalTelemetryContext:y})}):null,!po&&qs?d("div",{style:{height:ea,borderRadius:Gr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Ho&&d(gc,{sessionId:e,nonce:t,email:Qe.email,billingName:[Qe.firstName,Qe.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Oe,billingApiUrl:ct,paymentElementMethods:ka,stripeInstance:Un,paymentElementBaseOptions:gi,futureUseSession:_,onTokenizedBody:Fn,onErrorChange:me,onButtonClick:ee,onDecline:f,runBeforeButtonClick:ir,onLoadStateChange:Ls,isProcessing:xe,submitButtonColor:Yr,submitButtonBorderRadius:Qt,submitButtonStyle:S.submitButton,onExpandApm:ut,expandedApmMethod:un,themeId:mt,buttonAppearance:{backgroundColor:S.cardButton?.backgroundColor,borderColor:S.cardInputBorder,textColor:S.cardButton?.color,borderRadius:Gr}}),p&&d("button",{type:"button",onClick:async()=>{xe||!(await ir("card")).proceed||(ee?.("card"),H())},disabled:xe,style:{width:"100%",...q,...S.cardButton,...cs({themeBundle:Z,resolvedPrimaryColor:Yr,resolvedBorderRadius:Qt,submitButtonStyle:S.submitButton,explicitPrimaryColor:Dn?.colorPrimary}),fontSize:S.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:xe?"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:xe?.6:1},onMouseEnter:Q=>{!xe&&(Z||Dn?.colorPrimary)&&(Q.currentTarget.style.backgroundColor=ed)},onMouseLeave:Q=>{(Z||Dn?.colorPrimary)&&(Q.currentTarget.style.backgroundColor=Yr)},onMouseDown:Q=>{Q.currentTarget.style.transform="scale(0.985)"},onMouseUp:Q=>{Q.currentTarget.style.transform="scale(1)"},children:d(Po,{content:bt})}),at&&nt==="buttons"&&d(Eo,{margin:"0.25rem 0",styleOverride:S.errorBanner,children:at})]}),p&&g&&d("div",{style:{gridArea:"1 / 1",...D?{animation:D}:{},...nt==="collapsing"?{pointerEvents:"none"}:{}},children:tl}),ve&&ol&&un&&Aa&&Un&&d("div",{style:{gridArea:"1 / 1",...fo?{animation:fo}:{},...nt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ke("div",{style:{backgroundColor:Si,borderRadius:Ei,...Jo,padding:Ri},children:[Ke("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ke("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Vt,style:{display:"inline-flex",alignItems:"center",gap:wi?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:[d("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:d("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:d("path",{d:"M15 18l-6-6 6-6"})})}),d(vo,{content:Te})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:S.titleFontSize??"1.05rem",color:ki,paddingRight:80,...S.title},children:`Pay with ${fa(un)}`})]}),d(no,{stripe:Un,options:Aa,children:d(os,{method:un,sessionId:e,nonce:t,email:Qe.email,billingName:[Qe.firstName,Qe.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Oe,billingApiUrl:ct,onTokenizedBody:Fn,onErrorChange:me,onDecline:f,onCancel:Vt,runBeforeButtonClick:ir,onButtonClick:ee,isProcessing:xe,submitButtonColor:Yr,submitButtonBorderRadius:Qt,submitButtonStyle:S.submitButton,errorText:at})},un)]})})]})]})}return ol&&un&&Aa&&Un&&ve?Ke("form",{onSubmit:bi,className:ie,noValidate:!0,style:{position:"relative"},children:[d(Da,{}),ye&&d(Sr,{status:ye,errorMessage:at,authorized:Mn}),d("div",{style:{...fo?{animation:fo}:{},...nt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ke("div",{style:{backgroundColor:Si,borderRadius:Ei,...Jo,padding:Ri},children:[Ke("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ke("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Vt,style:{display:"inline-flex",alignItems:"center",gap:wi?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:[d("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:d("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:d("path",{d:"M15 18l-6-6 6-6"})})}),d(vo,{content:Te})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:S.titleFontSize??"1.05rem",color:ki,paddingRight:80,...S.title},children:`Pay with ${fa(un)}`})]}),d(no,{stripe:Un,options:Aa,children:d(os,{method:un,sessionId:e,nonce:t,email:Qe.email,billingName:[Qe.firstName,Qe.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Oe,billingApiUrl:ct,onTokenizedBody:Fn,onErrorChange:me,onDecline:f,onCancel:Vt,runBeforeButtonClick:ir,onButtonClick:ee,isProcessing:xe,submitButtonColor:Yr,submitButtonBorderRadius:Qt,submitButtonStyle:S.submitButton,errorText:at})},un)]})})]}):Ke("form",{onSubmit:bi,className:ie,noValidate:!0,style:{position:"relative"},children:[d(Da,{}),ye&&d(Sr,{status:ye,errorMessage:at,authorized:Mn}),Ke("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[nl("flopay-direct-paypal-gate-debug-default"),rl("flopay-stripe-gate-debug-default"),jo&&ot&&Ke(Fo,{children:[pe&&d("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."}),d(ia.Provider,{value:m,children:d($a,{sessionId:e,nonce:t,billingApiUrl:ct,email:Qe.email,billingName:oo||void 0,onBuyerIdentityReady:Oe,clientId:ot.clientId,environment:ot.environment,currency:Ct.toUpperCase(),isSubscription:Lt,providerObjectType:F,approvalPresentation:Ra==="popup"?void 0:Ra,onTokenizedBody:Fn,onComplete:s,onErrorChange:me,onDecline:f,onTechnicalFailure:lo,onButtonClick:ee,runBeforeButtonClick:ir,isProcessing:xe,onLoadStateChange:hi,onInitializationStateChange:Pi,session:re,existingOrderId:pe?.orderId,debug:M},pe?.orderId??"fresh")})]}),Wo&&d(no,{stripe:$o,options:Is,children:d(yc,{sessionId:e,nonce:t,email:Qe.email,billingName:oo||void 0,onBuyerIdentityReady:Oe,billingApiUrl:ct,onTokenizedBody:Fn,onErrorChange:me,isProcessing:xe,onButtonClick:ee,onDecline:f,onTechnicalFailure:lo,runBeforeButtonClick:ir,onLoadStateChange:Fs,placeholderBorderRadius:Gr,popupCapabilityOwner:m,externalTelemetryContext:$s,presentationMode:co})}),po&&d(no,{stripe:Un,options:ks,children:d(fc,{sessionId:e,nonce:t,email:Qe.email,billingName:oo||void 0,onBuyerIdentityReady:Oe,billingApiUrl:ct,intentKind:be>0?"payment":"setup",expressMethods:uo,onTokenizedBody:Fn,onErrorChange:me,onButtonClick:ee,onDecline:f,onTechnicalFailure:lo,runBeforeButtonClick:ir,onLoadStateChange:Os,placeholderBorderRadius:Gr,popupCapabilityOwner:m,externalTelemetryContext:y})}),Ho&&d(gc,{sessionId:e,nonce:t,email:Qe.email,billingName:[Qe.firstName,Qe.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:ct,paymentElementMethods:ka,stripeInstance:Un,paymentElementBaseOptions:gi,futureUseSession:_,onTokenizedBody:Fn,onErrorChange:me,onButtonClick:ee,onDecline:f,runBeforeButtonClick:ir,onLoadStateChange:Ls,isProcessing:xe,submitButtonColor:Yr,submitButtonBorderRadius:Qt,submitButtonStyle:S.submitButton,themeId:mt,onExpandApm:ut,expandedApmMethod:un,buttonAppearance:{backgroundColor:S.cardButton?.backgroundColor,borderColor:S.cardInputBorder,textColor:S.cardButton?.color,borderRadius:Gr}})]}),p&&(Kc||Vc||Gc)&&d(sl,{label:"or pay with card"}),p&&tl]})}import{Fragment as Rr,jsx as le,jsxs as sn}from"react/jsx-runtime";var Oo=44,hs="flopay_checkout_saved_payment_resume",si=new Map,ai=new Map;function Tc(e,t){t.settled&&t.consumers===0&&si.get(e)===t&&si.delete(e)}function Op(e,t,n){let o=ai.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};ai.set(e,i);let s=()=>{ai.get(e)===i&&ai.delete(e)};return a.then(s,s),a}function ha(e){return new Promise(t=>setTimeout(t,e))}function ii(e,t,n){let o=qa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Lc,enabled:t!==!1});return o.beginCheckout(n),o}function Pa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ps(e,t,n,o,a,i){let s=ii(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Pa(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 Sn&&t.code==="session_auto_completed"?!1:t instanceof Sn&&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 ys(e){return!e||e.data.stripe?.publishableKey?!1:!!Oc(e.data.paypal)?.clientId}var Np={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Lp(e){return new Ep(Np,{publishableKey:"provider_unavailable",...e})}async function ms(e,t){let{publishableKey:n,paypalPublishableKey:o}=Vi(e);return{...await Ki({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function Ps(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function zp(){if(!Ps())return null;try{let e=window.sessionStorage.getItem(hs);return e?JSON.parse(e):null}catch{return null}}function xc(e){if(Ps())try{window.sessionStorage.setItem(hs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function fs(){if(Ps())try{window.sessionStorage.removeItem(hs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Up(){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 gs(e,t){return Fp(!!e,t)}function qp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Fc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function jp(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 vs({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:s,loading:c,error:f,onComplete:C,onError:T,onInstrument:I,onDecline:z,onCountryChange:ie,onZipChange:O,showPayPal:Se=!0,showStripe:G=!0,walletPresentation:v="auto",enabledPaymentMethods:P,showApplePay:ve=!0,showGooglePay:N=!0,debug:_e=!1,layout:Y,theme:Ne,buttonsTheme:yt,buttonsStyles:Be,cardButtonContent:mt,cardBackButtonContent:Nt,cardTitleContent:fe,showSecurityFooter:Fe,onButtonClick:bt,onBeforeButtonClick:Te,enableAVS:qe,cardFieldOrder:Re,cardPreFormSlot:ee,avsLayout:je,submitLabel:lt,className:It,initialErrorMessage:rt=null,initialPayPalOrderId:ce,children:X,checkoutMode:L,confirmLabel:he,renderConfirmButton:$e,onSessionCompleted:Me}){let A=xp(o),Ye=Zn(()=>Nc(Ne),[Ne]),Je=i??Ye?.appearance,Ze=n?"embedded_checkout":"standard_checkout",We=gs(X,Y),[ze,De]=Jt(null),[be,Ct]=Jt(null),Zt=At(null),ot=At(null),Lt=At(0),[E,ne]=Jt(null),Ue=At(null),[M,se]=Jt(null),Xe=Zn(()=>n?ca(n):"",[n]),we=n?`create:${Xe}`:`session:${e??""}`,ht=Fc(M),Xt=At(new Set),m=At(we),w=At(we);Xo(()=>{w.current=we,m.current!==we&&(m.current=we,Xt.current.clear())},[we]);let Ee=Cn(k=>{if(w.current===we){if(Nl.has(k.name)){if(Xt.current.has(k.name))return;Xt.current.add(k.name)}Dt(()=>I?.(k))}},[we,I]),de=Ro(Ee,we),y=At(!1),re=Cn(k=>{if(y.current)return;let b=k.gateway||!ht?k:{...k,gateway:ht};Ee(b)},[Ee,ht]);dr(()=>{de({class:"lifecycle",name:"checkout.mount"})},[de]);let[_,F]=Jt(e??""),j=e??_,et=n?"":j,[St,wt]=Jt(!0),[ct,$]=Jt(null),[wn,On]=Jt(0),[fn,zt]=Jt("full"),[Ut,Tn]=Jt(!1),[vn,xt]=Jt(rt),[jn,qt]=Jt(null),[ur,jt]=Jt(null),[$n,Ae]=Jt(!1),[Le,Bt]=Jt(void 0),[kn,In]=Jt(""),[Rn,gn]=Jt(!1),[bn,ln]=Jt(!1),[on,$t]=Jt(!1),Rt=At(null),cn=At(0),dn=At(void 0),[ue,Xn]=Jt("loading"),[Mn,pr]=Jt(0),tn=At(!1),hn=At(!1),yr=At(!1),Wn=At(null),Wt=At(null),p=Zn(()=>({checkoutMode:L??fn,layout:qp(X,Y)}),[L,X,fn,Y]),dt=At(C);dt.current=C;let W=At(T);W.current=T;let oe=At(z);oe.current=z;let Pt=Cn(k=>Ga(Wn,async b=>{try{return await k(b)}catch(H){throw b.aborted?To(H):H}}),[]);dr(()=>()=>{Wn.current?.abort(),Wn.current=null},[]);let tt=Cn((k,b)=>{Zt.current=k,Ct(k),Ue.current=b,ne(b)},[]),kt=Cn(()=>{let k=ot.current;k&&(ot.current=null,k.destroy())},[]);dr(()=>{mn(be)?.setCheckoutContext(p),E&&E!==be&&mn(E)?.setCheckoutContext(p)},[be,E,p]);let ke=At(Me);ke.current=Me;let An=Cn(k=>{Xn(k),!(k!=="exhausted"||yr.current)&&(yr.current=!0,W.current?.(new Sn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Dr=Cn(()=>{Xn("retrying"),pr(k=>k+1)},[]);dr(()=>{Xn("loading"),pr(0),yr.current=!1},[j]),dr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Lc,checkout_type:Ze,checkout_layout:We,billing_api_url:A})},[We,Ze,A]);let _t=Zn(()=>n?ca(n,!0):"",[n]),Nn=Zn(()=>kn===_t?Le:void 0,[Le,kn,_t]),Qn=Zn(()=>n?Di(n,Nn):void 0,[n,Nn]),er=L??Qn?.checkoutMode??"full",Ht=Zn(()=>Qn?{...Qn,checkoutMode:er}:void 0,[Qn,er]);dr(()=>{Bt(void 0),In(_t),dn.current=void 0,Rt.current=null,$t(!1)},[_t]),dr(()=>{xt(rt)},[rt]);let mr=Cn((k,b,H)=>{Dt(()=>{oe.current?.(yn(k,b,H))})},[]),fr=Cn(async(k,b)=>{xt(null),jt(null),Ae(!1),qt("processing");let H=b?.sessionId??k.id,J=k.clientSecret||t,ut=Fc(k),Vt=Zt.current??Ue.current,ye=mn(Vt),x=Vt?null:ii(A,a,p),B={log:te=>{ye?ye.log(te):x?.log(te)},error:te=>{ye?ye.error(te):x?.error(te)},terminal:te=>{ye?ye.terminal(te):x?.terminal(te)},performance:te=>{ye?ye.performance(te):x?.performance(te)},now:()=>ye?.now()??x?.now()??0,elapsed:te=>ye?.elapsed(te)??Math.max(0,(x?.now()??te)-te)},R=B.now(),l=!!(b?.initialAutoProcessingError||b?.initialAutoProcessingPending),u=!1,h,V=()=>{u||(u=!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"}))},pe=!1,Ce=()=>{pe||(pe=!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"}),y.current=!0;try{B.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{y.current=!1}de({class:"lifecycle",name:"payment.processing.started",provider:ut}),l&&V();let Kt;try{let te=ec(b?.initialAutoProcessingError),Ie=b?.initialAutoProcessingError?.type==="3ds_required"&&!b.initialAutoProcessingError.threeDSecureToken&&b.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:b.initialAutoProcessingError.nextActionRedirectUrl}:null,Oe,at=Z=>(V(),Pt(S=>Mo(Z,{billingApiUrl:A,sessionId:H,nonce:J,session:k,signal:S})));if(Ie)Oe=await at(Ie);else if(te)V(),te.type==="paypal_redirect_required"&&Wt.current?.publishableKey&&xc({sessionId:H,publishableKey:Wt.current.publishableKey,paypalPublishableKey:Wt.current.paypalPublishableKey}),Oe=await Pt(Z=>Za(te,{flopay:Zt.current,paypalFlopay:Ue.current,attempt3DS:b?.attempt3DS,billingApiUrl:A,sessionId:H,session:k,telemetry:!1,signal:Z})),te.type==="paypal_redirect_required"&&fs();else if(b?.initialAutoProcessingPending){let Z=b.initialAutoProcessingPending,S=new oi(A,{telemetry:!1}),U=await Pt(xe=>S.waitForCheckoutSessionCompletion(Z.sessionId,{initialDelayMs:Z.retryAfterMs,nonce:J,statusUrl:Z.statusUrl,signal:xe})),He=qr(U,k),Pe=U.autoProcessingError?.type==="3ds_required"&&U.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:U.autoProcessingError.nextActionRedirectUrl}:null;if(Pe)Oe=await at(Pe);else{if(!Ar(He))throw So(He);Oe=Mr(He,H)}}else{if(b?.initialAutoProcessingError)throw kr(b.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.initialAutoProcessingError.checkoutMethod});if(b?.fromCreateSession)return b?.fallbackToFull&&(zt("full"),Bc("full")),!1;{let Z=await Ao({billingApiUrl:A,sessionId:H,session:k,nonce:J,telemetry:!1});Z.type==="success"?Oe=Z.result:Z.type==="next_action_required"?Oe=await at(Z):(V(),Z.type==="paypal_redirect_required"&&Wt.current?.publishableKey&&xc({sessionId:H,publishableKey:Wt.current.publishableKey,paypalPublishableKey:Wt.current.paypalPublishableKey}),Oe=await Pt(S=>Za(Z,{flopay:Zt.current,paypalFlopay:Ue.current,attempt3DS:b?.attempt3DS,billingApiUrl:A,sessionId:H,session:k,telemetry:!1,signal:S})),Z.type==="paypal_redirect_required"&&fs())}}H&&_o(H),Ce(),l&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),B.terminal({outcome:Oe.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Ae(Oe.status==="authorized"),qt("success"),await ha(600),Kt=()=>dt.current?.(Oe)}catch(te){let Ie=Ur(pa(te),H);if(Ie.code==="three_ds_aborted")return!1;let Oe=Ie.checkoutMethod??ua;xt(Ie.message),jt(Ie.message),Ae(!1),b?.fallbackToFull&&(B.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),zt("full"),Bc("full")),Ce();let at=Ie.statusCode===void 0?void 0:Dp(Ie.statusCode,"unknown"),Z=at==="4xx"?{requestCategory:"process_payment",statusClass:at}:{},S=at===void 0||at==="4xx";if(S&&(Ie.telemetryOutcome==="payment_declined"||!!(Ie.declineCode||Ie.code?.toLowerCase().includes("declin"))))B.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Z});else if(S&&(Ie.telemetryOutcome==="validation_rejected"||Ie.type==="validation_error"))B.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Z});else{let Pe=Dc(te,l?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),xe=Ie.telemetryRequestCategory??"process_payment";y.current=!0;try{B.error({...Pe,...Ie.telemetryFailureCategory?{failureCategory:Ie.telemetryFailureCategory}:{},stage:l?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:xe})}finally{y.current=!1}de({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:xe,provider:ut})}return Dt(()=>W.current?.(Ie)),mr(Oe,Ie,{code:Ie.code,declineCode:Ie.declineCode}),qt("error"),await Promise.allSettled([ha(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{Ce(),x&&Pa(x),qt(null),jt(null)}return Dt(Kt),!0},[mr,de,t,A,Pt,a,p]);dr(()=>{if(typeof window>"u"||hn.current)return;let k=new URLSearchParams(window.location.search),b=k.get("payment_intent_client_secret");if(!b)return;let H=zp();H&&(hn.current=!0,(async()=>{let J,ut=0;xt(null),jt(null),qt("processing"),Tn(!0);try{if(k.get("redirect_status")==="failed")throw Object.assign(new Sn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Vt,paypalFlopay:ye}=await Ki({publishableKey:H.publishableKey,paypalPublishableKey:H.paypalPublishableKey,billingApiUrl:A,locale:s,telemetry:a});J=mn(ye??Vt),J?.setCheckoutContext(p),ut=J?.now()??0,J?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),J?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let x=(ye??Vt)?.getRawProvider();if(!x)throw Object.assign(new Sn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:R}=await x.retrievePaymentIntent(b);if(R)throw Object.assign(new Sn(R.message??"Failed to retrieve PayPal payment status.","api_error",{code:R.code}),{checkoutMethod:"paypal"});let l=El(B?.status);if(!B||l==="failed")throw Object.assign(new Sn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let u=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,h=l;if(H.sessionId){let Ce=(await new oi(A,{telemetry:!1}).getUnifiedCheckoutSession(H.sessionId)).data.session;if(Ce&&Ce.status!=="complete"){let Kt=await Ao({billingApiUrl:A,sessionId:H.sessionId,session:Ce,telemetry:!1,tokenizedData:{id:u??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(Kt.type!=="success")throw Object.assign(new Sn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});h=Kt.result.status}}H.sessionId&&_o(H.sessionId),J?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),J?.performance({stage:"redirect_resume",durationMs:J.elapsed(ut),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),J?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),qt("success"),await ha(600),Dt(()=>dt.current?.({status:h,paymentIntentId:B.id,paymentMethodId:u,checkoutMethod:"paypal"}))}catch(Vt){let ye=Ur(pa(Vt),H.sessionId),x=ye.checkoutMethod??"paypal",B=!!(ye.declineCode||ye.code?.toLowerCase().includes("declin"));if(J)J.performance({stage:"redirect_resume",durationMs:J.elapsed(ut),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?J.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):J.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let R=ii(A,a,p);R.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Pa(R)}else ps(A,a,p,"REDIRECT_RESUME_FAILED","redirect_resume");xt(ye.message),jt(ye.message),Dt(()=>W.current?.(ye)),mr(x,ye,{code:ye.code,declineCode:ye.declineCode}),qt("error"),await ha(400)}finally{fs(),Up(),qt(null),jt(null),Tn(!1)}})())},[mr,s,A,a,p]);let xn=At(null),gr=Zn(()=>Ht?ca(Ht):"",[Ht]),Hn=At(Ht);Hn.current=Ht,dr(()=>{F(e??"")},[e]),dr(()=>{tn.current=!1,xt(rt),jt(null),Ae(!1),qt(null)},[gr,rt,e]);async function hr(k,b,H){let J=ii(A,a,p),ut=new oi(A,{telemetry:!1}),Vt=!1;try{let ye=k.idempotencyKey===void 0?void 0:_c(k.idempotencyKey),x=Gl(b,H),B=Kl(b,H);x?.canonicalIdentity===H&&B&&B.canonicalIdentity===void 0&&(Ha(b,H,B.idempotencyKey),B={...B,canonicalIdentity:H});let R=ye??(B?.canonicalIdentity===H?B.idempotencyKey:void 0),l,u=!1;J.log({name:x?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let h=x?.sid??null,V=null,pe,Ce,Kt=!1;if(h)try{V=await ut.getUnifiedCheckoutSession(h,x?.nonce),x&&x.canonicalIdentity===void 0&&(Vl(V.data.session,k)?(Va(b,H,h,x.nonce??V.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(Ha(b,H,B.idempotencyKey),R??(R=B.idempotencyKey))):(Wa(b,H),B=null,R=ye,h=null,V=null));let Ie=V?.data.session?.status,Oe=V?.data.session,at=Oe?.clientSecret||x?.nonce;if(h&&Oe?.buyerIdentified===!1&&at&&(Ce=Co(ut,h,at,k.account)),h&&V&&Ie==="complete"){if($i(h))return{sid:h,result:V};Wa(b,H),h=null,V=null,u=!0}}catch{J.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),x?.canonicalIdentity===void 0?(Wa(b,H),R=ye):ji(b,H),h=null}if(!h){!ye&&(u||!R)&&(R=_c(),l=R),R&&Ha(b,H,R);let Ie=J.now(),Oe=0;J.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let at={...k,idempotencyKey:R,avsCheck:!!qe,avsConfig:typeof qe=="object"?qe:void 0,checkoutType:"embedded_checkout",checkoutLayout:gs(X,Y)};Object.defineProperty(at,_p,{configurable:!1,enumerable:!1,value:{onAttempt:U=>{Oe=Math.max(Oe,U)}}});let Z=()=>{Mc(J,"session_create",Ie,Oe)},S=U=>{Ac(J,U,"session_create",Ie,Oe)&&de({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(Mp(at)){let U=await ut.createDetachedSession(at);U.claimed.catch(()=>{}),V=U.shell,h=U.sessionId,Ce=U.claim;let He=J.now();J.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),pe=U.claimed.then(Pe=>{let xe=Pe.data.session?.id??U.sessionId;return xe&&Va(b,H,xe,Pe.data.session?.clientSecret??U.nonce),Mc(J,"session_claim",He),Z(),Pe},Pe=>{throw ji(b,H),Ac(J,Pe,"session_claim",He,0)&&de({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Pe}).finally(()=>Pa(J)),pe.catch(()=>{}),Vt=!0,J.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),J.performance({stage:"session_shell",durationMs:J.now()-Ie,durationMode:"machine",requestCategory:"session_create",attempt:Oe,statusClass:"2xx",paymentMethodCategory:"card"})}else V=await ut.createAndFetchSession(at),Z()}catch(U){throw S(U),U}h=V.data.session?.id??h??"",h&&!pe&&Va(b,H,h,V.data.session?.clientSecret)}let te=V?.data.session;return!Ce&&h&&te?.buyerIdentified===!1&&te.clientSecret&&(Ce=Co(ut,h,te.clientSecret,k.account)),{sid:h??"",result:V,sdkGeneratedIdempotencyKey:l,...pe?{claimed:pe}:{},...Ce?{claim:Ce}:{},...Kt?{claimRequiresIdentity:!0}:{}}}finally{Vt||Pa(J)}}let Er=At(hr);Xo(()=>{Er.current=hr},[hr]);let Ln=Cn(async(k,b)=>{let H=Hn.current;if(!H)throw new Sn("createSession is required to bootstrap checkout.","validation_error");let J=Di(H,k),ut=ca(J),Vt=Hl(J),ye=si.get(ut);if(!ye){let R={canonicalIdentity:ut,promise:Er.current(J,Vt,ut),consumers:0,settled:!1};ye=R,si.set(ut,R);let l=()=>{R.settled=!0,Tc(ut,R)};R.promise.then(l,l)}ye.consumers+=1;let x=!1,B=()=>{x||(x=!0,ye.consumers-=1,Tc(ut,ye))};b?.(B);try{let R=await ye.promise;xn.current=ut,k&&(In(_t),Bt(te=>kl(te,k)));let{sid:l,result:u,claimed:h,claim:V,claimRequiresIdentity:pe}=R;if(dn.current=V,$t(pe===!0),De(u),u.data.session&&se(u.data.session),l&&F(l),h){cn.current+=1;let te=cn.current;Rt.current=h,ln(!0),h.then(Ie=>{cn.current===te&&(Rt.current===h&&(Rt.current=null),De(Ie),Ie.data.session&&se(Ie.data.session),ln(!1),$t(!1))},Ie=>{cn.current===te&&(Rt.current===h&&(Rt.current=null),ln(!1),$t(!1),$(Ie instanceof Sn?Ie:new Sn(Ie instanceof Error?Ie.message:"Failed to create session","api_error")))})}else cn.current+=1,Rt.current=null,ln(!1),$t(!1);let{flopay:Ce,paypalFlopay:Kt}=await ms(u,{billingApiUrl:A,locale:s,telemetry:a});return tt(Ce,Kt),wt(!1),R}catch(R){throw xn.current===ut&&(xn.current=null),R}finally{b||B()}},[_t,tt,s,A,a]),tr=At(fr);tr.current=fr;let nr=At(Ln);nr.current=Ln;let Mt=Cn(async k=>{if(!jp(k)||Rn)return{sessionId:_,session:M};gn(!0);try{let b=await Ln(k);return{sessionId:b.sid,session:b.result.data.session??null}}finally{gn(!1)}},[Ln,Rn,_,M]),zn=Cn(async k=>{let b=dn.current;if(!b)return;let H=cn.current,J=await b(k);cn.current===H&&(De(J),J.data.session&&se(J.data.session))},[]),En=Cn(async()=>{await Rt.current},[]),rr=Cn(async()=>(await En(),{proceed:!0}),[En]);dr(()=>{let k=!1,b,H=++Lt.current;kt(),$(null),On(0);let J=()=>{k=!0,Lt.current===H&&(Lt.current+=1,kt())},ut=Hn.current;if(gr&&ut)return zt(er),wt(!1),xn.current===gr?J:(se(Il(ut,L)),(async()=>{let x=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),B=er==="auto"&&!tn.current&&!x;B&&(xt(null),jt(null),qt("processing"));try{let R=await nr.current(void 0,V=>{b=V}),l=R.result.data.session??null;Wt.current=Vi(R.result);let u=ys(R.result),h=$i(R.sid||l?.id);if(!k&&B&&l&&!u&&!h){tn.current=!0,await Op(gr,R.sdkGeneratedIdempotencyKey,()=>tr.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}!k&&B&&((u||h)&&(tn.current=!0),qt(null),jt(null))}catch(R){if(k)return;let l=Na(R);if(B&&l==="session_auto_completed"){tn.current=!0,qt("success"),await ha(600),k||(Dt(()=>{dt.current?.({status:"succeeded"})}),qt(null),jt(null));return}B&&(qt(null),jt(null));let u=R instanceof Sn?R:new Sn(R instanceof Error?R.message:"Failed to create session","api_error");$(u)}finally{b?.(),b=void 0}})(),()=>{J(),b?.()});wt(!0);async function Vt(){let x=!1,B=null;try{let R=new oi(A,{telemetry:!1}),l=await R.getUnifiedCheckoutSession(j,t);if(B=l,k)return;De(l);let u=l.data.session??null;if(se(u),!u)throw new Sn("No session data returned","api_error");let h=u.checkoutMode;if(h==="setup")throw new Sn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(u.status==="authorized"){wt(!1),Dt(()=>{dt.current?.(Mr(u,j)),ke.current?.(u.successUrl??"")});return}if(u.status==="complete"){wt(!1),Dt(()=>{ke.current?.(u.successUrl??"")});return}if(u.status==="expired")throw Oa(u);x=!0;let V=L??h??"full";zt(V),cn.current+=1;let pe=u.clientSecret||t;dn.current=u.buyerIdentified===!1&&pe?Co(R,j,pe,{...u.customer?.id?{userId:u.customer.id}:{}}):void 0,ln(!1),$t(!1);let Ce=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Kt=ys(l);if(V==="auto"&&!tn.current&&!Ce&&!Kt){tn.current=!0;let te=ye(l);try{if(await tr.current(u,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>te,sessionId:j||u.id}),k)return;await te,k||wt(!1);return}catch{if(k)return;await te,k||wt(!1);return}}await ye(l),k||wt(!1)}catch(R){if(k)return;let l=wl(R,x);if(x&&de({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),l){let{errorCode:h,stage:V,...pe}=l;ps(A,a,p,h,V,pe)}if(l?.stage==="provider_load"&&(L??B?.data.session?.checkoutMode??"full")==="full"&&Sl(B,Se,G)){let h=Lp({billingApiUrl:A,locale:s,telemetry:a});ot.current=h,tt(h,null),On(1),wt(!1);return}let u=R instanceof Sn&&l?.stage!=="provider_load"?R:Cl();u!==R&&Dt(()=>W.current?.(u)),$(u),wt(!1)}}async function ye(x){let{flopay:B,paypalFlopay:R,...l}=await ms(x,{billingApiUrl:A,locale:s,telemetry:a});Wt.current={publishableKey:l.publishableKey,paypalPublishableKey:l.paypalPublishableKey},tt(B,R),On(0)}return Vt(),J},[L,gr,er,et,t,Se,G]);let or=Cn(async()=>{if(!ze||wn!==1)return;let k=Lt.current;On(2);try{let{flopay:b,paypalFlopay:H}=await ms(ze,{billingApiUrl:A,locale:s,telemetry:a});if(Lt.current!==k)return;kt(),tt(b,H),On(0)}catch(b){if(Lt.current!==k)return;let{errorCode:H,stage:J,...ut}=Fi(b);ps(A,a,p,H,J,ut)}},[kt,tt,s,wn,A,a,p,ze]),nt=!!(j&&(M?.clientSecret||t)),nn=Ut||!nt,un=Cn(async()=>{if(!(Ut||!nt||!M)){Tn(!0),xt(null);try{await fr(M,{attempt3DS:!0,fallbackToFull:!0,sessionId:j||M.id})}finally{Tn(!1)}}},[j,Ut,nt,fr,M]),Bn=Oc(ze?.data.paypal,ce),Or=ys(ze),Pr=Zn(()=>{if(!(!ze||!M||!ze.data.stripe?.publishableKey))return{billingApiUrl:A}},[ze,M,A]),_r=!!(n&&!X&&Y==="buttons"&&Te&&er==="full"),Vn=!!(j&&(Ap(M?.vault)||Qr(M))),rn=Zn(()=>({session:M,loading:St,error:ct,checkoutMode:fn,inlineSessionDraft:Ht,applyInlineSessionPatch:_r?Mt:void 0,inlineSessionPatchProcessing:Rn,claimPending:bn,claimRequiresIdentity:on,claimBuyerIdentity:zn,waitForDataAttachment:En}),[M,St,ct,fn,Ht,_r,Mt,Rn,bn,on,zn,En]),Nr=!!n&&Y==="buttons"&&!Or&&!Vn&&(!be||!Pr),an=jn?le(Sr,{status:jn,errorMessage:ur,authorized:$n}):null;if(St&&!Vn){if(c)return sn(Rr,{children:[c,an]});if(Y==="buttons"){let k=Ye?.buttonsLayout?.cardButton?.borderRadius??Ye?.appearance.variables?.borderRadius??8,b=H=>le("div",{style:{height:H,borderRadius:k,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:[Se&&b(Oo),G&&(ve||N)&&b(Oo),G&&b(Oo),le("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:[le("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),le("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),an]})}return ct?f?le(sr.Provider,{value:rn,children:f(ct)}):le(sr.Provider,{value:rn,children:le("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:ct.message})}):Nr?sn(Rr,{children:[le(sr.Provider,{value:rn,children:le(Wp,{onButtonClick:bt,showPayPal:Se,showStripe:G,showApplePay:ve,showGooglePay:N,theme:Ne,buttonsTheme:yt,buttonsStyles:Be,cardButtonContent:mt,cardBackButtonContent:Nt,cardTitleContent:fe})}),an]}):Or&&M&&Bn?sn(Rr,{children:[le(sr.Provider,{value:rn,children:sn("div",{className:It,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[vn&&le(Eo,{icon:!1,children:vn}),ue==="retrying"&&le("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),ue==="exhausted"&&sn("div",{role:"alert",children:[le("div",{children:"PayPal is temporarily unavailable. Please try again."}),le("button",{type:"button",onClick:Dr,children:"Retry PayPal"})]}),ue!=="exhausted"&&le("div",{"aria-hidden":ue==="retrying"?!0:void 0,style:ue==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:le($l,{sessionId:j,nonce:M.clientSecret||void 0,billingApiUrl:A,email:M.customer?.email||Ht?.account?.email,billingName:[M.customer?.firstName,M.customer?.lastName].filter(Boolean).join(" ")||[Ht?.account?.firstName,Ht?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:zn,clientId:Bn.clientId,environment:Bn.environment,currency:(M.currency??"usd").toUpperCase(),isSubscription:M.mode==="subscription",providerObjectType:Bn.providerObjectType,approvalPresentation:Bn.approvalPresentation,existingOrderId:Bn.existingOrderId,onComplete:C,onErrorChange:xt,onDecline:z,onButtonClick:bt,runBeforeButtonClick:rr,onInitializationStateChange:An,allowAutomaticRetry:Mn===0,session:M,telemetry:a,telemetryContext:p,onInstrument:re,debug:_e},`${we}:paypal-init-${Mn}`)})]})}),an]}):fn==="confirm"?sn(Rr,{children:[le(sr.Provider,{value:rn,children:le(Ka,{flopay:be,paypalFlopay:E,options:Pr??{billingApiUrl:A},onInstrument:re,children:sn("div",{className:It,children:[vn&&le("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:vn}),$e?$e({onConfirm:un,isProcessing:nn}):le("button",{type:"button",onClick:un,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:Ut?"Processing...":he??"Confirm Purchase"})]})},we)}),an]}):(!be||!Pr)&&!(Vn&&fn==="full")?le(Rr,{children:an}):sn(Rr,{children:[le(sr.Provider,{value:rn,children:sn(Ka,{flopay:be,paypalFlopay:E,options:Pr??{billingApiUrl:A},onInstrument:re,children:[wn===1&&le("button",{type:"button",onClick:or,children:"Retry payment methods"}),X?sn(Rr,{children:[vn&&le("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:vn}),le($p,{sessionId:j,nonce:M?.clientSecret||void 0,billingApiUrl:A,session:M,submitLabel:lt,walletPresentation:v,children:X})]}):le(ds,{sessionId:j,nonce:M?.clientSecret||void 0,telemetry:a,email:M?.customer?.email||Ht?.account?.email,userId:M?.customer?.id||Ht?.account?.userId,firstName:M?.customer?.firstName||Ht?.account?.firstName,lastName:M?.customer?.lastName||Ht?.account?.lastName,totalAmount:M?Math.round(Tp(M).total*100):0,currency:M?.currency?.toLowerCase()??"usd",onComplete:C,onError:T,onDecline:z,error:vn,onErrorChange:xt,showPayPal:Se,showStripe:G,walletPresentation:v,enabledPaymentMethods:wn?[]:P??ze?.data.stripe?.enabledPaymentMethods??M?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ze?.data.stripe?.enabledPaymentMethodCountries,showApplePay:ve,showGooglePay:N,layout:Y,theme:Ne,buttonsTheme:yt,buttonsStyles:Be,appearance:Je,cardButtonContent:mt,cardBackButtonContent:Nt,cardTitleContent:fe,onButtonClick:bt,onBeforeButtonClick:Te,onBuyerIdentityReady:zn,enableAVS:qe,...Re?{cardFieldOrder:Re}:{},...ee?{cardPreFormSlot:ee}:{},avsLayout:je,country:M?.customer?.country,city:M?.customer?.city,state:M?.customer?.state,onCountryChange:ie,onZipChange:O,avsCheck:!!qe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:gs(X,Y),className:It,submitLabel:lt,directPaypal:Bn,isSubscription:M?.mode==="subscription",session:M,dataAttachmentPending:bn,dataAttachmentRequiresIdentity:on,debug:_e})]},we)}),an]})}function $p({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,children:s}){return le(Rr,{children:us.Children.map(s,c=>{if(!us.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:us.cloneElement(c,C)})})}function Wp({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:o,showGooglePay:a,theme:i,buttonsTheme:s,buttonsStyles:c,cardButtonContent:f,cardBackButtonContent:C,cardTitleContent:T}){let[I,z]=Jt(!1),ie=Zn(()=>Nc(i),[i]),O=Zn(()=>{let P=ie?.buttonsLayout??Bp(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},[ie,s,c]),Se=ie?.buttonsLayout?.cardButton?.borderRadius??ie?.appearance.variables?.borderRadius??8,G=P=>le("div",{style:{height:P,borderRadius:Se,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(I){let P=O.cardInputBorder??"#e5e7eb",ve=O.cardInputBackground??"white",N=ho(C),_e=ho(T);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:[le("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...O.backButtonIcon},children:le("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:le("path",{d:"M15 18l-6-6 6-6"})})}),le(vo,{content:C})]}),_e?le("div",{style:{flex:1}}):le("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...O.title},children:le(ta,{content:T})})]}),le("div",{style:{backgroundColor:ve,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:le("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:[le("div",{style:{flex:1,backgroundColor:ve,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:le("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),le("div",{style:{flex:1,backgroundColor:ve,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:le("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),le("div",{style:{backgroundColor:ve,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:le("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),le("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...O.submitButton,opacity:.5}}),le("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 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 Hp,jsx as ro,jsxs as Vp}from"react/jsx-runtime";var Up=44;function Nc(e){return new Promise(t=>setTimeout(t,e))}function qp(e,t){return e instanceof ba?e:new ba(e instanceof Error?e.message:t,"api_error")}function jp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function $p(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 Wp({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=va(()=>Np(ve),[ve]),Pt=va(()=>$p({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=>Ga(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=ua)=>{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 Nc(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 Nc(400))},[Ae]),bt=Fr(async(d,m,A)=>{let T=d.data.session??null;if(!T)throw Ur(new ba("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(Oa(T),T.id||m);try{if(d.autoProcessingPending){let me=d.autoProcessingPending,We=new bs(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=>tc({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 bs(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(pa(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??ua}),jp(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 ba("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 ba("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 bs(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(Na(A)==="session_auto_completed"){await Qe({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw A}}catch(m){await De(Ur(qp(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=va(()=>zp(v),[v]),Oe=va(()=>{let d=ee?.buttonsLayout??Lp(he);return N?{...d,...N,cardButton:{...d.cardButton,...N.cardButton}}:d},[ee,he,N]),F=va(()=>{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??Ic(mt,.12),wt=Se?.borderRadius??"8px";return Vp(Hp,{children:[ro("button",{...pe,type:ct,onClick:Yt,disabled:ze||Re,"aria-busy":Re,style:{width:"100%",...lt===void 0?{boxSizing:"border-box",height:Up,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Oe.cardButton,...cs({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(vs,{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 Yp}from"react/jsx-runtime";var Kp={StripeSetupMethod:Pl,PayPalSetupMethod:hl};function Gp(e){return Yp(vl,{...e,branches:Kp})}export{$a as DirectPayPalButton,Wp as FloPayAutomaticPaymentButton,nd as FloPayCardSetup,td as FloPayCardSetupError,vs as FloPayCheckout,Gp as FloPayPaymentMethodSetup,Ka as FloPayProvider,ds as SplitCardForm,_i as VaultCardFields,Cf as dropThirdPartyOnlyError,kd as useCheckout,jr as useFloPay,Li as usePayPalFloPay};
|
|
21
|
+
`})]})}return sn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&G(Oo),n&&(o||a)&&G(Oo),n&&le("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:le(Po,{content:f})}),le("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Qp,jsx as ro,jsxs as ey}from"react/jsx-runtime";var Gp=44;function zc(e){return new Promise(t=>setTimeout(t,e))}function Yp(e,t){return e instanceof ba?e:new ba(e instanceof Error?e.message:t,"api_error")}function Jp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Zp(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 Xp({sessionId:e,nonce:t,createSession:n,paymentMethodId:o,checkoutMethod:a,clientId:i,products:s,items:c,subscriptions:f,account:C,successUrl:T,cancelUrl:I,couponCodes:z,tagsData:ie,utmMetadata:O,billingApiUrl:Se,locale:G,theme:v,appearance:P,buttonsTheme:ve,buttonsStyles:N,onSuccess:_e,onError:Y,onDecline:Ne,children:yt,disabled:Be=!1,type:mt="button",style:Nt,...fe}){let Fe=va(()=>Hp(Se),[Se]),bt=va(()=>Zp({createSession:n,clientId:i,products:s,items:c,subscriptions:f,account:C,successUrl:T,cancelUrl:I,couponCodes:z,tagsData:ie,utmMetadata:O}),[C,I,i,z,n,s,c,f,T,ie,O]),[Te,qe]=zo(!1),[Re,ee]=zo(null),[je,lt]=zo(null),[It,rt]=zo(!1),[ce,X]=zo(null),[L,he]=zo(null),$e=Lo(!0),Me=Lo(null),A=Lo(L),Ye=Lo(_e),Je=Lo(Y),Ze=Lo(Ne),We=Fr(m=>Ga(Me,async w=>{try{return await m(w)}catch(Ee){throw w.aborted?To(Ee):Ee}}),[]);No(()=>{A.current=L},[L]),No(()=>{Ye.current=_e},[_e]),No(()=>{Je.current=Y},[Y]),No(()=>{Ze.current=Ne},[Ne]),No(()=>($e.current=!0,()=>{$e.current=!1,Me.current?.abort()}),[]),No(()=>{if(typeof window>"u")return;let m=w=>{w.key==="Escape"&&he(null)};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[]);let ze=Fr((m,w=ua)=>{Ze.current?.(yn(w,m,{code:m.code,declineCode:m.declineCode}))},[]),De=Fr(async m=>{$e.current&&(lt(null),rt(m.result.status==="authorized"),ee("success"),await zc(600),$e.current&&Dt(()=>Ye.current?.(m)))},[]),be=Fr(async(m,w)=>{$e.current&&(Je.current?.(m),w?.emitDecline&&ze(m,w.method),lt(m.message),rt(!1),ee("error"),await zc(400))},[ze]),Ct=Fr(async(m,w,Ee)=>{let de=m.data.session??null;if(!de)throw Ur(new ba("No session data returned","api_error"),w);let y=de.clientSecret||t;if(Ar(de)){await De({result:Mr(de,w),session:de,sessionId:de.id||w,autoCompleted:!1});return}if(de.status==="expired")throw Ur(Oa(de),de.id||w);try{if(m.autoProcessingPending){let _=m.autoProcessingPending,F=new bs(Fe),j=await We(wt=>F.waitForCheckoutSessionCompletion(_.sessionId,{initialDelayMs:_.retryAfterMs,nonce:y,statusUrl:_.statusUrl,signal:wt})),et=qr(j,de),St=j.autoProcessingError?.type==="3ds_required"&&j.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:j.autoProcessingError.nextActionRedirectUrl}:null;if(St&&w&&y){let wt=await We(ct=>Mo(St,{billingApiUrl:Fe,sessionId:w,nonce:y,session:de,signal:ct,telemetry:!0}));await De({result:wt,session:de,sessionId:de.id||w,autoCompleted:!1});return}if(j.autoProcessingError)throw kr(j.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:j.autoProcessingError.checkoutMethod});if(!Ar(et))throw So(et);await De({result:Mr(et,w),session:et,sessionId:et.id||w,autoCompleted:!1});return}if(m.autoProcessingError){let _=m.autoProcessingError.nextActionRedirectUrl;if(m.autoProcessingError.type==="3ds_required"&&_&&w&&y){let F=await We(wt=>tc({billingApiUrl:Fe,sessionId:w,nonce:y,nextActionRedirectUrl:_,signal:wt}));if(F.status==="declined")throw kr({type:F.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:F.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:m.autoProcessingError.checkoutMethod});let et=await new bs(Fe).waitForCheckoutSessionCompletion(w,{initialDelayMs:0,nonce:y}),St=qr(et,de);if(!Ar(St))throw kr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:m.autoProcessingError.checkoutMethod});await De({result:Mr(St,w),session:St,sessionId:St.id||w,autoCompleted:!1});return}throw kr(m.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:m.autoProcessingError.checkoutMethod})}if(Ee?.fromCreateSession&&m.autoProcessingAttempted===!0)throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let re=await Ao({billingApiUrl:Fe,sessionId:w??de.id,session:de,nonce:y});if(re.type==="next_action_required"&&y){let _=w??de.id,F=await We(j=>Mo(re,{billingApiUrl:Fe,sessionId:_,nonce:y,session:de,signal:j,telemetry:!0}));await De({result:F,session:de,sessionId:de.id||_,autoCompleted:!1});return}if(re.type!=="success")throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await De({result:re.result,session:de,sessionId:de.id||w,autoCompleted:!1})}catch(re){let _=de.id||w,F=Ur(pa(re),_);if(F.code==="three_ds_aborted")return;if(F.code==="checkout_processing_timeout"){if(!$e.current)return;X(F.message),Dt(()=>Je.current?.(F));return}await be(F,{emitDecline:!0,method:F.checkoutMethod??ua}),Jp(F,_)&&_&&$e.current&&he({sessionId:_,errorMessage:F.message,nonce:y||void 0,payPalOrderId:F.orderId})}},[t,Fe,We,be,De]),Zt=Fr(async m=>{if(fe.onClick?.(m),!(m.defaultPrevented||Be||Te)){if(he(null),X(null),e&&bt){let w=new ba("Provide either sessionId or create-session props, not both.","validation_error");await be(w),$e.current&&(ee(null),lt(null));return}if(!e&&!bt){let w=new ba("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await be(w),$e.current&&(ee(null),lt(null));return}qe(!0),lt(null),rt(!1),ee("processing");try{let w=new bs(Fe);if(e){let Ee=await w.getUnifiedCheckoutSession(e,t);await Ct(Ee,e);return}try{let Ee=await w.createAndFetchSession({...bt});await Ct(Ee,Ee.data.session?.id??null,{fromCreateSession:!0})}catch(Ee){if(Na(Ee)==="session_auto_completed"){await De({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ee}}catch(w){await be(Ur(Yp(w,"Automatic payment failed. Please try again."),e))}finally{$e.current&&(ee(null),lt(null),qe(!1))}}},[fe.onClick,bt,Be,Te,t,Ct,Fe,e,be,De]),ot=Fr(m=>{let w=A.current;he(null),Ye.current?.({result:m,session:null,sessionId:w?.sessionId??null,autoCompleted:!1})},[]),Lt=Fr(m=>{Je.current?.(m)},[]),E=Fr(m=>{Ze.current?.(m)},[]),ne=va(()=>Kp(v),[v]),Ue=va(()=>{let m=ne?.buttonsLayout??Vp(ve);return N?{...m,...N,cardButton:{...m.cardButton,...N.cardButton}}:m},[ne,ve,N]),M=va(()=>{let m=ne?.appearance;return P?m?{...m,...P,variables:{...m.variables,...P.variables}}:P:m},[P,ne]),se=M?.variables,Xe=se?.colorPrimary??"#4A49FF",we=se?.colorPrimaryHover??Ec(Xe,.12),ht=se?.borderRadius??"8px";return ey(Qp,{children:[ro("button",{...fe,type:mt,onClick:Zt,disabled:Be||Te,"aria-busy":Te,style:{width:"100%",...yt===void 0?{boxSizing:"border-box",height:Gp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Ue.cardButton,...cs({themeBundle:ne,resolvedPrimaryColor:Xe,resolvedBorderRadius:ht,submitButtonStyle:Ue.submitButton,explicitPrimaryColor:se?.colorPrimary}),fontSize:Ue.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Be||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:Be||Te?.6:1,...Nt},onMouseEnter:m=>{fe.onMouseEnter?.(m),!m.defaultPrevented&&!Be&&!Te&&(ne||se?.colorPrimary)&&(m.currentTarget.style.backgroundColor=we)},onMouseLeave:m=>{fe.onMouseLeave?.(m),!m.defaultPrevented&&(ne||se?.colorPrimary)&&(m.currentTarget.style.backgroundColor=Xe)},onMouseDown:m=>{fe.onMouseDown?.(m),m.defaultPrevented||(m.currentTarget.style.transform="scale(0.985)")},onMouseUp:m=>{fe.onMouseUp?.(m),m.defaultPrevented||(m.currentTarget.style.transform="scale(1)")},children:ro(Po,{content:yt})}),ce&&ro("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ce}),Re&&ro(Sr,{status:Re,errorMessage:je,authorized:It}),L&&ro("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:m=>{m.target===m.currentTarget&&he(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(vs,{sessionId:L.sessionId,nonce:L.nonce,checkoutMode:"full",billingApiUrl:Fe,locale:G,theme:v,...M?{appearance:M}:{},buttonsTheme:ve,buttonsStyles:N,initialErrorMessage:L.errorMessage,initialPayPalOrderId:L.payPalOrderId,cardTitleContent:null,onComplete:ot,onError:Lt,onDecline:E})})})]})}import{jsx as ry}from"react/jsx-runtime";var ty={StripeSetupMethod:Pl,PayPalSetupMethod:hl};function ny(e){return ry(vl,{...e,branches:ty})}export{$a as DirectPayPalButton,Xp as FloPayAutomaticPaymentButton,od as FloPayCardSetup,rd as FloPayCardSetupError,vs as FloPayCheckout,ny as FloPayPaymentMethodSetup,Ka as FloPayProvider,ds as SplitCardForm,_i as VaultCardFields,Tf as dropThirdPartyOnlyError,Rd as useCheckout,jr as useFloPay,Li as usePayPalFloPay};
|